Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

fix(parse): check the PNG canvas size before Image.open (#2088)

Sakshi Jain706d8c383a8e
diff --git a/semantica/parse/image_parser.py b/semantica/parse/image_parser.py
index d389fd13..6000be2e 100644
--- a/semantica/parse/image_parser.py
+++ b/semantica/parse/image_parser.py
@@ -33,6 +33,7 @@ License: MIT
import io
import os
import stat
+import struct
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any, Dict, List, Optional, Union
@@ -63,6 +64,12 @@ FORMAT_ALIASES = {"JPG": "JPEG", "TIF": "TIFF", "MPO": "JPEG"}
DEFAULT_MAX_FILE_SIZE = 50 * 1024 * 1024 # bytes
+PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n"
+
+# Most chunks accepted between a PNG's IHDR and its image data. Real files
+# have a few dozen; libpng stops storing ancillary chunks after 1000.
+MAX_PNG_HEADER_CHUNKS = 1000
+
# Image modes Pillow's PNG encoder can write. 32-bit "I" is not one of them:
# Pillow 13 no longer clips it to 16 bits on save, so it is converted first.
PNG_MODES = frozenset({"1", "L", "LA", "I;16", "I;16B", "P", "RGB", "RGBA"})
@@ -111,6 +118,50 @@ def _webp_canvas_size(data: bytes) -> Optional[tuple]:
return None
+def _png_canvas_size(data: bytes) -> Optional[tuple]:
+ """
+ Read the canvas size from a PNG header without decoding.
+
+ For an APNG whose first frame disposes to the background, Pillow before
+ 13.0 allocates the full canvas inside Image.open, before it checks the
+ image size (GHSA-5xm2-6676-qcp9), so a tiny PNG can claim a huge canvas.
+
+ Args:
+ data: File contents
+
+ Returns:
+ tuple: (width, height), or None if the header can't be read, there
+ is more than one IHDR chunk, or there are more than
+ MAX_PNG_HEADER_CHUNKS chunks before the image data
+ """
+ # IHDR must be the first chunk: length, type, then big-endian width and
+ # height.
+ if len(data) < 24 or data[:8] != PNG_SIGNATURE or data[12:16] != b"IHDR":
+ return None
+
+ # Image.open reads chunks up to the image data and takes the size from
+ # the last IHDR, so a second one could claim a bigger canvas than the
+ # first. The PNG spec allows only one. The walk is bounded, so a file of
+ # millions of empty chunks can't stall it.
+ pos = 20 + int.from_bytes(data[8:12], "big")
+ for _ in range(MAX_PNG_HEADER_CHUNKS + 1):
+ if pos + 8 > len(data):
+ break
+ length, chunk = struct.unpack_from(">I4s", data, pos)
+ if chunk == b"IHDR":
+ return None
+ if chunk in (b"IDAT", b"fdAT", b"IEND"):
+ break
+ pos += 12 + length
+ else:
+ return None
+
+ return (
+ int.from_bytes(data[16:20], "big"),
+ int.from_bytes(data[20:24], "big"),
+ )
+
+
def _ocr_copy(img: PILImage) -> PILImage:
"""
Make the RGB copy that is handed to tesseract.
@@ -312,6 +363,15 @@ class ImageParser:
raise ValidationError(f"Unreadable WebP header: {file_path}")
self._check_pixels(size, file_path)
+ # Likewise Pillow's PNG plugin for some APNGs, before Pillow 13.0.
+ # Every PNG is checked, since they all share the header.
+ is_png = data[:8] == PNG_SIGNATURE
+ if is_png and "PNG" in self.allowed_formats:
+ size = _png_canvas_size(data)
+ if size is None:
+ raise ValidationError(f"Unreadable PNG header: {file_path}")
+ self._check_pixels(size, file_path)
+
try:
img = Image.open(io.BytesIO(data), formats=self.allowed_formats)
except UnidentifiedImageError:
diff --git a/tests/parse/test_image_parser.py b/tests/parse/test_image_parser.py
index 72cf488f..0524b528 100644
--- a/tests/parse/test_image_parser.py
+++ b/tests/parse/test_image_parser.py
@@ -12,8 +12,8 @@ Covers:
refused without blocking
- Unexpected open failures are logged and wrapped as ProcessingError
- The OCR input keeps text in 16-bit and transparent images
- - Config validation, pixel limits (including WebP headers and Pillow's
- own bomb check) and error mapping
+ - Config validation, pixel limits (including WebP and PNG headers and
+ Pillow's own bomb check) and error mapping
"""
import os
@@ -28,7 +28,12 @@ from unittest.mock import MagicMock, patch
from PIL import Image
-from semantica.parse.image_parser import ImageParser, _webp_canvas_size
+from semantica.parse.image_parser import (
+ MAX_PNG_HEADER_CHUNKS,
+ ImageParser,
+ _png_canvas_size,
+ _webp_canvas_size,
+)
from semantica.utils.exceptions import ProcessingError, ValidationError
@@ -348,8 +353,14 @@ class TestImageParserLimits(unittest.TestCase):
# --- Pixel limits ---
- def _png_header(self, width, height):
- """A PNG with only a header and an empty IDAT: opens, never decodes."""
+ def _png_header(self, width, height, animated=False):
+ """
+ A PNG with only a header and an empty IDAT: opens, never decodes.
+
+ animated adds the acTL and fcTL chunks of an APNG whose first frame
+ disposes to the background, for which Pillow before 13.0 allocates
+ the whole canvas inside Image.open.
+ """
def chunk(kind, body):
return (
@@ -360,26 +371,44 @@ class TestImageParserLimits(unittest.TestCase):
)
ihdr = struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0)
+ frames = b""
+ if animated:
+ # Sequence, size, offset, delay, then dispose_op 1 (background).
+ fctl = struct.pack(">IIIIIHHBB", 0, width, height, 0, 0, 1, 1, 1, 0)
+ frames = chunk(b"acTL", struct.pack(">II", 1, 0)) + chunk(b"fcTL", fctl)
path = self.dir / f"{width}x{height}.png"
path.write_bytes(
b"\x89PNG\r\n\x1a\n"
+ chunk(b"IHDR", ihdr)
+ + frames
+ chunk(b"IDAT", b"")
+ chunk(b"IEND", b"")
)
return path
+ def _bmp_header(self, width, height):
+ """
+ A BMP with only a header: opens, never decodes.
+
+ Unlike PNG and WebP, its size isn't checked before Image.open, so
+ it reaches Pillow's own bomb check.
+ """
+ info = struct.pack("<IiiHHIIiiII", 40, width, height, 1, 24, 0, 0, 0, 0, 0, 0)
+ path = self.dir / f"{width}x{height}.bmp"
+ path.write_bytes(struct.pack("<2sIHHI", b"BM", 54, 0, 0, 54) + info)
+ return path
+
def test_over_pillow_hard_limit_is_validation_error(self):
# Over 2 * MAX_IMAGE_PIXELS, Pillow raises DecompressionBombError.
side = int((2 * Image.MAX_IMAGE_PIXELS) ** 0.5) + 10
with self.assertRaises(ValidationError):
- ImageParser().extract_metadata(self._png_header(side, side))
+ ImageParser().extract_metadata(self._bmp_header(side, side))
def test_pillow_warning_does_not_escape(self):
# Between MAX and 2 * MAX Pillow only warns; our own check must
# still produce a ValidationError, even when warnings are errors.
side = int((1.5 * Image.MAX_IMAGE_PIXELS) ** 0.5)
- path = self._png_header(side, side)
+ path = self._bmp_header(side, side)
with warnings.catch_warnings():
warnings.simplefilter("error")
with self.assertRaises(ValidationError):
@@ -391,7 +420,7 @@ class TestImageParserLimits(unittest.TestCase):
# depend on.
parser = ImageParser()
png = self._image("a.png", "PNG")
- oversized = self._png_header(10_000, 10_000)
+ oversized = self._bmp_header(10_000, 10_000)
# Pillow's own warning still reaches the caller as usual; our check
# then rejects the image.
@@ -439,6 +468,74 @@ class TestImageParserLimits(unittest.TestCase):
expected = img.size
self.assertEqual(_webp_canvas_size(path.read_bytes()), expected)
+ def test_png_canvas_checked_before_pillow_opens_it(self):
+ # A tiny APNG claiming a 22000 x 22000 canvas: Pillow before 13.0
+ # would allocate about 1.9 GB inside Image.open (GHSA-5xm2-6676-qcp9),
+ # so it must be refused before that. Plain PNGs are checked the same
+ # way.
+ for animated in (True, False):
+ with self.subTest(animated=animated):
+ path = self._png_header(22_000, 22_000, animated=animated)
+ with patch("semantica.parse.image_parser.Image.open") as image_open:
+ with self.assertRaises(ValidationError):
+ ImageParser().extract_metadata(path)
+ image_open.assert_not_called()
+
+ def test_unreadable_png_header_is_refused(self):
+ # The PNG signature, but no IHDR chunk after it.
+ path = self.dir / "a.png"
+ path.write_bytes(b"\x89PNG\r\n\x1a\n" + b"\x00" * 16)
+ with patch("semantica.parse.image_parser.Image.open") as image_open:
+ with self.assertRaises(ValidationError):
+ ImageParser().extract_metadata(path)
+ image_open.assert_not_called()
+
+ def test_second_png_ihdr_is_refused(self):
+ # Pillow takes the size from the last IHDR, so a small first one
+ # followed by a 22000 x 22000 one must not get past the check.
+ big_ihdr = self._png_header(22_000, 22_000).read_bytes()[8:33]
+ path = self._png_header(1, 1, animated=True)
+ data = path.read_bytes()
+ path.write_bytes(data[:33] + big_ihdr + data[33:])
+ with patch("semantica.parse.image_parser.Image.open") as image_open:
+ with self.assertRaises(ValidationError):
+ ImageParser().extract_metadata(path)
+ image_open.assert_not_called()
+
+ def test_png_header_chunk_walk_is_bounded(self):
+ # Up to MAX_PNG_HEADER_CHUNKS chunks before the image data are
+ # walked; one more is refused without walking the rest, so millions
+ # of empty chunks can't stall the check.
+ data = self._image("a.png", "PNG").read_bytes()
+ empty = struct.pack(">I", 0) + b"tEXt" + struct.pack(">I", zlib.crc32(b"tEXt"))
+ path = self.dir / "chunks.png"
+
+ path.write_bytes(data[:33] + empty * MAX_PNG_HEADER_CHUNKS + data[33:])
+ self.assertEqual(ImageParser().extract_metadata(path).width, 8)
+
+ path.write_bytes(data[:33] + empty * (MAX_PNG_HEADER_CHUNKS + 1) + data[33:])
+ with patch("semantica.parse.image_parser.Image.open") as image_open:
+ with self.assertRaises(ValidationError):
+ ImageParser().extract_metadata(path)
+ image_open.assert_not_called()
+
+ def test_png_header_size_matches_pillow(self):
+ # The header reader must agree with Pillow for PNG and APNG.
+ variants = {
+ "plain": {},
+ "animated": {
+ "save_all": True,
+ "append_images": [Image.new("RGB", (37, 21), "red")],
+ },
+ }
+ for name, kwargs in variants.items():
+ with self.subTest(variant=name):
+ path = self.dir / f"{name}.png"
+ Image.new("RGB", (37, 21)).save(path, format="PNG", **kwargs)
+ with Image.open(path) as img:
+ expected = img.size
+ self.assertEqual(_png_canvas_size(path.read_bytes()), expected)
+
# --- Error mapping and metadata ---
def test_corrupt_allowed_image_fails_validation(self):