18.3. Activating and Maintaining Rules

Loading a ruleset by hand proves it works today; production use needs the rules to survive reboots, to fail safely on typos, and to be changeable on a remote machine without a rescue trip. This section builds those properties in that order.

18.3.1. Syntax Checks, Atomic Loading, and Persistent Startup

The check option earns its keep on the first bad file. On fwclient, as john, create ~/debian-handbook/firewall/broken.nft - an intentional typo in the hook name:

table inet badsyntax {
    chain input {
        type filter hook inputt priority filter;
    }
}

In the root shell, validate it without loading:

# nft -c -f /home/john/debian-handbook/firewall/broken.nft
/home/john/debian-handbook/firewall/broken.nft:3:26-31: Error: unknown chain hook
        type filter hook inputt priority filter;
                         ^^^^^^

nft exits with status 1, prints the file, line, and column range, and shows the offending text - and because -c was given, the loaded ruleset is untouched. The same error without -c is where the more important property shows. Create atomic-fail.nft, which contains one valid table followed by the broken one:

table inet atomicdemo {
    chain input {
        type filter hook input priority filter;
    }
}
table inet badsyntax {
    chain input {
        type filter hook inputt priority filter;
    }
}

Load it for real:

# nft -f /home/john/debian-handbook/firewall/atomic-fail.nft
/home/john/debian-handbook/firewall/atomic-fail.nft:8:26-31: Error: unknown chain hook
        type filter hook inputt priority filter;
                         ^^^^^^

The valid table earlier in the file never appeared. Ask for it:

# nft list table inet atomicdemo
Error: No such file or directory
list table inet atomicdemo
                ^^^^^^^^^^

A file passed to nft -f is one transaction: the kernel applies all of it or none of it, and a failure anywhere rolls the whole attempt back. That is why the host rulesets in Section 18.2 begin with flush ruleset - the flush and the replacement tables commit together, leaving no window with an empty or half-built policy, and a broken file leaves the running policy exactly as it was. The practical routine is always the pair already used: nft -c -f the file, fix what it reports, then nft -f it.

Persistence needs the service unit. Still in the root shell on fwclient, enable it:

# systemctl enable nftables
Created symlink '/etc/systemd/system/sysinit.target.wants/nftables.service' → '/usr/lib/systemd/system/nftables.service'.

The unit is a oneshot that runs /usr/sbin/nft -f /etc/nftables.conf, ordered before network-pre.target - so at boot the rules exist before interfaces are configured. Restart it to exercise the full start-then-load path; the restart prints nothing:

# systemctl restart nftables
# systemctl is-active nftables
active
# systemctl is-enabled nftables
enabled

Two details of the unit matter operationally. ExecStop runs nft flush ruleset, so systemctl stop nftables removes the whole firewall rather than freezing it - disabling the service is a policy decision, not a pause. And ExecReload repeats the same nft -f /etc/nftables.conf, so after editing the file, systemctl reload nftables is equivalent to the manual load above, with the same all-or-nothing transaction.

The real test is a reboot, which closes the current session. Run it from the root shell on fwclient:

# systemctl reboot
Connection to 192.168.121.219 closed by remote host.

The connection closed because the machine went down; the address in the message is fwclient's management-network address. After the host boots, open a new SSH session over the management network, enter a root shell again, and check the same three facts as before the reboot:

# uptime
 13:51:16 up 0 min,  1 user,  load average: 0.66, 0.15, 0.05
# systemctl is-active nftables
active
# nft list chain inet filter input
table inet filter {
    chain input {
        type filter hook input priority filter; policy drop;
        ct state invalid drop
        ct state established,related accept
        iifname "lo" accept
        iifname "eth0" ip saddr 192.168.121.0/24 tcp dport 22 accept
        iifname "eth1" ip saddr 192.168.218.0/24 tcp dport 22 accept
        iifname "eth1" tcp dport 8080 accept
        icmp type echo-request accept
        icmpv6 type { destination-unreachable, packet-too-big, time-exceeded, parameter-problem, echo-request, nd-router-solicit, nd-router-advert, nd-neighbor-solicit, nd-neighbor-advert } accept
        drop
    }
}

One minute of uptime, and the full input chain is back - loaded from /etc/nftables.conf by the enabled unit before the network came up. The service is reachable too; on fwrouter, as john:

$ curl -sS --max-time 3 http://192.168.218.10:8080/
hello from client 8080

The responder survived the reboot because its unit is enabled, and the request passed through the reloaded ruleset. Persistence is now three facts working together: the file in /etc, the unit that loads it, and the enablement that orders it at boot.

18.3.2. Remote Rollout with a Timed Rollback

Every previous change was made from a session that could not be cut off by its own ruleset: the SSH path to fwclient and fwrouter crosses the management network, which the practiced rulesets never filter. Real rollouts are not so comfortable - the same interface that carries the change may be the one the new ruleset disables. The standard protection is a timed rollback scheduled before the new ruleset loads: if the administrator does not cancel the timer within its window, the old ruleset reloads automatically.

The demonstration rolls a ruleset to fwrouter that drops SSH from the LAN, then lets the timer undo it. It needs SSH from fwclient to fwrouter as john to work without interaction - key-based authentication installed as Chapter 20 describes, with the router's host key already in fwclient's known_hosts from a verified fingerprint. It also needs john's sudo policy on fwrouter to permit the commands below without a password prompt, since the commands run sudo without a terminal - the NOPASSWD arrangement of Chapter 5, or a sudoers line limited to these commands. Check the path first, from fwclient, as john:

$ ssh john@192.168.218.2 hostname
fwrouter

Key-based login works and the target is the router. Step one: put a copy of the current known-good ruleset somewhere a mistake cannot reach it - /root on the router, outside john's home. The command prints nothing when it succeeds:

$ ssh john@192.168.218.2 "sudo cp /etc/nftables.conf /root/ch18-rollback.nft"

Step two: schedule the rollback before touching the policy. The options of systemd-run that matter here:

systemd-run option Description
--on-active=seconds Run the command once, seconds after the timer starts.
--unit=name Use name.timer and name.service instead of generated ones, so the timer can be stopped by name.
--timer-property=setting Pass a timer unit setting; used below for accuracy.

The rollback command and its schedule, still from fwclient as john:

$ ssh john@192.168.218.2 "sudo systemd-run --on-active=60 --timer-property=AccuracySec=1s --unit=ch18-rollback /usr/sbin/nft -f /root/ch18-rollback.nft"
Running timer as unit: ch18-rollback.timer
Will run service as unit: ch18-rollback.service

The timer is now armed for sixty seconds, and its action is to reload the backup ruleset. The AccuracySec=1s property is not decoration: by default a systemd timer is allowed to coalesce to a whole minute of accuracy, and a rollback that may fire a minute late is a rollback that can outlast a short verification window. With one-second accuracy the window is what it says. The unit name is arbitrary - choose one you will recognize in timer listings. Confirm the schedule, with the same ssh path:

$ ssh john@192.168.218.2 'systemctl list-timers ch18-rollback.timer --no-pager'
NEXT                        LEFT LAST PASSED UNIT                ACTIVATES
Sat 2026-11-21 13:53:03 UTC  57s -         - ch18-rollback.timer ch18-rollback.service

1 timers listed.
Pass --all to see loaded but inactive timers, too.

About a minute out, as intended. Step three: write the candidate ruleset on the router. On fwrouter, as john, create ~/debian-handbook/firewall/router-lockout.nft:

flush ruleset

define mgmt_if = "eth0"
define lan_if  = "eth1"
define mgmt_net = 192.168.121.0/24
define lan_net  = 192.168.218.0/24

table inet filter {
    chain input {
        type filter hook input priority filter; policy drop;
        ct state established,related accept
        iifname "lo" accept
        iifname $mgmt_if ip saddr $mgmt_net tcp dport 22 accept
        iifname $lan_if ip saddr $lan_net tcp dport 22 drop
        icmp type echo-request accept
        icmpv6 type { echo-request, destination-unreachable, packet-too-big, time-exceeded, parameter-problem, nd-router-solicit, nd-router-advert, nd-neighbor-solicit, nd-neighbor-advert } accept
        drop
    }
    chain forward {
        type filter hook forward priority filter; policy drop;
    }
    chain output {
        type filter hook output priority filter; policy accept;
    }
}

This candidate has a bug by design: the LAN SSH rule accepts nothing and drops everything from the LAN, and it would lock out the LAN-side administrator. The existing sessions survive - they match ct state established,related - but no new LAN connection can be made. From fwclient, as john, load the candidate onto the router; the command prints nothing when it succeeds:

$ ssh john@192.168.218.2 "sudo nft -f /home/john/debian-handbook/firewall/router-lockout.nft"

The lockout is now live. Try to open a new session over the LAN, and bound the attempt so the kernel's own TCP timeout does not make you wait:

$ ssh -o ConnectTimeout=5 john@192.168.218.2 hostname
ssh: connect to host 192.168.218.2 port 22: Connection timed out

Five seconds of silence and a timeout report: the LAN path to the router is filtered, exactly what the candidate ruleset said it would do. Nothing is lost - the management network still reaches the router, and the rollback timer is counting. Let it fire, then retry the same connection:

$ ssh john@192.168.218.2 hostname
fwrouter

The backup ruleset reloaded and the LAN path works again. The timer did its job and has gone:

$ ssh john@192.168.218.2 'systemctl list-timers ch18-rollback.timer --no-pager'
NEXT LEFT LAST PASSED UNIT ACTIVATES

0 timers listed.
Pass --all to see loaded but inactive timers, too.

The successful case needs the mirror-image skill: cancel a scheduled rollback once verification passes, or it will reload the old ruleset over a working new one. The pattern is the same with a longer window and a harmless action; from fwclient, as john, schedule one:

$ ssh john@192.168.218.2 "sudo systemd-run --on-active=300 --unit=ch18-cancel /usr/sbin/nft list ruleset"
Running timer as unit: ch18-cancel.timer
Will run service as unit: ch18-cancel.service
$ ssh john@192.168.218.2 'sudo systemctl stop ch18-cancel.timer'
$ ssh john@192.168.218.2 'systemctl list-timers --all ch18-cancel.timer --no-pager'
NEXT LEFT LAST PASSED UNIT ACTIVATES

0 timers listed.

Stopping the timer by the name given in --unit disarms it; the stop command prints nothing, and the listing confirms the timer is gone even with --all, which would show inactive timers. A real rollout runs the same sequence with the verification in the middle: arm the timer, load the candidate, verify through the new ruleset, and either systemctl stop the timer on success or reconnect through the management network and let the timer undo the change on failure.

18.3.3. Sets, Maps, Counters, and Rate-Limited Logging

Address lists, per-port verdicts, packet accounting and drop logging turn a working ruleset into an operable one. The extended client ruleset adds all four. On fwclient, as john, create ~/debian-handbook/firewall/client-host.nft:

flush ruleset

define mgmt_if = "eth0"
define lan_if = "eth1"
define mgmt_net = 192.168.121.0/24
define lan_net = 192.168.218.0/24

table inet filter {
    set blocked_hosts {
        type ipv4_addr
        flags interval
        elements = { 203.0.113.50 }
    }

    map service_verdict {
        type inet_service : verdict
        elements = { 8081 : drop }
    }

    counter web_requests {}
    counter dropped_packets {}

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

        ct state invalid counter name dropped_packets drop
        ct state established,related accept

        iifname "lo" accept

        iifname $mgmt_if ip saddr $mgmt_net tcp dport 22 accept
        iifname $lan_if ip saddr $lan_net tcp dport 22 accept

        iifname $lan_if ip saddr @blocked_hosts tcp dport 8080 counter name dropped_packets drop

        iifname $lan_if tcp dport 8080 counter name web_requests accept
        iifname $lan_if tcp dport vmap @service_verdict

        icmp type echo-request accept
        icmpv6 type { echo-request, destination-unreachable, packet-too-big, time-exceeded, parameter-problem, nd-router-solicit, nd-router-advert, nd-neighbor-solicit, nd-neighbor-advert } accept

        counter name dropped_packets
        limit rate 5/minute burst 2 packets log prefix "ch18-input-drop: " level info
        drop
    }

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

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

The new objects: a set of addresses - blocked_hosts - that a rule can match with ip saddr @blocked_hosts; a verdict map - service_verdict - that looks up the port and applies the verdict stored for it, via tcp dport vmap @service_verdict; two named counters; and the final block's limit ... log line, which writes matching packets to the kernel log at a bounded rate. In the root shell on fwclient, install, check and load - the three commands print nothing on success:

# install -m 0644 /home/john/debian-handbook/firewall/client-host.nft /etc/nftables.conf
# nft -c -f /etc/nftables.conf
# nft -f /etc/nftables.conf
# nft list chain inet filter input
table inet filter {
    chain input {
        type filter hook input priority filter; policy drop;
        ct state invalid counter name "dropped_packets" drop
        ct state established,related accept
        iifname "lo" accept
        iifname "eth0" ip saddr 192.168.121.0/24 tcp dport 22 accept
        iifname "eth1" ip saddr 192.168.218.0/24 tcp dport 22 accept
        iifname "eth1" ip saddr @blocked_hosts tcp dport 8080 counter name "dropped_packets" drop
        iifname "eth1" tcp dport 8080 counter name "web_requests" accept
        iifname "eth1" tcp dport vmap @service_verdict
        icmp type echo-request accept
        icmpv6 type { destination-unreachable, packet-too-big, time-exceeded, parameter-problem, echo-request, nd-router-solicit, nd-router-advert, nd-neighbor-solicit, nd-neighbor-advert } accept
        counter name "dropped_packets"
        limit rate 5/minute burst 2 packets log prefix "ch18-input-drop: " level info
        drop
    }
}

The ruleset behaves exactly as the basic one did - the same traffic passes, the same traffic drops - because the additions only refine how matches are decided and recorded.

A set changes membership without touching rules. It starts with one reserved address in it:

# nft list set inet filter blocked_hosts
table inet filter {
    set blocked_hosts {
        type ipv4_addr
        flags interval
        elements = { 203.0.113.50 }
    }
}

Add the router's LAN address to the set; the command prints nothing when it succeeds:

# nft add element inet filter blocked_hosts { 192.168.218.2 }
# nft list set inet filter blocked_hosts
table inet filter {
    set blocked_hosts {
        type ipv4_addr
        flags interval
        elements = { 192.168.218.2, 203.0.113.50 }
    }
}

The flags interval declaration allows ranges as well as single addresses. The set's rule matches it for port 8080 only, so on fwrouter, as john, the responder request now times out:

$ curl -sS --max-time 3 http://192.168.218.10:8080/
curl: (28) Connection timed out after 3002 milliseconds

Remove the element - also silent - and the same request succeeds again:

# nft delete element inet filter blocked_hosts { 192.168.218.2 }

On fwrouter, as john:

$ curl -sS --max-time 3 http://192.168.218.10:8080/
hello from client 8080

The rule never changed; the set did. This is the right tool for address lists that grow and shrink - denylists, partner networks, permitted administrators - because thousands of set elements cost a single lookup per packet, while the equivalent one-rule-per-address chain costs a linear walk.

A verdict map does the same for decisions. It currently holds a drop for port 8081:

# nft list map inet filter service_verdict
table inet filter {
    map service_verdict {
        type inet_service : verdict
        elements = { 8081 : drop }
    }
}

On fwrouter, as john, the 8081 responder is running but unreachable:

$ curl -sS --max-time 3 http://192.168.218.10:8081/
curl: (28) Connection timed out after 3002 milliseconds

Changing a verdict means replacing the map entry, and add element fails if the key already exists - so a verdict change is a delete and an add together, in one file to keep the transition atomic. On fwclient, as john, create map-allow.nft:

delete element inet filter service_verdict { 8081 : drop }
add element inet filter service_verdict { 8081 : accept }

Apply it from the root shell; nft -f prints nothing on success:

# nft -f /home/john/debian-handbook/firewall/map-allow.nft
# nft list map inet filter service_verdict
table inet filter {
    map service_verdict {
        type inet_service : verdict
        elements = { 8081 : accept }
    }
}

On fwrouter, as john, the same request now succeeds:

$ curl -sS --max-time 3 http://192.168.218.10:8081/
hello from client 8081

The mirror image, map-block.nft, reverses the pair:

delete element inet filter service_verdict { 8081 : accept }
add element inet filter service_verdict { 8081 : drop }
# nft -f /home/john/debian-handbook/firewall/map-block.nft

On fwrouter, as john, the same request times out again:

$ curl -sS --max-time 3 http://192.168.218.10:8081/
curl: (28) Connection timed out after 3002 milliseconds

Ports absent from the map fall through the vmap rule to whatever follows, so the map only needs entries that differ from the chain's default behavior.

The two counters record without changing any verdict: the accept rule for port 8080 counts into web_requests, and the block at the end counts everything it drops into dropped_packets. Read the web counter:

# nft list counter inet filter web_requests
table inet filter {
    counter web_requests {
        packets 3 bytes 180
    }
}

On fwrouter, as john, make one more request:

$ curl -sS --max-time 3 http://192.168.218.10:8080/
hello from client 8080
# nft list counter inet filter web_requests
table inet filter {
    counter web_requests {
        packets 4 bytes 240
    }
}

One request, one packet - and the number explains itself: the rule only ever sees a connection's first packet, because everything after it matches the ct state established,related accept rule higher up the chain. The 8080 rule counts new connections, and the counter moved exactly with them. Named counters like these outlive the rules that reference them and can be shared by several rules, which is why the drop counter appears in three places in the ruleset and still reads as one number.

That drop counter and the rate-limited log line above it work as a pair. Nothing in the ruleset allows port 9999, so a connection attempt to it falls through every rule to the final block. On fwrouter, as john, make the attempt - the probe prints nothing and exits with status 1 after its one-second wait:

$ nc -z -w1 192.168.218.10 9999

Repeat it a second later; the second attempt is also silent. Every packet was dropped - silence is the drop behavior - but not unrecorded. In the root shell on fwclient, read the kernel log for the prefix the rule set, with journalctl's kernel and grep filters as Chapter 8 introduced them; the pipeline feeds the matched lines to tail for the last four:

# journalctl -k -g ch18-input-drop --no-pager | tail -n 4
Nov 21 13:54:45 fwclient kernel: ch18-input-drop: IN=eth1 OUT= MAC=52:54:00:f2:2a:f6:52:54:00:f8:38:d3:08:00 SRC=192.168.218.2 DST=192.168.218.10 LEN=60 TOS=0x00 PREC=0x00 TTL=64 ID=56983 DF PROTO=TCP SPT=58242 DPT=9999 WINDOW=64240 RES=0x00 SYN URGP=0
Nov 21 13:54:46 fwclient kernel: ch18-input-drop: IN=eth1 OUT= MAC=52:54:00:f2:2a:f6:52:54:00:f8:38:d3:08:00 SRC=192.168.218.2 DST=192.168.218.10 LEN=60 TOS=0x00 PREC=0x00 TTL=64 ID=43024 DF PROTO=TCP SPT=40934 DPT=9999 WINDOW=64240 RES=0x00 SYN URGP=0

Two entries, one second apart, from the two attempts - the source ports differ - to destination port 9999. They are the two packets the limit rate 5/minute burst 2 packets clause allowed: the burst allowance is two packets, spent immediately, and the rate then admits one further log line every twelve seconds, so a third attempt a second later is dropped with no log entry - try it and read the journal again. The rate limit is what makes drop logging survivable - a port scanned thousands of times per second cannot be allowed to write thousands of journal entries per second - and the trade-off is exactly the one visible here: logging is sampling, not a complete record. The counter is the complete record:

# nft list counter inet filter dropped_packets
table inet filter {
    counter dropped_packets {
        packets 14 bytes 840
    }
}

Fourteen packets reached the drop block: the three SYN retransmissions of the blocked-source request in the set exercise, plus one 60-byte SYN for every connection attempt against port 9999. The run behind this capture made more attempts against that port than the two shown above, and every one of them is counted here, including those past the burst allowance that the journal never recorded. Every drop is in this one number, and 14 × 60 is the 840 bytes the counter shows. Counter for the question "how many", journal prefix for the question "which packet".

18.3.4. Updating Rules Without Losing the Active Policy

Occasionally a rule is needed immediately - an emergency allow, a temporary diagnostic - and the right move is to change the running ruleset in place, leaving the file to catch up later. nft edits live rules one at a time, and the directional verbs matter more than they look: add rule appends to the end of a chain, insert rule puts a rule before the first one. In a chain that ends with a drop, an appended allow is dead code - no packet ever reaches it. Demonstrate with the 8082 responder, which no rule currently allows. From the root shell on fwclient:

# nft insert rule inet filter input iifname "eth1" tcp dport 8082 counter accept

The command prints nothing when it succeeds. It put the new rule at the head of the input chain, with an anonymous counter attached. On fwrouter, as john:

$ curl -sS --max-time 3 http://192.168.218.10:8082/
hello from client 8082

The service is reachable through a rule that exists only in the kernel. To remove such a rule, list the chain with handles:

# nft -a list chain inet filter input
table inet filter {
    chain input { # handle 1
        type filter hook input priority filter; policy drop;
        iifname "eth1" tcp dport 8082 counter packets 6 bytes 403 accept # handle 22
        ct state invalid counter name "dropped_packets" drop # handle 8
        ct state established,related accept # handle 9
        iifname "lo" accept # handle 10
        iifname "eth0" ip saddr 192.168.121.0/24 tcp dport 22 accept # handle 11
        iifname "eth1" ip saddr 192.168.218.0/24 tcp dport 22 accept # handle 12
        iifname "eth1" ip saddr @blocked_hosts tcp dport 8080 counter name "dropped_packets" drop # handle 13
        iifname "eth1" tcp dport 8080 counter name "web_requests" accept # handle 14
        iifname "eth1" tcp dport vmap @service_verdict # handle 15
        icmp type echo-request accept # handle 16
        icmpv6 type { destination-unreachable, packet-too-big, time-exceeded, parameter-problem, echo-request, nd-router-solicit, nd-router-advert, nd-neighbor-solicit, nd-neighbor-advert } accept # handle 18
        counter name "dropped_packets" # handle 19
        limit rate 5/minute burst 2 packets log prefix "ch18-input-drop: " level info # handle 20
        drop # handle 21
    }
}

Every rule now carries its handle - a kernel-assigned number, valid until the rule is deleted - and the 8082 rule sits first, at handle 22. Its anonymous counter already holds several packets from the one connection the rule allowed: the rule sits above the ct state established,related accept line, so every packet of the session matches it first, not merely the connection-opening SYN - the same rule order that made Section 18.3.3's web_requests counter see only first packets, because that rule sits below the established line. Delete the rule by handle; the command is silent:

# nft delete rule inet filter input handle 22
# nft list chain inet filter input
table inet filter {
    chain input {
        type filter hook input priority filter; policy drop;
        ct state invalid counter name "dropped_packets" drop
        ct state established,related accept
        iifname "lo" accept
        iifname "eth0" ip saddr 192.168.121.0/24 tcp dport 22 accept
        iifname "eth1" ip saddr 192.168.218.0/24 tcp dport 22 accept
        iifname "eth1" ip saddr @blocked_hosts tcp dport 8080 counter name "dropped_packets" drop
        iifname "eth1" tcp dport 8080 counter name "web_requests" accept
        iifname "eth1" tcp dport vmap @service_verdict
        icmp type echo-request accept
        icmpv6 type { destination-unreachable, packet-too-big, time-exceeded, parameter-problem, echo-request, nd-router-solicit, nd-router-advert, nd-neighbor-solicit, nd-neighbor-advert } accept
        counter name "dropped_packets"
        limit rate 5/minute burst 2 packets log prefix "ch18-input-drop: " level info
        drop
    }
}

The rule is gone and the chain matches the installed file again. On fwrouter, as john, the responder is unreachable once more:

$ curl -sS --max-time 3 http://192.168.218.10:8082/
curl: (28) Connection timed out after 3002 milliseconds

Live edits are legitimate operations, not a substitute workflow: a rule that exists only in the kernel is lost at the next flush ruleset, diverges from the file in /etc, and will surprise the next administrator who reads only the file. The discipline is short: make the live change when time matters, then reproduce it in the ruleset file and reload, so the running policy and the on-disk policy agree before the session ends. The insert/delete pair is also the standard way to add a temporary diagnostic - the tracing rule in Section 18.5.1 is exactly this pattern.