Lesson 01 · 50 minutes
Label the layers of a network packet
- Name the layers of the OSI and TCP/IP models, and the protocols and devices that belong to each
- Build a packet in Python and label the Ethernet, IP and TCP headers in it
- Use the layers to say where a network fault is
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
Five users write to the help desk: "the network is down". Your team lead says: "I do not want 'the network'. I want a layer." The web server team sends you a recorded packet from the capture of one failing request, as a line of hexadecimal text. You must label every header in it, say which device reads which header, and then say, for four symptoms, which layer to test first.
The idea
A network does many jobs: move signals, deliver to the right machine, find a path, keep order, carry the words of a program. A layer is one of these jobs. Each layer uses the layer below it and serves the layer above it. The OSI model (Open Systems Interconnection) has seven layers. The TCP/IP model is the shorter model that matches the protocols of the internet: four layers. You need both, because engineers say "layer 4" (OSI) and read the real protocols as TCP/IP.
| OSI layer | Unit of data | Job | Protocols | Device |
|---|---|---|---|---|
| 7 Application | data | What the programs say | HTTP, DNS, SSH | Proxy, web application firewall |
| 6 Presentation | data | Format and encryption | TLS (placed here or in layer 5) | |
| 5 Session | data | Start and end a dialogue | TLS sessions | |
| 4 Transport | segment (TCP), datagram (UDP) | Ports, order, repeat when lost | TCP, UDP | Stateful firewall |
| 3 Network | packet | Addresses and paths between networks | IP, ICMP | Router |
| 2 Data link | frame | Delivery on one local network, by MAC address | Ethernet, Wi-Fi, ARP | Switch, access point |
| 1 Physical | bits | Signals on copper, fibre or radio | Cables, radio | Cable, hub, repeater |
The TCP/IP model joins layers 7, 6 and 5 into Application, keeps Transport (4), calls layer 3 Internet, and joins layers 2 and 1 into Link.
A MAC address is the 6-byte hardware address of a network card, for example 02:00:00:00:00:50. Only machines on the same local network use it to find each other.
Encapsulation is how the layers work together. The sender goes down: each layer puts its own header (control data) in front of the data from the layer above. The receiver goes up and removes the headers in reverse order.
- Laptop → Switch: frame to the router's MAC, IP of the server
- Switch → Router: reads the MAC header only, then forwards
- Router → Web server: new MAC header, same IPs, TTL 63
The layers also give you a method. A working layer proves that the layers below it work, for that path. A failing layer tells you where to look. A protocol is a set of agreed rules for one job. It lives in one layer, but a few, such as ARP and TLS, sit between two.
Worked example
1. Make a helper module
Go to your lab folder. The module inet.py holds three small functions that every later program of this lesson uses. checksum computes the check value that IP, TCP and UDP put in their headers, so that a receiver can find a damaged header. Treat it as a black box for now: read its lines later, when you want to know how it works. struct.unpack (in the struct module) turns bytes into numbers: the format !H means one 16-bit number.
cd ~/krlab/networkinginet.py
import struct
def checksum(data):
"""The 16-bit one's complement checksum that IP, TCP and UDP use."""
if len(data) % 2:
data += b"\x00"
total = sum(struct.unpack(f"!{len(data) // 2}H", data))
while total > 0xFFFF:
total = (total & 0xFFFF) + (total >> 16)
return ~total & 0xFFFF
def mac_text(raw):
return ":".join(f"{b:02x}" for b in raw)
def ip_text(raw):
return ".".join(str(b) for b in raw)2. Build a packet from the top down
struct.pack is the reverse of unpack: it turns numbers into bytes. The program builds the data first, then the TCP header, then the IP header, then the Ethernet header. This is encapsulation. It sends nothing: it writes the bytes of one frame, as hexadecimal text, into frame.hex. Two hexadecimal characters are one byte. socket.inet_aton turns the text of an IP address into its 4 bytes.
Read the program once and run it. You do not need to remember the codes. What matters is the order: data, then TCP, then IP, then Ethernet. Three small ideas help you read it:
structcodes. One letter is one field.!means network byte order, the biggest byte first.Bis 1 byte,His 2 bytes,Iis 4 bytes, and4sor6sis 4 or 6 raw bytes.- Numbers. A number that starts with
0xis hexadecimal.5 << 4moves the bits of 5 four places to the left, so the header length 5 sits in the high half of its byte.0x4000is the flag "do not fragment". - The checksum. Each header is built with 0 in the checksum field. Then the program computes the value and writes it in with slices:
tcp[:16]is the bytes before the field, andtcp[18:]is the bytes after it. The TCP checksum also covers a pseudo-header, a copy of the two IP addresses and the protocol.
build.py
import socket
import struct
from inet import checksum
SRC_MAC, DST_MAC = bytes.fromhex("020000000050"), bytes.fromhex("020000000001")
SRC_IP, DST_IP = socket.inet_aton("192.168.1.50"), socket.inet_aton("192.168.1.80")
PAYLOAD = b"GET /index.html HTTP/1.1\r\nHost: app.lab.test\r\n\r\n"
# Layer 4: TCP header, 20 bytes. Ports, sequence, acknowledgement, header length, flags PSH+ACK, window.
tcp = struct.pack("!HHIIBBHHH", 51514, 80, 1000, 5000, 5 << 4, 0x18, 64240, 0, 0)
pseudo = SRC_IP + DST_IP + struct.pack("!BBH", 0, 6, len(tcp) + len(PAYLOAD))
tcp = tcp[:16] + struct.pack("!H", checksum(pseudo + tcp + PAYLOAD)) + tcp[18:]
# Layer 3: IPv4 header, 20 bytes. Version 4 and length 5 words, total length, id, flags, TTL 64, protocol 6 (TCP).
ip = struct.pack("!BBHHHBBH4s4s", 0x45, 0, 20 + len(tcp) + len(PAYLOAD), 0x1234, 0x4000, 64, 6, 0, SRC_IP, DST_IP)
ip = ip[:10] + struct.pack("!H", checksum(ip)) + ip[12:]
# Layer 2: Ethernet header, 14 bytes. Destination, source, type 0x0800 (IPv4).
eth = DST_MAC + SRC_MAC + struct.pack("!H", 0x0800)
frame = eth + ip + tcp + PAYLOAD
open("frame.hex", "w").write(frame.hex() + "\n")
print(len(frame), "bytes")
print(frame.hex())python3 build.py102 bytes
020000000001020000000050080045000058123440004006a499c0a80132c0a80150c93a0050000003e8000013885018faf0030b0000474554202f696e6465782e68746d6c20485454502f312e310d0a486f73743a206170702e6c61622e746573740d0a0d0a3. Label the layers from the bytes
The reader program works from the bottom up. It cuts 14 bytes for layer 2, reads the length of the IP header, reads the protocol number to learn what comes next, and so on. This is decapsulation. It stops at a protocol that it does not know: you use that in "Your turn".
The first byte of the IP header holds two numbers of 4 bits each: the version (high half) and the header length (low half), counted in words of 4 bytes. & 15 keeps the low half, and * 4 turns words into bytes. >> 4 moves the high half down; the offset byte of the TCP header has the same layout. flags >> i & 1 moves bit number i to the right end and keeps it: 1 means that the flag is set.
layers.py
import struct
import sys
from inet import checksum, ip_text, mac_text
FLAGS = ["FIN", "SYN", "RST", "PSH", "ACK", "URG"]
frame = bytes.fromhex(open(sys.argv[1]).read())
print(f"frame: {len(frame)} bytes")
dst, src, ethertype = struct.unpack("!6s6sH", frame[:14])
print(f"layer 2 Ethernet dst {mac_text(dst)} src {mac_text(src)} type 0x{ethertype:04x}")
if ethertype != 0x0800:
sys.exit("not IPv4, stop here")
header_length = (frame[14] & 15) * 4
ip = frame[14:14 + header_length]
_, _, total, ident, _, ttl, proto, _, src_ip, dst_ip = struct.unpack("!BBHHHBBH4s4s", ip[:20])
good = "ok" if checksum(ip) == 0 else "BAD"
print(f"layer 3 IPv4 src {ip_text(src_ip)} dst {ip_text(dst_ip)} ttl {ttl} protocol {proto} "
f"length {total} checksum {good}")
rest = frame[14 + header_length:]
if proto == 6:
sport, dport, seq, ack, offset, flags = struct.unpack("!HHIIBB", rest[:14])
names = " ".join(n for i, n in enumerate(FLAGS) if flags >> i & 1)
print(f"layer 4 TCP sport {sport} dport {dport} seq {seq} ack {ack} flags {names}")
payload = rest[(offset >> 4) * 4:]
else:
sys.exit(f"protocol {proto}: not handled yet")
print(f"layer 7 data {len(payload)} bytes: {payload.splitlines()[0].decode()}")python3 layers.py frame.hexframe: 102 bytes
layer 2 Ethernet dst 02:00:00:00:00:01 src 02:00:00:00:00:50 type 0x0800
layer 3 IPv4 src 192.168.1.50 dst 192.168.1.80 ttl 64 protocol 6 length 88 checksum ok
layer 4 TCP sport 51514 dport 80 seq 1000 ack 5000 flags PSH ACK
layer 7 data 48 bytes: GET /index.html HTTP/1.1Read each line against the table. The MAC addresses are the layer 2 addresses: a switch uses them. The IP addresses and the protocol number 6 (TCP) are layer 3: a router uses them. The ports and the flags are layer 4: a stateful firewall uses them. seq and ack count bytes, and the flags are one-bit marks such as SYN and ACK (lesson 5 explains them). The text is layer 7. The destination port 80 tells the receiver which program gets the data.
4. Damage one header and watch the layer notice
sed (stream editor) changes text as it passes through, and 's/old/new/' replaces the first match. The TTL ("time to live") is a counter that each router lowers by one. This command copies the frame and changes the TTL byte from 64 to 63, as if a router had touched it without fixing the checksum. In hexadecimal, 40 is 64 and 3f is 63. The pattern includes the bytes next to the TTL (4000 before it, 06 and the checksum after it), so that it matches in one place only.
sed 's/40004006a499/40003f06a499/' frame.hex > bad.hex
python3 layers.py bad.hexframe: 102 bytes
layer 2 Ethernet dst 02:00:00:00:00:01 src 02:00:00:00:00:50 type 0x0800
layer 3 IPv4 src 192.168.1.50 dst 192.168.1.80 ttl 63 protocol 6 length 88 checksum BAD
layer 4 TCP sport 51514 dport 80 seq 1000 ack 5000 flags PSH ACK
layer 7 data 48 bytes: GET /index.html HTTP/1.1A real router lowers the TTL and writes a new checksum, so the packet stays valid. When the TTL reaches 0 the router drops the packet, which stops a loop.
5. Ask your own machine about three layers
Three commands show the layers of your machine. ip -br link lists the cards with their MAC addresses (layer 2). ip -4 -br addr lists the IP addresses (layer 3). ss -tln lists the TCP ports where programs wait for a client (layer 4). Your output will differ.
ip -br link
ip -4 -br addr
ss -tlnlo UNKNOWN 00:00:00:00:00:00 <LOOPBACK,UP,LOWER_UP>
ens1f0 UP 02:00:00:00:00:50 <BROADCAST,MULTICAST,UP,LOWER_UP>
lo UNKNOWN 127.0.0.1/8
ens1f0 UP 192.168.1.50/24
State Recv-Q Send-Q Local Address:Port Peer Address:Port
LISTEN 0 4096 127.0.0.53%lo:53 0.0.0.0:*UP with LOWER_UP means that layer 1 works: the card has a signal. Lessons 2 and 5 explain the other two commands.
6. Choose the first layer to test
| Symptom | Layer | First test |
|---|---|---|
The card is DOWN, or has no carrier | 1 | Cable, port, Wi-Fi switch |
No address, or the address starts with 169.254 | 2 or 3 | The address service (lesson 6) |
| You can reach your own network, but not another | 3 | The routing table (lesson 2) |
connection refused or a timeout | 4 | Port, service, firewall (lesson 5) |
| A certificate warning | 5 or 6 | TLS (lesson 9) |
404, 500 or a wrong name | 7 | The application, the name (lessons 7 and 8) |
Your turn
The web team sent a second recorded frame. Save it as mystery.hex. It does not use TCP.
mystery.hex
020000000001020000000077080045000039beef40004011f840c0a80132c0a801019d1500350025f53c1a2b01000001000000000000076578616d706c6503636f6d0000010001Label it. Today layers.py stops at the protocol that it does not know. Extend it so that it labels the next header, and so that it reads the name that the program at the top layer asks for. For the first part you need the UDP header. It has 8 bytes, each field is 16 bits, and the order is source port, destination port, length and checksum. For the second part, know that this protocol carries a DNS message (lesson 7 describes DNS): a 12-byte header, then the question. Each part of the name has a length byte in front of it, and a zero byte ends the name. With data as the bytes after the UDP header, this loop reads the name:
i = 12 # the name starts after the 12-byte DNS header
labels = []
while data[i]: # a length of 0 ends the name
labels.append(data[i + 1:i + 1 + data[i]].decode())
i += 1 + data[i]
print(".".join(labels))Then answer from your own output.
Write one line for each layer that says which device or program reads that header.
Check yourself
A frame crosses three routers. Which of the addresses change at each router?
The MAC addresses change at every hop, because each router builds a new frame for the next local network. The IP addresses stay the same from the sender to the receiver (unless NAT changes them, lesson 12). The TTL goes down by one at each router.
A user can ping 192.168.1.80 but the browser says "server not found". Which layer is the problem?
The ping proves layers 1 to 3. The browser needs a name, and DNS is a layer 7 protocol. Test the name resolution (lesson 7).
Which header does a switch read, and which does a router read?
A switch reads the Ethernet header (MAC addresses, layer 2). A router reads the IP header (IP addresses, layer 3).
Why is "the network is down" a poor report, and what should it say?
It names no layer and no scope. A good report says who is affected, what they try to reach, what they see, and the last working layer. For example: "Two users in room 4 cannot open the intranet, they can ping its address, and the error is a certificate warning." That points to layer 5 or 6, not to a cable.
Field notes
- A tool shows only the layers that it reads. A cloud flow log shows layers 3 and 4 (addresses, ports, bytes). A proxy log shows layer 7. Know what your log does not show.
- Tunnels hide layers inside layers. A VPN puts a whole IP packet inside the data of another packet, so a capture on the outside shows only the outer headers (lesson 11).
- The checksum finds accidents, not attacks. Anyone can compute a new checksum after a change. Integrity against an attacker needs a key (TLS, lesson 9).