Many Linux users, especially new ones, run their computers with nothing but the Linux OS. No network monitoring is performed, no IDS is running and no firewall is set up. While running a Linux distribution, the probability of being hacked is infinite lower than while running Windows, but still, it’s better to be safe than sorry.

This post will describe how to setup a very basic firewall using iptables by dropping all traffic by default and allowing only the traffic you really need.

First of all, you need to get this little script and edit it to suit your needs. You need to be root to run it so open a terminal and type:

sudo su
cd /etc/

Now, the first thing you need to edit in this script is your interface IP. To quickly find it, run this command:

ifconfig eth0 | grep "inet addr" | awk -F: '{print $2}' | awk '{print $1}'

Edit the script and modify the SERVER_IP at the top.

nano /etc/

Next, if you run a ssh server but on a different port than 22, find these two lines and edit the port number. If you don’t run a ssh server, you can comment them out by adding a ‘#‘ in front of them:

iptables -A INPUT -i eth0 -p tcp --dport 22 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -o eth0 -p tcp --sport 22 -m state --state ESTABLISHED -j ACCEPT

At the end of the script, there are two examples for rules that allows INCOMING and OUTGOING connections for example ports 3232. If you need to reach other ports, add the two lines for each port accordingly.

For example, let’s say you need to connect to a ssh server that runs on port 31, add the following lines to OUTGOING:

iptables -A OUTPUT -o eth0 -p tcp --dport 69 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A INPUT -i eth0 -p tcp --sport 69 -m state --state ESTABLISHED -j ACCEPT

Now let’s say you’re running a FTP server on port 21, add the following lines to INCOMING:

iptables -A INPUT -i eth0 -p tcp –dport 21 -j ACCEPT
iptables -A OUTPUT -o eth0 -p tcp –sport 21 -j ACCEPT

And so on, you get the idea.

Once you finished adding new ports, run the script (you are still as root from ‘sudo su’ command):

chmod +x /etc/
sh /etc/

To make the script run at every boot, add this line:
to /etc/rc.local

If something goes wrong, flush the rules and ACCEPT all:

iptables -F INPUT
iptables -F OUTPUT
iptables -F FORWARD
iptables -F LOGGING
iptables -t nat -F
iptables -P INPUT ACCEPT

Have fun!

HowTo Setup a Firewall on Ubuntu Using Iptables
Tagged on: