Skip to main content

Letting an AI Agent Emulate IoT Firmware Inside a Disposable Linux VM

· 7 min read

In Plain English: Taking apart the software inside a smart camera or router (its “firmware”) is usually slow, messy work: the program expects physical chips that your laptop doesn’t have, crashes immediately, and might try to phone home to the internet the second it wakes up. I tried giving an AI coding agent a throwaway, air-gapped Linux mini-VM (unkernel-rs) and letting it poke, patch, and reboot an extracted MIPS camera firmware in tight half-second loops. It couldn’t magically turn the camera into a full simulator, but it got surprisingly far — and turned hours of tedious setup into a clean, repeatable workflow.

TL;DR: Pairing an AI coding agent with an air-gapped, Copy-on-Write micro-VM (unkernel-rs --sinkhole --time-warp --mount ./rootfs:/mnt/fw:cow) turns early-stage IoT firmware emulation into a fast edit-compile-boot loop. The agent cross-compiles a tiny ~3 KB -nostdlib LD_PRELOAD shim in half a second, forks parallel VM snapshots to test hypotheses, and maps out the daemon’s real boot behavior — with zero Docker, zero host mutations, and zero packets leaving your machine.


Why Firmware Emulation Is Mostly Plumbing (and Why Agents Are Good at It)

When you extract the squashfs filesystem from an embedded Linux device — a router, an IP camera, a smart hub — and try to run its main daemon on your laptop, it almost never works on the first try.

Instead, you hit a predictable wall of friction:

  1. Wrong CPU architecture (mipsel, armv7l, aarch64) and a different C library (uClibc or musl instead of glibc).
  2. Missing device nodes (/dev/vendor_flash, /dev/watchdog, GPIO kernel modules).
  3. Custom vendor IPC libraries that open proprietary AF_NETLINK sockets or read factory partitions before starting HTTP/RTSP/cloud services.
  4. Hardcoded paths (/etc/default, /tmp/monitor_ready) and expired embedded certificates.

Normally, getting past those first five blockers takes an afternoon of strace, tiny C stubs, and careful cleanup so you don’t accidentally pollute your host or let a half-booted daemon spray packets onto your LAN.

That’s actually the exact kind of iterative, feedback-driven plumbing an AI coding agent is good at — if you give it a sandbox where:

  • Every boot is disposable and cannot mutate the extracted firmware directory.
  • Every outbound packet is trapped in a local sinkhole.
  • Rebuilding a shim and re-running takes seconds, not minutes.

The Sandbox Setup: CoW Mounts + Air-Gapped Sinkhole

Instead of wiring up Docker privileges, bridges, or a full-system QEMU image, I ran the entire experiment inside unkernel-rs — a real Linux 7.3 micro-VM running inside WebAssembly (wasmtime) with zero Docker, zero /dev/kvm, and zero host root.

Here is the entire command to mount an extracted firmware rootfs read-only-with-Copy-on-Write (:cow), enable isolated fake-root inside the VM (-u root), trap all outbound traffic (--sinkhole), and run a MIPS32el binary under qemu-mipsel:

unkernel-rs exec -u root --timeout-ms 60000 \
  --disk ./alpine-qemu-lab.ext4 \
  --mount ./firmware/rootfs:/mnt/fw:cow \
  --mount ./shim:/mnt/shim:ro \
  --sinkhole --time-warp --audit-file ./audit.jsonl \
  -- sh -c '
    ln -sfn /mnt/fw/etc/default /etc/default
    ln -sfn /mnt/fw/www /www
    cp /mnt/shim/fw_shim.so /mnt/fw/lib/fw_shim.so
    qemu-mipsel -L /mnt/fw -E LD_PRELOAD=/lib/fw_shim.so /mnt/fw/bin/main
  '

Four small details here do a lot of heavy lifting:

  • :cow mounts let the firmware create temp files, symlinks, and sockets freely inside /mnt/fw, while your extracted firmware folder on the host stays byte-for-byte untouched.
  • -u root gives the daemon fake-root inside the guest (so it can symlink /etc/default and bind privileged ports like 443 or 554) without a single elevated privilege on the host.
  • --sinkhole gives the guest a real virtual NIC and responds to DNS/HTTP locally while guaranteeing zero external packets ever leave your machine.
  • --audit-file records any DNS lookup or outbound connection attempt as structured JSONL.

The First Surprise: Why Host-Side Shims Don’t Work Under qemu-user

My first instinct was to intercept the failing vendor ioctl and custom AF_NETLINK protocol on the host side of qemu-mipsel. That failed immediately.

Why? Because qemu-mipsel validates Netlink protocol numbers and unknown ioctl commands in userspace and returns -EPROTONOSUPPORT or -ENOTTY before the Linux kernel ever sees a syscall.

The fix is to intercept those calls inside the guest process itself with a target-architecture LD_PRELOAD library. And because embedded firmware usually links against uClibc (not glibc), compiling the shim with -nostdlib avoids every C-library ABI mismatch and produces a tiny ~3 KB .so that loads cleanly into almost any MIPS32el binary:

/* Minimal -nostdlib dummy shim — zero libc dependency, ~3 KB compiled */
static unsigned char dummy_ctx[256];

void *vendor_ipc_create(void) { return dummy_ctx; }
int   vendor_ipc_init(void)   { return 0; }
int   vendor_ipc_send(void *h, int id, void *buf, int len) { return 0; }

/* Forward the daemon's internal log hook to stderr so boot progress is visible */
int vendor_push_log(int level, const char *msg) {
    (void)level;
    if (msg) write_stderr(msg);
    return 0;
}

/* Return deterministic synthetic bytes when hardware-backed keys are absent */
int mbedtls_pk_decrypt(void *ctx, const unsigned char *in, unsigned int ilen,
                       unsigned char *out, unsigned int *olen, unsigned int osize,
                       void *f_rng, void *p_rng) {
    unsigned int n = osize < 32 ? osize : 32;
    for (unsigned int i = 0; i < n; i++) out[i] = (unsigned char)('A' + (i % 26));
    if (olen) *olen = n;
    return 0;
}

Compiled once with a cached cross-compiler container:

mipsel-linux-gnu-gcc -march=mips32r2 -mabi=32 -fPIC -shared -nostdlib -O2 \
  fw_shim.c -o fw_shim.so

Recompiling took ~0.5 seconds. That turned the agent’s workflow into: read strace → tweak a few lines of C → recompile in 0.5s → reboot in a fresh :cow VM → inspect /proc/$PID/task and /proc/net/tcp.


Three Fun Moments in the Loop

Once the agent had that fast feedback loop, it peeled back layers of the firmware’s boot sequence one by one:

1. Accidentally Muting the Daemon’s Own Boot Logs

Early on, the daemon stayed alive (ALIVE=YES) but printed almost nothing. It turned out our no-op stubs for the vendor messaging library were silently swallowing its internal log calls. Forwarding that single function to stderr suddenly lit up the daemon’s entire initialization sequence — showing every subsystem as it came online (sntpc_init, nifc_init, osd_init, onvif_init, and so on).

2. Letting the Daemon Talk to Itself

With logs visible, we noticed the daemon finished its *_init() steps and stalled before starting its services because our stub was dropping internal messages between subsystems. Passing those messages through a small non-blocking local socket inside the shim let the daemon’s own event loop wake up and cross into its *_start() phase with 5 live threads — without ever needing the missing kernel driver.

3. Branching Hypotheses in Parallel with Snapshots

Instead of re-booting from scratch for every experiment (minimal shim vs. synthetic flash payload vs. crypto-decrypt stub), unkernel-rs’s Python API lets you boot once to a warm baseline and fork parallel CoW branches from the same snapshot:

import concurrent.futures
import unkernel_rs

with unkernel_rs.Vm(disk="./alpine-qemu-lab.ext4", sinkhole=True) as vm:
    snap = vm.snapshot()

def probe(variant, env_preload):
    with snap.restore() as branch:
        res = branch.exec(f"LD_PRELOAD={env_preload} /mnt/fw/bin/main", timeout_ms=10_000)
        return variant, res.exit_code, res.stdout[:200]

with concurrent.futures.ThreadPoolExecutor(max_workers=3) as pool:
    results = list(pool.map(lambda args: probe(*args), [
        ("baseline", "/lib/shim_v1.so"),
        ("async_ipc", "/lib/shim_v2.so"),
        ("synth_crypto", "/lib/shim_v3.so"),
    ]))

Every branch starts from the exact same filesystem state, runs isolated, and throws away its dirty blocks on exit.


Honest Limits: Is a “Reversing Agent” Actually Wise?

Yes — as a triage and emulation assistant, not as an autonomous magic wand.

Here is the honest split from actually running the experiment:

Where this workflow genuinely shines:

  • Fast first-hour triage: Auditing embedded configs, default JSON policies, init scripts, and expired certificates, and getting a foreign-architecture binary past its initial crash loop in minutes instead of hours.
  • Safe behavioral observation: Watching what files, Unix sockets, DNS names, and ports a binary touches on boot — inside a :cow + --sinkhole VM where nothing can leak or corrupt your host.
  • Runtime ABI discovery: Instrumenting ioctl pointers and IPC message IDs with a 3 KB shim is often much faster than staring at raw disassembly first.

Where it hits a real wall:

  • Deep hardware-driver locks: Monolithic embedded daemons eventually block on a futex waiting for an ISP, DSP, Wi-Fi, or GPIO kernel module that simply doesn’t exist in a generic VM.
  • Opaque binary flash formats: Spoofing ioctl(...) == 0 gets you past error checks, but returning a realistic vendor factory partition (CRCs, encrypted blobs, device-specific structs) still requires real static reverse engineering in Ghidra or Binary Ninja.
  • Speed under double emulation: Running qemu-mipsel inside an aarch64-in-WebAssembly Linux kernel is totally fine for config parsing and boot triage (~15–25s to parse dozens of JSON files), but not meant for high-throughput fuzzing.

Even when you do hit that wall, though, you don’t walk away empty-handed: instead of opening a 10 MB binary cold, the agent hands you the exact strace, the exact ioctl numbers, the internal boot log, and the exact futex address where hardware emulation becomes necessary.

For a 5.9 MB disposable VM with zero Docker and zero risk to your laptop, that’s a pretty good trade.

Follow-up: What happens if you take this idea to its logical extreme — combining ~55 ms live-RAM VM rewinds with a local RTX 5060 Ti LLM to synthesize missing configs, rebuild deleted .so libraries, and heal live SIGSEGV crashes mid-air? Read the sequel: Quick-Save VMs + a Local LLM: Letting Broken Linux Binaries Hallucinate What’s Missing.

The views and opinions expressed here are my own and do not reflect those of my employer.