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
- Model
- Word RAM
- Properties
- deterministicofflinenot randomizediterative
- Evidence
- Proof sketchCode in 1 languages
- 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 of abstract input messages, an output query OQ that resets the system, sends a word over and returns the word of responses, an equivalence oracle EQ, and a specification machine over . The system is assumed to behave as a deterministic Mealy machine with states over these abstract messages. The output is a Mealy machine that is equivalent to when EQ is exact, and the list of the shortest words on which and 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
is a list of access words, one for each state found so far, and is a list of distinguishing words. The row of a word lists, for each , the last outputs of OQ: the response of the state after to . Two words with different rows lead to different states. The counterexample rule of line L9, which adds every suffix of the counterexample to , is the variant of Maler and Pnueli; it keeps the rows of pairwise different, so the table needs no consistency check.
PROTOCOL-STATE-FUZZ(A, OQ, EQ, P)- 1
S ← [ε], E ← [a for each a in A] - 2
row(u) = [the last |e| letters of OQ(u e) for each e in E] - 3
repeat - 4
while some u a, with u in S and a in A, has a row that no word of S has do - 5
append u a to S - 6
H ← states S, start ε, δ(u, a) = the word of S with the row of u a, λ(u, a) = the last letter of OQ(u a) - 7
c ← EQ(H) ▷ none, or a word on which H and the system differ - 8
if c = none then leave the loop - 9
append every suffix of c that is not in E to E - 10
return H and DIFF(H, P) DIFF(H, P)- 11
search breadth-first over the pairs of states of H and P, from the two start states, along letters with equal outputs - 12
for 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 | 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 reach pairwise different states, and never has more than 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 is closed under suffixes. So after the suffixes of a counterexample are added, the hypothesis would agree with the system on if no state were added; hence every counterexample adds at least one state, and there are at most 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 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 with input alphabet of letters, initial state , and states reachable from . For a word , is the word of outputs after a reset, and is the state that reaches. For and a nonempty , is the last letters of , which is the output of on from the state . The row of is restricted to the columns . The table is the pair of lines L1 to L9.
Claim 1 (rows depend only on the state). If , then and have the same row for every . So two words of with different rows reach different states of .
Proof. is the output of on from , which depends only on .
Claim 2 (invariants). At every point, the rows of the words of are pairwise different, , , and is suffix-closed: every nonempty suffix of a word of is in .
Proof. Line L1 starts with and the one-letter words, which is suffix-closed. Line L5 adds a word whose row differs from all rows of . Line L9 adds columns, so rows that differ stay different, and it adds all suffixes of , so stays suffix-closed. By Claim 1, words of reach pairwise different states, so .
So the loop of lines L4 and L5 ends after at most additions in total. When it ends, the table is closed: the row of every with and is the row of exactly one word of . Line L6 then defines the hypothesis with the states , initial state , the word of with the row of , and . Write for the outputs of on from the state .
Claim 3 (the hypothesis agrees with the table). For every and every , .
Proof. By induction on . If , then . If with nonempty, then because is suffix-closed. Let , so and have the same row. Then , and by induction . The output of on from is its output on followed by its output on from , which is .
Claim 4 (each counterexample adds a state). If line L7 returns a word with , then the next hypothesis has more states than .
Proof. Suppose not. After line L9 the old words of still have pairwise different rows, so if the next run of lines L4 and L5 adds nothing, the table with the new columns is closed with the same . Let be the new hypothesis. For and , let be the word of with the new row of . The old row is the restriction of the new row to , so also has the old row of , and , because the old rows of are pairwise different. The outputs do not change. So . Now , because is a suffix of itself, and . By Claim 3 for , . This contradicts .
Claim 5 (termination and size). The learner asks at most equivalence queries and returns a hypothesis with at most states.
Proof. By Claim 2 every hypothesis has at most states, and by Claim 4 each counterexample adds at least one, starting from at least one.
Claim 6 (exact and minimal). If the oracle returns none only for machines equivalent to , the result is equivalent to , and no machine equivalent to has fewer states.
Proof. The first part is the condition of line L8. For the second part, let be equivalent to , and let be words of . Their rows differ, so there is with . Then gives different outputs on after and after , so it reaches different states after them. So has at least states, and has states.
Claim 7 (the number of output queries). With counterexamples of length at most , the learner asks different output queries.
Proof. The rows that are ever computed belong to , which has at most words by Claim 2. The columns are at most : the first , and at most suffixes for each of the at most counterexamples of Claim 5. Each entry is one output query, and line L6 reuses the queries of the column .
Claim 8 (the differences). Let be the list that DIFF (lines L11 and L12) returns for and the specification . Then is empty if and only if and are equivalent. Each reported word has the same outputs in and on and different outputs on its last letter, and the first word in is a shortest word on which and differ.
Proof. The search visits the pairs of states that and 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 when the pair of gives different outputs on , so and agree on and differ on . If and differ on some word, take a shortest one, . They agree on , so the pair of states after is visited, by a word of length at most , and it is reported with . If they agree on all words, no pair gives different outputs on a letter, and is empty. The pairs are visited by increasing length of their first word, so the first report has the least length.
Claim 9 (the exhaustive oracle). If and have at most and states and are not equivalent, some word of length at most separates them. So the oracle that tries all words of length at most is exact for machines of at most states.
Proof. On the disjoint union of the two machines, let mean that the states and give the same outputs on all words of length at most . The relation has one class, and each refines . Suppose and . Then and agree on each letter, and for each letter their successors are , hence . So , and the chain is constant from on. Let be the least length of a word that separates the two initial states. The chain is then strict from to , so has at least classes, and .
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 and its one-letter extensions, at most words. The columns are at most : the one-letter words and at most suffixes for each of at most counterexamples. So the learner asks different output queries, each of length at most , 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 is exact for machines of at most states but asks up to queries. Conformance test suites for a bound of states grow with . 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 , which needs a consistency check. Rivest and Schapire find one distinguishing suffix by binary search, and keep 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.
# 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
- 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)
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 27Q5V5 Edit this page History Report an error Markdown