Add docker-fence v1 with tests and docs
This commit is contained in:
commit
305cb562f8
46 files changed
+5473
No files matched your search
+423
@@ -0,0 +1,423 @@
|
||||
# shellcheck shell=bash
|
||||
# Commands that read or change after.rules and the firewall.
|
||||
|
||||
# ------------------------------------------------------------------ check
|
||||
|
||||
fence_cmd_check() {
|
||||
fence_env_check || return "$FENCE_EXIT_ENV"
|
||||
fence_info i_config_ok "$FENCE_CONFIG_FILE" "${CFG[mode]}" \
|
||||
"${#ADMIN_SRC[@]}" "${#ALLOW_PROTO[@]}" "${#C2H_PROTO[@]}"
|
||||
fence_generate_block
|
||||
}
|
||||
|
||||
# ------------------------------------------------------------ install
|
||||
|
||||
# Prepares the new content of after.rules in file $1.
|
||||
# Reads: OPT_REPLACE_LEGACY, OPT_FORCE.
|
||||
# Returns 0, or an exit code.
|
||||
fence_prepare_rules() {
|
||||
local out="$1" rules rc block
|
||||
rules="$(fence_rules_path)"
|
||||
if [[ ! -f "$rules" || ! -r "$rules" ]]; then
|
||||
fence_error e_no_rules "$rules"
|
||||
return "$FENCE_EXIT_ENV"
|
||||
fi
|
||||
fence_read_lines "$rules"
|
||||
|
||||
rc=0
|
||||
fence_find_legacy || rc=$?
|
||||
if (( rc == 2 )); then
|
||||
fence_error "$FENCE_BLOCK_ERR" "$rules" "$FENCE_LEGACY_BEGIN"
|
||||
return "$FENCE_EXIT_CONFIG"
|
||||
fi
|
||||
if (( rc == 0 )); then
|
||||
local known=1
|
||||
fence_legacy_is_known || known=0
|
||||
if (( ! OPT_REPLACE_LEGACY )); then
|
||||
fence_error e_legacy_present "$rules"
|
||||
fence_print_block >&2
|
||||
return "$FENCE_EXIT_LEGACY"
|
||||
fi
|
||||
if (( ! known )); then
|
||||
fence_warn w_legacy_unknown
|
||||
fence_legacy_diff >&2
|
||||
if (( ! OPT_FORCE )); then
|
||||
fence_error e_legacy_unknown
|
||||
return "$FENCE_EXIT_LEGACY"
|
||||
fi
|
||||
fi
|
||||
FENCE_LEGACY_CUT="$(fence_print_block)"
|
||||
fence_cut_block
|
||||
fi
|
||||
|
||||
rc=0
|
||||
fence_find_managed || rc=$?
|
||||
if (( rc == 2 )); then
|
||||
fence_error "$FENCE_BLOCK_ERR" "$rules" "${CFG[block_marker]}"
|
||||
return "$FENCE_EXIT_CONFIG"
|
||||
fi
|
||||
(( rc == 0 )) && fence_cut_block
|
||||
fence_trim_trailing_blank
|
||||
|
||||
block="$(mktemp)"
|
||||
fence_generate_block >"$block"
|
||||
fence_compose "$block" >"$out"
|
||||
rm -f -- "$block"
|
||||
return 0
|
||||
}
|
||||
|
||||
# Writes after.rules from the prepared file; backs up first.
|
||||
# fence_write_rules PREPARED_FILE; sets FENCE_BACKUP.
|
||||
fence_write_rules() {
|
||||
local new="$1" rules
|
||||
rules="$(fence_rules_path)"
|
||||
FENCE_BACKUP="$(fence_backup "$(fence_rules_basename)")" || {
|
||||
fence_error e_backup "$(fence_backup_dir)"
|
||||
return "$FENCE_EXIT_CONFIG"
|
||||
}
|
||||
fence_info i_backup "$FENCE_BACKUP"
|
||||
if [[ -n "${FENCE_LEGACY_CUT:-}" ]]; then
|
||||
(umask 077 && printf '%s\n' "$FENCE_LEGACY_CUT" >"$(fence_backup_dir)/legacy-block.rules")
|
||||
fence_info i_legacy_saved "$(fence_backup_dir)/legacy-block.rules"
|
||||
fi
|
||||
if ! fence_atomic_write "$rules" <"$new"; then
|
||||
fence_error e_write "$rules"
|
||||
return "$FENCE_EXIT_CONFIG"
|
||||
fi
|
||||
fence_info i_written "$rules"
|
||||
fence_log "write $rules backup=$FENCE_BACKUP mode=${CFG[mode]}"
|
||||
}
|
||||
|
||||
fence_cmd_install() {
|
||||
local new rc=0
|
||||
fence_env_check || return "$FENCE_EXIT_ENV"
|
||||
fence_refuse_if_pending || return
|
||||
new="$(mktemp)"
|
||||
fence_prepare_rules "$new" || rc=$?
|
||||
if (( rc != 0 )); then
|
||||
rm -f -- "$new"
|
||||
return "$rc"
|
||||
fi
|
||||
if cmp -s -- "$new" "$(fence_rules_path)"; then
|
||||
rm -f -- "$new"
|
||||
fence_info i_unchanged "$(fence_rules_path)"
|
||||
return 0
|
||||
fi
|
||||
fence_write_rules "$new" || rc=$?
|
||||
rm -f -- "$new"
|
||||
(( rc == 0 )) && fence_info i_install_done
|
||||
return "$rc"
|
||||
}
|
||||
|
||||
# ------------------------------------------------------------ kernel
|
||||
|
||||
fence_ufw_active() {
|
||||
"${CFG[bin_ufw]}" status 2>/dev/null | head -n 1 | grep -q '^Status: active'
|
||||
}
|
||||
|
||||
# Is the DOCKER-USER -> chain jump loaded?
|
||||
fence_kernel_jump_present() {
|
||||
"${CFG[bin_iptables]}" -C DOCKER-USER -j "${CFG[chain]}" >/dev/null 2>&1
|
||||
}
|
||||
|
||||
# Checks that the block is loaded after ufw reload.
|
||||
fence_kernel_verify() {
|
||||
local rules
|
||||
if ! fence_kernel_jump_present; then
|
||||
fence_error e_verify_jump "${CFG[chain]}"
|
||||
return 1
|
||||
fi
|
||||
rules="$("${CFG[bin_iptables]}" -S "${CFG[chain]}" 2>/dev/null | grep -c '^-A ')" || true
|
||||
if (( ${rules:-0} == 0 )); then
|
||||
fence_error e_verify_empty "${CFG[chain]}"
|
||||
return 1
|
||||
fi
|
||||
local i
|
||||
for i in "${!C2H_PROTO[@]}"; do
|
||||
if ! "${CFG[bin_iptables]}" -C ufw-after-input -i "${C2H_IFACE[i]}" -p "${C2H_PROTO[i]}" \
|
||||
--dport "${C2H_PORT[i]}" -j ACCEPT >/dev/null 2>&1; then
|
||||
fence_error e_verify_c2h "${C2H_PROTO[i]}" "${C2H_PORT[i]}"
|
||||
return 1
|
||||
fi
|
||||
done
|
||||
return 0
|
||||
}
|
||||
|
||||
# Removes what is left of the block in the kernel when the file has none:
|
||||
# ufw reload (--noflush) only flushes the chains declared in after.rules.
|
||||
fence_kernel_cleanup() {
|
||||
local c="${CFG[chain]}" d ipt="${CFG[bin_iptables]}" n=0
|
||||
d="$(fence_deny_chain)"
|
||||
while "$ipt" -C DOCKER-USER -j "$c" >/dev/null 2>&1 && (( n < 50 )); do
|
||||
"$ipt" -D DOCKER-USER -j "$c" || break
|
||||
n=$((n + 1))
|
||||
done
|
||||
"$ipt" -F "$c" >/dev/null 2>&1 || true
|
||||
"$ipt" -F "$d" >/dev/null 2>&1 || true
|
||||
"$ipt" -X "$c" >/dev/null 2>&1 || true
|
||||
"$ipt" -X "$d" >/dev/null 2>&1 || true
|
||||
fence_detail i_kernel_cleaned "$c"
|
||||
}
|
||||
|
||||
# ------------------------------------------------------- pending rollback
|
||||
|
||||
fence_pending_get() {
|
||||
local f
|
||||
f="$(fence_pending_file)"
|
||||
[[ -f "$f" ]] || return 1
|
||||
FENCE_PENDING="$(<"$f")"
|
||||
[[ -n "$FENCE_PENDING" ]]
|
||||
}
|
||||
|
||||
fence_refuse_if_pending() {
|
||||
if fence_pending_get; then
|
||||
fence_error e_pending "${CFG[unit_name]}"
|
||||
return "$FENCE_EXIT_CONFIG"
|
||||
fi
|
||||
}
|
||||
|
||||
fence_stop_timer() {
|
||||
"${CFG[bin_systemctl]}" stop "${CFG[unit_name]}.timer" >/dev/null 2>&1
|
||||
}
|
||||
|
||||
# Restores a backup, reloads UFW and cleans the kernel.
|
||||
# fence_restore BACKUP
|
||||
fence_restore() {
|
||||
local backup="$1" rules pre
|
||||
rules="$(fence_rules_path)"
|
||||
if [[ ! -f "$backup" || ! -r "$backup" ]]; then
|
||||
fence_error e_no_backup "$backup"
|
||||
return "$FENCE_EXIT_CONFIG"
|
||||
fi
|
||||
fence_stop_timer || true
|
||||
pre="$(fence_backup "$(fence_rules_basename).pre-rollback")" || true
|
||||
[[ -n "$pre" ]] && fence_detail i_backup "$pre"
|
||||
if ! fence_atomic_write "$rules" <"$backup"; then
|
||||
fence_error e_write "$rules"
|
||||
return "$FENCE_EXIT_APPLY"
|
||||
fi
|
||||
fence_info i_restored "$backup" "$rules"
|
||||
rm -f -- "$(fence_pending_file)"
|
||||
fence_log "rollback restored=$backup"
|
||||
if ! fence_run bin_ufw reload >/dev/null; then
|
||||
fence_error e_reload
|
||||
return "$FENCE_EXIT_APPLY"
|
||||
fi
|
||||
fence_read_lines "$rules"
|
||||
local rc=0
|
||||
fence_find_managed || rc=$?
|
||||
if (( rc != 0 )); then
|
||||
fence_kernel_cleanup
|
||||
fi
|
||||
return 0
|
||||
}
|
||||
|
||||
# ------------------------------------------------------------------ apply
|
||||
|
||||
# --set options to pass to the automatic rollback.
|
||||
fence_override_args() {
|
||||
local k
|
||||
for k in "${FENCE_SETTINGS[@]}"; do
|
||||
if [[ "${CFG_ORIGIN[$k]}" == option ]]; then
|
||||
printf '%s\n' --set "$k=${CFG[$k]}"
|
||||
fi
|
||||
done
|
||||
}
|
||||
|
||||
fence_cmd_apply() {
|
||||
local new rc=0 rules
|
||||
rules="$(fence_rules_path)"
|
||||
fence_env_check || return "$FENCE_EXIT_ENV"
|
||||
fence_env_require_bins bin_iptables bin_ufw bin_systemd_run bin_systemctl || return "$FENCE_EXIT_ENV"
|
||||
fence_refuse_if_pending || return
|
||||
if ! fence_ufw_active; then
|
||||
fence_error e_ufw_inactive
|
||||
return "$FENCE_EXIT_ENV"
|
||||
fi
|
||||
new="$(mktemp)"
|
||||
fence_prepare_rules "$new" || rc=$?
|
||||
if (( rc != 0 )); then
|
||||
rm -f -- "$new"
|
||||
return "$rc"
|
||||
fi
|
||||
fence_write_rules "$new" || rc=$?
|
||||
rm -f -- "$new"
|
||||
(( rc == 0 )) || return "$rc"
|
||||
printf '%s\n' "$FENCE_BACKUP" >"$(fence_pending_file)"
|
||||
|
||||
# Rollback scheduled before the reload.
|
||||
local -a run_args=(
|
||||
"--unit=${CFG[unit_name]}"
|
||||
"--on-active=${CFG[rollback_seconds]}s"
|
||||
"--timer-property=AccuracySec=1s"
|
||||
"--description=docker-fence rollback"
|
||||
)
|
||||
[[ -n "${FENCE_ROOT:-}" ]] && run_args+=("--setenv=FENCE_ROOT=$FENCE_ROOT")
|
||||
local -a ov
|
||||
mapfile -t ov < <(fence_override_args)
|
||||
if ! fence_run bin_systemd_run "${run_args[@]}" "$FENCE_SELF" rollback --auto \
|
||||
--config "$FENCE_CONFIG_FILE" "${ov[@]}" >/dev/null 2>&1; then
|
||||
fence_error e_timer "${CFG[unit_name]}"
|
||||
fence_atomic_write "$rules" <"$FENCE_BACKUP" || fence_error e_write "$rules"
|
||||
rm -f -- "$(fence_pending_file)"
|
||||
fence_log "apply aborted: timer"
|
||||
return "$FENCE_EXIT_APPLY"
|
||||
fi
|
||||
fence_info i_timer "${CFG[rollback_seconds]}" "${CFG[unit_name]}"
|
||||
|
||||
if ! fence_run bin_ufw reload >/dev/null; then
|
||||
fence_error e_reload
|
||||
fence_restore "$FENCE_BACKUP" || true
|
||||
return "$FENCE_EXIT_APPLY"
|
||||
fi
|
||||
if ! fence_kernel_verify; then
|
||||
fence_restore "$FENCE_BACKUP" || true
|
||||
fence_error e_apply_failed
|
||||
return "$FENCE_EXIT_APPLY"
|
||||
fi
|
||||
fence_log "apply ok mode=${CFG[mode]} pending=${CFG[unit_name]}"
|
||||
fence_info i_apply_done "${CFG[mode]}"
|
||||
fence_info i_confirm "${CFG[rollback_seconds]}"
|
||||
return 0
|
||||
}
|
||||
|
||||
# ---------------------------------------------------------------- confirm
|
||||
|
||||
fence_cmd_confirm() {
|
||||
if ! fence_pending_get; then
|
||||
fence_info i_nothing_pending
|
||||
return 0
|
||||
fi
|
||||
if ! fence_stop_timer; then
|
||||
fence_warn w_timer_stop "${CFG[unit_name]}.timer"
|
||||
fi
|
||||
rm -f -- "$(fence_pending_file)"
|
||||
fence_log "confirm"
|
||||
fence_info i_confirmed
|
||||
}
|
||||
|
||||
# --------------------------------------------------------------- rollback
|
||||
|
||||
fence_cmd_rollback() {
|
||||
local backup
|
||||
if (( OPT_AUTO )); then
|
||||
if ! fence_pending_get; then
|
||||
fence_info i_nothing_pending
|
||||
return 0
|
||||
fi
|
||||
backup="$FENCE_PENDING"
|
||||
fence_log "rollback --auto"
|
||||
elif [[ -n "${OPT_FILE:-}" ]]; then
|
||||
backup="$OPT_FILE"
|
||||
else
|
||||
backup="$(fence_latest_backup)"
|
||||
if [[ -z "$backup" ]]; then
|
||||
fence_error e_no_backups "$(fence_backup_dir)"
|
||||
return "$FENCE_EXIT_CONFIG"
|
||||
fi
|
||||
fi
|
||||
fence_restore "$backup"
|
||||
}
|
||||
|
||||
# --------------------------------------------------------------- uninstall
|
||||
|
||||
fence_cmd_uninstall() {
|
||||
local rules rc=0 legacy new
|
||||
rules="$(fence_rules_path)"
|
||||
fence_refuse_if_pending || return
|
||||
if [[ ! -f "$rules" ]]; then
|
||||
fence_error e_no_rules "$rules"
|
||||
return "$FENCE_EXIT_ENV"
|
||||
fi
|
||||
fence_read_lines "$rules"
|
||||
fence_find_managed || rc=$?
|
||||
if (( rc == 2 )); then
|
||||
fence_error "$FENCE_BLOCK_ERR" "$rules" "${CFG[block_marker]}"
|
||||
return "$FENCE_EXIT_CONFIG"
|
||||
fi
|
||||
if (( rc == 1 && ! OPT_RESTORE_LEGACY )); then
|
||||
fence_info i_not_installed "$rules"
|
||||
return 0
|
||||
fi
|
||||
(( rc == 0 )) && fence_cut_block
|
||||
fence_trim_trailing_blank
|
||||
|
||||
new="$(mktemp)"
|
||||
if (( OPT_RESTORE_LEGACY )); then
|
||||
legacy="$(fence_backup_dir)/legacy-block.rules"
|
||||
rc=0
|
||||
fence_find_legacy || rc=$?
|
||||
if (( rc != 1 )); then
|
||||
rm -f -- "$new"
|
||||
fence_error e_legacy_already "$rules"
|
||||
return "$FENCE_EXIT_CONFIG"
|
||||
fi
|
||||
if [[ ! -r "$legacy" ]]; then
|
||||
rm -f -- "$new"
|
||||
fence_error e_no_legacy_saved "$legacy"
|
||||
return "$FENCE_EXIT_CONFIG"
|
||||
fi
|
||||
fence_compose "$legacy" >"$new"
|
||||
else
|
||||
fence_compose >"$new"
|
||||
fi
|
||||
rc=0
|
||||
fence_write_rules "$new" || rc=$?
|
||||
rm -f -- "$new"
|
||||
(( rc == 0 )) || return "$rc"
|
||||
fence_log "uninstall restore_legacy=$OPT_RESTORE_LEGACY"
|
||||
|
||||
if fence_have bin_ufw && fence_ufw_active; then
|
||||
if ! fence_run bin_ufw reload >/dev/null; then
|
||||
fence_error e_reload
|
||||
return "$FENCE_EXIT_APPLY"
|
||||
fi
|
||||
fence_kernel_cleanup
|
||||
fence_info i_uninstalled_reloaded
|
||||
else
|
||||
fence_info i_uninstalled
|
||||
fi
|
||||
}
|
||||
|
||||
# ------------------------------------------------------------------ status
|
||||
|
||||
fence_cmd_status() {
|
||||
local rules mode="-" rc=0
|
||||
rules="$(fence_rules_path)"
|
||||
if [[ -r "$rules" ]]; then
|
||||
fence_read_lines "$rules"
|
||||
fence_find_managed || rc=$?
|
||||
if (( rc == 0 )); then
|
||||
if fence_print_block | grep -qF -- "--ctstate DNAT -j $(fence_deny_chain)"; then
|
||||
mode=enforce
|
||||
else
|
||||
mode=observe
|
||||
fi
|
||||
fence_info i_status_block "$rules" "$mode"
|
||||
else
|
||||
fence_info i_status_noblock "$rules"
|
||||
fi
|
||||
else
|
||||
fence_warn w_rules_unreadable "$rules"
|
||||
fi
|
||||
if fence_pending_get; then
|
||||
fence_info i_status_pending "${CFG[unit_name]}" "$FENCE_PENDING"
|
||||
fi
|
||||
if fence_have bin_iptables; then
|
||||
if fence_kernel_jump_present; then
|
||||
fence_info i_status_jump_yes "${CFG[chain]}"
|
||||
else
|
||||
fence_info i_status_jump_no "${CFG[chain]}"
|
||||
fi
|
||||
fence_info i_status_counters
|
||||
"${CFG[bin_iptables]}" -L "${CFG[chain]}" -n -v -x 2>&1 || true
|
||||
"${CFG[bin_iptables]}" -L "$(fence_deny_chain)" -n -v -x 2>&1 || true
|
||||
fi
|
||||
if fence_have bin_journalctl; then
|
||||
fence_info i_status_log
|
||||
"${CFG[bin_journalctl]}" -k --no-pager -o short-iso --since "${CFG[report_since]}" 2>/dev/null \
|
||||
| grep -F -e "${CFG[log_prefix_drop]} " -e "${CFG[log_prefix_observe]} " \
|
||||
| tail -n 20 || true
|
||||
fi
|
||||
return 0
|
||||
}
|
||||
+563
@@ -0,0 +1,563 @@
|
||||
# shellcheck shell=bash
|
||||
# Configuration: defaults, strict parsing of the .conf file, command
|
||||
# line overrides, validation. Nothing is evaluated by the shell: each
|
||||
# line is split by `read -r -a`, then checked with regular
|
||||
# expressions.
|
||||
|
||||
# Settings, in display order (show-config, init).
|
||||
FENCE_SETTINGS=(
|
||||
mode rollback_seconds lang
|
||||
log_rate_observe log_burst_observe log_rate_enforce log_burst_enforce
|
||||
log_prefix_observe log_prefix_drop log_level log_file
|
||||
chain block_marker unit_name ufw_after_rules docker_daemon_json
|
||||
backup_dir backup_keep report_since
|
||||
bin_iptables bin_ufw bin_docker bin_journalctl bin_systemd_run bin_systemctl
|
||||
)
|
||||
|
||||
declare -gA FENCE_DEFAULTS=(
|
||||
[mode]=observe
|
||||
[rollback_seconds]=120
|
||||
[lang]=en
|
||||
[log_rate_observe]=120/min
|
||||
[log_burst_observe]=200
|
||||
[log_rate_enforce]=20/min
|
||||
[log_burst_enforce]=40
|
||||
[log_prefix_observe]=DOCKER-WOULD-DROP
|
||||
[log_prefix_drop]=DOCKER-FENCE-DROP
|
||||
[log_level]=6
|
||||
[log_file]=/var/log/docker-fence.log
|
||||
[chain]=docker-fence
|
||||
[block_marker]=DOCKER-FENCE
|
||||
[unit_name]=docker-fence-rollback
|
||||
[ufw_after_rules]=/etc/ufw/after.rules
|
||||
[docker_daemon_json]=/etc/docker/daemon.json
|
||||
[backup_dir]=/var/backups/docker-fence
|
||||
[backup_keep]=20
|
||||
[report_since]="24 hours ago"
|
||||
[bin_iptables]=iptables
|
||||
[bin_ufw]=ufw
|
||||
[bin_docker]=docker
|
||||
[bin_journalctl]=journalctl
|
||||
[bin_systemd_run]=systemd-run
|
||||
[bin_systemctl]=systemctl
|
||||
)
|
||||
|
||||
# Maximum lengths set by iptables (chain name: 28 characters; log
|
||||
# prefix: 29 characters including the trailing space).
|
||||
readonly FENCE_MAX_CHAIN=28
|
||||
readonly FENCE_MAX_PREFIX=28
|
||||
|
||||
fence_config_reset() {
|
||||
declare -gA CFG=() CFG_ORIGIN=()
|
||||
local k
|
||||
for k in "${FENCE_SETTINGS[@]}"; do
|
||||
CFG[$k]="${FENCE_DEFAULTS[$k]}"
|
||||
CFG_ORIGIN[$k]=default
|
||||
done
|
||||
# Rules: parallel arrays, one index per rule.
|
||||
ADMIN_SRC=() ADMIN_IFACE=() ADMIN_LINE=()
|
||||
ALLOW_PROTO=() ALLOW_PORT=() ALLOW_SRC=() ALLOW_IFACE=() ALLOW_LINE=()
|
||||
C2H_PROTO=() C2H_PORT=() C2H_IFACE=() C2H_LINE=()
|
||||
TRUSTED_IFACE=() TRUSTED_LINE=()
|
||||
declare -gA FENCE_SEEN=()
|
||||
# Collected errors: "line<US>key<US>arg..."; formatted at the end,
|
||||
# once the language is known.
|
||||
FENCE_ERRORS=()
|
||||
FENCE_CONFIG_FILE=""
|
||||
}
|
||||
|
||||
# fence_add_error LINE KEY [ARGS...] (LINE empty when not applicable)
|
||||
fence_add_error() {
|
||||
local IFS=$'\x1f'
|
||||
FENCE_ERRORS+=("$*")
|
||||
}
|
||||
|
||||
# ----------------------------------------------------------------- validators
|
||||
# Each validator returns 0 if the value is valid; otherwise 1, with the
|
||||
# error message key in FENCE_VERR. Normalizers write the normalized
|
||||
# value to FENCE_NORM.
|
||||
|
||||
fence_is_uint() {
|
||||
[[ "$1" =~ ^(0|[1-9][0-9]{0,8})$ ]]
|
||||
}
|
||||
|
||||
# Integer in [min, max].
|
||||
fence_v_int() {
|
||||
local v="$1" min="$2" max="$3"
|
||||
if fence_is_uint "$v" && (( v >= min && v <= max )); then
|
||||
return 0
|
||||
fi
|
||||
FENCE_VERR=v_int
|
||||
FENCE_VARG="$min-$max"
|
||||
return 1
|
||||
}
|
||||
|
||||
# IPv4 address with optional mask; normalized to a.b.c.d/m.
|
||||
fence_norm_ipv4() {
|
||||
local v="$1" re='^([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})(/([0-9]{1,2}))?$'
|
||||
if ! [[ "$v" =~ $re ]]; then
|
||||
FENCE_VERR=v_ipv4
|
||||
return 1
|
||||
fi
|
||||
local -a o=("${BASH_REMATCH[1]}" "${BASH_REMATCH[2]}" "${BASH_REMATCH[3]}" "${BASH_REMATCH[4]}")
|
||||
local mask="${BASH_REMATCH[6]:-32}" x
|
||||
for x in "${o[@]}"; do
|
||||
# No leading zero (ambiguous: octal for some tools).
|
||||
if [[ "$x" =~ ^0[0-9] ]] || (( 10#$x > 255 )); then
|
||||
FENCE_VERR=v_ipv4
|
||||
return 1
|
||||
fi
|
||||
done
|
||||
if [[ "$mask" =~ ^0[0-9] ]] || (( 10#$mask > 32 )); then
|
||||
FENCE_VERR=v_ipv4
|
||||
return 1
|
||||
fi
|
||||
mask=$((10#$mask))
|
||||
if (( mask == 0 )); then
|
||||
FENCE_VERR=v_ipv4_any
|
||||
return 1
|
||||
fi
|
||||
local addr=$(( (10#${o[0]} << 24) | (10#${o[1]} << 16) | (10#${o[2]} << 8) | 10#${o[3]} ))
|
||||
local hostmask=$(( (1 << (32 - mask)) - 1 ))
|
||||
if (( addr & hostmask )); then
|
||||
FENCE_VERR=v_ipv4_hostbits
|
||||
return 1
|
||||
fi
|
||||
FENCE_NORM="$((10#${o[0]})).$((10#${o[1]})).$((10#${o[2]})).$((10#${o[3]}))/$mask"
|
||||
return 0
|
||||
}
|
||||
|
||||
# Port or range a-b; normalized to N or a:b.
|
||||
fence_norm_port() {
|
||||
local v="$1" p='(6553[0-5]|655[0-2][0-9]|65[0-4][0-9]{2}|6[0-4][0-9]{3}|[1-5][0-9]{4}|[1-9][0-9]{0,3})'
|
||||
if [[ "$v" =~ ^${p}$ ]]; then
|
||||
FENCE_NORM="$v"
|
||||
return 0
|
||||
fi
|
||||
if [[ "$v" =~ ^${p}-${p}$ ]]; then
|
||||
local a="${BASH_REMATCH[1]}" b="${BASH_REMATCH[2]}"
|
||||
if (( a < b )); then
|
||||
FENCE_NORM="$a:$b"
|
||||
return 0
|
||||
fi
|
||||
FENCE_VERR=v_port_range
|
||||
return 1
|
||||
fi
|
||||
FENCE_VERR=v_port
|
||||
return 1
|
||||
}
|
||||
|
||||
fence_v_proto() {
|
||||
[[ "$1" == tcp || "$1" == udp ]] && return 0
|
||||
FENCE_VERR=v_proto
|
||||
return 1
|
||||
}
|
||||
|
||||
# Interface name (at most 15 characters), trailing "+" accepted as a wildcard.
|
||||
fence_v_iface() {
|
||||
if [[ "$1" =~ ^[A-Za-z0-9_.-]{1,15}$ || "$1" =~ ^[A-Za-z0-9_.-]{0,14}\+$ ]]; then
|
||||
return 0
|
||||
fi
|
||||
FENCE_VERR=v_iface
|
||||
return 1
|
||||
}
|
||||
|
||||
fence_v_abspath() {
|
||||
if [[ "$1" =~ ^/[A-Za-z0-9_./-]*$ && ! "$1" =~ (^|/)\.\.(/|$) && "$1" != */ ]]; then
|
||||
return 0
|
||||
fi
|
||||
FENCE_VERR=v_path
|
||||
return 1
|
||||
}
|
||||
|
||||
fence_v_bin() {
|
||||
if [[ "$1" =~ ^[A-Za-z0-9_.+-]+$ ]]; then
|
||||
return 0
|
||||
fi
|
||||
fence_v_abspath "$1" && return 0
|
||||
FENCE_VERR=v_bin
|
||||
return 1
|
||||
}
|
||||
|
||||
fence_v_rate() {
|
||||
if [[ "$1" =~ ^[1-9][0-9]{0,5}/(second|sec|s|minute|min|m|hour|h|day|d)$ ]]; then
|
||||
return 0
|
||||
fi
|
||||
FENCE_VERR=v_rate
|
||||
return 1
|
||||
}
|
||||
|
||||
fence_v_prefix() {
|
||||
if [[ "$1" =~ ^[A-Za-z0-9_.:-]+$ ]] && (( ${#1} <= FENCE_MAX_PREFIX )); then
|
||||
return 0
|
||||
fi
|
||||
FENCE_VERR=v_prefix
|
||||
FENCE_VARG="$FENCE_MAX_PREFIX"
|
||||
return 1
|
||||
}
|
||||
|
||||
fence_v_chain() {
|
||||
local max=$(( FENCE_MAX_CHAIN - 5 ))
|
||||
if ! [[ "$1" =~ ^[A-Za-z0-9_-]+$ ]] || (( ${#1} > max )); then
|
||||
FENCE_VERR=v_chain
|
||||
FENCE_VARG="$max"
|
||||
return 1
|
||||
fi
|
||||
# No clash with the chains of Docker, UFW or the kernel.
|
||||
# Docker chains are upper case (DOCKER, DOCKER-USER, ...).
|
||||
if [[ "$1" =~ ^DOCKER(-|$) || "$1" == ufw-* || "$1" == ufw6-* \
|
||||
|| "${1^^}" =~ ^(INPUT|OUTPUT|FORWARD|PREROUTING|POSTROUTING|ACCEPT|DROP|RETURN|REJECT|LOG)$ ]]; then
|
||||
FENCE_VERR=v_chain_reserved
|
||||
return 1
|
||||
fi
|
||||
return 0
|
||||
}
|
||||
|
||||
fence_v_marker() {
|
||||
if [[ "$1" =~ ^[A-Za-z0-9_-]{1,40}$ ]]; then
|
||||
return 0
|
||||
fi
|
||||
FENCE_VERR=v_marker
|
||||
return 1
|
||||
}
|
||||
|
||||
fence_v_unit() {
|
||||
if [[ "$1" =~ ^[A-Za-z0-9_-]{1,64}$ ]]; then
|
||||
return 0
|
||||
fi
|
||||
FENCE_VERR=v_unit
|
||||
return 1
|
||||
}
|
||||
|
||||
fence_v_since() {
|
||||
if [[ "$1" =~ ^[A-Za-z0-9:+-]+( [A-Za-z0-9:+-]+)*$ ]] && (( ${#1} <= 64 )); then
|
||||
return 0
|
||||
fi
|
||||
FENCE_VERR=v_since
|
||||
return 1
|
||||
}
|
||||
|
||||
# Validates a setting: fence_validate_setting KEY VALUE.
|
||||
fence_validate_setting() {
|
||||
local k="$1" v="$2"
|
||||
FENCE_VARG=""
|
||||
case "$k" in
|
||||
mode)
|
||||
[[ "$v" == observe || "$v" == enforce ]] || { FENCE_VERR=v_mode; return 1; } ;;
|
||||
lang)
|
||||
[[ "$v" == fr || "$v" == en ]] || { FENCE_VERR=v_lang; return 1; } ;;
|
||||
rollback_seconds) fence_v_int "$v" 30 86400 ;;
|
||||
log_burst_observe|log_burst_enforce) fence_v_int "$v" 1 10000 ;;
|
||||
log_level) fence_v_int "$v" 0 7 ;;
|
||||
backup_keep) fence_v_int "$v" 1 1000 ;;
|
||||
log_rate_observe|log_rate_enforce) fence_v_rate "$v" ;;
|
||||
log_prefix_observe|log_prefix_drop) fence_v_prefix "$v" ;;
|
||||
chain) fence_v_chain "$v" ;;
|
||||
block_marker) fence_v_marker "$v" ;;
|
||||
unit_name) fence_v_unit "$v" ;;
|
||||
log_file|ufw_after_rules|docker_daemon_json|backup_dir) fence_v_abspath "$v" ;;
|
||||
report_since) fence_v_since "$v" ;;
|
||||
bin_*) fence_v_bin "$v" ;;
|
||||
*) FENCE_VERR=v_unknown; return 1 ;;
|
||||
esac
|
||||
}
|
||||
|
||||
fence_is_setting() {
|
||||
[[ -n "${FENCE_DEFAULTS[$1]+x}" ]]
|
||||
}
|
||||
|
||||
# -------------------------------------------------------------------- rules
|
||||
|
||||
# fence_seen KEY LINE: reports a rule identical to one already seen.
|
||||
fence_seen() {
|
||||
local key="$1" line="$2"
|
||||
if [[ -n "${FENCE_SEEN[$key]+x}" ]]; then
|
||||
fence_add_error "$line" e_duplicate "${FENCE_SEEN[$key]}"
|
||||
return 1
|
||||
fi
|
||||
FENCE_SEEN[$key]="$line"
|
||||
}
|
||||
|
||||
fence_parse_admin() {
|
||||
local n="$1"
|
||||
shift
|
||||
local -a t=("$@")
|
||||
if ! [[ ${#t[@]} -eq 1 || ( ${#t[@]} -eq 3 && "${t[1]}" == iface ) ]]; then
|
||||
fence_add_error "$n" e_syntax "admin <ipv4[/mask]> [iface <name>]"
|
||||
return
|
||||
fi
|
||||
local src iface=""
|
||||
if ! fence_norm_ipv4 "${t[0]}"; then
|
||||
fence_add_error "$n" "$FENCE_VERR" "${t[0]}"
|
||||
return
|
||||
fi
|
||||
src="$FENCE_NORM"
|
||||
if (( ${#t[@]} == 3 )); then
|
||||
if ! fence_v_iface "${t[2]}"; then
|
||||
fence_add_error "$n" "$FENCE_VERR" "${t[2]}"
|
||||
return
|
||||
fi
|
||||
iface="${t[2]}"
|
||||
fi
|
||||
fence_seen "admin|$src|$iface" "$n" || return
|
||||
ADMIN_SRC+=("$src") ADMIN_IFACE+=("$iface") ADMIN_LINE+=("$n")
|
||||
}
|
||||
|
||||
fence_parse_allow() {
|
||||
local n="$1"
|
||||
shift
|
||||
local -a t=("$@")
|
||||
if ! [[ ( ${#t[@]} -eq 4 || ( ${#t[@]} -eq 6 && "${t[4]}" == iface ) ) && "${t[2]:-}" == from ]]; then
|
||||
fence_add_error "$n" e_syntax "allow <tcp|udp> <port|a-b> from <ipv4[/mask]|any> [iface <name>]"
|
||||
return
|
||||
fi
|
||||
local proto="${t[0]}" port src iface="" ok=1
|
||||
fence_v_proto "$proto" || { fence_add_error "$n" "$FENCE_VERR" "$proto"; ok=0; }
|
||||
if fence_norm_port "${t[1]}"; then
|
||||
port="$FENCE_NORM"
|
||||
else
|
||||
fence_add_error "$n" "$FENCE_VERR" "${t[1]}"
|
||||
ok=0
|
||||
fi
|
||||
if [[ "${t[3]}" == any ]]; then
|
||||
src=any
|
||||
elif fence_norm_ipv4 "${t[3]}"; then
|
||||
src="$FENCE_NORM"
|
||||
else
|
||||
fence_add_error "$n" "$FENCE_VERR" "${t[3]}"
|
||||
ok=0
|
||||
fi
|
||||
if (( ${#t[@]} == 6 )); then
|
||||
if fence_v_iface "${t[5]}"; then
|
||||
iface="${t[5]}"
|
||||
else
|
||||
fence_add_error "$n" "$FENCE_VERR" "${t[5]}"
|
||||
ok=0
|
||||
fi
|
||||
fi
|
||||
(( ok )) || return
|
||||
fence_seen "allow|$proto|$port|$src|$iface" "$n" || return
|
||||
ALLOW_PROTO+=("$proto") ALLOW_PORT+=("$port") ALLOW_SRC+=("$src")
|
||||
ALLOW_IFACE+=("$iface") ALLOW_LINE+=("$n")
|
||||
}
|
||||
|
||||
fence_parse_c2h() {
|
||||
local n="$1"
|
||||
shift
|
||||
local -a t=("$@")
|
||||
if ! [[ ${#t[@]} -eq 2 || ( ${#t[@]} -eq 4 && "${t[2]}" == from_iface ) ]]; then
|
||||
fence_add_error "$n" e_syntax "container_to_host <tcp|udp> <port|a-b> [from_iface <name>]"
|
||||
return
|
||||
fi
|
||||
local proto="${t[0]}" port iface="br-+" ok=1
|
||||
fence_v_proto "$proto" || { fence_add_error "$n" "$FENCE_VERR" "$proto"; ok=0; }
|
||||
if fence_norm_port "${t[1]}"; then
|
||||
port="$FENCE_NORM"
|
||||
else
|
||||
fence_add_error "$n" "$FENCE_VERR" "${t[1]}"
|
||||
ok=0
|
||||
fi
|
||||
if (( ${#t[@]} == 4 )); then
|
||||
if fence_v_iface "${t[3]}"; then
|
||||
iface="${t[3]}"
|
||||
else
|
||||
fence_add_error "$n" "$FENCE_VERR" "${t[3]}"
|
||||
ok=0
|
||||
fi
|
||||
fi
|
||||
(( ok )) || return
|
||||
fence_seen "c2h|$proto|$port|$iface" "$n" || return
|
||||
C2H_PROTO+=("$proto") C2H_PORT+=("$port") C2H_IFACE+=("$iface") C2H_LINE+=("$n")
|
||||
}
|
||||
|
||||
fence_parse_trusted() {
|
||||
local n="$1"
|
||||
shift
|
||||
if (( $# != 1 )); then
|
||||
fence_add_error "$n" e_syntax "trusted_iface <name>"
|
||||
return
|
||||
fi
|
||||
if ! fence_v_iface "$1"; then
|
||||
fence_add_error "$n" "$FENCE_VERR" "$1"
|
||||
return
|
||||
fi
|
||||
fence_seen "trusted|$1" "$n" || return
|
||||
TRUSTED_IFACE+=("$1") TRUSTED_LINE+=("$n")
|
||||
}
|
||||
|
||||
# --------------------------------------------------------------------- file
|
||||
|
||||
# Parses one line. fence_parse_line NUMBER TEXT
|
||||
fence_parse_line() {
|
||||
local n="$1" line="$2" body
|
||||
# Empty line or comment.
|
||||
[[ "$line" =~ ^[[:space:]]*(#.*)?$ ]] && return
|
||||
# End-of-line comment: "#" after a blank.
|
||||
if [[ "$line" =~ ^([^#]*[[:space:]])#.*$ ]]; then
|
||||
body="${BASH_REMATCH[1]}"
|
||||
elif [[ "$line" == *'#'* ]]; then
|
||||
fence_add_error "$n" e_comment
|
||||
return
|
||||
else
|
||||
body="$line"
|
||||
fi
|
||||
# Allowed character set: anything else ($, `, ', ", \, ;, ...) is refused.
|
||||
if [[ "$body" =~ [^A-Za-z0-9_./:+[:blank:]-] ]]; then
|
||||
fence_add_error "$n" e_charset "${BASH_REMATCH[0]}"
|
||||
return
|
||||
fi
|
||||
local -a t
|
||||
read -r -a t <<<"$body"
|
||||
local d="${t[0]}"
|
||||
local -a args=("${t[@]:1}")
|
||||
case "$d" in
|
||||
admin) fence_parse_admin "$n" "${args[@]}" ;;
|
||||
allow) fence_parse_allow "$n" "${args[@]}" ;;
|
||||
container_to_host) fence_parse_c2h "$n" "${args[@]}" ;;
|
||||
trusted_iface) fence_parse_trusted "$n" "${args[@]}" ;;
|
||||
*)
|
||||
if ! fence_is_setting "$d"; then
|
||||
fence_add_error "$n" e_unknown_directive "$d"
|
||||
return
|
||||
fi
|
||||
local v
|
||||
if [[ "$d" == report_since ]]; then
|
||||
v="${args[*]}"
|
||||
elif (( ${#args[@]} != 1 )); then
|
||||
fence_add_error "$n" e_one_value "$d"
|
||||
return
|
||||
else
|
||||
v="${args[0]}"
|
||||
fi
|
||||
if [[ -z "$v" ]]; then
|
||||
fence_add_error "$n" e_one_value "$d"
|
||||
return
|
||||
fi
|
||||
if fence_validate_setting "$d" "$v"; then
|
||||
CFG[$d]="$v"
|
||||
CFG_ORIGIN[$d]="file:$n"
|
||||
else
|
||||
fence_add_error "$n" "$FENCE_VERR" "$v" "$FENCE_VARG"
|
||||
fi
|
||||
;;
|
||||
esac
|
||||
}
|
||||
|
||||
# Permission check: owned by root (or by the current user when the
|
||||
# tool does not run as root) and not writable by group or others.
|
||||
fence_config_check_perms() {
|
||||
local file="$1" st uid mode
|
||||
st="$(stat -L -c '%u %a' -- "$file")" || return 1
|
||||
uid="${st% *}"
|
||||
mode="${st#* }"
|
||||
if [[ "$uid" != 0 && "$uid" != "$EUID" ]]; then
|
||||
fence_add_error "" e_perm_owner "$file"
|
||||
return 1
|
||||
fi
|
||||
if (( (8#$mode & 8#022) != 0 )); then
|
||||
fence_add_error "" e_perm_mode "$file" "$mode"
|
||||
return 1
|
||||
fi
|
||||
}
|
||||
|
||||
# Finds the file: --config, $FENCE_CONFIG, ./fence.conf, /etc/docker-fence/fence.conf.
|
||||
fence_config_locate() {
|
||||
local opt="$1" etc
|
||||
etc="$(fence_path /etc/docker-fence/fence.conf)"
|
||||
if [[ -n "$opt" ]]; then
|
||||
FENCE_CONFIG_FILE="$opt"
|
||||
elif [[ -n "${FENCE_CONFIG:-}" ]]; then
|
||||
FENCE_CONFIG_FILE="$FENCE_CONFIG"
|
||||
elif [[ -f ./fence.conf ]]; then
|
||||
FENCE_CONFIG_FILE=./fence.conf
|
||||
else
|
||||
FENCE_CONFIG_FILE="$etc"
|
||||
fi
|
||||
if [[ ! -f "$FENCE_CONFIG_FILE" || ! -r "$FENCE_CONFIG_FILE" ]]; then
|
||||
fence_add_error "" e_no_config "$FENCE_CONFIG_FILE"
|
||||
return 1
|
||||
fi
|
||||
# Absolute path: the automatic rollback reads it again from systemd.
|
||||
FENCE_CONFIG_FILE="$(cd "$(dirname -- "$FENCE_CONFIG_FILE")" && pwd -P)/$(basename -- "$FENCE_CONFIG_FILE")"
|
||||
}
|
||||
|
||||
fence_config_parse_file() {
|
||||
local file="$1" line n=0
|
||||
while IFS= read -r line || [[ -n "$line" ]]; do
|
||||
n=$((n + 1))
|
||||
fence_parse_line "$n" "$line"
|
||||
done <"$file"
|
||||
}
|
||||
|
||||
# Overrides from the command line and the environment.
|
||||
# FENCE_OVERRIDES: array of "key=value" (--set, --mode, --lang).
|
||||
fence_config_apply_overrides() {
|
||||
if [[ -n "${FENCE_LANG:-}" ]]; then
|
||||
if fence_validate_setting lang "$FENCE_LANG"; then
|
||||
CFG[lang]="$FENCE_LANG"
|
||||
CFG_ORIGIN[lang]="env"
|
||||
else
|
||||
fence_add_error "" e_env "FENCE_LANG" "$FENCE_LANG"
|
||||
fi
|
||||
fi
|
||||
local kv k v
|
||||
for kv in "${FENCE_OVERRIDES[@]}"; do
|
||||
k="${kv%%=*}"
|
||||
v="${kv#*=}"
|
||||
if [[ "$kv" != *=* ]] || ! fence_is_setting "$k"; then
|
||||
fence_add_error "" e_option "--set $kv"
|
||||
continue
|
||||
fi
|
||||
if fence_validate_setting "$k" "$v"; then
|
||||
CFG[$k]="$v"
|
||||
CFG_ORIGIN[$k]=option
|
||||
else
|
||||
fence_add_error "" e_option "--set $kv"
|
||||
fi
|
||||
done
|
||||
}
|
||||
|
||||
# Checks on the configuration as a whole.
|
||||
fence_config_finish() {
|
||||
if (( ${#ADMIN_SRC[@]} == 0 )); then
|
||||
fence_add_error "" e_no_admin
|
||||
fi
|
||||
if (( ${#TRUSTED_IFACE[@]} == 0 )); then
|
||||
TRUSTED_IFACE=("br-+" docker0)
|
||||
TRUSTED_LINE=(default default)
|
||||
fi
|
||||
if [[ "${CFG[log_prefix_observe]}" == "${CFG[log_prefix_drop]}" ]]; then
|
||||
fence_add_error "" e_same_prefix
|
||||
fi
|
||||
}
|
||||
|
||||
# Loads the whole configuration. Returns 1 on errors (they are in
|
||||
# FENCE_ERRORS).
|
||||
fence_config_load() {
|
||||
local opt_file="$1"
|
||||
fence_config_reset
|
||||
if fence_config_locate "$opt_file" && fence_config_check_perms "$FENCE_CONFIG_FILE"; then
|
||||
fence_config_parse_file "$FENCE_CONFIG_FILE"
|
||||
fence_config_finish
|
||||
fi
|
||||
fence_config_apply_overrides
|
||||
(( ${#FENCE_ERRORS[@]} == 0 ))
|
||||
}
|
||||
|
||||
# Prints every collected error, with its line number.
|
||||
fence_config_print_errors() {
|
||||
local e line key
|
||||
local -a parts
|
||||
for e in "${FENCE_ERRORS[@]}"; do
|
||||
IFS=$'\x1f' read -r -a parts <<<"$e"
|
||||
line="${parts[0]}"
|
||||
key="${parts[1]}"
|
||||
if [[ -n "$line" ]]; then
|
||||
# shellcheck disable=SC2059
|
||||
printf "%s %s:%s: $(fence_fmt "$key")\n" "$(fence_fmt e_prefix)" \
|
||||
"$FENCE_CONFIG_FILE" "$line" "${parts[@]:2}" >&2
|
||||
else
|
||||
fence_error "$key" "${parts[@]:2}"
|
||||
fi
|
||||
done
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
# shellcheck shell=bash
|
||||
# Environment checks. Nothing is assumed about the exact output of the
|
||||
# tools: only simple patterns are looked for.
|
||||
|
||||
# First line of the output of a command, or "?".
|
||||
fence_first_line() {
|
||||
local out
|
||||
out="$("$@" 2>/dev/null | head -n 1)" || true
|
||||
printf '%s' "${out:-?}"
|
||||
}
|
||||
|
||||
fence_env_versions() {
|
||||
local docker_v="?" ipt_v="?" ufw_v="?"
|
||||
if fence_have bin_docker; then
|
||||
docker_v="$(fence_first_line "${CFG[bin_docker]}" version --format '{{.Server.Version}}')"
|
||||
fi
|
||||
if fence_have bin_iptables; then
|
||||
ipt_v="$(fence_first_line "${CFG[bin_iptables]}" --version)"
|
||||
fi
|
||||
if fence_have bin_ufw; then
|
||||
ufw_v="$(fence_first_line "${CFG[bin_ufw]}" version)"
|
||||
fi
|
||||
fence_info i_versions "${BASH_VERSION}" "$docker_v" "$ipt_v" "$ufw_v"
|
||||
}
|
||||
|
||||
# Reads daemon.json without a JSON parser: "key: value" patterns.
|
||||
# Returns 2 if the environment is not supported.
|
||||
fence_env_daemon_json() {
|
||||
local f content
|
||||
f="$(fence_path "${CFG[docker_daemon_json]}")"
|
||||
[[ -r "$f" ]] || return 0
|
||||
content="$(tr -d '\n\r\t ' <"$f")"
|
||||
if [[ "$content" =~ \"iptables\":false ]]; then
|
||||
fence_error e_docker_no_iptables "$f"
|
||||
return 2
|
||||
fi
|
||||
if [[ "$content" =~ \"firewall-backend\":\"nftables\" ]]; then
|
||||
fence_error e_docker_nftables "$f"
|
||||
return 2
|
||||
fi
|
||||
if [[ "$content" =~ \"ipv6\":true ]]; then
|
||||
fence_warn w_ipv6 "$f"
|
||||
fi
|
||||
return 0
|
||||
}
|
||||
|
||||
fence_env_networks() {
|
||||
fence_have bin_docker || return 0
|
||||
local drv nets
|
||||
for drv in macvlan ipvlan; do
|
||||
nets="$("${CFG[bin_docker]}" network ls --filter "driver=$drv" --format '{{.Name}}' 2>/dev/null | tr '\n' ' ')" || true
|
||||
nets="${nets% }"
|
||||
if [[ -n "$nets" ]]; then
|
||||
fence_warn w_macvlan "$drv" "$nets"
|
||||
fi
|
||||
done
|
||||
}
|
||||
|
||||
# Binaries required to change the firewall (apply, rollback...).
|
||||
fence_env_require_bins() {
|
||||
local k missing=0
|
||||
for k in "$@"; do
|
||||
if ! fence_have "$k"; then
|
||||
fence_error e_missing_bin "${CFG[$k]}"
|
||||
missing=1
|
||||
fi
|
||||
done
|
||||
(( missing == 0 ))
|
||||
}
|
||||
|
||||
# Full checks. Returns 2 if the environment is not supported.
|
||||
fence_env_check() {
|
||||
fence_env_versions
|
||||
local k
|
||||
for k in bin_iptables bin_ufw bin_docker; do
|
||||
fence_have "$k" || fence_warn w_missing_bin "${CFG[$k]}"
|
||||
done
|
||||
fence_env_daemon_json || return 2
|
||||
fence_env_networks
|
||||
return 0
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
# shellcheck shell=bash
|
||||
# Generation of the managed block for after.rules (iptables-restore format).
|
||||
# Only values validated by lib/config.sh go into it.
|
||||
|
||||
fence_block_begin() {
|
||||
printf '# BEGIN %s (%s)' "${CFG[block_marker]}" "$(fence_fmt block_header)"
|
||||
}
|
||||
|
||||
fence_block_end() {
|
||||
printf '# END %s' "${CFG[block_marker]}"
|
||||
}
|
||||
|
||||
fence_deny_chain() {
|
||||
printf '%s-deny' "${CFG[chain]}"
|
||||
}
|
||||
|
||||
# Every rule of the block, in order, one per line:
|
||||
# ROLE<US>INDEX<US>CHAIN<US>ARGUMENTS
|
||||
# ROLE says what the rule is for (used by the rules listing), INDEX points
|
||||
# into the rule arrays of lib/config.sh (or is empty). The block (generate)
|
||||
# and the kernel check (rules) both come from this single list.
|
||||
fence_rule_list() {
|
||||
local c="${CFG[chain]}" d i iface a
|
||||
local us=$'\x1f'
|
||||
d="$(fence_deny_chain)"
|
||||
printf '%s\n' "jump${us}${us}DOCKER-USER${us}-j $c" "return${us}${us}DOCKER-USER${us}-j RETURN"
|
||||
printf '%s\n' "established${us}${us}$c${us}-m conntrack --ctstate RELATED,ESTABLISHED -j RETURN"
|
||||
for i in "${!TRUSTED_IFACE[@]}"; do
|
||||
iface="${TRUSTED_IFACE[i]}"
|
||||
printf '%s\n' "trusted${us}$i${us}$c${us}-i $iface -j RETURN"
|
||||
done
|
||||
for i in "${!ADMIN_SRC[@]}"; do
|
||||
a=""
|
||||
[[ -n "${ADMIN_IFACE[i]}" ]] && a+="-i ${ADMIN_IFACE[i]} "
|
||||
a+="-s ${ADMIN_SRC[i]} -j RETURN"
|
||||
printf '%s\n' "admin${us}$i${us}$c${us}$a"
|
||||
done
|
||||
for i in "${!ALLOW_PROTO[@]}"; do
|
||||
a=""
|
||||
[[ -n "${ALLOW_IFACE[i]}" ]] && a+="-i ${ALLOW_IFACE[i]} "
|
||||
a+="-p ${ALLOW_PROTO[i]} -m conntrack --ctorigdstport ${ALLOW_PORT[i]}"
|
||||
[[ "${ALLOW_SRC[i]}" != any ]] && a+=" -s ${ALLOW_SRC[i]}"
|
||||
a+=" -j RETURN"
|
||||
printf '%s\n' "allow${us}$i${us}$c${us}$a"
|
||||
done
|
||||
if [[ "${CFG[mode]}" == enforce ]]; then
|
||||
a="-m conntrack --ctstate DNAT -j $d"
|
||||
else
|
||||
a="-m conntrack --ctstate DNAT -m limit --limit ${CFG[log_rate_observe]} --limit-burst ${CFG[log_burst_observe]}"
|
||||
a+=" -j LOG --log-prefix \"${CFG[log_prefix_observe]} \" --log-level ${CFG[log_level]}"
|
||||
fi
|
||||
printf '%s\n' "final${us}${us}$c${us}$a" "return${us}${us}$c${us}-j RETURN"
|
||||
a="-m limit --limit ${CFG[log_rate_enforce]} --limit-burst ${CFG[log_burst_enforce]}"
|
||||
a+=" -j LOG --log-prefix \"${CFG[log_prefix_drop]} \" --log-level ${CFG[log_level]}"
|
||||
printf '%s\n' "deny_log${us}${us}$d${us}$a" "deny_drop${us}${us}$d${us}-j DROP"
|
||||
# Container -> host rules: ufw-after-input is declared earlier in
|
||||
# after.rules, rules are only appended to it.
|
||||
for i in "${!C2H_PROTO[@]}"; do
|
||||
a="-i ${C2H_IFACE[i]} -p ${C2H_PROTO[i]} --dport ${C2H_PORT[i]} -j ACCEPT"
|
||||
printf '%s\n' "c2h${us}$i${us}ufw-after-input${us}$a"
|
||||
done
|
||||
}
|
||||
|
||||
# Splits the arguments of a rule into FENCE_ARGS; "..." is one argument
|
||||
# (only the log prefixes are quoted, and they hold no quote themselves).
|
||||
fence_split_args() {
|
||||
local s="$1" re='^[[:space:]]*"([^"]*)"(.*)$' re2='^[[:space:]]*([^[:space:]"]+)(.*)$'
|
||||
FENCE_ARGS=()
|
||||
while [[ -n "${s//[[:space:]]/}" ]]; do
|
||||
if [[ "$s" =~ $re || "$s" =~ $re2 ]]; then
|
||||
FENCE_ARGS+=("${BASH_REMATCH[1]}")
|
||||
s="${BASH_REMATCH[2]}"
|
||||
else
|
||||
return 1
|
||||
fi
|
||||
done
|
||||
}
|
||||
|
||||
# Prints the whole block to standard output.
|
||||
fence_generate_block() {
|
||||
local c d role _idx chain args c2h_open=0
|
||||
c="${CFG[chain]}"
|
||||
d="$(fence_deny_chain)"
|
||||
fence_block_begin; printf '\n'
|
||||
printf '*filter\n'
|
||||
printf ':DOCKER-USER - [0:0]\n'
|
||||
printf ':%s - [0:0]\n' "$c"
|
||||
printf ':%s - [0:0]\n' "$d"
|
||||
while IFS=$'\x1f' read -r role _idx chain args; do
|
||||
if [[ "$role" == c2h && "$c2h_open" -eq 0 ]]; then
|
||||
printf 'COMMIT\n*filter\n'
|
||||
c2h_open=1
|
||||
fi
|
||||
printf -- '-A %s %s\n' "$chain" "$args"
|
||||
done < <(fence_rule_list)
|
||||
printf 'COMMIT\n'
|
||||
fence_block_end; printf '\n'
|
||||
}
|
||||
+281
@@ -0,0 +1,281 @@
|
||||
# shellcheck shell=bash
|
||||
# rules: one table with the native UFW rules and the docker-fence rules.
|
||||
# Read only. UFW rules come from "ufw status verbose"; docker-fence rules
|
||||
# come from the configuration, and their state from "iptables -C" on the
|
||||
# exact rules of the block (lib/generate.sh).
|
||||
|
||||
# Table rows: fields separated by US, in column order.
|
||||
FENCE_ROWS=()
|
||||
|
||||
fence_row() {
|
||||
local IFS=$'\x1f'
|
||||
FENCE_ROWS+=("$*")
|
||||
}
|
||||
|
||||
# Length in characters (not bytes) of a string.
|
||||
fence_strlen() {
|
||||
local LC_ALL=C.UTF-8
|
||||
printf '%s' "${#1}"
|
||||
}
|
||||
|
||||
# Colors: --color always, never, or auto (standard output is a terminal,
|
||||
# NO_COLOR unset, TERM not dumb).
|
||||
fence_color_enabled() {
|
||||
case "${OPT_COLOR:-auto}" in
|
||||
always) return 0 ;;
|
||||
never) return 1 ;;
|
||||
esac
|
||||
[[ -t 1 && -z "${NO_COLOR:-}" && "${TERM:-dumb}" != dumb ]]
|
||||
}
|
||||
|
||||
# SGR code of a cell, from its column and value; empty for no color.
|
||||
# fence_cell_style KIND COLUMN TEXT (KIND: head, sep or row)
|
||||
fence_cell_style() {
|
||||
local kind="$1" col="$2" text="$3"
|
||||
case "$kind" in
|
||||
head) printf '1'; return ;;
|
||||
sep) printf '2'; return ;;
|
||||
esac
|
||||
case "$col" in
|
||||
0)
|
||||
case "$text" in
|
||||
ufw) printf '36' ;;
|
||||
fence) printf '35' ;;
|
||||
esac
|
||||
;;
|
||||
2)
|
||||
case "$text" in
|
||||
ALLOW) printf '1;32' ;;
|
||||
DENY|REJECT|DROP) printf '1;31' ;;
|
||||
LIMIT|LOG) printf '1;33' ;;
|
||||
esac
|
||||
;;
|
||||
5)
|
||||
if [[ "$text" == "$(fence_fmt l_loaded)" || "$text" == "$(fence_fmt l_active)" ]]; then
|
||||
printf '32'
|
||||
elif [[ "$text" == "$(fence_fmt l_not_loaded)" ]]; then
|
||||
printf '31'
|
||||
elif [[ "$text" == "$(fence_fmt l_unknown)" ]]; then
|
||||
printf '33'
|
||||
fi
|
||||
;;
|
||||
6) printf '2' ;;
|
||||
esac
|
||||
}
|
||||
|
||||
# Prints FENCE_ROWS as an aligned table, with a header.
|
||||
fence_print_table() {
|
||||
local -a head=("$@") widths=() cells
|
||||
local row i n w color=0
|
||||
fence_color_enabled && color=1
|
||||
for i in "${!head[@]}"; do
|
||||
widths[i]="$(fence_strlen "${head[i]}")"
|
||||
done
|
||||
for row in "${FENCE_ROWS[@]}"; do
|
||||
IFS=$'\x1f' read -r -a cells <<<"$row"
|
||||
for i in "${!head[@]}"; do
|
||||
n="$(fence_strlen "${cells[i]:-}")"
|
||||
(( n > widths[i] )) && widths[i]=$n
|
||||
done
|
||||
done
|
||||
fence_table_line head "${head[@]}"
|
||||
local -a dashes=()
|
||||
for i in "${!head[@]}"; do
|
||||
w="${widths[i]}"
|
||||
dashes+=("$(printf '%*s' "$w" '' | tr ' ' '-')")
|
||||
done
|
||||
fence_table_line sep "${dashes[@]}"
|
||||
for row in "${FENCE_ROWS[@]}"; do
|
||||
IFS=$'\x1f' read -r -a cells <<<"$row"
|
||||
local -a full=()
|
||||
for i in "${!head[@]}"; do
|
||||
full+=("${cells[i]:-}")
|
||||
done
|
||||
fence_table_line row "${full[@]}"
|
||||
done
|
||||
}
|
||||
|
||||
# One table line, padded to the widths computed by fence_print_table. The
|
||||
# padding is computed on the plain text, colors only wrap the text.
|
||||
# fence_table_line KIND CELL...
|
||||
fence_table_line() {
|
||||
local kind="$1"
|
||||
shift
|
||||
local i last=$(( $# - 1 )) cell pad out="" sgr
|
||||
local -a c=("$@")
|
||||
# Last non-empty cell: no trailing blanks after it.
|
||||
while (( last > 0 )) && [[ -z "${c[last]}" ]]; do
|
||||
last=$(( last - 1 ))
|
||||
done
|
||||
for i in "${!c[@]}"; do
|
||||
(( i <= last )) || break
|
||||
cell="${c[i]}"
|
||||
pad=$(( widths[i] - $(fence_strlen "$cell") ))
|
||||
if (( color )) && [[ -n "$cell" ]]; then
|
||||
sgr="$(fence_cell_style "$kind" "$i" "$cell")"
|
||||
[[ -n "$sgr" ]] && cell=$'\e['"${sgr}m$cell"$'\e[0m'
|
||||
fi
|
||||
out+="$cell"
|
||||
(( i < last )) && out+="$(printf '%*s' "$(( pad + 2 ))" '')"
|
||||
done
|
||||
printf '%s\n' "$out"
|
||||
}
|
||||
|
||||
# ---------------------------------------------------------------- UFW rules
|
||||
|
||||
# "Anywhere" -> any, "Anywhere on wg0" -> any on wg0 (translated); IPv6
|
||||
# marker removed.
|
||||
fence_ufw_addr() {
|
||||
local s="$1" iface=""
|
||||
s="${s/ (v6)/}"
|
||||
if [[ "$s" =~ ^(.*)\ on\ ([^ ]+)$ ]]; then
|
||||
s="${BASH_REMATCH[1]}"
|
||||
iface="${BASH_REMATCH[2]}"
|
||||
fi
|
||||
s="${s/Anywhere/$(fence_fmt l_any)}"
|
||||
[[ -n "$iface" ]] && s+=" $(fence_fmt l_on "$iface")"
|
||||
printf '%s' "$s"
|
||||
}
|
||||
|
||||
fence_ufw_rows() {
|
||||
local out line state to action from comment dir traffic note
|
||||
if ! out="$("${CFG[bin_ufw]}" status verbose 2>/dev/null)"; then
|
||||
fence_warn w_ufw_unreadable
|
||||
return 0
|
||||
fi
|
||||
if ! grep -q '^Status: active' <<<"$out"; then
|
||||
fence_warn w_ufw_inactive_rules
|
||||
return 0
|
||||
fi
|
||||
state="$(fence_fmt l_active)"
|
||||
local in_table=0
|
||||
local -a f
|
||||
while IFS= read -r line; do
|
||||
if [[ "$line" =~ ^--[[:space:]] ]]; then
|
||||
in_table=1
|
||||
continue
|
||||
fi
|
||||
(( in_table )) || continue
|
||||
[[ -n "${line//[[:space:]]/}" ]] || continue
|
||||
# Columns are separated by two blanks or more.
|
||||
mapfile -t f < <(sed -E 's/[[:space:]]{2,}/\n/g' <<<"$line")
|
||||
to="${f[0]:-}" action="${f[1]:-}" from="${f[2]:-}" comment="${f[3]:-}"
|
||||
comment="${comment#\# }"
|
||||
dir="${action##* }"
|
||||
action="${action%% *}"
|
||||
case "$dir" in
|
||||
OUT) traffic="$(fence_fmt l_host_out)" ;;
|
||||
FWD) traffic="$(fence_fmt l_routed)" ;;
|
||||
*) traffic="$(fence_fmt l_host_in)" ;;
|
||||
esac
|
||||
note="$comment"
|
||||
if [[ "$to" == *"(v6)"* || "$from" == *"(v6)"* ]]; then
|
||||
note="IPv6${note:+, $note}"
|
||||
fi
|
||||
fence_row ufw "$traffic" "$action" "$(fence_ufw_addr "$to")" "$(fence_ufw_addr "$from")" "$state" "$note"
|
||||
done <<<"$out"
|
||||
|
||||
# Default policies, applied after every rule.
|
||||
local def re='Default: ([a-z]+) \(incoming\), ([a-z]+) \(outgoing\), ([a-z]+|disabled) \(routed\)'
|
||||
def="$(grep -m1 '^Default:' <<<"$out" || true)"
|
||||
if [[ "$def" =~ $re ]]; then
|
||||
local any
|
||||
any="$(fence_fmt l_any)"
|
||||
fence_row ufw "$(fence_fmt l_host_in)" "${BASH_REMATCH[1]^^}" "$any" "$any" "$state" "$(fence_fmt l_default_policy)"
|
||||
fence_row ufw "$(fence_fmt l_host_out)" "${BASH_REMATCH[2]^^}" "$any" "$any" "$state" "$(fence_fmt l_default_policy)"
|
||||
fence_row ufw "$(fence_fmt l_routed)" "${BASH_REMATCH[3]^^}" "$any" "$any" "$state" "$(fence_fmt l_default_policy)"
|
||||
fi
|
||||
}
|
||||
|
||||
# ------------------------------------------------------- docker-fence rules
|
||||
|
||||
# State of one rule of the block, once the firewall is known to be readable:
|
||||
# loaded or not loaded. iptables -C exits 1 for a missing rule, but 2 when a
|
||||
# chain it names does not exist yet: both mean not loaded.
|
||||
fence_rule_state() {
|
||||
local chain="$1" args="$2"
|
||||
if fence_split_args "$args" \
|
||||
&& "${CFG[bin_iptables]}" -C "$chain" "${FENCE_ARGS[@]}" >/dev/null 2>&1; then
|
||||
fence_fmt l_loaded
|
||||
else
|
||||
fence_fmt l_not_loaded
|
||||
fi
|
||||
}
|
||||
|
||||
fence_port_text() {
|
||||
printf '%s/%s' "$(fence_port_conf "$1")" "$2"
|
||||
}
|
||||
|
||||
fence_fence_rows() {
|
||||
local role idx chain args state jump=ok any to from note
|
||||
any="$(fence_fmt l_any)"
|
||||
local pub c2h
|
||||
pub="$(fence_fmt l_published)"
|
||||
c2h="$(fence_fmt l_c2h)"
|
||||
# Firewall readable (root)? Otherwise every state is unknown.
|
||||
if fence_have bin_iptables && "${CFG[bin_iptables]}" -S INPUT >/dev/null 2>&1; then
|
||||
# Without the DOCKER-USER jump, no rule of the chain applies.
|
||||
if "${CFG[bin_iptables]}" -C DOCKER-USER -j "${CFG[chain]}" >/dev/null 2>&1; then
|
||||
jump=ok
|
||||
else
|
||||
jump=missing
|
||||
fi
|
||||
else
|
||||
jump=unknown
|
||||
fi
|
||||
while IFS=$'\x1f' read -r role idx chain args; do
|
||||
case "$role" in
|
||||
jump|return|deny_log|deny_drop) continue ;;
|
||||
esac
|
||||
if [[ "$jump" == unknown ]]; then
|
||||
state="$(fence_fmt l_unknown)"
|
||||
elif [[ "$role" != c2h && "$jump" == missing ]]; then
|
||||
state="$(fence_fmt l_not_loaded)"
|
||||
else
|
||||
state="$(fence_rule_state "$chain" "$args")"
|
||||
fi
|
||||
case "$role" in
|
||||
established)
|
||||
fence_row fence "$pub" ALLOW "$any" "$any" "$state" "$(fence_fmt l_replies)" ;;
|
||||
trusted)
|
||||
fence_row fence "$pub" ALLOW "$any" "$(fence_fmt l_iface "${TRUSTED_IFACE[idx]}")" "$state" "$(fence_fmt l_containers)" ;;
|
||||
admin)
|
||||
from="${ADMIN_SRC[idx]}"
|
||||
[[ -n "${ADMIN_IFACE[idx]}" ]] && from+=" $(fence_fmt l_on "${ADMIN_IFACE[idx]}")"
|
||||
fence_row fence "$pub" ALLOW "$(fence_fmt l_all_published)" "$from" "$state" "admin"
|
||||
;;
|
||||
allow)
|
||||
to="$(fence_port_text "${ALLOW_PORT[idx]}" "${ALLOW_PROTO[idx]}")"
|
||||
from="${ALLOW_SRC[idx]}"
|
||||
[[ "$from" == any ]] && from="$any"
|
||||
[[ -n "${ALLOW_IFACE[idx]}" ]] && from+=" $(fence_fmt l_on "${ALLOW_IFACE[idx]}")"
|
||||
fence_row fence "$pub" ALLOW "$to" "$from" "$state" "allow"
|
||||
;;
|
||||
final)
|
||||
if [[ "${CFG[mode]}" == enforce ]]; then
|
||||
note="$(fence_fmt l_final_enforce)"
|
||||
fence_row fence "$pub" DROP "$(fence_fmt l_other_published)" "$any" "$state" "$note"
|
||||
else
|
||||
note="$(fence_fmt l_final_observe)"
|
||||
fence_row fence "$pub" LOG "$(fence_fmt l_other_published)" "$any" "$state" "$note"
|
||||
fi
|
||||
;;
|
||||
c2h)
|
||||
to="$(fence_port_text "${C2H_PORT[idx]}" "${C2H_PROTO[idx]}")"
|
||||
fence_row fence "$c2h" ALLOW "$to" "$(fence_fmt l_iface "${C2H_IFACE[idx]}")" "$state" "container_to_host"
|
||||
;;
|
||||
esac
|
||||
done < <(fence_rule_list)
|
||||
}
|
||||
|
||||
fence_cmd_rules() {
|
||||
FENCE_ROWS=()
|
||||
if fence_have bin_ufw; then
|
||||
fence_ufw_rows
|
||||
else
|
||||
fence_warn w_missing_bin "${CFG[bin_ufw]}"
|
||||
fi
|
||||
fence_fence_rows
|
||||
fence_print_table "$(fence_fmt l_origin)" "$(fence_fmt l_traffic)" "$(fence_fmt l_action)" \
|
||||
"$(fence_fmt l_to)" "$(fence_fmt l_from)" "$(fence_fmt l_state)" "$(fence_fmt l_note)"
|
||||
}
|
||||
+486
@@ -0,0 +1,486 @@
|
||||
# shellcheck shell=bash
|
||||
# Every message of the tool, in English and French. Each value is a
|
||||
# printf format: a literal "%" is written "%%". Values from outside are
|
||||
# always passed as arguments, never inside the format.
|
||||
|
||||
declare -gA MSG_en=(
|
||||
[e_prefix]='error:'
|
||||
[w_prefix]='warning:'
|
||||
[block_header]='managed by docker-fence, do not edit by hand'
|
||||
|
||||
[v_int]='invalid value "%s": integer expected between %s'
|
||||
[v_ipv4]='invalid IPv4 address: "%s"'
|
||||
[v_ipv4_any]='"%s" covers every address: use "any" in allow, never in admin'
|
||||
[v_ipv4_hostbits]='"%s": host bits are set outside the mask (network address expected)'
|
||||
[v_port]='invalid port: "%s" (1 to 65535, or range a-b)'
|
||||
[v_port_range]='invalid port range: "%s" (a must be lower than b)'
|
||||
[v_proto]='invalid protocol: "%s" (tcp or udp)'
|
||||
[v_iface]='invalid interface name: "%s" (at most 15 characters among A-Z a-z 0-9 _ . -, trailing "+" accepted)'
|
||||
[v_path]='invalid path: "%s" (absolute path, characters A-Z a-z 0-9 _ . / -)'
|
||||
[v_bin]='invalid command: "%s" (plain name or absolute path)'
|
||||
[v_rate]='invalid rate: "%s" (for example 20/min)'
|
||||
[v_prefix]='invalid log prefix: "%s" (at most %s characters among A-Z a-z 0-9 _ . : -)'
|
||||
[v_chain]='invalid chain name: "%s" (at most %s characters among A-Z a-z 0-9 _ -)'
|
||||
[v_chain_reserved]='reserved chain name: "%s" (no DOCKER*, ufw-*, nor a kernel chain or target name)'
|
||||
[v_marker]='invalid block marker: "%s" (at most 40 characters among A-Z a-z 0-9 _ -)'
|
||||
[v_unit]='invalid unit name: "%s" (at most 64 characters among A-Z a-z 0-9 _ -)'
|
||||
[v_since]='invalid date: "%s" (for example "24 hours ago" or "2026-01-31 08:00")'
|
||||
[v_mode]='invalid mode: "%s" (observe or enforce)'
|
||||
[v_lang]='invalid language: "%s" (fr or en)'
|
||||
[v_unknown]='unknown setting: "%s"'
|
||||
|
||||
[e_syntax]='expected syntax: %s'
|
||||
[e_comment]='"#" must follow a blank to start a comment'
|
||||
[e_charset]='forbidden character: "%s" (nothing is interpreted by the shell)'
|
||||
[e_unknown_directive]='unknown directive: "%s"'
|
||||
[e_one_value]='"%s" takes exactly one value'
|
||||
[e_duplicate]='same rule as line %s'
|
||||
[e_no_admin]='at least one "admin" directive is required'
|
||||
[e_same_prefix]='log_prefix_observe and log_prefix_drop must differ'
|
||||
[e_no_config]='configuration file missing or unreadable: %s (see "docker-fence init")'
|
||||
[e_perm_owner]='%s must be owned by root (or by the user running the tool)'
|
||||
[e_perm_mode]='%s is writable by group or others (mode %s): chmod go-w'
|
||||
[e_env]='invalid variable %s: "%s"'
|
||||
[e_option]='invalid option: %s'
|
||||
[e_usage]='invalid usage: %s (see "docker-fence --help")'
|
||||
|
||||
[i_versions]='bash %s; docker %s; %s; %s'
|
||||
[w_missing_bin]='command not found: %s'
|
||||
[e_missing_bin]='command not found: %s'
|
||||
[e_docker_no_iptables]='%s disables iptables in Docker: not supported'
|
||||
[e_docker_nftables]='%s enables the native nftables firewall backend of Docker: not supported'
|
||||
[w_ipv6]='%s enables IPv6: IPv6 traffic is not filtered by docker-fence'
|
||||
[w_macvlan]='%s networks found (%s): their traffic bypasses DOCKER-USER and is not filtered'
|
||||
[w_no_docker]='docker unreachable: containers will not be named'
|
||||
|
||||
[e_no_rules]='rules file missing or unreadable: %s'
|
||||
[e_block_twice]='%s contains the start of block "%s" twice'
|
||||
[e_block_end]='%s contains an end of block "%s" without a start'
|
||||
[e_block_unclosed]='%s contains a block "%s" without an end'
|
||||
[e_legacy_present]='%s contains the original ufw-docker block (below): run again with --replace-legacy to replace it'
|
||||
[w_legacy_unknown]='the original block differs from the known version (differences below)'
|
||||
[e_legacy_unknown]='unknown original block: review the differences, then run again with --replace-legacy --force'
|
||||
[e_legacy_already]='%s already contains an original ufw-docker block'
|
||||
[e_no_legacy_saved]='no saved original block: %s'
|
||||
[i_legacy_saved]='original block saved: %s'
|
||||
[e_backup]='cannot write a backup in %s'
|
||||
[i_backup]='backup: %s'
|
||||
[e_write]='cannot write: %s'
|
||||
[i_written]='written: %s'
|
||||
[i_unchanged]='%s is already up to date, nothing to write'
|
||||
[i_install_done]='block installed; it loads on the next "ufw reload" (or use "docker-fence apply")'
|
||||
[i_log_unwritable]='log not writable: %s'
|
||||
[i_running]='running: %s'
|
||||
[i_config_ok]='configuration valid: %s (mode %s; %s admin, %s allow, %s container_to_host)'
|
||||
|
||||
[e_pending]='an automatic rollback is pending (%s): run "docker-fence confirm" or "docker-fence rollback" first'
|
||||
[e_ufw_inactive]='UFW is inactive: "ufw reload" would load nothing'
|
||||
[e_timer]='cannot schedule the rollback (%s): file restored, nothing was reloaded'
|
||||
[i_timer]='automatic rollback scheduled in %s s (unit %s)'
|
||||
[e_reload]='"ufw reload" failed'
|
||||
[e_verify_jump]='after reload, DOCKER-USER does not jump to %s'
|
||||
[e_verify_empty]='after reload, chain %s is empty'
|
||||
[e_verify_c2h]='after reload, container_to_host rule %s %s is missing from ufw-after-input'
|
||||
[e_apply_failed]='apply cancelled: rollback done'
|
||||
[i_apply_done]='block loaded (mode %s)'
|
||||
[i_confirm]='Confirm with "docker-fence confirm" within %s seconds, or the change rolls back automatically.'
|
||||
[i_nothing_pending]='no rollback pending (already confirmed, or already rolled back: see "docker-fence status")'
|
||||
[w_timer_stop]='cannot stop the timer: %s'
|
||||
[i_confirmed]='confirmed: the automatic rollback is cancelled'
|
||||
[e_no_backup]='backup missing or unreadable: %s'
|
||||
[e_no_backups]='no backup in %s'
|
||||
[i_restored]='restored: %s -> %s'
|
||||
[i_kernel_cleaned]='chain %s removed from the kernel'
|
||||
|
||||
[i_not_installed]='no managed block in %s'
|
||||
[i_uninstalled]='block removed (UFW inactive: nothing reloaded)'
|
||||
[i_uninstalled_reloaded]='block removed and UFW reloaded'
|
||||
[w_rules_unreadable]='rules file unreadable: %s'
|
||||
[i_status_block]='block installed in %s (mode %s)'
|
||||
[i_status_noblock]='no block installed in %s'
|
||||
[i_status_pending]='rollback pending (%s), backup: %s'
|
||||
[i_status_jump_yes]='jump DOCKER-USER -> %s: present'
|
||||
[i_status_jump_no]='jump DOCKER-USER -> %s: missing'
|
||||
[i_status_counters]='counters:'
|
||||
[i_status_log]='last log lines:'
|
||||
|
||||
[i_report_head]='report since "%s": %s logged packets'
|
||||
[r_count]='count'
|
||||
[r_source]='source'
|
||||
[r_target]='container:internal port'
|
||||
[r_published]='published port'
|
||||
[r_suggestions]='suggested allow lines (port published on the host):'
|
||||
[r_no_published]='%s -> %s: published port not found'
|
||||
|
||||
[p_intro]='ufw commands for host rules, in a safe order. docker-fence runs none of them.'
|
||||
[p_never_run]='Keep an admin session open and test each access from another session.'
|
||||
[p_admin]='Admin access to the host (first)'
|
||||
[p_allow]='allow exceptions: only for a port served by the host or a host-network container (a port published by Docker is covered by docker-fence)'
|
||||
[p_c2h]='container_to_host fallback, only if these rules are not loaded in ufw-after-input (one command per Docker network)'
|
||||
[p_no_subnets]='no Docker subnet found (docker unreachable?)'
|
||||
[p_delete]='Removal of old, too broad rules (last, review one by one)'
|
||||
[p_ssh_warning]='Never remove the SSH access rule before testing every admin address.'
|
||||
[p_no_added]='no rule read ("ufw show added" needs root)'
|
||||
[p_host_network]='Containers in network_mode: host bypass docker-fence: their ports are covered by the ufw rules above.'
|
||||
|
||||
[e_exists]='%s already exists (use --force to overwrite it)'
|
||||
[i_init_done]='template written: %s'
|
||||
[t_title]='docker-fence: configuration (one directive per line, see README)'
|
||||
[t_format]='Format: directive value...; "#" starts a comment; nothing is interpreted by the shell.'
|
||||
[t_defaults]='Commented settings show their default value.'
|
||||
[t_admin]='Source allowed to every published port (at least one).'
|
||||
[t_admin_doc]='192.0.2.10 is a documentation address: replace it.'
|
||||
[t_allow]='Exception: port published on the host and allowed source.'
|
||||
[t_c2h]='A container reaches this host port (INPUT rule; default interface br-+).'
|
||||
[t_trusted]='Trusted container interfaces (default br-+ and docker0).'
|
||||
[t_settings]='Settings'
|
||||
[o_header]='effective configuration, read from %s'
|
||||
[o_default]='default'
|
||||
[o_option]='option'
|
||||
[o_env]='environment'
|
||||
[o_file]='line %s'
|
||||
|
||||
[d_mode]='mode: observe logs what would be blocked; enforce blocks'
|
||||
[d_rollback_seconds]='delay before automatic rollback after apply (seconds, 30 to 86400)'
|
||||
[d_lang]='message language: fr or en'
|
||||
[d_log_rate_observe]='log rate in observe mode'
|
||||
[d_log_burst_observe]='log burst in observe mode'
|
||||
[d_log_rate_enforce]='log rate in enforce mode'
|
||||
[d_log_burst_enforce]='log burst in enforce mode'
|
||||
[d_log_prefix_observe]='log prefix in observe mode (at most 28 characters)'
|
||||
[d_log_prefix_drop]='log prefix in enforce mode (at most 28 characters)'
|
||||
[d_log_level]='kernel log level (0 to 7)'
|
||||
[d_log_file]='log of the actions of the tool'
|
||||
[d_chain]='chain name; the reject chain is <name>-deny'
|
||||
[d_block_marker]='marker of the # BEGIN and # END lines of the block'
|
||||
[d_unit_name]='systemd unit of the automatic rollback'
|
||||
[d_ufw_after_rules]='rules file to edit'
|
||||
[d_docker_daemon_json]='Docker daemon configuration (environment checks)'
|
||||
[d_backup_dir]='backup directory'
|
||||
[d_backup_keep]='number of backups kept'
|
||||
[d_report_since]='default report period (journalctl --since syntax)'
|
||||
[d_bin_iptables]='iptables command'
|
||||
[d_bin_ufw]='ufw command'
|
||||
[d_bin_docker]='docker command'
|
||||
[d_bin_journalctl]='journalctl command'
|
||||
[d_bin_systemd_run]='systemd-run command'
|
||||
[d_bin_systemctl]='systemctl command'
|
||||
|
||||
[usage]='Usage: docker-fence [options] <command> [command options]
|
||||
|
||||
Commands:
|
||||
check validate the configuration and print the generated block
|
||||
status state of the block, the kernel and the log
|
||||
install [--replace-legacy] [--force]
|
||||
write the block into after.rules, without reloading UFW
|
||||
apply [--replace-legacy] [--force]
|
||||
install, then reload with automatic rollback
|
||||
confirm cancel the automatic rollback
|
||||
rollback [--auto] [file] restore the latest backup (or the given one)
|
||||
uninstall [--restore-legacy]
|
||||
remove the managed block
|
||||
report [--since date] observation report
|
||||
ufw-plan print the ufw commands for host rules
|
||||
rules [--color auto|always|never]
|
||||
table of every rule: native UFW and docker-fence
|
||||
init [--output file] [--force]
|
||||
write a configuration template ("-": standard output)
|
||||
show-config effective configuration and origin of each value
|
||||
|
||||
Options:
|
||||
-c, --config file configuration file
|
||||
--mode observe|enforce override the mode of the file
|
||||
--lang fr|en message language
|
||||
--set directive=value override a setting of the file
|
||||
-q, --quiet print errors only
|
||||
-v, --verbose print the commands that run
|
||||
-h, --help this help
|
||||
--version version
|
||||
|
||||
Exit codes: 0 success; 1 configuration or usage; 2 unsupported environment;
|
||||
3 original ufw-docker block present; 4 apply failed (rollback done).'
|
||||
|
||||
[l_origin]='ORIGIN'
|
||||
[l_traffic]='TRAFFIC'
|
||||
[l_action]='ACTION'
|
||||
[l_to]='TO'
|
||||
[l_from]='FROM'
|
||||
[l_state]='STATE'
|
||||
[l_note]='NOTE'
|
||||
[l_any]='any'
|
||||
[l_on]='on %s'
|
||||
[l_iface]='iface %s'
|
||||
[l_host_in]='host input'
|
||||
[l_host_out]='host output'
|
||||
[l_routed]='routed'
|
||||
[l_published]='published ports'
|
||||
[l_c2h]='container -> host'
|
||||
[l_all_published]='all published ports'
|
||||
[l_other_published]='other published ports'
|
||||
[l_active]='active'
|
||||
[l_loaded]='loaded'
|
||||
[l_not_loaded]='not loaded'
|
||||
[l_unknown]='unknown (root?)'
|
||||
[l_default_policy]='default policy'
|
||||
[l_replies]='replies to established connections'
|
||||
[l_containers]='trusted containers'
|
||||
[l_final_observe]='observe mode: logged, not blocked'
|
||||
[l_final_enforce]='enforce mode: logged and dropped'
|
||||
[w_ufw_unreadable]='cannot read "ufw status verbose" (root needed): UFW rules not listed'
|
||||
[w_ufw_inactive_rules]='UFW is inactive: no UFW rule applies, and "docker-fence apply" needs UFW active'
|
||||
)
|
||||
|
||||
declare -gA MSG_fr=(
|
||||
[e_prefix]='erreur :'
|
||||
[w_prefix]='attention :'
|
||||
[block_header]='géré par docker-fence, ne pas modifier à la main'
|
||||
|
||||
# Value validation (argument 1: value; 2: detail).
|
||||
[v_int]='valeur « %s » invalide : entier attendu entre %s'
|
||||
[v_ipv4]='adresse IPv4 invalide : « %s »'
|
||||
[v_ipv4_any]='« %s » couvre toutes les adresses : utilisez « any » dans allow, jamais dans admin'
|
||||
[v_ipv4_hostbits]='« %s » : des bits d'"'"'hôte sont posés hors du masque (adresse de réseau attendue)'
|
||||
[v_port]='port invalide : « %s » (1 à 65535, ou plage a-b)'
|
||||
[v_port_range]='plage de ports invalide : « %s » (a doit être inférieur à b)'
|
||||
[v_proto]='protocole invalide : « %s » (tcp ou udp)'
|
||||
[v_iface]='nom d'"'"'interface invalide : « %s » (15 caractères au plus parmi A-Z a-z 0-9 _ . -, « + » final accepté)'
|
||||
[v_path]='chemin invalide : « %s » (chemin absolu, caractères A-Z a-z 0-9 _ . / -)'
|
||||
[v_bin]='commande invalide : « %s » (nom simple ou chemin absolu)'
|
||||
[v_rate]='cadence invalide : « %s » (par exemple 20/min)'
|
||||
[v_prefix]='préfixe de journal invalide : « %s » (%s caractères au plus parmi A-Z a-z 0-9 _ . : -)'
|
||||
[v_chain]='nom de chaîne invalide : « %s » (%s caractères au plus parmi A-Z a-z 0-9 _ -)'
|
||||
[v_chain_reserved]='nom de chaîne réservé : « %s » (pas de DOCKER*, ufw-*, ni de nom de chaîne ou de cible du noyau)'
|
||||
[v_marker]='marqueur de bloc invalide : « %s » (40 caractères au plus parmi A-Z a-z 0-9 _ -)'
|
||||
[v_unit]='nom d'"'"'unité invalide : « %s » (64 caractères au plus parmi A-Z a-z 0-9 _ -)'
|
||||
[v_since]='date invalide : « %s » (par exemple « 24 hours ago » ou « 2026-01-31 08:00 »)'
|
||||
[v_mode]='mode invalide : « %s » (observe ou enforce)'
|
||||
[v_lang]='langue invalide : « %s » (fr ou en)'
|
||||
[v_unknown]='réglage inconnu : « %s »'
|
||||
|
||||
# File parsing.
|
||||
[e_syntax]='syntaxe attendue : %s'
|
||||
[e_comment]='« # » doit être précédé d'"'"'un blanc pour commencer un commentaire'
|
||||
[e_charset]='caractère interdit : « %s » (rien n'"'"'est interprété par le shell)'
|
||||
[e_unknown_directive]='directive inconnue : « %s »'
|
||||
[e_one_value]='« %s » attend une seule valeur'
|
||||
[e_duplicate]='règle identique à celle de la ligne %s'
|
||||
[e_no_admin]='au moins une directive « admin » est obligatoire'
|
||||
[e_same_prefix]='log_prefix_observe et log_prefix_drop doivent être différents'
|
||||
[e_no_config]='fichier de configuration introuvable ou illisible : %s (voir « docker-fence init »)'
|
||||
[e_perm_owner]='%s doit appartenir à root (ou à l'"'"'utilisateur qui lance l'"'"'outil)'
|
||||
[e_perm_mode]='%s est modifiable par le groupe ou les autres (droits %s) : chmod go-w'
|
||||
[e_env]='variable %s invalide : « %s »'
|
||||
[e_option]='option invalide : %s'
|
||||
[e_usage]='usage invalide : %s (voir « docker-fence --help »)'
|
||||
|
||||
# Environment.
|
||||
[i_versions]='bash %s ; docker %s ; %s ; %s'
|
||||
[w_missing_bin]='commande introuvable : %s'
|
||||
[e_missing_bin]='commande introuvable : %s'
|
||||
[e_docker_no_iptables]='%s désactive iptables dans Docker : non supporté'
|
||||
[e_docker_nftables]='%s active le pare-feu nftables natif de Docker : non supporté'
|
||||
[w_ipv6]='%s active IPv6 : le trafic IPv6 n'"'"'est pas filtré par docker-fence'
|
||||
[w_macvlan]='réseaux %s présents (%s) : leur trafic ne passe pas par DOCKER-USER et n'"'"'est pas filtré'
|
||||
[w_no_docker]='docker injoignable : les conteneurs ne seront pas nommés'
|
||||
|
||||
# Rules file.
|
||||
[e_no_rules]='fichier de règles introuvable ou illisible : %s'
|
||||
[e_block_twice]='%s contient deux fois le début du bloc « %s »'
|
||||
[e_block_end]='%s contient une fin du bloc « %s » sans début'
|
||||
[e_block_unclosed]='%s contient un bloc « %s » sans fin'
|
||||
[e_legacy_present]='%s contient le bloc d'"'"'origine d'"'"'ufw-docker (ci-dessous) : relancez avec --replace-legacy pour le remplacer'
|
||||
[w_legacy_unknown]='le bloc d'"'"'origine diffère de la version connue (différences ci-dessous)'
|
||||
[e_legacy_unknown]='bloc d'"'"'origine inconnu : vérifiez les différences, puis relancez avec --replace-legacy --force'
|
||||
[e_legacy_already]='%s contient déjà un bloc d'"'"'origine d'"'"'ufw-docker'
|
||||
[e_no_legacy_saved]='aucun bloc d'"'"'origine sauvegardé : %s'
|
||||
[i_legacy_saved]='bloc d'"'"'origine sauvegardé : %s'
|
||||
[e_backup]='sauvegarde impossible dans %s'
|
||||
[i_backup]='sauvegarde : %s'
|
||||
[e_write]='écriture impossible : %s'
|
||||
[i_written]='écrit : %s'
|
||||
[i_unchanged]='%s est déjà à jour, rien à écrire'
|
||||
[i_install_done]='bloc installé ; il sera chargé au prochain « ufw reload » (ou utilisez « docker-fence apply »)'
|
||||
[i_log_unwritable]='journal non modifiable : %s'
|
||||
[i_running]='exécution : %s'
|
||||
[i_config_ok]='configuration valide : %s (mode %s ; %s admin, %s allow, %s container_to_host)'
|
||||
|
||||
# apply, confirm, rollback.
|
||||
[e_pending]='un retour arrière automatique est en attente (%s) : « docker-fence confirm » ou « docker-fence rollback » d'"'"'abord'
|
||||
[e_ufw_inactive]='UFW est inactif : « ufw reload » ne chargerait rien'
|
||||
[e_timer]='impossible de programmer le retour arrière (%s) : fichier restauré, rien n'"'"'a été rechargé'
|
||||
[i_timer]='retour arrière automatique programmé dans %s s (unité %s)'
|
||||
[e_reload]='échec de « ufw reload »'
|
||||
[e_verify_jump]='après rechargement, DOCKER-USER ne saute pas vers %s'
|
||||
[e_verify_empty]='après rechargement, la chaîne %s est vide'
|
||||
[e_verify_c2h]='après rechargement, la règle container_to_host %s %s est absente de ufw-after-input'
|
||||
[e_apply_failed]='application annulée : retour arrière effectué'
|
||||
[i_apply_done]='bloc chargé (mode %s)'
|
||||
[i_confirm]='Confirmez avec « docker-fence confirm » avant %s secondes, sinon retour arrière automatique.'
|
||||
[i_nothing_pending]='aucun retour arrière en attente (déjà confirmé, ou déjà effectué : voir « docker-fence status »)'
|
||||
[w_timer_stop]='arrêt du minuteur impossible : %s'
|
||||
[i_confirmed]='confirmé : le retour arrière automatique est annulé'
|
||||
[e_no_backup]='sauvegarde introuvable ou illisible : %s'
|
||||
[e_no_backups]='aucune sauvegarde dans %s'
|
||||
[i_restored]='restauré : %s -> %s'
|
||||
[i_kernel_cleaned]='chaîne %s retirée du noyau'
|
||||
|
||||
# uninstall, status.
|
||||
[i_not_installed]='aucun bloc géré dans %s'
|
||||
[i_uninstalled]='bloc retiré (UFW inactif : rien rechargé)'
|
||||
[i_uninstalled_reloaded]='bloc retiré et UFW rechargé'
|
||||
[w_rules_unreadable]='fichier de règles illisible : %s'
|
||||
[i_status_block]='bloc installé dans %s (mode %s)'
|
||||
[i_status_noblock]='aucun bloc installé dans %s'
|
||||
[i_status_pending]='retour arrière en attente (%s), sauvegarde : %s'
|
||||
[i_status_jump_yes]='saut DOCKER-USER -> %s : présent'
|
||||
[i_status_jump_no]='saut DOCKER-USER -> %s : absent'
|
||||
[i_status_counters]='compteurs :'
|
||||
[i_status_log]='dernières lignes du journal :'
|
||||
|
||||
# report.
|
||||
[i_report_head]='rapport depuis « %s » : %s paquets journalisés'
|
||||
[r_count]='nombre'
|
||||
[r_source]='source'
|
||||
[r_target]='conteneur:port interne'
|
||||
[r_published]='port publié'
|
||||
[r_suggestions]='lignes allow proposées (port publié sur l'"'"'hôte) :'
|
||||
[r_no_published]='%s -> %s : port publié introuvable'
|
||||
|
||||
# ufw-plan.
|
||||
[p_intro]='Commandes ufw pour les règles d'"'"'hôte, dans l'"'"'ordre sûr. Rien n'"'"'est exécuté par docker-fence.'
|
||||
[p_never_run]='Gardez une session d'"'"'administration ouverte et testez chaque accès depuis une autre session.'
|
||||
[p_admin]='Accès d'"'"'administration à l'"'"'hôte (en premier)'
|
||||
[p_allow]='Exceptions allow : seulement pour un port servi par l'"'"'hôte ou un conteneur en réseau hôte (un port publié par Docker est couvert par docker-fence)'
|
||||
[p_c2h]='Repli container_to_host, seulement si ces règles ne sont pas chargées dans ufw-after-input (une commande par réseau Docker)'
|
||||
[p_no_subnets]='aucun sous-réseau Docker trouvé (docker injoignable ?)'
|
||||
[p_delete]='Suppression des anciennes règles trop larges (en dernier, à examiner une par une)'
|
||||
[p_ssh_warning]='Ne retirez jamais la règle d'"'"'accès SSH avant d'"'"'avoir testé chaque adresse d'"'"'administration.'
|
||||
[p_no_added]='aucune règle lue (« ufw show added » demande les droits root)'
|
||||
[p_host_network]='Les conteneurs en network_mode: host ne passent pas par docker-fence : leurs ports relèvent des règles ufw ci-dessus.'
|
||||
|
||||
# init, show-config.
|
||||
[e_exists]='%s existe déjà (utilisez --force pour l'"'"'écraser)'
|
||||
[i_init_done]='modèle écrit : %s'
|
||||
[t_title]='docker-fence : configuration (une directive par ligne, voir README)'
|
||||
[t_format]='Format : directive valeur… ; « # » commence un commentaire ; rien n'"'"'est interprété par le shell.'
|
||||
[t_defaults]='Les réglages commentés montrent leur valeur par défaut.'
|
||||
[t_admin]='Source autorisée vers tous les ports publiés (au moins une).'
|
||||
[t_admin_doc]='192.0.2.10 est une adresse de documentation : remplacez-la.'
|
||||
[t_allow]='Exception : port publié sur l'"'"'hôte et source autorisée.'
|
||||
[t_c2h]='Un conteneur joint ce port de l'"'"'hôte (règle INPUT ; interface par défaut br-+).'
|
||||
[t_trusted]='Interfaces de conteneurs de confiance (par défaut br-+ et docker0).'
|
||||
[t_settings]='Réglages'
|
||||
[o_header]='configuration effective, lue dans %s'
|
||||
[o_default]='défaut'
|
||||
[o_option]='option'
|
||||
[o_env]='environnement'
|
||||
[o_file]='ligne %s'
|
||||
|
||||
[d_mode]='mode : observe journalise ce qui serait bloqué ; enforce bloque'
|
||||
[d_rollback_seconds]='délai avant retour arrière automatique après apply (secondes, 30 à 86400)'
|
||||
[d_lang]='langue des messages : fr ou en'
|
||||
[d_log_rate_observe]='cadence du journal en observation'
|
||||
[d_log_burst_observe]='rafale du journal en observation'
|
||||
[d_log_rate_enforce]='cadence du journal en application'
|
||||
[d_log_burst_enforce]='rafale du journal en application'
|
||||
[d_log_prefix_observe]='préfixe de journal en observation (28 caractères au plus)'
|
||||
[d_log_prefix_drop]='préfixe de journal en application (28 caractères au plus)'
|
||||
[d_log_level]='niveau de journal du noyau (0 à 7)'
|
||||
[d_log_file]='journal des actions de l'"'"'outil'
|
||||
[d_chain]='nom de la chaîne ; la chaîne de rejet est <nom>-deny'
|
||||
[d_block_marker]='marqueur des lignes # BEGIN et # END du bloc'
|
||||
[d_unit_name]='unité systemd du retour arrière automatique'
|
||||
[d_ufw_after_rules]='fichier de règles modifié'
|
||||
[d_docker_daemon_json]='configuration du démon Docker (contrôles d'"'"'environnement)'
|
||||
[d_backup_dir]='répertoire des sauvegardes'
|
||||
[d_backup_keep]='nombre de sauvegardes conservées'
|
||||
[d_report_since]='période par défaut du rapport (syntaxe de journalctl --since)'
|
||||
[d_bin_iptables]='commande iptables'
|
||||
[d_bin_ufw]='commande ufw'
|
||||
[d_bin_docker]='commande docker'
|
||||
[d_bin_journalctl]='commande journalctl'
|
||||
[d_bin_systemd_run]='commande systemd-run'
|
||||
[d_bin_systemctl]='commande systemctl'
|
||||
|
||||
[usage]='Usage : docker-fence [options] <commande> [options de la commande]
|
||||
|
||||
Commandes :
|
||||
check valide la configuration et affiche le bloc généré
|
||||
status état du bloc, du noyau et du journal
|
||||
install [--replace-legacy] [--force]
|
||||
écrit le bloc dans after.rules, sans recharger UFW
|
||||
apply [--replace-legacy] [--force]
|
||||
install, puis rechargement avec retour arrière automatique
|
||||
confirm annule le retour arrière automatique
|
||||
rollback [--auto] [fichier] restaure la dernière sauvegarde (ou celle indiquée)
|
||||
uninstall [--restore-legacy]
|
||||
retire le bloc géré
|
||||
report [--since date] rapport d'"'"'observation
|
||||
ufw-plan imprime les commandes ufw pour les règles d'"'"'hôte
|
||||
rules [--color auto|always|never]
|
||||
tableau de toutes les règles : UFW natives et docker-fence
|
||||
init [--output fichier] [--force]
|
||||
écrit un modèle de configuration (« - » : sortie standard)
|
||||
show-config configuration effective et origine de chaque valeur
|
||||
|
||||
Options :
|
||||
-c, --config fichier fichier de configuration
|
||||
--mode observe|enforce remplace le mode du fichier
|
||||
--lang fr|en langue des messages
|
||||
--set directive=valeur remplace un réglage du fichier
|
||||
-q, --quiet n'"'"'affiche que les erreurs
|
||||
-v, --verbose affiche les commandes exécutées
|
||||
-h, --help cette aide
|
||||
--version version
|
||||
|
||||
Codes de retour : 0 succès ; 1 configuration ou usage ; 2 environnement non supporté ;
|
||||
3 bloc d'"'"'origine d'"'"'ufw-docker présent ; 4 échec à l'"'"'application (retour arrière fait).'
|
||||
|
||||
[l_origin]='ORIGINE'
|
||||
[l_traffic]='TRAFIC'
|
||||
[l_action]='ACTION'
|
||||
[l_to]='VERS'
|
||||
[l_from]='DEPUIS'
|
||||
[l_state]='ÉTAT'
|
||||
[l_note]='NOTE'
|
||||
[l_any]='tout'
|
||||
[l_on]='via %s'
|
||||
[l_iface]='interface %s'
|
||||
[l_host_in]='entrant hôte'
|
||||
[l_host_out]='sortant hôte'
|
||||
[l_routed]='routé'
|
||||
[l_published]='ports publiés'
|
||||
[l_c2h]='conteneur -> hôte'
|
||||
[l_all_published]='tous les ports publiés'
|
||||
[l_other_published]='autres ports publiés'
|
||||
[l_active]='actif'
|
||||
[l_loaded]='chargée'
|
||||
[l_not_loaded]='non chargée'
|
||||
[l_unknown]='inconnu (root ?)'
|
||||
[l_default_policy]='politique par défaut'
|
||||
[l_replies]='réponses aux connexions établies'
|
||||
[l_containers]='conteneurs de confiance'
|
||||
[l_final_observe]='mode observe : journalisé, non bloqué'
|
||||
[l_final_enforce]='mode enforce : journalisé et rejeté'
|
||||
[w_ufw_unreadable]='lecture de « ufw status verbose » impossible (root nécessaire) : règles UFW non listées'
|
||||
[w_ufw_inactive_rules]='UFW est inactif : aucune règle UFW ne s'"'"'applique, et « docker-fence apply » exige UFW actif'
|
||||
)
|
||||
|
||||
# fence_fmt KEY [ARGS...]: without arguments, prints the raw format; with
|
||||
# arguments, prints it formatted.
|
||||
fence_fmt() {
|
||||
local key="$1" lang="${CFG[lang]:-en}" f
|
||||
shift
|
||||
if [[ "$lang" == fr ]]; then
|
||||
f="${MSG_fr[$key]-}"
|
||||
else
|
||||
f="${MSG_en[$key]-}"
|
||||
fi
|
||||
[[ -n "$f" ]] || f="$key"
|
||||
if (( $# == 0 )); then
|
||||
printf '%s' "$f"
|
||||
else
|
||||
# shellcheck disable=SC2059
|
||||
printf "$f" "$@"
|
||||
fi
|
||||
}
|
||||
+176
@@ -0,0 +1,176 @@
|
||||
# shellcheck shell=bash
|
||||
# Observation report (report) and host rules plan (ufw-plan).
|
||||
# Neither changes anything.
|
||||
|
||||
# Container table: IP -> name, and (IP, internal port, proto) -> ports
|
||||
# published on the host (IPv4). Only the name, addresses and ports are
|
||||
# requested from docker inspect: never the environment nor the arguments.
|
||||
fence_container_table() {
|
||||
declare -gA NAME_BY_IP=() PUB_BY_TARGET=()
|
||||
fence_have bin_docker || return 1
|
||||
local -a ids
|
||||
mapfile -t ids < <("${CFG[bin_docker]}" ps -q 2>/dev/null)
|
||||
(( ${#ids[@]} > 0 )) || return 0
|
||||
# shellcheck disable=SC2016 # Go template, not a shell expansion
|
||||
local fmt='{{.Name}}|{{range .NetworkSettings.Networks}}{{.IPAddress}} {{end}}|{{range $p, $c := .NetworkSettings.Ports}}{{if $c}}{{$p}}={{range $c}}{{.HostIp}}:{{.HostPort}},{{end}} {{end}}{{end}}'
|
||||
local line name ips ports ip tok key b hip hport
|
||||
while IFS= read -r line; do
|
||||
IFS='|' read -r name ips ports <<<"$line"
|
||||
name="${name#/}"
|
||||
for ip in $ips; do
|
||||
[[ "$ip" =~ ^[0-9.]+$ ]] || continue
|
||||
NAME_BY_IP[$ip]="$name"
|
||||
for tok in $ports; do
|
||||
key="${tok%%=*}" # 80/tcp
|
||||
[[ "$key" =~ ^([0-9]+)/(tcp|udp)$ ]] || continue
|
||||
local cport="${BASH_REMATCH[1]}" cproto="${BASH_REMATCH[2]}"
|
||||
local -a binds
|
||||
IFS=',' read -r -a binds <<<"${tok#*=}"
|
||||
for b in "${binds[@]}"; do
|
||||
[[ -n "$b" ]] || continue
|
||||
hport="${b##*:}"
|
||||
hip="${b%:*}"
|
||||
[[ "$hip" == *:* ]] && continue # IPv6, out of scope
|
||||
local t="$ip|$cport|$cproto"
|
||||
if [[ " ${PUB_BY_TARGET[$t]:-} " != *" $hport "* ]]; then
|
||||
PUB_BY_TARGET[$t]="${PUB_BY_TARGET[$t]:+${PUB_BY_TARGET[$t]} }$hport"
|
||||
fi
|
||||
done
|
||||
done
|
||||
done
|
||||
done < <("${CFG[bin_docker]}" inspect --format "$fmt" "${ids[@]}" 2>/dev/null)
|
||||
}
|
||||
|
||||
fence_cmd_report() {
|
||||
local since="${OPT_SINCE:-${CFG[report_since]}}"
|
||||
if ! fence_v_since "$since"; then
|
||||
fence_error e_option "--since $since"
|
||||
return "$FENCE_EXIT_CONFIG"
|
||||
fi
|
||||
fence_env_require_bins bin_journalctl || return "$FENCE_EXIT_ENV"
|
||||
if ! fence_container_table; then
|
||||
fence_warn w_no_docker
|
||||
fi
|
||||
|
||||
declare -A count=()
|
||||
local line src dst proto dpt total=0
|
||||
local re_src='[[:space:]]SRC=([0-9.]+)' re_dst='[[:space:]]DST=([0-9.]+)'
|
||||
local re_proto='[[:space:]]PROTO=([A-Za-z]+)' re_dpt='[[:space:]]DPT=([0-9]+)'
|
||||
while IFS= read -r line; do
|
||||
[[ "$line" =~ $re_src ]] || continue
|
||||
src="${BASH_REMATCH[1]}"
|
||||
[[ "$line" =~ $re_dst ]] || continue
|
||||
dst="${BASH_REMATCH[1]}"
|
||||
[[ "$line" =~ $re_proto ]] || continue
|
||||
proto="${BASH_REMATCH[1],,}"
|
||||
[[ "$line" =~ $re_dpt ]] || continue
|
||||
dpt="${BASH_REMATCH[1]}"
|
||||
count["$src|$dst|$dpt|$proto"]=$(( ${count["$src|$dst|$dpt|$proto"]:-0} + 1 ))
|
||||
total=$((total + 1))
|
||||
done < <("${CFG[bin_journalctl]}" -k --no-pager -o short-iso --since "$since" 2>/dev/null \
|
||||
| grep -F -e "${CFG[log_prefix_observe]} " -e "${CFG[log_prefix_drop]} " || true)
|
||||
|
||||
fence_info i_report_head "$since" "$total"
|
||||
if (( total == 0 )); then
|
||||
return 0
|
||||
fi
|
||||
|
||||
local k n name pubs p
|
||||
local -a sorted suggestions=()
|
||||
declare -A suggested=()
|
||||
mapfile -t sorted < <(for k in "${!count[@]}"; do printf '%s|%s\n' "${count[$k]}" "$k"; done \
|
||||
| sort -t '|' -k1,1nr -k2,2 -k3,3 -k4,4n)
|
||||
printf '%8s %-18s %-32s %s\n' "$(fence_fmt r_count)" "$(fence_fmt r_source)" \
|
||||
"$(fence_fmt r_target)" "$(fence_fmt r_published)"
|
||||
for line in "${sorted[@]}"; do
|
||||
IFS='|' read -r n src dst dpt proto <<<"$line"
|
||||
name="${NAME_BY_IP[$dst]:-$dst}"
|
||||
pubs="${PUB_BY_TARGET[$dst|$dpt|$proto]:-}"
|
||||
printf '%8s %-18s %-32s %s\n' "$n" "$src" "$name:$dpt/$proto" "${pubs:-?}"
|
||||
if [[ -z "$pubs" ]]; then
|
||||
suggestions+=("# $(fence_fmt r_no_published "$src" "$name:$dpt/$proto")")
|
||||
continue
|
||||
fi
|
||||
for p in $pubs; do
|
||||
k="$proto|$p|$src"
|
||||
[[ -n "${suggested[$k]+x}" ]] && continue
|
||||
suggested[$k]=1
|
||||
suggestions+=("$(printf 'allow %s %s from %s' "$proto" "$p" "$src") # $name")
|
||||
done
|
||||
done
|
||||
printf '\n%s\n' "$(fence_fmt r_suggestions)"
|
||||
printf '%s\n' "${suggestions[@]}"
|
||||
}
|
||||
|
||||
# ----------------------------------------------------------------- ufw-plan
|
||||
|
||||
# Address without /32, for readable ufw commands.
|
||||
fence_short_ip() {
|
||||
printf '%s' "${1%/32}"
|
||||
}
|
||||
|
||||
fence_cmd_ufw_plan() {
|
||||
local i port
|
||||
printf '# %s\n' "$(fence_fmt p_intro)"
|
||||
printf '# %s\n\n' "$(fence_fmt p_never_run)"
|
||||
|
||||
printf '# 1. %s\n' "$(fence_fmt p_admin)"
|
||||
for i in "${!ADMIN_SRC[@]}"; do
|
||||
if [[ -n "${ADMIN_IFACE[i]}" ]]; then
|
||||
printf 'ufw allow in on %s from %s\n' "${ADMIN_IFACE[i]}" "$(fence_short_ip "${ADMIN_SRC[i]}")"
|
||||
else
|
||||
printf 'ufw allow from %s\n' "$(fence_short_ip "${ADMIN_SRC[i]}")"
|
||||
fi
|
||||
done
|
||||
|
||||
printf '\n# 2. %s\n' "$(fence_fmt p_allow)"
|
||||
for i in "${!ALLOW_PROTO[@]}"; do
|
||||
local from=any in=""
|
||||
[[ "${ALLOW_SRC[i]}" != any ]] && from="$(fence_short_ip "${ALLOW_SRC[i]}")"
|
||||
[[ -n "${ALLOW_IFACE[i]}" ]] && in="in on ${ALLOW_IFACE[i]} "
|
||||
printf '# ufw allow %sproto %s from %s to any port %s\n' \
|
||||
"$in" "${ALLOW_PROTO[i]}" "$from" "${ALLOW_PORT[i]}"
|
||||
done
|
||||
(( ${#ALLOW_PROTO[@]} > 0 )) || printf '# -\n'
|
||||
|
||||
printf '\n# 3. %s\n' "$(fence_fmt p_c2h)"
|
||||
if (( ${#C2H_PROTO[@]} == 0 )); then
|
||||
printf '# -\n'
|
||||
else
|
||||
local -a subnets=()
|
||||
if fence_have bin_docker; then
|
||||
mapfile -t subnets < <("${CFG[bin_docker]}" network ls --filter driver=bridge -q 2>/dev/null \
|
||||
| while IFS= read -r id; do
|
||||
"${CFG[bin_docker]}" network inspect --format '{{range .IPAM.Config}}{{.Subnet}} {{end}}' "$id" 2>/dev/null
|
||||
done | tr ' ' '\n' | grep -E '^[0-9.]+/[0-9]+$' | sort -u)
|
||||
fi
|
||||
if (( ${#subnets[@]} == 0 )); then
|
||||
printf '# %s\n' "$(fence_fmt p_no_subnets)"
|
||||
fi
|
||||
local s
|
||||
for i in "${!C2H_PROTO[@]}"; do
|
||||
port="${C2H_PORT[i]}"
|
||||
for s in "${subnets[@]}"; do
|
||||
printf '# ufw allow proto %s from %s to any port %s\n' "${C2H_PROTO[i]}" "$s" "$port"
|
||||
done
|
||||
done
|
||||
fi
|
||||
|
||||
printf '\n# 4. %s\n' "$(fence_fmt p_delete)"
|
||||
printf '# %s\n' "$(fence_fmt p_ssh_warning)"
|
||||
local -a added=()
|
||||
if fence_have bin_ufw; then
|
||||
mapfile -t added < <("${CFG[bin_ufw]}" show added 2>/dev/null | grep -E '^ufw ' || true)
|
||||
fi
|
||||
if (( ${#added[@]} == 0 )); then
|
||||
printf '# %s\n' "$(fence_fmt p_no_added)"
|
||||
fi
|
||||
local r
|
||||
for r in "${added[@]}"; do
|
||||
if [[ "$r" =~ ^ufw\ route\ || ( "$r" =~ ^ufw\ (allow|limit)\ && "$r" != *" from "* ) ]]; then
|
||||
printf '# ufw --force delete %s\n' "${r#ufw }"
|
||||
fi
|
||||
done
|
||||
|
||||
printf '\n# %s\n' "$(fence_fmt p_host_network)"
|
||||
}
|
||||
@@ -0,0 +1,224 @@
|
||||
# shellcheck shell=bash
|
||||
# after.rules file: finding blocks, composing the new content, atomic
|
||||
# write, backups and rotation.
|
||||
|
||||
readonly FENCE_LEGACY_BEGIN='# BEGIN UFW AND DOCKER'
|
||||
readonly FENCE_LEGACY_END='# END UFW AND DOCKER'
|
||||
|
||||
# Original ufw-docker block, known version (README of the ufw-docker project).
|
||||
# Compared without empty lines nor trailing blanks.
|
||||
fence_legacy_known() {
|
||||
cat <<'EOF'
|
||||
# BEGIN UFW AND DOCKER
|
||||
*filter
|
||||
:ufw-user-forward - [0:0]
|
||||
:ufw-docker-logging-deny - [0:0]
|
||||
:DOCKER-USER - [0:0]
|
||||
-A DOCKER-USER -j ufw-user-forward
|
||||
-A DOCKER-USER -j RETURN -s 10.0.0.0/8
|
||||
-A DOCKER-USER -j RETURN -s 172.16.0.0/12
|
||||
-A DOCKER-USER -j RETURN -s 192.168.0.0/16
|
||||
-A DOCKER-USER -p udp -m udp --sport 53 --dport 1024:65535 -j RETURN
|
||||
-A DOCKER-USER -j ufw-docker-logging-deny -p tcp -m tcp --tcp-flags FIN,SYN,RST,ACK SYN -d 192.168.0.0/16
|
||||
-A DOCKER-USER -j ufw-docker-logging-deny -p tcp -m tcp --tcp-flags FIN,SYN,RST,ACK SYN -d 10.0.0.0/8
|
||||
-A DOCKER-USER -j ufw-docker-logging-deny -p tcp -m tcp --tcp-flags FIN,SYN,RST,ACK SYN -d 172.16.0.0/12
|
||||
-A DOCKER-USER -j ufw-docker-logging-deny -p udp -m udp --dport 0:32767 -d 192.168.0.0/16
|
||||
-A DOCKER-USER -j ufw-docker-logging-deny -p udp -m udp --dport 0:32767 -d 10.0.0.0/8
|
||||
-A DOCKER-USER -j ufw-docker-logging-deny -p udp -m udp --dport 0:32767 -d 172.16.0.0/12
|
||||
-A DOCKER-USER -j RETURN
|
||||
-A ufw-docker-logging-deny -m limit --limit 3/min --limit-burst 10 -j LOG --log-prefix "[UFW DOCKER BLOCK] "
|
||||
-A ufw-docker-logging-deny -j DROP
|
||||
COMMIT
|
||||
# END UFW AND DOCKER
|
||||
EOF
|
||||
}
|
||||
|
||||
# Reads a file into the FENCE_LINES array.
|
||||
fence_read_lines() {
|
||||
FENCE_LINES=()
|
||||
mapfile -t FENCE_LINES <"$1"
|
||||
}
|
||||
|
||||
# Looks for a block in FENCE_LINES.
|
||||
# fence_find_block BEGIN_REGEX END_REGEX
|
||||
# Returns 0 and sets FENCE_B / FENCE_E (0-based indexes) if found; 1 if
|
||||
# missing; 2 if the file is inconsistent (FENCE_BLOCK_ERR = key).
|
||||
fence_find_block() {
|
||||
local re_b="$1" re_e="$2" i
|
||||
FENCE_B=-1 FENCE_E=-1
|
||||
for i in "${!FENCE_LINES[@]}"; do
|
||||
if [[ "${FENCE_LINES[i]}" =~ $re_b ]]; then
|
||||
if (( FENCE_B >= 0 )); then
|
||||
FENCE_BLOCK_ERR=e_block_twice
|
||||
return 2
|
||||
fi
|
||||
FENCE_B=$i
|
||||
elif [[ "${FENCE_LINES[i]}" =~ $re_e ]]; then
|
||||
if (( FENCE_B < 0 || FENCE_E >= 0 )); then
|
||||
FENCE_BLOCK_ERR=e_block_end
|
||||
return 2
|
||||
fi
|
||||
FENCE_E=$i
|
||||
fi
|
||||
done
|
||||
if (( FENCE_B < 0 )); then
|
||||
return 1
|
||||
fi
|
||||
if (( FENCE_E < 0 )); then
|
||||
FENCE_BLOCK_ERR=e_block_unclosed
|
||||
return 2
|
||||
fi
|
||||
return 0
|
||||
}
|
||||
|
||||
fence_regex_quote() {
|
||||
printf '%s' "$1" | sed 's/[][\.*^$+?(){}|/]/\\&/g'
|
||||
}
|
||||
|
||||
fence_find_managed() {
|
||||
local m
|
||||
m="$(fence_regex_quote "${CFG[block_marker]}")"
|
||||
fence_find_block "^# BEGIN ${m}( |\$)" "^# END ${m}[[:space:]]*\$"
|
||||
}
|
||||
|
||||
fence_find_legacy() {
|
||||
fence_find_block "^${FENCE_LEGACY_BEGIN}[[:space:]]*\$" "^${FENCE_LEGACY_END}[[:space:]]*\$"
|
||||
}
|
||||
|
||||
# Removes lines FENCE_B..FENCE_E from FENCE_LINES.
|
||||
fence_cut_block() {
|
||||
FENCE_LINES=("${FENCE_LINES[@]:0:FENCE_B}" "${FENCE_LINES[@]:FENCE_E+1}")
|
||||
}
|
||||
|
||||
# Prints lines FENCE_B..FENCE_E.
|
||||
fence_print_block() {
|
||||
printf '%s\n' "${FENCE_LINES[@]:FENCE_B:FENCE_E-FENCE_B+1}"
|
||||
}
|
||||
|
||||
# Removes the trailing empty lines of FENCE_LINES.
|
||||
fence_trim_trailing_blank() {
|
||||
local n=${#FENCE_LINES[@]}
|
||||
while (( n > 0 )) && [[ "${FENCE_LINES[n-1]}" =~ ^[[:space:]]*$ ]]; do
|
||||
n=$((n - 1))
|
||||
done
|
||||
FENCE_LINES=("${FENCE_LINES[@]:0:n}")
|
||||
}
|
||||
|
||||
# Is the original block found (FENCE_B..FENCE_E) the known version?
|
||||
fence_legacy_is_known() {
|
||||
diff -q <(fence_print_block | sed 's/[[:space:]]*$//' | grep -v '^$') \
|
||||
<(fence_legacy_known) >/dev/null
|
||||
}
|
||||
|
||||
fence_legacy_diff() {
|
||||
diff -u <(fence_legacy_known) <(fence_print_block | sed 's/[[:space:]]*$//' | grep -v '^$') \
|
||||
| sed '1,2d' || true
|
||||
}
|
||||
|
||||
# Prints FENCE_LINES followed, if asked, by a block (file).
|
||||
# fence_compose [BLOCK_FILE]
|
||||
fence_compose() {
|
||||
if (( ${#FENCE_LINES[@]} > 0 )); then
|
||||
printf '%s\n' "${FENCE_LINES[@]}"
|
||||
[[ -n "${1:-}" ]] && printf '\n'
|
||||
fi
|
||||
if [[ -n "${1:-}" ]]; then
|
||||
cat -- "$1"
|
||||
fi
|
||||
}
|
||||
|
||||
# Writes standard input to TARGET atomically: temporary file in the same
|
||||
# directory, same mode and owner as the target, then mv.
|
||||
fence_atomic_write() {
|
||||
local target="$1" dir base tmp st
|
||||
dir="$(dirname -- "$target")"
|
||||
base="$(basename -- "$target")"
|
||||
tmp="$(mktemp -- "$dir/.$base.XXXXXX")" || return 1
|
||||
if ! cat >"$tmp"; then
|
||||
rm -f -- "$tmp"
|
||||
return 1
|
||||
fi
|
||||
if [[ -e "$target" ]]; then
|
||||
st="$(stat -c '%a %u %g' -- "$target")"
|
||||
local mode="${st%% *}" rest="${st#* }"
|
||||
local uid="${rest% *}" gid="${rest#* }"
|
||||
if ! chmod "$mode" -- "$tmp" || ! chown "$uid:$gid" -- "$tmp" 2>/dev/null; then
|
||||
rm -f -- "$tmp"
|
||||
return 1
|
||||
fi
|
||||
else
|
||||
chmod 0640 -- "$tmp"
|
||||
fi
|
||||
if ! mv -f -- "$tmp" "$target"; then
|
||||
rm -f -- "$tmp"
|
||||
return 1
|
||||
fi
|
||||
}
|
||||
|
||||
fence_backup_dir() {
|
||||
fence_path "${CFG[backup_dir]}"
|
||||
}
|
||||
|
||||
fence_rules_path() {
|
||||
fence_path "${CFG[ufw_after_rules]}"
|
||||
}
|
||||
|
||||
fence_pending_file() {
|
||||
printf '%s/pending-rollback' "$(fence_backup_dir)"
|
||||
}
|
||||
|
||||
fence_ensure_backup_dir() {
|
||||
local dir
|
||||
dir="$(fence_backup_dir)"
|
||||
if [[ ! -d "$dir" ]]; then
|
||||
(umask 077 && mkdir -p -- "$dir")
|
||||
fi
|
||||
}
|
||||
|
||||
# Backs up the rules file. fence_backup PREFIX; prints the path.
|
||||
fence_backup() {
|
||||
local prefix="$1" src dir dest
|
||||
src="$(fence_rules_path)"
|
||||
dir="$(fence_backup_dir)"
|
||||
fence_ensure_backup_dir || return 1
|
||||
dest="$dir/$prefix.$(date +%Y%m%d-%H%M%S-%N)"
|
||||
(umask 077 && cat -- "$src" >"$dest") || return 1
|
||||
chmod 0600 -- "$dest"
|
||||
fence_rotate "$prefix"
|
||||
printf '%s\n' "$dest"
|
||||
}
|
||||
|
||||
# Lists the backups of a prefix, oldest first.
|
||||
fence_list_backups() {
|
||||
local prefix="$1" dir f
|
||||
dir="$(fence_backup_dir)"
|
||||
[[ -d "$dir" ]] || return 0
|
||||
for f in "$dir/$prefix".[0-9]*; do
|
||||
[[ -f "$f" ]] && printf '%s\n' "$f"
|
||||
done | sort
|
||||
}
|
||||
|
||||
# Keeps the backup_keep most recent backups, never removing the one a
|
||||
# pending rollback waits for.
|
||||
fence_rotate() {
|
||||
local prefix="$1" keep="${CFG[backup_keep]}" pending="" f
|
||||
local -a all
|
||||
[[ -f "$(fence_pending_file)" ]] && pending="$(<"$(fence_pending_file)")"
|
||||
mapfile -t all < <(fence_list_backups "$prefix")
|
||||
local excess=$(( ${#all[@]} - keep ))
|
||||
for f in "${all[@]}"; do
|
||||
(( excess > 0 )) || break
|
||||
if [[ "$f" != "$pending" ]]; then
|
||||
rm -f -- "$f"
|
||||
fi
|
||||
excess=$((excess - 1))
|
||||
done
|
||||
}
|
||||
|
||||
fence_rules_basename() {
|
||||
basename -- "${CFG[ufw_after_rules]}"
|
||||
}
|
||||
|
||||
fence_latest_backup() {
|
||||
fence_list_backups "$(fence_rules_basename)" | tail -n 1
|
||||
}
|
||||
+114
@@ -0,0 +1,114 @@
|
||||
# shellcheck shell=bash
|
||||
# Configuration template (init) and effective configuration (show-config).
|
||||
|
||||
# Normalized port (a:b) back to the file format (a-b).
|
||||
fence_port_conf() {
|
||||
printf '%s' "${1/:/-}"
|
||||
}
|
||||
|
||||
fence_template() {
|
||||
local k
|
||||
printf '# %s\n' "$(fence_fmt t_title)"
|
||||
printf '# %s\n' "$(fence_fmt t_format)"
|
||||
printf '# %s\n\n' "$(fence_fmt t_defaults)"
|
||||
|
||||
printf '# %s\n' "$(fence_fmt d_mode)"
|
||||
printf 'mode %s\n\n' "${FENCE_DEFAULTS[mode]}"
|
||||
|
||||
printf '# admin <ipv4[/mask]> [iface <name>]\n'
|
||||
printf '# %s\n' "$(fence_fmt t_admin)"
|
||||
printf '# %s\n' "$(fence_fmt t_admin_doc)"
|
||||
printf 'admin 192.0.2.10\n'
|
||||
printf '# admin 192.0.2.11 iface wg0\n\n'
|
||||
|
||||
printf '# allow <tcp|udp> <port|a-b> from <ipv4[/mask]|any> [iface <name>]\n'
|
||||
printf '# %s\n' "$(fence_fmt t_allow)"
|
||||
printf '# allow tcp 443 from any\n'
|
||||
printf '# allow tcp 5432 from 198.51.100.20\n'
|
||||
printf '# allow tcp 9000-9010 from 203.0.113.0/24\n\n'
|
||||
|
||||
printf '# container_to_host <tcp|udp> <port|a-b> [from_iface <name>]\n'
|
||||
printf '# %s\n' "$(fence_fmt t_c2h)"
|
||||
printf '# container_to_host tcp 8080\n\n'
|
||||
|
||||
printf '# trusted_iface <name>\n'
|
||||
printf '# %s\n' "$(fence_fmt t_trusted)"
|
||||
printf '# trusted_iface br-+\n'
|
||||
printf '# trusted_iface docker0\n\n'
|
||||
|
||||
printf '# %s\n' "$(fence_fmt t_settings)"
|
||||
for k in "${FENCE_SETTINGS[@]}"; do
|
||||
[[ "$k" == mode ]] && continue
|
||||
printf '\n# %s\n' "$(fence_fmt "d_$k")"
|
||||
printf '# %s %s\n' "$k" "${FENCE_DEFAULTS[$k]}"
|
||||
done
|
||||
}
|
||||
|
||||
fence_cmd_init() {
|
||||
local out="${OPT_OUTPUT:-$(fence_path /etc/docker-fence/fence.conf)}"
|
||||
if [[ "$out" == - ]]; then
|
||||
fence_template
|
||||
return 0
|
||||
fi
|
||||
if [[ -e "$out" && ! "$OPT_FORCE" -eq 1 ]]; then
|
||||
fence_error e_exists "$out"
|
||||
return "$FENCE_EXIT_CONFIG"
|
||||
fi
|
||||
local dir
|
||||
dir="$(dirname -- "$out")"
|
||||
if [[ ! -d "$dir" ]]; then
|
||||
(umask 022 && mkdir -p -- "$dir") || { fence_error e_write "$out"; return "$FENCE_EXIT_CONFIG"; }
|
||||
fi
|
||||
if ! fence_template | (umask 022 && fence_atomic_write "$out"); then
|
||||
fence_error e_write "$out"
|
||||
return "$FENCE_EXIT_CONFIG"
|
||||
fi
|
||||
chmod 0644 -- "$out"
|
||||
fence_info i_init_done "$out"
|
||||
}
|
||||
|
||||
fence_origin_text() {
|
||||
local o="$1"
|
||||
case "$o" in
|
||||
default) fence_fmt o_default ;;
|
||||
option) fence_fmt o_option ;;
|
||||
env) fence_fmt o_env ;;
|
||||
file:*) fence_fmt o_file "${o#file:}" ;;
|
||||
esac
|
||||
}
|
||||
|
||||
fence_rule_origin() {
|
||||
if [[ "$1" == default ]]; then
|
||||
fence_fmt o_default
|
||||
else
|
||||
fence_fmt o_file "$1"
|
||||
fi
|
||||
}
|
||||
|
||||
# Prints the effective configuration, each line followed by its origin.
|
||||
# The output is itself a valid configuration file.
|
||||
fence_cmd_show_config() {
|
||||
local k i r
|
||||
printf '# %s\n' "$(fence_fmt o_header "$FENCE_CONFIG_FILE")"
|
||||
for k in "${FENCE_SETTINGS[@]}"; do
|
||||
printf '%-40s # %s\n' "$k ${CFG[$k]}" "$(fence_origin_text "${CFG_ORIGIN[$k]}")"
|
||||
done
|
||||
printf '\n'
|
||||
for i in "${!ADMIN_SRC[@]}"; do
|
||||
r="admin ${ADMIN_SRC[i]}"
|
||||
[[ -n "${ADMIN_IFACE[i]}" ]] && r+=" iface ${ADMIN_IFACE[i]}"
|
||||
printf '%-40s # %s\n' "$r" "$(fence_rule_origin "${ADMIN_LINE[i]}")"
|
||||
done
|
||||
for i in "${!ALLOW_PROTO[@]}"; do
|
||||
r="allow ${ALLOW_PROTO[i]} $(fence_port_conf "${ALLOW_PORT[i]}") from ${ALLOW_SRC[i]}"
|
||||
[[ -n "${ALLOW_IFACE[i]}" ]] && r+=" iface ${ALLOW_IFACE[i]}"
|
||||
printf '%-40s # %s\n' "$r" "$(fence_rule_origin "${ALLOW_LINE[i]}")"
|
||||
done
|
||||
for i in "${!C2H_PROTO[@]}"; do
|
||||
r="container_to_host ${C2H_PROTO[i]} $(fence_port_conf "${C2H_PORT[i]}") from_iface ${C2H_IFACE[i]}"
|
||||
printf '%-40s # %s\n' "$r" "$(fence_rule_origin "${C2H_LINE[i]}")"
|
||||
done
|
||||
for i in "${!TRUSTED_IFACE[@]}"; do
|
||||
printf '%-40s # %s\n' "trusted_iface ${TRUSTED_IFACE[i]}" "$(fence_rule_origin "${TRUSTED_LINE[i]}")"
|
||||
done
|
||||
}
|
||||
+75
@@ -0,0 +1,75 @@
|
||||
# shellcheck shell=bash
|
||||
# Common functions: output, log, paths, running binaries.
|
||||
|
||||
# Output level: 0 quiet, 1 normal, 2 verbose. Messages go to standard
|
||||
# error; standard output only carries data (generated block, report,
|
||||
# plan, configuration).
|
||||
FENCE_VERBOSITY=1
|
||||
|
||||
# Exit codes (see README).
|
||||
readonly FENCE_EXIT_OK=0
|
||||
readonly FENCE_EXIT_CONFIG=1
|
||||
readonly FENCE_EXIT_ENV=2
|
||||
readonly FENCE_EXIT_LEGACY=3
|
||||
readonly FENCE_EXIT_APPLY=4
|
||||
|
||||
# Path prefix reserved for tests (FENCE_ROOT).
|
||||
fence_path() {
|
||||
printf '%s%s' "${FENCE_ROOT:-}" "$1"
|
||||
}
|
||||
|
||||
fence_info() {
|
||||
if (( FENCE_VERBOSITY >= 1 )); then
|
||||
# shellcheck disable=SC2059
|
||||
printf "$(fence_fmt "$1")\n" "${@:2}" >&2
|
||||
fi
|
||||
}
|
||||
|
||||
fence_detail() {
|
||||
if (( FENCE_VERBOSITY >= 2 )); then
|
||||
# shellcheck disable=SC2059
|
||||
printf "$(fence_fmt "$1")\n" "${@:2}" >&2
|
||||
fi
|
||||
}
|
||||
|
||||
fence_warn() {
|
||||
# shellcheck disable=SC2059
|
||||
printf "%s $(fence_fmt "$1")\n" "$(fence_fmt w_prefix)" "${@:2}" >&2
|
||||
}
|
||||
|
||||
fence_error() {
|
||||
# shellcheck disable=SC2059
|
||||
printf "%s $(fence_fmt "$1")\n" "$(fence_fmt e_prefix)" "${@:2}" >&2
|
||||
}
|
||||
|
||||
# fence_die CODE KEY [ARGS...]
|
||||
fence_die() {
|
||||
local code="$1"
|
||||
shift
|
||||
fence_error "$@"
|
||||
exit "$code"
|
||||
}
|
||||
|
||||
# Log of the actions of the tool (never a secret: only paths, command
|
||||
# names and states are written).
|
||||
fence_log() {
|
||||
local file
|
||||
file="$(fence_path "${CFG[log_file]}")"
|
||||
local line
|
||||
line="$(date '+%Y-%m-%dT%H:%M:%S%z') $*"
|
||||
if ! { printf '%s\n' "$line" >>"$file"; } 2>/dev/null; then
|
||||
fence_detail i_log_unwritable "$file"
|
||||
fi
|
||||
}
|
||||
|
||||
# Runs a configured binary: fence_run bin_ufw reload
|
||||
fence_run() {
|
||||
local key="$1"
|
||||
shift
|
||||
fence_detail i_running "${CFG[$key]} $*"
|
||||
"${CFG[$key]}" "$@"
|
||||
}
|
||||
|
||||
fence_have() {
|
||||
command -v "${CFG[$1]}" >/dev/null 2>&1
|
||||
}
|
||||
Reference in new issue
Block a user