Wednesday, June 2, 2010

Ubuntu firewall for Home users and Save / Restore Iptables Rules

SkyHi @ Wednesday, June 02, 2010

For a personal home computer (running no services for the outside world), here is a simpler version :


#!/bin/bash

############################################################

#---- Script to setup a simple firewall using iptables -----

###

# * Blocks all incoming connections, except those opened by

# me, or related to already open connections

# * Blocks all forward requests

# * Allows all outgoing connections

###

############################################################


# Clearing all previous rules

iptables -F

# Setting Default Policies

iptables -P INPUT DROP

iptables -P OUTPUT ACCEPT

iptables -P FORWARD DROP

# Allowing already-established and related-incoming connections

iptables -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
#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 integr



tip:
iptables auto on/off
1.)
Run in terminal the next command:
sudo iptables-save > /etc/iptables.rules
2.) Edit /etc/network/interfaces file and add this two line to interface configuration:
pre-up iptables-restore < /etc/iptables.rules
To sum:
auto eth1
iface eth1 inet static
address 192.168.2.1
network 255.255.255.0
broadcast 192.168.2.255
pre-up iptables-restore /etc/iptables.rules
3.) Save and test (reboot)


REFERENCES
http://townx.org/simple_firewall_for_ubuntu_using_iptables

http://www.cyberciti.biz/faq/how-to-save-restore-iptables-firewall-config-ubuntu/