A .jpg that runs as code? How to protect file uploads

File upload becomes a flaw when the server trusts the file name and type the browser sends. The fix is that the server decides: extensions from an allowlist, a name it generates, storage outside the webroot, and a size limit.

Published 4 min read#App security#Web development

A file named avatar.jpg.php looks like an image to anyone who reads the start of its name, and the same name can make the server run it as code. The profile photo, the invoice a customer uploads, the CV on a job form: each one is a door that lets a file from outside into your server. This article shows where the mistake happens, and what your server has to decide on its own before it stores any file.

What does it mean to protect file uploads?

Protecting file uploads means the server decides which file type it accepts, what the file is called, where it is stored and how big it can be, instead of trusting what the browser sends. Every piece of information that arrives with the file, from its name to its type, was written by the user or their tool.

Among the recommendations at the top of the OWASP File Upload Cheat Sheet are: a list of allowed extensions, not trusting the Content-Type, changing the file name to one the application generates, storing files on a different server or outside the webroot, a size limit, and uploads for authorized users only.

Where does the mistake happen in file uploads?

The mistake happens when the code judges the file by its name or by the type the browser sends. Both are written by whoever uploads, so an attacker writes whatever they want.

The same cheat sheet gives two examples of names that fool an extension check:

  • A double extension such as .jpg.php, which slips past a check that looks for .jpg inside the name.

  • A null byte such as .php%00.jpg, when the name gets cut at the null byte, so .jpg goes away and .php stays.

The Content-Type is the same story. The cheat sheet says: "The Content-Type for uploaded files is provided by the user, and as such cannot be trusted, as it is trivial to spoof." So image/png in the request doesn't prove the file is an image.

For a shop owner: it's like accepting a parcel because it says "books" on the label, without opening it, and putting it in the customer room.

How do you protect file uploads in your code?

You protect file uploads when your server decides everything about the file itself: an extension from an allowed list, a new name it generates, and a storage place the web doesn't open as a page. Then the attacker's name and type change nothing.

In order:

  1. Take the last extension in the name, and compare it with an allowlist that holds only what your business needs. The cheat sheet advises "Only allow safe and critical extensions for business functionality".

  2. Don't rely on the Content-Type to accept the file. Keep it as a quick check only.

  3. Change the name. Per the cheat sheet, a random name such as a UUID "is essential".

  4. Store the file outside the webroot, or on a different server, so it can't open as a page that runs.

  5. Set a size limit in the upload library itself, before the whole file reaches the disk.

  6. Keep uploads for signed-in users only, so you can limit each one.

In Node.js, the path.extname documentation says it returns the extension "from the last occurrence of the . (period) character", so a name like avatar.jpg.php gives .php, and the list rejects it. This is one way to build the steps:

import { randomUUID } from 'node:crypto';
import { writeFile } from 'node:fs/promises';
import path from 'node:path';

const ALLOWED_EXTENSIONS = new Set(['.jpg', '.png', '.pdf']);

export async function storeUpload(userId, originalName, bytes) {
  const ext = path.extname(originalName).toLowerCase();
  if (!ALLOWED_EXTENSIONS.has(ext)) {
    throw new Error('File type not allowed');
  }
  if (bytes.length > config.maxUploadBytes) {
    throw new Error('File too large');
  }

  const storedName = `${randomUUID()}${ext}`;
  await writeFile(path.join(config.uploadsDir, storedName), bytes);
  await saveUploadRecord(userId, storedName, originalName);
  return storedName;
}

Here config.uploadsDir is a folder outside the webroot, and the file reaches the user through a route in your app that checks who is asking, not through a direct link to the disk. The original name stays in the database for display only.

Is checking the first bytes of the file enough?

Checking the first bytes of the file, its signature, is an extra layer, not a fix on its own. The cheat sheet says about it: "This should not be used on its own, as bypassing it is pretty common and easy."

So if you have a signature check, keep it, but on top of the six steps, not instead of them.

And even after the file is stored correctly, the browser may try to guess its type when it shows it. We wrote about that and the one-header fix: the X-Content-Type-Options header.

Where do you start today?

Start with every form on your platform that has an "upload file" button, and answer four questions for each one. A wrong answer to any of them is the first thing you fix.

  1. Is the extension checked against an allowlist, or against a deny-list, or not at all?

  2. Is the file stored under its original name, or under a name the server generates?

  3. Does the uploads folder open straight from the browser? Try opening the link of an uploaded file.

  4. Is there a size limit, and who can upload?

And if your platform takes uploads from customers or staff, and you want someone to try uploading to it the way an attacker would, that's the work of Muhassan. The rest of our articles on the subject: app security articles.

Where on your platform is there an upload button that nobody has checked for what it accepts?

FAQ

Is checking the Content-Type enough?

No. OWASP says the Content-Type is provided by the user and trivial to spoof, so it is a quick check only, not a protection on its own.

If I check the first bytes of the file, is it safe then?

Not on its own. OWASP says file signature validation should not be used alone because bypassing it is easy; it belongs on top of the extension allowlist, the random name and the storage location.

Do I need to keep the original file name?

Not on disk. Store the file under a name your application generates, such as a UUID, and if you need the original name for display, keep it in the database with a length limit and a restricted set of characters.

Who should be able to upload files?

Only registered or identifiable users. OWASP recommends allowing only authorized users to upload files, so you can set limits on each user's uploads.

Share

More articles