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
7 changes: 5 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -202,7 +202,10 @@ prints one object per line for a pipeline; `-q` prints only refusals.
scan of the bytes finds the name of a launch action, of JavaScript
that an older poppler does not report, and of the filters its images
are coded with (DCT, JPX, JBIG2, CCITT), with the `#xx` escapes a name
may hide behind undone.
may hide behind undone. A script's own key, `/JS`, is three bytes that
compressed image data spells by chance, so it counts only beside the
name of a rendition action, the one action besides a JavaScript action
that may carry a script.
5. **The limits**, against what the header said.

## What it does not do
Expand Down Expand Up @@ -257,7 +260,7 @@ TIFF whose tag points past the end of the file, a lossless JPEG, a JPEG with a s
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 TIFF, a JPEG and a PNG whose tags all claim the same bytes, a PDF of a thousand pages, a PDF with a page 200
inches wide. Nothing hostile is
inches wide, a PDF whose script sits inside another object's stream. 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
33 changes: 28 additions & 5 deletions src/sillybos/pdf.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,25 @@
because poppler before 26 reports only document-level scripts and not one
attached to an open-document action.

The name that says JavaScript is `/JavaScript`: it is the type of the
action that carries a script, and the key of the document's own table of
scripts. The script itself sits under the key `/JS`, and that name alone
says nothing, because it is three bytes long and compressed image data
spells any three bytes by chance: about once in 24 MB of random bytes,
and about once in 2 MB of the ASCII85 text that ReportLab writes its
streams in. Taking `/JS` alone for a script refused 27 of 689 ordinary
PDFs, scanned books and newspapers among them, none of which `pdfinfo`
found a script in. So `/JS` counts only in a file that also spells
`/Rendition`, the one other type of action that may carry a script, and
whose scripts `/JavaScript` would not find.

Passing over the bytes of streams would not have been a fix. A reader
finds an object where the cross-reference table says it is, and the table
may point into the middle of another object's stream: poppler reads an
action placed there without complaint. A scan that skipped streams would
then miss what the viewer runs, so every byte of the file is searched,
and it is the name searched for that has to be one chance does not spell.

The codec of each image is found the same way, by the name of its filter
(`/JBIG2Decode`, `/JPXDecode`, `/DCTDecode`, `/CCITTFaxDecode`). A stream's
dictionary cannot be hidden inside a compressed object stream, so the name
Expand Down Expand Up @@ -66,7 +85,9 @@ def _name_pattern(name: str) -> re.Pattern[bytes]:


_LAUNCH = _name_pattern("Launch")
_JAVASCRIPT_NAMES = (_name_pattern("JavaScript"), _name_pattern("JS"))
_JAVASCRIPT_NAME = _name_pattern("JavaScript")
_SCRIPT_KEY = _name_pattern("JS")
_RENDITION = _name_pattern("Rendition")


def _any_name(*names: str) -> re.Pattern[bytes]:
Expand Down Expand Up @@ -197,13 +218,15 @@ def _contents(
count = _ATTACHMENTS.search(listing)
if count is not None and int(count.group(1)) > 0:
found.append("attachments")
hits = _names_in(path, *_JAVASCRIPT_NAMES, _LAUNCH, *(p for _, p in _CODEC_NAMES))
scripted, script, launch = hits[:3]
if (scripted or script) and "javascript" not in found:
named, key, rendition, launch, *coded = _names_in(
path, _JAVASCRIPT_NAME, _SCRIPT_KEY, _RENDITION, _LAUNCH, *(p for _, p in _CODEC_NAMES)
)
# `/JS` alone is three bytes that compressed data spells by chance; see the module's notes.
if (named or (key and rendition)) and "javascript" not in found:
found.insert(0, "javascript")
if launch:
found.append("launch")
codecs = [name for (name, _), hit in zip(_CODEC_NAMES, hits[3:], strict=True) if hit]
codecs = [name for (name, _), hit in zip(_CODEC_NAMES, coded, strict=True) if hit]
return tuple(found), tuple(codecs)


Expand Down
37 changes: 34 additions & 3 deletions tests/corpus.py
Original file line number Diff line number Diff line change
Expand Up @@ -518,17 +518,27 @@ 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; ``document-javascript`` is a script in the
document's name tree, which is what every poppler reports; ``forms`` is an
document's name tree, which is what every poppler reports;
``rendition-javascript`` is a script on a rendition action, the one other
action that may carry one, which never spells ``/JavaScript``;
``javascript-in-a-stream`` is the open-document script again, with its
object written inside another object's stream and the cross-reference
table pointing into it, which poppler reads all the same; ``forms`` is an
AcroForm with one text field; ``attachments`` is one embedded file.

``jpeg``, ``jpx``, ``jbig2`` and ``ccitt`` draw one image coded with that
filter on the first page, its stream sixteen zero bytes that no decoder
is asked to read; ``escaped-jbig2`` is the JBIG2 one with the filter's
name written in ``#xx`` escapes.
name written in ``#xx`` escapes. ``script-key-by-chance`` is the JPEG one
with the bytes ``/JS(`` in its image data, as megabytes of compressed
pixels spell them sooner or later: a scan, with nothing in it to refuse.
"""
first = pages + 3
if feature in IMAGE_FILTERS:
if feature == "script-key-by-chance":
feature, data = "jpeg", b"\x00" * 6 + b"/JS(" + b"\x00" * 6
else:
data = b"\x00" * 16
if feature in IMAGE_FILTERS:
image = (
"<< /Type /XObject /Subtype /Image /Width 8 /Height 8 /ColorSpace /DeviceGray "
f"/BitsPerComponent 1 /Filter /{IMAGE_FILTERS[feature]} /Length {len(data)} >>\nstream\n"
Expand All @@ -555,6 +565,27 @@ def pdf_with(feature: str, pages: int = 1) -> bytes:
b"<< /Type /Action /S /JavaScript /JS (app.alert('hello');) >>",
],
)
if feature == "rendition-javascript":
return pdf(
pages,
catalog=f"/OpenAction {first} 0 R",
objects=[
b"<< /Type /Action /S /Rendition /JS (app.alert('hello');) >>",
],
)
if feature == "javascript-in-a-stream":
inner = (
f"{first + 1} 0 obj\n<< /Type /Action /S /JavaScript /JS (app.alert('hello');) >>"
"\nendobj\n"
).encode()
holder = f"<< /Length {len(inner)} >>\nstream\n".encode() + inner + b"endstream"
# The second object is a placeholder, so that the table has an entry
# to repoint at the action inside the first one's stream.
built = pdf(pages, catalog=f"/OpenAction {first + 1} 0 R", objects=[holder, b"null"])
placeholder = built.index(f"{first + 1} 0 obj\nnull".encode())
entry = f"{placeholder:010d} 00000 n".encode()
assert built.count(entry) == 1
return built.replace(entry, f"{built.index(inner):010d} 00000 n".encode())
if feature == "escaped-javascript":
return pdf(
pages,
Expand Down
12 changes: 12 additions & 0 deletions tests/test_check.py
Original file line number Diff line number Diff line change
Expand Up @@ -636,6 +636,8 @@ def test_a_jbig2_pdf_under_a_policy_that_refuses_it(self, tmp_path: Path) -> Non
("javascript", "javascript", "JavaScript"),
("document-javascript", "javascript", "JavaScript"),
("escaped-javascript", "javascript", "JavaScript"),
("rendition-javascript", "javascript", "JavaScript"),
("javascript-in-a-stream", "javascript", "JavaScript"),
("forms", "forms", "a form"),
("attachments", "attachments", "attached files"),
("launch", "launch", "a launch action"),
Expand All @@ -655,6 +657,16 @@ def test_a_pdf_with_a_feature_a_scan_never_has(
assert verdict.facts is not None and verdict.facts.features == (found,)
assert check(path, Policy(pdf_features=frozenset({found}))).ok

def test_a_scan_whose_image_data_spells_the_script_key(self, tmp_path: Path) -> None:
# `/JS` is three bytes, and compressed pixels spell them by chance:
# 27 of 689 ordinary PDFs were refused as JavaScript for it.
path = corpus.write(tmp_path / "scan.pdf", corpus.pdf_with("script-key-by-chance"))
assert b"/JS(" in path.read_bytes()
verdict = check(path)
assert verdict.ok
assert verdict.facts is not None and verdict.facts.features == ()
assert check(path, STRICT).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"})))
Expand Down
35 changes: 33 additions & 2 deletions tests/test_pdf.py
Original file line number Diff line number Diff line change
Expand Up @@ -127,9 +127,40 @@ def test_the_launch_scan_sees_a_name_across_a_chunk_boundary(
assert pdf_module._has_launch_action(path)


@pytest.mark.parametrize(
("body", "scripted"),
[
(b"<< /S /JavaScript /JS (x) >>", True),
(b"<< /Names << /JavaScript 4 0 R >> >>", True),
(b"<< /S /#4aavaScript /#4a#53 (x) >>", True),
(b"<< /S /Rendition /JS (x) >>", True),
(b"<< /S /R#65ndition /J#53 (x) >>", True),
# The key with no action that could carry it: bytes, not a script.
(b"<< /Length 9 >> stream\n\x00/JS(\x9c\x00\nendstream", False),
(b"<< /Font << /JS 4 0 R >> >>", False),
# A rendition that plays its media and runs nothing.
(b"<< /S /Rendition /OP 0 /R 4 0 R >>", False),
# Other names that begin the same way.
(b"<< /Renditions 4 0 R /JS (x) >>", False),
(b"<< /S /Rendition /JSON (x) >>", False),
],
)
def test_the_script_key_counts_only_beside_an_action_that_carries_one(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, body: bytes, scripted: bool
) -> None:
monkeypatch.setattr(pdf_module, "_tool", lambda tool, args, path, timeout: "")
path = tmp_path / "a.pdf"
path.write_bytes(b"%PDF-1.4\n1 0 obj " + body + b" endobj\n")
features, _ = pdf_module._contents("", path, Policy(), within_limit=True)
assert ("javascript" in features) is scripted


@needs_pdfinfo
@pytest.mark.parametrize(
"feature", ["javascript", "rendition-javascript", "javascript-in-a-stream"]
)
def test_javascript_is_found_by_name_when_pdfinfo_does_not_report_it(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, feature: str
) -> None:
"""poppler before 26 says `JavaScript: no` for a script on an open action; the name scan still sees it."""
real = pdf_module._pdfinfo
Expand All @@ -140,5 +171,5 @@ def older(args: list[str], path: Path, timeout: float) -> str:
)

monkeypatch.setattr(pdf_module, "_pdfinfo", older)
verdict = check(corpus.write(tmp_path / "scripted.pdf", corpus.pdf_with("javascript")))
verdict = check(corpus.write(tmp_path / "scripted.pdf", corpus.pdf_with(feature)))
assert verdict.facts is not None and verdict.facts.features == ("javascript",)
Loading