From e91870a2aee7dc6a87c8ac5e05892d0dd94529d8 Mon Sep 17 00:00:00 2001 From: Luis Date: Fri, 20 Nov 2026 10:47:36 -0500 Subject: [PATCH 1/2] feat: optional DNS-driven egress allowlist (separate compose file) Add egress-guard, an opt-in Linux-only sidecar that permits outbound connections from the ARTEX network only to the LLM endpoint, declared scope, and recon/package sources, while auto-allowing discovered subdomains of in-scope domains so asset discovery keeps working. Modes: monitor (default, log only) / enforce / off. Shipped as docker-compose.egress.yml; the main compose file is untouched, so it is fully opt-in. It needs NET_ADMIN and edits the host firewall (DOCKER-USER chain), documented as Linux-only in egress-guard/README.md. --- docker-compose.egress.yml | 42 ++++++++++ egress-guard/Dockerfile | 8 ++ egress-guard/README.md | 42 ++++++++++ egress-guard/entrypoint.sh | 115 +++++++++++++++++++++++++++ egress-guard/lists/base-domains.txt | 45 +++++++++++ egress-guard/lists/scope-cidrs.txt | 3 + egress-guard/lists/scope-domains.txt | 4 + egress-guard/logs/.gitignore | 2 + egress-guard/report.sh | 41 ++++++++++ 9 files changed, 302 insertions(+) create mode 100644 docker-compose.egress.yml create mode 100644 egress-guard/Dockerfile create mode 100644 egress-guard/README.md create mode 100755 egress-guard/entrypoint.sh create mode 100644 egress-guard/lists/base-domains.txt create mode 100644 egress-guard/lists/scope-cidrs.txt create mode 100644 egress-guard/lists/scope-domains.txt create mode 100644 egress-guard/logs/.gitignore create mode 100755 egress-guard/report.sh diff --git a/docker-compose.egress.yml b/docker-compose.egress.yml new file mode 100644 index 00000000..060c84b2 --- /dev/null +++ b/docker-compose.egress.yml @@ -0,0 +1,42 @@ +# Optional, Linux-only egress allowlist for the ARTEX network. See egress-guard/README.md. +# Enable by adding this overlay to every compose command: +# docker compose -f docker-compose.yml -f docker-compose.egress.yml up -d +# It needs NET_ADMIN and edits the host firewall (DOCKER-USER chain). Without +# this overlay the main compose file is unchanged, so this is fully opt-in. +services: + artex: + # Route DNS through egress-guard's dnsmasq (on the network gateway), which + # feeds the allowlist. depends_on merges with the base file's postgres entry. + dns: + - 172.31.250.1 + depends_on: + egress-guard: + condition: service_started + + egress-guard: + build: + context: ./egress-guard + image: artex-egress-guard:local + network_mode: host + cap_add: + - NET_ADMIN + - NET_RAW + environment: + # monitor (default, log only) | enforce (block) | off (DNS only) + EGRESS_MODE: ${EGRESS_MODE:-monitor} + ARTEX_SUBNET: 172.31.250.0/24 + ARTEX_GATEWAY: 172.31.250.1 + UPSTREAM_DNS: ${EGRESS_UPSTREAM_DNS:-} + volumes: + - ./egress-guard/lists:/etc/egress-guard:ro + - ./egress-guard/logs:/var/log/egress + restart: unless-stopped + +# Give the ARTEX network a fixed subnet/gateway so dnsmasq and the firewall +# rules have a known address to bind and match. +networks: + default: + ipam: + config: + - subnet: 172.31.250.0/24 + gateway: 172.31.250.1 diff --git a/egress-guard/Dockerfile b/egress-guard/Dockerfile new file mode 100644 index 00000000..b6616558 --- /dev/null +++ b/egress-guard/Dockerfile @@ -0,0 +1,8 @@ +# egress-guard: DNS-driven egress allowlist for the ARTEX network. +# Runs in the host network namespace (network_mode: host) with NET_ADMIN to manage +# an ipset + iptables rules in the DOCKER-USER chain. See README.md. +FROM alpine:3.20@sha256:d9e853e87e55526f6b2917df91a2115c36dd7c696a35be12163d44e6e2a4b6bc +RUN apk add --no-cache dnsmasq iptables ipset bash tini +COPY entrypoint.sh /usr/local/bin/egress-guard +RUN chmod +x /usr/local/bin/egress-guard +ENTRYPOINT ["/sbin/tini", "--", "/usr/local/bin/egress-guard"] diff --git a/egress-guard/README.md b/egress-guard/README.md new file mode 100644 index 00000000..b469289b --- /dev/null +++ b/egress-guard/README.md @@ -0,0 +1,42 @@ +# egress-guard + +DNS-driven egress allowlist for the ARTEX container. It blocks data from leaving +to arbitrary hosts (e.g. a malicious PoC sending the keys to an attacker) without +breaking asset discovery: any subdomain of an in-scope domain is allowed +automatically the moment it resolves. + +Opt-in and Linux-only. It is a separate compose file and needs `NET_ADMIN`; it +edits the host firewall, so read this before enabling it. + +## How it works +1. ARTEX uses `172.31.250.1` (this service's dnsmasq) as its DNS. DNS queries to + any other server (dnsx, bbot, `dig @8.8.8.8`) are redirected here. +2. Names matching a suffix in `lists/base-domains.txt` or `lists/scope-domains.txt` + have their resolved IPs added to the `artex_allow` ipset (they expire 6 h after + the last query). +3. In the `DOCKER-USER` chain, new outbound connections from the ARTEX network are + allowed only if the destination is in `artex_allow` or in `lists/scope-cidrs.txt`. + Everything else is logged (`ARTEX-EGRESS-*` in the kernel log) and, in + `enforce`, rejected. + +## Modes (`EGRESS_MODE` in `.env`) +| Mode | Effect | +|---|---| +| `monitor` (default) | only logs what would be blocked | +| `enforce` | blocks | +| `off` | no rules; DNS only | + +## Operation +- New engagement: edit `lists/scope-domains.txt` and `lists/scope-cidrs.txt`, then + `docker compose -f docker-compose.yml -f docker-compose.egress.yml restart egress-guard`. +- Calibrate: `sudo egress-guard/report.sh` (or pass `"48 hours ago"`). Lists flagged + connections and resolved names outside the allowlist. +- Turn blocking on: set `EGRESS_MODE=enforce` in `.env` and bring the service up again. +- Stopping the service removes the rules. If dnsmasq dies on its own, the rules stay + (fail-closed). + +## Known gaps +- Exfiltration through an allowed destination (a GitHub gist, OAST servers, an + in-scope host the attacker controls). +- Data hidden in DNS queries (slow; visible in `logs/dnsmasq.log`). +- CDN-shared IPs: allowing one name allows the IP for other sites on the same IP. diff --git a/egress-guard/entrypoint.sh b/egress-guard/entrypoint.sh new file mode 100755 index 00000000..3c3afdbe --- /dev/null +++ b/egress-guard/entrypoint.sh @@ -0,0 +1,115 @@ +#!/usr/bin/env bash +# egress-guard entrypoint. +# EGRESS_MODE monitor (default: log only) | enforce (log + reject) | off (no rules, DNS only) +# ARTEX_SUBNET the ARTEX docker network (must match docker-compose.yml) +# ARTEX_GATEWAY bridge gateway IP; dnsmasq listens here +# UPSTREAM_DNS comma-separated upstream resolvers; empty = host /etc/resolv.conf +# IPSET_TIMEOUT seconds a resolved IP stays allowed after its last lookup (default 21600) +set -euo pipefail + +MODE="${EGRESS_MODE:-monitor}" +SUBNET="${ARTEX_SUBNET:?ARTEX_SUBNET required}" +GW="${ARTEX_GATEWAY:?ARTEX_GATEWAY required}" +TIMEOUT="${IPSET_TIMEOUT:-21600}" +LISTS=/etc/egress-guard +LOGDIR=/var/log/egress +CONF=/run/egress-guard/dnsmasq.conf +IPT=iptables +command -v iptables-nft >/dev/null 2>&1 && IPT=iptables-nft +[ -n "${IPTABLES_BIN:-}" ] && IPT="$IPTABLES_BIN" + +log() { echo "[egress-guard] $*"; } + +case "$MODE" in monitor|enforce|off) ;; *) log "invalid EGRESS_MODE=$MODE"; exit 1;; esac + +# Read a list file: strip comments/blank lines, lowercase, drop leading dots/wildcards. +read_list() { [ -f "$1" ] || return 0; sed -e 's/#.*//' -e 's/[[:space:]]//g' "$1" | tr 'A-Z' 'a-z' | sed -e 's/^\*\.//' -e 's/^\.//' | grep -v '^$' || true; } + +cleanup_rules() { + # filter table: detach and delete our chain + while $IPT -C DOCKER-USER -s "$SUBNET" ! -d "$SUBNET" -j ARTEX-EGRESS 2>/dev/null; do + $IPT -D DOCKER-USER -s "$SUBNET" ! -d "$SUBNET" -j ARTEX-EGRESS + done + $IPT -F ARTEX-EGRESS 2>/dev/null || true + $IPT -X ARTEX-EGRESS 2>/dev/null || true + # nat table: DNS redirect + while $IPT -t nat -C PREROUTING -s "$SUBNET" -j ARTEX-DNS 2>/dev/null; do + $IPT -t nat -D PREROUTING -s "$SUBNET" -j ARTEX-DNS + done + $IPT -t nat -F ARTEX-DNS 2>/dev/null || true + $IPT -t nat -X ARTEX-DNS 2>/dev/null || true +} + +apply_rules() { + ipset create artex_allow hash:ip timeout "$TIMEOUT" -exist + ipset create artex_scope hash:net -exist + ipset flush artex_scope + local n=0 + while read -r cidr; do ipset add artex_scope "$cidr" -exist && n=$((n+1)); done < <(read_list "$LISTS/scope-cidrs.txt") + log "scope CIDRs loaded: $n" + + [ "$MODE" = off ] && { log "mode off: no firewall rules"; return; } + + # DOCKER-USER exists whenever dockerd runs; create it only for standalone tests. + if ! $IPT -L DOCKER-USER -n >/dev/null 2>&1; then + $IPT -N DOCKER-USER; $IPT -I FORWARD -j DOCKER-USER + fi + + # Redirect every DNS query leaving the ARTEX network to dnsmasq, so tools with + # hard-coded resolvers (dnsx, bbot, dig @8.8.8.8) still populate the allowlist. + $IPT -t nat -N ARTEX-DNS + $IPT -t nat -A ARTEX-DNS -d "$GW" -j RETURN + $IPT -t nat -A ARTEX-DNS -p udp --dport 53 -j DNAT --to-destination "$GW:53" + $IPT -t nat -A ARTEX-DNS -p tcp --dport 53 -j DNAT --to-destination "$GW:53" + $IPT -t nat -I PREROUTING 1 -s "$SUBNET" -j ARTEX-DNS + + $IPT -N ARTEX-EGRESS + $IPT -A ARTEX-EGRESS -m conntrack --ctstate ESTABLISHED,RELATED -j RETURN + $IPT -A ARTEX-EGRESS -m set --match-set artex_allow dst -j RETURN + $IPT -A ARTEX-EGRESS -m set --match-set artex_scope dst -j RETURN + $IPT -A ARTEX-EGRESS -m limit --limit 30/min --limit-burst 60 -j LOG --log-prefix "ARTEX-EGRESS-$MODE " --log-level 4 + if [ "$MODE" = enforce ]; then + $IPT -A ARTEX-EGRESS -p tcp -j REJECT --reject-with tcp-reset + $IPT -A ARTEX-EGRESS -j REJECT --reject-with icmp-port-unreachable + else + $IPT -A ARTEX-EGRESS -j RETURN + fi + $IPT -I DOCKER-USER 1 -s "$SUBNET" ! -d "$SUBNET" -j ARTEX-EGRESS + log "firewall rules applied (mode=$MODE, subnet=$SUBNET)" +} + +write_dnsmasq_conf() { + mkdir -p "$(dirname "$CONF")" "$LOGDIR" + { + echo "listen-address=$GW" + echo "bind-dynamic" + echo "except-interface=lo" + echo "no-hosts" + echo "cache-size=10000" + echo "log-queries=extra" + echo "log-facility=$LOGDIR/dnsmasq.log" + if [ -n "${UPSTREAM_DNS:-}" ]; then + echo "no-resolv" + IFS=',' read -ra ups <<< "$UPSTREAM_DNS" + for u in "${ups[@]}"; do echo "server=$u"; done + fi + } > "$CONF" + local n=0 + while read -r d; do echo "ipset=/$d/artex_allow" >> "$CONF"; n=$((n+1)); done < <(read_list "$LISTS/base-domains.txt"; read_list "$LISTS/scope-domains.txt") + log "allowed domain suffixes: $n" +} + +on_term() { log "stopping"; [ -n "${DNSMASQ_PID:-}" ] && kill "$DNSMASQ_PID" 2>/dev/null || true; cleanup_rules; exit 0; } +trap on_term TERM INT + +cleanup_rules +apply_rules +write_dnsmasq_conf +dnsmasq --test -C "$CONF" +dnsmasq -k -C "$CONF" & +DNSMASQ_PID=$! +log "dnsmasq listening on $GW:53 (pid $DNSMASQ_PID)" +wait "$DNSMASQ_PID" +# dnsmasq died unexpectedly: leave rules in place (fail closed) and let docker restart us. +log "dnsmasq exited; rules left in place" +exit 1 diff --git a/egress-guard/lists/base-domains.txt b/egress-guard/lists/base-domains.txt new file mode 100644 index 00000000..ac91398b --- /dev/null +++ b/egress-guard/lists/base-domains.txt @@ -0,0 +1,45 @@ +# Domain suffixes always allowed for the ARTEX container (a suffix covers all subdomains). +# Resolved IPs are added to the allowlist automatically. Reload: docker compose restart egress-guard + +# --- LLM providers (keep only the one you use) --- +api.deepseek.com +api.anthropic.com +api.openai.com + +# --- Passive recon sources seen in past runs --- +crt.sh +rapiddns.io +api.certspotter.com +api.hackertarget.com +api.threatminer.org +web.archive.org +archive.org +otx.alienvault.com +urlscan.io +services.nvd.nist.gov +api.osv.dev + +# --- Public code / advisories (downloads are still gated by the [hardening] approval rules) --- +github.com +api.github.com +raw.githubusercontent.com +objects.githubusercontent.com +release-assets.githubusercontent.com +codeload.github.com +gist.githubusercontent.com + +# --- Package registries (installs are gated by the approval rules) --- +pypi.org +files.pythonhosted.org +registry.npmjs.org +proxy.golang.org +deb.debian.org + +# --- Nuclei / Interactsh out-of-band testing (OAST). Remove if you do not use OAST checks: +# these servers accept arbitrary data, so they are also a possible exfiltration channel. +oast.pro +oast.live +oast.site +oast.online +oast.fun +oast.me diff --git a/egress-guard/lists/scope-cidrs.txt b/egress-guard/lists/scope-cidrs.txt new file mode 100644 index 00000000..c4628dec --- /dev/null +++ b/egress-guard/lists/scope-cidrs.txt @@ -0,0 +1,3 @@ +# Engagement scope: target IPs / CIDRs reached directly (no DNS). One per line. +# docker compose restart egress-guard +# 203.0.113.0/24 diff --git a/egress-guard/lists/scope-domains.txt b/egress-guard/lists/scope-domains.txt new file mode 100644 index 00000000..fc8257f9 --- /dev/null +++ b/egress-guard/lists/scope-domains.txt @@ -0,0 +1,4 @@ +# Engagement scope: target domain suffixes (one per line). Every subdomain is allowed, +# so newly discovered assets keep working. Edit per engagement, then: +# docker compose restart egress-guard +# example.com diff --git a/egress-guard/logs/.gitignore b/egress-guard/logs/.gitignore new file mode 100644 index 00000000..d6b7ef32 --- /dev/null +++ b/egress-guard/logs/.gitignore @@ -0,0 +1,2 @@ +* +!.gitignore diff --git a/egress-guard/report.sh b/egress-guard/report.sh new file mode 100755 index 00000000..0234dc9f --- /dev/null +++ b/egress-guard/report.sh @@ -0,0 +1,41 @@ +#!/usr/bin/env bash +# Calibration report for egress-guard. +# 1) destinations the firewall flagged (would be / were blocked), mapped back to DNS names +# 2) names the ARTEX container resolved that are NOT covered by the allowlist +# Usage: egress-guard/report.sh [since] (default since: "24 hours ago"; journalctl syntax) +# Reading the kernel log needs the adm/systemd-journal group or sudo. +set -euo pipefail +cd "$(dirname "$0")" +SINCE="${1:-24 hours ago}" +LOG=logs/dnsmasq.log + +suffixes() { sed -e 's/#.*//' -e 's/[[:space:]]//g' lists/base-domains.txt lists/scope-domains.txt | tr 'A-Z' 'a-z' | sed -e 's/^\*\.//' -e 's/^\.//' | grep -v '^$' || true; } + +declare -A ip2name +if [ -f "$LOG" ]; then + while read -r name ip; do ip2name[$ip]="$name"; done < <(awk '/ reply / && / is [0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$/ {for(i=1;i<=NF;i++) if($i=="reply"){print $(i+1), $NF}}' "$LOG") +fi + +echo "=== 1) Conexões sinalizadas pelo firewall (desde: $SINCE) ===" +if journalctl -k --since "$SINCE" -q --no-pager -g 'ARTEX-EGRESS-' >/dev/null 2>&1; then + journalctl -k --since "$SINCE" -q --no-pager -g 'ARTEX-EGRESS-' \ + | grep -oE 'ARTEX-EGRESS-[a-z]+ .*DST=[0-9.]+.*PROTO=[A-Z]+( .*DPT=[0-9]+)?' \ + | sed -E 's/^ARTEX-EGRESS-([a-z]+) .*DST=([0-9.]+).*PROTO=([A-Z]+)( .*DPT=([0-9]+))?.*/\1 \2 \3 \5/' \ + | sort | uniq -c | sort -rn \ + | while read -r cnt mode ip proto port; do printf '%6s %-8s %-16s %-5s %-6s %s\n' "$cnt" "$mode" "$ip" "$proto" "${port:--}" "${ip2name[$ip]:-(sem DNS: IP direto)}"; done +else + echo "(sem acesso ao log do kernel: rode com sudo ou adicione o usuário ao grupo adm)" +fi + +echo +echo "=== 2) Nomes resolvidos fora da allowlist (candidatos a liberar ou suspeitos) ===" +if [ -f "$LOG" ]; then + mapfile -t sfx < <(suffixes) + awk '/ query\[(A|AAAA)\] / {for(i=1;i<=NF;i++) if($i ~ /^query\[/){print tolower($(i+1))}}' "$LOG" | sort | uniq -c | sort -rn \ + | while read -r cnt name; do + ok=0; for s in "${sfx[@]}"; do [[ "$name" == "$s" || "$name" == *".$s" ]] && { ok=1; break; }; done + [ $ok -eq 0 ] && printf '%6s %s\n' "$cnt" "$name" + done +else + echo "(sem $LOG ainda)" +fi From 91a6a86332d8e30780e756864181c5a94bb3d8bc Mon Sep 17 00:00:00 2001 From: Luis Date: Sat, 21 Nov 2026 12:28:46 -0500 Subject: [PATCH 2/2] fix(egress): address review on the allowlist enforcement - Flush artex_allow at startup: a host removed from the lists no longer stays reachable until the ipset timeout. - Fail-closed setup (enforce): install a blanket subnet-egress deny before the allowlist is built and remove it only after setup completes; an ERR trap (set -E) leaves it in place and exits non-zero on failure, with a FATAL log. - IPv6: document the gap, warn when unfiltered, and add an ip6tables deny when ARTEX_SUBNET6 is set. - Gateway/host-proxy bypass: document it (container->gateway goes through host INPUT, not DOCKER-USER) and add an opt-in EGRESS_FILTER_GATEWAY INPUT filter. - README: make clear the allowlist only acts in enforce; monitor is observe-only. - Add egress-guard/selftest.sh and confirm in a real container (own netns): flush, rules, enforce REJECT, DNS redirect, and fail-closed all pass (10/10). --- egress-guard/README.md | 24 +++++++-- egress-guard/entrypoint.sh | 99 +++++++++++++++++++++++++++++++++----- egress-guard/selftest.sh | 53 ++++++++++++++++++++ 3 files changed, 162 insertions(+), 14 deletions(-) create mode 100755 egress-guard/selftest.sh diff --git a/egress-guard/README.md b/egress-guard/README.md index b469289b..accfee08 100644 --- a/egress-guard/README.md +++ b/egress-guard/README.md @@ -22,9 +22,16 @@ edits the host firewall, so read this before enabling it. ## Modes (`EGRESS_MODE` in `.env`) | Mode | Effect | |---|---| -| `monitor` (default) | only logs what would be blocked | -| `enforce` | blocks | -| `off` | no rules; DNS only | +| `monitor` (default) | **observe only** — logs what would be blocked, blocks nothing | +| `enforce` | the allowlist actually blocks | +| `off` | no firewall rules; DNS redirect only | + +**The allowlist only restricts egress in `enforce`.** The default `monitor` is a +dry run for calibration — it protects nothing. Set `EGRESS_MODE=enforce` (and +bring the service up again) for the guard to have any effect. In `enforce`, +setup is **fail-closed**: a blanket deny is installed before the allowlist is +built, so if setup fails the ARTEX container loses outbound connectivity (except +DNS) until the guard restarts cleanly. ## Operation - New engagement: edit `lists/scope-domains.txt` and `lists/scope-cidrs.txt`, then @@ -36,6 +43,17 @@ edits the host firewall, so read this before enabling it. (fail-closed). ## Known gaps +- **IPv6 is not filtered.** The allowlist is IPv4-only (ipset `hash:ip`/`hash:net`). + Keep the ARTEX network IPv4-only (do not set `enable_ipv6` on it) — then the + container has no IPv6 address and the gap is latent. If you do enable IPv6, set + `ARTEX_SUBNET6` so `enforce` installs an `ip6tables` deny for it; the guard logs + a warning when IPv6 is left unfiltered. +- **Traffic to the host/gateway bypasses the filter.** Container→gateway traffic + goes through the host `INPUT` chain, not `DOCKER-USER` (`FORWARD`), so a proxy + bound on the gateway IP is reachable. Don't run a forward proxy on the gateway, + or set `EGRESS_FILTER_GATEWAY=1` to have `enforce` add an `INPUT` rule that drops + everything from the subnet to the gateway except DNS (off by default — it edits + the host `INPUT` chain). - Exfiltration through an allowed destination (a GitHub gist, OAST servers, an in-scope host the attacker controls). - Data hidden in DNS queries (slow; visible in `logs/dnsmasq.log`). diff --git a/egress-guard/entrypoint.sh b/egress-guard/entrypoint.sh index 3c3afdbe..7e41579e 100755 --- a/egress-guard/entrypoint.sh +++ b/egress-guard/entrypoint.sh @@ -1,15 +1,27 @@ #!/usr/bin/env bash # egress-guard entrypoint. -# EGRESS_MODE monitor (default: log only) | enforce (log + reject) | off (no rules, DNS only) -# ARTEX_SUBNET the ARTEX docker network (must match docker-compose.yml) -# ARTEX_GATEWAY bridge gateway IP; dnsmasq listens here -# UPSTREAM_DNS comma-separated upstream resolvers; empty = host /etc/resolv.conf -# IPSET_TIMEOUT seconds a resolved IP stays allowed after its last lookup (default 21600) -set -euo pipefail +# EGRESS_MODE monitor (default: log only) | enforce (log + reject) | off (DNS only) +# ARTEX_SUBNET the ARTEX docker network (must match docker-compose.yml) +# ARTEX_GATEWAY bridge gateway IP; dnsmasq listens here +# ARTEX_SUBNET6 optional IPv6 subnet; when set, enforce also drops its egress +# EGRESS_FILTER_GATEWAY 1 = in enforce, also drop non-DNS traffic from the subnet to the +# host/gateway (closes the host-proxy bypass). Off by default because +# it edits the host INPUT chain. See README "Known gaps". +# UPSTREAM_DNS comma-separated upstream resolvers; empty = host /etc/resolv.conf +# IPSET_TIMEOUT seconds a resolved IP stays allowed after its last lookup (default 21600) +# +# Fail-closed (enforce): a blanket deny for the subnet's egress is installed BEFORE the allowlist +# is built and removed only after setup completes. If any setup step fails, the ERR trap leaves +# that deny in place and exits non-zero, so Docker restarts the guard while traffic stays blocked. +# The operator then sees the ARTEX container lose outbound connectivity (except DNS) until the +# guard comes up cleanly. In monitor/off mode a setup failure is non-fatal by design (log only). +set -Eeuo pipefail # -E so the ERR trap fires for failures inside functions (apply_rules) MODE="${EGRESS_MODE:-monitor}" SUBNET="${ARTEX_SUBNET:?ARTEX_SUBNET required}" GW="${ARTEX_GATEWAY:?ARTEX_GATEWAY required}" +SUBNET6="${ARTEX_SUBNET6:-}" +FILTER_GW="${EGRESS_FILTER_GATEWAY:-0}" TIMEOUT="${IPSET_TIMEOUT:-21600}" LISTS=/etc/egress-guard LOGDIR=/var/log/egress @@ -17,6 +29,11 @@ CONF=/run/egress-guard/dnsmasq.conf IPT=iptables command -v iptables-nft >/dev/null 2>&1 && IPT=iptables-nft [ -n "${IPTABLES_BIN:-}" ] && IPT="$IPTABLES_BIN" +IP6T=ip6tables +command -v ip6tables-nft >/dev/null 2>&1 && IP6T=ip6tables-nft +[ -n "${IP6TABLES_BIN:-}" ] && IP6T="$IP6TABLES_BIN" + +BOOT_CMT="artex-egress-bootstrap-deny" log() { echo "[egress-guard] $*"; } @@ -25,13 +42,54 @@ case "$MODE" in monitor|enforce|off) ;; *) log "invalid EGRESS_MODE=$MODE"; exit # Read a list file: strip comments/blank lines, lowercase, drop leading dots/wildcards. read_list() { [ -f "$1" ] || return 0; sed -e 's/#.*//' -e 's/[[:space:]]//g' "$1" | tr 'A-Z' 'a-z' | sed -e 's/^\*\.//' -e 's/^\.//' | grep -v '^$' || true; } +ensure_docker_user() { + # DOCKER-USER exists whenever dockerd runs; create it only for standalone tests. + $IPT -L DOCKER-USER -n >/dev/null 2>&1 || { $IPT -N DOCKER-USER; $IPT -I FORWARD -j DOCKER-USER; } + if [ -n "$SUBNET6" ] && command -v "$IP6T" >/dev/null 2>&1; then + $IP6T -L DOCKER-USER -n >/dev/null 2>&1 || { $IP6T -N DOCKER-USER; $IP6T -I FORWARD -j DOCKER-USER; } + fi +} + +bootstrap_deny() { + # enforce only: block the subnet's egress up-front so a partial setup fails closed. + [ "$MODE" = enforce ] || return 0 + $IPT -I DOCKER-USER 1 -s "$SUBNET" ! -d "$SUBNET" -m comment --comment "$BOOT_CMT" -j DROP + if [ -n "$SUBNET6" ] && command -v "$IP6T" >/dev/null 2>&1; then + $IP6T -I DOCKER-USER 1 -s "$SUBNET6" -m comment --comment "$BOOT_CMT" -j DROP 2>/dev/null \ + || log "WARN: ip6tables unavailable; IPv6 egress NOT filtered" + elif command -v "$IP6T" >/dev/null 2>&1; then + log "WARN: ARTEX_SUBNET6 unset; IPv6 egress is NOT filtered (keep the ARTEX network IPv4-only)" + fi +} + +remove_bootstrap_deny() { + [ "$MODE" = enforce ] || return 0 + while $IPT -C DOCKER-USER -s "$SUBNET" ! -d "$SUBNET" -m comment --comment "$BOOT_CMT" -j DROP 2>/dev/null; do + $IPT -D DOCKER-USER -s "$SUBNET" ! -d "$SUBNET" -m comment --comment "$BOOT_CMT" -j DROP + done + [ -n "$SUBNET6" ] && command -v "$IP6T" >/dev/null 2>&1 && \ + while $IP6T -C DOCKER-USER -s "$SUBNET6" -m comment --comment "$BOOT_CMT" -j DROP 2>/dev/null; do + $IP6T -D DOCKER-USER -s "$SUBNET6" -m comment --comment "$BOOT_CMT" -j DROP + done + return 0 +} + cleanup_rules() { + # Leave any bootstrap deny untouched here: cleanup runs on stop (on_term), where removing it + # is correct, and on startup before setup, where re-adding happens in bootstrap_deny. + remove_bootstrap_deny # filter table: detach and delete our chain while $IPT -C DOCKER-USER -s "$SUBNET" ! -d "$SUBNET" -j ARTEX-EGRESS 2>/dev/null; do $IPT -D DOCKER-USER -s "$SUBNET" ! -d "$SUBNET" -j ARTEX-EGRESS done $IPT -F ARTEX-EGRESS 2>/dev/null || true $IPT -X ARTEX-EGRESS 2>/dev/null || true + # optional host INPUT filter for the gateway + while $IPT -C INPUT -s "$SUBNET" -d "$GW" -j ARTEX-EGRESS-HOST 2>/dev/null; do + $IPT -D INPUT -s "$SUBNET" -d "$GW" -j ARTEX-EGRESS-HOST + done + $IPT -F ARTEX-EGRESS-HOST 2>/dev/null || true + $IPT -X ARTEX-EGRESS-HOST 2>/dev/null || true # nat table: DNS redirect while $IPT -t nat -C PREROUTING -s "$SUBNET" -j ARTEX-DNS 2>/dev/null; do $IPT -t nat -D PREROUTING -s "$SUBNET" -j ARTEX-DNS @@ -42,6 +100,8 @@ cleanup_rules() { apply_rules() { ipset create artex_allow hash:ip timeout "$TIMEOUT" -exist + ipset flush artex_allow # drop IPs allowed in a previous run: a host removed from the + # lists must not stay reachable until the ipset timeout expires. ipset create artex_scope hash:net -exist ipset flush artex_scope local n=0 @@ -50,11 +110,6 @@ apply_rules() { [ "$MODE" = off ] && { log "mode off: no firewall rules"; return; } - # DOCKER-USER exists whenever dockerd runs; create it only for standalone tests. - if ! $IPT -L DOCKER-USER -n >/dev/null 2>&1; then - $IPT -N DOCKER-USER; $IPT -I FORWARD -j DOCKER-USER - fi - # Redirect every DNS query leaving the ARTEX network to dnsmasq, so tools with # hard-coded resolvers (dnsx, bbot, dig @8.8.8.8) still populate the allowlist. $IPT -t nat -N ARTEX-DNS @@ -75,6 +130,19 @@ apply_rules() { $IPT -A ARTEX-EGRESS -j RETURN fi $IPT -I DOCKER-USER 1 -s "$SUBNET" ! -d "$SUBNET" -j ARTEX-EGRESS + + # Optional: close the host-proxy bypass. Traffic from the container to the host/gateway goes + # through the host INPUT chain, not DOCKER-USER (FORWARD), so a proxy bound on the gateway is + # otherwise reachable. Off by default because it edits the host INPUT chain. + if [ "$MODE" = enforce ] && [ "$FILTER_GW" = 1 ]; then + $IPT -N ARTEX-EGRESS-HOST 2>/dev/null || $IPT -F ARTEX-EGRESS-HOST + $IPT -A ARTEX-EGRESS-HOST -p udp --dport 53 -j RETURN + $IPT -A ARTEX-EGRESS-HOST -p tcp --dport 53 -j RETURN + $IPT -A ARTEX-EGRESS-HOST -j REJECT --reject-with icmp-port-unreachable + $IPT -I INPUT 1 -s "$SUBNET" -d "$GW" -j ARTEX-EGRESS-HOST + log "gateway filter on: only DNS to $GW allowed from the subnet" + fi + log "firewall rules applied (mode=$MODE, subnet=$SUBNET)" } @@ -102,10 +170,19 @@ write_dnsmasq_conf() { on_term() { log "stopping"; [ -n "${DNSMASQ_PID:-}" ] && kill "$DNSMASQ_PID" 2>/dev/null || true; cleanup_rules; exit 0; } trap on_term TERM INT +# Setup is fail-closed in enforce: install the blanket deny first, and keep it if anything below +# throws. The ERR trap fires under `set -e` before the shell exits. +on_setup_err() { local rc=$?; log "FATAL: setup failed (rc=$rc); fail-closed deny left in place, exiting for restart"; exit "$rc"; } +trap on_setup_err ERR + cleanup_rules +ensure_docker_user +bootstrap_deny apply_rules +remove_bootstrap_deny write_dnsmasq_conf dnsmasq --test -C "$CONF" +trap - ERR # setup done; a later dnsmasq exit is handled below, not as a fatal setup error. dnsmasq -k -C "$CONF" & DNSMASQ_PID=$! log "dnsmasq listening on $GW:53 (pid $DNSMASQ_PID)" diff --git a/egress-guard/selftest.sh b/egress-guard/selftest.sh new file mode 100755 index 00000000..e766ce76 --- /dev/null +++ b/egress-guard/selftest.sh @@ -0,0 +1,53 @@ +#!/usr/bin/env bash +# egress-guard self-test. Builds nothing; run it inside the image, in the container's +# OWN network namespace (NOT network_mode host), so it exercises the real ipset + iptables +# without touching the host firewall: +# +# docker build -t artex-egress-guard:local ./egress-guard +# docker run --rm --cap-add NET_ADMIN --cap-add NET_RAW \ +# -v "$PWD/egress-guard/selftest.sh:/selftest.sh:ro" \ +# --entrypoint bash artex-egress-guard:local /selftest.sh +# +# Checks: startup flush of a stale allow IP (#1), rules applied, enforce REJECT (#5), +# DNS redirect, and fail-closed on a setup error (#2: deny left in place, FATAL, exit 1). +set -u +IPT=iptables; command -v iptables-nft >/dev/null 2>&1 && IPT=iptables-nft +pass=0; fail=0 +ok(){ echo "PASS: $1"; pass=$((pass+1)); } +no(){ echo "FAIL: $1"; fail=$((fail+1)); } + +# dummy iface so dnsmasq can bind the gateway IP +ip link add dummy0 type dummy 2>/dev/null +ip addr add 10.123.0.1/24 dev dummy0 2>/dev/null +ip link set dummy0 up 2>/dev/null + +echo "######## TEST 1: happy path (enforce) ########" +# seed a STALE allowed IP to prove flush at startup +ipset create artex_allow hash:ip timeout 21600 -exist +ipset add artex_allow 203.0.113.99 -exist +export EGRESS_MODE=enforce ARTEX_SUBNET=10.123.0.0/24 ARTEX_GATEWAY=10.123.0.1 UPSTREAM_DNS=1.1.1.1 +/usr/local/bin/egress-guard >/tmp/g.log 2>&1 & +GP=$! +sleep 3 +if ipset list artex_allow 2>/dev/null | grep -q 203.0.113.99; then no "stale IP flushed at startup"; else ok "stale IP flushed at startup (#1)"; fi +$IPT -S DOCKER-USER 2>/dev/null | grep -q 'ARTEX-EGRESS' && ok "DOCKER-USER jumps to ARTEX-EGRESS" || no "DOCKER-USER jump present" +$IPT -S DOCKER-USER 2>/dev/null | grep -q 'bootstrap-deny' && no "bootstrap-deny removed after clean setup" || ok "bootstrap-deny removed after clean setup (#2)" +$IPT -S ARTEX-EGRESS 2>/dev/null | grep -q 'match-set artex_allow dst' && ok "allow ipset rule present" || no "allow ipset rule present" +$IPT -S ARTEX-EGRESS 2>/dev/null | grep -qi 'REJECT' && ok "enforce REJECT present (#5)" || no "enforce REJECT present" +$IPT -t nat -S ARTEX-DNS 2>/dev/null | grep -q 'DNAT' && ok "DNS redirect (DNAT) present" || no "DNS redirect present" +kill -TERM $GP 2>/dev/null; sleep 1 +$IPT -S ARTEX-EGRESS 2>/dev/null | grep -q . && no "chain removed on stop" || ok "chain removed on stop (cleanup)" + +echo "######## TEST 2: fail-closed (setup error after bootstrap) ########" +# invalid IPSET_TIMEOUT makes apply_rules fail right after bootstrap_deny is installed +export IPSET_TIMEOUT=notanumber +/usr/local/bin/egress-guard >/tmp/g2.log 2>&1 +rc=$? +[ "$rc" -ne 0 ] && ok "setup failure is fatal (exit $rc, #2 fail-closed)" || no "setup failure fatal" +$IPT -S DOCKER-USER 2>/dev/null | grep -q 'bootstrap-deny.*DROP' && ok "fail-closed DROP left in place (#2)" || no "fail-closed DROP present" +grep -q 'FATAL: setup failed' /tmp/g2.log && ok "operator sees FATAL message (#2 documented)" || no "FATAL message logged" +# cleanup +unset IPSET_TIMEOUT +$IPT -F DOCKER-USER 2>/dev/null; $IPT -X ARTEX-EGRESS 2>/dev/null +echo "=== guard log test1 ==="; cat /tmp/g.log; echo "=== guard log test2 ==="; cat /tmp/g2.log +echo "######## RESULT: pass=$pass fail=$fail ########"