← Lessons

quiz vs the machine

Gold1460

Security

Security Of File Uploads

Why accepting files is risky and how to store and serve them safely.

6 min read · core · beat Gold to climb

The Risk

Accepting uploads invites several problems. A file disguised as an image may be executable on the server. A user controlled name can trigger path traversal. A huge file can exhaust storage. A file served back inline can run as script in the victim browser. Trusting the client supplied type or name is the common thread.

The danger is letting an upload influence where it lands, what it is treated as, or how it is served.

The Defense

  • Validate type by content, not by extension or the declared type, and enforce a strict allowlist of formats.
  • Generate a new random name and never use the client name to build a path.
  • Store uploads outside the web root or in object storage, and serve them through a handler that sets safe headers.
  • Serve with a download disposition and a correct content type so files are not interpreted as active content.
  • Enforce size limits and scan where appropriate.

Key idea

Decide file type by content, rename and store uploads outside the web root, and serve them with safe headers so an upload cannot become code or escape its folder.

Check yourself

Answer to earn rating on the learn ladder.

1. Why not trust the declared file type?

2. Why generate a new random file name?

3. Why serve uploads with a download disposition?