SkillPilotAI

nft (nftables) (1/4)

nft is the command-line tool of Linux nftables, which replaces iptables, ip6tables, arptables and ebtables. This part covers hooks, command-line options, file syntax, tables, chains, rules, sets, maps, elements and flowtables, all tested on a real server with policy drop.

100.1 What it is and where it runs

  • One tool replaces iptables, ip6tables, arptables and ebtables.
  • Linux: nftables package, default since Debian 10 and RHEL 8; Windows/macOS: not native, use a Linux VM or WSL.
  • Structure: ruleset -> table -> chain -> rule.
  • Lab: server 192.168.120.80 (nftables 1.0.9), normal PC 192.168.120.10, admin PC 192.168.120.20.

100.2 How it works: hooks

Where a packet gets checked
  1. 1.Packet from PC 192.168.120.10 enters the prerouting hook

  2. 2.Routing decision: is it for this host?

  3. 3.Yes: input hook -> local app (sshd, nginx)

  4. 4.No: forward hook -> postrouting -> out

  5. 5.Local replies: output hook -> postrouting -> out

Base chains attach at exactly these hooks

HookSees
preroutingAll incoming, before routing
inputPackets delivered to the local system
forwardPackets forwarded to another host
outputPackets sent by local processes
postroutingEverything leaving
ingress (inet / netdev)Before L3 / right after tc ingress; needs a device
egress (netdev)Before tc egress; needs a device
arp input / outputARP received / sent

100.3 Ruleset file: include and variables

Output
include "/etc/n100/vars.nft"flush rulesettable inet filter { set admins {  type ipv4_addr  elements = { $ADMIN } } chain input {  type filter hook input priority filter  policy drop  icmp type echo-request counter accept  ip saddr @admins tcp dport 22 counter accept  tcp dport $WEB counter accept }}
Output
$ cat /etc/n100/vars.nftdefine ADMIN = 192.168.120.20define WEB = { 80, 443 }$ nft -f /etc/n100/rules.nft$ nft list rulesettable inet filter {  set admins {    type ipv4_addr    elements = { 192.168.120.20 }  }  chain input {    type filter hook input priority filter; policy drop;    icmp type echo-request counter packets 0 bytes 0 accept    ip saddr @admins tcp dport 22 counter packets 0 bytes 0 accept    tcp dport { 80, 443 } counter packets 0 bytes 0 accept  }}
  • include loads another file (wildcards like dir/*.nft load in A-Z order); define creates a variable used as $V; redefine / undefine change or remove it.
  • flush ruleset at the top makes the file replace everything.
  • The listing shows real values in place of the variables.

100.4 Command-line options: input, check, optimize

Terminal
nft -vnft -c -f /etc/n100/bad.nftnft -c -f /etc/n100/dvar.nftnft -D LAN_IF=eth0 -c -f /etc/n100/dvar.nftnft -c -o -f /etc/n100/opt.nft 2>&1 | cat
Output
$ nft -vnftables v1.0.9 (Old Doc Yak #3)$ nft -c -f /etc/n100/bad.nft/etc/n100/bad.nft:3:9-13: Error: syntax error, unexpected string    tcp dprot 22 accept        ^^^^^$ nft -c -f /etc/n100/dvar.nft/etc/n100/dvar.nft:3:14-19: Error: unknown identifier 'LAN_IF'    iifname $LAN_IF tcp dport 22 accept             ^^^^^^$ nft -D LAN_IF=eth0 -c -f /etc/n100/dvar.nft(exit 0: OK)$ nft -c -o -f /etc/n100/opt.nft 2>&1 | catMerging:/etc/n100/opt.nft:3:5-23:     tcp dport 80 accept/etc/n100/opt.nft:4:5-24:     tcp dport 443 accept/etc/n100/opt.nft:5:5-25:     tcp dport 8080 acceptinto:  tcp dport { 80, 443, 8080 } accept
OptionMeaning
-f FILE / -f -Load ruleset from a file / stdin
-cCheck only, do not apply (shows line:column of errors)
-D N=VDefine a variable for the file
-o / -c -oOptimize while loading / only show optimizations
-i / -I DIRInteractive CLI / include search directory
-a, -s, -tShow handles, omit counters, omit set elements
-n, -S, -N, -yFully numeric, port -> service name, reverse DNS (slow), numeric priority
-e, -j, -d LEVELEcho changes, JSON output, debug (netlink, eval, all...)

100.5 Practical: traffic against policy drop

Terminal
nc -zv -w 2 192.168.120.80 22   # adminnc -zv -w 2 192.168.120.80 22   # pcnc -zv -w 2 192.168.120.80 80   # pcping -c 2 -W 1 192.168.120.80   # pcnft list chain inet filter input
Output
admin$ nc -zv -w 2 192.168.120.80 22Connection to 192.168.120.80 22 port [tcp/ssh] succeeded!pc$ nc -zv -w 2 192.168.120.80 22nc: connect to 192.168.120.80 port 22 (tcp) timed out: Operation in progresspc$ nc -zv -w 2 192.168.120.80 80Connection to 192.168.120.80 80 port [tcp/http] succeeded!pc$ ping -c 2 -W 1 192.168.120.80 | tail -22 packets transmitted, 2 received, 0% packet loss, time 1008msrtt min/avg/max/mdev = 0.130/0.134/0.138/0.004 ms$ nft list chain inet filter inputtable inet filter {  chain input {    type filter hook input priority filter; policy drop;    icmp type echo-request counter packets 2 bytes 168 accept    ip saddr @admins tcp dport 22 counter packets 4 bytes 204 accept    tcp dport { 80, 443 } counter packets 4 bytes 204 accept  }}

Admin SSH matches ip saddr @admins and is accepted; the normal PC's SSH matches nothing and policy drop silently drops it; port 80 and ping are accepted by their rules.

100.6 Address families and tables

FamilySees
ipIPv4 (default family)
ip6IPv6
inetIPv4 + IPv6 in one table
arpARP packets (input/output hooks)
bridgeFrames passing a bridge device (not compiled in this lab kernel)
netdevDevice ingress/egress, any traffic type
Output
$ nft create table ip t4Error: Could not process rule: File existscreate table ip t4                ^^$ nft add table ip t4(exit 0)$ nft list table inet titable inet ti {  flags dormant}$ nft destroy table ip t4(exit 0)
  • add = OK if it exists; create = error if it exists.
  • delete = error if missing; destroy = no error if missing (works by name or handle).
  • flags dormant disables a table; flush table keeps chains but clears their rules.

100.7 Chains: types, priorities and policies

Terminal
nft add chain inet filter ssh_chknft 'add chain inet filter routed { type  filter hook forward priority filter + 10;  policy drop; }'nft 'add chain ip nat post { type nat hook  postrouting priority srcnat; }'nft -y list chains inetnft rename chain inet filter ssh_chk ssh_innft add rule inet filter input tcp dport \  2222 jump ssh_innft delete chain inet filter ssh_in
Output
$ nft -y list chains inettable inet filter {  chain input {    type filter hook input priority 0; policy drop;  chain out {    type filter hook output priority 0; policy accept;  chain routed {    type filter hook forward priority 10; policy drop;  chain raw1 {    type filter hook prerouting priority -300; policy accept;$ nft delete chain inet filter ssh_inError: Could not process rule: Resource busydelete chain inet filter ssh_in                         ^^^^^^
ItemValues
Base chain vs regular chainWith type/hook/priority = attached to a hook; without hook = only a jump/goto target
type filter / nat / routeAll families and hooks / conntrack NAT (prio > -200) / output re-route (ip, ip6)
Priority names (ip/ip6/inet)raw -300, mangle -150, dstnat -100, filter 0, security 50, srcnat 100
Priority ruleLower number runs first; relative forms like filter + 10 or mangle - 5
Bridge prioritiesdstnat -300, filter -200, out 100, srcnat 300
policyaccept (default) or drop (drop unless accepted)

A chain that is still a jump target cannot be deleted (Resource busy).

100.8 Rules and handles

Terminal
nft -a list chain inet filter inputnft insert rule inet filter input \  ip saddr 192.168.120.66 dropnft add rule inet filter input index 1 \  tcp dport 8080 accept comment \"test port\"nft replace rule inet filter input \  handle 12 tcp dport 8443 acceptnft add rule inet filter input handle 3 \  tcp dport 53 acceptnft delete rule inet filter input handle 99nft destroy rule inet filter input handle 99
Output
$ nft -a list chain inet filter inputtable inet filter {  chain input { # handle 1    type filter hook input priority filter; policy drop;    ip saddr 192.168.120.66 drop # handle 13    icmp type echo-request counter packets 2 bytes 168 accept # handle 3    tcp dport 53 accept # handle 15    tcp dport 8080 accept comment "test port" # handle 14    ip saddr @admins tcp dport 22 counter packets 4 bytes 204 accept # handle 4    tcp dport { 80, 443 } counter packets 4 bytes 204 accept # handle 6    tcp dport 8443 accept # handle 12  }}$ nft delete rule inet filter input handle 99Error: Could not process rule: No such file or directorydelete rule inet filter input handle 99                                     ^^$ nft destroy rule inet filter input handle 99(exit 0)
  • -a shows each rule's handle: its permanent address for edits.
  • add = end of chain (or after handle/index N); insert = start (or before handle/index N); replace ... handle N swaps a rule.
  • reset rule ... handle N zeroes one rule's counters; reset rules does a whole chain.

100.9 Sets, maps and elements

Terminal
nft 'add set inet filter blocklist { type  ipv4_addr; flags interval; auto-merge;  comment "bad hosts"; }'nft 'add set inet filter ban { type ipv4_addr;  flags timeout; timeout 1h; size 1024; }'nft insert rule inet filter input \  ip saddr @blocklist counter dropnft add element inet filter blocklist { \  192.168.120.8-192.168.120.9, \  192.168.120.10 }nft add element inet filter ban { \  192.168.120.66 timeout 30m \  comment \"scanner\" }
Output
$ nft list set inet filter blocklist  set blocklist {    elements = { 192.168.120.8-192.168.120.10 }pc$ nc -zv -w 2 192.168.120.80 80nc: connect to 192.168.120.80 port 80 (tcp) timed out: Operation in progress$ nft list chain inet filter input | grep blocklist    ip saddr @blocklist counter packets 2 bytes 120 drop$ nft list set inet filter ban  set ban {    timeout 1h    elements = { 192.168.120.66 timeout 30m expires 29m57s276ms comment "scanner" }
  • A named set is matched with @name; an anonymous set { a, b } is fixed and cannot be updated later.
  • flags interval holds ranges; auto-merge joined .8-.9 and .10 into one range.
  • flags timeout + timeout 1h: elements expire; a per-element timeout 30m overrides it.
  • typeof ip saddr . tcp dport builds a concatenated IP . port key.
  • With the PC in the blocklist even port 80 timed out (drop rule is on top); after deleting the element it worked again.
  • Deleting a set still used by a rule gives Resource busy.
Terminal
nft 'add map inet filter portv { type  inet_service : verdict; elements = {  80 : accept, 23 : drop }; }'nft 'add map inet filter backend { type  inet_service : ipv4_addr; elements = {  80 : 192.168.120.81 }; }'nft add rule inet filter input \  tcp dport vmap @portvnft get element inet filter portv { 23 }
Output
$ nft list map inet filter backend  map backend {    type inet_service : ipv4_addr    elements = { 80 : 192.168.120.81, 443 : 192.168.120.82 }$ nft get element inet filter portv { 23 }  map portv {    type inet_service : verdict    elements = { 23 : drop }
  • A map stores key : value; a verdict map (vmap) gives the verdict in one lookup.
  • A port -> IP map (backend) is useful later for DNAT.
  • Element commands: add, create (error if exists), delete, destroy, get, reset; per-element timeout, expires, comment.

100.10 Ruleset commands, output formats and flowtables

Output
$ nft list ruleset > /etc/n100/saved.nft; wc -l /etc/n100/saved.nft60 /etc/n100/saved.nft$ nft flush ruleset; nft list ruleset | wc -l0pc$ nc -zv -w 2 192.168.120.80 22Connection to 192.168.120.80 22 port [tcp/ssh] succeeded!$ nft -f /etc/n100/saved.nft; nft list tablestable inet filtertable arp tatable ip natpc$ nc -zv -w 2 192.168.120.80 22nc: connect to 192.168.120.80 port 22 (tcp) timed out: Operation in progress$ nft -e add rule inet filter input tcp dport 8080 acceptadd rule inet filter input tcp dport 8080 accept# new generation 53 by process 23592 (nft)$ nft -d netlink list tablesinet filter input 19  [ meta load nfproto => reg 1 ]  [ cmp eq reg 1 0x00000002 ]  [ payload load 4b @ network header + 12 => reg 1 ]  [ lookup reg 1 set blocklist 0x0 ]  [ counter pkts 2 bytes 120 ]  [ immediate reg 0 drop ]
  • list ruleset > file is a backup (like iptables-save); nft -f file restores it atomically.
  • flush ruleset removes everything: the firewall is off until you reload.
  • -j gives JSON for automation; -d netlink shows the kernel bytecode of each rule.
  • Flowtable: a software fast path where established flows skip the forward chain (flow add @ft); not compiled in this WSL kernel (CONFIG_NF_FLOW_TABLE is not set).

100.11 Common mistakes

  • Putting an accept above a blocklist drop: the first matching verdict is final, top to bottom.
  • Thinking iptables and nftables are separate firewalls: iptables -V shows (nf_tables) and Docker's iptables rule appears in nft list chain ip nat OUTPUT; both write to the same engine.
  • Loading a file without nft -c first.
  • Running flush ruleset on a remote box without a reload plan.
  • Deleting a chain or set that a rule still references (Resource busy).

100.12 Interview tips

  • nftables vs iptables: one tool for all families (ip, ip6, inet, arp, bridge, netdev); an inet table covers IPv4 and IPv6.
  • Sets and maps are built in: thousands of IPs match in one lookup; vmap gives a verdict in one lookup.
  • nft -f loads atomically: all or nothing.
  • A base chain has type, hook, priority and policy; lower priority runs first.
  • Edit rules by handle (nft -a), check files with nft -c.