TExcelTAD

Spectre, Meltdown and Rowhammer as Concepts

For decades, software security assumed that the hardware does what the instruction set says: a bounds check that fails means the load never happens; a page the process may not read cannot be read; a bit in memory changes only when something writes it. In 2018 the disclosure of Spectre and Meltdown showed that CPUs run ahead of their own checks and leave traces in the caches; Rowhammer (published in 2014) had already shown that hammering one row of DRAM can flip bits in a neighbouring row. These are hardware vulnerabilities: no line of the victim's code is wrong. This lesson explains the mechanisms on a toy model, the mitigations at every layer, and why browsers and kernels changed their architecture because of them. Exploitation on real hardware is out of scope.

Speculative execution and the cache

Modern CPUs predict the outcome of branches and execute ahead along the predicted path. If the prediction was wrong, the results are thrown away and execution restarts on the right path. Architecturally, nothing happened. Microarchitecturally, something did: memory that was loaded during the wrong path is now in the cache, and a later access to the same cache line is measurably faster. The cache is a side channel (timing side channels) that survives the rollback.

Spectre variant 1 (bounds check bypass) uses that on correct code:

c
if (x < array1_len)              /* the check is right ... */
    y = probe[array1[x] * 64];   /* ... but runs speculatively before it resolves */

Train the branch predictor with in-bounds x, then call with an out-of-bounds x. The CPU predicts "in bounds", loads array1[x] (a secret beyond the array) and touches the probe line selected by that secret, then discovers the misprediction and discards y. Timing which probe line is now cached reveals the secret byte.

The mechanism in a toy CPU

The model below is a simulation with a one-entry branch predictor and a set of cached lines. It does not touch real hardware: it shows why the leak happens and why each mitigation stops it. The secret LAB lies right after a 16-entry array. It runs in your browser:

python · try it yourself
# A toy CPU model (no real hardware involved): a branch predictor, speculative execution,
# and a cache whose state survives when speculative work is rolled back.
MEMORY = list(range(1, 17)) + list(b"LAB")      # array1[0..15], then a secret the code never reads
ARRAY1_LEN = 16

class ToyCPU:
    def __init__(self, mitigation):
        self.mitigation = mitigation
        self.predict_in_bounds = False           # one-entry branch predictor
        self.cache = set()                       # which probe lines are cached

    def victim(self, x):
        """if (x < array1_len) y = probe[array1[x] * 64];  -- correct, bounds-checked code."""
        in_bounds = x < ARRAY1_LEN
        if self.predict_in_bounds and not in_bounds and self.mitigation != "lfence":
            # Mispredicted: the CPU runs ahead before the comparison resolves ...
            idx = x & (ARRAY1_LEN - 1) if self.mitigation == "index masking" else x
            self.cache.add(MEMORY[idx])          # ... and the load leaves a cache line behind.
            # The architectural result is discarded: y is never written. The cache is not restored.
        if in_bounds:
            self.cache.add(MEMORY[x])
        self.predict_in_bounds = in_bounds       # the predictor learns from the real outcome

def leak_byte(cpu, x):
    for _ in range(5):
        cpu.victim(3)                            # train the predictor: "in bounds"
    cpu.cache.clear()                            # flush the probe lines
    cpu.victim(x)                                # out of bounds: architecturally does nothing
    hits = sorted(cpu.cache)                     # "time" each probe line: cached = fast
    return hits[0] if hits else None

for mitigation in ("none", "lfence", "index masking"):
    cpu = ToyCPU(mitigation)
    got = [leak_byte(cpu, ARRAY1_LEN + k) for k in range(3)]
    text = "".join(chr(b) if b and b >= 32 else "." for b in got) if any(got) else "nothing"
    print(f"mitigation {mitigation:<14} cache lines left behind: {got} -> reads {text!r}")
mitigation none           cache lines left behind: [76, 65, 66] -> reads 'LAB'
mitigation lfence         cache lines left behind: [None, None, None] -> reads 'nothing'
mitigation index masking  cache lines left behind: [1, 2, 3] -> reads '...'
  • No mitigation: after each out-of-bounds call the only cached line is the secret byte's (76, 65, 66: L, A, B), although the victim code never architecturally read it.
  • lfence (a speculation barrier) after the check: nothing runs past the comparison until it resolves; no line is left behind. Correct but costly if placed everywhere.
  • Index masking: the index is clamped with x & (len - 1) (in real code, a branch-free mask computed from the comparison) so even speculative loads stay inside the array. The cache shows array values 1, 2, 3: public data, not the secret.

The family

Issue (year disclosed) Mechanism, in one line Main mitigations
Spectre v1, bounds check bypass (2018) speculative load past a bounds check lfence/speculation barriers, index masking, speculative load hardening in compilers, process isolation
Spectre v2, branch target injection (2018) attacker trains indirect-branch predictor to send the victim's speculation to a chosen gadget retpolines, IBRS/eIBRS, IBPB on context switch, later hardware fixes
Meltdown, rogue data cache load (2018) user-mode load of kernel memory executes transiently before the permission fault KPTI (kernel unmapped in user mode), fixed hardware
L1TF / Foreshadow (2018), MDS (2019) data leaked from internal CPU buffers microcode, buffer clearing on context switch, disabling SMT in some threat models
later variants (return-stack, cross-thread, newer microarchitectures) new predictors and buffers, same principle microcode and OS updates, keep firmware current

The table is a map, not a complete list: new variants keep appearing because the root cause, performance features that change shared microarchitectural state, is fundamental. On Linux, /sys/devices/system/cpu/vulnerabilities/ lists each known issue and the mitigation status of the running system.

Why browsers and kernels changed their architecture

A web page's JavaScript can be the attacker of Spectre v1 against its own renderer's memory. Browsers therefore:

  • moved each site into its own process (site isolation, Browser Architecture), so a renderer's address space contains only one site's data;
  • coarsened timers and gated high-resolution tools such as SharedArrayBuffer behind cross-origin isolation (COOP and COEP headers);
  • added index masking and other hardening inside the JavaScript engine.

Kernels added KPTI, retpolines, barriers in sensitive paths and per-context-switch flushes (Kernel as a Target). The lasting lesson: the process (address space), backed by the kernel's flushes and barriers on context switch, is the boundary that speculation can be made to respect; anything finer-grained inside one process needs explicit hardening.

Rowhammer

DRAM stores bits as charge in tiny capacitors packed in rows. Activating one row very often (hammering) disturbs neighbouring rows and can flip bits in memory the attacker cannot write. Research showed that such flips can change page-table entries or security-relevant data, crossing every software boundary. Later work showed it from JavaScript and over the network in special setups, and that in-DRAM defences such as Target Row Refresh (TRR) could be bypassed with more complex hammering patterns.

Mitigations: ECC memory (corrects single-bit flips and reports them), higher refresh rates, in-DRAM counters and refresh management in newer DRAM generations, and software isolation (guard rows between security domains). Detection on servers: corrected-error counts in the memory-error logs (EDAC on Linux, machine-check logs) rising on one module are a signal worth investigating, Rowhammer or not.

How hardware issues are disclosed

Hardware vulnerabilities need long, multi-party embargoes: CPU vendors, operating-system and hypervisor vendors, cloud providers and browser makers must ship microcode, kernel and browser changes together. Spectre and Meltdown were under embargo for about seven months: Google Project Zero reported them to the CPU vendors in June 2017, and they were disclosed on 3 January 2018, a few days before the planned date because details had started to leak. The Disclosure section covers multi-party coordination.

Pitfalls

  • "My code has no bug, so Spectre doesn't apply." Spectre v1 exploits correct bounds checks. Code that handles secrets next to untrusted code in one process needs barriers or isolation.
  • Disabling mitigations for speed on shared or multi-tenant systems.
  • Treating ECC as a complete Rowhammer fix. It turns most flips into corrected errors, but multi-bit flips have been shown; monitor the counts.
  • Forgetting firmware. Many mitigations ship as microcode and BIOS updates, not OS patches.

Practice

1. In the model, why does the architecturally correct code still leak?

The predictor was trained "in bounds", so the out-of-bounds call executes the load speculatively before the comparison resolves. Rolling back discards y but not the cache line, which encodes the secret byte.

2. Why does index masking leak "1, 2, 3" instead of nothing, and why is that acceptable?

The speculative load still happens, but with the index clamped into the array, so it reads array1[0..2], values the caller may read anyway. Leaking public data is not a vulnerability.

3. A cloud host shows "Vulnerable" for one entry in /sys/devices/system/cpu/vulnerabilities/. What do you check?

Microcode and BIOS version, kernel version and boot parameters (mitigations not disabled with mitigations=off), and whether the issue matters for the host's threat model (multi-tenant, SMT on). Then update firmware and kernel.

Test yourself

What survives the rollback of mis-speculated instructions?

  1. Register values
  2. Microarchitectural state such as which cache lines were loaded
  3. The variable y
  4. Nothing

Which mitigation was introduced in kernels for Meltdown?

  1. ASLR
  2. KPTI: unmapping most kernel memory while user code runs
  3. Stack canaries
  4. Site isolation

Why did browsers adopt site isolation after Spectre?

  1. For speed
  2. Speculation can read anything in a process's address space, so other sites' data must live in other processes
  3. Cookies required it
  4. To use more cores

What does Rowhammer do?

  1. Crashes the CPU
  2. Repeatedly activating DRAM rows flips bits in neighbouring rows the attacker cannot write
  3. Overheats memory
  4. Reads the cache