nftables default-deny without losing server control
Permissions, independent rollback, and a fresh management connection matter more than the word drop.
A default-deny policy starts with an agreement: traffic passes only for a defined need. But deny alone says nothing about whether SSH survives, IPv6 works, or rules return after reboot. Those outcomes need design and verification.
Prepare a network-service inventory, verified administrative login, and an independent recovery console first. This article describes a method for your own Linux host. A universal ready-made ruleset would mislead: addresses, interfaces, containers, and outbound dependencies differ.
Practice on E-01: management first, then drop
I applied a separate host policy on the E-01 learning VPS running Debian 13. Before the change, I checked a fresh login with the selected SSH key, password-required sudo, and the provider’s independent console. After installing nftables and libnftables1 version 1.1.3-1 and libjansson4 2.14-2+b3, I read the complete kernel ruleset: it was empty. The absence of the nft command before installation would not establish that.
This VPS uses interface enp3s0 and management port TCP22. The uplink has DHCP, IPv6 link-local, and RA acceptance configured; it has no global IPv6 address. Forwarding is disabled for both families. These starting conditions determine the example below; another server needs its own inventory before reusing it.
One owned table with explicit permissions
The file contains the policy actually applied. create table performs an initial creation: an existing table with that name stops the operation. There is no global flush ruleset or attempt to rewrite other owners’ tables.
define uplink = "enp3s0"
define ssh_port = 22
create table inet e01_host {
counter loopback { }
counter established { }
counter dhcp4 { }
counter dhcp6 { }
counter invalid { }
counter icmp4 { }
counter icmp6 { }
counter ssh_new { }
counter input_drop { }
counter forward_drop { }
chain input {
type filter hook input priority filter; policy drop;
iifname "lo" counter name loopback accept
ct state established,related counter name established accept
meta nfproto ipv4 iifname $uplink udp sport 67 udp dport 68 counter name dhcp4 accept
meta nfproto ipv6 iifname $uplink udp sport 547 udp dport 546 counter name dhcp6 accept
ct state invalid counter name invalid drop
meta nfproto ipv4 meta l4proto icmp counter name icmp4 accept
meta nfproto ipv6 meta l4proto ipv6-icmp counter name icmp6 accept
iifname $uplink tcp dport $ssh_port ct state new counter name ssh_new accept
counter name input_drop drop
}
chain forward {
type filter hook forward priority filter; policy drop;
counter name forward_drop drop
}
}
DHCP4/6 are allowed on the uplink before invalid drop. ICMPv4 and ICMPv6 remain available for diagnostics and network control messages. Fresh SSH is allowed through the uplink without a source-address allowlist: WireGuard and trusted networks are not configured yet. Unsolicited LLMNR and other inbound application traffic reach drop. Web, database, and Redis ports are not opened here; there is no output chain, so this ruleset does not restrict egress.
Syntax validation and a ten-minute window
My controlled execution mechanism prepared the configuration and the units e01-host-firewall.service and e01-host-firewall-rollback.timer; they are not files supplied by the Debian package. The worker is the process that loads the rules; the watchdog independently starts rollback when the window expires.
The syntax check returned exit code 0 without output. Before loading the table, a separate local rollback timer was already running with OnActiveSec=600s, while the worker remained inactive:
$ /usr/sbin/nft --check --file /etc/solution200/firewall/e01-host.nft
$ systemctl show e01-host-firewall.service e01-host-firewall-rollback.timer -p Id -p ActiveState -p UnitFileState
Id=e01-host-firewall.service
ActiveState=inactive
UnitFileState=static
Id=e01-host-firewall-rollback.timer
ActiveState=active
UnitFileState=static
The sole worker then loaded the rules. I did not start the distribution’s nftables.service: its default configuration and stop action can clear the entire ruleset. The owned worker has no such stop action; stopping it does not delete the table. Repeated start or restart is not used to update the initial-create configuration.
A fresh SSH connection after applying
I opened another SSH session with the selected key and authenticated for password-required sudo. These replies came after applying the rules; they are not a continuation of the old established session:
$ id -u
0
$ systemctl is-active ssh.service e01-host-firewall.service
active
active
From the actual nft list chain inet e01_host input output, the chain header and its final two rules are shown below. Intermediate permissions are omitted here; the screenshot shows the complete chain:
type filter hook input priority filter; policy drop;
iifname "enp3s0" tcp dport 22 ct state new counter name "ssh_new" accept
counter name "input_drop" drop
Allowed and denied traffic
For the negative test, I first received a controlled nonce reply from my own TCP18080 and UDP18081 listeners. After applying, the same listeners remained bound, but external requests timed out. Together with the policy and growth of the guest drop counter, this explains denial better than testing a port with no listener.
| Path | Observed result |
|---|---|
| Fresh SSH and sudo | Key-based login works, sudo returns UID0, and the independent console remains available. |
| TCP18080 / UDP18081 | Reply before applying; timeout afterward while listeners remain bound. |
| Loopback DNS | Local resolver reply with matching query ID, QR, rcode 0, and two answers. |
| System DNS and outbound HTTPS | www.debian.org resolves; HTTPS returns 200 with normal TLS verification. |
| External ICMPv4 | Ping from an external point succeeds. |
| DHCP4/6 | Allow rules are installed; I did not force renewal, and counters on the VPS remained zero. |
| External IPv6 | Not tested: there is no global destination address. |
| Provider firewall | Neither changed nor verified; the guest policy does not replace it. |
Between control measurements, input_drop grew from 2 to 16 packets; the final screenshot shows 36 packets and 3821 bytes. This is a general counter that can include background traffic, so I do not attribute every packet to my probes. No individual flow was traced. The test listeners were stopped after measurement.
Commit applies to the current runtime
After accepting management access and the network checks, I confirmed the transaction before the window expired and stopped the specific timer. The final state:
transaction=committed
persistence=False
I tested automatic rollback, worker failures, and the commit/timer race separately in a disposable VM. On E-01 itself, the timer was armed and cancelled after successful acceptance; an actual rollback on the VPS was not run. After the timer expires, the process has a further 2-second stop period before forced termination, and completion depends on I/O and kernel process state. This does not promise restoration at exactly the 600th second. Changing the control script, configuration, or unit can also block the watchdog, so the independent console remains necessary.
At the end of this initial runtime pass, the worker remained active/static and the distribution’s nftables.service was inactive/disabled. At that stage I had not enabled boot loading or rebooted the VPS. persistence=False in the screenshot records that historical state. The separate implementation and post-reboot test follow below.
Screenshots from the practical run
Boot persistence: a separate pass with one reboot
After the initial runtime test, I separately implemented boot loading of the same reviewed policy from /etc/solution200/firewall/e01-host.nft. The earlier screenshots show the preceding stage. Its worker is bound to the previous boot; I neither enabled its boot startup nor ran it after reboot.
A loader before networking and SSH
The new loader has its own root-only helper and manifest. It creates the table only in an empty ruleset, or retains an existing complete ruleset when its normalized contents exactly match the reviewed policy. A different state stops the operation. This is not a direct repeat of nft -f on a create table file over an existing table; there is no global flush, table deletion or permissive recovery.
The service actually installed at /etc/systemd/system/e01-host-firewall-boot.service:
[Unit]
Description=Load the reviewed E01 host firewall before userspace networking
DefaultDependencies=no
Requires=local-fs.target
After=local-fs.target systemd-sysctl.service
Wants=network-pre.target
Before=network-pre.target shutdown.target nftables.service firewalld.service ufw.service netfilter-persistent.service iptables.service ip6tables.service
Conflicts=shutdown.target nftables.service firewalld.service ufw.service netfilter-persistent.service iptables.service ip6tables.service
[Service]
Type=oneshot
RemainAfterExit=yes
ExecStart=/usr/bin/python3 -I /var/lib/e01-host-firewall-boot/controller.py load
[Install]
WantedBy=multi-user.target
The same contents below are installed in each of the three named drop-in files. After sets the order; combined with it, Requires prevents these services from starting after a failed firewall load. Before=network-pre.target alone would not provide that gate. systemd dependency documentation.
# /etc/systemd/system/systemd-networkd.service.d/40-e01-firewall-boot.conf
# /etc/systemd/system/ssh.service.d/40-e01-firewall-boot.conf
# /etc/systemd/system/ssh.socket.d/40-e01-firewall-boot.conf
[Unit]
Requires=e01-host-firewall-boot.service
After=e01-host-firewall-boot.service
The pre-enable check caught a practical installer error: a private umask 077 left the new systemd files at 0600 instead of the intended 0644. The helper refused before enable or reboot. After checking the owned files, I corrected only the permissions of the four new units/drop-ins and three directories, then repeated verification. The installer lesson is to set the final mode explicitly rather than rely solely on the file-creation argument; the private helper and manifest remain root-only.
I first ran enable without --now. Below are the command and actual state fields; networking and SSH remained running without a restart:
$ systemctl enable e01-host-firewall-boot.service
$ systemctl show e01-host-firewall-boot.service -p ActiveState -p SubState -p UnitFileState
ActiveState=inactive
SubState=dead
UnitFileState=enabled
$ systemctl reboot
I then performed one approved reboot with the independent provider console open. Afterwards I obtained:
$ systemctl show e01-host-firewall-boot.service -p ActiveState -p SubState -p UnitFileState
ActiveState=active
SubState=exited
UnitFileState=enabled
$ nft list tables
table inet e01_host
$ systemctl is-active systemd-networkd.service ssh.service
active
active
active/exited is the normal outcome of a successful Type=oneshot with RemainAfterExit=yes: the rules remain in the kernel without a separate firewall daemon. The complete normalized ruleset matched the reviewed policy; systemd monotonic timestamps showed that the loader completed before networkd and SSH started.
Checks after the server returned
I opened a fresh SSH session with the selected key and completed password-required sudo to UID0. In the independent provider console I also confirmed root UID0 and the same new boot. The IPv4 default route was DHCP-marked, deb.debian.org resolved, and HTTPS to the official Debian Release returned 200 with normal TLS verification. ICMPv4 had 0% packet loss; there were no failed units.
For TCP18080 and UDP18081, my own live listeners first echoed a nonce over loopback. From outside, those same listeners returned no reply before timeout. The input_drop counter increased by 12; that is a total change that may include background traffic, not an exact count of my probes. Both test listeners were closed after measurement.
The result covers ordinary networkd/SSH userspace boot. If the loader fails, its dependent services do not start; this is a failure-closed gate for those paths, not proof covering all initrd networking or arbitrary root writers. The DHCP4 counter remained zero: an existing route does not establish a separate renewal exchange, and I did not force a lease renewal. I did not verify DHCPv6 exchange or external IPv6: there is no global IPv6 destination. Physical power-off/on and the provider firewall are outside this pass; deliberate failures were tested on a separate disposable VM, without another reboot of this VPS. This is a manual implementation; generic persistence in the Go CLI remains separate work.
Firewall startup screenshots
Define where denial applies
In nftables, base chains attach to network hooks. Input concerns packets addressed to the host, forward handles packets passing through it, and output handles locally generated packets. Setting input policy to drop does not automatically apply that policy to other paths.
The inet family supports handling IPv4 and IPv6 in one set of tables. Protocol conditions still need correct definitions for both families. The nft manual describes families, hooks, base-chain policies, and connection states.
For containers, establish whether traffic reaches input or traverses forwarding and redirection. Do not assume a host rule protects every published container port without checking.
Derive permissions from the inventory
An illustrative plan for a server with public web access and separate management:
| Traffic class | What to establish before writing rules |
|---|---|
| Loopback | Required local interactions |
| Established/related | Replies and related-connection behaviour |
| Administration | Actual source, protocol, and port of fresh login |
| Web requests | Agreed public services |
| ICMP and ICMPv6 | Diagnostics and necessary network messages |
| Forwarding | Routing and container dependencies |
| Outbound traffic | Separate policy for DNS, time, packages, and external services |
Do not mechanically block all ICMPv6: IPv6 depends on control messages, including neighbour discovery, while data transfer needs correct handling of packet-size messages. Choose allowed types for the interface and network role. The ICMPv6 filtering recommendations help identify necessary message classes but do not choose policy for the administrator.
Prepare restoration before applying
Save the previous rules and verify they are suitable for restoration. If other tools manage some rules, establish ownership boundaries. Blindly flushing the entire ruleset can remove container or other service rules.
Before applying, start a tested local delayed-rollback mechanism. It must work without a new SSH connection and know the exact previous configuration. Unless the operator cancels rollback, window expiry triggers worker cancellation and restoration. The mechanism shown here has an additional 2-second stop budget; actual completion depends on I/O and process state, so an exact completion time is not guaranteed. A command written in notes is insufficient. Test the mechanism in a non-production environment first; the console remains an additional independent route.
Validate the candidate and apply a coherent change
An illustrative local file prepared by an administrator for their test environment can be checked with:
sudo nft -c -f /tmp/example-candidate.nft
The filename is fictional. -c checks command validity without applying changes. This requires appropriate privileges and environment; it does not prove SSH reachability or policy correctness.
Loading a coherent batch through nft -f supports atomic rule changes. This removes intermediate states within the transaction but does not correct a logically wrong policy. The file must explicitly handle replacement of the intended objects: adding rules again does not automatically clear previous rules.
Test permissions, rejection, and a fresh connection
After applying, open a new administrative connection without reusing the old SSH transport. Check required privileges, a public-service request, and the specific path intended to be blocked. Where both families are present, test IPv4 and IPv6 separately, together with required container paths.
An existing session may survive through established/related handling even though fresh login is blocked. Its success is not an acceptance criterion. Rejection needs explanation too: a timeout without correlation to rules and service state does not prove the intended denial.
Cancel delayed rollback only after the defined checks pass. On failure or lost connectivity, let it run or use the console, then verify restoration.
Account for other rules and verification boundaries
An individual accept does not guarantee delivery to a service. In the nftables verdict model, a packet accepted at one point can be dropped by a later chain or hook. Investigate the whole relevant path, not merely the newly created table. This is particularly important when several tools manage rules.
Distinguish the blocking goal from the observation method. If a specific path to a test service must be denied, establish that the service actually accepts requests from an allowed source. Otherwise a negative result from the forbidden side may simply reflect a stopped process. Allowed and denied control points help explain the difference.
Delayed rollback needs its own completion criterion. Its execution does not end verification: confirm that the previous policy returned and fresh management works again. If automation did not execute, use the independent console and investigate before trying again. Do not repeat a failed exercise without changing its plan.
After success, retain the exact accepted configuration and list of tested paths. Adding another service starts with a new inventory entry, not a broad temporary permission that is easy to forget. Default-deny then remains a maintained policy throughout the product’s life.
Handle the next boot separately
Active rules and the configuration loaded after reboot are different states. On Debian, align the persistent file with the actual nftables startup mechanism; the Debian Handbook describes the standard approach. Repeat access checks after a planned reboot.
The result is a defined policy with working management, confirmed permissions, explained rejections, and tested restoration. Revisit it with the inventory whenever products’ network requirements change.