iptables Command Examples in Linux

The iptables tool enables you to manage packet filtering as well as stateful firewall functionality within Linux through various tables. Each table applies to a certain context and consists of rule sets, called chains, that the table uses to implement the firewall. A packet is compared to the first rule in the appropriate chain, and if it does not match that rule, it is compared to the next rule in the chain, and so on. If the packet matches a rule, it can either be evaluated by a new chain or have one of three actions applied to it: ACCEPT, DROP, or RETURN (skip to next rule in previous chain).

Each table has one or more built-in chains, but you can also define your own chains as desired.

Syntax

The syntax of the iptables command is:

# iptables [options] [-t table] [commands] {chain/rule specification}

As shown here, we use iptables -L to list the current firewall rules configured:

# iptables -L 
Chain INPUT (policy DROP) 
target   prot opt source        destination 
ACCEPT   tcp -- anywhere       anywhere       tcp dpt:ssh 
ACCEPT   tcp -- anywhere       anywhere       tcp dpt:smtp 
ACCEPT   icmp -- anywhere       anywhere       icmp echo-request 
  
Chain FORWARD (policy ACCEPT) 
target   prot opt source        destination 
  
Chain OUTPUT (policy ACCEPT) 
target   prot opt source        destination

In this example, the INPUT table has several rules configured. The INPUT table also has a default policy of DROP that defines what to do with the traffic if no rule matches. We can change the default policy with the command iptables -P INPUT ACCEPT, which will allow any traffic even if it is not defined in the INPUT table. The command can be handy if we need to troubleshoot a firewall, and it can be reversed with iptables -P INPUT DROP.

It is important to note that any rules applied with the iptables command are not persistent through a reboot. If you want to save the rules so they survive a reboot, you either need to edit the iptables configuration file directly or save the iptables currently in memory. To save the current iptables in memory, you would use something like iptables-save > /etc/iptables.rules.

iptables Command Examples

1. View chains, rules, and packet/byte counters for the filter table:

# iptables -vnL

2. Set chain policy rule:

# iptables -P chain rule

3. Append rule to chain policy for IP:

# iptables -A chain -s ip -j rule

4. Append rule to chain policy for IP considering protocol and port:

# iptables -A chain -s ip -p protocol --dport port -j rule

5. Add a NAT rule to translate all traffic from the `192.168.0.0/24` subnet to the host’s public IP:

# iptables -t nat -A POSTROUTING -s 192.168.0.0/24 -j MASQUERADE

6. Delete chain rule:

# iptables -D chain rule_line_number

7. Save iptables configuration of a given table to a file:

# iptables-save -t tablename > path/to/iptables_file

8. Restore iptables configuration from a file:

# iptables-restore 
Related Post