Sunday, October 07, 2007

How I setup a firewall using IPTABLES

There are many software firewalls available for Linux but since Linux usually comes with a firewall called IPTABLES, I decided to implement it by hand instead of using any GUI tools.

I started by searching online and found a few good tutorials and ready made scripts. There are also many script generators available, however, I recommend that you understand how IPTABLES work.

create a BASH script (here I name it iptables.rules and store it in /etc):

#!/bin/bash
# flush all chains
iptables -F
# set the default policy for each of the pre-defined chains
iptables -P INPUT DROP
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 eth0 -p udp -j DROP
iptables -A INPUT -i eth0 -p tcp -m tcp --syn -j DROP
# accept anything on localhost
iptables -A INPUT -i lo -j ACCEPT

make sure the script file is given execute file attributes:
# chmod +x iptables.rules

now when this script is executed the firewall is on:

# sh uptables.rules


But were are not done yet. If the system is rebooted the script has to be run again manually. So, it's important to launch the script automatically every time the system is booted.

To do this , an init.d script needs to be created (here I named it firewall and put it in /etc/init.d/):

#!/bin/bash
if [[ $1 == start ]] ; then
sudo /etc/iptables.rules
else
sudo iptables -F
fi

again I added the execute file attribute to this file

Finally I linked the scripts to the boot up process:

# update-rc.d firewall start 20 2 3 4 5 . stop 99 0 1 6 .

Have a safe surf


Powered by ScribeFire.

No comments: