iptables
iptables is a user-space utility that allows a system administrator to configure the IP packet filter rules of the Linux kernel firewall, implemented as a set of Netfilter hooks. For many years, it has been the standard tool for firewalling on Linux.
iptables
works by inspecting packets as they traverse the network stack and applying a set of rules in a specific order.
Common iptables
Commands
Here are some of the most frequently used commands for managing iptables
rules:
-
List All Rules (Verbose):
sudo iptables -L -v
-
List Rules for a Specific Chain:
sudo iptables -L INPUT -v
-
Append a Rule (adds to the end of the chain): This example allows incoming TCP traffic to the web server on port 80.
sudo iptables -A INPUT -p tcp --dport 80 -j ACCEPT
-
Insert a Rule (adds to a specific position): This inserts a rule at the beginning of the
INPUT
chain to allow SSH access.sudo iptables -I INPUT 1 -p tcp --dport 22 -j ACCEPT
-
Delete a Rule: You can delete a rule by specifying the same rule definition or by using the line number (which you can see with
--line-numbers
).# By rule definition
sudo iptables -D INPUT -p tcp --dport 80 -j ACCEPT
# By line number (e.g., delete rule number 3 in the INPUT chain)
sudo iptables -D INPUT 3 -
Flush Rules (Clear all rules in a chain):
sudo iptables -F INPUT
-
Flush All Chains and Delete Custom Chains:
sudo iptables -F
sudo iptables -X -
Save and Restore Rules: The method for making
iptables
rules persistent across reboots can vary by distribution. A common method is using theiptables-save
andiptables-restore
commands.# Save current rules
sudo iptables-save > /etc/iptables/rules.v4
# Restore rules from a file
sudo iptables-restore < /etc/iptables/rules.v4
While still widely used, iptables
is gradually being succeeded by nftables
, which offers a more modern and efficient syntax.