Tuesday, December 5, 2006

Firewall on Ubuntu using iptables

I decided to start by adding a firewall to Pericles, and a little searching revealed that iptables is exactly what I need for the very simple setup I am planning on running. Even if you run a separate firewall or router as a gateway, it may not be a bad idea to install iptables on your machine as well so that you can have full control over what goes in and out in the event that you ever have any guest machines connected on the network inside of the firewall.

The Ubuntu server distribution came with iptables preinstalled, I just had to create scripts to set up the firewall and get them to automatically start when the machine boots up.

I started here:

Easy Firewall Generator for IPTables

I generated a simple script, enabling SSH, DNS, Web Server, and a couple of other services I use on the first Ethernet interface (eth0), copied and pasted it into an editor (running under sudo) and modified it slightly:

I searched and found the line for the HTTP service:

$IPT -A tcp_inbound -p TCP -s 0/0 --destination-port 80 -j ACCEPT

I copied and pasted this and changed the port number to a few other ports I need open for specialized purposes. (Since I do more than just basic web hosting, I have clients using custom software that connect to specific ports.)

If you need to open a range, use something like 3000:3010 in place of the 80 in the above line.

Try to open as few ports as possible. That's kind of the point of a firewall.

Also, search for "ping", and you'll find a note on a line you can uncomment to allow pinging to your server. I prefer to allow pinging, you may choose not to. If you want pinging, uncomment it so it looks like this:

$IPT -A icmp_packets -p ICMP -s 0/0 --icmp-type 8 -j ACCEPT

Now save the finished file as /etc/init.d/iptables (which did not exist when I started)

Set the permissions so that it matches the rest of the files in /etc/init.d:
sudo chmod 755 /etc/init.d/iptables

Please test your firewall by running ./iptables start from the shell prompt. Remember, it won't close any ports that are already opened, so try opening a second ssh session or whatnot to verify that you can still access your box before deciding to make this firewall permanent. I recommend leaving some distinguishable port closed so you can verify that iptables is working--for example, I disabled icmp ping, and when I pinged the box and saw Request timed out, I knew that my firewall was working, so then I edited the iptables script to enable pinging again.

Once you are satisfied that it is working according to your desires, you need to add iptables to the list of daemons to automatically start for the various runlevels when your machine is booted up:
sudo update-rc.d iptables defaults

Finally, reboot your system and make sure the firewall comes up:
sudo reboot now

No comments: