iptables Command
iptables is a powerful, terminal-based utility for configuring the Linux kernel firewall (Netfilter). It allows for highly detailed and granular control over network traffic. It is complex, and for simpler use cases, a tool like ufw is often recommended.
Basic Concepts
iptables works with a system of tables, chains, and rules.
- Tables: The main tables are
filter(the default, for packet filtering),nat(for network address translation), andmangle(for specialized packet alteration). - Chains: Chains are lists of rules that match a set of packets. The default chains in the
filtertable areINPUT(for packets destined for the local server),FORWARD(for packets being routed through the server), andOUTPUT(for packets generated by the local server). - Rules: A rule specifies what to do with a packet that matches it (e.g.,
ACCEPT,DROP,REJECT).
Managing Rules
List All Rules
sudo iptables -L -v -n Lists all rules in all chains in the default filter table.
Flag breakdown:
-L→ List rules.-v→ Verbose output (shows more detail like packet/byte counters).-n→ Numeric output (shows IP addresses and port numbers instead of resolving names).
Allow Incoming Traffic on a Port
sudo iptables -A INPUT -p tcp --dport 22 -j ACCEPTThis rule appends (-A) to the INPUT chain a rule that accepts (-j ACCEPT) all TCP (-p tcp) packets destined for port 22 (--dport 22). This is how you would allow SSH access.
Drop Incoming Traffic from an IP
sudo iptables -A INPUT -s 123.45.67.89 -j DROPThis rule appends to the INPUT chain a rule that silently drops (-j DROP) all packets from the source IP 123.45.67.89 (-s).
Delete a Rule
sudo iptables -D INPUT 3Deletes (-D) the rule at a specific position in a chain. In this example, it deletes the 3rd rule in the INPUT chain. You can see the rule numbers by listing them with sudo iptables -L --line-numbers.
Flush All Rules
sudo iptables -FThe -F (flush) command removes all rules from all chains. Be careful with this, as it will leave your firewall wide open.