Missing upload file-type validation

Missing upload file-type validation

Description

The extension and MIME type reported by the client can differ from the actual upload format.

Potential impact

Scripts or executables stored in a public directory may be served to other users.

Remediation

Use multer’s fileFilter to check the extension and MIME type against an allow-list. Save the upload under a server-generated name outside public and executable paths, then check its bytes against the expected format.

Examples

Prepare the Express app and a private quarantine directory writable only by the application. The first example assumes upload has no type check.

Before

javascript
app.post("/upload", upload.single("file"), (req, res) => {
  res.json({ path: req.file.path });
});

After

javascript
const crypto = require("crypto");
const fs = require("fs/promises");
const path = require("path");
const multer = require("multer");

// An isolated directory, not public or executable, with writes restricted to the application
const QUARANTINE_DIR = "/srv/app/upload-quarantine";
const PNG_SIGNATURE = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);

const upload = multer({
  storage: multer.diskStorage({
    destination: QUARANTINE_DIR,
    filename(req, file, cb) {
      cb(null, `${crypto.randomUUID()}.png`);
    },
  }),
  limits: { fileSize: 5 * 1024 * 1024 },
  fileFilter(req, file, cb) {
    const extension = path.extname(file.originalname).toLowerCase();
    const allowed = file.mimetype === "image/png" && extension === ".png";
    cb(null, allowed);
  },
});

async function hasPngSignature(filePath) {
  const handle = await fs.open(filePath, "r");
  try {
    const header = Buffer.alloc(PNG_SIGNATURE.length);
    const { bytesRead } = await handle.read(header, 0, header.length, 0);
    return bytesRead === header.length && header.equals(PNG_SIGNATURE);
  } finally {
    await handle.close();
  }
}

app.post("/upload", upload.single("file"), async (req, res, next) => {
  if (!req.file) return res.status(400).send("invalid file type");

  try {
    if (!(await hasPngSignature(req.file.path))) {
      await fs.unlink(req.file.path);
      return res.status(400).send("invalid file type");
    }
    return res.json({ id: req.file.filename });
  } catch (error) {
    await fs.unlink(req.file.path).catch(() => {});
    return next(error);
  }
});

The revised handler limits uploads to 5 MiB and rejects requests with no req.file after filtering. It deletes files with the wrong PNG header and attempts cleanup on errors. To validate the whole image, decode it and re-encode it if needed.

References