{"id":"GHSA-27h8-gf7j-v5hc","summary":"Pillow: NULL dereference in ImagingExpand via rank filters on zero-size images","details":"```\n============================================================================\nNULL dereference in ImagingExpand via rank filters on zero-size images\nLocation: src/libImaging/Filter.c:79  in ImagingExpand()\nCommit:   a707c6b21c313880d0771e54965d142dd42358b6\n============================================================================\n```\n\nApplying Pillow's median, minimum, maximum or rank filter to an image with zero width or zero height crashes the whole Python process instead of raising an error. Empty images like this are easy to produce with ordinary calls, for example a crop box whose left and right edges (or top and bottom edges) are equal, or the second page of a crafted multi-page image file. An attacker who can supply crop coordinates or an uploaded file to an application that runs one of these filters can kill its worker process. The effect is a crash only, with no memory disclosure or corruption.\n\nThe fault is in `ImagingExpand()` in `src/libImaging/Filter.c`. This is the edge-padding step that `RankFilter.filter()` always runs through the core `expand()` method, so `MedianFilter`, `MinFilter` and `MaxFilter` go through it too. It fills the margin by copying the input's edge pixels, reading `imIn-\u003eimage[y][0]` and rows `0` / `ysize-1`, and never checks that the input has any pixels. For an empty image, `ImagingAllocateArray` leaves the line pointers NULL, so the first read dereferences NULL and the process dies with SIGSEGV, in every mode.\n\nZero-size images reach this point through public API alone:\n\n- `Image.crop()`, `ImageOps.crop()` and `Image.new()`;\n- a multi-page TIFF opened by path whose second IFD declares `ImageLength = 0`, on which `seek(1)` and `load()` succeed.\n\nEvery other `ImageFilter` returns an empty image for the same inputs. The zero-height case has crashed since the original PIL import, and the zero-width case since Pillow 4.3.0. This is separate from the `margin == 0` fix in #9755: the path is the same, but here the degenerate value is the image size rather than the kernel size. It has the same shape as the zero-dimension `ImagingOffset` crash fixed under GHSA-f87v-9578-p47w.\n\nThe attached reproducer shows a one-pixel-wide control crop filtering normally, while four empty crops passed through the rank filters are each killed by SIGSEGV. A patch that returns early in `ImagingExpand` for empty input is included.\n\n## Details\n\n`ImagingExpand()` (`src/libImaging/Filter.c`), the edge-padding helper that `ImageFilter.RankFilter` runs before the actual rank filter, reads the first pixel of each input line without checking that the input has any pixels. For an image with width 0 or height 0 the line pointers are NULL, so `Image.filter()` with `MedianFilter`, `MinFilter`, `MaxFilter` or `RankFilter` kills the interpreter with SIGSEGV instead of returning or raising:\n\n```python\nfrom PIL import Image, ImageFilter\nim = Image.new(\"L\", (10, 10)).crop((3, 0, 3, 10))   # size (0, 10); crop() accepts left == right\nim.filter(ImageFilter.MedianFilter(3))               # SIGSEGV\n```\n\nUnder gdb on the stock build the fault is at `ImagingExpand (imIn=…, margin=1) at src/libImaging/Filter.c:105` (the `EXPAND(UINT8, image8)` expansion), called from `_expand_image` at `src/_imaging.c:1151`, with `imIn-\u003exsize = 0` and `imIn-\u003eimage[0] = 0x0`. The same happens for every mode the rank filters accept (`L`, `RGB`, `RGBA`, `I`, `F`), and the core `expand(m)` method with `m \u003e= 1` crashes the same way in any mode, including `P`. The same input through `BoxBlur`, `GaussianBlur`, `Kernel`, `ModeFilter` and `UnsharpMask` returns a `(0, 10)` image; a `(1, 10)` crop through `MedianFilter` also returns normally.\n\nThe unchecked edge reads date from the PIL import (`9a640e315`, 2010, so every Pillow release): the zero-height case has crashed since then, and the zero-width case since `fd907fbdc` (\"Fix 0-width and 0-height images other way\", Pillow 4.3.0), which stopped backing zero-width images with a dummy block and left their row pointers NULL. It is adjacent to the `margin == 0` divide-by-zero fix in #9755 — same `expand()` → `ImagingExpand()` path, but the unhandled degenerate value here is the image size rather than the kernel size.\n\nThe path:\n\n```python\n# src/PIL/ImageFilter.py:111-116   RankFilter.filter  (MedianFilter/MinFilter/MaxFilter subclass it)\n        image = image.expand(self.size // 2)\n        return image.rankfilter(self.size, self.rank)\n```\n\n`expand(m)` with `m \u003e 0` is `ImagingExpand(self-\u003eimage, m)` (`src/_imaging.c:1142-1151`). It validates only `margin`, allocates an output of `(xsize+2*margin) × (ysize+2*margin)` — which is non-empty, so the allocation succeeds — and then fills the margin by replicating edge pixels of the input:\n\n```c\n// src/libImaging/Filter.c:70-101\n    imOut =\n        ImagingNewDirty(imIn-\u003emode, imIn-\u003exsize + 2 * margin, imIn-\u003eysize + 2 * margin);\n    …\n#define EXPAND_LINE(type, image, yin, yout)                       \\\n    {                                                             \\\n        for (x = 0; x \u003c margin; x++) {                            \\\n            imOut-\u003eimage[yout][x] = imIn-\u003eimage[yin][0];          \\   // line 79\n        }                                                         \\\n        …                                                         \\\n        for (x = 0; x \u003c margin; x++) {                            \\\n            imOut-\u003eimage[yout][margin + imIn-\u003exsize + x] =        \\\n                imIn-\u003eimage[yin][imIn-\u003exsize - 1];                \\   // [-1] when xsize == 0\n        }                                                         \\\n    }\n\n#define EXPAND(type, image)                                                      \\\n    {                                                                            \\\n        for (y = 0; y \u003c margin; y++) {                                           \\\n            EXPAND_LINE(type, image, 0, y);                                      \\   // line 0 of a 0-line image\n        }                                                                        \\\n        …\n        for (y = 0; y \u003c margin; y++) {                                           \\\n            EXPAND_LINE(type, image, imIn-\u003eysize - 1, margin + imIn-\u003eysize + y); \\   // line -1 when ysize == 0\n        }                                                                        \\\n    }\n```\n\nWhy the line pointers are NULL: `ImagingNewPrologueSubtype` callocs the `im-\u003eimage` pointer array (`src/libImaging/Storage.c:216`, at least one entry), and `ImagingAllocateArray` returns before assigning any of them for an empty image:\n\n```c\n// src/libImaging/Storage.c:423-426\n    /* 0-width or 0-height image. No need to do anything */\n    if (!im-\u003elinesize || !im-\u003eysize) {\n        return im;\n    }\n```\n\nSo with `xsize == 0` every `imIn-\u003eimage[y]` is NULL and `imIn-\u003eimage[yin][0]` faults; with `ysize == 0` the top-margin pass reads `imIn-\u003eimage[0]` (the single calloc'd NULL slot) and faults the same way, and the bottom-margin pass would index `imIn-\u003eimage[-1]`. `ImagingRankFilter` is never reached.\n\nZero-size images are ordinary objects in Pillow and arrive at `filter()` through public API only:\n\n- `Image.crop(box)` rejects only inverted boxes (`src/PIL/Image.py:1385-1390`); `left == right` or `upper == lower` yields a 0×N / N×0 image. `ImageOps.crop(im, border)` with `border == width // 2`, and `Image.new(mode, (0, n))`, do the same.\n- From a file: `ImageFile.__init__` refuses a zero first-frame size (`src/PIL/ImageFile.py:167-173`), but `TiffImagePlugin._setup()` takes `ImageWidth`/`ImageLength` of every later IFD as-is on `seek()` (`src/PIL/TiffImagePlugin.py:1468-1481`). For an uncompressed page of an image opened by path, `ImageFile.load()` takes the mmap branch (`src/PIL/ImageFile.py:307, 325-347`) and `Image.core.map_buffer` builds an `8×0` core image without complaint (`src/map.c:127-141`), so `im.seek(1); im.load()` succeeds and a following `im.filter(ImageFilter.MedianFilter(3))` segfaults in `ImagingExpand` exactly as above (verified under gdb: `imIn-\u003eysize = 0`, `imIn-\u003eimage[0] = 0x0`). A 384-byte two-page TIFF is enough.\n\n## Impact\n\nDenial of service: the whole embedding process (web worker, pipeline process) dies with SIGSEGV rather than the request failing with a Python exception. It is reachable by a remote user in two realistic shapes: (a) an application that crops an upload to user-supplied coordinates and then applies a median/min/max filter (denoise, dilate/erode, thumbnail clean-up) — a box with `x0 == x1` or `y0 == y1` passes `crop()` and crashes the worker; (b) an application that opens an uploaded TIFF from disk by path, iterates its pages and applies a rank filter to each — a crafted second IFD with `ImageLength = 0` crashes it. The faulting access is a read at address 0 (or a fixed small negative offset from the pointer array for the `[-1]` cases, which is not reached because the first read already faults), so there is no memory disclosure or corruption beyond the crash. The same shape, a zero-dimension image crashing C code reached through public API, was fixed in `ImagingOffset` in 39d14a0db (GHSA-f87v-9578-p47w).\n\n## Reproducing\n\n`repro` is a single Python script that uses the installed Pillow as-is (no rebuild). It runs each case in a fresh child interpreter, with core dumps disabled. That way a segfault shows up as the child's exit status and the script itself keeps running. Each child builds `Image.new(\"L\", (10, 10)).crop(box)`, prints its size, calls `im.filter(...)` and then prints the size of the result.\n\n- **Control**: a `(1, 10)` crop (`(3, 0, 4, 10)`) through `MedianFilter(3)`. The rank filter accepts a thin image and must return normally.\n- **PoC**: the rank filters on empty crops.\n  - A `(0, 10)` crop (`left == right`, `(3, 0, 3, 10)`) through `MedianFilter(3)` and `MaxFilter(5)`.\n  - A `(10, 0)` crop (`upper == lower`, `(0, 3, 10, 3)`) through `MinFilter(3)`.\n  - A `(0, 0)` crop (`(3, 3, 3, 3)`) through `RankFilter(3, 4)`.\n\nExpected output on the stock build:\n\n```\n  crop(3, 0, 4, 10)    MedianFilter(3)    (1, 10) -\u003e (1, 10)\n  crop(3, 0, 3, 10)    MedianFilter(3)    (0, 10) -\u003e killed by SIGSEGV\n  crop(3, 0, 3, 10)    MaxFilter(5)       (0, 10) -\u003e killed by SIGSEGV\n  crop(0, 3, 10, 3)    MinFilter(3)       (10, 0) -\u003e killed by SIGSEGV\n  crop(3, 3, 3, 3)     RankFilter(3, 4)   (0, 0) -\u003e killed by SIGSEGV\nBUG\n```\n\nThe size printed before `-\u003e` shows that the empty image was created without error. The crash happens inside `filter()`, in `ImagingExpand`. The last line is `BUG` if the control returned normally and at least one rank-filter child was killed by SIGSEGV. Otherwise it is `OK`. The script covers the crop route only; the TIFF route described above fails the same way (`im.seek(1); im.load(); im.filter(ImageFilter.MedianFilter(3))` on a by-path two-page TIFF whose second IFD has `ImageLength = 0`). With the attached patch, every PoC line prints the unchanged size (for example `(0, 10) -\u003e (0, 10)`) and the script prints `OK`.\n\n## Suggested fix\n\nThe attached patch handles the empty input in `ImagingExpand` (`src/libImaging/Filter.c`), right after the `margin` checks and before the `ImagingNewDirty` allocation and the replication loops. With `xsize == 0` or `ysize == 0` there are no edge pixels to replicate, so it returns a zeroed (`ImagingNew`, not `ImagingNewDirty`) image of the expanded size, with the input's palette copied. This keeps `ImagingExpand`'s size contract, so `ImagingRankFilter` then produces an output of `xsize - 2*margin` × `ysize - 2*margin`, i.e. the original empty size, matching every other filter. It mirrors the existing zero-dimension early returns in `src/libImaging/BoxBlur.c` (127004368) and `src/libImaging/Offset.c` (39d14a0db):\n\n```diff\n--- a/src/libImaging/Filter.c\n+++ b/src/libImaging/Filter.c\n@@ -67,6 +67,17 @@ ImagingExpand(Imaging imIn, int margin) {\n         return (Imaging)ImagingError_ValueError(\"filter size too large\");\n     }\n \n+    if (imIn-\u003exsize == 0 || imIn-\u003eysize == 0) {\n+        /* No edge pixels to replicate (and no lines to read from), so\n+           return a zeroed image of the expanded size */\n+        imOut = ImagingNew(imIn-\u003emode, imIn-\u003exsize + 2 * margin, imIn-\u003eysize + 2 * margin);\n+        if (!imOut) {\n+            return NULL;\n+        }\n+        ImagingCopyPalette(imOut, imIn);\n+        return imOut;\n+    }\n+\n     imOut =\n         ImagingNewDirty(imIn-\u003emode, imIn-\u003exsize + 2 * margin, imIn-\u003eysize + 2 * margin);\n     if (!imOut) {\n```\n\nThe patch also adds `test_rankfilter_zero_dimension` next to `test_rankfilter_error` in `Tests/test_image_filter.py`, which filters `Image.new(\"L\", size)` for `size` in `((0, 6), (6, 0), (0, 0))` with `MinFilter`, `MedianFilter`, `MaxFilter` and `RankFilter(3, 2)` and asserts the size is preserved. Applied to a clean checkout and rebuilt, the reproducer prints `OK` and `Tests/test_image_filter.py` passes. A Python-level guard in `RankFilter.filter` (`if 0 in image.size: return image.copy()`) would also stop the crash, but the C-level check protects any other caller of `expand()`.\n\n## The patch\n\nReturn a zeroed image from ImagingExpand when the input has zero width or height instead of reading NULL line pointers\n\nApplies to `src/libImaging/Filter.c` at the commit above.\n\n```diff\ndiff --git a/Tests/test_image_filter.py b/Tests/test_image_filter.py\nindex 974d4b7a3..8dc8e1a1a 100644\n--- a/Tests/test_image_filter.py\n+++ b/Tests/test_image_filter.py\n@@ -155,6 +155,23 @@ def test_rankfilter_error(filter: ImageFilter.RankFilter) -\u003e None:\n         im.filter(filter).getpixel((1, 1))\n \n \n+@pytest.mark.parametrize(\n+    \"filter\",\n+    (\n+        ImageFilter.MinFilter,\n+        ImageFilter.MedianFilter,\n+        ImageFilter.MaxFilter,\n+        ImageFilter.RankFilter(3, 2),\n+    ),\n+)\n+@pytest.mark.parametrize(\"size\", ((0, 6), (6, 0), (0, 0)))\n+def test_rankfilter_zero_dimension(\n+    filter: ImageFilter.RankFilter, size: tuple[int, int]\n+) -\u003e None:\n+    im = Image.new(\"L\", size)\n+    assert im.filter(filter).size == size\n+\n+\n def test_rankfilter_properties() -\u003e None:\n     rankfilter = ImageFilter.RankFilter(3, 2)\n \ndiff --git a/src/libImaging/Filter.c b/src/libImaging/Filter.c\nindex 3492a871f..d702db5f9 100644\n--- a/src/libImaging/Filter.c\n+++ b/src/libImaging/Filter.c\n@@ -67,6 +67,17 @@ ImagingExpand(Imaging imIn, int margin) {\n         return (Imaging)ImagingError_ValueError(\"filter size too large\");\n     }\n \n+    if (imIn-\u003exsize == 0 || imIn-\u003eysize == 0) {\n+        /* No edge pixels to replicate (and no lines to read from), so\n+           return a zeroed image of the expanded size */\n+        imOut = ImagingNew(imIn-\u003emode, imIn-\u003exsize + 2 * margin, imIn-\u003eysize + 2 * margin);\n+        if (!imOut) {\n+            return NULL;\n+        }\n+        ImagingCopyPalette(imOut, imIn);\n+        return imOut;\n+    }\n+\n     imOut =\n         ImagingNewDirty(imIn-\u003emode, imIn-\u003exsize + 2 * margin, imIn-\u003eysize + 2 * margin);\n     if (!imOut) {\n```\n\n## The reproducer\n\n\u003cdetails\u003e\n\u003csummary\u003eReproducer — \u003ccode\u003erepro\u003c/code\u003e, 1,333 bytes (click to open)\u003c/summary\u003e\n\nIts last line is `BUG` when the issue triggers and `OK` when it does not. Re-run on a clean build of that commit it printed `BUG`.\n\n```python\n#!/usr/bin/env python3\n# Pillow: rank filters (Median/Min/Max/RankFilter) on a 0-wide or 0-high image\n# SIGSEGV in ImagingExpand (src/libImaging/Filter.c) - NULL line pointer read.\n# Each case runs in a child interpreter; BUG if the control returns and any\n# zero-size case dies of SIGSEGV.\nimport signal, subprocess, sys\n\nCHILD = \"\"\"\nimport resource; resource.setrlimit(resource.RLIMIT_CORE, (0, 0))\nfrom PIL import Image, ImageFilter\nim = Image.new(\"L\", (10, 10)).crop(%s)      # public API; crop accepts x0==x1 / y0==y1\nprint(im.size, \"-\u003e\", end=\" \", flush=True)\nprint(im.filter(ImageFilter.%s).size)\n\"\"\"\n\ndef run(box, flt):\n    p = subprocess.run([sys.executable, \"-c\", CHILD % (box, flt)],\n                       capture_output=True, text=True)\n    out = p.stdout.strip()\n    if p.returncode \u003c 0:\n        out += \" killed by \" + signal.Signals(-p.returncode).name\n    print(f\"  crop{box!s:\u003c16} {flt:\u003c18} {out}\")\n    return p.returncode\n\nctrl = run((3, 0, 4, 10), \"MedianFilter(3)\")          # (1,10): must work\nrcs = [run((3, 0, 3, 10), \"MedianFilter(3)\"),        # (0,10)\n       run((3, 0, 3, 10), \"MaxFilter(5)\"),\n       run((0, 3, 10, 3), \"MinFilter(3)\"),           # (10,0)\n       run((3, 3, 3, 3), \"RankFilter(3, 4)\")]        # (0,0)\nbug = ctrl == 0 and any(rc == -signal.SIGSEGV for rc in rcs)\nprint(\"BUG\" if bug else \"OK\")\n```\n\u003c/details\u003e\n\n---","aliases":["CVE-2026-112392"],"modified":"2026-10-21T20:45:04.650633812Z","published":"2026-10-21T20:32:37Z","database_specific":{"severity":"HIGH","github_reviewed":true,"github_reviewed_at":"2026-10-21T20:32:37Z","nvd_published_at":"2026-10-19T22:17:06Z","cwe_ids":["CWE-476"]},"references":[{"type":"WEB","url":"https://github.com/python-pillow/Pillow/security/advisories/GHSA-27h8-gf7j-v5hc"},{"type":"ADVISORY","url":"https://nvd.nist.gov/vuln/detail/CVE-2026-112392"},{"type":"WEB","url":"https://github.com/python-pillow/Pillow/commit/443e3130a8c11594fd0e296afad497e11e678961"},{"type":"PACKAGE","url":"https://github.com/python-pillow/Pillow"},{"type":"WEB","url":"https://github.com/python-pillow/Pillow/releases/tag/13.0.0"}],"affected":[{"package":{"name":"pillow","ecosystem":"PyPI","purl":"pkg:pypi/pillow"},"ranges":[{"type":"ECOSYSTEM","events":[{"introduced":"0"},{"fixed":"13.0.0"}]}],"versions":["1.0","1.1","1.2","1.3","1.4","1.5","1.6","1.7.0","1.7.1","1.7.2","1.7.3","1.7.4","1.7.5","1.7.6","1.7.7","1.7.8","10.0.0","10.0.1","10.1.0","10.2.0","10.3.0","10.4.0","11.0.0","11.1.0","11.2.1","11.3.0","12.0.0","12.1.0","12.1.1","12.2.0","12.3.0","2.0.0","2.1.0","2.2.0","2.2.1","2.2.2","2.3.0","2.3.1","2.3.2","2.4.0","2.5.0","2.5.1","2.5.2","2.5.3","2.6.0","2.6.1","2.6.2","2.7.0","2.8.0","2.8.1","2.8.2","2.9.0","3.0.0","3.1.0","3.1.0.rc1","3.1.0rc1","3.1.1","3.1.2","3.2.0","3.3.0","3.3.1","3.3.2","3.3.3","3.4.0","3.4.1","3.4.2","4.0.0","4.1.0","4.1.1","4.2.0","4.2.1","4.3.0","5.0.0","5.1.0","5.2.0","5.3.0","5.4.0","5.4.0.dev0","5.4.1","6.0.0","6.1.0","6.2.0","6.2.1","6.2.2","7.0.0","7.1.0","7.1.1","7.1.2","7.2.0","8.0.0","8.0.1","8.1.0","8.1.1","8.1.2","8.2.0","8.3.0","8.3.1","8.3.2","8.4.0","9.0.0","9.0.1","9.1.0","9.1.1","9.2.0","9.3.0","9.4.0","9.5.0"],"database_specific":{"last_known_affected_version_range":"\u003c= 12.3.0","source":"https://github.com/github/advisory-database/blob/main/advisories/github-reviewed/2026/10/GHSA-27h8-gf7j-v5hc/GHSA-27h8-gf7j-v5hc.json"}}],"schema_version":"1.9.0","severity":[{"type":"CVSS_V4","score":"CVSS:4.0/AV:N/AC:L/AT:P/PR:N/UI:N/VC:N/VI:N/VA:H/SC:N/SI:N/SA:N"}]}