
Recall first from SSH hardening and packet diagnosis
- Verify a fresh key login before disabling other SSH authentication methods.
- Forwarding direction determines where the listener and destination connection exist.
- A reachable host does not prove a service is listening, and a local listener does not prove a remote client can reach it
Netfilter, iptables chains and connection state
3 min readThe previous lesson hardened SSH access and taught socket-based packet diagnosis. This lesson answers how netfilter, iptables and nftables filter traffic, and how to recover when a firewall change locks you out.
Netfilter is the Linux kernel framework that exposes packet-processing hooks for filtering, connection tracking and related functions. A hook is a point where registered processing can examine traffic. A firewall policy uses matches, such as protocol and destination port, and verdicts, such as accept or drop. Drop silently discards; reject sends a suitable error response.
For ordinary routed IP traffic, arriving packets reach prerouting processing before a routing decision. Packets destined for this machine take the input path; packets routed onward take forwarding; locally generated packets take output. Outgoing traffic reaches postrouting. A bridge or container can introduce additional paths, so begin with the simple host before generalizing.
Network Address Translation changes packet addresses, and sometimes ports, while preserving information needed to translate matching replies. Iptables organizes rules into tables and ordered chains. Its default filter table has INPUT, OUTPUT and FORWARD. nat performs address translation at relevant hooks. mangle changes selected packet properties, such as marks used by routing or traffic policy. iptables -t nat -S selects nat; omitting -t selects filter. Review iptables table semantics.
Connection tracking, commonly called conntrack, maintains kernel records relating packets to flows and their reply directions. It recognizes states including NEW, ESTABLISHED, RELATED and INVALID. These are firewall tracking states, not identical to TCP's socket states. UDP flows can be tracked despite having no TCP handshake. RELATED includes recognized associated traffic, such as certain ICMP errors; protocol helper behavior depends on explicit configuration.
A stateful host policy commonly accepts established replies and related traffic, accepts loopback, then permits specific new inbound services. The following is the contents of a proposed lab-v4.rules file for a clean, disposable IPv4 host. It replaces the filter table on load. It is an alternative to UFW, firewalld and the later nft example:
*filter
:INPUT DROP [0:0]
:FORWARD DROP [0:0]
:OUTPUT ACCEPT [0:0]
-A INPUT -i lo -j ACCEPT
-A INPUT -m conntrack --ctstate INVALID -j DROP
-A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
-A INPUT -p icmp -j ACCEPT
-A INPUT -p tcp -m conntrack --ctstate NEW -m multiport --dports 22,80,443 -j ACCEPT
COMMIT
Save the existing IPv4 configuration with sudo iptables-save > before-v4.rules. Check with sudo iptables-restore --test < lab-v4.rules; apply with sudo iptables-restore < lab-v4.rules only from a recoverable console. Restore the saved file through iptables-restore if needed. sudo iptables -L -n -v --line-numbers exposes rule order and counters. These counters are observations, not proof of end-to-end application success.
The example allows new inbound TCP only on the listed services, plus ICMP and tracked traffic. It assumes static IPv4 addressing; a DHCP client may need an explicit inbound UDP server-port-67 to client-port-68 allowance. It does not configure IPv6. It leaves outbound traffic allowed, so DNS client replies can match tracked state without opening inbound DNS service to everyone. Default FORWARD drop makes it unsuitable as a gateway until forwarding rules are designed.
Going deeperTracking consumes resources and preserves earlier decisions
Inspect net/netfilter/nf_conntrack_core.c and net/netfilter/nf_nat_core.c for implementation. Flow records hold original/reply endpoint tuples, protocol state, expiration and associated translation data. Floods can exhaust tracking capacity; inspect net.netfilter.nf_conntrack_count, net.netfilter.nf_conntrack_max and kernel logs. Higher limits consume memory. An ESTABLISHED allowance can preserve existing flows after new-connection policy changes, so test fresh connections.
nftables and a two-interface gateway
4 min readNftables is the successor ruleset framework to iptables, using the nft tool and kernel nf_tables infrastructure. It supports sets, common expressions and transactional batches. Unlike iptables' built-in chains, an nft base chain explicitly declares its type, hook, priority and policy. An ordinary chain needs a jump from another chain to process traffic. The inet family can filter both IPv4 and IPv6. See nftables chain configuration.
For an isolated host with no existing firewall manager or lab_host table, this file defines a small dual-family host policy:
table inet lab_host {
chain input {
type filter hook input priority 0; policy drop;
iifname "lo" accept
ct state invalid drop
ct state established,related accept
ip protocol icmp accept
meta l4proto ipv6-icmp accept
tcp dport { 22, 80, 443 } ct state new counter accept
}
chain forward {
type filter hook forward priority 0; policy drop;
}
chain output {
type filter hook output priority 0; policy accept;
}
}
Check sudo nft -c -f lab-host.nft before sudo nft -f lab-host.nft, then inspect sudo nft list ruleset. The batch applies transactionally, but a valid transaction can still lock you out. This example assumes static lab addressing; add DHCP rules if required. Allowing ICMPv6 preserves functions such as Neighbor Discovery and packet-too-big reporting. This is deliberately broader than a tuned product policy.
Do not repeatedly load the example into an existing table: rules can accumulate. Manage replacement explicitly through your distribution's nftables configuration service. Nor should you run flush ruleset on a machine with container, VPN or manager-owned rules. An accept verdict in one nft base chain does not guarantee a later base chain at the same hook will accept the packet; inspect all applicable chains.
1Separate migration from backend selection
iptables --version reports whether the command uses an nf_tables compatibility backend or the legacy backend. The iptables command name therefore does not prove legacy kernel implementation. iptables-translate -A INPUT -p tcp --dport 22 -j ACCEPT illustrates command translation; iptables-restore-translate -f before-v4.rules translates a saved ruleset. Review unsupported extensions and semantics, as the migration guide requires. Do not independently edit compatibility-generated rules with nft.
2Understand gateway requirements
Source NAT changes the sender; destination NAT changes the destination. MASQUERADE is source NAT using the outgoing interface's address, useful when an uplink address changes. NAT still requires an explicit forwarding policy.
Consider an IPv4-only isolated exercise: the board's eth1 is 192.168.60.1/24, eth0 reaches an upstream router, and clients on eth1 use the board as their default gateway. The board itself needs a working uplink route and DNS. Clients need their own valid DNS configuration too.
3Enable routing and define transit policy
The following alternative uses iptables on a clean gateway with no competing rules. Retain a separate host INPUT policy for the board's own services:
sudo sysctl -w net.ipv4.ip_forward=1
sudo iptables -A FORWARD -i eth1 -o eth0 -s 192.168.60.0/24 \
-m conntrack --ctstate NEW,ESTABLISHED,RELATED -j ACCEPT
sudo iptables -A FORWARD -i eth0 -o eth1 -d 192.168.60.0/24 \
-m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
sudo iptables -P FORWARD DROP
sudo iptables -t nat -A POSTROUTING -s 192.168.60.0/24 -o eth0 -j MASQUERADE
These append operations assume no earlier terminating rule defeats them. With the earlier host example, FORWARD contains only its policy, so appended allowances are evaluated before that policy. Record the original forwarding sysctl and restore it afterward. Persistent routing settings usually belong in a deliberate /etc/sysctl.d/ file; rule persistence is a separate distribution mechanism. The sample permits LAN-initiated forwarding broadly; a product should restrict destinations and protocols to its requirements.
For native nftables, place equivalent forwarding matches in the managed forward base chain. The IPv4 NAT component alone could be:
table ip lab_nat {
chain postrouting {
type nat hook postrouting priority 100; policy accept;
ip saddr 192.168.60.0/24 oifname "eth0" masquerade
}
}
This snippet supplies no forwarding permission. Stateful NAT establishes a mapping from the first packet, then uses the stored mapping for subsequent packets and reverse traffic; every packet does not independently select a fresh NAT rule. Review the nftables NAT documentation. Without NAT, the upstream network needs a route back to the client subnet. With NAT, the upstream sees the board's source address.
On an embedded image, the tool being present does not prove the required kernel Netfilter, conntrack and NAT features are built or available as modules. Build userspace tools for the target architecture and package matching kernel support. Measure tracking memory and forwarding CPU cost under actual traffic before assuming a small board can sustain the desired gateway workload.
Firewall frontends, common mistakes and recovery
5 min readUFW, the Uncomplicated Firewall, offers a simpler host-policy interface. On a clean Ubuntu lab using UFW alone, inspect the existing policy and permit the actual SSH port before enabling a default incoming deny:
sudo ufw status verbose
sudo ufw default deny incoming
sudo ufw default allow outgoing
sudo ufw allow 22/tcp
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
sudo ufw enable
sudo ufw status numbered
This enables persistent UFW policy. Confirm /etc/default/ufw has the intended IPv6 setting and inspect both families. Default incoming deny does not prohibit every ICMP or essential infrastructure packet: UFW has supporting rules. If a nonstandard SSH port is in use, permit that instead of assuming port 22. Review the UFW manual for ordering and remote management behavior.
An explicit sudo ufw deny 23/tcp demonstrates denying a service; it is redundant under default deny unless another rule permits it. Rules are ordered, so a deny after a matching broad allow may not do what you intend. Inspect numbered rules and delete or narrow the broad allowance rather than accumulating contradictions. Where practical, replace the broad SSH allowance with an allowance from your actual management subnet. Make the replacement before removing the working path.
Firewalld uses zones, named policy collections applied according to interface or source assignment. A connection assigned to the wrong zone can defeat an otherwise correct service allowance. On a separate firewalld-managed lab, inspect before changing:
sudo firewall-cmd --get-active-zones
sudo firewall-cmd --get-zone-of-interface=eth0
sudo firewall-cmd --zone=public --list-all
sudo firewall-cmd --zone=public --add-service=ssh
sudo firewall-cmd --zone=public --add-service=http
sudo firewall-cmd --zone=public --add-service=https
These modify runtime configuration in public; they help only if that zone actually handles the intended traffic. Confirm the assignment through the connection manager rather than blindly moving the interface. After a successful remote test, repeat the intended additions with --permanent, for example sudo firewall-cmd --permanent --zone=public --add-service=ssh, and likewise for http and https. Runtime changes are immediate; permanent changes normally take effect on reload or restart. Compare both configurations before sudo firewall-cmd --reload, which reloads permanent policy. See the firewalld service guide.
Adding those services does not remove preexisting allowances. Inspect runtime and permanent service lists, ports, rich rules and zone targets before claiming only three services are exposed. An SSH service definition normally means TCP 22; use the actual port or a suitable custom definition when different. UFW and firewalld are alternatives here, not layers to activate together.
1Diagnose the symptom before editing policy
| Symptom | Possible cause | Diagnose | Corrective action |
|---|---|---|---|
| Static address disappears | Only temporary kernel state changed | Compare manager profile and post-reboot address | Persist through the actual owner |
| Gateway remains INCOMPLETE | Wrong link, prefix, gateway or unavailable peer | Inspect route get, carrier and neighbors | Correct addressing or repair the local path |
| Numeric destination works, name fails | Resolver path or queried record problem | Compare getent, resolvectl and dig | Repair the responsible naming configuration |
| SSH connection refused | No listener, wrong port or explicit rejection | Inspect ss, service/socket units and rules | Start the correct listener or correct the port |
| SSH connection times out | Routing, dropping policy or unreachable peer | Compare client route, server counters and packet arrival | Repair the identified failing boundary |
| Permission denied after SSH connects | User, key or authentication policy mismatch | Read ssh -vv and server journal | Correct credentials or effective sshd policy |
| Web works locally only | Loopback bind or remote-path filtering | Compare bind address and external test | Bind intentionally and permit the required path |
| Firewall rule appears ineffective | Wrong family, chain, zone, order or existing flow | Inspect effective rules and test a new connection | Change the correct owner and matching path |
2Add measured brute-force defenses
Brute-force attempts repeatedly guess credentials. Key-only authentication and AllowUsers remove common password and account paths; source-restricted access further reduces exposure. Fail2ban watches authentication failures and installs temporary bans through a configured firewall action. It needs a working log source, matching filter and compatible action; it is not a cryptographic defense or a replacement for updates.
On a journal-based system with the required Python journal support installed, an example /etc/fail2ban/jail.d/sshd.local is:
[sshd]
enabled = true
backend = systemd
port = ssh
maxretry = 5
findtime = 10m
bantime = 10m
These are chosen lab thresholds. Set the actual port and a firewall-compatible action. Run sudo fail2ban-client -t before restarting; inspect sudo fail2ban-client status sshd and the journal. The systemd backend reads journal entries instead of a logpath, per the Fail2ban configuration. Consider shared client addresses before testing bans.
3Prove the intended access boundary
Run sudo ss -tlnp on the board, inspect the chosen manager's rules, and open fresh SSH, HTTP and HTTPS connections from a second host where services exist. Test an intentionally blocked lab service too. No listener is not proof of a firewall block; use a controlled listener when testing rejection. A working existing SSH session does not prove a new session is allowed. On boards, retain serial access and repeat the complete check after reboot.
Try it
1 min readContinue with Configure, harden and verify a networked lab board in the lesson's lab and practice pack. Configure a static address through the installed owner, then collect separate routing, DNS and reachability evidence before and after reboot. Prove a fresh key-only SSH login, use a client alias and one deliberately scoped tunnel, and evaluate your chosen firewall's allowed and blocked paths from a second machine. Use the practice pack for diagnosis scenarios and record your recovery method before moving to Bash scripting fundamentals.
Key takeaways
- INPUT protects this host; FORWARD controls traffic routed through it.
- Socket inspection, firewall inspection and remote connection tests provide different evidence.
- Address translation grants no forwarding permission; forwarding and translation are separate decisions
- Established flows can survive a policy change, so prove access with fresh connections from a separate client
Reflect
- Explain to a colleague, in two sentences: analyze packet traversal through Netfilter chains, connection tracking and address translation.
- Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
- What surprised you when you ran the commands yourself?
On a real board
Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.
References and further reading
- Man pageiptables tables, chains and targets
- Official docsnftables project documentation
- Official docsfirewalld: open a port or service
Official documentation first. Links checked when the lesson was published.