Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Practical 3 · Capstone: netcheck

Goal: a lab with a DNS server, a router and a web service, and netcheck, a Bash script you write from an empty folder. It asks lesson 1’s six questions in order and names the first that fails. Then the checker breaks your lab eleven ways, and netcheck has to name every one.

Time: ~90 minutes. Where: files in ~/linux-networking-zero/ on your computer; network commands inside the lab container (./on). Read lesson 7 and lesson 8 first.

./lab setup p3      # installs the DNS server, dnsmasq, in netlab

Skipped a practical, or your lab is in a state you don’t trust? ./lab reset p3 (on your computer) deletes every namespace in netlab and rebuilds what Practicals 0 to 2 built. Then run your p3.sh.

As before, commands in a bash block run inside the lab (./on opens a shell there); the ones starting with ./on or ./lab run on your computer.

Task 1 · The lab

Lesson 8’s lab, with a router in front of blue, so a route can break too. Write ~/linux-networking-zero/p3.sh:

  • starts clean: for each of red, blue, green, router, switch, stops every program running in it (ip netns pids <name> lists them), then deletes it; stops at the first failure
  • a switch br0 in switch, with red (10.0.1.2/24), green (10.0.1.3/24) and router (10.0.1.1/24) plugged in as in Practical 2: veth-<name> in the machine, sw-<name> on the bridge
  • a cable from r-blue in router (10.0.2.1/24) to veth-blue in blue (10.0.2.2/24), as in Practical 1
  • default routes: red and green via 10.0.1.1, blue via 10.0.2.1; forwarding on in router
  • green runs lesson 8’s DNS server, answering web.lab with 10.0.2.2 and listening on 10.0.1.3; red’s resolv.conf names it
  • blue runs lesson 8’s web service on port 8080
   red 10.0.1.2      green 10.0.1.3 (DNS)      router 10.0.1.1 | 10.0.2.1        blue 10.0.2.2 (web :8080)
   veth-red          veth-green                veth-router       r-blue ------------- veth-blue
      |                 |                         |
   switch:  sw-red ----- sw-green ------------- sw-router    (br0)
Hint

Copy P2’s loop for the three machines on the switch, and P1’s lines for the cable. dnsmasq puts itself in the background, so a plain ip netns exec green dnsmasq ... is enough; the web service needs setsid -f. Lesson 8’s lab started them like this, on 10.0.0.x addresses (change them for this lab):

ip netns exec green dnsmasq --no-resolv --no-hosts --address=/web.lab/10.0.0.2 --listen-address=10.0.0.3 --bind-interfaces --pid-file=/run/dnsmasq-green.pid
setsid -f ip netns exec blue bash -c 'while true; do printf "HTTP/1.0 200 OK\r\nContent-Length: 6\r\n\r\nhello\n" | nc -l -N 8080 >/dev/null; done' </dev/null >/dev/null 2>&1

--address=/web.lab/... is the one name it answers, --listen-address and --bind-interfaces keep it on green’s address only, and nc -l -N sends the reply and closes once the loop’s printf is done.

Solution
#!/bin/bash
# p3.sh: the capstone's lab: red, green (DNS) and router on a switch; blue (a web service) behind router
set -e
for ns in red blue green router switch; do
  ip netns pids $ns 2>/dev/null | xargs -r kill          # programs still running in an old namespace
  ip netns del $ns 2>/dev/null || true
done
ip netns add switch
ip -n switch link add br0 type bridge
ip -n switch link set br0 up
for c in red green router; do
  ip netns add $c
  ip link add veth-$c type veth peer name sw-$c
  ip link set veth-$c netns $c
  ip link set sw-$c netns switch
  ip -n switch link set sw-$c master br0
  ip -n switch link set sw-$c up
  ip -n $c link set lo up
  ip -n $c link set veth-$c up
done
ip -n red addr add 10.0.1.2/24 dev veth-red
ip -n green addr add 10.0.1.3/24 dev veth-green
ip -n router addr add 10.0.1.1/24 dev veth-router
ip netns add blue
ip link add veth-blue type veth peer name r-blue
ip link set veth-blue netns blue
ip link set r-blue netns router
ip -n router addr add 10.0.2.1/24 dev r-blue
ip -n blue addr add 10.0.2.2/24 dev veth-blue
ip -n router link set r-blue up
ip -n blue link set lo up
ip -n blue link set veth-blue up
ip -n red route add default via 10.0.1.1
ip -n green route add default via 10.0.1.1
ip -n blue route add default via 10.0.2.1
ip netns exec router sysctl -w net.ipv4.ip_forward=1
ip netns exec green dnsmasq --no-resolv --no-hosts --address=/web.lab/10.0.2.2 \
  --listen-address=10.0.1.3 --bind-interfaces --pid-file=/run/dnsmasq-green.pid
mkdir -p /etc/netns/red
rm -f /etc/netns/red/hosts                            # lesson 8's hosts line, if it's still there
echo "nameserver 10.0.1.3" > /etc/netns/red/resolv.conf
setsid -f ip netns exec blue bash -c 'while true; do
  printf "HTTP/1.0 200 OK\r\nContent-Length: 6\r\n\r\nhello\n" | nc -l -N 8080 >/dev/null; done' </dev/null >/dev/null 2>&1

Why the kill: a program running in a namespace keeps it alive after ip netns del, so without it an old dnsmasq or web service would keep running, unseen, in a namespace you can no longer reach.

./on bash p3.sh
./on ip netns exec red curl -sS http://web.lab:8080/

hello: everything works.

Predict first: turn forwarding off in router. Does red still get an answer for web.lab? Does curl?

ip netns exec router sysctl -w net.ipv4.ip_forward=0
ip netns exec red dig +short web.lab
ip netns exec red curl -sS -m5 http://web.lab:8080/
ip netns exec router sysctl -w net.ipv4.ip_forward=1
What you see

dig still answers 10.0.2.2: green is on red’s own link, so DNS needs no router. curl waits its 5 seconds and gives up. A break leaves the questions before it working, which is why netcheck can ask them one at a time.

Task 2 · netcheck: the way there

Make an empty folder ~/linux-networking-zero/netcheck/ and write netcheck/netcheck in it (chmod +x it). It runs in the lab, from the workspace:

./on netcheck/netcheck red web.lab 8080

The contract (the checker reads only the last line and the exit code):

LineWhen
ok <what it found>each question that passes, in order
BROKEN <what>: <detail>, exit 1the first that fails; <what> is one of dns route forward arp drop reject port app, or unknown when none of them explains it
OK ..., exit 0everything passed

Netcheck sees every namespace, like an admin logged in to every machine. The first half:

  • name (question 1): getent hosts from the machine; if it gives nothing, BROKEN dns, with dig’s status: or communications error line as the detail
  • route (question 2): ip -n <machine> route get <address>; if it fails, BROKEN route. Note its via (the gateway) and its src (the machine’s own address)
  • link (question 3): a ping -c1 -W1 to the next hop answers, else BROKEN arp with ip neigh show <hop>. When there is a gateway, find the namespace that has its address, check that it forwards (else BROKEN forward), has a route to the address (else BROKEN route) and gets a ping answer from it (else BROKEN arp)
  • back (question 2, the way back): the namespace with the address has a route back to src, else BROKEN route
Hint

Two small functions save most of the typing: broken() { echo "BROKEN $*"; exit 1; }, and one that loops over ip netns list and prints the namespace whose ip -n <ns> -br addr contains " <address>/". awk pulls a word out of a line: awk '{for (i = 1; i < NF; i++) if ($i == "via") print $(i + 1)}'.

Solution
#!/bin/bash
# netcheck <machine> <name> <port>: from <machine>, ask lesson 1's questions in order; name the first that fails
from=$1 name=$2 port=$3
[ -n "$port" ] || { echo "usage: netcheck <machine> <name> <port>"; exit 2; }

ok()     { echo "ok      $*"; }
broken() { echo "BROKEN  $*"; exit 1; }
owner()  {                                  # the namespace that has the address $1
  for ns in $(ip netns list | awk '{print $1}'); do
    ip -n $ns -br addr | grep -q " $1/" && echo $ns
  done
}
answers() {                                 # $1 pings $2 on its own link; else say why
  ip netns exec $1 ping -c1 -W1 $2 >/dev/null && return
  broken "arp: $1 gets no answer from $2 ($(ip -n $1 neigh show $2))"
}

# 1. name -> address
addr=$(ip netns exec $from getent hosts $name | awk '{print $1; exit}')
[ -n "$addr" ] || broken "dns: $name doesn't resolve on $from ($(ip netns exec $from dig +tries=1 +time=2 $name |
  grep -o -m1 -E 'status: [A-Z]+|communications error.*'))"
ok "name    $name is $addr"

# 2, 3. which way, who on the link: each hop to the machine that has the address
r=$(ip -n $from route get $addr 2>&1) || broken "route: $from has no route to $addr ($r)"
src=$(echo "$r" | awk '{for (i = 1; i < NF; i++) if ($i == "src") print $(i + 1)}')
gw=$(echo "$r" | awk '{for (i = 1; i < NF; i++) if ($i == "via") print $(i + 1)}')
if [ -n "$gw" ]; then
  answers $from $gw
  router=$(owner $gw)
  ok "route   $from sends it to $router ($gw)"
  [ "$(ip netns exec $router sysctl -n net.ipv4.ip_forward)" = 1 ] ||
    broken "forward: $router doesn't forward (net.ipv4.ip_forward = 0)"
  r=$(ip -n $router route get $addr 2>&1) || broken "route: $router has no route to $addr ($r)"
  answers $router $addr
else
  answers $from $addr
fi
target=$(owner $addr)
ok "link    $addr ($target) answers on its link"
r=$(ip -n $target route get $src 2>&1) || broken "route: $target has no route back to $src ($r)"
ok "back    $target has a route back to $src"
./on netcheck/netcheck red web.lab 8080
ok      name    web.lab is 10.0.2.2
ok      route   red sends it to router (10.0.1.1)
ok      link    10.0.2.2 (blue) answers on its link
ok      back    blue has a route back to 10.0.1.2

Break it. Take away blue’s way back, run netcheck, then point red at a DNS server that isn’t there:

ip -n blue route del default
netcheck/netcheck red web.lab 8080
echo "nameserver 10.0.1.9" > /etc/netns/red/resolv.conf
netcheck/netcheck red web.lab 8080
What you see
BROKEN  route: blue has no route back to 10.0.1.2 (RTNETLINK answers: Network is unreachable)

From red alone, this looks like a DROP (lesson 7); netcheck finds it by asking blue. The second run stops at the first question, after the resolver’s waits (about 15 s):

BROKEN  dns: web.lab doesn't resolve on red (communications error to 10.0.1.9#53: timed out)

Put the lab back with ./on bash p3.sh.

Task 3 · netcheck: let through, listening, answering

From the client, questions 4 to 6 come down to one request. Add to netcheck:

  • read the packet counters of every DROP and REJECT rule in every namespace (iptables -L -n -v -x), make one request with curl -s -o /dev/null -m 5, and read the counters again
  • let through? (question 4) a counter that went up: BROKEN drop or BROKEN reject, naming the namespace (lesson 7: the rule that counts is the one catching them)
  • listening? (question 5) curl exit code 7 (couldn’t connect): BROKEN port, with what ss -Htln shows listening on that port
  • answers? (question 6) connected but no HTTP status: BROKEN app; a 2xx or 3xx status: OK
Hint

curl -w '%{http_code} %{time_connect} %{errormsg}' prints the status (000 when there was none), how long the connection took (0.000000 when it never connected) and curl’s error. diff <(echo "$before") <(echo "$after") shows the counter lines that changed.

Solution
# 4, 5, 6. let through? listening? does the program answer? One request, and the firewall counters around it
counters() {
  for ns in $(ip netns list | awk '{print $1}'); do
    ip netns exec $ns iptables -L -n -v -x | awk -v ns=$ns '$3 == "DROP" || $3 == "REJECT" {print ns, $3, NR, $1}'
  done
}
before=$(counters)
out=$(ip netns exec $from curl -s -o /dev/null -m 5 -w '%{http_code} %{time_connect} %{errormsg}' http://$name:$port/)
rc=$?
after=$(counters)
hit=$(diff <(echo "$before") <(echo "$after") | awk '/^>/ {print $2, $3; exit}')    # e.g. "blue DROP"
if [ -n "$hit" ]; then
  set -- $hit
  broken "${2,,}: a $2 rule in $1 caught the packets (iptables -L -n -v)"
fi
ok "firewall no DROP or REJECT rule caught them"
if [ $rc = 7 ]; then
  listen=$(ip netns exec $target ss -Htln "sport = :$port" | awk '{print $4}')
  broken "port: nothing on $target listens on $addr:$port (listening: ${listen:-none})"
fi
read code connected why <<< "$out"
case "$code" in
  [23]??) ok "port    $target listens on $port"; echo "OK      $name:$port from $from: HTTP $code" ;;
  *) [ "$connected" != "0.000000" ] && broken "app: connected to $addr:$port, but no HTTP answer (curl: $why)"
     broken "unknown: curl: $why" ;;
esac

${2,,} is Bash for “$2 in lower case”.

./on netcheck/netcheck red web.lab 8080
ok      firewall no DROP or REJECT rule caught them
ok      port    blue listens on 8080
OK      web.lab:8080 from red: HTTP 200

Predict first: a REJECT rule on blue makes curl say Connection refused, the same words as a closed port. Will netcheck say port or reject?

ip netns exec blue iptables -I INPUT -p tcp --dport 8080 -j REJECT
netcheck/netcheck red web.lab 8080
ip netns exec blue iptables -D INPUT -p tcp --dport 8080 -j REJECT
What you see
BROKEN  reject: a REJECT rule in blue caught the packets (iptables -L -n -v)

The counters are read before the exit code, so the rule is found first.

Task 4 · Let the checker break it

./lab check p3

It checks the lab as p3.sh builds it and runs netcheck (it must end with OK). Then, only in a container with Practical 0’s --label, it breaks the lab one way at a time, runs netcheck, and undoes the break:

Breaknetcheck must sayLesson
red’s DNS server is 10.0.1.9; a name green doesn’t knowdns8
red’s default route deleted; blue’s default route deletedroute4
forwarding off in routerforward4
blue’s cable downarp5
a DROP on blue (INPUT); a DROP on router (FORWARD)drop, naming the namespace7
a REJECT on bluereject7
port 8081, where nothing listensport6
blue’s web service frozen with kill -STOPapp8

All 56 checks should pass. The frozen service is lesson 8’s point: the kernel still completes the handshake, so curl connects, and then no answer ever comes.

A check fails? Run that break by hand (./lab’s BREAKS lists them) and read netcheck’s whole output. ./on bash p3.sh rebuilds everything.

Go deeper: where netcheck stops

netcheck reads the counters iptables -L shows. A rule written with nft in a table of its own (lesson 7, Go deeper) isn’t among them:

ip netns exec blue nft add table inet lab
ip netns exec blue nft add chain inet lab input "{ type filter hook input priority 0; }"
ip netns exec blue nft add rule inet lab input tcp dport 8080 counter drop
ok      firewall no DROP or REJECT rule caught them
BROKEN  unknown: curl: Connection timed out after 5002 milliseconds

nft list table inet lab on blue shows the rule’s counter packets 5 bytes 300 drop. Reading nft list ruleset instead of iptables -L would catch both. Take the table out with ip netns exec blue nft delete table inet lab.

A DROP for ping on blue (iptables -I INPUT -p icmp -j DROP) fools the arp step:

BROKEN  arp: router gets no answer from 10.0.2.2 (10.0.2.2 dev r-blue lladdr c6:fb:96:df:3b:fe REACHABLE )

The detail gives it away: router has blue’s MAC (lladdr), so ARP worked and only the ping went unanswered. A script names the first failure it can see; a person still reads the detail. On real machines, netcheck’s view of every namespace becomes one ssh per hop.

Next: you’ve finished the course. The front page lists what each lesson covered.