From 6246f8cd8413cb2700af4383b4a179314643b80d Mon Sep 17 00:00:00 2001 From: Stephen Masters Date: Sun, 1 Nov 2026 21:36:07 +0000 Subject: [PATCH 1/2] feat!: refuse the PDF features a scanned book never has JavaScript, a form, attached files and a launch action are each a way for a document to make the viewer act rather than draw the page, and none of them belongs in a scan. The default policy now refuses all four, and `pdf_features` names the ones a policy will pass; `--pdf-features` does the same for the command. The verdict's facts carry what was found. JavaScript and forms are read from pdfinfo's report and attached files from pdfdetach's listing, so a feature inside a compressed object stream is still seen. A launch action is reported by no poppler tool, so it is found by its name in the file, the way pdfid finds it: a bounded scan of the bytes with the #xx escapes undone, which is a search and not a parser; AGENTS.md says so and says it must stay that way. Attached files and the scan are only looked for when the page count is within the limit, since a file over it is refused whatever else it carries. Breaking: a PDF that carries any of the four, which passed before, is refused by default. The hostile corpus gains a PDF for each, including the escaped spellings. Stage 2 of brief 022. Co-authored-by: Yvette Mankerian Co-Authored-By: Claude Fable 5.1 --- AGENTS.md | 10 ++-- README.md | 19 ++++--- docs/api.md | 2 + src/sillybos/__init__.py | 9 ++-- src/sillybos/check.py | 29 +++++++++- src/sillybos/cli.py | 10 ++++ src/sillybos/pdf.py | 113 ++++++++++++++++++++++++++++++++------- src/sillybos/policy.py | 21 ++++++++ tests/corpus.py | 82 ++++++++++++++++++++++++++-- tests/test_check.py | 45 ++++++++++++++++ tests/test_cli.py | 9 ++++ tests/test_pdf.py | 41 ++++++++++++++ 12 files changed, 352 insertions(+), 38 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index ef17afe..b00de3d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -34,9 +34,13 @@ code touches it. So: bounded code. Never replace a reader with a call into Pillow, `imageio` or anything else that decodes; never import Pillow outside `sillybos/pillow.py`, which is the optional extra. -- A PDF is asked about through `pdfinfo` in a subprocess with a timeout. - Never add a PDF parser as a dependency, and never read a PDF's objects - with code here. +- A PDF is asked about through `pdfinfo` and `pdfdetach` in a subprocess + with a timeout. Never add a PDF parser as a dependency, and never read a + PDF's objects with code here. The one thing this code does read from a + PDF's bytes is the *name* of a launch action, by a bounded search for + its spelling (`pdf.py`, `_has_launch_action`), because no poppler tool + reports one; a search for bytes is not a parser, and it must stay that + way. - The library has **no runtime dependencies**, and `[project] dependencies` stays `[]`. Everything else goes in an extra. - Every read of a file is bounded by a constant or by the policy, and every diff --git a/README.md b/README.md index b5b9246..75233ee 100644 --- a/README.md +++ b/README.md @@ -17,9 +17,10 @@ opens a file: *is this one of the formats I mean to read, within the limits I expect, and if not, why?* It names the format from the file's first bytes, whatever the file is called; reads the header of a JPEG, PNG or TIFF with a few dozen lines of its own, never a decoder's; asks poppler's `pdfinfo`, in -a separate process with a time limit, how many pages a PDF has and how large -they are; and refuses, in a plain sentence, anything outside the policy you -give it. +a separate process with a time limit, how many pages a PDF has, how large +they are and whether it carries JavaScript, a form, attached files or a +launch action; and refuses, in a plain sentence, anything outside the +policy you give it. > **Status: alpha.** The API is small and may still move. It is in use in > [Tetrak OCR](https://tetrak.dev/), which is where it came from. @@ -108,6 +109,7 @@ check(path, Policy(formats={"tiff", "pdf"}, max_pages=50)) | `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 | +| `pdf_features` | none | none | Which of JavaScript, forms, attached files and launch actions a PDF may carry. Each makes a viewer do something other than draw the page, and a scanned book has none. JavaScript and forms are read from `pdfinfo`'s report and attached files from `pdfdetach`'s; a launch action is found by its name in the file, since no poppler tool reports one | | `pdfinfo_timeout` | 30 s | 30 s | How long `pdfinfo` may take before the file is refused | The defaults were set from a real corpus of archival scans (largest page 39 @@ -143,6 +145,7 @@ ok scans/page-001.tif (TIFF, 4960x7016, 1 page, 1.6 MB) refused scans/page-002.png says PNG, is PostScript refused scans/poster.jpg a page of 1,200,000,000 pixels; the limit is 89,478,485 refused scans/report.pdf 1,412 pages; the limit is 500 +refused scans/form.pdf a PDF with JavaScript and a form; the policy allows none of the features a PDF can carry ``` Exit status 0 when every file passed, 1 when any was refused, 2 when the @@ -150,7 +153,7 @@ command could not do its job. `--strict`, `--formats`, `--max-pages`, `--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` +`--interlaced-png`, `--pdf-features` and `--any-name` adjust the policy; `--json` prints one object per line for a pipeline; `-q` prints only refusals. ## What it does, exactly @@ -180,8 +183,12 @@ prints one object per line for a pipeline; `-q` prints only refusals. 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. + `pdfinfo` reports the page count, whether it is encrypted, whether it + carries JavaScript or a form and, if the count is within the limit, + every page's size; `pdfdetach` reports attached files; and a bounded + scan of the bytes finds the name of a launch action, with the `#xx` + escapes a name may hide behind undone, since no poppler tool reports + one. 5. **The limits**, against what the header said. ## What it does not do diff --git a/docs/api.md b/docs/api.md index 66b660e..b479fd9 100644 --- a/docs/api.md +++ b/docs/api.md @@ -44,6 +44,8 @@ chooses from it. ::: sillybos.JPEG_FRAMES +::: sillybos.PDF_FEATURES + ::: sillybos.PNG_COLOUR_TYPES ::: sillybos.TIFF_COMPRESSIONS diff --git a/src/sillybos/__init__.py b/src/sillybos/__init__.py index 0ab8988..a761715 100644 --- a/src/sillybos/__init__.py +++ b/src/sillybos/__init__.py @@ -10,9 +10,10 @@ It reads the first bytes to learn what the file really is, whatever its name says; reads the header of a JPEG, PNG or TIFF with code of its own, never a -decoder's; asks poppler's `pdfinfo`, in a separate process, how many pages -a PDF has and how large they are; and refuses, with a reason in plain words, -anything outside a [Policy][sillybos.Policy]. +decoder's; asks poppler's `pdfinfo` and `pdfdetach`, in a separate process, +how many pages a PDF has, how large they are and whether it carries +JavaScript, a form or attached files; and refuses, with a reason in plain +words, anything outside a [Policy][sillybos.Policy]. ```python from sillybos import check @@ -34,6 +35,7 @@ DEFAULT, FORMATS, JPEG_FRAMES, + PDF_FEATURES, PNG_COLOUR_TYPES, STRICT, TIFF_COMPRESSIONS, @@ -51,6 +53,7 @@ "DEFAULT", "FORMATS", "JPEG_FRAMES", + "PDF_FEATURES", "PNG_COLOUR_TYPES", "STRICT", "TIFF_COMPRESSIONS", diff --git a/src/sillybos/check.py b/src/sillybos/check.py index b17a0bc..5c95029 100644 --- a/src/sillybos/check.py +++ b/src/sillybos/check.py @@ -30,6 +30,7 @@ DEFAULT, FORMATS, JPEG_FRAMES, + PDF_FEATURES, PNG_COLOUR_TYPES, TIFF_COMPRESSIONS, TIFF_PHOTOMETRICS, @@ -74,6 +75,9 @@ class Facts: a TIFF in strips and for the other formats. subsampling: A YCbCr TIFF's chroma subsampling, horizontal by vertical, as `"2x2"`; `None` otherwise. + features: Which of [sillybos.PDF_FEATURES][] a PDF carries: + JavaScript, a form, attached files, a launch action. Empty for + an image and for a PDF with none. """ bytes: int @@ -91,6 +95,7 @@ class Facts: interlaced: bool = False tile: tuple[int, int] | None = None subsampling: str | None = None + features: tuple[str, ...] = () @dataclass(frozen=True) @@ -216,7 +221,15 @@ def _wrong_format(fmt: str | None, claimed: str | None, policy: Policy) -> str: def _facts(path: Path, fmt: str, f: headers.Reader, size: int, policy: Policy) -> Facts: if fmt == "pdf": info = read_pdf(path, policy) - return Facts(size, info.width, info.height, info.pages, info.max_pixels, info.encrypted) + return Facts( + size, + info.width, + info.height, + info.pages, + info.max_pixels, + info.encrypted, + features=info.features, + ) header = headers.READERS[fmt](f, size, policy.max_pages) return Facts( size, @@ -250,6 +263,12 @@ def _against_limits(facts: Facts, policy: Policy, fmt: str) -> list[str]: 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") + refused_features = [name for name in facts.features if name not in policy.pdf_features] + if refused_features: + found = _listed([_FEATURE_WORDS[name] for name in refused_features]) + allowed = [_FEATURE_WORDS[name] for name in PDF_FEATURES if name in policy.pdf_features] + permits = _listed(allowed) if allowed else "none of the features a PDF can carry" + reasons.append(f"a PDF with {found}; the policy allows {permits}") 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" @@ -285,6 +304,14 @@ def _against_limits(facts: Facts, policy: Policy, fmt: str) -> list[str]: return reasons +_FEATURE_WORDS = { + "javascript": "JavaScript", + "forms": "a form", + "attachments": "attached files", + "launch": "a launch action", +} + + def _listed(names: list[str]) -> str: if len(names) < 2: return "".join(names) diff --git a/src/sillybos/cli.py b/src/sillybos/cli.py index 90736c9..d339fee 100644 --- a/src/sillybos/cli.py +++ b/src/sillybos/cli.py @@ -53,6 +53,8 @@ def _policy(args: argparse.Namespace) -> Policy: changes["tiff_photometrics"] = frozenset(args.tiff_photometrics.split(",")) if args.tiff_subsamplings: changes["tiff_subsamplings"] = frozenset(args.tiff_subsamplings.split(",")) + if args.pdf_features: + changes["pdf_features"] = frozenset(args.pdf_features.split(",")) if args.any_name: changes["name_must_match"] = False return dataclasses.replace(base, **changes) if changes else base @@ -134,6 +136,14 @@ def build_parser() -> argparse.ArgumentParser: "(default: none,ccitt,lzw,jpeg,deflate,packbits)" ), ) + parser.add_argument( + "--pdf-features", + metavar="LIST", + help=( + "comma-separated PDF features to allow, from " + "javascript,forms,attachments,launch (default: none)" + ), + ) parser.add_argument( "--any-name", action="store_true", diff --git a/src/sillybos/pdf.py b/src/sillybos/pdf.py index 0713b60..c462f99 100644 --- a/src/sillybos/pdf.py +++ b/src/sillybos/pdf.py @@ -1,4 +1,4 @@ -"""Page count and page sizes of a PDF, from poppler's `pdfinfo`. +"""Page count, page sizes and the features of a PDF, from poppler's `pdfinfo` and `pdfdetach`. A PDF's structure cannot be read from a fixed header the way an image's can: the page count lives in an object tree that may be compressed, and finding @@ -8,10 +8,17 @@ separate process with a time limit. A hang or a crash in `pdfinfo` is then one file's refusal, not the caller's. -`pdfinfo` comes with poppler (`brew install poppler`, `apt install -poppler-utils`), which anything that renders PDFs in Python already needs. -Without it, a PDF cannot be checked, and [PdfInfoMissing][sillybos.pdf.PdfInfoMissing] says so; -that is a configuration error, not a verdict on the file. +The same report says whether the file carries JavaScript or a form, and +`pdfdetach -list`, from the same package, whether it carries attached files. +A launch action, which tells the viewer to run a program, is reported by no +poppler tool, so it is found by its name in the file, the way `pdfid` finds +it: a bounded scan for the bytes, with the `#xx` escapes a name may be +written with undone, and no parsing. + +`pdfinfo` and `pdfdetach` come with poppler (`brew install poppler`, `apt +install poppler-utils`), which anything that renders PDFs in Python already +needs. Without them, a PDF cannot be checked, and [PdfInfoMissing][sillybos.pdf.PdfInfoMissing] +says so; that is a configuration error, not a verdict on the file. """ from __future__ import annotations @@ -28,14 +35,37 @@ _PAGES = re.compile(r"^Pages:\s+(\d+)\s*$", re.MULTILINE) _ENCRYPTED = re.compile(r"^Encrypted:\s+yes", re.MULTILINE) _PAGE_SIZE = re.compile(r"^Page(?:\s+(\d+))? size:\s+([\d.]+) x ([\d.]+) pts", re.MULTILINE) +_JAVASCRIPT = re.compile(r"^JavaScript:\s+yes", re.MULTILINE) +_FORM = re.compile(r"^Form:\s+(\S+)", re.MULTILINE) +_ATTACHMENTS = re.compile(r"^(\d+) embedded files?", re.MULTILINE) + + +def _name_pattern(name: str) -> re.Pattern[bytes]: + """A pattern for the PDF name `/name`, however its letters are escaped. + + A name in a PDF may write any character as `#` and two hex digits, so + `/Launch` may appear as `/L#61unch`. The pattern matches each letter + either way, and requires a delimiter after the name so that `/Launcher` + is not `/Launch`. + """ + letters = "".join( + f"(?:{re.escape(c)}|#{ord(c):02x}|#{ord(c):02X})" if c.isalpha() else re.escape(c) + for c in name + ) + return re.compile(rf"/{letters}(?![A-Za-z0-9#])".encode()) + + +_LAUNCH = _name_pattern("Launch") +_SCAN_CHUNK = 1024 * 1024 +_SCAN_OVERLAP = 32 # longer than the longest escaped spelling of the name class PdfInfoMissing(RuntimeError): - """`pdfinfo` is not on the PATH, so no PDF can be checked.""" + """A poppler tool (`pdfinfo`, `pdfdetach`) is not on the PATH, so no PDF can be checked.""" - def __init__(self) -> None: + def __init__(self, tool: str = "pdfinfo") -> None: super().__init__( - "pdfinfo (from poppler) is needed to check a PDF and is not on the PATH: " + f"{tool} (from poppler) is needed to check a PDF and is not on the PATH: " "`brew install poppler` on macOS, `apt install poppler-utils` on Debian" ) @@ -52,6 +82,9 @@ class PdfHeader: max_pixels: The most pixels any page would render to. `None` when the page count was over the limit and the sizes were not asked for. + features: Which of [sillybos.PDF_FEATURES][] the file carries, in + that order. Attached files and launch actions are only looked + for when the page count is within the limit. """ pages: int @@ -59,12 +92,17 @@ class PdfHeader: width: int height: int max_pixels: int | None + features: tuple[str, ...] = () def _pdfinfo(args: list[str], path: Path, timeout: float) -> str: - executable = shutil.which("pdfinfo") + return _tool("pdfinfo", args, path, timeout) + + +def _tool(tool: str, args: list[str], path: Path, timeout: float) -> str: + executable = shutil.which(tool) if executable is None: - raise PdfInfoMissing + raise PdfInfoMissing(tool) try: # The arguments are a fixed list plus the path being checked: nothing # here is a shell, and the file's contents go to pdfinfo's parser, @@ -78,28 +116,61 @@ def _pdfinfo(args: list[str], path: Path, timeout: float) -> str: check=False, ) except subprocess.TimeoutExpired: - raise HeaderError(f"pdfinfo did not finish within {timeout:g} seconds") from None + raise HeaderError(f"{tool} did not finish within {timeout:g} seconds") from None if done.returncode != 0: detail = done.stderr.strip().splitlines() reason = detail[-1] if detail else f"exit status {done.returncode}" - raise HeaderError(f"pdfinfo could not read it ({reason})") + raise HeaderError(f"{tool} could not read it ({reason})") return done.stdout +def _has_launch_action(path: Path) -> bool: + """Whether the bytes of the file spell the name `/Launch` anywhere. + + Read a chunk at a time with a short overlap, so a name across a chunk + boundary is still seen and the memory used does not grow with the file. + """ + tail = b"" + with path.open("rb") as f: + while chunk := f.read(_SCAN_CHUNK): + if _LAUNCH.search(tail + chunk): + return True + tail = chunk[-_SCAN_OVERLAP:] + return False + + +def _features(summary: str, path: Path, policy: Policy, *, within_limit: bool) -> tuple[str, ...]: + found = [] + if _JAVASCRIPT.search(summary): + found.append("javascript") + form = _FORM.search(summary) + if form is not None and form.group(1).lower() != "none": + found.append("forms") + if within_limit: + listing = _tool("pdfdetach", ["-list"], path, policy.pdfinfo_timeout) + count = _ATTACHMENTS.search(listing) + if count is not None and int(count.group(1)) > 0: + found.append("attachments") + if _has_launch_action(path): + found.append("launch") + return tuple(found) + + def _pixels(points: str, dpi: int) -> float: return float(points) / 72 * dpi def pdf(path: Path, policy: Policy) -> PdfHeader: - """Ask `pdfinfo` for the page count, encryption and, within the limit, every page's size. + """Ask poppler for the page count, encryption, features and, within the limit, every page's size. - Page sizes are only asked for when the count is within `policy.max_pages`: - a listing of a hundred thousand pages is work the file should not be able - to cause. + Page sizes, attached files and the scan for a launch action only happen + when the count is within `policy.max_pages`: a listing of a hundred + thousand pages is work the file should not be able to cause, and a file + over the limit is refused whatever else it carries. Raises: - HeaderError: If `pdfinfo` refuses the file or runs out of time. - PdfInfoMissing: If `pdfinfo` is not installed. + HeaderError: If `pdfinfo` or `pdfdetach` refuses the file or runs out of time. + PdfInfoMissing: If `pdfinfo` or `pdfdetach` is not installed. """ summary = _pdfinfo([], path, policy.pdfinfo_timeout) pages_match = _PAGES.search(summary) @@ -115,7 +186,8 @@ def pdf(path: Path, policy: Policy) -> PdfHeader: width = round(_pixels(first.group(2), policy.render_dpi)) height = round(_pixels(first.group(3), policy.render_dpi)) if pages > policy.max_pages: - return PdfHeader(pages, encrypted, width, height, None) + features = _features(summary, path, policy, within_limit=False) + return PdfHeader(pages, encrypted, width, height, None, features) listing = _pdfinfo(["-f", "1", "-l", str(pages)], path, policy.pdfinfo_timeout) sizes = [ _pixels(w, policy.render_dpi) * _pixels(h, policy.render_dpi) @@ -123,4 +195,5 @@ def pdf(path: Path, policy: Policy) -> PdfHeader: ] if not sizes: raise HeaderError("pdfinfo reported no page sizes") - return PdfHeader(pages, encrypted, width, height, round(max(sizes))) + features = _features(summary, path, policy, within_limit=True) + return PdfHeader(pages, encrypted, width, height, round(max(sizes)), features) diff --git a/src/sillybos/policy.py b/src/sillybos/policy.py index 6412ad3..c397375 100644 --- a/src/sillybos/policy.py +++ b/src/sillybos/policy.py @@ -83,6 +83,12 @@ """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.""" +PDF_FEATURES: tuple[str, ...] = ("javascript", "forms", "attachments", "launch") +"""Everything a PDF can carry that makes a viewer do something other than +draw the page: JavaScript, an interactive form, attached (embedded) files, and +a launch action that runs a program. A scanned book has none of them, so the +default policy refuses them all; a policy names the ones it will pass.""" + MIB = 1024 * 1024 @@ -160,6 +166,15 @@ class Policy: 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. + pdf_features: Which of [PDF_FEATURES][sillybos.PDF_FEATURES] a PDF may carry: + JavaScript, a form, attached files, a launch action. Each is a + way for a document to make the viewer act rather than draw, and + a scanned book has none, so the default allows none. JavaScript + and forms are read from `pdfinfo`'s report and attached files + from `pdfdetach`'s, both of which see inside compressed object + streams; a launch action is found by its name in the file, + since no poppler tool reports one, so an action hidden in a + compressed stream is not seen. pdfinfo_timeout: Seconds to give `pdfinfo` before giving up on a PDF, which is then refused. A crafted file can make a parser loop; a limit turns that into one file's failure. @@ -189,6 +204,7 @@ class Policy: default_factory=lambda: frozenset({"none", "ccitt", "lzw", "jpeg", "deflate", "packbits"}) ) allow_encrypted_pdf: bool = False + pdf_features: frozenset[str] = frozenset() pdfinfo_timeout: float = 30.0 def __post_init__(self) -> None: @@ -230,6 +246,11 @@ def __post_init__(self) -> None: ) if not chosen: raise ValueError(f"a policy must allow at least one {what}") + unknown = set(self.pdf_features) - set(PDF_FEATURES) + if unknown: + raise ValueError( + f"unknown PDF feature(s) {sorted(unknown)}; the features are {', '.join(PDF_FEATURES)}" + ) 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") diff --git a/tests/corpus.py b/tests/corpus.py index 0c7e1f3..5de2422 100644 --- a/tests/corpus.py +++ b/tests/corpus.py @@ -317,15 +317,26 @@ def pdf( height_pts: float = 842, *, sizes: list[tuple[float, float]] | None = None, + catalog: str = "", + objects: list[bytes] | None = None, ) -> bytes: - """A minimal but well-formed PDF: ``pages`` empty pages of the given size, with an xref.""" + """A minimal but well-formed PDF: ``pages`` empty pages of the given size, with an xref. + + ``catalog`` is appended inside the catalogue dictionary and ``objects`` + are added after the pages, numbered from ``pages + 3``, so a test can + give the document a feature a scan never has (see :func:`pdf_with`). + """ per_page = sizes or [(width_pts, height_pts)] * pages - objects: list[bytes] = [] + extra = objects or [] kids = " ".join(f"{3 + i} 0 R" for i in range(pages)) - objects.append(b"<< /Type /Catalog /Pages 2 0 R >>") - objects.append(f"<< /Type /Pages /Kids [{kids}] /Count {pages} >>".encode()) + parts: list[bytes] = [ + f"<< /Type /Catalog /Pages 2 0 R {catalog} >>".encode(), + f"<< /Type /Pages /Kids [{kids}] /Count {pages} >>".encode(), + ] for w, h in per_page: - objects.append(f"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 {w:g} {h:g}] >>".encode()) + parts.append(f"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 {w:g} {h:g}] >>".encode()) + parts.extend(extra) + objects = parts out = bytearray(b"%PDF-1.4\n%\xe2\xe3\xcf\xd3\n") offsets = [] for number, body in enumerate(objects, start=1): @@ -345,3 +356,64 @@ def pdf( def write(path: Path, data: bytes) -> Path: path.write_bytes(data) return path + + +def pdf_with(feature: str, pages: int = 1) -> bytes: + """A one-page PDF carrying one of the features a scanned book never has. + + ``javascript`` and ``launch`` are open-document actions; ``escaped-javascript`` + is the same JavaScript action with its name written in ``#xx`` escapes; + ``escaped-launch`` likewise; ``forms`` is an AcroForm with one text field; + ``attachments`` is one embedded file. + """ + first = pages + 3 + if feature == "javascript": + return pdf( + pages, + catalog=f"/OpenAction {first} 0 R", + objects=[ + b"<< /Type /Action /S /JavaScript /JS (app.alert('hello');) >>", + ], + ) + if feature == "escaped-javascript": + return pdf( + pages, + catalog=f"/OpenAction {first} 0 R", + objects=[ + b"<< /Type /Action /S /#4Aava#53cript /JS (app.alert('hello');) >>", + ], + ) + if feature == "launch": + return pdf( + pages, + catalog=f"/OpenAction {first} 0 R", + objects=[ + b"<< /Type /Action /S /Launch /F (cmd.exe) >>", + ], + ) + if feature == "escaped-launch": + return pdf( + pages, + catalog=f"/OpenAction {first} 0 R", + objects=[ + b"<< /Type /Action /S /L#61unc#68 /F (cmd.exe) >>", + ], + ) + if feature == "forms": + return pdf( + pages, + catalog=f"/AcroForm << /Fields [{first} 0 R] >>", + objects=[ + b"<< /FT /Tx /T (name) /Rect [0 0 10 10] /Subtype /Widget /Type /Annot >>", + ], + ) + if feature == "attachments": + return pdf( + pages, + catalog=f"/Names << /EmbeddedFiles << /Names [(payload.exe) {first} 0 R] >> >>", + objects=[ + f"<< /Type /Filespec /F (payload.exe) /EF << /F {first + 1} 0 R >> >>".encode(), + b"<< /Type /EmbeddedFile /Length 5 >>\nstream\nhello\nendstream", + ], + ) + raise ValueError(feature) diff --git a/tests/test_check.py b/tests/test_check.py index 9b00d2c..b0f9272 100644 --- a/tests/test_check.py +++ b/tests/test_check.py @@ -313,6 +313,50 @@ def test_strict_is_shorter(self, tmp_path: Path) -> None: verdict = check(corpus.write(tmp_path / "long.pdf", corpus.pdf(150)), STRICT) assert verdict.reasons == ("150 pages; the limit is 100",) + def test_a_plain_pdf_carries_no_features(self, tmp_path: Path) -> None: + verdict = check(corpus.write(tmp_path / "plain.pdf", corpus.pdf(1))) + assert verdict.ok and verdict.facts is not None and verdict.facts.features == () + + @pytest.mark.parametrize( + ("feature", "found", "words"), + [ + ("javascript", "javascript", "JavaScript"), + ("escaped-javascript", "javascript", "JavaScript"), + ("forms", "forms", "a form"), + ("attachments", "attachments", "attached files"), + ("launch", "launch", "a launch action"), + ("escaped-launch", "launch", "a launch action"), + ], + ) + def test_a_pdf_with_a_feature_a_scan_never_has( + self, tmp_path: Path, feature: str, found: str, words: str + ) -> None: + path = corpus.write(tmp_path / "doc.pdf", corpus.pdf_with(feature)) + + verdict = check(path) + + assert verdict.reasons == ( + f"a PDF with {words}; the policy allows none of the features a PDF can carry", + ) + assert verdict.facts is not None and verdict.facts.features == (found,) + assert check(path, Policy(pdf_features=frozenset({found}))).ok + + def test_the_policy_names_what_it_allows(self, tmp_path: Path) -> None: + path = corpus.write(tmp_path / "form.pdf", corpus.pdf_with("forms")) + verdict = check(path, Policy(pdf_features=frozenset({"javascript", "attachments"}))) + assert verdict.reasons == ( + "a PDF with a form; the policy allows JavaScript and attached files", + ) + + def test_a_long_pdf_still_reports_what_the_summary_shows(self, tmp_path: Path) -> None: + """Over the page limit nothing more is asked of the file, but what pdfinfo already said is kept.""" + path = corpus.write(tmp_path / "long.pdf", corpus.pdf_with("javascript", pages=3)) + verdict = check(path, Policy(max_pages=2)) + assert verdict.reasons == ( + "3 pages; the limit is 2", + "a PDF with JavaScript; the policy allows none of the features a PDF can carry", + ) + class TestPolicy: def test_presets(self) -> None: @@ -338,6 +382,7 @@ def test_presets(self) -> None: ({"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"), + ({"pdf_features": frozenset({"macros"})}, "unknown PDF feature"), ], ) def test_refuses_an_impossible_policy(self, changes: dict[str, object], reason: str) -> None: diff --git a/tests/test_cli.py b/tests/test_cli.py index 2892096..a71bf33 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -1,6 +1,7 @@ from __future__ import annotations import json +import shutil from pathlib import Path import pytest @@ -93,3 +94,11 @@ def test_version() -> None: with pytest.raises(SystemExit) as stop: main(["--version"]) assert stop.value.code == 0 + + +@pytest.mark.skipif(shutil.which("pdfinfo") is None, reason="pdfinfo (poppler)") +def test_pdf_features_can_be_allowed(tmp_path: Path) -> None: + scripted = corpus.write(tmp_path / "scripted.pdf", corpus.pdf_with("javascript")) + assert main([str(scripted)]) == 1 + assert main(["--pdf-features", "javascript", str(scripted)]) == 0 + assert main(["--pdf-features", "forms", str(scripted)]) == 1 diff --git a/tests/test_pdf.py b/tests/test_pdf.py index d41f5d7..34d61c3 100644 --- a/tests/test_pdf.py +++ b/tests/test_pdf.py @@ -84,3 +84,44 @@ def test_no_page_sizes_in_the_listing(tmp_path: Path, monkeypatch: pytest.Monkey ) with pytest.raises(HeaderError, match="no page sizes"): pdf_module.pdf(tmp_path / "a.pdf", Policy()) + + +def test_a_missing_pdfdetach_is_a_configuration_error( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + real_which = shutil.which + monkeypatch.setattr( + shutil, "which", lambda name: None if name == "pdfdetach" else real_which(name) + ) + if real_which("pdfinfo") is None: + pytest.skip("pdfinfo (poppler)") + with pytest.raises(PdfInfoMissing, match="pdfdetach"): + check(corpus.write(tmp_path / "a.pdf", corpus.pdf(1))) + + +@pytest.mark.parametrize( + ("escaped", "spelling"), + [ + (b"/Launch", True), + (b"/L#61unch", True), + (b"/#4c#61#75#6e#63#68", True), + (b"/Launcher", False), + (b"/Launch2", False), + (b"Launch", False), + ], +) +def test_the_launch_scan_reads_names_however_they_are_escaped( + tmp_path: Path, escaped: bytes, spelling: bool +) -> None: + path = tmp_path / "a.pdf" + path.write_bytes(b"%PDF-1.4\n1 0 obj << /S " + escaped + b" >> endobj\n") + assert pdf_module._has_launch_action(path) is spelling + + +def test_the_launch_scan_sees_a_name_across_a_chunk_boundary( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setattr(pdf_module, "_SCAN_CHUNK", 16) + path = tmp_path / "a.pdf" + path.write_bytes(b"%PDF-1.4\n<< /S /Launch /F (x) >>") # "/Launch" straddles byte 16 + assert pdf_module._has_launch_action(path) From 21fd7899e1203445c03c4080ebb295ffb008b92e Mon Sep 17 00:00:00 2001 From: Stephen Masters Date: Sun, 1 Nov 2026 21:38:48 +0000 Subject: [PATCH 2/2] fix(pdf): look for JavaScript by name too, since poppler before 26 does not report an open action's script CI's poppler, 24.02, says `JavaScript: no` for a script attached to the document's open action; 26.04 says yes. The report is still read, and the same bounded scan that finds a launch action now finds the names /JavaScript and /JS as well. The corpus gains a document-level script, which every poppler reports, and a test fakes the older report. Co-authored-by: Yvette Mankerian Co-Authored-By: Claude Fable 5.1 --- README.md | 8 ++++---- src/sillybos/pdf.py | 30 +++++++++++++++++++++++------- src/sillybos/policy.py | 9 +++++---- tests/corpus.py | 11 +++++++++-- tests/test_check.py | 3 ++- tests/test_pdf.py | 17 +++++++++++++++++ 6 files changed, 60 insertions(+), 18 deletions(-) diff --git a/README.md b/README.md index 75233ee..13f0104 100644 --- a/README.md +++ b/README.md @@ -109,7 +109,7 @@ check(path, Policy(formats={"tiff", "pdf"}, max_pages=50)) | `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 | -| `pdf_features` | none | none | Which of JavaScript, forms, attached files and launch actions a PDF may carry. Each makes a viewer do something other than draw the page, and a scanned book has none. JavaScript and forms are read from `pdfinfo`'s report and attached files from `pdfdetach`'s; a launch action is found by its name in the file, since no poppler tool reports one | +| `pdf_features` | none | none | Which of JavaScript, forms, attached files and launch actions a PDF may carry. Each makes a viewer do something other than draw the page, and a scanned book has none. Forms are read from `pdfinfo`'s report and attached files from `pdfdetach`'s; a launch action is found by its name in the file, since no poppler tool reports one; JavaScript is looked for both ways | | `pdfinfo_timeout` | 30 s | 30 s | How long `pdfinfo` may take before the file is refused | The defaults were set from a real corpus of archival scans (largest page 39 @@ -186,9 +186,9 @@ prints one object per line for a pipeline; `-q` prints only refusals. `pdfinfo` reports the page count, whether it is encrypted, whether it carries JavaScript or a form and, if the count is within the limit, every page's size; `pdfdetach` reports attached files; and a bounded - scan of the bytes finds the name of a launch action, with the `#xx` - escapes a name may hide behind undone, since no poppler tool reports - one. + scan of the bytes finds the name of a launch action, and of JavaScript + that an older poppler does not report, with the `#xx` escapes a name + may hide behind undone. 5. **The limits**, against what the header said. ## What it does not do diff --git a/src/sillybos/pdf.py b/src/sillybos/pdf.py index c462f99..ca91117 100644 --- a/src/sillybos/pdf.py +++ b/src/sillybos/pdf.py @@ -13,7 +13,9 @@ A launch action, which tells the viewer to run a program, is reported by no poppler tool, so it is found by its name in the file, the way `pdfid` finds it: a bounded scan for the bytes, with the `#xx` escapes a name may be -written with undone, and no parsing. +written with undone, and no parsing. JavaScript is looked for both ways, +because poppler before 26 reports only document-level scripts and not one +attached to an open-document action. `pdfinfo` and `pdfdetach` come with poppler (`brew install poppler`, `apt install poppler-utils`), which anything that renders PDFs in Python already @@ -56,6 +58,7 @@ def _name_pattern(name: str) -> re.Pattern[bytes]: _LAUNCH = _name_pattern("Launch") +_JAVASCRIPT_NAMES = (_name_pattern("JavaScript"), _name_pattern("JS")) _SCAN_CHUNK = 1024 * 1024 _SCAN_OVERLAP = 32 # longer than the longest escaped spelling of the name @@ -124,19 +127,29 @@ def _tool(tool: str, args: list[str], path: Path, timeout: float) -> str: return done.stdout -def _has_launch_action(path: Path) -> bool: - """Whether the bytes of the file spell the name `/Launch` anywhere. +def _names_in(path: Path, *patterns: re.Pattern[bytes]) -> list[bool]: + """Whether the bytes of the file spell each name anywhere, one answer per pattern. Read a chunk at a time with a short overlap, so a name across a chunk boundary is still seen and the memory used does not grow with the file. """ + found = [False] * len(patterns) tail = b"" with path.open("rb") as f: while chunk := f.read(_SCAN_CHUNK): - if _LAUNCH.search(tail + chunk): - return True + window = tail + chunk + for i, pattern in enumerate(patterns): + if not found[i] and pattern.search(window): + found[i] = True + if all(found): + break tail = chunk[-_SCAN_OVERLAP:] - return False + return found + + +def _has_launch_action(path: Path) -> bool: + """Whether the bytes of the file spell the name `/Launch` anywhere.""" + return _names_in(path, _LAUNCH)[0] def _features(summary: str, path: Path, policy: Policy, *, within_limit: bool) -> tuple[str, ...]: @@ -151,7 +164,10 @@ def _features(summary: str, path: Path, policy: Policy, *, within_limit: bool) - count = _ATTACHMENTS.search(listing) if count is not None and int(count.group(1)) > 0: found.append("attachments") - if _has_launch_action(path): + scripted, script, launch = _names_in(path, *_JAVASCRIPT_NAMES, _LAUNCH) + if (scripted or script) and "javascript" not in found: + found.insert(0, "javascript") + if launch: found.append("launch") return tuple(found) diff --git a/src/sillybos/policy.py b/src/sillybos/policy.py index c397375..d23dc9e 100644 --- a/src/sillybos/policy.py +++ b/src/sillybos/policy.py @@ -169,12 +169,13 @@ class Policy: pdf_features: Which of [PDF_FEATURES][sillybos.PDF_FEATURES] a PDF may carry: JavaScript, a form, attached files, a launch action. Each is a way for a document to make the viewer act rather than draw, and - a scanned book has none, so the default allows none. JavaScript - and forms are read from `pdfinfo`'s report and attached files - from `pdfdetach`'s, both of which see inside compressed object + a scanned book has none, so the default allows none. Forms are + read from `pdfinfo`'s report and attached files from + `pdfdetach`'s, both of which see inside compressed object streams; a launch action is found by its name in the file, since no poppler tool reports one, so an action hidden in a - compressed stream is not seen. + compressed stream is not seen; JavaScript is looked for both + ways. pdfinfo_timeout: Seconds to give `pdfinfo` before giving up on a PDF, which is then refused. A crafted file can make a parser loop; a limit turns that into one file's failure. diff --git a/tests/corpus.py b/tests/corpus.py index 5de2422..099125e 100644 --- a/tests/corpus.py +++ b/tests/corpus.py @@ -363,10 +363,17 @@ def pdf_with(feature: str, pages: int = 1) -> bytes: ``javascript`` and ``launch`` are open-document actions; ``escaped-javascript`` is the same JavaScript action with its name written in ``#xx`` escapes; - ``escaped-launch`` likewise; ``forms`` is an AcroForm with one text field; - ``attachments`` is one embedded file. + ``escaped-launch`` likewise; ``document-javascript`` is a script in the + document's name tree, which is what every poppler reports; ``forms`` is an + AcroForm with one text field; ``attachments`` is one embedded file. """ first = pages + 3 + if feature == "document-javascript": + return pdf( + pages, + catalog=f"/Names << /JavaScript << /Names [(init) {first} 0 R] >> >>", + objects=[b"<< /S /JavaScript /JS (app.alert('hello');) >>"], + ) if feature == "javascript": return pdf( pages, diff --git a/tests/test_check.py b/tests/test_check.py index b0f9272..673b634 100644 --- a/tests/test_check.py +++ b/tests/test_check.py @@ -321,6 +321,7 @@ def test_a_plain_pdf_carries_no_features(self, tmp_path: Path) -> None: ("feature", "found", "words"), [ ("javascript", "javascript", "JavaScript"), + ("document-javascript", "javascript", "JavaScript"), ("escaped-javascript", "javascript", "JavaScript"), ("forms", "forms", "a form"), ("attachments", "attachments", "attached files"), @@ -350,7 +351,7 @@ def test_the_policy_names_what_it_allows(self, tmp_path: Path) -> None: def test_a_long_pdf_still_reports_what_the_summary_shows(self, tmp_path: Path) -> None: """Over the page limit nothing more is asked of the file, but what pdfinfo already said is kept.""" - path = corpus.write(tmp_path / "long.pdf", corpus.pdf_with("javascript", pages=3)) + path = corpus.write(tmp_path / "long.pdf", corpus.pdf_with("document-javascript", pages=3)) verdict = check(path, Policy(max_pages=2)) assert verdict.reasons == ( "3 pages; the limit is 2", diff --git a/tests/test_pdf.py b/tests/test_pdf.py index 34d61c3..956314a 100644 --- a/tests/test_pdf.py +++ b/tests/test_pdf.py @@ -125,3 +125,20 @@ def test_the_launch_scan_sees_a_name_across_a_chunk_boundary( path = tmp_path / "a.pdf" path.write_bytes(b"%PDF-1.4\n<< /S /Launch /F (x) >>") # "/Launch" straddles byte 16 assert pdf_module._has_launch_action(path) + + +@needs_pdfinfo +def test_javascript_is_found_by_name_when_pdfinfo_does_not_report_it( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """poppler before 26 says `JavaScript: no` for a script on an open action; the name scan still sees it.""" + real = pdf_module._pdfinfo + + def older(args: list[str], path: Path, timeout: float) -> str: + return re.sub( + r"^JavaScript:\s+yes", "JavaScript: no", real(args, path, timeout), flags=re.M + ) + + monkeypatch.setattr(pdf_module, "_pdfinfo", older) + verdict = check(corpus.write(tmp_path / "scripted.pdf", corpus.pdf_with("javascript"))) + assert verdict.facts is not None and verdict.facts.features == ("javascript",)