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
  1. server_context returns a server-side context that presents the certificate in certfile with the private key in keyfile (both PEM). Minimum version TLS 1.2.
  2. client_context returns a client-side context that:
  3. trusts only the CA certificate in cafile, not the operating system's trust store,
  4. requires a valid certificate from the server and checks that it was issued for the name being connected to,
  5. accepts nothing older than TLS 1.2.
  6. send is problem 16 over TLS. Connect to (host, port), do the TLS handshake, send payload as one block, return the payload of one reply block.
  7. The name checked against the server certificate is server_hostname, or host when it is None. An IP address works if the certificate lists that address.
  8. A certificate problem raises ssl.SSLCertVerificationError from the handshake. Let it propagate.
  9. TimeoutError when the server stays silent for timeout seconds.
  10. ConnectionError when the server closes before a complete reply arrived.
  11. 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:

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
  1. server_context: as in problem 37 (presents certfile/keyfile, TLS 1.2 minimum), and requires a client certificate signed by the CA in client_cafile.
  2. client_context: as in problem 37 (trusts only cafile, requires and checks the server certificate and hostname, TLS 1.2 minimum), and presents the client certificate in certfile/keyfile.
  3. serve_once: accept one connection from the already-listening listener and do the TLS handshake. Read the CN from the client certificate. If it is in allowed: read one block, reply with handler(payload, common_name) as one block, close the connection, return the CN.
  4. 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 return None. No exception escapes and handler is not called.
  5. Leave listener open; the next serve_once uses 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:

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

  1. Install Wireshark (brew install --cask wireshark on macOS). Live capture needs permission to read the capture devices; without it, use the tcpdump route below.
  2. Start a capture on the loopback interface (lo0 on macOS, lo on Linux, "Adapter for loopback traffic capture" on Windows) with the capture filter tcp port 2575.
  3. 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.

  1. How many packets remain, and how many HL7 messages do they carry? Why are those two numbers different?
  2. 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.
  3. 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
  1. Nine packets, ten messages: five requests and five ACKs. One packet carries two messages (step 3 glued ADT^A08 and ORM^O01 into one write), and its Info column reads ADT (A08), ORM (O01).
  2. 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 10 is MSH-10) because MSH-1 is the separator itself. Do not quote Wireshark's field numbers in a ticket.
  3. 0b first, 1c 0d last. The byte before 1c is 0d: 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

  1. Find the ORU^R01. Step 2 sent it in three writes. How does Wireshark show that, and which packet carries the "message"?
  2. Find the packet with two messages in it. How many ACK packets answer it?
  3. Filter with tcp.stream eq 1. What was sent on the second connection, why does hl7 not match it, and how did that connection end?
Answers
  1. 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.
  2. Two ACK packets, one per message, each echoing its own control ID. One TCP packet is not one message in either direction (problem 02).
  3. 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

  1. Which message was refused, and why? Find it without scrolling.
  2. Show only the ADT messages. Then only what belongs to control ID MSG00002.
Answers
  1. 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, an ADT^A01 whose PID-3 is empty.
  2. 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
  1. Filter on hl7. What is missing?
  2. Fix it with Analyze > Decode As: TCP port 6661, HL7.
Answers
  1. Eight packets instead of nine. Off the registered port Wireshark has to guess, and its guess starts one packet late: the very first ADT^A01 is left as plain TCP.
  2. 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.

  1. What does Wireshark show now, with and without the hl7 filter?
  2. Use Decode As to tell it TCP port 2575 is TLS. Find the server name the client asked for.
  3. 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 the hl7 filter work now?
Answers
  1. 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.
  2. The packets are now dissected as TLS. In the Client Hello, the server_name extension says localhost. That name is what the client checks the certificate against (problem 37). Message types, control IDs and patient data are not visible.
  3. The followed stream shows the MLLP conversation in clear text. The hl7 filter 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

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.