Timing Side Channels and Constant-Time Code
A program can be functionally perfect and still leak its secrets through how long it takes. If checking a password stops at the first wrong character, an attacker who can time the check learns how many characters were right, and can guess the secret one character at a time instead of all at once. This is a timing side channel: information carried not by the output but by a physical property of the computation. Hardware security research is largely the study of such channels (time, caches, power, electromagnetic emanation) and of the code and hardware that close them. This lesson starts with the simplest one, entirely in software.
The mechanism
An early-exit comparison does work proportional to the length of the matching prefix:
for i in range(len(a)):
if a[i] != b[i]:
return False # returns sooner the earlier the mismatchAgainst an 8-byte secret, a blind guesser needs up to tries. An attacker who can tell "the first byte matched" from "it didn't" needs at most : for each position, try all 256 values and keep the one that took longest. Real measurements are noisy (network jitter, scheduling, caches), so real attacks repeat each query many times and use statistics. On the same machine, differences of a few nanoseconds can be resolved; across a network, published research has resolved differences of tens to hundreds of nanoseconds with enough repetitions (and with concurrency-based "timeless" techniques).
A model, a detector and a measurement
The example has three parts, each with deterministic output:
- The mechanism on a time model. Each comparison returns its cost, the number of bytes compared, which stands for its running time. The attacker recovers the toy token from the cost (and, for the last byte, the accept/reject answer).
- Detection, dudect-style. The dudect method (Reparaz, Balasch and Verbauwhede, 2017) runs the code on two classes of inputs and applies Welch's t-test to the timings; a large means the timing depends on the data. The threshold 4.5 used here is the convention from leakage assessment of hardware (TVLA); dudect's reference code is more lenient and reports a failure above 10. Here the timings are the modelled costs plus seeded random noise.
- A real measurement, kept stable by printing only a verdict: a 10 KiB comparison that fails at the last byte versus one that fails at the first, for the early-exit loop and for
hmac.compare_digest.
It runs in your browser:
import hmac, random, statistics, time
SECRET = b"k7Q2xv9a" # a toy API token held by a toy server
def leaky_equal(a, b):
"""Early-exit comparison. Returns (equal, cost), cost = bytes compared = modelled time."""
if len(a) != len(b):
return False, 1
for i in range(len(a)):
if a[i] != b[i]:
return False, i + 1
return True, len(a)
def ct_equal(a, b):
"""Constant-time comparison: always touches every byte, no data-dependent branch."""
if len(a) != len(b):
return False, len(a)
diff = 0
for x, y in zip(a, b):
diff |= x ^ y
return diff == 0, len(a)
# 1. Mechanism, on the time MODEL: guess byte by byte, keeping the guess with the highest
# (cost, accepted) answer. The constant-time version gives every guess the same cost.
def recover(compare):
known, queries = b"", 0
for pos in range(len(SECRET)):
best = max(range(256), key=lambda c: compare(known + bytes([c]) + b"\0" * (len(SECRET) - pos - 1), SECRET)[::-1])
queries += 256
known += bytes([best])
return known, queries
for name, cmp in (("early-exit", leaky_equal), ("constant-time", ct_equal)):
guess, q = recover(cmp)
print(f"{name:<13} model attack after {q} queries: {guess!r} correct: {guess == SECRET}")
# 2. Detection, dudect-style: two input classes, noisy modelled timings, Welch's t statistic.
rng = random.Random(0)
def t_stat(compare):
fixed = SECRET[:4] + b"0000" # class A: shares a 4-byte prefix with the secret
a = [compare(fixed, SECRET)[1] + rng.gauss(0, 2) for _ in range(2000)]
b = [compare(bytes(rng.randrange(256) for _ in range(8)), SECRET)[1] + rng.gauss(0, 2) for _ in range(2000)]
return (statistics.mean(a) - statistics.mean(b)) / ((statistics.variance(a) / 2000 + statistics.variance(b) / 2000) ** 0.5)
for name, cmp in (("early-exit", leaky_equal), ("constant-time", ct_equal)):
t = t_stat(cmp)
print(f"{name:<13} |t| = {abs(t):6.1f} -> {'LEAKS (|t| > 4.5)' if abs(t) > 4.5 else 'no leak detected'}")
# 3. Real measurements (noisy, so only the verdict is printed): a long token, mismatch early vs late.
def measure(compare, a, b, reps=50):
t0 = time.perf_counter()
for _ in range(reps):
compare(a, b)
return max(time.perf_counter() - t0, 1e-4) # browsers coarsen timers: floor at 0.1 ms
long_secret = bytes(range(256)) * 40 # 10 KiB
early = b"\xff" + long_secret[1:] # differs at byte 0
late = long_secret[:-1] + b"\x00" # differs at the last byte
for name, cmp in (("early-exit loop", lambda a, b: leaky_equal(a, b)[0]), ("hmac.compare_digest", hmac.compare_digest)):
ratio = measure(cmp, late, long_secret) / measure(cmp, early, long_secret)
print(f"measured, {name:<19}: mismatch at the end vs at the start: {'much slower' if ratio > 5 else 'about the same'}")early-exit model attack after 2048 queries: b'k7Q2xv9a' correct: True
constant-time model attack after 2048 queries: b'\x00\x00\x00\x00\x00\x00\x00\x00' correct: False
early-exit |t| = 63.1 -> LEAKS (|t| > 4.5)
constant-time |t| = 0.7 -> no leak detected
measured, early-exit loop : mismatch at the end vs at the start: much slower
measured, hmac.compare_digest: mismatch at the end vs at the start: about the same
- On the model, 2,048 guided queries recover
k7Q2xv9aexactly from the early-exit comparison, while the constant-time version gives every guess the same cost and the attack learns nothing. - The t-test separates them clearly: for the early-exit loop, for the constant-time one, under the same noise. In practice you run such a test on measured timings of your real code, in CI, with many thousands of samples.
- The measurement on your machine agrees: the early-exit loop is much slower when the mismatch is at the end;
hmac.compare_digesttakes about the same time either way. (Browsers deliberately coarsen their timers, partly because of Spectre, so tiny differences are hard to see from a web page; that is a mitigation too.)
Where timing leaks hide
| Code | Leak | Constant-time alternative |
|---|---|---|
comparing MACs, tokens, password hashes with == / memcmp |
prefix length | hmac.compare_digest, CRYPTO_memcmp, crypto/subtle.ConstantTimeCompare |
| table lookups indexed by secret bytes (classic AES T-tables) | cache lines touched (next lesson) | bitsliced or hardware AES (AES-NI) |
| branches on secret bits (square-and-multiply in RSA) | number of multiplications | Montgomery ladder, constant-time big-integer code |
| early-return validation in login code ("user not found" faster than "wrong password") | account existence | always hash, fixed work for both paths |
| variable-time CPU instructions (division on some CPUs) | operand values | avoid them on secrets; CPU features such as data-independent timing modes |
How timing leaks are detected
- Statistical testing of real timings with dudect or similar tools in CI for cryptographic code.
- Static and symbolic tools that flag branches and memory indices that depend on secret data (ct-verif-style analyses, compiler checks, Valgrind-based tools that mark secrets as "uninitialised" so any branch on them is reported).
- Code review for the patterns in the table, especially in authentication code.
How they are fixed
Use well-reviewed library primitives for every secret comparison and every cryptographic operation; never compare secrets with ==. Make both branches of security decisions do the same work. Rate-limit and add monitoring to authentication endpoints, which also limits the number of queries an attacker can make (Brute Force and Password Spraying). Random delays are not a fix: averaging removes them.
Pitfalls
- "The network noise hides it." Repetition and statistics remove noise; sub-microsecond differences have been measured across networks in published research.
- Compilers undoing constant-time code. Optimisers can turn a careful loop back into an early exit. Use library primitives that are written and tested against this.
- Constant time only for the comparison. A token lookup in a hash table or database index before the comparison can leak too.
- Adding random sleep. It slows legitimate users and only multiplies the attacker's sample count.
Practice
1. How many queries does the model attack need for a 32-byte token, and how many does blind guessing need?
queries for the timing attack (more in reality, for repetitions), against up to for blind guessing.
2. A login says "unknown user" in 2 ms and "wrong password" in 80 ms. What leaks, and how is it fixed?
Account existence: an attacker can enumerate valid user names by timing (or by the message). Fix: the same generic message for both cases, and for unknown users still run the password hash against a dummy hash, so both paths take the same time.
3. Why does ct_equal still reveal the length of the secret?
It returns immediately when the lengths differ, and its cost is proportional to the length. For fixed-length secrets such as MACs (always 32 bytes) that is fine; compare fixed-length digests rather than variable-length raw secrets.
Test yourself
Why does an early-exit comparison leak a secret?
- It returns the secret
- Its running time grows with the length of the matching prefix
- It uses too much memory
- It is not deterministic
How many queries did the model attack need for the 8-byte token?
- 8
- 2048 (256 per byte)
- 256
What does a dudect-style test compute?
- Code coverage
- A t statistic comparing timings of two input classes; large |t| means data-dependent timing
- The secret
- CPU temperature
Which is the right fix for comparing a received MAC in Python?
received == expectedhmac.compare_digest(received, expected)- Add a random sleep
- Compare their lengths only