Lesson 10 · 55 minutes
Capture and read the traffic of a connection
- Explain what a packet capture is and when a defender takes one
- Write a logging proxy that shows the bytes between a client and a server
- Compare readable HTTP with unreadable TLS and name what still leaks
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 security team found a small program on a lab machine that calls a service every few minutes. Nobody knows what it sends. The program is on your own machine now, and the service it calls is a plain HTTP server on the loopback. You must put a tool between the two, read the message, and report what the program sends: which software it names, and whether it sends a secret in clear text.
Recall
Which part of the TLS handshake can an observer on the network still read?
The server name in the SNI field of the first message, unless the connection uses Encrypted Client Hello. The addresses, ports and sizes are visible too. The paths, headers and bodies are not.
Which header carries a cookie from the client to the server?
The Cookie header. The server sets the value earlier in a Set-Cookie header of a response.
The idea
A packet capture records the packets that pass a network interface. The standard tool is tcpdump. It reads packets at a low level, so it needs special rights: root, or the capability CAP_NET_RAW. A saved capture is a .pcap file that other tools can open later.
A defender takes a capture to answer a narrow question: does this host talk to that address, is this protocol in clear text, what does the first failed handshake look like. Capture only networks and hosts that you own or may test. A capture often holds passwords and personal data, so keep the file as secret as the data inside it.
On your real network tcpdump needs root. In a private network that you make with unshare (lesson 3) you are root, so you can capture there without sudo. A second view comes from a proxy: a program that sits between a client and a server and passes the bytes on. If the proxy prints every byte that passes, you see what a capture on that link would show. This is a legitimate tool for your own lab; it works only because the client was told to talk to the proxy. You use both views.
- Client → Logging proxy: request, sent to the proxy port
- Logging proxy → Proxy terminal: prints the bytes
- Logging proxy → Web server: the same bytes
- Web server → Logging proxy: response
- Logging proxy → Client: the same bytes
Worked example
1. Know the tcpdump commands (needs root)
On your real network these commands need sudo (run as the administrator), so no output is shown here. Run them only on a machine that you own. -i lo is the loopback interface, -nn shows numbers, not names, -A prints the data as text, -w writes the packets to a file, -r reads such a file, and port 8000 is a filter.
sudo tcpdump -i lo -nn -A port 8000
sudo tcpdump -i lo -nn -w web.pcap port 8000
tcpdump -nn -r web.pcapThe first prints packets live. The second saves them to a file, and the third reads that file back (reading a file needs no root).
2. Capture without root
A new network namespace is empty and you are root in it, so tcpdump works there. The script caplab.sh starts a web server inside the namespace and captures its port into web.pcap. Then it sends one request with curl. A new loopback starts switched off, so the script turns it on first. -Z root stops tcpdump from dropping its rights, and -U writes each packet at once. At the end the script stops both programs. This step needs unshare, as in lesson 3. If unshare -Urn true fails on your system, skip it: "Your turn" gives a recorded capture. Your real network is not touched.
caplab.sh
#!/bin/sh
# Run with: unshare -Urn sh caplab.sh (a private network; your real one is not touched)
ip link set lo up # a new network starts with lo down
python3 -m http.server 8000 --bind 127.0.0.1 > /dev/null 2>&1 &
SERVER=$!
tcpdump -Z root -U -i lo -nn -w web.pcap port 8000 2> /dev/null &
DUMP=$!
sleep 1
curl -s -o /dev/null -H 'Cookie: sid=abc123' http://127.0.0.1:8000/
sleep 1
kill $DUMP $SERVERunshare -Urn sh caplab.sh
tcpdump -nn -t -r web.pcap 2>/dev/null | cut -d, -f1 | head -6
tcpdump -nn -A -r web.pcap 2>/dev/null | grep -oE 'GET / HTTP/1.1|Cookie: sid=abc123'The second command reads the file. -t leaves out the times, and cut -d, -f1 keeps the text before the first comma of each line. The third command prints the data of each packet (-A) and keeps only the two matches (-o). The ports of your run will differ.
IP 127.0.0.1.38878 > 127.0.0.1.8000: Flags [S]
IP 127.0.0.1.8000 > 127.0.0.1.38878: Flags [S.]
IP 127.0.0.1.38878 > 127.0.0.1.8000: Flags [.]
IP 127.0.0.1.38878 > 127.0.0.1.8000: Flags [P.]
IP 127.0.0.1.8000 > 127.0.0.1.38878: Flags [.]
IP 127.0.0.1.8000 > 127.0.0.1.38878: Flags [P.]
GET / HTTP/1.1
Cookie: sid=abc123The first three lines are the handshake of lesson 5: S is SYN, S. is SYN-ACK and . is ACK. P. is a packet that carries data. The cookie is in the file in clear text. A capture holds all that the packets held, so keep the file as secret as its data.
3. Start the servers
Use the folder from the earlier lessons. You need the web server from lesson 8 and https_server.py from lesson 9. If the certificate is older than 30 days, make a new one with the command of lesson 9. Run each in its own terminal.
cd ~/krlab/networking
python3 -m http.server 8000 --bind 127.0.0.1cd ~/krlab/networking
python3 https_server.py4. Write the logging proxy
Write proxy.py. It takes two ports: the port to listen on and the port of the real server. For each client it opens a connection to the server, and two threads (parts of the program that run at the same time) copy the bytes in each direction. The function show prints text as text, and anything else as the first bytes in hexadecimal. When one side stops sending, shutdown(socket.SHUT_WR) tells the other side that no more data comes, but still lets the answer travel back.
proxy.py
import socket
import sys
import threading
listen_port, target_port = int(sys.argv[1]), int(sys.argv[2])
def show(label, data):
print(f"--- {label}: {len(data)} bytes", flush=True)
try:
print(data.decode("ascii"), flush=True)
except UnicodeDecodeError:
print("(not text) first 24 bytes:", data[:24].hex(" "), flush=True)
def pipe(src, dst, label):
while data := src.recv(4096):
show(label, data)
dst.sendall(data)
try:
dst.shutdown(socket.SHUT_WR)
except OSError:
pass
listener = socket.create_server(("127.0.0.1", listen_port))
print(f"proxy on 127.0.0.1:{listen_port} -> 127.0.0.1:{target_port}", flush=True)
while True:
client, _ = listener.accept()
server = socket.create_connection(("127.0.0.1", target_port))
threading.Thread(target=pipe, args=(client, server, "client to server"), daemon=True).start()
threading.Thread(target=pipe, args=(server, client, "server to client"), daemon=True).start()5. Watch plain HTTP
Start the proxy for the web server in a third terminal.
python3 proxy.py 8020 8000In a fourth terminal, send a request through the proxy. -H adds a header to the request. The cookie is a made-up value that shows what passes.
curl -s http://127.0.0.1:8020/ -H 'Cookie: sid=abc123'The proxy terminal prints:
proxy on 127.0.0.1:8020 -> 127.0.0.1:8000
--- client to server: 98 bytes
GET / HTTP/1.1
Host: 127.0.0.1:8020
User-Agent: curl/8.18.0
Accept: */*
Cookie: sid=abc123
--- server to client: 185 bytes
HTTP/1.0 200 OK
Server: SimpleHTTP/0.6 Python/3.14.4
Content-type: text/html
Content-Length: 17
--- server to client: 17 bytes
hello from krlab(The output is shortened: the real answer also has the Date and Last-Modified headers.) Everything is readable, including the cookie. Anyone on a link that carries this traffic sees the same.
6. Watch HTTPS
Stop the first proxy with Ctrl+C. Start a second one that points to the HTTPS server on port 8010.
python3 proxy.py 8021 8010Connect through it. The proxy only moves bytes, so the TLS session goes end to end between curl and the server, and curl still checks the certificate.
curl -sS --cacert cert.pem https://localhost:8021/hello from krlabThe proxy terminal shows something very different:
proxy on 127.0.0.1:8021 -> 127.0.0.1:8010
--- client to server: 1569 bytes
(not text) first 24 bytes: 16 03 01 06 1c 01 00 06 18 03 03 63 0f f7 83 a8 18 4b 98 7c dd 21 81 48
--- server to client: 2457 bytes
(not text) first 24 bytes: 16 03 03 04 ba 02 00 04 b6 03 03 0a 5d 64 1b 74 d2 94 4c ff 83 3b d5 46
--- client to server: 80 bytes
...
--- client to server: 100 bytes
(not text) first 24 bytes: 17 03 03 00 5f 0e d6 79 9c a2 7b 8d 44 98 68 a5 1c 62 e0 a1 d6 e9 14 00
--- server to client: 271 bytes
(not text) first 24 bytes: 17 03 03 01 0a 1b 98 25 bd 83 6b 1a c7 e3 b5 53 39 96 c0 bc 64 90 76 c0The first byte of each chunk is the TLS record type. 16 is a handshake record (01 is a ClientHello, and in the second chunk 02 is a ServerHello). 17 is application data: your request and the answer, now encrypted. The path, the headers and the page are gone. The sizes and the timing remain.
7. Stop everything
Press Ctrl+C in each of the four terminals. Check that the ports are free. grep -E takes a pattern with alternatives, and || runs the echo only when grep finds nothing.
ss -tlnp | grep -E ':80(00|10|20|21)\b' || echo freefreeYour turn
Report on the program of the scenario. There are no steps here: use the proxy of the worked example, on a different client and server.
Save these two programs. sink.py is the service: it listens on 127.0.0.1, port 8072, and answers every POST with ok. beacon.py is the program that calls home: it connects to port 8070, or to the port that you give as an argument, and sends one fixed request.
sink.py
from http.server import BaseHTTPRequestHandler, HTTPServer
class Sink(BaseHTTPRequestHandler):
def do_POST(self):
self.rfile.read(int(self.headers["Content-Length"]))
self.send_response(200)
self.send_header("Content-Length", "3")
self.end_headers()
self.wfile.write(b"ok\n")
def log_message(self, *args):
pass
print("sink on 127.0.0.1 port 8072. Press Ctrl+C to stop.", flush=True)
HTTPServer(("127.0.0.1", 8072), Sink).serve_forever()beacon.py
import socket
import sys
port = int(sys.argv[1]) if len(sys.argv) > 1 else 8070
body = b"user=dana&token=T-4417-XK"
request = (
b"POST /login HTTP/1.1\r\n"
b"Host: sink.lab\r\n"
b"User-Agent: kr-beacon/1.0\r\n"
b"Content-Type: application/x-www-form-urlencoded\r\n"
b"Content-Length: " + str(len(body)).encode() + b"\r\n"
b"Connection: close\r\n"
b"\r\n" + body
)
with socket.create_connection(("127.0.0.1", port), timeout=3) as s:
s.sendall(request)
answer = b""
while chunk := s.recv(4096):
answer += chunk
print(answer.decode().splitlines()[0])Start sink.py in one terminal. Start your proxy.py in a second terminal so that it listens on port 8070 and forwards to port 8072. Run beacon.py in a third terminal. Read what the proxy prints. Then stop all three programs and check that the ports are free.
Now look at the same beacon in a capture, without a proxy. You have two ways, and the answer is the same.
- Copy
caplab.shand change it: startsink.pyin place of the web server, capture port 8072 intobeacon.pcap, and runpython3 beacon.py 8072in place ofcurl. - If
unshareis forbidden on your system, use a recording of that capture. Save the text below asbeacon.hex, and turn it into the file with the second command.
beacon.hex
d4c3b2a1020004000000000000000000000004000100000005b6016bdb170800
4a0000004a00000000000000000000000000000008004500003cdec340004006
5df67f0000017f000001a25c1f88e42ba02900000000a002ffd7fe3000000204
ffd70402080a39b66546000000000103030a05b6016be81708004a0000004a00
000000000000000000000000000008004500003c0000400040063cba7f000001
7f0000011f88a25c7e41e281e42ba02aa012ffcbfe3000000204ffd70402080a
34d9ecea39b665460103030a05b6016bf2170800420000004200000000000000
0000000000000000080045000034dec4400040065dfd7f0000017f000001a25c
1f88e42ba02a7e41e28280100040fe2800000101080a39b6654634d9ecea05b6
016b23180800f6000000f60000000000000000000000000000000800450000e8
dec5400040065d487f0000017f000001a25c1f88e42ba02a7e41e28280180040
fedc00000101080a39b6654634d9ecea504f5354202f6c6f67696e2048545450
2f312e310d0a486f73743a2073696e6b2e6c61620d0a557365722d4167656e74
3a206b722d626561636f6e2f312e300d0a436f6e74656e742d547970653a2061
70706c69636174696f6e2f782d7777772d666f726d2d75726c656e636f646564
0d0a436f6e74656e742d4c656e6774683a2032350d0a436f6e6e656374696f6e
3a20636c6f73650d0a0d0a757365723d64616e6126746f6b656e3d542d343431
372d584b05b6016b281808004200000042000000000000000000000000000000
080045000034142640004006289c7f0000017f0000011f88a25c7e41e282e42b
a0de80100040fe2800000101080a34d9ecea39b6654605b6016b001a0800b100
0000b10000000000000000000000000000000800450000a3142740004006282c
7f0000017f0000011f88a25c7e41e282e42ba0de80180040fe9700000101080a
34d9ecea39b66546485454502f312e3020323030204f4b0d0a5365727665723a
2042617365485454502f302e3620507974686f6e2f332e31342e340d0a446174
653a205361742c203231204e6f7620323032362031353a31373a323520474d54
0d0a436f6e74656e742d4c656e6774683a20330d0a0d0a05b6016b091a080042
00000042000000000000000000000000000000080045000034dec6400040065d
fb7f0000017f000001a25c1f88e42ba0de7e41e2f180100040fe280000010108
0a39b6654634d9ecea05b6016b1b1a0800450000004500000000000000000000
000000000008004500003714284000400628977f0000017f0000011f88a25c7e
41e2f1e42ba0de80180040fe2b00000101080a34d9ecea39b665466f6b0a05b6
016b1f1a08004200000042000000000000000000000000000000080045000034
dec7400040065dfa7f0000017f000001a25c1f88e42ba0de7e41e2f480100040
fe2800000101080a39b6654634d9ecea05b6016b401a08004200000042000000
00000000000000000000000008004500003414294000400628997f0000017f00
00011f88a25c7e41e2f4e42ba0de80110040fe2800000101080a34d9ecea39b6
654605b6016b541a080042000000420000000000000000000000000000000800
45000034dec8400040065df97f0000017f000001a25c1f88e42ba0de7e41e2f5
80110040fe2800000101080a39b6654634d9ecea05b6016b601a080042000000
42000000000000000000000000000000080045000034142a4000400628987f00
00017f0000011f88a25c7e41e2f5e42ba0df80100040fe2800000101080a34d9
ecea39b66546python3 -c "open('beacon.pcap','wb').write(bytes.fromhex(open('beacon.hex').read()))"Read beacon.pcap with tcpdump -nn -A -r beacon.pcap. If you have no tcpdump, count the token in the file: python3 -c "print(open('beacon.pcap','rb').read().count(b'T-4417-XK'))". Then answer.
Write one sentence for the security team: what would you change so that a person on the network could not read the token?
Check yourself
A capture of a login shows the line "password=hunter2" in clear text. What does that tell you?
The login uses plain HTTP (or another clear protocol), not TLS. Anyone on the path can read the password. The fix is to use HTTPS for the whole site and to redirect plain requests, not to hide the capture.
Your proxy sees the encrypted bytes. Why can it not read them, although it sits in the middle?
The keys exist only in the client and the server. The proxy has no key, and it passes the bytes through. To read them, a proxy must end the TLS session itself and open a new one to the server. Then the client sees a certificate for the proxy and must trust it. Lesson 11 describes proxies, and a reverse proxy that ends TLS is one of them.
What can an analyst still learn from a capture of encrypted traffic?
The addresses, the ports, the times, the sizes of the messages and how often they repeat. Usually the server name from SNI also shows (lesson 9). A beacon that calls home every 60 seconds with the same size is visible even when its content is not.
Field notes
- Capture as little as you need. Use a filter (
host,port) and a limit (-c 200, or-sfor a short snap length) so that you do not store whole payloads. A capture file of a production network is personal data, so follow your rules for that data. - Use
-wto save and read the file later. Working on the saved file is repeatable, and it keeps the original for evidence. Record the time, the interface, the filter and a hash (sha256sum) of the file. - You cannot read TLS 1.3 traffic in a capture even with the server's private key, because each session has its own keys (forward secrecy). To decrypt your own lab traffic, a client can write its session keys to a file (the
SSLKEYLOGFILEvariable that curl and browsers support). Use that only on your own client. - A capture on
anyor on the wrong interface hides the traffic you want, and offloading features of a network card can make checksums look wrong. If a packet looks odd, check the interface setting before you suspect an attack. - Tools that read
.pcapfiles, such as Wireshark andtshark, show the same bytes with protocol decoding. They are the next step aftertcpdump.