Skip to content

Lesson 4 of 19 · 18m

File Uploads and Path Traversal

Filenames are paths and extensions lie — server-generated names, magic-byte checks, and separate-origin serving that contain ImageTragick-class bugs.

You add "upload avatar" to the profile page. Three weeks later you have a web shell at /uploads/shell.php.jpg — or, on a Node/Python stack where .php does nothing, a path-traversal write that planted a file outside uploads/, an SVG that runs as HTML, and a 42 KB zip that expands to 4.5 petabytes inside your unzip call. File upload is the feature where every trust-boundary mistake in this course shows up at once, because an upload is not one input — it is a filename, a declared content type, a byte stream, and whatever your parser does with that byte stream.

The wrong mental model: "it's just an image." Nothing about avatar.jpg is just anything. The filename is attacker-controlled text that lands in a filesystem path or a database row. The Content-Type header is attacker-controlled text that lands in an if statement. The bytes are attacker-controlled input that lands in an image decoder written in C. Each one is a separate door.

The filename is a path

../../etc/cron.d/backdoor is a filename the client is allowed to send. If your code does os.path.join(UPLOAD_DIR, filename) and the filename starts with ../, join does not save you — it produces the traversal you wrote. The same bug in reverse is the download endpoint, GET /files?name=report.pdf fed with ../../../../etc/passwd, and the classic report.pdf%00.png-era tricks where a null byte truncated the validated suffix. Snyk cataloged the archive-extraction version in 2018 as "Zip Slip": a malicious entry named ../../../../evil.sh inside a zip silently escapes the target directory during unzip/tar -x/your ZipFile.extractall call.

The fix is to never let the client's name near the path:

stored_name = f"{uuid4()}{safe_ext}"   # you mint the name
path = os.path.join(UPLOAD_DIR, stored_name)
# and for extraction: resolve each member and confirm it stays under dest
target = (dest / member.filename).resolve()
if dest.resolve() not in target.parents:
    raise ValueError("zip-slip attempt")

The bytes are not the extension

Checking filename.endswith(".jpg") or trusting the Content-Type the client sent proves nothing — the client wrote both. Check magic bytes with python-magic/libmagic or a decoder that actually parses, and then re-encode images through a known-good library (Pillow open-and-resave) before storing. Re-encoding does two jobs: it strips EXIF metadata (GPS coordinates your users did not mean to publish) and it destroys polyglots — files crafted to be a valid GIF and valid HTML simultaneously, which defeat magic-byte sniffing alone.

Three failure shapes to know by name:

  • SVG is markup, not an image. It carries <script> and event handlers. Served inline, it is stored XSS with extra steps — sanitize it as HTML or reject it.
  • Archive bombs. 42.zip is ~42 KB on disk and expands to roughly 4.5 PB across five nested layers. Cap total uncompressed size, file count, nesting depth, and expansion ratio before you call extract.
  • Parser RCE. Your image library is attack surface. ImageTragick — CVE-2016-3714, May 2016 — let a crafted MVG/SVG input execute shell commands through ImageMagick's delegate mechanism and burned a large share of the sites that processed user images at the time. Modern equivalent thinking: if you must parse risky formats, do it in a sandboxed worker with no credentials and no network, or shell out to a minimal, locked-down binary — not the full ImageMagick install with delegates enabled.

Serving is part of the fix

Even a clean file becomes a problem if it serves from your origin with a browser-trusted content type. Store uploads on a separate hostname (uploads.example.com or an object-store bucket behind a CDN), send Content-Disposition: attachment for anything not explicitly renderable, force a fixed Content-Type from your own allowlist, and X-Content-Type-Options: nosniff so browsers can't MIME-confuse a .txt into HTML. An avatar URL served from a different origin means a surviving HTML payload executes outside your session cookie's reach.

Rate-limit and size-cap at the edge — Nginx client_max_body_size, your framework's limit — because "accept unlimited bytes from strangers" is a storage bill and a DoS, not a feature.

Try this

Take your current upload path and run the four checks from the threat-model lesson: traversal filename (../../../tmp/x), extension/content-type mismatch (evil.jpg containing HTML), an SVG with a <script>, and a nested zip. Count how many your code, your storage layer, and your serving layer each independently reject.

Pitfalls

  • MIME from the client is a suggestion. So is the extension. Verify bytes.
  • /tmp is not quarantine — files there get found by other bugs.
  • Virus scanning is a layer, not a control. It misses polyglots, zero-days, and application-level payloads like SVG script.
  • Sanitizing on read instead of write means every read path must remember to do it. They won't.

Was this lesson helpful?

Sign in to rate

Keep reading

Related articles from the SudoSecurity blog.