TExcelTAD
Home › Linux Server Administration › Netfilter & iptables Concepts

Netfilter & iptables Concepts

Every Linux firewall tool (iptables, nftables, ufw, firewalld, Docker's port publishing, Kubernetes' kube-proxy) is a front end to the same kernel subsystem: netfilter. Firewalls & ACLs covered rule evaluation in general; this lesson maps it onto the Linux kernel, so the tools in the next two lessons make sense. Changing a host firewall needs root and CAP_NET_ADMIN, so commands here are sample sessions and the logic is shown with a runnable model.

Hooks: where a packet meets the rules

Netfilter offers hooks at fixed points of the kernel's packet path. Rules are attached to chains, and chains to hooks:

text
 incoming packet                                                  outgoing packet
      │                                                                 ▲
      ▼                                                                 │
 PREROUTING ──► routing decision ──► FORWARD ──────────────────► POSTROUTING
 (DNAT)            │   (for another host: routers, Docker bridges)    (SNAT, masquerade)
                   ▼                                                    ▲
                 INPUT ──► local process (nginx, sshd) ──► OUTPUT ──────┘
Hook Sees Typical use on a server
INPUT packets addressed to this host the host firewall: which ports are reachable
OUTPUT packets created on this host egress restrictions (rare on servers, common in hardened setups)
FORWARD packets routed through the host routers, VPN gateways, containers behind a bridge
PREROUTING everything, before routing DNAT: port forwarding, Docker's -p 8080:80
POSTROUTING everything, after routing SNAT/masquerade: containers or a private network reaching the internet

The detail that surprises people: traffic to a published Docker port is DNATed in PREROUTING and then goes through FORWARD, not INPUT. A host firewall that only filters INPUT (which is what ufw's simple rules do) doesn't see it. Docker documents this; its DOCKER-USER chain is where your own restrictions for container traffic belong.

Tables and chains in iptables terms

iptables groups chains into tables by purpose: filter (accept/drop: INPUT, FORWARD, OUTPUT), nat (PREROUTING, OUTPUT, POSTROUTING), mangle (packet marks) and raw (before connection tracking). Each built-in chain has a policy: what happens when no rule matches.

bash
# Sample session: a minimal host firewall with iptables (legacy syntax, still everywhere in docs)
$ sudo iptables -P INPUT DROP
$ sudo iptables -A INPUT -i lo -j ACCEPT
$ sudo iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
$ sudo iptables -A INPUT -m conntrack --ctstate INVALID -j DROP
$ sudo iptables -A INPUT -p tcp --dport 22 -j ACCEPT
$ sudo iptables -A INPUT -p tcp -m multiport --dports 80,443 -j ACCEPT
$ sudo iptables -A INPUT -p icmp -j ACCEPT
$ sudo iptables -L INPUT -n -v --line-numbers
Chain INPUT (policy DROP 1532 packets, 81240 bytes)
num   pkts bytes target     prot opt in     out     source               destination
1      210 15890 ACCEPT     all  --  lo     *       0.0.0.0/0            0.0.0.0/0
2     8841 9.1M ACCEPT     all  --  *      *       0.0.0.0/0            0.0.0.0/0            ctstate RELATED,ESTABLISHED
3        0     0 DROP       all  --  *      *       0.0.0.0/0            0.0.0.0/0            ctstate INVALID
4       12   720 ACCEPT     tcp  --  *      *       0.0.0.0/0            0.0.0.0/0            tcp dpt:22
5      301 18060 ACCEPT     tcp  --  *      *       0.0.0.0/0            0.0.0.0/0            multiport dports 80,443
6        4   336 ACCEPT     icmp --  *      *       0.0.0.0/0            0.0.0.0/0

On current distributions the iptables command is usually iptables-nft: the same syntax, translated into nftables rules in the kernel (iptables -V prints (nf_tables)). Mixing it with hand-written nft rules works but is confusing to debug; pick one front end per host.

Connection tracking: why rule 2 matters

Netfilter's conntrack remembers every connection. A packet is NEW (first packet of a connection), ESTABLISHED (part of a known connection, in either direction), RELATED (an associated flow, such as an ICMP error about a known connection) or INVALID. Accepting ESTABLISHED,RELATED first means:

  • replies to connections the server itself opened (DNS lookups, apt update, calls to a database) come back in, although no rule opens those ports;
  • most packets match the first rules, so long rule lists stay cheap;
  • only NEW packets need port rules.

This model walks packets through such a chain. Everything is first-match-wins, with the policy as the fallback:

python · try it yourself
RULES = [  # (description, match function, verdict)
    ("loopback",            lambda p: p["iface"] == "lo",                      "ACCEPT"),
    ("established/related", lambda p: p["state"] in ("ESTABLISHED", "RELATED"), "ACCEPT"),
    ("invalid",             lambda p: p["state"] == "INVALID",                 "DROP"),
    ("ssh from office",     lambda p: p["dport"] == 22 and p["src"].startswith("198.51.100."), "ACCEPT"),
    ("web",                 lambda p: p["dport"] in (80, 443),                 "ACCEPT"),
]
POLICY = "DROP"

def verdict(p):
    for i, (name, match, action) in enumerate(RULES, 1):
        if match(p):
            return f"{action:<6} by rule {i} ({name})"
    return f"{POLICY:<6} by policy"

packets = [
    {"src": "203.0.113.7",  "iface": "eth0", "dport": 22,   "state": "NEW"},
    {"src": "198.51.100.4", "iface": "eth0", "dport": 22,   "state": "NEW"},
    {"src": "192.0.2.10",   "iface": "eth0", "dport": 443,  "state": "NEW"},
    {"src": "9.9.9.9",      "iface": "eth0", "dport": 41872, "state": "ESTABLISHED"},  # a DNS reply
    {"src": "192.0.2.10",   "iface": "eth0", "dport": 5432, "state": "NEW"},
    {"src": "127.0.0.1",    "iface": "lo",   "dport": 5432, "state": "NEW"},
]
for p in packets:
    print(f"{p['src']:>13} -> :{p['dport']:<5} {p['state']:<11} {verdict(p)}")
  203.0.113.7 -> :22    NEW         DROP   by policy
 198.51.100.4 -> :22    NEW         ACCEPT by rule 4 (ssh from office)
   192.0.2.10 -> :443   NEW         ACCEPT by rule 5 (web)
      9.9.9.9 -> :41872 ESTABLISHED ACCEPT by rule 2 (established/related)
   192.0.2.10 -> :5432  NEW         DROP   by policy
    127.0.0.1 -> :5432  NEW         ACCEPT by rule 1 (loopback)

The DNS reply on a random high port is accepted only thanks to conntrack; PostgreSQL is reachable from the host itself (loopback) but not from outside. Drop the established/related rule and the server can no longer resolve names or download updates, a classic self-inflicted outage.

DROP or REJECT?

DROP discards silently: the client waits until it times out. REJECT answers with a TCP reset or an ICMP error, so the client fails at once. For the public internet, DROP on the policy is common (it gives scanners nothing); inside your own network, REJECT makes misconfigurations fail fast and saves colleagues minutes of staring at a hanging curl. You can tell them apart from the client: a hang is DROP (or routing), "Connection refused" is a REJECT or a closed port (Network Troubleshooting).

Test yourself

Traffic to a Docker container published with -p 8080:80 is not blocked by an INPUT rule. Why?

  1. Docker disables the firewall
  2. The packets are DNATed in PREROUTING and then pass the FORWARD chain, not INPUT
  3. Port 8080 is always open
  4. Containers use UDP

Why is ESTABLISHED,RELATED → ACCEPT usually the first rule after loopback?

  1. It is required by iptables
  2. Replies to connections the host opened (DNS, updates) come back in, and most packets are decided by one cheap rule
  3. It blocks port scans
  4. It enables NAT

A client's connection attempt hangs for 30 seconds before failing. Which is more likely on the server side?

  1. REJECT
  2. DROP (or a routing problem)
  3. ACCEPT
  4. A full disk