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
31 changes: 19 additions & 12 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -92,9 +92,10 @@ check(path, Policy(formats={"tiff", "pdf"}, max_pages=50))
| `formats` | jpeg, png, tiff, pdf | the same | What may pass at all. Nothing else is ever allowed, whatever the policy says |
| `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. Also bounds the header walk itself |
| `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 |
| `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 |
| `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 @@ -131,7 +132,8 @@ 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` and `--any-name` adjust the policy; `--json`
`--max-pixels`, `--max-bytes`, `--jpeg-frames` 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 @@ -145,11 +147,13 @@ 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 from a JPEG's frame header, 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 every offset is checked against the file's size. For a PDF,
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
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.
5. **The limits**, against what the header said.
Expand All @@ -161,8 +165,9 @@ Say this plainly, because a security library carries an implied promise.
- **It does not protect against a flaw in the readers you *do* allow.** A
crafted JPEG that exploits a bug in your JPEG decoder passes this check,
because it is a JPEG of a sensible size. What this library removes is the
attack surface of every format you did not mean to read, and the whole
class of files that are too big to be safe. For the readers you keep:
attack surface of every format you did not mean to read, the whole class
of files that are too big to be safe, and, where the header shows them,
the rare codings a scanner never writes. For the readers you keep:
update them, and run them in a boxed process with memory and time
limits (a recipe for that is planned; it is deliberately not a
dependency).
Expand Down Expand Up @@ -192,9 +197,11 @@ 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 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
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
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
3 changes: 2 additions & 1 deletion src/sillybos/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
from __future__ import annotations

from sillybos.check import Facts, Refused, Verdict, check, require
from sillybos.policy import DEFAULT, FORMATS, STRICT, Policy
from sillybos.policy import DEFAULT, FORMATS, JPEG_FRAMES, STRICT, Policy

try:
from sillybos._version import __version__
Expand All @@ -38,6 +38,7 @@
__all__ = [
"DEFAULT",
"FORMATS",
"JPEG_FRAMES",
"STRICT",
"Facts",
"Policy",
Expand Down
21 changes: 19 additions & 2 deletions src/sillybos/check.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@
does not allow is refused by name, and no reader of ours runs on it.
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.
``pdfinfo`` in a separate process for PDF): dimensions, frames, pages,
and how a JPEG is coded.
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 @@ -25,7 +26,7 @@

from sillybos import headers, sniff
from sillybos.pdf import pdf as read_pdf
from sillybos.policy import DEFAULT, FORMATS, Policy
from sillybos.policy import DEFAULT, FORMATS, JPEG_FRAMES, Policy


@dataclass(frozen=True)
Expand All @@ -46,6 +47,8 @@ class Facts:
encrypted: Whether a PDF is encrypted. Always ``False`` for an image.
pages_exact: ``False`` when the frame walk stopped at the limit, so
``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.
"""

bytes: int
Expand All @@ -55,6 +58,7 @@ class Facts:
max_pixels: int | None
encrypted: bool = False
pages_exact: bool = True
coding: str | None = None


@dataclass(frozen=True)
Expand Down Expand Up @@ -189,6 +193,7 @@ def _facts(path: Path, fmt: str, f: headers.Reader, size: int, policy: Policy) -
header.pages,
header.max_pixels if header.complete else None,
pages_exact=header.complete,
coding=header.coding,
)


Expand All @@ -203,4 +208,16 @@ def _against_limits(facts: Facts, policy: Policy) -> list[str]:
reasons.append(f"a page of {facts.max_pixels:,} pixels; the limit is {policy.max_pixels:,}")
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:
allowed = [name for name in JPEG_FRAMES if name in policy.jpeg_frames]
article = "an" if facts.coding[0] in "aeiou" else "a"
reasons.append(
f"{article} {facts.coding} JPEG; the policy allows {_listed(allowed)} frames"
)
return reasons


def _listed(names: list[str]) -> str:
if len(names) < 2:
return "".join(names)
return ", ".join(names[:-1]) + " and " + names[-1]
11 changes: 11 additions & 0 deletions src/sillybos/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@ def _policy(args: argparse.Namespace) -> Policy:
}
if args.formats:
changes["formats"] = frozenset(args.formats.split(","))
if args.jpeg_frames:
changes["jpeg_frames"] = frozenset(args.jpeg_frames.split(","))
if args.any_name:
changes["name_must_match"] = False
return dataclasses.replace(base, **changes) if changes else base
Expand Down Expand Up @@ -63,6 +65,15 @@ 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(
"--jpeg-frames",
metavar="LIST",
help=(
"comma-separated JPEG frame codings to allow, from "
"baseline,extended,progressive,lossless,hierarchical,arithmetic "
"(default: the first three)"
),
)
parser.add_argument(
"--any-name",
action="store_true",
Expand Down
162 changes: 149 additions & 13 deletions src/sillybos/headers.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,13 +49,17 @@ class Header:
max_pixels: The most pixels in any one frame the reader looked at.
complete: ``False`` if the walk stopped at the limit, so ``pages``
and ``max_pixels`` describe only the frames it reached.
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.
"""

width: int
height: int
pages: int
max_pixels: int
complete: bool = True
coding: str | None = None


def _read_exactly(f: Reader, n: int, what: str) -> bytes:
Expand All @@ -74,19 +78,88 @@ def _dimensions(width: int, height: int, what: str) -> None:

# --- JPEG -------------------------------------------------------------------

# Start-of-frame markers, which carry the dimensions. C4 (DHT), C8 (JPG
# extension) and CC (DAC) share the range but are not frames.
_SOF = {0xC0, 0xC1, 0xC2, 0xC3, 0xC5, 0xC6, 0xC7, 0xC9, 0xCA, 0xCB, 0xCD, 0xCE, 0xCF}
# Start-of-frame markers, which carry the dimensions, and how each codes the
# image. C4 (DHT), C8 (JPG extension) and CC (DAC) share the range but are
# not frames. A scanner writes baseline or progressive frames; the rest are
# legal JPEG that no scanner produces and the decoder's rarest paths, and the
# policy says which may pass. The names are :data:`sillybos.JPEG_FRAMES`.
_FRAME_CODINGS = {
0xC0: "baseline",
0xC1: "extended",
0xC2: "progressive",
0xC3: "lossless",
0xC5: "hierarchical",
0xC6: "hierarchical",
0xC7: "hierarchical",
0xC9: "arithmetic",
0xCA: "arithmetic",
0xCB: "arithmetic",
0xCD: "hierarchical",
0xCE: "hierarchical",
0xCF: "hierarchical",
}
# Markers with no length field.
_STANDALONE = {0x01, 0xD0, 0xD1, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7, 0xD8}
_APP2 = 0xE2
_MPF = b"MPF\x00"
_MP_NUMBER_OF_IMAGES = 0xB001
_MP_ENTRY = 0xB002


@dataclass(frozen=True)
class _Frame:
width: int
height: int
coding: str
components: int


def jpeg(f: Reader, size: int, limit: int) -> Header:
"""Read a JPEG's frame header: walk the segments to the first SOF marker."""
del limit # a JPEG has one frame
f.seek(0)
"""Read a JPEG's frame header, and every picture of a multi-picture file.

The segments are walked to the first SOF marker, which carries the
dimensions, the coding and the component count. An APP2 segment holding
a Multi-Picture Format index (the MPO files that cameras and phones
write, which Pillow steps through as frames) names further pictures by
offset and size. Each is read the same way and counted as a page, and
each must match the first in coding and components, because the decoder
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)
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)
if not 2 <= offset < size:
raise HeaderError(f"picture {number} lies outside the file")
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}"
)
if picture.components != first.components:
raise HeaderError(
f"picture {number} has {picture.components} components "
f"where picture 1 has {first.components}"
)
pages += 1
max_pixels = max(max_pixels, picture.width * picture.height)
return Header(first.width, first.height, pages, max_pixels, coding=first.coding)


def _frame(f: Reader, size: int, start: int, what: str, *, index: bool) -> tuple[_Frame, list[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.
"""
f.seek(start)
if _read_exactly(f, 2, "header") != b"\xff\xd8":
raise HeaderError("no JPEG start-of-image marker")
raise HeaderError(f"no JPEG start-of-image marker in the {what}")
pictures: list[int] = []
for _ in range(MAX_SEGMENTS):
byte = _read_exactly(f, 1, "segment marker")
if byte != b"\xff":
Expand All @@ -101,23 +174,86 @@ def jpeg(f: Reader, size: int, limit: int) -> Header:
(length,) = struct.unpack(">H", _read_exactly(f, 2, "segment length"))
if length < 2:
raise HeaderError("a segment claims a length shorter than its own length field")
if marker in _SOF:
if length < 7:
if marker in _FRAME_CODINGS:
if length < 8:
raise HeaderError("the frame header is too short to hold the dimensions")
_precision, height, width = struct.unpack(">BHH", _read_exactly(f, 5, "frame header"))
_precision, height, width, components = struct.unpack(
">BHHB", _read_exactly(f, 6, "frame header")
)
if height == 0:
# Legal (a DNL marker supplies it later) and never seen in a
# scan; refusing it keeps every decoder's rarest path closed.
raise HeaderError("the height is deferred to a DNL marker")
_dimensions(width, height, "frame header")
return Header(width, height, 1, width * height)
next_offset = f.tell() + length - 2
_dimensions(width, height, what)
return _Frame(width, height, _FRAME_CODINGS[marker], components), pictures
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))
f.seek(next_offset)
raise HeaderError(f"no frame header in the first {MAX_SEGMENTS} segments")


def _mp_index(data: bytes, base: int) -> list[int]:
"""Read the MP Index IFD of a Multi-Picture Format segment.

``data`` is the segment after its ``MPF`` identifier: a small TIFF of
its own, whose offsets count from its first byte, which sits at ``base``
in the file. Returns the offset in the file of every picture after the
first. An index that names one picture, or none, is an ordinary JPEG,
which is how Pillow reads it too. Each entry also carries the picture's
size, which is ignored here as it is by Pillow's reader (and written
wrongly, from the third picture on, by Pillow's writer): a decoder that
never reads a field cannot be steered by it.
"""
if len(data) < 8:
raise HeaderError("the multi-picture index is too short")
endian = {b"II*\x00": "<", b"MM\x00*": ">"}.get(data[:4])
if endian is None:
raise HeaderError("the multi-picture index has no byte-order mark")
(offset,) = struct.unpack(endian + "I", data[4:8])
if offset + 2 > len(data):
raise HeaderError("the multi-picture index lies outside its segment")
(count,) = struct.unpack(endian + "H", data[offset : offset + 2])
if offset + 2 + count * 12 > len(data):
raise HeaderError("the multi-picture index runs past its segment")
number = 1
entries: list[tuple[int, int, int, int, int]] = []
for position in range(offset + 2, offset + 2 + count * 12, 12):
tag, _kind, n, raw = struct.unpack(endian + "HHI4s", data[position : position + 12])
if tag == _MP_NUMBER_OF_IMAGES:
(number,) = struct.unpack(endian + "I", raw)
elif tag == _MP_ENTRY:
(at,) = struct.unpack(endian + "I", raw)
if n % 16 or at + n > len(data):
raise HeaderError("the multi-picture entries lie outside their segment")
entries = [
struct.unpack(endian + "IIIHH", data[at + k : at + k + 16]) for k in range(0, n, 16)
]
if number <= 1 and len(entries) <= 1:
return []
if number != len(entries):
raise HeaderError(
f"the multi-picture index names {number:,} pictures but lists {len(entries):,}"
)
pictures = []
for position, (attribute, _length, offset, _dep1, _dep2) in enumerate(entries[1:], start=2):
if (attribute >> 24) & 0x07:
raise HeaderError(f"picture {position} is not coded as JPEG")
pictures.append(base + offset)
return pictures


# --- PNG --------------------------------------------------------------------


Expand Down
Loading
Loading