Timing Attacks: What Your Code Leaks, One Nanosecond at a Time

Every cryptographic check in your system rests on an assumption that never appears in the spec: that the only thing an attacker can observe is the output. In reality your process leaks constantly. How long a comparison took, which cache lines got touched, whether a branch predicted correctly — all of it is physically observable, and differences far too small for a human to notice are trivially measurable by a machine that takes a million samples.

Timing attacks turn those microscopic differences into secrets. They belong to the broader family of side-channel attacks, and they are uniquely uncomfortable because the code is logically correct. The comparison returns the right answer every time. The math holds. The vulnerability lives not in what the program computes but in how long it takes to compute it. This post walks through the classic leaking pattern, why it survives noisy networks, the fixes that actually close the channel, and the leaks that comparison hardening will never catch.

The Comparison That Leaks

Here is the canonical example: validating an API token or a session secret by comparing strings character by character.

func tokenValid(provided, expected string) bool {
	if len(provided) != len(expected) {
		return false
	}
	for i := 0; i < len(provided); i++ {
		if provided[i] != expected[i] {
			return false // leaks how many bytes matched
		}
	}
	return true
}

The early return is the leak. If the first byte of the guess is wrong, the function finishes after one loop iteration. If the first byte happens to be right, it does one extra iteration before bailing at position two. Correct prefixes buy the attacker progressively longer runtimes, so the total time is a function of how many leading bytes the guess shares with the secret. That function is invertible.

The attacker does not need to see a single timing number directly. They guess the first character, send that guess a few thousand times, and record response times. Every wrong guess produces one distribution; the right guess produces a distribution shifted by a single loop iteration. Repeat for position two, three, and so on, and the secret reconstructs itself one byte at a time. Each byte multiplies the search space by 256 in brute force, but timing reduces each position to roughly 256 candidate measurements instead of an intractable search over the whole secret.

The obvious objection is noise. Over a real network, response times bounce around by milliseconds while the signal lives in nanoseconds. That objection used to be a comfort, and it mostly is not anymore. Statistical aggregation across many requests separates tiny means from jitter, and techniques that exploit HTTP/2 multiplexing or browser connection pools can compare two carefully crafted requests inside the same connection, canceling out most network variance. Co-located attackers — a neighboring container, a shared VM host — skip the network entirely and read cache-level timing directly. The right posture is to assume the channel exists and close it, not to bet the secret on the attacker’s network connection being too slow.

Constant-Time Comparison: The Easy Fix

The fix is to make runtime independent of the input contents. Every mainstream language ships a primitive for this, and using it for every secret comparison should be reflexive:

import (
	"crypto/hmac"
	"crypto/subtle"
)

func tokenValid(provided, expected string) bool {
	return subtle.ConstantTimeCompare(
		[]byte(provided), []byte(expected),
	) == 1
}

func macValid(msg []byte, providedMAC, expectedMAC []byte) bool {
	return hmac.Equal(providedMAC, expectedMAC)
}

Under the hood these functions process every byte of both inputs unconditionally, accumulate the differences into a single running value, and only convert that value to a yes/no answer at the very end. The loop always runs to completion, so the runtime depends on the length of the inputs — which is usually public — and never on their contents. Python’s hmac.compare_digest and similar helpers in other runtimes implement the same idea.

Two footnotes worth knowing. First, constant-time comparison still leaks length: if the attacker can distinguish a 32-byte token from a 64-byte token by timing, that is usually fine because lengths are rarely secret, but keep it in mind for the rare cases where they are. Second, == on strings in Go and most compiled languages does something similar to the naive loop under the hood — early exit on the first differing byte — so swapping the loop for a library call is a real change, not a stylistic one.

The Leaks Comparison Hardening Cannot Touch

Constant-time comparison closes the most common hole, but the same principle — runtime as a function of secret data — shows up in places that no comparison primitive will save.

  • Secret-indexed lookups. Reading table[secretByte] touches one cache line; an attacker measuring memory-access latency can tell which one. This is exactly how cache-timing attacks against table-based AES implementations worked, and why modern CPUs ship AES instructions that process data without secret-dependent memory access. The general rule: never use secret values as array indexes, map keys, or loop bounds.
  • Branches on secret bits. An if secretBit == 1 { multiply } else { square } inside a modular exponentiation gives every RSA key bit a different execution path. The countermeasure is blinding: before computing the operation, mask the input with a fresh random factor, compute, then unmask. The secret-dependent computation now operates on a value the attacker cannot predict, so its timing distribution reveals nothing reusable.
  • Early returns in verifiers. Padding and format checks that validate length first, then bytes, then structure produce a timing fingerprint of which check failed. Well-audited crypto libraries order and flatten these checks deliberately; hand-rolled parsers around them usually do not.
  • Anything with a fast path. Optimized string search, regex engines with early bail-out, deserialization that stops at the first invalid field — each one can become an oracle if the data flowing through it is secret or attacker-influenced and the result influences an authentication decision.

The unifying rule is blunt: execution time, memory access patterns, and control flow must not depend on secret values. Achieving that in general is genuinely hard, which is why the practical advice is to use vetted constant-time implementations rather than to write your own — and to review the code around the crypto with this lens.

A Practical Defense Checklist

  • Route every comparison of passwords, tokens, MACs, and session identifiers through the language’s constant-time comparison primitive. Audit authentication middleware especially — it is where naive comparisons congregate.
  • Treat random-looking strings as secrets even when they are “just” identifiers. Signed URLs, invitation codes, and file IDs are exactly the values attackers try to guess byte by byte.
  • Do not index arrays or maps by secret data, and avoid branching on secret values in any code whose timing an outsider can influence or observe.
  • Prefer crypto libraries that enable blinding by default, and keep them updated — timing issues in popular libraries have been found and fixed repeatedly over the years.
  • Use rate limiting and uniform response shaping to shrink the attacker’s bandwidth, but treat these as damage reduction, not a fix. A narrowed channel is still a channel.
  • If you implement anything timing-sensitive yourself, measure it differentially: run the function many times with two different secret inputs and compare the timing distributions, not the medians of a benchmark harness. Benchmarks report medians, and medians are precisely what hides this class of bug.

Timing attacks are a humbling category of vulnerability because they invalidate the mental model most of us write code with. The abstraction that “the program’s behavior is its output” is false at the hardware level, and authentication logic sits exactly where that falsity becomes exploitable. The good news is that the highest-value fixes are cheap: one library call per secret comparison, vetted primitives everywhere else, and a habit of asking, for every branch and every lookup, whether the secret decided which path the CPU took.

Leave a Reply

Your email address will not be published. Required fields are marked *