Unsafe File Upload
An upload form accepts a file from a stranger, stores it on your server and often serves it back to other users. Each of those three steps can go wrong. Stored in the web root under the name the user chose, a file called shell.php may be executed by the server. Served from your main origin as text/html or image/svg+xml, an "avatar" becomes stored XSS for everyone who views it. Processed by a library (an image resizer, a PDF or office converter, an archive extractor), it can trigger parser bugs, path traversal through its name, or resource exhaustion through its size. This lesson builds an upload validator step by step and runs a set of hostile test files through it; the files are tiny byte strings the example creates, not real malware.
Definitions
- Client-supplied metadata: the file name and the
Content-Typeof a multipart part are chosen by the client. Neither proves anything about the content. - Magic bytes: a format's signature at the start of the file: PNG
89 50 4E 47 0D 0A 1A 0A, JPEGFF D8 FF, GIFGIF87a/GIF89a, PDF%PDF-, ZIP (and DOCX, XLSX, JAR, APK)PK\x03\x04. - Polyglot: a file that is valid in two formats at once (a GIF that is also JavaScript, a JPEG with HTML in a comment). Magic-byte checks alone don't stop them, which is why serving rules matter as much as validation.
- Web root: the directory a web server serves (and, for PHP, CGI or ASP, may execute) files from.
- Decompression bomb: a small archive or image that expands to gigabytes (a zip bomb, a PNG with enormous dimensions).
A validator, run against hostile uploads
The validator checks, in order: size, extension against an allow-list, magic bytes matching the extension, for images a dimension limit read from the header (the PNG IHDR chunk), and finally assigns a random server-side name. The fixed random generator is only there so the output is stable; real code uses secrets.token_hex(16).
import random, struct
MAX_BYTES = 2 * 1024 * 1024
ALLOWED = {".png": b"\x89PNG\r\n\x1a\n", ".jpg": b"\xff\xd8\xff", ".jpeg": b"\xff\xd8\xff", ".pdf": b"%PDF-"}
MAX_PIXELS = 25_000_000
rng = random.Random(7) # real code: secrets.token_hex(16)
def png(width, height):
ihdr = struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0)
return b"\x89PNG\r\n\x1a\n" + struct.pack(">I", 13) + b"IHDR" + ihdr + b"\x00" * 4
def validate(filename, content_type, data):
if len(data) > MAX_BYTES:
return "reject: too large"
name = filename.replace("\\", "/").rsplit("/", 1)[-1] # drop any client path
if "." not in name:
return "reject: no extension"
ext = "." + name.rsplit(".", 1)[1].lower() # only the LAST extension counts
if ext not in ALLOWED:
return f"reject: extension {ext} not allowed"
if not data.startswith(ALLOWED[ext]):
return f"reject: content is not {ext[1:].upper()} (magic bytes)"
if ext == ".png":
w, h = struct.unpack(">II", data[16:24])
if w * h > MAX_PIXELS:
return f"reject: {w}x{h} pixels (decompression bomb?)"
stored = f"{rng.getrandbits(64):016x}{ext}"
return f"accept as uploads/{stored} (declared type {content_type!r} ignored)"
tests = [
("cat.png", "image/png", png(640, 480)),
("shell.php", "image/png", b"<?php echo 'lab-marker'; ?>"),
("shell.php.png", "image/png", b"<?php echo 'lab'; ?>"),
("avatar.png.php", "image/png", png(64, 64)),
("logo.svg", "image/svg+xml", b"<svg xmlns='http://www.w3.org/2000/svg' onload='probe()'/>"),
("../../app/settings.png", "image/png", png(10, 10)),
("huge.png", "image/png", png(100_000, 100_000)),
("report.PDF", "application/pdf", b"%PDF-1.7 lab"),
("big.jpg", "image/jpeg", b"\xff\xd8\xff" + b"\x00" * (3 * 1024 * 1024)),
]
for filename, ctype, data in tests:
print(f"{filename:24} {validate(filename, ctype, data)}")cat.png accept as uploads/f2a74de452e6b438.png (declared type 'image/png' ignored)
shell.php reject: extension .php not allowed
shell.php.png reject: content is not PNG (magic bytes)
avatar.png.php reject: extension .php not allowed
logo.svg reject: extension .svg not allowed
../../app/settings.png accept as uploads/6513270e269e0d37.png (declared type 'image/png' ignored)
huge.png reject: 100000x100000 pixels (decompression bomb?)
report.PDF accept as uploads/0c5c7fd0a6a3a450.pdf (declared type 'application/pdf' ignored)
big.jpg reject: too large
Every hostile case was refused or neutralised, most by a different check. The PHP file declared image/png, which proves nothing. shell.php.png has an allowed extension, but its bytes aren't a PNG; avatar.png.php is a real PNG with a dangerous final extension (and Apache configurations that map .php anywhere in the name are why only the last extension must count, and why uploads must never be in an executable directory at all). The SVG was refused because SVG is XML that can carry script. The traversal name was accepted as an image but stored under a random name, so its ../../app/ never reaches the file system. The 3 MiB JPEG hit the size limit before anything else ran. The huge.png header claims ten billion pixels: a resizer would try to allocate tens of gigabytes. Note that the PHP test strings are inert text here; no PHP interpreter exists in this example.
Serving uploads safely
Validation narrows what is stored; serving decides what the browser does with it:
| Rule | Why |
|---|---|
| Store outside the web root, or in object storage (S3, GCS, Azure Blob) | nothing uploaded is ever executed by the app server |
Serve from a separate origin (lab-usercontent.test), never the main app origin |
an HTML or SVG file that slips through runs in a sandbox origin without your cookies |
Set Content-Type from your validated type, plus X-Content-Type-Options: nosniff |
the browser can't "sniff" HTML out of a fake image |
Content-Disposition: attachment for non-images |
documents download instead of rendering |
Content-Security-Policy: default-src 'none'; sandbox on the upload origin |
even rendered content can't run script |
| Re-encode images (decode and save as a fresh PNG/JPEG/WebP) | strips metadata (EXIF with GPS), comments and polyglot payloads |
How upload flaws are detected
- Testing (in scope): upload files that differ from what the form expects in each property separately: name (double and mixed-case extensions,
.php5,.phtml,.jsp,.aspx,.svg,.html, traversal sequences, very long names, NUL bytes), declared type, real content, size, image dimensions, archive contents. Then fetch each stored file: is it served? From which origin? With whichContent-Type? Is it executed? Use harmless markers (<?php echo 'm4rk3r'; ?>in a lab app), never working web shells. - Code review: the original file name used in the storage path;
Content-Typefrom the request trusted; uploads saved under a served directory; image libraries without size limits; extraction of archives without entry-name checks (path traversal). - Monitoring: new executable files in web directories (file-integrity monitoring), the web server process spawning shells (see command injection), requests to
/uploads/*.php, and malware scanning (ClamAV or a cloud scanner) of stored files.
How it is fixed
- Allow-list extensions and check the content (magic bytes, then a real parser or re-encoding).
- Size and dimension limits before processing; process in an isolated worker with memory and time limits.
- Random storage names, original names kept as metadata only (and encoded when displayed).
- Storage outside the web root, served from a separate origin with the headers above.
- Scan for malware where users share files with each other.
Pitfalls
- Trusting
Content-Typeor the extension alone. - Validating, then storing the original bytes under the original name in a public folder.
- Image libraries are attack surface: ImageMagick, Ghostscript and others have had remote-code-execution bugs triggered by crafted files; keep them patched and sandboxed, and restrict which coders/formats they accept.
Practice
1. Why does the validator take only the last extension and lower-case it?
The last extension is what most servers and browsers use to choose a handler or type; .PNG and .png must be treated the same; and considering any earlier extension (shell.php.png) as "the" type leads to inconsistent decisions between your validator and the server.
2. An SVG avatar feature is a product requirement. How do you allow it safely?
Convert SVG to a raster image server-side in a sandboxed worker and serve the PNG; or sanitise the SVG with an allow-list (no script, no event handlers, no external references) and serve it from a separate origin with Content-Security-Policy: default-src 'none'; style-src 'unsafe-inline'; sandbox and nosniff.
Test yourself
Which part of an upload can the server trust?
- The file name
- The declared Content-Type
- Nothing the client sent; only what the server checks itself
- The extension
Why must uploads be served from a separate origin?
- Speed
- An HTML or SVG file that slips through then runs without access to the main app's cookies and DOM
- It is required by HTTP
- To save storage
In the example, why was huge.png rejected although its magic bytes were correct?
- It was too many bytes
- Its header claims 100,000 x 100,000 pixels: a decompression bomb for any resizer
- Wrong extension
- It was an SVG
What does re-encoding an uploaded image achieve?
- Nothing
- It strips metadata, comments and polyglot payloads, keeping only pixels
- It encrypts the image
- It makes it larger