Using Iptables To Firewall Both IPv4 And IPv6

Published June 17th, 2014


The following is a quick example on how to firewall both IPv4 and IPv6 using iptables in Ubuntu. THe following article should be useful for other Linux disros as well though the last part about the iptables-persistant package may be Ubuntu/Debian specific. To start out lets keep it simple please and allow ssh, http, and https:

sudo iptables -A INPUT -i eth0 -m state --state ESTABLISHED,RELATED -j ACCEPT
sudo iptables -I INPUT 1 -p tcp --dport 22 -j ACCEPT
sudo iptables -I INPUT 1 -p tcp --dport 80 -j ACCEPT
sudo iptables -I INPUT 1 -p tcp --dport 443 -j ACCEPT

If you use FTP or allow remote access to MySQL you should think about not doing so in the future...

sudo iptables -I INPUT 1 -p tcp --dport 21 -j ACCEPT
sudo iptables -I INPUT 1 -p tcp --dport 3306 -j ACCEPT

Now add any other rules you may need now as well...

After running the commands to open things up close all other ports:

sudo iptables -A INPUT -j DROP

Then open up local loops:

sudo iptables -A INPUT -i lo -j ACCEPT

For IPv6 run the same commands as above just change "iptables" to "ip6tables" for example:

sudo ip6tables -A INPUT -i eth0 -m state --state ESTABLISHED,RELATED -j ACCEPT
sudo ip6tables -I INPUT 1 -p tcp --dport 22 -j ACCEPT

Continue adding rules as you did for IPv4...

Ubuntu (and Debian?) users can now install the following package to make life easier and carry rules through a reboot. The rules you just ran will be carried over automatically when setting up iptables-persistant if you let it:

sudo apt-get install iptables-persistent

The config files generated for IPv4 and IPv6 should look similar and look something like so:

*filter
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
-A INPUT -i lo -j ACCEPT
-A INPUT -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
-A INPUT -p tcp -m tcp --dport 22 -j ACCEPT
-A INPUT -p tcp -m tcp --dport 80 -j ACCEPT
-A INPUT -p tcp -m tcp --dport 443 -j ACCEPT
-A INPUT -j DROP
COMMIT