How to configure an iptables firewall on CentOS 6

As a quick note to self, here’s how I configured the firewall rules on a new CentOS 6 Linux server recently.

First, I created an “undo” script at /root/undo-iptables with these contents:

#!/bin/sh

OUT=/tmp/undo-iptables.out

echo "running UNDO at `date`"      > $OUT
unalias mv                        >> $OUT 2>&1
mv /etc/sysconfig/iptables /tmp   >> $OUT 2>&1
/etc/init.d/iptables restart      >> $OUT 2>&1

I then made that file executable.

Next, I added this entry to the root user crontab, using the crontab -e command:

# undo the iptables stuff in case i mess it up
0,15,30,45 * * * * /root/undo-iptables

Those two steps should have the effect of undo-ing my firewall rules every 15 minutes, in case I screw them up.

Next, I created the following file at /root/myfirewall:

#!/bin/bash

# iptables example configuration script

# Flush all current rules from iptables
iptables -F

# Allow SSH connections on tcp port 22
# This is essential when working on remote servers via SSH to prevent locking yourself out of the system
iptables -A INPUT -p tcp --dport 22 -j ACCEPT

# allow http on port 80
iptables -A INPUT -p tcp --dport 80 -j ACCEPT

# Set default policies for INPUT, FORWARD and OUTPUT chains
iptables -P INPUT DROP
iptables -P FORWARD DROP
iptables -P OUTPUT ACCEPT

# Set access for localhost
iptables -A INPUT -i lo -j ACCEPT

# Accept packets belonging to established and related connections
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

# limit login attempts on port 22
# only allow 5 TCP/SYN packets to port 22 from an IP address in 5 minutes.
# if it makes more attempts the door is closed till 5 minutes are over.
# from: http://serverfault.com/questions/275669/ssh-sshd-how-do-i-set-max-login-attempts
iptables -A INPUT -p tcp -m tcp --dport 22 -m limit --limit 48/hour -j ACCEPT

# Save settings
/sbin/service iptables save

# List rules
iptables -L -v

Again, I made that file executable.

Now I just ran this file like this:

# cd /root

# ./myfirewall

After that I tested different ports to make sure they weren’t publicly exposed. Once I was satisfied with them, I rebooted the system to make sure the rules came back up automatically after a restart.

Depending on your speed, you may want to adjust the time values in the crontab entry, but other than that, I followed this process on a new, remote CentOS 6 server, and it worked just fine.

If your firewall doesn’t automatically restart when your CentOS system is rebooted, see this article.