What are the iptables tables and chains, and what is each one for?
Show the answer
Say this first
A table groups rules by job, a chain is the point in the packet's path where they run. filter (the
default) accepts or drops in INPUT, FORWARD and OUTPUT. nat rewrites addresses in PREROUTING (DNAT),
POSTROUTING (SNAT, MASQUERADE), OUTPUT and INPUT, and only sees the first packet of each connection.
mangle changes packets or sets marks in all five chains. raw runs before connection tracking, mostly to
exempt traffic from it. security is for SELinux labels.
Go deeper
The map
| Table | Job | Built-in chains |
|---|---|---|
| filter | Allow or block | INPUT, FORWARD, OUTPUT |
| nat | Address and port translation | PREROUTING, INPUT, OUTPUT, POSTROUTING |
| mangle | Marks, TTL, DSCP, TCPMSS | PREROUTING, INPUT, FORWARD, OUTPUT, POSTROUTING |
| raw | Before conntrack, CT --notrack | PREROUTING, OUTPUT |
| security | SELinux security marks | INPUT, FORWARD, OUTPUT |
The five hooks in one line each
- PREROUTING: every packet arriving, before the routing decision.
- INPUT: packets for this host.
- FORWARD: packets routed through this host.
- OUTPUT: packets created by this host.
- POSTROUTING: every packet leaving, after routing.
Working with it
iptables -S # filter table as commands
iptables -t nat -S # nat table
iptables -N SSH-IN # user-defined chain
iptables -A INPUT -p tcp --dport 22 -j SSH-INWithout -t, iptables works on filter. Terminating targets are ACCEPT, DROP and REJECT; LOG and MARK
continue to the next rule; RETURN goes back to the calling chain.
They will ask next
Where does DNAT go, and where does SNAT go?
DNAT in nat PREROUTING (and nat OUTPUT for traffic the host itself creates), so the routing decision uses the new destination. SNAT and MASQUERADE in nat POSTROUTING, after routing has chosen the output interface.
Can you filter in the nat table?
You should not. nat chains see only the first packet of a connection, and DROP is not allowed there on modern versions. Filter in the filter table.
Traps
- Saying "the iptables INPUT chain" as if there were only one. Several tables have an INPUT chain.
- Forgetting that
iptableswith no-tis the filter table, soiptables -Lhides all NAT rules.