Saturday 15 January 2011

Basic iptables

Here are the basics of using iptables on your system:

Create /etc/iptables.new.rules with the following content:

( You can use sudo nano /etc/iptables.new.rules)
*filter
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
-A INPUT -i lo -j ACCEPT
-A INPUT -d 127.0.0.0/8 -i ! lo -j REJECT --reject-with icmp-port-unreachable
-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
# For SSH
-A INPUT -p tcp -m tcp --dport 22 -j ACCEPT
# For SMTP
-A INPUT -p tcp -m tcp --dport 25 -j ACCEPT
# For HTTP
-A INPUT -p tcp -m tcp --dport 80 -j ACCEPT
# For HTTPS
-A INPUT -p tcp -m tcp --dport 443 -j ACCEPT
-A INPUT -p icmp -m icmp --icmp-type 8 -j ACCEPT
-A INPUT -m limit --limit 5/min -j LOG --log-prefix "iptables denied: " --log-level 7
-A INPUT -j REJECT --reject-with icmp-port-unreachable
-A FORWARD -j REJECT --reject-with icmp-port-unreachable
-A OUTPUT -j ACCEPT
COMMIT
Add/delete ports depending on your own server setup.

Just to be on the safe side, let's backup the old rules:
sudo -i
iptables-save > /etc/iptables.old.rules
iptables-restore < /etc/iptables.new.rules

Check it:
iptables -L

If all is good, put it in a file for next time the server starts:
iptables-save > /etc/iptables.up.rules

Make sure these rules will get loaded again if you reboot the server:
nano /etc/network/interfaces

Add the iptable line below:
...
auto lo
iface lo inet loopback
pre-up iptables-restore < /etc/iptables.up.rules

Important note: If you access your server remotely, make sure to keep the current session open and try your new rules by opening a new connection to your server. If you can't connect, go back to your first connection and do:
sudo iptables-restore < /etc/iptables.old.rules
You should be good until you figure out your problem.

No comments:

Post a Comment