TExcelTAD

nftables

nftables is the current Linux packet filter: one tool (nft) for IPv4, IPv6, ARP and bridges, a real configuration language with sets and maps, and atomic rule-set replacement. Debian, Ubuntu and RHEL use it underneath their firewall front ends. Loading rules needs root and CAP_NET_ADMIN (even nft -c, the check mode, talks to the kernel), so the nft transcripts below are sample sessions from an Ubuntu 24.04 server; the rule-set logic is checked with a runnable model.

A complete host firewall in one file

nft
#!/usr/sbin/nft -f
# /etc/nftables.conf: loaded at boot by nftables.service
flush ruleset

define ADMIN_NETS = { 198.51.100.0/24, 10.8.0.0/16 }

table inet filter {                       # "inet" = IPv4 and IPv6 together
    set web_ports { type inet_service; elements = { 80, 443 } }

    set blocklist {
        type ipv4_addr
        flags interval, timeout
        elements = { 203.0.113.0/24 timeout 1d }
    }

    chain input {
        type filter hook input priority filter; policy drop;

        iif "lo" accept
        ct state established,related accept
        ct state invalid drop
        ip saddr @blocklist drop

        meta l4proto { icmp, ipv6-icmp } accept          # ping, PMTU discovery, IPv6 neighbour discovery
        tcp dport 22 ip saddr $ADMIN_NETS ct state new limit rate 10/minute accept
        tcp dport @web_ports accept

        counter log prefix "nft-drop: " level info limit rate 5/second
    }

    chain forward {
        type filter hook forward priority filter; policy drop;
    }

    chain output {
        type filter hook output priority filter; policy accept;
    }
}

Compared with iptables:

iptables nftables
fixed tables and chains you create tables and chains, and attach base chains to hooks (type filter hook input priority filter)
separate iptables and ip6tables table inet covers both
one rule per port, or -m multiport anonymous sets { 80, 443 } and named sets you can update at run time
-m conntrack --ctstate ct state
-j LOG then -j DROP several statements in one rule: counter log … drop
rule-by-rule changes nft -f file replaces the whole rule set atomically

ICMP is accepted on purpose: blocking it breaks Path MTU discovery (connections that hang on large responses) and IPv6, which needs ICMPv6 to work at all.

Loading, checking and inspecting

bash
$ sudo nft -c -f /etc/nftables.conf          # check: parse and validate against the kernel, change nothing
$ sudo nft -f /etc/nftables.conf             # apply atomically: all or nothing
$ sudo systemctl enable --now nftables       # load it at every boot
$ sudo nft list chain inet filter input
table inet filter {
	chain input {
		type filter hook input priority filter; policy drop;
		iif "lo" accept
		ct state established,related accept
		ct state invalid drop
		ip saddr @blocklist drop
		meta l4proto { icmp, ipv6-icmp } accept
		tcp dport 22 ip saddr { 10.8.0.0/16, 198.51.100.0/24 } ct state new limit rate 10/minute burst 5 packets accept
		tcp dport @web_ports accept
		counter packets 1834 bytes 96312 log prefix "nft-drop: " level info limit rate 5/second burst 5 packets
	}
}
$ sudo nft add element inet filter blocklist '{ 192.0.2.66 timeout 2h }'
$ sudo nft list set inet filter blocklist
table inet filter {
	set blocklist {
		type ipv4_addr
		flags interval,timeout
		elements = { 192.0.2.66 timeout 2h expires 1h59m58s, 203.0.113.0/24 timeout 1d expires 23h41m12s }
	}
}
$ journalctl -k --grep nft-drop -n 1 --no-pager
Jan 15 10:31:04 web1 kernel: nft-drop: IN=eth0 OUT= SRC=203.0.113.50 DST=10.0.0.21 PROTO=TCP SPT=51234 DPT=3306 SYN

Named sets are what fail2ban and similar tools update: adding an address to blocklist blocks it immediately, without touching the rules. nft list ruleset > /etc/nftables.conf saves the live state back to the file.

A pre-flight check before you apply

The sandbox can't run nft, but the most dangerous mistake is not a syntax error, it is a correct rule set that locks you out: policy drop on input without an SSH rule that matches your address. A small check like this model belongs in the script that deploys firewall rules; it reads the input chain and tests whether a given admin address still reaches port 22:

python · try it yourself
import ipaddress, re

RULESET = """
define ADMIN_NETS = { 198.51.100.0/24, 10.8.0.0/16 }
chain input {
    type filter hook input priority filter; policy drop;
    iif "lo" accept
    ct state established,related accept
    tcp dport 22 ip saddr $ADMIN_NETS ct state new accept
    tcp dport { 80, 443 } accept
}
"""

def admin_nets(text):
    m = re.search(r"define ADMIN_NETS = \{([^}]*)\}", text)
    return [ipaddress.ip_network(n.strip()) for n in m.group(1).split(",")]

def ssh_reachable(text, my_ip):
    policy = re.search(r"policy (\w+);", text).group(1)
    for line in text.splitlines():
        if "tcp dport 22" in line and line.strip().endswith("accept"):
            if "$ADMIN_NETS" not in line:
                return True, "port 22 open to everyone"
            ip = ipaddress.ip_address(my_ip)
            if any(ip in net for net in admin_nets(text)):
                return True, "matched ADMIN_NETS"
    return policy == "accept", f"no SSH rule matches, policy {policy}"

for me in ("198.51.100.23", "10.8.4.2", "192.0.2.15"):
    ok, why = ssh_reachable(RULESET, me)
    print(f"{me:>14}: {'OK  ' if ok else 'LOCKOUT'} ({why})")
 198.51.100.23: OK   (matched ADMIN_NETS)
      10.8.4.2: OK   (matched ADMIN_NETS)
    192.0.2.15: LOCKOUT (no SSH rule matches, policy drop)

If you administer from 192.0.2.15, applying this file ends your session (well, not the current one: it is established, but the next login). Real deployments add a dead man's switch: apply the new rules, and automatically restore the old ones unless you confirm within a few minutes.

bash
# Sample session: apply with automatic rollback after 2 minutes unless confirmed
$ sudo nft list ruleset > /root/nft-before.conf
$ sudo systemd-run --on-active=2min --unit=nft-rollback /usr/sbin/nft -f /root/nft-before.conf
Running timer as unit: nft-rollback.timer
Will run service as unit: nft-rollback.service
$ sudo nft -f /etc/nftables.conf
$ # open a NEW ssh session from your workstation; if it works:
$ sudo systemctl stop nft-rollback.timer

(The saved rule set should start with flush ruleset for the rollback to replace, not append; nft list ruleset output doesn't include it, so add it to the file.) firewalld has the same idea built in with --timeout, and many cloud consoles let you fix a lockout through a serial console, but only if you know where it is beforehand.

Go further: Rule Order, Shadowing and Redundancy finds rules that can never match, and Reading and Writing nftables Rulesets reviews a ruleset as an assessor.

Test yourself

What does table inet filter mean in nftables?

  1. Only IPv4
  2. A table whose chains handle both IPv4 and IPv6
  3. Internet-facing interfaces only
  4. The NAT table

Why is nft -f file safer than adding rules one by one?

  1. It's faster to type
  2. The whole file is applied atomically: either every rule is loaded or none, so there is no half-applied state
  3. It skips validation
  4. It doesn't need root

Why should a host firewall accept ICMP (at least the needed types)?

  1. For fun
  2. Path MTU discovery and IPv6 neighbour discovery depend on it; blocking it causes hanging connections and broken IPv6
  3. ICMP carries SSH
  4. nftables requires it