Files
2026-12-05 15:32:27 +00:00

564 lines
17 KiB
Bash

# 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
}