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

Lesson 06 · 60 minutes

Check a DHCP lease, a clock and an IPv6 address

After this lesson you can
  • Read a DHCP exchange and work out the lease times and a second DHCP server
  • Calculate the offset and the delay of a clock from four NTP time stamps
  • Classify IPv6 addresses and explain SLAAC and why IPv6 matters for security
Lab files of this lesson (32)

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

After a switch was replaced, some laptops get a wrong gateway, and their clocks are minutes off. The security team asks three things. Did a second DHCP server answer? How far off is a clock, and will it break certificates? Which clients in the web log use IPv6, a kind of address that the old report script skips? You get a recorded DHCP exchange, NTP time stamps and a web log. You answer from the data.

Recall

Which protocol finds the MAC address that belongs to an IP address on the same network?

ARP. The machine broadcasts "who has this address?", and the owner answers with its MAC address (lesson 3).

Why can a UDP sender not know if its packet arrived?

UDP has no handshake and no acknowledgement. The application must build its own answer and its own repeat (lesson 5). DHCP, NTP and DNS all use UDP and do this themselves.

The idea

DHCP (Dynamic Host Configuration Protocol) gives a machine its network settings when it joins: an address, the mask, the gateway and the DNS servers. It uses UDP, with port 67 on the server and 68 on the client. A new client has no address, so it speaks by broadcast. The exchange has four messages, called DORA.

DHCP, the four messages (DORA)
ClientServerDISCOVER (broadcast): who is a server?OFFER: I can give 192.168.1.50REQUEST: I take that offerACK: it is yours for 3600 sClientServer1234
  1. Client → Server: DISCOVER (broadcast): who is a server?
  2. Server → Client: OFFER: I can give 192.168.1.50
  3. Client → Server: REQUEST: I take that offer
  4. Server → Client: ACK: it is yours for 3600 s

The address is a lease: it is lent for a time. At half of the lease time (T1) the client asks its server to renew. At seven eighths (T2) it asks any server. A client that gets no answer takes an address that starts with 169.254 (lesson 2). The danger: DHCP has no login. If two servers answer, clients often take the first offer, so a rogue server can send a false gateway and a false DNS server.

A rogue DHCP server answers first
Office networkReal DHCP serverLaptopRogue DHCP server1234Office networkReal DHCPserverLaptopRogue DHCPserver1234
  1. Laptop → Real DHCP server: DISCOVER, a broadcast: all hear it
  2. Rogue DHCP server → Laptop: OFFER with a false gateway, arrives first
  3. Real DHCP server → Laptop: OFFER with the true gateway, later
  4. Laptop → Rogue DHCP server: REQUEST: takes the first offer

NTP (Network Time Protocol) keeps clocks right. Four time stamps, t1 to t4, give two results:

The four time stamps of one NTP exchange
ClientServerrequest, sent at t1 (client clock)writes t2 when it arrivesanswer, sent at t3 (server clock)writes t4 when it arrivesClientServer1234
  1. Client → Server: request, sent at t1 (client clock)
  2. Server: writes t2 when it arrives
  3. Server → Client: answer, sent at t3 (server clock)
  4. Client: writes t4 when it arrives
  • offset = ((t2 - t1) + (t3 - t4)) / 2. How far the server clock is ahead of yours.
  • delay = (t4 - t1) - (t3 - t2). The time that the message spent on the network.

A sample with a short delay is more trustworthy: the offset can be wrong by up to half of the delay. Time matters for security in four ways:

  • You cannot join the logs of two systems if their clocks differ.
  • A TLS certificate is valid only between two dates. A clock that is behind gives "not yet valid".
  • Kerberos refuses a clock that is off by more than a few minutes.
  • A one-time code works for 30 seconds.

IPv6 has 128-bit addresses, written as eight groups of hexadecimal digits. One run of zero groups can be written as ::. The first 64 bits are normally the network (the prefix, /64) and the last 64 are the interface.

KindPrefixMeaning
Loopback::1This machine
Link-localfe80::/10One local link only. Every IPv6 interface has one.
Unique localfc00::/7Private, like the ranges of lesson 2
Global2000::/3Public and routed
Multicastff00::/8A group of machines. There is no broadcast in IPv6.
Documentation2001:db8::/32For examples. This course uses it in place of global addresses.

SLAAC (stateless address autoconfiguration) needs no DHCP server. A router sends a router advertisement with the prefix. The host adds an interface ID and checks that nobody else uses the address. The classic interface ID, EUI-64, comes from the MAC address: flip one bit of the first byte and put ff:fe into the middle. Modern systems use random IDs instead, because EUI-64 shows the MAC address. IPv6 does not use ARP: it uses neighbour discovery, which also has no check of who answers.

Worked example

1. Record a DHCP exchange

exchange.txt is a recorded exchange in the form of a capture tool: the time, the two ends, the message type and its fields. The client has no address (0.0.0.0) and both sides use broadcast.

cd ~/krlab/networking
cat > exchange.txt <<'EOT'
0.000 0.0.0.0:68 > 255.255.255.255:67 DISCOVER xid=0x3903f326 mac=02:00:00:00:00:50
0.012 192.168.1.1:67 > 255.255.255.255:68 OFFER xid=0x3903f326 yiaddr=192.168.1.50 server=192.168.1.1 lease=3600 router=192.168.1.1 dns=192.168.1.1
0.013 0.0.0.0:68 > 255.255.255.255:67 REQUEST xid=0x3903f326 mac=02:00:00:00:00:50 requested=192.168.1.50 server=192.168.1.1
0.020 192.168.1.1:67 > 255.255.255.255:68 ACK xid=0x3903f326 yiaddr=192.168.1.50 server=192.168.1.1 lease=3600 router=192.168.1.1 dns=192.168.1.1
EOT

The xid is the transaction number that ties the four messages together. yiaddr is "your address".

2. Read the lease

dhcp.py prints each message and then the lease from the first ACK, with the two timers. line.split() cuts a line at its spaces, and *rest collects the fields at the end.

dhcp.py

import sys

messages = []
for line in open(sys.argv[1]):
    when, src, _, dst, kind, *rest = line.split()
    fields = dict(item.split("=", 1) for item in rest)
    messages.append((kind, fields))
    print(f"{when:>6}  {src:<21} > {dst:<21} {kind:<9} xid {fields['xid']}")

acks = [fields for kind, fields in messages if kind == "ACK"]
if not acks:
    sys.exit("no ACK: the client got no lease")
ack = acks[0]
lease = int(ack["lease"])
print(f"lease: {ack['yiaddr']} from {ack['server']}, gateway {ack['router']}, dns {ack['dns']}")
print(f"time: {lease} s, renew (T1) at {lease // 2} s, rebind (T2) at {lease * 7 // 8} s")
python3 dhcp.py exchange.txt
 0.000  0.0.0.0:68            > 255.255.255.255:67    DISCOVER  xid 0x3903f326
 0.012  192.168.1.1:67        > 255.255.255.255:68    OFFER     xid 0x3903f326
 0.013  0.0.0.0:68            > 255.255.255.255:67    REQUEST   xid 0x3903f326
 0.020  192.168.1.1:67        > 255.255.255.255:68    ACK       xid 0x3903f326
lease: 192.168.1.50 from 192.168.1.1, gateway 192.168.1.1, dns 192.168.1.1
time: 3600 s, renew (T1) at 1800 s, rebind (T2) at 3150 s

The whole exchange took 20 milliseconds. The gateway and the DNS server come from the ACK, so whoever answers first controls them.

3. Calculate the offset of a clock

Each line of ntp.txt has t1 t2 t3 t4 in seconds. ntp.py uses the two formulas and gives a verdict. The limits of the verdict (0.1 s and 300 s) are rules of this lesson. 300 s is the usual limit of Kerberos. A TLS certificate fails only when the clock is near its start or end date.

cat > ntp.txt <<'EOT'
1000.000 1000.012 1000.013 1000.021
1000.000 1350.010 1350.011 1000.021
1000.000 1000.300 1000.301 1000.601
EOT

ntp.py

import sys

for line in open(sys.argv[1]):
    t1, t2, t3, t4 = (float(x) for x in line.split())
    offset = ((t2 - t1) + (t3 - t4)) / 2  # how far the server clock is ahead of ours
    delay = (t4 - t1) - (t3 - t2)  # time spent on the network, without the server's own pause
    if abs(offset) < 0.1:
        verdict = "ok"
    elif abs(offset) < 300:
        verdict = "logs will not line up"
    elif offset > 0:
        verdict = "Kerberos fails, new certificates look not yet valid"
    else:
        verdict = "Kerberos fails, certificates look expired too early"
    print(f"offset {offset * 1000:9.1f} ms  delay {delay * 1000:6.1f} ms  {verdict}")
python3 ntp.py ntp.txt
offset       2.0 ms  delay   20.0 ms  ok
offset  350000.0 ms  delay   20.0 ms  Kerberos fails, new certificates look not yet valid
offset       0.0 ms  delay  600.0 ms  ok

The second sample is a clock that is 350 seconds behind the server: the network was fast, so the offset is real. The third has a slow network but no offset: a long delay is not a wrong clock.

4. Ask your machine about its clock

timedatectl (time and date control) is the tool of systemd for the clock. The two lines say if the clock is synchronised and if an NTP service runs. Your system may use other tools, and the output then differs.

timedatectl | grep -E 'synchronized|NTP service'
System clock synchronized: yes
              NTP service: active

5. Classify IPv6 addresses

ipv6.py uses the module ipaddress (lesson 2). It tests the special ranges first and then the general ones, and it has a function slaac that forms an address from a prefix and a MAC address. bytearray is a list of bytes that you can change, ^= flips a bit, and int.from_bytes turns bytes into one number.

ipv6.py

import ipaddress
import sys

ULA = ipaddress.ip_network("fc00::/7")  # unique local: the IPv6 private range
DOC = ipaddress.ip_network("2001:db8::/32")  # reserved for documentation


def kind(a):
    if a.version == 4:
        return "IPv4"
    if a.is_loopback:
        return "loopback"
    if a.is_unspecified:
        return "unspecified"
    if a.is_multicast:
        return "multicast"
    if a.is_link_local:
        return "link-local"
    if a.ipv4_mapped:
        return "IPv4-mapped"
    if a in ULA:
        return "unique local"
    if a in DOC:
        return "documentation"
    return "global" if a.is_global else "other"


def slaac(prefix, mac):
    """The address that a host forms from a /64 prefix and its MAC address (EUI-64)."""
    raw = bytearray(bytes.fromhex(mac.replace(":", "")))
    raw[0] ^= 0x02  # flip the "universal/local" bit
    interface_id = bytes(raw[:3]) + b"\xff\xfe" + bytes(raw[3:])
    network = ipaddress.ip_network(prefix)
    return ipaddress.ip_address(int(network.network_address) | int.from_bytes(interface_id, "big"))


if __name__ == "__main__":
    for line in open(sys.argv[1]):
        a = ipaddress.ip_address(line.strip())
        print(f"{a.compressed:<24} {kind(a)}")
cat > addrs.txt <<'EOT'
192.168.1.50
::1
fe80::ff:fe00:50
fd00:20::5
ff02::1
2001:db8:0:0:0:0:0:25
::ffff:192.0.2.55
2606:4700:4700::1111
EOT
python3 ipv6.py addrs.txt
192.168.1.50             IPv4
::1                      loopback
fe80::ff:fe00:50         link-local
fd00:20::5               unique local
ff02::1                  multicast
2001:db8::25             documentation
::ffff:192.0.2.55        IPv4-mapped
2606:4700:4700::1111     global

The last block runs only when you start the file, not when another file imports it, so step 6 can use slaac. Notice that 2001:db8:0:0:0:0:0:25 came out as 2001:db8::25: the module prints the short form (.compressed). .exploded gives all eight groups. An IPv4-mapped address carries an IPv4 address inside an IPv6 socket, so a server that listens on IPv6 also logs IPv4 clients this way.

6. Form a SLAAC address

Check the EUI-64 rule on the MAC address 02:00:00:00:00:50, and then list the addresses of your own machine (-6 means IPv6 only).

python3 -c "import ipv6; print(ipv6.slaac('fe80::/64', '02:00:00:00:00:50')); print(ipv6.slaac('2001:db8:1:1::/64', '02:00:00:00:00:50'))"
ip -6 -br addr
fe80::ff:fe00:50
2001:db8:1:1:0:ff:fe00:50
lo               UNKNOWN        ::1/128
ens1f0           UP             fe80::2a80:23ff:fe9b:5fb0/64

Your machine has a link-local address even if your network has no IPv6 at all. That is normal, and it is the first reason why you cannot ignore IPv6.

Your turn

Answer the questions of the security team. Save the data.

cat > exchange2.txt <<'EOT'
0.000 0.0.0.0:68 > 255.255.255.255:67 DISCOVER xid=0x7b21c9a4 mac=02:00:00:00:00:77
0.004 192.168.1.66:67 > 255.255.255.255:68 OFFER xid=0x7b21c9a4 yiaddr=192.168.1.201 server=192.168.1.66 lease=86400 router=192.168.1.66 dns=192.168.1.66
0.031 192.168.1.1:67 > 255.255.255.255:68 OFFER xid=0x7b21c9a4 yiaddr=192.168.1.50 server=192.168.1.1 lease=3600 router=192.168.1.1 dns=192.168.1.1
0.032 0.0.0.0:68 > 255.255.255.255:67 REQUEST xid=0x7b21c9a4 mac=02:00:00:00:00:77 requested=192.168.1.201 server=192.168.1.66
0.036 192.168.1.66:67 > 255.255.255.255:68 ACK xid=0x7b21c9a4 yiaddr=192.168.1.201 server=192.168.1.66 lease=86400 router=192.168.1.66 dns=192.168.1.66
EOT
cat > ntp2.txt <<'EOT'
5000.000 5000.640 5000.641 5000.201
5000.000 5000.480 5000.481 5000.041
5000.000 5000.700 5000.701 5000.561
EOT
cat > web.log <<'EOT'
203.0.113.9 /home 200
2001:db8:10:1::25 /login 200
2001:db8:10:1:ac5e:1ff:fe03:7 /admin 403
fd00:20::5 /api 200
::1 /status 200
198.51.100.7 /login 401
2001:db8:10:2::9 /login 401
2001:db8:10:1::25 /orders 200
::ffff:192.0.2.55 /orders 200
10.20.1.8 /home 200
EOT
  1. Run dhcp.py on exchange2.txt. Extend it to print how many different servers sent an OFFER, and to warn if there is more than one. Which server did the client choose, and why that one?
  2. The three lines of ntp2.txt are three samples of one clock. Use the sample that you trust most (the shortest delay) and say what the offset of the clock is.
  3. Write a program that reads web.log with ipaddress. Count the lines whose address ipaddress reports as version 6 (an IPv4-mapped address counts), and the number of different /64 networks among the 2001:db8 clients.
  4. Stretch task, outside the 60 minutes: find which MAC address made the interface ID of 2001:db8:10:1:ac5e:1ff:fe03:7: reverse the EUI-64 rule, and write down the MAC address that you find.
A model program for web.log
import ipaddress

v6 = 0
networks = set()
for line in open("web.log"):
    address = ipaddress.ip_address(line.split()[0])
    if address.version == 6:
        v6 += 1
        if address in ipaddress.ip_network("2001:db8::/32"):
            networks.add(ipaddress.ip_network(f"{address}/64", strict=False))
print(v6, len(networks))

It prints 7 2. The mapped address ::ffff:192.0.2.55 is version 6 too. strict=False lets the module cut an address down to its /64 network.

For task 4: the interface ID is ac5e:01ff:fe03:0007. Remove the middle ff:fe, and flip bit 7 of the first byte back (ac becomes ae). The MAC address is ae:5e:01:03:00:07.

Check yourself

Why does a DHCP client send its first message as a broadcast from 0.0.0.0?

It has no address yet and does not know where the server is. A broadcast reaches every machine on the local network, and the server answers it. This is also why DHCP works only on one local network, unless a relay agent passes the messages on.

A laptop has the address 169.254.7.20 and no gateway. What happened?

The client sent DISCOVER and got no OFFER, so it gave itself a link-local address. Look for a DHCP server that is down, a port in the wrong VLAN (lesson 4), or a lease pool that is full.

One phone shows "certificate not yet valid" for every site, but other devices are fine. What do you check first?

Its clock. A clock that is behind the start date of a certificate makes the check fail, and the fix is to sync the clock, not to trust the certificate.

A server allows only your office IPv4 range, and the firewall has IPv4 rules only. Why can it still be open to the world?

IPv4 and IPv6 have separate rule sets. If the server has a global IPv6 address and listens on ::, the IPv4 rules do not apply to it. Check ss -tln for listeners on [::], and write the rules for both families.

Field notes

  • DHCP is specified in RFC 2131, NTP version 4 in RFC 5905, SLAAC in RFC 4862 and IPv6 addressing in RFC 4291.
  • A rogue DHCP server is a man-in-the-middle with one packet. Switches can allow DHCP answers only from trusted ports (DHCP snooping), and a monitor can alert when it sees two different servers answer one xid. A rogue router advertisement does the same in IPv6, and RA guard on the switch stops it.
  • Log the lease, not only the address. "Who had 192.168.1.50 at 09:14?" needs the lease records and clocks that agree. Write logs in UTC, and alert when the offset of a system is above a limit.
  • Do not turn IPv6 off to be safe: you only lose sight of it. Keep it, filter it, and log it. Write allow-lists and reports for both families, and group IPv6 clients by /64, because one host can use many addresses.
  • NTP over plain UDP has no check of the server, so a network attacker can move a clock. Use several sources, and where you can, NTP with authentication (Network Time Security).