iptables Chains and Packet Flow
What you'll learn: How network packets travel through iptables' five built-in chains as they enter, traverse, or leave your Linux system.
Understanding the Packet Journey
When a packet arrives at your Linux firewall, it doesn't just randomly hit rules. Instead, it follows a predetermined path through specific chains—ordered lists of rules that examine and decide the packet's fate. Think of chains like security checkpoints at an airport, where packets must pass through different gates depending on where they're going.
The Five Built-In Chains
PREROUTING
The first stop for incoming packets, before routing decisions are made. This is where you manipulate packets before the system decides where to send them (useful for destination NAT).
INPUT
Packets destined for the local system itself pass through here. If someone is trying to connect to a service running on your firewall, INPUT rules apply.
FORWARD
Packets passing through your system (not destined for it) traverse this chain. This is critical when your Linux box acts as a router or gateway between networks.
OUTPUT
Packets originating from the local system start here. When your firewall itself initiates connections or sends data, these rules apply.
POSTROUTING
The final checkpoint before packets leave the system, after routing decisions. This is where source NAT happens (masquerading).
The Flow
- Incoming packet → PREROUTING → routing decision → INPUT (if local) or FORWARD (if transit) → POSTROUTING → out
- Locally generated → OUTPUT → routing decision → POSTROUTING → out
Each chain processes the packet sequentially through its rules until a match determines the action (ACCEPT, DROP, etc.).
Key Takeaway: Understanding packet flow through PREROUTING, INPUT, FORWARD, OUTPUT, and POSTROUTING chains is essential for placing iptables rules in the correct location to achieve your security objectives.