CentOS – Setup the iptables Firewall

KB ID 0000938

Problem

I was a little perturbed to find out the firewall on my CentOS web server was wide open today. My server setup notes yielded no clues, so it was time to put my ‘Linux Head’ on and fix it.

Solution

1. Connect to the server via console or SSH. As I’m going to change the iptables config file lets back it up (always assume you are going to smash something!)

cp /etc/sysconfig/iptables iptables.bak

2. I have a VPS so I’m usually logged on via SSH, so to avoid locking myself out I’m going to change the default policy to allow (yes in my current scenario that’s a moot point, but it’s good practice). Then I can flush the current rules, without kicking myself out.

iptables -P INPUT ACCEPT iptables -F

3. Then allow packets destined to Loopback (127.0.0.1), some processes on the server rely on this, and expect it to be open.

iptables -A INPUT -i lo -j ACCEPT

4. Allow packets that were not initiated by the server, but are already established or related to an established connection.

iptables -A INPUT -m state –state ESTABLISHED,RELATED -j ACCEPT

5. Allow in the ports you require (your requirements may differ).

iptables -A INPUT -p tcp –dport 22 -j ACCEPT iptables -A INPUT -p tcp –dport 80 -j ACCEPT iptables -A INPUT -p tcp –dport 443 -j ACCEPT iptables -A INPUT -p tcp –dport 25 -j ACCEPT iptables -A INPUT -p tcp –dport 110 -j ACCEPT iptables -A INPUT -p tcp –dport 53 -j ACCEPT iptables -A INPUT -p tcp –dport 993 -j ACCEPT iptables -A INPUT -p udp –dport 53 -j ACCEPT iptables -A INPUT -p tcp –dport 12345 -j ACCEPT

6. To allow your server to respond to pings (if required);

iptables -A INPUT -p icmp -j ACCEPT

7. Drop all other traffic, and set the forwarding table to also drop all traffic. Then I’m going to allow all outbound ports from the server.

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

8. TEST EVERYTHING! Then save the changes, to make them persistent.

/sbin/service iptables save

Show iptables Settings

iptables -L -v

Start/Stop and Restart the iptables Service

service iptables stop service iptables start service iptables restart

 

Related Articles, References, Credits, or External Links

NA

 

Author: Migrated

Share This Post On