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

18 KiB

docker-fence

Filters by source the traffic to ports published by Docker, with UFW.

A port published by Docker (-p 8080:80) is not protected by ufw allow / ufw deny: the packet is redirected (DNAT) to the container and goes through the FORWARD chain, never through INPUT, where UFW rules live. docker-fence manages a delimited block in /etc/ufw/after.rules, hooked to the DOCKER-USER chain that Docker provides for the administrator. The block lets through:

  • replies to established connections;
  • traffic coming from containers (interfaces br-+ and docker0, or the ones you list);
  • admin addresses (admin);
  • exceptions per published port and source (allow).

All other traffic redirected by Docker is logged (observe mode) or dropped (enforce mode). A new container that publishes a port is therefore covered right away, without touching the configuration.

The tool is generic: it holds no site-specific data. The configuration file of a host lives elsewhere (for example in the deployment repository).

Requirements

  • bash 5 or later, iptables (nf_tables or legacy backend), an active ufw, systemd. No other dependency: no Python, no yq.
  • Docker with its iptables firewall (the default).

Out of scope: IPv6, the native nftables firewall backend of Docker ("firewall-backend": "nftables"), macvlan and ipvlan networks, Docker Swarm, containers in network_mode: host (their ports are UFW's job). check reports these cases: it stops for the nftables backend and for "iptables": false, and warns for IPv6, macvlan and ipvlan.

Installation

One command, no git needed (curl and root only):

curl -fsSL https://git.djeex.fr/Djeex/docker-fence/raw/branch/main/install.sh | sudo bash

A tagged version, once tags exist: ... | sudo bash -s -- --tag 1.0.0. From a clone, run sudo ./install.sh instead.

Installing writes no firewall rule. It only copies the tool to /usr/local/lib/docker-fence and links /usr/local/bin/docker-fence; nothing changes on the host until docker-fence apply. The installer then prints the next steps:

sudo docker-fence init        # 1. writes /etc/docker-fence/fence.conf (commented template)
sudo editor /etc/docker-fence/fence.conf   # 2. admin addresses, allow, container_to_host
sudo docker-fence check       # 3. validates it and prints the block, changes nothing
sudo docker-fence apply       # 4. loads it (mode observe: logs only), rolls back unless confirmed
sudo docker-fence confirm     # 5. keeps it
sudo docker-fence rules       # table of every rule, UFW and docker-fence

The configuration lives in /etc/docker-fence/fence.conf. After each change: check, then apply and confirm (see Recommended rollout).

install.sh is plain bash (no make) and must run as root. It prints every file it installs or removes:

  • run from a pipe or alone, it downloads each file of the tool from /raw/ on the repository (the archive download is blocked by the anti-bot proxy of the server), and refuses anything that is not the expected bash script;
  • --prefix /opt/docker-fence installs under another prefix (absolute path); --branch NAME, --tag NAME or --source-url URL choose what to download;
  • running it again updates the installed files and removes libraries that are no longer part of the tool;
  • --uninstall (with the same --prefix, if any) removes the installed files, and keeps a bin/docker-fence it did not install. It changes no firewall rule: run sudo docker-fence uninstall first to remove the block from UFW.

install.sh never creates, changes or removes /etc/docker-fence/fence.conf.

Configuration

File /etc/docker-fence/fence.conf, looked up in this order: --config, $FENCE_CONFIG, ./fence.conf, /etc/docker-fence/fence.conf. For a setting, the priority is: command line option, then environment variable (FENCE_LANG only), then file, then default. docker-fence show-config prints the effective configuration and the origin of each value.

One directive per line: directive value..., separated by blanks. # starts a comment, at the start of a line or after a blank. Parsing is strict: nothing is evaluated by the shell (no source, no eval), and only the characters A-Z a-z 0-9 _ . / : + - are accepted outside comments. An unknown directive or an invalid value is an error, always reported with its line number. check reports all of them at once.

The file is refused if it is writable by group or others, or if it is not owned by root (or by the user running the tool, when that is not root).

Rules (repeatable directives, in file order)

Directive Role
admin <ipv4[/mask]> [iface <name>] source allowed to every published port; at least one is required
allow <tcp|udp> <port or a-b> from <ipv4[/mask]|any> [iface <name>] exception: port published on the host and allowed source
container_to_host <tcp|udp> <port or a-b> [from_iface <name>] a container reaches this host port (INPUT rule; default br-+)
trusted_iface <name> trusted container interface; without any: br-+ and docker0

An address without a mask means /32. An address with host bits set outside the mask (192.0.2.1/24) is refused, and so is 0.0.0.0/0: use from any. A rule identical to an earlier one is an error. An interface name is at most 15 characters long; a trailing + is a wildcard (br-+).

Settings (optional; the last value wins)

Directive Default Role
mode observe observe logs, enforce blocks
rollback_seconds 120 delay before the automatic rollback (30 to 86400)
lang en message language (en or fr)
log_rate_observe, log_burst_observe 120/min, 200 log rate in observe mode
log_rate_enforce, log_burst_enforce 20/min, 40 log rate in enforce mode
log_prefix_observe, log_prefix_drop DOCKER-WOULD-DROP, DOCKER-FENCE-DROP log prefixes (at most 28 characters; the tool adds the trailing space)
log_level 6 kernel log level
log_file /var/log/docker-fence.log log of the actions of the tool
chain docker-fence chain name (at most 23 characters); the reject chain is <name>-deny
block_marker DOCKER-FENCE marker of the # BEGIN and # END lines
unit_name docker-fence-rollback systemd unit of the rollback
ufw_after_rules /etc/ufw/after.rules file to edit
docker_daemon_json /etc/docker/daemon.json Docker daemon configuration (checks)
backup_dir, backup_keep /var/backups/docker-fence, 20 backups and rotation
report_since 24 hours ago default report period (journalctl --since syntax)
bin_iptables, bin_ufw, bin_docker, bin_journalctl, bin_systemd_run, bin_systemctl command names binaries to use

Example (documentation addresses, RFC 5737)

# /etc/docker-fence/fence.conf
mode observe
rollback_seconds 120

admin 192.0.2.10                      # admin workstation
admin 192.0.2.11 iface wg0

trusted_iface br-+
trusted_iface docker0

allow tcp 443 from any                # public service
allow tcp 5432 from 198.51.100.20     # machine to machine flow
allow tcp 9000-9010 from 203.0.113.0/24

container_to_host tcp 8080            # container -> host call

The block generated for this example is in tests/golden/example-observe.rules (observe mode) and tests/golden/example-enforce.rules (enforce mode).

Commands

Command Role
check validates the configuration and the environment, prints the generated block; changes nothing
status installed block (and its mode), pending rollback, DOCKER-USER -> docker-fence jump, counters, last 20 log lines
install [--replace-legacy] [--force] backs up after.rules and writes the block, without reloading UFW
apply [--replace-legacy] [--force] install, then reload with automatic rollback
confirm cancels the automatic rollback
rollback [--auto] [file] restores the latest backup (or the given one) and reloads UFW
uninstall [--restore-legacy] removes the managed block, reloads UFW if active (--restore-legacy puts the original ufw-docker block back)
report [--since date] observation report
ufw-plan prints, without running them, the ufw commands for host rules
rules [--color auto|always|never] prints one table with every rule: native UFW rules (from ufw status verbose, default policies last) and docker-fence rules, with their state in the kernel; changes nothing
init [--output file] [--force] writes a commented template (--output -: standard output); overwrites nothing without --force
show-config effective configuration, with the origin of each value; the output is itself a valid file

General options: -c, --config file, --mode observe|enforce, --lang en|fr, --set directive=value (any setting), -q, --quiet, -v, --verbose (prints the commands that run), -h, --help, --version. Messages go to standard error; standard output only carries data (block, report, plan, configuration): docker-fence check > block.rules gives the block alone.

Exit codes: 0 success; 1 configuration or usage error; 2 unsupported environment; 3 original ufw-docker block present (without --replace-legacy, or unknown version without --force); 4 apply failed (rollback already done).

How apply works

  1. Validates the configuration and the environment. Checks that UFW is active and that no rollback is already pending.
  2. Backs up after.rules into backup_dir (mode 0600), then writes the new file atomically (temporary file in the same directory, same mode and owner, then mv).
  3. Schedules the rollback: systemd-run --unit=docker-fence-rollback --on-active=<rollback_seconds>s docker-fence rollback --auto --config <file>.
  4. ufw reload, then checks that DOCKER-USER jumps to the chain, that the chain is not empty and that the container_to_host rules are loaded. On failure: immediate rollback, exit code 4.
  5. Prints: "Confirm with docker-fence confirm within N seconds, or the change rolls back automatically."

Why rollback also cleans the kernel: UFW reloads after.rules with iptables-restore --noflush, which only flushes the chains declared in the file. Once the block is gone, DOCKER-USER would keep its jump to docker-fence. rollback and uninstall therefore remove that jump and delete the chains of the tool when the restored file no longer holds the block.

Original ufw-docker block

install and apply detect the # BEGIN UFW AND DOCKER ... # END UFW AND DOCKER block. Without --replace-legacy, they stop (exit code 3) and show the block. With the option, the block is saved to backup_dir/legacy-block.rules, removed, and the managed block is appended at the end of the file. A block that differs from the known version is reported with a diff, and replaced only when --force is given too. uninstall --restore-legacy puts it back.

After this replacement, the ufw route rules created for ufw-docker are no longer used: ufw-plan lists them among the rules to review.

  1. Configuration in mode observe, then sudo docker-fence apply and sudo docker-fence confirm. The block logs what would be blocked, without blocking anything.
  2. Wait 24 to 48 h, then run sudo docker-fence report and complete the allow and container_to_host lines.
  3. Switch to mode enforce, then sudo docker-fence apply. Check the services from another session, then sudo docker-fence confirm.
  4. Watch sudo docker-fence status, and the [UFW BLOCK] lines with IN=br- in the kernel log (forgotten container -> host flows).

Run the first trial on a test host, with a rescue admin session open. An unconfirmed apply rolls back on its own after rollback_seconds.

Observation report (report)

The LOG target in FORWARD sees the packet after DNAT: DST is the IP of the container and DPT its internal port. The report:

  1. finds the container from the IP (docker inspect: name, addresses and ports only, never the environment nor the arguments);
  2. aggregates source -> container:port/proto, most frequent first;
  3. suggests allow lines with the port published on the host, the only port usable in an exception.

Host rules (ufw-plan)

ufw-plan prints, without running anything, in a safe order:

  1. the ufw allow from <ip> commands for admin addresses;
  2. commented out, the allow exceptions in UFW form, only useful for a port served by the host or by a host-network container;
  3. commented out, a fallback for container_to_host, one command per Docker network, in case these rules are not loaded in ufw-after-input;
  4. last, commented out, the removal of old too broad rules, read from ufw show added, spelled out with ufw --force delete.

Never remove the SSH access rule before testing every admin address from another session.

Rules table (rules)

sudo docker-fence rules prints every rule in one aligned table, in evaluation order: first the UFW rules of the host, then the docker-fence rules for published ports and container -> host calls.

ORIGIN  TRAFFIC            ACTION  TO                     FROM                  STATE   NOTE
------  -----------------  ------  ---------------------  --------------------  ------  ----------------------------------
ufw     host input         ALLOW   22/tcp                 any                   active  ssh
ufw     host input         ALLOW   any on wg0             192.0.2.10            active
ufw     routed             ALLOW   80/tcp                 any                   active
ufw     host input         DENY    any                    any                   active  default policy
ufw     host output        ALLOW   any                    any                   active  default policy
ufw     routed             DENY    any                    any                   active  default policy
fence   published ports    ALLOW   any                    any                   loaded  replies to established connections
fence   published ports    ALLOW   any                    iface br-+            loaded  trusted containers
fence   published ports    ALLOW   all published ports    192.0.2.10/32         loaded  admin
fence   published ports    ALLOW   all published ports    192.0.2.11/32 on wg0  loaded  admin
fence   published ports    ALLOW   443/tcp                any                   loaded  allow
fence   published ports    ALLOW   5432/tcp               198.51.100.20/32      loaded  allow
fence   published ports    LOG     other published ports  any                   loaded  observe mode: logged, not blocked
fence   container -> host  ALLOW   8080/tcp               iface br-+            loaded  container_to_host

The state of a docker-fence rule is checked with iptables -C on the exact rule of the block: loaded, not loaded (not applied yet, or the DOCKER-USER jump is missing), or unknown (run it as root). UFW rules are listed only when UFW is active and readable.

In a terminal the table is colored: bold header, ALLOW in green, DENY, REJECT and DROP in red, LIMIT and LOG in yellow, loaded/active in green, not loaded in red, unknown in yellow. Colors are off when the output is not a terminal (pipe, file) or when NO_COLOR is set; --color always|never|auto forces the choice.

Known pitfalls

  • Published ports do not go through INPUT: ufw status says nothing about their filtering. Use docker-fence status.
  • LOG in FORWARD shows the internal port: never write an exception with it, use the published port (the report finds it).
  • ss on the host does not see the connections of containers; use /proc/net/nf_conntrack.
  • A filter on an address range (172.16.0.0/12) misses Docker networks created elsewhere: the tool filters on interfaces. A network created with com.docker.network.bridge.name has another interface name: add it with trusted_iface.
  • Two containers of the same network that reach each other through the host IP go through INPUT (UFW), not FORWARD: that is what container_to_host is for.
  • ufw delete in numbered mode asks for confirmation: use --force with the rule spelled out.

To check on the target host

  1. Content of any original block in after.rules.
  2. Versions of Docker and iptables (nf_tables or legacy) and firewall backend of Docker (check prints them).
  3. IPv6 enabled in Docker.
  4. macvlan or ipvlan networks, or containers receiving public traffic on a dedicated IP.
  5. UFW active, default policy, rules overlapping those of the tool.
  6. Host-network services that must stay reachable (they are UFW's job).
  7. Loading of the container_to_host rules into ufw-after-input by a real ufw reload (the syntax is tested, the real load order remains to be confirmed; apply rolls back if it fails).

Tests

make is only used for tests and checks:

make ci                 # shellcheck, bats tests, bash 4 refusal; Docker alone is enough
make test               # bats tests locally (needs bats-core and iptables)
make lint               # shellcheck locally

Tests run without a real firewall: FENCE_ROOT (reserved for tests) prefixes /etc and /var, and fake ufw, iptables, systemd-run, systemctl, docker and journalctl come first in PATH. The fake ufw reload reproduces the --noflush behaviour. Generated blocks are compared with golden files (tests/golden/) and fed to a real iptables-restore --test in the network namespace of the test container (NET_ADMIN), without loading anything on the host.

Language

Messages, configuration template and help exist in English (default) and French: lang fr in the file, --lang fr or FENCE_LANG=fr. Every message is in lib/messages.sh.