18.2. Building a Host Firewall

A host firewall answers three questions: what may arrive at this machine, what may leave it, and what may pass through it. A plain server answers the third question trivially - nothing passes through - but stating it explicitly is still worthwhile, because a machine that later acquires a second interface or a container bridge should fail closed, not open.

18.2.1. Selecting Input, Output, and Forwarding Policies

Each base chain carries a policy - the verdict applied to packets that match no rule. The policy is the safety net under the rules, and choosing it per chain is the real decision point of a host firewall:

Deployment input output forward
Workstation or server with one interface drop accept drop
Server that must not talk to arbitrary addresses drop drop, with allows drop
Router or hypervisor host drop accept drop, with explicit transit rules

Two patterns deserve comment. Filtering output strictly is defensible on servers that should never initiate unexpected traffic - exfiltration paths and malware callbacks both cross output - but it costs maintenance: every update client, DNS lookup and monitoring probe needs its own allowance. The host rulesets in this chapter keep output open and spend their effort on input, which is the conventional first step; a restrictive output policy composes naturally later by changing the output chain to policy drop and adding allows in front of it.

The second pattern is the explicit final rule. A chain with policy drop and nothing else is silent: dropped packets vanish with no log line and no counter. The rulesets in this chapter therefore end their input chains with a small block - a named counter, a rate-limited log line, then drop - which produces the same verdict while recording that it happened. The policy behind it still reads drop, and remains a backstop for traffic that somehow evaluates past the final rule; Section 18.3.3 explains the logging block in detail.

18.2.2. Writing an nftables Ruleset for IPv4 and IPv6

The nftables package ships /etc/nftables.conf as a minimal skeleton - a flush ruleset line, an inet filter table, and empty input, forward and output chains - and the nftables.service unit disabled. Loading a real policy means writing the file and enabling the unit; this section does the first half, and Section 18.3.1 the second.

Write the ruleset as a file in john's workspace, then install it into /etc/nftables.conf - keeping the editable copy under john's control and the authoritative copy in /etc. On fwclient, as john (leave the root shell with exit, or use a second terminal), create ~/debian-handbook/firewall/client-basic.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 invalid 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 tcp dport 8080 accept

        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;
    }
}

Four structural points before the rules themselves. flush ruleset clears every table in every family before the file's own tables load - as one transaction with the load, so there is no instant with no firewall; it also means this file, and every file like it, is the whole policy, not an addition to whatever came before. The define lines are textual substitutions, used the way a shell uses variables, so the interfaces and networks appear in one place. The inet family makes one table match both address families: the tcp dport 22 rule protects SSH over IPv4 and IPv6 alike, and rules that must be family-specific say so with ip or ip6 qualifiers - as the two SSH allows do, because the administration and LAN networks are IPv4 in this lab. And the three chains are base chains at the standard filter priority, so they run where Figure 18.1 shows.

Now load it, in the root shell on fwclient. Install the file, check it, apply it - all three commands print nothing when they succeed:

# install -m 0644 /home/john/debian-handbook/firewall/client-basic.nft /etc/nftables.conf
# nft -c -f /etc/nftables.conf
# nft -f /etc/nftables.conf

The check-then-apply pair is the discipline the next section builds on: -c validates the whole file without touching the loaded ruleset, so a typo costs nothing. Confirm what the kernel now holds:

# 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
    }
}

The listing is the file's substance in kernel form, with the defines expanded. A shorter view of the skeleton the three chains form:

# nft list chains
table inet filter {
    chain input {
        type filter hook input priority filter; policy drop;
    }
    chain forward {
        type filter hook forward priority filter; policy drop;
    }
    chain output {
        type filter hook output priority filter; policy accept;
    }
}

One base chain per hook, drop guarding the two hooks that face traffic the host did not initiate, and the policy table from Section 18.2.1 made concrete. The rules are few enough to take in order:

  • ct state invalid drop discards packets that fit no flow before anything else looks at them.
  • ct state established,related accept lets replies to traffic this host initiated back in - the rule the whole policy leans on.
  • iifname "lo" accept keeps local inter-process traffic working.
  • The two tcp dport 22 rules allow SSH only from the administration network and the LAN, by interface and source prefix both.
  • tcp dport 8080 on the LAN interface is the one application service the host publishes.
  • The icmp and icmpv6 lines allow the diagnostic and control traffic the next section exercises.
  • The final drop ends the chain for everything unmatched, ahead of the chain policy.

18.2.3. Allowing Established Traffic, Loopback, and Essential ICMP

The stateful rules are what make this policy usable at all, and they are worth watching work. From fwclient, as john, ping the router - an outbound flow this host initiates:

$ ping -c 2 192.168.218.2
PING 192.168.218.2 (192.168.218.2) 56(84) bytes of data.
64 bytes from 192.168.218.2: icmp_seq=1 ttl=64 time=0.371 ms
64 bytes from 192.168.218.2: icmp_seq=2 ttl=64 time=0.412 ms

--- 192.168.218.2 ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 1021ms
rtt min/avg/max/mdev = 0.371/0.391/0.412/0.020 ms

The echo requests left through the open output chain. The replies arrived at an input chain that has no rule allowing ICMP replies to outbound pings - they passed because conntrack recognized them as belonging to established flows. One ct state established,related accept rule is doing the work that a stateless firewall would need a per-protocol allow rule for, in each direction, for every service.

Loopback is its own interface, and the ruleset accepts all of it with iifname "lo" accept. Local sockets routinely talk to local sockets - a database client on this host connecting to a local database, a service reading its own HTTP endpoint - and loopback traffic traverses the input and output chains like any other. Both directions work through the same rules:

$ curl -sS --max-time 3 http://127.0.0.1:8080/
hello from client 8080
$ ping -c 2 127.0.0.1
PING 127.0.0.1 (127.0.0.1) 56(84) bytes of data.
64 bytes from 127.0.0.1: icmp_seq=1 ttl=64 time=0.023 ms
64 bytes from 127.0.0.1: icmp_seq=2 ttl=64 time=0.028 ms

--- 127.0.0.1 ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 1010ms
rtt min/avg/max/mdev = 0.023/0.025/0.028/0.002 ms

The ICMP allowances are next. From fwrouter, as john, ping fwclient across the LAN:

$ ping -c 2 192.168.218.10
PING 192.168.218.10 (192.168.218.10) 56(84) bytes of data.
64 bytes from 192.168.218.10: icmp_seq=1 ttl=64 time=0.401 ms
64 bytes from 192.168.218.10: icmp_seq=2 ttl=64 time=0.469 ms

--- 192.168.218.10 ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 1002ms
rtt min/avg/max/mdev = 0.401/0.435/0.469/0.034 ms

The requests matched icmp type echo-request accept; the replies matched the established rule on their way out of fwclient. Allowing echo requests is a policy choice - some sites drop unsolicited pings - but the error-reporting types are not optional, and the IPv6 list is longer for a structural reason. An IPv6 stack cannot function without its discovery exchanges: router solicitations and advertisements, and neighbor solicitations and advertisements, are how IPv6 learns its gateways and replaces ARP. Dropping them does not harden a host, it breaks its connectivity. The packet-too-big type carries path-MTU information, and filtering it is a classic way to produce the "small packets work, large ones hang" failure Chapter 17 diagnoses; the same reasoning covers the IPv4 destination-unreachable and time-exceeded types on the ICMP list. A host that must not answer pings can remove echo-request from both lists and keep the rest.

18.2.4. Restricting Administrative and Application Services

The application-service rules are where policy gets specific. On fwrouter, as john, ask for the allowed service and for a port that has a listener but no rule:

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

Both responders are running; only port 8080 has an allow rule. The 8081 request produced no refusal, no reset, nothing - the final drop discarded it, and curl reports its own three-second limit. A timeout rather than an error is what a drop looks like from the outside.

Now restrict a machine harder than fwclient: a DMZ web server that must answer HTTP from anywhere on its DMZ link but accept administration only from the management network. On fwserver, as john, create ~/debian-handbook/firewall/server-host.nft:

flush ruleset

define mgmt_if = "eth0"
define dmz_if  = "eth1"
define mgmt_net = 192.168.121.0/24

table inet filter {
    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 $dmz_if tcp dport 80 accept

        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-server-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 differences from the client ruleset are the policy: SSH allowed from the management network only - no LAN clause at all; HTTP open on the DMZ interface with no source restriction, because a web server's clients are not enumerable; and the final block now counts and logs what it drops, with a named counter declared at the top of the table. On fwserver, in a root shell, install, check and load - again all three print nothing on success:

# install -m 0644 /home/john/debian-handbook/firewall/server-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" tcp dport 80 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
        counter name "dropped_packets"
        limit rate 5/minute burst 2 packets log prefix "ch18-server-drop: " level info
        drop
    }
}

Test the three outcomes from fwrouter, as john. HTTP over the DMZ link is allowed:

$ curl -sS --max-time 3 http://192.168.220.10/
hello from server 80

The port-8081 responder is not running on fwserver, and no rule would allow it anyway - the request times out:

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

The SSH probes from here on use nc; its options as used in this chapter:

nc option Description
-z Scan only: connect and disconnect, send no data.
-w secs Total timeout for the connection attempt and any later I/O.
-v Verbose: report the outcome instead of exiting silently.

And SSH from the router is dropped, because the router arrives over the DMZ interface and no rule allows SSH from there:

$ nc -z -w3 192.168.220.10 22

The command prints nothing and exits with status 1 after its three second timeout - the third outcome, a drop. Administration still works: an SSH session to fwserver over the management network matches the eth0 rule. The failure modes separate cleanly: if the port were merely closed, the probe would have reported a refused connection within milliseconds.

One more property of this ruleset is worth a test, because it is the one a firewall is for: the policy is enforced where the traffic arrives. fwclient reaches fwserver only through fwrouter, which has no filter loaded yet and forwards everything. From fwclient, as john:

$ curl -sS --max-time 3 http://192.168.220.10/
hello from server 80
$ curl -sS --max-time 3 http://192.168.220.10:8081/
curl: (28) Connection timed out after 3002 milliseconds

The allowed request crossed two networks and came back; the forbidden one crossed the router fine and was dropped by fwserver itself. The router's own policy is the next ruleset. On fwrouter, as john, create ~/debian-handbook/firewall/router-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 {
    counter input_drops {}

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

        ct state invalid counter name input_drops 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

        icmp type { echo-request, destination-unreachable, time-exceeded, parameter-problem } 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 input_drops
        limit rate 5/minute burst 2 packets log prefix "ch18-router-input: " level info
        drop
    }

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

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

This is the client ruleset's administrative section with a router's twist: SSH is allowed from the management network and from the LAN, and the input chain counts and logs its drops. On fwrouter, in a root shell, install, check and load - the three commands print nothing when they succeed:

# install -m 0644 /home/john/debian-handbook/firewall/router-host.nft /etc/nftables.conf
# nft -c -f /etc/nftables.conf
# nft -f /etc/nftables.conf

The forward chain in this file is policy drop with no rules, which stops all transit traffic through the router - deliberate for now, because the forward policy arrives with the NAT ruleset in Section 18.4. The input policy is testable immediately. From fwclient, as john, SSH to the router over the LAN is allowed:

$ nc -z -w3 192.168.218.2 22
Connection to 192.168.218.2 22 port [tcp/ssh] succeeded!

On fwremote, as john, the same probe against the router's WAN address times out - exit status 1, no output after the wait:

$ nc -z -w3 192.168.219.2 22

The untrusted network gets no SSH. The router's access rules now read: administration from the management network, work from the LAN, nothing from the WAN.

The section has now produced two of the three answers a connection attempt can receive. The SSH probe to the router over the LAN connected immediately: allowed and answered. The dropped probes - SSH to fwserver, SSH to the router's WAN address - waited out their timeouts in silence. The third answer is the one a firewall never gives, and telling it apart from a drop is the single most useful skill in this chapter. Against a port that no firewall blocks but nothing listens on, the kernel answers at once. From fwclient, as john, with the verbose flag so the failure is visible:

$ nc -v -w3 127.0.0.1 9999
nc: connect to 127.0.0.1 port 9999 (tcp) failed: Connection refused

The packet reached the TCP stack through the loopback rule, found no listener, and the kernel sent a reset: connection refused means the path works and the port is simply closed. The three outcomes read as diagnosis: refused - the packet arrived and something answered, so the fault is the service; connected - nothing to find; timed-out silence - a drop somewhere, or no route to the target, and that is where Section 18.5's tools take over. Refused means "no one home"; timed out means "someone removed the doorbell".