Add docker-fence v1 with tests and docs

This commit is contained in:
Djeex committed 2026-12-05 15:32:27 +00:00
commit 305cb562f8
46 files changed
+5473

No files matched your search

+210
View File
@@ -0,0 +1,210 @@
#!/usr/bin/env bats
# apply, confirm, rollback: systemd timer, reload, verification,
# rollback.
load helpers
bats_require_minimum_version 1.5.0
setup() {
setup_env
cp "$REPO/examples/fence.conf" "$CONF"
chmod 0644 "$CONF"
}
@test "apply: writes, schedules the rollback, reloads, verifies" {
run fence apply
[ "$status" -eq 0 ]
grep -qF '# BEGIN DOCKER-FENCE' "$RULES"
grep -q '^systemd-run --unit=docker-fence-rollback --on-active=120s ' "$STUB_LOG"
grep -q '^ufw reload' "$STUB_LOG"
# The timer is scheduled before the reload.
[ "$(grep -n '^systemd-run' "$STUB_LOG" | cut -d: -f1)" -lt "$(grep -n '^ufw reload' "$STUB_LOG" | cut -d: -f1)" ]
grep -qxF -- '-A DOCKER-USER -j docker-fence' "$KERNEL"
grep -qxF -- '-A ufw-after-input -i br-+ -p tcp --dport 8080 -j ACCEPT' "$KERNEL"
[ -f "$BACKUPS/pending-rollback" ]
[[ "$output" == *'Confirm with "docker-fence confirm" within 120 seconds'* ]]
grep -q 'apply ok mode=observe' "$FENCE_ROOT/var/log/docker-fence.log"
}
@test "the timer command reads the same configuration and options" {
fence --mode enforce --set rollback_seconds=45 apply
grep -q -- '--on-active=45s' "$STUB_LOG"
mapfile -t cmd <"$STUB_STATE/timer_cmd"
[ "${cmd[0]}" = "$FENCE" ]
[ "${cmd[1]}" = rollback ]
[ "${cmd[2]}" = --auto ]
[ "${cmd[3]}" = --config ]
[ "${cmd[4]}" = "$CONF" ]
[[ " ${cmd[*]} " == *" --set mode=enforce "* ]]
[[ " ${cmd[*]} " == *" --set rollback_seconds=45 "* ]]
[ "$(cat "$STUB_STATE/timer_env")" = "FENCE_ROOT=$FENCE_ROOT" ]
}
@test "apply without confirm: the timer restores the exact previous state" {
local orig
orig="$(sum_of "$RULES")"
fence apply
run fire_timer
[ "$status" -eq 0 ]
[ "$(sum_of "$RULES")" = "$orig" ]
[ "$(stat -c %a "$RULES")" = 640 ]
[ ! -e "$BACKUPS/pending-rollback" ]
# Nothing of the block is left in the kernel.
! grep -qF -- 'docker-fence' "$KERNEL"
! grep -qF -- '--dport 8080' "$KERNEL"
grep -q 'rollback --auto' "$FENCE_ROOT/var/log/docker-fence.log"
}
@test "confirm stops the timer; no rollback afterwards" {
fence apply
run fence confirm
[ "$status" -eq 0 ]
[[ "$output" == *"confirmed"* ]]
grep -q '^systemctl stop docker-fence-rollback.timer' "$STUB_LOG"
[ ! -e "$STUB_STATE/timer_cmd" ]
[ ! -e "$BACKUPS/pending-rollback" ]
# Even if the timer fired anyway, rollback --auto would do nothing.
local now
now="$(sum_of "$RULES")"
run fence rollback --auto
[ "$status" -eq 0 ]
[[ "$output" == *"no rollback pending"* ]]
[ "$(sum_of "$RULES")" = "$now" ]
}
@test "unconfirmed switch observe -> enforce: back to observe mode" {
fence apply
fence confirm
local observe
observe="$(sum_of "$RULES")"
fence --mode enforce apply
grep -qxF -- '-A docker-fence -m conntrack --ctstate DNAT -j docker-fence-deny' "$KERNEL"
fire_timer
[ "$(sum_of "$RULES")" = "$observe" ]
# The block is still there: the kernel is reloaded in observe mode.
grep -qxF -- '-A DOCKER-USER -j docker-fence' "$KERNEL"
! grep -qF -- '-j docker-fence-deny' "$KERNEL"
grep -qF -- 'DOCKER-WOULD-DROP' "$KERNEL"
}
@test "apply refused when a rollback is already pending" {
fence apply
run fence --mode enforce apply
[ "$status" -eq 1 ]
[[ "$output" == *"an automatic rollback is pending"* ]]
run fence install
[ "$status" -eq 1 ]
run fence uninstall
[ "$status" -eq 1 ]
}
@test "UFW inactive: apply refused, nothing changes" {
local orig
orig="$(sum_of "$RULES")"
STUB_UFW_INACTIVE=1 run fence apply
[ "$status" -eq 2 ]
[[ "$output" == *"UFW is inactive"* ]]
[ "$(sum_of "$RULES")" = "$orig" ]
! grep -q '^systemd-run' "$STUB_LOG"
}
@test "missing binary: apply refused (exit code 2)" {
run fence --set bin_systemd_run=/nonexistent/systemd-run apply
[ "$status" -eq 2 ]
[[ "$output" == *"command not found: /nonexistent/systemd-run"* ]]
}
@test "systemd-run fails: file restored, nothing reloaded (exit code 4)" {
local orig
orig="$(sum_of "$RULES")"
STUB_SYSTEMD_RUN_RC=1 run fence apply
[ "$status" -eq 4 ]
[[ "$output" == *"cannot schedule the rollback"* ]]
[ "$(sum_of "$RULES")" = "$orig" ]
! grep -q '^ufw reload' "$STUB_LOG"
[ ! -e "$BACKUPS/pending-rollback" ]
}
@test "ufw reload fails: immediate rollback (exit code 4)" {
local orig
orig="$(sum_of "$RULES")"
STUB_UFW_RELOAD_RC=1 run fence apply
[ "$status" -eq 4 ]
[[ "$output" == *'"ufw reload" failed'* ]]
[ "$(sum_of "$RULES")" = "$orig" ]
[ ! -e "$BACKUPS/pending-rollback" ]
grep -q '^systemctl stop docker-fence-rollback.timer' "$STUB_LOG"
}
@test "block missing from the kernel after reload: immediate rollback (exit code 4)" {
local orig
orig="$(sum_of "$RULES")"
STUB_UFW_RELOAD_NOOP=1 run fence apply
[ "$status" -eq 4 ]
[[ "$output" == *"DOCKER-USER does not jump to docker-fence"* ]]
[[ "$output" == *"rollback done"* ]]
[ "$(sum_of "$RULES")" = "$orig" ]
[ ! -e "$STUB_STATE/timer_cmd" ]
}
@test "container_to_host rule not loaded: immediate rollback (exit code 4)" {
local orig
orig="$(sum_of "$RULES")"
STUB_UFW_DROP_C2H=1 run fence apply
[ "$status" -eq 4 ]
[[ "$output" == *"container_to_host rule tcp 8080 is missing"* ]]
[ "$(sum_of "$RULES")" = "$orig" ]
! grep -qF -- '-j docker-fence' "$KERNEL"
}
@test "manual rollback: latest backup, then the given backup" {
local orig v1
orig="$(sum_of "$RULES")"
fence install
v1="$(sum_of "$RULES")"
fence --mode enforce install
run fence rollback
[ "$status" -eq 0 ]
[ "$(sum_of "$RULES")" = "$v1" ]
grep -q '^ufw reload' "$STUB_LOG"
local first
first="$(find "$BACKUPS" -name 'after.rules.[0-9]*' | sort | head -n 1)"
run fence rollback "$first"
[ "$status" -eq 0 ]
[ "$(sum_of "$RULES")" = "$orig" ]
# Each rollback keeps the state it replaces.
[ "$(find "$BACKUPS" -name 'after.rules.pre-rollback.[0-9]*' | wc -l)" -eq 2 ]
}
@test "rollback without backup or with a missing file" {
run fence rollback
[ "$status" -eq 1 ]
[[ "$output" == *"no backup in"* ]]
run fence rollback /nonexistent
[ "$status" -eq 1 ]
[[ "$output" == *"backup missing or unreadable"* ]]
}
@test "confirm with no rollback pending" {
run fence confirm
[ "$status" -eq 0 ]
[[ "$output" == *"no rollback pending"* ]]
}
@test "rotation never removes the backup a pending rollback waits for" {
local f
for f in messages util config rulesfile; do
source "$REPO/lib/$f.sh"
done
fence_config_reset
CFG[backup_keep]=1
mkdir -p "$BACKUPS"
touch "$BACKUPS/after.rules.20260101-000000-1" "$BACKUPS/after.rules.20260102-000000-1" \
"$BACKUPS/after.rules.20260103-000000-1"
printf '%s\n' "$BACKUPS/after.rules.20260101-000000-1" >"$BACKUPS/pending-rollback"
fence_rotate after.rules
[ -e "$BACKUPS/after.rules.20260101-000000-1" ]
[ ! -e "$BACKUPS/after.rules.20260102-000000-1" ]
[ -e "$BACKUPS/after.rules.20260103-000000-1" ]
}
+170
View File
@@ -0,0 +1,170 @@
#!/usr/bin/env bats
# Command line, init, bash version, code quality.
load helpers
bats_require_minimum_version 1.5.0
setup() {
setup_env
}
@test "--help in English and French" {
run "$FENCE" --help
[ "$status" -eq 0 ]
[[ "$output" == "Usage: docker-fence"* ]]
[[ "$output" == *"Exit codes"* ]]
run "$FENCE" --lang fr --help
[[ "$output" == "Usage : docker-fence"* ]]
FENCE_LANG=fr run "$FENCE" -h
[[ "$output" == "Usage : docker-fence"* ]]
}
@test "--version" {
run "$FENCE" --version
[ "$status" -eq 0 ]
[[ "$output" =~ ^docker-fence\ [0-9]+\.[0-9]+\.[0-9]+$ ]]
}
@test "usage errors: exit code 1" {
minimal_conf
run fence
[ "$status" -eq 1 ]
run fence frobnicate
[ "$status" -eq 1 ]
[[ "$output" == *"invalid usage: frobnicate"* ]]
run fence --nope check
[ "$status" -eq 1 ]
run fence check --force
[ "$status" -eq 1 ]
[[ "$output" == *"check --force"* ]]
run fence check extra
[ "$status" -eq 1 ]
run fence report --since
[ "$status" -eq 1 ]
run fence rollback --auto somefile
[ "$status" -eq 1 ]
}
@test "--option=value form" {
printf 'admin 192.0.2.10\n' | write_conf
run "$FENCE" --config="$CONF" --mode=enforce show-config
[ "$status" -eq 0 ]
[[ "$output" == *"mode enforce"*"# option"* ]]
}
@test "--quiet prints errors only, --verbose prints commands" {
minimal_conf
run --separate-stderr fence -q check
[ "$status" -eq 0 ]
[ -z "$stderr" ] || [[ "$stderr" != *"configuration valid"* ]]
run fence -v apply
[[ "$output" == *"running: ufw reload"* ]]
}
@test "bash too old: exit code 2" {
source "$FENCE"
run _fence_require_bash 4 4.4.23
[ "$status" -eq 2 ]
[[ "$output" == *"bash 5 or later"*"bash 4.4.23"* ]]
run _fence_require_bash 5 5.0
[ "$status" -eq 0 ]
}
@test "init writes a valid template, mode 0644, without overwriting" {
run "$FENCE" init
[ "$status" -eq 0 ]
[ -f "$CONF" ]
[ "$(stat -c %a "$CONF")" = 644 ]
run fence check
[ "$status" -eq 0 ]
[[ "$output" == *"mode observe"* ]]
printf '# mine\nadmin 192.0.2.10\n' >"$CONF"
local before
before="$(sum_of "$CONF")"
run "$FENCE" init
[ "$status" -eq 1 ]
[[ "$output" == *"already exists"* ]]
[ "$(sum_of "$CONF")" = "$before" ]
run "$FENCE" init --force
[ "$status" -eq 0 ]
[ "$(sum_of "$CONF")" != "$before" ]
}
@test "init --output: chosen file or standard output" {
run "$FENCE" init --output "$BATS_TEST_TMPDIR/sub/dir/my.conf"
[ "$status" -eq 0 ]
[ -f "$BATS_TEST_TMPDIR/sub/dir/my.conf" ]
run --separate-stderr "$FENCE" init --output -
[ "$status" -eq 0 ]
[[ "${lines[0]}" == "# docker-fence: configuration"* ]]
}
@test "the template lists every directive with its default value" {
source "$REPO/lib/messages.sh"
source "$REPO/lib/config.sh"
run --separate-stderr "$FENCE" init --output -
local k
for k in "${FENCE_SETTINGS[@]}"; do
[[ "$output" == *"$k ${FENCE_DEFAULTS[$k]}"* ]] || { echo "missing: $k"; return 1; }
done
for k in admin allow container_to_host trusted_iface; do
[[ "$output" == *"# $k "* ]] || { echo "missing: $k"; return 1; }
done
}
@test "the French template is valid too" {
"$FENCE" --lang fr init --output "$BATS_TEST_TMPDIR/fr.conf"
grep -q 'Réglages' "$BATS_TEST_TMPDIR/fr.conf"
run "$FENCE" -c "$BATS_TEST_TMPDIR/fr.conf" check
[ "$status" -eq 0 ]
}
@test "quality: no eval, configuration never sourced" {
! grep -nwE 'eval' "$FENCE" "$REPO"/lib/*.sh
# Only the libraries of the tool are loaded with source.
run grep -nE '^[[:space:]]*(source|\.)[[:space:]]' "$FENCE" "$REPO"/lib/*.sh
[ "$(grep -cvE 'source "\$libdir/[a-z]+\.sh"' <<<"$output")" -eq 0 ]
}
@test "quality: set -euo pipefail in the tool and the fake binaries" {
grep -q 'set -euo pipefail' "$FENCE"
local f
for f in "$REPO"/tests/stubs/*; do
grep -q 'set -euo pipefail' "$f"
done
}
@test "messages: same keys in both languages, no missing key" {
source "$REPO/lib/messages.sh"
diff <(printf '%s\n' "${!MSG_fr[@]}" | sort) <(printf '%s\n' "${!MSG_en[@]}" | sort)
local key
local -a used
mapfile -t used < <(grep -ohE '(fence_(info|detail|warn|error|fmt)|fence_add_error "[^"]*"|fence_die [^ ]+) "?[a-z][a-z0-9_]+' \
"$FENCE" "$REPO"/lib/*.sh | awk '{print $NF}' | tr -d '"' | sort -u)
mapfile -t -O "${#used[@]}" used < <(grep -ohE 'FENCE_VERR=[a-z0-9_]+' "$REPO"/lib/*.sh | cut -d= -f2 | sort -u)
for key in "${used[@]}"; do
[[ "$key" == d_ ]] && continue
[[ -n "${MSG_fr[$key]+x}" ]] || { echo "missing key: $key"; return 1; }
done
source "$REPO/lib/config.sh"
for key in "${FENCE_SETTINGS[@]}"; do
[[ -n "${MSG_fr[d_$key]+x}" ]] || { echo "missing description: d_$key"; return 1; }
done
}
@test "messages: no em dash" {
! grep -n $'\xe2\x80\x94' "$REPO/lib/messages.sh"
}
@test "no address outside documentation ranges in the example and the README" {
local f
for f in "$REPO/examples/fence.conf" "$REPO/README.md"; do
[ -f "$f" ] || continue
# Every IPv4 quoted must be RFC 5737, private (Docker) or generic.
! grep -oE '\b[0-9]{1,3}(\.[0-9]{1,3}){3}\b' "$f" \
| grep -vE '^(192\.0\.2|198\.51\.100|203\.0\.113)\.|^(172\.(1[6-9]|2[0-9]|3[01])|10|127)\.|^0\.0\.0\.0$'
done
}
+418
View File
@@ -0,0 +1,418 @@
#!/usr/bin/env bats
# Configuration parsing.
load helpers
bats_require_minimum_version 1.5.0
setup() {
setup_env
}
# Checks that a configuration line is refused, with its line number.
# expect_refused LINE PATTERN
expect_refused() {
printf 'admin 192.0.2.10\n%s\n' "$1" | write_conf
run fence check
[ "$status" -eq 1 ]
[[ "$output" == *"fence.conf:2: "* ]]
[[ "$output" == *"$2"* ]]
}
@test "the example of the repository is valid" {
cp "$REPO/examples/fence.conf" "$CONF"
chmod 0644 "$CONF"
run fence check
[ "$status" -eq 0 ]
[[ "$output" == *"configuration valid"* ]]
}
@test "empty lines, comments and comment after a directive" {
write_conf <<'EOF'
# comment
# indented comment
admin 192.0.2.10 # admin workstation
mode enforce # tabs
EOF
run fence show-config
[ "$status" -eq 0 ]
[[ "$output" == *"admin 192.0.2.10/32"*"# line 4"* ]]
[[ "$output" == *"mode enforce"*"# line 5"* ]]
}
@test "a # stuck to a value is refused" {
expect_refused 'mode observe#x' 'must follow a blank'
}
@test "unknown directive refused with its line number" {
expect_refused 'alow tcp 443 from any' 'unknown directive: "alow"'
}
@test "\$ and backtick are refused, never interpreted" {
expect_refused 'admin $HOME' 'forbidden character: "$"'
expect_refused 'admin `id`' 'forbidden character: "`"'
expect_refused 'log_file /tmp/$(touch x)' 'forbidden character'
[ ! -e x ]
[ ! -e "$BATS_TEST_TMPDIR/x" ]
}
@test "quotes, semicolon and backslash are refused" {
expect_refused 'mode "observe"' 'forbidden character'
expect_refused 'mode observe; id' 'forbidden character: ";"'
expect_refused 'mode observe\' 'forbidden character'
}
@test "invalid IPv4 addresses" {
expect_refused 'admin 256.1.1.1' 'invalid IPv4 address'
expect_refused 'admin 192.0.2' 'invalid IPv4 address'
expect_refused 'admin 192.0.2.010' 'invalid IPv4 address'
expect_refused 'admin 192.0.2.1/33' 'invalid IPv4 address'
expect_refused 'admin 192.0.2.1/' 'invalid IPv4 address'
expect_refused 'admin 192.0.2.1/24' 'host bits are set'
expect_refused 'admin 0.0.0.0/0' 'covers every address'
expect_refused 'allow tcp 80 from 0.0.0.0/0' 'covers every address'
expect_refused 'admin fe80::1' 'invalid IPv4 address'
}
@test "invalid ports and ranges" {
expect_refused 'allow tcp 0 from any' 'invalid port:'
expect_refused 'allow tcp 65536 from any' 'invalid port:'
expect_refused 'allow tcp 080 from any' 'invalid port:'
expect_refused 'allow tcp http from any' 'invalid port:'
expect_refused 'allow tcp 10-5 from any' 'invalid port range'
expect_refused 'allow tcp 10-10 from any' 'invalid port range'
expect_refused 'allow tcp 1:5 from any' 'invalid port:'
expect_refused 'allow icmp 80 from any' 'invalid protocol'
}
@test "port boundaries are accepted" {
write_conf <<'EOF'
admin 192.0.2.10
allow tcp 1 from any
allow udp 65535 from any
allow tcp 1-65535 from 198.51.100.0/24
container_to_host udp 1-2
EOF
run fence show-config
[ "$status" -eq 0 ]
[[ "$output" == *"allow tcp 1-65535 from 198.51.100.0/24"* ]]
[[ "$output" == *"container_to_host udp 1-2 from_iface br-+"* ]]
}
@test "rule syntax" {
expect_refused 'admin' 'expected syntax: admin'
expect_refused 'admin 192.0.2.1 wg0' 'expected syntax: admin'
expect_refused 'admin 192.0.2.1 iface' 'expected syntax: admin'
expect_refused 'allow tcp 443 any' 'expected syntax: allow'
expect_refused 'allow tcp 443 to any' 'expected syntax: allow'
expect_refused 'allow tcp 443 from any iface' 'expected syntax: allow'
expect_refused 'container_to_host tcp' 'expected syntax: container_to_host'
expect_refused 'container_to_host tcp 80 iface br-+' 'expected syntax: container_to_host'
expect_refused 'trusted_iface' 'expected syntax: trusted_iface'
expect_refused 'trusted_iface a b' 'expected syntax: trusted_iface'
}
@test "interface names" {
expect_refused 'admin 192.0.2.1 iface wg0/1' 'invalid interface name'
expect_refused 'trusted_iface abcdefghijklmnop' 'invalid interface name'
expect_refused 'trusted_iface br+x' 'invalid interface name'
write_conf <<'EOF'
admin 192.0.2.10 iface abcdefghijklmno
trusted_iface br-+
trusted_iface veth.1_a-b
EOF
run fence check
[ "$status" -eq 0 ]
}
@test "repeated rules add up, in order" {
write_conf <<'EOF'
admin 192.0.2.10
admin 192.0.2.11
allow tcp 443 from any
allow tcp 443 from 198.51.100.20
EOF
run fence check
[ "$status" -eq 0 ]
[[ "$output" == *"-s 192.0.2.10/32 -j RETURN"*"-s 192.0.2.11/32 -j RETURN"* ]]
[[ "$output" == *"--ctorigdstport 443 -j RETURN"*"--ctorigdstport 443 -s 198.51.100.20/32 -j RETURN"* ]]
}
@test "duplicates refused with the line of the first rule" {
write_conf <<'EOF'
admin 192.0.2.10
admin 192.0.2.10/32
allow tcp 443 from any
allow tcp 443 from any
container_to_host tcp 8080
container_to_host tcp 8080 from_iface br-+
trusted_iface wg0
trusted_iface wg0
EOF
run fence check
[ "$status" -eq 1 ]
[[ "$output" == *"fence.conf:2: "*"same rule as line 1"* ]]
[[ "$output" == *"fence.conf:4: "*"same rule as line 3"* ]]
[[ "$output" == *"fence.conf:6: "*"same rule as line 5"* ]]
[[ "$output" == *"fence.conf:8: "*"same rule as line 7"* ]]
}
@test "the same source on another interface is not a duplicate" {
write_conf <<'EOF'
admin 192.0.2.10
admin 192.0.2.10 iface wg0
EOF
run fence check
[ "$status" -eq 0 ]
}
@test "a repeated setting takes the last value" {
write_conf <<'EOF'
admin 192.0.2.10
mode enforce
rollback_seconds 60
mode observe
EOF
run fence show-config
[ "$status" -eq 0 ]
[[ "$output" == *"mode observe"*"# line 4"* ]]
}
@test "a setting takes exactly one value" {
expect_refused 'mode observe enforce' '"mode" takes exactly one value'
expect_refused 'mode' '"mode" takes exactly one value'
}
@test "report_since accepts several words" {
printf 'admin 192.0.2.10\nreport_since 2 days ago\n' | write_conf
run fence show-config
[ "$status" -eq 0 ]
[[ "$output" == *"report_since 2 days ago"* ]]
}
@test "invalid setting values" {
expect_refused 'mode block' 'invalid mode'
expect_refused 'lang de' 'invalid language'
expect_refused 'rollback_seconds 29' 'integer expected between 30-86400'
expect_refused 'rollback_seconds 86401' 'integer expected'
expect_refused 'rollback_seconds -5' 'integer expected'
expect_refused 'log_level 8' 'integer expected between 0-7'
expect_refused 'log_burst_enforce 0' 'integer expected'
expect_refused 'backup_keep 0' 'integer expected'
expect_refused 'log_rate_observe 20' 'invalid rate'
expect_refused 'log_rate_observe 20/week' 'invalid rate'
expect_refused 'log_file var/log/x.log' 'invalid path'
expect_refused 'backup_dir /var/../etc' 'invalid path'
expect_refused 'ufw_after_rules /etc/ufw/' 'invalid path'
expect_refused 'bin_ufw ../ufw' 'invalid command'
expect_refused 'unit_name a.b' 'invalid unit name'
expect_refused 'block_marker A:B' 'invalid block marker'
}
@test "log prefix: 28 characters accepted, 29 refused" {
printf 'admin 192.0.2.10\nlog_prefix_drop %s\n' "$(printf 'A%.0s' {1..28})" | write_conf
run fence check
[ "$status" -eq 0 ]
[[ "$output" == *"--log-prefix \"$(printf 'A%.0s' {1..28}) \""* ]]
expect_refused "log_prefix_drop $(printf 'A%.0s' {1..29})" 'at most 28 characters'
expect_refused 'log_prefix_drop [UFW]' 'forbidden character'
}
@test "identical prefixes refused" {
printf 'admin 192.0.2.10\nlog_prefix_drop X\nlog_prefix_observe X\n' | write_conf
run fence check
[ "$status" -eq 1 ]
[[ "$output" == *"must differ"* ]]
}
@test "chain name: <name>-deny must fit in 28 characters" {
printf 'admin 192.0.2.10\nchain %s\n' "$(printf 'c%.0s' {1..23})" | write_conf
run fence check
[ "$status" -eq 0 ]
[[ "$output" == *":$(printf 'c%.0s' {1..23})-deny - [0:0]"* ]]
expect_refused "chain $(printf 'c%.0s' {1..24})" 'at most 23 characters'
}
@test "reserved chain names" {
expect_refused 'chain DOCKER-USER' 'reserved chain name'
expect_refused 'chain DOCKER' 'reserved chain name'
expect_refused 'chain DOCKER-FORWARD' 'reserved chain name'
expect_refused 'chain ufw-x' 'reserved chain name'
expect_refused 'chain FORWARD' 'reserved chain name'
expect_refused 'chain drop' 'reserved chain name'
}
@test "every default value passes validation" {
source "$REPO/lib/messages.sh"
source "$REPO/lib/config.sh"
local k
for k in "${FENCE_SETTINGS[@]}"; do
fence_validate_setting "$k" "${FENCE_DEFAULTS[$k]}" || {
echo "invalid default: $k"
return 1
}
done
[ "${#FENCE_SETTINGS[@]}" -eq "${#FENCE_DEFAULTS[@]}" ]
}
@test "empty file or comments only: admin missing" {
: | write_conf
run fence check
[ "$status" -eq 1 ]
[[ "$output" == *'at least one "admin" directive is required'* ]]
printf '# nothing\n\n \n' | write_conf
run fence check
[ "$status" -eq 1 ]
[[ "$output" == *'at least one "admin" directive is required'* ]]
}
@test "at least one admin is required" {
printf 'mode observe\nallow tcp 443 from any\n' | write_conf
run fence check
[ "$status" -eq 1 ]
[[ "$output" == *'at least one "admin" directive is required'* ]]
}
@test "every error is reported, each with its line" {
write_conf <<'EOF'
admin 192.0.2.10
mode bad
allow tcp 99999 from 1.2.3
foo bar
EOF
run fence check
[ "$status" -eq 1 ]
[[ "$output" == *"fence.conf:2: "*"invalid mode"* ]]
[[ "$output" == *"fence.conf:3: "*"invalid port"* ]]
[[ "$output" == *"fence.conf:3: "*"invalid IPv4 address"* ]]
[[ "$output" == *"fence.conf:4: "*"unknown directive"* ]]
# Nothing is generated when the configuration is invalid.
[[ "$output" != *"BEGIN"* ]]
}
@test "file without a final newline" {
printf 'admin 192.0.2.10\nmode enforce' | write_conf
run fence show-config
[ "$status" -eq 0 ]
[[ "$output" == *"mode enforce"*"# line 2"* ]]
}
@test "Windows line endings refused" {
printf 'admin 192.0.2.10\r\n' | write_conf
run fence check
[ "$status" -eq 1 ]
[[ "$output" == *"fence.conf:1: "*"forbidden character"* ]]
}
@test "priority: option > environment > file > default" {
printf 'admin 192.0.2.10\nmode enforce\nlang fr\n' | write_conf
run fence show-config
[[ "$output" == *"mode enforce"*"# ligne 2"* ]]
[[ "$output" == *"rollback_seconds 120"*"# défaut"* ]]
[[ "$output" == *"lang fr"*"# ligne 3"* ]]
FENCE_LANG=en run fence show-config
[[ "$output" == *"lang en"*"# environment"* ]]
FENCE_LANG=en run fence --lang fr --mode observe --set rollback_seconds=300 show-config
[ "$status" -eq 0 ]
[[ "$output" == *"lang fr"*"# option"* ]]
[[ "$output" == *"mode observe"*"# option"* ]]
[[ "$output" == *"rollback_seconds 300"*"# option"* ]]
}
@test "invalid --set options" {
minimal_conf
run fence --set nope=1 check
[ "$status" -eq 1 ]
[[ "$output" == *"invalid option: --set nope=1"* ]]
run fence --set mode=bad check
[ "$status" -eq 1 ]
run fence --set mode check
[ "$status" -eq 1 ]
run fence --mode block check
[ "$status" -eq 1 ]
FENCE_LANG=xx run fence check
[ "$status" -eq 1 ]
[[ "$output" == *"invalid variable FENCE_LANG"* ]]
}
@test "messages in French" {
printf 'admin 192.0.2.10\nlang fr\nfoo\n' | write_conf
run fence check
[ "$status" -eq 1 ]
[[ "$output" == *"erreur : "*"fence.conf:3: directive inconnue : « foo »"* ]]
}
@test "search order: --config, FENCE_CONFIG, ./fence.conf, /etc" {
printf 'admin 192.0.2.10\nmode enforce\n' >"$CONF"; chmod 0644 "$CONF"
mkdir -p work && cd work
run "$FENCE" show-config
[[ "$output" == *"mode enforce"* ]]
printf 'admin 192.0.2.10\nrollback_seconds 31\n' >fence.conf; chmod 0644 fence.conf
run "$FENCE" show-config
[[ "$output" == *"rollback_seconds 31"* ]]
printf 'admin 192.0.2.10\nrollback_seconds 32\n' >env.conf; chmod 0644 env.conf
FENCE_CONFIG=env.conf run "$FENCE" show-config
[[ "$output" == *"rollback_seconds 32"* ]]
printf 'admin 192.0.2.10\nrollback_seconds 33\n' >opt.conf; chmod 0644 opt.conf
FENCE_CONFIG=env.conf run "$FENCE" --config opt.conf show-config
[[ "$output" == *"rollback_seconds 33"* ]]
[[ "$output" == *"$PWD/opt.conf"* ]]
}
@test "missing file" {
run "$FENCE" -c /nonexistent.conf check
[ "$status" -eq 1 ]
[[ "$output" == *"missing or unreadable: /nonexistent.conf"* ]]
}
@test "file writable by group or others refused" {
minimal_conf
chmod 0664 "$CONF"
run fence check
[ "$status" -eq 1 ]
[[ "$output" == *"writable by group or others (mode 664)"* ]]
chmod 0646 "$CONF"
run fence check
[ "$status" -eq 1 ]
chmod 0600 "$CONF"
run fence check
[ "$status" -eq 0 ]
}
@test "file owned by another user refused" {
[ "$EUID" -eq 0 ] || skip "chown needs root"
minimal_conf
chown 12345 "$CONF"
run fence check
[ "$status" -eq 1 ]
[[ "$output" == *"must be owned by root"* ]]
}
@test "show-config prints a valid, equivalent configuration" {
cp "$REPO/examples/fence.conf" "$CONF"; chmod 0644 "$CONF"
run fence check
local before="$output"
fence show-config >"$BATS_TEST_TMPDIR/again.conf"
chmod 0644 "$BATS_TEST_TMPDIR/again.conf"
run "$FENCE" -c "$BATS_TEST_TMPDIR/again.conf" check
[ "$status" -eq 0 ]
[ "${output#*# BEGIN}" = "${before#*# BEGIN}" ]
}
@test "default trusted_iface: br-+ and docker0" {
minimal_conf
run fence show-config
[[ "$output" == *"trusted_iface br-+"*"# default"* ]]
[[ "$output" == *"trusted_iface docker0"*"# default"* ]]
printf 'admin 192.0.2.10\ntrusted_iface br-custom\n' | write_conf
run fence check
[[ "$output" == *"-i br-custom -j RETURN"* ]]
[[ "$output" != *"-i docker0"* ]]
[[ "$output" != *"-i br-+ -j RETURN"* ]]
}
+4
View File
@@ -0,0 +1,4 @@
FROM debian:trixie-slim
RUN apt-get update \
&& apt-get install -y --no-install-recommends bats curl iptables make procps \
&& rm -rf /var/lib/apt/lists/*
+30
View File
@@ -0,0 +1,30 @@
#
# rules.input-after
#
# Rules that should be run after the ufw command line added rules. Custom
# rules should be added to one of these chains:
# ufw-after-input
# ufw-after-output
# ufw-after-forward
#
# Don't delete these required lines, otherwise there will be errors
*filter
:ufw-after-input - [0:0]
:ufw-after-output - [0:0]
:ufw-after-forward - [0:0]
# End required lines
# don't log noisy services by default
-A ufw-after-input -p udp --dport 137 -j ufw-skip-to-policy-input
-A ufw-after-input -p udp --dport 138 -j ufw-skip-to-policy-input
-A ufw-after-input -p tcp --dport 139 -j ufw-skip-to-policy-input
-A ufw-after-input -p tcp --dport 445 -j ufw-skip-to-policy-input
-A ufw-after-input -p udp --dport 67 -j ufw-skip-to-policy-input
-A ufw-after-input -p udp --dport 68 -j ufw-skip-to-policy-input
# don't log noisy broadcast
-A ufw-after-input -m addrtype --dst-type BROADCAST -j ufw-skip-to-policy-input
# don't delete the 'COMMIT' line or these rules won't be processed
COMMIT
+18
View File
@@ -0,0 +1,18 @@
# Changed settings, interfaces, udp, ranges, French messages.
lang fr
mode enforce
chain fence-x
block_marker FENCE-TEST
log_prefix_observe OBS
log_prefix_drop DRP
log_rate_enforce 5/second
log_burst_enforce 7
log_level 4
admin 192.0.2.0/28 iface wg0
admin 198.51.100.7
trusted_iface br-custom
trusted_iface veth+
allow udp 51820 from any iface eth0
allow udp 6000-6010 from 203.0.113.128/25
container_to_host udp 53 from_iface docker0
container_to_host tcp 3000-3002
+1
View File
@@ -0,0 +1 @@
admin 192.0.2.10
+2
View File
@@ -0,0 +1,2 @@
n1
n2
+2
View File
@@ -0,0 +1,2 @@
/web|172.18.0.2 |80/tcp=0.0.0.0:8080,:::8080, 53/udp=0.0.0.0:5353,
/db|172.19.0.3 172.20.0.3 |5432/tcp=0.0.0.0:15432,0.0.0.0:25432,
+2
View File
@@ -0,0 +1,2 @@
aaa111
bbb222
+2
View File
@@ -0,0 +1,2 @@
n1 172.17.0.0/16
n2 172.18.0.0/16 fd00::/64
+7
View File
@@ -0,0 +1,7 @@
2026-12-05T10:00:00+0000 host kernel: DOCKER-WOULD-DROP IN=eth0 OUT=br-1a2b3c4d5e6f MAC=00:00:00:00:00:00 SRC=203.0.113.5 DST=172.18.0.2 LEN=60 TOS=0x00 PREC=0x00 TTL=50 ID=1 DF PROTO=TCP SPT=51000 DPT=80 WINDOW=64240 RES=0x00 SYN URGP=0
2026-12-05T10:00:01+0000 host kernel: DOCKER-WOULD-DROP IN=eth0 OUT=br-1a2b3c4d5e6f MAC=00:00:00:00:00:00 SRC=203.0.113.5 DST=172.18.0.2 LEN=60 TOS=0x00 PREC=0x00 TTL=50 ID=2 DF PROTO=TCP SPT=51001 DPT=80 WINDOW=64240 RES=0x00 SYN URGP=0
2026-12-05T10:00:02+0000 host kernel: DOCKER-WOULD-DROP IN=eth0 OUT=br-1a2b3c4d5e6f MAC=00:00:00:00:00:00 SRC=203.0.113.5 DST=172.18.0.2 LEN=60 TOS=0x00 PREC=0x00 TTL=50 ID=3 DF PROTO=TCP SPT=51002 DPT=80 WINDOW=64240 RES=0x00 SYN URGP=0
2026-12-05T10:00:03+0000 host kernel: DOCKER-FENCE-DROP IN=eth0 OUT=br-99887766aabb MAC=00:00:00:00:00:00 SRC=198.51.100.20 DST=172.20.0.3 LEN=60 TOS=0x00 PREC=0x00 TTL=50 ID=4 DF PROTO=TCP SPT=40000 DPT=5432 WINDOW=64240 RES=0x00 SYN URGP=0
2026-12-05T10:00:04+0000 host kernel: DOCKER-WOULD-DROP IN=eth0 OUT=br-1a2b3c4d5e6f MAC=00:00:00:00:00:00 SRC=198.51.100.20 DST=172.18.0.2 LEN=40 TOS=0x00 PREC=0x00 TTL=50 ID=5 PROTO=UDP SPT=40001 DPT=53 LEN=20
2026-12-05T10:00:05+0000 host kernel: DOCKER-WOULD-DROP IN=eth0 OUT=br-ffffffffffff MAC=00:00:00:00:00:00 SRC=192.0.2.99 DST=172.30.0.9 LEN=60 TOS=0x00 PREC=0x00 TTL=50 ID=6 DF PROTO=TCP SPT=40002 DPT=9999 WINDOW=64240 RES=0x00 SYN URGP=0
2026-12-05T10:00:06+0000 host kernel: [UFW BLOCK] IN=br-1a2b3c4d5e6f OUT= MAC=00:00:00:00:00:00 SRC=172.18.0.2 DST=172.18.0.1 LEN=60 PROTO=TCP SPT=40003 DPT=8080 WINDOW=64240 SYN URGP=0
+27
View File
@@ -0,0 +1,27 @@
# 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
+6
View File
@@ -0,0 +1,6 @@
Added user rules (see 'ufw status' for running firewall):
ufw allow 22/tcp
ufw allow from 192.0.2.10
ufw limit 2222/tcp
ufw allow proto tcp from 198.51.100.0/24 to any port 5432
ufw route allow proto tcp from any to any port 80
+15
View File
@@ -0,0 +1,15 @@
Status: active
Logging: on (low)
Default: deny (incoming), allow (outgoing), deny (routed)
New profiles: skip
To Action From
-- ------ ----
22/tcp ALLOW IN Anywhere # ssh
Anywhere on wg0 ALLOW IN 192.0.2.10
5432/tcp DENY IN 198.51.100.0/24
2222/tcp LIMIT IN Anywhere
22/tcp (v6) ALLOW IN Anywhere (v6) # ssh
80/tcp ALLOW FWD Anywhere
53 ALLOW OUT Anywhere
+114
View File
@@ -0,0 +1,114 @@
#!/usr/bin/env bats
# Block generation: comparison with golden files and real syntax check
# with iptables-restore --test.
load helpers
bats_require_minimum_version 1.5.0
setup() {
setup_env
}
# golden CONFIG REFERENCE [OPTIONS...]
golden() {
local ref="$2"
# Copy: the configuration must belong to the current user.
cp "$1" "$CONF"
chmod 0644 "$CONF"
shift 2
run --separate-stderr fence "$@" check
[ "$status" -eq 0 ]
diff -u "$GOLDEN/$ref" <(printf '%s\n' "$output")
}
@test "example in observe mode" {
golden "$REPO/examples/fence.conf" example-observe.rules
}
@test "example in enforce mode" {
golden "$REPO/examples/fence.conf" example-enforce.rules --mode enforce
}
@test "minimal configuration: no second container_to_host block" {
golden "$FIXTURES/conf/minimal.conf" minimal-observe.rules
[[ "$output" != *"ufw-after-input"* ]]
}
@test "changed settings, interfaces, udp, ranges, French header" {
golden "$FIXTURES/conf/custom.conf" custom-enforce.rules
}
@test "standard output only carries the block" {
cp "$REPO/examples/fence.conf" "$CONF"; chmod 0644 "$CONF"
run --separate-stderr fence check
[ "${lines[0]}" = "# BEGIN DOCKER-FENCE (managed by docker-fence, do not edit by hand)" ]
[ "${lines[-1]}" = "# END DOCKER-FENCE" ]
[[ "$stderr" == *"configuration valid"* ]]
}
@test "one rule per source, never a comma-separated list" {
cp "$REPO/examples/fence.conf" "$CONF"; chmod 0644 "$CONF"
run --separate-stderr fence check
! grep -E -- '-s [^ ]*,' <<<"$output"
}
@test "from any drops the -s option" {
printf 'admin 192.0.2.10\nallow tcp 443 from any\n' | write_conf
run --separate-stderr fence check
grep -qxF -- '-A docker-fence -p tcp -m conntrack --ctorigdstport 443 -j RETURN' <<<"$output"
}
@test "check changes nothing" {
cp "$REPO/examples/fence.conf" "$CONF"; chmod 0644 "$CONF"
local before
before="$(sum_of "$RULES")"
run fence check
[ "$status" -eq 0 ]
[ "$(sum_of "$RULES")" = "$before" ]
[ ! -e "$BACKUPS" ]
[ ! -s "$KERNEL" ]
! grep -qE '^(ufw reload|iptables -[ADFX]|systemd-run)' "$STUB_LOG"
}
# Real syntax: needs iptables-restore and the NET_ADMIN capability (the test
# runs in the network namespace of the test container, nothing is loaded).
REAL_PATH=/usr/sbin:/sbin:/usr/bin:/bin
need_iptables_restore() {
PATH="$REAL_PATH" command -v iptables-restore >/dev/null || skip "iptables-restore not found"
PATH="$REAL_PATH" iptables -S >/dev/null 2>&1 || skip "not enough privileges (NET_ADMIN)"
}
# Returns the exit code of iptables-restore --test on the given block.
restore_test() {
local input="$BATS_TEST_TMPDIR/restore.rules"
{
# Chain declared by UFW earlier in after.rules.
printf '*filter\n:ufw-after-input - [0:0]\nCOMMIT\n'
cat "$1"
} >"$input"
PATH="$REAL_PATH" iptables-restore --test --noflush "$input"
}
@test "iptables-restore --test accepts the observe block" {
need_iptables_restore
restore_test "$GOLDEN/example-observe.rules"
}
@test "iptables-restore --test accepts the enforce block" {
need_iptables_restore
restore_test "$GOLDEN/example-enforce.rules"
}
@test "iptables-restore --test accepts the custom block" {
need_iptables_restore
restore_test "$GOLDEN/custom-enforce.rules"
}
@test "iptables-restore --test refuses a broken block (the check is meaningful)" {
need_iptables_restore
sed 's/--ctorigdstport 443/--ctorigdstport x443/' "$GOLDEN/example-observe.rules" >"$BATS_TEST_TMPDIR/bad.rules"
run restore_test "$BATS_TEST_TMPDIR/bad.rules"
[ "$status" -ne 0 ]
}
+24
View File
@@ -0,0 +1,24 @@
# BEGIN FENCE-TEST (géré par docker-fence, ne pas modifier à la main)
*filter
:DOCKER-USER - [0:0]
:fence-x - [0:0]
:fence-x-deny - [0:0]
-A DOCKER-USER -j fence-x
-A DOCKER-USER -j RETURN
-A fence-x -m conntrack --ctstate RELATED,ESTABLISHED -j RETURN
-A fence-x -i br-custom -j RETURN
-A fence-x -i veth+ -j RETURN
-A fence-x -i wg0 -s 192.0.2.0/28 -j RETURN
-A fence-x -s 198.51.100.7/32 -j RETURN
-A fence-x -i eth0 -p udp -m conntrack --ctorigdstport 51820 -j RETURN
-A fence-x -p udp -m conntrack --ctorigdstport 6000:6010 -s 203.0.113.128/25 -j RETURN
-A fence-x -m conntrack --ctstate DNAT -j fence-x-deny
-A fence-x -j RETURN
-A fence-x-deny -m limit --limit 5/second --limit-burst 7 -j LOG --log-prefix "DRP " --log-level 4
-A fence-x-deny -j DROP
COMMIT
*filter
-A ufw-after-input -i docker0 -p udp --dport 53 -j ACCEPT
-A ufw-after-input -i br-+ -p tcp --dport 3000:3002 -j ACCEPT
COMMIT
# END FENCE-TEST
+24
View File
@@ -0,0 +1,24 @@
# BEGIN DOCKER-FENCE (managed by docker-fence, do not edit by hand)
*filter
:DOCKER-USER - [0:0]
:docker-fence - [0:0]
:docker-fence-deny - [0:0]
-A DOCKER-USER -j docker-fence
-A DOCKER-USER -j RETURN
-A docker-fence -m conntrack --ctstate RELATED,ESTABLISHED -j RETURN
-A docker-fence -i br-+ -j RETURN
-A docker-fence -i docker0 -j RETURN
-A docker-fence -s 192.0.2.10/32 -j RETURN
-A docker-fence -i wg0 -s 192.0.2.11/32 -j RETURN
-A docker-fence -p tcp -m conntrack --ctorigdstport 443 -j RETURN
-A docker-fence -p tcp -m conntrack --ctorigdstport 5432 -s 198.51.100.20/32 -j RETURN
-A docker-fence -p tcp -m conntrack --ctorigdstport 9000:9010 -s 203.0.113.0/24 -j RETURN
-A docker-fence -m conntrack --ctstate DNAT -j docker-fence-deny
-A docker-fence -j RETURN
-A docker-fence-deny -m limit --limit 20/min --limit-burst 40 -j LOG --log-prefix "DOCKER-FENCE-DROP " --log-level 6
-A docker-fence-deny -j DROP
COMMIT
*filter
-A ufw-after-input -i br-+ -p tcp --dport 8080 -j ACCEPT
COMMIT
# END DOCKER-FENCE
+24
View File
@@ -0,0 +1,24 @@
# BEGIN DOCKER-FENCE (managed by docker-fence, do not edit by hand)
*filter
:DOCKER-USER - [0:0]
:docker-fence - [0:0]
:docker-fence-deny - [0:0]
-A DOCKER-USER -j docker-fence
-A DOCKER-USER -j RETURN
-A docker-fence -m conntrack --ctstate RELATED,ESTABLISHED -j RETURN
-A docker-fence -i br-+ -j RETURN
-A docker-fence -i docker0 -j RETURN
-A docker-fence -s 192.0.2.10/32 -j RETURN
-A docker-fence -i wg0 -s 192.0.2.11/32 -j RETURN
-A docker-fence -p tcp -m conntrack --ctorigdstport 443 -j RETURN
-A docker-fence -p tcp -m conntrack --ctorigdstport 5432 -s 198.51.100.20/32 -j RETURN
-A docker-fence -p tcp -m conntrack --ctorigdstport 9000:9010 -s 203.0.113.0/24 -j RETURN
-A docker-fence -m conntrack --ctstate DNAT -m limit --limit 120/min --limit-burst 200 -j LOG --log-prefix "DOCKER-WOULD-DROP " --log-level 6
-A docker-fence -j RETURN
-A docker-fence-deny -m limit --limit 20/min --limit-burst 40 -j LOG --log-prefix "DOCKER-FENCE-DROP " --log-level 6
-A docker-fence-deny -j DROP
COMMIT
*filter
-A ufw-after-input -i br-+ -p tcp --dport 8080 -j ACCEPT
COMMIT
# END DOCKER-FENCE
+17
View File
@@ -0,0 +1,17 @@
# BEGIN DOCKER-FENCE (managed by docker-fence, do not edit by hand)
*filter
:DOCKER-USER - [0:0]
:docker-fence - [0:0]
:docker-fence-deny - [0:0]
-A DOCKER-USER -j docker-fence
-A DOCKER-USER -j RETURN
-A docker-fence -m conntrack --ctstate RELATED,ESTABLISHED -j RETURN
-A docker-fence -i br-+ -j RETURN
-A docker-fence -i docker0 -j RETURN
-A docker-fence -s 192.0.2.10/32 -j RETURN
-A docker-fence -m conntrack --ctstate DNAT -m limit --limit 120/min --limit-burst 200 -j LOG --log-prefix "DOCKER-WOULD-DROP " --log-level 6
-A docker-fence -j RETURN
-A docker-fence-deny -m limit --limit 20/min --limit-burst 40 -j LOG --log-prefix "DOCKER-FENCE-DROP " --log-level 6
-A docker-fence-deny -j DROP
COMMIT
# END DOCKER-FENCE
+64
View File
@@ -0,0 +1,64 @@
# shellcheck shell=bash
# Variables used by the .bats files:
# shellcheck disable=SC2034
# Common test functions: temporary tree (FENCE_ROOT), fake binaries
# first in PATH, test configuration.
REPO="$(cd "$BATS_TEST_DIRNAME/.." && pwd)"
FENCE="$REPO/docker-fence"
FIXTURES="$REPO/tests/fixtures"
GOLDEN="$REPO/tests/golden"
setup_env() {
export FENCE_ROOT="$BATS_TEST_TMPDIR/root"
export STUB_STATE="$BATS_TEST_TMPDIR/state"
export STUB_LOG="$BATS_TEST_TMPDIR/calls.log"
export STUB_DOCKER_DIR="$BATS_TEST_TMPDIR/docker"
mkdir -p "$FENCE_ROOT/etc/ufw" "$FENCE_ROOT/etc/docker-fence" "$FENCE_ROOT/etc/docker" \
"$FENCE_ROOT/var/log" "$STUB_STATE" "$STUB_DOCKER_DIR"
RULES="$FENCE_ROOT/etc/ufw/after.rules"
cp "$FIXTURES/after.rules" "$RULES"
chmod 0640 "$RULES"
CONF="$FENCE_ROOT/etc/docker-fence/fence.conf"
BACKUPS="$FENCE_ROOT/var/backups/docker-fence"
KERNEL="$STUB_STATE/kernel"
: >"$STUB_LOG"
export PATH="$REPO/tests/stubs:$PATH"
unset FENCE_LANG FENCE_CONFIG
cd "$BATS_TEST_TMPDIR" || return 1
}
# Writes the test configuration from standard input.
write_conf() {
cat >"$CONF"
chmod 0644 "$CONF"
}
# Minimal valid configuration.
minimal_conf() {
printf 'admin 192.0.2.10\n' | write_conf
}
fence() {
"$FENCE" -c "$CONF" "$@"
}
# Runs the command recorded by the fake systemd-run (rollback timer
# expiry).
fire_timer() {
local -a cmd
mapfile -t cmd <"$STUB_STATE/timer_cmd"
rm -f "$STUB_STATE/timer_cmd"
"${cmd[@]}"
}
# Checksum of a file (byte for byte comparison).
sum_of() {
sha256sum "$1" | cut -d' ' -f1
}
# Appends the original ufw-docker block to the rules file.
add_legacy() {
printf '\n' >>"$RULES"
cat "$FIXTURES/legacy-block.rules" >>"$RULES"
}
+266
View File
@@ -0,0 +1,266 @@
#!/usr/bin/env bats
# install, uninstall, original ufw-docker block, backups, environment.
load helpers
bats_require_minimum_version 1.5.0
setup() {
setup_env
cp "$REPO/examples/fence.conf" "$CONF"
chmod 0644 "$CONF"
}
count_backups() {
find "$BACKUPS" -maxdepth 1 -name 'after.rules.[0-9]*' 2>/dev/null | wc -l
}
@test "install appends the block without touching the rest" {
run fence install
[ "$status" -eq 0 ]
# The start of the file is the original, byte for byte.
local n
n="$(wc -l <"$FIXTURES/after.rules")"
diff "$FIXTURES/after.rules" <(head -n "$n" "$RULES")
# Then an empty line and the golden block.
diff <(printf '\n'; cat "$GOLDEN/example-observe.rules") <(tail -n +"$((n + 1))" "$RULES")
}
@test "install does not reload UFW" {
run fence install
[ "$status" -eq 0 ]
! grep -q '^ufw reload' "$STUB_LOG"
! grep -q '^systemd-run' "$STUB_LOG"
[[ "$output" == *'next "ufw reload"'* ]]
}
@test "install is idempotent (byte for byte) and makes no useless backup" {
fence install
local first
first="$(sum_of "$RULES")"
[ "$(count_backups)" -eq 1 ]
run fence install
[ "$status" -eq 0 ]
[[ "$output" == *"already up to date"* ]]
[ "$(sum_of "$RULES")" = "$first" ]
[ "$(count_backups)" -eq 1 ]
}
@test "install replaces the existing block, one block in the file" {
fence install
fence --mode enforce install
[ "$(grep -c '^# BEGIN DOCKER-FENCE' "$RULES")" -eq 1 ]
grep -qF -- '--ctstate DNAT -j docker-fence-deny' "$RULES"
! grep -qF -- 'DOCKER-WOULD-DROP' "$RULES"
# Back to observe mode: same file as after the first install.
fence install
local n
n="$(wc -l <"$FIXTURES/after.rules")"
diff <(cat "$FIXTURES/after.rules"; printf '\n'; cat "$GOLDEN/example-observe.rules") "$RULES"
}
@test "a block moved inside the file goes back to the end, once" {
{
cat "$GOLDEN/example-enforce.rules"
cat "$FIXTURES/after.rules"
} >"$RULES"
run fence install
[ "$status" -eq 0 ]
diff <(cat "$FIXTURES/after.rules"; printf '\n'; cat "$GOLDEN/example-observe.rules") "$RULES"
}
@test "file without a final newline" {
printf '*filter\nCOMMIT' >"$RULES"
fence install
diff <(printf '*filter\nCOMMIT\n\n'; cat "$GOLDEN/example-observe.rules") "$RULES"
}
@test "backup: original content, mode 0600, directory 0700" {
local before
before="$(sum_of "$RULES")"
fence install
local b
b="$(find "$BACKUPS" -name 'after.rules.[0-9]*')"
[ "$(sum_of "$b")" = "$before" ]
[ "$(stat -c %a "$b")" = 600 ]
[ "$(stat -c %a "$BACKUPS")" = 700 ]
}
@test "atomic write: mode and owner kept, no temporary file left" {
chmod 0604 "$RULES"
if [ "$EUID" -eq 0 ]; then
chown 4321:4322 "$RULES"
fi
fence install
[ "$(stat -c %a "$RULES")" = 604 ]
if [ "$EUID" -eq 0 ]; then
[ "$(stat -c %u:%g "$RULES")" = 4321:4322 ]
fi
[ -z "$(find "$FENCE_ROOT/etc/ufw" -name '.after.rules.*')" ]
}
@test "backup rotation (backup_keep)" {
printf 'backup_keep 3\n' >>"$CONF"
local i
for i in 1 2 3 4 5; do
fence --set rollback_seconds="$((100 + i))" --set log_burst_observe="$i" install
done
[ "$(count_backups)" -eq 3 ]
}
@test "missing after.rules: unsupported environment" {
rm "$RULES"
run fence install
[ "$status" -eq 2 ]
[[ "$output" == *"missing or unreadable"* ]]
}
@test "inconsistent managed block: start without end, two starts, end alone" {
local before
printf '\n# BEGIN DOCKER-FENCE\n*filter\n' >>"$RULES"
before="$(sum_of "$RULES")"
run fence install
[ "$status" -eq 1 ]
[[ "$output" == *"without an end"* ]]
[ "$(sum_of "$RULES")" = "$before" ]
cp "$FIXTURES/after.rules" "$RULES"
cat "$GOLDEN/example-observe.rules" "$GOLDEN/example-observe.rules" >>"$RULES"
run fence install
[ "$status" -eq 1 ]
[[ "$output" == *"twice"* ]]
cp "$FIXTURES/after.rules" "$RULES"
printf '# END DOCKER-FENCE\n' >>"$RULES"
run fence install
[ "$status" -eq 1 ]
[[ "$output" == *"without a start"* ]]
}
@test "original block without --replace-legacy: exit code 3, nothing changes" {
add_legacy
local before
before="$(sum_of "$RULES")"
run fence install
[ "$status" -eq 3 ]
[[ "$output" == *"--replace-legacy"* ]]
[[ "$output" == *"# BEGIN UFW AND DOCKER"* ]]
[ "$(sum_of "$RULES")" = "$before" ]
[ ! -e "$BACKUPS" ]
}
@test "--replace-legacy removes and saves the original block, managed block at the end" {
add_legacy
run fence install --replace-legacy
[ "$status" -eq 0 ]
! grep -q 'UFW AND DOCKER' "$RULES"
diff <(cat "$FIXTURES/after.rules"; printf '\n'; cat "$GOLDEN/example-observe.rules") "$RULES"
diff "$FIXTURES/legacy-block.rules" "$BACKUPS/legacy-block.rules"
[ "$(stat -c %a "$BACKUPS/legacy-block.rules")" = 600 ]
}
@test "modified original block: reported with a diff, replaced only with --force" {
add_legacy
sed -i 's|-A DOCKER-USER -j RETURN -s 192.168.0.0/16|-A DOCKER-USER -j RETURN -s 192.168.1.0/24|' "$RULES"
local before
before="$(sum_of "$RULES")"
run fence install --replace-legacy
[ "$status" -eq 3 ]
[[ "$output" == *"differs from the known version"* ]]
[[ "$output" == *"+-A DOCKER-USER -j RETURN -s 192.168.1.0/24"* ]]
[ "$(sum_of "$RULES")" = "$before" ]
run fence install --replace-legacy --force
[ "$status" -eq 0 ]
! grep -q 'UFW AND DOCKER' "$RULES"
grep -q '192.168.1.0/24' "$BACKUPS/legacy-block.rules"
}
@test "an original block without an end is refused" {
printf '\n# BEGIN UFW AND DOCKER\n*filter\n' >>"$RULES"
run fence install --replace-legacy
[ "$status" -eq 1 ]
}
@test "uninstall removes the block, reloads UFW and cleans the kernel" {
fence install
"$REPO/tests/stubs/ufw" reload
grep -qxF -- '-A DOCKER-USER -j docker-fence' "$KERNEL"
run fence uninstall
[ "$status" -eq 0 ]
diff "$FIXTURES/after.rules" "$RULES"
grep -q '^ufw reload' "$STUB_LOG"
# ufw reload (--noflush) does not flush DOCKER-USER: the tool removes the jump.
! grep -qF -- '-j docker-fence' "$KERNEL"
! grep -q '^-A docker-fence' "$KERNEL"
grep -qx 'docker-fence' "$STUB_STATE/deleted-chains"
grep -qx 'docker-fence-deny' "$STUB_STATE/deleted-chains"
}
@test "uninstall without block: nothing to do" {
run fence uninstall
[ "$status" -eq 0 ]
[[ "$output" == *"no managed block"* ]]
diff "$FIXTURES/after.rules" "$RULES"
}
@test "uninstall with UFW inactive: file changed, nothing reloaded" {
fence install
STUB_UFW_INACTIVE=1 run fence uninstall
[ "$status" -eq 0 ]
[[ "$output" == *"nothing reloaded"* ]]
! grep -q '^ufw reload' "$STUB_LOG"
}
@test "uninstall --restore-legacy puts the original block back" {
add_legacy
local orig
orig="$(sum_of "$RULES")"
fence install --replace-legacy
run fence uninstall --restore-legacy
[ "$status" -eq 0 ]
[ "$(sum_of "$RULES")" = "$orig" ]
}
@test "uninstall --restore-legacy without a saved original block" {
fence install
run fence uninstall --restore-legacy
[ "$status" -eq 1 ]
[[ "$output" == *"no saved original block"* ]]
}
@test "daemon.json: iptables disabled or nftables backend refused (exit code 2)" {
printf '{\n "iptables" : false\n}\n' >"$FENCE_ROOT/etc/docker/daemon.json"
run fence install
[ "$status" -eq 2 ]
[[ "$output" == *"disables iptables"* ]]
run fence check
[ "$status" -eq 2 ]
printf '{"firewall-backend": "nftables"}\n' >"$FENCE_ROOT/etc/docker/daemon.json"
run fence install
[ "$status" -eq 2 ]
[[ "$output" == *"native nftables"* ]]
[ ! -e "$BACKUPS" ]
}
@test "daemon.json: IPv6 enabled gives a warning" {
printf '{"ipv6": true, "iptables": true}\n' >"$FENCE_ROOT/etc/docker/daemon.json"
run fence check
[ "$status" -eq 0 ]
[[ "$output" == *"warning: "*"IPv6"* ]]
}
@test "macvlan and ipvlan networks reported" {
printf 'lan\n' >"$STUB_DOCKER_DIR/macvlan"
printf 'l2a\nl2b\n' >"$STUB_DOCKER_DIR/ipvlan"
run fence check
[ "$status" -eq 0 ]
[[ "$output" == *"macvlan networks found (lan)"* ]]
[[ "$output" == *"ipvlan networks found (l2a l2b)"* ]]
}
@test "versions are printed" {
run fence check
[[ "$output" == *"bash ${BASH_VERSION}; docker 29.0.0; iptables v1.8.10 (nf_tables); ufw 0.36.2"* ]]
}
+238
View File
@@ -0,0 +1,238 @@
#!/usr/bin/env bats
# install.sh: installation and removal under a temporary prefix.
load helpers
bats_require_minimum_version 1.5.0
INSTALLER=""
setup() {
setup_env
INSTALLER="$REPO/install.sh"
PREFIX="$BATS_TEST_TMPDIR/prefix"
}
need_root() {
[ "$EUID" -eq 0 ] || skip "install.sh needs root"
}
# State of the real configuration file, read only: checksum, or "absent".
config_state() {
if [ -e /etc/docker-fence/fence.conf ]; then
sum_of /etc/docker-fence/fence.conf
else
echo absent
fi
}
@test "install.sh refuses to run without root" {
if [ "$EUID" -eq 0 ]; then
command -v setpriv >/dev/null || skip "setpriv not found"
run setpriv --reuid=65534 --regid=65534 --clear-groups bash "$INSTALLER" --prefix "$PREFIX"
else
run bash "$INSTALLER" --prefix "$PREFIX"
fi
[ "$status" -eq 1 ]
[[ "$output" == *"must be run as root"* ]]
[ ! -e "$PREFIX" ]
}
@test "install.sh installs the tool and the libraries, and prints them" {
need_root
run bash "$INSTALLER" --prefix "$PREFIX"
[ "$status" -eq 0 ]
[ "$(stat -c %a "$PREFIX/lib/docker-fence/docker-fence")" = 755 ]
local f
for f in "$REPO"/lib/*.sh; do
cmp "$f" "$PREFIX/lib/docker-fence/lib/$(basename "$f")"
[ "$(stat -c %a "$PREFIX/lib/docker-fence/lib/$(basename "$f")")" = 644 ]
[[ "$output" == *"installed $PREFIX/lib/docker-fence/lib/$(basename "$f")"* ]]
done
[ "$(readlink "$PREFIX/bin/docker-fence")" = "$PREFIX/lib/docker-fence/docker-fence" ]
[[ "$output" == *"installed $PREFIX/lib/docker-fence/docker-fence"* ]]
[[ "$output" == *"linked $PREFIX/bin/docker-fence -> $PREFIX/lib/docker-fence/docker-fence"* ]]
# The installed command works through the symlink.
run "$PREFIX/bin/docker-fence" --version
[ "$status" -eq 0 ]
[[ "$output" == "docker-fence "* ]]
run "$PREFIX/bin/docker-fence" -c "$REPO/examples/fence.conf" --help
[ "$status" -eq 0 ]
}
@test "install.sh twice gives the same result and removes stale libraries" {
need_root
bash "$INSTALLER" --prefix "$PREFIX"
touch "$PREFIX/lib/docker-fence/lib/old.sh"
run bash "$INSTALLER" --prefix "$PREFIX"
[ "$status" -eq 0 ]
[ ! -e "$PREFIX/lib/docker-fence/lib/old.sh" ]
[[ "$output" == *"removed stale $PREFIX/lib/docker-fence/lib/old.sh"* ]]
diff <(cd "$REPO/lib" && ls) <(cd "$PREFIX/lib/docker-fence/lib" && ls)
}
@test "install.sh never touches /etc/docker-fence/fence.conf" {
need_root
! grep -nE '(>|rm|cp|mv|install|ln|chmod|chown|mkdir)[^#]*\$CONFIG' "$INSTALLER"
local before
before="$(config_state)"
bash "$INSTALLER" --prefix "$PREFIX"
[ "$(config_state)" = "$before" ]
bash "$INSTALLER" --prefix "$PREFIX" --uninstall
[ "$(config_state)" = "$before" ]
}
@test "install.sh --uninstall removes what was installed, nothing else" {
need_root
bash "$INSTALLER" --prefix "$PREFIX"
touch "$PREFIX/bin/other-tool"
run bash "$INSTALLER" --prefix "$PREFIX" --uninstall
[ "$status" -eq 0 ]
[ ! -e "$PREFIX/bin/docker-fence" ]
[ ! -e "$PREFIX/lib/docker-fence" ]
[ -e "$PREFIX/bin/other-tool" ]
[[ "$output" == *"removed $PREFIX/bin/docker-fence"* ]]
[[ "$output" == *"removed $PREFIX/lib/docker-fence/lib/config.sh"* ]]
[[ "$output" == *"removed $PREFIX/lib/docker-fence"* ]]
}
@test "install.sh --uninstall when nothing is installed" {
need_root
run bash "$INSTALLER" --prefix "$PREFIX" --uninstall
[ "$status" -eq 0 ]
[[ "$output" == *"nothing to remove in $PREFIX"* ]]
}
@test "install.sh keeps a docker-fence command it did not install" {
need_root
mkdir -p "$PREFIX/bin"
printf '#!/bin/sh\n' >"$PREFIX/bin/docker-fence"
run bash "$INSTALLER" --prefix "$PREFIX"
[ "$status" -eq 1 ]
[[ "$output" == *"is not a symlink"* ]]
run bash "$INSTALLER" --prefix "$PREFIX" --uninstall
[ "$status" -eq 0 ]
[ -f "$PREFIX/bin/docker-fence" ]
[[ "$output" == *"kept $PREFIX/bin/docker-fence"* ]]
rm "$PREFIX/bin/docker-fence"
ln -s /usr/bin/true "$PREFIX/bin/docker-fence"
run bash "$INSTALLER" --prefix "$PREFIX" --uninstall
[ -L "$PREFIX/bin/docker-fence" ]
[[ "$output" == *"points elsewhere"* ]]
}
@test "install.sh options: --help, invalid prefix, unknown option" {
run bash "$INSTALLER" --help
[ "$status" -eq 0 ]
[[ "$output" == "Usage: install.sh"* ]]
run bash "$INSTALLER" --prefix relative/dir
[ "$status" -eq 1 ]
[[ "$output" == *"absolute path"* ]]
run bash "$INSTALLER" --prefix '/opt/a b'
[ "$status" -eq 1 ]
run bash "$INSTALLER" --prefix /
[ "$status" -eq 1 ]
run bash "$INSTALLER" --prefix
[ "$status" -eq 1 ]
run bash "$INSTALLER" --frobnicate
[ "$status" -eq 1 ]
[[ "$output" == *"unknown option: --frobnicate"* ]]
}
@test "install.sh --prefix=DIR form" {
need_root
run bash "$INSTALLER" --prefix="$PREFIX"
[ "$status" -eq 0 ]
[ -L "$PREFIX/bin/docker-fence" ]
}
@test "install.sh lists exactly the files of the tool" {
local listed actual
listed="$(sed -n '/^readonly FILES=(/,/^)/p' "$INSTALLER" | sed '1d;$d' | tr -d ' ' | sort)"
actual="$( (cd "$REPO" && printf '%s\n' docker-fence lib/*.sh) | sort)"
[ "$listed" = "$actual" ]
}
@test "install.sh writes no firewall rule and explains the next steps" {
need_root
: >"$STUB_LOG"
run bash "$INSTALLER" --prefix "$PREFIX"
[ "$status" -eq 0 ]
# The fake ufw, iptables, systemd-run and systemctl are first in PATH.
! grep -qE '^(ufw|iptables|systemd-run|systemctl) ' "$STUB_LOG"
[ ! -s "$KERNEL" ]
[[ "$output" == *"No firewall rule was written."* ]]
[[ "$output" == *"/etc/docker-fence/fence.conf"* ]]
[[ "$output" == *" init "* || "$output" == *"already exists"* ]]
[[ "$output" == *" check "* ]]
[[ "$output" == *" apply "* ]]
[[ "$output" == *" confirm "* ]]
[[ "$output" == *" rules "* ]]
}
@test "install.sh alone downloads the files (curl, no git)" {
need_root
command -v curl >/dev/null || skip "curl not found"
mkdir -p "$BATS_TEST_TMPDIR/alone"
cp "$INSTALLER" "$BATS_TEST_TMPDIR/alone/install.sh"
run bash "$BATS_TEST_TMPDIR/alone/install.sh" --prefix "$PREFIX" --source-url "file://$REPO"
[ "$status" -eq 0 ]
[[ "$output" == *"downloading docker-fence from file://$REPO"* ]]
cmp "$REPO/docker-fence" "$PREFIX/lib/docker-fence/docker-fence"
local f
for f in "$REPO"/lib/*.sh; do
cmp "$f" "$PREFIX/lib/docker-fence/lib/$(basename "$f")"
done
run "$PREFIX/bin/docker-fence" --version
[ "$status" -eq 0 ]
}
@test "curl ... | sudo bash: install.sh read from a pipe" {
need_root
command -v curl >/dev/null || skip "curl not found"
run bash -c 'bash -s -- --prefix "$1" --source-url "file://$2" <"$3"' _ "$PREFIX" "$REPO" "$INSTALLER"
[ "$status" -eq 0 ]
[[ "$output" == *"downloading docker-fence"* ]]
[ -L "$PREFIX/bin/docker-fence" ]
"$PREFIX/bin/docker-fence" --version
}
@test "install.sh refuses a download that is not the expected script" {
need_root
command -v curl >/dev/null || skip "curl not found"
local bad="$BATS_TEST_TMPDIR/bad"
mkdir -p "$bad/lib"
cp "$REPO"/lib/*.sh "$bad/lib/"
printf '<!doctype html><title>Making sure you are not a bot</title>\n' >"$bad/docker-fence"
run bash -s -- --prefix "$PREFIX" --source-url "file://$bad" <"$INSTALLER"
[ "$status" -eq 1 ]
[[ "$output" == *"unexpected content for docker-fence"* ]]
[ ! -e "$PREFIX" ]
cp "$REPO/docker-fence" "$bad/docker-fence"
rm "$bad/lib/listing.sh"
run bash -s -- --prefix "$PREFIX" --source-url "file://$bad" <"$INSTALLER"
[ "$status" -eq 1 ]
[[ "$output" == *"download failed"*"lib/listing.sh"* ]]
[ ! -e "$PREFIX" ]
}
@test "install.sh refuses invalid source URL and ref names" {
run bash "$INSTALLER" --source-url http://example.invalid/x
[ "$status" -eq 1 ]
[[ "$output" == *"https:// or file:// URL"* ]]
run bash "$INSTALLER" --tag 'v1;id'
[ "$status" -eq 1 ]
[[ "$output" == *"invalid branch or tag name"* ]]
run bash "$INSTALLER" --branch
[ "$status" -eq 1 ]
}
@test "install.sh --uninstall says the firewall is not changed" {
need_root
bash "$INSTALLER" --prefix "$PREFIX"
run bash "$INSTALLER" --prefix "$PREFIX" --uninstall
[ "$status" -eq 0 ]
[[ "$output" == *"No firewall rule was changed"* ]]
}
+143
View File
@@ -0,0 +1,143 @@
#!/usr/bin/env bats
# report, ufw-plan, status: read only.
load helpers
bats_require_minimum_version 1.5.0
setup() {
setup_env
cp "$REPO/examples/fence.conf" "$CONF"
chmod 0644 "$CONF"
cp "$FIXTURES"/docker/* "$STUB_DOCKER_DIR/"
export STUB_JOURNAL="$FIXTURES/journal.log"
}
@test "report aggregates by source and container, most frequent first" {
run --separate-stderr fence report
[ "$status" -eq 0 ]
[[ "$stderr" == *'report since "24 hours ago": 6 logged packets'* ]]
# Header line, then the sorted flows.
[[ "${lines[1]}" =~ ^\ +3\ +203\.0\.113\.5\ +web:80/tcp\ +8080$ ]]
[[ "$output" =~ 1\ +198\.51\.100\.20\ +db:5432/tcp\ +15432\ 25432 ]]
[[ "$output" =~ 1\ +198\.51\.100\.20\ +web:53/udp\ +5353 ]]
[[ "$output" =~ 1\ +192\.0\.2\.99\ +172\.30\.0\.9:9999/tcp\ +\? ]]
}
@test "report suggests allow lines with the published port, not the internal one" {
run --separate-stderr fence report
[[ "$output" == *"allow tcp 8080 from 203.0.113.5 # web"* ]]
[[ "$output" == *"allow tcp 15432 from 198.51.100.20 # db"* ]]
[[ "$output" == *"allow tcp 25432 from 198.51.100.20 # db"* ]]
[[ "$output" == *"allow udp 5353 from 198.51.100.20 # web"* ]]
[[ "$output" == *"# 192.0.2.99 -> 172.30.0.9:9999/tcp: published port not found"* ]]
[[ "$output" != *"allow tcp 80 "* ]]
[[ "$output" != *"allow tcp 5432 "* ]]
# One line per suggestion, even for three packets.
[ "$(grep -c 'allow tcp 8080 from 203.0.113.5' <<<"$output")" -eq 1 ]
}
@test "suggested allow lines are valid configuration lines" {
run --separate-stderr fence report
{ printf 'admin 192.0.2.10\n'; grep '^allow ' <<<"$output"; } >"$BATS_TEST_TMPDIR/proposed.conf"
chmod 0644 "$BATS_TEST_TMPDIR/proposed.conf"
run "$FENCE" -c "$BATS_TEST_TMPDIR/proposed.conf" check
[ "$status" -eq 0 ]
}
@test "report never asks for the environment or arguments of containers" {
fence report >/dev/null 2>&1
grep -q '^docker inspect --format' "$STUB_LOG"
! grep -qiE 'Env|Args|Cmd|Entrypoint|Config' <(grep '^docker inspect' "$STUB_LOG")
}
@test "report --since is validated and passed to journalctl" {
fence report --since "2026-12-01 08:00" >/dev/null 2>&1
grep -qF -- '--since 2026-12-01 08:00' "$STUB_LOG"
run fence report --since '$(id)'
[ "$status" -eq 1 ]
}
@test "report with no logged packet" {
STUB_JOURNAL=/dev/null run fence report
[ "$status" -eq 0 ]
[[ "$output" == *": 0 logged packets"* ]]
}
@test "report without docker: IPs are still shown" {
run --separate-stderr fence --set bin_docker=/nonexistent/docker report
[ "$status" -eq 0 ]
[[ "$stderr" == *"docker unreachable"* ]]
[[ "$output" =~ 3\ +203\.0\.113\.5\ +172\.18\.0\.2:80/tcp\ +\? ]]
}
@test "ufw-plan: safe order, nothing runs" {
export STUB_UFW_ADDED="$FIXTURES/ufw-added"
run --separate-stderr fence ufw-plan
[ "$status" -eq 0 ]
local admin allow c2h del
admin="$(grep -n '^# 1\. ' <<<"$output" | cut -d: -f1)"
allow="$(grep -n '^# 2\. ' <<<"$output" | cut -d: -f1)"
c2h="$(grep -n '^# 3\. ' <<<"$output" | cut -d: -f1)"
del="$(grep -n '^# 4\. ' <<<"$output" | cut -d: -f1)"
[ "$admin" -lt "$allow" ] && [ "$allow" -lt "$c2h" ] && [ "$c2h" -lt "$del" ]
# Only reads were made.
! grep -qE '^ufw (allow|delete|deny|route|--force)' "$STUB_LOG"
grep -q '^ufw show added' "$STUB_LOG"
}
@test "ufw-plan: content of the four sections" {
export STUB_UFW_ADDED="$FIXTURES/ufw-added"
run --separate-stderr fence ufw-plan
# 1. Admin: active commands.
grep -qx 'ufw allow from 192.0.2.10' <<<"$output"
grep -qx 'ufw allow in on wg0 from 192.0.2.11' <<<"$output"
# 2. allow: commented out.
grep -qx '# ufw allow proto tcp from any to any port 443' <<<"$output"
grep -qx '# ufw allow proto tcp from 198.51.100.20 to any port 5432' <<<"$output"
grep -qx '# ufw allow proto tcp from 203.0.113.0/24 to any port 9000:9010' <<<"$output"
# 3. container_to_host fallback: one IPv4 network per line.
grep -qx '# ufw allow proto tcp from 172.17.0.0/16 to any port 8080' <<<"$output"
grep -qx '# ufw allow proto tcp from 172.18.0.0/16 to any port 8080' <<<"$output"
! grep -q 'fd00::' <<<"$output"
# 4. Too broad rules, spelled out with --force.
grep -qx '# ufw --force delete allow 22/tcp' <<<"$output"
grep -qx '# ufw --force delete limit 2222/tcp' <<<"$output"
grep -qx '# ufw --force delete route allow proto tcp from any to any port 80' <<<"$output"
! grep -q 'delete allow from 192.0.2.10' <<<"$output"
! grep -q 'delete allow proto tcp from 198.51.100.0/24' <<<"$output"
[[ "$output" == *"Never remove the SSH access rule"* ]]
[[ "$output" == *"network_mode: host"* ]]
}
@test "ufw-plan without root nor docker" {
run --separate-stderr fence --set bin_docker=/nonexistent/docker ufw-plan
[ "$status" -eq 0 ]
[[ "$output" == *"ufw show added"*"root"* ]]
[[ "$output" == *"no Docker subnet found"* ]]
}
@test "status after apply: block, pending, jump, counters, log" {
fence apply
run fence status
[ "$status" -eq 0 ]
[[ "$output" == *"block installed in $RULES (mode observe)"* ]]
[[ "$output" == *"rollback pending (docker-fence-rollback)"* ]]
[[ "$output" == *"jump DOCKER-USER -> docker-fence: present"* ]]
grep -q '^iptables -L docker-fence -n -v -x' "$STUB_LOG"
[[ "$output" == *"SRC=198.51.100.20 DST=172.20.0.3"* ]]
[[ "$output" != *"[UFW BLOCK]"* ]]
}
@test "status without block" {
run fence status
[ "$status" -eq 0 ]
[[ "$output" == *"no block installed"* ]]
[[ "$output" == *"jump DOCKER-USER -> docker-fence: missing"* ]]
}
@test "status recognizes enforce mode" {
fence --mode enforce install
run fence status
[[ "$output" == *"(mode enforce)"* ]]
}
+262
View File
@@ -0,0 +1,262 @@
#!/usr/bin/env bats
# rules: table of native UFW rules and docker-fence rules. Read only.
load helpers
bats_require_minimum_version 1.5.0
setup() {
setup_env
cp "$REPO/examples/fence.conf" "$CONF"
chmod 0644 "$CONF"
export STUB_UFW_STATUS="$FIXTURES/ufw-status-verbose"
}
# Line of the table that contains every given text, in order.
# row TEXT...
row() {
local pattern="" t
for t in "$@"; do
pattern+="*$t"
done
local line
for line in "${lines[@]}"; do
# shellcheck disable=SC2053
[[ "$line" == $pattern* ]] && { echo "$line"; return 0; }
done
echo "no row matching: $*" >&2
return 1
}
# Number of the first line that contains a text.
line_of() {
local i
for i in "${!lines[@]}"; do
[[ "${lines[i]}" == *"$1"* ]] && { echo "$i"; return 0; }
done
return 1
}
@test "rules lists the native UFW rules" {
run --separate-stderr fence rules
[ "$status" -eq 0 ]
[[ "${lines[0]}" =~ ^ORIGIN\ +TRAFFIC\ +ACTION\ +TO\ +FROM\ +STATE\ +NOTE$ ]]
[[ "${lines[1]}" =~ ^-+\ +-+ ]]
row ufw "host input" ALLOW "22/tcp" any active ssh
row ufw "host input" ALLOW "any on wg0" "192.0.2.10" active
row ufw "host input" DENY "5432/tcp" "198.51.100.0/24" active
row ufw "host input" LIMIT "2222/tcp" any active
row ufw "host input" ALLOW "22/tcp" any active "IPv6, ssh"
row ufw routed ALLOW "80/tcp" any active
row ufw "host output" ALLOW 53 any active
}
@test "rules ends the UFW rules with the default policies" {
run --separate-stderr fence rules
row ufw "host input" DENY any any active "default policy"
row ufw "host output" ALLOW any any active "default policy"
row ufw routed DENY any any active "default policy"
[ "$(line_of "53 ")" -lt "$(line_of "default policy")" ]
}
@test "rules before apply: docker-fence rules are not loaded" {
run --separate-stderr fence rules
[ "$status" -eq 0 ]
row fence "published ports" ALLOW any any "not loaded" "replies to established connections"
row fence "published ports" ALLOW "all published ports" "192.0.2.10/32" "not loaded" admin
row fence "container -> host" ALLOW "8080/tcp" "iface br-+" "not loaded" container_to_host
}
@test "rules after apply (observe): every docker-fence rule is loaded, in block order" {
fence apply
run --separate-stderr fence rules
[ "$status" -eq 0 ]
row fence "published ports" ALLOW any any loaded "replies to established connections"
row fence "published ports" ALLOW any "iface br-+" loaded "trusted containers"
row fence "published ports" ALLOW any "iface docker0" loaded "trusted containers"
row fence "published ports" ALLOW "all published ports" "192.0.2.10/32" loaded admin
row fence "published ports" ALLOW "all published ports" "192.0.2.11/32 on wg0" loaded admin
row fence "published ports" ALLOW "443/tcp" any loaded allow
row fence "published ports" ALLOW "5432/tcp" "198.51.100.20/32" loaded allow
row fence "published ports" ALLOW "9000-9010/tcp" "203.0.113.0/24" loaded allow
row fence "published ports" LOG "other published ports" any loaded "observe mode: logged, not blocked"
row fence "container -> host" ALLOW "8080/tcp" "iface br-+" loaded container_to_host
# Order: UFW first, then docker-fence in evaluation order.
[ "$(line_of "default policy")" -lt "$(line_of "replies to established")" ]
[ "$(line_of "192.0.2.10/32")" -lt "$(line_of "443/tcp")" ]
[ "$(line_of "443/tcp")" -lt "$(line_of "other published ports")" ]
[ "$(line_of "other published ports")" -lt "$(line_of "container -> host")" ]
[[ "$output" != *"not loaded"* ]]
}
@test "rules after apply (enforce): the last rule drops" {
fence --mode enforce apply
run --separate-stderr fence --mode enforce rules
row fence "published ports" DROP "other published ports" any loaded "enforce mode: logged and dropped"
}
@test "rules after uninstall: docker-fence rules are no longer loaded" {
fence apply
fence confirm
fence uninstall
run --separate-stderr fence rules
row fence "published ports" ALLOW "443/tcp" any "not loaded" allow
row fence "container -> host" ALLOW "8080/tcp" "iface br-+" "not loaded"
}
@test "rules: state unknown when the firewall cannot be read" {
fence apply
STUB_IPT_CHECK_RC=4 run --separate-stderr fence rules
[ "$status" -eq 0 ]
row fence "published ports" ALLOW "443/tcp" any "unknown (root?)" allow
row fence "container -> host" ALLOW "8080/tcp" "iface br-+" "unknown (root?)"
}
@test "rules: columns are aligned, also with accents (French)" {
fence apply
local lang offsets
for lang in en fr; do
run --separate-stderr fence --lang "$lang" rules
[ "$status" -eq 0 ]
# Start of each column in the header, in characters.
local header="${lines[0]}" col
local -a starts=()
local LC_ALL=C.UTF-8
local i prev=" "
for (( i = 0; i < ${#header}; i++ )); do
[[ "$prev" == " " && "${header:i:1}" != " " ]] && starts+=("$i")
prev="${header:i:1}"
done
[ "${#starts[@]}" -eq 7 ]
local line
for line in "${lines[@]:1}"; do
for col in "${starts[@]:1}"; do
# An empty last cell ends the line early (no trailing blanks).
(( ${#line} > col )) || continue
# Every column starts after two blanks at least.
[[ "${line:col-2:2}" == " " && "${line:col:1}" != " " ]] \
|| { echo "misaligned ($lang): $line"; return 1; }
done
done
done
[[ "$output" == "ORIGINE"*"TRAFIC"*"ÉTAT"* ]]
}
@test "rules without UFW access or with UFW inactive still lists docker-fence" {
run --separate-stderr fence --set bin_ufw=/nonexistent/ufw rules
[ "$status" -eq 0 ]
[[ "$stderr" == *"command not found: /nonexistent/ufw"* ]]
row fence "published ports" ALLOW "443/tcp"
STUB_UFW_INACTIVE=1 run --separate-stderr fence rules
[ "$status" -eq 0 ]
[[ "$stderr" == *"UFW is inactive: no UFW rule applies"* ]]
[[ "$output" != *"host input"* ]]
row fence "published ports" ALLOW "443/tcp"
}
@test "rules changes nothing" {
fence apply
fence confirm
local before kernel
before="$(sum_of "$RULES")"
kernel="$(sum_of "$KERNEL")"
: >"$STUB_LOG"
run fence rules
[ "$status" -eq 0 ]
[ "$(sum_of "$RULES")" = "$before" ]
[ "$(sum_of "$KERNEL")" = "$kernel" ]
! grep -qE '^(ufw (reload|allow|delete|route)|iptables -[ADFXIN]|systemd-run|systemctl)' "$STUB_LOG"
}
@test "rules: chain loaded but DOCKER-USER jump missing means not loaded" {
fence apply
# Something removed the jump (for example a manual iptables -D).
"$REPO/tests/stubs/iptables" -D DOCKER-USER -j docker-fence
grep -qF -- '-A docker-fence -s 192.0.2.10/32 -j RETURN' "$KERNEL"
run --separate-stderr fence rules
row fence "published ports" ALLOW "443/tcp" any "not loaded" allow
row fence "published ports" ALLOW "all published ports" "192.0.2.10/32" "not loaded" admin
# container_to_host rules do not depend on the jump.
row fence "container -> host" ALLOW "8080/tcp" "iface br-+" loaded
}
@test "rules in French translates the UFW interface marker too" {
run --separate-stderr fence --lang fr rules
[ "$status" -eq 0 ]
row ufw "entrant hôte" ALLOW "tout via wg0" "192.0.2.10" actif
[[ "$output" != *" on wg0"* ]]
}
@test "rules: no colors when standard output is not a terminal" {
fence apply
run --separate-stderr fence rules
[ "$status" -eq 0 ]
[[ "$output" != *$'\e['* ]]
run --separate-stderr fence --color never rules
[[ "$output" != *$'\e['* ]]
}
@test "rules --color always: bold header, colored actions and states" {
fence apply
run --separate-stderr fence --color always rules
[ "$status" -eq 0 ]
[[ "${lines[0]}" == $'\e[1mORIGIN\e[0m'* ]]
[[ "${lines[1]}" == $'\e[2m-'* ]]
[[ "$output" == *$'\e[1;32mALLOW\e[0m'* ]]
[[ "$output" == *$'\e[1;31mDENY\e[0m'* ]]
[[ "$output" == *$'\e[1;33mLIMIT\e[0m'* ]]
[[ "$output" == *$'\e[1;33mLOG\e[0m'* ]]
[[ "$output" == *$'\e[32mloaded\e[0m'* ]]
[[ "$output" == *$'\e[32mactive\e[0m'* ]]
[[ "$output" == *$'\e[36mufw\e[0m'* ]]
[[ "$output" == *$'\e[35mfence\e[0m'* ]]
fence confirm
fence --mode enforce apply
run --separate-stderr fence --mode enforce --color=always rules
[[ "$output" == *$'\e[1;31mDROP\e[0m'* ]]
}
@test "rules --color always: states not loaded and unknown" {
run --separate-stderr fence --color always rules
[[ "$output" == *$'\e[31mnot loaded\e[0m'* ]]
STUB_IPT_CHECK_RC=4 run --separate-stderr fence --color always rules
[[ "$output" == *$'\e[33munknown (root?)\e[0m'* ]]
run --separate-stderr fence --lang fr --color always rules
[[ "$output" == *$'\e[31mnon chargée\e[0m'* ]]
}
@test "rules --color always: same table as without colors once codes are removed" {
fence apply
local plain colored
for lang in en fr; do
plain="$(fence --lang "$lang" --color never rules 2>/dev/null)"
colored="$(fence --lang "$lang" --color always rules 2>/dev/null | sed -E $'s/\e\\[[0-9;]*m//g')"
[ "$plain" = "$colored" ]
done
}
@test "rules --color: invalid value and other commands refused" {
run fence --color sometimes rules
[ "$status" -eq 1 ]
run fence --color always check
[ "$status" -eq 1 ]
}
@test "rules as root before apply: missing chain (iptables -C exits 2) means not loaded, not unknown" {
run "$REPO/tests/stubs/iptables" -C DOCKER-USER -j docker-fence
[ "$status" -eq 2 ]
run --separate-stderr fence rules
[ "$status" -eq 0 ]
[[ "$output" != *"unknown"* ]]
row fence "published ports" ALLOW any any "not loaded" "replies to established connections"
row fence "container -> host" ALLOW "8080/tcp" "iface br-+" "not loaded"
}
@test "localized system (LANGUAGE=fr): UFW is still read as active" {
LANGUAGE=fr_FR:fr run --separate-stderr fence rules
[ "$status" -eq 0 ]
[[ "$stderr" != *"inactive"* ]]
row ufw "host input" ALLOW "22/tcp" any active ssh
LANGUAGE=fr_FR:fr run --separate-stderr fence apply
[ "$status" -eq 0 ]
}
+19
View File
@@ -0,0 +1,19 @@
#!/usr/bin/env bash
# Fake docker: answers read from files in $STUB_DOCKER_DIR.
set -euo pipefail
printf 'docker %s\n' "$*" >>"$STUB_LOG"
d="${STUB_DOCKER_DIR:-/nonexistent}"
case "$1 ${2:-}" in
"version --format") echo "29.0.0" ;;
"ps -q") cat "$d/ps" 2>/dev/null || true ;;
"inspect --format") cat "$d/inspect" 2>/dev/null || true ;;
"network ls")
case "$*" in
*driver=macvlan*) cat "$d/macvlan" 2>/dev/null || true ;;
*driver=ipvlan*) cat "$d/ipvlan" 2>/dev/null || true ;;
*driver=bridge*) cat "$d/bridges" 2>/dev/null || true ;;
esac
;;
"network inspect") grep -- "^${*: -1} " "$d/subnets" 2>/dev/null | cut -d' ' -f2- || true ;;
*) exit 1 ;;
esac
+37
View File
@@ -0,0 +1,37 @@
#!/usr/bin/env bash
# Fake iptables: kernel state is a list of "-A CHAIN ..." lines.
set -euo pipefail
printf 'iptables %s\n' "$*" >>"$STUB_LOG"
kernel="$STUB_STATE/kernel"
touch "$kernel"
op="${1:-}"
shift || true
case "$op" in
--version) echo "iptables v1.8.10 (nf_tables)" ;;
# Like the real one, -C compares arguments, not quoting, and exits 2 when
# the target chain does not exist. STUB_IPT_CHECK_RC simulates an error on
# every read (4: permission denied).
-C)
[[ -z "${STUB_IPT_CHECK_RC:-}" ]] || exit "$STUB_IPT_CHECK_RC"
args=("$@")
for (( i = 0; i < ${#args[@]} - 1; i++ )); do
if [[ "${args[i]}" == -j && "${args[i+1]}" =~ [a-z] ]] \
&& ! grep -q -- "^-A ${args[i+1]} " "$kernel"; then
echo "iptables: Couldn't load target \`${args[i+1]}':No such file or directory" >&2
exit 2
fi
done
tr -d '"' <"$kernel" | grep -qxF -- "-A $*"
;;
-D)
line="-A $*"
n="$(grep -nxF -- "$line" "$kernel" | head -n 1 | cut -d: -f1)"
[[ -n "$n" ]] || exit 1
sed -i "${n}d" "$kernel"
;;
-F) grep -v -- "^-A $1 " "$kernel" >"$kernel.tmp" || true; mv "$kernel.tmp" "$kernel" ;;
-X) printf '%s\n' "$1" >>"$STUB_STATE/deleted-chains" ;;
-S) [[ -z "${STUB_IPT_CHECK_RC:-}" ]] || exit "$STUB_IPT_CHECK_RC"; echo "-N $1"; grep -- "^-A $1 " "$kernel" || true ;;
-L) echo "Chain $1"; grep -- "^-A $1 " "$kernel" || true ;;
*) exit 1 ;;
esac
+4
View File
@@ -0,0 +1,4 @@
#!/usr/bin/env bash
set -euo pipefail
printf 'journalctl %s\n' "$*" >>"$STUB_LOG"
cat "${STUB_JOURNAL:-/dev/null}"
+7
View File
@@ -0,0 +1,7 @@
#!/usr/bin/env bash
set -euo pipefail
printf 'systemctl %s\n' "$*" >>"$STUB_LOG"
if [[ "${1:-}" == stop ]]; then
[[ -f "$STUB_STATE/timer_cmd" ]] || exit 5
rm -f "$STUB_STATE/timer_cmd"
fi
+11
View File
@@ -0,0 +1,11 @@
#!/usr/bin/env bash
# Fake systemd-run: records the timer command without running it.
set -euo pipefail
printf 'systemd-run %s\n' "$*" >>"$STUB_LOG"
[[ "${STUB_SYSTEMD_RUN_RC:-0}" == 0 ]] || exit "$STUB_SYSTEMD_RUN_RC"
# systemd-run options come before the scheduled command.
while (( $# > 0 )) && [[ "$1" == --* ]]; do
[[ "$1" == --setenv=* ]] && printf '%s\n' "${1#--setenv=}" >"$STUB_STATE/timer_env"
shift
done
printf '%s\n' "$@" >"$STUB_STATE/timer_cmd"
+47
View File
@@ -0,0 +1,47 @@
#!/usr/bin/env bash
# Fake ufw: simulates loading after.rules with iptables-restore
# --noflush (only declared chains are flushed, then filled).
set -euo pipefail
printf 'ufw %s\n' "$*" >>"$STUB_LOG"
kernel="$STUB_STATE/kernel"
touch "$kernel"
case "${1:-}" in
status)
# Like the real one (Python gettext), LANGUAGE wins over LC_ALL.
if [[ "${LANGUAGE:-}" == fr* ]]; then
echo "État : actif"
exit 0
fi
if [[ "${STUB_UFW_INACTIVE:-0}" == 1 ]]; then
echo "Status: inactive"
elif [[ "${2:-}" == verbose && -n "${STUB_UFW_STATUS:-}" ]]; then
cat "$STUB_UFW_STATUS"
else
echo "Status: active"
fi
;;
version) echo "ufw 0.36.2" ;;
reload)
[[ "${STUB_UFW_RELOAD_RC:-0}" == 0 ]] || exit "$STUB_UFW_RELOAD_RC"
[[ "${STUB_UFW_RELOAD_NOOP:-0}" == 1 ]] && exit 0
rules="$FENCE_ROOT/etc/ufw/after.rules"
declared="$(grep -E '^:[^ ]+ ' "$rules" | sed 's/^:\([^ ]*\) .*/\1/' | sort -u || true)"
tmp="$(mktemp)"
while IFS= read -r line; do
chain="$(printf '%s' "$line" | awk '{print $2}')"
if ! grep -qxF -- "$chain" <<<"$declared"; then
printf '%s\n' "$line"
fi
done <"$kernel" >"$tmp"
grep -E '^-A ' "$rules" >>"$tmp" || true
if [[ "${STUB_UFW_DROP_C2H:-0}" == 1 ]]; then
grep -v -- '-j ACCEPT$' "$tmp" >"$tmp.2" || true
mv "$tmp.2" "$tmp"
fi
mv "$tmp" "$kernel"
;;
show)
[[ -n "${STUB_UFW_ADDED:-}" ]] && cat "$STUB_UFW_ADDED"
;;
*) exit 1 ;;
esac