unkernel-rs 0.5.0

Native Rust + Wasmtime host library and CLI for unkernel (Linux 7.x on WebAssembly) — zero Node, zero JSPI, zero KVM
Documentation

unkernel-rs

Native Rust library and CLI hosting pithings/unkernel (Linux 7.x compiled to WebAssembly) directly on wasmtime — running natively on Linux, macOS, and Windows with zero Node.js, zero V8, zero JSPI, zero Docker, zero WSL2, and zero /dev/kvm.

Status: Pinned to unkernel v0.3.0-261130-3ef745b (Alpine 3.24.4 / Linux 7.3.4+ aarch64, also tested with x86_64 bundles via --bundle).

Highlights

  • Single native binary (~15 MiB): Boots an unmodified Linux 7.3.4+ kernel and Alpine aarch64 rootfs with no Node.js runtime or hypervisor privileges.
  • Zero-Node bootstrap: Native Rust KWP1 kernel patch unpacker (src/kwpatch.rs), pinned HTTPS artifact fetch with SHA-256 verification (src/cache.rs), and version-keyed .cwasm AOT precompilation cache (~5 ms cached load).
  • Structured exec, interactive PTY, and concurrent NDJSON daemon: Full host virtio-vsock bridge (src/vsock.rs) speaking kwtty (src/kwtty.rs) for separated stdout/stderr/exit codes, fake-root (uid=0), interactive shells, and a concurrent serve mode for AI coding agents (nono-agent, Go/Python/Node controllers).
  • Untamperable host-side telemetry, Level-3 VMI process monitoring, HTTPS forensic decryption (--vmi-tls / --mitm-tls), whole-VM freeze/resume & interactive approvals: Observe and gate network (net.dns, net.connect, TLS ClientHello SNI net.tls_sni, decrypted HTTPS plaintext net.tls_decrypted, HTTP request line net.http, net.close), 9P filesystem activity (fs.op with automatic credential/secret detection for .env, .npmrc, .ssh/*, .aws/*, .kube/*, etc.), and live guest Linux processes (proc.exec, proc.exit, vm.active_processes()). Level-3 Virtual Machine Introspection (src/vmi.rs) dynamically auto-calibrates Linux struct task_struct offsets directly from wasmtime::SharedMemory at boot (zero guest agents, zero kernel patches, zero hardcoded offsets), attaches originating ProcInfo (pid, ppid, comm) to network/filesystem/approval events, and lets you inspect live guest processes even while the VM is completely frozen via --freeze-on-ask or vm.pause() (src/monitor.rs). For forensic HTTPS inspection (src/tls_inspect.rs), choose Method 1 (--vmi-tls / --tls-keylog) to extract live TLS 1.3/1.2 session keys directly from SharedMemory with zero CA injection (invisible to guest root, works even with certificate pinning, covers OpenSSL/BoringSSL as well as Go crypto/tls and rustls across AES-128/256-GCM and ChaCha20-Poly1305 via 3-pass VMI scanning, and writes Wireshark SSLKEYLOGFILE), or Method 2 (--mitm-tls) for a transparent Sans-I/O rustls MITM proxy using an ephemeral per-VM Root CA installed only in the disposable guest overlay.
  • Scoped 9P2000.L host mounts + Copy-on-Write (:cow) workspace staging: Mount host directories into the guest (--mount ./work:/workspace[:ro|rw|cow]) with strict canonical root confinement (blocks .. and symlink escapes outside the mount) and EROFS enforcement. In :cow mode, all guest creates, edits, renames, truncates, symlinks, and deletes stay in a pure-Rust in-memory overlay (never touching the host directory), with diff, read_workspace_file, discard, and atomic commit (src/fs9p.rs).
  • Persistent ext4 disks & forkable Tier-A OS branching (--disk, Vm::snapshot): Auto-unpacks the bundled 4 GiB sparse ext4 overlay template (unkernel.datadisk / KWSPARS1) so apk add / apt-get install persist across restarts, or boot immutable golden images with --disk-snapshot in-memory 4 KiB COW (src/disk.rs). Capture a cloneable VmSnapshot (DiskSnapshot + all :cow WorkspaceSnapshots) and fork independent parallel branch VMs (snap.boot_branch(...)) with different network or approval policies for counterfactual agent evaluation.
  • Opt-in user-space NAT networking (--net): Air-gapped by default. When --net is passed, provides ARP/DHCP/ICMP/DNS/TCP NAT (10.0.2.15/24) over host sockets with SSRF/LAN protection (blocks loopback & RFC1918/homelab ranges by default unless --allow-lan, which also maps 10.0.2.2 to host 127.0.0.1 via QEMU SLIRP convention) and optional --allow-host <domain> allowlisting enforced on both DNS and TCP (src/net.rs).
  • Multi-VM Virtual L2 Switch & Forensic Network Lab (unkernel-rs lab): Boot 2+ isolated Wasmtime Linux VMs in parallel connected over a pure-Rust learning Layer-2 Ethernet switch (switch0, src/switch.rs) with MAC table learning, real-time chaos fault injection (cut, reconnect, drop <pct>, delay <ms>), zero-dependency Wireshark-compatible PCAPng packet capture (--pcap), optional per-node NAT uplink + VMI/TLS inspection, and both scripted (--run) and interactive/NDJSON control loops.
  • Cranelift guest JIT (kw_host_jit_*): Compiles guest-emitted aarch64 basic-block Wasm modules via Cranelift and syncs __indirect_function_table slots across per-task Stores via a lock-free atomic jit_epoch check (src/jit.rs).
  • Defense-in-depth sandboxing: Air-gapped by default (no network or host FS imports exposed), wasmtime StoreLimits + epoch_interruption hard VM timeouts, and optional outer Linux Landlock (ABI v1–v4) + PR_SET_NO_NEW_PRIVS self-sandboxing blocking all host paths outside explicit mounts and blocking host TCP bind (and connect when air-gapped) on ABI v4+ (src/sandbox.rs).

Architecture: Hosting unkernel Without JSPI

Upstream unkernel relies on V8/Node's experimental WebAssembly JSPI (WebAssembly.Suspending) to suspend/resume Linux kernel task stacks during wasm_switch_to.

unkernel-rs avoids JSPI, Asyncify, and unstable stack-switching proposals by unpacking the SMP kernel delta (unkernel.kernel.smp.kwpatch) bundled inside unkernel.wasm:

  1. env.memory is shared (flags=0x3) — maps directly to stable wasmtime::SharedMemory.
  2. 0 active data segments, 38 passive data segments, initialized once atomically via __wasm_init_memory / __wasm_init_memory_flag — instantiating additional wasmtime::Instances on the same SharedMemory never overwrites kernel .data.
  3. Only 5 mutable globals (all exported by name): __stack_pointer, __tls_base, current, kw_irq_flags, and kw_irq_word.
+-----------------------------------------------------------------------+
| Outer OS Sandbox (Linux Landlock ABI v4 + PR_SET_NO_NEW_PRIVS)        |
|   - Host FS restricted strictly to explicit --mount dirs (or none)    |
|   - Host TCP bind/connect blocked on Landlock ABI v4+                 |
|                                                                       |
|  +-----------------------------------------------------------------+  |
|  | Rust + Wasmtime Host (StoreLimits + Epoch Timeout)              |  |
|  |                                                                 |  |
|  |   SharedMemory (128 MiB guest RAM)   <-- shared by all tasks    |  |
|  |   InstancePre<TaskStore>             <-- pre-linked once        |  |
|  |                                                                 |  |
|  |   [kthread 0]  <-- 5 globals + token via sync_channel(1) -->    |  |
|  |   [kthread 1]      (single-CPU cooperative, wasm_cpu_count=1)   |  |
|  |                                                                 |  |
|  |   Drivers: Block RO (.erofs) | Vsock + IRQ | Cranelift JIT      |  |
|  |   Services: kwtty (port 1022) | 9P2000.L (port 564)             |  |
|  +-----------------------------------------------------------------+  |
+-----------------------------------------------------------------------+

On wasm_switch_to(prev, next, is_new, prev_dead):

  • The outgoing task saves the 5 mutable globals and transfers them + execution token to next over an mpsc::sync_channel(1).
  • When next resumes, it restores the 5 globals and performs a single atomic Acquire check against jit_epoch (zero overhead when no new JIT block was compiled).
  • Dead tasks unwind immediately when prev_dead != 0 or wasm_stack_drop is called.
  • Host interrupts (vsock packets, console input) atomically OR bits into the exported wasm_host_irqs linear-memory word and wake poll_oneoff via Condvar.

Quick Start

# Build release binary
cargo build --release

# Download/verify pinned unkernel.wasm + alpine.erofs and precompile .cwasm cache
./target/release/unkernel-rs fetch

# Run an air-gapped, Landlock-sandboxed Linux command
./target/release/unkernel-rs exec --sandbox -- uname -a

# Mount a local directory read-write at /workspace (or append :ro for read-only, :cow for staged copy-on-write)
./target/release/unkernel-rs exec --sandbox -m ./work:/workspace -- sh -c 'ls -la /workspace'

# Stage agent edits in a Copy-on-Write (:cow) overlay and inspect the diff without touching host files
./target/release/unkernel-rs exec --sandbox -m ./work:/workspace:cow --show-diff \
  -- sh -c 'echo staged > /workspace/new.txt'

# Forensic HTTPS inspection (Method 1: zero-touch VMI SharedMemory key extraction + Wireshark keylog)
./target/release/unkernel-rs exec --sandbox --vmi-tls --tls-keylog ./sslkeylog.txt --audit \
  -- wget -qO- https://example.com

# Forensic HTTPS inspection (Method 2: transparent host TLS MITM with ephemeral per-VM lab CA)
./target/release/unkernel-rs exec --sandbox --mitm-tls --audit \
  -- wget -qO- https://example.com

# Fake-root inside the disposable guest overlay rootfs
./target/release/unkernel-rs exec --sandbox -u root -- id

# Opt-in networking with domain allowlist + persistent sparse ext4 disk (LAN blocked by default)
./target/release/unkernel-rs exec --sandbox --net --allow-host alpinelinux.org \
  --disk ./state.ext4 -u root -- apk add --no-cache jq

# Reuse the persistent disk completely air-gapped in immutable COW snapshot mode
./target/release/unkernel-rs exec --sandbox --offline \
  --disk ./state.ext4 --disk-snapshot -- jq --version

# Boot Debian 13 (apt) instead of Alpine
./target/release/unkernel-rs exec --distro debian --mem 384 --sandbox --net \
  --allow-host deb.debian.org --disk ./debian.ext4 -u root -- sh -c 'apt-get update && apt-get install -y jq'

# Hard CPU/wall-clock timeout via Wasmtime epoch interruption
./target/release/unkernel-rs exec --sandbox --vm-timeout-ms 1500 -- sh -c 'while :; do :; done'

# Interactive PTY shell
./target/release/unkernel-rs shell --sandbox

# Long-lived NDJSON daemon for external AI agents (Go/Python/Node/shell)
printf '{"id":1,"cmd":"uname -sr"}\n{"id":2,"cmd":"id -u","user":"root"}\n{"shutdown":true}\n' \
  | ./target/release/unkernel-rs serve --sandbox

# Multi-VM virtual L2 Ethernet switch lab with cable-cut chaos + Wireshark PCAPng capture
./target/release/unkernel-rs lab --node web --node client --pcap ./lab.pcapng \
  --run "client:ping -c 2 -W 2 web" \
  --run "cut:web" \
  --run "client:ping -c 1 -W 1 web" \
  --run "reconnect:web" \
  --run "macs"

Rust Library API

use std::time::Duration;
use unkernel_rs::{ExecOptions, MountSpec, Vm, VmConfig};

fn main() -> wasmtime::Result<()> {
    let mut cfg = VmConfig::default();
    cfg.sandbox = true;
    cfg.vm_timeout = Some(Duration::from_secs(10));
    cfg.mounts.push(MountSpec::parse("./work:/workspace:ro")?);

    let vm = Vm::boot(cfg)?;
    let res = vm.exec(&ExecOptions::shell("uname -sr && ls /workspace"))?;
    println!("exit={:?}\n{}", res.exit_code, res.stdout_lossy());
    vm.shutdown();
    Ok(())
}

Host-Side Monitoring, Freeze/Resume & Interactive Approvals

Because all host networking (src/net.rs), host directory access (src/fs9p.rs), and CPU scheduling (src/host.rs) cross the Wasmtime host boundary, unkernel-rs can observe, freeze, and gate suspicious behavior from outside the guest Linux kernel — useful both for supervising AI coding agents and for analyzing untrusted packages / supply-chain threats (e.g. Shai-Hulud credential harvesters scanning .env / .npmrc and phoning home):

CLI Audit & Interactive Approval Mode (exec)

# Stream JSONL audit events (stderr) + write to a Landlock-preopened log file,
# pausing & freezing the entire VM before any outbound TCP connect, 9P write,
# or sensitive credential read (.env, .npmrc, .ssh/*, .aws/*, .kube/*, *.pem, ...)
./target/release/unkernel-rs exec --sandbox \
  -m ./untrusted-repo:/workspace:rw \
  --audit --audit-file ./audit.jsonl \
  --ask-net --ask-fs-write --ask-sensitive --freeze-on-ask \
  -- sh -c 'cat /workspace/.env; wget -qO- https://example.com'

When an approval gate fires in exec mode, unkernel-rs prompts directly on /dev/tty (pre-opened before Landlock):

[SANDBOX APPROVAL #1] FsSensitiveRead: /workspace/.env (sensitive_read)
  [a]llow once / [A]llow always / [d]eny once / [D]eny always >
  • On network deny, the host immediately injects a TCP RST to the guest before any host TcpStream is ever opened (zero packets leave the machine).
  • On filesystem deny, the 9P server returns EACCES before touching the host file (covering open with O_RDONLY/O_RDWR, create, write, unlink, rename bypass attempts, truncate, and chmod).
  • With --freeze-on-ask, wasmtime epoch interruption halts every guest kernel task and pauses guest monotonic time (/proc/uptime, timers) until you decide.

Concurrent NDJSON serve Protocol (for AI Agents & External Controllers)

Start serve with --audit and any --ask-* flags:

./target/release/unkernel-rs serve --sandbox --audit \
  --ask-net --ask-fs-write --ask-sensitive --freeze-on-ask \
  -m ./work:/workspace:rw

While commands execute asynchronously in worker threads, serve streams real-time audit events on stdout ({"event":"..."}) and accepts immediate control messages on stdin:

Direction Message Example Purpose
Host → Controller {"event":"proc.exec","pid":42,"ppid":41,"comm":"curl",...} / {"event":"proc.exit",...} Untamperable Level-3 VMI guest process lifecycle from SharedMemory
Host → Controller {"event":"approval.required","approval_id":1,"kind":"fs_sensitive_read","target":"/workspace/.env","proc":{"pid":43,"comm":"cat",...}} Operation paused awaiting judgment (with originating guest process)
Host → Controller {"event":"vm.paused","ts_ms":...,"reason":"approval #1: /workspace/.env"} Whole VM frozen via epoch interruption
Host → Controller {"event":"net.tls_sni","ip":"...","port":443,"sni":"registry.npmjs.org","proc":{...}} Extracted TLS ClientHello SNI
Host → Controller {"event":"net.tls_decrypted","ip":"...","port":443,"method":"vmi","direction":"tx","http_summary":"GET /...","preview":"..."} Decrypted HTTPS payload (via --vmi-tls or --mitm-tls)
Host → Controller {"event":"net.http","ip":"...","port":80,"method":"POST","path":"/exfil","host":"...","proc":{...}} Extracted HTTP request line (plaintext or decrypted HTTPS)
Controller → Host {"id":"a1","approve":1,"decision":"deny_once"} Resolve approval (allow_once | allow_always | deny_once | deny_always)
Controller → Host {"id":"p1","pause":true} / {"id":"p2","resume":true} Manually freeze / resume entire guest VM & clock
Controller → Host {"id":"ps1","procs":true} List live guest Linux processes via VMI (works even while VM is frozen)
Controller → Host {"id":"d1","diff":"/workspace"} / {"id":"x1","discard":"/workspace"} / {"id":"c1","commit":"/workspace"} Inspect, roll back, or commit staged :cow workspace changes
Controller → Host {"id":"s1","snapshot":"cp1"} / {"id":"r1","restore":"cp1"} Capture a named Tier-A disk+workspace snapshot or branch/restore from it
Controller → Host {"id":"q1","pending":true} List currently waiting approval requests
Controller → Host {"id":1,"cmd":"npm test","cwd":"/workspace"} Execute command inside sandbox
Controller → Host {"shutdown":true} Cleanly flush disks and power off

The same controls are exposed directly on the Rust Vm struct via vm.pause(), vm.resume(), vm.is_paused(), vm.active_processes(), vm.current_process(), vm.vmi_offsets(), vm.workspace_diff(...), vm.discard_workspace(...), vm.commit_workspace(...), vm.snapshot(), Vm::branch_from_snapshot(...), vm.pending_approvals(), vm.resolve_approval(...), and MonitorConfig.

Level-3 VMI & Counterfactual OS Branching (Rust API)

use std::sync::Arc;
use unkernel_rs::{ApprovalDecision, ExecOptions, MonitorConfig, MountSpec, Vm, VmConfig};

// 1. Boot parent VM with COW ext4 disk + :cow workspace and prepare shared base state
let mut cfg = VmConfig::default();
cfg.data_disk = Some("./state.ext4".into());
cfg.data_disk_snapshot = true;
cfg.mounts.push(MountSpec::parse("./repo:/workspace:cow")?);
let parent = Vm::boot(cfg)?;
parent.exec(&ExecOptions::shell("echo ready > /workspace/setup.txt"))?;

// 2. Snapshot disk + :cow workspace (0 host mutations) and fork two counterfactual branches
let snap = parent.snapshot()?;
let branch_allow = snap.boot_branch(None, Some(MonitorConfig {
    ask_sensitive_read: true,
    approval_callback: Some(Arc::new(|_| ApprovalDecision::AllowOnce)),
    ..MonitorConfig::default()
}))?;
let branch_deny = snap.boot_branch(None, Some(MonitorConfig {
    ask_sensitive_read: true,
    approval_callback: Some(Arc::new(|_| ApprovalDecision::DenyOnce)),
    ..MonitorConfig::default()
}))?;

// Inspect live guest processes from SharedMemory even while frozen!
branch_deny.pause();
let procs_while_frozen = branch_deny.active_processes();

Interactive WebUI Demo: "Catch Me If You Can"

Try a live Red-Team vs. Blue-Team browser demonstrator (examples/catch_me_if_you_can.rs) with zero extra dependencies:

# Local solo split-screen demo (http://127.0.0.1:8787/)
cargo run --release --example catch_me_if_you_can

# Two-player LAN mode (prints separate /red and token-protected /blue URLs)
cargo run --release --example catch_me_if_you_can -- --bind 0.0.0.0:8787
  • / (Split View): Left pane runs a live guest Linux shell seeded with fake canary secrets (/workspace/.env, .npmrc, .ssh/id_ed25519, app.js) and one-click Shai-Hulud / SSRF / DNS probes; right pane shows the untamperable host SOC monitor with real-time SSE audit telemetry, taint status, whole-VM Freeze / Resume, forensic guest inspection, and Allow / Deny approval cards.
  • /red & /blue?token=...: Separate 2-player views where Player 1 operates blindly inside the guest VM while Player 2 audits, freezes, and blocks attacks from outside (and in LAN mode Red cannot self-approve).
  • Optional AI Blue-Team Auto-Judge: Toggle AI Judge in the Blue Team bar (or pass --ai-endpoint + --ai-model, e.g., local Ollama http://127.0.0.1:11434/v1/chat/completions) to let an external LLM inspect the structured audit timeline and decide approvals automatically while the VM stays frozen.

Benchmarks (2026-11-28, Linux x86_64 host, Alpine 3.24.4 / Linux 7.3.4+ aarch64, 128 MiB guest)

Reproduce locally with ./target/release/unkernel-rs bench.

Metric Node.js (v23.11.1 + JSPI) unkernel-rs (wasmtime 48)
Runtime footprint Node.js + unkernel npm pkg 15 MiB native binary (+ 26 MiB .cwasm cache)
Module load / compile 103 ms (createKernel) ~2.2 s cold AOT → 5–6 ms cached .cwasm
Cold boot → first exec("true") 379 ms 254–279 ms (total process start to ready)
Peak host RSS (VmHWM, single VM) 231.9 MiB 72.9 MiB (3.2× less RAM)
exec("true") round-trip latency 3.4 ms 6.8 ms (5-run average)
seq 50000 | sort -r (JIT ON) 1,340 ms (V8 Liftoff: 90 ms compile) 2,419 ms (Cranelift: 793 ms compile / 1.63 s run, 96 blocks)
seq 50000 | sort -r (JIT OFF) — 4,228 ms (1.75× Cranelift JIT speedup)
Native host baseline (seq 50000 | sort -r) 27–47 ms 27–47 ms

Honest Tradeoffs

  • Where unkernel-rs shines: Unprivileged, zero-KVM, zero-Docker, cross-OS Linux sandboxing inside nested VMs, CI runners, Kubernetes pods, or developer machines for short untrusted agent scripts/tools where 73 MiB RAM, ~270 ms cold boot, disposable fake root, and triple-layered isolation matter more than raw CPU throughput.
  • Where other tools win: Userspace binaries run via kwemu software aarch64 emulation (even with Cranelift JIT, CPU-bound workloads are much slower than native). For heavy compilation builds (cargo build, npm ci), prefer /dev/kvm microVMs (Firecracker, libkrun) or native OS sandboxing (nono / Landlock).
  • Upstream ABI coupling: unkernel (v0.3.0) is actively evolving; this crate pins and SHA-256-verifies v0.3.0-261130-3ef745b.
  • Headless scope: Display/framebuffer, GPU (virgl/Vulkan), audio, and evdev input are intentionally omitted.

Verification

cargo test --release

Tests verify native kwpatch SHA-256 identity, exec stdout/stderr/stdin/env/cwd/exit-code, fake-root + air-gap isolation, 9P2000.L read-write/read-only/:cow mounts + symlink escape blocking + diff/discard/commit, persistent sparse ext4 disks + immutable --disk-snapshot COW overlays + multi-branch Tier-A OS snapshot branching (Vm::snapshot / boot_branch), Level-3 VMI dynamic task_struct calibration + process attribution + frozen-VM process listing, forensic HTTPS decryption via both zero-touch SharedMemory VMI key extraction (--vmi-tls + Wireshark SSLKEYLOGFILE) and transparent ephemeral-CA MITM (--mitm-tls), user-space NAT DHCP/ICMP + SSRF/LAN blocking + --allow-host domain refusal, Cranelift guest JIT block compilation, Wasmtime epoch hard timeout on infinite loops, Linux Landlock ABI v4 NDJSON serve mode (including procs, diff, snapshot, restore), host-side audit telemetry (TLS SNI, HTTP request line, sensitive credential detection), whole-VM freeze/resume with frozen guest monotonic clock, and interactive approve/deny gates across both Rust API and concurrent NDJSON serve.


Licensing

unkernel-rs is dual-licensed under MIT (LICENSE-MIT) or Apache-2.0 (LICENSE-APACHE).

Runtime artifacts downloaded and cached on first use remain under their respective upstream licenses:

  • unkernel.wasm (Linux 7.x kernel) — GPL-2.0-only (pithings/unkernel).
  • Distro images (alpine.erofs, etc.) — licenses of their included distribution packages.