> For the complete documentation index, see [llms.txt](https://sarpers-organization.gitbook.io/ctftricks/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://sarpers-organization.gitbook.io/ctftricks/_chapter-intro-17/bypass/file-upload/trick-0128.md).

# File Upload Magic Byte Bypass

***

Server-side file validation sometimes checks the initial bytes (magic bytes) instead of just the file extension to determine the file type. To bypass this, prepend the magic bytes of an allowed file type (like a PNG image) to your malicious payload.

Identify the required magic bytes (e.g., PNG: `89 50 4E 47`). Common magic bytes for other file types include JPEG (`FF D8 FF E0`), GIF (`47 49 46 38`), and PDF (`25 50 44 46`). Use tools like `xxd` and `cat` to create a new file starting with these bytes, followed by your payload's content. For instance, to prepend PNG magic bytes to a file named `payload.php`:

```bash
echo '89 50 4E 47' | xxd -p -r > crafted_payload.php; cat payload.php >> crafted_payload.php
```

Another command-line approach uses `echo -ne` with hex escape sequences:

```bash
echo -ne '\x89\x50\x4e\x47\x0d\x0a\x1a\x0a' > fake_image.png
cat /path/to/your/payload.php >> fake_image.png
```

Alternatively, `printf` can also be used:

```bash
printf "\x89\x50\x4e\x47" | cat - payload.php > crafted_payload.php
```

Then, upload the `crafted_payload.php`. The validation might see the image magic bytes and accept the file, allowing your script to be uploaded and potentially executed if placed in a web-accessible directory.

Alternatively, a hex editor can be used to manually or programmatically insert the magic bytes at the beginning of the file. Using a command-line hex editor like `hexedit`, you can open the payload file, insert the necessary bytes at offset 0, and save the modified file. For example, to add the PNG magic bytes `89 50 4E 47` to `payload.php` using `hexedit`:

```bash
hexedit payload.php
```

Inside `hexedit`, navigate to the beginning of the file (offset 0). Press `Ctrl-I` to enter insert mode, type the hex pairs (e.g., `89504E47`), then press `Ctrl-X` to save and exit. This method directly modifies the original file or saves it as a new one with the prepended bytes. This technique works by tricking the server-side check that relies on identifying file types based on these leading bytes.
