Skip to content
Memory corruption Write-up Advanced

Exploiting Retbleed in the real world

The report describes exploiting the Retbleed CPU vulnerability on AMD Zen 2 processors to read arbitrary physical memory from a sandboxed, unprivileged process and from a virtual machine. An attacker could leak sensitive data such as cryptographic keys and list running processes and VMs on the host.

bughunters.google.com

Published on bughunters.google.com

We’re sharing details of exploiting Retbleed in a realistic, well-secured setting. Retbleed is a CPU vulnerability discovered in 2022 by ETH Zürich researchers which affects modern processors, particularly AMD’s Zen and Zen 2.

The author, on bughunters.google.com

The full write-up lives on its author's site

It belongs to its author, so we link to it rather than copy it. The other two tabs are our own rewrites, checked against it.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 24 min read.

Context

Retbleed is a CPU vulnerability discovered in 2022 by ETH Zürich researchers. It affects modern processors, particularly AMD's Zen and Zen 2, and it targets return instructions rather than the indirect jumps and calls used by Spectre V2. The work described here is an exploitation effort on AMD Zen 2 that demonstrates arbitrary physical memory read access from a sandboxed, unprivileged process and from a virtual machine. It builds on the original public Retbleed exploit, improving reliability, speed and compatibility in restrictive environments.

The exploit strategy breaks virtual and physical KASLR using microarchitectural side channels and creates ideal disclosure gadgets through speculative Return Oriented Programming (ROP). The authors report data leakage at approximately 13 KB/s with high accuracy, enough to list running processes and VMs on the host machine and to leak sensitive data from them in a targeted fashion, such as cryptographic keys. The exploit also works from inside VMs, allowing leakage of host machine data. A proof-of-concept is released alongside the write-up; it uses Retbleed to produce a list of all processes on a machine from inside a process sandbox.

Setup

The target is the Linux kernel on AMD Zen 2 hardware. The attacker model is a sandboxed, unprivileged process, such as a compromised Chrome renderer, or code running inside an SVM-based VM (for example KVM). These are common calls used by nearly every workload and are almost always allowed in system call policies for sandboxed jobs.

The sandbox policy of most interesting targets lets the process map arbitrary code at any chosen address. This is often required to support JIT compilers or FFI libraries such as Python's cffi. Such a policy allows both the MAP_FIXED flag for mmap, which maps memory at an address chosen by the caller instead of one randomly assigned by the kernel, and PROT_WRITE | PROT_EXEC, which maps RWX memory. Alternatively, it lets the process make memory executable using mprotect.

The exploit code compiles to about 4 KB of shellcode (2.3 KB gzipped), which can easily be injected into a compromised target. The exploit still needs the offsets of the target return and of the gadgets in the target machine's kernel. The authors argue that kernel images should be easy to obtain for a motivated attacker, especially if the target machine uses a stock distro kernel.

Finding it

The starting point is the published Retbleed research. On AMD CPUs vulnerable to Retbleed, the CPU can be trained to mistake a return for a regular indirect branch, in which case the indirect branch predictor takes precedence over the return predictor. This makes exploitation on AMD easier than on Intel, because injecting predictions into the return predictor is much harder than injecting them into the indirect branch predictor. The Intel variant also requires more complex conditions for the vulnerable return, such as a deep call stack, which is why the authors chose Zen 2.

Retbleed lets an attacker read all data in host physical memory. On Linux the kernel maps all physical memory linearly in a special region of virtual memory called the physmap. Like all other kernel memory, the physmap is marked as supervisor memory in the page tables, so it cannot be read directly from userspace. Because the disclosure gadget executes in the kernel, accessing that memory from the gadget works and does not raise an exception, which lets the attacker leak the data.

From the original on bughunters.google.com

Retbleed was published in 2022 and cannot be fixed with microcode updates; it needs software mitigation. The available software mitigations are to clear the branch predictor's state on all context switches including user to kernel (IBPB), or to replace every return instruction in the kernel with a jump to a single sanitised return instruction (jmp2ret). Both are expensive: the authors measured 5-6% overhead for jmp2ret and 55-60% overhead for IBPB on Redis.

Exploitation

Background: pipelining, branches and prediction

Modern high-performance CPUs are pipelined: each instruction is executed in several stages, and with every cycle it moves to the next one. A modern x86 CPU has around 20 pipeline stages (Zen 2 has 19, Ice Lake has 14 to 19). Pipelining only pays off when the CPU feeds new work into the first stage every cycle. If the first stage sits idle for one cycle, the second stage will be idle in the next cycle, and so on. This is called a bubble, and designers try to avoid it at all costs.

Branches are a problem because some instructions take a long time to execute, and a branch that depends on such an instruction can take hundreds of cycles to resolve. Roughly 1 in 6 instructions executed by the CPU is a branch. The perf tool shows this on an execution of ls:

Text
bin  boot  dev  etc  home  lib  lost+found mnt  proc  root  run  sbin  sys  tmp  user usr  var
Performance counter stats for 'ls /':
       1,173,576      instructions
         229,637      branches

Branch prediction solves this by predicting branch targets very early in the pipeline. The CPU can start fetching and executing at the target address before that address is computed, and even before it knows that the instruction is a branch. Predictors are highly accurate; the same perf measurement shows the miss rate:

Text
bin  boot  dev  etc  home  lib  lost+found mnt  proc  root  run  sbin  sys  tmp  user usr  var
 Performance counter stats for 'ls /':
         1,191,090      instructions
           233,365      branches
             8,631      branch-misses

Only 3.7% of branches were predicted incorrectly. When a prediction is wrong the CPU must discard the speculative work and restart at the correct target, but it may execute hundreds of instructions speculatively before noticing. Software must never see the results of speculatively executed instructions, and the CPU enforces this by discarding them.

Background: Spectre, training and cache channels

Spectre showed how speculative execution can leak sensitive data from other code on the same CPU. Attackers train branch predictors, which usually use a branch's previous executions to predict its future targets, to control what the CPU executes speculatively. On many CPUs such as Zen 2 and Skylake it is possible to train branches in another process or in the kernel from a userspace process, because the branch predictor's state is shared by all code that runs on the CPU at all privilege levels. Newer CPUs such as Zen 4 and Cascade Lake tag branch predictor entries per privilege domain, but even these protections can be bypassed sometimes.

A cache covert channel uses the CPU cache as a communication mechanism without the OS's oversight. The most common one is Flush+Reload, which uses an array of 256 memory locations to encode the value of a byte. The receiver flushes all 256 locations, the sender accesses the location corresponding to the secret byte, and the receiver times accesses to each location: the cached one is fastest and reveals the byte. On x86 the clflush instruction flushes a cache line and rdtsc times a memory access. Both are unprivileged and can be executed in any context.

From the original on bughunters.google.com

Speculatively executed code cannot have architecturally visible side effects, but it can still affect the cache, because the cache is transparent to software and is not reset when speculative work is discarded. All non-trivial software contains disclosure gadgets, sequences of instructions that can be misused to read an attacker-chosen secret and encode it into the cache when executed speculatively. The concept is similar to ROP: the attacker reuses existing code instead of injecting their own. The two main Spectre variants are V1, which targets conditional branches, and V2, which targets indirect branches. A typical disclosure gadget looks like this:

Text
x = flush_reload_array[secret * 4096]

Step 1: Training kernel returns through the BTB

On AMD Zen and Zen 2 a userspace process can train any return in the kernel simply by executing a branch. AMD CPUs use a hash table-like structure, the branch target buffer (BTB), to track indirect branches. Collisions in the BTB can be exploited to train branches in victim code. The original Retbleed researchers reverse-engineered the AMD BTB and found that it is keyed using a combination of the virtual address of the branch itself and the target address of the last executed branch. They also reverse-engineered the hash function and documented it in the Retbleed paper.

A userspace branch that collides with a kernel return in the BTB can be constructed by placing the branch at an address that collides with the address of the return under this hash function. The length of the basic blocks terminated by the return and by the training branch must also match. The collisions are generated by XORing a virtual address with a constant documented in the original exploit. Executing the colliding branch in userspace once is enough to train the kernel return.

From the original on bughunters.google.com

Step 2: Choosing the vulnerable return

The exploit uses the same strategy as the exploit published by the Retbleed authors. It trains the return from the mmap system call, which is allowed in the seccomp policy, and uses it to execute a disclosure gadget. An invalid mapping size is passed to mmap to trigger an error return early in the code, so that the code does not modify the values of the rdi and rsi registers before returning. The contents of rdi and rsi, which hold the first two system call arguments, are therefore controlled by the attacker when the CPU executes the vulnerable return.

Step 3: Breaking KASLR with the prefetch side channel

The first step is to locate the kernel's image in memory. Zen 2 supports SMEP, which disallows the CPU from executing instructions in a user page when running in supervisor mode, even speculatively. SMEP prevents the use of a userspace disclosure gadget and forces the use of one in the kernel, so the attacker needs to know where that gadget is. The kernel loads itself at a random address, and the address of a kernel gadget depends on it.

The original exploit uses Retbleed with Prime+Probe to defeat KASLR; this work uses a prefetch side channel instead because it is more reliable. x86 has a prefetch instruction which tells the CPU to load data at a given address into the cache. The prefetch paper's authors found that the instruction executes more slowly when the target address is unmapped and more quickly when it is mapped and the mapping is in the TLB. The instruction never generates page faults even for unmapped addresses, so its running time can be timed precisely. The exploit prefetches all 512 possible addresses where the kernel can load itself and times the instruction: a quick execution means the kernel is mapped there. This KASLR bypass succeeds in more than 99% of cases, runs in less than 1 second, and works on every x86 CPU.

Step 4: Finding the physical address and the physmap

The second step is to allocate memory for the Flush+Reload array and find its address in the physmap. The array cannot be accessed through its userspace address from the gadget because of SMAP, which prevents the CPU from accessing userspace memory in supervisor mode. The bypass is to access a supervisor mapping of the same memory. x86 CPUs have physically indexed and physically tagged caches, so the CPU uses the physical address to look up contents in the cache; accessing the array through two different mappings when encoding and when timing still works. All memory is mapped in the physmap at an address equal to the base of the physmap plus the physical address of the memory. The two parts are bruteforced separately, which is much more efficient (about 2^20 tries instead of 2^37).

A special disclosure gadget is used to bruteforce the physical address of the Flush+Reload array. The gadget adds the base of the physmap to an attacker-controlled value and dereferences the result. The array is allocated in a 2 MiB region aligned to 2 MiB in virtual memory. Linux always uses a 2 MiB mapping for this, and the architecture requires that the physical address of a 2 MiB mapped page is also aligned to 2 MiB. This reduces the search space by 512 times compared to 4 KiB pages. The exploit iterates over every possible 2 MiB-aligned physical address and speculatively executes the gadget. A correct guess brings the start of the array into the cache, which is detected by timing a memory access in userspace. Assuming at most 2 TiB of physical memory, at most 2^20 guesses are needed, which takes about 20 seconds.

The same gadget minus adding the base of the physmap, and the same technique, bruteforces the base address of the physmap. The base is randomised at boot time but always aligned to 1 GiB, so at most 2^17 guesses are needed. The base address together with the physical address of the array gives the virtual address of a mapping for the array that the disclosure gadget can point to.

Step 5: Selecting a disclosure gadget

The gadget must satisfy a few requirements:

  1. It needs to be fast. The CPU must speculatively execute at least two loads, the second being a data-dependent load of the first. The first load reads the secret and the second brings an element of the Flush+Reload array into the cache. The second load cannot start until the first is done, and if the CPU detects the mispredicted return too quickly the gadget fails. The gadget should be as short as possible and have no unnecessary instructions.
  2. It needs to scale the secret value. The gadget must multiply the leaked value by at least 64 before using it as an index into the array, because caches store memory in 64-byte lines on x86. Without scaling, values such as 0 and 30 would land in the same cache line and be indistinguishable. The multiplier is the leak stride. If the stride is too low, hardware prefetching introduces noise; the authors experimentally determined that a stride of at least 512 is required to minimise false positives on AMD CPUs, and higher is better.
  3. It needs to use registers whose contents the attacker controls. Controllable values can also be retrieved from the store buffer, for example when written to the stack. The exploit targets the return from __x64_sys_mmap(unsigned long addr, unsigned long len, unsigned long prot, unsigned long flags, unsigned long fd, unsigned long off) and controls rdi and rsi, the first two arguments to the system call.

The authors experimentally verified that Retbleed can only leak data if the secret data is in the L1d cache. Using performance counters, they confirmed that only the first load in the gadget executes when the secret is not in L1d. AMD CPUs have a performance counter that counts loads crossing a cache line boundary, which are very rare; by making one or both loads cross a boundary and reading the counter, the executed loads can be seen clearly.

Step 6: Working around the missing sibling thread

The original exploit bypasses the L1d limitation by using a second thread to widen the speculation window. AMD Zen 2 CPUs have 2-way simultaneous multithreading: each core executes instructions from two threads at once, which the OS sees as two independent CPUs sharing execution resources such as the ALU and the L1 and L2 caches. Because the caches are shared, one thread can evict data belonging to its sibling. The original exploit uses this to evict the main thread's kernel stack from the cache before the CPU executes the target return, so the actual target address must be loaded from the L3 cache or RAM, which can take hundreds of cycles. A longer speculation window lets the original exploit execute a gadget that takes longer to complete.

From the original on bughunters.google.com

This work cannot widen the window the same way, because the sandbox policy cannot be assumed to allow creating new threads and scheduling them on the sibling core. Before the target return executes, the kernel makes at least one function call which brings the stack into the L1d cache, and without new threads there is no way to evict it.

The authors experimentally observed that the secret data is sometimes not in the L1d cache even if the vulnerable system call is executed multiple times. Even if the first execution brings the secret into the cache, in some cases it has already been evicted by the time the call executes again. The L1d is very small (32 KiB) and shared competitively with the sibling thread; on a busy production machine another process is likely working on the same core, and some cache sets see more activity than others, so the success rate can depend on the address of the secret.

The solution is to execute the disclosure gadget multiple times within the same system call by training multiple returns. mmap is implemented in __x64_sys_mmap, which is tail-called by the system call dispatcher x64_sys_call. The tail call is not a jump to __x64_sys_mmap but an actual call instruction followed by pop rbp; ret, so as soon as __x64_sys_mmap returns, the CPU immediately executes another return without modifying rdi and rsi. Both returns can be trained to execute the gadget. The first execution might not directly leak the data, but it at least brings it into the L1d, so the exploit can leak it during the second execution.

From the original on bughunters.google.com

Step 7: Building an ideal gadget with speculative ROP

Speculative ROP is used to create an ideal disclosure gadget that does not exist in the kernel. Unlike the gadget chaining techniques in the original speculative ROP paper, this version works on kernels that enable Spectre V2 mitigations (retpolines). An ideal gadget loads one byte of secret data, multiplies it by the leak stride (ideally 4096 or more), and accesses the Flush+Reload array using the scaled secret as an index. No such gadget exists in the kernel, so the original exploit had to compromise with a non-ideal gadget using a 16-bit load and a stride of 2048. That still works, but to leak a byte the exploit must also know the value of the byte that comes before it. Sometimes the previous byte is known: the top 2 bytes of a kernel pointer are always 0xffff because of address canonicalisation, so the previous byte is known for every value stored after a pointer. For a random address the previous byte is unknown and must be bruteforced, which makes the exploit less reliable. The requirement also introduces cascading failures: when leaking a large amount of data, spurious failures are always possible, and if the gadget relies on the previous leaked byte and that byte was wrong, the next byte will be wrong too. Sometimes this is detectable and fixable with retries, but not always.

The ideal gadget is constructed by combining 3 ROP gadgets, which are easy to find with any of the many ROP gadget finders. Retbleed lets the attacker train returns, so the return in each gadget can be trained to jump to the next one. The first gadget loads one byte from the secret, the second shifts the leaked byte by 12 bits, and the third accesses the Flush+Reload array using the scaled secret byte as offset. Even though it contains 2 returns, the gadget executes quickly enough to leak data in the short speculation window and lets the exploit read any data without knowing the preceding byte.

From the original on bughunters.google.com

Step 8: Training returns without page faults

The original exploit trains kernel returns by jumping to the address of the disclosure gadget from userspace, which always causes a page fault and a SIGSEGV. Because SMEP forces the use of a kernel gadget, jumping to its address from userspace always raises a #PF, which Linux converts to a SIGSEGV directed at the exploit process. The sandbox policy lets the process set signal handlers, so the SIGSEGV can be handled and the exploit can recover, but this is inefficient. Every training, which happens multiple times per system call because of the gadgets used, triggers a series of context switches between userspace and kernel (#PF handler, signal handler, kernel, training code).

This slows the exploit down and breaks it when the process is ptrace-d. When a ptrace-d process receives a signal, the tracer is notified and has to decide what to do; the additional context switches slow training further and can break it. The authors observed that under ptrace the leak gadget never works unless a second thread is used to widen the speculation window. They are not exactly sure why, but think the extra context switches evict critical exploit data from a cache. This matters because common process sandboxes such as gVisor and sandbox2 ptrace the sandboxed process, and the original exploit breaks under such a sandbox.

The fix is to execute the training jump speculatively, which still trains the return but does not raise a page fault. The Inception paper showed that branches can be trained using speculatively executed branches on AMD CPUs, and this also works for Retbleed: the training jump is executed speculatively rather than architecturally. Even though the jump faults, its target is still added to the BTB and trains the return. As long as the jump is never executed architecturally, training never generates a page fault, because exceptions are raised at instruction retirement. A retpoline is used to trigger speculative execution: the capture_spec infinite loop in the original code is replaced with a jump to the training code, which is always executed speculatively but never architecturally. This is much faster than the original method because it avoids all the context switches, and it solves the ptrace problem for the same reason. Ironically, a Spectre mitigation that itself exploits a Spectre variant (Spectre RSB) is used to exploit a speculative execution bug.

From the original on bughunters.google.com

Step 9: Process discovery and memory translation

The exploit parses kernel data structures to discover other processes and then leaks data from them. The kernel keeps metadata about each thread in a task_struct object, one per thread. These objects are kept in a global linked list containing all threads and processes on the machine, as well as in a tree-like structure mirroring the process tree. The exploit starts from init_task, the task_struct representing the first process, which is at a known offset from the base of the kernel in memory, and traverses the linked list to build a list of all processes. It then reads each process's name and PID from its task_struct.

Once a target process is found, for example a password manager, the exploit needs to know where its data sits in physical memory. Because the physmap maps all physical memory linearly, data can be read from there once its physical address is known. What matters, however, is the data at a certain virtual address in another process, because reading pointers from another process yields virtual addresses, not physical ones. The exploit reads and parses the page tables of other processes. A process's task_struct contains a pointer to an mm_struct, which contains a pointer to the process's top-level page table. Each entry contains the physical address of the next level table, down to the last level where each entry contains the physical address of memory. The x86 page table format is documented in the Intel SDM, so the authors wrote code that parses other processes' page tables and performs memory translation. This can be used either to scan another process's memory for secrets with a regex, or to follow a chain of pointers to interesting secret data.

Step 10: Leaking host memory from inside a VM

The same strategy applies to leaking all memory on the host machine from inside an SVM-based VM such as KVM. The exploit works almost exactly the same way, except that it attacks the host machine's kernel instead of the VM's kernel.

AMD CPUs have Secure Virtual Machine (SVM), analogous to Intel's VT-x, which is the execution backend for most hypervisors on AMD CPUs (KVM, Xen, Hyper-V and others). SVM provides a guest mode used to run VMs; when a VM performs certain operations such as interacting with hardware, the CPU switches back to host mode and lets the VMM handle the operation (a VM exit). The hypervisor and the VM share a lot of CPU state such as the BTB, just as the BTB is shared between usermode processes and the kernel, so a VM can train return instructions executed by the hypervisor and attack it with Retbleed.

Host KASLR is broken with Jump over ASLR. The prefetch side channel used against the kernel from userspace does not work here, because the host kernel's code is not mapped in the VM's address space at all rather than being mapped but inaccessible, so it cannot be prefetched. Jump over ASLR exploits the shared BTB: when the guest causes a VM exit and the host handles it, the CPU adds the host kernel's branches to the BTB. If the guest later executes a branch at an address that collides with a host kernel branch in the BTB, the CPU uses the host entry to predict it, resulting in a misprediction. The guest detects mispredictions by timing how long the CPU takes to start executing at the correct target address, which gives an oracle for the host kernel's memory address and lets the attacker bruteforce it. In a way this KASLR bypass is very similar to Retbleed, but done in reverse.

The vulnerable return targeted in the host is the one from kvm_pv_send_ipi, which can be triggered from the guest using the vmmcall instruction with controlled registers. Hypercalls are similar to system calls and let a guest that knows it runs in a VM request host actions. SVM defines the vmmcall instruction, which typically causes a VM exit under a hypervisor and is used to implement hypercalls. The KVM_HC_SEND_IPI hypercall lets the guest send an interprocessor interrupt, and the implementation in kvm_pv_send_ipi has an early return that can be triggered by passing an invalid parameter. When this return executes, rsi, rdx, rcx and r8 all contain guest-controlled values that can be used to leak memory in the disclosure gadget. The vmmcall instruction is unprivileged and can be executed in a guest at CPL 3 (usermode), but KVM only executes the hypercall handler if it was executed in the guest at CPL 0. The restriction is bypassed by loading a small kernel module that makes the hypercall from guest CPL 0. In a cloud computing scenario tenants typically have full control over the VM, so this is still a realistic attack. It lets the attacker leak all memory on the entire physical machine from inside a compromised guest, including the memory of all other VMs on the same machine.

Root cause

Retbleed is a branch type confusion in the CPU's branch prediction. Returns are normally predicted by a dedicated return predictor, but on vulnerable AMD CPUs the CPU can be trained to mistake a return for a regular indirect branch, in which case the indirect branch predictor takes precedence. Because the BTB is shared across privilege levels and is keyed by a hash of the branch's virtual address and the target of the last executed branch, an unprivileged process can insert a prediction for a kernel return by executing a colliding branch at a chosen address. The kernel then speculatively executes an attacker-chosen disclosure gadget with attacker-controlled registers, and the gadget encodes kernel memory into the cache through Flush+Reload.

The existing defences did not stop this. SMEP prevents executing userspace gadgets but not kernel gadgets, and SMAP prevents accessing userspace memory from the kernel but not accessing the physmap through a supervisor mapping. KASLR is defeated by side channels (prefetch from userspace, Jump over ASLR from a VM). The software mitigations that do exist, IBPB and jmp2ret, are expensive and are not free: the authors measured 5-6% overhead for jmp2ret and 55-60% for IBPB on Redis. Retbleed cannot be fixed with microcode updates and needs software mitigation.

Impact

Under ideal conditions (an idle machine) the exploit leaks data at about 13 KB/s with 100% accuracy. That is enough to list running processes and VMs on the host machine and to leak sensitive data from them in a targeted fashion, such as cryptographic keys. The exploit works from a sandboxed, unprivileged process with a restrictive policy and from inside a VM, where it can read the memory of all other VMs on the same physical machine.

That includes code execution inside sandboxes such as Sandbox2, Sandboxed API, NSJail, minijail, the Chrome sandbox and gVisor. Sandboxing is usually used to contain code that is more exposed to untrusted input or more prone to bugs, so the authors consider this a realistic scenario. The KVM variant requires CPL0 code execution in a VM, which is compatible with the threat model of cloud services where the attacker is assumed to have root in their VM.

A current limitation is that the exploit needs the offsets of the target return and of the gadgets in the target machine's kernel. The authors think these images should be easy to obtain for a motivated attacker, especially with a stock distro kernel, and that with a few more months of work the limitation could be removed by guessing or bruteforcing the locations using a microarchitectural side channel as an oracle, as demonstrated by attacks such as BlindSide.

Fix

Retbleed has been addressed in newer CPU generations, starting with Zen 3 on AMD. Software mitigations are available in the operating system for the vulnerable generations and are enabled in the default configuration of the Linux kernel, but they are expensive. In Google Cloud, workloads that execute arbitrary user code have been moved away from the affected CPU models. Elsewhere, stricter sandbox policies have been implemented which prevent bugs like Retbleed from being exploited, or workloads have been upgraded to VM-based sandboxing, which is easier to harden against CPU bugs. The authors are also investing in more holistic mitigation strategies that mitigate bugs such as Retbleed at the host level.

Variants to test

  1. Other vulnerable returns in the kernel. The exploit can be adapted to target return instructions in other system call implementations or elsewhere in the kernel.
  2. Other hypercall handlers in KVM. The VM variant targets the early return in kvm_pv_send_ipi. Other hypercalls with early returns and guest-controlled registers are candidates.
  3. Other sandboxes with MAP_FIXED and RWX or mprotect. Any sandbox that allows mapping code at a chosen address and making it executable is a candidate.
  4. ptrace-based sandboxes. The speculative training technique removes the page fault and the context switches, so it should work under gVisor, sandbox2 and similar tracers.
  5. KASLR bypasses. The prefetch side channel works on every x86 CPU from userspace; Jump over ASLR is used from a VM.
  6. Removing the kernel image requirement. The authors suggest bruteforcing the locations of vulnerable returns and gadgets with a microarchitectural side channel as an oracle.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 35 min read.

What happened, in plain words

Every computer has a processor (CPU) that runs the programs you use. Modern processors try to be fast by guessing what the program will do next and starting that work early. This guessing is called speculative execution. In 2022, researchers at ETH Zürich found a flaw in how some processors guess, and they called it Retbleed. It affects modern processors, particularly AMD's Zen and Zen 2 families.

The work described here is an exploitation effort: a team took the original public Retbleed exploit and made it work in a realistic, well-secured setting. They demonstrated that a program trapped inside a sandbox can read arbitrary physical memory. They also showed the same attack working from inside a virtual machine (a computer simulated in software), where it can read the memory of the machine hosting it.

They report reading data at about 13 KB/s with high accuracy. That is enough to list the processes and virtual machines running on the host and to pull sensitive data out of them, such as cryptographic keys. A proof-of-concept is released alongside the write-up; it uses Retbleed to produce a list of all processes on a machine from inside a process sandbox.

Setup

The target is the Linux kernel (the core of the operating system) running on AMD Zen 2 hardware. The attacker is a sandboxed, unprivileged process, meaning a program with no special rights that is confined by a sandbox, such as a compromised Chrome renderer (the part of the browser that draws pages, deliberately kept in a cage because it handles untrusted web content). The other attacker position is code running inside a virtual machine based on AMD's virtualisation technology, SVM, for example KVM.

The exploit only needs access to three system calls: mmap, mprotect and sched_yield. A system call is how a normal program asks the operating system to do something on its behalf, such as reserving memory. These three are extremely common and are almost always allowed in the rules that sandboxes use to decide which system calls a program may make.

The sandbox policy of most interesting targets lets the process map arbitrary code at any address it chooses. This is often needed to support JIT compilers (software that turns code into machine instructions while it runs) or FFI libraries such as Python's cffi. Such a policy allows the MAP_FIXED flag for mmap, which maps memory at an address chosen by the caller instead of one randomly assigned by the kernel, and PROT_WRITE | PROT_EXEC, which maps memory that is both writable and executable (often shortened to RWX). Alternatively, it lets the process make memory executable using mprotect.

The exploit code compiles to about 4 KB of shellcode (2.3 KB gzipped). Shellcode is a small blob of machine instructions that an attacker can drop into a running program. A blob that small is easy to inject into a compromised target. The exploit still needs the offsets of the target return and of the gadgets in the target machine's kernel. An offset here is a distance from a known starting point, used to find a specific piece of code. The authors argue that kernel images should be easy to obtain for a motivated attacker, especially if the target machine uses a stock distro kernel (the standard kernel shipped by a Linux distribution).

Finding it

The starting point is the published Retbleed research. On AMD CPUs vulnerable to Retbleed, the CPU can be trained to mistake a return for a regular indirect branch, in which case the indirect branch predictor takes precedence over the return predictor. To unpack that: a return is the instruction that ends a function and goes back to whoever called it, and an indirect branch is a jump whose destination is not written into the instruction but held in a register or memory. The CPU has separate guessing machinery for each. On these AMD chips the wrong machinery can be made to win, which makes exploitation on AMD easier than on Intel, because injecting predictions into the return predictor is much harder than injecting them into the indirect branch predictor. The Intel variant also requires more complex conditions for the vulnerable return, such as a deep call stack (a long chain of nested function calls), which is why the authors chose Zen 2.

Retbleed lets an attacker read all data in host physical memory. Physical memory is the actual RAM chips; programs normally see virtual addresses, which the processor translates into physical ones. On Linux the kernel maps all physical memory linearly in a special region of virtual memory called the physmap. Like all other kernel memory, the physmap is marked as supervisor memory in the page tables, so it cannot be read directly from userspace. Page tables are the kernel's lookup tables that say which virtual address points to which physical memory and who is allowed to touch it. Because the disclosure gadget executes in the kernel, accessing that memory from the gadget works and does not raise an exception, which lets the attacker leak the data. A disclosure gadget is a short sequence of existing instructions that, when run speculatively, reads a secret and leaves a trace the attacker can observe.

From the original on bughunters.google.com

Retbleed was published in 2022 and cannot be fixed with microcode updates. Microcode is firmware inside the CPU that can be updated, but this flaw needs a software fix. The available software mitigations are to clear the branch predictor's state on all context switches including user to kernel (IBPB), or to replace every return instruction in the kernel with a jump to a single sanitised return instruction (jmp2ret). A context switch is the moment the CPU stops running one task and starts another. Both mitigations are expensive: the authors measured 5-6% overhead for jmp2ret and 55-60% overhead for IBPB on Redis, a popular in-memory database. Overhead means the machine does less useful work because it spends time on the defence.

Exploitation

Background: pipelining, branches and prediction

Modern high-performance CPUs are pipelined: each instruction is executed in several stages, and with every cycle it moves to the next one. Think of an assembly line where each worker does one small step and passes the item on. A modern x86 CPU has around 20 pipeline stages (Zen 2 has 19, Ice Lake has 14 to 19). Pipelining only pays off when the CPU feeds new work into the first stage every cycle. If the first stage sits idle for one cycle, the second stage will be idle in the next cycle, and so on. This is called a bubble, and designers try to avoid it at all costs.

Branches are a problem because some instructions take a long time to execute, and a branch that depends on such an instruction can take hundreds of cycles to resolve. A branch is a point where the program can go one of two ways, like a fork in a road. Roughly 1 in 6 instructions executed by the CPU is a branch. The perf tool, a standard Linux profiler that counts hardware events, shows this on an execution of ls, the command that lists a directory:

Text
bin  boot  dev  etc  home  lib  lost+found mnt  proc  root  run  sbin  sys  tmp  user usr  var
Performance counter stats for 'ls /':
       1,173,576      instructions
         229,637      branches

The first line is the output of ls /, the contents of the root directory. The lines below are the counters: about 1.17 million instructions were executed, of which about 230 thousand were branches. That is roughly one branch in five.

Branch prediction solves this by predicting branch targets very early in the pipeline. The CPU can start fetching and executing at the target address before that address is computed, and even before it knows that the instruction is a branch. Predictors are highly accurate; the same perf measurement shows the miss rate:

Text
bin  boot  dev  etc  home  lib  lost+found mnt  proc  root  run  sbin  sys  tmp  user usr  var
 Performance counter stats for 'ls /':
         1,191,090      instructions
           233,365      branches
             8,631      branch-misses

Here the counters show about 1.19 million instructions, about 233 thousand branches, and 8,631 branch misses, meaning the guess was wrong. Only 3.7% of branches were predicted incorrectly. When a prediction is wrong the CPU must discard the speculative work and restart at the correct target, but it may execute hundreds of instructions speculatively before noticing. Software must never see the results of speculatively executed instructions, and the CPU enforces this by discarding them.

Background: Spectre, training and cache channels

Spectre is the family of attacks that showed how speculative execution can leak sensitive data from other code on the same CPU. Attackers train branch predictors, which usually use a branch's previous executions to predict its future targets, to control what the CPU executes speculatively. Training is like teaching a dog a trick by repetition: run the same pattern often enough and the predictor expects it. On many CPUs such as Zen 2 and Skylake it is possible to train branches in another process or in the kernel from a userspace process, because the branch predictor's state is shared by all code that runs on the CPU at all privilege levels. Newer CPUs such as Zen 4 and Cascade Lake tag branch predictor entries per privilege domain, meaning they keep userspace and kernel guesses apart, but even these protections can be bypassed sometimes.

A cache covert channel uses the CPU cache as a communication mechanism without the OS's oversight. The cache is a small, very fast memory inside the CPU that holds recently used data; it is like the handful of tools you keep on your desk instead of walking to the shed. The most common channel is Flush+Reload, which uses an array of 256 memory locations to encode the value of a byte. A byte can hold 256 different values, so one slot per value. The receiver flushes all 256 locations (removes them from the cache), the sender accesses the location corresponding to the secret byte, and the receiver times accesses to each location: the cached one is fastest and reveals the byte. On x86 the clflush instruction flushes a cache line and rdtsc times a memory access. Both are unprivileged and can be executed in any context.

From the original on bughunters.google.com

Speculatively executed code cannot have architecturally visible side effects, meaning it cannot change anything the program can see, but it can still affect the cache, because the cache is transparent to software and is not reset when speculative work is discarded. All non-trivial software contains disclosure gadgets, sequences of instructions that can be misused to read an attacker-chosen secret and encode it into the cache when executed speculatively. The concept is similar to ROP (Return Oriented Programming): the attacker reuses existing code instead of injecting their own. The two main Spectre variants are V1, which targets conditional branches (branches taken depending on a condition), and V2, which targets indirect branches. A typical disclosure gadget looks like this:

Text
x = flush_reload_array[secret * 4096]

This line takes a secret value, multiplies it by 4096, and uses the result as an index into an array. Multiplying by 4096 spreads each possible secret value far apart in memory, so each one lands in a different cache line and can be told apart later. The attacker then times which array slot is cached to learn the secret.

Step 1: Training kernel returns through the BTB

On AMD Zen and Zen 2 a userspace process can train any return in the kernel simply by executing a branch. AMD CPUs use a hash table-like structure, the branch target buffer (BTB), to track indirect branches. A hash table is a way of storing things by computing a short fingerprint of a key; two different keys can end up in the same slot, which is called a collision. Collisions in the BTB can be exploited to train branches in victim code. The original Retbleed researchers reverse-engineered the AMD BTB and found that it is keyed using a combination of the virtual address of the branch itself and the target address of the last executed branch. They also reverse-engineered the hash function and documented it in the Retbleed paper.

A userspace branch that collides with a kernel return in the BTB can be constructed by placing the branch at an address that collides with the address of the return under this hash function. The length of the basic blocks terminated by the return and by the training branch must also match. A basic block is a straight run of instructions with no branch in the middle. The collisions are generated by XORing a virtual address with a constant documented in the original exploit. XOR is a simple bit operation that mixes two values together. Executing the colliding branch in userspace once is enough to train the kernel return.

From the original on bughunters.google.com

Step 2: Choosing the vulnerable return

The exploit uses the same strategy as the exploit published by the Retbleed authors. It trains the return from the mmap system call, which is allowed in the seccomp policy, and uses it to execute a disclosure gadget. Seccomp is the Linux feature that lets a sandbox list which system calls a program may make. An invalid mapping size is passed to mmap to trigger an error return early in the code, so that the code does not modify the values of the rdi and rsi registers before returning. Registers are the CPU's tiny built-in storage slots. The contents of rdi and rsi, which hold the first two system call arguments, are therefore controlled by the attacker when the CPU executes the vulnerable return. In other words, the attacker arranges for the kernel to bail out early, while the attacker's own numbers are still sitting in the registers the gadget will use.

Step 3: Breaking KASLR with the prefetch side channel

The first step is to locate the kernel's image in memory. Zen 2 supports SMEP, which disallows the CPU from executing instructions in a user page when running in supervisor mode, even speculatively. Supervisor mode is the privileged mode the kernel runs in; user pages are memory belonging to ordinary programs. SMEP prevents the use of a userspace disclosure gadget and forces the use of one in the kernel, so the attacker needs to know where that gadget is. The kernel loads itself at a random address, a defence called KASLR (Kernel Address Space Layout Randomisation), and the address of a kernel gadget depends on it. KASLR is like shuffling the furniture every time you leave the house so a burglar cannot plan ahead.

The original exploit uses Retbleed with Prime+Probe to defeat KASLR; this work uses a prefetch side channel instead because it is more reliable. A side channel is any observable side effect, such as timing, that leaks information the program was not supposed to reveal. Prime+Probe is a cache-based side channel that fills the cache with the attacker's data and then watches which parts get evicted. x86 has a prefetch instruction which tells the CPU to load data at a given address into the cache. The prefetch paper's authors found that the instruction executes more slowly when the target address is unmapped and more quickly when it is mapped and the mapping is in the TLB. The TLB is a small cache of recent address translations. The instruction never generates page faults even for unmapped addresses, so its running time can be timed precisely. The exploit prefetches all 512 possible addresses where the kernel can load itself and times the instruction: a quick execution means the kernel is mapped there. This KASLR bypass succeeds in more than 99% of cases, runs in less than 1 second, and works on every x86 CPU.

Step 4: Finding the physical address and the physmap

The second step is to allocate memory for the Flush+Reload array and find its address in the physmap. The array cannot be accessed through its userspace address from the gadget because of SMAP, which prevents the CPU from accessing userspace memory in supervisor mode. SMAP is the mirror image of SMEP: SMEP stops the kernel executing user code, SMAP stops it reading user data. The bypass is to access a supervisor mapping of the same memory. x86 CPUs have physically indexed and physically tagged caches, so the CPU uses the physical address to look up contents in the cache; accessing the array through two different mappings when encoding and when timing still works. In plain terms, the cache does not care which virtual door you came through, only which physical room you are in. All memory is mapped in the physmap at an address equal to the base of the physmap plus the physical address of the memory. The two parts are bruteforced separately, which is much more efficient (about 2^20 tries instead of 2^37). Bruteforcing means trying every possibility until one works.

A special disclosure gadget is used to bruteforce the physical address of the Flush+Reload array. The gadget adds the base of the physmap to an attacker-controlled value and dereferences the result. Dereferencing means following an address to read what is stored there. The array is allocated in a 2 MiB region aligned to 2 MiB in virtual memory. MiB is a megabyte; alignment means the address is a multiple of that size, like parking only in spaces numbered in steps of 2 MiB. Linux always uses a 2 MiB mapping for this, and the architecture requires that the physical address of a 2 MiB mapped page is also aligned to 2 MiB. This reduces the search space by 512 times compared to 4 KiB pages. The exploit iterates over every possible 2 MiB-aligned physical address and speculatively executes the gadget. A correct guess brings the start of the array into the cache, which is detected by timing a memory access in userspace. Assuming at most 2 TiB of physical memory, at most 2^20 guesses are needed, which takes about 20 seconds. TiB is a terabyte, a very large amount of memory.

The same gadget minus adding the base of the physmap, and the same technique, bruteforces the base address of the physmap. The base is randomised at boot time but always aligned to 1 GiB, so at most 2^17 guesses are needed. GiB is a gigabyte. The base address together with the physical address of the array gives the virtual address of a mapping for the array that the disclosure gadget can point to.

Step 5: Selecting a disclosure gadget

The gadget must satisfy a few requirements:

  1. It needs to be fast. The CPU must speculatively execute at least two loads, the second being a data-dependent load of the first. A load is an instruction that reads memory. The first load reads the secret and the second brings an element of the Flush+Reload array into the cache. The second load cannot start until the first is done, and if the CPU detects the mispredicted return too quickly the gadget fails. The gadget should be as short as possible and have no unnecessary instructions.
  2. It needs to scale the secret value. The gadget must multiply the leaked value by at least 64 before using it as an index into the array, because caches store memory in 64-byte lines on x86. A cache line is the smallest chunk the cache moves around. Without scaling, values such as 0 and 30 would land in the same cache line and be indistinguishable. The multiplier is the leak stride. If the stride is too low, hardware prefetching introduces noise; the authors experimentally determined that a stride of at least 512 is required to minimise false positives on AMD CPUs, and higher is better. Hardware prefetching is the CPU guessing which data you will need next and loading it early.
  3. It needs to use registers whose contents the attacker controls. Controllable values can also be retrieved from the store buffer, for example when written to the stack. The store buffer is a small queue of writes waiting to reach memory. The exploit targets the return from __x64_sys_mmap(unsigned long addr, unsigned long len, unsigned long prot, unsigned long flags, unsigned long fd, unsigned long off) and controls rdi and rsi, the first two arguments to the system call. The signature lists the six arguments mmap takes: address, length, protection, flags, file descriptor and offset.

The authors experimentally verified that Retbleed can only leak data if the secret data is in the L1d cache. L1d is the smallest and fastest data cache, sitting right next to the CPU core. Using performance counters, they confirmed that only the first load in the gadget executes when the secret is not in L1d. Performance counters are hardware counters inside the CPU that count events such as instructions or cache misses. AMD CPUs have a performance counter that counts loads crossing a cache line boundary, which are very rare; by making one or both loads cross a boundary and reading the counter, the executed loads can be seen clearly.

Step 6: Working around the missing sibling thread

The original exploit bypasses the L1d limitation by using a second thread to widen the speculation window. A thread is one sequence of instructions the CPU runs; a program can have several. The speculation window is how many instructions the CPU manages to run speculatively before it notices the guess was wrong. AMD Zen 2 CPUs have 2-way simultaneous multithreading: each core executes instructions from two threads at once, which the OS sees as two independent CPUs sharing execution resources such as the ALU and the L1 and L2 caches. The ALU is the arithmetic unit. Because the caches are shared, one thread can evict data belonging to its sibling. Evict means push out to make room. The original exploit uses this to evict the main thread's kernel stack from the cache before the CPU executes the target return, so the actual target address must be loaded from the L3 cache or RAM, which can take hundreds of cycles. The kernel stack is the kernel's scratch space for the current call. A longer speculation window lets the original exploit execute a gadget that takes longer to complete.

From the original on bughunters.google.com

This work cannot widen the window the same way, because the sandbox policy cannot be assumed to allow creating new threads and scheduling them on the sibling core. Before the target return executes, the kernel makes at least one function call which brings the stack into the L1d cache, and without new threads there is no way to evict it.

The authors experimentally observed that the secret data is sometimes not in the L1d cache even if the vulnerable system call is executed multiple times. Even if the first execution brings the secret into the cache, in some cases it has already been evicted by the time the call executes again. The L1d is very small (32 KiB) and shared competitively with the sibling thread; on a busy production machine another process is likely working on the same core, and some cache sets see more activity than others, so the success rate can depend on the address of the secret. A cache set is one group of slots inside the cache.

The solution is to execute the disclosure gadget multiple times within the same system call by training multiple returns. mmap is implemented in __x64_sys_mmap, which is tail-called by the system call dispatcher x64_sys_call. The dispatcher is the kernel code that receives a system call and routes it to the right handler. The tail call is not a jump to __x64_sys_mmap but an actual call instruction followed by pop rbp; ret, so as soon as __x64_sys_mmap returns, the CPU immediately executes another return without modifying rdi and rsi. pop rbp restores a saved register and ret returns. Both returns can be trained to execute the gadget. The first execution might not directly leak the data, but it at least brings it into the L1d, so the exploit can leak it during the second execution.

From the original on bughunters.google.com

Step 7: Building an ideal gadget with speculative ROP

Speculative ROP is used to create an ideal disclosure gadget that does not exist in the kernel. ROP, Return Oriented Programming, is a classic technique of chaining together small existing code fragments, each ending in a return, to make the program do something it was not written to do. Here the chaining happens speculatively. Unlike the gadget chaining techniques in the original speculative ROP paper, this version works on kernels that enable Spectre V2 mitigations (retpolines). A retpoline is a software trick that keeps the CPU from speculatively following an indirect branch. An ideal gadget loads one byte of secret data, multiplies it by the leak stride (ideally 4096 or more), and accesses the Flush+Reload array using the scaled secret as an index. No such gadget exists in the kernel, so the original exploit had to compromise with a non-ideal gadget using a 16-bit load and a stride of 2048. A 16-bit load reads two bytes at once. That still works, but to leak a byte the exploit must also know the value of the byte that comes before it. Sometimes the previous byte is known: the top 2 bytes of a kernel pointer are always 0xffff because of address canonicalisation, so the previous byte is known for every value stored after a pointer. Canonicalisation is the rule that makes the upper bits of an address copies of one bit. For a random address the previous byte is unknown and must be bruteforced, which makes the exploit less reliable. The requirement also introduces cascading failures: when leaking a large amount of data, spurious failures are always possible, and if the gadget relies on the previous leaked byte and that byte was wrong, the next byte will be wrong too. Sometimes this is detectable and fixable with retries, but not always.

The ideal gadget is constructed by combining 3 ROP gadgets, which are easy to find with any of the many ROP gadget finders. Retbleed lets the attacker train returns, so the return in each gadget can be trained to jump to the next one. The first gadget loads one byte from the secret, the second shifts the leaked byte by 12 bits, and the third accesses the Flush+Reload array using the scaled secret byte as offset. Shifting by 12 bits multiplies by 4096, which is the scaling the cache needs. Even though it contains 2 returns, the gadget executes quickly enough to leak data in the short speculation window and lets the exploit read any data without knowing the preceding byte.

From the original on bughunters.google.com

Step 8: Training returns without page faults

The original exploit trains kernel returns by jumping to the address of the disclosure gadget from userspace, which always causes a page fault and a SIGSEGV. A page fault is the CPU complaining that a memory access is not allowed; SIGSEGV is the signal Linux sends to a program that made such an access. Because SMEP forces the use of a kernel gadget, jumping to its address from userspace always raises a #PF, which Linux converts to a SIGSEGV directed at the exploit process. The sandbox policy lets the process set signal handlers, so the SIGSEGV can be handled and the exploit can recover, but this is inefficient. A signal handler is a function a program registers to run when a signal arrives. Every training, which happens multiple times per system call because of the gadgets used, triggers a series of context switches between userspace and kernel (#PF handler, signal handler, kernel, training code).

This slows the exploit down and breaks it when the process is ptrace-d. ptrace is the Linux facility that lets one process watch and control another, and sandboxes use it to police the programs they contain. When a ptrace-d process receives a signal, the tracer is notified and has to decide what to do; the additional context switches slow training further and can break it. The authors observed that under ptrace the leak gadget never works unless a second thread is used to widen the speculation window. They are not exactly sure why, but think the extra context switches evict critical exploit data from a cache. This matters because common process sandboxes such as gVisor and sandbox2 ptrace the sandboxed process, and the original exploit breaks under such a sandbox.

The fix is to execute the training jump speculatively, which still trains the return but does not raise a page fault. The Inception paper showed that branches can be trained using speculatively executed branches on AMD CPUs, and this also works for Retbleed: the training jump is executed speculatively rather than architecturally. Architecturally means in a way the program can actually see and that really happens. Even though the jump faults, its target is still added to the BTB and trains the return. As long as the jump is never executed architecturally, training never generates a page fault, because exceptions are raised at instruction retirement. Retirement is the final stage where an instruction's effects become real. A retpoline is used to trigger speculative execution: the capture_spec infinite loop in the original code is replaced with a jump to the training code, which is always executed speculatively but never architecturally. This is much faster than the original method because it avoids all the context switches, and it solves the ptrace problem for the same reason. Ironically, a Spectre mitigation that itself exploits a Spectre variant (Spectre RSB) is used to exploit a speculative execution bug. Spectre RSB targets the return stack buffer, the small stack of guesses the CPU keeps for return addresses.

From the original on bughunters.google.com

Step 9: Process discovery and memory translation

The exploit parses kernel data structures to discover other processes and then leaks data from them. Parsing means reading structured data and picking out the fields you want. The kernel keeps metadata about each thread in a task_struct object, one per thread. These objects are kept in a global linked list containing all threads and processes on the machine, as well as in a tree-like structure mirroring the process tree. A linked list is a chain where each item points to the next. The exploit starts from init_task, the task_struct representing the first process, which is at a known offset from the base of the kernel in memory, and traverses the linked list to build a list of all processes. It then reads each process's name and PID from its task_struct. PID is the process identifier, the number the OS uses to name a running program.

Once a target process is found, for example a password manager, the exploit needs to know where its data sits in physical memory. Because the physmap maps all physical memory linearly, data can be read from there once its physical address is known. What matters, however, is the data at a certain virtual address in another process, because reading pointers from another process yields virtual addresses, not physical ones. A pointer is a value that holds a memory address. The exploit reads and parses the page tables of other processes. A process's task_struct contains a pointer to an mm_struct, which contains a pointer to the process's top-level page table. Each entry contains the physical address of the next level table, down to the last level where each entry contains the physical address of memory. The x86 page table format is documented in the Intel SDM, the official Intel software developer manual, so the authors wrote code that parses other processes' page tables and performs memory translation. This can be used either to scan another process's memory for secrets with a regex, a pattern-matching expression, or to follow a chain of pointers to interesting secret data.

Step 10: Leaking host memory from inside a VM

The same strategy applies to leaking all memory on the host machine from inside an SVM-based VM such as KVM. The host is the real machine; the guest is the virtual machine running on it. The exploit works almost exactly the same way, except that it attacks the host machine's kernel instead of the VM's kernel.

AMD CPUs have Secure Virtual Machine (SVM), analogous to Intel's VT-x, which is the execution backend for most hypervisors on AMD CPUs (KVM, Xen, Hyper-V and others). A hypervisor is the software that runs virtual machines. SVM provides a guest mode used to run VMs; when a VM performs certain operations such as interacting with hardware, the CPU switches back to host mode and lets the VMM handle the operation (a VM exit). The VMM is the virtual machine monitor, the hypervisor component that manages guests. The hypervisor and the VM share a lot of CPU state such as the BTB, just as the BTB is shared between usermode processes and the kernel, so a VM can train return instructions executed by the hypervisor and attack it with Retbleed.

Host KASLR is broken with Jump over ASLR. The prefetch side channel used against the kernel from userspace does not work here, because the host kernel's code is not mapped in the VM's address space at all rather than being mapped but inaccessible, so it cannot be prefetched. Jump over ASLR exploits the shared BTB: when the guest causes a VM exit and the host handles it, the CPU adds the host kernel's branches to the BTB. If the guest later executes a branch at an address that collides with a host kernel branch in the BTB, the CPU uses the host entry to predict it, resulting in a misprediction. The guest detects mispredictions by timing how long the CPU takes to start executing at the correct target address, which gives an oracle for the host kernel's memory address and lets the attacker bruteforce it. An oracle here is simply a test that answers a yes or no question about a hidden value. In a way this KASLR bypass is very similar to Retbleed, but done in reverse.

The vulnerable return targeted in the host is the one from kvm_pv_send_ipi, which can be triggered from the guest using the vmmcall instruction with controlled registers. Hypercalls are similar to system calls and let a guest that knows it runs in a VM request host actions. SVM defines the vmmcall instruction, which typically causes a VM exit under a hypervisor and is used to implement hypercalls. The KVM_HC_SEND_IPI hypercall lets the guest send an interprocessor interrupt, a signal from one CPU to another. The implementation in kvm_pv_send_ipi has an early return that can be triggered by passing an invalid parameter. When this return executes, rsi, rdx, rcx and r8 all contain guest-controlled values that can be used to leak memory in the disclosure gadget. The vmmcall instruction is unprivileged and can be executed in a guest at CPL 3 (usermode), but KVM only executes the hypercall handler if it was executed in the guest at CPL 0. CPL is the privilege level; CPL 0 is the most privileged, CPL 3 the least. The restriction is bypassed by loading a small kernel module that makes the hypercall from guest CPL 0. A kernel module is code that can be loaded into the kernel to extend it. In a cloud computing scenario tenants typically have full control over the VM, so this is still a realistic attack. It lets the attacker leak all memory on the entire physical machine from inside a compromised guest, including the memory of all other VMs on the same machine.

Root cause

Retbleed is a branch type confusion in the CPU's branch prediction. Returns are normally predicted by a dedicated return predictor, but on vulnerable AMD CPUs the CPU can be trained to mistake a return for a regular indirect branch, in which case the indirect branch predictor takes precedence. Because the BTB is shared across privilege levels and is keyed by a hash of the branch's virtual address and the target of the last executed branch, an unprivileged process can insert a prediction for a kernel return by executing a colliding branch at a chosen address. The kernel then speculatively executes an attacker-chosen disclosure gadget with attacker-controlled registers, and the gadget encodes kernel memory into the cache through Flush+Reload.

The existing defences did not stop this. SMEP prevents executing userspace gadgets but not kernel gadgets, and SMAP prevents accessing userspace memory from the kernel but not accessing the physmap through a supervisor mapping. KASLR is defeated by side channels (prefetch from userspace, Jump over ASLR from a VM). The software mitigations that do exist, IBPB and jmp2ret, are expensive and are not free: the authors measured 5-6% overhead for jmp2ret and 55-60% for IBPB on Redis. Retbleed cannot be fixed with microcode updates and needs software mitigation.

Impact

Under ideal conditions (an idle machine) the exploit leaks data at about 13 KB/s with 100% accuracy. That is enough to list running processes and VMs on the host machine and to leak sensitive data from them in a targeted fashion, such as cryptographic keys. The exploit works from a sandboxed, unprivileged process with a restrictive policy and from inside a VM, where it can read the memory of all other VMs on the same physical machine.

The exploit can only be used by an attacker who already has arbitrary native code execution in a userspace process on the target machine or inside a VM. That includes code execution inside sandboxes such as Sandbox2, Sandboxed API, NSJail, minijail, the Chrome sandbox and gVisor. Sandboxing is usually used to contain code that is more exposed to untrusted input or more prone to bugs, so the authors consider this a realistic scenario. The KVM variant requires CPL0 code execution in a VM, which is compatible with the threat model of cloud services where the attacker is assumed to have root in their VM. Root is the all-powerful administrator account.

A current limitation is that the exploit needs the offsets of the target return and of the gadgets in the target machine's kernel. The authors think these images should be easy to obtain for a motivated attacker, especially with a stock distro kernel, and that with a few more months of work the limitation could be removed by guessing or bruteforcing the locations using a microarchitectural side channel as an oracle, as demonstrated by attacks such as BlindSide.

Fix

Retbleed has been addressed in newer CPU generations, starting with Zen 3 on AMD. Software mitigations are available in the operating system for the vulnerable generations and are enabled in the default configuration of the Linux kernel, but they are expensive. In Google Cloud, workloads that execute arbitrary user code have been moved away from the affected CPU models. Elsewhere, stricter sandbox policies have been implemented which prevent bugs like Retbleed from being exploited, or workloads have been upgraded to VM-based sandboxing, which is easier to harden against CPU bugs. The authors are also investing in more holistic mitigation strategies that mitigate bugs such as Retbleed at the host level.

Variants to test

  1. Other vulnerable returns in the kernel. The exploit can be adapted to target return instructions in other system call implementations or elsewhere in the kernel.
  2. Other hypercall handlers in KVM. The VM variant targets the early return in kvm_pv_send_ipi. Other hypercalls with early returns and guest-controlled registers are candidates.
  3. Other sandboxes with MAP_FIXED and RWX or mprotect. Any sandbox that allows mapping code at a chosen address and making it executable is a candidate.
  4. ptrace-based sandboxes. The speculative training technique removes the page fault and the context switches, so it should work under gVisor, sandbox2 and similar tracers.
  5. KASLR bypasses. The prefetch side channel works on every x86 CPU from userspace; Jump over ASLR is used from a VM.
  6. Removing the kernel image requirement. The authors suggest bruteforcing the locations of vulnerable returns and gadgets with a microarchitectural side channel as an oracle.

Glossary

  • ALU: the arithmetic logic unit inside a CPU, which performs maths and logic operations.
  • Architectural: an effect a program can actually see and that really happens, as opposed to a speculative one that is thrown away.
  • Basic block: a straight run of instructions with no branch in the middle.
  • Branch: a point where a program can go one of two ways, like a fork in a road.
  • Branch target buffer (BTB): a hash-table-like structure in the CPU that remembers where indirect branches went last time.
  • Bruteforce: trying every possibility until one works.
  • Bubble: an idle cycle in a CPU pipeline that wastes work.
  • Cache: a small, very fast memory inside the CPU holding recently used data.
  • Cache line: the smallest chunk of memory the cache moves around, 64 bytes on x86.
  • Cache set: one group of slots inside a cache.
  • Canonicalisation: the rule that makes the upper bits of an address copies of one bit.
  • Context switch: the moment the CPU stops running one task and starts another.
  • CPL: the privilege level of the code being run; CPL 0 is most privileged, CPL 3 least.
  • Disclosure gadget: a short sequence of existing instructions that, run speculatively, reads a secret and leaves an observable trace.
  • Evict: push data out of a cache to make room.
  • Flush+Reload: a cache side channel that removes data from the cache, lets a sender touch one slot, and times accesses to see which slot was touched.
  • Guest: a virtual machine running on a host.
  • Hash table: a structure that stores things by computing a short fingerprint of a key; different keys can collide in the same slot.
  • Host: the real physical machine that runs virtual machines.
  • Hypercall: a request from a guest to its hypervisor, similar to a system call.
  • Hypervisor: the software that runs and manages virtual machines.
  • IBPB: a mitigation that clears the branch predictor's state on context switches.
  • Indirect branch: a jump whose destination is held in a register or memory rather than written into the instruction.
  • JIT compiler: software that turns code into machine instructions while it runs.
  • jmp2ret: a mitigation that replaces every kernel return with a jump to a single sanitised return.
  • KASLR: Kernel Address Space Layout Randomisation, which loads the kernel at a random address each boot.
  • Kernel: the core of the operating system.
  • Kernel module: code that can be loaded into the kernel to extend it.
  • L1d: the smallest and fastest data cache, sitting next to the CPU core.
  • Linked list: a chain where each item points to the next.
  • Load: an instruction that reads memory.
  • Microcode: firmware inside the CPU that can be updated.
  • MiB / GiB / TiB: units of memory size, megabyte, gigabyte and terabyte.
  • Offset: a distance from a known starting point, used to find a specific piece of code or data.
  • Oracle: a test that answers a yes or no question about a hidden value.
  • Overhead: work a machine does for a defence instead of for the user.
  • Page fault: the CPU complaining that a memory access is not allowed.
  • Page tables: the kernel's lookup tables mapping virtual addresses to physical memory and recording permissions.
  • Parsing: reading structured data and picking out the fields you want.
  • Physmap: the kernel's linear mapping of all physical memory.
  • PID: the process identifier, the number the OS uses to name a running program.
  • Pipeline: the assembly-line arrangement of a CPU, where each instruction moves through several stages.
  • Pointer: a value that holds a memory address.
  • Prefetch: an instruction that asks the CPU to load data into the cache ahead of time.
  • Prime+Probe: a cache side channel that fills the cache with the attacker's data and watches which parts get evicted.
  • ptrace: the Linux facility that lets one process watch and control another.
  • Register: a tiny storage slot inside the CPU.
  • Retirement: the final stage where an instruction's effects become real.
  • Retpoline: a software trick that keeps the CPU from speculatively following an indirect branch.
  • Return: the instruction that ends a function and goes back to its caller.
  • Return stack buffer (RSB): the small stack of guesses the CPU keeps for return addresses.
  • ROP (Return Oriented Programming): chaining small existing code fragments, each ending in a return, to make a program do something it was not written to do.
  • Root: the all-powerful administrator account.
  • Sandbox: a restricted environment that stops a program from touching anything outside it.
  • Seccomp: the Linux feature that lets a sandbox list which system calls a program may make.
  • Shellcode: a small blob of machine instructions an attacker can drop into a running program.
  • Side channel: any observable side effect, such as timing, that leaks information a program was not supposed to reveal.
  • SIGSEGV: the signal Linux sends to a program that made an illegal memory access.
  • SMAP: Supervisor Mode Access Prevention, which stops the kernel reading userspace memory.
  • SMEP: Supervisor Mode Execution Prevention, which stops the kernel executing userspace code.
  • Speculation window: how many instructions the CPU manages to run speculatively before it notices a wrong guess.
  • Speculative execution: the CPU guessing what the program will do next and starting that work early.
  • Store buffer: a small queue of writes waiting to reach memory.
  • SVM: AMD's Secure Virtual Machine, the hardware feature that runs virtual machines.
  • System call: how a normal program asks the operating system to do something on its behalf.
  • Tail call: a call made as the very last action of a function, which the compiler can turn into a jump.
  • Thread: one sequence of instructions the CPU runs; a program can have several.
  • TLB: a small cache of recent address translations.
  • Training: teaching a branch predictor by repetition so it expects a chosen target.
  • Virtual machine (VM): a computer simulated in software on a real machine.
  • VM exit: the moment the CPU switches from running a guest back to the hypervisor.
  • VMM: the virtual machine monitor, the hypervisor component that manages guests.
  • XOR: a simple bit operation that mixes two values together.

Similar reports

View all

Same bug class and techniques, clearest first.

Memory corruption

The lesson behind this report.

Native code reads or writes memory it should not: overflows, use-after-free, type confusion. The core of browser, kernel and parser bugs.