Course contentsShow
← Security
Lesson 956 of 3,05220. Web Security - File Upload and ProcessingFree lesson

Content-Type Header Validation and Mismatches

Understand how to properly validate Content-Type headers and detect discrepancies with actual file content.

Content-Type Header Validation and Mismatches

What you'll learn: How servers can be tricked when they trust HTTP Content-Type headers without verifying the actual file content.

The Trust Problem

When you upload a file, your browser sends a Content-Type header (like image/png or application/pdf) to tell the server what kind of file it is. The vulnerability occurs when servers trust this header blindly without checking if the file's actual content matches what the header claims.

Think of it like receiving a package labeled "books" but never opening it to verify it actually contains books—it could be anything inside.

How Attackers Exploit This

Building on magic byte verification (concept 955), attackers can manipulate the Content-Type header to bypass security filters:

  1. Header-only validation: Server checks Content-Type: image/jpeg and allows upload
  2. Actual content: File contains PHP web shell code, not image data
  3. Result: Malicious code passes through filters designed to block scripts

The Mismatch Attack

An attacker might upload malicious.php with these manipulated headers:

  • Browser sends: Content-Type: image/jpeg
  • File signature (magic bytes): <?php system($_GET['cmd']); ?>
  • Server thinks: "JPEG is safe, allowing upload"
  • Reality: Executable PHP code stored on server

Proper Validation Strategy

Secure servers must perform dual validation:

  1. Never trust the Content-Type header alone
  2. Always verify magic bytes match the claimed type
  3. Cross-reference header against actual file signature
  4. Reject mismatches when header and content disagree

If someone claims to send an image but the file starts with <?php instead of JPEG magic bytes (FF D8 FF), that's a clear attack indicator.

Key Takeaway: Content-Type headers are client-controlled and easily spoofed; always validate that HTTP headers match the actual file content through magic byte inspection and never make security decisions based on headers alone.