iptables — guide

iptables is the configuration interface for packet filtering in the Linux kernel (Netfilter). The rules live in tables, in chains; ; each rule has matching conditions and a target.

Tables and chains

TableChains
filterINPUT, FORWARD, OUTPUT
natPREROUTING, INPUT, OUTPUT, POSTROUTING
manglePREROUTING, INPUT, FORWARD, OUTPUT, POSTROUTING
rawPREROUTING, OUTPUT
securityINPUT, FORWARD, OUTPUT

Packet path

PREROUTING (raw → mangle → nat) → routing decision → either INPUT (mangle, filter, security, nat) for local traffic, or FORWARD (mangle, filter, security) → POSTROUTING (mangle, nat).

Locally generated traffic: OUTPUT (raw, mangle, nat, filter, security) → POSTROUTING.

Targets

  • ACCEPT— lets the packet continue.
  • DROP— drops silently.
  • REJECT— drops and responds (e.g. --reject-with tcp-reset).
  • LOG— logs to the kernel log, does not stop processing.
  • RETURN— returns to the previous chain.
  • DNAT / SNAT / MASQUERADE / REDIRECT— address/port transformations.

Basic commands

# listing
iptables -L -n -v --line-numbers
iptables -S
# append at the end / insert / delete
iptables -A INPUT ...
iptables -I INPUT 1 ...
iptables -D INPUT 3
# default policy
iptables -P INPUT DROP
# flush (WARNING: with the DROP policy you lock yourself out; set iptables -P INPUT ACCEPT first)
iptables -F
# IPv6
ip6tables ...
# save / restore
iptables-save > /etc/iptables/rules.v4
iptables-restore < /etc/iptables/rules.v4
# persistence on Debian/Ubuntu
netfilter-persistent save
# anti-lockout (applies a rules file and reverts if you do not confirm in time)
iptables-apply

Best practices

  • Use -m conntrack --ctstate instead of -m state --state (deprecated).
  • Rules are evaluated top to bottom; the first matching rule with a terminal target wins.
  • Test from a second session (so you do not lock yourself out).
  • fail2ban complements iptables, it does not replace it.
  • ufw and firewalld are front-ends.

iptables and nftables

On modern distributions iptables may be a wrapper iptables-nft (iptables -V shows (nf_tables) or (legacy)). nft list ruleset lists the nftables rules. iptables-translate converts a rule to nft syntax.

Kernel log format (SIMULATED example)

IPT-DROP: IN=eth0 OUT= MAC=... SRC=203.0.113.7 DST=198.51.100.10 LEN=60 TOS=0x00 PREC=0x00 TTL=52 ID=12345 DF PROTO=TCP SPT=44321 DPT=22 WINDOW=64240 RES=0x00 SYN URGP=0