TExcelTAD
Home › Network Security: Discovery, Segmentation, Firewalls, VPN & IDS › Reading and Writing nftables Rulesets

Reading and Writing nftables Rulesets

A firewall review is mostly reading. You get an export (nft list ruleset, a file from configuration management) and have to answer: what does this host accept, from whom, and what happens to everything else? This lesson reads a complete host ruleset for the lab web server, now in the DMZ of the redesigned network (10.10.1.10, admins in 10.10.5.0/26, see Zones, DMZs and Trust Boundaries), line by line, checks it for syntax errors the way you would before deploying, and lists what a reviewer looks for. The nftables syntax itself is taught in nftables and introduced for analysts in ss, ip and nftables; here the focus is on the security meaning of each part.

The ruleset

text
#!/usr/sbin/nft -f
flush ruleset

define ADMIN_NET = 10.10.5.0/26
define MONITOR   = 10.10.5.10

table inet host_www {
    set ssh_blocklist {
        type ipv4_addr
        flags timeout
        timeout 1h
    }

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

        ct state established,related accept
        ct state invalid counter drop
        iif "lo" accept

        ip protocol icmp icmp type { echo-request } limit rate 5/second accept
        ip protocol icmp icmp type { destination-unreachable, time-exceeded } accept
        meta l4proto ipv6-icmp icmpv6 type { nd-neighbor-solicit, nd-neighbor-advert, nd-router-advert, echo-request, destination-unreachable, packet-too-big, time-exceeded } accept

        tcp dport { 80, 443 } accept comment "public web"
        ip saddr @ssh_blocklist drop
        ip saddr $ADMIN_NET tcp dport 22 ct state new limit rate 10/minute accept comment "admins via bastion"
        ip saddr $MONITOR tcp dport 9100 accept comment "metrics scrape"

        limit rate 10/second log prefix "www-in-drop: " level info
        counter drop
    }

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

Read it as a reviewer:

Part Meaning Review notes
flush ruleset the file replaces everything, atomically good: no leftovers from earlier rules; but it also flushes other tools' tables (Docker, fail2ban)
define named constants the admin network appears once, so it can't drift between rules
table inet one table for IPv4 and IPv6 good; but ip saddr rules match IPv4 only, so SSH and metrics are IPv4-only (IPv6 admin attempts fall to the drop)
set ssh_blocklist … timeout 1h a dynamic set: addresses added (by a tool or a rule) expire after an hour used by the rule ip saddr @ssh_blocklist drop
hook input priority filter; policy drop; the chain sees packets addressed to this host; anything no rule accepts is dropped default deny: correct
ct state established,related accept replies and related ICMP first, as it should be (Stateless versus Stateful Filtering)
ct state invalid counter drop junk that fits no flow, counted good
iif "lo" accept local processes may talk to each other needed; note it accepts every loopback service
ICMP / ICMPv6 lines ping rate-limited; errors allowed; IPv6 neighbour discovery allowed IPv6 breaks without ND and packet-too-big; dropping all ICMP is a classic mistake that breaks path MTU discovery
tcp dport { 80, 443 } the public service correct for a web server
@ssh_blocklist drop after web blocked sources can still reach the web server intentional? if the blocklist is meant for all services it must come before the web rule
SSH rule only from the admin network, only new connections, at most 10 per minute the rate limit is global, not per source: one noisy admin script can lock other admins out; a per-source meter would be fairer
metrics rule Prometheus node exporter only from the monitoring host good; check the exporter binds only where needed
limit rate 10/second log … log dropped packets, at most 10 per second rate-limited logging protects the disk and the journal during scans (Egress Filtering and Logging)
counter drop explicit final drop with a counter redundant with the policy but gives a counter for "everything else"
chain output … policy accept the server may connect anywhere finding: no egress filtering on a public web server

Syntax checks before deploying

The sandbox can't load rules (no CAP_NET_ADMIN), but nft -c parses and type-checks the whole file first and reports real mistakes before failing on permissions. The session writes the ruleset, then four broken copies with typical mistakes, and prints only the non-permission errors. (When there are no syntax errors, nft goes on to try each statement and fails with "Operation not permitted"; the helper reports that case as "syntax OK".)

bash · try it yourself
cat > www.nft <<'RULES'
#!/usr/sbin/nft -f
flush ruleset
define ADMIN_NET = 10.10.5.0/26
define MONITOR   = 10.10.5.10
table inet host_www {
    set ssh_blocklist {
        type ipv4_addr
        flags timeout
        timeout 1h
    }
    chain input {
        type filter hook input priority filter; policy drop;
        ct state established,related accept
        ct state invalid counter drop
        iif "lo" accept
        ip protocol icmp icmp type { echo-request } limit rate 5/second accept
        ip protocol icmp icmp type { destination-unreachable, time-exceeded } accept
        meta l4proto ipv6-icmp icmpv6 type { nd-neighbor-solicit, nd-neighbor-advert, nd-router-advert, echo-request, destination-unreachable, packet-too-big, time-exceeded } accept
        tcp dport { 80, 443 } accept comment "public web"
        ip saddr @ssh_blocklist drop
        ip saddr $ADMIN_NET tcp dport 22 ct state new limit rate 10/minute accept comment "admins via bastion"
        ip saddr $MONITOR tcp dport 9100 accept comment "metrics scrape"
        limit rate 10/second log prefix "www-in-drop: " level info
        counter drop
    }
    chain output {
        type filter hook output priority filter; policy accept;
    }
}
RULES
check() {
  local out; out=$(nft -c -f "$1" 2>&1)
  if ! grep 'Error:' <<<"$out" | grep -vq 'Operation not permitted'; then
    echo "$1: syntax OK (loading it needs CAP_NET_ADMIN)"; return
  fi
  awk '/Error:/ && !/Operation not permitted/ {n=3} n-- > 0' <<<"$out"
}
sed 's/accept comment "public web"/acept comment "public web"/' www.nft > typo.nft
sed 's/\$ADMIN_NET/$ADMINS/'                                  www.nft > undefined.nft
sed 's/type ipv4_addr/type ipv4_address/'                      www.nft > badtype.nft
sed 's|define MONITOR   = 10.10.5.10|define MONITOR   = 10.10.5.300|' www.nft > badaddr.nft
for f in www.nft typo.nft undefined.nft badtype.nft badaddr.nft; do echo "== $f"; check $f; done
== www.nft
www.nft: syntax OK (loading it needs CAP_NET_ADMIN)
== typo.nft
typo.nft:19:37-43: Error: syntax error, unexpected comment
        tcp dport { 80, 443 } acept comment "public web"
                                    ^^^^^^^
== undefined.nft
undefined.nft:21:19-24: Error: unknown identifier 'ADMINS'; did you mean identifier ‘ADMIN_NET’?
        ip saddr $ADMINS tcp dport 22 ct state new limit rate 10/minute accept comment "admins via bastion"
                  ^^^^^^
== badtype.nft
badtype.nft:7:14-25: Error: unknown datatype ipv4_address
        type ipv4_address
             ^^^^^^^^^^^^
badtype.nft:6:9-21: Error: set definition does not specify key
    set ssh_blocklist {
        ^^^^^^^^^^^^^
badtype.nft:20:18-31: Error: No such file or directory; did you mean set ‘ssh_blocklist’ in table inet ‘host_www’?
        ip saddr @ssh_blocklist drop
                 ^^^^^^^^^^^^^^
== badaddr.nft
badaddr.nft:4:20-30: Error: Could not resolve hostname: Name or service not known
define MONITOR   = 10.10.5.300
                   ^^^^^^^^^^^

Four kinds of mistakes, four precise messages with the line and the column: a misspelt verdict, an undefined variable (with a suggestion), an unknown data type (which also breaks every rule that uses the set), and an impossible address (10.10.5.300 isn't an IPv4 address, so nft tries to resolve it as a host name and fails; on a host with DNS it might even succeed and silently use whatever the name resolves to, which is why rulesets should never contain host names). Running nft -c in CI before every deployment catches all of them. What it can't catch is a rule that is valid but wrong, such as the blocklist placed after the web rule. That needs review, or a tool that reasons about rule order (Rule Order, Shadowing and Redundancy).

Reading a live ruleset

On a real host with root, the reviewer also needs the counters and the handles (rule identifiers used to delete or insert precisely). Lab session on www.lab.test (read-only commands; scope 10.10.1.10):

console
root@www:~# nft -a list chain inet host_www input
table inet host_www {
	chain input { # handle 1
		type filter hook input priority filter; policy drop;
		ct state established,related accept # handle 4
		ct state invalid counter packets 312 bytes 13104 drop # handle 5
		iif "lo" accept # handle 6
		ip protocol icmp icmp type echo-request limit rate 5/second burst 5 packets accept # handle 7
		ip protocol icmp icmp type { destination-unreachable, time-exceeded } accept # handle 9
		icmpv6 type { destination-unreachable, packet-too-big, time-exceeded, echo-request, nd-router-advert, nd-neighbor-solicit, nd-neighbor-advert } accept # handle 11
		tcp dport { 80, 443 } accept comment "public web" # handle 13
		ip saddr @ssh_blocklist drop # handle 14
		ip saddr 10.10.5.0/26 tcp dport 22 ct state new limit rate 10/minute burst 5 packets accept comment "admins via bastion" # handle 15
		ip saddr 10.10.5.10 tcp dport 9100 accept comment "metrics scrape" # handle 16
		limit rate 10/second burst 5 packets log prefix "www-in-drop: " level info # handle 17
		counter packets 48211 bytes 2604198 drop # handle 18
	}
}
root@www:~# nft list set inet host_www ssh_blocklist
table inet host_www {
	set ssh_blocklist {
		type ipv4_addr
		timeout 1h
		elements = { 198.51.100.23 expires 41m12s }
	}
}

Notice that nft list prints the resolved ruleset: $ADMIN_NET appears as 10.10.5.0/26, a one-element set { echo-request } as a plain value, every limit with its default burst 5 packets, the redundant meta l4proto ipv6-icmp folded into icmpv6 type, and set elements may be reordered. (The transcript's layout follows nftables 1.0.9 loading this file; handle numbers depend on the order objects were created.) Compare the file in version control with this output, not with itself. The final counter, 48,211 dropped packets, is the "everything else" a scan or an attack sends; the log lines say what it was.

How rule changes are detected

  • nft monitor prints rule changes live; configuration management (Ansible, Puppet) re-applies the approved file and reports drift.
  • A periodic job exports nft list ruleset and diffs it with the version in git.
  • Audit rules on the nft binary and on netlink changes (auditd), so manual changes are attributed to a person.

Pitfalls

  • Several tools writing to nftables on one host (Docker, firewalld, fail2ban, a hand-written file): the effective policy is the combination of all their chains, ordered by hook priority. Read nft list ruleset, not just your file.
  • flush ruleset in a file deployed to a host where Docker or Kubernetes manages its own tables: it deletes their rules too.
  • Dropping all ICMPv6: IPv6 stops working in subtle ways.
  • Rate limits without per-source tracking, as in the SSH rule above.

Practice

1. A packet arrives from 198.51.100.23 to port 443. The address is in ssh_blocklist. Is it accepted?

Yes. Rules are checked in order and tcp dport { 80, 443 } accept comes before the blocklist rule. If the blocklist should block everything, move ip saddr @ssh_blocklist drop right after iif "lo" accept.

2. Write the egress rules the output chain is missing for this web server.

Policy drop on output, then ct state established,related accept, oif "lo" accept, DNS to the internal resolvers (ip daddr 10.10.2.53 udp dport 53 accept, same for TCP), the database (ip daddr 10.10.2.30 tcp dport 5432 accept), updates through the proxy only, NTP to the internal servers, logs to the log collector, and a rate-limited log rule before the drop.

3. Rewrite the SSH rule so each source gets its own limit.

ip saddr $ADMIN_NET tcp dport 22 ct state new meter ssh_rate { ip saddr limit rate 10/minute } accept (with a drop or log for the excess falling to later rules). Newer nftables versions prefer a named set with flags dynamic and update @set { ip saddr limit rate 10/minute }.

Test yourself

Why is ct state established,related accept placed first?

  1. It is required by syntax
  2. Most packets belong to existing flows; accepting them first is efficient and lets replies in without opening ports
  3. It blocks scans
  4. It enables logging

What does nft -c -f file do?

  1. Loads the rules
  2. Parses and checks the file without committing it
  3. Clears the ruleset
  4. Counts packets

Which error does nft -c NOT catch?

  1. A misspelt verdict
  2. An undefined variable
  3. A valid rule placed after a rule that already decides the same packets
  4. An invalid IP address

Why is dropping all ICMPv6 a mistake?

  1. It is slow
  2. IPv6 needs neighbour discovery and packet-too-big messages to work
  3. ICMPv6 carries web traffic
  4. It disables IPv4