From 032f4e3df682298bc194f17f4a90d57b3c8be27c Mon Sep 17 00:00:00 2001 From: Stephen Masters Date: Sun, 1 Nov 2026 16:26:31 +0000 Subject: [PATCH] feat!: header checks for TIFF compression, layout, tiles and colour, PNG kind, and metadata size Six checks from the November 2026 advisory backfill, landed together so that the version moves once. Each is a field on Policy with a reason in the house style, a case in the hostile corpus, and a reading of real Pillow output to agree with. TIFF. The IFD walk, which read only the dimensions, now reads the compression scheme, photometric interpretation, samples per pixel, bits per sample, tile size and YCbCr subsampling of every frame, and checks every entry's data against the file before anything else (the shape of CVE-2023-6277). tiff_compressions names the schemes that pass, by default the six a scanner writes; PixarLog and the other rare codecs, where most of libtiff's flaws have been (CVE-2026-12912), are refused, and an unknown code is refused outright. Every frame must share the first frame's scheme and pixel layout, since the decoder sizes its buffers from the first (CVE-2026-96639); Pillow's own mixed-mode output is refused. tiff_photometrics and tiff_subsamplings name the colour models and chroma subsamplings that pass (CVE-2026-4775). A tile is reported, held to max_pixels on its own because the decoder allocates it whole, and allow_tiled_tiff refuses tiles under the strict preset (CVE-2026-112395, CVE-2026-112404). PNG. The whole IHDR is decoded and impossible combinations refused. allow_interlaced_png is off by default, as no scanner writes Adam7 and the interlaced 16-bit path was the way into two libpng overflows (CVE-2025-65018, CVE-2026-22695); png_colour_types and max_png_bit_depth are knobs, with the strict preset at 8 bits. The chunk walk now goes to IEND, skipping image data, since a decoder reads the chunks after it too. Metadata. max_metadata_bytes (4 MiB, 1 MiB strict) bounds the largest PNG chunk, TIFF tag's data or JPEG colour profile (CVE-2026-96643). BREAKING CHANGE: a TIFF compressed with a scheme outside none, CCITT, LZW, JPEG, Deflate and PackBits, or with frames that differ in compression or pixel layout, or declaring CIELab, a mask, raw sensor data or LogLuv, or a YCbCr file subsampled by four; an interlaced PNG or one whose IHDR pairs a colour type with a depth it cannot have; and an image with a metadata block over 4 MiB, all passed before and are refused now. Co-Authored-By: Claude Fable 5.1 --- README.md | 46 +++- src/sillybos/__init__.py | 16 +- src/sillybos/check.py | 76 ++++++- src/sillybos/cli.py | 58 +++++ src/sillybos/headers.py | 430 ++++++++++++++++++++++++++++++++---- src/sillybos/policy.py | 136 +++++++++++- tests/corpus.py | 151 ++++++++++++- tests/test_check.py | 121 +++++++++++ tests/test_cli.py | 24 ++ tests/test_headers.py | 459 ++++++++++++++++++++++++++++++++++++++- 10 files changed, 1438 insertions(+), 79 deletions(-) diff --git a/README.md b/README.md index b121157..c3c928c 100644 --- a/README.md +++ b/README.md @@ -93,8 +93,16 @@ check(path, Policy(formats={"tiff", "pdf"}, max_pages=50)) | `max_bytes` | 512 MiB | 128 MiB | The file. Checked before anything reads it | | `max_pixels` | 89,478,485 | 50,000,000 | Any one page or frame, decoded. For a PDF page, at `render_dpi`. The default is Pillow's own decompression-bomb threshold, enforced here rather than left to a global | | `max_pages` | 500 | 100 | Pages of a PDF, frames of a TIFF or animated PNG, pictures of a multi-picture JPEG. Also bounds the header walk itself | +| `max_metadata_bytes` | 4 MiB | 1 MiB | The largest block of metadata in an image: a PNG chunk other than image data, a TIFF tag's out-of-line data, a JPEG colour profile across its segments. A scan carries kilobytes; a block the size of the file is where parsers' quadratic paths and allocation flaws live (CVE-2026-96643, CVE-2023-6277) | | `render_dpi` | 200 | 200 | What you will render PDF pages at, so a page's pixels are known before the renderer allocates them | | `name_must_match` | yes | yes | Refuse a JPEG called `.png`. The readers would cope; the lie is what you want to know about | +| `png_colour_types` | all five | the same | Which PNG colour types pass: greyscale, rgb, palette, greyscale-alpha, rgba. A policy for scans alone can keep to the first two, which closes libpng's palette paths (CVE-2025-64720, CVE-2026-33636) | +| `max_png_bit_depth` | 16 | 8 | The deepest PNG sample. A scanner writes 8; some archival software writes 16-bit greyscale | +| `allow_interlaced_png` | no | no | No scanner writes Adam7, and the interlaced 16-bit path was the way into two libpng overflows (CVE-2025-65018, CVE-2026-22695) | +| `allow_tiled_tiff` | yes | no | A scanner writes strips; digitisation and mapping software write tiles. A tile is held to `max_pixels` on its own, since the decoder allocates it whole, and the tiled path is where two of Pillow's recent over-reads were (CVE-2026-112395, CVE-2026-112404) | +| `tiff_photometrics` | greyscale, rgb, palette, cmyk, ycbcr | the same | Which colour models a TIFF may declare. The rest (CIELab, masks, raw sensor data, LogLuv) a scan never uses; a value the library does not know is refused outright | +| `tiff_subsamplings` | 1x1, 2x1, 1x2, 2x2 | the same | Which chroma subsamplings a YCbCr TIFF may declare. The factor-of-four paths are where libtiff's most recent heap write was found (CVE-2026-4775) | +| `tiff_compressions` | none, ccitt, lzw, jpeg, deflate, packbits | the same | How a TIFF may be compressed, by name. The other codecs in libtiff are where most of its flaws have been found (PixarLog most recently, CVE-2026-12912), and a scan never needs them. A code the library does not know is refused whatever the policy says, and every frame must use the same scheme | | `jpeg_frames` | baseline, extended, progressive | the same | How a JPEG's frame may be coded. Lossless, hierarchical and arithmetic frames are legal JPEG that no scanner writes and the decoder's least-exercised code; a lossless frame was the way into a heap overflow in Pillow's JPEG decoder (CVE-2026-112403) | | `allow_encrypted_pdf` | no | no | A scanned book is never encrypted | | `pdfinfo_timeout` | 30 s | 30 s | How long `pdfinfo` may take before the file is refused | @@ -132,8 +140,10 @@ refused scans/report.pdf 1,412 pages; the limit is 500 Exit status 0 when every file passed, 1 when any was refused, 2 when the command could not do its job. `--strict`, `--formats`, `--max-pages`, -`--max-pixels`, `--max-bytes`, `--jpeg-frames` and `--any-name` adjust the -policy; `--json` +`--max-pixels`, `--max-bytes`, `--max-metadata-bytes`, `--jpeg-frames`, +`--tiff-compressions`, `--tiff-photometrics`, `--tiff-subsamplings`, +`--no-tiled-tiff`, `--png-colour-types`, `--max-png-bit-depth`, +`--interlaced-png` and `--any-name` adjust the policy; `--json` prints one object per line for a pipeline; `-q` prints only refusals. ## What it does, exactly @@ -147,12 +157,21 @@ prints one object per line for a pipeline; `-q` prints only refusals. unknown format". Refused by name, and no reader of ours runs on it. 3. **Name against contents.** `says PNG, is JPEG`. 4. **The header**, with a reader of its own for each raster format: the - dimensions, coding and component count from a JPEG's frame header, and - every picture of a multi-picture (MPF) JPEG, each read the same way and - required to match the first; a PNG's `IHDR` (and `acTL` frame count); - and every directory in a TIFF's chain, which is walked with a limit and - a memory of where it has been, so that a chain that loops or points off - the end of the file is a refusal, not a hang. Every read is bounded and + dimensions, coding and component count from a JPEG's frame header, the + size of its colour profile, and every picture of a multi-picture (MPF) + JPEG, each read the same way and required to match the first; a PNG's + whole `IHDR` (bit depth, colour type, interlacing, and the methods the + specification fixes), its `acTL` frame count, and the size of every + other chunk, before and after the image data; and every directory in a TIFF's + chain, each with its dimensions, its + compression scheme, which must be one the policy names, and its pixel + layout (photometric interpretation and, for YCbCr, chroma subsampling, + both of which the policy names; samples per pixel; bits per sample), + all of which must be the same in every frame, since the decoder sizes + its buffers from the first, its tile size if it is tiled, and every + tag's data checked to lie inside the file; the chain is walked with a limit and a memory of where it has + been, so that one that loops or points off the end of the file is a + refusal, not a hang. Every read is bounded and every offset is checked against the file's size. For a PDF, `pdfinfo` reports the page count, whether it is encrypted and, if the count is within the limit, every page's size. @@ -197,10 +216,13 @@ ruff check . && ruff format --check . && mypy && pytest --cov ``` The tests build the hostile corpus by hand at test time (`tests/corpus.py`): -renamed PostScript, a 100-byte PNG that claims ten billion pixels, a -lossless JPEG, a multi-picture JPEG whose second picture is four billion -pixels or changes colour mode, a TIFF with ten thousand frames, a TIFF -whose frame chain loops, a PDF of a thousand pages, a PDF with a page 200 +renamed PostScript, a 100-byte PNG that claims ten billion pixels, a PNG +with a five-megabyte EXIF chunk after the image data, an interlaced PNG, +a PNG whose header pairs a colour type with a bit depth it cannot have, a +TIFF whose tag points past the end of the file, a lossless JPEG, a multi-picture JPEG whose second picture is four billion +pixels or changes colour mode, a PixarLog-compressed TIFF, a CIELab TIFF, a YCbCr TIFF subsampled four to one, a TIFF that +changes compression or colour mode between frames, a TIFF whose tiles are four billion pixels each, a TIFF with ten thousand frames, a +TIFF whose frame chain loops, a PDF of a thousand pages, a PDF with a page 200 inches wide. Nothing hostile is checked in. The readers are also checked against Pillow's reading of real files, so that they agree with the decoder they stand in front of. diff --git a/src/sillybos/__init__.py b/src/sillybos/__init__.py index 7104c6b..8d21360 100644 --- a/src/sillybos/__init__.py +++ b/src/sillybos/__init__.py @@ -28,7 +28,17 @@ from __future__ import annotations from sillybos.check import Facts, Refused, Verdict, check, require -from sillybos.policy import DEFAULT, FORMATS, JPEG_FRAMES, STRICT, Policy +from sillybos.policy import ( + DEFAULT, + FORMATS, + JPEG_FRAMES, + PNG_COLOUR_TYPES, + STRICT, + TIFF_COMPRESSIONS, + TIFF_PHOTOMETRICS, + TIFF_SUBSAMPLINGS, + Policy, +) try: from sillybos._version import __version__ @@ -39,7 +49,11 @@ "DEFAULT", "FORMATS", "JPEG_FRAMES", + "PNG_COLOUR_TYPES", "STRICT", + "TIFF_COMPRESSIONS", + "TIFF_PHOTOMETRICS", + "TIFF_SUBSAMPLINGS", "Facts", "Policy", "Refused", diff --git a/src/sillybos/check.py b/src/sillybos/check.py index a711160..97ee837 100644 --- a/src/sillybos/check.py +++ b/src/sillybos/check.py @@ -11,7 +11,7 @@ 3. Whether its name agrees with its contents. 4. Its header, with the reader for its format (ours for JPEG, PNG and TIFF; ``pdfinfo`` in a separate process for PDF): dimensions, frames, pages, - and how a JPEG is coded. + how a JPEG is coded, how a TIFF is compressed, what kind of PNG it is. 5. The policy's ceilings against what the header said. Every reason is a sentence an operator can act on, and the verdict carries @@ -26,7 +26,16 @@ from sillybos import headers, sniff from sillybos.pdf import pdf as read_pdf -from sillybos.policy import DEFAULT, FORMATS, JPEG_FRAMES, Policy +from sillybos.policy import ( + DEFAULT, + FORMATS, + JPEG_FRAMES, + PNG_COLOUR_TYPES, + TIFF_COMPRESSIONS, + TIFF_PHOTOMETRICS, + TIFF_SUBSAMPLINGS, + Policy, +) @dataclass(frozen=True) @@ -49,6 +58,22 @@ class Facts: ``pages`` is a floor, not a count. coding: How a JPEG's frame is coded, by a name from :data:`sillybos.JPEG_FRAMES`; ``None`` for the other formats. + compression: How a TIFF's frames are compressed, by a name from + :data:`sillybos.TIFF_COMPRESSIONS`; ``None`` for the other + formats. + metadata: The largest block of metadata in an image, as (what it + is, bytes): a PNG chunk, a TIFF tag's data, a JPEG colour + profile. ``None`` for a PDF or an image with none. + colour: A PNG's colour type, by a name from + :data:`sillybos.PNG_COLOUR_TYPES`, or a TIFF's photometric + interpretation, from :data:`sillybos.TIFF_PHOTOMETRICS`; + ``None`` for a JPEG or a PDF. + depth: A PNG's or TIFF's bits per sample; ``None`` otherwise. + interlaced: Whether a PNG is Adam7 interlaced. + tile: A tiled TIFF's largest tile as (width, height); ``None`` for + a TIFF in strips and for the other formats. + subsampling: A YCbCr TIFF's chroma subsampling, horizontal by + vertical, as ``"2x2"``; ``None`` otherwise. """ bytes: int @@ -59,6 +84,13 @@ class Facts: encrypted: bool = False pages_exact: bool = True coding: str | None = None + compression: str | None = None + metadata: tuple[str, int] | None = None + colour: str | None = None + depth: int | None = None + interlaced: bool = False + tile: tuple[int, int] | None = None + subsampling: str | None = None @dataclass(frozen=True) @@ -159,7 +191,7 @@ def check(path: str | os.PathLike[str], policy: Policy = DEFAULT) -> Verdict: reasons.append(f"the header could not be read: {exc}") return Verdict(path, False, fmt, claimed, None, tuple(reasons)) - reasons.extend(_against_limits(facts, policy)) + reasons.extend(_against_limits(facts, policy, fmt)) return Verdict(path, not reasons, fmt, claimed, facts, tuple(reasons)) @@ -194,10 +226,17 @@ def _facts(path: Path, fmt: str, f: headers.Reader, size: int, policy: Policy) - header.max_pixels if header.complete else None, pages_exact=header.complete, coding=header.coding, + compression=header.compression, + metadata=header.metadata, + colour=header.colour, + depth=header.depth, + interlaced=header.interlaced, + tile=header.tile, + subsampling=header.subsampling, ) -def _against_limits(facts: Facts, policy: Policy) -> list[str]: +def _against_limits(facts: Facts, policy: Policy, fmt: str) -> list[str]: reasons = [] if facts.pages > policy.max_pages: if facts.pages_exact: @@ -206,6 +245,9 @@ def _against_limits(facts: Facts, policy: Policy) -> list[str]: reasons.append(f"more than {policy.max_pages:,} pages, which is the limit") if facts.max_pixels is not None and facts.max_pixels > policy.max_pixels: reasons.append(f"a page of {facts.max_pixels:,} pixels; the limit is {policy.max_pixels:,}") + if facts.metadata is not None and facts.metadata[1] > policy.max_metadata_bytes: + what, size = facts.metadata + reasons.append(f"a {what} of {size:,} bytes; the limit is {policy.max_metadata_bytes:,}") if facts.encrypted and not policy.allow_encrypted_pdf: reasons.append("the PDF is encrypted") if facts.coding is not None and facts.coding not in policy.jpeg_frames: @@ -214,6 +256,32 @@ def _against_limits(facts: Facts, policy: Policy) -> list[str]: reasons.append( f"{article} {facts.coding} JPEG; the policy allows {_listed(allowed)} frames" ) + if fmt == "png" and facts.colour is not None and facts.colour not in policy.png_colour_types: + allowed = [name for name in PNG_COLOUR_TYPES if name in policy.png_colour_types] + reasons.append(f"a {facts.colour} PNG; the policy allows {_listed(allowed)}") + if fmt == "tiff" and facts.colour is not None and facts.colour not in policy.tiff_photometrics: + allowed = [name for name in TIFF_PHOTOMETRICS if name in policy.tiff_photometrics] + reasons.append(f"a {facts.colour} TIFF; the policy allows {_listed(allowed)}") + if facts.subsampling is not None and facts.subsampling not in policy.tiff_subsamplings: + allowed = [name for name in TIFF_SUBSAMPLINGS if name in policy.tiff_subsamplings] + reasons.append( + f"a ycbcr TIFF subsampled {facts.subsampling}; the policy allows {_listed(allowed)}" + ) + if facts.depth is not None and facts.depth > policy.max_png_bit_depth: + reasons.append(f"a {facts.depth}-bit PNG; the limit is {policy.max_png_bit_depth} bits") + if facts.interlaced and not policy.allow_interlaced_png: + reasons.append("an interlaced PNG; the policy does not allow interlacing") + if facts.tile is not None: + if not policy.allow_tiled_tiff: + reasons.append("a tiled TIFF; the policy allows strips only") + tile_pixels = facts.tile[0] * facts.tile[1] + if tile_pixels > policy.max_pixels: + reasons.append(f"a tile of {tile_pixels:,} pixels; the limit is {policy.max_pixels:,}") + if facts.compression is not None and facts.compression not in policy.tiff_compressions: + allowed = [name for name in TIFF_COMPRESSIONS if name in policy.tiff_compressions] + reasons.append( + f"a {facts.compression}-compressed TIFF; the policy allows {_listed(allowed)}" + ) return reasons diff --git a/src/sillybos/cli.py b/src/sillybos/cli.py index d72f5ad..29474ac 100644 --- a/src/sillybos/cli.py +++ b/src/sillybos/cli.py @@ -30,6 +30,8 @@ def _policy(args: argparse.Namespace) -> Policy: ("max_bytes", args.max_bytes), ("max_pixels", args.max_pixels), ("max_pages", args.max_pages), + ("max_metadata_bytes", args.max_metadata_bytes), + ("max_png_bit_depth", args.max_png_bit_depth), ) if value is not None } @@ -37,6 +39,18 @@ def _policy(args: argparse.Namespace) -> Policy: changes["formats"] = frozenset(args.formats.split(",")) if args.jpeg_frames: changes["jpeg_frames"] = frozenset(args.jpeg_frames.split(",")) + if args.tiff_compressions: + changes["tiff_compressions"] = frozenset(args.tiff_compressions.split(",")) + if args.png_colour_types: + changes["png_colour_types"] = frozenset(args.png_colour_types.split(",")) + if args.interlaced_png: + changes["allow_interlaced_png"] = True + if args.no_tiled_tiff: + changes["allow_tiled_tiff"] = False + if args.tiff_photometrics: + changes["tiff_photometrics"] = frozenset(args.tiff_photometrics.split(",")) + if args.tiff_subsamplings: + changes["tiff_subsamplings"] = frozenset(args.tiff_subsamplings.split(",")) if args.any_name: changes["name_must_match"] = False return dataclasses.replace(base, **changes) if changes else base @@ -65,6 +79,12 @@ def build_parser() -> argparse.ArgumentParser: "--max-pixels", type=int, metavar="N", help="most pixels in any one page or frame" ) parser.add_argument("--max-pages", type=int, metavar="N", help="most pages or frames") + parser.add_argument( + "--max-metadata-bytes", + type=int, + metavar="N", + help="largest metadata block (a PNG chunk, a TIFF tag's data, a JPEG colour profile)", + ) parser.add_argument( "--jpeg-frames", metavar="LIST", @@ -74,6 +94,44 @@ def build_parser() -> argparse.ArgumentParser: "(default: the first three)" ), ) + parser.add_argument( + "--png-colour-types", + metavar="LIST", + help=( + "comma-separated PNG colour types to allow, from " + "greyscale,rgb,palette,greyscale-alpha,rgba (default: all five)" + ), + ) + parser.add_argument( + "--max-png-bit-depth", type=int, metavar="N", help="deepest PNG sample (default: 16)" + ) + parser.add_argument( + "--interlaced-png", action="store_true", help="do not refuse an interlaced PNG" + ) + parser.add_argument( + "--no-tiled-tiff", action="store_true", help="refuse a TIFF laid out in tiles" + ) + parser.add_argument( + "--tiff-photometrics", + metavar="LIST", + help=( + "comma-separated TIFF photometric interpretations to allow, by name " + "(default: greyscale,rgb,palette,cmyk,ycbcr)" + ), + ) + parser.add_argument( + "--tiff-subsamplings", + metavar="LIST", + help="comma-separated YCbCr subsamplings to allow, as 2x2 (default: 1x1,2x1,1x2,2x2)", + ) + parser.add_argument( + "--tiff-compressions", + metavar="LIST", + help=( + "comma-separated TIFF compression schemes to allow, by name " + "(default: none,ccitt,lzw,jpeg,deflate,packbits)" + ), + ) parser.add_argument( "--any-name", action="store_true", diff --git a/src/sillybos/headers.py b/src/sillybos/headers.py index d916948..ef5f545 100644 --- a/src/sillybos/headers.py +++ b/src/sillybos/headers.py @@ -27,6 +27,11 @@ """How many JPEG segments or PNG chunks to walk before giving up: a bound on the time a crafted file can cost. A real scan has tens.""" +MAX_IDAT_CHUNKS = 1 << 18 +"""How many image-data chunks a PNG may have before the walk gives up. +libpng writes one per 8 KiB, so a file at the default byte limit has a +quarter of this; the bound is on the time a crafted file can cost.""" + MAX_DIMENSION = 1 << 31 """A width or height at or above this is not a dimension; it is a bug or an attack, and refused before the multiplication that would overflow a C @@ -52,6 +57,25 @@ class Header: coding: For a JPEG, how its frame is coded, by a name from :data:`sillybos.JPEG_FRAMES` (``"baseline"``, ``"progressive"``, ``"lossless"``, ...). ``None`` for the other formats. + compression: For a TIFF, how its frames are compressed, by a name + from :data:`sillybos.TIFF_COMPRESSIONS` (``"none"``, ``"lzw"``, + ``"jpeg"``, ...); every frame the reader looked at uses it. + ``None`` for the other formats. + metadata: The largest block of metadata the reader passed over, as + (what it is, its size in bytes): a PNG chunk other than image + data, a TIFF tag's out-of-line data, a JPEG colour profile + across its segments. ``None`` if there was none. + colour: For a PNG, its colour type by a name from + :data:`sillybos.PNG_COLOUR_TYPES`; for a TIFF, its photometric + interpretation by a name from :data:`sillybos.TIFF_PHOTOMETRICS`. + ``None`` for a JPEG. + depth: For a PNG or TIFF, its bits per sample. ``None`` for a JPEG. + interlaced: For a PNG, whether it is Adam7 interlaced. + subsampling: For a YCbCr TIFF, its chroma subsampling as + ``"2x2"`` (horizontal by vertical). ``None`` otherwise. + tile: For a tiled TIFF, the (width, height) of its largest tile, + which is what the decoder allocates whole. ``None`` for a TIFF + in strips and for the other formats. """ width: int @@ -60,6 +84,13 @@ class Header: max_pixels: int complete: bool = True coding: str | None = None + compression: str | None = None + metadata: tuple[str, int] | None = None + colour: str | None = None + depth: int | None = None + interlaced: bool = False + tile: tuple[int, int] | None = None + subsampling: str | None = None def _read_exactly(f: Reader, n: int, what: str) -> bytes: @@ -102,6 +133,7 @@ def _dimensions(width: int, height: int, what: str) -> None: _STANDALONE = {0x01, 0xD0, 0xD1, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7, 0xD8} _APP2 = 0xE2 _MPF = b"MPF\x00" +_ICC = b"ICC_PROFILE\x00" _MP_NUMBER_OF_IMAGES = 0xB001 _MP_ENTRY = 0xB002 @@ -126,15 +158,18 @@ def jpeg(f: Reader, size: int, limit: int) -> Header: that sized its buffers for the first picture is the one that will decode the rest. As with a TIFF, the walk stops after ``limit + 1`` pictures. """ - first, pictures = _frame(f, size, 0, "frame header", index=True) + first, pictures, profile = _frame(f, size, 0, "frame header", index=True) + metadata = ("JPEG colour profile", profile) if profile else None pages = 1 max_pixels = first.width * first.height for number, offset in enumerate(pictures, start=2): if pages > limit: - return Header(first.width, first.height, pages, max_pixels, False, first.coding) + return Header( + first.width, first.height, pages, max_pixels, False, first.coding, metadata=metadata + ) if not 2 <= offset < size: raise HeaderError(f"picture {number} lies outside the file") - picture, _ = _frame(f, size, offset, f"picture {number}", index=False) + picture, _, _ = _frame(f, size, offset, f"picture {number}", index=False) if picture.coding != first.coding: raise HeaderError( f"picture {number} is {picture.coding} where picture 1 is {first.coding}" @@ -146,20 +181,25 @@ def jpeg(f: Reader, size: int, limit: int) -> Header: ) pages += 1 max_pixels = max(max_pixels, picture.width * picture.height) - return Header(first.width, first.height, pages, max_pixels, coding=first.coding) + return Header( + first.width, first.height, pages, max_pixels, coding=first.coding, metadata=metadata + ) -def _frame(f: Reader, size: int, start: int, what: str, *, index: bool) -> tuple[_Frame, list[int]]: +def _frame( + f: Reader, size: int, start: int, what: str, *, index: bool +) -> tuple[_Frame, list[int], int]: """Walk one picture's segments from ``start`` to its frame header. - Returns the frame and, when ``index`` is set and the picture carries a - Multi-Picture index, the offset in the file of every further picture it - names. + Returns the frame and, when ``index`` is set, the offset in the file of + every further picture a Multi-Picture index names and the total bytes + of colour profile carried in APP2 segments. """ f.seek(start) if _read_exactly(f, 2, "header") != b"\xff\xd8": raise HeaderError(f"no JPEG start-of-image marker in the {what}") pictures: list[int] = [] + profile = 0 for _ in range(MAX_SEGMENTS): byte = _read_exactly(f, 1, "segment marker") if byte != b"\xff": @@ -185,21 +225,23 @@ def _frame(f: Reader, size: int, start: int, what: str, *, index: bool) -> tuple # scan; refusing it keeps every decoder's rarest path closed. raise HeaderError("the height is deferred to a DNL marker") _dimensions(width, height, what) - return _Frame(width, height, _FRAME_CODINGS[marker], components), pictures + return _Frame(width, height, _FRAME_CODINGS[marker], components), pictures, profile payload = f.tell() next_offset = payload + length - 2 if next_offset > size: raise HeaderError("a segment runs past the end of the file") - if ( - index - and marker == _APP2 - and length >= 2 + len(_MPF) - and _read_exactly(f, len(_MPF), "APP2 segment") == _MPF - ): - if pictures: - raise HeaderError("two multi-picture indexes") - data = _read_exactly(f, length - 2 - len(_MPF), "multi-picture index") - pictures = _mp_index(data, payload + len(_MPF)) + if index and marker == _APP2 and length >= 2 + len(_MPF): + ident = _read_exactly(f, len(_MPF), "APP2 segment") + if ident == _MPF: + if pictures: + raise HeaderError("two multi-picture indexes") + data = _read_exactly(f, length - 2 - len(_MPF), "multi-picture index") + pictures = _mp_index(data, payload + len(_MPF)) + elif ident == _ICC[:4] and length >= 4 + len(_ICC): + # After the identifier come the segment's number and the + # count of segments, then the profile bytes themselves. + if _read_exactly(f, len(_ICC) - 4, "APP2 segment") == _ICC[4:]: + profile += length - 4 - len(_ICC) f.seek(next_offset) raise HeaderError(f"no frame header in the first {MAX_SEGMENTS} segments") @@ -256,35 +298,86 @@ def _mp_index(data: bytes, base: int) -> list[int]: # --- PNG -------------------------------------------------------------------- +# Colour types by IHDR value, named as :data:`sillybos.PNG_COLOUR_TYPES` names +# them, with the bit depths the specification allows each. +_COLOUR_TYPES = { + 0: ("greyscale", {1, 2, 4, 8, 16}), + 2: ("rgb", {8, 16}), + 3: ("palette", {1, 2, 4, 8}), + 4: ("greyscale-alpha", {8, 16}), + 6: ("rgba", {8, 16}), +} + def png(f: Reader, size: int, limit: int) -> Header: - """Read a PNG's IHDR, and count the frames of an animated one (acTL).""" + """Read a PNG's IHDR, count the frames of an animated one, and size every other chunk. + + The walk goes to IEND, not just to the first image-data chunk, because + a decoder reads the chunks after the image data too (an ``eXIf`` or a + text chunk may sit there). Image-data chunks are skipped, not read, and + counted against :data:`MAX_IDAT_CHUNKS`; every other chunk counts + against :data:`MAX_SEGMENTS`, and the largest is reported so that the + policy can bound it. + """ del limit # the frame count is one field; no walk to bound f.seek(8) # the signature was checked by sniff length, kind = struct.unpack(">I4s", _read_exactly(f, 8, "first chunk")) if kind != b"IHDR" or length != 13: raise HeaderError("the first chunk is not a 13-byte IHDR") - width, height = struct.unpack(">II", _read_exactly(f, 8, "IHDR")) + width, height, depth, colour_type, compression, filter_method, interlace = struct.unpack( + ">IIBBBBB", _read_exactly(f, 13, "IHDR") + ) _dimensions(width, height, "IHDR") - f.seek(13 - 8 + 4, 1) # the rest of IHDR, and its CRC + if colour_type not in _COLOUR_TYPES: + raise HeaderError(f"IHDR gives a colour type of {colour_type}") + colour, depths = _COLOUR_TYPES[colour_type] + if depth not in depths: + raise HeaderError(f"IHDR gives a bit depth of {depth} for a {colour} image") + if compression != 0 or filter_method != 0: + raise HeaderError("IHDR gives a compression or filter method other than 0") + if interlace > 1: + raise HeaderError(f"IHDR gives an interlace method of {interlace}") + f.seek(4, 1) # the IHDR CRC pages = 1 - for _ in range(MAX_SEGMENTS): + chunks = idats = 0 + metadata: tuple[str, int] | None = None + while True: head = f.read(8) if len(head) < 8: break length, kind = struct.unpack(">I4s", head) - if kind in (b"IDAT", b"IEND"): - break - if kind == b"acTL" and length >= 4: - (pages,) = struct.unpack(">I", _read_exactly(f, 4, "acTL")) - if pages < 1: - raise HeaderError("acTL gives zero frames") - break next_offset = f.tell() + length + 4 if next_offset > size: raise HeaderError("a chunk runs past the end of the file") + if kind == b"IDAT": + idats += 1 + if idats > MAX_IDAT_CHUNKS: + raise HeaderError(f"more than {MAX_IDAT_CHUNKS:,} image-data chunks") + else: + chunks += 1 + if chunks > MAX_SEGMENTS: + raise HeaderError(f"more than {MAX_SEGMENTS:,} chunks besides the image data") + if not kind.isalpha() or not kind.isascii(): + raise HeaderError("a chunk type is not four letters") + if length and (metadata is None or length > metadata[1]): + metadata = (f"PNG {kind.decode('ascii')} chunk", length) + if kind == b"IEND": + break + if kind == b"acTL" and length >= 4: + (pages,) = struct.unpack(">I", _read_exactly(f, 4, "acTL")) + if pages < 1: + raise HeaderError("acTL gives zero frames") f.seek(next_offset) - return Header(width, height, pages, width * height) + return Header( + width, + height, + pages, + width * height, + metadata=metadata, + colour=colour, + depth=depth, + interlaced=interlace == 1, + ) # --- TIFF ------------------------------------------------------------------- @@ -293,15 +386,120 @@ def png(f: Reader, size: int, limit: int) -> Header: _TIFF_LONG = 4 _IMAGE_WIDTH = 256 _IMAGE_LENGTH = 257 +_BITS_PER_SAMPLE = 258 +_COMPRESSION = 259 +_PHOTOMETRIC = 262 +_SAMPLES_PER_PIXEL = 277 +_TILE_WIDTH = 322 +_TILE_LENGTH = 323 +_YCBCR_SUBSAMPLING = 530 +_YCBCR = 6 +_SINGLE_VALUE_TAGS = ( + _IMAGE_WIDTH, + _IMAGE_LENGTH, + _COMPRESSION, + _PHOTOMETRIC, + _SAMPLES_PER_PIXEL, + _TILE_WIDTH, + _TILE_LENGTH, +) +_TAG_NAMES = { + _IMAGE_WIDTH: "a dimension tag", + _IMAGE_LENGTH: "a dimension tag", + _COMPRESSION: "a compression tag", + _PHOTOMETRIC: "a photometric tag", + _SAMPLES_PER_PIXEL: "a samples-per-pixel tag", + _TILE_WIDTH: "a tile tag", + _TILE_LENGTH: "a tile tag", +} +_TYPE_SIZES = {1: 1, 2: 1, 3: 2, 4: 4, 5: 8, 6: 1, 7: 1, 8: 2, 9: 4, 10: 8, 11: 4, 12: 8, 13: 4} +"""Bytes per value for each TIFF field type (BYTE, ASCII, SHORT, LONG, +RATIONAL, ...). A type not listed is counted as one byte, which is how +libtiff treats a type it does not know.""" +_TAG_LABELS = { + 270: "ImageDescription", + 273: "StripOffsets", + 279: "StripByteCounts", + 324: "TileOffsets", + 325: "TileByteCounts", + 700: "XMP", + 33723: "IPTC", + 34377: "Photoshop", + 34665: "Exif", + 34675: "ICC profile", +} +MAX_SAMPLES = 64 +"""The most samples per pixel a BitsPerSample tag may list. A scan has one, +three or four; the bound keeps the out-of-line read small.""" + +# Photometric interpretations by tag value, named as +# :data:`sillybos.TIFF_PHOTOMETRICS` names them. White-is-zero and +# black-is-zero are both greyscale: the same buffer, inverted. +_PHOTOMETRICS = { + 0: "greyscale", + 1: "greyscale", + 2: "rgb", + 3: "palette", + 4: "mask", + 5: "cmyk", + 6: "ycbcr", + 8: "cielab", + 9: "icclab", + 10: "itulab", + 32803: "cfa", + 32844: "logl", + 32845: "logluv", + 34892: "linear-raw", +} +_SUBSAMPLING_FACTORS = {1, 2, 4} + +# Compression schemes by their tag value, named as :data:`sillybos.TIFF_COMPRESSIONS` +# names them. A scanner writes the first six. A code not listed here is +# refused outright: the policy can only name what the library knows. +_COMPRESSIONS = { + 1: "none", + 2: "ccitt", # modified Huffman RLE + 3: "ccitt", # T.4 (Group 3) + 4: "ccitt", # T.6 (Group 4) + 32771: "ccitt", # word-aligned RLE + 5: "lzw", + 7: "jpeg", + 8: "deflate", # Adobe + 32946: "deflate", # PKZIP-style + 32773: "packbits", + 6: "old-jpeg", + 32766: "next", + 32809: "thunderscan", + 32895: "it8", + 32896: "it8", + 32897: "it8", + 32898: "it8", + 32908: "pixar", # PixarFilm + 32909: "pixar", # PixarLog + 34661: "jbig", + 34676: "sgilog", + 34677: "sgilog", + 34712: "jpeg2000", + 34887: "lerc", + 34925: "lzma", + 50000: "zstd", + 50001: "webp", + 50002: "jxl", + 52546: "jxl", +} def tiff(f: Reader, size: int, limit: int) -> Header: - """Walk a classic TIFF's IFD chain: dimensions per frame, frames counted. + """Walk a classic TIFF's IFD chain: dimensions and compression per frame, frames counted. Stops after ``limit + 1`` frames and reports that many, so that a file with a million frames costs the time of ``limit`` reads, not a million. An IFD that points at itself, at an earlier one, or past the end of the - file is an error, not a loop. + file is an error, not a loop. Every frame must share the first frame's + compression scheme and pixel layout (photometric interpretation, samples + per pixel, bits per sample): a decoder that set itself up for the first + frame is the one that reads the rest, and no scanner mixes them within + one file. """ f.seek(0) order = _read_exactly(f, 2, "header") @@ -314,13 +512,31 @@ def tiff(f: Reader, size: int, limit: int) -> Header: (offset,) = struct.unpack(endian + "I", _read_exactly(f, 4, "header")) seen: set[int] = set() first: tuple[int, int] | None = None + compression: str | None = None + layout: tuple[str, int, int] | None = None + metadata: tuple[str, int] | None = None + tile: tuple[int, int] | None = None + subsampling: str | None = None max_pixels = 0 pages = 0 while offset != 0: if pages > limit: if first is None: return _no_frames() - return Header(first[0], first[1], pages, max_pixels, complete=False) + assert layout is not None # noqa: S101 - set with the first frame + return Header( + first[0], + first[1], + pages, + max_pixels, + False, + compression=compression, + metadata=metadata, + tile=tile, + colour=layout[0], + depth=layout[2], + subsampling=subsampling, + ) if offset in seen: raise HeaderError("the frame chain loops back on itself") if offset + 2 > size or offset < 8: @@ -331,14 +547,54 @@ def tiff(f: Reader, size: int, limit: int) -> Header: if offset + 2 + count * 12 + 4 > size: raise HeaderError("a frame directory runs past the end of the file") width = height = None + # The tags' defaults: uncompressed, white is zero, one sample per pixel, 1 bit. + values: dict[int, int | None] = { + _COMPRESSION: 1, + _PHOTOMETRIC: 0, + _SAMPLES_PER_PIXEL: 1, + _TILE_WIDTH: None, + _TILE_LENGTH: None, + } + bits: tuple[int, bytes] | None = None # (count, field) to resolve after the directory + factors = (2, 2) # the subsampling tag's default for _ in range(count): tag, kind, n, raw = struct.unpack( endian + "HHI4s", _read_exactly(f, 12, "frame directory") ) - if tag not in (_IMAGE_WIDTH, _IMAGE_LENGTH): + data_size = n * _TYPE_SIZES.get(kind, 1) + if data_size > 4: + # The field holds an offset to the data. A count that would + # put it past the end of the file is what makes a decoder + # allocate for nothing (CVE-2023-6277). + (where,) = struct.unpack(endian + "I", raw) + if where < 8 or where + data_size > size: + raise HeaderError(f"frame {pages + 1}'s tag {tag:,} data lies outside the file") + if metadata is None or data_size > metadata[1]: + label = _TAG_LABELS.get(tag) + name = f"TIFF tag {tag:,}" + (f" ({label})" if label else "") + metadata = (name, data_size) + if tag == _BITS_PER_SAMPLE: + if kind != _TIFF_SHORT: + raise HeaderError("a bits-per-sample tag is not SHORT") + if n < 1 or n > MAX_SAMPLES: + raise HeaderError(f"a bits-per-sample tag lists {n:,} samples") + bits = (n, raw) continue + if tag == _YCBCR_SUBSAMPLING: + if kind != _TIFF_SHORT or n != 2: + raise HeaderError("a subsampling tag is not two SHORTs") + horizontal, vertical = struct.unpack(endian + "HH", raw) + if horizontal not in _SUBSAMPLING_FACTORS or vertical not in _SUBSAMPLING_FACTORS: + raise HeaderError( + f"frame {pages + 1} gives a subsampling of {horizontal}x{vertical}" + ) + factors = (horizontal, vertical) + continue + if tag not in _SINGLE_VALUE_TAGS: + continue + what = _TAG_NAMES[tag] if n != 1: - raise HeaderError("a dimension tag holds more than one value") + raise HeaderError(f"{what} holds more than one value") if kind == _TIFF_SHORT: # A SHORT sits in the first two bytes of the field in either # byte order: the value is left-justified, not right-aligned. @@ -346,22 +602,116 @@ def tiff(f: Reader, size: int, limit: int) -> Header: elif kind == _TIFF_LONG: (value,) = struct.unpack(endian + "I", raw) else: - raise HeaderError("a dimension tag is neither SHORT nor LONG") + raise HeaderError(f"{what} is neither SHORT nor LONG") if tag == _IMAGE_WIDTH: width = value - else: + elif tag == _IMAGE_LENGTH: height = value + else: + values[tag] = value if width is None or height is None: raise HeaderError(f"frame {pages + 1} has no width or height") _dimensions(width, height, f"frame {pages + 1}") + (next_offset,) = struct.unpack(endian + "I", _read_exactly(f, 4, "frame directory")) + tile_width, tile_length = values[_TILE_WIDTH], values[_TILE_LENGTH] + if (tile_width is None) != (tile_length is None): + raise HeaderError(f"frame {pages + 1} has a tile width or length but not both") + if tile_width is not None and tile_length is not None: + _dimensions(tile_width, tile_length, f"frame {pages + 1}'s tile") + if tile is None or tile_width * tile_length > tile[0] * tile[1]: + tile = (tile_width, tile_length) + depth = _bits_per_sample(f, size, endian, bits, pages + 1) + photometric, samples = values[_PHOTOMETRIC], values[_SAMPLES_PER_PIXEL] + assert photometric is not None and samples is not None # noqa: S101 - defaults above + colour = _PHOTOMETRICS.get(photometric) + if colour is None: + raise HeaderError( + f"frame {pages + 1} uses photometric interpretation {photometric:,}, " + "which is not one this library knows" + ) + if photometric == _YCBCR: + this_subsampling = f"{factors[0]}x{factors[1]}" + if subsampling is None: + subsampling = this_subsampling + elif this_subsampling != subsampling: + raise HeaderError( + f"frame {pages + 1} is subsampled {this_subsampling} " + f"where frame 1 is subsampled {subsampling}" + ) + this_layout = (colour, samples, depth) + if layout is None: + layout = this_layout + elif this_layout != layout: + raise HeaderError( + f"frame {pages + 1} is {_describe_layout(this_layout)} " + f"where frame 1 is {_describe_layout(layout)}" + ) + code = values[_COMPRESSION] + scheme = _COMPRESSIONS.get(code) if code is not None else None + if scheme is None: + raise HeaderError( + f"frame {pages + 1} uses compression code {code:,}, which is not one this " + "library knows" + ) + if compression is None: + compression = scheme + elif scheme != compression: + raise HeaderError( + f"frame {pages + 1} is compressed with {scheme} where frame 1 is " + f"compressed with {compression}" + ) pages += 1 max_pixels = max(max_pixels, width * height) if first is None: first = (width, height) - (offset,) = struct.unpack(endian + "I", _read_exactly(f, 4, "frame directory")) + offset = next_offset if first is None: return _no_frames() - return Header(first[0], first[1], pages, max_pixels) + assert layout is not None # noqa: S101 - set with the first frame + return Header( + first[0], + first[1], + pages, + max_pixels, + compression=compression, + metadata=metadata, + tile=tile, + colour=layout[0], + depth=layout[2], + subsampling=subsampling, + ) + + +def _bits_per_sample( + f: Reader, size: int, endian: str, bits: tuple[int, bytes] | None, frame: int +) -> int: + """The one bit depth a frame's samples share, or 1 if the tag is absent. + + One or two values sit in the tag's own field; more sit at an offset the + field holds, which is checked against the file before it is read. + Samples of different depths are legal TIFF that no decoder here + accepts, so they are a refusal. + """ + if bits is None: + return 1 + count, field = bits + if count <= 2: + values = struct.unpack(endian + f"{count}H", field[: 2 * count]) + else: + (where,) = struct.unpack(endian + "I", field) + if where + 2 * count > size or where < 8: # pragma: no cover - the entry walk checks first + raise HeaderError(f"frame {frame}'s bits per sample lie outside the file") + f.seek(where) + values = struct.unpack(endian + f"{count}H", _read_exactly(f, 2 * count, "bits per sample")) + if len(set(values)) != 1: + raise HeaderError(f"frame {frame} gives different bit depths per sample") + return int(values[0]) + + +def _describe_layout(layout: tuple[str, int, int]) -> str: + colour, samples, depth = layout + plural = "" if samples == 1 else "s" + return f"{colour}, {samples} sample{plural} of {depth} bits" def _no_frames() -> Header: diff --git a/src/sillybos/policy.py b/src/sillybos/policy.py index 24f06d1..2f56ce7 100644 --- a/src/sillybos/policy.py +++ b/src/sillybos/policy.py @@ -28,6 +28,61 @@ writes the first three. The rest are legal, rare, and the decoder's least exercised code.""" +TIFF_PHOTOMETRICS: tuple[str, ...] = ( + "greyscale", + "rgb", + "palette", + "cmyk", + "ycbcr", + "mask", + "cielab", + "icclab", + "itulab", + "cfa", + "logl", + "logluv", + "linear-raw", +) +"""Every photometric interpretation a TIFF can declare, by name. A scanner +writes the first five (YCbCr is what a JPEG-compressed scan is); the rest +are colour models a scan never uses. A value outside this list is refused +whatever the policy says.""" + +TIFF_SUBSAMPLINGS: tuple[str, ...] = ("1x1", "2x1", "1x2", "2x2", "4x1", "1x4", "4x2", "2x4", "4x4") +"""Every chroma subsampling a YCbCr TIFF can declare, horizontal by +vertical. A scanner writes the first four; the factor-of-four paths are +the least exercised in libtiff (CVE-2026-4775).""" + +TIFF_COMPRESSIONS: tuple[str, ...] = ( + "none", + "ccitt", + "lzw", + "jpeg", + "deflate", + "packbits", + "old-jpeg", + "next", + "thunderscan", + "it8", + "pixar", + "jbig", + "sgilog", + "jpeg2000", + "lerc", + "lzma", + "zstd", + "webp", + "jxl", +) +"""Every TIFF compression scheme the library knows, by name. A scanner +writes the first six. The rest are codecs in libtiff that a scan never +needs and that most of its security history lives in; a code outside this +list is refused whatever the policy says.""" + +PNG_COLOUR_TYPES: tuple[str, ...] = ("greyscale", "rgb", "palette", "greyscale-alpha", "rgba") +"""Every colour type a PNG can have, by name. A scanner writes greyscale or +RGB; the palette paths are where several of libpng's recent flaws were.""" + MIB = 1024 * 1024 @@ -49,6 +104,14 @@ class Policy: or animated PNG. Bounds the time and the memory a run takes, and stops the header walk itself on a file with a million empty frames. + max_metadata_bytes: The largest block of metadata in an image: a + PNG chunk other than image data, a TIFF tag's out-of-line data, + a JPEG colour profile across its segments. A scan carries a few + kilobytes of EXIF and a colour profile well under a megabyte; + a block the size of the file is where parsers' quadratic paths + and allocation flaws have been found (CVE-2026-96643, + CVE-2023-6277). Pillow refuses a PNG text chunk over 1 MiB on + its own; the default leaves room for a large profile or XMP. render_dpi: The resolution the PDF renderer will be run at, so a page's size in points can be turned into pixels before the renderer allocates them. @@ -64,6 +127,37 @@ class Policy: frame was the way into a heap overflow in Pillow's JPEG decoder (CVE-2026-112403). A multi-picture JPEG's pictures count as pages and are each read. + png_colour_types: Which of :data:`PNG_COLOUR_TYPES` may pass. The + default is all five; a policy for scans alone can keep to + greyscale and RGB, which closes libpng's palette paths + (CVE-2025-64720, CVE-2025-66293, CVE-2026-33636). + max_png_bit_depth: The deepest PNG sample. A scanner writes 8 bits; + some archival software writes 16-bit greyscale, so the default + allows it and the strict preset does not. + allow_interlaced_png: Pass an Adam7-interlaced PNG. No scanner + writes one, and the interlaced 16-bit path was the way into + two libpng overflows (CVE-2025-65018, CVE-2026-22695), so the + default refuses. + tiff_photometrics: Which of :data:`TIFF_PHOTOMETRICS` may pass. The + default is what a scanner writes: greyscale, RGB, palette, CMYK + and YCbCr. Every frame of a file must share one. + tiff_subsamplings: Which of :data:`TIFF_SUBSAMPLINGS` a YCbCr TIFF + may declare. The default is the four a scanner writes; the + factor-of-four paths are where libtiff's most recent heap + write was found (CVE-2026-4775). + allow_tiled_tiff: Pass a TIFF laid out in tiles rather than strips. + A scanner writes strips; digitisation and mapping software + write tiles, so the default allows them and the strict preset + does not. A tile is what the decoder allocates whole, so a + tile is also held to ``max_pixels`` on its own; the tiled decode + path is where two of Pillow's recent over-reads were + (CVE-2026-112395, CVE-2026-112404). + tiff_compressions: Which of :data:`TIFF_COMPRESSIONS` may pass. The + default is what a scanner writes: none, CCITT, LZW, JPEG, + Deflate and PackBits. The other codecs are where most of + libtiff's flaws have been found (PixarLog most recently, + CVE-2026-12912), and a scan never needs them. Every frame of a + file must use the same scheme. allow_encrypted_pdf: Pass a PDF that ``pdfinfo`` reports as encrypted. A scanned book never is, so the default refuses. pdfinfo_timeout: Seconds to give ``pdfinfo`` before giving up on a @@ -75,11 +169,25 @@ class Policy: max_bytes: int = 512 * MIB max_pixels: int = 89_478_485 max_pages: int = 500 + max_metadata_bytes: int = 4 * MIB render_dpi: int = 200 name_must_match: bool = True jpeg_frames: frozenset[str] = field( default_factory=lambda: frozenset({"baseline", "extended", "progressive"}) ) + png_colour_types: frozenset[str] = field(default_factory=lambda: frozenset(PNG_COLOUR_TYPES)) + max_png_bit_depth: int = 16 + allow_interlaced_png: bool = False + allow_tiled_tiff: bool = True + tiff_photometrics: frozenset[str] = field( + default_factory=lambda: frozenset({"greyscale", "rgb", "palette", "cmyk", "ycbcr"}) + ) + tiff_subsamplings: frozenset[str] = field( + default_factory=lambda: frozenset({"1x1", "2x1", "1x2", "2x2"}) + ) + tiff_compressions: frozenset[str] = field( + default_factory=lambda: frozenset({"none", "ccitt", "lzw", "jpeg", "deflate", "packbits"}) + ) allow_encrypted_pdf: bool = False pdfinfo_timeout: float = 30.0 @@ -99,7 +207,30 @@ def __post_init__(self) -> None: ) if not self.jpeg_frames: raise ValueError("a policy must allow at least one JPEG frame coding") - for name in ("max_bytes", "max_pixels", "max_pages", "render_dpi"): + unknown = set(self.png_colour_types) - set(PNG_COLOUR_TYPES) + if unknown: + raise ValueError( + f"unknown PNG colour type(s) {sorted(unknown)}; " + f"the types are {', '.join(PNG_COLOUR_TYPES)}" + ) + if not self.png_colour_types: + raise ValueError("a policy must allow at least one PNG colour type") + if self.max_png_bit_depth not in (1, 2, 4, 8, 16): + raise ValueError("max_png_bit_depth must be 1, 2, 4, 8 or 16") + for field_name, known, what in ( + ("tiff_compressions", TIFF_COMPRESSIONS, "TIFF compression"), + ("tiff_photometrics", TIFF_PHOTOMETRICS, "TIFF photometric interpretation"), + ("tiff_subsamplings", TIFF_SUBSAMPLINGS, "TIFF subsampling"), + ): + chosen = getattr(self, field_name) + unknown = set(chosen) - set(known) + if unknown: + raise ValueError( + f"unknown {what}(s) {sorted(unknown)}; the names are {', '.join(known)}" + ) + if not chosen: + raise ValueError(f"a policy must allow at least one {what}") + for name in ("max_bytes", "max_pixels", "max_pages", "max_metadata_bytes", "render_dpi"): if getattr(self, name) < 1: raise ValueError(f"{name} must be at least 1") if self.pdfinfo_timeout <= 0: @@ -117,5 +248,8 @@ def allows(self, fmt: str) -> bool: max_bytes=128 * MIB, max_pixels=50_000_000, max_pages=100, + max_metadata_bytes=1 * MIB, + max_png_bit_depth=8, + allow_tiled_tiff=False, ) """For files from outside: smaller, shorter, and no more lenient on format.""" diff --git a/tests/corpus.py b/tests/corpus.py index 3c4085d..0c7e1f3 100644 --- a/tests/corpus.py +++ b/tests/corpus.py @@ -30,11 +30,36 @@ def _chunk(kind: bytes, data: bytes) -> bytes: return struct.pack(">I", len(data)) + kind + data + struct.pack(">I", zlib.crc32(kind + data)) -def png(width: int, height: int, *, frames: int | None = None, extra: bytes = b"") -> bytes: - """A PNG header with the given dimensions. No pixels: the check never reads them.""" - ihdr = _chunk(b"IHDR", struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0)) +def png( + width: int, + height: int, + *, + frames: int | None = None, + extra: bytes = b"", + after_idat: bytes = b"", + idats: int = 1, + depth: int = 8, + colour: int = 2, + interlace: int = 0, + methods: tuple[int, int] = (0, 0), +) -> bytes: + """A PNG header with the given dimensions. No pixels: the check never reads them. + + ``extra`` goes before the image data, ``after_idat`` between the image + data and IEND; ``idats`` is how many empty image-data chunks to write. + The IHDR's bit depth, colour type, interlace method and (compression, + filter) methods default to an 8-bit RGB image as a scanner writes one. + """ + fields = (width, height, depth, colour, *methods, interlace) + ihdr = _chunk(b"IHDR", struct.pack(">IIBBBBB", *fields)) actl = _chunk(b"acTL", struct.pack(">II", frames, 0)) if frames is not None else b"" - return PNG_SIGNATURE + ihdr + extra + actl + _chunk(b"IDAT", b"") + _chunk(b"IEND", b"") + idat = _chunk(b"IDAT", b"") * idats + return PNG_SIGNATURE + ihdr + extra + actl + idat + after_idat + _chunk(b"IEND", b"") + + +def png_chunk(kind: bytes, size: int) -> bytes: + """One PNG chunk of the given type, ``size`` zero bytes long.""" + return _chunk(kind, b"\x00" * size) # --- JPEG -------------------------------------------------------------------- @@ -130,9 +155,27 @@ def jpeg_padding(n: int) -> bytes: return _segment(0xFE, b"") * n +def jpeg_profile(size: int) -> bytes: + """``size`` bytes of colour profile, split across APP2 segments as a writer splits it.""" + per_segment = 65533 - 2 - len(b"ICC_PROFILE\x00") + pieces = [b"\x00" * min(per_segment, size - at) for at in range(0, size, per_segment)] + return b"".join( + _segment(0xE2, b"ICC_PROFILE\x00" + bytes([n + 1, len(pieces)]) + piece) + for n, piece in enumerate(pieces) + ) + + # --- TIFF -------------------------------------------------------------------- +Tile = tuple[int | None, int | None] +"""(TileWidth, TileLength) for a hand-made TIFF frame; ``None`` leaves that tag out.""" + +Layout = tuple[int, int, int | tuple[int, ...]] +"""(photometric, samples per pixel, bits per sample) for a hand-made TIFF frame; +the bits may be one value for every sample or one per sample.""" + + def tiff( frames: list[tuple[int, int]], *, @@ -141,13 +184,28 @@ def tiff( dangling: bool = False, drop_height: bool = False, long_dims: bool = False, + compression: int | list[int | None] | None = None, + layout: Layout | list[Layout | None] | None = None, + tags: list[tuple[int, int, bytes]] | None = None, + data_outside: bool = False, + tile: Tile | list[Tile | None] | None = None, + subsampling: tuple[int, int] | list[tuple[int, int] | None] | None = None, ) -> bytes: - """A classic TIFF with one IFD per frame, holding just the two dimension tags. + """A classic TIFF with one IFD per frame, holding the two dimension tags. ``loop_to_first`` points the last IFD back at the first; ``dangling`` points it past the end of the file; ``drop_height`` leaves the height out of the first frame; ``long_dims`` writes the dimensions as LONG - rather than SHORT. + rather than SHORT; ``compression`` adds a Compression tag with that + value to every frame, or one value per frame from a list; ``layout`` + likewise adds PhotometricInterpretation, SamplesPerPixel and + BitsPerSample, the last written out of line when there are more than + two samples; ``tags`` adds further entries to every frame as (tag, type, + data), written out of line when the data is over four bytes; + ``data_outside`` points all out-of-line data past the end of the file; + ``tile`` adds TileWidth and TileLength tags (either may be ``None`` to + leave it out) to every frame, or one pair per frame from a list; + ``subsampling`` likewise adds a YCbCrSubSampling tag. """ order = b"II" if endian == "<" else b"MM" header = order + struct.pack(endian + "HI", 42, 8) @@ -155,7 +213,8 @@ def tiff( offset = 8 first = 8 for index, (width, height) in enumerate(frames): - entries = [] + # (tag, kind, count, inline field or out-of-line data) + entries: list[tuple[int, int, int, bytes]] = [] kind = 4 if long_dims else 3 for tag, value in ((256, width), (257, height)): if tag == 257 and drop_height and index == 0: @@ -164,23 +223,91 @@ def tiff( raw = struct.pack(endian + "I", value) else: raw = struct.pack(endian + "H", value) + b"\x00\x00" - entries.append(struct.pack(endian + "HHI", tag, kind, 1) + raw) + entries.append((tag, kind, 1, raw)) + code = compression[index] if isinstance(compression, list) else compression + if code is not None: + entries.append((259, 3, 1, struct.pack(endian + "H", code) + b"\x00\x00")) + this = layout[index] if isinstance(layout, list) else layout + if this is not None: + photometric, samples, bits = this + depths = (bits,) * samples if isinstance(bits, int) else bits + entries.append((262, 3, 1, struct.pack(endian + "H", photometric) + b"\x00\x00")) + entries.append((277, 3, 1, struct.pack(endian + "H", samples) + b"\x00\x00")) + packed = struct.pack(endian + f"{len(depths)}H", *depths) + entries.append((258, 3, len(depths), packed.ljust(4, b"\x00"))) + this_tile = tile[index] if isinstance(tile, list) else tile + if this_tile is not None: + for tag, side in zip((322, 323), this_tile, strict=True): + if side is not None: + entries.append((tag, 4, 1, struct.pack(endian + "I", side))) + this_subsampling = subsampling[index] if isinstance(subsampling, list) else subsampling + if this_subsampling is not None: + entries.append((530, 3, 2, struct.pack(endian + "HH", *this_subsampling))) + for tag, type_, data in tags or []: + per_value = {1: 1, 2: 1, 3: 2, 4: 4, 5: 8, 7: 1, 12: 8}.get(type_, 1) + entries.append((tag, type_, len(data) // per_value, data.ljust(4, b"\x00"))) + entries.sort() ifd_size = 2 + 12 * len(entries) + 4 + out_of_line = b"" + fields = b"" + for tag, kind, count, data in entries: + if len(data) > 4: + where = (1 << 30) if data_outside else offset + ifd_size + len(out_of_line) + fields += struct.pack(endian + "HHII", tag, kind, count, where) + out_of_line += data + else: + fields += struct.pack(endian + "HHI", tag, kind, count) + data + total = ifd_size + len(out_of_line) last = index == len(frames) - 1 if not last: - next_offset = offset + ifd_size + next_offset = offset + total elif loop_to_first: next_offset = first elif dangling: next_offset = 1 << 30 else: next_offset = 0 - body += struct.pack(endian + "H", len(entries)) + b"".join(entries) - body += struct.pack(endian + "I", next_offset) - offset += ifd_size + body += struct.pack(endian + "H", len(entries)) + fields + body += struct.pack(endian + "I", next_offset) + out_of_line + offset += total return header + body +def tiled_tiff(width: int, height: int, tile: int) -> bytes: + """A complete 8-bit greyscale uncompressed TIFF in ``tile`` x ``tile`` tiles, pixels and all. + + Unlike :func:`tiff`, this one decodes: the agreement test opens it with + Pillow, which reads tiled files through libtiff. + """ + across, down = -(-width // tile), -(-height // tile) + count = across * down + tile_bytes = tile * tile + entries = [ + (256, 4, 1, width), + (257, 4, 1, height), + (258, 3, 1, 8), + (259, 3, 1, 1), + (262, 3, 1, 1), + (277, 3, 1, 1), + (322, 4, 1, tile), + (323, 4, 1, tile), + ] + ifd_size = 2 + 12 * (len(entries) + 2) + 4 + offsets_at = 8 + ifd_size + counts_at = offsets_at + 4 * count + pixels_at = counts_at + 4 * count + fields = b"" + for tag, kind, n, value in entries: + raw = struct.pack(" No path = corpus.write(tmp_path / "scan.jpg", corpus.mpo([(10, 10)] * 4)) assert check(path, Policy(max_pages=3)).reasons == ("4 pages; the limit is 3",) + def test_a_pixarlog_tiff(self, tmp_path: Path) -> None: + path = corpus.write(tmp_path / "scan.tif", corpus.tiff([(10, 10)], compression=32909)) + verdict = check(path) + assert verdict.reasons == ( + "a pixar-compressed TIFF; the policy allows none, ccitt, lzw, jpeg, deflate " + "and packbits", + ) + assert verdict.facts is not None and verdict.facts.compression == "pixar" + + def test_the_policy_can_allow_a_scheme(self, tmp_path: Path) -> None: + path = corpus.write(tmp_path / "scan.tif", corpus.tiff([(10, 10)], compression=50000)) + assert check(path, Policy(tiff_compressions=frozenset({"zstd"}))).ok + verdict = check(path, Policy(tiff_compressions=frozenset({"lzw"}))) + assert verdict.reasons == ("a zstd-compressed TIFF; the policy allows lzw",) + + def test_a_cielab_tiff(self, tmp_path: Path) -> None: + path = corpus.write(tmp_path / "scan.tif", corpus.tiff([(10, 10)], layout=(8, 3, 8))) + verdict = check(path) + assert verdict.reasons == ( + "a cielab TIFF; the policy allows greyscale, rgb, palette, cmyk and ycbcr", + ) + assert verdict.facts is not None and verdict.facts.colour == "cielab" + assert check(path, Policy(tiff_photometrics=frozenset({"cielab"}))).ok + + def test_a_ycbcr_tiff_subsampled_four_by_four(self, tmp_path: Path) -> None: + data = corpus.tiff([(10, 10)], layout=(6, 3, 8), subsampling=(4, 4)) + path = corpus.write(tmp_path / "scan.tif", data) + assert check(path).reasons == ( + "a ycbcr TIFF subsampled 4x4; the policy allows 1x1, 2x1, 1x2 and 2x2", + ) + assert check(path, Policy(tiff_subsamplings=frozenset({"4x4"}))).ok + usual = corpus.write(tmp_path / "usual.tif", corpus.tiff([(10, 10)], layout=(6, 3, 8))) + verdict = check(usual) + assert verdict.ok and verdict.facts is not None and verdict.facts.subsampling == "2x2" + + def test_a_tiled_tiff_passes_by_default_and_not_under_strict(self, tmp_path: Path) -> None: + path = corpus.write(tmp_path / "map.tif", corpus.tiff([(5000, 5000)], tile=(512, 512))) + verdict = check(path) + assert verdict.ok and verdict.facts is not None and verdict.facts.tile == (512, 512) + assert check(path, STRICT).reasons == ("a tiled TIFF; the policy allows strips only",) + assert check(path, Policy(allow_tiled_tiff=False)).reasons == ( + "a tiled TIFF; the policy allows strips only", + ) + + def test_a_tile_bigger_than_the_pixel_limit(self, tmp_path: Path) -> None: + path = corpus.write(tmp_path / "scan.tif", corpus.tiff([(10, 10)], tile=(65_535, 65_535))) + assert check(path).reasons == ("a tile of 4,294,836,225 pixels; the limit is 89,478,485",) + + def test_a_tiff_that_changes_mode_between_frames(self, tmp_path: Path) -> None: + path = corpus.write( + tmp_path / "scan.tif", + corpus.tiff([(10, 10), (10, 10)], layout=[(1, 1, 8), (2, 3, 8)]), + ) + assert check(path).reasons == ( + "the header could not be read: frame 2 is rgb, 3 samples of 8 bits where frame 1 " + "is greyscale, 1 sample of 8 bits", + ) + + def test_a_tiff_that_changes_scheme_between_frames(self, tmp_path: Path) -> None: + path = corpus.write( + tmp_path / "scan.tif", corpus.tiff([(10, 10), (10, 10)], compression=[1, 5]) + ) + assert check(path).reasons == ( + "the header could not be read: frame 2 is compressed with lzw where frame 1 is " + "compressed with none", + ) + + def test_an_interlaced_png(self, tmp_path: Path) -> None: + path = corpus.write(tmp_path / "scan.png", corpus.png(10, 10, interlace=1)) + assert check(path).reasons == ("an interlaced PNG; the policy does not allow interlacing",) + assert check(path, Policy(allow_interlaced_png=True)).ok + verdict = check(path, Policy(allow_interlaced_png=True)) + assert verdict.facts is not None and verdict.facts.interlaced + + def test_a_palette_png_under_a_scans_only_policy(self, tmp_path: Path) -> None: + path = corpus.write(tmp_path / "scan.png", corpus.png(10, 10, colour=3, depth=8)) + assert check(path).ok + verdict = check(path, Policy(png_colour_types=frozenset({"greyscale", "rgb"}))) + assert verdict.reasons == ("a palette PNG; the policy allows greyscale and rgb",) + + def test_a_sixteen_bit_png_is_strict_only_by_default(self, tmp_path: Path) -> None: + path = corpus.write(tmp_path / "scan.png", corpus.png(10, 10, colour=0, depth=16)) + assert check(path).ok + assert check(path, STRICT).reasons == ("a 16-bit PNG; the limit is 8 bits",) + + def test_a_png_with_an_enormous_exif_chunk(self, tmp_path: Path) -> None: + data = corpus.png(10, 10, after_idat=corpus.png_chunk(b"eXIf", 5_000_000)) + verdict = check(corpus.write(tmp_path / "scan.png", data)) + assert verdict.reasons == ("a PNG eXIf chunk of 5,000,000 bytes; the limit is 4,194,304",) + assert verdict.facts is not None and verdict.facts.metadata == ("PNG eXIf chunk", 5_000_000) + + def test_strict_allows_less_metadata(self, tmp_path: Path) -> None: + data = corpus.jpeg(10, 10, before_sof=corpus.jpeg_profile(2_000_000)) + path = corpus.write(tmp_path / "scan.jpg", data) + assert check(path).ok + assert check(path, STRICT).reasons == ( + "a JPEG colour profile of 2,000,000 bytes; the limit is 1,048,576", + ) + assert ( + check(path, Policy(max_metadata_bytes=1_999_999)) + .reasons[0] + .startswith("a JPEG colour profile") + ) + + def test_a_tiff_tag_over_the_limit(self, tmp_path: Path) -> None: + data = corpus.tiff([(10, 10)], tags=[(34377, 7, b"\x00" * 4_194_305)]) + verdict = check(corpus.write(tmp_path / "scan.tif", data)) + assert verdict.reasons == ( + "a TIFF tag 34,377 (Photoshop) of 4,194,305 bytes; the limit is 4,194,304", + ) + def test_a_tiff_with_ten_thousand_frames(self, tmp_path: Path) -> None: verdict = check(corpus.write(tmp_path / "frames.tif", corpus.tiff([(10, 10)] * 10_000))) assert verdict.reasons == ("more than 500 pages, which is the limit",) @@ -215,7 +326,17 @@ def test_presets(self) -> None: ({"formats": frozenset()}, "at least one format"), ({"jpeg_frames": frozenset({"baseline", "mpeg"})}, "unknown JPEG frame coding"), ({"jpeg_frames": frozenset()}, "at least one JPEG frame coding"), + ({"tiff_compressions": frozenset({"lzw", "rar"})}, "unknown TIFF compression"), + ({"tiff_compressions": frozenset()}, "at least one TIFF compression"), + ({"tiff_photometrics": frozenset({"hsv"})}, "unknown TIFF photometric"), + ({"tiff_photometrics": frozenset()}, "at least one TIFF photometric"), + ({"tiff_subsamplings": frozenset({"3x3"})}, "unknown TIFF subsampling"), + ({"tiff_subsamplings": frozenset()}, "at least one TIFF subsampling"), ({"max_pages": 0}, "max_pages must be at least 1"), + ({"max_metadata_bytes": 0}, "max_metadata_bytes must be at least 1"), + ({"png_colour_types": frozenset({"cmyk"})}, "unknown PNG colour type"), + ({"png_colour_types": frozenset()}, "at least one PNG colour type"), + ({"max_png_bit_depth": 12}, "must be 1, 2, 4, 8 or 16"), ({"pdfinfo_timeout": 0}, "must be positive"), ], ) diff --git a/tests/test_cli.py b/tests/test_cli.py index 3bb9330..2892096 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -45,6 +45,30 @@ def test_options_adjust_the_policy(tmp_path: Path) -> None: lossless = corpus.write(tmp_path / "lossless.jpg", corpus.jpeg(10, 10, marker=0xC3)) assert main([str(lossless)]) == 1 assert main(["--jpeg-frames", "baseline,lossless", str(lossless)]) == 0 + webp_tiff = corpus.write(tmp_path / "webp.tif", corpus.tiff([(10, 10)], compression=50001)) + assert main([str(webp_tiff)]) == 1 + assert main(["--tiff-compressions", "none,webp", str(webp_tiff)]) == 0 + big_chunk = corpus.write( + tmp_path / "chunk.png", corpus.png(10, 10, extra=corpus.png_chunk(b"zTXt", 5000)) + ) + assert main([str(big_chunk)]) == 0 + assert main(["--max-metadata-bytes", "4000", str(big_chunk)]) == 1 + deep = corpus.write(tmp_path / "deep.png", corpus.png(10, 10, colour=3, depth=8, interlace=1)) + assert main([str(deep)]) == 1 + assert main(["--interlaced-png", str(deep)]) == 0 + assert main(["--interlaced-png", "--png-colour-types", "rgb", str(deep)]) == 1 + assert main(["--interlaced-png", "--max-png-bit-depth", "4", str(deep)]) == 1 + tiled = corpus.write(tmp_path / "map.tif", corpus.tiff([(10, 10)], tile=(16, 16))) + assert main([str(tiled)]) == 0 + assert main(["--no-tiled-tiff", str(tiled)]) == 1 + lab = corpus.write(tmp_path / "lab.tif", corpus.tiff([(10, 10)], layout=(8, 3, 8))) + assert main([str(lab)]) == 1 + assert main(["--tiff-photometrics", "cielab", str(lab)]) == 0 + chroma = corpus.write( + tmp_path / "chroma.tif", corpus.tiff([(10, 10)], layout=(6, 3, 8), subsampling=(4, 1)) + ) + assert main([str(chroma)]) == 1 + assert main(["--tiff-subsamplings", "2x2,4x1", str(chroma)]) == 0 assert main(["--any-name", str(jpeg_called_png)]) == 0 assert main(["--strict", "--max-bytes", "10", str(png)]) == 1 diff --git a/tests/test_headers.py b/tests/test_headers.py index 9095980..172c038 100644 --- a/tests/test_headers.py +++ b/tests/test_headers.py @@ -2,13 +2,22 @@ from __future__ import annotations +import dataclasses import io +import os import struct import pytest -from PIL import Image - -from sillybos import JPEG_FRAMES, headers +from PIL import Image, TiffImagePlugin + +from sillybos import ( + JPEG_FRAMES, + PNG_COLOUR_TYPES, + TIFF_COMPRESSIONS, + TIFF_PHOTOMETRICS, + TIFF_SUBSAMPLINGS, + headers, +) from sillybos.headers import HeaderError from tests import corpus @@ -137,7 +146,9 @@ def test_a_deferred_height_is_refused(self) -> None: class TestPng: def test_reads_the_dimensions_from_ihdr(self) -> None: - assert read("png", corpus.png(640, 480)) == headers.Header(640, 480, 1, 307_200) + assert read("png", corpus.png(640, 480)) == headers.Header( + 640, 480, 1, 307_200, colour="rgb", depth=8 + ) def test_counts_the_frames_of_an_animated_png(self) -> None: assert read("png", corpus.png(10, 10, frames=12)).pages == 12 @@ -167,7 +178,9 @@ class TestTiff: @pytest.mark.parametrize("endian", ["<", ">"]) def test_reads_every_frame_in_either_byte_order(self, endian: str) -> None: data = corpus.tiff([(200, 300), (400, 600), (50, 50)], endian=endian) - assert read("tiff", data) == headers.Header(200, 300, 3, 240_000) + assert read("tiff", data) == headers.Header( + 200, 300, 3, 240_000, compression="none", colour="greyscale", depth=1 + ) def test_reads_long_dimensions(self) -> None: data = corpus.tiff([(70_000, 2)], long_dims=True) @@ -197,6 +210,333 @@ def test_refuses_a_malformed_header(self, data: bytes, reason: str) -> None: read("tiff", data) +class TestTiffCompression: + def test_no_tag_means_uncompressed(self) -> None: + assert read("tiff", corpus.tiff([(10, 10)])).compression == "none" + + @pytest.mark.parametrize( + ("code", "name"), + [ + (1, "none"), + (2, "ccitt"), + (4, "ccitt"), + (5, "lzw"), + (6, "old-jpeg"), + (7, "jpeg"), + (8, "deflate"), + (32946, "deflate"), + (32773, "packbits"), + (32909, "pixar"), + (34661, "jbig"), + (34712, "jpeg2000"), + (50001, "webp"), + ], + ) + def test_names_the_scheme(self, code: int, name: str) -> None: + header = read("tiff", corpus.tiff([(10, 10), (10, 10)], compression=code)) + assert header == headers.Header( + 10, 10, 2, 100, compression=name, colour="greyscale", depth=1 + ) + + def test_every_scheme_name_is_one_the_policy_knows(self) -> None: + assert set(headers._COMPRESSIONS.values()) <= set(TIFF_COMPRESSIONS) + + def test_the_scheme_is_reported_when_the_walk_stops_early(self) -> None: + header = read("tiff", corpus.tiff([(10, 10)] * 8, compression=5), limit=3) + assert not header.complete and header.compression == "lzw" + + @pytest.mark.parametrize( + ("data", "reason"), + [ + (corpus.tiff([(10, 10)], compression=12345), "compression code 12,345, which is not"), + ( + corpus.tiff([(10, 10), (10, 10)], compression=[5, 7]), + "frame 2 is compressed with jpeg where frame 1 is compressed with lzw", + ), + ( + corpus.tiff([(10, 10), (10, 10)], compression=[None, 5]), + "frame 2 is compressed with lzw where frame 1 is compressed with none", + ), + ], + ) + def test_refuses_an_unknown_or_mixed_scheme(self, data: bytes, reason: str) -> None: + with pytest.raises(HeaderError, match=reason): + read("tiff", data) + + def test_a_compression_tag_with_two_values_is_refused(self) -> None: + data = corpus.tiff([(10, 10)], compression=5) + broken = data.replace(struct.pack(" None: + header = read("png", corpus.png(10, 10)) + assert (header.colour, header.depth, header.interlaced) == ("rgb", 8, False) + + @pytest.mark.parametrize( + ("colour", "depth", "name"), + [ + (0, 1, "greyscale"), + (0, 16, "greyscale"), + (3, 4, "palette"), + (4, 8, "greyscale-alpha"), + (6, 16, "rgba"), + ], + ) + def test_names_the_colour_type(self, colour: int, depth: int, name: str) -> None: + header = read("png", corpus.png(10, 10, colour=colour, depth=depth)) + assert (header.colour, header.depth) == (name, depth) + + def test_every_name_is_one_the_policy_knows(self) -> None: + assert {name for name, _ in headers._COLOUR_TYPES.values()} == set(PNG_COLOUR_TYPES) + + def test_interlaced(self) -> None: + assert read("png", corpus.png(10, 10, interlace=1)).interlaced + + @pytest.mark.parametrize( + ("data", "reason"), + [ + (corpus.png(10, 10, colour=1), "colour type of 1"), + (corpus.png(10, 10, colour=7), "colour type of 7"), + (corpus.png(10, 10, colour=2, depth=4), "bit depth of 4 for a rgb image"), + (corpus.png(10, 10, colour=3, depth=16), "bit depth of 16 for a palette image"), + (corpus.png(10, 10, colour=0, depth=3), "bit depth of 3 for a greyscale image"), + (corpus.png(10, 10, methods=(1, 0)), "compression or filter method other than 0"), + (corpus.png(10, 10, methods=(0, 1)), "compression or filter method other than 0"), + (corpus.png(10, 10, interlace=2), "interlace method of 2"), + ], + ) + def test_refuses_an_impossible_ihdr(self, data: bytes, reason: str) -> None: + with pytest.raises(HeaderError, match=reason): + read("png", data) + + +class TestMetadata: + """The largest block of metadata each reader passes over, for the policy to bound.""" + + def test_the_largest_png_chunk_before_the_image_data(self) -> None: + extra = corpus.png_chunk(b"iCCP", 3000) + corpus.png_chunk(b"tEXt", 500) + assert read("png", corpus.png(10, 10, extra=extra)).metadata == ("PNG iCCP chunk", 3000) + + def test_a_png_chunk_after_the_image_data_counts(self) -> None: + data = corpus.png(10, 10, after_idat=corpus.png_chunk(b"eXIf", 70_000), idats=40) + assert read("png", data).metadata == ("PNG eXIf chunk", 70_000) + + def test_png_image_data_is_skipped_not_measured(self) -> None: + data = corpus.png(10, 10, extra=corpus.png_chunk(b"IDAT", 90_000)) + assert read("png", data).metadata is None + + def test_a_png_with_too_many_image_data_chunks(self, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(headers, "MAX_IDAT_CHUNKS", 10) + with pytest.raises(HeaderError, match="more than 10 image-data chunks"): + read("png", corpus.png(10, 10, idats=11)) + + def test_a_png_with_too_many_other_chunks(self) -> None: + data = corpus.png(10, 10, extra=corpus.png_chunk(b"tEXt", 0) * headers.MAX_SEGMENTS) + with pytest.raises(HeaderError, match="chunks besides the image data"): + read("png", data) + + def test_a_png_chunk_type_that_is_not_letters(self) -> None: + with pytest.raises(HeaderError, match="not four letters"): + read("png", corpus.png(10, 10, extra=corpus.png_chunk(b"eX\x00f", 4))) + + def test_a_png_chunk_after_the_image_data_that_runs_past_the_end(self) -> None: + data = corpus.png(10, 10, after_idat=b"\x00\x10\x00\x00eXIf") + with pytest.raises(HeaderError, match="runs past the end"): + read("png", data) + + def test_a_jpeg_colour_profile_summed_across_segments(self) -> None: + data = corpus.jpeg(10, 10, before_sof=corpus.jpeg_profile(200_000)) + assert read("jpeg", data).metadata == ("JPEG colour profile", 200_000) + + def test_a_jpeg_without_a_profile_has_no_metadata_block(self) -> None: + assert read("jpeg", corpus.jpeg(10, 10, before_sof=corpus.jpeg_padding(3))).metadata is None + + def test_the_largest_tiff_tag_data(self) -> None: + tags = [(700, 1, b"" * 1000), (270, 2, b"a scan\x00")] + header = read("tiff", corpus.tiff([(10, 10)], tags=tags)) + assert header.metadata == ("TIFF tag 700 (XMP)", 6000) + + def test_an_unlabelled_tiff_tag(self) -> None: + header = read("tiff", corpus.tiff([(10, 10)], tags=[(50_000, 7, b"\x00" * 99)])) + assert header.metadata == ("TIFF tag 50,000", 99) + + def test_tiff_tag_data_inside_the_field_is_not_a_block(self) -> None: + assert read("tiff", corpus.tiff([(10, 10)], tags=[(296, 3, b"\x02\x00")])).metadata is None + + @pytest.mark.parametrize("type_", [4, 12, 99]) + def test_tiff_tag_data_outside_the_file(self, type_: int) -> None: + data = corpus.tiff([(10, 10)], tags=[(700, type_, b"\x00" * 64)], data_outside=True) + with pytest.raises(HeaderError, match="frame 1's tag 700 data lies outside the file"): + read("tiff", data) + + def test_a_tiff_tag_claiming_more_data_than_the_file_holds(self) -> None: + data = corpus.tiff([(10, 10)]).replace( + struct.pack("<HHI", 256, 3, 1), struct.pack("<HHI", 256, 3, 1 << 30) + ) + with pytest.raises(HeaderError, match="tag 256 data lies outside the file"): + read("tiff", data) + + +class TestTiffPhotometric: + def test_white_and_black_is_zero_are_both_greyscale(self) -> None: + data = corpus.tiff([(10, 10), (10, 10)], layout=[(0, 1, 1), (1, 1, 1)]) + header = read("tiff", data) + assert (header.colour, header.depth, header.pages) == ("greyscale", 1, 2) + + @pytest.mark.parametrize( + ("code", "name"), + [ + (2, "rgb"), + (3, "palette"), + (4, "mask"), + (5, "cmyk"), + (6, "ycbcr"), + (8, "cielab"), + (32803, "cfa"), + (34892, "linear-raw"), + ], + ) + def test_names_the_photometric(self, code: int, name: str) -> None: + assert read("tiff", corpus.tiff([(10, 10)], layout=(code, 3, 8))).colour == name + + def test_every_name_is_one_the_policy_knows(self) -> None: + assert set(headers._PHOTOMETRICS.values()) == set(TIFF_PHOTOMETRICS) + + def test_an_unknown_photometric_is_refused(self) -> None: + with pytest.raises(HeaderError, match="photometric interpretation 99, which is not"): + read("tiff", corpus.tiff([(10, 10)], layout=(99, 3, 8))) + + def test_ycbcr_defaults_to_two_by_two(self) -> None: + assert read("tiff", corpus.tiff([(10, 10)], layout=(6, 3, 8))).subsampling == "2x2" + + def test_reads_the_subsampling_tag(self) -> None: + data = corpus.tiff([(10, 10)], layout=(6, 3, 8), subsampling=(4, 4)) + assert read("tiff", data).subsampling == "4x4" + + def test_subsampling_is_ignored_unless_ycbcr(self) -> None: + data = corpus.tiff([(10, 10)], layout=RGB, subsampling=(4, 4)) + assert read("tiff", data).subsampling is None + + def test_every_subsampling_name_is_one_the_policy_knows(self) -> None: + names = {f"{h}x{v}" for h in (1, 2, 4) for v in (1, 2, 4)} + assert names == set(TIFF_SUBSAMPLINGS) + + @pytest.mark.parametrize( + ("data", "reason"), + [ + (corpus.tiff([(10, 10)], layout=(6, 3, 8), subsampling=(3, 1)), "subsampling of 3x1"), + (corpus.tiff([(10, 10)], layout=(6, 3, 8), subsampling=(2, 0)), "subsampling of 2x0"), + ( + corpus.tiff([(10, 10)] * 2, layout=(6, 3, 8), subsampling=[(2, 2), (1, 1)]), + "frame 2 is subsampled 1x1 where frame 1 is subsampled 2x2", + ), + ( + corpus.tiff([(10, 10)], layout=(6, 3, 8)).replace( + struct.pack("<HHI", 277, 3, 1), struct.pack("<HHI", 530, 3, 1) + ), + "subsampling tag is not two SHORTs", + ), + ], + ) + def test_refuses_a_malformed_subsampling(self, data: bytes, reason: str) -> None: + with pytest.raises(HeaderError, match=reason): + read("tiff", data) + + +class TestTiffTiles: + def test_strips_have_no_tile(self) -> None: + assert read("tiff", corpus.tiff([(10, 10)])).tile is None + + def test_the_largest_tile_across_frames(self) -> None: + data = corpus.tiff([(1000, 1000)] * 3, tile=[(256, 256), (512, 256), (16, 16)]) + assert read("tiff", data).tile == (512, 256) + + def test_a_tile_larger_than_the_image_is_legal(self) -> None: + assert read("tiff", corpus.tiff([(100, 100)], tile=(256, 256))).tile == (256, 256) + + @pytest.mark.parametrize( + ("data", "reason"), + [ + (corpus.tiff([(10, 10)], tile=(16, None)), "tile width or length but not both"), + (corpus.tiff([(10, 10)], tile=(None, 16)), "tile width or length but not both"), + (corpus.tiff([(10, 10)], tile=(0, 16)), "frame 1's tile gives a zero width"), + ( + corpus.tiff([(10, 10)], tile=(16, 1 << 31)), + "frame 1's tile gives a width or height of", + ), + ], + ) + def test_refuses_a_malformed_tiling(self, data: bytes, reason: str) -> None: + with pytest.raises(HeaderError, match=reason): + read("tiff", data) + + +GREY = (1, 1, 8) +RGB = (2, 3, 8) + + +class TestTiffLayout: + """Every frame must share the first frame's photometric, samples and bit depth.""" + + def test_defaults_when_the_tags_are_absent(self) -> None: + assert read("tiff", corpus.tiff([(10, 10), (10, 10)])).pages == 2 + + def test_a_shared_layout_passes_with_bits_out_of_line(self) -> None: + data = corpus.tiff([(10, 10), (20, 20), (30, 30)], layout=RGB) + assert read("tiff", data).pages == 3 + + @pytest.mark.parametrize("endian", ["<", ">"]) + def test_in_either_byte_order(self, endian: str) -> None: + data = corpus.tiff([(10, 10), (10, 10)], layout=[(2, 4, 16), (2, 4, 16)], endian=endian) + assert read("tiff", data).pages == 2 + + @pytest.mark.parametrize( + ("layouts", "reason"), + [ + ([GREY, RGB], "frame 2 is rgb, 3 samples of 8 bits where frame 1 is greyscale"), + ([GREY, (1, 1, 16)], "frame 2 is greyscale, 1 sample of 16 bits"), + ([RGB, (2, 4, 8)], "frame 2 is rgb, 4 samples of 8 bits where frame 1 is rgb, 3"), + ([GREY, None], "frame 2 is greyscale, 1 sample of 1 bits"), + ([(5, 4, 8), (6, 3, 8)], "frame 2 is ycbcr, 3 samples of 8 bits where frame 1 is cmyk"), + ], + ) + def test_refuses_a_frame_that_changes_layout( + self, layouts: list[corpus.Layout | None], reason: str + ) -> None: + with pytest.raises(HeaderError, match=reason): + read("tiff", corpus.tiff([(10, 10), (10, 10)], layout=layouts)) + + @pytest.mark.parametrize( + ("data", "reason"), + [ + (corpus.tiff([(10, 10)], layout=(2, 3, (8, 8, 16))), "different bit depths per sample"), + (corpus.tiff([(10, 10)], layout=(1, 2, (8, 16))), "different bit depths per sample"), + (corpus.tiff([(10, 10)], layout=(2, 3, 8), data_outside=True), "outside the file"), + (corpus.tiff([(10, 10)], layout=(2, 65, 8)), "lists 65 samples"), + ( + corpus.tiff([(10, 10)], layout=GREY).replace( + struct.pack("<HHI", 258, 3, 1), struct.pack("<HHI", 258, 4, 1) + ), + "bits-per-sample tag is not SHORT", + ), + ( + corpus.tiff([(10, 10)], layout=GREY).replace( + struct.pack("<HHI", 262, 3, 1), struct.pack("<HHI", 262, 3, 2) + ), + "photometric tag holds more than one value", + ), + ], + ) + def test_refuses_a_malformed_layout(self, data: bytes, reason: str) -> None: + with pytest.raises(HeaderError, match=reason): + read("tiff", data) + + class TestAgainstPillow: """Real files, as Pillow writes them: our readers agree with Pillow's.""" @@ -205,18 +545,119 @@ def test_single_images(self, fmt: str, mode: str) -> None: buffer = io.BytesIO() Image.new(mode, (123, 45)).save(buffer, format=fmt) data = buffer.getvalue() - coding = "baseline" if fmt == "JPEG" else None - assert read(fmt.lower(), data) == headers.Header(123, 45, 1, 123 * 45, coding=coding) + expected = headers.Header(123, 45, 1, 123 * 45) + if fmt == "JPEG": + expected = dataclasses.replace(expected, coding="baseline") + elif fmt == "PNG": + expected = dataclasses.replace(expected, colour="rgba", depth=8) + else: + expected = dataclasses.replace( + expected, compression="none", colour="greyscale", depth=1 + ) + assert read(fmt.lower(), data) == expected + + @pytest.mark.parametrize( + ("mode", "pillow_name", "name"), + [ + ("1", "group4", "ccitt"), + ("L", "tiff_lzw", "lzw"), + ("RGB", "jpeg", "jpeg"), + ("L", "tiff_adobe_deflate", "deflate"), + ("L", "packbits", "packbits"), + ], + ) + def test_compressed_tiffs(self, mode: str, pillow_name: str, name: str) -> None: + buffer = io.BytesIO() + Image.new(mode, (40, 24)).save(buffer, format="TIFF", compression=pillow_name) + assert read("tiff", buffer.getvalue()).compression == name - def test_a_multi_frame_tiff(self) -> None: + @pytest.mark.parametrize( + ("mode", "colour", "depth"), + [ + ("1", "greyscale", 1), + ("L", "greyscale", 8), + ("I;16", "greyscale", 16), + ("P", "palette", 8), + ("LA", "greyscale-alpha", 8), + ("RGB", "rgb", 8), + ("RGBA", "rgba", 8), + ], + ) + def test_png_kinds_as_pillow_writes_them(self, mode: str, colour: str, depth: int) -> None: buffer = io.BytesIO() - first, *rest = [Image.new("L", (20 + i, 30)) for i in range(4)] + image = Image.new(mode, (8, 8)) + if mode == "P": + image.putpalette(list(range(256)) * 3) # else Pillow writes the palette at 1 bit + image.save(buffer, format="PNG") + header = read("png", buffer.getvalue()) + assert (header.colour, header.depth, header.interlaced) == (colour, depth, False) + + @pytest.mark.parametrize( + ("mode", "colour", "depth", "subsampling"), + [ + ("1", "greyscale", 1, None), + ("L", "greyscale", 8, None), + ("I;16", "greyscale", 16, None), + ("P", "palette", 8, None), + ("RGB", "rgb", 8, None), + ("CMYK", "cmyk", 8, None), + ("YCbCr", "ycbcr", 8, "1x1"), + ("LAB", "cielab", 8, None), + ], + ) + def test_tiff_photometrics_as_pillow_writes_them( + self, mode: str, colour: str, depth: int, subsampling: str | None + ) -> None: + buffer = io.BytesIO() + Image.new(mode, (8, 8)).save(buffer, format="TIFF") + header = read("tiff", buffer.getvalue()) + assert (header.colour, header.depth, header.subsampling) == (colour, depth, subsampling) + + def test_a_tiled_tiff_as_pillow_reads_it(self) -> None: + """Pillow does not write tiles, so a hand-made one is checked against its reading.""" + data = corpus.tiled_tiff(40, 24, 16) + header = read("tiff", data) + with Image.open(io.BytesIO(data)) as image: + assert isinstance(image, TiffImagePlugin.TiffImageFile) + image.load() + assert (image.size, image.tag_v2[322], image.tag_v2[323]) == ((40, 24), 16, 16) + assert header.width == 40 and header.height == 24 and header.tile == (16, 16) + + def test_metadata_blocks_as_pillow_writes_them(self) -> None: + """The profile is incompressible so that a PNG's deflated iCCP stays its size.""" + profile = os.urandom(100_000) + image = Image.new("RGB", (16, 16)) + exif = image.getexif() + exif[0x010E] = "x" * 2000 + for fmt in ("JPEG", "PNG", "TIFF"): + buffer = io.BytesIO() + image.save(buffer, format=fmt, icc_profile=profile, exif=exif) + header = read(fmt.lower(), buffer.getvalue()) + with Image.open(buffer) as back: + assert len(back.info["icc_profile"]) == len(profile) + assert header.metadata is not None + assert header.metadata[1] >= len(profile), (fmt, header.metadata) + assert header.metadata[1] < len(profile) + 100, (fmt, header.metadata) + + @pytest.mark.parametrize("mode", ["L", "RGB", "RGBA", "I;16"]) + def test_a_multi_frame_tiff(self, mode: str) -> None: + buffer = io.BytesIO() + first, *rest = [Image.new(mode, (20 + i, 30)) for i in range(4)] first.save(buffer, format="TIFF", save_all=True, append_images=rest) header = read("tiff", buffer.getvalue()) with Image.open(buffer) as image: assert header.pages == getattr(image, "n_frames", 1) == 4 assert header.max_pixels == 23 * 30 + def test_a_multi_frame_tiff_that_changes_mode_is_refused(self) -> None: + """The shape of CVE-2026-96639: a later frame wider than the buffer sized for the first.""" + buffer = io.BytesIO() + Image.new("L", (20, 30)).save( + buffer, format="TIFF", save_all=True, append_images=[Image.new("RGB", (20, 30))] + ) + with pytest.raises(HeaderError, match="frame 2 is rgb, 3 samples of 8 bits where frame 1"): + read("tiff", buffer.getvalue()) + def test_a_progressive_jpeg_and_an_exif_jpeg(self) -> None: buffer = io.BytesIO() image = Image.new("RGB", (64, 32))