Перейти к основному содержимому
Emulating IoT Binaries with QEMU & Auditing Hardcoded Secrets
Урок 6 из 9

Emulating IoT Binaries with QEMU & Auditing Hardcoded Secrets

Emulate ARM and MIPS firmware binaries on an x86_64 lab host with qemu-user and chroot, bypass missing NVRAM or hardware checks, and combine Ghidra with gdb-multiarch to verify hardcoded secrets and sinks.

Эксперт 32 мин IoT и встраиваемые
Этого урока пока нет на выбранном языке — показана версия на другом языке. Перевод готовится.
Только в разрешённой среде — Описанные здесь приёмы применяются только в учебных лабораториях и в системах, которые принадлежат вам или на которые есть письменное разрешение.

Цели обучения

  • Select the matching QEMU user-mode emulator from ELF header architecture and endianness metadata
  • Run dynamically linked MIPS or ARM firmware binaries inside a chroot rootfs with syscall tracing and remote GDB
  • Overcome missing NVRAM or device dependencies using LD_PRELOAD shims inside an isolated lab VM
  • Combine Ghidra static cross-references with QEMU dynamic execution to confirm hardcoded secrets and unsafe sinks

Рекомендуется заранее: Firmware Extraction: OTA Captures, Flash Dumps & BootloadersFirmware Analysis: Unpacking SquashFS/JFFS2 with Binwalk

#Why this matters

Once you extract a SquashFS root filesystem, static inspection quickly hits a wall when important logic lives inside compiled C binaries rather than shell scripts. Embedded web servers (httpd, goahead), custom management daemons, and proprietary cloud agents often obfuscate API keys, build authentication tokens dynamically, or parse binary protocols across dozens of helper functions.

Reading raw MIPS or ARM disassembly in Ghidra alone is slow when configuration structs depend on runtime state. By emulating the target binary on your x86_64 workstation with QEMU, you can execute the real code path, watch its syscalls, feed harmless test inputs, and inspect registers at the exact moment a secret or command string is assembled.

#Selecting the right QEMU mode and binary

QEMU supports two distinct emulation approaches for firmware analysis:

Mode Scope Best used when Main limitation
User-mode (qemu-*-static) Single ELF binary + chroot Auditing CLI tools, CGI handlers, or standalone daemons No target kernel; custom /dev/* ioctls fail unless shimmed
System-mode (qemu-system-*) Full target kernel + rootfs Booting multi-service firmware with kernel drivers Slower setup; requires matching kernel/DTB or FirmAE-style wrappers

User-mode emulation starts in seconds and is ideal for targeted binary audits. First, inspect the target binary with file and readelf to identify three critical properties: CPU architecture, endianness (MSB vs LSB), and dynamic linker path.

Identifying architecture, endianness, and dynamic linker
$ file rootfs_out/usr/sbin/cfg_mgr
rootfs_out/usr/sbin/cfg_mgr: ELF 32-bit LSB executable, MIPS, MIPS32 rel2 version 1 (SYSV), dynamically linked, interpreter /lib/ld-uClibc.so.0, stripped
$ readelf -d rootfs_out/usr/sbin/cfg_mgr | grep NEEDED
 0x00000001 (NEEDED)                     Shared library: [libnvram.so]
 0x00000001 (NEEDED)                     Shared library: [libcrypto.so.1.1]
 0x00000001 (NEEDED)                     Shared library: [libc.so.0]

Match the ELF metadata carefully to the static QEMU binary:

  • ARM (32-bit little-endian): qemu-arm-static
  • AArch64 (64-bit ARM): qemu-aarch64-static
  • MIPS + MSB (big-endian): qemu-mips-static
  • MIPS + LSB (little-endian): qemu-mipsel-static

Static QEMU binaries (qemu-user-static) have no host shared-library dependencies, so they continue working cleanly after chroot switches / to the unpacked firmware directory.

#Running and tracing inside chroot

Copy the matching qemu-*-static binary into the unpacked rootfs (for example rootfs_out/usr/bin/), then run the target either with -strace to log every Linux syscall or with -g 1234 to pause at the entry point for gdb-multiarch.

Running a MIPS little-endian binary with QEMU syscall tracing
$ cp $(which qemu-mipsel-static) rootfs_out/usr/bin/
$ sudo chroot rootfs_out /usr/bin/qemu-mipsel-static -strace /usr/sbin/cfg_mgr --help
21401 open("/lib/libnvram.so",O_RDONLY) = 3
21401 open("/dev/nvram",O_RDONLY) = -1 errno=2 (No such file or directory)
21401 write(2,"FATAL: nvram open failed\n",25) = 25
21401 exit_group(1)

That three-second trace already explains why the binary exited: it tried to open /dev/nvram, a character device provided by a proprietary kernel module on the real hardware.

  1. Identify ELFfile + readelf for arch, endianness, linker
  2. Chroot + traceqemu-*-static -strace exposes missing NVRAM/files
  3. Shim blockersCompile small LD_PRELOAD stub for target arch
  4. Verify in GDBgdb-multiarch + Ghidra inspect runtime keys/sinks

#Bypassing missing NVRAM and hardware checks

Embedded daemons frequently exit early when hardware devices (/dev/mtd0, /dev/nvram), network interfaces (br0), or PID directories (/var/run) are absent inside an unpacked directory. Handle these blockers cleanly in layers:

  1. Create missing paths or stub files: inspect -strace open() failures and populate dummy files (such as mkdir -p rootfs_out/var/run or creating a placeholder config file).
  2. Shim library calls with LD_PRELOAD: when a binary imports libnvram.so or reads hardware serial numbers from a shared library, cross-compile a tiny C stub for the same architecture and endianness and pass it via -E LD_PRELOAD=/libnvram_shim.so.
c
// Minimal lab shim cross-compiled for MIPS little-endian:
// mipsel-linux-gnu-gcc -shared -fPIC nvram_shim.c -o rootfs_out/libnvram_shim.so
#include <string.h>

const char *nvram_get(const char *key) {
    if (strcmp(key, "lan_ipaddr") == 0) return "192.0.2.1";
    if (strcmp(key, "http_user") == 0) return "admin";
    return "";
}

When invoked with -E LD_PRELOAD=/libnvram_shim.so, cfg_mgr receives valid strings instead of NULL pointers and proceeds straight into its core request-handling logic. If a daemon forks into the background, pass its foreground/debug flag (often -f or -D) or tell gdb-multiarch to track child processes (set follow-fork-mode child).

#Auditing secrets and sinks with Ghidra and GDB

Once the binary runs cleanly under QEMU, pair Ghidra static analysis with gdb-multiarch dynamic verification to avoid guessing what obfuscated routines do.

In Ghidra, import cfg_mgr using the exact processor and endianness reported by file (for example MIPS:LE:32:default), run auto-analysis, and inspect three high-signal targets:

  • Hardcoded secrets and key material: search defined strings for BEGIN PRIVATE KEY, password, token, or hex key literals, and inspect cross-references (XREF) into crypto APIs such as AES_set_decrypt_key or EVP_DecryptInit_ex.
  • De-obfuscated secrets: when a binary XORs or hashes a static salt at startup before calling strcmp, static reading alone is error-prone. Note the function address in Ghidra, launch QEMU with -g 1234, attach gdb-multiarch, set a breakpoint right before strcmp, and read the decoded string directly from register $a1 (MIPS) or r1 (ARM).
  • Command-injection sinks: check cross-references to system, popen, and execve to see whether HTTP headers or CGI parameters reach a shell format string (snprintf into system).
Attaching gdb-multiarch to QEMU to inspect a runtime comparison
# Terminal 1 (inside isolated lab VM):
$ sudo chroot rootfs_out /usr/bin/qemu-mipsel-static -E LD_PRELOAD=/libnvram_shim.so -g 1234 /usr/sbin/cfg_mgr

# Terminal 2:
$ gdb-multiarch -q rootfs_out/usr/sbin/cfg_mgr
(gdb) set architecture mips:isa32r2
(gdb) target remote 127.0.0.1:1234
(gdb) b *0x0040284c
(gdb) continue
Breakpoint 1, 0x0040284c in ?? ()
(gdb) x/s $a1
0x7fff2a40: "LAB_FACTORY_TOKEN_9482"

In this workflow, Ghidra identifies the exact comparison address (0x0040284c) and registers, while QEMU plus gdb-multiarch reveals the final runtime token without requiring you to re-implement a custom key-derivation loop by hand.

#Common mistakes and defence

  • Wrong endianness or host dynamic linker: running a big-endian binary with qemu-mipsel-static or running without chroot (causing the host's /lib/ld-linux to conflict with /lib/ld-uClibc.so.0) triggers immediate Invalid ELF image or No such file or directory errors.
  • Emulating outside a sandboxed VM: chroot does not prevent an emulated binary from binding network ports or writing inside /proc if mounted; keep all firmware emulation inside an isolated VM snapshot.
  • Ignoring ASLR and base-address mismatches in Ghidra: for position-independent executables (ET_DYN / PIE), verify runtime load addresses in /proc/<pid>/maps or GDB before setting breakpoints from Ghidra offsets.
  • Vendor defence: eliminate static shared secrets and model-derived maintenance tokens, replace system() / popen() shell wrappers with parameterized execve() calls, and remove undocumented factory endpoints before release.

#Summary

QEMU user-mode emulation lets you execute extracted ARM and MIPS firmware binaries directly on an x86_64 lab VM using chroot and matching qemu-*-static binaries. Using -strace exposes missing files or /dev/nvram dependencies that can be resolved with dummy directories and LD_PRELOAD shims, while -g connects gdb-multiarch to Ghidra cross-references so you can verify hardcoded secrets and command-injection sinks with certainty.

Проверка знаний

Войдите, чтобы проходить тест, завершать уроки и сохранять прогресс. Войти в систему

Практика: проверьте свои знания