From f7a31ea75e460e108c37126da1f47812f21f6b09 Mon Sep 17 00:00:00 2001
From: Andrew Murray <3112309+radarhere@users.noreply.github.com>
Date: Tue, 30 Jun 2026 09:17:05 +1000
Subject: [PATCH] Add max_length to PdfStream decode() (#9718)

---
 Tests/test_pdfparser.py | 11 +++++++++++
 src/PIL/PdfParser.py    | 15 +++++++++------
 2 files changed, 20 insertions(+), 6 deletions(-)

Index: pillow-11.3.0/Tests/test_pdfparser.py
===================================================================
--- pillow-11.3.0.orig/Tests/test_pdfparser.py
+++ pillow-11.3.0/Tests/test_pdfparser.py
@@ -1,6 +1,7 @@
 from __future__ import annotations
 
 import time
+import zlib
 
 import pytest
 
@@ -95,6 +96,16 @@ def test_parsing() -> None:
             assert time.strftime("%Y%m%d%H%M%S", getattr(d, name)) == value
 
 
+def test_pdfstream_flatedecode() -> None:
+    d = PdfDict({b"Filter": b"FlateDecode"})
+    buf = zlib.compress(b"test")
+    s = PdfStream(d, buf)
+    assert s.decode() == b"test"
+
+    with pytest.raises(ValueError, match="Decompressed data too large"):
+        s.decode(3)
+
+
 def test_pdf_repr() -> None:
     assert bytes(IndirectReference(1, 2)) == b"1 2 R"
     assert bytes(IndirectObjectDef(*IndirectReference(1, 2))) == b"1 2 obj"
Index: pillow-11.3.0/src/PIL/PdfParser.py
===================================================================
--- pillow-11.3.0.orig/src/PIL/PdfParser.py
+++ pillow-11.3.0/src/PIL/PdfParser.py
@@ -251,6 +251,8 @@ class PdfArray(list[Any]):
         return b"[ " + b" ".join(pdf_repr(x) for x in self) + b" ]"
 
 
+from . import ImageFile
+
 TYPE_CHECKING = False
 if TYPE_CHECKING:
     _DictBase = collections.UserDict[Union[str, bytes], Any]
@@ -319,17 +321,18 @@ class PdfStream:
         self.dictionary = dictionary
         self.buf = buf
 
-    def decode(self) -> bytes:
+    def decode(self, max_length: int = ImageFile.SAFEBLOCK) -> 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))
+            dobj = zlib.decompressobj()
+            plaintext = dobj.decompress(self.buf, max_length)
+            if dobj.unconsumed_tail:
+                msg = "Decompressed data too large"
+                raise ValueError(msg)
+            return plaintext
         else:
             msg = f"stream filter {repr(filter)} unknown/unsupported"
             raise NotImplementedError(msg)
