Basic Firewall Script for Ubuntu
Thursday, 17 July 2008 00:00

Tonight will just be a quick post that outlines a script I wrote to lock down the ports that are open on my Ubuntu box. My main goal was to allow for any traffic that originated from the server, but to otherwise only allow traffic in on the SSH port (22) and the HTTP port (80). The script can be adapted to allow for any additional ports.

Start by creating a bootup script within /etc/init.d/ (I called my file firewall):

#!/bin/bash

# flush all rules for all chains
iptables -F

# set the default policies
iptables -P FORWARD DROP
iptables -P INPUT DROP
iptables -P OUTPUT ACCEPT

# allow all loopback traffic
iptables -A INPUT -i lo -j ACCEPT
iptables -A OUTPUT -o lo -j ACCEPT

# allow SSH
iptables -A INPUT -p tcp --dport 22 -j ACCEPT
iptables -A OUTPUT -p tcp --sport 22 -j ACCEPT

# allow HTTP
iptables -A INPUT -p tcp --dport 80 -j ACCEPT
iptables -A OUTPUT -p tcp --sport 80 -j ACCEPT

# allow returning traffic from locally initiated requests
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

For each port, I included both an input and an output rule, even though the output one isn't fully necessary.

Then you simply need to install this script so that it will run on bootup:

sudo update-rc.d firewall defaults

That's it! After a reboot (or you can just manually run the script), your server will restrict access to only the ports you define.