Skip to content

Iptables cheatsheet

Published:

What is iptables

Iptables is a user-space utility program that allows a system administrator to configure the IP packet filter rules of the Linux kernel firewall. When a connection does not go through, it’s usually because of a firewall rule.

Struttura di iptables

Iptables is made up of a series of rules organized in tables and chains.

The tables are the following:

Each table contains a series of predefined chains:

Loading diagram...

All chains contain an arbitrary number of rules that are evaluated in sequence, until the conditions of a rule are met. This will determine the action to take, which can be ACCEPT, DROP, REJECT, LOG, RETURN, etc. A default policy determines what to do with packets for which no match is found.

The sequence of rule evaluation is summarised as follows:

Loading diagram...
Loading diagram...

Basic commands

List rules

# List rules
iptables -L [chain] [options]
# E.g.
# List all INPUT rules
iptables -L INPUT
# List all rules with line numbers
iptables -L -n --line-numbers
# List all rules with verbose output
iptables -L -v

Add a rule

# Append a rule to the end of a chain
iptables -A <chain> [index] <rule>
# E.g.
# Allow all incoming traffic on the loopback interface
iptables -A INPUT -i lo -j ACCEPT
# Allow all incoming tcp traffic on port 80
iptables -A INPUT -p tcp --dport 80 -j ACCEPT
# Insert a rule at a specific position in a chain
iptables -I <chain> [index] <rule>
# E.g.
# Allow traffic from interface eth0. Inserted on top of the chain (index is 1 by default)
iptables -I INPUT -i eth0 -j ACCEPT
# Accepts incoming traffic from a specific IP address on port 22
iptables -I INPUT 2 -s 192.168.1.1 -p tcp --dport 22 -j ACCEPT
# Accept established connections
iptables -I INPUT 3 -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT

Delete a rule

# Delete a rule from a chain
iptables -D <chain> <index>
# E.g.
# Delete the rule at index 2 from the INPUT chain
iptables -D INPUT 2
# Delete a rule based on its definition
iptables -D INPUT -m conntrack --ctstate INVALID -j DROP
# Delete all rules from a chain
iptables -F <chain>
# E.g.
# Delete all rules from the INPUT chain
iptables -F INPUT

Save and restore rules

# Save rules to a file
iptables-save > /etc/iptables/rules.v4
# Restore rules from a file
iptables-restore < /etc/iptables/rules.v4