Week 5 practice
Privacy + AI · 3 exercises
The full text of every practice problem that fits week 5, grouped by lecture section. Set up the two sets first: the commands are on the practice problems page. Each reference solution is collapsed under its exercise; run the tests before you open it.
MLLP on the wire
Lecture: MLLP on the wire.
mellp 37: Lock It Down
Medium · tls · certificates · ssl
MLLP has no security of its own. Anyone on the path between two systems can read every name, birth date and result in the stream. Inside one data center that may be accepted; between organizations the link runs through a VPN or over TLS. With TLS the work is mostly configuration, and most of the ways to get it wrong still connect fine, which is why this problem tests the refusals as much as the round trip.
def server_context(certfile: str, keyfile: str) -> ssl.SSLContext
def client_context(cafile: str) -> ssl.SSLContext
def send(
host: str,
port: int,
payload: bytes,
context: ssl.SSLContext,
*,
server_hostname: str | None = None,
timeout: float = 5.0,
) -> bytes
server_contextreturns a server-side context that presents the certificate incertfilewith the private key inkeyfile(both PEM). Minimum version TLS 1.2.client_contextreturns a client-side context that:- trusts only the CA certificate in
cafile, not the operating system's trust store, - requires a valid certificate from the server and checks that it was issued for the name being connected to,
- accepts nothing older than TLS 1.2.
sendis problem 16 over TLS. Connect to(host, port), do the TLS handshake, sendpayloadas one block, return the payload of one reply block.- The name checked against the server certificate is
server_hostname, orhostwhen it isNone. An IP address works if the certificate lists that address. - A certificate problem raises
ssl.SSLCertVerificationErrorfrom the handshake. Let it propagate. TimeoutErrorwhen the server stays silent fortimeoutseconds.ConnectionErrorwhen the server closes before a complete reply arrived.- The reply may arrive one byte at a time.
Example 1:
ca = CertificateAuthority(tmp) # harness/certs.py
cert, key = ca.issue("localhost", server=True) # valid for localhost and 127.0.0.1
server = ScriptedServer(tls=server_context(cert, key))
send("127.0.0.1", server.port, adt, client_context(ca.certfile), server_hostname="localhost")
-> b"MSH|^~\\&|LAB|HOSP|EPIC|HOSP|...\rMSA|AA|MSG00001\r"
send("127.0.0.1", server.port, adt, client_context(ca.certfile))
-> the same ACK: 127.0.0.1 is checked, and the certificate lists it
Example 2:
send("127.0.0.1", server.port, adt, client_context(ca.certfile), server_hostname="fhir.example")
-> ssl.SSLCertVerificationError: the certificate is not for fhir.example
send("127.0.0.1", server.port, adt, client_context(other_ca.certfile), server_hostname="localhost")
-> ssl.SSLCertVerificationError: issued by a CA this client does not trust
Example 3:
expired_cert, expired_key = ca.issue("expired", server=True, expired=True)
server = ScriptedServer(tls=server_context(expired_cert, expired_key))
send("127.0.0.1", server.port, adt, client_context(ca.certfile), server_hostname="localhost")
-> ssl.SSLCertVerificationError: certificate has expired
Constraints:
- Certificates and keys are PEM files made by
harness.certs.CertificateAuthority. The CA file holds exactly one certificate. - Tests run the server on 127.0.0.1 with
harness.net.ScriptedServer(tls=...), which answers each block with an ACK. - A plaintext client that connects to your server must not get an ACK. The TLS layer takes care of that once
server_contextis right. - Tests must also pass on Python 3.13+, where
ssl.create_default_context()turns on strict X.509 checks. The test certificates satisfy them.
Follow-up: your partner's server certificate expires at 02:00 on a Sunday. How would you find out three weeks before, rather than from the first refused handshake?
Hint 1
ssl.create_default_context(cafile=cafile) builds a client context that requires a certificate, checks the hostname, and loads only cafile (the system store is loaded only when no CA is given). For the server, ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) then load_cert_chain(certfile, keyfile). On Python 3.12 a new context already reports minimum_version == ssl.TLSVersion.TLSv1_2; set it anyway so the requirement is visible in the code.
Hint 2
context.wrap_socket(sock, server_hostname=name) turns a connected socket into a TLS socket and runs the handshake. After that, sendall and recv work as before, and your problem 16 loop applies unchanged.
Write it in problems/37-lock-it-down/solution.py, then run:
uv run pytest problems/37-*
Reference solution
import socket
import ssl
SB = b"\x0b"
EB = b"\x1c\x0d"
def server_context(certfile: str, keyfile: str) -> ssl.SSLContext:
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
context.minimum_version = ssl.TLSVersion.TLSv1_2
context.load_cert_chain(certfile, keyfile)
return context
def client_context(cafile: str) -> ssl.SSLContext:
# With cafile given, the system trust store is not loaded. Hostname checking and
# CERT_REQUIRED are the defaults of a client context.
context = ssl.create_default_context(cafile=cafile)
context.minimum_version = ssl.TLSVersion.TLSv1_2
return context
def send(
host: str,
port: int,
payload: bytes,
context: ssl.SSLContext,
*,
server_hostname: str | None = None,
timeout: float = 5.0,
) -> bytes:
with socket.create_connection((host, port), timeout=timeout) as plain:
with context.wrap_socket(plain, server_hostname=server_hostname or host) as sock:
sock.sendall(SB + payload + EB)
buffer = b""
while EB not in buffer:
chunk = sock.recv(65536)
if not chunk:
raise ConnectionError("server closed before a complete reply arrived")
buffer += chunk
return buffer[buffer.index(SB) + 1 : buffer.index(EB)]
mellp 38: Show Me Your Papers
Medium · mutual tls · client certificates · ssl
In problem 37 the client checks who the server is, but the server will talk to anyone who can reach its port. With mutual TLS the client presents a certificate too, issued by a CA the server trusts, and the server can decide per partner: the lab system may send results, a pharmacy system on the same network may not. The partner's identity is in its certificate, here the common name (CN).
def server_context(certfile: str, keyfile: str, client_cafile: str) -> ssl.SSLContext
def client_context(cafile: str, certfile: str, keyfile: str) -> ssl.SSLContext
def serve_once(
listener: socket.socket,
context: ssl.SSLContext,
handler: Callable[[bytes, str], bytes],
allowed: set[str],
) -> str | None
server_context: as in problem 37 (presentscertfile/keyfile, TLS 1.2 minimum), and requires a client certificate signed by the CA inclient_cafile.client_context: as in problem 37 (trusts onlycafile, requires and checks the server certificate and hostname, TLS 1.2 minimum), and presents the client certificate incertfile/keyfile.serve_once: accept one connection from the already-listeninglistenerand do the TLS handshake. Read the CN from the client certificate. If it is inallowed: read one block, reply withhandler(payload, common_name)as one block, close the connection, return the CN.- If the handshake fails (no client certificate, one from an unknown CA, an expired one, a peer that is not speaking TLS) or the CN is not in
allowed: close the connection without replying and returnNone. No exception escapes andhandleris not called. - Leave
listeneropen; the nextserve_onceuses it.
Example 1:
ca = CertificateAuthority(tmp)
server_cert = ca.issue("localhost", server=True)
lab = ca.issue("lab-system") # a client certificate, CN lab-system
serve_once(listener, server_context(*server_cert, ca.certfile), handler, {"lab-system"})
client: Client(port, tls=client_context(ca.certfile, *lab)).request(adt) -> the AA
handler was called with (adt, "lab-system")
-> "lab-system"
Example 2:
pharmacy = ca.issue("pharmacy")
serve_once(listener, server_context(*server_cert, ca.certfile), handler, {"lab-system"})
client: Client(port, tls=client_context(ca.certfile, *pharmacy)).request(adt)
-> ConnectionError: the connection closed with no reply
-> None
Explanation: the certificate is valid, but pharmacy is not on the list.
Example 3:
serve_once(listener, server_context(*server_cert, ca.certfile), handler, {"lab-system"})
client: Client(port, tls=ssl.create_default_context(cafile=ca.certfile)).request(adt)
-> ssl.SSLError: [SSL: TLSV13_ALERT_CERTIFICATE_REQUIRED] tlsv13 alert certificate required
-> None
Explanation: a client without a certificate. Note that the client's handshake succeeded and
the error only appeared when it read.
Constraints:
- Certificates are made by
harness.certs.CertificateAuthority; a client certificate's subject holds just the CN. - Under TLS 1.3 the client finishes its handshake before the server has checked the client certificate. A refused client may therefore only notice on its first read, as an
ssl.SSLErrorcarrying the server's alert, aConnectionError, or end of stream. The tests accept any of these on the client side and check your return value and the handler. - Every client in the tests connects and sends promptly, so
serve_oncedoes not need its own timeout. - Tests must also pass on Python 3.13+, where
ssl.create_default_context()turns on strict X.509 checks. The test certificates satisfy them.
Follow-up: the lab vendor renews its certificate and the new one has CN lab-system-2027. What would you key the allow list on instead, and how do you rotate without an outage?
Hint 1
On the server context, verify_mode = ssl.CERT_REQUIRED and load_verify_locations(client_cafile). On the client context, load_cert_chain(certfile, keyfile). After the handshake, tls.getpeercert()["subject"] is a tuple of RDNs, each a tuple of (key, value) pairs: ((("commonName", "lab-system"),),).
Hint 2
context.wrap_socket(conn, server_side=True) raises ssl.SSLError when the handshake fails, and some other OSError when the peer vanishes during it. ssl.SSLError is itself a subclass of OSError, and so is every failure you can meet while reading afterwards.
Write it in problems/38-show-me-your-papers/solution.py, then run:
uv run pytest problems/38-*
Reference solution
import socket
import ssl
from collections.abc import Callable
SB = b"\x0b"
EB = b"\x1c\x0d"
def server_context(certfile: str, keyfile: str, client_cafile: str) -> ssl.SSLContext:
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
context.minimum_version = ssl.TLSVersion.TLSv1_2
context.load_cert_chain(certfile, keyfile)
context.verify_mode = ssl.CERT_REQUIRED
context.load_verify_locations(client_cafile)
return context
def client_context(cafile: str, certfile: str, keyfile: str) -> ssl.SSLContext:
context = ssl.create_default_context(cafile=cafile)
context.minimum_version = ssl.TLSVersion.TLSv1_2
context.load_cert_chain(certfile, keyfile)
return context
def common_name(certificate: dict) -> str | None:
"""`getpeercert()` gives the subject as a tuple of RDNs, each a tuple of (key, value) pairs."""
return dict(pair for rdn in certificate["subject"] for pair in rdn).get("commonName")
def read_block(sock: ssl.SSLSocket) -> bytes:
buffer = b""
while EB not in buffer:
chunk = sock.recv(65536)
if not chunk:
raise ConnectionError("peer closed before a complete block arrived")
buffer += chunk
return buffer[buffer.index(SB) + 1 : buffer.index(EB)]
def serve_once(
listener: socket.socket,
context: ssl.SSLContext,
handler: Callable[[bytes, str], bytes],
allowed: set[str],
) -> str | None:
conn, _ = listener.accept()
try:
# wrap_socket takes over conn's file descriptor and closes it if the handshake fails.
with context.wrap_socket(conn, server_side=True) as tls:
name = common_name(tls.getpeercert())
if name not in allowed:
return None
reply = handler(read_block(tls), name)
tls.sendall(SB + reply + EB)
return name
except OSError: # ssl.SSLError and connection failures are all OSError
return None
mellp Lab A: Read MLLP on the wire
Lab · wireshark · 30 to 45 minutes
When an interface misbehaves, both vendors say their side is fine. A packet capture settles it: it shows the bytes that were really sent, when, and who closed the connection. This lab teaches you to read one.
Everything below was checked against Wireshark/TShark 4.4.
Setup
- Install Wireshark (
brew install --cask wiresharkon macOS). Live capture needs permission to read the capture devices; without it, use the tcpdump route below. - Start a capture on the loopback interface (
lo0on macOS,loon Linux, "Adapter for loopback traffic capture" on Windows) with the capture filtertcp port 2575. - In a terminal, play the scripted conversation:
uv run python labs/wireshark/traffic.py
It prints six numbered steps. Stop the capture when it says done.
No capture rights? Use tcpdump and open the file in Wireshark afterwards:
sudo tcpdump -i lo0 -w mllp.pcap tcp port 2575 # Linux: -i lo
Every question has a TShark one-liner too, in case you prefer the terminal: tshark -r mllp.pcap -Y hl7.
Part 1: find the messages
Type hl7 in the display filter bar.
- How many packets remain, and how many HL7 messages do they carry? Why are those two numbers different?
- Click the first one. In the packet details, expand "Health Level Seven". Which line holds the patient identifier? Compare the field number Wireshark shows with the number you would write in a spec.
- In the packet bytes pane, find the three MLLP framing bytes of that message. Which byte comes right before
0x1C, and what is it?
Answers
- Nine packets, ten messages: five requests and five ACKs. One packet carries two messages (step 3 glued
ADT^A08andORM^O01into one write), and its Info column readsADT (A08), ORM (O01). field 4: 12345^^^HOSP^MR. Wireshark counts the segment name as field 1, so PID-3 is shown as "field 4" and PID-5 as "field 6". In MSH the numbers happen to match the standard (field 10is MSH-10) because MSH-1 is the separator itself. Do not quote Wireshark's field numbers in a ticket.0bfirst,1c 0dlast. The byte before1cis0d: the carriage return that ends the last segment. It belongs to the HL7 message, not to the framing (problem 01).
Part 2: framing on the wire
- Find the
ORU^R01. Step 2 sent it in three writes. How does Wireshark show that, and which packet carries the "message"? - Find the packet with two messages in it. How many ACK packets answer it?
- Filter with
tcp.stream eq 1. What was sent on the second connection, why doeshl7not match it, and how did that connection end?
Answers
- The ORU appears on the packet that delivered its last piece, with a "3 Reassembled TCP Segments (422 bytes)" entry in the details. The two earlier pieces are plain TCP packets. This is problem 03 done by Wireshark. Filter:
tcp.reassembled.length. - Two ACK packets, one per message, each echoing its own control ID. One TCP packet is not one message in either direction (problem 02).
- One data packet of 121 bytes: the first half of
MSG00006. There is no end marker, so the dissector never sees a complete block and leaves it as TCP. The connection ends with[RST, ACK]from the sender instead of the usual FIN exchange. Filter:tcp.flags.reset == 1. This is problem 05 as the receiver's network sees it.
Part 3: find the one that failed
- Which message was refused, and why? Find it without scrolling.
- Show only the
ADTmessages. Then only what belongs to control IDMSG00002.
Answers
frame contains "MSA|AE"finds the ACK:MSA|AE|MSG00005|PID-3 is required. The request is the packet just before it on the same stream, anADT^A01whose PID-3 is empty.hl7.message.type == "ADT"(the glued packet matches because one of its two messages is an ADT).hl7.field contains "MSG00002"matches both the ORU and its ACK, since the ACK echoes the control ID in MSA-2.
Two preferences worth knowing (Preferences > Protocols > HL7): one adds the raw message text to the tree, which makes hl7.raw.segment contains "MSA|AE" work; the other adds the MLLP start and end bytes to the tree. Both are off by default.
Part 4: a port Wireshark does not know
Real interfaces rarely use 2575. Capture again with the capture filter tcp port 6661 and run:
uv run python labs/wireshark/traffic.py --port 6661
- Filter on
hl7. What is missing? - Fix it with Analyze > Decode As: TCP port 6661, HL7.
Answers
- Eight packets instead of nine. Off the registered port Wireshark has to guess, and its guess starts one packet late: the very first
ADT^A01is left as plain TCP. - After Decode As, all nine are back. TShark:
tshark -r mllp6661.pcap -d tcp.port==6661,hl7 -Y hl7.
Part 5: TLS
Capture on tcp port 2575 once more and run the same conversation encrypted:
uv run python labs/wireshark/traffic.py --tls
The script writes the TLS session keys to sslkeys.log (Python's ssl.SSLContext.keylog_filename). Keep that file out of version control; it decrypts the capture.
- What does Wireshark show now, with and without the
hl7filter? - Use Decode As to tell it TCP port 2575 is TLS. Find the server name the client asked for.
- Point Preferences > Protocols > TLS > "(Pre)-Master-Secret log filename" at
sslkeys.log, then right-click a packet and choose Follow > TLS Stream. What do you see? Does thehl7filter work now?
Answers
- Nothing matches
hl7, and every packet is shown as plain TCP. Wireshark assumed HL7 on 2575, found no block markers in the ciphertext, and gave up. - The packets are now dissected as TLS. In the Client Hello, the
server_nameextension sayslocalhost. That name is what the client checks the certificate against (problem 37). Message types, control IDs and patient data are not visible. - The followed stream shows the MLLP conversation in clear text. The
hl7filter still matches nothing: Wireshark decrypts the stream but does not hand TLS payload to the HL7 dissector. For encrypted interfaces you read the followed stream, or you capture on the far side of the TLS terminator.
TShark: tshark -r mllp-tls.pcap -d tcp.port==2575,tls -o tls.keylog_file:sslkeys.log -q -z follow,tls,ascii,0
Take it further
- Capture your own problem 16 client against your problem 20 server. Find the three-way handshake, the request, the ACK and the FIN exchange. Then capture problem 17's session and count the handshakes.
- Capture problem 18 retrying against a server that never answers. Measure your real timeout from the packet timestamps.
- In a real capture, the first three questions are always the same: did the message leave, did an ACK come back, and who closed the connection.
The lab files are in labs/wireshark/.
mellp statements and solutions are copied from mellp at commit 5d8e459.
Course content © 2026 HeyItWorked. All rights reserved.
Site design adapted from The Missing Semester of Your CS Education under CC BY-NC-SA 4.0. See copyright and license.