Skip to content
Network debugging for platform engineers · Chapter 11 of 21 Day 9: Firewall and NAT

Day 9: Firewall and NAT

Goal: You read a machine’s complete rule set with nft, prove with counters whether a rule matches at all, read the connection tracking table with conntrack, set up a port forward (DNAT) and find two faults that aren’t in any rule: a forward that only works from outside, and a connection that stays with the old destination after a rule change · Duration: approx. 90 min · Prerequisite: Day 8 (router without its own filter table, only table ip nat from Day 0)

Briefing

  • On Day 4 you recognized firewalls from the outside: DROP looks like a timeout, REJECT like a missing service. Today you look inside. On Linux that has been nftables for years; on current systems iptables is only a translation layer in front of it.
  • Every firewall with NAT comes with conntrack, the kernel’s connection tracking table. It remembers every connection including its translation. That is why rules you change apply only to new connections – the cause of today’s nastiest fault.
  • Kubernetes builds Services with exactly these building blocks (DNAT to pod addresses, conntrack), whether via kube-proxy with iptables or nftables, or via eBPF as with Cilium. What you learn today explains on Day 12 why a Service sometimes talks to a pod that no longer exists.

Drill 1: Reading all rules

# on netz
# Everything the router has in terms of rules
#   list ruleset   all tables, chains and rules of this namespace
sudo ip netns exec router nft list ruleset
# With handles: the number used to delete or replace individual rules
#   -a                     show handles
#   list table ip nat      only this table
sudo ip netns exec router nft -a list table ip nat

Expected:

table ip nat {
    chain postrouting {
        type nat hook postrouting priority srcnat; policy accept;
        oifname "wan0" masquerade
    }
}
table ip nat { # handle 1
    chain postrouting { # handle 1
        type nat hook postrouting priority srcnat; policy accept;
        oifname "wan0" masquerade # handle 2
    }
}

This is how you read a chain:

Part Meaning
table ip nat table named nat for IPv4 (ip); inet would mean IPv4 and IPv6
hook postrouting point on the packet’s path: just before it leaves the machine
priority srcnat order relative to other chains on the same hook
policy accept what happens to packets no rule finally matches
oifname "wan0" masquerade condition (output wan0), then action (replace the source)

The hooks a packet passes are always the same: prerouting (just arrived), then input (for this machine) or forward (being forwarded), finally output (locally generated) and postrouting (going out). DNAT belongs in prerouting, SNAT and masquerade in postrouting, filters in input or forward.

Many tools – Docker, kube-proxy, ufw – still write their rules with iptables. On Ubuntu that is iptables-nft: it writes into the same nftables tables. That has a catch:

# on netz
# Which iptables variant?
iptables -V
# iptables doesn't see the chain created by nft as its own
#   -t nat   table nat
#   -S       print rules as commands
sudo ip netns exec router iptables -t nat -S | head -1
# Create a rule with iptables in web …
#   -A INPUT -p tcp --dport 9999 -j DROP   append to the INPUT chain: drop TCP port 9999
sudo ip netns exec web iptables -A INPUT -p tcp --dport 9999 -j DROP
# … and look at it with nft
sudo ip netns exec web nft list ruleset

Expected:

iptables v1.8.10 (nf_tables)
# Table `nat' contains incompatible base-chains, use 'nft' tool to list them.
table ip filter {
    chain INPUT {
        type filter hook input priority filter; policy accept;
        tcp dport 9999 counter packets 0 bytes 0 drop
    }
}

The rule: nft list ruleset shows everything, iptables -S only what iptables created itself. On a Kubernetes node with Cilium and Docker, that is a big difference. Clean up:

# on netz
#   delete table ip filter   the entire table iptables created
sudo ip netns exec web nft delete table ip filter

Save your progress? Sign up for free

Drill 2: Does the rule match at all?

A rule that never matches is the most common firewall fault – wrong port, wrong interface, wrong order. Counters answer the question without guesswork. For this you set up the first port forward: whoever addresses the router on its outside address 192.168.100.2, port 8080, ends up at the web server.

# on netz
# Chain for DNAT at the router's input
#   hook prerouting priority dstnat   right after receipt, before the routing decision
sudo ip netns exec router nft add chain ip nat prerouting '{ type nat hook prerouting priority dstnat; }'
# Port forward: only packets arriving via wan0
#   iifname wan0                  input interface wan0 (from the VM, “outside”)
#   tcp dport 8080                to port 8080
#   counter                       count packets and bytes
#   dnat to 10.2.0.10:80          rewrite the destination to web, port 80
sudo ip netns exec router nft add rule ip nat prerouting iifname wan0 tcp dport 8080 counter dnat to 10.2.0.10:80
# From outside, i.e. from the VM itself
curl -s http://192.168.100.2:8080/
sudo ip netns exec router nft list chain ip nat prerouting

Expected:

hallo von web
table ip nat {
    chain prerouting {
        type nat hook prerouting priority dstnat; policy accept;
        iifname "wan0" tcp dport 8080 counter packets 1 bytes 60 dnat to 10.2.0.10:80
    }
}

packets 1: only the first packet of the connection (the SYN) passes through the NAT chain. The kernel translates all further packets from conntrack without consulting the rules again (Drill 3). If the counter is at 0 after a test, the rule didn’t match – then you look there, not at the service. Before a new test you reset the counters:

# on netz
#   reset rules table ip nat   set the counters of all rules in this table to 0 (prints the rules while doing so)
sudo ip netns exec router nft reset rules table ip nat >/dev/null
sudo ip netns exec router nft list chain ip nat prerouting | grep counter

Expected:

        iifname "wan0" tcp dport 8080 counter packets 0 bytes 0 dnat to 10.2.0.10:80

Save your progress? Sign up for free

Drill 3: The connection tracking table

# on netz
# A fetch to the internet, through the router's NAT
sudo ip netns exec client curl -s -o /dev/null -w '%{http_code}\n' https://example.com/
# What did the router remember?
#   conntrack -L       list the connection tracking table
#   -p tcp --dport 443 only TCP to port 443
sudo ip netns exec router conntrack -L -p tcp --dport 443

Expected (addresses, ports and remaining time differ):

200
tcp      6 119 TIME_WAIT src=10.1.0.10 dst=172.66.147.243 sport=42786 dport=443 src=172.66.147.243 dst=192.168.100.2 sport=443 dport=42786 [ASSURED] mark=0 use=1
conntrack v1.4.8 (conntrack-tools): 1 flow entries have been shown.

Each entry has two directions. The first (src=10.1.0.10 dst=172.66…) is the packet as it arrived. The second is the expected reply: it comes from 172.66… and goes to 192.168.100.2 – not to 10.1.0.10. That a different address appears there is the NAT: the router replaced the source with its outside address (masquerade). 119 is the remaining time in seconds, ASSURED means: there were replies in both directions.

How an entry is created and changes is shown live by conntrack -E:

# on netz
# Follow events for 3 seconds while a fetch runs
#   ( … ) &        start the fetch in the background after 1 second
#   timeout 3      end conntrack -E after 3 seconds
#   -E -p tcp      events for TCP
( sleep 1; sudo ip netns exec client curl -s -o /dev/null http://web.firma.lab/ ) &
sudo ip netns exec router timeout 3 conntrack -E -p tcp

Expected (ports differ):

    [NEW] tcp      6 120 SYN_SENT src=10.1.0.10 dst=10.2.0.10 sport=38536 dport=80 [UNREPLIED] src=10.2.0.10 dst=10.1.0.10 sport=80 dport=38536
 [UPDATE] tcp      6 60 SYN_RECV src=10.1.0.10 dst=10.2.0.10 sport=38536 dport=80 src=10.2.0.10 dst=10.1.0.10 sport=80 dport=38536
 [UPDATE] tcp      6 432000 ESTABLISHED src=10.1.0.10 dst=10.2.0.10 sport=38536 dport=80 src=10.2.0.10 dst=10.1.0.10 sport=80 dport=38536 [ASSURED]
 [UPDATE] tcp      6 120 FIN_WAIT src=10.1.0.10 dst=10.2.0.10 sport=38536 dport=80 src=10.2.0.10 dst=10.1.0.10 sport=80 dport=38536 [ASSURED]
 [UPDATE] tcp      6 30 LAST_ACK src=10.1.0.10 dst=10.2.0.10 sport=38536 dport=80 src=10.2.0.10 dst=10.1.0.10 sport=80 dport=38536 [ASSURED]
 [UPDATE] tcp      6 120 TIME_WAIT src=10.1.0.10 dst=10.2.0.10 sport=38536 dport=80 src=10.2.0.10 dst=10.1.0.10 sport=80 dport=38536 [ASSURED]
conntrack v1.4.8 (conntrack-tools): 6 flow events have been shown.

These are the TCP states from Day 5, only from the router’s point of view. Note the remaining time for ESTABLISHED: 432,000 seconds, five days. A connection that is silent that long stays in the table that long – with its translation from back then.

Command Purpose
conntrack -L list the table, filter with -p, --dport, -s, -d
conntrack -C number of entries (compare against net.netfilter.nf_conntrack_max)
conntrack -E events live
conntrack -D … delete matching entries (Challenge)
conntrack -F delete all entries – existing connections usually break afterwards

Save your progress? Sign up for free

Exercise

A colleague at site A reports: “The port forward 192.168.100.2:8080 works from outside, but not from my machine.” Check it from client, prove with the counter why, and fix it so that both paths work.

Solution

# on netz
sudo ip netns exec router nft reset rules table ip nat >/dev/null
sudo ip netns exec client curl -sS -m3 http://192.168.100.2:8080/
sudo ip netns exec router nft -a list chain ip nat prerouting

Expected (handle numbers grow with every change to the table; in a freshly built lab they are 3 and 4 – use your number in the next step):

curl: (7) Failed to connect to 192.168.100.2 port 8080 after 0 ms: Couldn't connect to server
table ip nat {
    chain prerouting { # handle 3
        type nat hook prerouting priority dstnat; policy accept;
        iifname "wan0" tcp dport 8080 counter packets 0 bytes 0 dnat to 10.2.0.10:80 # handle 4
    }
}

The counter stays at 0: client’s packet comes in via eth-a, not via wan0 – the rule doesn’t match. Without DNAT, 192.168.100.2:8080 is a port on the router itself, and nobody listens there: Connection refused (Day 4). Fix: the forward should be tied to the address, not to the interface.

# on netz
# delete the old rule by its handle
#   delete rule ip nat prerouting handle 4   exactly this rule (number from the output above)
sudo ip netns exec router nft delete rule ip nat prerouting handle 4
#   ip daddr 192.168.100.2   destination is the router's outside address – no matter where the packet comes from
sudo ip netns exec router nft add rule ip nat prerouting ip daddr 192.168.100.2 tcp dport 8080 counter dnat to 10.2.0.10:80
sudo ip netns exec client curl -sS -m3 http://192.168.100.2:8080/
curl -s -m3 http://192.168.100.2:8080/

Expected:

hallo von web
hallo von web

This is enough here because client and web are in different networks: web’s reply goes back through the router, which translates it back. If both were in the same network, web would reply directly to client – with its own address instead of 192.168.100.2, and client would throw the reply away. Then you additionally need SNAT (“hairpin NAT”). Many home routers and cloud load balancers can’t do exactly that.

Save your progress? Sign up for free

Challenge

Build a “Service address” as in Kubernetes: 10.9.9.9:5353 (UDP) belongs to no machine; the router translates it to a backend service.

# on netz
# Two UDP services that identify themselves by name
#   socat UDP-RECVFROM:5353,fork   accept each datagram individually, reply goes to the sender
#   SYSTEM:'echo …'                output of this command is the reply
sudo systemd-run --unit=udp-web ip netns exec web socat UDP-RECVFROM:5353,fork SYSTEM:'echo antwort von web'
sudo systemd-run --unit=udp-db ip netns exec db socat UDP-RECVFROM:5353,fork SYSTEM:'echo antwort von db'
# Service address 10.9.9.9 points to web
sudo ip netns exec router nft add rule ip nat prerouting ip daddr 10.9.9.9 udp dport 5353 counter dnat to 10.2.0.10
# A client with a fixed source port, like a long-lived DNS resolver
#   socat -t1 -   send text from stdin, wait 1 second for the reply
#   UDP:10.9.9.9:5353,sourceport=40000   destination, always the same source port
echo ping | sudo ip netns exec client socat -t1 - UDP:10.9.9.9:5353,sourceport=40000

Expected:

antwort von web

Now the service moves. A colleague switches the rule to db:

# on netz
# Look up the handle of the Service rule and replace the rule
sudo ip netns exec router nft -a list chain ip nat prerouting | grep 10.9.9.9
#   replace rule … handle <n>   replace the rule in place with a new one (number from the line above)
sudo ip netns exec router nft replace rule ip nat prerouting handle 6 ip daddr 10.9.9.9 udp dport 5353 counter dnat to 10.2.0.20
echo ping | sudo ip netns exec client socat -t1 - UDP:10.9.9.9:5353,sourceport=40000

Expected (handle 6 in a fresh lab, otherwise your number):

        ip daddr 10.9.9.9 udp dport 5353 counter packets 1 bytes 33 dnat to 10.2.0.10 # handle 6
antwort von web

The rule says db, the reply comes from web. Find the reason, prove it and fix it without touching the rule.

Solution

# on netz
# Cross-check with a different source port
echo ping | sudo ip netns exec client socat -t1 - UDP:10.9.9.9:5353,sourceport=40001
# What is in the connection tracking table?
sudo ip netns exec router conntrack -L -p udp --dport 5353

Expected (remaining times differ):

antwort von db
udp      17 27 src=10.1.0.10 dst=10.9.9.9 sport=40000 dport=5353 src=10.2.0.10 dst=10.1.0.10 sport=5353 dport=40000 mark=0 use=1
udp      17 28 src=10.1.0.10 dst=10.9.9.9 sport=40001 dport=5353 src=10.2.0.20 dst=10.1.0.10 sport=5353 dport=40001 mark=0 use=1
conntrack v1.4.8 (conntrack-tools): 2 flow entries have been shown.

The new port 40001 lands at db, the old 40000 still at web. UDP has no connection teardown; the entry for 40000 lives as long as packets keep coming (30 seconds after the last one, 120 with traffic in both directions). The NAT rule is never consulted again for this “connection”. A client that sends regularly – a DNS resolver, a syslog agent, a metrics exporter – talks to the old destination for hours this way. Solution: delete the affected entries, then the new rule takes effect.

# on netz
#   -D -p udp --orig-port-dst 5353   delete all UDP entries whose original destination port is 5353
sudo ip netns exec router conntrack -D -p udp --orig-port-dst 5353 >/dev/null
echo ping | sudo ip netns exec client socat -t1 - UDP:10.9.9.9:5353,sourceport=40000

Expected:

conntrack v1.4.8 (conntrack-tools): 2 flow entries have been deleted.
antwort von db

This is exactly how kube-proxy cleans up UDP entries for Services after a change. If that doesn’t happen – older versions, a custom proxy, a node under load – pods talk for minutes after the DNS pod restarts to an address that no longer exists. The symptom “DNS doesn’t work on some pods, but does on others” often has exactly this cause.

Save your progress? Sign up for free

Checkpoint

# on netz
# Forward from inside and outside
sudo ip netns exec client curl -s http://192.168.100.2:8080/
curl -s http://192.168.100.2:8080/
# Service address points to db, also for the old source port
echo ping | sudo ip netns exec client socat -t1 - UDP:10.9.9.9:5353,sourceport=40000
# no iptables filter table left in web
sudo ip netns exec web nft list tables | wc -l

Expected:

hallo von web
hallo von web
antwort von db
0

Clean up

# on netz
# Remove port forward and Service address: the entire prerouting chain
sudo ip netns exec router nft delete chain ip nat prerouting
sudo systemctl stop udp-web udp-db
# socat exits with an error code when stopped; reset-failed forgets the units so the names are free
sudo systemctl reset-failed udp-web udp-db
# Empty the router's connection tracking table (lab only!)
sudo ip netns exec router conntrack -F
sudo ip netns exec router nft list ruleset

Expected:

conntrack v1.4.8 (conntrack-tools): connection tracking table has been emptied.
table ip nat {
    chain postrouting {
        type nat hook postrouting priority srcnat; policy accept;
        oifname "wan0" masquerade
    }
}

Interview note

“You changed a firewall rule, but some clients behave as before. Why?” conntrack: NAT rules and many filter decisions apply only to the first packet of a connection; everything after that comes from the connection tracking table. With UDP, entries live as long as traffic flows. Proof with conntrack -L, remedy with conntrack -D. Bonus points: nft list ruleset instead of iptables -S, because iptables only shows its own chains, and counters (counter) to prove whether a rule matches at all.

Enterprise note

A full conntrack table is a classic outage on heavily loaded nodes and NAT gateways: the kernel reports nf_conntrack: table full, dropping packet, new connections fail randomly, existing ones keep running. Monitor conntrack -C against net.netfilter.nf_conntrack_max (node_exporter: node_nf_conntrack_entries and node_nf_conntrack_entries_limit) and plan enough headroom for many short connections. And before conntrack -F on a production machine: it removes the translation of all existing connections – NAT connections break afterwards.

Command Drills

Practise commands from Day 9

3 drills · approx. 8 minutes · in your browser, no VM

Task

NAT table with handles

With an account your progress is saved and drills that are due come back in your daily round. Without an account it stays in this browser only. Sign up for free

Contents

More