Django's ImageField Let an EPS Through. Then Pillow Called Ghostscript
On November 21, pwn.ai published the full write-up of Upload2Shell, now CVE-2026-125396: a use-after-free in Ghostscript's Type 1 font loader that lets a crafted document switch off the -dSAFER sandbox and run commands a
On November 21, pwn.ai published the full write-up of Upload2Shell, now CVE-2026-125396: a use-after-free in Ghostscript's Type 1 font loader that lets a crafted document switch off the -dSAFER sandbox and run commands as whatever account is doing the rendering. Artifex fixed it in Ghostscript 10.08.0 back on September 8, the CVE was published on November 9, and The Hacker News notes there are no reports of it being exploited in the wild.
So why write about a bug that was patched two and a half months ago? Because of one table in the pwn.ai research post. In their tests on Pillow 13.0.0, Image.open() followed by load(), crop() or thumbnail() invoked Ghostscript when the upload contained EPS content, even when the file was named .png. Their list of affected application paths includes Gradio, ComfyUI, InvokeAI, Frappe, Home Assistant and django-filer, all of which reach Ghostscript through Pillow.
I write Django. Pillow is in almost every project we ship. So I opened a shell and checked what Django itself does with that file.
What the bug is, in two paragraphs
Ghostscript renders PostScript and PDF. PostScript is a full programming language, so "rendering" an untrusted PostScript file means running an untrusted program. -dSAFER is the interpreter's own sandbox: checks inside Ghostscript that stop a document from opening files or starting commands. It is not a kernel boundary like seccomp; if the interpreter's memory can be corrupted, the checks can be turned off.
That is what Upload2Shell does. A font-loading helper (.putgstringcopy) used a privileged internal write and did not check its operand types first. A document could make it fail, recover the privileged write from its own error handler, and use it to leave a dangling reference across a save/restore. From there the researchers flipped Ghostscript's path-control flag in memory and ran a command through %pipe%, with -dSAFER still on the command line. CVSS 4.0 scores it 8.5 with a local attack vector, but pwn.ai reached it remotely through an anonymous CUPS print queue on Debian 13, an email thumbnail in Roundcube, public upload forms in two WordPress plugins and several other paths.
What I ran
I did not run the exploit and I did not install Ghostscript. I wanted to know one thing: does a stock Django upload flow let EPS bytes reach the point where Pillow would call gs? To see the call without executing anything, I put a fake gs script on PATH that logs its arguments and exits.
Setup: Python 3.13, Pillow 13.0.0, Django 6.1.3, Django REST Framework 3.18.3, a benign 10Γ10 EPS file (a single line drawn with moveto/lineto) saved as avatar.png.
EPS = b"""%!PS-Adobe-3.0 EPSF-3.0
%%BoundingBox: 0 0 10 10
newpath 0 0 moveto 10 10 lineto stroke showpage
%%EOF
"""
open("avatar.png", "wb").write(EPS)
from PIL import Image
im = Image.open("avatar.png")
print(im.format, im.size) # EPS (10, 10)
im.thumbnail((5, 5)) # needs pixels
Image.open() identified the file as EPS from its bytes and called nothing. The moment thumbnail() needed pixels, my fake gs logged two calls:
gs called: --version
gs called: -q -g10x10 -r72.000000x72.000000 -dBATCH -dNOPAUSE -dSAFER
-sDEVICE=pnmraw -sOutputFile=/tmp/tmpbq1z_wry -c 0 0 translate
-f /workspace/.../avatar.png -c showpage
That matches the pwn.ai table exactly: the file name is irrelevant, the bytes decide, and the renderer starts at the first operation that needs pixels. With no gs on the machine at all, the same call raised OSError: Unable to locate Ghostscript on paths, which is the outcome you want.
Django's ImageField let it through
Next, the part I actually care about. A plain forms.ImageField, the same validation a models.ImageField uses through its form field:
from django import forms
from django.core.files.uploadedfile import SimpleUploadedFile
class AvatarForm(forms.Form):
avatar = forms.ImageField()
f = AvatarForm(files={"avatar": SimpleUploadedFile(
"avatar.png", EPS, content_type="image/png")})
print(f.is_valid()) # True
up = f.cleaned_data["avatar"]
print(up.image.format, up.content_type) # EPS application/postscript
The form was valid. Django's ImageField opens the file with Pillow and calls verify(), which proves Pillow can identify it. It does not restrict which formats Pillow may identify, and EPS is one of them. Two more findings from the same run:
-
"eps" in django.core.validators.get_available_image_extensions()wasTrue, so even the model field's extension validator acceptsphoto.eps. And it only checks the name, which the attacker controls anyway. - DRF's
serializers.ImageFielddelegates to Django's form field, so a DRF upload endpoint behaved the same:is_valid()returnedTrue.
None of this is a Django bug. Validation stopped where it is documented to stop. The problem is what comes next: the thumbnail task, the avatar resize, the "crop your photo" step. Every one of those calls load() on a file Django has already told you is a valid image.
Fix 1: patch the Ghostscript you actually ship
The root fix is Ghostscript 10.08.0 or a distro backport. The catch is that "the server is patched" and "the renderer is patched" are different statements. Updating the host does not touch a Ghostscript inside a container image or a bundled app.
Check inside the image that runs your workers, not on your laptop:
docker run --rm --entrypoint sh your-worker-image -c \
'command -v gs && gs --version; dpkg -s ghostscript 2>/dev/null | grep -i ^version'
Then compare against your distro's tracker for this specific CVE. Per pwn.ai's survey as of November 12:
-
Debian 12 (Bookworm) was still listed as vulnerable. That matters for Python images, because tags like
python:3.13-slim-bookwormare still published and widely pinned. The barepython:3.13-slimtag now resolves to Debian 13 (Trixie), where a fixed package exists. -
Ubuntu shipped fixes for seven releases in USN-8949-1 on October 21 (it predates the CVE and says "No CVE number"); for 24.04 LTS the fixed package is
10.02.1~dfsg1-0ubuntu7.10. - Amazon Linux 2, 2023 and 2027 Preview showed a pending fix, and several SUSE and openSUSE Leap branches were affected or in progress.
A version number below 10.08.0 does not prove you are vulnerable (backports exist), and a recent Ghostscript update for some other CVE does not prove you are fixed. Check the tracker.
Fix 2: allowlist formats where you decode
Even with a patched Ghostscript, there is no reason for an avatar endpoint to run a PostScript interpreter. Pillow lets you say which decoders open() may try:
from PIL import Image, UnidentifiedImageError
SAFE_FORMATS = ["PNG", "JPEG", "WEBP", "GIF"]
try:
im = Image.open(upload, formats=SAFE_FORMATS)
except UnidentifiedImageError:
raise ValueError("Unsupported image type")
On the same avatar.png, this raised UnidentifiedImageError and my fake gs logged nothing.
To put the same rule into Django validation, subclass the form field and check the format Pillow detected:
from django import forms
ALLOWED_IMAGE_FORMATS = {"PNG", "JPEG", "WEBP", "GIF"}
class StrictImageField(forms.ImageField):
def to_python(self, data):
f = super().to_python(data)
if f is not None and f.image.format not in ALLOWED_IMAGE_FORMATS:
raise forms.ValidationError(
"Upload a PNG, JPEG, WebP or GIF image.", code="invalid_image")
return f
The EPS upload now fails with that message and a real PNG still passes. For DRF, the serializer field accepts the Django field class to use:
avatar = serializers.ImageField(_DjangoImageField=StrictImageField)
That rejected the EPS in my run too. The leading underscore means it is not a documented public API, so pin it with a test like the one at the end of this post.
Fix 3: take EPS out of Pillow entirely
If nothing in your process should ever decode EPS, remove it from Pillow's registries once at startup, for example in an AppConfig.ready():
from PIL import Image
def disable_eps():
Image.init()
for registry in (Image.OPEN, Image.SAVE, Image.MIME):
registry.pop("EPS", None)
Image.ID[:] = [fmt for fmt in Image.ID if fmt != "EPS"]
After this ran, a plain Image.open("avatar.png").load() raised UnidentifiedImageError and no gs call was logged. These are module-level registries rather than a documented switch, so treat it as defence in depth behind Fix 2, and keep a test that fails if a Pillow upgrade changes the behaviour.
Fix 4: don't ship Ghostscript where it isn't needed
Pillow only calls Ghostscript if it can find a gs binary. Slim Python images don't include one, but it comes back easily: installing ImageMagick, a PDF tool or a "full" base image can pull it in. If your web or worker image has no business rendering PostScript or PDF, make "no gs on PATH" an explicit check in CI, next to your vulnerability scan.
If you do need PDF or PostScript rendering, and plenty of document products do, move it into a separate worker whose only job is rendering: its own container, a non-root user, no network egress, no application secrets in its environment, a read-only filesystem apart from a scratch directory, and a hard timeout. pwn.ai's commands ran as lp and www-data, the rendering accounts. Make sure the rendering account in your stack can't reach anything worth stealing.
Check the order of operations
One detail from the Roundcube chain is worth copying into code review: the attachment was declared image/jpeg, named quarterly-results.jpg, contained PostScript, and the thumbnail was generated before anything checked the real type. Look for the same shape in your own code: a signal handler or Celery task that generates thumbnails post_save, a library that creates renditions on first request, a preview endpoint that runs before validation. Validation that runs after the renderer is not validation.
If you read our post on the Rails Active Storage upload bug that was really an ImageMagick bug, this is the same lesson one layer lower: the vulnerable code is rarely in your upload handler. It is in whatever your upload handler hands the file to.
What I'm checking on our Django projects this week
No results to report yet, so here is the list rather than a story:
-
grep -rn "Image.open\|thumbnail\|imread" --include=*.py .and note every path where user-supplied bytes get decoded, including thumbnail libraries and admin widgets. - For each one: is there a
formats=allowlist or a strict field in front of it? - In every built image (web, Celery workers, cron jobs): is
gspresent, and if so, which package version and which distro release? - Any base images pinned to
-bookworm? Those get the tracker check first. - A regression test with the benign EPS above, so nobody reintroduces the open path:
# pytest-django; adjust the URL and expected status to your view
def test_avatar_rejects_eps_named_png(client, django_user_model):
user = django_user_model.objects.create_user("u", password="p")
client.force_login(user)
resp = client.post("/account/avatar/", {
"avatar": SimpleUploadedFile("avatar.png", EPS, content_type="image/png"),
})
assert resp.status_code == 400
Not every library behaves like Pillow. In pwn.ai's matrix, OpenCV, prebuilt Sharp, PHP GD, Jimp, Java ImageIO and Go's standard decoders did not start Ghostscript for the same inputs, while imageio and scikit-image did (through Pillow) and libvips depended on how it was built. If you are not on Pillow, check your own decoder rather than assuming either way.
The takeaway
Upload2Shell is patched, and you should still install the patch. But the more useful lesson is about the layer above it: Django will hand your thumbnail code an EPS file that calls itself avatar.png, because "Pillow can identify this" and "this is a photo" are different checks. Add the second check.
So, for your stack: do you allowlist image formats at decode time, or do you rely on keeping Ghostscript patched and off the box? And has anyone actually checked which gs lives in your worker image?
Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes β full credit and traffic to the original publisher.