Lesson 12 · 45 minutes
Filter and translate in a router lab
- Make a Linux host forward packets and read the TTL change
- Write a firewall rule that drops one port, and a rule set with default deny
- Rewrite the source address with NAT and say what the server sees
The lab folder as it stands after this lesson. Unzip it in ~/krlab.
More
The zip holds every file that the course has printed up to here. To start this lesson with the files of the earlier lessons only, take the zip of the lesson before. Type the code yourself first: you learn more.
Scenario
The team of lesson 11 moves the application to a private network behind a small router. The router must pass the traffic of one client to port 8080 of the application, block everything else, and hide the client network behind its own address. You build this router in a private lab, with the rules that a real one would have, and you check what the server sees.
Recall
A connection attempt ends with "timed out", not "refused". Which firewall action fits that result?
A drop. The firewall throws the packet away and sends nothing back, so the client waits until the timeout. A reject would send an answer, and the client would see "refused" at once.
What does a router do with the TTL of a packet, and why?
It lowers the TTL by one at every hop (lesson 1). When it reaches zero, the router drops the packet and tells the sender, so a packet cannot circle for ever.
The idea
A Linux host becomes a router when it forwards: it takes a packet that arrives on one card and sends it out of another, and it does not keep the packet for itself. Forwarding is off by default. The firewall of Linux is nft (nftables). A table holds chains, a chain holds rules, and a chain is attached to a hook, a point on the path of a packet. The hook forward sees the packets that the router passes on. The hook postrouting is the last step before a packet leaves, which is where NAT changes the source address.
A stateful firewall tracks connections (ct stands for connection tracking). The rule ct state established,related accept lets the replies of a connection back in, and a new connection must match a rule of its own. With policy drop (default deny), a packet that no rule accepts is thrown away.
- Client → Router: request to 10.0.2.2, port 8080
- Router → Server: allowed, source rewritten to 10.0.2.1
- Server → Router: reply to 10.0.2.1
- Router → Client: reply, sent back to 10.0.1.2
- Scanner → Router (blocked): port 8081, dropped
Worked example
1. Build a router and make it forward
The three steps use a private lab: a client, a router and a server, each in its own network namespace (lesson 3). Your shell is the router, and you need no root. nft writes the firewall rules and can live in /usr/sbin. If unshare -Urn true fails on your system, see "If it fails" in the set-up: the rest of this lesson needs it.
Save the files in the lab folder, not in pub from lesson 11.
cd ~/krlab/networkingwhoami.py tells each client the address that it sees. routerlab.sh builds the lab and runs the part that you name.
- Client 10.0.1.2 → Router: curl to 10.0.2.2, by the default route
- Router → Server 10.0.2.2: forwarded, TTL 63 (ip_forward is 1)
- Server 10.0.2.2 → Router: whoami answers with the address it sees
- Router → Client 10.0.1.2: you are 10.0.1.2
whoami.py
import sys
from http.server import BaseHTTPRequestHandler, HTTPServer
class Who(BaseHTTPRequestHandler):
def do_GET(self):
body = f"you are {self.client_address[0]}\n".encode()
self.send_response(200)
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def log_message(self, *args):
pass
HTTPServer(("0.0.0.0", int(sys.argv[1])), Who).serve_forever()routerlab.sh
#!/bin/sh
# Run with: unshare -Urn sh routerlab.sh PART.sh
# This shell is the router. Its network is private; your real network is not touched.
unshare -n sleep 60 & # an empty network: the client
CLIENT=$!
unshare -n sleep 60 & # another empty network: the server
SERVER=$!
sleep 0.5
ip link add c0 type veth peer name c1
ip link set c1 netns $CLIENT
ip link add s0 type veth peer name s1
ip link set s1 netns $SERVER
ip addr add 10.0.1.1/24 dev c0; ip link set c0 up
ip addr add 10.0.2.1/24 dev s0; ip link set s0 up
nsenter -t $CLIENT -n sh -c 'ip addr add 10.0.1.2/24 dev c1; ip link set c1 up; ip route add default via 10.0.1.1'
nsenter -t $SERVER -n sh -c 'ip addr add 10.0.2.2/24 dev s1; ip link set s1 up; ip route add default via 10.0.2.1'
nsenter -t $SERVER -n python3 whoami.py 8080 &
WHO1=$!
nsenter -t $SERVER -n python3 whoami.py 8081 &
WHO2=$!
sleep 1
. ./"$1" # the part that you chose
kill $CLIENT $SERVER $WHO1 $WHO2The lines work as in lesson 3: unshare -n sleep 60 & makes an empty network that lives for 60 seconds, ip link add c0 type veth peer name c1 makes a virtual cable, and ip link set c1 netns $CLIENT moves one end into the client network. ip addr add gives an end an address and ip link set ... up switches it on. ip route add default via 10.0.1.1 sends everything else to the router. The server side is the same, on the network 10.0.2.0/24.
Linux passes packets from one card to another only when net.ipv4.ip_forward is 1: this makes a host a router. sysctl reads and sets a kernel setting: -w writes a value and -q keeps it quiet. forward.sh pings with it off and on. -W 1 waits one second, and -t 1 sets the TTL to 1.
forward.sh
sysctl -q -w net.ipv4.ip_forward=0
echo "--- forwarding off"
nsenter -t $CLIENT -n ping -c 1 -W 1 10.0.2.2 | grep -oE '[0-9]+% packet loss'
sysctl -q -w net.ipv4.ip_forward=1
echo "--- forwarding on"
nsenter -t $CLIENT -n ping -c 1 -W 1 10.0.2.2 | grep -oE 'ttl=[0-9]+|[0-9]+% packet loss'
echo "--- TTL 1"
nsenter -t $CLIENT -n ping -c 1 -t 1 10.0.2.2 | grep exceededunshare -Urn sh routerlab.sh forward.sh--- forwarding off
100% packet loss
--- forwarding on
ttl=63
0% packet loss
--- TTL 1
From 10.0.1.1 icmp_seq=1 Time to live exceededThe ping left with TTL 64 and arrived with 63: the router lowered it by one (lesson 1). With TTL 1 the router drops the packet and tells the sender. This is how traceroute finds each router.
2. Block a port with a firewall rule
In nft, a table holds chains, and a chain holds rules. The chain below hooks into forward, so it sees every packet that the router passes on. policy accept applies when no rule matches. curl -m 2 gives up after two seconds, and its exit code 28 means a timeout.
firewall.sh
sysctl -q -w net.ipv4.ip_forward=1
nft add table inet filter
nft add chain inet filter forward '{ type filter hook forward priority 0; policy accept; }'
nft add rule inet filter forward tcp dport 8081 drop
nsenter -t $CLIENT -n curl -s -m 2 http://10.0.2.2:8080/
nsenter -t $CLIENT -n curl -s -m 2 http://10.0.2.2:8081/
echo "curl exit $?"
nft list rulesetunshare -Urn sh routerlab.sh firewall.shyou are 10.0.1.2
curl exit 28
table inet filter {
chain forward {
type filter hook forward priority filter; policy accept;
tcp dport 8081 drop
}
}Port 8080 answers, and the server sees the client address. Port 8081 gets no answer at all, which is a drop (lesson 5). This chain is "allow all, block one thing". The next task turns it round.
3. Rewrite the source address with NAT
Source NAT (masquerade) changes the source address of each packet that leaves through one card to the address of that card. The chain hooks into postrouting, the last step before a packet leaves. oifname s0 means "the outgoing card is s0".
nat.sh
sysctl -q -w net.ipv4.ip_forward=1
nft add table ip nat
nft add chain ip nat post '{ type nat hook postrouting priority 100; }'
nft add rule ip nat post oifname s0 masquerade
nsenter -t $CLIENT -n curl -s -m 2 http://10.0.2.2:8080/
nft list rulesetunshare -Urn sh routerlab.sh nat.shyou are 10.0.2.1
table ip nat {
chain post {
type nat hook postrouting priority srcnat; policy accept;
oifname "s0" masquerade
}
}The server now sees 10.0.2.1, the address of the router, not the client. The router keeps a table of the connections, so it sends the replies back to 10.0.1.2. Your home router does this. On a real host, sudo nft list ruleset and sudo ufw status verbose read the rules (they need root, so no output is shown).
Your turn
Make the router of the scenario. There are no steps here: use nft as in the worked example. Write the rules in mine.sh, and run it with unshare -Urn sh routerlab.sh mine.sh. The rules are these. The forward chain has policy drop. The client 10.0.1.2 may open connections to TCP port 8080 of the server, and nothing else may be opened. The replies of allowed connections must pass. The source address of packets that leave through s0 is rewritten (masquerade). Then, from the client, run curl -s -m 2 on port 8080 and on port 8081 of 10.0.2.2 (print $? after each), and one ping -c 1 -W 1 of 10.0.2.2.
Then remove the line with ct state and run again. Answer from your own output.
Say in two sentences why port 8080 stops working without the ct rule, although the client is allowed to open it.
A model solution
sysctl -q -w net.ipv4.ip_forward=1
nft add table inet filter
nft add chain inet filter forward '{ type filter hook forward priority 0; policy drop; }'
nft add rule inet filter forward ct state established,related accept
nft add rule inet filter forward ip saddr 10.0.1.2 tcp dport 8080 accept
nft add table ip nat
nft add chain ip nat post '{ type nat hook postrouting priority 100; }'
nft add rule ip nat post oifname s0 masquerade
nsenter -t $CLIENT -n curl -s -m 2 http://10.0.2.2:8080/
echo "8080 exit $?"
nsenter -t $CLIENT -n curl -s -m 2 http://10.0.2.2:8081/
echo "8081 exit $?"
nsenter -t $CLIENT -n ping -c 1 -W 1 10.0.2.2 | grep -oE '[0-9]+% packet loss'The client's request passes, because the rule accepts it, and the server answers you are 10.0.2.1, the address of the router. The ping is an ICMP packet, and no rule accepts it, so it is lost. Without the ct rule the request reaches the server, but the reply is a new packet in the other direction, and the policy drops it. The client waits until -m 2 ends: exit code 28.
Check yourself
Why is NAT not a security control?
Its job is to share addresses. It happens to block unrequested inbound connections, but a port forward, a compromised inside host that calls out, or a protocol that opens its own mapping all pass through it. A firewall rule states the intent; NAT does not.
A router has `policy accept` and one rule that drops port 8081. A new service starts on port 9000 on the server. Is it reachable?
Yes. A list of blocked things always misses something. With policy drop, the new port stays closed until you write a rule for it.
With NAT, the server logs show 10.0.2.1 for every request. What do you lose, and where can you find the real client?
The server cannot tell the clients apart in its own logs. The router keeps a table of the connections (conntrack), and its logs hold the real client address. A reverse proxy solves the same problem with the header X-Forwarded-For (lesson 11).
Field notes
- Keep egress (outbound) rules too. Default deny on outbound traffic makes data theft harder, because malware cannot call home to an address that you did not allow.
- Rules that you add with
nft addlive until the next reboot. A real host loads them from a file (/etc/nftables.conf) at start. - Reject or drop? A drop gives an attacker no information and costs a scanner time, but a reject helps your own users and tools to see the problem at once. Many sites drop on the outside and reject on the inside.