Skip to content

iptables as a stateful firewall: conntrack states, ordering, and a complete ruleset

How the iptables state machine actually works, the order chains must be evaluated in, and a production-grade ruleset for a Linux server with public services.

A stateless firewall accepts SSH on port 22 and reasons about each packet in isolation. A stateful firewall accepts the first SYN of an SSH connection, then accepts every subsequent packet of that flow because conntrack has marked it ESTABLISHED — without an explicit rule for return traffic. The difference matters once you start blocking outbound traffic, dealing with FTP-style helper protocols, or trying to make sense of why a rule that looks correct silently drops the response. This article goes through the conntrack state machine, the chain evaluation order, and a complete ruleset for a hardened server.

How to verify

Inspect chains, counters, and conntrack:

iptables -L -n -v --line-numbers
iptables -t nat -L -n -v --line-numbers
iptables -t mangle -L -n -v --line-numbers
cat /proc/net/nf_conntrack | head
conntrack -L --proto tcp --state ESTABLISHED | wc -l
sysctl net.netfilter.nf_conntrack_count net.netfilter.nf_conntrack_max
iptables-save | grep -c '^-A'

If conntrack is missing on a system, the kernel falls back to stateless behaviour silently. modprobe nf_conntrack and confirm it appears in lsmod | grep conntrack.

What’s happening

Netfilter inserts hook points at five places in the packet path: PREROUTING, INPUT, FORWARD, OUTPUT, POSTROUTING. iptables exposes those hooks as chains, grouped by tables — raw, mangle, nat, filter. Rules are evaluated in this order for inbound-to-host traffic: raw/PREROUTING → mangle/PREROUTING → nat/PREROUTING → routing decision → mangle/INPUT → filter/INPUT. For forwarded traffic the path goes through FORWARD; for locally generated traffic it goes through OUTPUT and POSTROUTING. Knowing the order is the whole game — a DNAT in nat/PREROUTING happens before filter/INPUT, so the rules in INPUT see the post-NAT destination.

Conntrack is a separate kernel subsystem that tracks every flow the kernel has seen. The states you write rules against are:

  • NEW — the first packet of a flow that conntrack accepts
  • ESTABLISHED — packets belonging to a conntrack entry that has seen traffic in both directions
  • RELATED — packets that are logically tied to an existing flow but not part of it (ICMP errors, FTP data channels via the nf_conntrack_ftp helper)
  • INVALID — packets that fail conntrack’s sanity checks (out-of-window TCP, malformed)
  • UNTRACKED — explicitly excluded from tracking via raw/PREROUTING -j NOTRACK

The canonical opening rule is iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT. With that one line, you only need explicit ACCEPTs for new inbound connections; reply traffic to outbound flows is handled by ESTABLISHED.

The procedure

  1. Set safe defaults and flush. A misplaced default-DROP without an SSH rule will lock you out. Use a script that flushes, sets defaults, adds rules, and only then sets policy to DROP.

    iptables -F
    iptables -X
    iptables -P INPUT   ACCEPT
    iptables -P FORWARD DROP
    iptables -P OUTPUT  ACCEPT
  2. Allow loopback and conntrack ESTABLISHED. These two rules account for ~80% of legitimate inbound packets on a typical server.

    iptables -A INPUT -i lo -j ACCEPT
    iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
    iptables -A INPUT -m conntrack --ctstate INVALID -j DROP
  3. Permit ICMPv4 with rate limit. Echo requests should not be blanket-blocked; rate-limit them instead.

    iptables -A INPUT -p icmp --icmp-type echo-request \
      -m limit --limit 30/sec --limit-burst 60 -j ACCEPT
    iptables -A INPUT -p icmp --icmp-type destination-unreachable -j ACCEPT
    iptables -A INPUT -p icmp --icmp-type time-exceeded -j ACCEPT
  4. Allow SSH with brute-force protection. Use the recent module to throttle new SSH connections per source.

    iptables -A INPUT -p tcp --dport 22 -m conntrack --ctstate NEW \
      -m recent --set --name ssh-bf
    iptables -A INPUT -p tcp --dport 22 -m conntrack --ctstate NEW \
      -m recent --update --seconds 60 --hitcount 6 --name ssh-bf -j DROP
    iptables -A INPUT -p tcp --dport 22 -j ACCEPT
  5. Allow public services. Anything client-facing — usually 80/443 — goes here.

    iptables -A INPUT -p tcp -m multiport --dports 80,443 -j ACCEPT
  6. Log and drop the rest. Logging is rate-limited so an attack does not flood dmesg.

    iptables -A INPUT -m limit --limit 5/min -j LOG --log-prefix "iptables-drop: " --log-level 4
    iptables -A INPUT -j DROP
    iptables -P INPUT DROP
  7. Persist. On Debian/Ubuntu, netfilter-persistent save writes to /etc/iptables/rules.v4. On RHEL-family, iptables-save > /etc/sysconfig/iptables and enable iptables.service. Either way the script that produced the rules should also be in git.

Operational notes

  • Order inside a chain matters. First match wins. A blanket DROP before a port-specific ACCEPT will silently break the service; counters on iptables -L -v confirm whether traffic ever reached the intended rule.
  • -m conntrack vs -m state. The older state module is an alias; new rules should use conntrack. They compose the same way but conntrack exposes more match keys (ctorigsrc, ctorigdst, ctdir).
  • conntrack table size is finite. A busy server hits nf_conntrack: table full, dropping packet if nf_conntrack_max is too low — see the conntrack tuning article.
  • NOTRACK for very high traffic. DNS responders and stateless DDoS scrubbers benefit from raw/PREROUTING -j NOTRACK to skip conntrack entirely; you lose ESTABLISHED tracking for those flows in exchange for throughput.
  • Containers add hidden rules. Docker, Kubernetes kube-proxy, and Podman insert their own chains; review iptables -L -t nat before assuming your filter rules are the only thing standing between the host and the network.

In the engagements we run, the rules above sit in an Ansible role that ships with every server we operate. The shape stays the same across estates — loopback, conntrack, ICMP, SSH-with-throttle, declared public services, logged DROP — and what changes between clients is the list of public ports and the source restrictions. Migrating mature estates to nftables is on our roadmap, but iptables remains the production baseline, and the operating model is documented in the managed-operations practice.