diff --git a/README.md b/README.md index aac991d..75e9635 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_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 | | `pdf_image_codecs` | jpeg, jpx, jbig2, ccitt | the same | Which codecs a PDF's images may be coded with: JPEG, JPEG 2000 (OpenJPEG), JBIG2 and CCITT fax. Each hands the stream to a decoder of its own inside poppler, and the JBIG2 decoder is where several of its flaws have been (CVE-2025-32365, CVE-2026-93312, CVE-2026-93313). Scanners and the archives that derive PDFs from scans write all four, so both presets allow them; refuse one only when you know your source never writes it. Found by the filter's name in the file, not by `pdfimages -list`, which opens a JPX stream with OpenJPEG just to describe it | diff --git a/docs/advisories/README.md b/docs/advisories/README.md index 536fd18..ec93441 100644 --- a/docs/advisories/README.md +++ b/docs/advisories/README.md @@ -182,7 +182,8 @@ advisory, what rides across: a setting of `max_metadata_bytes` or `max_pages` rather than by default. - A tag in the directory the TIFF reader already walks (private and DNG tags, a ColorMap that does not fit the sample depth, a Predictor libtiff - rejects): B, awaiting a policy on a TIFF's tags. + rejects, a count of samples per pixel the decoder does not keep): B, + with a policy on a TIFF's tags. - The object graph of a PDF handed to Pillow's own parser on append: C. The check belongs in front of that PDF for what it does see, but a cycle in the page tree is not a header field. diff --git a/docs/advisories/record.json b/docs/advisories/record.json index eb59d22..54905e8 100644 --- a/docs/advisories/record.json +++ b/docs/advisories/record.json @@ -1,5 +1,5 @@ { - "generated": "2026-11-09", + "generated": "2026-11-16", "buckets": { "A": "Already refused by an existing check", "B": "Preventable from a header field our readers can see", @@ -17,11 +17,11 @@ "other": "some other way; the finding says" }, "counts": { - "records": 124, + "records": 125, "refused_by_default": 46, "by_bucket": { "A": 39, - "B": 19, + "B": 20, "B2": 3, "C": 19, "D": 3, @@ -31,7 +31,7 @@ "by_library": { "FreeType": 4, "OpenJPEG": 6, - "Pillow": 61, + "Pillow": 62, "libpng": 15, "libtiff": 18, "poppler": 16, @@ -39,6 +39,41 @@ } }, "records": [ + { + "key": "CVE-2026-128067", + "aliases": [], + "library": "Pillow", + "package": "pillow", + "ecosystem": "PyPI", + "title": "Tags carried into a TIFF save make Pillow's libtiff encoder read or write past its row buffer", + "summary": "Pillow: Heap buffer overflow saving TIFF with libtiff when tags override image size", + "published": "2026-11-12", + "severity": 8.4, + "affected": "< 13.0.0", + "fixed": "13.0.0", + "reached_by": "save", + "trigger": "Opening a greyscale or palette TIFF that gives each pixel a spare sample and saving it back as TIFF; or saving any image as a compressed TIFF with the EXIF or the tag table of the file it came from.", + "bucket": "B", + "finding": "The file is the input by three routes, and the check reaches one of them. First, a greyscale or palette TIFF whose pixels carry a second sample declared unspecified (SamplesPerPixel 2, ExtraSamples 0) opens in Pillow as a one-band image while its tag still says two, and a bare save, with no option from the program, hands that tag to libtiff's encoder, which reads two samples for every one in the row. SamplesPerPixel is in the directory the reader walks, and a policy that refuses spare samples refuses the file before Pillow sees it (allow_spare_tiff_samples). It is a valid TIFF that a read is not harmed by, so the default allows it and the setting is what closes this. Second, a JPEG whose EXIF holds TIFF geometry tags (ImageWidth, SamplesPerPixel) reaches the encoder only when the program passes the file's EXIF to a compressed TIFF save; the tags sit in a block the JPEG reader measures and does not parse, so nothing refuses that file. Third, a TIFF with a rotating Orientation, which Pillow turns on load while its tags keep the old size, reaches it when the program passes the tag table or the EXIF back; that file is well formed and every rotated scan is one, so no policy could refuse it without refusing them all. A size that is stale because the program resized the image is the program's own. Tetrak OCR copies each frame before saving, which drops the tag table, and passes no EXIF, so it is not reached there.", + "refusal": { + "check": "allow_spare_tiff_samples", + "default": false, + "setting": "Policy(allow_spare_tiff_samples=False)" + }, + "verified_by": [ + "tests/test_check.py::TestHostileFiles::test_a_palette_tiff_with_a_spare_sample_under_a_policy_without_them" + ], + "protect": { + "general": "Upgrade to Pillow 13.0.0, whose encoder refuses a scanline longer than the row it was given.", + "specific": "Refuse spare samples (allow_spare_tiff_samples) wherever a file from outside is saved back as TIFF; on a Pillow before 13.0.0, do not pass a file's own EXIF or tag table to a TIFF save (exif=, tiffinfo=); upgrade to Pillow 13.0.0." + }, + "sources": [ + "https://osv.dev/vulnerability/GHSA-xcvg-w56q-r89m" + ], + "triaged": "2026-11-16", + "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-107080", "aliases": [], diff --git a/docs/advisories/record/CVE-2026-128067.json b/docs/advisories/record/CVE-2026-128067.json new file mode 100644 index 0000000..da310c3 --- /dev/null +++ b/docs/advisories/record/CVE-2026-128067.json @@ -0,0 +1,35 @@ +{ + "key": "CVE-2026-128067", + "aliases": [], + "library": "Pillow", + "package": "pillow", + "ecosystem": "PyPI", + "title": "Tags carried into a TIFF save make Pillow's libtiff encoder read or write past its row buffer", + "summary": "Pillow: Heap buffer overflow saving TIFF with libtiff when tags override image size", + "published": "2026-11-12", + "severity": 8.4, + "affected": "< 13.0.0", + "fixed": "13.0.0", + "reached_by": "save", + "trigger": "Opening a greyscale or palette TIFF that gives each pixel a spare sample and saving it back as TIFF; or saving any image as a compressed TIFF with the EXIF or the tag table of the file it came from.", + "bucket": "B", + "finding": "The file is the input by three routes, and the check reaches one of them. First, a greyscale or palette TIFF whose pixels carry a second sample declared unspecified (SamplesPerPixel 2, ExtraSamples 0) opens in Pillow as a one-band image while its tag still says two, and a bare save, with no option from the program, hands that tag to libtiff's encoder, which reads two samples for every one in the row. SamplesPerPixel is in the directory the reader walks, and a policy that refuses spare samples refuses the file before Pillow sees it (allow_spare_tiff_samples). It is a valid TIFF that a read is not harmed by, so the default allows it and the setting is what closes this. Second, a JPEG whose EXIF holds TIFF geometry tags (ImageWidth, SamplesPerPixel) reaches the encoder only when the program passes the file's EXIF to a compressed TIFF save; the tags sit in a block the JPEG reader measures and does not parse, so nothing refuses that file. Third, a TIFF with a rotating Orientation, which Pillow turns on load while its tags keep the old size, reaches it when the program passes the tag table or the EXIF back; that file is well formed and every rotated scan is one, so no policy could refuse it without refusing them all. A size that is stale because the program resized the image is the program's own. Tetrak OCR copies each frame before saving, which drops the tag table, and passes no EXIF, so it is not reached there.", + "refusal": { + "check": "allow_spare_tiff_samples", + "default": false, + "setting": "Policy(allow_spare_tiff_samples=False)" + }, + "verified_by": [ + "tests/test_check.py::TestHostileFiles::test_a_palette_tiff_with_a_spare_sample_under_a_policy_without_them" + ], + "protect": { + "general": "Upgrade to Pillow 13.0.0, whose encoder refuses a scanline longer than the row it was given.", + "specific": "Refuse spare samples (allow_spare_tiff_samples) wherever a file from outside is saved back as TIFF; on a Pillow before 13.0.0, do not pass a file's own EXIF or tag table to a TIFF save (exif=, tiffinfo=); upgrade to Pillow 13.0.0." + }, + "sources": [ + "https://osv.dev/vulnerability/GHSA-xcvg-w56q-r89m" + ], + "triaged": "2026-11-16", + "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." +} diff --git a/docs/advisories/seen.json b/docs/advisories/seen.json index f0e7f20..a826457 100644 --- a/docs/advisories/seen.json +++ b/docs/advisories/seen.json @@ -1,5 +1,5 @@ { - "recorded": "2026-11-09", + "recorded": "2026-11-16", "seen": [ "CVE-2003-0107", "CVE-2004-0797", @@ -708,6 +708,7 @@ "CVE-2026-112901", "CVE-2026-112902", "CVE-2026-114501", + "CVE-2026-128067", "CVE-2026-12912", "CVE-2026-18495", "CVE-2026-22184", diff --git a/scripts/fuzz_headers.py b/scripts/fuzz_headers.py index 1e9bfa0..398b111 100644 --- a/scripts/fuzz_headers.py +++ b/scripts/fuzz_headers.py @@ -73,6 +73,7 @@ def seeds() -> list[bytes]: corpus.tiff([(64, 64), (32, 32), (16, 16)]), corpus.tiff([(64, 64)], endian=">"), corpus.tiled_tiff(256, 256, 64), + corpus.spare_sample_tiff(64, 8), ] try: from PIL import Image diff --git a/src/sillybos/check.py b/src/sillybos/check.py index 1531593..785e64f 100644 --- a/src/sillybos/check.py +++ b/src/sillybos/check.py @@ -91,6 +91,10 @@ class Facts: and for a TIFF of standard tags only. inconsistencies: Each way a TIFF's tags contradict each other, in a sentence. Empty when they agree, and for the other formats. + spare_samples: How many samples each pixel of a greyscale or + 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. """ bytes: int @@ -113,6 +117,7 @@ class Facts: codecs: tuple[str, ...] = () tags: tuple[tuple[str, int], ...] = () inconsistencies: tuple[str, ...] = () + spare_samples: int = 0 @dataclass(frozen=True) @@ -268,6 +273,7 @@ def _facts(path: Path, fmt: str, f: headers.Reader, size: int, policy: Policy) - subsampling=header.subsampling, tags=header.tags, inconsistencies=header.inconsistencies, + spare_samples=header.spare_samples, ) @@ -349,6 +355,12 @@ def _against_limits(facts: Facts, policy: Policy, fmt: str) -> list[str]: reasons.append( "a TIFF whose tags contradict each other: " + "; ".join(facts.inconsistencies) ) + if facts.spare_samples and not policy.allow_spare_tiff_samples: + reasons.append( + f"a {facts.colour} TIFF with {facts.spare_samples + 1:,} samples per pixel, where " + "the image uses one and the rest are not an alpha channel; the policy does not " + "allow spare samples" + ) return reasons diff --git a/src/sillybos/cli.py b/src/sillybos/cli.py index 1677155..0fa01e6 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.no_spare_tiff_samples: + changes["allow_spare_tiff_samples"] = False if args.pdf_features: changes["pdf_features"] = frozenset(args.pdf_features.split(",")) if args.pdf_image_codecs: @@ -163,6 +165,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( + "--no-spare-tiff-samples", + action="store_true", + help="refuse a greyscale or palette TIFF whose pixels carry extra samples that are " + "not an alpha channel", + ) parser.add_argument( "--pdf-features", metavar="LIST", diff --git a/src/sillybos/headers.py b/src/sillybos/headers.py index 3284578..5191e9b 100644 --- a/src/sillybos/headers.py +++ b/src/sillybos/headers.py @@ -88,6 +88,15 @@ class Header: other, in a sentence: a ColorMap with the wrong number of entries for the bit depth, a floating-point Predictor on integer samples. Empty when they agree. + spare_samples: For a greyscale or palette TIFF, how many samples + each pixel carries beyond the one the image uses, unless + that is a single sample declared as alpha: 2 samples per + pixel with ExtraSamples 0 ("unspecified data") is 1. The + most in any frame the reader looked at; 0 for a TIFF whose + pixels carry only what its colour model needs, for one + 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. """ width: int @@ -106,6 +115,7 @@ class Header: subsampling: str | None = None tags: tuple[tuple[str, int], ...] = () inconsistencies: tuple[str, ...] = () + spare_samples: int = 0 def _read_exactly(f: Reader, n: int, what: str) -> bytes: @@ -426,10 +436,15 @@ def png(f: Reader, size: int, limit: int) -> Header: _YCBCR_SUBSAMPLING = 530 _PREDICTOR = 317 _COLORMAP = 320 +_EXTRA_SAMPLES = 338 _SAMPLE_FORMAT = 339 _YCBCR = 6 _FLOATING_POINT_PREDICTOR = 3 _FLOATING_POINT_SAMPLES = 3 +_ALPHA = (1, 2) # ExtraSamples: associated and unassociated alpha; 0 is "unspecified data" +_ONE_SAMPLE_COLOURS = ("greyscale", "palette") +"""The colour models whose pixels need one sample, and which a decoder +opens as a one-band image even when the file gives each pixel more.""" _SINGLE_VALUE_TAGS = ( _PREDICTOR, _IMAGE_WIDTH, @@ -592,6 +607,7 @@ def tiff(f: Reader, size: int, limit: int) -> Header: subsampling: str | None = None tags: dict[int, str] = {} # every tag outside the standard set, by number inconsistencies: list[str] = [] + spare_samples = 0 max_pixels = 0 max_side = 0 pages = 0 @@ -615,6 +631,7 @@ def tiff(f: Reader, size: int, limit: int) -> Header: subsampling=subsampling, tags=tuple((kind, number) for number, kind in tags.items()), inconsistencies=tuple(inconsistencies), + spare_samples=spare_samples, ) if offset in seen: raise HeaderError("the frame chain loops back on itself") @@ -639,6 +656,7 @@ def tiff(f: Reader, size: int, limit: int) -> Header: colormap_entries: int | None = None 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 for _ in range(count): tag, kind, n, raw = struct.unpack( endian + "HHI4s", _read_exactly(f, 12, "frame directory") @@ -652,6 +670,14 @@ def tiff(f: Reader, size: int, limit: int) -> Header: # is left as the default, since nothing here depends on # reading it, and a wrong guess would refuse a sound file. (sample_format,) = struct.unpack(endian + "H", raw[:2]) + elif tag == _EXTRA_SAMPLES: + # Only a single SHORT can make the one extra sample alpha; + # any other shape of the tag leaves the samples undeclared. + # Should the tag appear twice, a reading that is not alpha + # stands: decoders differ on which entry they keep. + declared = kind == _TIFF_SHORT and n == 1 + value = struct.unpack(endian + "H", raw[:2])[0] if declared else 0 + alpha = value in _ALPHA and alpha is not False data_size = n * _TYPE_SIZES.get(kind, 1) if data_size > 4: # The field holds an offset to the data. A count that would @@ -734,6 +760,12 @@ def tiff(f: Reader, size: int, limit: int) -> Header: f"frame {pages + 1} uses photometric interpretation {photometric:,}, " "which is not one this library knows" ) + if colour in _ONE_SAMPLE_COLOURS and samples > 1 and not (samples == 2 and alpha): + # A decoder opens this as a one-band image and drops the rest, + # but the tag still says how many samples a row holds, and a + # save that carries the tag across has an encoder read that + # many from a row of one (CVE-2026-128067). + spare_samples = max(spare_samples, samples - 1) if photometric == _YCBCR: this_subsampling = f"{factors[0]}x{factors[1]}" if subsampling is None: @@ -788,6 +820,7 @@ def tiff(f: Reader, size: int, limit: int) -> Header: subsampling=subsampling, tags=tuple((kind, number) for number, kind in tags.items()), inconsistencies=tuple(inconsistencies), + spare_samples=spare_samples, ) diff --git a/src/sillybos/policy.py b/src/sillybos/policy.py index 347ba1f..1e4ca60 100644 --- a/src/sillybos/policy.py +++ b/src/sillybos/policy.py @@ -208,6 +208,21 @@ 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_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 + with ExtraSamples 0, "unspecified data". It is a valid TIFF, + a decoder drops the spare sample on a read, and the default + allows it. A program that opens such a file and saves it + back as a compressed TIFF carries its SamplesPerPixel tag + into libtiff's encoder, which then read two samples for + every one in the row it was given, copying process memory + into the output or, with a Predictor, writing past the row + (CVE-2026-128067); such a program should refuse them. No + scanner writes one. A greyscale or palette TIFF with an + alpha channel, and an RGB or CMYK TIFF with a spare sample, + are not what this refuses: there the decoder's own count of + samples is what the encoder is given. allow_encrypted_pdf: Pass a PDF that `pdfinfo` reports as encrypted. A scanned book never is, so the default refuses. pdf_features: Which of [PDF_FEATURES][sillybos.PDF_FEATURES] a PDF may carry: @@ -262,6 +277,7 @@ class Policy: ) tiff_tags: frozenset[str] = field(default_factory=lambda: frozenset(TIFF_TAGS)) allow_inconsistent_tiff_tags: bool = False + allow_spare_tiff_samples: bool = True allow_encrypted_pdf: bool = False pdf_features: frozenset[str] = frozenset() pdf_image_codecs: frozenset[str] = field(default_factory=lambda: frozenset(PDF_IMAGE_CODECS)) diff --git a/tests/corpus.py b/tests/corpus.py index 481e526..aee2992 100644 --- a/tests/corpus.py +++ b/tests/corpus.py @@ -311,6 +311,53 @@ def tiled_tiff(width: int, height: int, tile: int) -> bytes: return b"II*\x00" + struct.pack(" bytes: + """A complete 8-bit PackBits TIFF with ``samples`` samples to the pixel, pixels and all. + + The default is the carrier of CVE-2026-128067: a palette image whose + pixels each hold a second sample that ExtraSamples declares + "unspecified data" (0). ``photometric`` 1 makes it greyscale and 2 RGB; + ``extra`` 1 or 2 declares the last sample alpha, and ``None`` leaves the + ExtraSamples tag out. Like :func:`tiled_tiff` this one decodes, so that + the agreement test can open it with Pillow; it is compressed because a + program that saves it back with no options inherits the compression, + which is what sends the save through libtiff. + """ + row = bytes(width * samples) + runs = [row[at : at + 128] for at in range(0, len(row), 128)] + strip = b"".join(bytes([len(run) - 1]) + run for run in runs) * height + # (tag, kind, count, the field's data: out of line when over four bytes) + entries: list[tuple[int, int, int, bytes]] = [ + (256, 4, 1, struct.pack(" 4) + entries.append((273, 4, 1, struct.pack(" 4: + fields += struct.pack(" None: + # CVE-2026-128067: SamplesPerPixel 2 on a palette image, which Pillow + # opens as one band and whose tag a bare save hands to libtiff's + # encoder, to read two samples for every one in the row. + path = corpus.write(tmp_path / "scan.tif", corpus.spare_sample_tiff(64, 4)) + verdict = check(path) + assert verdict.ok and verdict.facts is not None and verdict.facts.spare_samples == 1 + assert check(path, STRICT).ok + assert check(path, Policy(allow_spare_tiff_samples=False)).reasons == ( + "a palette TIFF with 2 samples per pixel, where the image uses one and the rest " + "are not an alpha channel; the policy does not allow spare samples", + ) + grey = corpus.write(tmp_path / "grey.tif", corpus.spare_sample_tiff(64, 4, photometric=1)) + assert check(grey, Policy(allow_spare_tiff_samples=False)).reasons == ( + "a greyscale TIFF with 2 samples per pixel, where the image uses one and the rest " + "are not an alpha channel; the policy does not allow spare samples", + ) + for photometric, samples, extra in ((3, 2, 2), (1, 2, 2), (2, 4, 0)): + data = corpus.spare_sample_tiff( + 64, 4, photometric=photometric, samples=samples, extra=extra + ) + kept = corpus.write(tmp_path / f"kept-{photometric}-{extra}.tif", data) + assert check(kept, Policy(allow_spare_tiff_samples=False)).ok + def test_a_cielab_tiff(self, tmp_path: Path) -> None: path = corpus.write(tmp_path / "scan.tif", corpus.tiff([(10, 10)], layout=(8, 3, 8))) verdict = check(path) diff --git a/tests/test_cli.py b/tests/test_cli.py index 1f26276..58eaa2d 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -122,6 +122,13 @@ def test_inconsistent_tiff_tags_are_refused_unless_allowed(tmp_path: Path) -> No assert main(["--inconsistent-tiff-tags", 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 + assert main(["--strict", str(scan)]) == 0 + assert main(["--no-spare-tiff-samples", str(scan)]) == 1 + + def test_pdf_image_codecs_can_be_refused(tmp_path: Path) -> None: scan = corpus.write(tmp_path / "scan.pdf", corpus.pdf_with("jbig2")) assert main([str(scan)]) == 0 diff --git a/tests/test_headers.py b/tests/test_headers.py index fed181e..9650ae8 100644 --- a/tests/test_headers.py +++ b/tests/test_headers.py @@ -259,6 +259,78 @@ def test_a_floating_point_predictor_on_floating_point_samples_is_fine(self) -> N assert read("tiff", data).inconsistencies == () +class TestTiffSpareSamples: + @pytest.mark.parametrize( + ("layout", "extra", "spare"), + [ + ((3, 2, 8), [(338, 3, b"\x00\x00")], 1), # CVE-2026-128067: palette, unspecified + ((1, 2, 8), [(338, 3, b"\x00\x00")], 1), # greyscale, unspecified + ((0, 2, 8), [(338, 3, b"\x00\x00")], 1), # white-is-zero greyscale + ((1, 2, 8), [], 1), # two samples and no ExtraSamples tag at all + ((3, 3, 8), [(338, 3, b"\x02\x00\x00\x00")], 2), # alpha and one more + ((3, 2, 8), [(338, 3, b"\x03\x00")], 1), # a value the tag does not define + ((3, 2, 8), [(338, 1, b"\x02")], 1), # alpha, but not written as a SHORT + ((3, 2, 8), [(338, 3, b"\x00\x00"), (338, 3, b"\x02\x00")], 1), # said twice + ((3, 2, 8), [(338, 3, b"\x02\x00"), (338, 3, b"\x03\x00")], 1), + ((3, 2, 8), [(338, 3, b"\x02\x00")], 0), # unassociated alpha + ((1, 2, 8), [(338, 3, b"\x01\x00")], 0), # associated alpha + ((1, 1, 8), [], 0), + ((3, 1, 8), [], 0), + ((2, 4, 8), [(338, 3, b"\x00\x00")], 0), # RGB keeps its own count of samples + ((5, 5, 8), [(338, 3, b"\x00\x00")], 0), # as does CMYK + ], + ) + def test_samples_beyond_the_one_a_one_sample_image_uses( + self, layout: corpus.Layout, extra: list[tuple[int, int, bytes]], spare: int + ) -> None: + data = corpus.tiff([(10, 10)], compression=5, layout=layout, tags=extra) + assert read("tiff", data).spare_samples == spare + + def test_the_tag_is_read_in_either_byte_order(self) -> None: + for endian in "<>": + alpha = [(338, 3, struct.pack(endian + "H", 2))] + data = corpus.tiff([(10, 10)], endian=endian, layout=(3, 2, 8), tags=alpha) + assert read("tiff", data).spare_samples == 0 + unspecified = [(338, 3, struct.pack(endian + "H", 0))] + data = corpus.tiff([(10, 10)], endian=endian, layout=(3, 2, 8), tags=unspecified) + assert read("tiff", data).spare_samples == 1 + + def test_the_most_in_any_frame_is_reported_when_the_walk_stops(self) -> None: + data = corpus.tiff([(10, 10)] * 4, layout=(3, 2, 8), tags=[(338, 3, b"\x00\x00")]) + header = read("tiff", data, limit=2) + assert not header.complete and header.spare_samples == 1 + + @pytest.mark.parametrize( + ("photometric", "samples", "extra", "mode"), + [ + (3, 2, 0, "P"), # CVE-2026-128067 + (1, 2, 0, "L"), + (3, 2, 2, "PA"), + (1, 2, 2, "LA"), + (2, 4, 0, "RGB"), + (2, 4, 2, "RGBA"), + ], + ) + def test_spare_samples_as_pillow_reads_them( + self, photometric: int, samples: int, extra: int, mode: str + ) -> None: + """Spare is what Pillow opens as one band while the tag it keeps says more. + + That pair is the flaw's precondition: a save sizes its row from the + bands and hands libtiff the tag. + """ + data = corpus.spare_sample_tiff( + 16, 4, photometric=photometric, samples=samples, extra=extra + ) + header = read("tiff", data) + with Image.open(io.BytesIO(data)) as image: + assert isinstance(image, TiffImagePlugin.TiffImageFile) + image.load() + assert image.mode == mode and image.tag_v2[277] == samples + one_band_and_a_tag_that_says_more = len(image.getbands()) == 1 and samples > 1 + assert bool(header.spare_samples) == one_band_and_a_tag_that_says_more + + class TestTiffCompression: def test_no_tag_means_uncompressed(self) -> None: assert read("tiff", corpus.tiff([(10, 10)])).compression == "none"