Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

fix(pdf): check resource headers and align directory accounting (#7798)

LearningCircuitb777cf4c9b54
diff --git a/SECURITY.md b/SECURITY.md
index a65700ed7e..00a4d7c956 100644
--- a/SECURITY.md
+++ b/SECURITY.md
@@ -149,7 +149,7 @@ By setting this, the operator acknowledges the residual risk above. To minimise
The general HTTP fetch path (`safe_requests`, used for RAG sources and web scraping) resolves the hostname and connects to that **same** validated address: `security.dns_pinning` pins the resolved IP for the outbound connection (re-resolving and re-validating at connect time, and re-pinning at every redirect hop) so `requests`/`urllib3` cannot connect to a different address than the one the guard checked. The request keeps the original hostname, so TLS SNI and certificate verification are unchanged — only name resolution is pinned. The notification path above reuses this same shim (via `pinned_notification_send`, plus the block-private window for unpinned plugin-endpoint hosts) — but with redirect-following disabled outright rather than validated hop-by-hop, since a notification webhook has no legitimate need to follow redirects. It still does not apply to callers that hand a URL to an external client that re-resolves on its own with no in-thread `getaddrinfo` interception (LLM SDKs — see "LLM Provider URL Validation"); for those, egress restriction remains the primary defense. It also does not apply when `requests` is configured to use a forward proxy (`HTTP(S)_PROXY` / `trust_env`): `urllib3` then resolves the *proxy* host rather than the target, so target-IP selection is delegated to the proxy and the pin is a safe no-op (the pre-connection `validate_url` check still runs).
-The PDF export resource fetcher (`_SafeUrlFetcher` in `web/services/pdf_service.py`) fetches every resource the render loads (the images a report's Markdown references, and any stylesheet, font or image those or a caller-supplied stylesheet reference in turn) through WeasyPrint's urllib-based `URLFetcher`, with redirects disabled. Raw HTML in report text is escaped before rendering, as in the on-screen report view, so report text itself references resources only through Markdown image syntax. Each fetch runs inside `dns_pinning.pinned_request` nested with `dns_pinning.block_private_resolution`, both with the policy its `validate_url` call applies (public addresses only; cloud-metadata always blocked). The connection therefore goes only to an address that passed the same policy at connect time. For an ASCII host name it is pinned to the validated address. An IP-literal host is not pinned, because there is no DNS to rebind; its lookup goes through the block window like any other unpinned lookup, such as a non-ASCII host that urllib looks up in a different form from the pin key. Each such lookup is checked against that policy on the answer actually used. urllib connects on the rendering thread, which is the thread the pin and window apply to, and keeps the hostname for TLS SNI and certificate verification. The fetch is refused if the `getaddrinfo` shim is not the active resolver, and resource URLs that carry userinfo (any `@` in the authority) are refused outright, because urllib would look up the whole `user@host` authority rather than the pinned host. If `HTTP(S)_PROXY` is set, urllib connects to the proxy and the proxy resolves the target, so the forward-proxy caveat above applies to the target. The proxy's own lookup is exempted from the public-only policy by exact host and port (taken from the fetcher's proxy configuration, via `dns_pinning.allow_resolution`), so a proxy on a private or loopback address keeps working; cloud-metadata and other link-local addresses are still refused for it, and every other lookup during the fetch keeps the public-only policy. Two proxy setups are not mirrored and fail closed, meaning a private proxy is refused rather than let through: a plain-http resource whose `HTTP_PROXY` has an `https://` scheme while `HTTPS_PROXY` is also set, where urllib tunnels through the `HTTPS_PROXY` host; and a Python without urllib's private `_parse_proxy` helper.
+The PDF export resource fetcher (`_SafeUrlFetcher` in `web/services/pdf_service.py`) fetches every resource the render loads (the images a report's Markdown references, and any stylesheet, font or image those or a caller-supplied stylesheet reference in turn) through WeasyPrint's urllib-based `URLFetcher`, with redirects disabled. Raw HTML in report text is escaped before rendering, as in the on-screen report view, so report text itself references resources only through Markdown image syntax. Each fetch runs inside `dns_pinning.pinned_request` nested with `dns_pinning.block_private_resolution`, both with the policy its `validate_url` call applies (public addresses only; cloud-metadata always blocked). The connection therefore goes only to an address that passed the same policy at connect time. For an ASCII host name it is pinned to the validated address. An IP-literal host is not pinned, because there is no DNS to rebind; its lookup goes through the block window like any other unpinned lookup, such as a non-ASCII host that urllib looks up in a different form from the pin key. Each such lookup is checked against that policy on the answer actually used. urllib connects on the rendering thread, which is the thread the pin and window apply to, and keeps the hostname for TLS SNI and certificate verification. The fetch is refused if the `getaddrinfo` shim is not the active resolver, and resource URLs that carry userinfo (any `@` or percent-encoded `%40` in the authority) are refused outright, because urllib would look up the whole `user@host` authority rather than the pinned host. If `HTTP(S)_PROXY` is set, urllib connects to the proxy and the proxy resolves the target, so the forward-proxy caveat above applies to the target. The proxy's own lookup is exempted from the public-only policy by exact host and port (taken from the fetcher's proxy configuration, via `dns_pinning.allow_resolution`), so a proxy on a private or loopback address keeps working; cloud-metadata and other link-local addresses are still refused for it, and every other lookup during the fetch keeps the public-only policy. Two proxy setups are not mirrored and fail closed, meaning a private proxy is refused rather than let through: a plain-http resource whose `HTTP_PROXY` has an `https://` scheme while `HTTPS_PROXY` is also set, where urllib tunnels through the `HTTPS_PROXY` host; and a Python without urllib's private `_parse_proxy` helper.
### JS-Rendering Browser Redirect SSRF
diff --git a/changelog.d/+pdf-image-header-structure.security.md b/changelog.d/+pdf-image-header-structure.security.md
new file mode 100644
index 0000000000..bf1932242c
--- /dev/null
+++ b/changelog.d/+pdf-image-header-structure.security.md
@@ -0,0 +1 @@
+PDF exports check image structure before opening the images: GIF and JPEG headers, the Exif metadata the image decoder loads from JPEG, PNG and WebP images when the renderer opens and orients them (a PNG's eXIf chunk and its tEXt chunk keyed "exif" included), the number of chunks in PNG and WebP images, the bytes a PNG's compressed profile and text chunks (iCCP, zTXt, compressed iTXt) decompress to, and the number of frame headers and scans in a JPEG. Resources above the format-specific structure, metadata, chunk-count, decompression and scan-count limits are omitted while the export continues. A PNG's compressed chunks are decompressed in bounded steps and charged as they go against a 4 MiB cap for the whole image, including what a chunk decompresses to before its data turns out to be corrupt (a step the decompressor rejects is charged the most it could have produced); the check stops one byte past the cap, and each later open of an accepted PNG by the image decoder decompresses no more than the cap. A PNG whose zTXt or iTXt text chunk is keyed "exif" is refused outright rather than trusting what the Exif reader makes of decoded text. A GIF whose block structure cannot be walked to the end of its first frame (cut short, holding an unknown block, or ending before any image) is omitted, even where the image decoder would still open it. JPEG images are measured by the area the decoder processes, padded to whole decoding blocks (MCUs), both against the per-image pixel limit and against the per-export pixel budget, and a JPEG with more than 10 scans is charged against that budget in proportion to its scans.
diff --git a/src/local_deep_research/web/services/pdf_service.py b/src/local_deep_research/web/services/pdf_service.py
index df89f159e5..5b59fddc11 100644
--- a/src/local_deep_research/web/services/pdf_service.py
+++ b/src/local_deep_research/web/services/pdf_service.py
@@ -202,9 +202,10 @@ MAX_PDF_RESOURCE_BYTES = 16 * 1024 * 1024
# image; see the per-export note below). This bounds one image's dimensions,
# not the renderer's total peak memory, which includes other buffers.
MAX_PDF_IMAGE_PIXELS = 16 * 1024 * 1024
-# The most pixels all of one export's accepted raster images may declare
-# together. The byte caps do not bound this: a highly compressible image (a
-# flat colour, a simple chart) is tiny on the wire yet costs the same to decode
+# The most pixels all of one export's accepted raster images may be charged
+# together (their declared pixels; for a JPEG, see below). The byte caps do
+# not bound this: a highly compressible image (a flat colour, a simple
+# chart) is tiny on the wire yet costs the same to decode
# as a noisy one its size, so a report of thousands of distinct-URL images,
# each under the per-image cap and cheap on the wire, could impose unbounded
# total decode work. (It would not keep that many *resident*: WeasyPrint's
@@ -212,9 +213,17 @@ MAX_PDF_IMAGE_PIXELS = 16 * 1024 * 1024
# is, everything else re-encoded to PNG -- in an in-memory cache keyed by URL,
# and decodes to raw pixels only transiently, one image at a time. Re-encoding
# can change the compressed size, so the fetched byte budget is not a bound
-# on resident image memory. This separate cap bounds the total declared
-# pixels to decode.)
-# `_refuse_unbounded_resource` charges each accepted image its declared pixels
+# on resident image memory. This separate cap bounds the total pixels to
+# decode.) A JPEG is charged what libjpeg decodes rather than
+# what it declares: its area padded to whole MCUs (groups of 8x8 blocks, up
+# to 32x32 pixels with chroma subsampling, so a 1-pixel-high image is
+# decoded 8 to 32 rows high), times its scans past `_JPEG_BUDGET_SCANS`
+# divided by that many (libjpeg passes over the blocks once per scan; see
+# `_jpeg_budget_charge`). So the budget bounds total decode work to about
+# this many pixels of ordinary decoding, not this many pixels whatever
+# their shape and scans. Per-pixel cost still varies with content (noise
+# costs several times a flat colour) and format.
+# `_refuse_unbounded_resource` charges each accepted image these pixels
# against this budget and refuses the rest, so the export still completes. 256
# M pixels admits dozens of multi-megapixel images (about 21 at 12 MP, 64 at 4
# MP, 128 at 2 MP) -- far more than an ordinary report -- while a thousands-of-
@@ -269,6 +278,249 @@ _GLYPH_IMAGE_TABLES = frozenset({b"sbix", b"CBDT", b"CBLC", b"SVG "})
# is refused rather than walked.
_MAX_FONT_TABLES = 512
_MAX_FONT_COLLECTION_FACES = 256
+# A GIF body starts with one of these (Pillow's GIF sniffer matches exactly
+# them). `_gif_structure_refusal` walks such a body's block structure before
+# Pillow parses any of it, the size probe included.
+_GIF_SIGNATURES = (b"GIF87a", b"GIF89a")
+# Caps on a GIF's block structure. Pillow's GIF parser takes one Python step
+# per block, and Pillow 12.3's is worse than linear in comments: it joins a
+# comment extension's data sub-blocks with ``comment += block`` and a frame's
+# comment extensions with ``info["comment"] += ...``, so their cost grows
+# with the square of their number (timed on the test machine: 128 Ki one-byte
+# comment sub-blocks, a 256 KiB body, cost 0.25 s; 512 Ki, a 1 MiB body,
+# 4.1 s; a 16 MiB body would cost minutes). Pillow 13.0.0 collects them in a
+# list and joins it once, linear in their number, but still takes one Python
+# step per block. The guard's probe parses the header once
+# and WeasyPrint's ``Image.open`` again, so a body past any cap is refused
+# before either runs. The pre-scan itself only follows offsets, and these
+# caps bound its steps.
+#
+# WeasyPrint draws only a GIF's first frame: ``Image.open``, ``convert`` and
+# ``save(format="PNG")`` without ``save_all`` read frame 0 and nothing after
+# it, and nothing asks for ``n_frames`` or ``is_animated``. So the frame cap
+# need not admit every animation, only far more than a report embeds: 16384
+# frames is over nine minutes at 30 frames a second. For the same reason,
+# once one frame is complete, the walk ends without refusing at a cut or at
+# bytes it cannot read: Pillow never reads that far.
+_MAX_GIF_FRAMES = 16384
+# Every block and data sub-block, image data included. Encoders write image
+# data in 255-byte sub-blocks, so a well-formed GIF within the 16 MiB
+# resource cap has about 64 Ki of them, plus at least four blocks per frame
+# (a descriptor, a graphic control extension and its sub-block, and an
+# image-data sub-block: 64 Ki at the frame cap). 256 Ki is twice the sum of
+# both, and bounds the pre-scan's own steps.
+_MAX_GIF_BLOCKS = 256 * 1024
+# Extensions (graphic control, application, plain text and comment) and
+# their data sub-blocks. A graphic control extension per frame takes two (32
+# Ki at the frame cap), a NETSCAPE loop block three, and an ICC profile or
+# XMP packet a few thousand at most; 64 Ki leaves room for all of them
+# together. Counting the extensions themselves, not only their sub-blocks,
+# also bounds the walk over empty ones.
+_MAX_GIF_EXTENSION_BLOCKS = 64 * 1024
+# Comment extensions plus their data sub-blocks, and the bytes those carry:
+# the parts Pillow concatenates. Encoders typically write one short comment
+# (a tool name or a caption), in 255-byte sub-blocks. At these caps
+# Pillow's concatenation costs milliseconds.
+_MAX_GIF_COMMENT_BLOCKS = 4096
+_MAX_GIF_COMMENT_BYTES = 64 * 1024
+# A JPEG body starts with these (Pillow's JPEG sniffer matches exactly them).
+# `_jpeg_structure_refusal` walks its marker segments up to the first scan
+# before Pillow parses any of it.
+_JPEG_SIGNATURE = b"\xff\xd8\xff"
+# Markers Pillow 12.3 reads no length for (``MARKER`` entries without a
+# handler): JPG, RST0-7, SOI, EOI and JPG0-13.
+_JPEG_STANDALONE_MARKERS = frozenset(
+ {0xC8, *range(0xD0, 0xDA), *range(0xF0, 0xFE)}
+)
+# Markers Pillow reads a two-byte length and a segment for: SOFn, DHT, DAC,
+# SOS, DQT, DNL, DRI, DHP, EXP, APP0-15 and COM. Any other marker makes
+# Pillow raise, so the walk refuses it too.
+_JPEG_SEGMENT_MARKERS = frozenset(
+ {*range(0xC0, 0xC8), *range(0xC9, 0xD0), *range(0xDA, 0xF0), 0xFE}
+)
+# Caps on a JPEG's header, everything before its first scan (SOS), which is
+# all Pillow parses on open. Pillow (12.3 and 13.0.0 alike, except where
+# noted) is not linear in it:
+#
+# - it joins every ``Exif\0\0`` APP1 segment with ``info["exif"] += s[6:]``,
+# quadratic in their number (timed on the test machine: 80 Ki one-byte
+# segments, an 880 KB body, 0.19 s; 1.4 M, under the 16 MiB cap, about
+# 50 s); Pillow 12.3 then strips every leading ``Exif\0\0`` header one
+# slice at a time, quadratic in their number (512 KiB of them, 0.6 s),
+# where 13.0.0 strips at most two with one regular expression;
+# - it loads the Exif data's TIFF directories (``_read_dpi_from_exif`` on
+# open; ``exif_transpose``, which WeasyPrint runs for its default
+# ``image-orientation: from-image``, also loads and decodes the Exif, GPS
+# and Interop directories), reading every tag's data however many tags
+# point at the same bytes: one 64 KiB segment of 5400 such tags, 0.19 s;
+# - it decodes every tag of an ``MPF`` APP2 segment's TIFF directory
+# (``_getmp``, run by the JPEG factory itself) into Python values: one
+# 64 KiB segment of 5400 overlapping tags, 9.7 s.
+#
+# Everything else on the header path (ICC, Photoshop and XMP segments,
+# comments, tables) is linear in the body. A JPEG past any cap below is
+# refused before the probe or WeasyPrint parses it.
+#
+# Marker segments and standalone markers, before the first scan and between
+# scans up to the end of the image (EOI). An ordinary JPEG has a dozen or
+# two; an ICC profile split over 64 KiB APP2 segments, an extended XMP
+# packet, or MPO and multi-APP1 camera metadata add a few dozen more, and a
+# progressive JPEG a table or two per scan. Only 256 full-size segments fit
+# in the 16 MiB resource cap at all.
+_MAX_JPEG_SEGMENTS = 1024
+# Frame headers: SOFn, and DHP, which Pillow parses with the same handler.
+# Pillow appends a tuple to one list for every component each of them
+# declares (up to 21 Ki in one 64 KiB segment), so their memory grows with
+# their number. A JPEG has one frame; only hierarchical JPEG has more, and
+# libjpeg does not decode it.
+_JPEG_FRAME_MARKERS = frozenset(
+ {*range(0xC0, 0xC4), *range(0xC5, 0xC8), *range(0xC9, 0xCC)}
+ | {*range(0xCD, 0xD0), 0xDE}
+)
+_MAX_JPEG_FRAME_HEADERS = 1
+# Scans (SOS segments) up to EOI. The declared pixels do not bound a JPEG's
+# decode work by themselves: libjpeg decodes a JPEG with several scans
+# (progressive, or sequential or lossless with one scan per component or
+# group of components) one scan at a time, each scan a pass over the image's
+# blocks, so decode time grows with blocks times scans. libjpeg's default
+# progressive scripts write 6 to 18 scans (grey to CMYK), optimizing
+# encoders about as many, and a non-interleaved sequential JPEG one per
+# component; 64 leaves room for custom scripts.
+_MAX_JPEG_SCANS = 64
+# The scans a JPEG may have and still be charged its pixels once against the
+# export's pixel budget (`_jpeg_budget_charge`); one with more is charged in
+# proportion. An ordinary progressive JPEG has about 10 (one of 64 is
+# charged 6.4 times), so many-scan images cannot multiply the work the
+# budget admits by the scan cap.
+_JPEG_BUDGET_SCANS = 10
+# The next marker in entropy-coded data, as libjpeg finds it: 0xFF followed by
+# anything but a stuffed 0x00, a fill byte 0xFF or a restart marker (RST0-7,
+# which belongs to the scan).
+_JPEG_SCAN_MARKER = re.compile(rb"\xff[^\x00\xd0-\xd7\xff]")
+# Fill bytes (0xFF), stuffed 0xFF00 pairs and stray bytes between segments,
+# each one Python step for Pillow (about 0.27 s per MiB). Encoders write
+# none or a few.
+_MAX_JPEG_PADDING_BYTES = 4096
+# ``Exif\0\0`` APP1 segments, and the bytes Pillow joins from them. The Exif
+# standard puts Exif in one APP1 segment, at most 64 KiB; some cameras
+# continue it over a few more. 16 segments and 256 KiB (four full segments)
+# leave room for those while keeping the join to milliseconds.
+_MAX_JPEG_EXIF_SEGMENTS = 16
+_MAX_JPEG_EXIF_BYTES = 256 * 1024
+# Leading ``Exif\0\0`` headers, which Pillow strips before it reads the
+# TIFF data: 12.3 every one, a slice at a time; 13.0.0 at most two, so that
+# a third is read as the TIFF header and fails. There is one, and a faulty
+# writer may repeat it once. Also applied to PNG and WebP Exif data, which
+# Pillow strips the same way.
+_MAX_JPEG_EXIF_HEADERS = 4
+# Caps on the TIFF directories Pillow loads from the Exif data (IFD0 and the
+# Exif, GPS and Interop directories it points to) and from each MPF segment:
+# their entries; the bytes the entries' data declare (each entry's ``count``
+# times its type's size, past what fits in the entry itself), which Pillow
+# reads; and how many numbers among them (every type but BYTE, ASCII
+# and UNDEFINED), which it decodes to Python values one by one. Ordinary
+# Exif has a few dozen entries and a few hundred numbers at most (a transfer
+# function is 768), and MPF a handful. Their data are disjoint, so they
+# total less than the Exif data (at most 64 KiB in one segment, a maker note
+# included) or the MPF segment; 128 KiB is twice one segment. Timed at these
+# caps, decoding and re-encoding the lot in ``exif_transpose`` costs at most
+# about 0.05 s (4096 rationals).
+_MAX_TIFF_IFD_ENTRIES = 1024
+_MAX_TIFF_IFD_DATA_BYTES = 128 * 1024
+_MAX_TIFF_IFD_NUMBERS = 4096
+# The size of one value of each TIFF type Pillow 12.3 loads
+# (``ImageFileDirectory_v2._load_dispatch``); it skips any other type.
+_TIFF_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, 16: 8,
+} # fmt: skip
+# BYTE, ASCII and UNDEFINED: data Pillow decodes as a whole, not
+# number by number.
+_TIFF_BYTE_STRING_TYPES = frozenset({1, 2, 7})
+# Integer representations whose first decoded value can identify a
+# directory offset, indexed by their ``struct`` codes.
+_TIFF_INTEGER_CODES = {
+ 3: "H", 4: "L", 6: "b", 8: "h", 9: "l", 13: "L", 16: "Q",
+} # fmt: skip
+# TIFF headers Pillow's ``ImageFileDirectory_v2`` reads as a classic TIFF
+# directory (its ``PREFIXES`` other than little-endian BigTIFF, which fails
+# at once on Exif's 8-byte header).
+_TIFF_CLASSIC_HEADERS = {
+ b"II*\x00": "<",
+ b"II\x00*": "<",
+ b"MM\x00*": ">",
+ b"MM*\x00": ">",
+ b"MM\x00+": ">",
+}
+# The tags through which Pillow's ``Exif.tobytes`` loads further
+# directories: from IFD0, the Exif and GPS directories; from the Exif
+# directory, the Interop directory.
+_EXIF_IFD_POINTERS = {None: (0x8769, 0x8825), 0x8769: (0xA005,)}
+# PNG and WebP carry Exif data in a chunk: PNG in ``eXIf`` (Pillow also
+# takes a ``tEXt`` chunk keyed ``exif`` as raw Exif), WebP in ``EXIF``.
+# WeasyPrint's ``exif_transpose`` loads it as it does a JPEG's, with the same
+# header strip and TIFF directory reads, so `_png_structure_refusal` and
+# `_webp_structure_refusal` find those chunks and apply the
+# ``_MAX_JPEG_EXIF_HEADERS`` and ``_MAX_TIFF_*`` caps to each. Both formats
+# allow one Exif chunk; Pillow keeps PNG's last and WebP's first, so every
+# one is checked, up to this many. `_png_structure_refusal` also refuses
+# outright a ``zTXt`` or ``iTXt`` chunk keyed ``exif``: Pillow decodes that
+# value to text, which ``getexif`` hands to ``Exif.load`` as text (a
+# TypeError there today, which WeasyPrint turns into a dropped image), and
+# the walk relies on none of that.
+#
+# ``Image.getexif`` reads one PNG carrier more: a text chunk keyed ``Raw
+# profile type exif`` (the raw-profile form ImageMagick writes), which it
+# hex-decodes as Exif -- but only when ``info`` has no ``exif`` entry.
+# Nothing on WeasyPrint 70's path calls ``getexif`` on a PNG except
+# ``exif_transpose``, which ``rotate_pillow_image`` runs only for an image
+# whose ``info`` has an ``exif`` entry, so that carrier is never decoded in
+# an export and the walk leaves it alone (pinned by TestPngAndWebpExif).
+_MAX_EXIF_CHUNKS = 4
+_PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n"
+_PNG_TEXT_CHUNK_KINDS = (b"tEXt", b"zTXt", b"iTXt")
+# Chunks the walks step over, one Python step each. Pillow's PNG reader also
+# takes one per chunk, but for the chunks whose payload decompresses --
+# ``iCCP`` profiles, and ``zTXt`` and compressed ``iTXt`` text -- whose work
+# `_MAX_PNG_DECOMPRESSED_BYTES` bounds instead. Encoders write PNG image data
+# in chunks of 8 KiB or more, so a PNG within the 16 MiB resource cap has a
+# few thousand at most; an animated PNG adds two per frame. libwebp's demuxer
+# walks a WebP's chunks in C; a still WebP has a handful, and an animated one
+# two or three per frame, all of which the walk counts: the frame's ``ANMF``
+# chunk, which it enters, and the image chunks inside (``VP8 `` or ``VP8L``,
+# and ``ALPH``) -- so the cap admits over 20,000 frames.
+_MAX_PNG_CHUNKS = 64 * 1024
+_MAX_WEBP_CHUNKS = 64 * 1024
+# What a PNG's compressed metadata chunks -- ``iCCP``, ``zTXt`` and
+# compressed ``iTXt`` -- may decompress to together. Pillow decompresses
+# each of them itself (``PngStream.chunk_iCCP``, ``chunk_zTXt``,
+# ``chunk_iTXt``), per chunk bounded only by its own ``MAX_TEXT_CHUNK`` of
+# 1 MiB, and with no cumulative bound at all for ``iCCP`` (its cumulative
+# ``MAX_TEXT_MEMORY`` check covers text chunks only). A chunk that fails does
+# not stop it: it swallows the ``zlib.error`` of corrupt data, after
+# decompressing up to the corruption, and -- under ``LOAD_TRUNCATED_IMAGES``,
+# which WeasyPrint sets on import -- the error of a chunk past 1 MiB too,
+# keeps no value from that chunk and goes on to the next. 1 KiB of compressed
+# zeros per iCCP chunk decompresses to 1 MiB each, so 400 such chunks (a
+# 0.42 MB body) cost 0.96 s inside one Pillow open on the test machine
+# (about 2.5 ms per decompressed MiB), and a 16 MiB body holds some 15,000
+# of them -- tens of seconds per open, and Pillow opens an accepted PNG
+# three or four times per fetch: the size probe, WeasyPrint's open, and a
+# re-open each time WeasyPrint writes the image into the PDF
+# (``get_x_object``: once, or twice for an image drawn both with and
+# without smoothing, which ``image-rendering`` selects). So the walk
+# decompresses these payloads itself (`_png_inflated_bytes`), a step at a
+# time, charging each step what it puts out (and a step zlib rejects, whose
+# output CPython discards, the most it may put out), and refuses the PNG as
+# soon as the total passes this cap, at most one byte past it. However the
+# chunks compress or fail, the walk decompresses at most that much of one
+# PNG, and each Pillow open of an accepted PNG at most this cap, since
+# Pillow decompresses no chunk past what the walk charged it: four or five
+# passes in all, at most about 0.05 s at the measured rate. One that would
+# cost more is refused before Pillow parses it. Pillow keeps only the last
+# iCCP chunk's profile, so the cap is far past what a real image
+# decompresses.
+_MAX_PNG_DECOMPRESSED_BYTES = 4 * 1024 * 1024
# What all of one export's fetches may cost together: four resources at the
# per-resource limit. Every response is charged what reading it cost
# (`_FetchCost`), whether it was accepted, refused or failed part-way, so many
@@ -320,9 +572,10 @@ class _ResourceBudget:
``remaining`` is the byte budget (`MAX_PDF_EXPORT_RESOURCE_BYTES`) for
reading and decoding bodies. ``image_pixels`` is a separate budget, in
pixels, for the raster images accepted so far: the byte budget does not
- bound an image's decode, so each accepted image is charged its declared
- pixels here (`_refuse_unbounded_resource`), and once it is spent further
- images are refused.
+ bound an image's decode, so each accepted image is charged its pixels
+ here (declared; for a JPEG, MCU-padded and scaled by scans:
+ `_refuse_unbounded_resource`), and once it is spent further images are
+ refused.
"""
__slots__ = (
@@ -352,7 +605,7 @@ class _ResourceBudget:
self.remaining = max(0, self.remaining - cost)
def charge_image_pixels(self, pixels: int) -> bool:
- """Deduct an accepted image's declared pixels; return whether they fit.
+ """Deduct an accepted image's charged pixels; return whether they fit.
A declaration past what is left spends the rest of the budget (so
every later image is refused too) and returns ``False``.
@@ -668,10 +921,11 @@ def _pillow_raster_format(body: bytes) -> Optional[str]:
(`_PREFIX_RULED_RASTER_FORMATS`) or by running their reviewed
header-only factory (`_HEADER_ONLY_RASTER_FORMATS`) on the already
byte-capped body. Never open an unreviewed format: some (ICO, ICNS, BLP)
- decode pixels during ``_open``. A header-only factory that raises
- ``ValueError`` or ``OSError`` (which ``Image.open`` would propagate, not
- skip) fails closed: its format is returned, so the body is refused with
- the guard's own warning. Non-raster bodies (SVG, ICC profiles,
+ decode pixels during ``_open``. A header-only factory or accept sniffer
+ that raises any exception other than the non-matches ``Image.open``
+ skips (``SyntaxError``, ``IndexError``, ``TypeError``, ``struct.error``)
+ fails closed: its format is returned, so the body is refused with the
+ guard's own warning. Non-raster bodies (SVG, ICC profiles,
stylesheets, TTF/OTF fonts, text) return None.
"""
from PIL import Image
@@ -695,14 +949,19 @@ def _pillow_raster_format(body: bytes) -> Optional[str]:
except (SyntaxError, IndexError, TypeError, struct.error):
# Same non-matches Image.open skips while trying plugins.
continue
- except (ValueError, OSError):
+ except Exception:
# Image.open would raise these rather than try the next
# plugin: fail closed under this format's name.
return fmt
try:
matched = accept(prefix)
- except Exception:
+ except (SyntaxError, IndexError, TypeError, struct.error):
+ # Same non-matches Image.open skips while trying plugins.
continue
+ except Exception:
+ # Image.open would raise these rather than try the next plugin:
+ # fail closed under this format's name.
+ return fmt
# A str result is a reason the format was *not* accepted (e.g. WebP
# support missing), which Image.open treats as no match.
if matched and not isinstance(matched, str):
@@ -713,23 +972,43 @@ def _pillow_raster_format(body: bytes) -> Optional[str]:
def _declared_image_pixels(body: bytes, fmt: str) -> Optional[int]:
"""The pixel count an allow-listed raster image declares in its header.
+ For a JPEG, the declared area padded to whole MCUs (`_jpeg_mcu_padded`),
+ which is what libjpeg decodes; both caps compare against this count.
+
Runs the identified format's own factory (``Image.OPEN[fmt][0]``), not
``Image.open``: so no other format's decoder is tried if this header
- fails, and Pillow's ``_decompression_bomb_check`` (which ``Image.open``
- runs after the factory, and which warns past ~89 M pixels) is never
- reached. Nothing here touches the process-wide ``warnings`` filters,
- which ``warnings.catch_warnings`` would, unsafely, while exports run in
- other threads; the cap below answers an oversized declaration instead.
+ fails, and the ``_decompression_bomb_check`` that ``Image.open`` runs
+ after the factory (which warns past ~89 M pixels) is not reached. A
+ factory may still run that check itself: GIF's ``_seek`` does when a
+ frame extends past the logical screen, and enlarges the size it reports
+ to cover the frame, so the cap below still sees the enlarged size. PNG
+ animation headers can also emit a warning. Nothing here
+ touches the process-wide ``warnings`` filters, which
+ ``warnings.catch_warnings`` would, unsafely, while exports run in other
+ threads; the cap below answers an oversized declaration instead.
No factory decodes pixels, but not all of them read only a fixed-size
- header. PNG and GIF read their header chunks. JPEG walks its markers up
- to the first frame, so a body of markers alone is scanned to its end
- (linear in the body, which the byte cap bounds). WebP hands the body to
- libwebp's demuxer and animation decoder, which allocates a canvas buffer
- for the declared size (up to 16383x16383 RGBA, about 1 GiB of virtual
- memory, mostly never touched) before this cap is compared. Returns None
- if the header cannot be read (an allocation failure included), so the
- caller can refuse it.
+ header. PNG reads every chunk before its first image data, one Python
+ step per chunk except the ones whose payload decompresses (``iCCP``,
+ ``zTXt``, compressed ``iTXt``), which `_png_structure_refusal` bounds
+ before this probe runs by decompressing them itself within
+ `_MAX_PNG_DECOMPRESSED_BYTES`. GIF reads every block before its
+ first image descriptor, one Python step each (Pillow 12.3 also joins
+ comment sub-blocks by repeated concatenation, quadratic in their
+ number), so `_gif_structure_refusal` bounds a GIF's blocks before this
+ probe runs. JPEG reads every marker segment before its first scan, and
+ is not linear in them either: it joins Exif segments by repeated
+ concatenation, and reads and decodes the TIFF directories of its Exif
+ and MPF data however many tags share the same bytes;
+ `_jpeg_structure_refusal` bounds those before this probe runs. WebP
+ hands the body to libwebp's demuxer and animation decoder, which
+ allocates a canvas buffer for the declared size before this cap is
+ compared: in Pillow 12.3 up to 16383x16383 RGBA, about 1 GiB of virtual
+ memory (mostly never touched); Pillow 13.0.0 first reads the declared
+ size from the header and raises past twice its own ``MAX_IMAGE_PIXELS``
+ (about 179 M pixels, a 0.7 GB canvas). Returns None if the header
+ cannot be read (an allocation failure included), so the caller can
+ refuse it.
"""
from PIL import Image
@@ -740,11 +1019,754 @@ def _declared_image_pixels(body: bytes, fmt: str) -> Optional[int]:
try:
with opener[0](io.BytesIO(body), "") as image:
width, height = image.size
+ if fmt == "JPEG":
+ width, height = _jpeg_mcu_padded(image, width, height)
except Exception:
return None
return width * height
+def _jpeg_mcu_padded(image, width: int, height: int) -> tuple[int, int]:
+ """``width`` x ``height`` rounded up to whole MCUs of the JPEG ``image``.
+
+ An MCU is 8 pixels times the largest horizontal and vertical sampling
+ factor of the frame's components; libjpeg decodes whole MCUs. Pillow's
+ ``layer`` holds each component as (id, high nibble, low nibble, table)
+ of its sampling byte, which the JPEG standard defines as horizontal,
+ then vertical (Pillow's own comment names them the other way round).
+ """
+ layers = getattr(image, "layer", None) or [(0, 1, 1, 0)]
+ mcu_h = 8 * max(max(layer[1] for layer in layers), 1)
+ mcu_v = 8 * max(max(layer[2] for layer in layers), 1)
+ return -(-width // mcu_h) * mcu_h, -(-height // mcu_v) * mcu_v
+
+
+class _MalformedImage(ValueError):
+ """An image structure a pre-scan cannot walk within its caps."""
+
+
+def _gif_sub_blocks(body: bytes, pos: int, limit: int) -> tuple[int, int, int]:
+ """Skip the data sub-blocks at ``pos``, up to and past their terminator.
+
+ Returns ``(end, count, size)``: the offset after the terminator, how many
+ sub-blocks there were and how many bytes they carry. Stops after
+ ``limit + 1`` sub-blocks, returning that count, so a caller's cap bounds
+ the walk. Only offsets are followed; no sub-block is copied. Raises
+ `_MalformedImage` if a sub-block or the terminator lies past the body.
+ """
+ end = len(body)
+ count = size = 0
+ while count <= limit:
+ if pos >= end:
+ raise _MalformedImage("truncated")
+ length = body[pos]
+ pos += 1
+ if length == 0:
+ return pos, count, size
+ pos += length
+ if pos > end:
+ raise _MalformedImage("truncated")
+ count += 1
+ size += length
+ return pos, count, size
+
+
+class _GifWalk:
+ """The counts `_walk_gif` checks against the ``_MAX_GIF_*`` caps."""
+
+ def __init__(self) -> None:
+ self.frames = self.complete_frames = self.blocks = 0
+ self.extension_blocks = self.comment_blocks = self.comment_bytes = 0
+
+ def over_cap(self) -> Optional[str]:
+ """Why the counts so far are refused, or None."""
+ if (
+ self.frames <= _MAX_GIF_FRAMES
+ and self.blocks <= _MAX_GIF_BLOCKS
+ and self.extension_blocks <= _MAX_GIF_EXTENSION_BLOCKS
+ and self.comment_blocks <= _MAX_GIF_COMMENT_BLOCKS
+ and self.comment_bytes <= _MAX_GIF_COMMENT_BYTES
+ ):
+ return None # the common case, checked once per block
+ for count, cap, what in (
+ (self.frames, _MAX_GIF_FRAMES, "frames"),
+ (self.blocks, _MAX_GIF_BLOCKS, "blocks"),
+ (
+ self.extension_blocks,
+ _MAX_GIF_EXTENSION_BLOCKS,
+ "extension blocks",
+ ),
+ (self.comment_blocks, _MAX_GIF_COMMENT_BLOCKS, "comment blocks"),
+ (self.comment_bytes, _MAX_GIF_COMMENT_BYTES, "bytes of comments"),
+ ):
+ if count > cap:
+ return f"a GIF image with more than {cap} {what}"
+ return None
+
+
+def _gif_block(body: bytes, pos: int, walk: _GifWalk) -> Optional[int]:
+ """Walk the block at ``pos``; the offset after it, or None at the end.
+
+ Counts what it walks into ``walk``, stopping a sub-block walk once a
+ cap is passed. Raises `_MalformedImage` for a block it cannot walk.
+ """
+ end = len(body)
+ if pos >= end:
+ raise _MalformedImage("truncated")
+ introducer = body[pos]
+ pos += 1
+ walk.blocks += 1
+ if introducer == 0x3B: # trailer
+ if not walk.complete_frames:
+ raise _MalformedImage("no image")
+ return None
+ if introducer == 0x21: # extension: label, then sub-blocks
+ if pos >= end:
+ raise _MalformedImage("truncated")
+ is_comment = body[pos] == 0xFE
+ pos += 1
+ walk.extension_blocks += 1
+ limit = min(
+ _MAX_GIF_BLOCKS - walk.blocks,
+ _MAX_GIF_EXTENSION_BLOCKS - walk.extension_blocks,
+ )
+ if is_comment:
+ walk.comment_blocks += 1
+ limit = min(limit, _MAX_GIF_COMMENT_BLOCKS - walk.comment_blocks)
+ pos, count, size = _gif_sub_blocks(body, pos, max(limit, 0))
+ walk.blocks += count
+ walk.extension_blocks += count
+ if is_comment:
+ walk.comment_blocks += count
+ walk.comment_bytes += size
+ return pos
+ if introducer == 0x2C: # image descriptor
+ walk.frames += 1
+ if walk.frames > _MAX_GIF_FRAMES:
+ return pos
+ if pos + 9 > end:
+ raise _MalformedImage("truncated")
+ flags = body[pos + 8]
+ pos += 9
+ if flags & 0x80:
+ pos += 3 << ((flags & 7) + 1)
+ pos += 1 # LZW minimum code size
+ if pos > end:
+ raise _MalformedImage("truncated")
+ pos, count, _ = _gif_sub_blocks(
+ body, pos, max(_MAX_GIF_BLOCKS - walk.blocks, 0)
+ )
+ walk.blocks += count
+ if walk.blocks <= _MAX_GIF_BLOCKS:
+ walk.complete_frames += 1
+ return pos
+ raise _MalformedImage(f"unknown block 0x{introducer:02X}")
+
+
+def _walk_gif(body: bytes) -> Optional[str]:
+ """`_gif_structure_refusal`'s walk: a cap a body is past, or None.
+
+ Raises `_MalformedImage` for a structure it cannot walk before its
+ first complete frame. After that, the walk just ends there: Pillow reads
+ only frame 0 for WeasyPrint, so nothing it cannot walk is parsed.
+ """
+ end = len(body)
+ if end < 13:
+ raise _MalformedImage("truncated")
+ pos: Optional[int] = 13
+ flags = body[10]
+ if flags & 0x80:
+ pos = 13 + (3 << ((flags & 7) + 1))
+ walk = _GifWalk()
+ while pos is not None:
+ if pos == end and walk.complete_frames:
+ return None # no trailer, but no block is cut short
+ try:
+ pos = _gif_block(body, pos, walk)
+ except _MalformedImage:
+ if walk.complete_frames:
+ return None
+ raise
+ reason = walk.over_cap()
+ if reason is not None:
+ return reason
+ return None
+
+
+def _gif_structure_refusal(body: bytes) -> Optional[str]:
+ """Why a GIF body's block structure is refused, or None if it is not.
+
+ Walks the structure by byte offsets alone -- the logical screen
+ descriptor and global colour table, then each extension and its data
+ sub-blocks and each image descriptor, local colour table and image data
+ sub-blocks, to the trailer -- before Pillow parses any of it. Refuses a
+ body past `_MAX_GIF_FRAMES`, `_MAX_GIF_BLOCKS`,
+ `_MAX_GIF_EXTENSION_BLOCKS`, `_MAX_GIF_COMMENT_BLOCKS` or
+ `_MAX_GIF_COMMENT_BYTES`. Before the first complete frame, which is all
+ WeasyPrint draws, it also refuses (fails closed) a structure it cannot
+ walk: a block or table past the end of the body, an unknown block type,
+ or a trailer with no image. After it, the walk ends at the trailer, at
+ the end of the body, or at whatever it cannot walk, and accepts. Every
+ step either advances past a counted block or stops, so the walk is
+ linear and bounded by the caps.
+ """
+ try:
+ return _walk_gif(body)
+ except _MalformedImage as exc:
+ return f"a GIF image whose block structure is unreadable ({exc})"
+
+
+class _TiffWalk:
+ """What `_tiff_refusal` has charged against the ``_MAX_TIFF_*`` caps."""
+
+ def __init__(self) -> None:
+ self.entries = self.data_bytes = self.numbers = 0
+
+ def over_cap(self, what: str) -> Optional[str]:
+ """``what`` names the data: ``"a JPEG image whose MPF data"``."""
+ if self.entries > _MAX_TIFF_IFD_ENTRIES:
+ return (
+ f"{what} has more than "
+ f"{_MAX_TIFF_IFD_ENTRIES} directory entries"
+ )
+ if self.data_bytes > _MAX_TIFF_IFD_DATA_BYTES:
+ return (
+ f"{what} declares more than "
+ f"{_MAX_TIFF_IFD_DATA_BYTES} bytes of tag data"
+ )
+ if self.numbers > _MAX_TIFF_IFD_NUMBERS:
+ return (
+ f"{what} declares more than "
+ f"{_MAX_TIFF_IFD_NUMBERS} numeric tag values"
+ )
+ return None
+
+
+def _tiff_directory(
+ data: bytes, start: int, stop: int, at: int, order: str, walk: _TiffWalk
+) -> dict:
+ """Charge the TIFF directory at ``start + at`` to ``walk``.
+
+ Mirrors what Pillow's ``ImageFileDirectory_v2.load`` reads: the entry
+ count, then as many 12-byte entries as fit before ``stop``. Each entry
+ of a type Pillow loads is charged its declared data past four bytes
+ (bounded by the TIFF data's length, as Pillow's read is). Returns the
+ first integer values of pointer entries, grouped by tag. Account for
+ each supported directory reference so duplicate-tag selection across
+ supported Pillow versions does not change the budget. Only offsets
+ are followed; nothing is copied.
+ """
+ pos = start + at
+ if at < 0 or pos + 2 > stop:
+ return {} # Pillow's read of the entry count fails: nothing loaded
+ (count,) = struct.unpack_from(order + "H", data, pos)
+ count = min(count, (stop - pos - 2) // 12)
+ walk.entries += count
+ if walk.entries > _MAX_TIFF_IFD_ENTRIES:
+ return {}
+ values = {}
+ for entry in range(pos + 2, pos + 2 + 12 * count, 12):
+ tag, kind, items = struct.unpack_from(order + "HHL", data, entry)
+ unit = _TIFF_TYPE_SIZES.get(kind)
+ if unit is None:
+ continue
+ size = items * unit
+ data_at = entry + 8
+ if size > 4:
+ walk.data_bytes += min(size, stop - start)
+ if kind not in _TIFF_BYTE_STRING_TYPES:
+ walk.numbers += min(items, (stop - start) // unit)
+ (offset,) = struct.unpack_from(order + "L", data, entry + 8)
+ data_at = start + offset
+ elif kind not in _TIFF_BYTE_STRING_TYPES:
+ walk.numbers += items
+ if (
+ items
+ and tag in (0x8769, 0x8825, 0xA005)
+ and kind in _TIFF_INTEGER_CODES
+ and data_at + size <= stop
+ ):
+ (value,) = struct.unpack_from(
+ order + _TIFF_INTEGER_CODES[kind], data, data_at
+ )
+ values.setdefault(tag, []).append(value)
+ return values
+
+
+def _tiff_refusal(
+ data: bytes, start: int, stop: int, what: str, *, exif: bool
+) -> Optional[str]:
+ """Why the TIFF data at ``data[start:stop]`` is refused, or None.
+
+ Walks the first directory, and for Exif (``exif``) the Exif, GPS and
+ Interop directories Pillow's ``Exif.tobytes`` loads through it
+ (`_EXIF_IFD_POINTERS`), charging them all to one `_TiffWalk`. Data
+ Pillow cannot read as a classic TIFF directory fails there at once, so
+ it is not refused here.
+ """
+ if stop - start < 8:
+ return None
+ order = _TIFF_CLASSIC_HEADERS.get(data[start : start + 4])
+ if order is None:
+ return None
+ walk = _TiffWalk()
+ (first,) = struct.unpack_from(order + "L", data, start + 4)
+ # Directory entries, including repeated references, share one budget.
+ pending: list = [(None, first)]
+ while pending:
+ parent, at = pending.pop()
+ values = _tiff_directory(data, start, stop, at, order, walk)
+ reason = walk.over_cap(what)
+ if reason is not None:
+ return reason
+ if exif:
+ for pointer in _EXIF_IFD_POINTERS.get(parent, ()):
+ pending.extend((pointer, at) for at in values.get(pointer, ()))
+ return None
+
+
+class _JpegWalk:
+ """What `_walk_jpeg` counts against the ``_MAX_JPEG_*`` caps."""
+
+ def __init__(self) -> None:
+ self.segments = self.padding = self.frames = 0
+ self.scans = 0
+ self.scan_data = 0 # where the first scan's entropy-coded data starts
+ self.exif: list = [] # (start, stop) of each Exif segment's payload
+ self.exif_bytes = 0
+ self.refusal: Optional[str] = None # an MPF segment's, if any
+
+ def over_cap(self) -> Optional[str]:
+ if self.refusal is not None:
+ return self.refusal
+ for count, cap, what in (
+ (self.segments, _MAX_JPEG_SEGMENTS, "marker segments"),
+ (self.padding, _MAX_JPEG_PADDING_BYTES, "padding bytes"),
+ (self.frames, _MAX_JPEG_FRAME_HEADERS, "frame headers"),
+ (self.scans, _MAX_JPEG_SCANS, "scans"),
+ (len(self.exif), _MAX_JPEG_EXIF_SEGMENTS, "Exif segments"),
+ (self.exif_bytes, _MAX_JPEG_EXIF_BYTES, "bytes of Exif"),
+ ):
+ if count > cap:
+ return f"a JPEG image with more than {cap} {what}"
+ return None
+
+
+def _exif_refusal(
+ data: bytes, start: int, stop: int, image: str, headers: int = 0
+) -> Optional[str]:
+ """Why the Exif data ``data[start:stop]`` of ``image`` is refused, or None.
+
+ Mirrors Pillow's ``Exif.load``, which strips leading ``Exif\\0\\0``
+ headers and reads the rest as TIFF data: this skips every leading
+ header (``headers`` counts those Pillow itself put in front, as it does
+ for PNG's ``eXIf``), refusing past `_MAX_JPEG_EXIF_HEADERS`, then checks
+ the rest (`_tiff_refusal`). Pillow 12.3 strips every header too, one
+ slice at a time; 13.0.0 strips at most two and fails to read a third
+ as TIFF, so it reads TIFF data only where this checks it. ``image``
+ names the image in the reason.
+ """
+ while data.startswith(b"Exif\x00\x00", start, stop):
+ headers += 1
+ start += 6
+ if headers > _MAX_JPEG_EXIF_HEADERS:
+ return (
+ f"{image} whose Exif data repeats its header more than "
+ f"{_MAX_JPEG_EXIF_HEADERS} times"
+ )
+ return _tiff_refusal(
+ data, start, stop, f"{image} whose Exif data", exif=True
+ )
+
+
+def _jpeg_exif_refusal(body: bytes, parts: list) -> Optional[str]:
+ """Why the Exif data Pillow joins from ``parts`` is refused, or None.
+
+ Pillow keeps the first ``Exif\\0\\0`` segment whole and appends the rest
+ without their header. One segment is walked in place; several are
+ joined once, within `_MAX_JPEG_EXIF_BYTES`, as Pillow's walk will see
+ them.
+ """
+ if len(parts) == 1:
+ data, (start, stop) = body, parts[0]
+ else:
+ first, *rest = parts
+ data = body[first[0] : first[1]] + b"".join(
+ body[a + 6 : b] for a, b in rest
+ )
+ start, stop = 0, len(data)
+ return _exif_refusal(data, start, stop, "a JPEG image")
+
+
+def _jpeg_segment(body: bytes, pos: int, walk: _JpegWalk) -> int:
+ """Walk the marker or padding byte at ``pos``; the offset after it.
+
+ Steps as Pillow's ``JpegImageFile._open`` does: a stray byte, a fill
+ byte (0xFF before another 0xFF) or a stuffed 0xFF00 is padding; a
+ standalone marker is two bytes; any other known marker is followed by a
+ segment whose two-byte length is read and checked against the body.
+ Returns -1 after the first scan's header (SOS), where Pillow's open
+ stops. Raises `_MalformedImage` past the body or at a marker Pillow
+ would refuse, and also (failing closed) at a segment length of 0 or 1,
+ which no valid segment has: there Pillow reads an empty segment and
+ goes on after the length, so the walk does not mirror it.
+ """
+ end = len(body)
+ if pos + 1 >= end:
+ raise _MalformedImage("truncated before the first scan")
+ marker = body[pos + 1]
+ if body[pos] != 0xFF or marker == 0xFF:
+ walk.padding += 1
+ return pos + 1
+ if marker == 0x00:
+ walk.padding += 1
+ return pos + 2
+ walk.segments += 1
+ if marker in _JPEG_STANDALONE_MARKERS:
+ return pos + 2
+ if marker not in _JPEG_SEGMENT_MARKERS:
+ raise _MalformedImage(f"unknown marker 0xFF{marker:02X}")
+ if pos + 4 > end:
+ raise _MalformedImage("truncated before the first scan")
+ length = (body[pos + 2] << 8) | body[pos + 3]
+ start, stop = pos + 4, pos + 2 + length
+ if length < 2:
+ raise _MalformedImage(f"segment length {length}")
+ if stop > end:
+ raise _MalformedImage("truncated before the first scan")
+ if marker in _JPEG_FRAME_MARKERS:
+ walk.frames += 1
+ if marker == 0xDA: # start of scan
+ walk.scans = 1
+ walk.scan_data = stop
+ return -1
+ if marker == 0xE1 and body.startswith(b"Exif\x00\x00", start, stop):
+ walk.exif.append((start, stop))
+ walk.exif_bytes += stop - start - (6 if len(walk.exif) > 1 else 0)
+ elif marker == 0xE2 and body.startswith(b"MPF\x00", start, stop):
+ walk.refusal = _tiff_refusal(
+ body, start + 4, stop, "a JPEG image whose MPF data", exif=False
+ )
+ return stop
+
+
+def _jpeg_scans(body: bytes, pos: int, walk: _JpegWalk) -> None:
+ """Count the markers from ``pos``, the first scan's data, to EOI.
+
+ Steps over entropy-coded data as libjpeg does (`_JPEG_SCAN_MARKER`),
+ then over each marker: a segment by its length (libjpeg skips at least
+ the two length bytes), any other marker as two bytes. Counts every
+ marker against `_MAX_JPEG_SEGMENTS` and every SOS against
+ `_MAX_JPEG_SCANS`, and stops at EOI, at the end of the body, at a
+ segment cut short or once a cap is passed. Where libjpeg would stop at
+ an error instead, this walk goes on, so it counts no fewer scans.
+ """
+ end = len(body)
+ while walk.over_cap() is None:
+ found = _JPEG_SCAN_MARKER.search(body, pos)
+ if found is None:
+ return
+ pos = found.start()
+ marker = body[pos + 1]
+ if marker == 0xD9: # end of image: libjpeg reads no further
+ return
+ walk.segments += 1
+ if marker not in _JPEG_SEGMENT_MARKERS:
+ pos += 2
+ continue
+ if pos + 4 > end:
+ return
+ if marker == 0xDA:
+ walk.scans += 1
+ pos += 2 + max((body[pos + 2] << 8) | body[pos + 3], 2)
+
+
+def _walk_jpeg(body: bytes, walk: _JpegWalk) -> Optional[str]:
+ """`_jpeg_structure_refusal`'s walk: a cap a body is past, or None."""
+ pos = 2 # Pillow's open starts at the 0xFF after SOI
+ while pos >= 0:
+ pos = _jpeg_segment(body, pos, walk)
+ reason = walk.over_cap()
+ if reason is not None:
+ return reason
+ _jpeg_scans(body, walk.scan_data, walk)
+ reason = walk.over_cap()
+ if reason is not None:
+ return reason
+ if walk.exif:
+ return _jpeg_exif_refusal(body, walk.exif)
+ return None
+
+
+def _jpeg_structure_refusal(
+ body: bytes, walk: Optional[_JpegWalk] = None
+) -> Optional[str]:
+ """Why a JPEG body's header is refused, or None if it is not.
+
+ ``walk``, if given, is left holding what the walk counted (its
+ ``scans`` for `_jpeg_budget_charge`).
+
+ Walks the marker segments from SOI to the first scan (SOS) by offsets,
+ stepping over padding as Pillow does, then the markers between scans to
+ EOI as libjpeg's decoder finds them (`_jpeg_scans`). Refuses a header
+ past `_MAX_JPEG_SEGMENTS`, `_MAX_JPEG_PADDING_BYTES`,
+ `_MAX_JPEG_FRAME_HEADERS`, `_MAX_JPEG_EXIF_SEGMENTS`,
+ `_MAX_JPEG_EXIF_BYTES` or `_MAX_JPEG_EXIF_HEADERS`, an image past
+ `_MAX_JPEG_SCANS` or (with the header's) `_MAX_JPEG_SEGMENTS`, Exif or
+ MPF data whose TIFF directories pass `_MAX_TIFF_IFD_ENTRIES`,
+ `_MAX_TIFF_IFD_DATA_BYTES` or `_MAX_TIFF_IFD_NUMBERS`, and (failing
+ closed) a header cut short before the first scan or holding a marker
+ Pillow would refuse. Every step advances past a counted byte or
+ segment, or (in entropy-coded data) is a regular-expression search, so
+ the walk is linear and bounded by the caps.
+ """
+ try:
+ return _walk_jpeg(body, _JpegWalk() if walk is None else walk)
+ except _MalformedImage as exc:
+ return f"a JPEG image whose header is unreadable ({exc})"
+
+
+def _jpeg_budget_charge(pixels: int, scans: int) -> int:
+ """What a JPEG of ``pixels`` (MCU-padded) and ``scans`` scans is charged
+ against the export's pixel budget: its pixels, scaled by its scans past
+ `_JPEG_BUDGET_SCANS` (libjpeg passes over the image once per scan)."""
+ return pixels * max(scans, _JPEG_BUDGET_SCANS) // _JPEG_BUDGET_SCANS
+
+
+def _png_text_key(body: bytes, start: int, stop: int) -> bytes:
+ """The keyword the text chunk ``body[start:stop]`` maps to in Pillow's
+ ``info``.
+
+ Pillow's ``chunk_tEXt``, ``chunk_zTXt`` and ``chunk_iTXt`` split the
+ chunk at its first NUL; ``tEXt`` and ``zTXt`` fall back to the whole
+ chunk as the keyword when there is none (their "broken tEXt tags"), and
+ ``iTXt`` stores nothing its header cannot split. The walk keys every
+ flavour the same way, and refuses an ``exif`` keyword even in an
+ unsplittable ``iTXt`` chunk Pillow would drop -- erring in the safe
+ direction only.
+ """
+ sep = body.find(b"\0", start, stop)
+ if sep < 0:
+ return body[start:stop]
+ return body[start:sep]
+
+
+def _png_itxt_payload(body: bytes, start: int, stop: int) -> Optional[tuple]:
+ """Where ``chunk_iTXt`` decompresses its text from, or None if it does
+ not decompress (or would store nothing at all).
+
+ After the keyword and its NUL come a compression flag and method, then
+ the language and translated keyword each NUL-terminated, then the text,
+ a zlib stream when the flag is set and the method is 0. Mirrors
+ Pillow's parse: a chunk whose header does not split this way stores
+ nothing and costs no decompression.
+ """
+ sep = body.find(b"\0", start, stop)
+ if sep < 0 or sep + 3 > stop:
+ return None
+ compressed, method = body[sep + 1], body[sep + 2]
+ lang_end = body.find(b"\0", sep + 3, stop)
+ if lang_end < 0:
+ return None
+ text = body.find(b"\0", lang_end + 1, stop)
+ if text < 0:
+ return None
+ if compressed == 0 or method != 0:
+ return None
+ return text + 1, stop
+
+
+def _png_inflated_bytes(
+ body: bytes, start: int, stop: int, left: int
+) -> Optional[int]:
+ """What decompressing the zlib stream ``body[start:stop]`` is charged,
+ or None if that is more than ``left``.
+
+ Decompresses it a step at a time, as `_inflate` does: each step takes
+ in at most `_INFLATE_INPUT_CHUNK_BYTES` and puts out at most
+ `_RESOURCE_READ_CHUNK_BYTES`, and never more than ``left + 1`` bytes
+ in all (never 0, which zlib reads as no limit). Each step is charged
+ what it puts out as it returns, so what a stream puts out before zlib
+ rejects it is charged too. A step zlib rejects returns nothing (CPython
+ discards its output), so it is charged the most it may put out, and the
+ stream ends there. The count stops one byte past ``left``, so the work
+ is bounded by ``left`` plus the compressed bytes taken in, which the
+ body bounds. Pillow decompresses each such chunk (``chunk_iCCP``,
+ ``chunk_zTXt``, ``chunk_iTXt``) in one call of at most ``MAX_TEXT_CHUNK``
+ and swallows a ``zlib.error``, so it decompresses no more of the stream
+ than this charges. The charge is the stream's decompressed size when
+ zlib accepts all of it; a payload zlib rejects outright, before any
+ output, is charged a whole step.
+ """
+ inflater = zlib.decompressobj()
+ view = memoryview(body)
+ pos = start
+ pending = b""
+ charged = 0
+ while not inflater.eof:
+ if pending:
+ piece = pending
+ else:
+ piece = view[pos : min(pos + _INFLATE_INPUT_CHUNK_BYTES, stop)]
+ pos += len(piece)
+ most = min(_RESOURCE_READ_CHUNK_BYTES, left + 1 - charged)
+ try:
+ out = inflater.decompress(piece, most)
+ except zlib.error:
+ charged += most
+ break
+ charged += len(out)
+ if charged > left or (not out and not piece):
+ break
+ pending = inflater.unconsumed_tail
+ return charged if charged <= left else None
+
+
+def _png_structure_refusal(body: bytes) -> Optional[str]:
+ """Why a PNG body's chunk structure is refused, or None if it is not.
+
+ Walks the chunks after the signature by their lengths to IEND, the end
+ of the body or a chunk cut short (which Pillow's reader cannot read
+ either), and applies `_exif_refusal` to every chunk Pillow stores as
+ ``info["exif"]``: ``eXIf``, to which Pillow prepends an
+ ``Exif\\0\\0`` header, and ``tEXt`` keyed ``exif``, whose value it
+ stores as is. Refuses outright a ``zTXt`` or ``iTXt`` chunk keyed
+ ``exif``, whatever its value: Pillow decodes that value to text, which
+ ``getexif`` hands to ``Exif.load`` as text (a TypeError there today,
+ which WeasyPrint turns into a dropped image), and the walk relies on
+ none of that rather than on what ``Exif.load`` rejects. A text chunk
+ keyed ``Raw profile type exif`` is left alone: WeasyPrint never decodes
+ it (see `_MAX_EXIF_CHUNKS`). Refuses a PNG past `_MAX_PNG_CHUNKS` or
+ `_MAX_EXIF_CHUNKS`, and one whose compressed metadata (``iCCP``,
+ ``zTXt``, compressed ``iTXt``) is charged more than
+ `_MAX_PNG_DECOMPRESSED_BYTES` in all (`_png_inflated_bytes`).
+
+ Each step advances past a counted chunk, and each payload that
+ decompresses is decompressed once here, a step at a time and no further
+ than one byte past what is left of `_MAX_PNG_DECOMPRESSED_BYTES`, so the
+ walk is bounded by the caps. So is Pillow's decompression of the same
+ chunks in each open of an accepted PNG (the size probe, WeasyPrint's
+ open and its re-opens in ``get_x_object``), however they compress or
+ fail: it decompresses no chunk past what the walk charged it.
+ """
+ end = len(body)
+ pos = len(_PNG_SIGNATURE)
+ chunks = exif = inflated = 0
+ while pos + 8 <= end:
+ chunks += 1
+ if chunks > _MAX_PNG_CHUNKS:
+ return f"a PNG image with more than {_MAX_PNG_CHUNKS} chunks"
+ length, kind = struct.unpack_from(">L4s", body, pos)
+ start = pos + 8
+ stop = start + length
+ if kind == b"IEND" or stop > end:
+ return None
+ headers = None
+ pump = None # the payload Pillow decompresses, where it decompresses
+ if kind == b"eXIf":
+ headers = 1
+ elif kind == b"tEXt" and body.startswith(b"exif\x00", start, stop):
+ headers, start = 0, start + 5
+ elif kind == b"iCCP":
+ # A keyword, a NUL, a compression-method byte, then the profile
+ # as a zlib stream (Pillow's chunk_iCCP).
+ sep = body.find(b"\0", start, stop)
+ comp = start if sep < 0 else sep + 1
+ pump = (comp + 1, stop) if comp < stop and body[comp] == 0 else None
+ elif kind in _PNG_TEXT_CHUNK_KINDS:
+ key = _png_text_key(body, start, stop)
+ if key == b"exif" and kind != b"tEXt":
+ # A zTXt or iTXt value keyed exif is decoded to text and
+ # handed to Exif.load as text; refused rather than relied
+ # on (see the docstring).
+ which = "an" if kind == b"iTXt" else "a"
+ return (
+ f"a PNG image with Exif in {which} {kind.decode()} chunk "
+ f"keyed {key.decode('latin-1')!r}"
+ )
+ if kind == b"zTXt":
+ # A keyword, a NUL, a compression-method byte, then the text
+ # as a zlib stream (Pillow's chunk_zTXt).
+ sep = body.find(b"\0", start, stop)
+ pump = (
+ (sep + 2, stop)
+ if sep >= 0 and body[sep + 1 : sep + 2] == b"\0"
+ else None
+ )
+ elif kind == b"iTXt":
+ # (tEXt stores its value as is: nothing to decompress.)
+ pump = _png_itxt_payload(body, start, stop)
+ if pump is not None:
+ more = _png_inflated_bytes(
+ body, pump[0], pump[1], _MAX_PNG_DECOMPRESSED_BYTES - inflated
+ )
+ if more is None:
+ return (
+ "a PNG image whose metadata chunks decompress to more "
+ f"than {_MAX_PNG_DECOMPRESSED_BYTES} bytes"
+ )
+ inflated += more
+ if headers is not None:
+ exif += 1
+ if exif > _MAX_EXIF_CHUNKS:
+ return (
+ f"a PNG image with more than {_MAX_EXIF_CHUNKS} Exif chunks"
+ )
+ reason = _exif_refusal(body, start, stop, "a PNG image", headers)
+ if reason is not None:
+ return reason
+ pos = stop + 4 # the chunk's CRC
+ return None
+
+
+def _webp_structure_refusal(body: bytes) -> Optional[str]:
+ """Why a WebP body's Exif data is refused, or None if it is not.
+
+ Walks the RIFF chunks after the 12-byte header to the end of the body
+ or a chunk cut short. libwebp's demuxer (1.6.0, ``ParseVP8XChunks``)
+ steps over each chunk by its even-padded size except ``ANMF``, whose
+ payload it enters (``ParseAnimationFrame`` reads the 16-byte frame
+ header, ``StoreFrame`` the frame's image chunks) and from where it goes
+ on parsing chunks as if at the top level. It does check the ``ANMF``
+ size (rejecting one under 16 bytes, or frame image chunks that overrun
+ it or the file); this walk ignores that size and enters every ``ANMF``,
+ whatever the VP8X flags, so it visits every position the demuxer does
+ and some it would reject. Applies
+ `_exif_refusal` to every ``EXIF`` chunk (Pillow stores the first the
+ demuxer keeps as ``info["exif"]``, as is), whether or not the demuxer
+ would keep it. Refuses a WebP past `_MAX_WEBP_CHUNKS` or
+ `_MAX_EXIF_CHUNKS`. Each step advances past a counted chunk, so the
+ walk is linear and bounded by the caps.
+ """
+ end = len(body)
+ pos = 12
+ chunks = exif = 0
+ while pos + 8 <= end:
+ chunks += 1
+ if chunks > _MAX_WEBP_CHUNKS:
+ return f"a WebP image with more than {_MAX_WEBP_CHUNKS} chunks"
+ kind, length = struct.unpack_from("<4sL", body, pos)
+ start = pos + 8
+ stop = start + length
+ if kind == b"ANMF":
+ pos = start + 16 # the frame header; its chunks follow
+ continue
+ if stop > end:
+ return None
+ if kind == b"EXIF":
+ exif += 1
+ if exif > _MAX_EXIF_CHUNKS:
+ return (
+ f"a WebP image with more than {_MAX_EXIF_CHUNKS} "
+ "Exif chunks"
+ )
+ reason = _exif_refusal(body, start, stop, "a WebP image")
+ if reason is not None:
+ return reason
+ pos = stop + (length & 1)
+ return None
+
+
class _MalformedFont(ValueError):
"""A font container `_font_refusal` cannot read within its caps."""
@@ -836,15 +1858,29 @@ def _refuse_unbounded_resource(body: bytes, url) -> None:
cannot be read within bounds (`_font_refusal`);
- a Mac resource-fork (dfont) font, which HarfBuzz also reads tables
from but this guard does not parse;
+ - a GIF or JPEG whose block or marker structure is past the
+ `_MAX_GIF_*` or `_MAX_JPEG_*`/`_MAX_TIFF_*` caps or cannot be walked
+ (`_gif_structure_refusal`, `_jpeg_structure_refusal`), a PNG with a
+ ``zTXt``/``iTXt`` chunk keyed ``exif``, or a PNG or WebP whose
+ chunks or Exif data are past `_MAX_PNG_CHUNKS`, `_MAX_WEBP_CHUNKS`,
+ `_MAX_EXIF_CHUNKS` or the Exif caps, or whose compressed metadata
+ decompresses past `_MAX_PNG_DECOMPRESSED_BYTES` (as
+ `_png_inflated_bytes` charges it)
+ (`_png_structure_refusal`, `_webp_structure_refusal`), checked before
+ Pillow parses it;
- a raster image whose format is not allow-listed;
- - a raster image whose header declares more than `MAX_PDF_IMAGE_PIXELS`;
+ - a raster image whose header declares more than `MAX_PDF_IMAGE_PIXELS`
+ (a JPEG: its MCU-padded area);
- an allow-listed image once the export's `MAX_PDF_EXPORT_IMAGE_PIXELS`
- decode budget is spent. Each accepted image is charged its declared
- pixels against that budget, so many images that are cheap on the wire
+ decode budget is spent. Each accepted image is charged its pixels
+ against that budget (declared; a JPEG its MCU-padded area, scaled by its
+ scans past `_JPEG_BUDGET_SCANS`: `_declared_image_pixels`,
+ `_jpeg_budget_charge`), so many images that are cheap on the wire
(a flat colour, a simple chart) but costly to decode cannot add up to
unbounded total decode work. WeasyPrint keeps no raw image resident --
its `RasterImage` retains only re-encoded, compressed bytes and decodes
- one image at a time -- so this bounds decode *work*, not resident RAM.
+ one image at a time -- so this bounds decode work (in pixels of
+ ordinary decoding), not resident RAM.
Everything else -- SVG, an ICC colour profile, a stylesheet, a TTF/OTF
font with outline glyphs only, plain text -- passes. The byte cap bounds
@@ -865,6 +1901,22 @@ def _refuse_unbounded_resource(body: bytes, url) -> None:
reason = _font_refusal(body)
if reason is not None:
_refuse_image_or_font(url, reason)
+ # Before any Pillow parse, the size probe's included: Pillow's GIF and
+ # JPEG header parsers, and its Exif loading for JPEG, PNG and WebP, are
+ # superlinear in some structures (see the _MAX_GIF_*, _MAX_JPEG_* and
+ # _MAX_TIFF_* caps).
+ reason = None
+ jpeg = _JpegWalk()
+ if body[:6] in _GIF_SIGNATURES:
+ reason = _gif_structure_refusal(body)
+ elif body[:3] == _JPEG_SIGNATURE:
+ reason = _jpeg_structure_refusal(body, jpeg)
+ elif body[:8] == _PNG_SIGNATURE:
+ reason = _png_structure_refusal(body)
+ elif body[:4] == b"RIFF" and body[8:12] == b"WEBP":
+ reason = _webp_structure_refusal(body)
+ if reason is not None:
+ _refuse_image_or_font(url, reason)
fmt = _pillow_raster_format(body)
if fmt is None:
if magic == _RESOURCE_FORK_FONT_TAG:
@@ -891,8 +1943,11 @@ def _refuse_unbounded_resource(body: bytes, url) -> None:
f"a {pixels}-pixel {fmt} image, over the "
f"{MAX_PDF_IMAGE_PIXELS}-pixel per-image limit",
)
+ charge = pixels
+ if fmt == "JPEG":
+ charge = _jpeg_budget_charge(pixels, jpeg.scans)
budget = _export_resource_budget.get()
- if budget is not None and not budget.charge_image_pixels(pixels):
+ if budget is not None and not budget.charge_image_pixels(charge):
# Warn once per export, not once per image: a report can reference any
# number. Every over-budget image is still refused (and dropped).
if not budget.image_budget_reported:
@@ -935,7 +1990,9 @@ class _BoundedBodyProcessor(urllib.request.BaseHandler):
the work WeasyPrint does on the body afterwards. So the read, charged
body is then passed to `_refuse_unbounded_resource`, which refuses a
compressed web font, a font with colour-bitmap or SVG glyph tables (or
- an unreadable table directory), a raster image that is not an
+ an unreadable table directory), a GIF, JPEG, PNG or WebP whose
+ structure is past its pre-scan's caps or (GIF, JPEG) unreadable, a
+ raster image that is not an
allow-listed format
or declares more than `MAX_PDF_IMAGE_PIXELS`, and an allow-listed image
once the export's `MAX_PDF_EXPORT_IMAGE_PIXELS` decode budget is spent
diff --git a/tests/web/services/test_pdf_resource_size_limits.py b/tests/web/services/test_pdf_resource_size_limits.py
index e880dc42fa..4d8537696f 100644
--- a/tests/web/services/test_pdf_resource_size_limits.py
+++ b/tests/web/services/test_pdf_resource_size_limits.py
@@ -29,6 +29,7 @@ import socket
import struct
import sys
import threading
+import time
import urllib.error
import urllib.request
import warnings
@@ -268,6 +269,21 @@ def _gif_declaring(width: int, height: int) -> bytes:
return bytes(gif)
+def _jpeg_with_sampling(width: int, height: int, sampling) -> bytes:
+ """A Pillow RGB JPEG with its frame header's per-component sampling
+ bytes (horizontal factor in the high nibble) set to ``sampling``."""
+ from PIL import Image
+
+ out = io.BytesIO()
+ Image.new("RGB", (width, height)).save(out, "JPEG", subsampling=0)
+ jpeg = bytearray(out.getvalue())
+ at = jpeg.index(b"\xff\xc0")
+ assert jpeg[at + 9] == len(sampling)
+ for i, factors in enumerate(sampling):
+ jpeg[at + 11 + 3 * i] = factors
+ return bytes(jpeg)
+
+
def _jpeg_declaring(width: int, height: int) -> bytes:
"""A real 2x2 JPEG with the size in its SOF frame header patched."""
jpeg = _tiny("JPEG")
@@ -1351,6 +1367,59 @@ class TestExportImageDecodeBudget:
assert start == pdf_service.MAX_PDF_EXPORT_IMAGE_PIXELS
assert start - budget.image_pixels == 1234 * 567
+ @pytest.mark.parametrize(
+ ("sampling", "charged"),
+ [
+ ((0x11, 0x11, 0x11), 24 * 8),
+ ((0x21, 0x11, 0x11), 32 * 8),
+ ((0x22, 0x11, 0x11), 32 * 16),
+ # The largest factors need not be the first component's.
+ ((0x11, 0x22, 0x11), 32 * 16),
+ ((0x11, 0x11, 0x12), 24 * 16),
+ ],
+ ids=["4:4:4", "4:2:2", "4:2:0", "chroma-2x2", "third-1x2"],
+ )
+ def test_a_jpeg_charges_its_area_in_whole_mcus(
+ self, origin, sampling, charged
+ ):
+ # libjpeg decodes whole MCUs (8x8 blocks times the largest sampling
+ # factors of any component), so a 17x1 JPEG costs 24x8 to 32x16
+ # pixels of decoding.
+ body = _jpeg_with_sampling(17, 1, sampling)
+ origin.add("/img.jpg", body, headers={"Content-Type": "image/jpeg"})
+ budget = pdf_service._ResourceBudget(16 * MIB)
+ start = budget.image_pixels
+ token = pdf_service._export_resource_budget.set(budget)
+ try:
+ pdf_service._safe_url_fetcher(ORIGIN + "/img.jpg").close()
+ finally:
+ pdf_service._export_resource_budget.reset(token)
+
+ assert start - budget.image_pixels == charged
+
+ @pytest.mark.parametrize(
+ ("scans", "charged"), [(1, 64), (10, 64), (20, 128), (64, 409)]
+ )
+ def test_a_jpeg_with_many_scans_is_charged_per_scan(
+ self, origin, scans, charged
+ ):
+ # A 1x1 JPEG decodes one 8x8 MCU per scan; past ten scans, each
+ # adds a tenth of its pixels to the charge.
+ origin.add(
+ "/img.jpg",
+ _jpeg_with_scans(scans),
+ headers={"Content-Type": "image/jpeg"},
+ )
+ budget = pdf_service._ResourceBudget(16 * MIB)
+ start = budget.image_pixels
+ token = pdf_service._export_resource_budget.set(budget)
+ try:
+ pdf_service._safe_url_fetcher(ORIGIN + "/img.jpg").close()
+ finally:
+ pdf_service._export_resource_budget.reset(token)
+
+ assert start - budget.image_pixels == charged
+
def test_images_past_the_export_pixel_budget_are_refused(self, origin):
for i in range(3):
origin.add(
@@ -1592,6 +1661,22 @@ class TestPillowFormatBoundary:
pdf_service._safe_url_fetcher(ORIGIN + "/body")
factory.assert_not_called()
+ def test_a_sniffer_that_raises_an_unexpected_error_fails_closed(self):
+ # Image.open lets a sniffer raise anything but SyntaxError,
+ # IndexError, TypeError and struct.error out of the whole open
+ # rather than try the next plugin; the probe fails closed under that
+ # format's name instead of classifying the body some other way.
+ from PIL import Image
+
+ Image.init()
+ factory, accept = Image.OPEN["BMP"]
+
+ def raising(prefix):
+ raise ValueError("sniffer broke")
+
+ with patch.dict(Image.OPEN, {"BMP": (factory, raising)}, clear=True):
+ assert pdf_service._pillow_raster_format(b"not an image") == "BMP"
+
@pytest.mark.parametrize(
"body",
[
@@ -1613,6 +1698,24 @@ class TestPillowFormatBoundary:
class TestHeaderOnlyFactories:
+ @pytest.mark.parametrize("error", [OSError, OverflowError])
+ def test_header_factory_failures_use_the_resource_refusal(
+ self, origin, pdf_logs, error
+ ):
+ from PIL import Image
+
+ Image.init()
+ factory = Mock(side_effect=error("unavailable header"))
+ origin.add("/resource", b"ordinary body")
+ with (
+ patch.dict(Image.OPEN, {"IMT": (factory, None)}),
+ pytest.raises(pdf_service.UnsupportedPDFResourceError),
+ ):
+ pdf_service._safe_url_fetcher(ORIGIN + "/resource")
+ factory.assert_called_once()
+ assert any("Refused a IMT image" in line for line in pdf_logs)
+ assert not any("unavailable header" in line for line in pdf_logs)
+
def test_the_reviewed_format_sets_are_not_widened(self):
# Widening any of these runs a factory, or accepts a format, that
# no one reviewed for decoding on open; it needs that review first.
@@ -1669,6 +1772,1850 @@ class TestHeaderOnlyFactories:
assert len(refusals) == 1, pdf_logs
+# A 1x1 logical screen without a global colour table, and a 1x1 frame whose
+# image data is one 2-byte sub-block: the smallest GIF parts Pillow opens.
+_GIF_SCREEN = b"GIF89a" + struct.pack("<HHBBB", 1, 1, 0, 0, 0)
+_GIF_FRAME = b",\x00\x00\x00\x00\x01\x00\x01\x00\x00" + b"\x02\x02\x44\x01\x00"
+
+
+def _gif(*blocks: bytes) -> bytes:
+ """A GIF of ``blocks`` between the logical screen and the trailer."""
+ return _GIF_SCREEN + b"".join(blocks) + b";"
+
+
+def _gif_extension(label: int, sub_blocks: Iterable[bytes]) -> bytes:
+ """An extension block: introducer, label, data sub-blocks, terminator."""
+ data = b"".join(bytes([len(block)]) + block for block in sub_blocks)
+ return b"\x21" + bytes([label]) + data + b"\x00"
+
+
+def _comment(*sub_blocks: bytes) -> bytes:
+ return _gif_extension(0xFE, sub_blocks)
+
+
+def _saved_gif(**params) -> bytes:
+ from PIL import Image
+
+ out = io.BytesIO()
+ colours = [(255, 0, 0), (0, 255, 0), (0, 0, 255)]
+ frames = [Image.new("RGB", (8, 8), colour) for colour in colours]
+ if params.pop("animated", False):
+ params.update(save_all=True, append_images=frames[1:], duration=40)
+ frames[0].save(out, "GIF", **params)
+ return out.getvalue()
+
+
+def _pillow_reads_the_size(body: bytes) -> bool:
+ """Whether the size probe's GIF factory alone would accept ``body``."""
+ from PIL import Image
+
+ Image.init()
+ try:
+ with Image.OPEN["GIF"][0](io.BytesIO(body), "") as image:
+ return min(image.size) > 0
+ except Exception:
+ return False
+
+
+class TestGifBlockStructure:
+ """Pillow's GIF parser takes a Python step per block, and Pillow 12.3's
+ joins comment sub-blocks by repeated concatenation, so its header parse
+ is quadratic in their number (a 1 MiB body of one-byte comment
+ sub-blocks costs seconds per parse); 13.0.0 joins them once. The size
+ probe and WeasyPrint each parse the header. `_gif_structure_refusal`
+ walks a GIF's blocks by offsets before Pillow parses any of it, and
+ refuses one past the ``_MAX_GIF_*`` caps or one it cannot walk.
+
+ Each fixture past a cap, and each cut image Pillow would still open,
+ declares a 1x1 image whose header Pillow reads (asserted with
+ `_pillow_reads_the_size`), so only the pre-scan refuses it. Most of the
+ truncated and malformed fixtures Pillow cannot read either.
+ """
+
+ def _accepted(self, origin, body: bytes) -> None:
+ origin.add("/image.gif", body, headers={"Content-Type": "image/gif"})
+ resource = pdf_service._safe_url_fetcher(ORIGIN + "/image.gif")
+ try:
+ assert resource.read() == body
+ finally:
+ resource.close()
+
+ def _refused(self, origin, body: bytes) -> str:
+ origin.add("/image.gif", body, headers={"Content-Type": "image/gif"})
+ with pytest.raises(pdf_service.UnsupportedPDFResourceError) as refused:
+ pdf_service._safe_url_fetcher(ORIGIN + "/image.gif")
+ return str(refused.value)
+
+ def test_many_comment_sub_blocks_are_refused_before_pillow_parses(
+ self, origin
+ ):
+ from PIL import Image
+
+ # 64 Ki one-byte comment sub-blocks, 16 times the cap. Pillow's
+ # factory would accept the 1x1 header; it must not be run at all.
+ body = _gif(_comment(*[b"A"] * (64 * 1024)), _GIF_FRAME)
+ assert _pillow_reads_the_size(body)
+ Image.init()
+ factory, accept = Image.OPEN["GIF"]
+ watched = Mock(wraps=factory)
+
+ started = time.perf_counter()
+ with patch.dict(Image.OPEN, {"GIF": (watched, accept)}):
+ reason = self._refused(origin, body)
+ elapsed = time.perf_counter() - started
+
+ assert "comment blocks" in reason
+ watched.assert_not_called()
+ # The walk stops at the cap: far under a second; 10 s is only a
+ # backstop against a walk that is itself superlinear.
+ assert elapsed < 10
+
+ def test_too_many_frames_are_refused(self, origin):
+ cap = pdf_service._MAX_GIF_FRAMES
+ body = _gif(*[_GIF_FRAME] * (cap + 1))
+ assert _pillow_reads_the_size(body)
+
+ assert f"more than {cap} frames" in self._refused(origin, body)
+
+ def test_frames_up_to_the_cap_are_accepted(self, origin):
+ self._accepted(
+ origin, _gif(*[_GIF_FRAME] * pdf_service._MAX_GIF_FRAMES)
+ )
+
+ @pytest.mark.parametrize(
+ "body",
+ [
+ pytest.param(bytes(_tiny("GIF", "P")), id="static"),
+ pytest.param(
+ _saved_gif(animated=True, loop=0), id="animated-looping"
+ ),
+ pytest.param(
+ _saved_gif(comment=b"Made with a charting tool. " * 40),
+ id="modest-comment",
+ ),
+ pytest.param(
+ _gif(
+ _comment(*[b"c" * 128] * 512),
+ _GIF_FRAME,
+ ),
+ id="comment-bytes-at-the-cap",
+ ),
+ pytest.param(
+ bytes(_tiny("GIF", "P"))[:-1], id="no-trailer-after-a-frame"
+ ),
+ pytest.param(
+ bytes(_tiny("GIF", "P")) + b"after the trailer",
+ id="data-after-the-trailer",
+ ),
+ pytest.param(
+ _gif(
+ _gif_extension(
+ 0xFF,
+ [b"A"] * (pdf_service._MAX_GIF_EXTENSION_BLOCKS - 1),
+ ),
+ _GIF_FRAME,
+ ),
+ id="extension-blocks-at-the-cap",
+ ),
+ pytest.param(
+ _gif(
+ *[_comment()] * pdf_service._MAX_GIF_COMMENT_BLOCKS,
+ _GIF_FRAME,
+ ),
+ id="comment-blocks-at-the-cap",
+ ),
+ pytest.param(
+ # A descriptor, its sub-blocks and the trailer: the cap.
+ _gif(
+ b",\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02"
+ + b"\x01\x00" * (pdf_service._MAX_GIF_BLOCKS - 2)
+ + b"\x00"
+ ),
+ id="blocks-at-the-cap",
+ ),
+ ],
+ )
+ def test_ordinary_gifs_are_accepted(self, origin, body):
+ self._accepted(origin, body)
+
+ @pytest.mark.parametrize(
+ "body",
+ [
+ pytest.param(
+ _GIF_SCREEN + _GIF_FRAME + b"\x00;", id="stray-byte-at-the-end"
+ ),
+ pytest.param(_GIF_SCREEN + _GIF_FRAME + b"\r\n", id="crlf-trailer"),
+ pytest.param(
+ _GIF_SCREEN + _GIF_FRAME + b"\x00\x00", id="zero-trailer"
+ ),
+ pytest.param(
+ _GIF_SCREEN + _GIF_FRAME + b"junk after the frame",
+ id="junk-after-the-first-frame",
+ ),
+ pytest.param(
+ _GIF_SCREEN + _GIF_FRAME + _GIF_FRAME[:12],
+ id="cut-inside-the-second-frame",
+ ),
+ ],
+ )
+ def test_what_follows_the_first_frame_is_not_refused(self, origin, body):
+ # WeasyPrint draws frame 0 only, and Pillow reads nothing past it,
+ # so a body it cannot walk after one complete frame is accepted.
+ assert _pillow_reads_the_size(body)
+
+ self._accepted(origin, body)
+
+ @pytest.mark.parametrize(
+ ("body", "reason"),
+ [
+ pytest.param(
+ _gif(
+ _comment(*[b"c" * 255] * 258),
+ _GIF_FRAME,
+ ),
+ "bytes of comments",
+ id="comment-bytes",
+ ),
+ pytest.param(
+ _gif(
+ *[_comment()] * (pdf_service._MAX_GIF_COMMENT_BLOCKS + 1),
+ _GIF_FRAME,
+ ),
+ "comment blocks",
+ id="empty-comment-extensions",
+ ),
+ pytest.param(
+ _gif(
+ _gif_extension(
+ 0xFF,
+ [b"A"] * pdf_service._MAX_GIF_EXTENSION_BLOCKS,
+ ),
+ _GIF_FRAME,
+ ),
+ "extension blocks",
+ id="application-sub-blocks",
+ ),
+ pytest.param(
+ _gif(
+ b",\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02"
+ + b"\x01\x00" * pdf_service._MAX_GIF_BLOCKS
+ + b"\x00"
+ ),
+ f"more than {pdf_service._MAX_GIF_BLOCKS} blocks",
+ id="image-data-sub-blocks",
+ ),
+ ],
+ )
+ def test_a_gif_past_a_block_cap_is_refused(self, origin, body, reason):
+ assert _pillow_reads_the_size(body)
+
+ assert reason in self._refused(origin, body)
+
+ @pytest.mark.parametrize(
+ "body",
+ [
+ pytest.param(
+ _GIF_SCREEN + _GIF_FRAME[:12], id="in-image-data-sub-block"
+ ),
+ pytest.param(_GIF_SCREEN + _comment(b"note")[:-3], id="in-comment"),
+ pytest.param(
+ # Flags declare a 256-entry (768-byte) global colour table.
+ b"GIF89a" + struct.pack("<HHBBB", 1, 1, 0x87, 0, 0) + bytes(99),
+ id="in-colour-table",
+ ),
+ pytest.param(_GIF_SCREEN + _GIF_FRAME[:6], id="in-descriptor"),
+ pytest.param(_GIF_SCREEN[:10], id="in-screen-descriptor"),
+ pytest.param(
+ # Ends right after a whole sub-block, before its terminator.
+ _GIF_SCREEN + _GIF_FRAME[:14],
+ id="at-a-sub-block-boundary",
+ ),
+ ],
+ )
+ def test_a_truncated_gif_is_refused(self, origin, body):
+ assert "truncated" in self._refused(origin, body)
+
+ def test_a_cut_image_pillow_would_still_open_is_refused(self, origin):
+ # Pillow's header parse stops at the first image descriptor, so it
+ # reads the size of a body cut inside the image data; the pre-scan
+ # walks the image data too.
+ body = bytes(_tiny("GIF", "P"))[:-4]
+ assert _pillow_reads_the_size(body)
+
+ assert "truncated" in self._refused(origin, body)
+
+ @pytest.mark.parametrize(
+ ("body", "reason"),
+ [
+ pytest.param(
+ _gif(b"\x00", _GIF_FRAME),
+ "unknown block 0x00",
+ id="unknown-block-before-the-first-frame",
+ ),
+ pytest.param(_gif(), "no image", id="no-image"),
+ ],
+ )
+ def test_a_malformed_gif_is_refused(self, origin, body, reason):
+ assert reason in self._refused(origin, body)
+
+ def test_the_caps_the_comments_state(self):
+ # The comments in pdf_service quote these and the reasoning behind
+ # them; a change here must change those too.
+ assert pdf_service._MAX_GIF_FRAMES == 16384
+ assert pdf_service._MAX_GIF_BLOCKS == 256 * 1024
+ assert pdf_service._MAX_GIF_EXTENSION_BLOCKS == 64 * 1024
+ assert pdf_service._MAX_GIF_COMMENT_BLOCKS == 4096
+ assert pdf_service._MAX_GIF_COMMENT_BYTES == 64 * 1024
+ # "over nine minutes at 30 frames a second"
+ assert pdf_service._MAX_GIF_FRAMES / 30 / 60 > 9
+ # 255-byte image sub-blocks filling the resource cap, plus four
+ # blocks per frame at the frame cap (descriptor, graphic control
+ # extension and its sub-block, an image-data sub-block), fit within
+ # half the block cap.
+ image_sub_blocks = pdf_service.MAX_PDF_RESOURCE_BYTES // 256
+ per_frame = 4 * pdf_service._MAX_GIF_FRAMES
+ assert 2 * (image_sub_blocks + per_frame) <= pdf_service._MAX_GIF_BLOCKS
+
+
+# A 1x1 baseline frame header and a scan header followed by stand-in
+# entropy-coded data: all Pillow's open reads of a JPEG past its other
+# marker segments.
+_JPEG_SOF = (
+ b"\xff\xc0" + struct.pack(">HBHHB", 11, 8, 1, 1, 1) + b"\x01\x11\x00"
+)
+_JPEG_SOS = (
+ b"\xff\xda\x00\x08\x01\x01\x00\x00\x3f\x00" + bytes(16) + b"\xff\xd9"
+)
+
+
+def _jpeg_marker_segment(marker: int, payload: bytes) -> bytes:
+ return (
+ b"\xff"
+ + bytes([marker])
+ + struct.pack(">H", len(payload) + 2)
+ + payload
+ )
+
+
+def _jpeg(*segments: bytes) -> bytes:
+ """SOI, ``segments``, then a 1x1 frame header and a scan."""
+ return b"\xff\xd8" + b"".join(segments) + _JPEG_SOF + _JPEG_SOS
+
+
+def _exif(payload: bytes = b"A") -> bytes:
+ return _jpeg_marker_segment(0xE1, b"Exif\x00\x00" + payload)
+
+
+def _tiff(*directories, pad: int = 0, header: bytes = b"II*\x00") -> bytes:
+ """TIFF data: the header, then ``directories`` in order.
+
+ Each directory is a list of ``(tag, type, count, value)`` entries; the
+ first starts at offset 8, right after the header. ``pad`` zero bytes
+ follow, for entries whose data point back into the TIFF data. The byte
+ order follows ``header``: big-endian for ``MM``, else little-endian.
+ """
+ order = ">" if header.startswith(b"MM") else "<"
+ out = header + struct.pack(order + "L", 8)
+ for entries in directories:
+ out += struct.pack(order + "H", len(entries))
+ out += b"".join(struct.pack(order + "HHLL", *e) for e in entries)
+ out += struct.pack(order + "L", 0)
+ return out + bytes(pad)
+
+
+def _ifd_size(entries: int) -> int:
+ return 2 + 12 * entries + 4
+
+
+def _saved_jpeg(fmt: str = "JPEG", **params) -> bytes:
+ from PIL import Image
+
+ out = io.BytesIO()
+ image = Image.new("RGB", (16, 16), (200, 10, 10))
+ if fmt == "MPO":
+ second = Image.new("RGB", (16, 16), (10, 200, 10))
+ params.update(save_all=True, append_images=[second])
+ image.save(out, fmt, **params)
+ return out.getvalue()
+
+
+def _camera_exif(description_size: int = 64) -> bytes:
+ """Exif with an orientation, Exif and GPS directories and a long text."""
+ from PIL import Image
+
+ exif = Image.Exif()
+ exif[0x010F] = "Maker"
+ exif[0x0112] = 6
+ exif[0x010E] = "d" * description_size
+ exif.get_ifd(0x8769)[0x9003] = "2024:01:01 00:00:00"
+ exif.get_ifd(0x8825)[0x0001] = "N"
+ return exif.tobytes()
+
+
+def _jpeg_pillow_reads_the_size(body: bytes) -> bool:
+ """Whether the size probe's JPEG factory alone would accept ``body``."""
+ from PIL import Image
+
+ Image.init()
+ try:
+ with Image.OPEN["JPEG"][0](io.BytesIO(body), "") as image:
+ return min(image.size) > 0
+ except Exception:
+ return False
+
+
+_EXIF_BYTES_CAP = 256 * 1024
+
+
+def _exif_totalling(total: int) -> list:
+ """Exif segments whose payloads Pillow joins to ``total`` bytes: the
+ first in full, each later one without its 6-byte header."""
+ segments = [_exif(bytes(65533 - 6))]
+ left = total - 65533
+ while left > 0:
+ size = min(left, 65533 - 6)
+ segments.append(_exif(bytes(size)))
+ left -= size
+ return segments
+
+
+def _directory_pointer(tag: int) -> bytes:
+ """Exif whose IFD0 points through ``tag`` to a directory one entry past
+ the entry cap (unknown type 0, so Pillow reads but skips them); for the
+ Interop pointer, through an Exif directory."""
+ cap = pdf_service._MAX_TIFF_IFD_ENTRIES
+ big = [(0x100 + i, 0, 1, 0) for i in range(cap)]
+ if tag == 0xA005:
+ exif_at = 8 + _ifd_size(1)
+ target = exif_at + _ifd_size(1)
+ return _tiff([(0x8769, 4, 1, exif_at)], [(0xA005, 4, 1, target)], big)
+ return _tiff([(tag, 4, 1, 8 + _ifd_size(1))], big)
+
+
+def _directory_pointer_form(tag: int, kind: int, items: int) -> bytes:
+ """A nested directory reached through an alternate integer representation.
+
+ The pointer's first value is the directory's offset: in the entry
+ itself if its values fit in four bytes, else in data after the TIFF
+ directories. That data is offset from the TIFF data's start; in a JPEG
+ whose first segment holds the Exif, the TIFF data starts 12 bytes in
+ (SOI, the APP1 header, ``Exif\\0\\0``). So the 12 bytes before the data
+ hold a decoy pointing at an empty directory: a reader that took the
+ offset from the start of the body would follow it and find nothing to
+ refuse.
+ """
+ cap = pdf_service._MAX_TIFF_IFD_ENTRIES
+ nested = [(0x100 + i, 0, 1, 0) for i in range(cap)]
+ target = 8 + _ifd_size(1) * (2 if tag == 0xA005 else 1)
+ decoy_at = target + _ifd_size(cap)
+ data_at = decoy_at + 12
+ empty_at = data_at + 8
+ inline = items * pdf_service._TIFF_TYPE_SIZES[kind] <= 4
+ value = target if inline else data_at
+ pointer = [(tag, kind, items, value)]
+ directories = [pointer, nested]
+ if tag == 0xA005:
+ directories.insert(0, [(0x8769, 4, 1, 8 + _ifd_size(1))])
+ data = _tiff(*directories)
+ assert len(data) == decoy_at
+ if kind == 16:
+ data += struct.pack("<Q", empty_at) + bytes(4)
+ data += struct.pack("<Q", target)
+ elif kind == 4:
+ data += struct.pack("<LL", empty_at, 0) + bytes(4)
+ data += struct.pack("<LL", target, 0)
+ else:
+ data += bytes(20)
+ return data + struct.pack("<HL", 0, 0)
+
+
+def _caps(name: str) -> int:
+ return getattr(pdf_service, name)
+
+
+# For each cap: a body at the cap (accepted) and one past it (refused), by
+# the number the cap counts.
+_JPEG_CAP_FIXTURES = {
+ "_MAX_JPEG_SEGMENTS": (
+ # COM segments, then the frame and scan headers.
+ lambda n: _jpeg(*[_jpeg_marker_segment(0xFE, b"c")] * (n - 2)),
+ "marker segments",
+ ),
+ "_MAX_JPEG_PADDING_BYTES": (
+ lambda n: _jpeg(b"\xff" * n),
+ "padding bytes",
+ ),
+ "_MAX_JPEG_EXIF_SEGMENTS": (
+ lambda n: _jpeg(*[_exif()] * n),
+ "Exif segments",
+ ),
+ "_MAX_JPEG_EXIF_BYTES": (
+ lambda n: _jpeg(*_exif_totalling(n)),
+ "bytes of Exif",
+ ),
+ "_MAX_JPEG_EXIF_HEADERS": (
+ # Pillow keeps the first segment's own header: n in all.
+ lambda n: _jpeg(_exif(b"Exif\x00\x00" * (n - 1) + _tiff([]))),
+ "repeats its header",
+ ),
+ "_MAX_TIFF_IFD_ENTRIES": (
+ lambda n: _jpeg(_exif(_tiff([(0x100 + i, 0, 1, 0) for i in range(n)]))),
+ "directory entries",
+ ),
+ "_MAX_TIFF_IFD_DATA_BYTES": (
+ # UNDEFINED entries of 2048 bytes each, reading padding after IFD0.
+ lambda n: _jpeg(
+ _exif(
+ _tiff(
+ [(0x100 + i, 7, 2048, 8) for i in range(n // 2048 - 1)]
+ + [(0x200, 7, 2048 + n % 2048, 8)],
+ pad=4096,
+ )
+ )
+ ),
+ "bytes of tag data",
+ ),
+ "_MAX_TIFF_IFD_NUMBERS": (
+ # SHORT entries of 1024 values each.
+ lambda n: _jpeg(
+ _exif(
+ _tiff(
+ [(0x100 + i, 3, 1024, 8) for i in range(n // 1024 - 1)]
+ + [(0x200, 3, 1024 + n % 1024, 8)],
+ pad=4096,
+ )
+ )
+ ),
+ "numeric tag values",
+ ),
+}
+
+
+_JPEG_SCAN_HEADER = b"\xff\xda\x00\x08\x01\x01\x00\x00\x3f\x00"
+
+
+def _jpeg_with_scans(
+ scans: int,
+ entropy: bytes = bytes(16),
+ between: bytes = b"",
+ fill: bytes = b"",
+) -> bytes:
+ """SOI, a 1x1 frame header, then ``scans`` scans of ``entropy`` data,
+ each followed by ``between`` (tables or other segments), then EOI.
+ ``fill`` (0xFF fill bytes) goes before each scan's header."""
+ scan = fill + _JPEG_SCAN_HEADER + entropy + between
+ return b"\xff\xd8" + _JPEG_SOF + scan * scans + b"\xff\xd9"
+
+
+# Every frame-header marker Pillow parses with its SOF handler (SOF0-3,
+# 5-7, 9-11, 13-15 and DHP), and every TIFF header it reads as a classic
+# directory; listed here so that dropping one from pdf_service fails.
+_JPEG_FRAME_MARKERS = [
+ *range(0xC0, 0xC4),
+ *range(0xC5, 0xC8),
+ *range(0xC9, 0xCC),
+ *range(0xCD, 0xD0),
+ 0xDE,
+]
+_TIFF_HEADERS = [b"II*\x00", b"II\x00*", b"MM\x00*", b"MM*\x00", b"MM\x00+"]
+_TIFF_HEADER_IDS = ["II*0", "II0*", "MM0*", "MM*0", "MM0+"]
+
+
+def _split_exif(tiff: bytes, cut: int) -> list:
+ """``tiff`` as two Exif segments, cut ``cut`` bytes in: Pillow joins
+ the second's payload, without its header, to the first."""
+ return [_exif(tiff[:cut]), _exif(tiff[cut:])]
+
+
+class TestJpegHeaderStructure:
+ """Pillow's JPEG open is superlinear in parts of the header before the
+ first scan: it joins ``Exif\\0\\0`` APP1 segments with
+ ``info["exif"] += s[6:]`` (quadratic in their number; Pillow 12.3 then
+ also strips repeated Exif headers one slice at a time), and it reads
+ and decodes the TIFF directories of the Exif and MPF data however many
+ tags point at the same bytes (one 64 KiB MPF segment: seconds). The
+ size probe and WeasyPrint each open it, and WeasyPrint's
+ ``exif_transpose`` decodes the Exif directories again.
+ `_jpeg_structure_refusal` walks the header by offsets before Pillow
+ parses any of it, and refuses one past the ``_MAX_JPEG_*``/
+ ``_MAX_TIFF_*`` caps or one it cannot walk.
+ """
+
+ def _accepted(self, origin, body: bytes) -> None:
+ origin.add("/image.jpg", body, headers={"Content-Type": "image/jpeg"})
+ resource = pdf_service._safe_url_fetcher(ORIGIN + "/image.jpg")
+ try:
+ assert resource.read() == body
+ finally:
+ resource.close()
+
+ def _refused(self, origin, body: bytes) -> str:
+ origin.add("/image.jpg", body, headers={"Content-Type": "image/jpeg"})
+ with pytest.raises(pdf_service.UnsupportedPDFResourceError) as refused:
+ pdf_service._safe_url_fetcher(ORIGIN + "/image.jpg")
+ return str(refused.value)
+
+ @pytest.mark.parametrize(
+ ("body", "reason"),
+ [
+ pytest.param(
+ # 160 Ki one-byte Exif segments: about 0.5 s per Pillow open.
+ _jpeg(*[_exif()] * (160 * 1024)),
+ "Exif segments",
+ id="exif-segment-flood",
+ ),
+ pytest.param(
+ # One MPF segment whose 1100 entries each declare the same
+ # 60 KB of SHORTs: about 2 s per Pillow open.
+ _jpeg(
+ _jpeg_marker_segment(
+ 0xE2,
+ b"MPF\x00"
+ + _tiff(
+ [(0x100 + i, 3, 30000, 8) for i in range(1100)]
+ ),
+ )
+ ),
+ "directory entries",
+ id="mpf-overlapping-tags",
+ ),
+ pytest.param(
+ # Decode time grows with pixels times scans.
+ _jpeg_with_scans(1000),
+ "scans",
+ id="progressive-scan-flood",
+ ),
+ pytest.param(
+ # Pillow keeps a tuple per declared component of each.
+ b"\xff\xd8" + _JPEG_SOF * 250 + _JPEG_SOS,
+ "frame headers",
+ id="frame-header-flood",
+ ),
+ ],
+ )
+ def test_a_costly_header_is_refused_before_pillow_parses(
+ self, origin, body, reason
+ ):
+ from PIL import Image
+
+ Image.init()
+ factory, accept = Image.OPEN["JPEG"]
+ watched = Mock(wraps=factory)
+
+ started = time.perf_counter()
+ with patch.dict(Image.OPEN, {"JPEG": (watched, accept)}):
+ refusal = self._refused(origin, body)
+ elapsed = time.perf_counter() - started
+
+ assert reason in refusal
+ watched.assert_not_called()
+ # The walk stops at the cap; 10 s is only a backstop against a walk
+ # that is itself superlinear.
+ assert elapsed < 10
+
+ @pytest.mark.parametrize(
+ "body",
+ [
+ pytest.param(bytes(_tiny("JPEG")), id="plain"),
+ pytest.param(_saved_jpeg(progressive=True), id="progressive"),
+ pytest.param(
+ _saved_jpeg(exif=_camera_exif(60000)), id="large-single-exif"
+ ),
+ pytest.param(
+ _saved_jpeg(exif=_camera_exif()), id="exif-gps-orientation"
+ ),
+ pytest.param(
+ _saved_jpeg("MPO", exif=_camera_exif()), id="mpo-app-segments"
+ ),
+ pytest.param(
+ _saved_jpeg(icc_profile=bytes(200_000)),
+ id="icc-profile-over-four-app2-segments",
+ ),
+ pytest.param(
+ _jpeg(b"\xff\xff\xff") + bytes(4096) + b"\xff\xd9",
+ id="fill-bytes-and-scan-data",
+ ),
+ ],
+ )
+ def test_ordinary_jpegs_are_accepted(self, origin, body):
+ assert _jpeg_pillow_reads_the_size(body)
+
+ self._accepted(origin, body)
+
+ @pytest.mark.parametrize("cap_name", sorted(_JPEG_CAP_FIXTURES))
+ def test_a_header_at_each_cap_is_accepted(self, origin, cap_name):
+ build, _ = _JPEG_CAP_FIXTURES[cap_name]
+ body = build(_caps(cap_name))
+ assert _jpeg_pillow_reads_the_size(body)
+
+ self._accepted(origin, body)
+
+ @pytest.mark.parametrize("cap_name", sorted(_JPEG_CAP_FIXTURES))
+ def test_a_header_one_past_each_cap_is_refused(self, origin, cap_name):
+ build, reason = _JPEG_CAP_FIXTURES[cap_name]
+ body = build(_caps(cap_name) + 1)
+ assert _jpeg_pillow_reads_the_size(body)
+
+ assert reason in self._refused(origin, body)
+
+ @pytest.mark.parametrize(
+ "pointer",
+ [0x8769, 0x8825, 0xA005],
+ ids=["exif-directory", "gps-directory", "interop-directory"],
+ )
+ def test_the_directories_exif_transpose_loads_are_counted(
+ self, origin, pointer
+ ):
+ # IFD0 alone is within the caps; the directory it points to is not.
+ body = _jpeg(_exif(_directory_pointer(pointer)))
+ assert _jpeg_pillow_reads_the_size(body)
+
+ assert "directory entries" in self._refused(origin, body)
+
+ @pytest.mark.parametrize("pointer", [0x8769, 0x8825, 0xA005])
+ @pytest.mark.parametrize(
+ "kind,items",
+ # SHORT, LONG, SBYTE, SSHORT, SLONG, IFD and LONG8: every integer
+ # type whose first value Pillow can follow as an offset.
+ [(3, 2), (4, 2), (6, 1), (8, 1), (9, 1), (13, 1), (16, 1)],
+ )
+ def test_directory_pointer_integer_representations(
+ self, origin, pointer, kind, items
+ ):
+ body = _jpeg(_exif(_directory_pointer_form(pointer, kind, items)))
+ assert _jpeg_pillow_reads_the_size(body)
+ assert "directory entries" in self._refused(origin, body)
+
+ @pytest.mark.parametrize("extra", [0, 1])
+ def test_signed_byte_values_count_against_numeric_budget(
+ self, origin, extra
+ ):
+ count = pdf_service._MAX_TIFF_IFD_NUMBERS + extra
+ body = _jpeg(_exif(_tiff([(0x100, 6, count, 8)], pad=count)))
+ assert _jpeg_pillow_reads_the_size(body)
+ if extra:
+ assert "numeric tag values" in self._refused(origin, body)
+ else:
+ self._accepted(origin, body)
+
+ @pytest.mark.parametrize("pointer", [0x8769, 0x8825, 0xA005])
+ @pytest.mark.parametrize("reverse", [False, True])
+ @pytest.mark.parametrize("nested_entries", [0, 4])
+ def test_repeated_directory_references_share_the_budget(
+ self, origin, monkeypatch, pointer, reverse, nested_entries
+ ):
+ monkeypatch.setattr(pdf_service, "_MAX_TIFF_IFD_ENTRIES", 4)
+ prefix = (
+ [[(0x8769, 4, 1, 8 + _ifd_size(1))]] if pointer == 0xA005 else []
+ )
+ empty_at = 8 + sum(_ifd_size(len(d)) for d in prefix) + _ifd_size(2)
+ offsets = [empty_at, empty_at + _ifd_size(0)]
+ if reverse:
+ offsets.reverse()
+ references = [(pointer, 4, 1, at) for at in offsets]
+ nested = [(0x100 + i, 0, 1, 0) for i in range(nested_entries)]
+ body = _jpeg(_exif(_tiff(*prefix, references, [], nested)))
+ assert _jpeg_pillow_reads_the_size(body)
+ if nested_entries:
+ assert "directory entries" in self._refused(origin, body)
+ else:
+ self._accepted(origin, body)
+
+ def test_exif_split_over_segments_is_walked_as_joined(self, origin):
+ # One directory one past the entry cap, its entries cut across two
+ # Exif segments: neither segment alone holds more than a few.
+ cap = pdf_service._MAX_TIFF_IFD_ENTRIES
+ tiff = _tiff([(0x100 + i, 0, 1, 0) for i in range(cap + 1)])
+ body = _jpeg(*_split_exif(tiff, 100))
+ assert _jpeg_pillow_reads_the_size(body)
+
+ assert "directory entries" in self._refused(origin, body)
+
+ def test_a_pointer_past_joined_exif_data_is_not_followed(self, origin):
+ # The Exif directory pointer's (out-of-line) value lies past the end
+ # of the joined data: Pillow cannot read it, nor does the walk.
+ tiff = _tiff([(0x8769, 4, 2, 0x10000)])
+ body = _jpeg(*_split_exif(tiff, 12))
+ assert _jpeg_pillow_reads_the_size(body)
+
+ self._accepted(origin, body)
+
+ @pytest.mark.parametrize(
+ "padding",
+ [b"\xff", b"\xff\x00", b"\x00"],
+ ids=["fill-byte", "stuffed-ff00", "stray-byte"],
+ )
+ def test_every_kind_of_padding_counts(self, origin, padding):
+ # After a comment segment, since a JPEG body starts 0xFFD8FF.
+ cap = pdf_service._MAX_JPEG_PADDING_BYTES
+ comment = _jpeg_marker_segment(0xFE, b"c")
+ at_cap = _jpeg(comment, padding * cap)
+ assert _jpeg_pillow_reads_the_size(at_cap)
+ self._accepted(origin, at_cap)
+
+ past_cap = _jpeg(comment, padding * (cap + 1))
+ assert _jpeg_pillow_reads_the_size(past_cap)
+ assert "padding bytes" in self._refused(origin, past_cap)
+
+ @pytest.mark.parametrize(
+ "marker",
+ [0xD0, 0xD7, 0xF0, 0xFD],
+ ids=["rst0", "rst7", "jpg0", "jpg13"],
+ )
+ def test_standalone_markers_are_two_bytes_and_count(self, origin, marker):
+ # Pillow reads no length after these. Each is a marker segment.
+ cap = pdf_service._MAX_JPEG_SEGMENTS
+ at_cap = _jpeg(bytes([0xFF, marker]) * (cap - 2))
+ assert _jpeg_pillow_reads_the_size(at_cap)
+ self._accepted(origin, at_cap)
+
+ past_cap = _jpeg(bytes([0xFF, marker]) * (cap - 1))
+ assert "marker segments" in self._refused(origin, past_cap)
+
+ @pytest.mark.parametrize(
+ "entry",
+ [(0x100, 7, 0x7FFFFFFF, 8), (0x100, 3, 0x3FFFFFFF, 8)],
+ ids=["undefined-bytes", "shorts"],
+ )
+ def test_tag_data_is_charged_only_what_the_exif_holds(self, origin, entry):
+ # A count far past the data: Pillow reads what there is, so only
+ # that is charged.
+ body = _jpeg(_exif(_tiff([entry], pad=64)))
+ assert _jpeg_pillow_reads_the_size(body)
+
+ self._accepted(origin, body)
+
+ def test_numbers_held_in_the_entries_count(self, origin):
+ # Four SBYTEs fit in an entry itself; Pillow decodes them all the
+ # same. 1023 such entries hold 4092 numbers, and one out-of-line
+ # entry of five SHORTs takes the total past the cap.
+ entries = [(0x100 + i, 6, 4, 0) for i in range(1023)]
+ tiff = _tiff(entries + [(0x500, 3, 5, 8)], pad=16)
+ assert 4 * 1023 + 5 == pdf_service._MAX_TIFF_IFD_NUMBERS + 1
+ body = _jpeg(_exif(tiff))
+ assert _jpeg_pillow_reads_the_size(body)
+
+ assert "numeric tag values" in self._refused(origin, body)
+
+ @pytest.mark.parametrize("header", _TIFF_HEADERS, ids=_TIFF_HEADER_IDS)
+ def test_every_classic_tiff_header_is_walked(self, origin, header):
+ cap = pdf_service._MAX_TIFF_IFD_ENTRIES
+ tiff = _tiff(
+ [(0x100 + i, 0, 1, 0) for i in range(cap + 1)], header=header
+ )
+ body = _jpeg(_exif(tiff))
+ assert _jpeg_pillow_reads_the_size(body)
+
+ assert "directory entries" in self._refused(origin, body)
+
+ def test_split_exif_is_joined_without_the_later_headers(self, origin):
+ # The split falls at the Exif directory IFD0 points to. Joined
+ # without the second segment's header, both directories hold one
+ # entry; joined with it, the pointer would land on that header and
+ # read the zero padding after it as hundreds of entries.
+ target = 8 + _ifd_size(1)
+ tiff = _tiff([(0x8769, 4, 1, target)], [(0x9000, 0, 1, 0)], pad=13000)
+ body = _jpeg(*_split_exif(tiff, target))
+ assert _jpeg_pillow_reads_the_size(body)
+
+ self._accepted(origin, body)
+
+ @pytest.mark.parametrize(
+ "marker",
+ _JPEG_FRAME_MARKERS,
+ ids=[f"{m:02x}" for m in _JPEG_FRAME_MARKERS],
+ )
+ def test_a_second_frame_header_is_refused(self, origin, marker):
+ second = bytes([0xFF, marker]) + _JPEG_SOF[2:]
+ body = _jpeg(second)
+ assert _jpeg_pillow_reads_the_size(body)
+
+ assert "frame headers" in self._refused(origin, body)
+
+ def test_scans_up_to_the_cap_are_accepted(self, origin):
+ # Stuffed 0xFF00 bytes and restart markers are scan data, and a
+ # table segment between scans is skipped whole, 0xFFDA in it or not.
+ cap = pdf_service._MAX_JPEG_SCANS
+ entropy = b"\x12\xff\x00\xff\xd3" * 16
+ table = _jpeg_marker_segment(0xFE, b"\xff\xda" * 8)
+ body = _jpeg_with_scans(cap, entropy, table, fill=b"\xff")
+ assert _jpeg_pillow_reads_the_size(body)
+
+ self._accepted(origin, body)
+
+ @pytest.mark.parametrize("fill", [b"", b"\xff", b"\xff\xff"])
+ def test_scans_past_the_cap_are_refused(self, origin, fill):
+ # Fill bytes before a marker do not hide it.
+ body = _jpeg_with_scans(pdf_service._MAX_JPEG_SCANS + 1, fill=fill)
+ assert _jpeg_pillow_reads_the_size(body)
+
+ assert "scans" in self._refused(origin, body)
+
+ def test_markers_between_scans_count_as_segments(self, origin):
+ cap = pdf_service._MAX_JPEG_SEGMENTS
+ comments = _jpeg_marker_segment(0xFE, b"c") * cap
+ body = _jpeg_with_scans(2, between=comments)
+ assert _jpeg_pillow_reads_the_size(body)
+
+ assert "marker segments" in self._refused(origin, body)
+
+ def test_what_follows_the_end_of_image_is_not_counted(self, origin):
+ # libjpeg stops at EOI, so a second image appended (as in MPO) or
+ # other trailing data is not decoded as this image's scans.
+ body = _jpeg_with_scans(pdf_service._MAX_JPEG_SCANS) + _jpeg_with_scans(
+ pdf_service._MAX_JPEG_SCANS
+ )
+
+ self._accepted(origin, body)
+
+ @pytest.mark.parametrize(
+ "body",
+ [
+ pytest.param(
+ b"\xff\xd8" + _exif(b"cut")[:-2], id="in-an-app-segment"
+ ),
+ pytest.param(b"\xff\xd8" + _JPEG_SOF, id="no-scan"),
+ pytest.param(
+ b"\xff\xd8" + _JPEG_SOF + _JPEG_SOS[:6], id="in-the-scan-header"
+ ),
+ pytest.param(b"\xff\xd8\xff", id="after-soi"),
+ ],
+ )
+ def test_a_header_cut_before_the_scan_is_refused(self, origin, body):
+ assert "truncated" in self._refused(origin, body)
+
+ @pytest.mark.parametrize(
+ ("body", "reason"),
+ [
+ pytest.param(
+ _jpeg(b"\xff\x01"), "unknown marker 0xFF01", id="unknown-marker"
+ ),
+ pytest.param(
+ _jpeg(b"\xff\xfe\x00\x01"),
+ "segment length 1",
+ id="short-segment-length",
+ ),
+ ],
+ )
+ def test_a_malformed_header_is_refused(self, origin, body, reason):
+ assert reason in self._refused(origin, body)
+
+ def test_the_caps_the_comments_state(self):
+ # The comments in pdf_service quote these and the reasoning behind
+ # them; a change here must change those too.
+ assert pdf_service._MAX_JPEG_SEGMENTS == 1024
+ assert pdf_service._MAX_JPEG_PADDING_BYTES == 4096
+ assert pdf_service._MAX_JPEG_EXIF_SEGMENTS == 16
+ assert pdf_service._MAX_JPEG_EXIF_BYTES == _EXIF_BYTES_CAP
+ assert pdf_service._MAX_JPEG_EXIF_HEADERS == 4
+ assert pdf_service._MAX_TIFF_IFD_ENTRIES == 1024
+ assert pdf_service._MAX_TIFF_IFD_DATA_BYTES == 128 * 1024
+ assert pdf_service._MAX_TIFF_IFD_NUMBERS == 4096
+ assert pdf_service._MAX_JPEG_FRAME_HEADERS == 1
+ assert sorted(pdf_service._JPEG_FRAME_MARKERS) == _JPEG_FRAME_MARKERS
+ assert sorted(pdf_service._TIFF_CLASSIC_HEADERS) == sorted(
+ _TIFF_HEADERS
+ )
+ assert pdf_service._MAX_JPEG_SCANS == 64
+ assert pdf_service._JPEG_BUDGET_SCANS == 10
+ # "Only 256 full-size segments fit in the 16 MiB resource cap"
+ assert pdf_service.MAX_PDF_RESOURCE_BYTES // (64 * 1024) == 256
+ # "256 KiB (four full segments)" and "128 KiB is twice one segment"
+ assert pdf_service._MAX_JPEG_EXIF_BYTES == 4 * 64 * 1024
+ assert pdf_service._MAX_TIFF_IFD_DATA_BYTES == 2 * 64 * 1024
+
+
+def _png_chunk(kind: bytes, data: bytes) -> bytes:
+ return (
+ struct.pack(">I", len(data))
+ + kind
+ + data
+ + struct.pack(">I", zlib.crc32(kind + data))
+ )
+
+
+def _png_text_chunk(
+ kind: bytes, key: bytes, value: bytes, compressed: bool = False
+) -> bytes:
+ """A ``tEXt``, ``zTXt`` or ``iTXt`` chunk in each flavour's wire form:
+ zTXt compresses its value, iTXt carries a language and translated key
+ (and compresses its value when ``compressed``)."""
+ if kind == b"tEXt":
+ return _png_chunk(kind, key + b"\0" + value)
+ if kind == b"zTXt":
+ return _png_chunk(kind, key + b"\0\x00" + zlib.compress(value))
+ flags = b"\x01\x00" if compressed else b"\x00\x00"
+ payload = zlib.compress(value) if compressed else value
+ return _png_chunk(kind, key + b"\0" + flags + b"en\x00\x00" + payload)
+
+
+def _png_iccp_chunk(profile: bytes) -> bytes:
+ return _png_chunk(b"iCCP", b"profile\x00\x00" + zlib.compress(profile))
+
+
+def _png_with_chunks(
+ *chunks: bytes, after_image: Iterable[bytes] = ()
+) -> bytes:
+ """A 1x1 greyscale PNG with ``chunks`` before its image data and
+ ``after_image`` after it (which Pillow reads when it loads the image)."""
+ ihdr = struct.pack(">IIBBBBB", 1, 1, 8, 0, 0, 0, 0)
+ return (
+ b"\x89PNG\r\n\x1a\n"
+ + _png_chunk(b"IHDR", ihdr)
+ + b"".join(chunks)
+ + _png_chunk(b"IDAT", zlib.compress(b"\x00\x00"))
+ + b"".join(after_image)
+ + _png_chunk(b"IEND", b"")
+ )
+
+
+def _saved_webp(exif: bytes = b"", **params) -> bytes:
+ from PIL import Image
+
+ out = io.BytesIO()
+ image = Image.new("RGB", (2, 2), (200, 10, 10))
+ image.save(out, "WEBP", exif=exif, **params)
+ return out.getvalue()
+
+
+def _with_webp_chunks(webp: bytes, *chunks: bytes) -> bytes:
+ """Extended-format ``webp`` with ``chunks`` appended, its RIFF size
+ updated and its Exif flag set (libwebp reads ``EXIF`` only with it)."""
+ assert webp[12:16] == b"VP8X"
+ body = bytearray(webp + b"".join(chunks))
+ body[4:8] = struct.pack("<L", len(body) - 8)
+ body[20] |= 0x08
+ return bytes(body)
+
+
+def _webp_chunk(kind: bytes, data: bytes) -> bytes:
+ return (
+ kind + struct.pack("<L", len(data)) + data + b"\x00" * (len(data) & 1)
+ )
+
+
+def _entries_past_the_cap() -> bytes:
+ cap = pdf_service._MAX_TIFF_IFD_ENTRIES
+ return _tiff([(0x100 + i, 0, 1, 0) for i in range(cap + 1)])
+
+
+def _pillow_exif(body: bytes) -> bytes:
+ """The Exif data Pillow holds for ``body`` once it has loaded it."""
+ from PIL import Image
+
+ with Image.open(io.BytesIO(body)) as image:
+ image.load()
+ return image.info["exif"]
+
+
+def _animated_webp_with_exif(
+ exif: bytes, where: str, frame: int = 0, animation_flag: bool = True
+) -> bytes:
+ """A three-frame animated WebP with an ``EXIF`` chunk holding ``exif``:
+ inside ``ANMF`` chunk number ``frame``, after its image data
+ (``in-frame``), or right after that chunk (``after-frame``). Without
+ ``animation_flag``, the VP8X animation flag is cleared (libwebp's
+ demuxer enters an ``ANMF`` chunk after ``ANIM`` either way)."""
+ from PIL import Image
+
+ out = io.BytesIO()
+ colors = ("red", "blue", "green")
+ frames = [Image.new("RGB", (4, 4), color) for color in colors]
+ frames[0].save(
+ out, "WEBP", save_all=True, append_images=frames[1:], lossless=True
+ )
+ webp, pos, chunks = out.getvalue(), 12, []
+ while pos + 8 <= len(webp):
+ kind, size = struct.unpack_from("<4sL", webp, pos)
+ chunks.append([kind, webp[pos + 8 : pos + 8 + size]])
+ pos += 8 + size + (size & 1)
+ frames_seen = 0
+ body = b""
+ for kind, data in chunks:
+ if kind == b"ANMF":
+ frames_seen += 1
+ if frames_seen == frame + 1:
+ if where == "in-frame":
+ data += _webp_chunk(b"EXIF", exif)
+ else:
+ body += _webp_chunk(kind, data)
+ kind, data = b"EXIF", exif
+ body += _webp_chunk(kind, data)
+ assert frames_seen == len(colors) > frame
+ webp = bytearray(_with_webp_chunks(webp[:12] + body))
+ if not animation_flag:
+ webp[20] &= ~0x02
+ return bytes(webp)
+
+
+def _pillow_loads_exif(body: bytes) -> bool:
+ """Whether Pillow opens ``body`` with Exif data, as WeasyPrint would."""
+ from PIL import Image
+
+ with Image.open(io.BytesIO(body)) as image:
+ image.load()
+ return "exif" in image.info
+
+
+def _short_entries(count: int) -> bytes:
+ """TIFF data with ``count`` entries Pillow's ``Exif`` read stores.
+
+ Each is one inline SHORT value, so the decode retains ``count`` tags
+ however large ``count`` is -- past `_MAX_TIFF_IFD_ENTRIES` at 1025."""
+ return _tiff([(0x100 + i, 3, 1, 0) for i in range(count)])
+
+
+def _raw_exif_profile(tiff: bytes) -> bytes:
+ """An ImageMagick raw profile of ``tiff`` Exif data: the text format
+ ``Image.getexif`` hex-decodes (everything after its third line)."""
+ hexed = tiff.hex()
+ lines = [hexed[i : i + 72] for i in range(0, len(hexed), 72)]
+ return ("\nexif\n%8d\n" % len(tiff) + "\n".join(lines)).encode("latin-1")
+
+
+def _png_raw_profile_chunk(kind: bytes, tiff: bytes) -> bytes:
+ """A ``kind`` text chunk (``tEXt``, ``zTXt`` or ``iTXt``) carrying a raw
+ Exif profile of ``tiff`` under the keyword ``Image.getexif`` reads it
+ from (the keyword is never compressed)."""
+ keyword = b"Raw profile type exif"
+ profile = _raw_exif_profile(tiff)
+ if kind == b"tEXt":
+ data = keyword + b"\x00" + profile
+ elif kind == b"zTXt":
+ data = keyword + b"\x00\x00" + zlib.compress(profile)
+ else:
+ data = keyword + b"\x00\x00\x00\x00\x00" + profile
+ return _png_chunk(kind, data)
+
+
+def _pillow_getexif(body: bytes) -> dict:
+ """The Exif tags ``Image.getexif`` reads from ``body``: what
+ ``exif_transpose`` decodes, every carrier included."""
+ from PIL import Image
+
+ with Image.open(io.BytesIO(body)) as image:
+ image.load()
+ return dict(image.getexif())
+
+
+def _saved_png(exif: bytes = b"") -> bytes:
+ """A PNG as Pillow writes one: an ``eXIf`` chunk when ``exif`` is
+ given, no text chunks either way."""
+ from PIL import Image
+
+ out = io.BytesIO()
+ image = Image.new("RGB", (2, 2), (200, 10, 10))
+ image.save(out, "PNG", **({"exif": exif} if exif else {}))
+ return out.getvalue()
+
+
+class TestPngAndWebpExif:
+ """WeasyPrint runs ``exif_transpose`` on every image with Exif data,
+ PNG (``eXIf``, or a ``tEXt`` chunk keyed ``exif``) and WebP (``EXIF``)
+ as well as JPEG, and Pillow loads it the same way for all three: it
+ strips leading ``Exif\\0\\0`` headers (Pillow 12.3 every one, a
+ slice at a time; 13.0.0 at most two) and reads the TIFF directories
+ however many tags share the same bytes.
+ `_png_structure_refusal` and `_webp_structure_refusal` find those chunks
+ and apply the same caps before Pillow parses the body; the tests below
+ sweep those carriers with ``getexif()`` as their oracle. Pillow's
+ ``Image.getexif`` reads one PNG carrier more, but only when neither is
+ present: a ``tEXt``, ``zTXt`` or ``iTXt`` chunk keyed ``Raw profile
+ type exif``, whose value it hex-decodes as an ImageMagick raw profile.
+ WeasyPrint transposes (its only ``getexif`` call on a PNG) only an
+ image that has an ``exif`` entry, so it never reads that carrier, and
+ the walk leaves it alone. A ``zTXt`` or ``iTXt`` chunk keyed ``exif``
+ is refused outright: Pillow stores its decoded text at
+ ``info["exif"]``, which ``getexif`` hands to ``Exif.load`` as text (a
+ TypeError there today), and the walk relies on none of that.
+ """
+
+ def _accepted(self, origin, body: bytes, kind: str) -> None:
+ origin.add("/image", body, headers={"Content-Type": f"image/{kind}"})
+ resource = pdf_service._safe_url_fetcher(ORIGIN + "/image")
+ try:
+ assert resource.read() == body
+ finally:
+ resource.close()
+
+ def _refused(self, origin, body: bytes, kind: str) -> str:
+ origin.add("/image", body, headers={"Content-Type": f"image/{kind}"})
+ with pytest.raises(pdf_service.UnsupportedPDFResourceError) as refused:
+ pdf_service._safe_url_fetcher(ORIGIN + "/image")
+ return str(refused.value)
+
+ @pytest.mark.parametrize(
+ ("body", "kind", "reason"),
+ [
+ pytest.param(
+ _png_with_chunks(_png_chunk(b"eXIf", _entries_past_the_cap())),
+ "png",
+ "a PNG image whose Exif data has more than",
+ id="png-exif",
+ ),
+ pytest.param(
+ _png_with_chunks(
+ _png_chunk(b"tEXt", b"exif\x00" + _entries_past_the_cap())
+ ),
+ "png",
+ "a PNG image whose Exif data has more than",
+ id="png-text-exif",
+ ),
+ pytest.param(
+ _png_with_chunks(
+ after_image=[_png_chunk(b"eXIf", _entries_past_the_cap())]
+ ),
+ "png",
+ "a PNG image whose Exif data has more than",
+ id="png-exif-after-image-data",
+ ),
+ pytest.param(
+ _saved_webp(_entries_past_the_cap()),
+ "webp",
+ "a WebP image whose Exif data has more than",
+ id="webp-exif",
+ ),
+ pytest.param(
+ # After an odd-sized chunk and its padding byte.
+ _with_webp_chunks(
+ _saved_webp(xmp=b"<x/> "),
+ _webp_chunk(b"EXIF", _entries_past_the_cap()),
+ ),
+ "webp",
+ "a WebP image whose Exif data has more than",
+ id="webp-exif-after-odd-chunk",
+ ),
+ ],
+ )
+ def test_exif_past_the_directory_caps_is_refused_before_pillow_parses(
+ self, origin, body, kind, reason
+ ):
+ from PIL import Image
+
+ assert _pillow_loads_exif(body)
+ Image.init()
+ fmt = kind.upper()
+ factory, accept = Image.OPEN[fmt]
+ watched = Mock(wraps=factory)
+
+ with patch.dict(Image.OPEN, {fmt: (watched, accept)}):
+ assert reason in self._refused(origin, body, kind)
+ watched.assert_not_called()
+
+ @pytest.mark.parametrize(
+ ("build", "kind"),
+ [
+ # Pillow puts one header in front of an eXIf chunk's data.
+ (
+ lambda n: _png_with_chunks(
+ _png_chunk(b"eXIf", b"Exif\x00\x00" * (n - 1))
+ ),
+ "png",
+ ),
+ # A tEXt value is stored as is: no header in front.
+ (
+ lambda n: _png_with_chunks(
+ _png_chunk(b"tEXt", b"exif\x00" + b"Exif\x00\x00" * n)
+ ),
+ "png",
+ ),
+ (lambda n: _saved_webp(b"Exif\x00\x00" * (n + 1)), "webp"),
+ ],
+ ids=["png", "png-text", "webp"],
+ )
+ def test_repeated_exif_headers_are_capped(self, origin, build, kind):
+ # Pillow's WebP writer drops one leading header of what it is given.
+ cap = pdf_service._MAX_JPEG_EXIF_HEADERS
+ self._accepted(origin, build(cap), kind)
+
+ assert "repeats its header" in self._refused(
+ origin, build(cap + 1), kind
+ )
+
+ @pytest.mark.parametrize(
+ ("body", "kind"),
+ [
+ pytest.param(
+ _png_with_chunks(*[_png_chunk(b"eXIf", _tiff([]))] * 5),
+ "png",
+ id="png",
+ ),
+ pytest.param(
+ _with_webp_chunks(
+ _saved_webp(_tiff([])),
+ *[_webp_chunk(b"EXIF", _tiff([]))] * 4,
+ ),
+ "webp",
+ id="webp",
+ ),
+ ],
+ )
+ def test_more_exif_chunks_than_the_cap_are_refused(
+ self, origin, body, kind
+ ):
+ assert "Exif chunks" in self._refused(origin, body, kind)
+
+ @pytest.mark.parametrize("oversized_first", [True, False])
+ def test_every_png_exif_chunk_is_checked(self, origin, oversized_first):
+ # Pillow keeps the last eXIf chunk; the walk checks both.
+ small, big = _tiff([(0x100, 0, 1, 0)]), _entries_past_the_cap()
+ first, second = (big, small) if oversized_first else (small, big)
+ body = _png_with_chunks(
+ _png_chunk(b"eXIf", first), _png_chunk(b"eXIf", second)
+ )
+ assert _pillow_exif(body) == b"Exif\x00\x00" + second
+
+ assert "directory entries" in self._refused(origin, body, "png")
+
+ @pytest.mark.parametrize("oversized_first", [True, False])
+ def test_every_webp_exif_chunk_is_checked(self, origin, oversized_first):
+ # libwebp's demuxer hands Pillow the first EXIF chunk; the walk
+ # checks both.
+ small, big = _tiff([(0x100, 0, 1, 0)]), _entries_past_the_cap()
+ first, second = (big, small) if oversized_first else (small, big)
+ body = _with_webp_chunks(
+ _saved_webp(first), _webp_chunk(b"EXIF", second)
+ )
+ assert _pillow_exif(body) == first
+
+ assert "directory entries" in self._refused(origin, body, "webp")
+
+ @pytest.mark.parametrize(
+ ("where", "frame", "animation_flag"),
+ [
+ ("in-frame", 0, True),
+ ("after-frame", 0, True),
+ ("in-frame", 1, True),
+ ("in-frame", 2, True),
+ ("in-frame", 0, False),
+ ],
+ ids=[
+ "in-frame",
+ "after-frame",
+ "in-second-frame",
+ "in-third-frame",
+ "in-frame-without-animation-flag",
+ ],
+ )
+ def test_exif_of_an_animated_webp_is_checked(
+ self, origin, where, frame, animation_flag
+ ):
+ # libwebp's demuxer reads a frame's image chunks inside its ANMF
+ # chunk, then goes on reading chunks from there, for every frame and
+ # whatever the animation flag, so an EXIF chunk inside any frame is
+ # the image's Exif data as much as one after it.
+ body = _animated_webp_with_exif(
+ _entries_past_the_cap(), where, frame, animation_flag
+ )
+ # Without the flag the demuxer still enters each frame, but keeps no
+ # frame, so Pillow cannot open the image; the walk does not depend
+ # on the flag either way.
+ if animation_flag:
+ assert _pillow_loads_exif(body)
+
+ assert "directory entries" in self._refused(origin, body, "webp")
+
+ def test_animated_webp_exif_within_the_caps_is_accepted(self, origin):
+ body = _animated_webp_with_exif(_camera_exif(), "in-frame")
+ assert _pillow_loads_exif(body)
+
+ self._accepted(origin, body, "webp")
+
+ def test_png_chunks_after_iend_are_not_read(self, origin):
+ # Pillow stops at IEND.
+ body = _png_with_chunks() + _png_chunk(b"eXIf", _entries_past_the_cap())
+
+ self._accepted(origin, body, "png")
+
+ def test_png_chunks_past_the_cap_are_refused(self, origin):
+ # IHDR, IDAT and IEND, and private chunks after the image data.
+ cap = pdf_service._MAX_PNG_CHUNKS
+ filler = _png_chunk(b"prIv", b"")
+ self._accepted(
+ origin, _png_with_chunks(after_image=[filler] * (cap - 3)), "png"
+ )
+
+ body = _png_with_chunks(after_image=[filler] * (cap - 2))
+ assert "chunks" in self._refused(origin, body, "png")
+
+ def test_webp_chunks_past_the_cap_are_refused(self, origin):
+ webp = _saved_webp(_tiff([]))
+ count = len(_webp_chunks(webp))
+ cap = pdf_service._MAX_WEBP_CHUNKS
+ filler = _webp_chunk(b"JUNK", b"")
+ at_cap = _with_webp_chunks(webp, *[filler] * (cap - count))
+ self._accepted(origin, at_cap, "webp")
+
+ past_cap = _with_webp_chunks(webp, *[filler] * (cap - count + 1))
+ assert "chunks" in self._refused(origin, past_cap, "webp")
+
+ @pytest.mark.parametrize(
+ ("body", "kind"),
+ [
+ pytest.param(_png_with_chunks(), "png", id="png"),
+ pytest.param(
+ _png_with_chunks(_png_chunk(b"eXIf", _camera_exif(60000))),
+ "png",
+ id="png-camera-exif",
+ ),
+ pytest.param(
+ _png_with_chunks(
+ _png_chunk(b"tEXt", b"Comment\x00exif\x00text")
+ ),
+ "png",
+ id="png-other-text",
+ ),
+ pytest.param(_saved_webp(), "webp", id="webp"),
+ pytest.param(
+ _saved_webp(_camera_exif(60000)), "webp", id="webp-camera-exif"
+ ),
+ ],
+ )
+ def test_ordinary_images_are_accepted(self, origin, body, kind):
+ self._accepted(origin, body, kind)
+
+ @pytest.mark.parametrize(
+ ("kind", "value"),
+ [
+ pytest.param(b"zTXt", _camera_exif(), id="ztxt"),
+ pytest.param(b"iTXt", b"pretend exif", id="itxt"),
+ ],
+ )
+ def test_text_keyed_exif_is_refused_not_relied_on(
+ self, origin, kind, value
+ ):
+ # Pillow stores a zTXt or iTXt value as text at info["exif"], which
+ # getexif hands to Exif.load as text: a TypeError there today (an
+ # image load failure inside WeasyPrint). The walk refuses the chunk
+ # before Pillow sees it rather than rely on any of that. (The iTXt
+ # value is text for Pillow to store at all; one that is not valid
+ # UTF-8 is stored nowhere.)
+ from PIL import Image
+
+ body = _png_with_chunks(_png_text_chunk(kind, b"exif", value))
+ with Image.open(io.BytesIO(body)) as image:
+ image.load()
+ with pytest.raises(TypeError):
+ image.getexif()
+
+ assert "keyed 'exif'" in self._refused(origin, body, "png")
+
+ @pytest.mark.parametrize("kind", [b"tEXt", b"zTXt", b"iTXt"])
+ def test_a_raw_exif_profile_is_never_decoded_so_is_accepted(
+ self, origin, kind
+ ):
+ # Pillow's getexif() does decode this carrier (5400 tags, far past
+ # the directory caps), but only for an image with no info["exif"],
+ # and WeasyPrint's orientation step -- its only getexif() call on a
+ # PNG -- runs only for an image with one. So the render never
+ # decodes it, and the image stays in the export (ImageMagick
+ # writes Exif this way, so many real PNGs carry it).
+ from PIL import Image
+ from weasyprint.images import rotate_pillow_image
+
+ tiff = _short_entries(5400)
+ body = _png_with_chunks(_png_raw_profile_chunk(kind, tiff))
+ assert len(_pillow_getexif(body)) == 5400
+ # A control the same spy sees: an eXIf chunk is transposed.
+ oriented = _png_with_chunks(_png_chunk(b"eXIf", _camera_exif()))
+
+ for image_body, loads in ((oriented, True), (body, False)):
+ with (
+ patch.object(Image.Exif, "load", autospec=True) as load,
+ Image.open(io.BytesIO(image_body)) as image,
+ ):
+ rotate_pillow_image(image, "from-image")
+ assert load.called is loads
+
+ self._accepted(origin, body, "png")
+
+ @pytest.mark.parametrize(
+ ("build", "kind", "reason"),
+ [
+ pytest.param(
+ lambda t: _png_with_chunks(_png_chunk(b"eXIf", t)),
+ "png",
+ "directory entries",
+ id="png-exif",
+ ),
+ pytest.param(
+ lambda t: _png_with_chunks(
+ _png_chunk(b"tEXt", b"exif\x00" + t)
+ ),
+ "png",
+ "directory entries",
+ id="png-text-exif",
+ ),
+ pytest.param(
+ lambda t: _saved_webp(t),
+ "webp",
+ "directory entries",
+ id="webp-exif",
+ ),
+ ],
+ )
+ def test_every_exif_carrier_the_renderer_reads_is_capped(
+ self, origin, build, kind, reason
+ ):
+ # getexif() is the oracle here, not info["exif"]: the decoder
+ # really reads this over-cap metadata through this carrier (and
+ # nothing through the same image without it), and the guard
+ # refuses the image before Pillow parses it.
+ count = pdf_service._MAX_TIFF_IFD_ENTRIES + 1
+ body = build(_short_entries(count))
+ assert len(_pillow_getexif(body)) == count
+ bare = _png_with_chunks() if kind == "png" else _saved_webp()
+ assert len(_pillow_getexif(bare)) == 0
+
+ assert reason in self._refused(origin, body, kind)
+ # Boundary honesty: the same carrier at the cap is accepted.
+ self._accepted(origin, build(_short_entries(count - 1)), kind)
+
+ def test_getexif_reads_no_further_exif_carrier(self):
+ # The sweep above covers the "exif" carriers and
+ # test_a_raw_exif_profile_is_never_decoded_so_is_accepted the raw
+ # profile; this executes that lookup and pins it, so a Pillow that
+ # learns another Exif carrier fails here first (checked against
+ # Pillow 12.3 and 13.0.0). The XMP keys it also reads hold at most
+ # one orientation number, no Exif.
+ from PIL import Image
+
+ seen = set()
+
+ class _Recording(dict):
+ def get(self, key, default=None):
+ seen.add(key)
+ return super().get(key, default)
+
+ def __contains__(self, key):
+ seen.add(key)
+ return super().__contains__(key)
+
+ def __getitem__(self, key):
+ seen.add(key)
+ return super().__getitem__(key)
+
+ with Image.open(io.BytesIO(_png_with_chunks())) as image:
+ image.load()
+ image.info = _Recording(image.info)
+ assert len(image.getexif()) == 0
+ carriers = {
+ key
+ for key in seen
+ if isinstance(key, str)
+ and ("exif" in key.lower() or "profile" in key.lower())
+ }
+ assert carriers == {"exif", "Raw profile type exif"}
+
+ def test_real_pillow_pngs_are_accepted(self, origin):
+ # No over-refusal: a PNG as Pillow writes one -- with its Exif in
+ # an eXIf chunk, or with none -- stays in the export.
+ plain = _saved_png()
+ assert len(_pillow_getexif(plain)) == 0
+
+ self._accepted(origin, plain, "png")
+ with_exif = _saved_png(_camera_exif())
+ assert len(_pillow_getexif(with_exif)) > 0
+
+ self._accepted(origin, with_exif, "png")
+
+ def test_the_caps_the_comments_state(self):
+ assert pdf_service._MAX_EXIF_CHUNKS == 4
+ assert pdf_service._MAX_PNG_CHUNKS == 64 * 1024
+ assert pdf_service._MAX_WEBP_CHUNKS == 64 * 1024
+ # "a PNG within the 16 MiB resource cap has a few thousand at most"
+ assert pdf_service.MAX_PDF_RESOURCE_BYTES // (8 * 1024) == 2048
+ # "4 MiB": what one accepted PNG's metadata chunks decompress to at
+ # most in each Pillow open (in the walk, at most one byte more).
+ assert pdf_service._MAX_PNG_DECOMPRESSED_BYTES == 4 * 1024 * 1024
+ # The walk keys the text chunks of exactly these flavours.
+ assert pdf_service._PNG_TEXT_CHUNK_KINDS == (b"tEXt", b"zTXt", b"iTXt")
+
+
+def _webp_chunks(webp: bytes) -> list:
+ """The four-character codes of ``webp``'s top-level chunks."""
+ kinds, pos = [], 12
+ while pos + 8 <= len(webp):
+ (size,) = struct.unpack_from("<L", webp, pos + 4)
+ kinds.append(webp[pos : pos + 4])
+ pos += 8 + size + (size & 1)
+ return kinds
+
+
+def _zlib_ending(data: bytes, ending: str) -> bytes:
+ """``data`` as a zlib stream: whole (``valid``), or one that puts out
+ all of ``data`` and then fails -- on a wrong Adler-32 checksum
+ (``checksum``) or on an invalid block after a sync flush (``block``)."""
+ if ending == "block":
+ compressor = zlib.compressobj(9)
+ flushed = compressor.compress(data) + compressor.flush(
+ zlib.Z_SYNC_FLUSH
+ )
+ return flushed + b"\xff" # final block of reserved type 3
+ stream = bytearray(zlib.compress(data, 9))
+ if ending == "checksum":
+ stream[-1] ^= 0xFF
+ return bytes(stream)
+
+
+def _png_zlib_chunk(kind: str, index: int, stream: bytes) -> bytes:
+ """An ``iccp``, ``ztxt`` or (compressed) ``itxt`` chunk whose payload
+ is the zlib ``stream`` as given; text chunks are keyed by ``index``."""
+ if kind == "iccp":
+ return _png_chunk(b"iCCP", b"profile\x00\x00" + stream)
+ key = f"t{index}".encode()
+ if kind == "ztxt":
+ return _png_chunk(b"zTXt", key + b"\x00\x00" + stream)
+ return _png_chunk(b"iTXt", key + b"\x00\x01\x00en\x00\x00" + stream)
+
+
+class TestPngTextAndProfileChunks:
+ """The work PNG's metadata chunks make Pillow do, and the Exif a text
+ chunk can carry. iCCP profiles and zTXt/compressed iTXt text decompress
+ their payload inside every Pillow open, which swallows a chunk's zlib
+ error (and, under ``LOAD_TRUNCATED_IMAGES``, its error past 1 MiB) and
+ goes on to the next chunk. The walk decompresses them first, a step at a
+ time, charging what each step puts out against
+ `_MAX_PNG_DECOMPRESSED_BYTES`, so no PNG drives unbounded decompression
+ in the decoder. A ``zTXt`` or ``iTXt`` chunk keyed ``exif`` is refused
+ before Pillow parses the body.
+ """
+
+ def _accepted(self, origin, body: bytes) -> None:
+ origin.add("/image", body, headers={"Content-Type": "image/png"})
+ resource = pdf_service._safe_url_fetcher(ORIGIN + "/image")
+ try:
+ assert resource.read() == body
+ finally:
+ resource.close()
+
+ def _refused(self, origin, body: bytes) -> str:
+ origin.add("/image", body, headers={"Content-Type": "image/png"})
+ with pytest.raises(pdf_service.UnsupportedPDFResourceError) as refused:
+ pdf_service._safe_url_fetcher(ORIGIN + "/image")
+ return str(refused.value)
+
+ def test_an_iccp_bomb_is_refused_before_pillow_parses(self, origin):
+ from PIL import Image
+
+ # The gate's cost probe: 400 one-kilobyte iCCP chunks decompressing
+ # to 1 MiB each -- 0.96 s of CPU inside one Pillow open, invisible
+ # to the pixel and chunk caps. Refused in the walk now, before any
+ # Pillow parse runs.
+ chunk = _png_iccp_chunk(bytes(1024 * 1024))
+ body = _png_with_chunks(*[chunk] * 400)
+ Image.init()
+ factory, accept = Image.OPEN["PNG"]
+ watched = Mock(wraps=factory)
+
+ with patch.dict(Image.OPEN, {"PNG": (watched, accept)}):
+ assert "decompress to more than" in self._refused(origin, body)
+ watched.assert_not_called()
+
+ @pytest.mark.parametrize("kind", ["iccp", "ztxt", "itxt"])
+ def test_the_decompression_cap_is_honest_at_the_boundary(
+ self, origin, kind
+ ):
+ # Eight chunks of an eighth of the cap decompress to exactly the
+ # cap; one decompressed byte past it is refused. The cap bounds the
+ # decompressed bytes whatever the chunks compress to.
+ cap = pdf_service._MAX_PNG_DECOMPRESSED_BYTES
+ assert cap % 8 == 0
+ eighth = cap // 8
+
+ def chunk(index: int, size: int) -> bytes:
+ zeros = bytes(size)
+ if kind == "iccp":
+ return _png_iccp_chunk(zeros)
+ if kind == "ztxt":
+ return _png_text_chunk(b"zTXt", f"t{index}".encode(), zeros)
+ return _png_text_chunk(b"iTXt", f"t{index}".encode(), zeros, True)
+
+ at = _png_with_chunks(*[chunk(i, eighth) for i in range(8)])
+ self._accepted(origin, at)
+
+ over = _png_with_chunks(
+ *[chunk(i, eighth) for i in range(8)], chunk(8, 1)
+ )
+ assert "decompress to more than" in self._refused(origin, over)
+
+ @pytest.mark.parametrize("ending", ["valid", "checksum", "block"])
+ @pytest.mark.parametrize("kind", ["iccp", "ztxt", "itxt"])
+ def test_what_a_chunk_puts_out_before_it_fails_is_charged(
+ self, origin, kind, ending
+ ):
+ # Eight chunks of 1 MiB less a byte each: within Pillow's per-chunk
+ # MAX_TEXT_CHUNK, twice the cap together. Pillow decompresses each
+ # whole before it reaches the bad checksum or block, swallows the
+ # zlib.error and opens the image, so a walk that charged a failing
+ # chunk nothing would accept a body that makes every Pillow open
+ # decompress all of it (a 16 MiB body of such chunks: gigabytes).
+ # The valid streams are the control, refused as before.
+ from PIL import Image
+
+ stream = _zlib_ending(bytes(MIB - 1), ending)
+ if ending != "valid":
+ with pytest.raises(zlib.error):
+ zlib.decompress(stream)
+ body = _png_with_chunks(
+ *[_png_zlib_chunk(kind, i, stream) for i in range(8)]
+ )
+ with Image.open(io.BytesIO(body)) as image:
+ image.load()
+ assert image.size == (1, 1)
+ Image.init()
+ factory, accept = Image.OPEN["PNG"]
+ watched = Mock(wraps=factory)
+
+ with patch.dict(Image.OPEN, {"PNG": (watched, accept)}):
+ assert "decompress to more than" in self._refused(origin, body)
+ watched.assert_not_called()
+
+ def test_a_step_zlib_rejects_is_charged_all_it_may_put_out(self, origin):
+ # CPython discards what a decompress call put out before zlib
+ # rejected the stream, so the walk cannot count it: that step is
+ # charged its whole allowance, one _RESOURCE_READ_CHUNK_BYTES step.
+ # A stream that puts out 60 KiB and then fails its checksum fails
+ # within its first step, so it is charged one step (Pillow still
+ # decompresses its 60 KiB): the cap admits cap // step such chunks
+ # and refuses one more.
+ step = pdf_service._RESOURCE_READ_CHUNK_BYTES
+ cap = pdf_service._MAX_PNG_DECOMPRESSED_BYTES
+ stream = _zlib_ending(bytes(60 * 1024), "checksum")
+ chunk = _png_zlib_chunk("iccp", 0, stream)
+ self._accepted(origin, _png_with_chunks(*[chunk] * (cap // step)))
+
+ over = _png_with_chunks(*[chunk] * (cap // step + 1))
+ assert "decompress to more than" in self._refused(origin, over)
+
+ def test_output_after_data_that_puts_out_nothing_is_charged(self, origin):
+ # A step that takes in data and puts out nothing (here 10 KiB of
+ # empty stored blocks, more than two input steps) does not end the
+ # stream: Pillow decompresses what follows in the same call, so the
+ # walk must go on counting. Five such chunks of 1 MiB each.
+ compressor = zlib.compressobj(9)
+ # The header and one empty stored block, which leaves the stream
+ # byte-aligned, then 2048 more empty stored blocks.
+ empty = compressor.flush(zlib.Z_SYNC_FLUSH) + b"\0\0\0\xff\xff" * 2048
+ stream = empty + compressor.compress(bytes(MIB)) + compressor.flush()
+ assert len(empty) > 2 * pdf_service._INFLATE_INPUT_CHUNK_BYTES
+ assert zlib.decompress(stream) == bytes(MIB)
+ body = _png_with_chunks(*[_png_zlib_chunk("iccp", 0, stream)] * 5)
+
+ assert "decompress to more than" in self._refused(origin, body)
+
+ def test_the_walk_never_asks_zlib_for_more_than_the_cap(self):
+ # zlib reads a max_length of 0 as no limit at all, so the walk
+ # must never pass one -- above all once earlier chunks have used up
+ # the cap exactly -- and what it decompresses in all stops one byte
+ # past the cap. Eight chunks fill the cap exactly; a ninth, 16 MiB
+ # of zeros in a 16 KiB stream, is refused after one more byte.
+ cap = pdf_service._MAX_PNG_DECOMPRESSED_BYTES
+ body = _png_with_chunks(
+ *[_png_iccp_chunk(bytes(cap // 8))] * 8,
+ _png_iccp_chunk(bytes(16 * MIB)),
+ )
+ calls = []
+ inflater_type = zlib.decompressobj
+
+ class _Metered:
+ def __init__(self, *args, **kwargs):
+ self._inflater = inflater_type(*args, **kwargs)
+
+ def decompress(self, data, max_length=0):
+ out = self._inflater.decompress(data, max_length)
+ calls.append((max_length, len(out)))
+ return out
+
+ def __getattr__(self, name):
+ return getattr(self._inflater, name)
+
+ with patch.object(pdf_service.zlib, "decompressobj", _Metered):
+ reason = pdf_service._png_structure_refusal(body)
+
+ assert "decompress to more than" in reason
+ assert all(max_length > 0 for max_length, _ in calls)
+ assert sum(out for _, out in calls) == cap + 1
+
+ def test_a_png_with_small_compressed_chunks_is_accepted(self, origin):
+ # What encoders write -- a compressed ICC profile and compressed
+ # text -- plus a text chunk whose stream is corrupt, which Pillow
+ # skips: each is charged what it puts out (the corrupt one a step),
+ # far under the cap, so none is refused.
+ from PIL import Image, PngImagePlugin
+
+ info = PngImagePlugin.PngInfo()
+ info.add_text("Comment", "caption " * 100, zip=True)
+ info.add_itxt("Description", "text " * 100, zip=True)
+ out = io.BytesIO()
+ Image.new("RGB", (2, 2), (10, 200, 10)).save(
+ out, "PNG", pnginfo=info, icc_profile=bytes(3000)
+ )
+ saved = out.getvalue()
+ corrupt = _png_zlib_chunk(
+ "ztxt", 0, _zlib_ending(b"note " * 64, "checksum")
+ )
+ body = saved[:33] + corrupt + saved[33:] # right after IHDR
+ with Image.open(io.BytesIO(body)) as image:
+ image.load()
+ assert image.info["Comment"].startswith("caption")
+ assert image.info["Description"].startswith("text")
+ assert image.info["t0"] == "" # Pillow kept nothing of it
+
+ self._accepted(origin, saved)
+ self._accepted(origin, body)
+
+ @pytest.mark.parametrize(
+ "build",
+ [
+ pytest.param(
+ lambda: _png_text_chunk(b"tEXt", b"comment", bytes(5 * MIB)),
+ id="text",
+ ),
+ pytest.param(
+ lambda: _png_text_chunk(b"iTXt", b"comment", bytes(5 * MIB)),
+ id="itxt",
+ ),
+ pytest.param(
+ # More uncompressed iTXt chunks than the cap has steps: were
+ # their text fed to zlib, each would fail and be charged a
+ # whole step.
+ lambda: b"".join(
+ _png_text_chunk(b"iTXt", f"c{i}".encode(), b"text")
+ for i in range(100)
+ ),
+ id="many-itxt",
+ ),
+ ],
+ )
+ def test_text_that_does_not_decompress_is_not_charged(self, origin, build):
+ # Only chunks that decompress are charged the cap: a plain text
+ # value is linear in the body, which the byte caps already bound, so
+ # more of it than the cap is not refused (no over-refusal).
+ self._accepted(origin, _png_with_chunks(build()))
+
+ def test_a_png_pillow_writes_with_metadata_is_accepted(self, origin):
+ from PIL import Image, PngImagePlugin
+
+ info = PngImagePlugin.PngInfo()
+ info.add_text("comment", "caption")
+ info.add_itxt("itxt comment", "text")
+ out = io.BytesIO()
+ Image.new("RGB", (2, 2), (10, 200, 10)).save(
+ out,
+ "PNG",
+ pnginfo=info,
+ exif=_camera_exif(),
+ icc_profile=bytes(200),
+ )
+ body = out.getvalue()
+ with Image.open(io.BytesIO(body)) as image:
+ image.load()
+ assert image.getexif().get(0x010F) == "Maker"
+
+ self._accepted(origin, body)
+
+
class TestSizeProbeLeavesWarningsAlone:
"""The size probe runs while other exports render in other threads, so
it must not touch the process-wide ``warnings`` filters, which