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