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

File Content Polyglots and Magic Bytes

Creating files that are valid in multiple formats to bypass content validation while maintaining malicious functionality.

File Content Polyglots and Magic Bytes

What you'll learn: How attackers craft files that are valid in multiple formats simultaneously to slip past content-based security checks.

What Are Polyglot Files?

A polyglot file is a single file that is valid in multiple formats at once. Think of it like a person who can pass as a citizen of two different countries—they speak both languages fluently and carry identification for both. In the context of file uploads, an attacker might create a file that looks like an innocent image to your validator but also contains executable code or scripts.

Magic Bytes Explained

Every file format has a magic byte sequence—a unique identifier at the beginning of the file that tells the operating system what it is. For example:

  • JPEG images start with FF D8 FF
  • PNG images start with 89 50 4E 47
  • PHP files might start with <?php

Security validators often check these magic bytes to verify file types, rather than trusting file extensions alone.

The Polyglot Attack

Attackers exploit this by crafting files with legitimate magic bytes at the start, passing validation, but embedding malicious content within. For instance:

  1. Start with valid JPEG magic bytes
  2. Add image data that parsers will accept
  3. Embed PHP code in a comment section or metadata field
  4. When the server processes or includes this file, the PHP executes

The file validates as a JPEG but also functions as executable code when accessed directly through a web browser or if the server mishandles it.

This bypasses both extension-based filters (you learned about blacklist bypasses) and MIME-type validation (which checks magic bytes). It's particularly dangerous when combined with techniques like path traversal or if uploaded files are stored in web-accessible directories.

Key Takeaway: Polyglot files abuse the dual-nature capability of file formats by satisfying validation requirements of one format while maintaining malicious functionality of another—making content-based validation alone insufficient for security.