← Back to all chapters

Chapter 24Down the Rabbit Hole: How Spectre v1 Reads Memory Through a Bounds Check

6 min read
rabbit-holesecuritycpu-architectureside-channels

Here's the line of code at the center of this story:

if (x < array1_size)
    y = array2[array1[x] * 512];

The check is correct. If x is out of range, the body doesn't run. In 2017 every compiler, kernel and interpreter was full of code shaped like this, and all of it was considered safe.

In January 2018, Kocher and colleagues, alongside Google Project Zero and others, showed it leaks arbitrary memory. Not through a bug in the check, but through the CPU doing what it was designed to do. That's Spectre variant 1, "bounds check bypass", CVE-2017-5753. I wanted to understand why a rollback that really is exact isn't enough.

The CPU guesses#

When a CPU hits an if whose answer isn't ready (say array1_size is coming from RAM), it doesn't wait. A branch predictor guesses, and the CPU executes the guessed path speculatively. If the guess was wrong, registers, flags and memory writes are restored as if nothing happened. That rollback is bit-exact.

The catch is "architecturally". Caches, TLBs and predictor tables are microarchitectural state, never part of the rollback contract. Anything a wrong-path instruction touches in the cache stays touched. And caches can be timed: a recent line answers in tens of cycles, one from RAM in hundreds.

Those two facts side by side are Spectre.

wrong-path loadArchitectural stateregisters, flags,memory writesrolled back exactlyMicroarchitectural statecache, TLB,predictor tablesnot rolled back: stays warmhit: tens of cycles, RAM: hundreds
Wrong-path instructions touch two kinds of state, and only one is rolled back (schematic).
x = 3                      x < array1_size ?
predictor: "taken"   ───▶  yes, in bounds
body runs, array1[3] is a normal byte
predictor learns: taken
The same branch, two outcomes (schematic).

The attack, one round#

The dive's analogy: a librarian guesses ahead and runs to shelf 12 while the desk checks your card. If the desk says no, she puts the book back. But she glanced at a number inside the cover and visited one of 256 sub-shelves to remember it. That sub-shelf is still warm. Time her fetches and you learn the number.

1/5Flush
array2 lines:  [0][1][2] ... [81] ... [255]
cache state:    -  -  -  ...  -   ...  -     all cold
predictor:      untrained
CPU:            flushing all 256 lines

Evict every candidate line so none starts warm by accident.

One round against a 256-line probe array. Step through it.
cache-hitthresholdline 0line 255line 81fast = the secret byte255 slow lines (RAM)
What the probe sees: read time for each of the 256 lines (schematic, not measured data).
The paper's proof of concept, line by line
unsigned int array1_size = 16;
uint8_t array1[160] = { 1,2,3, /* ... */ };   // secret lies past the end
uint8_t array2[256 * 512];
#define CACHE_HIT_THRESHOLD (80)              // cycles
 
void victim_function(size_t x) {
  if (x < array1_size) {
    temp &= array2[array1[x] * 512];
  }
}

The secret is reached with malicious_x = secret - array1. Of the 30 calls per round, every sixth (five) uses malicious_x; the choice is branchless so the predictor gets no tell from the attacker's loop.

for (i = 0; i < 256; i++) {
  mix_i = ((i * 167) + 13) & 255;
  addr = &array2[mix_i * 512];
  time1 = __rdtscp(&junk);
  junk = *addr;
  time2 = __rdtscp(&junk) - time1;
  if (time2 <= CACHE_HIT_THRESHOLD && mix_i != array1[tries % array1_size])
    results[mix_i]++;
}

Each detail matters. The * 512 stride keeps loading one candidate from warming its neighbour. The odd order (i * 167 + 13) & 255 stops the stride prefetcher from faking a hit. The second array is the point: the CPU never reveals the secret's value, but reveals which of 256 lines it chose.

The equation is a vote#

A single timing can't be trusted: scheduling jitter, other cores and frequency scaling add random hits. So each round is a noisy vote, repeated up to 999 times, and a byte is accepted only when the leader wins by a landslide:

accept j  <=>  results[j] >= 2 * results[k] + 5    (k = runner-up)

On an i7 Surface Pro 3 the paper measured about 10 KB/s end to end. Slow next to a bulk copy, plenty for keys, passwords or pointers in seconds to minutes.

The 5-to-1 training ratio, in a toy

The dive included a simulator of a saturating-counter predictor and the vote. It's a model, not a measurement.

attack calls/round  success rate   avg rounds   speculation fired
1/30 (train 29)    100.0%           2.1      100.0% of attack calls
5/30 (train 25)    100.0%           1.1      100.0% of attack calls  <- paper's ratio
10/30 (train 20)    100.0%           1.0      100.0% of attack calls
15/30 (train 15)    100.0%           1.0      100.0% of attack calls
25/30 (train 5)    100.0%           3.2        6.7% of attack calls
29/30 (train 1)      0.0%         999.0        0.0% of attack calls

Predictors use short-memory saturating counters, so you only need to outvote the attack calls. Push the attack share too high and the counter can't recover toward "in bounds", speculation stops firing, and the attack fails even with 999 rounds.

  • 1/30 attack calls100%
  • 5/30 (paper's ratio)100%
  • 15/30100%
  • 25/306.7%
  • 29/300%
How often speculation fires, by share of attack calls in the toy model (percent).

Why there's no clean fix#

Meltdown got KPTI. Spectre v2 got microcode and hardware responses. Variant 1 has stayed software-only in every mainstream vendor's public guidance the dive found, so mitigations are a tax on branches, paid case by case.

ApproachCoverageCost
Index masking (array_index_nospec)Only known, annotated gadgetsCheap
LFENCE on every branchClose to complete2-3x on V8's Octane, worse in adversarial microbenchmarks
Speculative Load Hardening (SLH)Masks loaded values instead of stallingGoogle's Haswell numbers: about 1.8-2.5x less costly than fencing
Targeted hardening (2025)Only branches flagged by static analysisLowest, if the analysis finds every gadget

The Linux kernel wraps user-controlled indexes in array_index_nospec() at syscall boundaries, and its docs say the annotations "may not cover all attack vectors". LLVM ships SLH opt-in and deliberately skips some constant-stack-offset loads. V8 poisons loads with a register that goes zero on a mispredicted path, under 20% on Octane against 2-3x for fencing everything, but Chrome's real backstop is Site Isolation.

Where the fixes leak#

  • Timers. Browsers coarsened and jittered performance.now() in 2018. Within months Aleph Security showed the channel still worked at about 1 bit per second from pure JavaScript, by repeating and filtering out jitter. Slower, not closed.
  • Compiler fences. Silberstein and colleagues (2018) reported Microsoft's inserted LFENCEs missed gadget shapes close to the canonical one. SLH's correctness argument also depends on CPUs not speculating on flags or certain register values, which Intel's manual doesn't formally guarantee.
  • The misconception. "A microcode patch fixed Spectre" is false for v1.

The open question#

Detecting and exploiting v1 is settled. The live work: harden only where needed, provably, and find gadgets nobody annotated.

  • LightSLH (USENIX Security 2025): fixpoint static analysis hardens only exploitable loads. On OpenSSL, libsodium, NaCl and PQClean it measured 0% overhead in half the cases and found two new v1 issues.
  • Speculation-Passing Style: reduces proving speculative constant-time security to proving ordinary constant-time security, so existing verifiers can be reused.
  • dfence (2026): a CPU instruction generalising SLH, under 1% average overhead in a research CPU.
  • SpecRL: reinforcement learning to hunt speculative leaks in black-box chips without RTL.

The gaps are wide: no agreed definition of "speculative-execution security", no tool proving a large real binary gadget-free, no head-to-head comparisons between hardening papers, and no public answer on whether the conditional-branch predictor can be fixed in hardware at all.

What I keep thinking about is how small the original sin was: a promise, "wrong guesses are invisible", true for everything anyone thought to check, and false for the one structure whose purpose is to remember what you touched.

Next, if I go deeper: Spectre v2, where the attacker mistrains the indirect branch predictor, and which did get a hardware answer.

Sources#

© 2026 Bharat Kaurav. Built with Next.js & Tailwind.

>_ bk@netherwatcheresc to close

Welcome, reader. Type help to see what this shell can do.