← Back to section · Tutorials & Labs
Timing-Leak Self-Test Lab: Giving Your Own Comparison Function a Checkup
In an isolated environment, use statistical methods to measure timing differences in comparison functions you wrote yourself — password checks, token comparisons — and learn to judge whether a piece of comparison code leaks secret length information to anyone holding a stopwatch.
Scope and Goals
This lab has exactly one subject: code you wrote yourself. The typical case is a function that compares user-submitted bytes against a locally stored secret byte by byte — login verification, token comparison, message authentication code checks. The whole lab runs on your own machine or in an isolated virtual machine; it never touches any live service and never tests anyone else’s system. What we are practicing is a defender’s basic skill: before code ships, measure your own implementation with the same ruler an attacker would use, and confirm it does not write secret length information into its running time.
By the end of the lab you should be able to answer three questions. First, does your comparison function take measurably different average time for inputs that “fail in the first few bytes” versus inputs that “fail only at the last byte”? Second, is that difference statistically significant rather than machine noise? Third, after rewriting it in constant time, does the same measurement conclude “no significant difference”?
Why Byte-by-Byte Comparison Leaks Time
The most common buggy pattern is a loop that returns failure the moment it finds a mismatching byte. Functionally it is perfectly correct, but its running time is proportional to the position of the first mismatch. An attacker who controls the input, submits repeatedly, and times precisely can extract the secret one byte at a time — every correctly guessed byte adds a small increment to the average latency of the next request. This is exactly the principle behind several real historical timing attacks, and defenders can use the same principle on the bench to audit themselves: group inputs by “matched prefix length”, measure the timing distribution of each group, and look for a staircase that rises monotonically as the prefix grows.
Note that modern CPU pipelines, caches, and frequency scaling inject noise far larger than the target signal. A timing self-test is therefore never “run it once and look at the number” — it is a statistical experiment, and sample size, control groups, and test methodology are all indispensable. The procedure below is designed to that standard.
Procedure
Step one: prepare two versions of the function under test. Version A is the byte-by-byte comparison your project currently uses. Version B is the constant-time version: XOR-accumulate all bytes into a single variable, and only after the loop ends check whether the accumulator is zero, never returning early. The two versions must be functionally equivalent — first confirm with ordinary unit tests that they return identical results for identical inputs.
Step two: construct two classes of input. Fixed class: take a known secret and generate inputs whose prefixes match zero, one, two, up to all bytes of it. Random class: random bytes unrelated to the secret, serving as a noise baseline. Submit each class enough times — for a teaching lab, at least tens of thousands per group — and shuffle the submission order randomly to avoid systematic bias from cache warm-up and temperature drift.
Step three: timing and recording. Use a monotonic clock (such as Python’s time.perf_counter_ns) to record each run, discard the first few warm-up samples, and save the timings per group. Keep the timing code itself simple: no printing or logging inside the timed region.
import time, statistics
def measure(fn, secret, candidate, rounds=20000):
samples = []
for _ in range(rounds):
start = time.perf_counter_ns()
fn(secret, candidate)
samples.append(time.perf_counter_ns() - start)
return statistics.median(samples)
Step four: analysis. Compare each group’s median and interquartile range in a chart or table. If version A’s median latency rises steadily with matched prefix length, with adjacent-group differences larger than within-group spread, while version B’s groups are essentially level, the leak exists and the fix works. For more rigor, run a two-sample t-test on adjacent groups, or use the Welch t-test framework introduced in the dudect lab below, and check whether the t value crosses the usual thresholds.
Reading the Results and Common Misjudgments
Two rules of discipline govern interpretation. First, a difference from one or a handful of samples proves nothing: laptop power management, background processes, and VM scheduling all manufacture millisecond-scale false signals. Only a staircase that reproduces stably at large sample sizes counts as evidence. Second, failing to detect a difference does not mean absolute safety — it only means no difference was detected at this experiment’s resolution, which is exactly why professional assessments state their detection limits. The purpose of a self-test is to catch obvious implementation-level leaks, not to issue your code a security certificate.
Another common misjudgment is treating “short-circuit comparison in the language” as the only risk source: string ==, early exits inside library functions, and even hash-table lookups can introduce data-dependent timing differences. The value of the lab is the measurement habit it builds: any comparison path that handles secrets deserves a trip to the bench.
Rewrite and Re-Test
Once a leak is found, switch the comparison path to a constant-time implementation: use the constant-time comparison function your language or crypto library provides (such as Python’s standard-library hmac.compare_digest), or implement version B’s pattern yourself — while watching out for compilers optimizing away “apparently useless” accumulation, and checking library documentation to confirm the function was designed for this purpose. After the rewrite, re-run the same measurement procedure, confirm the staircase is gone, and keep the self-test script as part of your regression suite: every future change to this code re-runs it, so the leak cannot quietly return.
A Complete Worked Reading
Let us close with a concrete example to compare against. Suppose the secret is sixteen bytes. Version A’s median latency at zero matched prefix bytes is about one hundred units; each additional correct byte adds a stable ten units or so, reaching about two hundred sixty units at a full match, while each group’s interquartile range is only about five units — the staircase is crisp and the groups do not overlap: the classic picture of a leak. Version B’s groups all sit around two hundred sixty units, with adjacent differences smaller than within-group spread and an insignificant t-test: the picture of a fix that landed. When reading results, look at the trend before the numbers: a monotone trend larger than the noise is the conclusion; the absolute numbers vary by machine and never constitute one. Archive both charts together with the raw data, so that a future machine or implementation change can be re-measured on the same footing — that archive is this code’s timing checkup history.
Tags: timing side channelconstant timeself-test labdefensive programming