Getting started with iptables

Posted:  May 14th, 2016

 

The "iptables" firewall software, installed by default on most Linux systems, is used to filter, redirect or block network traffic according to specific rules.

 

We will only see the table "filter", which is the default table.

 

Here are some commands:

 

Get a list of all current IP tables rules:

 

    iptables -L

 

Get a list of all current IP tables rules and show the number of packets that each output rule has "caught":

 

    iptables -L -nv

 

Clear (flush) all IP tables rules:

 

    iptables -F

 

Save iptables rules:

 

    /etc/init.d/iptables save

 

    or

 

    iptables-save

 

Save current iptables rules to a file:

 

   iptables-save > /path/to/file

 

Restore iptables rules from a file:

 

    iptables-restore < /path/to/file

 

Here are some examples of rules:

 

Block all traffic from an IP address:

 

    iptables -I INPUT -s x.x.x.x -j DROP

 

Allow all traffic from an IP address:

 

    iptables -A INPUT -s x.x.x.x -j ACCEPT

 

Block all traffic on a specific port:

 

    iptables -A INPUT -j DROP -p tcp --destination-port 22 -i eth0

 

(Take care to replace x.x.x.x by the IP address)

 

-i eth0: Only process packets arriving on eth0. If you do not specify any interface, the rule will be applied to traffic on all interfaces

-A: Add the rule to the end of the string (--append)

-I: Insert the rule at the beginning of the chain (--insert)

-D: To delete an existing rule (--delete)

-p tcp: Force "iptables" to only process tcp packets (use udp to process upd packets)

 

Please refer to the official "iptables" man page for complete instructions:  http://ipset.netfilter.org/iptables.man.html