TExcelTAD

Protocol State Machines and Protocol Fuzzing

A file parser sees one input. A protocol implementation sees a conversation: messages that are only valid in a certain order, in a certain state. Many of the worst protocol bugs are not in parsing a message at all, but in accepting a perfectly well-formed message at the wrong time: data before authentication, a "change cipher" message before the keys are agreed, a resumption path that skips a check the full handshake performs. This lesson treats a protocol as a state machine, shows how such bugs arise, and finds one with message-level fuzzing and a bounded systematic search.

Protocols as state machines

Every protocol specification implies a state machine: states (connected, keys agreed, authenticated), messages, and the allowed transitions. Implementations rarely write that machine down explicitly. Instead, state is spread over flags and variables (have_key, authed, resuming), and each message handler checks the flags it thinks are relevant. Bugs appear where those checks disagree with the specification:

State-machine bug What happens
skipped step a message is accepted although a required earlier message never came (data before auth, finished without a key exchange)
early message a security-relevant message accepted too early, before the state it depends on is ready
repeated step a handshake message accepted twice, resetting or confusing state
leftover state a failure path does not reset flags, so a retry starts half-authenticated
mixed paths a shortcut for one mode (resumption, renegotiation, fallback) is reachable in another

A historical example: in 2014 OpenSSL accepted the TLS ChangeCipherSpec message too early in the handshake (CVE-2014-0224), which let a man in the middle force weak keys between vulnerable clients and servers. In 2015 a systematic study of TLS libraries ("SMACK", state machine attacks) found several libraries that let peers skip handshake messages. Both were found by thinking about message order, not message content. The fixes tightened the order checks, and OpenSSL later (version 1.1.0) rebuilt its handshake code around an explicit state machine.

A toy protocol with a seeded bug

The toy server speaks HELLO, KEY, AUTH_OK or AUTH_BAD, DATA and CLOSE. Its intended machine is INIT -> HELLO_DONE -> KEYED -> READY, and DATA belongs to READY. The seeded bug: the DATA handler also accepts state KEYED, a shortcut someone added for a session-resumption path. The security property, the oracle, is: DATA is accepted only after a successful AUTH in the same session.

The example searches for violations in two ways. A message-level fuzzer sends random sequences of valid messages in random order (no byte mutation: every message is well formed, only the order is fuzzed). A bounded exhaustive search tries every sequence up to length 4, shortest first. Then it checks the fixed server against all 55,986 sequences up to length 6. It runs in your browser:

python · try it yourself
import itertools, random

class Server:
    """Toy protocol: HELLO -> KEY -> AUTH -> DATA... -> CLOSE. One seeded state-machine bug."""
    def __init__(self, fixed=False):
        self.state, self.authed, self.fixed = "INIT", False, fixed

    def handle(self, msg):
        s = self.state
        if msg == "HELLO" and s == "INIT":
            self.state = "HELLO_DONE"
        elif msg == "KEY" and s == "HELLO_DONE":
            self.state = "KEYED"
        elif msg == "AUTH_OK" and s == "KEYED":
            self.state, self.authed = "READY", True
        elif msg == "AUTH_BAD" and s == "KEYED":
            return "DENIED"                               # stays KEYED, may retry
        elif msg == "DATA" and (s == "READY" or (s == "KEYED" and not self.fixed)):
            return "DATA_ACCEPTED"                        # BUG: KEYED is enough (written for a resume path)
        elif msg == "CLOSE":
            self.state = "CLOSED"
        else:
            return "ALERT"                                # unexpected message: reject it
        return "ok"

MSGS = ["HELLO", "KEY", "AUTH_OK", "AUTH_BAD", "DATA", "CLOSE"]

def violates(seq, fixed=False):
    """Security property: DATA is only accepted after a successful AUTH in this session."""
    srv = Server(fixed)
    for m in seq:
        if srv.handle(m) == "DATA_ACCEPTED" and not srv.authed:
            return True
        if srv.state == "CLOSED":
            return False
    return False

# 1. Message-level fuzzing: random sequences of valid messages, in random order.
rng = random.Random(4)
for n, seq in enumerate(([rng.choice(MSGS) for _ in range(rng.randint(1, 6))] for _ in range(100000)), 1):
    if violates(seq):
        print(f"random sequences: violation after {n} tries: {seq}")
        break

# 2. Systematic: every sequence up to length 4, shortest first (a bounded search).
tried = 0
for length in range(1, 5):
    found = None
    for seq in itertools.product(MSGS, repeat=length):
        tried += 1
        if violates(seq):
            found = seq
            break
    if found:
        print(f"exhaustive search: shortest violation, length {length} ({tried} sequences tried): {list(found)}")
        break

# 3. After the fix, the same bounded search finds nothing.
bad = sum(violates(seq, fixed=True) for L in range(1, 7) for seq in itertools.product(MSGS, repeat=L))
total = sum(len(MSGS) ** L for L in range(1, 7))
print(f"fixed server: {bad} violations in all {total} sequences up to length 6")
random sequences: violation after 53 tries: ['HELLO', 'AUTH_BAD', 'KEY', 'DATA']
exhaustive search: shortest violation, length 3 (53 sequences tried): ['HELLO', 'KEY', 'DATA']
fixed server: 0 violations in all 55986 sequences up to length 6

The random fuzzer stumbles on a violating sequence after 53 tries; the systematic search reports the shortest one: HELLO, KEY, DATA, three messages, no authentication. For a small message alphabet, exhaustive search to a bounded depth is cheap and gives minimal counterexamples for free; for real protocols, with many messages and fields, coverage-guided and grammar-aware fuzzers take over. After the fix, the bounded search finds nothing up to depth 6, which is strong evidence (not proof) for that depth. Proof for all lengths needs a model and a model checker (next lesson).

Notice a second weakness the example reveals: an unexpected message gets an ALERT but the session continues (the random sequence contained AUTH_BAD in the wrong state, and the handshake went on). Strict protocols close the connection on any unexpected message, which removes whole families of state confusion.

Protocol fuzzing in practice

Approach Tools and ideas
generation from a message model boofuzz and similar frameworks: messages described field by field, with lengths and checksums computed
stateful, coverage-guided fuzzers that mutate whole message sequences recorded from real sessions and use server-response codes as a rough state signal (AFLNet-style)
in-process harnesses feed a byte buffer containing several messages to the library's handshake function, with network I/O replaced by memory buffers (how OSS-Fuzz fuzzes TLS libraries)
state-machine learning active automata learning (the L* family, e.g. LearnLib) sends sequences to a black-box implementation, infers its state machine, and a human compares it with the specification
differential run the same sequence against two implementations and compare responses

All of these run against your own instances in a lab: a server you started, on 127.0.0.1 or in a lab network, never a production system or someone else's host.

How state-machine bugs are detected and prevented

Detection: the property-based oracle above (security invariants checked after every message), inferred state machines compared with the specification, and differential testing between implementations. Prevention: an explicit state machine in the code (a table of allowed messages per state, a single place that checks it), fail closed (any message not allowed in the current state ends the session), reset all security state on failure, and test suites with negative sequences (every message in every wrong state).

Pitfalls

  • Fuzzing only message contents. A byte-level fuzzer rarely produces a well-formed message in the wrong order; fuzz the order too.
  • Flags instead of states. authed, have_key and resuming combine into states nobody designed.
  • Lenient error handling. "Ignore unexpected messages" keeps a half-broken session alive.
  • Testing someone else's server. Protocol fuzzing sends unusual traffic; only aim it at instances you own and run.

Practice

1. Write the allowed-message table for the fixed server.

INIT: {HELLO, CLOSE}, HELLO_DONE: {KEY, CLOSE}, KEYED: {AUTH_OK, AUTH_BAD, CLOSE}, READY: {DATA, CLOSE}, CLOSED: {}. Anything else: send an alert and close.

2. Make the server fail closed (any ALERT closes the session) and re-run. How does the random fuzzer's result change?

The random sequence HELLO, AUTH_BAD, KEY, DATA now ends at the AUTH_BAD alert, so it no longer violates the property. The buggy DATA shortcut is still reachable by the clean sequence HELLO, KEY, DATA, so the systematic search still finds it: failing closed reduces confusion but does not fix the shortcut.

3. Why is the shortest counterexample valuable in a report?

It shows the root cause with nothing else (no retries, no noise), becomes a minimal regression test, and lets the maintainer see immediately which transition is wrong: KEYED --DATA--> accepted.

Test yourself

What is a state-machine bug?

  1. A crash in a message parser
  2. Accepting a valid message in a state where the protocol does not allow it
  3. A slow handshake
  4. A wrong checksum

What was the oracle in the example?

  1. A crash
  2. The property: DATA is accepted only after a successful AUTH in the same session
  3. Code coverage
  4. A timeout

What does 'fail closed' mean for a protocol implementation?

  1. Close the port
  2. Any message not allowed in the current state ends the session
  3. Encrypt everything
  4. Retry on errors

What does a bounded search up to length 6 without violations prove?

  1. The protocol is secure
  2. No violation exists in sequences up to length 6; longer ones need a model checker or a proof
  3. Nothing
  4. The fuzzer is broken