Speculative Execution Attacks
Side-Channel Attacks · Advanced Exploitation track
8 min read
In this module
The CPU's Educated Guesses
Modern CPUs don't run one instruction at a time. To stay fast, they look ahead and run instructions speculatively, before it's even settled that those instructions should run at all. When the CPU hits a conditional branch (an if statement), it makes a guess about which way the branch will go and starts pushing instructions down that path. Right guess? It saved itself a few cycles. Wrong guess? It throws the speculative results away and restarts on the correct path.
This trick, called speculative execution, has been a cornerstone of high-performance CPU design since the 1990s. Intel, AMD, ARM — everyone leans on it heavily. The unpleasant surprise, exposed in 2017, was that speculation leaves measurable traces behind even after the speculation gets rolled back.
Spectre: The Branch Prediction Attack
Spectre (CVE-2017-5753 for variant 1, CVE-2017-5715 for variant 2) abuses the CPU's branch predictor. The attacker conditions the predictor to expect a certain outcome, then triggers speculative execution down a code path that touches secret data. The access gets rolled back. The cache footprint doesn't.
Consider this code pattern, which shows up everywhere:
if (index < array_length) { value = array[index]; temp = probe_array[value * 4096];}Under normal execution, if index >= array_length, the body never runs. But the branch predictor might still predict the branch will be taken, because it was taken plenty of times during normal operation. So the CPU speculatively executes the body:
- It reads
array[index]speculatively, even thoughindexis out of bounds. That read pulls a secret byte from memory past the array. - It uses the secret byte to index into
probe_array, loading the cache line atprobe_array[secret_value * 4096]. - The branch condition finally resolves as false. The CPU rolls back the architectural effects, restoring registers and memory.
- The cache change from step 2 persists. The line for
probe_array[secret_value * 4096]is still sitting in cache.
Now the attacker probes all 256 possible cache lines in probe_array, one per byte value. Whichever line was speculatively loaded produces a cache hit. There's the secret byte.
Attack flow:1. Train branch predictor: call with valid index many times2. Call with out-of-bounds index3. CPU speculatively reads secret byte4. Secret byte used to index probe_array → cache line loaded5. Speculation rolled back (architecturally invisible)6. Probe cache → find which line was loaded → learn secret byteStep through the attack below and watch the cache line that survives the squash. Then set the training calls to 0 and run it again: with the predictor still saying not taken, the CPU never enters the body and the probe comes back empty.
Spectre variant 1, one step at a time
Train the predictor, flush, call with a bad index, then probe the cache. array_length = 16, attack index = 1000. Cycle counts and addresses are illustrative.
Secret: 0x53 'S'
Start
The predictor for this branch starts at "weakly not taken". array_length is 16 and sits in the cache.
Code
// victimif (index < array_length) {value = array[index];temp = probe_array[value * 4096];}// attackerflush(&array_length); flush each probe_array[i * 4096];for (i = 0; i < 256; i++)t[i] = time_access(&probe_array[i * 4096]);
Branch predictor (2-bit counter)
- 00Strongly not taken
- 01Weakly not taken
- 10Weakly taken
- 11Strongly taken
Predicts not taken. Taken means the condition holds and the body runs.
Pipeline
No call in flight.
- Architectural value:
- unset
- Speculative value:
- none
Cache: probe_array lines 0 to 255
No probe_array lines cached. array_length is cached.
Each cell is one line, 4096 bytes apart, so the prefetcher won't drag a neighbour in.
Probe timings (cycles, illustrative)
The attacker hasn't probed yet.
Mitigations: an lfence right after the bounds check stops the CPU running the body until the comparison resolves. Index masking (Linux's array_index_nospec) clamps index to the array even during speculation, so the out-of-bounds read never happens.
Spectre is a class of vulnerabilities that exploit speculative execution. The CPU's branch predictor is tricked into speculatively executing instructions that access secret data. Although the speculative results are rolled back architecturally, the cache effects persist and can be measured. Spectre is particularly dangerous because it affects virtually all modern CPUs and can be exploited across security boundaries.
Spectre Variant 2: Branch Target Injection
Spectre variant 2 goes after indirect branches, the kind where the target address is computed at runtime (virtual function calls, switch statements, that family). The CPU keeps a Branch Target Buffer (BTB) that caches recent targets of indirect branches.
The attacker primes the BTB by running their own code with indirect branches to an address of their choosing. Because of how the BTB indexes its entries, the victim's indirect branch may end up sharing the same slot. When the victim hits that branch, the CPU speculatively jumps to the attacker-chosen address and runs attacker-selected gadgets speculatively, in the victim's context.
Variant 2 is the scarier one. The attacker chooses where speculation goes, not just what data gets touched. They can pick gadgets in the victim's code that speculatively read and leak any memory location they want.
Meltdown: Reading the Unreadable
Meltdown (CVE-2017-5754) leans on a related but distinct piece of CPU behaviour: out-of-order execution. On affected Intel processors, when user-space code tries to read kernel memory, the CPU does the read first and checks permissions later. The permission check eventually fails and an exception fires, but by then the secret value has already flowed through speculative instructions that left their fingerprints in the cache.
/* Meltdown attack (simplified) *//* This instruction faults because user space cannot read kernel memory */secret = *(unsigned char *)kernel_address;/* But speculatively, the CPU already read the value */
/* Speculative execution continues: */temp = probe_array[secret * 4096]; /* Cache line loaded based on secret */
/* Exception is delivered, but cache effect persists */The attacker swallows the exception (signal handlers or Intel TSX), then probes the cache to find out which line was loaded. That's the kernel memory byte.
Meltdown was devastating. Any user-space program could read the entire kernel's memory — passwords, keys, every byte of physical memory, since the kernel maps all of it into its address space.
The big difference from Spectre: Meltdown is an implementation flaw (the CPU lets speculative instructions consume data before the permission check completes), whereas Spectre rides on the fundamental nature of speculative execution itself. Meltdown mostly hit Intel, with IBM POWER and Arm's Cortex-A75 along for the ride. AMD's processors weren't affected, because they don't forward data from a load that fails its permission check. Spectre touches almost every modern CPU.
Mitigations
For Meltdown:
- KPTI (Kernel Page Table Isolation): The primary defence. While running in user space, the kernel page tables are mostly unmapped. Even if a Meltdown attack tries to read the virtual address, there's nothing there — the kernel pages simply aren't present. Covered in the kernel exploitation module, where it shows up specifically as the Meltdown counter.
For Spectre variant 1:
- Bounds check bypass mitigation: Compilers drop in speculation barriers (the
lfenceinstruction on x86) right after bounds checks, stopping speculation from running past the check. The barrier forces the CPU to resolve the branch first. - Array index masking: Compiler transformations that mask the array index so it stays in bounds even during speculation.
For Spectre variant 2:
- Retpoline: A compiler trick that swaps indirect branches for a sequence that traps speculative execution in an infinite loop, denying the CPU the chance to speculate down the wrong target. The name is a portmanteau of "return trampoline."
- IBRS/IBPB/STIBP: Hardware features bolted onto CPUs that flush or partition the branch predictor, killing cross-context branch target injection.
- Enhanced IBRS (eIBRS): A newer hardware feature that automatically refuses to use branch-predictor entries trained at a different privilege level.
The Scope of Transient Execution Attacks
Spectre and Meltdown opened the floodgates on a much wider family known as transient execution attacks: attacks that ride the CPU's speculative and out-of-order machinery to do unauthorised data access that gets rolled back later but leaves measurable side effects in its wake.
Since 2018, researchers have racked up a long list of variants:
- Spectre v4 (Speculative Store Bypass, 2018): A load speculatively runs ahead of an older store to the same address and reads the stale value
- Foreshadow (L1TF, 2018): A Meltdown-style read of whatever sits in the L1 data cache, enough to pull secrets out of SGX enclaves and across VMs
- Spectre-RSB: Hits the Return Stack Buffer (RSB), which predicts return addresses
- SpectreRewind: A covert channel rather than a new leak. Transient instructions hog a shared execution unit (the floating-point divider), slowing down older instructions on the same thread that the attacker times
- Retbleed (2022): Gets return instructions predicted like indirect branches, which retpolines didn't cover
- LVI (Load Value Injection): Meltdown in reverse — injecting attacker-controlled values into a victim's speculative loads
- MDS (Microarchitectural Data Sampling): Drains CPU internal buffers (line fill buffers, store buffers, load ports) to leak data in flight
- TAA (TSX Asynchronous Abort): Uses Intel's TSX feature to fish data out of internal buffers
- Downfall (2023): Intel's gather instructions transiently expose data from an internal vector register buffer
- Inception (2023): Plants phantom predictions on AMD Zen cores to steer transient execution, much as variant 2 did
Each variant pokes at a different microarchitectural optimisation. The underlying problem is that CPUs are gigantic, with hundreds of buffers, predictors, and optimisations, any one of which can hatch a new side channel.
The Performance vs. Security Tension
Speculative execution attacks dragged a deep contradiction into the open. The same optimisations that make CPUs fast — branch prediction, speculative execution, out-of-order execution, caching — are exactly the features that hand attackers their side channels.
Fully mitigating transient execution attacks costs measurable performance. KPTI tacks overhead onto every system call. Retpolines slow indirect branches. Speculation barriers stop the CPU from looking as far ahead. Real workloads that cross security boundaries a lot (heavy syscall users) have shown 5-30% hits.
So vendors and OS developers spend their days haggling between security and speed. Today's mitigations cut the risk dramatically without erasing it. Researchers keep finding fresh transient execution variants, and the arms race between CPU optimisations and security mitigations rolls on.