Firewallingwithiptables

IPTables is quick and easy to install, and it’s a great way to lock down your server. Here’s a quick start that will give you access to the server only for ssh, web, and email traffic.


sudo su - # to become root

yum install iptables

# GROUND RULES: Allow established TCP traffic 
iptables -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
iptables -A FORWARD -i eth0 -m state --state RELATED,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -m state --state NEW,RELATED,ESTABLISHED -j ACCEPT

# ALLOW: ssh, smtp, http, https, pings, local traffic
iptables -A INPUT -p tcp --dport 22 -j ACCEPT
iptables -A INPUT -p tcp --dport 25 -j ACCEPT
iptables -A INPUT -p tcp --dport 80 -j ACCEPT
iptables -A INPUT -p tcp --dport 443 -j ACCEPT
iptables -A INPUT -p icmp -j ACCEPT
iptables -A INPUT -s 127.0.0.1 -j ACCEPT

# REJECT: anything that wasn't explicitly allowed
iptables -A INPUT -j REJECT
iptables -A FORWARD -j REJECT

# Save rules so they'll be used after reboots
service iptables save

That’s should give you a nice and secure system, but there are times you need to make exceptions. For instance, what if you have separate web server and database servers? You don’t want to allow everyone in, but you will need to allow the web server to connect to the mysql port, 3306, on your database server. You can do that with a rule like this:


iptables -A INPUT -p tcp -s <source address> -d <destination address> --dport 3306 -j ACCEPT

In our example, the source address would be the private address of your web server, and the destination address would be the private address of the db server. Use ‘ifconfig eth1’ on the servers to double-check your private address. You can easily tailor this command to only allow ssh or web traffic from certain IP addresses.

Be sure to run service iptables save as root to save your rules after you make changes.

If you mess up, you can flush all rules and start over with iptables --flush, or you can delete a rule by changing the -A to -D, e.g.


iptables -A INPUT -s 120.23.210.33 -p tcp --dport 22 -j ACCEPT
# Ooops. Typo in the source address. Delete it and try again:
iptables -D INPUT -s 120.23.210.33 -p tcp --dport 22 -j ACCEPT
iptables -A INPUT -s 120.23.210.32 -p tcp --dport 22 -j ACCEPT