Skip to content

Lesson 2 of 9 · 22m

Type Confusion: Extension, MIME, and Magic Bytes

Why extensions lie, why MIME sniffing disagrees with browsers and servers, and how to establish one authoritative file type.

Type confusion is the center of most upload exploitation. The application thinks it accepted a PNG. The browser thinks it received HTML. The web server thinks .php.jpg is PHP. The image library thinks it is actually a malformed TIFF. Once components disagree, the attacker only has to find the interpretation that benefits them.

Three different notions of "type"

filename:      invoice.pdf.exe
Content-Type:  application/pdf
magic bytes:   MZ ............  (Windows executable)

The extension is a naming convention. Content-Type is supplied by the client. Magic bytes are evidence from the file itself, but not proof of safety. A secure pipeline picks one authoritative classification mechanism and treats the rest as advisory.

Common disagreement points

  • Double extensions: shell.php.jpg may execute as PHP on badly configured Apache or nginx/PHP-FPM routing.
  • MIME sniffing: browsers historically sniff content when Content-Type is absent or generic.
  • Case normalization: .PhP, .pHp5, .phtml differences matter on case-sensitive filesystems and case-insensitive routing.
  • Ambiguous containers: SVG is XML that can carry scripts; PDF can carry JavaScript; Office files are ZIP containers.
  • Polyglot-ish ambiguity: bytes can be valid enough to satisfy multiple parsers.

Establish authoritative type detection

Use a library based on magic signatures, then enforce an allowlist:

import magic

kind = magic.from_buffer(data, mime=True)
if kind not in {"image/png", "image/jpeg", "image/webp"}:
    reject_upload()

That is necessary but insufficient. A file can be a real PNG and still malicious in downstream behavior. Type detection answers "what parser should handle this," not "is this safe."

Server configuration must agree. A minimal nginx hardening example:

location /uploads/ {
    types { }
    default_type application/octet-stream;
    add_header X-Content-Type-Options nosniff always;
    add_header Content-Disposition attachment always;
}

Practical rules

Allowlist exact business formats, reject everything else, normalize before checking, and never execute uploaded content. If you accept images, decode and re-encode them with the same parser your application uses for display. This both validates structure and strips hostile metadata and odd encodings.

Field notes

  • file and libmagic are useful evidence, not a security boundary by themselves.
  • SVG is not "just an image"; treat it as active XML/HTML-like content.
  • Never rely on blacklist checks like "not .php." Attackers know every alternate executable extension your framework accepts.

Was this lesson helpful?

Sign in to rate