Skip to content

Instantly share code, notes, and snippets.

@felixSchl
Created March 4, 2019 05:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save felixSchl/6f5c0e0be79a6730d97e9b4fc8fd80bb to your computer and use it in GitHub Desktop.
Save felixSchl/6f5c0e0be79a6730d97e9b4fc8fd80bb to your computer and use it in GitHub Desktop.
#!/bin/bash
#
# Disable public access to all exported ports on docker containers.
# Restrict access only to well-known cloudflare servers.
set -eo pipefail
function update_rules {
local target_file=$1
awk -v "rules=$2" '
BEGIN { skip=0; }
/^# BEGIN GENERATED CLOUDFLARE RULES/ { skip=1; }
/^# END GENERATED CLOUDFLARE RULES/ { skip=0; next; }
skip == 0 { print $0; }
END {
print "# BEGIN GENERATED CLOUDFLARE RULES";
print rules;
print "# END GENERATED CLOUDFLARE RULES";
}
' "$target_file" > "${target_file}.tmp" && mv "${target_file}.tmp" "$target_file"
}
# ip4 rules
rules=$(for ip in $(curl -s https://www.cloudflare.com/ips-v4); do echo "-A DOCKER-USER -i eth0 ! -s $ip -j DROP"; done)
update_rules /etc/ufw/after.rules "$rules"
# ip6 rules
rules=$(for ip in $(curl -s https://www.cloudflare.com/ips-v6); do echo "-A DOCKER-USER -i eth0 ! -s $ip -j DROP"; done)
update_rules /etc/ufw/after6.rules "$rules"
ufw reload
# vim: set noet :
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment