From 35dad4511593e30e0d4ba88a803ad869764a07aa Mon Sep 17 00:00:00 2001 From: Stephen Masters Date: Mon, 16 Nov 2026 22:32:40 +0000 Subject: [PATCH] feat!: refuse a file whose tags claim more data than it holds A decoder reads the value of every tag into memory as it loads a tag directory, and nothing in the format stops each of thousands of tags from pointing at the same bytes: a 144 KB TIFF cost Pillow 1.6 GB inside Image.open, and a 66 KB JPEG 340 MB (CVE-2026-128066). The values of an honest directory do not overlap, so they cannot add up to more than the bytes they are read from. The readers now add them up, and a directory that claims more is refused by default: - a TIFF: each frame's directory, and the Exif, GPS and interoperability directories its tags point to, against the file; - a JPEG: the main, thumbnail, Exif, GPS and interoperability directories of its EXIF block, across every segment that carries it and in every picture of a multi-picture file, and its multi-picture index, against the block; - a PNG: the same directories of an eXIf chunk. A block whose directories hold more entries between them than it has bytes for is refused the same way, which bounds the walk by the size of the block. A value that lies outside its block is not counted, since a decoder reads nothing for it and cameras do write EXIF that sloppy. Run over 3.2 million real images, the reader reported an overlap in none. A JPEG's segments are now walked to the start of the image data, not to the frame header, because that is how far a decoder reads them: an EXIF block, a colour profile or a multi-picture index after the frame header is read by Pillow and is now read here. Up to the frame header a segment the reader cannot follow is an error, as before; after it the walk stops there, as the decoder does. Policy gains allow_overlapping_tag_data, False under DEFAULT and STRICT; Facts and Header carry `overlaps`; the command line has --overlapping-tag-data. Not seen, and said so in the README and the record: EXIF that a PNG holds in a text chunk, which may be compressed, and a camera maker's own directory inside a maker note. Closes #26 BREAKING CHANGE: a TIFF, JPEG or PNG with a tag directory whose values add up to more than the file (or the EXIF block) holds is now refused by default; allow_overlapping_tag_data=True, or --overlapping-tag-data, passes one. A JPEG's colour profile and multi-picture index are now found after its frame header as well as before it, so max_metadata_bytes and the checks on each picture apply to them there too, and a JPEG with more than 4,096 segments before its image data is refused. Co-authored-by: Yvette Mankerian Co-Authored-By: Claude Fable 5.2 --- README.md | 15 +- docs/advisories/record.json | 45 +++- docs/advisories/record/CVE-2026-128066.json | 37 +++ docs/advisories/seen.json | 1 + scripts/fuzz_headers.py | 8 + src/sillybos/check.py | 12 + src/sillybos/cli.py | 8 + src/sillybos/headers.py | 285 ++++++++++++++++++-- src/sillybos/policy.py | 17 ++ tests/corpus.py | 91 ++++++- tests/test_check.py | 56 ++++ tests/test_cli.py | 6 + tests/test_headers.py | 279 +++++++++++++++++++ 13 files changed, 824 insertions(+), 36 deletions(-) create mode 100644 docs/advisories/record/CVE-2026-128066.json diff --git a/README.md b/README.md index 75e9635..46d10b8 100644 --- a/README.md +++ b/README.md @@ -111,6 +111,7 @@ check(path, Policy(formats={"tiff", "pdf"}, max_pages=50)) | `jpeg_frames` | baseline, extended, progressive | the same | How a JPEG's frame may be coded. Lossless, hierarchical and arithmetic frames are legal JPEG that no scanner writes and the decoder's least-exercised code; a lossless frame was the way into a heap overflow in Pillow's JPEG decoder (CVE-2026-112403) | | `tiff_tags` | standard, metadata, private | the same | Which kinds of tag a TIFF's directories may hold. Standard is the TIFF 6.0 set; metadata the registered blocks (XMP, IPTC, Photoshop, Exif, ICC, GPS, GeoTIFF); private everything else, the vendor and DNG tags a scan never carries. A read is not harmed by a private tag, so the default allows all three; a program that saves a file back as TIFF with its tag table carries every tag into libtiff's encoder, where a crafted one copied process memory into the output (CVE-2026-112902), and should allow standard and metadata only | | `allow_inconsistent_tiff_tags` | no | no | Pass a TIFF whose tags contradict each other: a ColorMap of the wrong size for the bit depth (CVE-2026-112896), a floating-point Predictor on integer samples (CVE-2026-112396). No scanner writes either; both reach an encoder that trusts the tag, so the default refuses them, malformed by design or by accident. Allow only for a source known to write such files | +| `allow_overlapping_tag_data` | no | no | Pass a file with a tag directory whose tags claim more data between them than the file holds: a TIFF's frame or one of the Exif, GPS and interoperability directories it points to, or, measured against the block itself, the EXIF block of a JPEG or a PNG and a JPEG's multi-picture index. A decoder reads every tag's value into memory as it loads a directory, and nothing in the format stops each of thousands of tags from pointing at the same bytes: a 144 KB TIFF cost Pillow 1.6 GB to open, and a 66 KB JPEG 340 MB (CVE-2026-128066). The values of an honest directory do not overlap, so they cannot add up to more than the bytes they are read from, and no writer produces a file that fails this. Not seen: EXIF that a PNG carries in a text chunk, which may be compressed, and a camera maker's own directory inside a maker note | | `allow_spare_tiff_samples` | yes | yes | Pass a greyscale or palette TIFF whose pixels carry more samples than the one the image uses, where the rest are not a single alpha sample (two samples per pixel with ExtraSamples 0, "unspecified data"). A valid TIFF that no scanner writes; a decoder drops the spare sample, so a read is not harmed and the default allows it. A program that saves such a file back as a compressed TIFF carries its SamplesPerPixel tag into libtiff's encoder, which read two samples for every one in the row it was given and copied process memory into the output (CVE-2026-128067), and should refuse them. An alpha channel, and a spare sample on an RGB or CMYK TIFF, are not refused: there the decoder's own count is what the encoder is given | | `allow_encrypted_pdf` | no | no | A scanned book is never encrypted | | `pdf_features` | none | none | Which of JavaScript, forms, attached files and launch actions a PDF may carry. Each makes a viewer do something other than draw the page, and a scanned book has none. Forms are read from `pdfinfo`'s report and attached files from `pdfdetach`'s; a launch action is found by its name in the file, since no poppler tool reports one; JavaScript is looked for both ways | @@ -173,18 +174,22 @@ prints one object per line for a pipeline; `-q` prints only refusals. 3. **Name against contents.** `says PNG, is JPEG`. 4. **The header**, with a reader of its own for each raster format: the dimensions, coding and component count from a JPEG's frame header, the - size of its colour profile, and every picture of a multi-picture (MPF) + size of its colour profile and the tag directories of its EXIF block, + from every segment up to the start of the image data, as a decoder + reads them, and every picture of a multi-picture (MPF) JPEG, each read the same way and required to match the first; a PNG's whole `IHDR` (bit depth, colour type, interlacing, and the methods the - specification fixes), its `acTL` frame count, and the size of every - other chunk, before and after the image data; and every directory in a TIFF's + specification fixes), its `acTL` frame count, the size of every + other chunk, before and after the image data, and the tag directories + of an `eXIf` chunk; and every directory in a TIFF's chain, each with its dimensions, its compression scheme, which must be one the policy names, and its pixel layout (photometric interpretation and, for YCbCr, chroma subsampling, both of which the policy names; samples per pixel; bits per sample), all of which must be the same in every frame, since the decoder sizes its buffers from the first, its tile size if it is tiled, every - tag's data checked to lie inside the file, every tag sorted into + tag's data checked to lie inside the file and, added together, to be + no more than the file holds, every tag sorted into standard, metadata or private, and its ColorMap and Predictor checked against its samples; the chain is walked with a limit and a memory of where it has been, so that one that loops or points off the end of the file is a @@ -250,7 +255,7 @@ a PNG whose header pairs a colour type with a bit depth it cannot have, a TIFF whose tag points past the end of the file, a lossless JPEG, a multi-picture JPEG whose second picture is four billion pixels or changes colour mode, a PixarLog-compressed TIFF, a CIELab TIFF, a YCbCr TIFF subsampled four to one, a TIFF that changes compression or colour mode between frames, a TIFF whose tiles are four billion pixels each, a TIFF with ten thousand frames, a -TIFF whose frame chain loops, a PDF of a thousand pages, a PDF with a page 200 +TIFF whose frame chain loops, a TIFF, a JPEG and a PNG whose tags all claim the same bytes, a PDF of a thousand pages, a PDF with a page 200 inches wide. Nothing hostile is checked in. The readers are also checked against Pillow's reading of real files, so that they agree with the decoder they stand in front of. diff --git a/docs/advisories/record.json b/docs/advisories/record.json index 54905e8..5ccd0dd 100644 --- a/docs/advisories/record.json +++ b/docs/advisories/record.json @@ -17,11 +17,11 @@ "other": "some other way; the finding says" }, "counts": { - "records": 125, - "refused_by_default": 46, + "records": 126, + "refused_by_default": 47, "by_bucket": { "A": 39, - "B": 20, + "B": 21, "B2": 3, "C": 19, "D": 3, @@ -31,7 +31,7 @@ "by_library": { "FreeType": 4, "OpenJPEG": 6, - "Pillow": 62, + "Pillow": 63, "libpng": 15, "libtiff": 18, "poppler": 16, @@ -74,6 +74,43 @@ "checked": "2026-11-16", "notes": "Triaged from the advisory's text on 2026-11-16, and the bucket confirmed by a person the same day. The words filter labelled the issue likely-not-reached on \"saving\"; read against the question of what rides from an opened file into a save, the file is the input. The advisory names the palette layout for the bare save; the greyscale one was found by trying a bare save of each layout on Pillow 13.0.0, where the encoder's new guard refuses (encoder error -8) the greyscale and the palette image with an unspecified sample, and no image with an alpha channel, nor RGB or CMYK with a spare sample. The overflow itself was not reproduced on an earlier Pillow. The policy was built on 2026-11-16." }, + { + "key": "CVE-2026-128066", + "aliases": [], + "library": "Pillow", + "package": "pillow", + "ecosystem": "PyPI", + "title": "Tags that all claim the same bytes make Pillow hold thousands of times a file's size in memory", + "summary": "Pillow: Memory DoS in TIFF and EXIF IFD parsing via overlapping tag data", + "published": "2026-11-12", + "severity": null, + "affected": "< 13.0.0", + "fixed": "13.0.0", + "reached_by": "open", + "trigger": "Opening a TIFF or a JPEG whose tag directory holds thousands of tags that each claim the same bytes as their value; for a PNG, asking for the EXIF of one.", + "bucket": "B", + "finding": "The trigger is a tag directory, which is a header: each entry gives the size of its value and where it lies, and the loader reads every value into memory with nothing to stop them all being the same bytes. The values of an honest directory do not overlap, so they cannot add up to more than the bytes they are read from, and the reader now adds them up: for each frame of a TIFF and the Exif, GPS and interoperability directories it points to, against the file; for the EXIF block of a JPEG or a PNG (its main, thumbnail, Exif, GPS and interoperability directories) and a JPEG's multi-picture index, against the block. A directory that claims more is refused by default, as is a block whose directories hold more entries between them than it has bytes for. The JPEG walk now goes on past the frame header to the image data, since Pillow reads an EXIF block from anywhere before the scan. The advisory's own TIFF was already refused, by accident: its tags point at the second byte of the file, inside the header, which the reader does not allow; moved eight bytes on, it passed every policy. Refusing private tags did not help, since the standard numbers serve as well. Two carriers are not seen: EXIF that a PNG holds in a text chunk (\"Raw profile type exif\"), which may be compressed and so cannot be read without inflating it, and a camera maker's own directory inside a maker note. Both are reached only when a program asks for the EXIF, not on opening.", + "refusal": { + "check": "allow_overlapping_tag_data", + "default": true, + "setting": "allow_overlapping_tag_data" + }, + "verified_by": [ + "tests/test_check.py::TestHostileFiles::test_a_tiff_whose_tags_all_claim_the_same_bytes", + "tests/test_check.py::TestHostileFiles::test_a_jpeg_whose_exif_tags_all_claim_the_same_bytes", + "tests/test_check.py::TestHostileFiles::test_a_png_whose_exif_tags_all_claim_the_same_bytes" + ], + "protect": { + "general": "Upgrade to Pillow 13.0.0, whose loader skips a tag once the directory's values add up to more than the stream.", + "specific": "Keep allow_overlapping_tag_data off, as it is by default; on a Pillow before 13.0.0, do not ask for the EXIF of a PNG from outside (getexif, ImageOps.exif_transpose) unless its text chunks are known to hold none; upgrade to Pillow 13.0.0." + }, + "sources": [ + "https://osv.dev/vulnerability/GHSA-wqgw-9xfh-qf2g" + ], + "triaged": "2026-11-16", + "checked": "2026-11-16", + "notes": "Triaged from the advisory's text on 2026-11-16, and the bucket and the default confirmed by a person the same day. Upstream gives the severity as moderate, with no score. Each route was tried on Pillow 13.0.0, whose bounded loader warns where it used to read: a TIFF, a JPEG's EXIF block before or after the frame header and across several segments, and a JPEG's multi-picture index all reach the loader inside Image.open; a PNG's eXIf chunk and its raw-profile text chunk, compressed or not, on getexif; the Exif and GPS directories on get_ifd. An EXIF block with a BigTIFF header does not reach it. The reader was run over 3.2 million real images (7,501 JPEG, 126,337 TIFF, 3,064,088 PNG) and reported an overlap in none. The memory cost itself was not reproduced on an earlier Pillow. The check was built on 2026-11-16." + }, { "key": "CVE-2026-107080", "aliases": [], diff --git a/docs/advisories/record/CVE-2026-128066.json b/docs/advisories/record/CVE-2026-128066.json new file mode 100644 index 0000000..b94c9c7 --- /dev/null +++ b/docs/advisories/record/CVE-2026-128066.json @@ -0,0 +1,37 @@ +{ + "key": "CVE-2026-128066", + "aliases": [], + "library": "Pillow", + "package": "pillow", + "ecosystem": "PyPI", + "title": "Tags that all claim the same bytes make Pillow hold thousands of times a file's size in memory", + "summary": "Pillow: Memory DoS in TIFF and EXIF IFD parsing via overlapping tag data", + "published": "2026-11-12", + "severity": null, + "affected": "< 13.0.0", + "fixed": "13.0.0", + "reached_by": "open", + "trigger": "Opening a TIFF or a JPEG whose tag directory holds thousands of tags that each claim the same bytes as their value; for a PNG, asking for the EXIF of one.", + "bucket": "B", + "finding": "The trigger is a tag directory, which is a header: each entry gives the size of its value and where it lies, and the loader reads every value into memory with nothing to stop them all being the same bytes. The values of an honest directory do not overlap, so they cannot add up to more than the bytes they are read from, and the reader now adds them up: for each frame of a TIFF and the Exif, GPS and interoperability directories it points to, against the file; for the EXIF block of a JPEG or a PNG (its main, thumbnail, Exif, GPS and interoperability directories) and a JPEG's multi-picture index, against the block. A directory that claims more is refused by default, as is a block whose directories hold more entries between them than it has bytes for. The JPEG walk now goes on past the frame header to the image data, since Pillow reads an EXIF block from anywhere before the scan. The advisory's own TIFF was already refused, by accident: its tags point at the second byte of the file, inside the header, which the reader does not allow; moved eight bytes on, it passed every policy. Refusing private tags did not help, since the standard numbers serve as well. Two carriers are not seen: EXIF that a PNG holds in a text chunk (\"Raw profile type exif\"), which may be compressed and so cannot be read without inflating it, and a camera maker's own directory inside a maker note. Both are reached only when a program asks for the EXIF, not on opening.", + "refusal": { + "check": "allow_overlapping_tag_data", + "default": true, + "setting": "allow_overlapping_tag_data" + }, + "verified_by": [ + "tests/test_check.py::TestHostileFiles::test_a_tiff_whose_tags_all_claim_the_same_bytes", + "tests/test_check.py::TestHostileFiles::test_a_jpeg_whose_exif_tags_all_claim_the_same_bytes", + "tests/test_check.py::TestHostileFiles::test_a_png_whose_exif_tags_all_claim_the_same_bytes" + ], + "protect": { + "general": "Upgrade to Pillow 13.0.0, whose loader skips a tag once the directory's values add up to more than the stream.", + "specific": "Keep allow_overlapping_tag_data off, as it is by default; on a Pillow before 13.0.0, do not ask for the EXIF of a PNG from outside (getexif, ImageOps.exif_transpose) unless its text chunks are known to hold none; upgrade to Pillow 13.0.0." + }, + "sources": [ + "https://osv.dev/vulnerability/GHSA-wqgw-9xfh-qf2g" + ], + "triaged": "2026-11-16", + "checked": "2026-11-16", + "notes": "Triaged from the advisory's text on 2026-11-16, and the bucket and the default confirmed by a person the same day. Upstream gives the severity as moderate, with no score. Each route was tried on Pillow 13.0.0, whose bounded loader warns where it used to read: a TIFF, a JPEG's EXIF block before or after the frame header and across several segments, and a JPEG's multi-picture index all reach the loader inside Image.open; a PNG's eXIf chunk and its raw-profile text chunk, compressed or not, on getexif; the Exif and GPS directories on get_ifd. An EXIF block with a BigTIFF header does not reach it. The reader was run over 3.2 million real images (7,501 JPEG, 126,337 TIFF, 3,064,088 PNG) and reported an overlap in none. The memory cost itself was not reproduced on an earlier Pillow. The check was built on 2026-11-16." +} diff --git a/docs/advisories/seen.json b/docs/advisories/seen.json index a826457..27c04af 100644 --- a/docs/advisories/seen.json +++ b/docs/advisories/seen.json @@ -708,6 +708,7 @@ "CVE-2026-112901", "CVE-2026-112902", "CVE-2026-114501", + "CVE-2026-128066", "CVE-2026-128067", "CVE-2026-12912", "CVE-2026-18495", diff --git a/scripts/fuzz_headers.py b/scripts/fuzz_headers.py index 398b111..f39821a 100644 --- a/scripts/fuzz_headers.py +++ b/scripts/fuzz_headers.py @@ -74,6 +74,14 @@ def seeds() -> list[bytes]: corpus.tiff([(64, 64)], endian=">"), corpus.tiled_tiff(256, 256, 64), corpus.spare_sample_tiff(64, 8), + corpus.overlapping_tiff(40), + corpus.overlapping_tiff(40, pointer=34665), + corpus.jpeg(64, 64, before_sof=corpus.jpeg_exif(corpus.overlapping_block(40))), + corpus.jpeg( + 64, 64, after_sof=corpus.jpeg_exif(corpus.overlapping_block(40, pointer=34853)) + ), + corpus.jpeg(64, 64, before_sof=corpus.jpeg_mp_index(corpus.overlapping_block(40))), + corpus.png(64, 64, extra=corpus.png_exif(corpus.overlapping_block(40))), ] try: from PIL import Image diff --git a/src/sillybos/check.py b/src/sillybos/check.py index 785e64f..361bcbe 100644 --- a/src/sillybos/check.py +++ b/src/sillybos/check.py @@ -95,6 +95,11 @@ class Facts: palette TIFF carries beyond the one the image uses, unless that is a single alpha sample. 0 for every other TIFF and for the other formats. + overlaps: Each tag directory whose tags claim more data between + them than the file holds, in a sentence: a TIFF's frame or + one of the directories it points to, the EXIF block of a + JPEG or a PNG, a JPEG's multi-picture index. Empty when none + does, and for a PDF. """ bytes: int @@ -118,6 +123,7 @@ class Facts: tags: tuple[tuple[str, int], ...] = () inconsistencies: tuple[str, ...] = () spare_samples: int = 0 + overlaps: tuple[str, ...] = () @dataclass(frozen=True) @@ -274,6 +280,7 @@ def _facts(path: Path, fmt: str, f: headers.Reader, size: int, policy: Policy) - tags=header.tags, inconsistencies=header.inconsistencies, spare_samples=header.spare_samples, + overlaps=header.overlaps, ) @@ -361,6 +368,11 @@ def _against_limits(facts: Facts, policy: Policy, fmt: str) -> list[str]: "the image uses one and the rest are not an alpha channel; the policy does not " "allow spare samples" ) + if facts.overlaps and not policy.allow_overlapping_tag_data: + reasons.append( + f"a {sniff.describe(fmt)} whose tags claim more data than it holds: " + + "; ".join(facts.overlaps) + ) return reasons diff --git a/src/sillybos/cli.py b/src/sillybos/cli.py index 0fa01e6..8479a74 100644 --- a/src/sillybos/cli.py +++ b/src/sillybos/cli.py @@ -58,6 +58,8 @@ def _policy(args: argparse.Namespace) -> Policy: changes["tiff_tags"] = frozenset(args.tiff_tags.split(",")) if args.inconsistent_tiff_tags: changes["allow_inconsistent_tiff_tags"] = True + if args.overlapping_tag_data: + changes["allow_overlapping_tag_data"] = True if args.no_spare_tiff_samples: changes["allow_spare_tiff_samples"] = False if args.pdf_features: @@ -165,6 +167,12 @@ def build_parser() -> argparse.ArgumentParser: help="do not refuse a TIFF whose tags contradict each other (a ColorMap of the wrong " "size, a floating-point Predictor on integer samples)", ) + parser.add_argument( + "--overlapping-tag-data", + action="store_true", + help="do not refuse a file whose tags claim more data between them than it holds " + "(a TIFF's directory, the EXIF block of a JPEG or PNG)", + ) parser.add_argument( "--no-spare-tiff-samples", action="store_true", diff --git a/src/sillybos/headers.py b/src/sillybos/headers.py index 5191e9b..d42db0a 100644 --- a/src/sillybos/headers.py +++ b/src/sillybos/headers.py @@ -97,6 +97,13 @@ class Header: with an alpha channel, for RGB, CMYK and YCbCr (where a decoder drops the sample and keeps its own count), and for the other formats. + overlaps: Each tag directory whose tags claim more data between + them than the file holds, in a sentence: a frame of a TIFF + or one of its Exif, GPS or interoperability directories; the + EXIF block of a JPEG or a PNG, or a JPEG's multi-picture + index, measured against the block. The values of an honest + directory do not overlap, so they cannot add up to more than + the bytes they are read from. Empty when none does. """ width: int @@ -116,6 +123,7 @@ class Header: tags: tuple[tuple[str, int], ...] = () inconsistencies: tuple[str, ...] = () spare_samples: int = 0 + overlaps: tuple[str, ...] = () def _read_exactly(f: Reader, n: int, what: str) -> bytes: @@ -132,6 +140,160 @@ def _dimensions(width: int, height: int, what: str) -> None: raise HeaderError(f"the {what} gives a width or height of {max(width, height):,}") +# --- Tag directories ---------------------------------------------------------- + +# A TIFF's frames, the EXIF block of a JPEG or a PNG and a JPEG's +# multi-picture index are all the same structure: a directory of twelve-byte +# entries, each holding a value of up to four bytes or the offset of a longer +# one. A decoder reads every longer value into memory as it loads the +# directory, and nothing in the format stops every entry from pointing at the +# same bytes, so a directory of N entries can cost N times the file +# (CVE-2026-128066). The values of an honest directory do not overlap, and +# so cannot add up to more than the bytes they are read from; that sum is +# what is measured here. + +Pieces = tuple[tuple[int, int], ...] +"""Where a block of tag directories sits in the file, as (offset, length) +runs: one for a TIFF or a PNG's `eXIf` chunk, and one per segment for a +JPEG's EXIF block, which a decoder joins end to end.""" + +_BYTE_ORDERS = {b"II*\x00": "<", b"MM\x00*": ">"} +_POINTERS = {34665: "Exif", 34853: "GPS", 40965: "interoperability"} +"""The tags whose value is the offset of a further directory, which a +decoder loads when the program asks for the file's EXIF.""" + + +@dataclass +class _Room: + """How many more entries a block has room for, and which directories were measured.""" + + entries: int + seen: set[int] + + +def _read_at(f: Reader, pieces: Pieces, at: int, n: int) -> bytes | None: + """`n` bytes from offset `at` of a block, or `None` where the block does not hold them.""" + out = b"" + for start, length in pieces: + if at >= length: + at -= length + continue + f.seek(start + at) + out += f.read(min(n - len(out), length - at)) + at = 0 + if len(out) >= n: + break + return out if len(out) == n else None + + +def _claimed( + f: Reader, pieces: Pieces, length: int, endian: str, offset: int +) -> tuple[int, int, list[tuple[int, int]], int | None] | None: + """Measure the tag directory at `offset` of a block of `length` bytes. + + Returns how many entries were read, how many bytes of data they claim + between them, the (tag, offset) of each further directory they point + to, and the offset of the directory that follows; or `None` if no + directory starts there. Only a value that lies inside the block is + counted, since a decoder reads nothing for one that does not. A + directory that runs past the end of the block is measured as far as + it goes, since a decoder keeps what it read before it gave up. + """ + head = _read_at(f, pieces, offset, 2) + if head is None: + return None + (count,) = struct.unpack(endian + "H", head) + fit = min(count, (length - offset - 2) // 12) + table = _read_at(f, pieces, offset + 2, fit * 12) + if table is None: + return None + claimed = 0 + pointers: list[tuple[int, int]] = [] + for tag, kind, n, raw in struct.iter_unpack(endian + "HHI4s", table): + data_size = n * _TYPE_SIZES.get(kind, 1) + if data_size > 4: + (where,) = struct.unpack(endian + "I", raw) + if where + data_size <= length: + claimed += data_size + elif tag in _POINTERS and n == 1 and kind in (_TIFF_SHORT, _TIFF_LONG): + width_of = 2 if kind == _TIFF_SHORT else 4 + where = int.from_bytes(raw[:width_of], "little" if endian == "<" else "big") + pointers.append((tag, where)) + following = None + if fit == count: + tail = _read_at(f, pieces, offset + 2 + count * 12, 4) + if tail is not None: + (following,) = struct.unpack(endian + "I", tail) + return fit, claimed, pointers, following + + +def _overlapping( + f: Reader, + pieces: Pieces, + endian: str, + queue: list[tuple[str, int, bool]], + room: _Room, + what: str, + unit: str, +) -> list[str]: + """Measure each queued directory and those it points to; a sentence for each that overlaps. + + `queue` holds (name, offset, whether to go on to the directory that + follows). Each directory is measured once, and the entries of all of + them are counted against `room`: directories that hold more entries + between them than the block has bytes for are overlapping each other, + which bounds the walk by the size of the block. + """ + length = sum(n for _, n in pieces) + found = [] + while queue and room.entries >= 0: + name, offset, onward = queue.pop(0) + if offset in room.seen: + continue + room.seen.add(offset) + measured = _claimed(f, pieces, length, endian, offset) + if measured is None: + continue + entries, claimed, pointers, following = measured + room.entries -= entries + if room.entries < 0: + found.append( + f"the tag directories of {unit} of {length:,} bytes hold more entries " + "between them than it has room for" + ) + elif claimed > length: + found.append( + f"{what}'s {name}tags claim {claimed:,} bytes of data between them " + f"in {unit} of {length:,} bytes" + ) + queue.extend((f"{_POINTERS[tag]} ", where, False) for tag, where in pointers) + if onward and following: + queue.append(("thumbnail ", following, False)) + return found + + +def _block_overlaps(f: Reader, pieces: Pieces, what: str, *, onward: bool = True) -> list[str]: + """The overlapping directories of a block that is a small TIFF of its own. + + An EXIF block has a main directory, the thumbnail's after it, and the + Exif, GPS and interoperability directories its tags point to; a + decoder loads each on request, with one pass of the same loader. A + block with no TIFF header has no directory for a decoder to load (a + BigTIFF header among them: Pillow gives up on one), so there is nothing + to measure. + """ + length = sum(n for _, n in pieces) + head = _read_at(f, pieces, 0, 8) + if head is None: + return [] + endian = _BYTE_ORDERS.get(head[:4]) + if endian is None: + return [] + (first,) = struct.unpack(endian + "I", head[4:]) + room = _Room(length // 12, set()) + return _overlapping(f, pieces, endian, [("", first, onward)], room, what, "a block") + + # --- JPEG ------------------------------------------------------------------- # Start-of-frame markers, which carry the dimensions, and how each codes the @@ -156,7 +318,9 @@ def _dimensions(width: int, height: int, what: str) -> None: } # Markers with no length field. _STANDALONE = {0x01, 0xD0, 0xD1, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7, 0xD8} +_APP1 = 0xE1 _APP2 = 0xE2 +_EXIF = b"Exif\x00\x00" _MPF = b"MPF\x00" _ICC = b"ICC_PROFILE\x00" _MP_NUMBER_OF_IMAGES = 0xB001 @@ -183,7 +347,7 @@ def jpeg(f: Reader, size: int, limit: int) -> Header: that sized its buffers for the first picture is the one that will decode the rest. As with a TIFF, the walk stops after `limit + 1` pictures. """ - first, pictures, profile = _frame(f, size, 0, "frame header", index=True) + first, pictures, profile, overlaps = _frame(f, size, 0, "frame header", index=True) metadata = ("JPEG colour profile", profile) if profile else None pages = 1 max_pixels = first.width * first.height @@ -199,10 +363,12 @@ def jpeg(f: Reader, size: int, limit: int) -> Header: False, first.coding, metadata=metadata, + overlaps=tuple(overlaps), ) if not 2 <= offset < size: raise HeaderError(f"picture {number} lies outside the file") - picture, _, _ = _frame(f, size, offset, f"picture {number}", index=False) + picture, _, _, more = _frame(f, size, offset, f"picture {number}", index=False) + overlaps += more if picture.coding != first.coding: raise HeaderError( f"picture {number} is {picture.coding} where picture 1 is {first.coding}" @@ -223,38 +389,51 @@ def jpeg(f: Reader, size: int, limit: int) -> Header: max_side, coding=first.coding, metadata=metadata, + overlaps=tuple(overlaps), ) def _frame( f: Reader, size: int, start: int, what: str, *, index: bool -) -> tuple[_Frame, list[int], int]: - """Walk one picture's segments from `start` to its frame header. +) -> tuple[_Frame, list[int], int, list[str]]: + """Walk one picture's segments from `start` to its image data. + + Returns the frame, from the first frame header; when `index` is set, + the offset in the file of every further picture a Multi-Picture index + names and the total bytes of colour profile carried in APP2 segments; + and a sentence for each tag directory of the picture's EXIF block, or + of its Multi-Picture index, whose tags overlap. - Returns the frame and, when `index` is set, the offset in the file of - every further picture a Multi-Picture index names and the total bytes - of colour profile carried in APP2 segments. + The walk goes on past the frame header to the start of the image data, + because a decoder's does: Pillow reads an EXIF block, a colour profile + or a Multi-Picture index from wherever it sits before the scan. Up to + the frame header, a segment the reader cannot follow is an error. After + it, the walk simply stops there, as the decoder does. """ f.seek(start) if _read_exactly(f, 2, "header") != b"\xff\xd8": raise HeaderError(f"no JPEG start-of-image marker in the {what}") + frame: _Frame | None = None pictures: list[int] = [] profile = 0 + exif: list[tuple[int, int]] = [] + overlaps: list[str] = [] for _ in range(MAX_SEGMENTS): - byte = _read_exactly(f, 1, "segment marker") - if byte != b"\xff": - raise HeaderError("a segment does not start with a marker") - marker = _read_exactly(f, 1, "segment marker")[0] - while marker == 0xFF: # fill bytes before a marker are allowed - marker = _read_exactly(f, 1, "segment marker")[0] + try: + marker, length = _segment(f) + except HeaderError: + if frame is None: + raise + break if marker in _STANDALONE: continue if marker in (0xD9, 0xDA): - raise HeaderError("the image data starts before any frame header") - (length,) = struct.unpack(">H", _read_exactly(f, 2, "segment length")) - if length < 2: - raise HeaderError("a segment claims a length shorter than its own length field") - if marker in _FRAME_CODINGS: + if frame is None: + raise HeaderError("the image data starts before any frame header") + break + payload = f.tell() + next_offset = payload + length - 2 + if marker in _FRAME_CODINGS and frame is None: if length < 8: raise HeaderError("the frame header is too short to hold the dimensions") _precision, height, width, components = struct.unpack( @@ -265,25 +444,56 @@ def _frame( # scan; refusing it keeps every decoder's rarest path closed. raise HeaderError("the height is deferred to a DNL marker") _dimensions(width, height, what) - return _Frame(width, height, _FRAME_CODINGS[marker], components), pictures, profile - payload = f.tell() - next_offset = payload + length - 2 - if next_offset > size: - raise HeaderError("a segment runs past the end of the file") - if index and marker == _APP2 and length >= 2 + len(_MPF): + frame = _Frame(width, height, _FRAME_CODINGS[marker], components) + elif next_offset > size: + if frame is None: + raise HeaderError("a segment runs past the end of the file") + break + elif index and marker == _APP2 and length >= 2 + len(_MPF): ident = _read_exactly(f, len(_MPF), "APP2 segment") if ident == _MPF: if pictures: raise HeaderError("two multi-picture indexes") + block = ((payload + len(_MPF), length - 2 - len(_MPF)),) data = _read_exactly(f, length - 2 - len(_MPF), "multi-picture index") pictures = _mp_index(data, payload + len(_MPF)) + overlaps += _block_overlaps(f, block, "the multi-picture index", onward=False) elif ident == _ICC[:4] and length >= 4 + len(_ICC): # After the identifier come the segment's number and the # count of segments, then the profile bytes themselves. if _read_exactly(f, len(_ICC) - 4, "APP2 segment") == _ICC[4:]: profile += length - 4 - len(_ICC) + elif marker == _APP1 and length >= 2 + len(_EXIF): + # A decoder joins the EXIF segments of a picture end to end, + # each without its identifier, and reads the directories from + # the whole. + if _read_exactly(f, len(_EXIF), "APP1 segment") == _EXIF: + exif.append((payload + len(_EXIF), length - 2 - len(_EXIF))) f.seek(next_offset) - raise HeaderError(f"no frame header in the first {MAX_SEGMENTS} segments") + else: + if frame is None: + raise HeaderError(f"no frame header in the first {MAX_SEGMENTS} segments") + raise HeaderError(f"no image data in the first {MAX_SEGMENTS:,} segments") + if exif: + block_name = "the EXIF block" if index else f"{what}'s EXIF block" + overlaps += _block_overlaps(f, tuple(exif), block_name) + return frame, pictures, profile, overlaps + + +def _segment(f: Reader) -> tuple[int, int]: + """Read the marker of the next segment, and its length if it has one.""" + byte = _read_exactly(f, 1, "segment marker") + if byte != b"\xff": + raise HeaderError("a segment does not start with a marker") + marker = _read_exactly(f, 1, "segment marker")[0] + while marker == 0xFF: # fill bytes before a marker are allowed + marker = _read_exactly(f, 1, "segment marker")[0] + if marker in _STANDALONE or marker in (0xD9, 0xDA): + return marker, 0 + (length,) = struct.unpack(">H", _read_exactly(f, 2, "segment length")) + if length < 2: + raise HeaderError("a segment claims a length shorter than its own length field") + return marker, length def _mp_index(data: bytes, base: int) -> list[int]: @@ -381,6 +591,7 @@ def png(f: Reader, size: int, limit: int) -> Header: pages = 1 chunks = idats = 0 metadata: tuple[str, int] | None = None + overlaps: list[str] = [] while True: head = f.read(8) if len(head) < 8: @@ -407,6 +618,8 @@ def png(f: Reader, size: int, limit: int) -> Header: (pages,) = struct.unpack(">I", _read_exactly(f, 4, "acTL")) if pages < 1: raise HeaderError("acTL gives zero frames") + if kind == b"eXIf": + overlaps += _block_overlaps(f, ((f.tell(), length),), "the EXIF block") f.seek(next_offset) return Header( width, @@ -418,6 +631,7 @@ def png(f: Reader, size: int, limit: int) -> Header: colour=colour, depth=depth, interlaced=interlace == 1, + overlaps=tuple(overlaps), ) @@ -608,6 +822,8 @@ def tiff(f: Reader, size: int, limit: int) -> Header: tags: dict[int, str] = {} # every tag outside the standard set, by number inconsistencies: list[str] = [] spare_samples = 0 + overlaps: list[str] = [] + room = _Room(size // 12, set()) # for the directories the frames' tags point to max_pixels = 0 max_side = 0 pages = 0 @@ -632,6 +848,7 @@ def tiff(f: Reader, size: int, limit: int) -> Header: tags=tuple((kind, number) for number, kind in tags.items()), inconsistencies=tuple(inconsistencies), spare_samples=spare_samples, + overlaps=tuple(overlaps), ) if offset in seen: raise HeaderError("the frame chain loops back on itself") @@ -657,6 +874,8 @@ def tiff(f: Reader, size: int, limit: int) -> Header: predictor = 1 # the tag's default: none sample_format = 1 # the tag's default: unsigned integer alpha: bool | None = None # whether ExtraSamples declares one alpha sample + claimed = 0 # the bytes of data this directory's tags hold between them + pointers: list[tuple[int, int]] = [] # (tag, offset) of each directory it points to for _ in range(count): tag, kind, n, raw = struct.unpack( endian + "HHI4s", _read_exactly(f, 12, "frame directory") @@ -690,6 +909,11 @@ def tiff(f: Reader, size: int, limit: int) -> Header: label = _TAG_LABELS.get(tag) name = f"TIFF tag {tag:,}" + (f" ({label})" if label else "") metadata = (name, data_size) + claimed += data_size + elif tag in _POINTERS and n == 1 and kind in (_TIFF_SHORT, _TIFF_LONG): + width_of = 2 if kind == _TIFF_SHORT else 4 + where = int.from_bytes(raw[:width_of], "little" if endian == "<" else "big") + pointers.append((tag, where)) if tag == _BITS_PER_SAMPLE: if kind != _TIFF_SHORT: raise HeaderError("a bits-per-sample tag is not SHORT") @@ -797,6 +1021,16 @@ def tiff(f: Reader, size: int, limit: int) -> Header: f"frame {pages + 1} is compressed with {scheme} where frame 1 is " f"compressed with {compression}" ) + if claimed > size: + # No decoder reads a frame's directory without reading these. + overlaps.append( + f"frame {pages + 1}'s tags claim {claimed:,} bytes of data between them " + f"in a file of {size:,} bytes" + ) + queue = [(f"{_POINTERS[tag]} ", where, False) for tag, where in pointers] + overlaps += _overlapping( + f, ((0, size),), endian, queue, room, f"frame {pages + 1}", "a file" + ) pages += 1 max_pixels = max(max_pixels, width * height) max_side = max(max_side, width, height) @@ -821,6 +1055,7 @@ def tiff(f: Reader, size: int, limit: int) -> Header: tags=tuple((kind, number) for number, kind in tags.items()), inconsistencies=tuple(inconsistencies), spare_samples=spare_samples, + overlaps=tuple(overlaps), ) diff --git a/src/sillybos/policy.py b/src/sillybos/policy.py index 1e4ca60..72f35f5 100644 --- a/src/sillybos/policy.py +++ b/src/sillybos/policy.py @@ -208,6 +208,22 @@ class Policy: the tag, so the default refuses them, malformed by design or by accident. A policy for a source known to write such files can allow them. + allow_overlapping_tag_data: Pass a file with a tag directory whose + tags claim more data between them than the file holds: a + frame of a TIFF or one of the Exif, GPS and interoperability + directories it points to, or, measured against the block + itself, the EXIF block of a JPEG or a PNG and a JPEG's + multi-picture index. A decoder reads every tag's value into + memory as it loads a directory, and nothing in the format + stops each of thousands of tags from pointing at the same + bytes, so a 144 KB TIFF cost Pillow 1.6 GB to open and a + 66 KB JPEG 340 MB (CVE-2026-128066). The values of an honest + directory do not overlap, so they cannot add up to more than + the bytes they are read from; no writer produces a file that + fails this, and the default refuses one. Not seen: EXIF that + a PNG carries in a text chunk, as ImageMagick once wrote it, + which may be compressed; and a camera maker's own directory + inside a maker note. allow_spare_tiff_samples: Pass a greyscale or palette TIFF whose pixels carry more samples than the one the image uses, where the rest are not a single alpha sample: 2 samples per pixel @@ -277,6 +293,7 @@ class Policy: ) tiff_tags: frozenset[str] = field(default_factory=lambda: frozenset(TIFF_TAGS)) allow_inconsistent_tiff_tags: bool = False + allow_overlapping_tag_data: bool = False allow_spare_tiff_samples: bool = True allow_encrypted_pdf: bool = False pdf_features: frozenset[str] = frozenset() diff --git a/tests/corpus.py b/tests/corpus.py index aee2992..0ed91ec 100644 --- a/tests/corpus.py +++ b/tests/corpus.py @@ -65,6 +65,17 @@ def png_chunk(kind: bytes, size: int) -> bytes: return _chunk(kind, b"\x00" * size) +def png_exif(block: bytes) -> bytes: + """An ``eXIf`` chunk holding ``block``, for :func:`png`'s ``extra`` or ``after_idat``.""" + return _chunk(b"eXIf", block) + + +def png_with(data: bytes, chunk: bytes, *, after_idat: bool = False) -> bytes: + """A real PNG's bytes with ``chunk`` put in before its image data, or after it.""" + at = data.index(b"IEND" if after_idat else b"IDAT") - 4 + return data[:at] + chunk + data[at:] + + # --- JPEG -------------------------------------------------------------------- @@ -77,15 +88,48 @@ def jpeg( height: int, *, before_sof: bytes = b"", + after_sof: bytes = b"", sof: bool = True, marker: int = 0xC0, components: int = 1, + scan: bool = True, ) -> bytes: - """A JPEG header: SOI, a JFIF APP0, optional padding segments, a SOF (baseline by default).""" + """A JPEG header: SOI, a JFIF APP0, optional padding segments, a SOF (baseline by default). + + ``after_sof`` goes between the frame header and the start of the scan, + where a decoder still reads segments; ``scan`` false leaves the scan + out, as a file cut short after its header. + """ app0 = _segment(0xE0, b"JFIF\x00\x01\x01\x00\x00\x01\x00\x01\x00\x00") layout = b"".join(bytes([n + 1, 0x11, 0]) for n in range(components)) frame = _segment(marker, struct.pack(">BHHB", 8, height, width, components) + layout) - return b"\xff\xd8" + app0 + before_sof + (frame if sof else b"") + b"\xff\xda\x00\x02\xff\xd9" + end = b"\xff\xda\x00\x02\xff\xd9" if scan else b"" + return b"\xff\xd8" + app0 + before_sof + (frame if sof else b"") + after_sof + end + + +def jpeg_exif(block: bytes, *, pieces: int = 1) -> bytes: + """``block`` as a JPEG's EXIF: one APP1 segment, or split across ``pieces`` of them.""" + step = max(1, -(-len(block) // pieces)) + return b"".join( + _segment(0xE1, b"Exif\x00\x00" + block[at : at + step]) + for at in range(0, max(1, len(block)), step) + ) + + +def jpeg_mp_index(block: bytes) -> bytes: + """``block`` as a JPEG's Multi-Picture index: an APP2 segment with the ``MPF`` identifier.""" + return _segment(0xE2, b"MPF\x00" + block) + + +def jpeg_with(data: bytes, segments: bytes, *, after_frame: bool = False) -> bytes: + """A real JPEG's bytes with ``segments`` put in after its SOI, or after its frame header.""" + at = 2 + while after_frame: + marker = data[at + 1] + at += 2 + struct.unpack(">H", data[at + 2 : at + 4])[0] + if marker in (0xC0, 0xC1, 0xC2): + break + return data[:at] + segments + data[at:] _MP_HEADER_AT = 2 + 18 + 4 + 4 @@ -311,6 +355,49 @@ def tiled_tiff(width: int, height: int, tile: int) -> bytes: return b"II*\x00" + struct.pack(" bytes: + """A little-endian tag directory of (tag, type, count, value or offset) entries.""" + fields = b"".join(struct.pack(" bytes: + """A small TIFF of its own, as an EXIF block is, whose tags all claim the same bytes. + + The carrier of CVE-2026-128066: a header and one directory of + ``entries`` private tags (1,000 upwards), each a run of BYTEs that + covers the whole block after its header, at a cost of twelve bytes + apiece. With ``pointer`` (34665 for the Exif directory, 34853 for GPS) + the main directory is honest and holds that one tag, and the + overlapping tags sit in the directory it points to. ``pad`` adds that + many bytes to the end, which the tags claim too. + """ + at = 8 if pointer is None else 8 + 2 + 12 + 4 + total = at + 2 + 12 * entries + 4 + pad + directory = _directory([(1000 + k, 1, total - 8, 8) for k in range(entries)]) + main = b"" if pointer is None else _directory([(pointer, 4, 1, at)]) + return b"II*\x00" + struct.pack(" bytes: + """A complete 1x1 greyscale TIFF, which decodes, whose tags all claim the same bytes. + + As :func:`overlapping_block`, with the tags a decoder needs for the one + pixel: the ``entries`` private tags (40,000 upwards) sit in the frame's + own directory, or with ``pointer`` in the directory that tag points to. + """ + image = [(256, 3, 1, 1), (257, 3, 1, 1), (258, 3, 1, 8), (259, 3, 1, 1), (262, 3, 1, 1)] + image += [(273, 4, 1, 0), (278, 3, 1, 1), (279, 4, 1, 1)] # the pixel is a header byte + own = entries if pointer is None else 1 + after_main = 8 + 2 + 12 * (len(image) + own) + 4 + total = after_main if pointer is None else after_main + 2 + 12 * entries + 4 + overlapping = [(40000 + k, 1, total - 8, 8) for k in range(entries)] + if pointer is None: + return b"II*\x00" + struct.pack(" bytes: diff --git a/tests/test_check.py b/tests/test_check.py index eef604d..43e2183 100644 --- a/tests/test_check.py +++ b/tests/test_check.py @@ -237,6 +237,62 @@ def test_a_tiff_with_a_floating_point_predictor_on_integer_samples( ) assert check(path, Policy(allow_inconsistent_tiff_tags=True)).ok + def test_a_tiff_whose_tags_all_claim_the_same_bytes(self, tmp_path: Path) -> None: + # CVE-2026-128066: the advisory's 144 KB file, 12,000 tags that each + # claim the whole of it, which cost Pillow 1.6 GB inside Image.open. + data = corpus.overlapping_tiff(12_000) + assert len(data) == 144_110 + path = corpus.write(tmp_path / "scan.tif", data) + reason = ( + "a TIFF whose tags claim more data than it holds: frame 1's tags claim " + "1,729,224,000 bytes of data between them in a file of 144,110 bytes" + ) + assert check(path).reasons == (reason,) + assert check(path, STRICT).reasons == (reason,) + # Refusing private tags would not have done: the standard numbers serve as well. + assert check(path, Policy(tiff_tags=frozenset({"standard", "metadata"}))).reasons[-1] == ( + reason + ) + assert check(path, Policy(allow_overlapping_tag_data=True)).ok + hidden = corpus.write(tmp_path / "hidden.tif", corpus.overlapping_tiff(200, pointer=34665)) + assert check(hidden).reasons == ( + "a TIFF whose tags claim more data than it holds: frame 1's Exif tags claim " + "504,000 bytes of data between them in a file of 2,528 bytes", + ) + + def test_a_jpeg_whose_exif_tags_all_claim_the_same_bytes(self, tmp_path: Path) -> None: + # CVE-2026-128066: a 66 KB JPEG whose APP1 segment holds 5,400 such + # tags, about 340 MB inside Image.open, wherever the segment sits. + exif = corpus.jpeg_exif(corpus.overlapping_block(5_400)) + reason = ( + "a JPEG whose tags claim more data than it holds: the EXIF block's tags claim " + "349,952,400 bytes of data between them in a block of 64,814 bytes" + ) + for data in ( + corpus.jpeg(64, 64, before_sof=exif), + corpus.jpeg(64, 64, after_sof=exif), + ): + path = corpus.write(tmp_path / "scan.jpg", data) + assert check(path).reasons == (reason,) + assert check(path, Policy(allow_overlapping_tag_data=True)).ok + index = corpus.jpeg_mp_index(corpus.overlapping_block(5_400)) + path = corpus.write(tmp_path / "pictures.jpg", corpus.jpeg(64, 64, before_sof=index)) + assert check(path).reasons == ( + "a JPEG whose tags claim more data than it holds: the multi-picture index's tags " + "claim 349,952,400 bytes of data between them in a block of 64,814 bytes", + ) + + def test_a_png_whose_exif_tags_all_claim_the_same_bytes(self, tmp_path: Path) -> None: + # CVE-2026-128066: a 96 KB eXIf chunk, 754 MB once a program asks + # for the EXIF, as one does to turn a photograph the right way up. + chunk = corpus.png_exif(corpus.overlapping_block(8_000)) + path = corpus.write(tmp_path / "scan.png", corpus.png(64, 64, extra=chunk)) + assert check(path).reasons == ( + "a PNG whose tags claim more data than it holds: the EXIF block's tags claim " + "768,048,000 bytes of data between them in a block of 96,014 bytes", + ) + assert check(path, Policy(allow_overlapping_tag_data=True)).ok + def test_a_palette_tiff_with_a_spare_sample_under_a_policy_without_them( self, tmp_path: Path ) -> None: diff --git a/tests/test_cli.py b/tests/test_cli.py index 58eaa2d..641b7e1 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -122,6 +122,12 @@ def test_inconsistent_tiff_tags_are_refused_unless_allowed(tmp_path: Path) -> No assert main(["--inconsistent-tiff-tags", str(scan)]) == 0 +def test_overlapping_tag_data_is_refused_unless_allowed(tmp_path: Path) -> None: + scan = corpus.write(tmp_path / "scan.tif", corpus.overlapping_tiff(200)) + assert main([str(scan)]) == 1 + assert main(["--overlapping-tag-data", str(scan)]) == 0 + + def test_spare_tiff_samples_can_be_refused(tmp_path: Path) -> None: scan = corpus.write(tmp_path / "scan.tif", corpus.spare_sample_tiff(64, 4)) assert main([str(scan)]) == 0 diff --git a/tests/test_headers.py b/tests/test_headers.py index 9650ae8..b82efc6 100644 --- a/tests/test_headers.py +++ b/tests/test_headers.py @@ -6,6 +6,7 @@ import io import os import struct +import warnings import pytest from PIL import Image, TiffImagePlugin @@ -331,6 +332,284 @@ def test_spare_samples_as_pillow_reads_them( assert bool(header.spare_samples) == one_band_and_a_tag_that_says_more +def _real(fmt: str, mode: str = "L", **options: object) -> bytes: + buffer = io.BytesIO() + Image.new(mode, (8, 8)).save(buffer, format=fmt, **options) + return buffer.getvalue() + + +def _pillow_refuses_tags(data: bytes) -> bool: + """Whether Pillow's loader, bounded since 13.0.0, skips tags of this file as too large. + + Opened, decoded and asked for its EXIF and the directories that points + to, which is every way a program reaches the loader. + """ + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + with Image.open(io.BytesIO(data)) as image: + image.load() + exif = image.getexif() + for pointer in (34665, 34853, 40965): + exif.get_ifd(pointer) + return any("Tag data larger than file" in str(warning.message) for warning in caught) + + +class TestOverlappingTagData: + """CVE-2026-128066: tags that all claim the same bytes cost a decoder N times the file.""" + + def test_a_tiff_frame_whose_tags_all_claim_the_file(self) -> None: + data = corpus.overlapping_tiff(200) + assert read("tiff", data).overlaps == ( + f"frame 1's tags claim {200 * (len(data) - 8):,} bytes of data between them " + f"in a file of {len(data):,} bytes", + ) + + @pytest.mark.parametrize(("pointer", "name"), [(34665, "Exif"), (34853, "GPS")]) + def test_a_directory_a_tiff_frame_points_to(self, pointer: int, name: str) -> None: + data = corpus.overlapping_tiff(200, pointer=pointer) + assert read("tiff", data).overlaps == ( + f"frame 1's {name} tags claim {200 * (len(data) - 8):,} bytes of data between " + f"them in a file of {len(data):,} bytes", + ) + + def test_tags_with_data_of_their_own_do_not_overlap(self) -> None: + tags = [(700, 1, b"" * 64), (270, 2, b"a scan of a page\x00"), (34675, 7, bytes(512))] + assert read("tiff", corpus.tiff([(10, 10)] * 3, tags=tags)).overlaps == () + + def test_two_tags_may_share_one_value(self) -> None: + """Some writers store one resolution and point both tags at it; that is not this.""" + image = [(256, 3, 1, 1), (257, 3, 1, 1), (282, 5, 1, 62), (283, 5, 1, 62)] + directory = struct.pack(" None: + block = corpus.overlapping_block(200) + expected = ( + f"the EXIF block's tags claim {200 * (len(block) - 8):,} bytes of data between " + f"them in a block of {len(block):,} bytes", + ) + for exif in (corpus.jpeg_exif(block), corpus.jpeg_exif(block, pieces=3)): + assert read("jpeg", corpus.jpeg(64, 64, before_sof=exif)).overlaps == expected + assert read("jpeg", corpus.jpeg(64, 64, after_sof=exif)).overlaps == expected + + def test_the_directories_an_exif_block_points_to(self) -> None: + for pointer, name in ((34665, "Exif"), (34853, "GPS"), (40965, "interoperability")): + block = corpus.overlapping_block(200, pointer=pointer) + data = corpus.jpeg(64, 64, before_sof=corpus.jpeg_exif(block)) + assert read("jpeg", data).overlaps == ( + f"the EXIF block's {name} tags claim {200 * (len(block) - 8):,} bytes of data " + f"between them in a block of {len(block):,} bytes", + ) + + def test_the_thumbnail_directory_of_an_exif_block(self) -> None: + honest = struct.pack(" None: + data = corpus.mpo([(64, 64), (32, 32)]) + second = data.rindex(b"\xff\xd8") + exif = corpus.jpeg_exif(corpus.overlapping_block(100)) + data = data[: second + 2] + exif + data[second + 2 :] + header = read("jpeg", data) + assert header.pages == 2 + assert len(header.overlaps) == 1 + assert header.overlaps[0].startswith("picture 2's EXIF block's tags claim ") + + def test_a_multi_picture_index_whose_tags_all_claim_the_block(self) -> None: + block = corpus.overlapping_block(100) + header = read("jpeg", corpus.mpo([(64, 64)], index=block)) + assert header.pages == 1 + assert header.overlaps == ( + f"the multi-picture index's tags claim {100 * (len(block) - 8):,} bytes of data " + f"between them in a block of {len(block):,} bytes", + ) + + def test_a_png_whose_exif_tags_all_claim_the_block(self) -> None: + block = corpus.overlapping_block(200) + expected = ( + f"the EXIF block's tags claim {200 * (len(block) - 8):,} bytes of data between " + f"them in a block of {len(block):,} bytes", + ) + assert read("png", corpus.png(64, 64, extra=corpus.png_exif(block))).overlaps == expected + after = corpus.png(64, 64, after_idat=corpus.png_exif(block)) + assert read("png", after).overlaps == expected + + @pytest.mark.parametrize( + "block", + [ + b"", + b"II*\x00", # too short for a header + b"not a TIFF header at all", + b"II+\x00" + bytes(40), # a BigTIFF header, which Pillow gives up on + b"II*\x00" + struct.pack(" None: + assert read("jpeg", corpus.jpeg(64, 64, before_sof=corpus.jpeg_exif(block))).overlaps == () + assert read("png", corpus.png(64, 64, extra=corpus.png_exif(block))).overlaps == () + + def test_a_value_outside_the_block_is_not_counted(self) -> None: + """A decoder reads nothing for it, and cameras do write EXIF this sloppy.""" + entries = [(1000 + k, 1, 5000, 4000) for k in range(50)] + block = b"II*\x00" + struct.pack(" None: + """Pillow keeps the values it read before the directory ran out.""" + block = corpus.overlapping_block(200)[: 8 + 2 + 12 * 60] + header = read("jpeg", corpus.jpeg(64, 64, before_sof=corpus.jpeg_exif(block))) + assert len(header.overlaps) == 0 # every value now runs past the end of the block + entries = b"".join(struct.pack(" None: + """The GPS pointer leads back into the main directory, twelve bytes on. + + Read from there, the first entry's tag number is a count of two + entries, so the block's directories hold five entries between + them where it has room for four. + """ + entries = [(2, 1, 1, 0), (3, 1, 1, 0), (34853, 4, 1, 10)] + block = b"II*\x00" + struct.pack(" None: + xmp = ( + b"\xff\xe1" + + struct.pack(">H", 2 + 29 + 8) + + b"http://ns.adobe.com/xap/1.0/\x00" + ) + assert read("jpeg", corpus.jpeg(64, 64, before_sof=xmp)).overlaps == () + + def test_a_pointer_written_as_a_short(self) -> None: + sub = 8 + 2 + 12 + 4 + total = sub + 2 + 12 * 50 + 4 + main = struct.pack(" None: + """Both pointers lead to the same honest directory; it is not counted twice.""" + sub = 8 + 2 + 24 + 4 + main = struct.pack(" None: + """What the reader calls overlapping is what Pillow's bounded loader skips, and no more.""" + fmt = {b"\xff\xd8": "jpeg", b"\x89P": "png", b"II": "tiff"}[data[:2]] + assert bool(read(fmt, data).overlaps) == overlaps, name + assert _pillow_refuses_tags(data) == overlaps, name + + +class TestJpegSegmentsAfterTheFrameHeader: + """A decoder reads segments up to the scan, so the reader does too.""" + + def test_a_profile_after_the_frame_header_is_measured(self) -> None: + data = corpus.jpeg(64, 64, after_sof=corpus.jpeg_profile(70_000)) + assert read("jpeg", data).metadata == ("JPEG colour profile", 70_000) + + def test_a_header_cut_short_after_its_frame_still_reads(self) -> None: + for cut in (corpus.jpeg(640, 480, scan=False), corpus.jpeg(640, 480, scan=False) + b"\xff"): + assert (read("jpeg", cut).width, read("jpeg", cut).height) == (640, 480) + junk = corpus.jpeg(640, 480, scan=False) + b"not a segment" + assert read("jpeg", junk).width == 640 + overrun = corpus.jpeg(640, 480, scan=False) + b"\xff\xfe\xff\xff" + assert read("jpeg", overrun).width == 640 + + def test_a_second_frame_header_is_passed_over(self) -> None: + second = struct.pack(">BBHBHHB", 0xFF, 0xC0, 11, 8, 32, 32, 1) + b"\x01\x11\x00" + assert read("jpeg", corpus.jpeg(640, 480, after_sof=second)).width == 640 + + def test_no_scan_within_the_segment_limit(self) -> None: + data = corpus.jpeg(64, 64, after_sof=corpus.jpeg_padding(headers.MAX_SEGMENTS)) + with pytest.raises(HeaderError, match="no image data in the first 4,096 segments"): + read("jpeg", data) + + class TestTiffCompression: def test_no_tag_means_uncompressed(self) -> None: assert read("tiff", corpus.tiff([(10, 10)])).compression == "none"