Lab: the TLS 1.3 handshake on the wire, with SNI, ALPN and HTTP/2 vs HTTP/3
Record a real TLS 1.3 handshake through a local relay, decode the plaintext ClientHello and ServerHello (SNI, ALPN, versions, key shares), name the encrypted messages with openssl s_client -trace, decrypt your own session from an SSLKEYLOGFILE, watch hybrid ML-KEM key exchange, compare HTTP/2 over TCP with HTTP/3 over QUIC, and diagnose six broken endpoints.
Contentsand lesson path
On this page
- Goal and setup
- Step 1: Start a TLS server and a recording relay
- Step 2: Connect through the relay and keep the session keys
- Step 3: Read what the network sees
- Step 4: Name the encrypted messages with s_client -trace
- Step 5: Decrypt your own session with the key log
- Step 6: Hybrid post-quantum key exchange
- Step 7: HTTP/2 over TCP and HTTP/3 over QUIC
- Step 8: Diagnose six broken endpoints
- Troubleshooting
- Check your understanding
- Apply it
- Review prompt
Lessons of TLS & PKI
- What TLS gives you: confidentiality, integrity and authentication Concept · 15 min
- Lab: the TLS 1.3 handshake on the wire, with SNI, ALPN and HTTP/2 vs HTTP/3 Lab · 25 min
- Certificates and chains: how a client decides to trust a server Concept · 20 min
- Lab: a two-tier private CA (offline root, issuing CA), server and client certificates, and mutual TLS Lab · 30 min
- Operating PKI: ACME automation as lifetimes shrink, revocation availability and CA compromise plans Worked example · 25 min
- Check: debug five broken TLS endpoints with openssl s_client Knowledge check · 10 questions
What you will learn
- Explain the TLS 1.3 handshake - key exchange, server authentication, SNI and ALPN - and what TLS does and does not protect.
- Diagnose TLS failures - expired or mismatched certificates, incomplete chains, protocol or cipher mismatches - with openssl s_client and Wireshark.
01. Goal and setup
In lesson 1 you read the handshake as a list of messages; here you watch it. A small relay on 127.0.0.1 saves every byte, so you see what a network observer sees: two plaintext hellos, then opaque records. It replaces packet capture, which usually needs root rights. You then decrypt your own session from a key log, compare HTTP/2 with HTTP/3, and diagnose six broken endpoints with openssl s_client.
You need: openssl 3.x (outputs below are from OpenSSL 3.0.2 on Ubuntu 22.04), curl with HTTP/2 support (curl -V lists HTTP2) and uv. uv's own Python 3.12 build (--managed-python) brings OpenSSL 3.5, which matters in step 6. The packages are aioquic==1.8.0 (QUIC and HTTP/3), hypercorn[h3]==0.18.0 (a server for HTTP/1.1, HTTP/2 and HTTP/3) and cryptography==50.0.2 (for decrypt.py). Everything uses ports 8441 to 8448 on 127.0.0.1. Run every block in one terminal, which keeps its variables.
tls-wire-lab/
├── wire.crt, wire.key lab certificate for wire.lab.test
├── default.crt, default.key a second certificate, for the SNI case in step 8
├── chain*.crt, chain*.key root, issuing CA and leaf for case E in step 8
├── relay.py step 1: TCP relay that saves every byte it forwards
├── wire_client.py step 2: Python TLS client (offers h2 and http/1.1)
├── tlsparse.py step 3: prints records and decodes the two hellos
├── decrypt.py step 5: decrypts a capture with an SSLKEYLOGFILE
├── pq_server.py step 6: TLS server built on OpenSSL 3.5
├── app.py step 7: tiny ASGI app for HTTP/2 and HTTP/3
└── h3get.py step 7: HTTP/3 client (aioquic)mkdir tls-wire-lab && cd tls-wire-lab
uv venv -q --managed-python --python 3.12 .venv && source .venv/bin/activate
uv pip install -q "aioquic==1.8.0" "hypercorn[h3]==0.18.0" "cryptography==50.0.2"
openssl version
python -c "import ssl; print(ssl.OPENSSL_VERSION)"OpenSSL 3.0.2 15 Mar 2022 (Library: OpenSSL 3.0.2 15 Mar 2022)
OpenSSL 3.5.7 9 Jun 2026for name in wire default; do
openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:P-256 -nodes \
-keyout $name.key -out $name.crt -days 30 -subj "/CN=$name.lab.test" \
-addext "subjectAltName=DNS:$name.lab.test" \
-addext "basicConstraints=critical,CA:FALSE" \
-addext "extendedKeyUsage=serverAuth" 2>/dev/null
done
openssl x509 -in wire.crt -noout -subject -ext subjectAltNamesubject=CN = wire.lab.test
X509v3 Subject Alternative Name:
DNS:wire.lab.test02. Step 1: Start a TLS server and a recording relay
openssl s_server is OpenSSL's test server. With -www it answers any request with a status page, and -alpn http/1.1 makes it accept only that protocol. The relay forwards bytes both ways and saves them to a JSON file when the connection closes. It does not understand TLS, which is the point: it sees what any router on the path sees.
"""A TCP relay that records every byte it forwards, one JSON file per connection.
Usage: python relay.py LISTEN_PORT UPSTREAM_PORT NAME (both on 127.0.0.1)
"""
import json
import selectors
import socket
import sys
def relay(client: socket.socket, upstream: int, path: str) -> None:
server = socket.create_connection(("127.0.0.1", upstream))
peer = {client: server, server: client}
label = {client: "c2s", server: "s2c"} # client-to-server, server-to-client
chunks = []
sel = selectors.DefaultSelector()
for s in peer:
sel.register(s, selectors.EVENT_READ)
open_sides = 2
while open_sides:
for key, _ in sel.select():
data = key.fileobj.recv(65536)
if not data: # this side closed: stop reading it, tell the other side
sel.unregister(key.fileobj)
try:
peer[key.fileobj].shutdown(socket.SHUT_WR)
except OSError:
pass # the other side is already gone
open_sides -= 1
continue
chunks.append([label[key.fileobj], data.hex()])
peer[key.fileobj].sendall(data)
client.close()
server.close()
with open(path, "w") as f:
json.dump(chunks, f)
print(f"saved {path}", flush=True)
def main() -> None:
listen, upstream, name = int(sys.argv[1]), int(sys.argv[2]), sys.argv[3]
listener = socket.create_server(("127.0.0.1", listen))
print(f"relay 127.0.0.1:{listen} -> 127.0.0.1:{upstream}", flush=True)
number = 0
while True:
client, _ = listener.accept()
number += 1
relay(client, upstream, f"{name}-{number}.json")
if __name__ == "__main__":
main()openssl s_server -accept 127.0.0.1:8441 -cert wire.crt -key wire.key \
-alpn http/1.1 -www -quiet > s_server.log 2>&1 &
S_SERVER_PID=$!
python relay.py 8442 8441 classic > relay.log 2>&1 &
RELAY_PID=$!
sleep 1 && cat relay.logrelay 127.0.0.1:8442 -> 127.0.0.1:844103. Step 2: Connect through the relay and keep the session keys
The client below offers ALPN h2 and http/1.1, sends SNI wire.lab.test and trusts only wire.crt. ssl.create_default_context() reads the environment variable SSLKEYLOGFILE: when it is set, Python appends the session secrets of every connection to that file in the NSS key log format, which Wireshark and curl also use. Treat a key log like a private key. Anyone who has it can read the recorded sessions, so only enable it on test systems.
"""TLS client for the lab: offers h2 and http/1.1, sends one HTTP/1.0 request."""
import socket
import ssl
import sys
port = int(sys.argv[1]) if len(sys.argv) > 1 else 8442
ctx = ssl.create_default_context(cafile="wire.crt") # reads SSLKEYLOGFILE if set
ctx.set_alpn_protocols(["h2", "http/1.1"])
with socket.create_connection(("127.0.0.1", port)) as raw:
with ctx.wrap_socket(raw, server_hostname="wire.lab.test") as tls:
print(tls.version(), tls.cipher()[0], "alpn:", tls.selected_alpn_protocol())
tls.sendall(b"GET / HTTP/1.0\r\n\r\n")
reply = b""
while chunk := tls.recv(4096):
reply += chunk
print(reply.split(b"\r\n", 1)[0].decode())SSLKEYLOGFILE=keys.log python wire_client.py 8442
sleep 0.5 && cat relay.logTLSv1.3 TLS_AES_256_GCM_SHA384 alpn: http/1.1
HTTP/1.0 200 ok
relay 127.0.0.1:8442 -> 127.0.0.1:8441
saved classic-1.jsonThe server picked http/1.1, the only protocol it accepts from the client's list. If the lists had nothing in common, RFC 7301 says the server must end the handshake with a no_application_protocol alert rather than guess.
04. Step 3: Read what the network sees
Every TLS record starts with a 5-byte header: a content type, a legacy version and a length. tlsparse.py splits each direction into records. For the two hello messages, which are not encrypted, it also decodes the fields you met in lesson 1.
"""Print the TLS records in a relay capture and decode the two plaintext hellos."""
import json
import sys
import textwrap
RECORD = {20: "change_cipher_spec", 21: "alert", 22: "handshake",
23: "application_data"}
GROUPS = {0x001D: "x25519", 0x0017: "secp256r1", 0x0018: "secp384r1",
0x0019: "secp521r1", 0x001E: "x448", 0x0100: "ffdhe2048",
0x0101: "ffdhe3072", 0x11EC: "X25519MLKEM768"}
VERSIONS = {0x0304: "TLS 1.3", 0x0303: "TLS 1.2"}
SUITES = {0x1301: "TLS_AES_128_GCM_SHA256", 0x1302: "TLS_AES_256_GCM_SHA384",
0x1303: "TLS_CHACHA20_POLY1305_SHA256"}
def u16(b: bytes, i: int) -> int:
return int.from_bytes(b[i:i + 2], "big")
def stream(chunks: list, direction: str) -> bytes:
"""All bytes one side sent, in order (c2s = client to server)."""
return b"".join(bytes.fromhex(h) for d, h in chunks if d == direction)
def records(data: bytes):
"""Split a byte stream into (type, header, body) TLS records."""
i = 0
while i + 5 <= len(data):
length = u16(data, i + 3)
yield data[i], data[i:i + 5], data[i + 5:i + 5 + length]
i += 5 + length
def extensions(data: bytes):
"""Yield (type, body) for a list of TLS extensions (without the length prefix)."""
i = 0
while i + 4 <= len(data):
etype, elen = u16(data, i), u16(data, i + 2)
yield etype, data[i + 4:i + 4 + elen]
i += 4 + elen
def names(codes: list, table: dict) -> str:
return ", ".join(table.get(c, hex(c)) for c in codes)
def show(label: str, text: str) -> None:
"""Print one field, wrapped so that long lists stay readable."""
print(textwrap.fill(text, 80, initial_indent=f" {label:<18}: ",
subsequent_indent=" " * 24))
def hello(body: bytes) -> None:
kind, msg = body[0], body[4:] # 1 = ClientHello, 2 = ServerHello
i = 2 + 32 # skip legacy_version and random
i += 1 + msg[i] # skip legacy_session_id
if kind == 1:
n = u16(msg, i)
suites = [u16(msg, i + 2 + k) for k in range(0, n, 2)]
tls13 = [s for s in suites if s in SUITES]
show("cipher_suites", f"{names(tls13, SUITES)} + {len(suites) - len(tls13)}"
" TLS 1.2 suites")
i += 2 + n
i += 1 + msg[i] # skip legacy_compression_methods
else:
show("cipher_suite", names([u16(msg, i)], SUITES))
i += 3
for etype, ext in extensions(msg[i + 2:]):
if etype == 0: # server_name (SNI)
show("server_name (SNI)", ext[5:].decode())
elif etype == 16: # ALPN: list of length-prefixed names
protos, j = [], 2
while j < len(ext):
protos.append(ext[j + 1:j + 1 + ext[j]].decode())
j += 1 + ext[j]
show("alpn", ", ".join(protos))
elif etype == 43: # supported_versions
codes = [u16(ext, 0)] if kind == 2 else \
[u16(ext, 1 + k) for k in range(0, ext[0], 2)]
show("supported_versions", names(codes, VERSIONS))
elif etype == 10: # supported_groups
codes = [u16(ext, 2 + k) for k in range(0, u16(ext, 0), 2)]
show("supported_groups", names(codes, GROUPS))
elif etype == 51: # key_share: group and size of each public value
shares, j = [], 2 if kind == 1 else 0
while j < len(ext):
group, size = u16(ext, j), u16(ext, j + 2)
shares.append(f"{GROUPS.get(group, hex(group))} ({size} bytes)")
j += 4 + size
show("key_share", ", ".join(shares))
def main(path: str) -> None:
chunks = json.load(open(path))
for direction, title in (("c2s", "client -> server"), ("s2c", "server -> client")):
print(title)
for rtype, _, body in records(stream(chunks, direction)):
label = f" {RECORD.get(rtype, rtype):<18} {len(body):>5} bytes"
if rtype == 22 and body[0] in (1, 2):
print(label + (" ClientHello" if body[0] == 1 else " ServerHello"))
hello(body)
else:
print(label + (" (encrypted)" if rtype == 23 else ""))
if __name__ == "__main__":
main(sys.argv[1])python tlsparse.py classic-1.jsonclient -> server
handshake 1533 bytes ClientHello
cipher_suites : TLS_AES_256_GCM_SHA384, TLS_CHACHA20_POLY1305_SHA256,
TLS_AES_128_GCM_SHA256 + 14 TLS 1.2 suites
server_name (SNI) : wire.lab.test
supported_groups : X25519MLKEM768, x25519, secp256r1, x448, secp384r1,
secp521r1, ffdhe2048, ffdhe3072
alpn : h2, http/1.1
supported_versions: TLS 1.3, TLS 1.2
key_share : X25519MLKEM768 (1216 bytes), x25519 (32 bytes)
change_cipher_spec 1 bytes
application_data 69 bytes (encrypted)
application_data 35 bytes (encrypted)
server -> client
handshake 122 bytes ServerHello
cipher_suite : TLS_AES_256_GCM_SHA384
supported_versions: TLS 1.3
key_share : x25519 (32 bytes)
change_cipher_spec 1 bytes
application_data 38 bytes (encrypted)
application_data 467 bytes (encrypted)
application_data 96 bytes (encrypted)
application_data 69 bytes (encrypted)
application_data 266 bytes (encrypted)
application_data 266 bytes (encrypted)
application_data 4862 bytes (encrypted)
application_data 19 bytes (encrypted)Read it as an observer would. The ClientHello shows the name wire.lab.test, the ALPN offer, the versions and two key shares: a 1,216-byte hybrid X25519MLKEM768 share and a 32-byte x25519 share. The server runs OpenSSL 3.0, so it answers with x25519. The one-byte change_cipher_spec only keeps old middleboxes calm (RFC 8446, appendix D.4). Everything after it, including the certificate and the ALPN choice, claims to be application_data. What leaks is the number and size of the records.
05. Step 4: Name the encrypted messages with s_client -trace
openssl s_client holds the session keys, so -trace can print every handshake message after decryption. The filter keeps only the direction and the message name, and stops at the client's Finished (NewSessionTicket messages may follow, depending on timing). < /dev/null makes s_client close at once instead of waiting for input.
openssl s_client -connect 127.0.0.1:8441 -servername wire.lab.test \
-CAfile wire.crt -alpn h2,http/1.1 -trace < /dev/null 2>/dev/null \
| awk '/^Sent Record/ {d = "client:"} /^Received Record/ {d = "server:"}
/^ [A-Za-z]+, Length=/ {sub(/,.*/, ""); print d, $1}' \
| sed '/^client: Finished/q'client: ClientHello
server: ServerHello
server: EncryptedExtensions
server: Certificate
server: CertificateVerify
server: Finished
client: FinishedThis is lesson 1's handshake from a real server. -msg gives a shorter view, used in step 8.
06. Step 5: Decrypt your own session with the key log
Each key log line has a label, the client random (32 bytes from the ClientHello that identify the connection) and a secret. TLS 1.3 has separate handshake and application secrets for each direction.
awk '!/^#/ {print $1, substr($2, 1, 8) "...", substr($3, 1, 8) "..."}' keys.logSERVER_HANDSHAKE_TRAFFIC_SECRET 4318da83... 96010e25...
EXPORTER_SECRET 4318da83... 1d41fe02...
SERVER_TRAFFIC_SECRET_0 4318da83... 40271076...
CLIENT_HANDSHAKE_TRAFFIC_SECRET 4318da83... 522ad3b1...
CLIENT_TRAFFIC_SECRET_0 4318da83... dccab213...decrypt.py does what Wireshark does. It finds the lines for the capture's client random, derives a key and an IV (initialisation vector) from each secret with HKDF-Expand-Label (RFC 8446, section 7.1), builds each record's nonce from the IV and the record number, and opens the record with AES-GCM. Each side switches from its handshake secret to its application secret after its Finished.
"""Decrypt a relay capture with an SSLKEYLOGFILE, the way Wireshark does it."""
import json
import sys
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.ciphers.aead import AESGCM, ChaCha20Poly1305
from cryptography.hazmat.primitives.kdf.hkdf import HKDFExpand
from tlsparse import extensions, records, stream, u16
SUITES = {0x1301: (AESGCM, 16, hashes.SHA256), 0x1302: (AESGCM, 32, hashes.SHA384),
0x1303: (ChaCha20Poly1305, 32, hashes.SHA256)}
MESSAGES = {4: "NewSessionTicket", 8: "EncryptedExtensions", 11: "Certificate",
13: "CertificateRequest", 15: "CertificateVerify", 20: "Finished"}
def expand_label(secret: bytes, label: str, length: int, algo) -> bytes:
"""HKDF-Expand-Label from RFC 8446 section 7.1, with an empty context."""
full = b"tls13 " + label.encode()
info = length.to_bytes(2, "big") + bytes([len(full)]) + full + b"\x00"
return HKDFExpand(algorithm=algo(), length=length, info=info).derive(secret)
class RecordKeys:
"""Traffic key and IV for one direction (RFC 8446 section 7.3)."""
def __init__(self, secret: bytes, suite: int):
aead, key_len, algo = SUITES[suite]
self.aead = aead(expand_label(secret, "key", key_len, algo))
self.iv = expand_label(secret, "iv", 12, algo)
self.seq = 0 # record sequence number, restarts at 0 for every new key
def open(self, header: bytes, body: bytes) -> tuple[int, bytes]:
nonce = bytes(a ^ b for a, b in zip(self.iv, self.seq.to_bytes(12, "big")))
self.seq += 1
plain = self.aead.decrypt(nonce, body, header).rstrip(b"\x00") # drop padding
return plain[-1], plain[:-1] # the real content type is the last byte
def describe(ctype: int, data: bytes) -> str:
if ctype == 21:
return f"alert level={data[0]} description={data[1]}"
if ctype != 22:
return "application data: " + repr(data[:40])
found, i = [], 0
while i < len(data):
size = int.from_bytes(data[i + 1:i + 4], "big")
name = MESSAGES.get(data[i], str(data[i]))
if data[i] == 8: # EncryptedExtensions: show the server's ALPN choice
for etype, ext in extensions(data[i + 6:i + 4 + size]):
if etype == 16:
name += f" (alpn={ext[3:3 + ext[2]].decode()})"
found.append(name)
i += 4 + size
return "handshake: " + ", ".join(found)
def main(capture: str, keylog: str) -> None:
chunks = json.load(open(capture))
client_hello = next(records(stream(chunks, "c2s")))[2]
client_random = client_hello[6:38].hex()
secrets = {}
for line in open(keylog):
parts = line.split()
if len(parts) == 3 and parts[1] == client_random:
secrets[parts[0]] = bytes.fromhex(parts[2])
if not secrets:
sys.exit(f"no lines in {keylog} match the client random of this capture")
server_hello = next(records(stream(chunks, "s2c")))[2]
suite = u16(server_hello, 4 + 34 + 1 + server_hello[4 + 34])
for direction, side in (("s2c", "SERVER"), ("c2s", "CLIENT")):
print("server -> client" if side == "SERVER" else "client -> server")
keys = RecordKeys(secrets[f"{side}_HANDSHAKE_TRAFFIC_SECRET"], suite)
for rtype, header, body in records(stream(chunks, direction)):
if rtype != 23:
continue # hellos and change_cipher_spec are not encrypted
ctype, data = keys.open(header, body)
print(" " + describe(ctype, data))
if ctype == 22 and data[0] == 20: # after Finished: application keys
keys = RecordKeys(secrets[f"{side}_TRAFFIC_SECRET_0"], suite)
if __name__ == "__main__":
main(sys.argv[1], sys.argv[2])python decrypt.py classic-1.json keys.logserver -> client
handshake: EncryptedExtensions (alpn=http/1.1)
handshake: Certificate
handshake: CertificateVerify
handshake: Finished
handshake: NewSessionTicket
handshake: NewSessionTicket
application data: b'HTTP/1.0 200 ok\r\nContent-type: text/html'
alert level=1 description=0
client -> server
handshake: Finished
application data: b'GET / HTTP/1.0\r\n\r\n'Note that the server's ALPN answer sits inside EncryptedExtensions, so an observer sees the offer but never the choice. Now try a key log from a different connection, the usual reason decryption fails.
SSLKEYLOGFILE=other.log python wire_client.py 8441 > /dev/null
python decrypt.py classic-1.json other.log; echo "exit=$?"no lines in other.log match the client random of this capture
exit=1With Wireshark (optional): capture on the loopback interface with the filter tcp port 8442 and run step 2 again. In Edit, Preferences, Protocols, TLS, set "(Pre)-Master-Secret log filename" to the full path of keys.log. The display filter tls.handshake.type == 8 then shows the decrypted EncryptedExtensions. Wireshark follows the same rule as decrypt.py: no line for the client random, no decryption.
07. Step 6: Hybrid post-quantum key exchange
The server below uses the OpenSSL 3.5 inside uv's Python, which supports and prefers X25519MLKEM768. Put a second relay in front of it and run the same client.
"""A minimal TLS server built on the OpenSSL that ships with this Python."""
import socket
import ssl
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
ctx.load_cert_chain("wire.crt", "wire.key")
ctx.set_alpn_protocols(["http/1.1"])
print("server library:", ssl.OPENSSL_VERSION, flush=True)
with socket.create_server(("127.0.0.1", 8446)) as listener:
while True:
raw, _ = listener.accept()
try:
with ctx.wrap_socket(raw, server_side=True) as tls:
tls.recv(4096)
tls.sendall(b"HTTP/1.0 200 ok\r\n\r\nhello\r\n")
except (ssl.SSLError, OSError) as err:
print("handshake failed:", err, flush=True)python pq_server.py > pq_server.log 2>&1 &
PQ_PID=$!
python relay.py 8447 8446 hybrid > relay-hybrid.log 2>&1 &
RELAY2_PID=$!
sleep 1 && cat pq_server.log
python wire_client.py 8447 && sleep 0.5
python tlsparse.py hybrid-1.json | grep -A4 ServerHelloserver library: OpenSSL 3.5.7 9 Jun 2026
TLSv1.3 TLS_AES_256_GCM_SHA384 alpn: http/1.1
HTTP/1.0 200 ok
handshake 1210 bytes ServerHello
cipher_suite : TLS_AES_256_GCM_SHA384
supported_versions: TLS 1.3
key_share : X25519MLKEM768 (1120 bytes)
change_cipher_spec 1 bytesThe client did not change, but now the server chose the hybrid group: its share is 1,120 bytes (an ML-KEM ciphertext plus an X25519 key, as RFC 10024 describes) and the ServerHello grows from 122 to 1,210 bytes. The 1,533-byte ClientHello from step 3 is larger than one typical 1,460-byte TCP segment, and some old middleboxes that expect it in one packet fail. The certificate signature is still classical.
08. Step 7: HTTP/2 over TCP and HTTP/3 over QUIC
HTTP/2 runs over TLS on TCP with ALPN h2. HTTP/3 runs over QUIC on UDP with ALPN h3; QUIC carries the TLS 1.3 handshake messages in its own CRYPTO frames instead of TLS records (RFC 9001). A browser usually learns about HTTP/3 from an Alt-Svc header on an earlier response (RFC 9114, section 3.1) or from a DNS HTTPS record, and stays on TCP if UDP is blocked. Hypercorn serves both on port 8443, one TCP and one UDP socket.
"""A tiny ASGI app that reports which HTTP version carried the request."""
async def app(scope, receive, send):
if scope["type"] != "http":
return # ignore lifespan events
body = f"hello over HTTP/{scope['http_version']}\n".encode()
await send({"type": "http.response.start", "status": 200,
"headers": [(b"content-type", b"text/plain")]})
await send({"type": "http.response.body", "body": body})hypercorn --certfile wire.crt --keyfile wire.key --bind 127.0.0.1:8443 \
--quic-bind 127.0.0.1:8443 app:app > hypercorn.log 2>&1 &
HYPERCORN_PID=$!
for i in 1 2 3 4 5 6 7 8 9 10; do grep -qs QUIC hypercorn.log && break; sleep 1; done
ss -Hltnu 'sport = :8443' | awk '{print $1, $2, $5}'
curl -sv --http2 --cacert wire.crt --resolve wire.lab.test:8443:127.0.0.1 \
https://wire.lab.test:8443/ 2>&1 | grep -E '^\* ALPN|^< (HTTP|alt-svc)|^hello'udp UNCONN 127.0.0.1:8443
tcp LISTEN 127.0.0.1:8443
* ALPN, offering h2
* ALPN, offering http/1.1
* ALPN, server accepted to use h2
< HTTP/2 200
< alt-svc: h3=":8443"; ma=3600
hello over HTTP/2--resolve connects to 127.0.0.1 while still sending SNI and checking the certificate for wire.lab.test. The server accepted h2 and advertised HTTP/3 on UDP port 8443 for 3,600 seconds. Ubuntu 22.04's curl cannot speak HTTP/3, so a small aioquic client does the second half.
"""Fetch https://wire.lab.test:PORT/ over HTTP/3 (QUIC on UDP) with aioquic."""
import asyncio
import sys
from aioquic.asyncio import QuicConnectionProtocol, connect
from aioquic.h3.connection import H3_ALPN, H3Connection
from aioquic.h3.events import DataReceived, HeadersReceived
from aioquic.quic.configuration import QuicConfiguration
from aioquic.quic.events import ProtocolNegotiated
HOST = "wire.lab.test"
class H3Client(QuicConnectionProtocol):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.h3 = H3Connection(self._quic)
self.done = asyncio.get_running_loop().create_future()
def quic_event_received(self, event) -> None:
if isinstance(event, ProtocolNegotiated): # the TLS handshake inside QUIC
print("alpn :", event.alpn_protocol)
for h3_event in self.h3.handle_event(event):
if isinstance(h3_event, HeadersReceived):
for name, value in h3_event.headers:
if name in (b":status", b"server", b"alt-svc"):
print(f"{name.decode():<8}: {value.decode()}")
elif isinstance(h3_event, DataReceived):
if h3_event.data:
print("body :", h3_event.data.decode().strip())
if h3_event.stream_ended:
self.done.set_result(True)
async def get(self, path: str) -> None:
stream_id = self._quic.get_next_available_stream_id()
self.h3.send_headers(stream_id, [
(b":method", b"GET"), (b":scheme", b"https"),
(b":authority", HOST.encode()), (b":path", path.encode())],
end_stream=True)
self.transmit()
await asyncio.wait_for(self.done, timeout=5)
async def main(port: int) -> None:
config = QuicConfiguration(is_client=True, alpn_protocols=H3_ALPN,
server_name=HOST) # SNI and the name to verify
config.load_verify_locations("wire.crt")
async with connect("127.0.0.1", port, configuration=config,
create_protocol=H3Client) as client:
await client.get("/")
if __name__ == "__main__":
asyncio.run(main(int(sys.argv[1])))python h3get.py 8443alpn : h3
:status : 200
server : hypercorn-h3
alt-svc : h3=":8443"; ma=3600
body : hello over HTTP/309. Step 8: Diagnose six broken endpoints
Start two deliberately broken servers. The one on 8444 accepts only TLS 1.3 with the ChaCha20 cipher suite. The one on 8445 hosts two names and picks the certificate from SNI: wire.lab.test gets wire.crt, anything else gets default.crt.
openssl s_server -accept 127.0.0.1:8444 -cert wire.crt -key wire.key -tls1_3 \
-ciphersuites TLS_CHACHA20_POLY1305_SHA256 -www -quiet > broken-a.log 2>&1 &
BROKEN_A_PID=$!
openssl s_server -accept 127.0.0.1:8445 -cert default.crt -key default.key \
-servername wire.lab.test -cert2 wire.crt -key2 wire.key -www -quiet \
> broken-b.log 2>&1 &
BROKEN_B_PID=$!
sleep 1Case A, protocol version mismatch. A client limited to TLS 1.2 meets a server that requires TLS 1.3. The server cannot pick a version, so it sends a fatal protocol_version alert (number 70) instead of a ServerHello.
openssl s_client -connect 127.0.0.1:8444 -servername wire.lab.test -tls1_2 \
< /dev/null 2>&1 | grep -oE 'alert [a-z ]+|SSL alert number [0-9]+'alert protocol version
SSL alert number 70Case B, no common cipher suite. -msg shows the shape: ClientHello out, alert back, no ServerHello. An alert straight after ClientHello points at version, cipher suite or group settings, not certificates, because no certificate has been sent yet.
openssl s_client -connect 127.0.0.1:8444 -servername wire.lab.test \
-ciphersuites TLS_AES_128_GCM_SHA256 -msg < /dev/null 2>&1 | grep -E '^(>>>|<<<)'>>> TLS 1.0, RecordHeader [length 0005]
>>> TLS 1.3, Handshake [length 0132], ClientHello
<<< TLS 1.2, RecordHeader [length 0005]
<<< TLS 1.3, Alert [length 0002], fatal handshake_failureCase C, name mismatch. Ask for a name the certificate does not list. By default s_client reports the verification error and carries on, because it is a diagnostic tool; add -verify_return_error to make it behave like a real client and abort.
openssl s_client -connect 127.0.0.1:8441 -servername wire.lab.test -CAfile wire.crt \
-verify_hostname shop.lab.test < /dev/null 2>&1 | grep -E '^verify error|^Verify'
openssl s_client -connect 127.0.0.1:8441 -servername wire.lab.test -CAfile wire.crt \
-verify_hostname shop.lab.test -verify_return_error < /dev/null 2>&1 \
| grep -oE 'certificate verify failed|^Verify return code: .*'verify error:num=62:hostname mismatch
Verify return code: 62 (hostname mismatch)
certificate verify failed
Verify return code: 62 (hostname mismatch)Case D, no SNI. -noservername sends none, as happens when a tool connects to a bare IP address (RFC 6066 does not allow IP addresses in SNI). The shared server falls back to its default certificate.
openssl s_client -connect 127.0.0.1:8445 -noservername < /dev/null 2>/dev/null \
| grep '^subject='
openssl s_client -connect 127.0.0.1:8445 -servername wire.lab.test < /dev/null \
2>/dev/null | grep '^subject='subject=CN = default.lab.test
subject=CN = wire.lab.testCase E, incomplete chain. A server must send its leaf and every intermediate, because the client holds only the root. Build a small chain (a root, an issuing CA and a leaf for chain.lab.test) and start a server on 8448 that sends only the leaf.
EC="-newkey ec -pkeyopt ec_paramgen_curve:P-256 -nodes"
openssl req -x509 $EC -keyout chain-root.key -out chain-root.crt -days 30 \
-subj "/CN=Wire Lab Root" -addext "basicConstraints=critical,CA:TRUE" 2>/dev/null
openssl req -new $EC -keyout chain-int.key -out chain-int.csr \
-subj "/CN=Wire Lab Issuing CA" 2>/dev/null
printf '%s\n' "basicConstraints=critical,CA:TRUE,pathlen:0" \
"keyUsage=critical,keyCertSign" > chain-int.ext
openssl x509 -req -in chain-int.csr -CA chain-root.crt -CAkey chain-root.key \
-days 30 -extfile chain-int.ext -out chain-int.crt 2>/dev/null
openssl req -new $EC -keyout chain.key -out chain.csr -subj "/CN=chain.lab.test" \
2>/dev/null
printf '%s\n' "subjectAltName=DNS:chain.lab.test" "extendedKeyUsage=serverAuth" \
> chain.ext
openssl x509 -req -in chain.csr -CA chain-int.crt -CAkey chain-int.key -days 30 \
-extfile chain.ext -out chain.crt 2>/dev/null
openssl s_server -accept 127.0.0.1:8448 -cert chain.crt -key chain.key -www -quiet \
> broken-e.log 2>&1 &
BROKEN_E_PID=$!
sleep 1-showcerts prints one s: line per certificate sent. The restarted server adds the intermediate with -cert_chain.
openssl s_client -connect 127.0.0.1:8448 -servername chain.lab.test \
-CAfile chain-root.crt -showcerts < /dev/null 2>&1 \
| grep -E '^verify error|^Verify return|^ *[0-9] s:'
kill $BROKEN_E_PID && sleep 1
openssl s_server -accept 127.0.0.1:8448 -cert chain.crt -key chain.key \
-cert_chain chain-int.crt -www -quiet > broken-e.log 2>&1 &
BROKEN_E_PID=$!
sleep 1
openssl s_client -connect 127.0.0.1:8448 -servername chain.lab.test \
-CAfile chain-root.crt -showcerts < /dev/null 2>&1 \
| grep -E '^verify error|^Verify return|^ *[0-9] s:'verify error:num=20:unable to get local issuer certificate
verify error:num=21:unable to verify the first certificate
0 s:CN = chain.lab.test
Verify return code: 21 (unable to verify the first certificate)
0 s:CN = chain.lab.test
1 s:CN = Wire Lab Issuing CA
Verify return code: 0 (ok)With only the leaf, s_client cannot find the issuer (error 20) or verify the first certificate (error 21); with the intermediate, the same root is enough. Lesson 3 explains why browsers may hide this.
Case F, expired certificate. -attime checks wire.crt (valid for 30 days) as if it were 60 days later. A certificate that was not renewed, or a client with a wrong clock, gives the same error 10.
openssl s_client -connect 127.0.0.1:8441 -servername wire.lab.test -CAfile wire.crt \
-attime "$(date -d '+60 days' +%s)" < /dev/null 2>&1 \
| grep -E '^verify error|^Verify return'verify error:num=10:certificate has expired
Verify return code: 10 (certificate has expired)kill $S_SERVER_PID $RELAY_PID $PQ_PID $RELAY2_PID $HYPERCORN_PID \
$BROKEN_A_PID $BROKEN_B_PID $BROKEN_E_PID
cd ..10. Troubleshooting
11. Check your understanding
12. Apply it
The practice project asks you to decrypt your own session in Wireshark. Do it for a real client: run SSLKEYLOGFILE=$PWD/curl-keys.log curl -s https://example.com -o /dev/null while Wireshark captures, load the log and find the HTTP request. Then add the signature_algorithms extension (type 13) to tlsparse.py, and use s_client with -tls1_2, -tls1_3 and -alpn h2 to record what your own endpoints accept. Delete the key logs afterwards.
13. Review prompt
Without looking back, list the ClientHello fields an observer can read, and name the first encrypted server message and one thing it carries. Explain how a key log decrypts a session without the server's private key, and why a log from another session fails. Then describe how a browser moves from HTTP/2 to HTTP/3, and which s_client symptom points to a version or cipher mismatch rather than a certificate problem.
References
- RFC 8446: The Transport Layer Security (TLS) Protocol Version 1.3
- RFC 7301: TLS Application-Layer Protocol Negotiation Extension
- RFC 6066: TLS Extensions, section 3: Server Name Indication
- RFC 9114: HTTP/3, section 3.1: Discovering an HTTP/3 Endpoint
- RFC 9001: Using TLS to Secure QUIC
- RFC 10024: Post-Quantum Traditional Hybrid Key Agreement Mechanisms for TLS 1.3
- OpenSSL 3.0 manual: openssl-s_client
- Wireshark wiki: TLS (decrypting with a key log file)
- aioquic documentation
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.