Skip to main content
Firewall Configuration, Egress Filtering & Hardening
Lesson 7 of 12

Firewall Configuration, Egress Filtering & Hardening

Configure stateful host firewalls using nftables and ufw, enforce dual-stack default-deny ingress and egress policies, and prevent common locking or bypass mistakes.

Intermediate 26 min Networking
Authorised environments only — The techniques described here are used only in training labs and on systems you own or have written permission to test.

Learning objectives

  • Explain the difference between stateless packet filtering and stateful connection tracking in Netfilter
  • Configure a dual-stack inet nftables ruleset with default-deny input, forward, and output policies
  • Apply egress filtering to restrict unauthorized outbound connections and command-and-control callbacks
  • Manage host firewall rules safely with ufw and verify the active kernel ruleset

Recommended first: Network Security Fundamentals & Protocol WeaknessesNetwork Scanning & Service Enumeration with NmapSuspicious Network Traffic: Beaconing, Tunneling & Exfil

#Why this matters

Earlier lessons showed how port scans uncover exposed services and how compromised hosts phone home using covert beacons or reverse shells. A host firewall is the first line of defence that shrinks both risks at the kernel boundary. Even when a network perimeter firewall exists, every server and workstation should enforce its own local policy.

Most administrators filter only inbound traffic and leave outbound traffic wide open. If an attacker exploits a web application on port 443, an unrestricted outbound policy lets the host download extra tools, tunnel traffic out, or exfiltrate data. Default-deny ingress paired with disciplined egress filtering turns a minor foothold into a dead end.

#Stateful filtering and Netfilter hooks

A stateless packet filter examines each packet in isolation using headers such as source IP, destination IP, and port. Maintaining stateless rules quickly becomes fragile because you must also allow arbitrary high-numbered ephemeral return ports.

A stateful firewall solves this with connection tracking (conntrack). The kernel records active sessions in a state table and classifies each packet as new, established, related, or invalid. Once an inbound or outbound connection is approved as new, its return packets match established,related and pass without opening wide ephemeral port ranges.

  1. Packet arrivesNetfilter hook (input or output)
  2. Drop invalidct state invalid -> drop
  3. Fast pathct state established,related -> accept
  4. Inspect new flowMatch explicit allow rules (port, subnet)
  5. Base policyUnmatched packets hit policy drop

On modern Linux systems, nftables replaces legacy iptables, ip6tables, and arptables with one unified framework. Unlike iptables, which requires separate commands and tables for IPv4 and IPv6, nftables supports the inet family to filter both address families together and loads rules atomically so there is no gap during reloads.

Feature iptables (legacy) nftables (current) ufw (frontend)
IPv4 and IPv6 Separate tools (iptables, ip6tables) Single inet table Manages both via backend
Rule reload Non-atomic per rule Atomic file replacement Wrapper around Netfilter
Best suited for Legacy scripts Servers, routers, automation Quick single-host policies

#Building a hardened nftables ruleset

Suppose a lab web server at 10.10.10.20 serves HTTPS on port 443, accepts SSH only from an admin subnet 10.10.10.0/24, resolves DNS only through an internal resolver 10.10.10.2, and synchronises time over NTP (123/udp). All other inbound, forwarded, and outbound traffic must be dropped and logged.

Save the policy in /etc/nftables.conf:

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

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

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

        # Allow essential ICMPv4 and ICMPv6 (Neighbor Discovery and PMTUD)
        ip protocol icmp icmp type { echo-request, destination-unreachable, time-exceeded } accept
        ip6 nexthdr ipv6-icmp icmpv6 type { echo-request, destination-unreachable, packet-too-big, time-exceeded, nd-neighbor-solicit, nd-neighbor-advert, nd-router-advert } accept

        # Admin SSH only from management subnet, HTTPS from anywhere
        ip saddr 10.10.10.0/24 tcp dport 22 ct state new accept
        tcp dport 443 ct state new accept

        limit rate 5/minute log prefix "nft-input-drop: "
    }

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

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

        oif "lo" accept
        ct state invalid drop
        ct state established,related accept

        # Allow essential ICMP and approved egress services only
        ip protocol icmp accept
        ip6 nexthdr ipv6-icmp accept
        ip daddr 10.10.10.2 udp dport 53 accept
        ip daddr 10.10.10.2 tcp dport 53 accept
        udp dport 123 accept

        limit rate 5/minute log prefix "nft-output-drop: "
    }
}

Before loading the file, validate syntax with nft -c -f /etc/nftables.conf and verify the active kernel table afterward:

Validating and inspecting nftables in the lab
$ sudo nft -c -f /etc/nftables.conf
$ sudo nft -f /etc/nftables.conf
$ sudo nft list ruleset | head -n 12
table inet filter {
    chain input {
        type filter hook input priority filter; policy drop;
        iif "lo" accept

Notice two critical design choices here. First, chain forward uses policy drop because a standard host should never route packets between interfaces. Second, limit rate 5/minute before log prevents a flood of blocked packets from filling /var/log and exhausting disk space.

#Managing host firewalls with UFW

On Ubuntu and Debian servers, UFW (Uncomplicated Firewall) provides a concise interface that compiles rules down to the kernel firewall backend. By default, UFW denies incoming traffic but allows all outgoing traffic, which leaves egress unfiltered until you change it.

Configuring default-deny ingress and egress with UFW
$ sudo ufw default deny incoming
Default incoming policy changed to 'deny'
$ sudo ufw default deny outgoing
Default outgoing policy changed to 'deny'
$ sudo ufw allow in from 10.10.10.0/24 to any port 22 proto tcp
Rule added
$ sudo ufw allow out to 10.10.10.2 port 53
Rule added
$ sudo ufw allow out 123/udp
Rule added
$ sudo ufw enable
Firewall is active and enabled on system startup
$ sudo ufw status numbered
Status: active

     To                         Action      From
     --                         ------      ----
[ 1] 22/tcp                     ALLOW IN    10.10.10.0/24
[ 2] 10.10.10.2 53              ALLOW OUT   Anywhere
[ 3] 123/udp                    ALLOW OUT   Anywhere

#Common mistakes

  • Filtering IPv4 only: Writing rules in table ip instead of table inet leaves IPv6 completely unprotected on dual-stack hosts.
  • Leaving egress wide open: Relying solely on default deny incoming allows malware or exploited services to initiate arbitrary outbound connections.
  • Blocking all ICMPv6: Dropping Neighbor Discovery (nd-neighbor-solicit, nd-neighbor-advert) or packet-too-big breaks IPv6 connectivity and Path MTU Discovery.
  • Running competing firewall managers: Enabling ufw, firewalld, and manual nft scripts simultaneously causes rules to overwrite one another unpredictably.
  • Skipping safe rollback during remote changes: Loading a broken policy drop ruleset over SSH without testing syntax (nft -c) or scheduling a safety flush locks out remote administration.

#Summary

  • Stateful firewalls use Netfilter conntrack (established,related) so return traffic works without exposing wide ephemeral port ranges.
  • Use nftables with table inet to enforce atomic, dual-stack IPv4 and IPv6 policies across input, forward, and output chains.
  • Enforcing policy drop on the output chain (egress filtering) blocks unauthorized reverse shells, tool downloads, and data exfiltration.
  • Whether authoring nftables directly or using ufw, always allow essential ICMPv6, rate-limit logging, and verify the active kernel ruleset.

Knowledge check

Sign in to take the test, complete lessons and save your progress. Log in

Practice: test your knowledge