Skip to content
Memory corruption Write-up Advanced

CVR: The Mines of Kakadûm

The text describes memory corruption vulnerabilities in a third-party JPEG 2000 image library called Kakadu, and introduces a technique called 'Conditional Corruption' to achieve remote code execution. It claims that exploiting these vulnerabilities typically requires knowledge of the target environment, but the technique overcomes that challenge.

bughunters.google.com

Published on bughunters.google.com

Exploits leveraging memory corruption vulnerabilities typically require some knowledge about the target environment, such as the binary, OS, and allocator. These insights are required to e.g. prepare the heap and deploy ROP chain gadgets.

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

Context

Google's Cloud Vulnerability Research team (CVR) set out to exploit memory corruption in server-side software where the attacker has no access to the source code or binary, and where the deployment environment is unknown. The target of this research is Kakadu, a third-party JPEG 2000 image library. In a 2007 study Kakadu outperformed other JPEG 2000 libraries, and it describes itself as the leading JPEG 2000 development kit.

The report presents two vulnerabilities in Kakadu: an arbitrary file read and a heap out-of-bounds write caused by multiplication with a signed integer. It then documents how the two were combined into a remote code execution exploit against an unknown environment, using a technique CVR calls "Conditional Corruption".

The code snippets in the report are taken from decompiled code of the freely available demonstration binaries of Kakadu, simplified for clarity, and are based on version 8.41 of the demo binaries.

Setup

There are no accounts, roles or credentials in this research. The relevant preconditions are:

  • The target processes attacker-supplied JPEG 2000 images with Kakadu, in an environment the attacker cannot inspect.
  • The attacker can view the output image produced after processing.
  • The deployment may sit behind a load balancer, so consecutive requests may be handled by different workers.
  • The allocator in the target is tcmalloc.

The team read the JPEG 2000 standard and the Kakadu source code to understand the parsing flow and internal data structures, and used fuzzing to discover an internal variant of TALOS-2017-0309, an out-of-bounds write on the heap due to signed integer multiplication.

Finding it

JPEG 2000 background

The file format can be divided into two concepts: Boxes and Codestream Segment Markers.

Boxes are Length-Type-Value containers for metadata about the image, such as width, height and colour information, and can also hold the position of the actual codestream within the image. A Box has these fields:

Field Size Description
LBox 32 bits Length of the box.
TBox 32 bits Box type, typically a 4-byte ASCII sequence with the box name. For example, ftyp is the name for the File-Type box.
XLBox 64 bits Extended length, only present if LBox is set to 1.
DBox Variable Box data (variable length based on LBox and the box type).

Boxes can contain other Boxes. For example, the JP2 header Box may contain Boxes that provide more information about the image, such as a colr (Colour) Box. The following graphic shows how an image could be organised:

From the original on bughunters.google.com

The codestream contains the actual image data and sits inside a Codestream Box. It consists of Type-Length-Value containers called Segment Markers. The first 2 bytes are a unique value telling the parser which marker is being parsed; markers always begin with 0xFF, and the second byte can be any value from 0x01 to 0xFE. The next two bytes are a length field for the marker-specific data that follows, and because that field is only 2 bytes, a Segment Marker can have a maximum length of 65535.

The decompressed image is made up of rectangular tiles, all the same size. Each tile's data is compressed individually and can have completely different decoder parameters, such as the number of decoding passes. There can be up to 65535 tiles, and they may appear in the codestream in arbitrary order. Each tile must contain at least two markers, Start-of-Tile (SOT) and Start-of-Data (SOD).

The SOT layout is:

Field Size Description
SOT 16 bits Segment Marker (0xFF90).
Lsot 16 bits Marker segment length in bytes (not including the marker).
Isot 16 bits Tile index used to calculate the (x, y) coordinates of a tile.
Psot 32 bits Length of the tile data.
TPsot 8 bits Tile-part index, zero if there are no tile-parts.
TNsot 8 bits Number of tile-parts.

The SOD marker is one of the simplest and simply contains the compressed tile data. It has no length field of its own; its length is determined by the Psot field of the preceding SOT marker.

Field Size Description
SOD 16 bits Segment Marker (0xFF93).
Data Variable Tile data (variable length).

The X, Y coordinates of a tile can be calculated from the tile index, the image width/height and the tile width/height. From the SIZ marker these values are Xsiz, Ysiz, XTsiz and YTsiz respectively. The layout of tiles by index is shown in the diagram below.

From the original on bughunters.google.com

Tile dimensions in context of the larger image.

Service discovery

The team crafted images that rely on Kakadu quirks and features implemented only by Kakadu, to fingerprint endpoints that use Kakadu to convert JPEG 2000 images. The feature relied on is "Codestream fragmentation", defined in the second part of the JPEG 2000 standard. It is described further under Vulnerability Discovery, because it also allows an arbitrary file read.

Exploitation

Step 1: Arbitrary file read via JPX fragmentation

The ISO/IEC 15444-2 standard specifies an extended format for JPEG 2000 files called JPX. One feature of this extended format is the ability to fragment an image's codestream within the same file, across multiple files, or across multiple URLs on the Internet. As described in the specification, this optional extension is inherently vulnerable.

Kakadu implements the feature, reading data from local files referenced by a JPX image and using it to build the image's codestream. A high level visualisation of the JPX fragmentation feature is shown below:

From the original on bughunters.google.com

To use it, a JPX image needs to include:

  • A single Data Reference Box, which contains a list of Data Entry URL Boxes, each of which contains the path to a file within the local filesystem as a null-terminated string.
  • A Fragment Table Box, which contains a single Fragment List Box that specifies fragments from which to build the continuous codestream.

The Fragment Table Box has the following fields:

Field Size Description
NF 16 bits Total number of fragments.
OFFi 64 bits Offset to the start of the i-th fragment in the file specified by DRi, relative to the first byte of the file.
LENi 32 bits Length of the i-th fragment.
DRi 16 bits Data reference index, determines which file to load fragment data from. If zero, the current file is used.

By crafting JPX images with these Boxes, the team could inject into the codestream precise amounts of bytes read at specific offsets from specific local files, and have resulting images with such data encoded within their properties or pixels. Assuming an environment where the output image can be viewed after processing, this achieves an arbitrary file read.

Size-based read

The first proof of concept was a JPX image that would read the first and second bytes (starting from a given offset) of a given file. The SIZ Segment marker contains multiple 4-byte fields holding the decompressed image's width and height. Since the width and height of the exploit image are visible, some of those values could be substituted with bytes from a local file and derived from the decompressed image's dimensions.

Neither width nor height can be zero, and both are 32-bit unsigned integers, so each was encoded as (0x00, 0x00, 0x01, read byte). Each value therefore ends up as 0x100 plus the value of the respective read byte, giving a range from 0x100 to 0x1FF.

Because both the file to be read and the starting offset are controlled, this is already an exploitable arbitrary file read: a full file can be leaked by uploading images with increasing starting read offsets. However, it was insufficient for leaking /proc/self/maps, because only 2 bytes could be leaked per request. Even with increasing offsets, the contents change depending on the worker handling the request, so the output file would be a mix of different workers. Leaking through the image size could be improved slightly by accurately leaking up to 3 bytes at once in each property, so 6 bytes per JPX image, but that would require huge image sizes likely to exceed safety limits, and it still would not be enough for highly variable files.

Dynamic tile read

To leak more data in a single image, the team needed either a single segment marker with a large array of data that could be reliably decoded from the output image, or a segment marker that could be repeated to produce a noticeable effect.

The tile data itself is tempting: a single large tile with a large number of leaked bytes in its compressed pixel data. But the compression applied to tiles made this impossible. Tile data is encoded with a variable length encoding technique that does not permit the 0xFF byte in the stream. JPEG 2000 compression is also extremely complex, using wavelet transforms with dynamic coefficients, so the length and meaning of the tile changed based on the leaked data in a way that almost guaranteed parsing errors.

The team settled on the Comment (COM) marker, which includes an arbitrary number of bytes of unstructured data. The COM marker is not saved to the output image, so the Ccomi bytes could not be leaked directly, but it is valid in any part of the codestream and has variable length, which made it useful.

The COM marker has the following fields:

Field Size Description
COM 16 bits Segment Marker (0xFF64).
Lcom 16 bits Marker segment length in bytes (not including the marker).
Rcom 16 bits String encoding, 0 for binary, 1 for Latin.
Ccomi 8 bits Byte of comment data (variable length).

The mechanism leaks a single byte per tile with a jump table based on leaked bytes, using three types of codestream marker: Start-of-tile (SOT), Comment (COM) and Start-of-Data (SOD).

For each tile, a COM marker is included with variable length depending on a leaked byte (d<sub>i</sub>). A table of 256 entries follows, each with tile data and another COM marker. In each entry, the tile data encodes a different pixel colour. Each entry is exactly 256 bytes long, so depending on the value of the leaked byte a different entry is "chosen". An example of this encoding is shown below:

From the original on bughunters.google.com

SOT+COM table layout.

This mechanism leaked 20KB of data in a single image. Theoretically 65535 bytes could be leaked (the maximum number of tiles), but Kakadu also limits the number of fragments to 65535 and the exploit required about 3 fragments per leaked byte.

Because the pixel data is directly influenced by the leaked bytes, the image itself visualises the leaked data, which can also be decoded by examining the pixel values. The following image demonstrates what an output image could look like, in this case leaking bytes from Kakadu's kdu_expand binary via /proc/self/exe.

From the original on bughunters.google.com

Info leak of /proc/self/exe with Kakadu's kdu_expand binary.

This would have enabled an attacker to build ROP chain gadgets and understand the internals of the service, allowing remote code execution without previous insider knowledge. /proc/self/maps and /proc/self/environ could also be leaked to understand the targeted environment, and another attack path opened by this primitive is leaking memory contents via /proc/self/mem.

Step 2: Heap overflow via signed integer multiplication

The SIZ Segment Marker contains information about the size of the decompressed image. The relevant fields are:

Field Size Description
SIZ 16 bits Segment Marker (0xFF51).
Lsiz 16 bits Marker segment length in bytes (not including the marker).
Xsiz 32 bits Width of the reference grid.
Ysiz 32 bits Height of the reference grid.
XTsiz 32 bits Width of one reference tile with respect to the reference grid.
YTsiz 32 bits Height of one reference tile with respect to the reference grid.
Csiz 16 bits Number of components in the image (e.g. RGB).

The final size of decompressed image data in memory is calculated as:

Height * Width * Number of Components

Height and Width correspond to Xsiz and Ysiz and can be fully controlled. The number of Components can also be controlled via the Csiz field, but is limited to 16384 by the standard.

The multiplication does not overflow when making the allocation for the output image buffer, because Kakadu calls a Google internal callback that uses 8-byte integers:

Text
  size_t buf_length = 0;
  size_t area = 0;
  if (!util_intops::SafeMultiply(width, height, &area)) {
    LOG(ERROR) << "Integer overflow when computing width*height.";
    return false;
  }

  if (!util_intops::SafeMultiply(area, num_components, &buf_length)) {
    LOG(ERROR) << "Integer overflow when computing area*num_components.";
    return false;
  }

However, an integer overflow occurs while writing the image data, because Kakadu continues to use 4-byte variables. When writing a multi-row tile, Kakadu writes the tile data row by row, meaning it writes Width * Number of Components bytes per row. Once the first row has been written, it advances a pointer to the next row by adding the result of Width * Number of Components to the pointer. This addition is done using a signed, 4-byte integer, so the value can overflow and the pointer points outside the image.

The row_gap is calculated in the snippet below, which is the 4-byte signed integer added to the row pointer when writing row by row:

Text
00436eb4  int32_t row_gap
00436eb4  if (row_gaps == 0)
00436f10    row_gap = sample_gap * component_state->row_width
00436eb6  else
00436eb6    row_gap = *(row_gaps + i)
00436ebd  *(component_state - 8) = row_gap

Because the width can be controlled, the team could write controlled data backwards in memory with a controlled distance. The following image visualises the out-of-bounds write logic:

From the original on bughunters.google.com

Step 3: The exploitation plan

With the two primitives, the plan to achieve remote code execution impact was:

  1. Use the info leak to read /proc/self/maps and learn the address of the heap, executable, etc.
  2. Send a second image to exploit the heap overflow, corrupting a predictable object and obtaining code execution in the service. The image reads a known byte from /proc/self/mem based on the address leaked in step 1. If this step fails, the exploit is not triggered. This ensures the exploit triggers on the same worker with the known address layout.
  3. Run proof-of-concept code to verify remote code execution impact.
  4. Perform all of the above with no impact to users.

Step 4: Understanding the heap layout

Using the heap overflow, the team could write backwards in memory by a known, large distance. To exploit this, they had to understand where the image would be allocated on the heap, because its location determined what data could be overwritten.

Because the image width is large, the memory requested for pixel data is over 4GB. The target uses tcmalloc, which has specific behaviour with large allocations. If the heap does not have available memory for the large allocation, tcmalloc expands the heap and places the allocation in a predictable location. This effect can be observed in /proc/self/maps before and after the allocation. When submitting an image of width 0x0040000000, the requested allocation is 0x0200000000 bytes.

Text
      # /proc/self/maps before allocation
      256400000000-256432600000 ---p 032600000 00:00 0  [anon:tcmalloc_region_NORMAL]
      256432600000-25643d600000 rw-p 00b000000 00:00 0  [anon:tcmalloc_region_NORMAL]
      25643d600000-25643d7c0000 rw-p 0001c0000 00:00 0  [anon:tcmalloc_region_NORMAL]
      25643d7c0000-256440000000 rw-p 002840000 00:00 0  [anon:tcmalloc_region_NORMAL]
Text
      # /proc/self/maps after allocation
      256400000000-256431400000 ---p 031400000 00:00 0  [anon:tcmalloc_region_NORMAL]
      256431400000-25643d600000 rw-p 00c200000 00:00 0  [anon:tcmalloc_region_NORMAL]
      25643d600000-25643d7c0000 rw-p 0001c0000 00:00 0  [anon:tcmalloc_region_NORMAL]
      25643d7c0000-256640000000 rw-p 202840000 00:00 0  [anon:tcmalloc_region_NORMAL]

To accommodate the request, tcmalloc extends the 25643d7c0000-256440000000 range to 25643d7c0000-256640000000. The increase is exactly 0x0200000000 bytes and the image buffer is allocated at address 256440000000. Knowing the address of the image buffer allows the exact addresses overwritten by the heap overflow to be calculated.

Step 5: The 808080 Apocalypse

One problem with the heap overflow primitive is the large amount of data that must be written to the heap. Due to the large allocation, there is often a large gap between the image buffer and any useful objects on the heap. The team experimented with different overflow distances and tile widths to find optimal values for more reliable objects, crafting an image with a single tile containing pixel data of all 0x41 and a dynamic width and tile width, then fuzzing those values against a copy of the production job and recording crash locations and registers for each attempt.

After a few hours of experimentation, they were crashing reliably in the following objects related to Kakadu:

  • kd_supp_local::jx_composition::~jx_composition
  • kdu_supp::jp2_input_box::close
  • kd_core_local::kd_precinct_server::get
  • kd_supp_local::jx_codestream_source::~jx_codestream_source
  • kd_supp_local::jx_layer_source::~jx_layer_source
  • kd_supp_local::kdsd_tile::process
  • kdu_core::kdu_params::access_unique
  • kdu_supp::kdu_stripe_decompressor::pull_common
  • and a few crashes in non-Kakadu objects

However, while they sometimes saw segfaults on a controlled address (e.g. 0x4141414141414141), they often saw segfaults for the address 0x8080808080808080. The majority of crashes at the time looked something like the following:

From the original on bughunters.google.com

That value was nowhere in the input pixel data, but was being sprayed everywhere over the heap, corrupting random objects with 0x80 bytes and segfaulting unpredictably. They dubbed this the "808080 Apocalypse". After a few hours of head scratching, they realised that Kakadu was writing the crafted 0x41 tile, followed by hundreds of tiles with "uninitialised" pixel data set to 0x80, an arbitrary default value used by Kakadu.

From the original on bughunters.google.com

The 808080 Apocalypse would make exploitation incredibly difficult, since these 0x80 tiles almost always clobbered random objects on the heap. However, within the tile processing code, the team found a Kakadu-specific technique to write a single tile and then cause an error, skipping the writes for uninitialised tiles. The Start of tile-part (SOT) marker contains a 16-bit parameter Isot, which indicates the tile index of the current tile. If Kakadu encounters a tile index greater than the number of possible tiles in the image, it throws an error and stops writing pixel data. The exploit was crafted using the following tiles to write exactly one tile worth of controlled data:

From the original on bughunters.google.com

Rendering this image threw the following error:

Text
Corrupt SOT marker segment found in codestream: tile-number lies outside
  the range of available tiles derived from the SIZ marker segment.

After collecting metrics on the observed crash fingerprints and rolling out this fix to the exploit, the team observed a sharp increase in ~jx_composition crashes and the 808080 Apocalypse had ended.

From the original on bughunters.google.com

Visualization of crash fingerprint prevalence over time.

Step 6: Finding a reliable gadget on the heap

With the 808080 Apocalypse solved, the team continued searching for an object to target on the heap. Because tcmalloc utilises randomisation, finding such a gadget turned out to be fairly difficult. However, since the memory location of the image buffer was reliably known, and the write backwards into the heap happens at a controlled offset up to -2GB, they had an "arbitrary heap write primitive" if the worker's heap was smaller than 2GB. That means any object on the heap could be overwritten, given its location is known.

Global heap pointers

The first approach was to use the arbitrary file read to read /proc/self/mem, looking for a global variable that points into the heap. This would bypass tcmalloc's randomisation and write at a known location, which in theory could have resulted in a 100% reliable exploit. The large issue was that although a known object could be reliably written to, the size written was not controlled, around 20KB on average. No exploitable object of that size pointed to by a global variable was found, so other random data on the heap would be overwritten, often leading to an uncontrolled crash as another thread used the corrupted data before the target object did.

The team discussed reading the data around the target address and restoring the heap data to prevent these crashes, but did not follow this approach: they discovered another gadget and concluded that even with restoration there would still be a race condition where the data is corrupted and would lead to a crash.

Large allocation to prevent randomisation

The next approach was to make Kakadu allocate an array of objects that, when corrupted, would yield a reliable primitive such as a vtable overwrite. After some searching, they found such a primitive, triggered by including a Composition Layer Extensions Box from Part 2 of the JPEG 2000 standard. The reduced code snippet below shows the attacker-controlled allocation:

Text
// from kdu_expand
00476140 jx_container_source::parse_info(struct jx_container_source* this)
0047620c   if (jp2_input_box::read(&curr->__offset(0x140).q, &Mjclx) == 0)
00476466     box_reading_error:
00476466     kdu_core::kdu_error::kdu_error(&var_68)
00476473     kdu_core::kdu_error::put_text(&var_68)
00476473     goto label_47647b
00476221    if (jp2_input_box::read(&curr->__offset(0x140).q, &Cjclx) == 0)
00476221      goto box_reading_error
00476236    if (jp2_input_box::read(&curr->__offset(0x140).q, &Ljclx) == 0)
00476236      goto box_reading_error
0047624b    if (jp2_input_box::read(&curr->__offset(0x140).q, &Tjclx) == 0)
0047624b      goto box_reading_error
00476260    if (jp2_input_box::read(&curr->__offset(0x140).q, &Fjclx) == 0)
00476260      goto box_reading_error
0047626c    if (jp2_input_box::read(&curr->__offset(0x140).q, &Sjclx) == 0 && Tjclx != 0)
00476453      goto box_reading_error
// ...
00476875    struct j2_memsafe* allocator = curr->allocator.__offset(0x48).q
00476893    // 0x2c0 = size of individual jx_track_source objects
00476893    // 8 = alignment of allocation
00476893    // Tjclx = number of jx_track_source objects
00476893    struct jx_track_source *track_sources
00476893      = j2_memsafe::alloc(allocator, 0x2c0, 8, Tjclx)

An attacker can fully control the Tjclx value and make Kakadu allocate an array of hundreds of megabytes. This had two advantages: the team would never corrupt data outside of the array, and the size of the array made it highly likely to be "hit" with a memory corruption distance that was reliable between the array and the output image buffer.

Write-what-where

The destructor of each jx_track_source object would at some point call the destructor of jx_composition, which in turn would call the jp2_input_box::close() method on a jp2_input_box object that was an inline member. Assuming all fields in the inline objects are fully controlled due to the memory corruption, this triggers an arbitrary write primitive. A simplified version of the corresponding close() code is shown below:

Text
0041e800  uint64_t kdu_supp::jp2_input_box::close(struct jp2_input_box* this)
0041e812    if (this->is_opened != 0)
0041e840      bool dynamic_length = this->dynamic_length
0041e847      this->is_opened = false
0041e86d      struct jp2_input_box* parent_box = this->parent_box
0041e874      if (parent_box != 0)
0041e876        uint64_t next_box_position = this->next_box_position
0041e8b9        if (next_box_position == 0 && dynamic_length != 0)
0041e8bb          uint64_t box_position = this->box_position
0041e8c2          parent_box->__offset(0x96).b = 1
0041e8c9          parent_box->box_position = box_position

parent_box is a pointer that can be fully controlled. If the dynamic_length value is set to true and next_box_position is 0, the code writes to parent_box-152 (the offset of the box_position member), with a fully controlled 8-byte value. Since an array of these objects can be corrupted, the arbitrary write can be triggered multiple times, making it a powerful primitive.

Unfortunately, while the jx_track_source array was reliably allocated near the image buffer, the exact offset varied. To avoid unexpected behaviour, the precise object alignment modulo the size of the object (696 bytes) had to be known, so that the heap overflow could precisely overwrite a slice of objects from the array.

Step 7: Exploit reliability engineering, the Kha-Kha Slide

Or, "finding a jx_comp needle in a haystack".

The team puzzled over the object alignment problem for some time, hoping that with enough experimentation they could find alignments that were more likely based on the heap layout. There were some patterns: approximately 14% shared the same offset, but this was not reliable enough for production, since guessing wrong meant crashing the service.

Using experience from crafting the Dynamic Tile info leak, they created a mechanism within the codestream to dynamically change the tile data written by the heap overflow, based on data from the heap itself read via /proc/self/mem. They called it the Kha-Kha Slide.

From the original on bughunters.google.com

At the start of the slide, an SOT is included whose length encompasses the entire slide. This means that somewhere within the slide there must be an SOD with tile data, but there can also be an arbitrary number of other markers before the SOD. A series of 696 lookup tables is then crafted, one for each possible offset of the jx_composition object. Using this mechanism, the exploit effectively searches memory for a specific byte value that tells it the object offset.

Each table starts with a COM marker whose length is based on a leaked byte from /proc/self/mem. Within the table are 256 additional COM markers, one for each possible leaked byte value. Each COM has a variable length to jump over the other markers and into the "COM S" marker at the end of the table. If the byte value being looked for is found (0x41 in the diagram), the parser jumps directly to a SOD marker with tile data specifically crafted for that offset. If the byte is not found, the "COM S" marker jumps over the exploit and onto the next COM table. The exploit proceeds through each COM table, looking at a different address each time, until one of them finds the byte and triggers the exploit.

The darker coloured path in the diagram shows an example path through the COM tables. For example, if the first few bytes of memory are 01417fff, the parser will see the following markers:

Text
SOT 00 0a 00 01 TL 00 01

COM 01 06 00 00 41 41 <256 bytes>

COM L2 L2 00 00 <L2 bytes>

COM SS SS 00 00 41 41

COM 41 06 00 00 41 41 <16640 bytes>

SOD exploit[d2]

COM E2 E2 00 00 41 41
...

SOT 00 0a ff ff 00 00 00 00 00 01

The jx_composition object is mostly initialised to zero, with a few heap pointers and vtables. One of these vtables can be chosen with a unique byte in the pointer. For the production binary, the vtable address chosen was 0x3f5a04f0. Its least significant byte, 0xf0, was unique within the jx_composition object, giving an oracle byte to search for with the Kha-Kha Slide.

The Kha-Kha Slide increased reliability significantly, but one last bit of randomness remained: the load balancer. The exploit requires two requests, one to leak /proc/self/maps and the next to perform the heap overflow, and different workers might process them. If that happened, the exploit would have the wrong addresses and certainly segfault. To harden the second payload against invalid addresses, the team added one last info leak early in the codestream. While reading fragments, if fread() returns zero, Kakadu exits early and sets an error for the current marker. For most markers, Kakadu simply ignores the error and continues parsing. For the SIZ marker, however, Kakadu throws the following error and skips all further parsing:

Text
Code-stream must contain a valid SIZ marker segment, immediately after the SOC marker!

If the exploit seek()s to an address in /proc/self/mem that is not mapped, the subsequent fread() returns zero (corresponding to an I/O error). A known value from /proc/self/mem can therefore be embedded within the SIZ marker such that, with a valid memory layout, the value completes the SIZ marker, and with an invalid memory layout, the exploit bails out and skips processing the image altogether. The Rsiz field of the SIZ marker was chosen, which has a null byte in it, and for the leak address the first null byte in the memory region containing the executable. That crossed the final reliability hurdle.

Step 8: Putting it together

The team used an arbitrary file read in Kakadu to obtain information about the server environment. Similar effects can be achieved with an arbitrary memory read primitive, an example being another bug CVR discovered in PostgreSQL that allowed the attacker to fully obtain the target binary.

The same file-read primitive was then used for "Conditional Corruption", a technique CVR published in 2023 when targeting ClamAV, which was subsequently awarded a Pwnie award. This technique allowed the team to target the same worker they leaked information from in the first step of the exploit, greatly improving reliability and removing chance from the exploit. "Conditional Corruption" was used again to verify the exploit payload would overwrite the correct data on the heap before triggering, ensuring reliability. This gave a write-what-where primitive.

With the info leak and the write-what-where primitive, the team could locate and modify global variables, hijack the control flow of the process and execute arbitrary code without impact to users.

Root cause

The arbitrary file read is a design consequence of the JPX fragmentation feature from ISO/IEC 15444-2: a JPX image can reference local files by path and splice bytes from them into the codestream, and Kakadu implements this as specified. The report describes the optional extension as inherently vulnerable.

The heap overflow is a signedness and width mismatch. The allocation size is computed with 8-byte integers through a Google internal callback, so it does not overflow. The write path, however, keeps using 4-byte variables: the per-row advance is a signed 4-byte integer (row_gap), so a controlled width makes it overflow and the row pointer lands outside the image buffer. The allocation uses safe 8-byte multiplication, while the write path uses a signed 4-byte row advance.

Impact

Under the conditions described, an attacker who can submit images and view the output can read arbitrary local files, including /proc/self/maps, /proc/self/environ, /proc/self/exe and /proc/self/mem, and can leak memory contents. That is enough to build ROP chain gadgets and understand the internals of the service without insider knowledge. Combined with the heap overflow, the team achieved remote code execution impact, hijacking the control flow of the process and executing arbitrary code without impact to users. The report notes it is likely that major companies are affected, including a Google service. The exploit assumes the output image can be viewed after processing, and the write primitive covers a controlled offset up to -2GB only if the worker's heap is smaller than 2GB.

Fix

The report does not describe a patch for either vulnerability. The only change it documents is on the exploit side: crafting the tiles so that a tile index outside the range derived from the SIZ marker makes Kakadu throw an error and stop writing pixel data, which skips the writes for uninitialised tiles and ends the 808080 Apocalypse.

Variants to test

  • JPX fragmentation on other decoders. Submit a JPX image with a Data Reference Box pointing at a local path and a Fragment Table Box with DRi set to that entry. A positive result is output whose dimensions or pixels encode bytes from the referenced file.
  • Size-based leak. Encode SIZ width and height as (0x00, 0x00, 0x01, read byte) and compare the decompressed dimensions against the file contents. A positive result is dimensions in the 0x100 to 0x1FF range that track the file's bytes.
  • Dynamic tile leak. Build per-tile COM jump tables of 256 entries of exactly 256 bytes each, with tile data encoding a different pixel colour per entry. A positive result is an output image whose pixel values decode to file contents, up to 20KB per image in this report's setup.
  • Signed row advance. Set a large Xsiz with a multi-row tile and observe whether the row pointer wraps.
  • Uninitialised tile spray. Use a single tile of controlled pixel data and watch for a default fill value (here 0x80) appearing across the heap. A positive result is crashes on an address built from that default value rather than the controlled one.
  • Tile index out of range. Set Isot beyond the number of tiles derived from SIZ and check whether the decoder errors out before writing uninitialised tiles. A positive result is the "tile-number lies outside the range" error with no further pixel writes.
  • Composition Layer Extensions Box. Supply a Tjclx value that forces a large jx_track_source allocation. A positive result is a large jx_track_source allocation.
  • Alignment oracle. Search /proc/self/mem for a unique byte of a vtable pointer inside the target object, using COM tables of 696 entries.
  • Load balancer bail-out. Embed a known byte from /proc/self/mem in the Rsiz field of SIZ and seek() to an unmapped address.

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

What happened, in plain words

Google's Cloud Vulnerability Research team (CVR) spent time attacking a piece of software called Kakadu. Kakadu is a library: a bundle of code that other programs can borrow to do a job. Its job is to read and write JPEG 2000 images, a modern image format. The team found two bugs in Kakadu and worked out how to chain them to achieve remote code execution impact. They did this without ever seeing the server's source code or the compiled program, and without knowing what the server's environment looked like.

That last part is the interesting bit. Most attacks that take over a program rely on knowing exactly what the program looks like inside, because the attacker needs to know where things sit in memory. When the software runs on a server you cannot inspect, you are guessing. The team's contribution is a set of tricks that turn guessing into something reliable, including a technique they call "Conditional Corruption".

A quick word on the two bugs, because the rest of the article builds on them:

  • Arbitrary file read: the attacker can make the server hand back the contents of any file on its disk, by asking Kakadu to build an image out of pieces of that file.
  • Heap out-of-bounds write: the attacker can make Kakadu write data past the end of a memory buffer, into memory it should not touch. This is the kind of bug that can lead to running arbitrary code.

In a 2007 study Kakadu outperformed other JPEG 2000 libraries, and it describes itself as the leading JPEG 2000 development kit. The team notes it is likely that major companies are affected by the vulnerabilities, including a Google service.

The code snippets in the report come from decompiled code of the freely available demonstration binaries of Kakadu, simplified for clarity, and are based on version 8.41 of the demo binaries. "Decompiled" means taking a finished program and turning it back into something that looks like source code, so a human can read it.

Setup

There are no accounts, roles or credentials in this research. The relevant preconditions are:

  • The target processes attacker-supplied JPEG 2000 images with Kakadu, in an environment the attacker cannot inspect.
  • The attacker can view the output image produced after processing.
  • The deployment may sit behind a load balancer, so consecutive requests may be handled by different workers.
  • The allocator in the target is tcmalloc.

A few of those need unpacking.

A load balancer is the front door of a busy service. When you send a request, the load balancer picks one of several identical servers ("workers") to handle it. The next request may go to a different worker. This matters enormously for an attack that needs two steps: if step one learns something about worker A and step two runs on worker B, the knowledge is useless.

An allocator is the part of a program that hands out chunks of memory when the program asks for them, and takes them back when it is done. tcmalloc is Google's allocator. Its behaviour with very large requests is central to the exploit later on.

The team read the JPEG 2000 standard and the Kakadu source code to understand how the parser flows and what its internal data structures look like. They also used fuzzing: feeding a program huge numbers of slightly mutated inputs and watching for crashes. Fuzzing found an internal variant of TALOS-2017-0309, an out-of-bounds write on the heap due to signed integer multiplication.

Finding it

JPEG 2000 background

The file format can be divided into two concepts: Boxes and Codestream Segment Markers.

Boxes are Length-Type-Value containers for metadata about the image, such as width, height and colour information, and can also hold the position of the actual codestream within the image. "Length-Type-Value" is a common way to structure data: first say how long the thing is, then say what kind of thing it is, then give the thing itself. It is like a parcel with the weight written on the outside, then a label saying "books", then the books.

A Box has these fields:

Field Size Description
LBox 32 bits Length of the box.
TBox 32 bits Box type, typically a 4-byte ASCII sequence with the box name. For example, ftyp is the name for the File-Type box.
XLBox 64 bits Extended length, only present if LBox is set to 1.
DBox Variable Box data (variable length based on LBox and the box type).

A bit is a single 0 or 1. A byte is 8 bits. "32 bits" means 4 bytes, and "64 bits" means 8 bytes. The size of a field tells you how big a number it can hold: a 32-bit number can go up to about 4 billion, a 64-bit number much higher.

Boxes can contain other Boxes. For example, the JP2 header Box may contain Boxes that provide more information about the image, such as a colr (Colour) Box. The following graphic shows how an image could be organised:

From the original on bughunters.google.com

The codestream contains the actual image data and sits inside a Codestream Box. It consists of Type-Length-Value containers called Segment Markers. The first 2 bytes are a unique value telling the parser which marker is being parsed; markers always begin with 0xFF, and the second byte can be any value from 0x01 to 0xFE. The next two bytes are a length field for the marker-specific data that follows, and because that field is only 2 bytes, a Segment Marker can have a maximum length of 65535.

The 0x prefix means the number is written in hexadecimal, base 16, which programmers use because it maps neatly onto bytes. 0xFF is 255, 0x01 is 1.

The decompressed image is made up of rectangular tiles, all the same size. Each tile's data is compressed individually and can have completely different decoder parameters, such as the number of decoding passes. There can be up to 65535 tiles, and they may appear in the codestream in arbitrary order. Each tile must contain at least two markers, Start-of-Tile (SOT) and Start-of-Data (SOD).

Think of a tiled image like a wall of bathroom tiles: the whole picture is assembled from identical rectangles, and each rectangle is stored separately. Because each tile is stored separately, an attacker can make each tile behave differently, which is exactly what the team exploits later.

The SOT layout is:

Field Size Description
SOT 16 bits Segment Marker (0xFF90).
Lsot 16 bits Marker segment length in bytes (not including the marker).
Isot 16 bits Tile index used to calculate the (x, y) coordinates of a tile.
Psot 32 bits Length of the tile data.
TPsot 8 bits Tile-part index, zero if there are no tile-parts.
TNsot 8 bits Number of tile-parts.

The SOD marker is one of the simplest and simply contains the compressed tile data. It has no length field of its own; its length is determined by the Psot field of the preceding SOT marker.

Field Size Description
SOD 16 bits Segment Marker (0xFF93).
Data Variable Tile data (variable length).

The X, Y coordinates of a tile can be calculated from the tile index, the image width/height and the tile width/height. From the SIZ marker these values are Xsiz, Ysiz, XTsiz and YTsiz respectively. The layout of tiles by index is shown in the diagram below.

From the original on bughunters.google.com

Tile dimensions in context of the larger image.

Service discovery

The team crafted images that rely on Kakadu quirks and features implemented only by Kakadu, to fingerprint endpoints that use Kakadu to convert JPEG 2000 images. "Fingerprinting" means working out what software is running on the other side by sending it something and watching how it reacts, the way you might identify a car by the sound of its engine. The feature relied on is "Codestream fragmentation", defined in the second part of the JPEG 2000 standard. It is described further under Exploitation, because it also allows an arbitrary file read.

Exploitation

Step 1: Arbitrary file read via JPX fragmentation

The ISO/IEC 15444-2 standard specifies an extended format for JPEG 2000 files called JPX. One feature of this extended format is the ability to fragment an image's codestream within the same file, across multiple files, or across multiple URLs on the Internet. As described in the specification, this optional extension is inherently vulnerable.

"Fragment" here means "split into pieces". The idea is sensible: a huge image can be stored as several pieces, and the decoder stitches them together. The problem is that the pieces can be other files on the same machine. A high level visualisation of the JPX fragmentation feature is shown below:

From the original on bughunters.google.com

To use it, a JPX image needs to include:

  • A single Data Reference Box, which contains a list of Data Entry URL Boxes, each of which contains the path to a file within the local filesystem as a null-terminated string.
  • A Fragment Table Box, which contains a single Fragment List Box that specifies fragments from which to build the continuous codestream.

A "null-terminated string" is text followed by a zero byte, which tells the program where the text ends. It is like writing a word and then putting a full stop so the reader knows to stop.

The Fragment Table Box has the following fields:

Field Size Description
NF 16 bits Total number of fragments.
OFFi 64 bits Offset to the start of the i-th fragment in the file specified by DRi, relative to the first byte of the file.
LENi 32 bits Length of the i-th fragment.
DRi 16 bits Data reference index, determines which file to load fragment data from. If zero, the current file is used.

An "offset" is a position counted from the start of a file, like a page number in a book. So OFFi says "start reading at this position", LENi says "read this many bytes", and DRi says "from this file".

By crafting JPX images with these Boxes, the team could inject into the codestream precise amounts of bytes read at specific offsets from specific local files, and have resulting images with such data encoded within their properties or pixels. Assuming an environment where the output image can be viewed after processing, this achieves an arbitrary file read.

In plain terms: the attacker writes an image file that says "take bytes from this offset of this local file and use them as part of my picture". The server builds the picture, and the attacker looks at the picture to read the file. The file never has to be sent back directly; it is smuggled out through the image itself.

Size-based read

The first proof of concept was a JPX image that would read the first and second bytes (starting from a given offset) of a given file. The SIZ Segment marker contains multiple 4-byte fields holding the decompressed image's width and height. Since the width and height of the exploit image are visible, some of those values could be substituted with bytes from a local file and derived from the decompressed image's dimensions.

Neither width nor height can be zero, and both are 32-bit unsigned integers, so each was encoded as (0x00, 0x00, 0x01, read byte). Each value therefore ends up as 0x100 plus the value of the respective read byte, giving a range from 0x100 to 0x1FF.

An "unsigned integer" is a whole number that cannot be negative. The trick here is arithmetic: if you put 0x01 in the third byte and the secret byte in the fourth, the resulting number is 0x100 plus the secret. The attacker reads the secret off the ruler of the image dimensions.

Because both the file to be read and the starting offset are controlled, this is already an exploitable arbitrary file read: a full file can be leaked by uploading images with increasing starting read offsets. However, it was insufficient for leaking /proc/self/maps, because only 2 bytes could be leaked per request. Even with increasing offsets, the contents change depending on the worker handling the request, so the output file would be a mix of different workers. Leaking through the image size could be improved slightly by accurately leaking up to 3 bytes at once in each property, so 6 bytes per JPX image, but that would require huge image sizes likely to exceed safety limits, and it still would not be enough for highly variable files.

/proc/self/maps is a special file on Linux. Reading it tells you which parts of memory the current program has mapped, and at what addresses. It is the map an attacker needs to know where to aim. But it changes from process to process, so a two-bytes-per-request leak would produce a jumble of different workers' maps.

Dynamic tile read

To leak more data in a single image, the team needed either a single segment marker with a large array of data that could be reliably decoded from the output image, or a segment marker that could be repeated to produce a noticeable effect.

The tile data itself is tempting: a single large tile with a large number of leaked bytes in its compressed pixel data. But the compression applied to tiles made this impossible. Tile data is encoded with a variable length encoding technique that does not permit the 0xFF byte in the stream. JPEG 2000 compression is also extremely complex, using wavelet transforms with dynamic coefficients, so the length and meaning of the tile changed based on the leaked data in a way that almost guaranteed parsing errors.

A "variable length encoding" is a way of storing data where the number of bytes used depends on the value. It is efficient but fragile: if you inject arbitrary bytes, the decoder loses track of where one value ends and the next begins, like a sentence with no spaces.

The team settled on the Comment (COM) marker, which includes an arbitrary number of bytes of unstructured data. The COM marker is not saved to the output image, so the Ccomi bytes could not be leaked directly, but it is valid in any part of the codestream and has variable length, which made it useful.

The COM marker has the following fields:

Field Size Description
COM 16 bits Segment Marker (0xFF64).
Lcom 16 bits Marker segment length in bytes (not including the marker).
Rcom 16 bits String encoding, 0 for binary, 1 for Latin.
Ccomi 8 bits Byte of comment data (variable length).

The mechanism leaks a single byte per tile with a jump table based on leaked bytes, using three types of codestream marker: Start-of-tile (SOT), Comment (COM) and Start-of-Data (SOD).

A "jump table" is a list of destinations where the program picks one based on a value. Think of a railway switchyard: depending on which track is set, the train goes to a different platform. Here the "value" is the secret byte, and the "platform" is a piece of tile data that paints a particular colour.

For each tile, a COM marker is included with variable length depending on a leaked byte (d<sub>i</sub>). A table of 256 entries follows, each with tile data and another COM marker. In each entry, the tile data encodes a different pixel colour. Each entry is exactly 256 bytes long, so depending on the value of the leaked byte a different entry is "chosen". An example of this encoding is shown below:

From the original on bughunters.google.com

SOT+COM table layout.

Because every entry is the same length, the decoder can jump straight to entry number N by multiplying N by 256. The secret byte decides N. The colour of the resulting pixel then tells the attacker what the secret byte was. One tile, one byte, one colour.

This mechanism leaked 20KB of data in a single image. Theoretically 65535 bytes could be leaked (the maximum number of tiles), but Kakadu also limits the number of fragments to 65535 and the exploit required about 3 fragments per leaked byte.

Because the pixel data is directly influenced by the leaked bytes, the image itself visualises the leaked data, which can also be decoded by examining the pixel values. The following image demonstrates what an output image could look like, in this case leaking bytes from Kakadu's kdu_expand binary via /proc/self/exe.

From the original on bughunters.google.com

Info leak of /proc/self/exe with Kakadu's kdu_expand binary.

/proc/self/exe is a shortcut to the program's own executable file. Reading it is like reading the program's own brain: it tells the attacker exactly what code is running, which is what you need to build a ROP chain.

A ROP chain (Return-Oriented Programming) is a way of making a program do what you want by stringing together small pieces of its own existing code, like making a sentence out of words already in the dictionary. To build one, you need to know the exact code, which is why leaking the binary matters.

This would have enabled an attacker to build ROP chain gadgets and understand the internals of the service, allowing remote code execution without previous insider knowledge. /proc/self/maps and /proc/self/environ could also be leaked to understand the targeted environment, and another attack path opened by this primitive is leaking memory contents via /proc/self/mem.

/proc/self/environ holds the program's environment variables, which often include configuration and sometimes secrets. /proc/self/mem is the program's entire memory, exposed as if it were a file. Being able to read it is close to being able to read everything.

Step 2: Heap overflow via signed integer multiplication

The SIZ Segment Marker contains information about the size of the decompressed image. The relevant fields are:

Field Size Description
SIZ 16 bits Segment Marker (0xFF51).
Lsiz 16 bits Marker segment length in bytes (not including the marker).
Xsiz 32 bits Width of the reference grid.
Ysiz 32 bits Height of the reference grid.
XTsiz 32 bits Width of one reference tile with respect to the reference grid.
YTsiz 32 bits Height of one reference tile with respect to the reference grid.
Csiz 16 bits Number of components in the image (e.g. RGB).

The final size of decompressed image data in memory is calculated as:

Height * Width * Number of Components

Height and Width correspond to Xsiz and Ysiz and can be fully controlled. The number of Components can also be controlled via the Csiz field, but is limited to 16384 by the standard.

The multiplication does not overflow when making the allocation for the output image buffer, because Kakadu calls a Google internal callback that uses 8-byte integers:

Text
  size_t buf_length = 0;
  size_t area = 0;
  if (!util_intops::SafeMultiply(width, height, &area)) {
    LOG(ERROR) << "Integer overflow when computing width*height.";
    return false;
  }

  if (!util_intops::SafeMultiply(area, num_components, &buf_length)) {
    LOG(ERROR) << "Integer overflow when computing area*num_components.";
    return false;
  }

Line by line:

  • size_t buf_length = 0; and size_t area = 0; set up two variables to hold the results. size_t is a type designed to hold sizes, and on a 64-bit system it is 8 bytes wide.
  • if (!util_intops::SafeMultiply(width, height, &area)) multiplies width by height using a helper that checks for overflow. If the multiplication would overflow, it returns false and the code logs an error and returns false, refusing the image.
  • The second block does the same for area times the number of components.

An integer overflow happens when a number is too big for the box it is stored in. Imagine a car odometer with six digits: after 999999 it rolls over to 000000. In a computer, a 32-bit number that goes past its maximum wraps around to a small value, which is dangerous because the program then thinks a huge number is tiny.

However, an integer overflow occurs while writing the image data, because Kakadu continues to use 4-byte variables. When writing a multi-row tile, Kakadu writes the tile data row by row, meaning it writes Width * Number of Components bytes per row. Once the first row has been written, it advances a pointer to the next row by adding the result of Width * Number of Components to the pointer. This addition is done using a signed, 4-byte integer, so the value can overflow and the pointer points outside the image.

A pointer is a variable that holds a memory address, like a bookmark holding a page number. "Advance the pointer" means "move the bookmark to the next page". If the arithmetic that moves the bookmark overflows, the bookmark lands somewhere it should not, and the next write goes there.

The row_gap is calculated in the snippet below, which is the 4-byte signed integer added to the row pointer when writing row by row:

Text
00436eb4  int32_t row_gap
00436eb4  if (row_gaps == 0)
00436f10    row_gap = sample_gap * component_state->row_width
00436eb6  else
00436eb6    row_gap = *(row_gaps + i)
00436ebd  *(component_state - 8) = row_gap

Line by line:

  • int32_t row_gap declares a signed 32-bit integer. "Signed" means it can be negative as well as positive, which is exactly what allows the overflow to send the pointer backwards.
  • if (row_gaps == 0) checks whether a precomputed list of gaps exists. If not, the gap is calculated by multiplying a sample gap by the row width.
  • else takes the gap from the list.
  • *(component_state - 8) = row_gap stores the result back into a structure.

Because the width can be controlled, the team could write controlled data backwards in memory with a controlled distance. The following image visualises the out-of-bounds write logic:

From the original on bughunters.google.com

An out-of-bounds write is exactly what it sounds like: the program writes data outside the area it was given. It is like painting a wall and carrying on past the edge onto the furniture. If the attacker controls what is painted and where the edge is, they can paint on something important.

Step 3: The exploitation plan

With the two primitives, the plan to achieve remote code execution impact was:

  1. Use the info leak to read /proc/self/maps and learn the address of the heap, executable, etc.
  2. Send a second image to exploit the heap overflow, corrupting a predictable object and obtaining code execution in the service. The image reads a known byte from /proc/self/mem based on the address leaked in step 1. If this step fails, the exploit is not triggered. This ensures the exploit triggers on the same worker with the known address layout.
  3. Run proof-of-concept code to verify remote code execution impact.
  4. Perform all of the above with no impact to users.

A primitive in security means a small, reliable capability that you can build bigger things from, like a single Lego brick. "Arbitrary file read" and "out-of-bounds write" are primitives.

Step 2 is the clever part. The second image checks, before doing anything dangerous, that the memory it expects is actually there. If the request landed on a different worker, the check fails and the image is quietly rejected. That is the "Conditional" in Conditional Corruption: the corruption only happens if a condition is met.

Step 4: Understanding the heap layout

Using the heap overflow, the team could write backwards in memory by a known, large distance. To exploit this, they had to understand where the image would be allocated on the heap, because its location determined what data could be overwritten.

The heap is the area of memory a program uses for data that is created while it runs, as opposed to the stack, which is for short-lived local variables. Think of the heap as a warehouse: the program asks the allocator for shelf space, and the allocator hands out a spot.

Because the image width is large, the memory requested for pixel data is over 4GB. The target uses tcmalloc, which has specific behaviour with large allocations. If the heap does not have available memory for the large allocation, tcmalloc expands the heap and places the allocation in a predictable location. This effect can be observed in /proc/self/maps before and after the allocation. When submitting an image of width 0x0040000000, the requested allocation is 0x0200000000 bytes.

Text
      # /proc/self/maps before allocation
      256400000000-256432600000 ---p 032600000 00:00 0  [anon:tcmalloc_region_NORMAL]
      256432600000-25643d600000 rw-p 00b000000 00:00 0  [anon:tcmalloc_region_NORMAL]
      25643d600000-25643d7c0000 rw-p 0001c0000 00:00 0  [anon:tcmalloc_region_NORMAL]
      25643d7c0000-256440000000 rw-p 002840000 00:00 0  [anon:tcmalloc_region_NORMAL]

Each line describes one chunk of memory: a start address, an end address, permissions (---p means no access, rw-p means readable and writable), and a name. The [anon:tcmalloc_region_NORMAL] label tells you this memory belongs to tcmalloc. The addresses are in hexadecimal.

Text
      # /proc/self/maps after allocation
      256400000000-256431400000 ---p 031400000 00:00 0  [anon:tcmalloc_region_NORMAL]
      256431400000-25643d600000 rw-p 00c200000 00:00 0  [anon:tcmalloc_region_NORMAL]
      25643d600000-25643d7c0000 rw-p 0001c0000 00:00 0  [anon:tcmalloc_region_NORMAL]
      25643d7c0000-256640000000 rw-p 202840000 00:00 0  [anon:tcmalloc_region_NORMAL]

To accommodate the request, tcmalloc extends the 25643d7c0000-256440000000 range to 25643d7c0000-256640000000. The increase is exactly 0x0200000000 bytes and the image buffer is allocated at address 256440000000. Knowing the address of the image buffer allows the exact addresses overwritten by the heap overflow to be calculated.

This is the key insight: a huge allocation forces the allocator to grow the heap in a predictable way, so the attacker knows where the image will sit. Without that, the heap overflow would be firing into the dark.

Step 5: The 808080 Apocalypse

One problem with the heap overflow primitive is the large amount of data that must be written to the heap. Due to the large allocation, there is often a large gap between the image buffer and any useful objects on the heap. The team experimented with different overflow distances and tile widths to find optimal values for more reliable objects, crafting an image with a single tile containing pixel data of all 0x41 and a dynamic width and tile width, then fuzzing those values against a copy of the production job and recording crash locations and registers for each attempt.

0x41 is the byte for the capital letter A. Using a recognisable byte makes it easy to spot in a crash report: if the program crashes at address 0x4141414141414141, you know the attacker's data got there.

After a few hours of experimentation, they were crashing reliably in the following objects related to Kakadu:

  • kd_supp_local::jx_composition::~jx_composition
  • kdu_supp::jp2_input_box::close
  • kd_core_local::kd_precinct_server::get
  • kd_supp_local::jx_codestream_source::~jx_codestream_source
  • kd_supp_local::jx_layer_source::~jx_layer_source
  • kd_supp_local::kdsd_tile::process
  • kdu_core::kdu_params::access_unique
  • kdu_supp::kdu_stripe_decompressor::pull_common
  • and a few crashes in non-Kakadu objects

These are names of functions and objects inside Kakadu. A function is a named block of code that does a job. An object is a bundle of data and the functions that work on it. The ::~ part is a destructor, a function that runs when an object is being cleaned up.

However, while they sometimes saw segfaults on a controlled address (e.g. 0x4141414141414141), they often saw segfaults for the address 0x8080808080808080. The majority of crashes at the time looked something like the following:

From the original on bughunters.google.com

A segfault is the operating system's way of stopping a program that has tried to touch memory it is not allowed to touch. It is a crash, and it is the attacker's signal that they hit something.

That value was nowhere in the input pixel data, but was being sprayed everywhere over the heap, corrupting random objects with 0x80 bytes and segfaulting unpredictably. They dubbed this the "808080 Apocalypse". After a few hours of head scratching, they realised that Kakadu was writing the crafted 0x41 tile, followed by hundreds of tiles with "uninitialised" pixel data set to 0x80, an arbitrary default value used by Kakadu.

From the original on bughunters.google.com

"Uninitialised" means the program never filled that memory with real data, so it contains whatever default the program chose. Here Kakadu chose 0x80. The attacker's carefully aimed write was being followed by a flood of junk, like writing a letter and then having someone scribble over the envelope.

The 808080 Apocalypse would make exploitation incredibly difficult, since these 0x80 tiles almost always clobbered random objects on the heap. However, within the tile processing code, the team found a Kakadu-specific technique to write a single tile and then cause an error, skipping the writes for uninitialised tiles. The Start of tile-part (SOT) marker contains a 16-bit parameter Isot, which indicates the tile index of the current tile. If Kakadu encounters a tile index greater than the number of possible tiles in the image, it throws an error and stops writing pixel data. The exploit was crafted using the following tiles to write exactly one tile worth of controlled data:

From the original on bughunters.google.com

Rendering this image threw the following error:

Text
Corrupt SOT marker segment found in codestream: tile-number lies outside
  the range of available tiles derived from the SIZ marker segment.

This is the error message Kakadu produces. It is not a failure for the attacker; it is the goal. The error stops Kakadu before it writes the uninitialised tiles, so only the attacker's controlled tile lands in memory.

After collecting metrics on the observed crash fingerprints and rolling out this fix to the exploit, the team observed a sharp increase in ~jx_composition crashes and the 808080 Apocalypse had ended.

From the original on bughunters.google.com

Visualization of crash fingerprint prevalence over time.

A crash fingerprint is the pattern of where and how a program crashes. If you see the same fingerprint repeatedly, you know your exploit is behaving consistently. The graph shows the ~jx_composition fingerprint becoming dominant once the fix was in.

Step 6: Finding a reliable gadget on the heap

With the 808080 Apocalypse solved, the team continued searching for an object to target on the heap. Because tcmalloc utilises randomisation, finding such a gadget turned out to be fairly difficult. However, since the memory location of the image buffer was reliably known, and the write backwards into the heap happens at a controlled offset up to -2GB, they had an "arbitrary heap write primitive" if the worker's heap was smaller than 2GB. That means any object on the heap could be overwritten, given its location is known.

A gadget in this context is a useful object or code fragment that the attacker can hijack. Randomisation (ASLR, Address Space Layout Randomisation) is a defence that shuffles memory addresses so attackers cannot predict them. The team's trick is that a huge allocation makes tcmalloc place the image buffer in a predictable location.

Global heap pointers

The first approach was to use the arbitrary file read to read /proc/self/mem, looking for a global variable that points into the heap. This would bypass tcmalloc's randomisation and write at a known location, which in theory could have resulted in a 100% reliable exploit. The large issue was that although a known object could be reliably written to, the size written was not controlled, around 20KB on average. No exploitable object of that size pointed to by a global variable was found, so other random data on the heap would be overwritten, often leading to an uncontrolled crash as another thread used the corrupted data before the target object did.

A global variable is a variable that exists for the whole life of the program, not just inside one function. A thread is a separate line of execution inside one program, like a second worker in the same office. If another thread reads corrupted data before the attacker's target does, the program crashes in an uncontrolled way.

The team discussed reading the data around the target address and restoring the heap data to prevent these crashes, but did not follow this approach: they discovered another gadget and concluded that even with restoration there would still be a race condition where the data is corrupted and would lead to a crash.

A race condition is when the result depends on which of two things happens first. Here, the attacker would need to restore data before another thread reads it, and there is no guarantee of that.

Large allocation to prevent randomisation

The next approach was to make Kakadu allocate an array of objects that, when corrupted, would yield a reliable primitive such as a vtable overwrite. After some searching, they found such a primitive, triggered by including a Composition Layer Extensions Box from Part 2 of the JPEG 2000 standard. The reduced code snippet below shows the attacker-controlled allocation:

Text
// from kdu_expand
00476140 jx_container_source::parse_info(struct jx_container_source* this)
0047620c   if (jp2_input_box::read(&curr->__offset(0x140).q, &Mjclx) == 0)
00476466     box_reading_error:
00476466     kdu_core::kdu_error::kdu_error(&var_68)
00476473     kdu_core::kdu_error::put_text(&var_68)
00476473     goto label_47647b
00476221    if (jp2_input_box::read(&curr->__offset(0x140).q, &Cjclx) == 0)
00476221      goto box_reading_error
00476236    if (jp2_input_box::read(&curr->__offset(0x140).q, &Ljclx) == 0)
00476236      goto box_reading_error
0047624b    if (jp2_input_box::read(&curr->__offset(0x140).q, &Tjclx) == 0)
0047624b      goto box_reading_error
00476260    if (jp2_input_box::read(&curr->__offset(0x140).q, &Fjclx) == 0)
00476260      goto box_reading_error
0047626c    if (jp2_input_box::read(&curr->__offset(0x140).q, &Sjclx) == 0 && Tjclx != 0)
00476453      goto box_reading_error
// ...
00476875    struct j2_memsafe* allocator = curr->allocator.__offset(0x48).q
00476893    // 0x2c0 = size of individual jx_track_source objects
00476893    // 8 = alignment of allocation
00476893    // Tjclx = number of jx_track_source objects
00476893    struct jx_track_source *track_sources
00476893      = j2_memsafe::alloc(allocator, 0x2c0, 8, Tjclx)

Line by line:

  • The function jx_container_source::parse_info reads a series of values from the input box: Mjclx, Cjclx, Ljclx, Tjclx, Fjclx, Sjclx. Each read returns 0 on failure, and on failure the code jumps to box_reading_error, which raises an error.
  • The last check also requires Tjclx != 0, so a zero count is rejected.
  • Later, j2_memsafe::alloc(allocator, 0x2c0, 8, Tjclx) asks the allocator for space. The arguments are: the allocator, the size of each object (0x2c0), the alignment (8), and the number of objects (Tjclx).

A vtable is a table of function pointers used by object-oriented code to decide which function to call. If an attacker can overwrite a vtable, they can redirect a function call to code of their choosing. It is like swapping the labels on the office doors.

An attacker can fully control the Tjclx value and make Kakadu allocate an array of hundreds of megabytes. This had two advantages: the team would never corrupt data outside of the array, and the size of the array made it highly likely to be "hit" with a memory corruption distance that was reliable between the array and the output image buffer.

Write-what-where

The destructor of each jx_track_source object would at some point call the destructor of jx_composition, which in turn would call the jp2_input_box::close() method on a jp2_input_box object that was an inline member. Assuming all fields in the inline objects are fully controlled due to the memory corruption, this triggers an arbitrary write primitive. A simplified version of the corresponding close() code is shown below:

Text
0041e800  uint64_t kdu_supp::jp2_input_box::close(struct jp2_input_box* this)
0041e812    if (this->is_opened != 0)
0041e840      bool dynamic_length = this->dynamic_length
0041e847      this->is_opened = false
0041e86d      struct jp2_input_box* parent_box = this->parent_box
0041e874      if (parent_box != 0)
0041e876        uint64_t next_box_position = this->next_box_position
0041e8b9        if (next_box_position == 0 && dynamic_length != 0)
0041e8bb          uint64_t box_position = this->box_position
0041e8c2          parent_box->__offset(0x96).b = 1
0041e8c9          parent_box->box_position = box_position

Line by line:

  • if (this->is_opened != 0) only proceeds if the box is open.
  • bool dynamic_length = this->dynamic_length reads a flag from the object. Because the object is corrupted, the attacker controls this flag.
  • this->is_opened = false marks the box closed.
  • struct jp2_input_box* parent_box = this->parent_box reads a pointer. Again, the attacker controls it.
  • if (parent_box != 0) checks the pointer is not null.
  • if (next_box_position == 0 && dynamic_length != 0) is the condition that must hold for the dangerous write.
  • parent_box->__offset(0x96).b = 1 and parent_box->box_position = box_position write to memory relative to the attacker-controlled pointer.

A write-what-where primitive means the attacker can write a value of their choosing (the "what") to an address of their choosing (the "where").

parent_box is a pointer that can be fully controlled. If the dynamic_length value is set to true and next_box_position is 0, the code writes to parent_box-152 (the offset of the box_position member), with a fully controlled 8-byte value. Since an array of these objects can be corrupted, the arbitrary write can be triggered multiple times, making it a powerful primitive.

Unfortunately, while the jx_track_source array was reliably allocated near the image buffer, the exact offset varied. To avoid unexpected behaviour, the precise object alignment modulo the size of the object (696 bytes) had to be known, so that the heap overflow could precisely overwrite a slice of objects from the array.

"Modulo" means the remainder after division. If objects are 696 bytes each and the array starts at some address, then the objects sit at addresses that are multiples of 696 apart. Knowing the remainder tells you exactly where each object begins. Without it, the overflow might land in the middle of an object and corrupt the wrong fields.

Step 7: Exploit reliability engineering, the Kha-Kha Slide

Or, "finding a jx_comp needle in a haystack".

The team puzzled over the object alignment problem for some time, hoping that with enough experimentation they could find alignments that were more likely based on the heap layout. There were some patterns: approximately 14% shared the same offset, but this was not reliable enough for production, since guessing wrong meant crashing the service.

Using experience from crafting the Dynamic Tile info leak, they created a mechanism within the codestream to dynamically change the tile data written by the heap overflow, based on data from the heap itself read via /proc/self/mem. They called it the Kha-Kha Slide.

From the original on bughunters.google.com

At the start of the slide, an SOT is included whose length encompasses the entire slide. This means that somewhere within the slide there must be an SOD with tile data, but there can also be an arbitrary number of other markers before the SOD. A series of 696 lookup tables is then crafted, one for each possible offset of the jx_composition object. Using this mechanism, the exploit effectively searches memory for a specific byte value that tells it the object offset.

Each table starts with a COM marker whose length is based on a leaked byte from /proc/self/mem. Within the table are 256 additional COM markers, one for each possible leaked byte value. Each COM has a variable length to jump over the other markers and into the "COM S" marker at the end of the table. If the byte value being looked for is found (0x41 in the diagram), the parser jumps directly to a SOD marker with tile data specifically crafted for that offset. If the byte is not found, the "COM S" marker jumps over the exploit and onto the next COM table. The exploit proceeds through each COM table, looking at a different address each time, until one of them finds the byte and triggers the exploit.

The darker coloured path in the diagram shows an example path through the COM tables. For example, if the first few bytes of memory are 01417fff, the parser will see the following markers:

Text
SOT 00 0a 00 01 TL 00 01

COM 01 06 00 00 41 41 <256 bytes>

COM L2 L2 00 00 <L2 bytes>

COM SS SS 00 00 41 41

COM 41 06 00 00 41 41 <16640 bytes>

SOD exploit[d2]

COM E2 E2 00 00 41 41
...

SOT 00 0a ff ff 00 00 00 00 00 01

Line by line:

  • SOT 00 0a 00 01 TL 00 01 starts a tile whose length covers the whole slide.
  • COM 01 06 00 00 41 41 <256 bytes> is a comment marker whose length is chosen by the first leaked byte (01).
  • COM L2 L2 00 00 <L2 bytes> is the next comment, with length L2.
  • COM SS SS 00 00 41 41 is the "COM S" marker that jumps over the exploit if the byte was not found.
  • COM 41 06 00 00 41 41 <16640 bytes> is the marker reached when the leaked byte is 0x41, the value being searched for.
  • SOD exploit[d2] is the tile data that performs the exploit, tailored to the offset d2.
  • COM E2 E2 00 00 41 41 is the next table's marker.
  • SOT 00 0a ff ff 00 00 00 00 00 01 is the final tile, with an out-of-range index that stops processing.

The jx_composition object is mostly initialised to zero, with a few heap pointers and vtables. One of these vtables can be chosen with a unique byte in the pointer. For the production binary, the vtable address chosen was 0x3f5a04f0. Its least significant byte, 0xf0, was unique within the jx_composition object, giving an oracle byte to search for with the Kha-Kha Slide.

An oracle is a way of asking a yes/no question about something you cannot see directly. Here, the question is "is the object at this alignment?", and the answer comes from whether the byte 0xf0 is found at the expected place.

The Kha-Kha Slide increased reliability significantly, but one last bit of randomness remained: the load balancer. The exploit requires two requests, one to leak /proc/self/maps and the next to perform the heap overflow, and different workers might process them. If that happened, the exploit would have the wrong addresses and certainly segfault. To harden the second payload against invalid addresses, the team added one last info leak early in the codestream. While reading fragments, if fread() returns zero, Kakadu exits early and sets an error for the current marker. For most markers, Kakadu simply ignores the error and continues parsing. For the SIZ marker, however, Kakadu throws the following error and skips all further parsing:

Text
Code-stream must contain a valid SIZ marker segment, immediately after the SOC marker!

fread() is a standard function for reading from a file. It returns the number of items read, so zero means "nothing was read", which happens when the address is not mapped.

If the exploit seek()s to an address in /proc/self/mem that is not mapped, the subsequent fread() returns zero (corresponding to an I/O error). A known value from /proc/self/mem can therefore be embedded within the SIZ marker such that, with a valid memory layout, the value completes the SIZ marker, and with an invalid memory layout, the exploit bails out and skips processing the image altogether. The Rsiz field of the SIZ marker was chosen, which has a null byte in it, and for the leak address the first null byte in the memory region containing the executable. That crossed the final reliability hurdle.

seek() moves the read position in a file, like skipping to a page. If the page does not exist, the next read fails. The team turned that failure into a safety switch: wrong worker, no exploit, no crash.

Step 8: Putting it together

The team used an arbitrary file read in Kakadu to obtain information about the server environment. Similar effects can be achieved with an arbitrary memory read primitive, an example being another bug CVR discovered in PostgreSQL that allowed the attacker to fully obtain the target binary.

The same file-read primitive was then used for "Conditional Corruption", a technique CVR published in 2023 when targeting ClamAV, which was subsequently awarded a Pwnie award. This technique allowed the team to target the same worker they leaked information from in the first step of the exploit, greatly improving reliability and removing chance from the exploit. "Conditional Corruption" was used again to verify the exploit payload would overwrite the correct data on the heap before triggering, ensuring reliability. This gave a write-what-where primitive.

A Pwnie award is a light-hearted award given in the security community for notable research and achievements.

With the info leak and the write-what-where primitive, the team could locate and modify global variables, hijack the control flow of the process and execute arbitrary code without impact to users.

"Hijack the control flow" means making the program run the attacker's instructions instead of its own. It is the difference between a passenger and a driver.

Root cause

The arbitrary file read is a design consequence of the JPX fragmentation feature from ISO/IEC 15444-2: a JPX image can reference local files by path and splice bytes from them into the codestream, and Kakadu implements this as specified. The report describes the optional extension as inherently vulnerable.

The heap overflow is a signedness and width mismatch. The allocation size is computed with 8-byte integers through a Google internal callback, so it does not overflow. The write path, however, keeps using 4-byte variables: the per-row advance is a signed 4-byte integer (row_gap), so a controlled width makes it overflow and the row pointer lands outside the image buffer. The existing defence, the safe multiplication at allocation time, did not cover the arithmetic used while writing pixel data.

"Signedness" means whether a number is allowed to be negative. A signed number that goes below zero wraps around to a huge positive value, and vice versa. The allocation code was careful; the writing code was not.

Impact

Under the conditions described, an attacker who can submit images and view the output can read arbitrary local files, including /proc/self/maps, /proc/self/environ, /proc/self/exe and /proc/self/mem, and can leak memory contents. That is enough to build ROP chain gadgets and understand the internals of the service without insider knowledge. Combined with the heap overflow, the team achieved remote code execution impact, hijacking the control flow of the process and executing arbitrary code without impact to users. The report notes it is likely that major companies are affected, including a Google service. The exploit assumes the output image can be viewed after processing, and the write primitive covers a controlled offset up to -2GB only if the worker's heap is smaller than 2GB.

Fix

The report does not describe a patch for either vulnerability. The only change it documents is on the exploit side: crafting the tiles so that a tile index outside the range derived from the SIZ marker makes Kakadu throw an error and stop writing pixel data, which skips the writes for uninitialised tiles and ends the 808080 Apocalypse.

Variants to test

  • JPX fragmentation on other decoders. Submit a JPX image with a Data Reference Box pointing at a local path and a Fragment Table Box with DRi set to that entry. A positive result is output whose dimensions or pixels encode bytes from the referenced file.
  • Size-based leak. Encode SIZ width and height as (0x00, 0x00, 0x01, read byte) and compare the decompressed dimensions against the file contents. A positive result is dimensions in the 0x100 to 0x1FF range that track the file's bytes.
  • Dynamic tile leak. Build per-tile COM jump tables of 256 entries of exactly 256 bytes each, with tile data encoding a different pixel colour per entry. A positive result is an output image whose pixel values decode to file contents, up to 20KB per image in this report's setup.
  • Signed row advance. Set a large Xsiz with a multi-row tile and observe whether the row pointer wraps.
  • Uninitialised tile spray. Use a single tile of controlled pixel data and watch for a default fill value (here 0x80) appearing across the heap. A positive result is crashes on an address built from that default value rather than the controlled one.
  • Tile index out of range. Set Isot beyond the number of tiles derived from SIZ and check whether the decoder errors out before writing uninitialised tiles. A positive result is the "tile-number lies outside the range" error with no further pixel writes.
  • Composition Layer Extensions Box. Supply a Tjclx value that forces a large jx_track_source allocation. A positive result is a large jx_track_source allocation.
  • Alignment oracle. Search /proc/self/mem for a unique byte of a vtable pointer inside the target object, using COM tables of 696 entries.
  • Load balancer bail-out. Embed a known byte from /proc/self/mem in the Rsiz field of SIZ and seek() to an unmapped address.

Glossary

  • Allocator: the part of a program that hands out and reclaims chunks of memory.
  • Arbitrary file read: a bug that lets an attacker read any file on the server.
  • Bit: a single 0 or 1.
  • Box: a Length-Type-Value container in a JPEG 2000 file holding metadata or data.
  • Byte: 8 bits.
  • Codestream: the part of a JPEG 2000 file that holds the actual compressed image data.
  • Conditional Corruption: a technique where memory corruption only happens if a condition checked at runtime is met, so the exploit can bail out safely.
  • Crash fingerprint: the pattern of where and how a program crashes, used to recognise consistent behaviour.
  • Destructor: a function that runs when an object is being cleaned up.
  • Fuzzing: feeding a program many mutated inputs to find crashes.
  • Gadget: a useful object or code fragment an attacker can hijack.
  • Global variable: a variable that exists for the whole life of the program.
  • Heap: the area of memory used for data created while a program runs.
  • Hexadecimal: base-16 number notation, written with a 0x prefix.
  • Integer overflow: when a number is too big for its storage and wraps around.
  • Jump table: a list of destinations chosen by a value.
  • Load balancer: the front door that sends each request to one of several identical servers.
  • Modulo: the remainder after division.
  • Null-terminated string: text followed by a zero byte marking its end.
  • Offset: a position counted from the start of a file or memory region.
  • Oracle: a way of asking a yes/no question about something you cannot see directly.
  • Out-of-bounds write: writing data outside the memory area the program was given.
  • Pointer: a variable holding a memory address.
  • Primitive: a small, reliable capability used to build a bigger attack.
  • Pwnie award: a light-hearted award in the security community.
  • Race condition: when the result depends on which of two things happens first.
  • ROP chain: a sequence of small pieces of existing code strung together to make a program do something new.
  • Segment Marker: a Type-Length-Value container inside the codestream.
  • Segfault: the operating system stopping a program that touched memory it should not.
  • Signed integer: a whole number that can be negative or positive.
  • Thread: a separate line of execution inside one program.
  • Tile: a rectangular piece of an image, compressed separately.
  • tcmalloc: Google's memory allocator.
  • Unsigned integer: a whole number that cannot be negative.
  • Variable length encoding: a way of storing data where the number of bytes depends on the value.
  • vtable: a table of function pointers used to decide which function to call.
  • Write-what-where: a primitive that lets an attacker write a chosen value to a chosen address.

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.