Writing Testable Security Tools
A detection script that nobody tested is a guess. It may have worked on the one log file its author looked at, and it may stop working the day the log format gains a field, or the day an attacker sends the one input that makes it crash. Tests turn "I think it works" into "these twenty cases pass", and for security tools they have a second job: they are the place where you try to break your own parser before someone else does. This lesson writes three kinds of test for small tools: example tests, edge-case tests and a tiny fuzzer.
Definitions
- Unit test: calls one function with a fixed input and checks the output.
unittestis in the standard library;pytestis the popular third-party runner with plainer syntax (assert x == y). - Golden test: compares the whole output with a saved, reviewed expected output (exactly what this site's
outputblocks are). - Edge case: input at a boundary: empty, one item, maximum length, the value just over a threshold, malformed.
- Fuzzing: feeding many generated or mutated inputs and watching for crashes, hangs and broken invariants. A seeded generator makes the run reproducible, so a crash can be replayed.
- Invariant: something that must hold for every input, such as "the parser either returns records or raises
ValueError; it never raises anything else".
Tests for a detection rule
The function under test flags a source that fails to log in threshold or more times within window seconds. The tests pin down the boundaries: exactly at the threshold, one below, failures spread just wider than the window, and an empty log.
import io, unittest
from collections import defaultdict, deque
def burst_sources(events, threshold=5, window=60):
"""events: (second, src, ok) sorted by time. Return sources with >= threshold failures in any window."""
recent, flagged = defaultdict(deque), set()
for t, src, ok in events:
if ok:
continue
q = recent[src]
q.append(t)
while q and t - q[0] >= window:
q.popleft()
if len(q) >= threshold:
flagged.add(src)
return flagged
def fails(src, times):
return [(t, src, False) for t in times]
class BurstTests(unittest.TestCase):
def test_exactly_threshold(self):
self.assertEqual(burst_sources(fails("203.0.113.7", [0, 10, 20, 30, 40])), {"203.0.113.7"})
def test_one_below_threshold(self):
self.assertEqual(burst_sources(fails("203.0.113.7", [0, 10, 20, 30])), set())
def test_spread_wider_than_window(self):
self.assertEqual(burst_sources(fails("10.10.0.22", [0, 15, 30, 45, 60])), set())
def test_successes_do_not_count(self):
ev = [(t, "10.10.0.21", True) for t in range(10)]
self.assertEqual(burst_sources(ev), set())
def test_two_sources_independent(self):
ev = sorted(fails("198.51.100.9", [0, 1, 2]) + fails("203.0.113.7", [3, 4, 5, 6, 7]))
self.assertEqual(burst_sources(ev), {"203.0.113.7"})
def test_empty(self):
self.assertEqual(burst_sources([]), set())
stream = io.StringIO()
result = unittest.TextTestRunner(stream=stream, verbosity=2).run(
unittest.defaultTestLoader.loadTestsFromTestCase(BurstTests))
for line in stream.getvalue().splitlines():
if " ... " in line:
print(line.split(" (")[0], "...", line.rsplit(" ... ", 1)[1])
print("run:", result.testsRun, "failures:", len(result.failures), "errors:", len(result.errors))test_empty ... ok
test_exactly_threshold ... ok
test_one_below_threshold ... ok
test_spread_wider_than_window ... ok
test_successes_do_not_count ... ok
test_two_sources_independent ... ok
run: 6 failures: 0 errors: 0
The boundary tests are what make the rule's meaning precise. test_spread_wider_than_window documents that failures at 0 and 60 seconds are not in the same 60-second window (the code uses >= window to expire old entries). If someone later changes that to >, the test fails and the change has to be a decision, not an accident.
A tiny fuzzer finds a crash
The next parser is a first draft of the TLV reader from Binary Formats with struct, with one check missing. The fuzzer mutates a valid input with a seeded generator (so the run can be repeated exactly), and checks the invariant: the parser may return records or raise ValueError, nothing else.
import random, struct
def parse_tlv_draft(data):
out, pos = [], 0
while pos < len(data):
t, n = struct.unpack_from("!BH", data, pos) # BUG: no check that 3 bytes remain
pos += 3
if n > len(data) - pos:
raise ValueError("record longer than data")
out.append((t, data[pos:pos + n]))
pos += n
return out
seed_input = struct.pack("!BH", 1, 5) + b"alice" + struct.pack("!BH", 2, 2) + b"\x00\x2a"
rng = random.Random(1234) # seeded: reproducible
def mutate(data):
data = bytearray(data)
for _ in range(rng.randint(1, 3)):
op = rng.choice(["flip", "cut", "insert"])
if op == "flip" and data:
i = rng.randrange(len(data)); data[i] ^= 1 << rng.randrange(8)
elif op == "cut" and data:
del data[rng.randrange(len(data)):]
else:
data.insert(rng.randrange(len(data) + 1), rng.randrange(256))
return bytes(data)
crashes = {}
for i in range(2000):
case = mutate(seed_input)
try:
parse_tlv_draft(case)
except ValueError:
pass # expected rejection
except Exception as e:
key = f"{type(e).__module__}.{type(e).__name__}"
if key not in crashes or len(case) < len(crashes[key]):
crashes[key] = case # keep the shortest example
print("cases: 2000, crash types:", sorted(crashes))
for name, case in crashes.items():
print(name, "shortest input:", case.hex(" "))cases: 2000, crash types: ['struct.error']
struct.error shortest input: 14
The invariant broke: struct.error escaped, because a cut-off input left fewer than three bytes for the next header. In a monitoring pipeline that exception would stop the whole run, so one crafted packet blinds the tool. The fix is the check from the struct lesson (if len(data) - pos < 3: raise ValueError(...)), and the shortest crashing input becomes a permanent regression test.
How untested behaviour is detected
- Coverage:
coverage run -m pytestthencoverage reportshows lines no test executed. Error-handling branches are usually the uncovered ones, and they are the ones attackers reach. - Mutation testing (
mutmut): change>=to>in the code and see whether any test fails. If none does, the boundary is untested. - Fuzzing in CI: run a few thousand mutated inputs on every change; real projects use coverage-guided fuzzers (Atheris for Python, AFL++ and libFuzzer for C), covered in the research course.
How to make tools testable
- Pure core, thin shell: parsing and rules in functions that take data and return results; files, network, printing and
sys.exitin a smallmain. - Inject what varies: the clock, the network and the file system come in as parameters (
now=, aconnectfunction, a list of lines), so tests can pass fakes. - One test per rule boundary and one per bug ever found.
- Synthetic test data in the repository, never real logs with real user names or addresses (see Lab Safety).
- Seed every generator in tests and print the seed of a failing fuzz run.
Pitfalls
- Testing only the happy path. A security tool's interesting behaviour is on malformed input.
- Asserting too little.
assertTrue(result)passes for any non-empty result; compare with the exact expected value. - Tests that depend on the wall clock or the network fail randomly and get ignored. Inject time; fake connections.
- Catching
Exceptionin the tool itself to "never crash" hides bugs. Catch the specific error at the edge and report it as a finding.
Practice
1. Write a test showing that a burst of five failures where the first and last are 59 seconds apart is flagged.
self.assertEqual(burst_sources(fails("203.0.113.7", [0, 15, 30, 45, 59])), {"203.0.113.7"}). At t = 59 the oldest entry (0) has age 59 < 60, so all five are in the window.
2. After fixing the draft parser, what should the fuzzer report?
crash types: []: every mutated input either parses or raises ValueError. Keep the old shortest crashing input as a unit test that now expects ValueError.
3. How would you test a function that connects to TCP ports without opening real sockets?
Give it a connect parameter (default socket.create_connection) and pass a fake in tests that returns or raises ConnectionRefusedError/TimeoutError according to a table, the way the TCP checker does with its simulated network.
Test yourself
Why are failures at second 0 and second 60 not in the same window in burst_sources?
- Because of a bug
- The code expires entries whose age is >= window, and the test pins that choice down
- Python rounds the times
- The threshold is 6
What invariant did the fuzzer check?
- The parser is fast
- The parser returns records or raises ValueError, never any other exception
- Every input parses
- The output is sorted
Why is the fuzzer's generator seeded?
- To make it faster
- So a failing run can be repeated exactly and the crash reproduced
- Because unseeded generators crash
- To find more bugs
Which design makes a tool easiest to test?
- One long main() that reads files and prints
- A pure core that takes data and returns results, with I/O in a thin main
- Global variables for configuration
- Catching every exception