#!/bin/bash # # Purpose : Keep other machines on the network from reaching the ports Docker # containers publish. Run by system/firewall.sh, after ufw-docker # installs its rules, and by a migration. # # ufw-docker's rules let any private address (10.x, 172.16-31.x, 192.168.x) # reach a published port, and on a café's or hotel's Wi-Fi that's everyone # there. This lets only Docker's own bridges past instead, so containers still # reach the network and each other, and this machine still reaches their ports. # Your own changes to the rules are left alone. # # To let other machines reach one container's port: # sudo ufw-docker allow set -o pipefail AFTER_RULES="${UFW_AFTER_RULES:-/etc/ufw/after.rules}" # ufw-docker's lines that let private addresses through export PRIVATE='^-A DOCKER-USER -j RETURN -s (10\.0\.0\.0/8|172\.16\.0\.0/12|192\.168\.0\.0/16)$' sudo grep -qE "$PRIVATE" "$AFTER_RULES" 2> /dev/null || exit 0 echo "Keeping other machines on the network from reaching Docker containers' ports..." # Docker's bridges in place of the first of those lines, unless they're there # already; the private ranges' lines go tmp="$(mktemp)" || exit 1 if ! sudo cat "$AFTER_RULES" | awk ' $0 == "-A DOCKER-USER -j RETURN -i docker0" { bridges = 1 } { lines[NR] = $0 } END { for (i = 1; i <= NR; i++) { if (lines[i] ~ ENVIRON["PRIVATE"]) { if (!bridges) { print "-A DOCKER-USER -j RETURN -i docker0" print "-A DOCKER-USER -j RETURN -i br-+" bridges = 1 } continue } print lines[i] } }' > "$tmp"; then rm -f "$tmp" exit 1 fi # Never put back a file that lost ufw's own rules if ! grep -q '^COMMIT$' "$tmp" || ! grep -q '^# BEGIN UFW AND DOCKER' "$tmp"; then echo "Couldn't change $AFTER_RULES; it's as it was." rm -f "$tmp" exit 1 fi # Keep the file's owner and mode (ufw's own are root and 640) if ! mode="$(sudo stat -c %a "$AFTER_RULES")" \ || ! sudo install -m "$mode" -o root -g root "$tmp" "$AFTER_RULES"; then rm -f "$tmp" exit 1 fi rm -f "$tmp" # ufw loads after.rules when it starts if systemctl is-active -q ufw.service; then sudo systemctl restart ufw.service fi