Setting up an IP Tables Firewall in Linux

Over the past couple years, I found myself spending more time with Linux servers. I generally work with Ubuntu servers but more recently began swimming in the yum’s and rpm’s of CentOS. Although each server requires specific configurations and fine tuning, my general starting point after creating a user account was setting up a firewall.

There are various software firewalls available for each distribution. The one I’ve used most is IP Tables, and setting up is relatively straight forward.

Start by viewing your current configuration (if available)

sudo iptables -L

This command will allow you to view the current set of rules that exist. To start on a clean slate, I would recommend saving all your rules to a file. Let’s start by flushing the existing rules.

sudo iptables -F

Below, I’ve included a general configuration which includes most of the services a web host would use. To start a new file,

nano /etc/firewall.rules

Copy and paste these configurations below. Make sure you’ve modified it to your environment, and remove any services that you are not using.


#  Allow traffic originating from the loopback and drop other
-A INPUT -i lo -j ACCEPT
-A INPUT ! -i lo -d -j REJECT

#  Allow established inbound connections and outbound traffic

# Allow connections to SSH
-A INPUT -p tcp -m state --state NEW --dport 22 -j ACCEPT

# Allow connections to Web-Server HTTP and HTTPS
-A INPUT -p tcp --dport 80 -j ACCEPT
-A INPUT -p tcp --dport 443 -j ACCEPT

# Allow connections to FTP
-A INPUT -p tcp --dport 20 -j ACCEPT
-A INPUT -p tcp --dport 21 -j ACCEPT

# Allow server to sent mail using SMTP
-I INPUT -p tcp --dport 25 -m state --state NEW,ESTABLISHED -j ACCEPT
-I OUTPUT -p tcp --sport 25 -m state --state NEW,ESTABLISHED -j ACCEPT

# Allow connections to MySQL
-A INPUT -p tcp --dport 3306 -j ACCEPT

# Allow connections to WebMin
-A INPUT -p tcp --dport 10000 -j ACCEPT

# Allow connections to SVN
-A INPUT -p tcp --dport 3690 -j ACCEPT

# Allow type-8 pings
-A INPUT -p icmp -m icmp --icmp-type 8 -j ACCEPT

# Log rejected traffic
-A INPUT -m limit --limit 5/min -j LOG --log-prefix "iptables denied: " --log-level 7

# Reject all other inbound traffic


To save this, you would issue the following command.

sudo /sbin/iptables-restore < /etc/firewall.rules

You’re all done. You can view your configurations again by issuing the command,

sudo iptables -L

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>