18.1. Understanding Linux Packet Filtering
Netfilter is not a program but a set of well-defined points in the kernel's network stack - hooks - where registered code can inspect every packet and return a verdict for it. Userspace tools do not filter anything themselves: they compile rules and hand them to the kernel, which keeps them and applies them at the hooks. Two consequences follow, and both shape this chapter. First, filtering survives the exit of any tool; a ruleset loaded once keeps working until something replaces or flushes it. Second, every tool that speaks to the same hooks edits the same kernel state, so mixing tools carelessly on one host produces one ruleset with two authors.
18.1.1. Netfilter Hooks, Tables, Chains, and Rule Order
Start on fwclient, in a root shell ($ sudo -i, then work as #).
Confirm the tool and look at what is loaded:
# nft --version
nftables v1.1.3 (Commodore Bullmoose #4)
# nft list ruleset
The second command's empty output is the answer, not a failure: on a
freshly installed Debian 13 nothing has registered any rules, so every
packet is accepted. nft reads the whole ruleset - every table, chain,
set and counter in every family - and prints nothing when there is
none. The nft options used in this chapter, and two more that
matter for scripted or abbreviated listings:
nft option |
Description |
|---|---|
-c |
Check the input only; validate syntax and semantics without applying anything. |
-f file |
Read commands from file instead of the command line. |
-a |
Show object handles with listings; needed to delete rules by handle. |
-j |
JSON output for scripts that parse listings. |
-s |
Stateless output: omit counters and other stateful details from listings. |
Figure 18.1 shows the hooks a packet can pass through and where the chapter's chains attach. Two paths matter on a host - input for traffic addressed to the machine, output for traffic it generates - and one more on a router, forward, for traffic that merely transits.
Figure 18.1. A conceptual map of the netfilter path: prerouting sees everything that arrives, the routing decision splits local delivery from forwarding, and postrouting sees everything that leaves. Base chains attach to one hook each; the priorities shown are the ones this chapter's rulesets use.
A table is a named container for chains, sets and counters, and it
belongs to a family: ip, ip6, arp, bridge, netdev, or the
dual-stack inet family that matches both IPv4 and IPv6. A base
chain is attached to one hook with a priority; a regular chain has
no hook and is reached only when a rule jumps to it. Priority orders
base chains at the same hook - lower numbers run first - and nftables
gives the conventional points names:
| Priority name (number) | Hook where it is used | What runs there |
|---|---|---|
dstnat (-100) |
prerouting, output | Destination NAT: rewriting where a packet is going. |
filter (0) |
input, forward, output | Filtering decisions; the default home of accept and drop rules. |
srcnat (100) |
postrouting | Source NAT: rewriting who a packet appears to come from. |
mangle (-150) |
any | Early marking and header adjustment, ahead of NAT decisions. |
raw (-300) |
prerouting, output | Work before connection tracking, such as selecting flows to exclude from it. |
Within a chain, rules are evaluated top to bottom and the first
matching rule wins: its verdict - accept, drop, jump, or another -
takes effect immediately, and nothing later in the chain runs. A short
demonstration makes the rule order visible with named counters. On
fwclient, as john, create ~/debian-handbook/firewall/order.nft:
table inet orderdemo {
counter first_hit {}
counter second_hit {}
chain input {
type filter hook input priority -150; policy accept;
iifname "eth1" icmp type echo-request counter name first_hit accept
iifname "eth1" icmp type echo-request counter name second_hit drop
}
}
The table declares two named counters and one base chain at the input
hook. Both rules match exactly the same traffic - ICMP echo requests
arriving on eth1 - but the first accepts and the second drops, and
they count into separate objects. Back in the root shell, load the
file; nft -f prints nothing when it succeeds:
# nft -f /home/john/debian-handbook/firewall/order.nft
On fwrouter, as john, send two echo requests to fwclient over the
LAN:
$ ping -c 2 192.168.218.10
PING 192.168.218.10 (192.168.218.10) 56(84) bytes of data.
64 bytes from 192.168.218.10: icmp_seq=1 ttl=64 time=0.414 ms
64 bytes from 192.168.218.10: icmp_seq=2 ttl=64 time=0.308 ms
--- 192.168.218.10 ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 1014ms
rtt min/avg/max/mdev = 0.308/0.361/0.414/0.053 ms
Both replies came back - so the drop rule never ran. On fwclient,
in the root shell, read the counters:
# nft list table inet orderdemo
table inet orderdemo {
counter first_hit {
packets 2 bytes 168
}
counter second_hit {
packets 0 bytes 0
}
chain input {
type filter hook input priority mangle; policy accept;
iifname "eth1" icmp type echo-request counter name "first_hit" accept
iifname "eth1" icmp type echo-request counter name "second_hit" drop
}
}
first_hit counted both packets and second_hit counted nothing: the
first matching rule ended the evaluation, exactly as the replies
already showed. The listing also displays the numeric priority -150
under its conventional name mangle, and shows the chain policy,
accept, which is what happens when no rule matches - here the
policy never came into play because the first rule matched everything
the demo sent. Remove the practice table, which prints nothing:
# nft delete table inet orderdemo
Two lessons carry through the chapter: put the decisive rules first,
because later rules never run for a packet an earlier rule accepted or
dropped; and when a chain's last rule is an explicit drop, a policy of
drop becomes a backstop that logs and counters can sit in front of.
18.1.2. Connection Tracking and Stateful Filtering
Packet-by-packet filtering is easy to write wrong: a rule that allows
replies must somehow distinguish a reply from a new attack, and a rule
that allows anything outbound must not let the responses to it back in.
The kernel solves this with connection tracking: the first packet of
a flow creates an entry that records the flow's endpoints, protocol
state and expected replies, and every later packet of the flow is
classified against that entry. Filter rules can then ask about the
flow rather than the packet, with ct state:
ct state |
Meaning | Typical use |
|---|---|---|
new |
The packet starts a flow the tracker has not seen; for TCP, a packet with SYN set that is not part of an existing flow. | Allow selected services; NAT happens for these packets. |
established |
The packet matches a known flow in a state consistent with its direction. | One rule allows all replies to everything already permitted. |
related |
A new flow that the tracker knows is connected to an existing one - an ICMP error quoting a tracked flow is the common case. | Allow alongside established traffic, or ICMP breaks path-mismatch reporting. |
invalid |
The packet fits no flow: unreadable sequence state, wrong checksums, or no known flow for an ACK. | Drop early; it is almost never wanted. |
The pair ct state established,related accept, placed ahead of
service-specific rules, is the backbone of every ruleset in this
chapter. It lets one inbound SSH-allowance cover the whole session
without opening anything else, and it is what makes the host rulesets
safe to load over an existing SSH connection: the tracked session
matches established immediately, so the ruleset swap does not cut the
wire the change came in on.
Connection tracking also underpins NAT. A NAT decision is recorded in the flow's conntrack entry when the first packet crosses the nat chain, and every later packet of the flow - including all packets of the reply - is translated from that stored entry, without consulting the nat rules again. That is why a masquerading rule is one line and needs no reverse rule, and Section 18.5.2 shows the stored rewriting when reading the tracking table directly. The tracking table is finite; a host under heavy load can hit its limit, and the statistics command shown in Section 18.5.2 is how that failure announces itself.
Flows do not live forever. Each conntrack entry has a timeout that
depends on its state - a TCP connection that has finished sits in
TIME_WAIT for a couple of minutes before the entry is reclaimed, and
an unfinished handshake attempt is dropped after a few retries. Nothing
in this chapter requires tuning those timeouts, but the state names
that appear in tracking listings come from the same state machine.
18.1.3. nftables and Compatibility with iptables Interfaces
The iptables command family is the historical interface to the same
kernel hooks, and most documentation a reader will meet still speaks
its vocabulary - INPUT, FORWARD, -j MASQUERADE. Debian 13 keeps
that vocabulary usable while standardizing on the nftables kernel
backend. The iptables package contains both backends, and
update-alternatives selects which one the iptables command runs;
the default is the nftables one:
# iptables -V
iptables v1.8.11 (nf_tables)
The interfaces available on a Debian 13 host:
| Interface | Backend | Status on Debian 13 | Suited for | Caveats |
|---|---|---|---|---|
nft and /etc/nftables.conf |
native nftables | The default; its service ships disabled | Everything in this chapter; dual-stack rulesets; sets and maps | A newer syntax; older iptables tutorials do not apply directly |
iptables (iptables-nft) |
translates to nftables | Default alternative for the iptables command |
Scripts and documentation written in iptables syntax | Rules land in nftables tables named after the old ones; two tools editing one ruleset invites conflicts |
iptables-legacy |
pre-nftables kernel interface | Available but not the default | Interoperating with software that requires it specifically | A separate ruleset the nft listings do not show; avoid on new systems |
ufw |
front end over iptables-nft | Packaged and supported | Simple single-host policies managed with a handful of commands | Policy expressed through another tool's model; chapter techniques do not apply to its rules directly |
The translation is exact enough to inspect. iptables-translate prints
what an iptables command would become, changing nothing:
# iptables-translate -A INPUT -p tcp --dport 22 -j ACCEPT
nft 'add rule ip filter INPUT tcp dport 22 counter accept'
# iptables-translate -t nat -A POSTROUTING -o eth0 -j MASQUERADE
nft 'add rule ip nat POSTROUTING oifname "eth0" counter masquerade'
The translated rules reveal the mapping: iptables' named tables become
nftables tables (ip filter, ip nat), its built-in chains become
base chains at the same hooks, and iptables' implicit per-rule
accounting becomes an explicit counter. Running a real iptables
command makes the correspondence visible in the live ruleset. In the
root shell on fwclient, create a chain and add one rule to it; both
commands print nothing when they succeed:
# iptables -N demo
# iptables -A demo -p tcp --dport 9999 -j ACCEPT
demo is a regular chain, not attached to a hook, so nothing routes
traffic through it yet - it exists only to be inspected. Ask nft,
not iptables, and the rule appears as a native object:
# nft list chain ip filter demo
table ip filter {
chain demo {
tcp dport 9999 counter packets 0 bytes 0 accept
}
}
One command family created the table ip filter and its chain; the
other family's tool reads it without knowing or caring which command
typed it. Clean up with the same interface that created it; both are
silent:
# iptables -F demo
# iptables -X demo
The compatibility layer is a migration aid, not an invitation to run two policy authors on one host. iptables-nft rules and native nftables rules coexist in the same kernel tables, ordered by chain priority, and each tool hides what it does not understand about the other's objects - an iptables ruleset loaded alongside an inet-family ruleset is two policies interacting in ways neither listing shows completely. Pick one author per host, as Chapter 17 insisted on one configuration owner per interface. This chapter writes native nftables throughout; the one place the two-worlds question becomes unavoidable is a host that runs container or virtualization software, which Section 18.4.4 treats.