MasterServerBlog › iptables

Configuring iptables on Linux

← all articles

Sometimes you need to add rules to the server firewall. On Linux, this is done through iptables.

First, let's check whether iptables is installed; run this command as the root user
# cat /etc/sysconfig/iptables

If the file exists, its contents will be displayed.

Otherwise, install the package with the command
# yum install iptables iptables-services

Now let's view the current state of the rules
# iptables -nvL --line-number

The output shows 3 chains: INPUT, FORWARD and OUTPUT
These are the chains we will be adding our rules to later.


INPUT — rules for incoming packets go here
FORWARD — rules for incoming packets that are forwarded onward
OUTPUT — rules for outgoing packets go here

We can also display just one chain; for example, let's print the OUTPUT chain
# iptables -nvL OUTPUT --line-number

How to add or remove rules in iptables

You can add or remove rules either with console commands or by opening the file /etc/sysconfig/iptables and making changes in any text editor.
When adding rules we use the -I or -A options; the difference is that -A always appends the new rule to the very end.
With -I you can insert a rule at a specific position by number.
If you use -I without a number, the rule is placed on the first line.
This is important to understand, since all rules are processed strictly in order — the higher a rule is, the higher its priority.

Examples of iptables rules and commands

Block incoming connections from IP 33.33.33.33 (the rule will be placed on line 1 of the INPUT chain)
# iptables -I INPUT -s 33.33.33.33 -j DROP

Block incoming connections from IP 33.33.33.33 and place the rule on line 3 of the INPUT chain
# iptables -I INPUT 3 -s 33.33.33.33 -j DROP

Delete the tenth rule from the INPUT chain
# iptables -D INPUT 10

Allow ICMP Ping requests
# iptables -A INPUT -p icmp --icmp-type echo-request -j ACCEPT

Block ICMP Ping requests
# iptables -A INPUT -p icmp --icmp-type echo-request -j DROP

Block a specific IP address or subnet
# iptables -A INPUT -s 105.188.0.5 -j DROP
# iptables -A INPUT -s 105.188.0.0/24 -j DROP

Block outgoing traffic to 66.66.224.0/19
# iptables -A OUTPUT -p tcp -d 69.171.224.0/19 -j DROP

Block access to a domain
# iptables -A OUTPUT -p tcp -d www.apple.com -j DROP
# iptables -A OUTPUT -p tcp -d apple.com -j DROP

Restore the default rules
# iptables-restore < /etc/iptables.rules

Flush all rules
# iptables -F

Save the file after running all the commands
# iptables-save > /etc/sysconfig/iptables

Restart the firewall for the changes to take effect
# service iptables restart