GitHub advisory · PyPI
Pillow: P;2L and P;4L decoders may read 1 to 3 bytes past the passed buffer size
Description
On main, even with the guard in #9725, it's possible to have these decoders read 1 to 3 bytes past the end of the passed buffer with a suitable width/height.
ImagingRawDecode and the P;2L / P;4L unpackers disagree about how many bytes a line of data occupies.
The raw decoder derives the line size from the bits per pixel
state->bytes = (state->xsize * state->bits + 7) / 8;
and uses it both for the bounds check and to advance to the next line. For P;2L and P;4L, bits is 2 and 4 respectively.
But these two rawmodes are not packed pixels but 2 or 4 bit planes, each padded to a whole number of bytes. unpackP2L computes s = (pixels + 7) / 8 and reads plane k at offset k * s, and unpackP4L does the same across four planes. Their real footprint is therefore planes * ((xsize + 7) / 8).
For some widths, padding each plane separately makes this footprint larger than state->bytes. For example, at width 1, the decoder accounts for one byte, while the unpackers read two or four bytes. The decoder accepts data that is too short for the last line and on the other hand advances to subsequent lines by less than a line, so every line after the first is also read from the wrong offset.
#9725's check is misshapen for this:
P;2L image is 2 bytes but is not accepted.len(data), which is an element count rather than a byte count; e.g. memoryview(array("I", [0,0,0,0,0])) (20 bytes) is rejected while mv.tobytes() is accepted.ghsa_p2l_p4l.py)from array import array
from PIL import Image
# 1 byte past
Image.frombytes("P", (1, 4), array("B", [0] * 4), "raw", "P;2L")
# 3 bytes past
Image.frombytes("P", (1, 8), array("B", [0] * 8), "raw", "P;4L")
is the almost-simplest reproducer.
(array is needed to get ASan to reliably…
Manual fix · PyPI
pip install --upgrade "Pillow>=13.0.0"Sources