Blog Details

blog
about

Your upload form runs a stranger's bytes through a parser

Your upload form runs a stranger's bytes through a parser

The endpoint that runs a parser on someone else's bytes

Nearly every part of a web application treats input as text. JSON arrives, a schema validator rejects half of it. A query string arrives, the router splits it. A form field arrives and goes into a prepared statement. You have libraries for all of that, and years of habit telling you what sanitising means.

Uploads are the exception. A stranger picks the bytes, and a piece of C code you installed six years ago tries to make sense of them. PNG, JPEG, PDF, ZIP, HEIC, WebP, DOCX, MP4: every one of those formats is parsed by software with a long history of memory-safety bugs, and the parsing happens inside your request cycle. CVE-2026-46520 was a heap buffer overflow in ImageMagick's multi-frame handling, reachable from any service that converts a user-supplied image. That is a thumbnail generator on a marketplace. That is a profile photo form.

Most teams think about one failure here: a malicious file getting executed. Three others cost less to fix and do more damage in practice.

  • Code execution through the parser, or through a file that lands somewhere executable.
  • Availability loss from a file that is small on disk and enormous in memory.
  • Stored XSS from a file the browser treats as a document instead of an image.
  • Data leakage from metadata nobody looked at, on a file that is otherwise perfectly safe.

An extension is a string the uploader writes

A filename is attacker-controlled text. So is the Content-Type header, and so is everything else in a multipart body. None of it describes what the file contains, because the client sets all of it. This is the first thing to internalise: validation that trusts the client is decoration.

Content sniffing is better and still not sufficient. PHP's getimagesize() and mime_content_type() read the leading bytes and match a signature. A file that begins with GIF89a and then contains PHP is a legitimate GIF as far as the sniffer is concerned, and it is also legitimate PHP. Polyglots are not exotic; they are a weekend exercise. The same trick works with JPEG comment segments and with ZIP files that are also valid PDFs.

The check has to be structural, not declarative. Either a library fully decodes the file and you accept what it produces, or you reject the upload. "The extension was jpg and the header looked right" is a formality that costs a line of code and buys nothing.

SVG is a document, not an image

This is where the stored XSS comes from, and it keeps shipping. CVE-2026-5615 was a file upload XSS in Vvvebjs: the allow-list in upload.php simply included svg. CVE-2026-27621 hit TypiCMS, where the MIME type was validated and the content was not, so a crafted SVG with a script element saved cleanly and executed when an administrator opened it.

The mechanics are simple. SVG is XML. Browsers render it natively. If you serve it as image/svg+xml from your own origin, any script inside it runs with your origin's cookies, your origin's session, your admin's privileges. Serving it under a path that "only admins can see" makes it worse, not better, because admins are the interesting target.

Three options exist and only three. Reject SVG if you are not certain you need it, which is most of the time. Sanitise it with a real XML parser that strips script elements, event handler attributes, and external references: a purpose-built sanitiser, not a regular expression. Or serve it from a separate cookieless hostname with a sandboxing Content-Security-Policy and Content-Disposition: attachment. A regex over the file text is not an option, because XML can encode the same payload a dozen ways.

Decode once, re-encode, throw the original away

The control that fixes the most problems at once is unglamorous. Accept the bytes into a scratch location outside the web root, decode them with an image library, write a fresh JPEG or PNG that your own code produced, and delete the upload. What the user downloaded afterwards is a file you made, so nothing they embedded survives: no EXIF, no trailing PHP after the image data, no polyglot trailer, no malformed chunk that exploits a decoder quirk on the next read.

The catch is that this moves the risk instead of removing it. The decoder is now the thing processing hostile input, and image decoders are the most reliably exploitable component in a typical stack. Treat that worker as hostile territory. Give it a container, a seccomp profile, no network, no database credentials, and a memory ceiling that would make the process die instead of swap.

ImageMagick deserves its own line because so many PHP and Node stacks reach for it. Its security model is "everything allowed unless denied", and the default policy.xml denies almost nothing. The module deny that vendors now recommend is worth pasting verbatim: deny {LABEL,MSL,MVG,PS,SVG,TEXT,URL,XPS}, then cap memory, disk, width, height, and frame count. Those coders are the ones that reach outside the file, fetch URLs, read local paths through indirect filenames, or shell out to Ghostscript. If your stack never renders SVG or PostScript server-side, none of them need to be available at all.

Files that cost nothing to send and everything to open

A PNG of forty kilobytes can decode to three gigabytes of pixel data. A ZIP of a megabyte can legitimately expand past a gigabyte, because DEFLATE tops out around a thousand-to-one and the format has no obligation to be polite. A twelve thousand pixel square is 144 megapixels, which is 576 megabytes once it sits in memory as raw RGBA before your resize touches it.

None of that is a bug in the format. None of it is caught by a file-size limit.

Two pre-checks handle most of it. Read the declared dimensions from the header before decoding: PNG puts width and height in IHDR, JPEG in a SOF marker. Reject anything over roughly twelve thousand pixels on a side or forty megapixels in total, and reject the file rather than clamping it, because an unusual declared size on an ordinary product photo is itself the signal. For archives, cap the uncompressed byte count while you stream, checking the running total as each block lands, so the process stops before the disk fills rather than after.

Multi-frame formats are the same attack with extra steps. An animated GIF, APNG, or TIFF with ten thousand frames is a dimension bomb that also happens to pass a per-frame check. Cap the frame count at one for anything you are not deliberately animating.

Where the file lands is half the vulnerability

Writing uploads into the document root with the name the client supplied connects every other weakness to a web shell. shell.php.jpg becomes code the moment a misconfigured handler mapping decides the last dot does not matter, and that mapping lives in Apache config that nobody has read since the site launched.

Name the file yourself. A UUID, extension chosen from your own allow-list based on the format you decoded, stored outside the web root, served by a handler that sets the headers. Keep the display name in a database column for the Content-Disposition header. There is no reason for the original name to reach the filesystem at all, and every reason for it not to: traversal sequences, null bytes, control characters, and 400-character Unicode filenames all disappear as a class of bug.

Then fix the serving side. X-Content-Type-Options: nosniff on every response, an explicit Content-Type from your own mapping rather than the stored value, Content-Disposition: attachment for anything you did not re-encode, and a separate hostname for user content. A separate origin is the difference between a stored XSS on a support attachment and a stored XSS inside an authenticated admin session.

Metadata is customer data you published by accident

Phone photos carry GPS coordinates, capture timestamps, device model, serial number, and often a thumbnail of an earlier crop. On a marketplace listing, that is a seller's home address in the first photo they uploaded. On a KYC document, it is a secondary identifier that ties a passport scan to a physical location. Neither shows up in a thumbnail, and neither is caught by any validation rule.

Stripping tags with an EXIF tool removes the readable fields and leaves the container, including any segments the tool did not recognise. Re-encoding removes the container, which is why the decode step from earlier does this job for free. PDFs and DOCX are harder: author names, original filesystem paths, and revision history survive in ways that most tools do not surface. If a document leaves your platform for a customer, open the copy you plan to send and read its properties first.

Validation is not authorization

Every uploaded file gets an identifier, and identifiers are the easiest thing in an application to enumerate. A route like /api/files/9182 that returns whatever the row points at, without checking which tenant owns it, is broken object-level authorization, and no amount of MIME validation touches it. The same applies to presigned URLs: scoped to one object, short-lived, and never the only control on a sensitive document.

Storage buckets get checked from outside, not from the console. Fetch a known object URL from a machine that is not yours and see what comes back. Public read on a media bucket is a common default and it usually survives until someone notices.

The order to fix it in

Most upload pipelines were built in an afternoon by whoever shipped the feature first, then left alone because they kept working. The surface is small and bounded, which makes it one of the cheapest places in a codebase to put a real control. Work through it in this order, because each step removes a class of attack rather than a single instance.

  1. Cut the allow-list down to formats you actually display, and drop SVG, HTML, and PostScript unless there is a business case you can name.
  2. Cap file size, declared dimensions, and frame count before anything decodes the file.
  3. Decode in an isolated worker, re-encode, and discard the original bytes.
  4. Generate the stored filename yourself and keep it out of the document root.
  5. Serve through a handler with nosniff, an explicit content type, and a separate origin for user content.
  6. Check tenant ownership on every file read, including downloads and thumbnails.
  7. Harden the image library itself: module denies, resource limits, no network from that container.

Run the pipeline against your own worst file before someone else does. A 12,000 pixel square PNG, an SVG with a script tag in the first element, a GIF declaring 10,000 frames, a JPEG with GPS coordinates for a street address. Push all four through the real worker, with the real memory limit, and watch what it does. That takes twenty minutes and tells you more about the upload path than a scan report will, because the scan report only knows which library version you pinned and not what your code did with it.

Send Us a Message