Skip to content

Instantly share code, notes, and snippets.

@ulexxander
Created April 24, 2024 18:06
Show Gist options
  • Save ulexxander/d072ac619d93fc81547f753fe6d4cc06 to your computer and use it in GitHub Desktop.
Save ulexxander/d072ac619d93fc81547f753fe6d4cc06 to your computer and use it in GitHub Desktop.
Docker friendly iptables rules when cloud firewall rules can't be used, e.g. on baremetal hosts. Can protect both regular services as well as Docker containers forwarded ports.
# 1. Set IPTABLES_RESTORE_NOFLUSH=yes in /etc/default/netfilter-persistent
# 2. Put contents of that file in /etc/iptables/rules.v4
# 3. Apply this file now and after each reboot by running: systemctl enable --now iptables.service
# 4. You can also apply this file directlry using: iptables-restore --noflush < /etc/iptables/rules.v4
*filter
#################################################
############# INPUT chain #############
#################################################
# Clear the whole chain before adding rules.
-F INPUT
# Connection tracking.
-A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
-A INPUT -m conntrack --ctstate INVALID -j DROP
# Allow localhost and WireGuard communications.
-A INPUT -i lo -j ACCEPT
-A INPUT -i wg0 -j ACCEPT
-A INPUT -p udp -m udp --dport 51820 -j ACCEPT
# Allow Docker containers communication.
-A INPUT -s 172.16.0.0/16 -j ACCEPT
# Allow SSH from external interface for maintenance purposes.
-A INPUT -s 1.2.3.4/32 -p tcp --dport 22 -j ACCEPT
# Some service.
-A INPUT -p tcp --dport 12345 -j ACCEPT
# Drop everything else.
# -A INPUT -m limit --limit 30/min -j LOG --log-prefix "iptables INPUT drop: "
-A INPUT -j DROP
#################################################
############# DOCKER-USER chain #############
#################################################
# Clear the whole chain before adding rules.
-F DOCKER-USER
# Connection tracking.
-A DOCKER-USER -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
-A DOCKER-USER -m conntrack --ctstate INVALID -j DROP
# Open port to internet, wg0 don't need to be whitelisted.
-A DOCKER-USER -i enp6s0 -p tcp --dport 45678 -j ACCEPT
# Drop everything else.
# -A DOCKER-USER -i enp6s0 -m limit --limit 30/min -j LOG --log-prefix "iptables DOCKER-USER drop: "
-A DOCKER-USER -i enp6s0 -j DROP
-A DOCKER-USER -j RETURN
COMMIT
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment