Repository navigation
Updated constraints due security reasons (triggered on 2026-11-06T12:00:44+00:00 by 6a520992270dc923bdd55f49df432630bae31f2b) - #33
Merged
Androidbeingx merged 1 commit intoNov 6, 2026
Conversation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Dependency issues not solved for Python 3.10
Image.save(..., format="PDF", append=True), Pillow parses that file withPdfParser. Two recursive parsers have no effective bound.linearize_page_treefollows/Kidswith no visited set or depth limit, so a cyclic or duplicated page tree recurses without end.read_prev_trailerrejects only an exactly repeated/Prevoffset, so a long chain of unique offsets still recurses. The trailer-loop guard added for CVE-2026-42310 does not cover either case. ### Detailslinearize_page_treerecurses on/Kidswith no cycle or depth check: -src/PIL/PdfParser.py:1078-1092read_prev_trailercatches only a repeated offset: -src/PIL/PdfParser.py:697-720(theprocessed_offsetscheck at:714-718is the CVE-2026-42310 fix; a unique-offset chain slips past it) ### PoCpython from PIL import PdfParser # A page tree whose /Pages nodes reference each other in a cycle (2 -> 3 -> 2). objs = { 1: b"<< /Type /Catalog /Pages 2 0 R >>", 2: b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>", 3: b"<< /Type /Pages /Kids [2 0 R] /Count 1 >>", } buf = bytearray(b"%PDF-1.4\n") off = {} for oid in (1, 2, 3): off[oid] = len(buf) buf += b"%d 0 obj\n" % oid + objs[oid] + b"\nendobj\n" xref = len(buf) buf += b"xref\n0 4\n0000000000 65535 f \n" buf += b"".join(b"%010d 00000 n \n" % off[o] for o in (1, 2, 3)) buf += b"trailer\n<< /Root 1 0 R /Size 4 >>\nstartxref\n%d\n%%%%EOF\n" % xref open("poc.pdf", "wb").write(buf) PdfParser.PdfParser("poc.pdf", mode="r+b") # append=True parses the existing file the same wayRun it:$ python 11_poc.py RecursionError: maximum recursion depth exceededThe 315-byte file triggers the recursion on parse. A duplicated (non-cyclic)/Kidstree instead produces super-linear CPU and memory work, and a long unique-offset/Prevchain triggers the trailer-side recursion. ### Impact A service that appends to user-supplied PDFs, for example a stamping or watermarking pipeline, can be driven into uncaught recursion or heavy CPU and memory use before any image is written. Follow-up to CVE-2026-42310. Since Pillow's policy discourages filing plain Python exceptions as denial of service, lead with the cyclic-tree case, which burns CPU and memory rather than only raisingRecursionError. The fix is a visited set plus a depth limit in both parsers.============================================================================ GIF seek keeps rejected size after DecompressionBombError, allowing DoS Location: src/PIL/GifImagePlugin.py:293 in GifImageFile._seek() Commit: a707c6b21c313880d0771e54965d142dd42358b6 ============================================================================A GIF of about 60 bytes can make Pillow allocate gigabytes of memory. This affects applications that catch the "image too large" error raised while stepping to a later animation frame and then keep using the same image object. Pillow correctly refuses the oversized frame, but it stores the refused dimensions on the image object anyway, and later operations size their memory from them. An attacker who can upload a GIF to such a service can exhaust its memory: the process either fails with an out-of-memory error after committing gigabytes, or is killed by the operating system. There is no memory corruption. The bug is inGifImageFile._seek()(src/PIL/GifImagePlugin.py:292-294). When a frame's extent enlarges the image, the code assigns the new size toself._sizeand only then callsImage._decompression_bomb_check(). Nothing restores the old size whenDecompressionBombErroris raised, becauseseek()only rolls back onEOFError. After the caught error,im.sizereports the rejected size while the pixel bufferim.imis still the 1×1 first frame. Because the extent is a 16-bit offset plus a 16-bit size, that rejected size can be as large as 131070×131070. In the attached reproducer, the rejected size is 40000×40000. A retriedseek(1)followed byload()then reachesload_prepare(), which callsImage.core.fill()with that size to decode a single pixel. Peak memory rises from 17 MiB to 1700 MiB before a 3 GiB address-space cap stops the next allocation.Image.new("RGB", im.size, ...)androtate(..., expand=True)also allocate from the stale size. The default paths are unaffected: plainImage.open()plusload(),ImageSequence.Iterator, andn_frames/is_animated. The ordering was introduced in c9f1b35e9810 ("Added GIF decompression bomb check", 2022-06-30, first released in 9.2.0), the check added for CVE-2022-45198. The two dispose-extent checks later in the same function already validate before using the size, and the attached patch makes this check follow the same order. ## DetailsGifImageFile._seek()lets a later frame enlarge the image, and performs the decompression-bomb check for the new size only after storing it on the object:python # src/PIL/GifImagePlugin.py:289-294 (GifImageFile._seek) x0, y0 = i16(s, 0), i16(s, 2) x1, y1 = x0 + i16(s, 4), y0 + i16(s, 6) if (x1 > self.size[0] or y1 > self.size[1]) and update_image: self._size = max(x1, self.size[0]), max(y1, self.size[1]) # state mutated Image._decompression_bomb_check(self._size) # ...then validated_decompression_bomb_check()(src/PIL/Image.py:3586) raisesDecompressionBombErrorfor anything above2 * MAX_IMAGE_PIXELS(178 956 970 px by default), but by thenself._sizealready holds the rejected value and nothing restores it:seek()(GifImagePlugin.py:166-179) only rolls back onEOFError, and_seek(0)only ever grows_size. The object that the application still holds therefore reportsim.size == (40000, 40000)whileim.imis the 1×1 buffer of frame 0. Compare the two dispose-extent checks a few lines further down in the same function (GifImagePlugin.py:383and:407), which call_decompression_bomb_check(dispose_size)before the correspondingImage.core.fill(), andTiffImagePlugin.load_prepare()(src/PIL/TiffImagePlugin.py:1319-1321), which checks_tile_sizebefore allocating from it. With this 60-byte GIF (hex)47494638396101000100800000000000ffffff GIF89a, 1x1 screen, 2-entry global palette 2c000000000100010000 02 024401 00 frame 0: 1x1 @ (0,0), LZW data 2c00000000409c409c00 frame 1 descriptor: 40000x40000 @ (0,0) 2c000000000100010000 02 024401 00 another 1x1 frame 3b trailerImage.open()succeeds (im.size == (1, 1)),im.seek(1)raisesDecompressionBombError: Image size (1600000000 pixels) exceeds limit of 178956970 pixels, and afterwardsim.size == (40000, 40000),im.im.size == (1, 1),im.tell() == 0. What happens next depends on what the application does with the object, but several ordinary operations take their dimensions fromim.sizerather than from the C buffer: - Retryingim.seek(1). The failed_seekleftself.__offset == 0and the file pointer just past the 9-byte descriptor, so the retry parses whatever follows — in the file above, a valid 1×1 frame — and succeeds.im.load()then runsGifImageFile.load_prepare():python # src/PIL/GifImagePlugin.py:452-456 elif self.mode in ("RGB", "RGBA"): self._prev_im = self.im if self._frame_palette: self.im = Image.core.fill("P", self.size, self._frame_transparency or 0)which allocates andmemsets a 40000×40000 "P" image (1.6 GB) to decode a 1×1 tile into, andload_end()(GifImagePlugin.py:485-491) fills a second one and converts it to RGB (another 1.6 GB + 6.4 GB). -im.rotate(angle, expand=True)for a non-multiple-of-90 angle, or the common flatten-onto-background idiomImage.new("RGB", im.size, bg), allocate fromim.sizeas well (measured on an object poisoned to 20000×20000:rotate(45, expand=True)completes and touches 776 MiB;Image.new("RGB", im.size, "white")touches 1.5 GiB). Operations that passim.sizeas a box against the real buffer (thumbnail,resize,save) fail withValueError/SystemErrorinstead. The extent fields are 16-bit offset plus 16-bit size, so the stored size can be pushed to 131070×131070 (17.2 Gpx; 17 GB for mode "P", 69 GB for "RGB"/"RGBA" storage), 96× the error threshold.n_frames/is_animatedare not affected: they call_seek(frame, update_image=False), which skips the_sizeassignment (the file above reportsn_frames == 2,is_animated == Trueand leavesim.sizeat 1×1). ## Impact A remote user who can upload a GIF to a service that (a) seeks animation frames and (b) catches the exception fromseek()— a broadexcept Exceptionaround awhile True: im.seek(im.tell()+1)frame-collection loop, or an explicitexcept DecompressionBombError: log and continue— and then keeps using the sameImageobject, ends up driving allocations of 1.6 GB to tens of GB from a 60-byte file:MemoryErrorafter the process has committed gigabytes, or an OOM kill of the worker when no address-space limit is set. TheMAX_IMAGE_PIXELSguard fires, but does not actually keep the rejected dimensions out of the object it is guarding. The precondition is real application behaviour but not the default path:Image.open(); im.load()is unaffected, andImageSequence.Iteratorpropagates the error out of theforstatement (atryinside the loop body does not swallow it). Hence low severity. This is adjacent to the GIF extent bomb check added for CVE-2022-45198: the ordering was introduced with that check inc9f1b35e9810("Added GIF decompression bomb check", 2022-06-30), first released in Pillow 9.2.0. Before it, the same size growth happened with no check at all; the check introduced there is the one that runs too late. ## Reproducingreprois a single Python script run against the installed Pillow. It needs about 1.7 GB of free RAM. 1.setup_env()caps the process address space at 3 GiB withRLIMIT_AS, so the oversized allocations end inMemoryErrorinstead of the OOM killer. It then opens the 60-byte GIF shown above, built in memory bybomb_gif(). The GIF contains a 1×1 screen and a 1×1 frame 0, soImage.open()passes its own bomb check. Next comes a bare frame-1 image descriptor that declares 40000×40000 (1.6 Gpx, about 9× the error threshold). A real 1×1 frame follows it. 2.poc()callsim.seek(1)and catchesDecompressionBombError, the way an application that skips bad frames would. 3. First check: the state is inconsistent. The script printsim.sizenext to the real pixel bufferim.im.size. If the rejected frame had left the object unchanged, both would be(1, 1). On the affected codeim.sizeis(40000, 40000). 4. Second check: memory use. The script retriesim.seek(1), which now parses the trailing 1×1 frame, and callsim.load(). It prints the process's peak RSS before and after.load_prepare()sizes itsImage.core.fill()fromim.size, so loading a single pixel fills a 1.6 GB buffer before the 3 GiB cap stops the next allocation. Expected output on the affected tree:open(): 60-byte GIF, size=(1, 1) seek(1) raised as intended: Image size (1600000000 pixels) exceeds limit of 178956970 pixels, could be decompression bomb DOS attack. after the caught error: im.size=(40000, 40000), pixel buffer im.im.size=(1, 1) seek(1) + load() of a 1x1 frame: MemoryError at the 3 GiB cap; peak RSS 18 MiB -> 1700 MiB BUGThe script printsBUGonly if both checks hold: the over-limit size stayed on the object after the exception, and peak RSS grew by more than 1000 MiB while loading a 1×1 frame. Otherwise it printsOK. With the attached patch applied, it printsim.size=(1, 1), peak RSS stays at about 23 MiB, and the last line isOK. ## Suggested fix The attached patch validates before mutating inGifImageFile._seek()(src/PIL/GifImagePlugin.py:292-294): the enlarged extent is computed into a local, passed to_decompression_bomb_check(), and only then assigned toself._size, matching the order of the twodispose_sizechecks further down the same function. A rejected frame therefore leaves the object in its pre-seek state; valid files behave as before, and the exception is still raised at the same point:diff --- a/src/PIL/GifImagePlugin.py +++ b/src/PIL/GifImagePlugin.py @@ -290,8 +290,9 @@ class GifImageFile(ImageFile.ImageFile): x0, y0 = i16(s, 0), i16(s, 2) x1, y1 = x0 + i16(s, 4), y0 + i16(s, 6) if (x1 > self.size[0] or y1 > self.size[1]) and update_image: - self._size = max(x1, self.size[0]), max(y1, self.size[1]) - Image._decompression_bomb_check(self._size) + size = max(x1, self.size[0]), max(y1, self.size[1]) + Image._decompression_bomb_check(size) + self._size = size frame_dispose_extent = x0, y0, x1, y1 flags = s[8]n_frames/is_animatedgo throughupdate_image=Falseand are unaffected. The patch also extendstest_exception_gif_extentsinTests/test_decompression_bomb.pyto assert thatim.sizeis unchanged after theDecompressionBombError. It does not changeseek()itself; optionally,seek()could also treatDecompressionBombErrorlikeEOFErrorand re-seek tolast_frame, so that a retriedseek()does not resume parsing from the middle of the rejected frame. ## The patch GIF: run the decompression bomb check on an enlarging frame's extent before storing it in self._size Applies tosrc/PIL/GifImagePlugin.pyat the commit above.diff diff --git a/Tests/test_decompression_bomb.py b/Tests/test_decompression_bomb.py index 98d833736..83cc785fc 100644 --- a/Tests/test_decompression_bomb.py +++ b/Tests/test_decompression_bomb.py @@ -63,6 +63,9 @@ class TestDecompressionBomb: with pytest.raises(Image.DecompressionBombError): im.seek(1) + # The rejected frame should not have changed the image size + assert im.size == (100, 100) + def test_exception_gif_zero_width(self, monkeypatch: pytest.MonkeyPatch) -> None: # Set limit to trigger exception on the test file monkeypatch.setattr(Image, "MAX_IMAGE_PIXELS", 4 * 64 * 128) diff --git a/src/PIL/GifImagePlugin.py b/src/PIL/GifImagePlugin.py index 11fb180fc..f9bda06c2 100644 --- a/src/PIL/GifImagePlugin.py +++ b/src/PIL/GifImagePlugin.py @@ -290,8 +290,9 @@ class GifImageFile(ImageFile.ImageFile): x0, y0 = i16(s, 0), i16(s, 2) x1, y1 = x0 + i16(s, 4), y0 + i16(s, 6) if (x1 > self.size[0] or y1 > self.size[1]) and update_image: - self._size = max(x1, self.size[0]), max(y1, self.size[1]) - Image._decompression_bomb_check(self._size) + size = max(x1, self.size[0]), max(y1, self.size[1]) + Image._decompression_bomb_check(size) + self._size = size frame_dispose_extent = x0, y0, x1, y1 flags = s[8]## The reproducerReproducer —
Its last line isrepro, 2,474 bytes (click to open)BUGwhen the issue triggers andOKwhen it does not. Re-run on a clean build of that commit it printedBUG.python #!/usr/bin/env python3 # GifImageFile._seek() stores a frame's enlarged size in self._size and only # *then* runs the decompression-bomb check. The check raises, but the object # keeps the rejected 40000x40000 size over its real 1x1 pixel buffer, and the # next load() allocates from that size: 1.6+ GB for a 60-byte GIF. import io import resource import struct from PIL import Image BOMB = 40000 # 40000x40000 = 1.6 Gpx, ~9x the DecompressionBombError threshold LIMIT = 2 * Image.MAX_IMAGE_PIXELS def frame_1x1(): # image descriptor at (0,0) 1x1, then a 1-pixel LZW stream return b"," + struct.pack("<HHHHB", 0, 0, 1, 1, 0) + b"\x02\x02\x44\x01\x00" def bomb_gif(): return ( b"GIF89a" + struct.pack("<HHBBB", 1, 1, 0x80, 0, 0) + b"\x00" * 3 + b"\xff" * 3 + frame_1x1() # frame 0: 1x1, passes open() + b"," + struct.pack("<HHHHB", 0, 0, BOMB, BOMB, 0) # frame 1 claims 40000x40000 + frame_1x1() # a real 1x1 frame follows + b";" ) def peak_rss_mib(): return resource.getrusage(resource.RUSAGE_SELF).ru_maxrss // 1024 def setup_env(): # Cap the address space so the oversized allocations end in MemoryError # instead of the OOM killer. resource.setrlimit(resource.RLIMIT_AS, (3 << 30, 3 << 30)) data = bomb_gif() im = Image.open(io.BytesIO(data)) print(f"open(): {len(data)}-byte GIF, size={im.size}") return im def poc(im): # An application skips the bomb frame and keeps going. try: im.seek(1) except Image.DecompressionBombError as e: print(f"seek(1) raised as intended: {e}") return True return False im = setup_env() raised = poc(im) # Expected: a rejected frame leaves the object as it was (size == buffer == 1x1). print(f"after the caught error: im.size={im.size}, pixel buffer im.im.size={im.im.size}") poisoned = raised and im.size[0] * im.size[1] > LIMIT and im.im.size == (1, 1) # Effect: retrying the seek lands on the real 1x1 frame, but load() sizes its # buffers from the poisoned im.size. before = peak_rss_mib() im.seek(1) try: im.load() outcome = "completed" except MemoryError: outcome = "MemoryError at the 3 GiB cap" after = peak_rss_mib() print(f"seek(1) + load() of a 1x1 frame: {outcome}; peak RSS {before} MiB -> {after} MiB") ballooned = after - before > 1000 print("BUG" if poisoned and ballooned else "OK")============================================================================ TiffDecode returns uninitialized memory as pixels for short JPEG strips Location: src/libImaging/TiffDecode.c:554 in _decodeStrip() Commit: a707c6b21c313880d0771e54965d142dd42358b6 ============================================================================Pillow hands back leftover process memory as image pixels when it opens a small crafted TIFF file. Anyone who can get an application to open their image, and can see something produced from its pixels (a thumbnail, a preview, a converted copy), can read heap memory that the process had previously used and freed. This works in the default configuration: opening and loading the 478-byte file succeeds with no error or warning, and every row below the first eight holds stale memory instead of picture content. The bug is in_decodeStrip()insrc/libImaging/TiffDecode.c, and_decodeTile()has the same shape. The functionrealloc()sstate->buffertoTIFFStripSize()bytes without initialising it and callsTIFFReadEncodedStrip(). Whenever that call does not return -1, it copies allRowsPerStriprows of the buffer into the image. libtiff's JPEG codec only warns when the JPEG embedded in a strip has fewer rows than the strip, and Pillow silences libtiff warnings. The codec decodes the rows that exist and still returns the full strip size, so the untouched remainder is copied out as pixels. libtiff's Group 4 fax codec behaves the same way for a stream that ends early. The attached reproducer builds a 256×256 TIFF whose single strip or tile is a 256×8 JPEG. Before loading it, the script frees buffers filled withb"LEAK". It then finds 15,872 copies ofLEAKin rows 8–255 of the decoded image (the same freed chunk was reused in 500 of 500 runs). Under glibc'sMALLOC_PERTURB_, those rows are entirely the allocator's fill byte. A well-formed control file decodes correctly in both cases. This is a read of uninitialised heap memory, not memory corruption. Each strip can disclose up to width ×RowsPerStripbytes, and what comes back depends on the allocator's state at the time. The strip path was introduced in e91b851fdc1c ("Add reading old-JPEG compressed TIFFs", first released in Pillow 6.0.0). The tile path has had the same pattern since f0436a4ddc95 (Pillow 5.3.0). ## Detailssrc/libImaging/TiffDecode.cdecodes compressed TIFFs through libtiff into a strip (or tile) buffer that itrealloc()s toTIFFStripSize()bytes and never initialises, and then copies allRowsPerStriprows of that buffer into the image wheneverTIFFReadEncodedStrip()does not return -1. libtiff's JPEG codec does not fail when the JPEG stream inside a strip has fewer rows than the strip: it decodes the rows that exist and returns the full strip size. The rows it did not write are whatever the heap held before, and Pillow returns them as pixels. A 478-byte file shows it: a classic little-endian TIFF, 256×256,BitsPerSample=8,Compression=7,PhotometricInterpretation=1,RowsPerStrip=256, one strip whose data is a baseline JPEG of 256×8 pixels (as written byImage.new("L",(256,8),200).save(…,"JPEG")).Image.open(BytesIO(data)).load()succeeds with default settings (compressed TIFFs always take the libtiff path). Rows 0–7 of the result are the JPEG content (value 200); the remaining 63488 bytes ofim.tobytes()are heap garbage: run under glibc'sMALLOC_PERTURB_=1they are all0xFE, underMALLOC_PERTURB_=170all0x55(the fresh-mallocfill byte), and in a process that has just freed buffers containingb"LEAK"they contain 15872 copies ofLEAK. Feeding the same file to libtiff 4.5.0 directly confirms the library side:TIFFReadEncodedStrip(t, 0, buf, 65536)printsJPEGPreDecode: Warning, Improper JPEG strip/tile size, expected 256x256, got 256x8., returns 65536, and leaves 63488 of the 65536 buffer bytes untouched. Pillow installsTIFFSetWarningHandler(NULL)(TiffDecode.c:682), so the warning is not visible either. The strip path:c // src/libImaging/TiffDecode.c:552 /* realloc to fit whole strip */ /* malloc check above */ new_data = realloc(state->buffer, state->bytes); // state->bytes = TIFFStripSize() … state->buffer = new_data; for (; state->y < state->ysize; state->y += rows_per_strip) { … if (TIFFReadEncodedStrip( tiff, TIFFComputeStrip(tiff, state->y, plane), (tdata_t)state->buffer, strip_size ) == -1) { … return -1; } … // iterate over each row in the strip and stuff data into image for (strip_row = 0; strip_row < MIN((INT32)rows_per_strip, state->ysize - state->y); strip_row++) { … shuffler( (UINT8 *)im->image[state->y + state->yoff + strip_row] + state->xoff * im->pixelsize, state->buffer + strip_row * row_byte_size, state->xsize );state->bufferarrives here as the one-rowcallocmade bydecode.c:230((bits*xsize+7)/8= 256 bytes for the example). Thereallocto 65536 bytes hands back a different, uninitialised chunk; nothing zeroes it.TIFFReadEncodedStrip()returns the nominal strip size on success, not the number of rows produced, and the only check is== -1, so the row loop unconditionally copies 256 rows × 256 bytes intoim->image(which itself is zeroed bycore.new, so the garbage provably comes fromstate->buffer)._decodeTile()has the same shape (TiffDecode.c:448realloctoTIFFTileSize(), thentile_lengthrows copied after eachTIFFReadTile()at 460–488). For a well-formed file the JPEG inside the strip is 256×256, libtiff fills all 65536 bytes and the copy is correct. The malicious file differs only in the SOF height of the embedded JPEG; libtiff treats "JPEG smaller than strip" as a warning, clamps the row count to the JPEG height, and reports success. JPEG is not the only libtiff codec that succeeds on a short strip.Fax4Decode(Compression=4) returns success for a T.6 stream that ends early: a 133-byte 512×256 1-bit TIFF whose strip is the Group 4 stream of a 512×16 image loads without error, libtiff writes 17 rows (1088 bytes) of the 16384-byte buffer (Fax4Decode: Warning, Premature EOL at line 16, return value 16384) and the other 15296 bytes are again heap contents. LZW, Deflate, PackBits, Group 3 and CCITT RLE were checked and do return -1 on short data, so Pillow raisesOSErrorfor those. The strip path was introduced ine91b851fdc1c("Add reading old-JPEG compressed TIFFs", 2018-12-08), first released in Pillow 6.0.0, which replaced row-by-rowTIFFReadScanline()(where libtiff errors on the first missing row) with the whole-striprealloc()and copy. The tile path has had the same shape since it was added inf0436a4ddc95(2018-07-02, Pillow 5.3.0). ## Impact Any application that opens attacker-supplied images with Pillow in the default configuration and returns something derived from the pixels (thumbnail, preview, format conversion, OCR text) discloses freed heap memory of the worker process to the uploader: everything below the rows the embedded JPEG/G4 stream actually encodes, up toImageWidth × RowsPerStrip × SamplesPerPixelbytes per strip and tens of MB per image within the defaultMAX_IMAGE_PIXELS.load()raises nothing, so the application has no signal that the image is malformed. What comes back depends on allocator state; in a long-running web worker it is typically recently freed request bodies, other users' decoded image buffers and Python object contents. There is no memory corruption; this is a read of uninitialised (previously used) heap memory, analogous in effect to an out-of-bounds read that lands in pixels. ## Reproducingreprois a short Python script that runs against the installed Pillow build with default settings: no rebuild, no sanitizer, no files written. It runs twice, once normally and once re-executing itself under glibc'sMALLOC_PERTURB_=170, and the last line it prints isBUGorOK. Input.tiff(jpeg_rows, tiled)builds a little-endian TIFF in memory. The header declares a 256×256 8-bit greyscale image withCompression=7(JPEG), either as one strip (RowsPerStrip=256) or as one 256×256 tile (TileWidth/TileLength). The strip or tile is a baseline JPEG of 256×jpeg_rowspixels, all value 200, written by Pillow's own JPEG encoder. For each layout the script builds two files: - Control:jpeg_rows=256. This is a well-formed file, and libtiff fills the whole 64 KiB strip/tile. - Crafted:jpeg_rows=8, 478 bytes (strip) or 490 bytes (tile). The only difference is the embedded JPEG's height. libtiff decodes 8 rows (2048 bytes), warnsImproper JPEG strip/tile size(Pillow silences the warning) and returns the full strip/tile size as success. Steps. Each file is opened (the script asserts it takes thelibtiffdecoder). Just beforeim.load()the script allocates and frees six 64 KiBbytearrays filled withb"LEAK", which leaves freed heap chunks about the size of the buffer that_decodeStrip()/_decodeTile()is about torealloc(). For rows 8–255 it then counts copies ofLEAKand bytes equal to0x55(glibc's fresh-mallocfill underMALLOC_PERTURB_=170). The files contain noLEAKbytes (the script asserts this), so any copy in the image came from freed heap memory. It reportsBUGif a crafted file shows anyLEAKin the normal pass, or rows 8–255 entirely0x55in the perturbed pass. Expected output on this tree:[normal ] strip well-formed (1222 B) rows 8-255: 0 x b'LEAK', 0/63488 == 0x55, head=b'\xc8\xc8\xc8\xc8\xc8\xc8\xc8\xc8' [normal ] strip crafted ( 478 B) rows 8-255: 15872 x b'LEAK', 0/63488 == 0x55, head=b'LEAKLEAK' [normal ] tiled well-formed (1234 B) rows 8-255: 0 x b'LEAK', 0/63488 == 0x55, head=b'\xc8\xc8\xc8\xc8\xc8\xc8\xc8\xc8' [normal ] tiled crafted ( 490 B) rows 8-255: 15872 x b'LEAK', 0/63488 == 0x55, head=b'LEAKLEAK' [perturb] strip well-formed (1222 B) rows 8-255: 0 x b'LEAK', 0/63488 == 0x55, head=b'\xc8\xc8\xc8\xc8\xc8\xc8\xc8\xc8' [perturb] strip crafted ( 478 B) rows 8-255: 0 x b'LEAK', 63488/63488 == 0x55, head=b'UUUUUUUU' [perturb] tiled well-formed (1234 B) rows 8-255: 0 x b'LEAK', 0/63488 == 0x55, head=b'\xc8\xc8\xc8\xc8\xc8\xc8\xc8\xc8' [perturb] tiled crafted ( 490 B) rows 8-255: 0 x b'LEAK', 63488/63488 == 0x55, head=b'UUUUUUUU' BUGim.load()succeeds for every file. For the crafted files rows 8–255 are the uninitialised strip/tile buffer, copied as-is into the image. With the attached patch applied, rows 8–255 of the crafted files come back as\x00bytes, with noLEAKand no0x55, and the script ends withOK. TheLEAKcount depends on where glibc places the buffer (the same freed chunk was reused in 500 of 500 runs here); theMALLOC_PERTURB_pass does not. The script covers the JPEG codec only. The Group 4 variant in the Details section (Compression=4, a T.6 stream that ends early) goes through the same_decodeStrip()copy, and the same fix covers it. ## Suggested fix The attached patch zeroesstate->bufferbefore each libtiff read in both loops ofsrc/libImaging/TiffDecode.c— beforeTIFFReadTile()in_decodeTile()and beforeTIFFReadEncodedStrip()in_decodeStrip()— so rows a codec does not produce are deterministic zeros rather than stale heap:diff --- a/src/libImaging/TiffDecode.c +++ b/src/libImaging/TiffDecode.c @@ _decodeTile for (x = state->xoff; x < state->xsize; x += tile_width) { + memset(state->buffer, 0, state->bytes); if (TIFFReadTile(tiff, (tdata_t)state->buffer, x, y, 0, plane) == -1) { @@ _decodeStrip for (plane = 0; plane < planes; plane++) { ImagingShuffler shuffler = unpackers[plane]; + memset(state->buffer, 0, state->bytes); if (TIFFReadEncodedStrip(Amemsetper strip/tile (rather than onecallocafter the size is known) is needed because the same buffer is reused for every strip, and a short last strip would otherwise expose the previous strip's rows — harmless for disclosure, but the per-readmemsetkeeps the behaviour uniform at the cost of one extra pass over the buffer. Promoting libtiff warnings to errors via a warning handler is not a good alternative: both codecs only warn (Improper JPEG strip/tile size,Premature EOL), but so do many legitimate files (unknown tags, bad tag counts), and the return value ofTIFFReadEncodedStrip()carries no row count to check against. Initialising the buffer covers every codec._decodeAsRGBA()needs no change:TIFFRGBAImageGet()fills its whole raster, and JPEG files do not reach it (JPEGCOLORMODE_RGBsends them down the strip path). Valid files decode exactly as before; rows a codec does not produce are now black instead of garbage, and nothing that previously loaded now fails. The patch also addstest_jpeg_short_striptoTests/test_file_libtiff.py, parametrised over strip and tile, which builds the 256×8-JPEG-in-256×256 file and asserts rows 8–255 are zero. It is a regression guard for the fixed code rather than a reliable detector of the bug: in a fresh pytest process the unfixed strip variant can pass because the new heap chunk happens to be zero (the tiled variant fails before the fix). With the patch,Tests/test_file_libtiff.pyandTests/test_file_tiff.pypass and the reproducer printsOK. ## The patch Zero the libtiff strip/tile buffer before each TIFFReadEncodedStrip/TIFFReadTile in TiffDecode.c so short strips do not expose uninitialised heap Applies tosrc/libImaging/TiffDecode.cat the commit above.diff diff --git a/Tests/test_file_libtiff.py b/Tests/test_file_libtiff.py index 3d804ea4a..67bc96329 100644 --- a/Tests/test_file_libtiff.py +++ b/Tests/test_file_libtiff.py @@ -1162,6 +1162,45 @@ class TestFileLibTiff(LibTiffTestCase): im.load() assert im.size == (950, 975) + @pytest.mark.parametrize("tiled", (False, True)) + def test_jpeg_short_strip(self, tiled: bool) -> None: + # The JPEG data in the strip/tile only contains 8 of the 256 rows that + # RowsPerStrip/TileLength declare. libtiff decodes the rows that exist + # and still reports success, so the remaining rows must be cleared + # rather than left as uninitialised memory. + jpeg = io.BytesIO() + Image.new("L", (256, 8), 200).save(jpeg, "JPEG") + jpeg_data = jpeg.getvalue() + + ifd = TiffImagePlugin.ImageFileDirectory_v2() + ifd[256] = 256 # ImageWidth + ifd[257] = 256 # ImageLength + ifd[258] = 8 # BitsPerSample + ifd[259] = 7 # Compression: JPEG + ifd[262] = 1 # PhotometricInterpretation: BlackIsZero + ifd[277] = 1 # SamplesPerPixel + if tiled: + ifd[322] = 256 # TileWidth + ifd[323] = 256 # TileLength + ifd[324] = 0 # TileOffsets + ifd[325] = len(jpeg_data) # TileByteCounts + # Point the tile data at the end of the IFD + ifd[324] = 8 + len(ifd.tobytes(8)) + else: + ifd[278] = 256 # RowsPerStrip + ifd[STRIPOFFSETS] = 0 # Updated by tobytes() to follow the IFD + ifd[279] = len(jpeg_data) # StripByteCounts + + b = io.BytesIO() + ifd.save(b) + b.write(jpeg_data) + + with Image.open(b) as im: + assert im.tile[0][0] == "libtiff" + im.load() + assert im.crop((0, 0, 256, 8)).getextrema() == (200, 200) + assert im.crop((0, 8, 256, 256)).getextrema() == (0, 0) + def test_orientation(self) -> None: with Image.open("Tests/images/g4_orientation_1.tif") as base_im: for i in range(2, 9): diff --git a/src/libImaging/TiffDecode.c b/src/libImaging/TiffDecode.c index 8a57c523d..d1d6bfbbb 100644 --- a/src/libImaging/TiffDecode.c +++ b/src/libImaging/TiffDecode.c @@ -457,6 +457,11 @@ _decodeTile( for (plane = 0; plane < planes; plane++) { ImagingShuffler shuffler = unpackers[plane]; for (x = state->xoff; x < state->xsize; x += tile_width) { + // Some codecs (e.g. JPEG, Group 4) succeed on a tile that decodes + // to fewer rows than the tile length, leaving the rest of the + // buffer untouched. Clear it so that uninitialised memory is not + // copied into the image. + memset(state->buffer, 0, state->bytes); if (TIFFReadTile(tiff, (tdata_t)state->buffer, x, y, 0, plane) == -1) { TRACE(("Decode Error, Tile at %dx%d\n", x, y)); state->errcode = IMAGING_CODEC_BROKEN; @@ -563,6 +568,11 @@ _decodeStrip( int plane; for (plane = 0; plane < planes; plane++) { ImagingShuffler shuffler = unpackers[plane]; + // Some codecs (e.g. JPEG, Group 4) succeed on a strip that decodes + // to fewer rows than RowsPerStrip, leaving the rest of the buffer + // untouched. Clear it so that uninitialised memory is not copied + // into the image. + memset(state->buffer, 0, state->bytes); if (TIFFReadEncodedStrip( tiff, TIFFComputeStrip(tiff, state->y, plane),## The reproducerReproducer —
Its last line isrepro, 2,688 bytes (click to open)BUGwhen the issue triggers andOKwhen it does not. Re-run on a clean build of that commit it printedBUG.python #!/usr/bin/env python3 # Pillow TiffDecode.c _decodeStrip/_decodeTile: strip/tile buffer is realloc()ed, never # initialised, and copied whole into the image even when libtiff's JPEG codec decoded # fewer rows than RowsPerStrip/TileLength. Two independent signals: # pass 1 (normal heap): seed freed 64 KiB chunks with b"LEAK" just before load() and # count copies of LEAK in the decoded pixels (file contains no such bytes); # pass 2 (same script re-run under glibc MALLOC_PERTURB_=170): fresh malloc memory is # 0x55, so rows that come back all-0x55 are provably uninitialised heap. import gc, io, os, struct, subprocess, sys from PIL import Image W = H = 256; ROWS = 8 perturbed = os.environ.get("MALLOC_PERTURB_") == "170" if not perturbed: print("Pillow", Image.__version__, Image.core.__file__) def tiff(jpeg_rows, tiled): j = io.BytesIO(); Image.new("L", (W, jpeg_rows), 200).save(j, "JPEG"); j = j.getvalue() tags = [(256,3,1,W), (257,3,1,H), (258,3,1,8), (259,3,1,7), (262,3,1,1), (277,3,1,1)] tags += ([(322,3,1,W), (323,3,1,H), (324,4,1,0), (325,4,1,len(j))] if tiled else [(273,4,1,0), (278,3,1,H), (279,4,1,len(j))]) tags.sort(); off = 8 + 2 + 12*len(tags) + 4 tags = [(t,ty,c, off if t in (273,324) else v) for t,ty,c,v in tags] ifd = struct.pack("<H", len(tags)) + b"".join(struct.pack("<HHLL", *t) for t in tags) return b"II*\0" + struct.pack("<L", 8) + ifd + struct.pack("<L", 0) + j bug = False for tiled in (False, True): for jpeg_rows, label in ((H, "well-formed"), (ROWS, "crafted")): data = tiff(jpeg_rows, tiled); assert b"LEAK" not in data im = Image.open(io.BytesIO(data)); assert im.tile[0][0] == "libtiff" junk = [bytearray(b"LEAK" * (W*H//4)) for _ in range(6)]; del junk; gc.collect() im.load() # no exception for either file below = im.tobytes()[W*ROWS:] n55, nleak = below.count(0x55), below.count(b"LEAK") print(f"[{'perturb' if perturbed else 'normal '}] {'tiled' if tiled else 'strip'} " f"{label:11s} ({len(data):4d} B) rows {ROWS}-{H-1}: {nleak:5d} x b'LEAK', " f"{n55:5d}/{len(below)} == 0x55, head={below[:8]!r}") if jpeg_rows == ROWS and (nleak > 0 or (perturbed and n55 == len(below))): bug = True if not perturbed: r = subprocess.run([sys.executable, sys.argv[0]], env={**os.environ, "MALLOC_PERTURB_": "170"}, capture_output=True, text=True) lines = r.stdout.rstrip().split("\n") print("\n".join(lines[:-1])); sys.stderr.write(r.stderr) bug = bug or lines[-1] == "BUG" print("BUG" if bug else "OK")_decodeTiledecoder, used to decode tiled TIFF images, allocates a per-tile buffer usingrealloc(state->buffer, TIFFTileSize(tiff)). After eachTIFFReadTileit then iteratestile_yfrom 0 up tocurrent_tile_lengthand calls the configured row unpacker (herecopy4) with the source pointerstate->buffer + tile_y * row_byte_size. When libtiff returns atile_bytes_sizesmaller than the worst-caserow_byte_size * tile_length, the inner stride-and-copy loop walks past the realloc'd region andcopy4performs a 1024-bytememcpythat reads up to(tile_length-1) * row_byte_size + row_byte_sizebytes from a buffer sized only totile_bytes_size. The supplied PoC TIFF triggers a 1024-byte over-read exactly 0 bytes past a 196608-byte allocation. An attacker who can convince a Pillow-using application to decode a crafted TIFF can trigger a process crash (DoS) and may cause adjacent heap memory to be copied into the decoded pixel buffer. ### Details Pillow's TIFF decoder, when libtiff reports the file is tiled, takes the_decodeTilepath. The function: 1. Asks libtiff forTIFFTileSize(tiff)(the bytes-per-tile) andTIFFTileRowSize(tiff)(the bytes per row as stored by libtiff). 2. Reallocatesstate->bufferto exactlytile_bytes_size. 3. For each tile origin(x, y)and each plane, callsTIFFReadTileintostate->buffer, then walks the tile row by row, calling the configuredImagingShuffler(herecopy4) on each row's worth of source bytes. The validation done before the loop is:c if (tile_bytes_size > ((tile_length * state->bits / planes + 7) / 8) * tile_width) { state->errcode = IMAGING_CODEC_BROKEN; return -1; }This rejects oversized libtiff tiles, but it does not reject undersized ones — i.e. the case where libtiff returns atile_bytes_sizestrictly less thanrow_byte_size * tile_length. The loop body, however, indexes into the buffer assuming the buffer is at leastrow_byte_size * tile_lengthbytes long. ### Vulnerable Codec // src/libImaging/TiffDecode.c:446-490 — _decodeTile new_data = realloc(state->buffer, state->bytes); // bytes = tile_bytes_size if (!new_data) { ... } state->buffer = new_data; for (y = state->yoff; y < state->ysize; y += tile_length) { for (plane = 0; plane < planes; plane++) { ImagingShuffler shuffler = unpackers[plane]; for (x = state->xoff; x < state->xsize; x += tile_width) { if (TIFFReadTile(tiff, (tdata_t)state->buffer, x, y, 0, plane) == -1) { ... } current_tile_width = min((INT32)tile_width, state->xsize - x); current_tile_length = min((INT32)tile_length, state->ysize - y); for (tile_y = 0; tile_y < current_tile_length; tile_y++) { shuffler( (UINT8 *)im->image[tile_y + y] + x * im->pixelsize, state->buffer + tile_y * row_byte_size, // <-- OOB stride current_tile_width ); } } } }c // src/libImaging/Unpack.c:1288-1291 — copy4 (the crash site) static void copy4(UINT8 *out, const UINT8 *in, int pixels) { /* RGBA, CMYK quadruples */ memcpy(out, in, 4 * pixels); // <-- ASAN-detected READ here }The PoC's tile metadata yieldstile_width = tile_length = 256,row_byte_size = 1024(4 bytes/pixel × 256 pixels), andtile_bytes_size = 196608(which is 256·256·3 = three-channel-byte storage). The realloc'd buffer is 196608 bytes. The unpacker iteratestile_yfrom 0 to 255 and for the highest rows the source pointerstate->buffer + tile_y * 1024already lies at or past offset 196608 — the very last row'smemcpy(in=buffer+255·1024, 1024)reads 1024 bytes starting260096 - 196608 = 63488bytes past the allocation; ASAN flags the very first byte past the heap region (READ of size 1024 at … 0 bytes after 196608-byte region). The mismatch is real: libtiff'sTIFFTileSizereturns the packed per-tile storage (which depends on the file's photometric/separation layout — it can legitimately be smaller thanrow_byte_size × tile_length), while the inner loop strides as if the buffer always equalsrow_byte_size × tile_length. ## Attribution This issue was found by Anthropic from using Claude to study security of open source projects, and I am from Ada Logics helping validate the found issues and report to maintainers. The data in this report has been reviewed manually.============================================================================ OOB read in TiffDecode.c tile and RGBA paths leaks heap memory into pixels Location: src/libImaging/TiffDecode.c:483 in _decodeTile() Commit: a707c6b21c313880d0771e54965d142dd42358b6 ============================================================================Pillow reads past the end of a heap buffer when decoding certain malformed compressed TIFF files, and copies the bytes it reads into the pixels of the image it returns. An attacker who can get an application to open and load an image file, for example by uploading it to a service that returns thumbnails, previews or converted images, gets back fragments of that process's heap memory, including pointer values. A slightly larger file instead crashes the process. No special settings are needed, and nothing is written out of bounds. The bug is in_decodeTile()and_decodeAsRGBA()insrc/libImaging/TiffDecode.c. Both size their decode buffer from libtiff's view of the pixel layout (TIFFTileSize()/TIFFTileRowSize(), orimg.width * 4). They then unpack each row with the unpacker thatTiffImagePlugin._setup()chose from Pillow's own parse of the directory, and neither checks that the unpacker's input row fits inside the row libtiff produced._decodeStrip()has exactly this check, added for OSS-Fuzzcrash-0da0in 8.2.0, but the tile and RGBA paths never got it. The two parsers can be made to disagree with a duplicatedPhotometricInterpretationorBitsPerSampletag, because libtiff keeps the first occurrence and Pillow keeps the last. Pillow then unpacks 4 to 8 bytes per pixel from rows that libtiff filled with 1 to 4 bytes, so the last rows of each tile are read from beyond the buffer. The disclosed memory is a few tile rows past the buffer, and the attacker chooses the tile width. The amount does not grow with the number of tiles, because the buffer is reused for every tile. The tile half was introduced in 1c295bf43 (first released in 8.2.0). The RGBA half was introduced in eb8c1206d, the CVE-2020-35654 fix (8.1.0). The attached reproducer runs against an unmodified build. It writes three roughly 400-byte files that load without error, yet the last pixel rows of each change with glibc's malloc fill pattern and contain heap pointer bytes. A fourth file with a 65536x16 tile segfaults incopy4←_decodeTile(TiffDecode.c:483) in most runs, depending on what is mapped after the buffer. ## Details_decodeTile()and_decodeAsRGBA()insrc/libImaging/TiffDecode.csizestate->bufferfrom what libtiff says it will produce (TIFFTileSize(), resp.img.width * 4), but unpack each row with the shuffler thatTiffImagePlugin._setup()selected from Pillow's own parse of the IFD. Nothing in either function checks that the unpacker's input row (width * state->bits / 8bytes) fits inside the row libtiff wrote._decodeStrip()has exactly that check; the other two do not. Whenever the two IFD parsers disagree about the pixel layout — a tag with the wrong count or type that libtiff ignores but Pillow accepts, or a duplicatedPhotometricInterpretation/BitsPerSample/SamplesPerPixelentry (libtiff keeps the first occurrence,ImageFileDirectory_v2.load()the last) — the unpacker reads past the end of the heap buffer and the bytes it reads become pixels of the returned image. Any Pillow rawmode wider than libtiff's actual sample layout works (RGBX,RGB;16N,RGBA;16N,I;32,F;32F, …);RGBA;16N(64 bits/pixel) against 1-bit libtiff data is the largest ratio, where every row after the first of each tile is read almost entirely from beyond the buffer. The ~400-byte TIFFtile_count2.tifgenerated by the reproducer — one 16x16 tile,BitsPerSample 8,SamplesPerPixel 1,Compression 8(Adobe Deflate), andPhotometricInterpretationwritten as a SHORT with count 2 (6, 6) — is opened byImage.open()as modeRGBwith libtiff rawmodeRGBX, andload()succeeds on the stock build. Rows 13–15 of the result contain bytes that lie 16, 32 and 48 bytes past the 256-byte tile buffer: decoding the same file twice underMALLOC_PERTURB_=85and=170yields identical rows 0–12 and different bytes in rows 13–15 (aavs55, i.e. glibc's fill pattern). Under an ASan build of the extensions the sameload()reportsheap-buffer-overflow READ of size 64incopy4(src/libImaging/Unpack.c:1290) called fromsrc/libImaging/TiffDecode.c:483, against the 256-byte region allocated atTiffDecode.c:448. The same layout with a single 65536x16 tile (4.5 KB file) makes the stock build SIGSEGV incopy4 ← _decodeTilereading an unmapped address in most runs (whether it faults depends on what is mapped after the 1 MiB buffer; a wider tile makes it reliable). ### Why the two parsers disagree libtiff 4.5 rejects aPhotometricInterpretationentry whose count is not 1 (TIFFFetchNormalTag: Incorrect count for "PhotometricInterpretation"; tag ignored), so for this fileTIFFGetField(tiff, TIFFTAG_PHOTOMETRIC, …)returns 0 and libtiff treats the data as one 8-bit sample per pixel:TIFFTileSize() = 256,TIFFTileRowSize() = 16. Pillow keeps the first value and carries on:python # src/PIL/TiffImagePlugin.py:762-770 (ImageFileDirectory_v2._setitem, reached from load()) try: (dest[tag],) = values except ValueError: # We've got a builtin tag with 1 expected entry warnings.warn(f"Metadata Warning, tag {tag} had too many entries: ...") dest[tag] = values[0]so_setup()seesphoto == 6.OPEN_INFO[(II, 6, (1,), 1, (8,), ())]is("L", "L"), and because the file is compressed the libtiff branch then overrides the rawmode:python # src/PIL/TiffImagePlugin.py:1578, 1600-1607 self.use_load_libtiff = READ_LIBTIFF or self._compression != "raw" … if photo == 6: self._mode = "RGB" if self._compression in "jpeg" and self._planar_configuration == 1: rawmode = "RGB" else: rawmode = "RGBX"RGBXis a 32-bit rawmode, soget_unpacker()(src/decode.c:301-309) setsstate->bits = 32andstate->shuffle = copy4. The intent of thephoto == 6override is that libtiff will deliver RGBA throughTIFFRGBAImage, but that decision is made in C from libtiff's reading of the tag, which here is "not YCbCr":c // src/libImaging/TiffDecode.c:737-764 TIFFGetField(tiff, TIFFTAG_PHOTOMETRIC, &photometric); // unset -> stays 0 … readAsRGBA = photometric == PHOTOMETRIC_YCBCR; // 0 … if (TIFFIsTiled(tiff)) { _decodeTile(im, state, tiff, planes, unpackers); // unpackers[0] = copy4### The missing check_decodeTile()only guards against libtiff's tile being larger than what the unpacker expects, then allocates exactlyTIFFTileSize()bytes and feedsrow_byte_size-strided rows to the shuffler:c // src/libImaging/TiffDecode.c:403-487 (_decodeTile) tile_bytes_size = TIFFTileSize(tiff); // 256 … row_byte_size = TIFFTileRowSize(tiff); // 16 … if (tile_bytes_size > ((tile_length * state->bits / planes + 7) / 8) * tile_width) { // 256 > 1024 is false -> no abort … } state->bytes = tile_bytes_size; new_data = realloc(state->buffer, state->bytes); // 256-byte buffer (line 448) … for (tile_y = 0; tile_y < current_tile_length; tile_y++) { shuffler( // copy4: reads current_tile_width*4 = 64 bytes (UINT8 *)im->image[tile_y + y] + x * im->pixelsize, state->buffer + tile_y * row_byte_size, // from offset 16*tile_y current_tile_width );Rowtile_yis read from[16·tile_y, 16·tile_y + 64); fortile_y= 13, 14, 15 that ends 16, 32, 48 bytes past the 256-byte allocation. In general the last rows of every tile over-read by up to(state->bits / libtiff_bits_per_pixel − 1) × row_byte_sizebytes, androw_byte_sizescales with the attacker-chosenTileWidth. Note also that the existing one-sided check at line 434 multiplies the file-controlledtile_width/tile_length(UINT32, accepted up toINT_MAXat line 428) bystate->bitsin 32-bit unsigned arithmetic, sotile_width * state->bitswraps fortile_width ≥ 2^32 / bits(2^26 for the 64-bit rawmodes, 2^27 forRGBX/I;32/F;32F). An 8 KB file declaring a 2,097,152×1 image withTILEWIDTH = 2^26+16,TILELENGTH = 1, 1-bit data for libtiff andRGBA;16Nfor Pillow makes libtiff allocate an ~8 MB tile from whichunpackRGBA16Lreads 16 MB, and the stock build SIGSEGVs inunpackRGBA16L ← _decodeTile (TiffDecode.c:483); a row-size comparison written in t