Skip to content

Instantly share code, notes, and snippets.

@christroutner
Last active January 24, 2018 22:35
Show Gist options
  • Save christroutner/09254971bdc0423e040b48931a955961 to your computer and use it in GitHub Desktop.
Save christroutner/09254971bdc0423e040b48931a955961 to your computer and use it in GitHub Desktop.
Docker Firewall

This is an iptables script that should be copied to the /etc/iptables/rules.v4 file. This script is based on this blog entry. The goal is to setup a Docker container that is restricted from attacking the host.

The code below allows DNS to pass through, but blocks the Docker container from direct access to the 192.168.x.x subnet. It also enforces this same rule on the Host, in case it was to get hacked.

This script needs to be customized for each hardware target, as the name of the ethernet port will change. I also want to incorporate some ideas from this article:

  • Prevent DoS Attack
*nat
:PREROUTING ACCEPT [0:0]
:INPUT ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
:POSTROUTING ACCEPT [0:0]
-A POSTROUTING -o enp0s3 -j MASQUERADE
COMMIT

# Generated by iptables-save v1.6.0 on Wed Jan 24 08:06:27 2018
*filter
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]

# Allow localhost
-A INPUT -i lo -j ACCEPT
-A OUTPUT -o lo -j ACCEPT

# ICMP
-A INPUT -p icmp -j ACCEPT

# Docker
## Prevent docker from speaking directly to any devices on the LAN
-A FORWARD -i docker0 -d 192.168.0.0/16 -j DROP
## Allow all other traffic to pass through
-A FORWARD -i docker0 -o enp0s3 -j ACCEPT
-A FORWARD -i enp0s3 -o docker0 -j ACCEPT

# Incoming
-A INPUT -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
## Allow DNS to pass through
-A INPUT -p udp -i enp0s3 --sport 53 -j ACCEPT

# Outgoing
## Allow DNS to pass through
-A OUTPUT -p udp -o enp0s3 --dport 53 -j ACCEPT
## Do not allow host to speak to LAN devices, in case it gets hacked.
-A OUTPUT -d 192.168.0.0/16 -j DROP
-A OUTPUT -j ACCEPT

# Routing
-A FORWARD -j ACCEPT

COMMIT

When a change is made, I can update the firwall with this command:

netfilter-persistent reload 
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment