Courses3 levels
Level 1 · Foundations11 courses
Level 2 · Core5 courses
Level 3 · Advanced5 courses
Labs8 topics
Library Practice exams AI Range Pricing Start free

Part 4 · Operations and troubleshooting · Lesson 06 · 55 minutes

Troubleshoot the network layer by layer

After this lesson you can
  • Work through a network fault in a fixed order, one change at a time, and write down what you see
  • Tell a wrong address, a wrong gateway, a wrong name server, a closed port and a firewall rule apart by their symptoms
  • Repair each fault with a real command and prove the repair with a test
Lab files of this lesson (16)

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

On Monday morning a colleague writes: "the shop is down". The shop page works on the server itself, so the fault is somewhere between the client and the server. You could try commands at random, and sometimes that works. A better habit is a method: start at the bottom, test one layer at a time, change one thing, and write down what you saw. In this lesson a script plants five faults in a private network, and you find each one.

Recall

Which file holds the name servers that programs use, and which command shows what a name resolves to?

/etc/resolv.conf names the servers, and getent hosts NAME resolves a name the way programs do (lesson 1 of Part 3).

How does a dropped packet look to the sender, and how does a rejected one look?

A drop gives silence and a time-out (curl exit code 28). A reject gives an answer "refused" at once (exit code 7). Lesson 3 of Part 3 showed both.

The idea

A network connection needs eight things, one on top of the other, and you make seven checks between them. If a lower one is broken, the tests above it fail too, so you test from the bottom up and stop at the first failure. The drawing shows the order. The text on an arrow is the command that proves the box before it.

The checks, from the bottom up
Link upAddress rightRoute rightServer reachablePort openFilter allows itName resolvesPage loadsip -br link shows UPip -br addrip route get ADDRESSping ADDRESSss -tln, on the servernft list ruleset, on the servergetent hosts NAME, then curlLink upAddress rightRoute rightServer reachablePort openFilter allows itName resolvesPage loads1234567
  1. Link up → Address right: ip -br link shows UP
  2. Address right → Route right: ip -br addr
  3. Route right → Server reachable: ip route get ADDRESS
  4. Server reachable → Port open: ping ADDRESS
  5. Port open → Filter allows it: ss -tln, on the server
  6. Filter allows it → Name resolves: nft list ruleset, on the server
  7. Name resolves → Page loads: getent hosts NAME, then curl

The exit code of curl tells you where to look:

Exit codeMessageUsual cause
6Could not resolve hostThe name does not exist, or no name server is set: the answer is "no", or there is none
7Failed to connectNo route, or nothing listens on that port (refused)
28Operation timed outNo answer came back. Resolving in the message means that the name server did not answer (fault 3). Connection timed out means a dropped packet or a gateway that does not answer (faults 2 and 5)

Fault 3 gives 28, not 6: a name server that does not answer is a time-out. Read the words of the message, not only the number.

Four rules for the method:

  1. Reproduce first. Make the failing request yourself and read its exact error.
  2. Narrow it. Test by address, and then by name. If the address works and the name fails, the fault is in the name service.
  3. One change at a time. After each change, repeat the test. If the change did not help, undo it.
  4. Write down the time, the command, what you saw and what you think. When you hand over the case, the notes are the proof.

Worked example

The lab needs administrator rights. It builds a network namespace named krclient: a private copy of the network stack (lesson 7 of Part 3 named it). The namespace is the client. It is joined to the host by a virtual cable, krhost0 on the host side and krc0 in the namespace, with the addresses 192.0.2.1 and 192.0.2.2. The host is the server: it runs a web page on 203.0.113.1 port 8080 and a name server on port 53. The addresses come from ranges that are kept for documentation, so no real network is touched. Nothing touches eth0.

The network of the lab
Namespace krclientHost, the serverClientName serverkrhost0Web page123Namespace krclientHost, the serverClientName serverkrhost0Web page123
  1. Client → krhost0: virtual cable, 192.0.2.2 to 192.0.2.1
  2. krhost0 → Name server: shop.krlab.test? on port 53
  3. krhost0 → Web page: GET / on 203.0.113.1:8080

1. Save the lab and build it

Two files make the lab. You do not need to read their code to learn the method: use them as tools. Save both files in ~/krlab/linux-operations (the code is in the collapsed block below).

  • krdns.py is a tiny name server. It answers one name, shop.krlab.test, and says "no such name" for every other name. It runs as root, because port 53 is privileged.
  • netlab.sh builds the private network and plants the faults. It has four commands: up builds the namespace, the cable and the two servers; fault N first restores the working state and then plants fault N (1 to 5); good restores; down removes everything.
The finished files: krdns.py and netlab.sh

krdns.py

#!/usr/bin/env python3
"""krdns.py - a tiny name server for the lab. Usage: krdns.py LISTEN-ADDRESS ANSWER-ADDRESS
It answers every A question for shop.krlab.test with ANSWER-ADDRESS, and says "no such name" for other names."""
import socket
import struct
import sys

listen, answer = sys.argv[1], socket.inet_aton(sys.argv[2])
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind((listen, 53))
while True:
    data, peer = sock.recvfrom(512)
    end = data.index(b"\0", 12) + 1                 # the name of the question ends with a zero byte
    name = data[12:end]
    qtype = struct.unpack("!H", data[end:end + 2])[0]
    known = name == b"\x04shop\x05krlab\x04test\x00"
    flags = 0x8180 if known else 0x8183             # answer, or "no such name"
    reply = data[:2] + struct.pack("!HHHHH", flags, 1, int(known and qtype == 1), 0, 0) + data[12:end + 4]
    if known and qtype == 1:                        # type 1 is an A record: an IPv4 address
        reply += b"\xc0\x0c" + struct.pack("!HHIH", 1, 1, 60, 4) + answer
    sock.sendto(reply, peer)

netlab.sh

#!/bin/bash
# netlab.sh - a private network for troubleshooting practice. Run it with sudo.
#   up       build the lab: the namespace krclient, a web server and a name server on the host side
#   fault N  plant fault N (1 to 5) on top of a working lab
#   good     put the working state back
#   down     remove everything
# The client is the namespace krclient (192.0.2.2). The server is on the host side (203.0.113.1).
set -u
[ "$(id -u)" -eq 0 ] || { echo "run it with sudo"; exit 1; }
NS=krclient
RUN=/run/krlab-netlab
HERE=$(cd "$(dirname "$0")" && pwd)

client() { ip netns exec "$NS" "$@"; }

serve_web() {    # serve_web PORT: an ordinary user serves a page on 203.0.113.1
    mkdir -p "$RUN/site" && echo "shop ok" > "$RUN/site/index.html"
    chmod -R a+rX "$RUN"
    setpriv --reuid=nobody --regid=nogroup --clear-groups python3 -m http.server "$1" \
        --bind 203.0.113.1 --directory "$RUN/site" > /dev/null 2>&1 &
    echo $! > "$RUN/web.pid"
}

stop_web() { [ -f "$RUN/web.pid" ] && kill "$(cat "$RUN/web.pid")" 2> /dev/null; rm -f "$RUN/web.pid"; }

good() {
    stop_web
    nft delete table inet krfault 2> /dev/null
    ip -n "$NS" addr flush dev krc0
    ip -n "$NS" addr add 192.0.2.2/24 dev krc0
    ip -n "$NS" route add default via 192.0.2.1
    echo "nameserver 203.0.113.1" > /etc/netns/$NS/resolv.conf
    serve_web 8080
    sleep 1
}

case "${1:-}" in
up)
    mkdir -p "$RUN" /etc/netns/$NS
    ip netns add "$NS"
    ip link add krhost0 type veth peer name krc0 netns "$NS"
    ip addr add 192.0.2.1/24 dev krhost0
    ip addr add 203.0.113.1/24 dev krhost0
    ip link set krhost0 up
    ip -n "$NS" link set lo up
    ip -n "$NS" link set krc0 up
    python3 "$HERE/krdns.py" 203.0.113.1 203.0.113.1 &
    echo $! > "$RUN/dns.pid"
    good
    echo "lab is up: the client is the namespace $NS"
    ;;
fault)
    good
    case "${2:-}" in
    1) ip -n "$NS" addr flush dev krc0; ip -n "$NS" addr add 198.18.0.2/24 dev krc0 ;;
    2) ip -n "$NS" route replace default via 192.0.2.254 ;;
    3) echo "nameserver 192.0.2.53" > /etc/netns/$NS/resolv.conf ;;
    4) stop_web; serve_web 8081; sleep 1 ;;
    5) nft add table inet krfault
       nft add chain inet krfault input '{ type filter hook input priority 0 ; }'
       nft add rule inet krfault input ip saddr 192.0.2.0/24 tcp dport 8080 drop ;;
    *) echo "fault 1 to 5"; exit 1 ;;
    esac
    echo "fault ${2} is planted"
    ;;
good)
    good
    echo "working state is back"
    ;;
down)
    stop_web
    [ -f "$RUN/dns.pid" ] && kill "$(cat "$RUN/dns.pid")" 2> /dev/null
    nft delete table inet krfault 2> /dev/null
    ip link del krhost0 2> /dev/null
    ip netns del "$NS" 2> /dev/null
    rm -rf "$RUN" /etc/netns/$NS
    echo "lab is down"
    ;;
*)
    echo "usage: sudo bash netlab.sh up|fault N|good|down"
    exit 1
    ;;
esac

ip netns exec krclient COMMAND runs one command inside the namespace. The small function c shortens it. Build the lab and look at the client.

cd ~/krlab/linux-operations
sudo bash netlab.sh up
c() { sudo ip netns exec krclient "$@"; }
c ip -br addr
c ip route
lab is up: the client is the namespace krclient
lo               UNKNOWN        127.0.0.1/8 ::1/128 
krc0@if4         UP             192.0.2.2/24 
default via 192.0.2.1 dev krc0 
192.0.2.0/24 dev krc0 proto kernel scope link src 192.0.2.2 

The number after @if (here 4) differs on your machine.

2. Know what "working" looks like

Test the layers once while all is well. Then you know what each answer should be. ping -c 1 -W 2 sends one echo request and waits two seconds.

c ping -c 1 -W 2 192.0.2.1 | grep "packet loss"
c getent hosts shop.krlab.test
c curl -s -m 3 http://shop.krlab.test:8080/
1 packets transmitted, 1 received, 0% packet loss, time 0ms
203.0.113.1     shop.krlab.test
shop ok

3. Fault 3: the name does not resolve

Plant the fault and make the request that the colleague made. curl -sS is silent, but shows an error. Then ask by address.

sudo bash netlab.sh fault 3
c curl -sS -m 3 http://shop.krlab.test:8080/
c curl -s -m 3 http://203.0.113.1:8080/
fault 3 is planted
curl: (28) Resolving timed out after 3001 milliseconds
shop ok

By address it works, so the link, the address, the route, the port and the filter are fine. The fault is in the name service. Look at the name server that the client uses:

c cat /etc/resolv.conf
nameserver 192.0.2.53

Nothing answers on 192.0.2.53. The right server is 203.0.113.1. Change that one line, and test again. (getent waits about 12 seconds when the server is wrong, so a fast getent means that it is right.)

echo "nameserver 203.0.113.1" | sudo tee /etc/netns/krclient/resolv.conf
c getent hosts shop.krlab.test
nameserver 203.0.113.1
203.0.113.1     shop.krlab.test

4. Fault 5: the connection hangs

ss -tlnp is the ss -tln of the earlier faults with -p added: it shows the process that owns each socket.

sudo bash netlab.sh fault 5
c curl -sS -m 3 http://203.0.113.1:8080/
c ping -c 1 -W 2 203.0.113.1 | grep "packet loss"
sudo ss -tlnp | grep python3
fault 5 is planted
curl: (28) Connection timed out after 3002 milliseconds
1 packets transmitted, 1 received, 0% packet loss, time 0ms
LISTEN 0      5        203.0.113.1:8080      0.0.0.0:*    users:(("python3",pid=3434,fd=3))

Read it from the bottom of the list: the link, the address and the route work, because ping reaches the server. The server listens on port 8080 (ss on the server side). The web server belongs to the user nobody, so you need sudo to see its process. Yet the connection times out. A time-out with a listening server means that a packet is dropped. Look at the filter rules of the server.

sudo nft list ruleset
table inet krfault {
	chain input {
		type filter hook input priority filter; policy accept;
		ip saddr 192.0.2.0/24 tcp dport 8080 drop
	}
}

A rule drops port 8080 from the client's network:

The rule that hangs the page
ip saddr 192.0.2.0/24from the client's networktcp dport 8080to the web page portdropthrow the packet awayip saddr 192.0.2.0/24from the client's networktcp dport 8080to the web page portdropthrow the packet away

Remove the table that holds it, and test again.

sudo nft delete table inet krfault
c curl -sS -m 3 http://203.0.113.1:8080/
shop ok

5. Keep notes

Notes make the case repeatable. Write them as you work, in a file with one line for each test: what you ran, what you saw, what you believe. For fault 5 they would read:

13:40  curl by address     -> exit 28, timeout      -> a packet is dropped
13:41  ping the server     -> 0% loss                -> link, address, route are fine
13:42  ss on the server    -> listens on 8080       -> the service is up
13:43  nft list ruleset    -> a drop rule for 8080  -> the cause; deleted the table
13:43  curl by address     -> shop ok               -> fixed

Remove the lab when you have finished the lesson: sudo bash netlab.sh down.

Your turn

Three faults are left: 1, 2 and 4. For each one: plant it with sudo bash netlab.sh fault N, make the request, go through the layers in order, find the cause, repair it with a real command (not with netlab.sh good) and test again. Keep notes in notes.txt. Useful forms: ip -n krclient COMMAND runs ip inside the namespace, ip route replace default via ADDRESS changes the gateway, and ip route get ADDRESS shows the route that a packet would take. For fault 4, the repair that a person with no access to the lab script makes is to find the port and use it. Answer from your own terminal.

Check yourself

Ping to the server works, but the web page times out. Which layers can you rule out, and what do you check next?

The link, the address and the route work, because the echo reached the server and came back. Check that the service listens (ss -tln on the server), then the firewall: a drop rule for that port gives exactly this symptom.

curl by address works and curl by name fails. Where is the fault?

In the name service: the resolv.conf file, a name server that does not answer, or a wrong record. Every layer below it works.

Why change only one thing between two tests?

If you change two things and the fault goes away, you do not know which one fixed it, and the other change may be a new fault. One change at a time keeps cause and effect clear.

A request fails at once with "connection refused". How does this differ from a time-out?

The server host answered and said that nothing listens on that port: the service is stopped or listens on another port or address. A time-out means that no answer came back: a firewall or a bad route.

Field notes

  • Check the same path in both directions. A reply can take another route than the request, and a firewall rule can drop only one direction.
  • ping can be blocked while a service works, and it can work while a service is down. Use it as a hint for the lower layers, and test the real service last.
  • A name can resolve differently in /etc/hosts, in the resolver and at the name server. getent hosts follows the order that your programs use, so trust it before a tool that asks the name server only.
  • To see the packets themselves, use the capture lesson of the course Networking hands-on.
  • Do not change a production network to test a theory: build the fault in a namespace, as here, or on a copy. Keep the notes, because in an incident the written order of what you tried is the first thing that a second person asks for.