Safe Penetration Testing Labs · beginner · ~12 min

Classify a firmware blob from its magic bytes

Identify common firmware file types by their first few bytes.

Overview

Bounds-check, then compare prefix bytes against a small table; return a tag.

Why it matters

Magic-byte sniffing is the gateway to every other forensic tool.

Lesson

Why this matters

Before you even mount or extract a firmware image, you need to know what it is. binwalk and file lead with the same trick: compare the first 4–8 bytes against a table of known magic numbers.

What the magics look like

Magic Meaning
4D 5A PE / DOS executable
7F 45 4C 46 ELF
27 05 19 56 U-Boot uImage (big-endian)
68 73 71 73 Squashfs (hsqs)
19 85 JFFS2

Your job

Implement int detect_firmware_type(const uint8_t *buf, size_t n). Return:

  • 1 = PE
  • 2 = ELF
  • 3 = uImage
  • 4 = Squashfs
  • 5 = JFFS2
  • 0 = unknown but valid pointer
  • -1 = NULL buf

If n is too short to even check a given magic, fall through to the next; if none match, return 0.

Common mistakes

  • Treating uImage's magic as little-endian. It's big-endian on disk.
  • Reading 4 bytes when n < 4.
  • Returning the wrong constant.

What this is NOT

  • A binwalk replacement. We classify; we don't extract.
  • A virus scanner.

Summary

Five magics, five tags. Check length before each comparison.

Practice with these exercises