Wednesday, October 28, 2009

Simple firewall for Ubuntu using iptables

Linux's built-in firewall iptables is very useful, but pretty hard to configure. I used to use lokkit, but this caused problems when moving between different networks. I was also having problems with the network configuration tools in Ubuntu, which work but aren't automatic enough for me. And I wanted to be able to switch the firewall and the network configuration simultaneously.

In the end, I bit the bullet and worked out how to write a simple iptables script. Here it is:
#!/bin/bash
# flush all chains
iptables -F
# set the default policy for each of the pre-defined chains
iptables -P INPUT ACCEPT
iptables -P OUTPUT ACCEPT
iptables -P FORWARD DROP
# allow establishment of connections initialised by my outgoing packets
iptables -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
# drop everything else
iptables -A INPUT -i eth+ -p udp -j DROP
iptables -A INPUT -i eth+ -p tcp -m tcp --syn -j DROP
# accept anything on localhost
iptables -A INPUT -i lo -j ACCEPT


I have network interfaces on eth0 and eth1, so this script has rules which cover both; if your interfaces have different names, you will need to edit the rules to cover that. This drops everything incoming, except for connections which were initially established by my outgoing packets (thanks Luke! - see comments); which means it's no good for servers.

I put this script in /opt/scripts/iptables.script and made it executable. Once you run it, you can find out whether it has worked by displaying your current iptables rules with:
sudo iptables -L -v


I then created a simple init script to start/stop the firewall (in /etc/init.d/firewall):
#!/bin/bash
if [[ $1 == start ]] ; then
sudo /opt/scripts/iptables.script
else
sudo iptables -F
fi

Then I symlinked this into my /etc/rc.* directories using the update-rc.d tool, so the firewall starts before the network comes up:
update-rc.d firewall start 20 2 3 4 5 . stop 99 0 1 6 .


I find having this script helps me a lot. I have it integrated with a start/stop script with my network, so I can easily switch network and firewall configuration from the command line.

No comments:

Post a Comment