Configuring iptables on your VPS

Aidan | Security | 23 September

iptables-network-security

After just installing iptables, it will have no rules on the INPUT, OUTPUT or FORWARD chains:

# iptables -L

Chain INPUT (policy ACCEPT)
target prot opt source destination

Chain FORWARD (policy ACCEPT)
target prot opt source destination

Chain OUTPUT (policy ACCEPT)
target prot opt source destination

And the default policy on each chain is "ACCEPT", which means there are no restrictions: any incoming and any outgoing packets are allowed.

We want to connect to any address and port from our system, so we'll leave the OUTPUT chain to ACCEPT all outgoing connections. However, we don't anyone to connect to our server unless we specify which ports are open, etc, so let's DROP everything on the INPUT and FORWARD chains. Our initial minimal firewall script will look like this:

iptables -F
iptables -X

iptables -P OUTPUT ACCEPT
iptables -P FORWARD DROP
iptables -P INPUT DROP

With these initial rules, we can connect to any other servers, but nobody can connect to us. But now our system is so "safe", it's almost useless! Since no-one can connect to us, it also means when we connect to someone else, they can't even reply! So the next step is to add a rule to the script to tell iptables to allow incoming packets only if they are related to a connection that we established:

iptables -A INPUT -i eth0 -m state --state ESTABLISHED,RELATED -j ACCEPT

Now we can browse Web sites, check mail, etc, but no one can establish a new connection to our machine.  Since we're running a Web server, we need to allow incoming connections only for the HTTP port (port 80). Let's also allow people to ping us (icmp protocol):

iptables -A INPUT -i eth0 -p tcp --dport http -j ACCEPT
iptables -A INPUT -i eth0 -p icmp -j ACCEPT

Now you just continue in this way to open the ports you want to allow (smtp, pop3, ssh etc). You can also configure iptables to log invalid packets, etc.

Once you're done with your firewall script, you can configure iptables to automatically load the new changes after reboots:

# iptables-save > /etc/sysconfig/iptables

New Call-to-action