TExcelTAD
Home › Wireless, IoT & Mobile Security › Analysing a Synthetic Firmware Image

Analysing a Synthetic Firmware Image

A firmware image is the whole device in one file: bootloader, kernel, filesystem, configuration, keys. Vendors publish images for updates, so anyone can download one and look inside without touching a device. That is why firmware analysis is the first step of every IoT security review, by defenders and attackers alike, and why secrets inside firmware are never secret. This lesson builds a small, entirely synthetic image of the course's smart-home hub, then analyses it the way a reviewer does: header, integrity, sections, entropy, filesystem, secrets.

Scope: the image is made by the lesson's own code. Analysing firmware of products you own, or images a vendor publishes, is common research practice; extracting firmware from devices you don't own, or bypassing licence protections, may not be legal where you are (Radio Law and Scope).

How real images are structured

Real images vary by vendor, but the parts repeat:

Part Typical content What a reviewer checks
header magic bytes, version, board ID, offsets and lengths, a checksum, sometimes a signature is there a signature, and does the device check it?
bootloader U-Boot or a vendor loader debug console enabled? environment writable?
kernel a compressed Linux kernel (gzip, LZMA, XZ) or an RTOS binary version and known CVEs
root filesystem SquashFS, JFFS2, UBIFS, CramFS users, passwords, start-up scripts, services, certificates, keys, libraries and their versions
config / data key-value stores, sometimes encrypted default credentials, cloud endpoints, encryption keys

Tools such as binwalk find these parts by scanning for known signatures; unsquashfs and similar tools unpack filesystems; then the work is reading files. Our image uses a made-up header (LHFW), a zlib-compressed "kernel", a toy filesystem format and an encrypted-looking vault, so that all of it fits in one example.

Step 1: build the image

The first half of the program creates the image: a 64-byte header packed with struct, then the three sections. Every credential in it is a fake lab value. The second half is the analysis: parse the header, verify the CRC, measure each section's entropy, walk the filesystem and search each file for secrets and risky services.

python · try it yourself
import struct, zlib, hashlib

def lfs(files):                 # the toy "LabFS" filesystem: name length, name, data length, data
    return b"".join(struct.pack("<B", len(n)) + n.encode() + struct.pack("<I", len(d)) + d for n, d in files)

FILES = [
    ("/etc/passwd", b"root:x:0:0:root:/root:/bin/sh\nsupport:x:1000:1000::/home/support:/bin/sh\n"),
    ("/etc/shadow", b"root:$1$labsalt$9cXk2yVbF0lab.only.not.real:19000:0:99999:7:::\nsupport:support123:19000::::::\n"),
    ("/etc/init.d/rcS", b"#!/bin/sh\nmount -a\n/usr/sbin/telnetd -l /bin/sh -p 2323 &\n/usr/bin/labhomed &\n"),
    ("/etc/config/cloud.conf", b"broker=mqtt.lab.test:1883\nmqtt_user=hub\nmqtt_password=lab-only-Mqtt-2026\napi_key=LABKEY-7F2C-9E41\n"),
    ("/etc/ssl/private/device.key", b"-----BEGIN PRIVATE KEY-----\nLAB-ONLY-PLACEHOLDER-NOT-A-REAL-KEY\n-----END PRIVATE KEY-----\n"),
    ("/usr/share/version", b"LabHome Hub 1.4.2 build 2026-01-15\n"),
]
def stream(seed, n):            # deterministic high-entropy bytes standing in for encrypted data
    out = b""
    while len(out) < n:
        out += hashlib.sha256(seed + len(out).to_bytes(4, "big")).digest()
    return out[:n]

kernel = zlib.compress(b"".join(b"lab kernel text %05d " % i + bytes(range(i % 40)) for i in range(900)), 9)
rootfs = lfs(FILES) + bytes(4096 - len(lfs(FILES)) % 4096)          # padded to 4 KiB
vault = stream(b"lab-vault", 2048)                                    # an encrypted config store
payload = kernel + rootfs + vault
HDR = 64
FMT = "<4sHH3sxIIIIIIIH16s"   # magic, header version, header size, fw version, build time, kernel off/len,
                                 # rootfs off/len, vault length, CRC-32 of the payload, signature length, board
header = struct.pack(FMT, b"LHFW", 1, HDR, bytes([1, 4, 2]), 1768435200, HDR, len(kernel),
                     HDR + len(kernel), len(rootfs), len(vault), zlib.crc32(payload), 0, b"labhome-hub-v2")
image = header.ljust(HDR, b"\x00") + payload

# ---- the analysis: what a reviewer does with an image file ----
import math, re
from collections import Counter

def entropy(b):
    n = len(b)
    return -sum(c / n * math.log2(c / n) for c in Counter(b).values()) if n else 0.0

(magic, hv, hsize, ver, built, k_off, k_len, r_off, r_len, v_len, crc, sig_len, board) = struct.unpack_from(FMT, image)
print(f"magic {magic}  board {board.rstrip(bytes(1)).decode()}  firmware {ver[0]}.{ver[1]}.{ver[2]}  header {hsize} bytes")
print(f"CRC-32 {'ok' if zlib.crc32(image[hsize:]) == crc else 'BAD'}   signature length {sig_len}"
      + ("  <- unsigned image: the device can't tell a modified one apart" if sig_len == 0 else ""))
sections = {"kernel": image[k_off:k_off + k_len], "rootfs": image[r_off:r_off + r_len], "vault": image[r_off + r_len:]}
for name, data in sections.items():
    print(f"  {name:6} {len(data):5} bytes  entropy {entropy(data):.2f} bits/byte")
print("kernel starts with", sections["kernel"][:2].hex(), "-> zlib stream; decompresses to",
      len(zlib.decompress(sections["kernel"])), "bytes")

# Walk the filesystem and look for secrets and risky services
fs, pos = sections["rootfs"], 0
PATTERNS = {"plaintext password in shadow": rb"(?m)^\w+:(?![$*!]|x:)[^:]+:\d+:", "MD5-crypt hash": rb"\$1\
quot;, "password setting": rb"(?i)password\s*=\s*\S+", "api key": rb"(?i)api_key\s*=\s*\S+", "private key": rb"-----BEGIN [A-Z ]*PRIVATE KEY-----", "telnet with a shell": rb"telnetd.*-l /bin/sh"} while pos < len(fs) and fs[pos]: n = fs[pos]; name = fs[pos + 1:pos + 1 + n].decode() size, = struct.unpack_from("<I", fs, pos + 1 + n) data = fs[pos + 5 + n:pos + 5 + n + size] hits = [label for label, rx in PATTERNS.items() if re.search(rx, data)] print(f" {name:28} {size:4} bytes {', '.join(hits) if hits else ''}") pos += 5 + n + size
magic b'LHFW'  board labhome-hub-v2  firmware 1.4.2  header 64 bytes
CRC-32 ok   signature length 0  <- unsigned image: the device can't tell a modified one apart
  kernel  2838 bytes  entropy 6.72 bits/byte
  rootfs  4096 bytes  entropy 1.38 bits/byte
  vault   2048 bytes  entropy 7.90 bits/byte
kernel starts with 78da -> zlib stream; decompresses to 37150 bytes
  /etc/passwd                    73 bytes  
  /etc/shadow                    94 bytes  plaintext password in shadow, MD5-crypt hash
  /etc/init.d/rcS                78 bytes  telnet with a shell
  /etc/config/cloud.conf         98 bytes  password setting, api key
  /etc/ssl/private/device.key    90 bytes  private key
  /usr/share/version             35 bytes  

Reading the results

  • Header: the image carries a CRC-32 but no signature (length 0). A CRC detects transmission errors; anyone can recompute it after modifying the image (why a CRC is not integrity). If the device accepts this image, it accepts a modified one too.
  • Entropy tells sections apart without parsing them (entropy profiles): the filesystem with its text files and padding is low (1.38 bits per byte), the zlib-compressed kernel high (6.72; small compressed blocks stay below 8), and the vault near the maximum (7.90), which means compressed or encrypted. The zlib magic 78 da confirms the kernel is compression, not encryption. An encrypted vault in a device that decrypts it at boot means the key is somewhere in the firmware or the hardware: finding it is the next step of a review.
  • Filesystem findings: a support account with a plaintext password in /etc/shadow and root with an MD5-crypt hash ($1$, fast to guess); Telnet started at boot on port 2323 with a root shell and no login (-l /bin/sh); MQTT credentials and an API key in plain text; a device private key that is identical in every unit that runs this image.

That last point matters most. A key or password inside a published image is a shared secret of the entire product line. Whoever reads it can impersonate any device to the cloud, read every hub's MQTT traffic, or decrypt every vault.

The lab: entropy at a glance

The entropy-scan lab slides a window over a synthetic file and plots its entropy. The setting "document with an embedded archive" has the same shape as our image: a structured header, low-entropy text, and a compressed block in the middle. Change the window size and see how the threshold for "compressed or encrypted" depends on it.

file: document with an embedded archive, 32 KiBASCIIcompressedASCIIentropy of a 1024-byte window, step 256 bytes024680 KiB8 KiB16 KiB24 KiB32 KiB7.2: likely compressed or encryptedheaderASCII textzero paddingcompressed (zip-like)

Step 2: the same review with command-line tools

In the sandbox (no network), the session writes the same image with the same builder, then uses file, xxd, strings and a YARA rule. YARA (YARA basics) turns the secret search into a reusable check that can run on every build.

bash · try it yourself
cat > build_fw.py <<'PY'
import struct, zlib, hashlib

def lfs(files):                 # the toy "LabFS" filesystem: name length, name, data length, data
    return b"".join(struct.pack("<B", len(n)) + n.encode() + struct.pack("<I", len(d)) + d for n, d in files)

FILES = [
    ("/etc/passwd", b"root:x:0:0:root:/root:/bin/sh\nsupport:x:1000:1000::/home/support:/bin/sh\n"),
    ("/etc/shadow", b"root:$1$labsalt$9cXk2yVbF0lab.only.not.real:19000:0:99999:7:::\nsupport:support123:19000::::::\n"),
    ("/etc/init.d/rcS", b"#!/bin/sh\nmount -a\n/usr/sbin/telnetd -l /bin/sh -p 2323 &\n/usr/bin/labhomed &\n"),
    ("/etc/config/cloud.conf", b"broker=mqtt.lab.test:1883\nmqtt_user=hub\nmqtt_password=lab-only-Mqtt-2026\napi_key=LABKEY-7F2C-9E41\n"),
    ("/etc/ssl/private/device.key", b"-----BEGIN PRIVATE KEY-----\nLAB-ONLY-PLACEHOLDER-NOT-A-REAL-KEY\n-----END PRIVATE KEY-----\n"),
    ("/usr/share/version", b"LabHome Hub 1.4.2 build 2026-01-15\n"),
]
def stream(seed, n):            # deterministic high-entropy bytes standing in for encrypted data
    out = b""
    while len(out) < n:
        out += hashlib.sha256(seed + len(out).to_bytes(4, "big")).digest()
    return out[:n]

kernel = zlib.compress(b"".join(b"lab kernel text %05d " % i + bytes(range(i % 40)) for i in range(900)), 9)
rootfs = lfs(FILES) + bytes(4096 - len(lfs(FILES)) % 4096)          # padded to 4 KiB
vault = stream(b"lab-vault", 2048)                                    # an encrypted config store
payload = kernel + rootfs + vault
HDR = 64
FMT = "<4sHH3sxIIIIIIIH16s"   # magic, header version, header size, fw version, build time, kernel off/len,
                                 # rootfs off/len, vault length, CRC-32 of the payload, signature length, board
header = struct.pack(FMT, b"LHFW", 1, HDR, bytes([1, 4, 2]), 1768435200, HDR, len(kernel),
                     HDR + len(kernel), len(rootfs), len(vault), zlib.crc32(payload), 0, b"labhome-hub-v2")
image = header.ljust(HDR, b"\x00") + payload
open("fw.bin", "wb").write(image)
PY
python3 build_fw.py
file fw.bin
xxd -l 64 fw.bin
echo "== printable strings that look like secrets or services"
strings -n 8 fw.bin | grep -iE 'pass|key|telnet|BEGIN' 
cat > secrets.yar <<'YAR'
rule lab_firmware_secrets
{
    strings:
        $pw   = /password\s*=\s*\S+/ nocase
        $key  = "PRIVATE KEY-----"
        $tel  = /telnetd .{0,20}-l \/bin\/sh/
        $md5  = "$1
quot; condition: uint32(0) == 0x5746484c and 2 of them // "LHFW" at offset 0, read little-endian } YAR yara -s secrets.yar fw.bin
fw.bin: data
00000000: 4c48 4657 0100 4000 0104 0200 002e 6869  LHFW..@.......hi
00000010: 4000 0000 160b 0000 560b 0000 0010 0000  @.......V.......
00000020: 0008 0000 5340 ef4b 0000 6c61 6268 6f6d  ....S@.K..labhom
00000030: 652d 6875 622d 7632 0000 0000 0000 0000  e-hub-v2........
== printable strings that look like secrets or services
/etc/passwdI
/usr/sbin/telnetd -l /bin/sh -p 2323 &
mqtt_password=lab-only-Mqtt-2026
api_key=LABKEY-7F2C-9E41
/etc/ssl/private/device.keyZ
-----BEGIN PRIVATE KEY-----
LAB-ONLY-PLACEHOLDER-NOT-A-REAL-KEY
-----END PRIVATE KEY-----
lab_firmware_secrets fw.bin
0xcc7:$pw: password=lab-only-Mqtt-2026
0xd27:$key: PRIVATE KEY-----
0xd65:$key: PRIVATE KEY-----
0xc4e:$tel: telnetd -l /bin/sh
0xbc4:$md5: $1$

file doesn't know the made-up format ("data"), which is normal for vendor images. The hex dump shows the header fields in little-endian order (4000 0000 = kernel offset 64). strings finds every secret in seconds, which is the point: no skill is needed to read a secret from a firmware image. The YARA rule keys on the magic number and reports each match with its offset, ready for a CI job that fails the build when a release image contains credentials or a Telnet shell.

How firmware weaknesses are detected

  • Release-pipeline checks on every image: secret scanning (YARA, gitleaks-style rules, entropy checks for keys), a list of enabled services from start-up scripts, an SBOM of included components and their known vulnerabilities.
  • Comparison between versions: new open ports, new accounts or changed start-up scripts between 1.4.1 and 1.4.2 are review items.
  • Signature presence and enforcement: an image without a signature, or a device that boots a modified image in a lab test, is a critical finding (secure boot, update security).

How it is fixed

  • No shared secrets in images. Per-device credentials and keys are provisioned at manufacturing into protected storage (a secure element, TPM or the chip's key store), or generated on the device at first boot with the public part registered in the cloud.
  • No debug services in production builds: build flags that remove Telnet, test accounts and debug shells, verified by the release check.
  • Strong password hashing for any local accounts (yescrypt, bcrypt, SHA-512-crypt at minimum), unique per device, or no local password login at all.
  • Signed images, verified by the bootloader and the updater; encryption of the image only as an addition, never instead of signing.

Pitfalls

  • "Our firmware is encrypted, so secrets are safe": the device must decrypt it, so the key is in the device and has been extracted from many products.
  • Leaving test keys from the chip vendor's SDK in production images.
  • Checking only the filesystem: bootloader environments and vaults hold secrets too.

Practice

1. Add a file /etc/dropbear/authorized_keys containing ssh-ed25519 AAAA... support@lab to FILES. What does it mean if a release image contains it, and how would you detect it automatically?

Whoever holds the matching private key can log in to every device over SSH: a vendor backdoor, deliberate or forgotten. Add a pattern for authorized_keys files (and for SSH private keys) to the analysis and to the YARA rule, and fail the build on a match.

2. Why is the vault's entropy close to 8 bits per byte but the kernel's only 6.72?

The vault is (simulated) encrypted data, which looks uniformly distributed. The kernel is compressed, which is close to uniform for large inputs, but a small compressed block still has header bytes and structure, and a 2.8 KiB sample can't show all 256 byte values evenly.

3. The vendor fixes the findings by encrypting the root filesystem with AES and a key in the bootloader. Is the finding closed?

No. The key is in every device's bootloader, which can be read from a published update or from the flash chip, and then every secret is readable again. The fix is to remove shared secrets from the image and to sign it.

Test yourself

What does a CRC-32 in a firmware header protect against?

  1. Malicious modification
  2. Accidental corruption only; anyone can recompute it
  3. Reverse engineering
  4. Downgrades

The vault section has an entropy of 7.90 bits per byte. What does that suggest?

  1. Plain text
  2. Compressed or encrypted data
  3. Zero padding
  4. Machine code

Why is a private key inside a published firmware image a product-wide problem?

  1. Keys expire
  2. Every unit running the image has the same key, so one extraction affects all devices
  3. It slows the boot
  4. It breaks the CRC

Which line in the start-up script is a critical finding?

  1. mount -a
  2. telnetd -l /bin/sh -p 2323
  3. /usr/bin/labhomed &
  4. #!/bin/sh