mediumCWE-434A04:2021

MIME Type Mismatch

Validating file type only by extension instead of content allows attackers to upload malicious files with renamed extensions, bypassing security controls.

How It Works

Many applications check file types by looking at the file extension (.jpg, .pdf) or the Content-Type header sent by the browser. Both can be trivially spoofed. An attacker can rename malware.exe to invoice.pdf or set the Content-Type to image/jpeg for a PHP web shell. The server accepts the file thinking it is safe. When the file is later served or processed, the actual content determines behavior — a PHP file with a .jpg extension may still execute if the server is misconfigured. Proper validation requires reading the file's magic bytes (the first few bytes that identify file format) to determine the true content type.

Vulnerable Code
app.post('/upload', upload.single('doc'), (req, res) => {
  const ext = path.extname(req.file.originalname).toLowerCase();
  const allowed = ['.pdf', '.docx', '.xlsx'];
  if (!allowed.includes(ext)) {
    return res.status(400).json({ error: 'Invalid file type' });
  }
  // File accepted based on extension only
  res.json({ url: `/docs/${req.file.filename}` });
});
Secure Code
const { fileTypeFromBuffer } = require('file-type');
app.post('/upload', upload.single('doc'), async (req, res) => {
  const buffer = fs.readFileSync(req.file.path);
  const type = await fileTypeFromBuffer(buffer);
  const allowed = ['application/pdf',
    'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'];
  if (!type || !allowed.includes(type.mime)) {
    fs.unlinkSync(req.file.path);
    return res.status(400).json({ error: 'Invalid file type' });
  }
  res.json({ url: `/docs/${req.file.filename}` });
});

Real-World Example

In 2019, WhatsApp had a vulnerability (CVE-2019-11931) where attackers sent specially crafted MP4 files that were actually exploit payloads. The client validated the file extension but not the content, allowing buffer overflow attacks that could execute arbitrary code on the recipient's device.

How to Prevent It

  • Use the file-type library to detect actual file type from magic bytes
  • Never trust file extensions or client-sent Content-Type headers
  • Delete files immediately if content validation fails
  • Set X-Content-Type-Options: nosniff header to prevent browser MIME sniffing

Affected Technologies

Node.jsPythonJavaPHPGo

Data Hogo detects this vulnerability automatically.

Scan Your Repo Free

Related Vulnerabilities