Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 34 additions & 12 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down Expand Up @@ -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
Expand All @@ -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.
Expand Down Expand Up @@ -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.
Expand Down
16 changes: 15 additions & 1 deletion src/sillybos/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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__
Expand All @@ -39,7 +49,11 @@
"DEFAULT",
"FORMATS",
"JPEG_FRAMES",
"PNG_COLOUR_TYPES",
"STRICT",
"TIFF_COMPRESSIONS",
"TIFF_PHOTOMETRICS",
"TIFF_SUBSAMPLINGS",
"Facts",
"Policy",
"Refused",
Expand Down
76 changes: 72 additions & 4 deletions src/sillybos/check.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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)
Expand All @@ -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
Expand All @@ -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)
Expand Down Expand Up @@ -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))


Expand Down Expand Up @@ -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:
Expand All @@ -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:
Expand All @@ -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


Expand Down
58 changes: 58 additions & 0 deletions src/sillybos/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,13 +30,27 @@ 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
}
if args.formats:
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
Expand Down Expand Up @@ -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",
Expand All @@ -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",
Expand Down
Loading
Loading