DEV Community

Cover image for 📤 File Upload Security: Why Your Extension Check Fails (and the Fix)
Krishna Kumar
Krishna Kumar

Posted on

📤 File Upload Security: Why Your Extension Check Fails (and the Fix)

Most upload handlers ask the uploaded file three questions: what's your name, what type are you, and what do your first few bytes look like? Then they believe the answers.

All three answers come from the client. The filename is a string in the request. The Content-Type is a string in the request. The bytes are, obviously, whatever was sent. A check built on any one of them is a check the sender gets to fill in.

This post is the developer side of file upload bugs: four checks that look fine in code review, what gets past each one, a small upload function where the server decides everything that matters, and a test suite that goes red on the old code and green on the new. Everything runs locally with harmless stand-in files (one line of HTML, nothing executable). Only test systems you own or are authorized to test.

What the bug is

PortSwigger describes file upload vulnerabilities as a server accepting files without properly validating things like their name, type, contents or size. It's tracked as CWE-434, "Unrestricted Upload of File with Dangerous Type".

PortSwigger also makes the point that decides severity: the impact depends on which property you failed to validate and on what restrictions apply to the file once it's stored. That second half is where most fixes stop too early. The worst case is a server that executes what it stored. But a file doesn't need to execute on the server to hurt you:

  • An HTML or SVG file containing a script, served back from your own origin, is stored XSS. PortSwigger notes this only works when the file is served from the same origin it was uploaded to, which is a hint about the fix.
  • A filename that's used as a path can overwrite files or land outside the upload folder.
  • No size limit means anyone can fill your disk.

So there are two jobs: decide what to accept, and make sure whatever you accepted is inert when it's served.

Four checks that look fine

Here are four validators of the kind that pass review, and a script that runs four stand-in uploads through each. Every "file" is a line of HTML; one has a PNG signature glued on the front.

"""Four upload checks that look fine in review, and what gets past each.
Every 'file' here is a harmless stand-in: a line of HTML, nothing executable."""
import posixpath

PNG_MAGIC = b"\x89PNG\r\n\x1a\n"
HTML = b"<h1>not an image</h1>"


def blocklist(name, ctype, data):
    return not name.endswith((".php", ".exe", ".sh"))


def contains_ext(name, ctype, data):
    return ".png" in name or ".jpg" in name


def content_type(name, ctype, data):
    return ctype in ("image/png", "image/jpeg")


def magic_only(name, ctype, data):
    return data.startswith(PNG_MAGIC)


CHECKS = [blocklist, contains_ext, content_type, magic_only]

UPLOADS = [
    # (filename, Content-Type sent by the client, bytes)
    ("page.html", "text/html", HTML),
    ("avatar.png.html", "text/html", HTML),
    ("notes.html", "image/png", HTML),
    ("pixel.html", "text/html", PNG_MAGIC + HTML),
]

for check in CHECKS:
    passed = [name for name, ctype, data in UPLOADS if check(name, ctype, data)]
    print(f"{check.__name__:<13} accepts: {', '.join(passed) or '-'}")

# The fifth problem is not a check at all: trusting the name as a path.
for name in ("avatar.png", "../app/templates/home.png"):
    print(f"{name!r:<29} -> {posixpath.normpath(posixpath.join('/srv/uploads', name))}")
Enter fullscreen mode Exit fullscreen mode

Output from my run (Python 3.14):

blocklist     accepts: page.html, avatar.png.html, notes.html, pixel.html
contains_ext  accepts: avatar.png.html
content_type  accepts: notes.html
magic_only    accepts: pixel.html
'avatar.png'                  -> /srv/uploads/avatar.png
'../app/templates/home.png'   -> /srv/app/templates/home.png
Enter fullscreen mode Exit fullscreen mode

Each check accepted at least one HTML file. Here's why, with what the primary sources say about each:

  1. The blocklist. You can't list every dangerous extension. This one forgot .html, and it would also miss .pHp, because it's case-sensitive. The OWASP File Upload Cheat Sheet calls blocking extensions a weak protection on its own, and PortSwigger lists lesser-known executable extensions that slip past such lists.
  2. "Contains .png". The extension that matters is the last one. OWASP uses a double extension as its example of what gets past a loose pattern match.
  3. The Content-Type. In a multipart upload, each part's Content-Type is written by the client. OWASP says it can't be trusted and is trivial to spoof; treat it as a quick sanity check at most.
  4. Magic bytes alone. The first bytes prove what the first bytes are. The Django security docs describe exactly this file: a valid PNG header followed by HTML, which passes the image library's verification. OWASP says signature validation shouldn't be used on its own.
  5. The name as a path. The last two lines of output aren't a failed check; they're the missing one. Join a client filename to your upload folder and the client picks where the file goes.

The fix: the server decides

The pattern that holds is the one the OWASP cheat sheet and PortSwigger's prevention list describe between them: allowlist the extension, give the file a name of your own, don't let the client's filename act as a path, and (from OWASP) cap the size. Here it is as one function plus the headers for serving the file back.

"""Accept an upload by deciding everything on the server side."""
import uuid
from pathlib import Path

MAX_BYTES = 2 * 1000 * 1000  # pick the smallest limit your feature can live with

# extension -> (leading bytes we expect, Content-Type WE will serve it with)
ALLOWED = {
    ".png": (b"\x89PNG\r\n\x1a\n", "image/png"),
    ".jpg": (b"\xff\xd8\xff", "image/jpeg"),
    ".jpeg": (b"\xff\xd8\xff", "image/jpeg"),
    ".pdf": (b"%PDF-", "application/pdf"),
}


class UploadRejected(ValueError):
    pass


def store_upload(upload_dir: Path, original_name: str, data: bytes) -> str:
    """Validate, then write under a name we generate. Returns that name (the file ID)."""
    if len(data) > MAX_BYTES:
        raise UploadRejected("too large")

    # 1. The client's name is used for one thing: reading the LAST extension.
    ext = Path(original_name).suffix.lower()
    if ext not in ALLOWED:
        raise UploadRejected(f"extension {ext or '(none)'} not allowed")

    # 2. The bytes must agree with that extension. The client's Content-Type is never read.
    magic, _ = ALLOWED[ext]
    if not data.startswith(magic):
        raise UploadRejected("content does not match extension")

    # 3. The stored name is ours: random, with the extension we validated.
    file_id = f"{uuid.uuid4().hex}{ext}"
    (upload_dir / file_id).write_bytes(data)
    return file_id


def download_headers(file_id: str) -> dict:
    """Headers for serving a stored file. The type comes from our table, not the client."""
    _, ctype = ALLOWED[Path(file_id).suffix]
    return {
        "Content-Type": ctype,
        "X-Content-Type-Options": "nosniff",
        "Content-Disposition": f'attachment; filename="{file_id}"',
    }
Enter fullscreen mode Exit fullscreen mode

What each decision buys you:

  • The extension is an allowlist, read from the last suffix, lowercased. avatar.png.html is .html and is rejected. .htaccess has no suffix at all and is rejected. No SVG unless you add it on purpose, and if you do, remember it can carry script.
  • The client's filename never reaches the filesystem. The stored name is a random ID plus the extension you validated, so traversal sequences, overwrites and odd characters have nowhere to go. If you need the original name for display, keep it in a database column and escape it when you render it. Werkzeug's secure_filename is fine for cleaning a display name, but its docs note it can return an empty string, so it isn't a replacement for generating your own.
  • The Content-Type you serve comes from your table. With X-Content-Type-Options: nosniff, MDN says the browser uses the declared type instead of guessing, so a response declared as image/png isn't treated as HTML. Content-Disposition: attachment tells the browser to download rather than display. For images you want shown inline, drop that header and keep the other two.

What the client claims about an upload, the check that believes it, and what the server decides instead

Be honest about what the signature check does. A PNG header followed by HTML, uploaded as pixel.png, passes this function. That's fine, and it's the point of the second job: it's stored as <random>.png and served as image/png with nosniff, so nothing renders it as a page. The content check narrows what you accept; the storage and serving rules are what make the leftovers harmless. OWASP makes the same kind of caveat about re-encoding images: worth doing, not a guarantee.

The parts that live outside the function

Some of the fix is configuration, and no unit test of store_upload will cover it:

  • Where the files live. OWASP's order of preference: a different host, otherwise outside the webroot, with a handler that maps IDs to files for public access. upload_dir above should not be a folder your web server serves or executes from.
  • Which origin serves them. Django's docs recommend serving user content from a distinct top-level or second-level domain, and say a subdomain of your main site isn't enough. That's what takes the stored-XSS case off the table even if a header gets dropped somewhere.
  • No code execution in the upload path. Django's docs call out disabling handlers that would execute static files as code; OWASP adds disabling per-directory config overrides so an uploaded config file can't change the rules.
  • Size limits before your code runs. len(data) only helps after the body is in memory. Flask's upload docs say it accepts unlimited sizes by default and that setting MAX_CONTENT_LENGTH makes it reject larger bodies with RequestEntityTooLarge (a 413); Django's docs say to cap the body at the web server as well.
  • Who can upload. OWASP lists authentication, authorization and CSRF protection for the upload endpoint alongside the file checks.
# Flask, from its file upload docs; not run for this post
app.config["MAX_CONTENT_LENGTH"] = 2 * 1000 * 1000
Enter fullscreen mode Exit fullscreen mode

Prove the fix

A fix you haven't seen fail is a hope. These tests start with a control (a real upload still works), then make sure each rejected file leaves nothing on disk.

import re
import tempfile
import unittest
from pathlib import Path

from uploads import MAX_BYTES, UploadRejected, download_headers, store_upload

PNG = b"\x89PNG\r\n\x1a\n" + b"\x00" * 32
HTML = b"<h1>not an image</h1>"


class UploadTests(unittest.TestCase):
    def setUp(self):
        self.tmp = tempfile.TemporaryDirectory()
        self.root = Path(self.tmp.name)
        self.uploads = self.root / "uploads"
        self.uploads.mkdir()

    def tearDown(self):
        self.tmp.cleanup()

    def stored(self):
        return sorted(p.relative_to(self.root).as_posix() for p in self.root.rglob("*") if p.is_file())

    def test_control_real_png_is_stored_under_our_name(self):
        file_id = store_upload(self.uploads, "My Avatar.PNG", PNG)
        self.assertRegex(file_id, r"^[0-9a-f]{32}\.png$")
        self.assertEqual(self.stored(), [f"uploads/{file_id}"])

    def test_rejects_extensions_outside_the_allowlist(self):
        for name in ("page.html", "avatar.png.html", "logo.svg", "run.pHp", "noext", ".htaccess"):
            with self.subTest(name=name), self.assertRaises(UploadRejected):
                store_upload(self.uploads, name, PNG)
        self.assertEqual(self.stored(), [])

    def test_rejects_content_that_does_not_match_the_extension(self):
        with self.assertRaises(UploadRejected):
            store_upload(self.uploads, "avatar.png", HTML)
        self.assertEqual(self.stored(), [])

    def test_client_path_never_reaches_the_filesystem(self):
        file_id = store_upload(self.uploads, "../app/templates/home.png", PNG)
        self.assertEqual(self.stored(), [f"uploads/{file_id}"])

    def test_rejects_oversized_upload(self):
        with self.assertRaises(UploadRejected):
            store_upload(self.uploads, "big.png", PNG + b"\x00" * MAX_BYTES)

    def test_download_headers_come_from_our_table(self):
        file_id = store_upload(self.uploads, "pixel.png", PNG + HTML)
        headers = download_headers(file_id)
        self.assertEqual(headers["Content-Type"], "image/png")
        self.assertEqual(headers["X-Content-Type-Options"], "nosniff")
        self.assertTrue(re.match(r'^attachment; filename="[0-9a-f]{32}\.png"$', headers["Content-Disposition"]))


if __name__ == "__main__":
    unittest.main()
Enter fullscreen mode Exit fullscreen mode

Against the function above:

Ran 6 tests in 0.030s

OK
Enter fullscreen mode Exit fullscreen mode

Then I pointed the same tests at a "before" version: the blocklist from earlier, writing to upload_dir / original_name, with no serving headers. All six tests failed:

FAILED (failures=11, errors=1)
Enter fullscreen mode Exit fullscreen mode

The count is higher than six because each filename in the allowlist test reports separately. Even the control fails there, since the file is stored under the client's name. The traversal test is the one to look at: the old code wrote app/templates/home.png next to the uploads folder, inside the temp directory, exactly where the name told it to.

If you're testing someone else's upload feature with permission, the same logic applies in reverse. An upload being accepted is a lead, not a finding. The proof is what happens when you request the file back: which URL and origin it's served from, with which Content-Type, and whether a harmless marker like the heading above renders as a page. Detection isn't proof; the response is.

Try it yourself

Only on targets you own or are authorized to test.

Conclusion

Filename, Content-Type and leading bytes are claims. Use the last extension as a filter, make the bytes agree with it, and then stop trusting the file anyway: give it your own name, keep it out of the webroot, and serve it with a type you chose from an origin that isn't your app. Then keep the tests, so the next refactor can't quietly bring the old behaviour back.

Further reading

I'm Krishna, a pentester and the founder of Xalgorix, an open-source AI pentester that only reports vulnerabilities it has actually exploited.


🔐 If this was useful, follow me for more hands-on web & API security write-ups.

🔗 Connect with me on LinkedIn: https://www.linkedin.com/in/xalgord/

Top comments (0)