iptables Rule Syntax and Matching
You'll learn: How to write iptables rules with specific match criteria to control which network traffic is allowed or blocked.
The Core Idea
Writing an iptables rule is like creating a security checkpoint instruction: "If a packet looks like this (matches these criteria), then do that (take this action)." The match criteria let you precisely identify traffic by protocol type, port numbers, network interfaces, IP addresses, and connection states.
Think of it like airport security sorting passengers: "Any person (packet) from Terminal B (source IP), holding a boarding pass for Gate 12 (destination port 80), traveling to New York (destination IP) should proceed through checkpoint 3 (ACCEPT)."
Basic Syntax Structure
An iptables rule follows this pattern:
iptables -A CHAIN -p PROTOCOL -s SOURCE_IP -d DEST_IP --sport SOURCE_PORT --dport DEST_PORT -i IN_INTERFACE -o OUT_INTERFACE -m state --state STATE -j ACTION
Common Match Criteria
-p tcp/udp/icmp– Match protocol type-s 192.168.1.100– Match source IP address-d 10.0.0.5– Match destination IP--sport 12345– Match source port (requires-p)--dport 80– Match destination port-i eth0– Match incoming network interface-o eth1– Match outgoing interface-m state --state ESTABLISHED,RELATED– Match connection state (requires the state module)
Example Rule Explained
iptables -A INPUT -p tcp --dport 22 -s 192.168.1.0/24 -j ACCEPT
This says: "In the INPUT chain, accept TCP packets destined for port 22 (SSH) coming from the 192.168.1.0/24 network."
Key Takeaway: iptables rules use match criteria like protocol, ports, IPs, interfaces, and states to precisely identify which packets should be accepted, dropped, or rejected—giving you granular control over network traffic flow.