Algorithm Search⌘K

Algorithmadvanced

Protocol state fuzzing

Also called state machine learning of protocol implementations.

Learns the state machine of a protocol implementation with active automata learning and checks it for unexpected states and transitions.

Time
O(k n (k + n m) (n + m)) worst
Space
O(k n (k + n m) (n + m)) extra
Where
k = the number of abstract input messages; m = the length of the longest counterexample; n = the number of states of the implementation
Properties
deterministicofflinenot randomizediterative
Origin
Joeri de Ruiter, Erik Poll, 2015

Protocol state fuzzing learns the state machine of a protocol implementation from the outside and then compares it with the state machine that the specification describes. The implementation is treated as a black box that accepts a reset and a sequence of abstract messages, such as "Hello" or "Finished", and returns the sequence of its responses. An active learning algorithm, L* adapted to Mealy machines, chooses the sequences, builds a hypothesis, and refines it with counterexamples until an equivalence check accepts it. Every place where the learned model answers differently from the specification is a candidate bug for a human to inspect. De Ruiter and Poll (USENIX Security 2015) introduced the name and the method for TLS. Here the system is always a simulated machine, and the costs are in the word-RAM model.

In plain words

A protocol is a conversation with rules about order. A server must get a greeting before a key, and a key before the "finished" message. Bugs often hide in the wrong orders: a server that accepts "finished" without a key may skip a security step.

Protocol state fuzzing does not send random bytes. It sends short sequences of well-formed messages, resets the server, and tries again. From the answers it draws a map of the states of the server and the moves between them. It keeps asking until a check finds no sequence on which the map and the server disagree.

Then a person compares this map with the map of the standard. An extra arrow, such as "finished" accepted too early, points to a bug.

The problem

The input is an alphabet AA of kk abstract input messages, an output query OQ that resets the system, sends a word ww over AA and returns the word of responses, an equivalence oracle EQ, and a specification machine PP over AA. The system is assumed to behave as a deterministic Mealy machine MM with nn states over these abstract messages. The output is a Mealy machine HH that is equivalent to MM when EQ is exact, and the list of the shortest words on which HH and PP differ.

The abstraction is part of the problem. A test harness maps each abstract message to a concrete message and each concrete response to an abstract output, and it keeps the cryptographic state that the concrete messages need. The method learns the behaviour of the harness and the system together, so a bug in the harness looks like a bug in the system.

The algorithm

SS is a list of access words, one for each state found so far, and EE is a list of distinguishing words. The row of a word uu lists, for each e∈Ee \in E, the last ∣e∣|e| outputs of OQ(ue)(u e): the response of the state after uu to ee. Two words with different rows lead to different states. The counterexample rule of line L9, which adds every suffix of the counterexample to EE, is the variant of Maler and Pnueli; it keeps the rows of SS pairwise different, so the table needs no consistency check.

  1. PROTOCOL-STATE-FUZZ(A, OQ, EQ, P)
  2. 1S ← [ε], E ← [a for each a in A]
  3. 2row(u) = [the last |e| letters of OQ(u e) for each e in E]
  4. 3repeat
  5. 4while some u a, with u in S and a in A, has a row that no word of S has do
  6. 5append u a to S
  7. 6H ← states S, start ε, δ(u, a) = the word of S with the row of u a, λ(u, a) = the last letter of OQ(u a)
  8. 7c ← EQ(H) ▷ none, or a word on which H and the system differ
  9. 8if c = none then leave the loop
  10. 9append every suffix of c that is not in E to E
  11. 10return H and DIFF(H, P)
  12. DIFF(H, P)
  13. 11search breadth-first over the pairs of states of H and P, from the two start states, along letters with equal outputs
  14. 12for each pair reached first by w and each letter a with different outputs, report w a and the two output words

In practice EQ is not exact. Without the true machine, the learner can only test: try many random words, or all words up to a length, or a conformance test suite built for a bound on the number of states. A test that finds a difference gives a counterexample. A test suite that finds none gives no proof, so the model can miss states that only long or rare sequences reach.

Example

The alphabet has four messages: Hello, Key, Finished and Data. The specification has five states: start, after Hello, after Key, open and closed. In each state the expected message gives ServerHello, Empty, Fin or Data, and moves on; open stays open on Data. Any other message gives Alert and moves to closed, which answers Closed to everything.

The implementation has a planted bug. After Hello it also accepts Finished, answers Fin, and goes to a state that answers one Data message and then sends Alert. It has seven states. The tests play the equivalence oracle with the true machine, so the oracle is exact here.

round rows of SS hypothesis counterexample
1 6 Hello, Finished is taken as the word of the open state, because it answers like open to every single message Hello, Key, Finished, Data, Data: the system answers Data twice, the hypothesis Data and then Alert
2 7 the suffix Data, Data separates the real open state from the state of the bug none

The learner used 204 different output queries. DIFF reports one word, Hello, Finished, with the outputs ServerHello, Fin from the model and ServerHello, Alert from the specification. That is the planted bug.

The tests also show the weak point. A random oracle with 200 words of length at most 6 and generator seed 5 accepts the six-state hypothesis, because it never tries Hello, Key, Finished, Data, Data. DIFF then also reports that the correct handshake followed by two Data messages fails, which is false. With 5,000 random words of length at most 8 the oracle finds the counterexample, and the model is correct.

Correctness

The rows depend only on the state of the system after the word, so the words of SS reach pairwise different states, and SS never has more than nn words. After the loop of lines L4 and L5, the table is closed and the hypothesis of line L6 is well defined. By induction on the length of a column, the hypothesis gives the same outputs as the system on every entry of the table; this uses that EE is closed under suffixes. So after the suffixes of a counterexample cc are added, the hypothesis would agree with the system on cc if no state were added; hence every counterexample adds at least one state, and there are at most nn rounds. When EQ is exact, the result is equivalent to the system and has the least number of states of any equivalent machine, because two words of SS are separated by a column. DIFF reports nothing if and only if the model and the specification are equivalent, and its first report is a shortest separating word. The full proof is in the proof file. The tests check the learned model against the true machine by partition refinement on 600 random machines, and DIFF against brute force on 500 random pairs.

Proof: Correctness of protocol state fuzzingfull

We prove the claims of the Correctness section for PROTOCOL-STATE-FUZZ (lines L1 to L12). The system under learning is a deterministic Mealy machine MM with input alphabet AA of kk letters, initial state q0q_0, and nn states reachable from q0q_0. For a word ww, M(w)M(w) is the word of outputs after a reset, and q(w)q(w) is the state that MM reaches. For uu and a nonempty ee, T(u)(e)T(u)(e) is the last ∣e∣|e| letters of M(ue)M(u e), which is the output of MM on ee from the state q(u)q(u). The row of uu is T(u)T(u) restricted to the columns EE. The table is the pair (S,E)(S, E) of lines L1 to L9.

Claim 1 (rows depend only on the state). If q(u)=q(v)q(u) = q(v), then uu and vv have the same row for every EE. So two words of SS with different rows reach different states of MM.

Proof. T(u)(e)T(u)(e) is the output of MM on ee from q(u)q(u), which depends only on q(u)q(u). □\square

Claim 2 (invariants). At every point, the rows of the words of SS are pairwise different, ∣S∣≤n|S| \le n, ε∈S\varepsilon \in S, and EE is suffix-closed: every nonempty suffix of a word of EE is in EE.

Proof. Line L1 starts with S={ε}S = \{\varepsilon\} and EE the one-letter words, which is suffix-closed. Line L5 adds a word whose row differs from all rows of SS. Line L9 adds columns, so rows that differ stay different, and it adds all suffixes of cc, so EE stays suffix-closed. By Claim 1, words of SS reach pairwise different states, so ∣S∣≤n|S| \le n. □\square

So the loop of lines L4 and L5 ends after at most n−1n - 1 additions in total. When it ends, the table is closed: the row of every uau a with u∈Su \in S and a∈Aa \in A is the row of exactly one word of SS. Line L6 then defines the hypothesis HH with the states SS, initial state ε\varepsilon, δ(u,a)\delta(u, a) the word of SS with the row of uau a, and λ(u,a)=T(u)(a)\lambda(u, a) = T(u)(a). Write Hu(e)H_u(e) for the outputs of HH on ee from the state uu.

Claim 3 (the hypothesis agrees with the table). For every u∈Su \in S and every e∈Ee \in E, Hu(e)=T(u)(e)H_u(e) = T(u)(e).

Proof. By induction on ∣e∣|e|. If e=ae = a, then Hu(a)=λ(u,a)=T(u)(a)H_u(a) = \lambda(u, a) = T(u)(a). If e=ae′e = a e' with e′e' nonempty, then e′∈Ee' \in E because EE is suffix-closed. Let v=δ(u,a)v = \delta(u, a), so vv and uau a have the same row. Then Hu(e)=λ(u,a)⋅Hv(e′)H_u(e) = \lambda(u, a) \cdot H_v(e'), and by induction Hv(e′)=T(v)(e′)=T(ua)(e′)H_v(e') = T(v)(e') = T(u a)(e'). The output of MM on ae′a e' from q(u)q(u) is its output on aa followed by its output on e′e' from q(ua)q(u a), which is T(u)(a)⋅T(ua)(e′)=T(u)(e)T(u)(a) \cdot T(u a)(e') = T(u)(e). □\square

Claim 4 (each counterexample adds a state). If line L7 returns a word cc with H(c)≠M(c)H(c) \ne M(c), then the next hypothesis has more states than HH.

Proof. Suppose not. After line L9 the old words of SS still have pairwise different rows, so if the next run of lines L4 and L5 adds nothing, the table with the new columns E′E' is closed with the same SS. Let H′H' be the new hypothesis. For u∈Su \in S and a∈Aa \in A, let vv be the word of SS with the new row of uau a. The old row is the restriction of the new row to EE, so vv also has the old row of uau a, and v=δ(u,a)v = \delta(u, a), because the old rows of SS are pairwise different. The outputs λ(u,a)=T(u)(a)\lambda(u, a) = T(u)(a) do not change. So H′=HH' = H. Now c∈E′c \in E', because cc is a suffix of itself, and ε∈S\varepsilon \in S. By Claim 3 for H′H', H′(c)=Hε′(c)=T(ε)(c)=M(c)H'(c) = H'_\varepsilon(c) = T(\varepsilon)(c) = M(c). This contradicts H(c)≠M(c)H(c) \ne M(c). □\square

Claim 5 (termination and size). The learner asks at most nn equivalence queries and returns a hypothesis with at most nn states.

Proof. By Claim 2 every hypothesis has at most nn states, and by Claim 4 each counterexample adds at least one, starting from at least one. □\square

Claim 6 (exact and minimal). If the oracle returns none only for machines equivalent to MM, the result HH is equivalent to MM, and no machine equivalent to MM has fewer states.

Proof. The first part is the condition of line L8. For the second part, let NN be equivalent to MM, and let u≠vu \ne v be words of SS. Their rows differ, so there is e∈Ee \in E with T(u)(e)≠T(v)(e)T(u)(e) \ne T(v)(e). Then NN gives different outputs on ee after uu and after vv, so it reaches different states after them. So NN has at least ∣S∣|S| states, and HH has ∣S∣|S| states. □\square

Claim 7 (the number of output queries). With counterexamples of length at most mm, the learner asks O(kn(k+nm))O(k n (k + n m)) different output queries.

Proof. The rows that are ever computed belong to S∪SAS \cup S A, which has at most n(k+1)n (k + 1) words by Claim 2. The columns are at most k+nmk + n m: the first kk, and at most mm suffixes for each of the at most nn counterexamples of Claim 5. Each entry is one output query, and line L6 reuses the queries uau a of the column aa. □\square

Claim 8 (the differences). Let DD be the list that DIFF (lines L11 and L12) returns for HH and the specification PP. Then DD is empty if and only if HH and PP are equivalent. Each reported word waw a has the same outputs in HH and PP on ww and different outputs on its last letter, and the first word in DD is a shortest word on which HH and PP differ.

Proof. The search visits the pairs of states that HH and PP reach together on words on which they agree, and for each such pair it records the first word that reaches it, which is a shortest one because the search is breadth-first. It reports waw a when the pair of ww gives different outputs on aa, so HH and PP agree on ww and differ on aa. If HH and PP differ on some word, take a shortest one, waw a. They agree on ww, so the pair of states after ww is visited, by a word of length at most ∣w∣|w|, and it is reported with aa. If they agree on all words, no pair gives different outputs on a letter, and DD is empty. The pairs are visited by increasing length of their first word, so the first report has the least length. □\square

Claim 9 (the exhaustive oracle). If HH and MM have at most n1n_1 and n2n_2 states and are not equivalent, some word of length at most n1+n2−1n_1 + n_2 - 1 separates them. So the oracle that tries all words of length at most 2n−12n - 1 is exact for machines of at most nn states.

Proof. On the disjoint union of the two machines, let p≡jrp \equiv_j r mean that the states pp and rr give the same outputs on all words of length at most jj. The relation ≡0\equiv_0 has one class, and each ≡j+1\equiv_{j+1} refines ≡j\equiv_j. Suppose ≡j+1=≡j\equiv_{j+1} = \equiv_j and p≡j+1rp \equiv_{j+1} r. Then pp and rr agree on each letter, and for each letter their successors are ≡j\equiv_j, hence ≡j+1\equiv_{j+1}. So p≡j+2rp \equiv_{j+2} r, and the chain is constant from jj on. Let jj be the least length of a word that separates the two initial states. The chain is then strict from ≡0\equiv_0 to ≡j\equiv_j, so ≡j\equiv_j has at least j+1j + 1 classes, and j+1≤n1+n2j + 1 \le n_1 + n_2. □\square

The guarantees of Claims 6 and 9 are about the model, not about the system. If the true system has more states than the bound that the oracle assumes, or if a random oracle is used, the learner can return a smaller, wrong model. Claim 8 then compares a wrong model with the specification, and its reports can be false or incomplete. The tests show both cases on the example of the page.

Complexity

The rows ever computed belong to SS and its one-letter extensions, at most n(k+1)n (k + 1) words. The columns are at most k+nmk + n m: the one-letter words and at most mm suffixes for each of at most nn counterexamples. So the learner asks O(kn(k+nm))O(k n (k + n m)) different output queries, each of length at most n+mn + m, which gives the time and the space of the query cache in the front matter. The cost of EQ is extra. An exhaustive oracle up to length 2n−12n - 1 is exact for machines of at most nn states but asks up to k2n−1k^{2n-1} queries. Conformance test suites for a bound of n+dn + d states grow with kdk^{d}. On a real system, each query costs a reset and a network exchange, so the number of queries, not the work of the learner, decides the running time.

Properties

  • Black box. It needs only resets and abstract messages, not the source code.
  • Deterministic. With a deterministic oracle and system, the queries and the model are fixed.
  • Exact only with an exact oracle. The model is minimal and correct when the oracle is exact; with testing it can be smaller than the system.
  • Needs determinism and a small alphabet. Nondeterministic behaviour, such as time-outs, breaks the assumptions.

Variants and improvements

  • Other counterexample rules. Angluin adds the prefixes of the counterexample to SS, which needs a consistency check. Rivest and Schapire find one distinguishing suffix by binary search, and keep EE small.
  • Tree-based learners. Kearns and Vazirani and later algorithms such as TTT store the distinguishing words in a tree, and ask fewer queries on long counterexamples.
  • Mealy machine learning. Learning a Mealy machine directly, with outputs in the table, avoids the larger alphabet of a DFA over input and output pairs, and usually needs fewer queries.
  • Automatic checks of the model. Instead of manual inspection, check the model against linear temporal logic properties with a model checker, or compare the models of several implementations with each other, as in differential testing.
  • Other protocols. Later work applied the method to SSH, TCP and DTLS implementations, and to bank cards and smart cards.

When to use it

Use it on implementations of protocols with a clear message order, where a known specification state machine exists and the system can be reset cheaply: TLS, SSH, TCP, and smart card or payment protocols. It finds logic flaws in the order of messages, such as skipped steps, that byte-level fuzzers rarely hit because their inputs do not get past parsing. It does not look for memory errors inside a message; combine it with coverage-guided fuzzing for that.

Pitfalls

  • Unsafe targets. Learning sends many sequences of messages. Run it only on a test copy of the implementation, in a closed test setup that you own, and never against a host of someone else.
  • The abstraction hides the bug. If the harness maps two different concrete messages to one abstract message, the model cannot separate their behaviour.
  • Nondeterminism. Time-outs, retransmissions and shared state across resets make answers vary. The learner then sees inconsistent rows. Repeat queries and check that answers are stable.
  • False confidence from testing. A random or bounded oracle can accept a model that misses states, as in the example, and DIFF then gives false and missing reports. Report the oracle and its bound with every model.
  • Reading the model. A model with dozens of states takes time to read. The flaws come from comparing it with the specification, which is manual work unless a property checker is added.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

protocol_state_fuzzing.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/protocol-state-fuzzing/. The authors are listed in prov/27Q5V5.jsonl.
"""Protocol state fuzzing: learn the state machine of an implementation, then compare it with the specification.

The implementation is a black box with a reset and a step: an output query
gives a word of abstract messages and returns the word of responses. Active
automata learning (Angluin's L*, adapted to Mealy machines) builds a model
from output queries and an equivalence oracle. The model is then compared with
a specification machine, and every shortest input word after which the two
answer differently is reported for a human to inspect.

Here the black box is always a Mealy machine simulated in Python, built by the
tests. Nothing here talks to a real host or a real network.

The counterexample rule (add every suffix of the counterexample to the
columns, after Maler and Pnueli) and the choice of the equivalence oracle are
design choices. The exhaustive oracle is exact when the number of states of
the black box is at most the bound it is given; the random oracle is not.
"""

import itertools
import random
from collections import deque
from dataclasses import dataclass, field
from typing import Callable, Hashable, Optional, Sequence

Word = tuple
OutputQuery = Callable[[Word], Word]


@dataclass
class MealyMachine:
    """A deterministic Mealy machine with initial state 0 and total transitions."""

    inputs: tuple
    delta: list[dict] = field(default_factory=list)  # delta[s][a] = next state
    lam: list[dict] = field(default_factory=list)  # lam[s][a] = output

    @property
    def size(self) -> int:
        return len(self.delta)

    def run(self, word: Sequence) -> Word:
        s, out = 0, []
        for a in word:
            out.append(self.lam[s][a])
            s = self.delta[s][a]
        return tuple(out)


class CountingQuery:
    """Wraps an output query with a cache and counts the queries that reach the system."""

    def __init__(self, query: OutputQuery) -> None:
        self.query = query
        self.cache: dict[Word, Word] = {}
        self.count = 0

    def __call__(self, word: Word) -> Word:
        if word not in self.cache:
            self.count += 1
            self.cache[word] = tuple(self.query(word))
        return self.cache[word]


def learn_mealy(inputs: Sequence[Hashable], query: OutputQuery, equivalence: Callable[[MealyMachine], Optional[Word]]) -> MealyMachine:
    """Learn a Mealy machine with L* from output queries and an equivalence oracle.

    query(w) returns the outputs of the black box on w after a reset.
    equivalence(h) returns None if h is accepted, or a word on which h and the
    black box give different outputs. If the black box has n states, the
    result has at most n states, and it has exactly the minimal number when
    the oracle returns None only for equivalent machines. Cost
    O(k n (k + n m)) output queries for k inputs and counterexamples of
    length at most m.
    """
    inputs = tuple(inputs)
    S: list[Word] = [()]  # @line L1
    E: list[Word] = [(a,) for a in inputs]

    def row(u: Word) -> tuple:
        return tuple(query(u + e)[len(u):] for e in E)  # @line L2

    while True:  # @line L3
        while True:
            rows_s = {row(u): u for u in S}
            missing = None
            for u in S:  # @line L4
                for a in inputs:
                    if row(u + (a,)) not in rows_s:
                        missing = u + (a,)
                        break
                if missing is not None:
                    break
            if missing is None:
                break
            S.append(missing)  # @line L5
        rows_s = {row(u): i for i, u in enumerate(S)}
        h = MealyMachine(inputs, [dict() for _ in S], [dict() for _ in S])  # @line L6
        for i, u in enumerate(S):
            for a in inputs:
                h.delta[i][a] = rows_s[row(u + (a,))]
                h.lam[i][a] = query(u + (a,))[-1]
        c = equivalence(h)  # @line L7
        if c is None:
            return h  # @line L8
        for i in range(len(c)):  # @line L9
            suffix = tuple(c[i:])
            if suffix not in E:
                E.append(suffix)


def differences(m1: MealyMachine, m2: MealyMachine) -> list[tuple[Word, Word, Word]]:
    """Every shortest word that ends in a transition where m1 and m2 differ.

    Breadth-first search over pairs of states from (0, 0). For each pair of
    states reached first by the word w and each input a with different
    outputs, report (w + (a,), outputs of m1, outputs of m2). Cost
    O(n1 n2 k) for machines of n1 and n2 states and k inputs.
    """
    out = []
    start = (0, 0)
    seen = {start: ()}
    q = deque([start])  # @line L11
    while q:
        s1, s2 = q.popleft()
        w = seen[(s1, s2)]
        for a in m1.inputs:
            if m1.lam[s1][a] != m2.lam[s2][a]:  # @line L12
                word = w + (a,)
                out.append((word, m1.run(word), m2.run(word)))
                continue
            nxt = (m1.delta[s1][a], m2.delta[s2][a])
            if nxt not in seen:
                seen[nxt] = w + (a,)
                q.append(nxt)
    return out


def protocol_state_fuzz(inputs: Sequence[Hashable], query: OutputQuery, equivalence: Callable[[MealyMachine], Optional[Word]], spec: MealyMachine) -> tuple[MealyMachine, list[tuple[Word, Word, Word]]]:
    """Learn the model of the black box and list its differences from the specification."""
    model = learn_mealy(inputs, query, equivalence)
    return model, differences(model, spec)  # @line L10


def exhaustive_oracle(query: OutputQuery, depth: int) -> Callable[[MealyMachine], Optional[Word]]:
    """An equivalence oracle that tries every word of length at most depth, shortest first.

    If the black box has at most n states and the hypothesis has at most n
    states, depth = 2n - 1 makes the oracle exact. Cost O(k^depth) queries.
    """
    def eq(h: MealyMachine) -> Optional[Word]:
        for d in range(1, depth + 1):
            for w in itertools.product(h.inputs, repeat=d):
                if h.run(w) != query(w):
                    return w
        return None
    return eq


def random_oracle(query: OutputQuery, rng: random.Random, tests: int, max_len: int) -> Callable[[MealyMachine], Optional[Word]]:
    """An equivalence oracle that tries random words. It can accept a wrong hypothesis."""
    def eq(h: MealyMachine) -> Optional[Word]:
        for _ in range(tests):
            w = tuple(rng.choice(h.inputs) for _ in range(rng.randint(1, max_len)))
            if h.run(w) != query(w):
                return w
        return None
    return eq
test_protocol_state_fuzzing.py 197 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/protocol-state-fuzzing/. The authors are listed in prov/27Q5V5.jsonl.
import itertools
import random

from protocol_state_fuzzing import (
    CountingQuery,
    MealyMachine,
    differences,
    exhaustive_oracle,
    learn_mealy,
    protocol_state_fuzz,
    random_oracle,
)

INPUTS = ("Hello", "Key", "Finished", "Data")


def handshake(skip_key: bool) -> MealyMachine:
    """The toy handshake of the page.

    States 0 to 3 are start, after Hello, after Key and open; state 4 is the
    closed sink. With skip_key, Finished is accepted before Key and leads to
    state 5, which answers one Data message and then sends an Alert from state 6.
    """
    order = [("Hello", "ServerHello"), ("Key", "Empty"), ("Finished", "Fin"), ("Data", "Data")]
    sink, n = 4, 7 if skip_key else 5
    m = MealyMachine(INPUTS, [dict() for _ in range(n)], [dict() for _ in range(n)])
    for s in range(n):
        for a in INPUTS:
            m.delta[s][a], m.lam[s][a] = (sink, "Closed") if s == sink else (sink, "Alert")
    for s, (a, out) in enumerate(order):
        m.delta[s][a], m.lam[s][a] = min(s + 1, 3), out
    if skip_key:
        m.delta[1]["Finished"], m.lam[1]["Finished"] = 5, "Fin"
        m.delta[5]["Data"], m.lam[5]["Data"] = 6, "Data"
    return m


def shortest_counterexample(h, target):
    """An independent equivalence oracle: level-by-level search of the product machine."""
    seen = {(0, 0)}
    level = [((0, 0), ())]
    while level:
        nxt = []
        for (p, q), w in level:
            for a in target.inputs:
                if h.lam[p][a] != target.lam[q][a]:
                    return w + (a,)
                pair = (h.delta[p][a], target.delta[q][a])
                if pair not in seen:
                    seen.add(pair)
                    nxt.append((pair, w + (a,)))
        level = nxt
    return None


def classes(machines):
    """Moore partition refinement on the disjoint union. Returns the class of (machine, state)."""
    nodes = [(i, s) for i, m in enumerate(machines) for s in range(m.size)]
    inputs = machines[0].inputs
    block = {v: tuple(machines[v[0]].lam[v[1]][a] for a in inputs) for v in nodes}
    while True:
        key = {v: (block[v], tuple(block[(v[0], machines[v[0]].delta[v[1]][a])] for a in inputs)) for v in nodes}
        ids = {}
        new = {v: ids.setdefault(key[v], len(ids)) for v in nodes}
        if len(ids) == len(set(block.values())):
            return new
        block = new


def equivalent(m1, m2):
    c = classes([m1, m2])
    return c[(0, 0)] == c[(1, 0)]


def minimal_size(m):
    seen, stack = {0}, [0]
    while stack:
        s = stack.pop()
        for a in m.inputs:
            t = m.delta[s][a]
            if t not in seen:
                seen.add(t)
                stack.append(t)
    c = classes([m])
    return len({c[(0, s)] for s in seen})


def random_machine(rng, n, k, outs):
    inputs = tuple("abc"[:k])
    return MealyMachine(
        inputs,
        [{a: rng.randrange(n) for a in inputs} for _ in range(n)],
        [{a: rng.randrange(outs) for a in inputs} for _ in range(n)],
    )


def test_page_example():
    spec, impl = handshake(False), handshake(True)
    query = CountingQuery(impl.run)
    model, diffs = protocol_state_fuzz(INPUTS, query, lambda h: shortest_counterexample(h, impl), spec)
    assert model.size == 7 and equivalent(model, impl)
    assert diffs == [(("Hello", "Finished"), ("ServerHello", "Fin"), ("ServerHello", "Alert"))]
    assert query.count == 204
    assert differences(spec, spec) == []
    # The first hypothesis takes Hello, Finished as the word of the open state.
    rounds = []

    def oracle(h):
        c = shortest_counterexample(h, impl)
        rounds.append((h.size, c))
        return c

    learn_mealy(INPUTS, CountingQuery(impl.run), oracle)
    assert rounds == [(6, ("Hello", "Key", "Finished", "Data", "Data")), (7, None)]
    assert impl.run(rounds[0][1])[-2:] == ("Data", "Data")


def test_page_example_with_practical_oracles():
    impl, spec = handshake(True), handshake(False)
    q = CountingQuery(impl.run)
    model, diffs = protocol_state_fuzz(INPUTS, q, exhaustive_oracle(q, 6), spec)
    assert equivalent(model, impl) and len(diffs) == 1
    # Too few random tests accept the wrong first hypothesis; more tests find the counterexample.
    q = CountingQuery(impl.run)
    model, diffs = protocol_state_fuzz(INPUTS, q, random_oracle(q, random.Random(5), 200, 6), spec)
    assert model.size == 6 and not equivalent(model, impl)
    # The wrong model also gives a false report on the correct handshake.
    assert [w for w, _, _ in diffs] == [("Hello", "Finished"), ("Hello", "Key", "Finished", "Data", "Data")]
    q = CountingQuery(impl.run)
    model, diffs = protocol_state_fuzz(INPUTS, q, random_oracle(q, random.Random(5), 5000, 8), spec)
    assert model.size == 7 and equivalent(model, impl)


def test_one_state_and_one_input():
    m = MealyMachine(("a",), [{"a": 0}], [{"a": "x"}])
    h = learn_mealy(m.inputs, m.run, lambda h: shortest_counterexample(h, m))
    assert h.size == 1 and h.run(("a", "a")) == ("x", "x")
    # A counter modulo 3 needs two columns beyond the first to separate its states.
    c = MealyMachine(("a",), [{"a": 1}, {"a": 2}, {"a": 0}], [{"a": 0}, {"a": 0}, {"a": 1}])
    h = learn_mealy(c.inputs, c.run, lambda h: shortest_counterexample(h, c))
    assert h.size == 3 and equivalent(h, c)


def test_random_machines_are_learned_exactly_and_minimally():
    rng = random.Random(41)
    for _ in range(600):
        n, k = rng.randint(1, 7), rng.randint(1, 3)
        target = random_machine(rng, n, k, rng.randint(1, 3))
        query = CountingQuery(target.run)
        hyps = []

        def oracle(h):
            hyps.append(h.size)
            return shortest_counterexample(h, target)

        h = learn_mealy(target.inputs, query, oracle)
        assert equivalent(h, target)
        assert h.size == minimal_size(target)
        # Each counterexample adds at least one state.
        assert all(a < b for a, b in zip(hyps, hyps[1:]))
        assert len(hyps) <= h.size


def test_random_exhaustive_oracle_is_exact_with_the_state_bound():
    rng = random.Random(42)
    for _ in range(500):
        n, k = rng.randint(1, 3), rng.randint(1, 2)
        target = random_machine(rng, n, k, 2)
        q = CountingQuery(target.run)
        h = learn_mealy(target.inputs, q, exhaustive_oracle(q, 2 * n - 1))
        assert equivalent(h, target)


def brute_shortest(m1, m2, depth):
    for d in range(1, depth + 1):
        for w in itertools.product(m1.inputs, repeat=d):
            if m1.run(w) != m2.run(w):
                return d
    return None


def test_random_differences_against_brute_force():
    rng = random.Random(43)
    for _ in range(500):
        k = rng.randint(1, 2)
        m1 = random_machine(rng, rng.randint(1, 3), k, 2)
        m2 = random_machine(rng, rng.randint(1, 3), k, 2)
        diffs = differences(m1, m2)
        d = brute_shortest(m1, m2, m1.size + m2.size - 1)
        assert (d is None) == (diffs == []) == equivalent(m1, m2)
        for w, o1, o2 in diffs:
            assert o1 == m1.run(w) and o2 == m2.run(w)
            assert o1[:-1] == o2[:-1] and o1[-1] != o2[-1]
        if diffs:
            assert len(diffs[0][0]) == d

History

Moore (1956) studied which experiments can reveal the state of a black-box machine. Angluin (1987) gave L*, which learns the minimal DFA of a regular language in polynomial time from membership and equivalence queries. Rivest and Schapire (1993) improved the processing of counterexamples, and later work adapted L* to Mealy machines, which fit systems with inputs and outputs. Automata learning was applied to testing of reactive systems in the 2000s. De Ruiter and Poll (USENIX Security 2015) used it on TLS implementations under the name protocol state fuzzing. By inspecting the learned models they found security flaws in GnuTLS, the Java Secure Socket Extension (JSSE) and OpenSSL, and they observed that the models also differ enough to tell implementations apart.

References

  1. Joeri de Ruiter and Erik Poll, Protocol state fuzzing of TLS implementations, USENIX Security 2015, pp. 193 to 206, the abstract (state machine learning of TLS implementations, manual analysis of the models, flaws in GnuTLS, JSSE and OpenSSL)
  2. Dana Angluin, Learning regular sets from queries and counterexamples, Information and Computation 75(2), 87 to 106, 1987, the observation table, closed tables and the learner L*

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • at least three sources
  • a scene preset for the example