MIME Type Sniffing and Security Implications
What you'll learn: How browsers try to "guess" file types independently of what the server declares, and how attackers weaponize this behavior to slip past security checks.
What is MIME Type Sniffing?
MIME type sniffing (also called content sniffing) is when a browser examines the actual content of a file to determine its type, rather than trusting the Content-Type header sent by the server. Browsers do this to be "helpful"—if a server misconfigures a header or serves a file with the wrong MIME type, the browser attempts to detect the real type by inspecting the file's magic bytes and structure.
Think of it like a postal worker who ignores the label on a package and opens it to see what's really inside. Well-intentioned, but dangerous.
The Security Problem
Attackers exploit MIME sniffing to bypass upload validation. Here's the classic attack pattern:
- You upload a file containing malicious JavaScript or HTML disguised as an image
- The filename is
innocent.jpgand you set theContent-Type: image/jpegheader - Your validation only checks the extension and MIME type—both look safe
- But the file's actual content starts with
<html>or<script> - When a victim visits the file's URL, the browser sniffs the content, detects HTML/JavaScript, and executes it as a web page
Even though your server says "this is an image," the browser says "I disagree—this is HTML" and treats it accordingly.
Real-World Impact
This transforms a seemingly harmless image upload into:
- Stored XSS (the HTML/JS runs in your domain's context)
- Credential theft via injected login forms
- Drive-by malware downloads
Prevention
Disable MIME sniffing using the HTTP header:
X-Content-Type-Options: nosniff
This forces browsers to respect your declared Content-Type instead of guessing.
Key Takeaway: MIME type sniffing lets browsers override your Content-Type declarations by inspecting file contents—attackers exploit this by uploading malicious code disguised as safe file types. Always use X-Content-Type-Options: nosniff to prevent browser guessing games.