unkernel-rs
Native Rust library, CLI, and Python bindings 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 withx86_64bundles via--bundle).
Install
# CLI from crates.io
# Rust library
# Python library (Linux x86_64/aarch64, macOS arm64, Windows x64 — Python 3.9+)
# Air-gapped Linux 7.x VM in 3 lines — zero Docker, zero KVM, zero root
=
# host ./repo untouched until commit!
See bindings/python/README.md for full Python examples (SSH & TCP port forwarding via port_forwards, counterfactual snapshot().branch(), --vmi-tls audit streams, and Freeze-on-Ask callbacks).
Highlights
- Single native binary (~15 MiB): Boots an unmodified Linux 7.3.4+ kernel and Alpine
aarch64rootfs with no Node.js runtime or hypervisor privileges. - Zero-Node bootstrap: Native Rust
KWP1kernel patch unpacker (src/kwpatch.rs), pinned HTTPS artifact fetch with SHA-256 verification (src/cache.rs), and version-keyed.cwasmAOT precompilation cache (~5 ms cached load). - Structured
exec, interactive PTY, and concurrent NDJSON daemon: Full host virtio-vsock bridge (src/vsock.rs) speakingkwtty(src/kwtty.rs) for separated stdout/stderr/exit codes, fake-root (uid=0), interactive shells, and a concurrentservemode 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, TLSClientHelloSNInet.tls_sni, decrypted HTTPS plaintextnet.tls_decrypted, HTTP request linenet.http,net.close), 9P filesystem activity (fs.opwith 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 Linuxstruct task_structoffsets directly fromwasmtime::SharedMemoryat boot (zero guest agents, zero kernel patches, zero hardcoded offsets), attaches originatingProcInfo(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-askorvm.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 fromSharedMemorywith zero CA injection (invisible to guestroot, works even with certificate pinning, covers OpenSSL/BoringSSL as well as Gocrypto/tlsandrustlsacross AES-128/256-GCM and ChaCha20-Poly1305 via 3-pass VMI scanning, and writes WiresharkSSLKEYLOGFILE), or Method 2 (--mitm-tls) for a transparent Sans-I/OrustlsMITM 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) andEROFSenforcement. In:cowmode, all guest creates, edits, renames, truncates, symlinks, and deletes stay in a pure-Rust in-memory overlay (never touching the host directory), withdiff,read_workspace_file,discard, and atomiccommit(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) soapk add/apt-get installpersist across restarts, or boot immutable golden images with--disk-snapshotin-memory 4 KiB COW (src/disk.rs). Capture a cloneableVmSnapshot(DiskSnapshot+ all:cowWorkspaceSnapshots) 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--netis 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 maps10.0.2.2to host127.0.0.1via 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-emittedaarch64basic-block Wasm modules via Cranelift and syncs__indirect_function_tableslots across per-taskStores via a lock-free atomicjit_epochcheck (src/jit.rs). - Defense-in-depth sandboxing: Air-gapped by default (no network or host FS imports exposed),
wasmtimeStoreLimits+epoch_interruptionhard VM timeouts, and optional outer Linux Landlock (ABI v1–v4) +PR_SET_NO_NEW_PRIVSself-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:
env.memoryisshared(flags=0x3) — maps directly to stablewasmtime::SharedMemory.- 0 active data segments, 38 passive data segments, initialized once atomically via
__wasm_init_memory/__wasm_init_memory_flag— instantiating additionalwasmtime::Instances on the sameSharedMemorynever overwrites kernel.data. - Per-CPU mutable globals (such as
__stack_pointer,__tls_base,current,kw_irq_flags, andkw_irq_word) are automatically re-exported before AOT compilation (ensure_mutable_globals_exported) and saved/restored acrosswasm_switch_to.
+-----------------------------------------------------------------------+
| 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
nextover anmpsc::sync_channel(1). - When
nextresumes, it restores the 5 globals and performs a single atomicAcquirecheck againstjit_epoch(zero overhead when no new JIT block was compiled). - Dead tasks unwind immediately when
prev_dead != 0orwasm_stack_dropis called. - Host interrupts (
vsockpackets, console input) atomically OR bits into the exportedwasm_host_irqslinear-memory word and wakepoll_oneoffviaCondvar.
Quick Start
# Build release binary
# Download/verify pinned unkernel.wasm + alpine.erofs and precompile .cwasm cache
# Run an air-gapped, Landlock-sandboxed Linux command
# Mount a local directory read-write at /workspace (or append :ro for read-only, :cow for staged copy-on-write)
# Stage agent edits in a Copy-on-Write (:cow) overlay and inspect the diff without touching host files
# Forensic HTTPS inspection (Method 1: zero-touch VMI SharedMemory key extraction + Wireshark keylog)
# Forensic HTTPS inspection (Method 2: transparent host TLS MITM with ephemeral per-VM lab CA)
# Fake-root inside the disposable guest overlay rootfs
# Opt-in networking with domain allowlist + persistent sparse ext4 disk (LAN blocked by default)
# Reuse the persistent disk completely air-gapped in immutable COW snapshot mode
# Boot Debian 13 (apt) instead of Alpine
# Hard CPU/wall-clock timeout via Wasmtime epoch interruption
# Interactive PTY shell
# Long-lived NDJSON daemon for external AI agents (Go/Python/Node/shell)
|
# Multi-VM virtual L2 Ethernet switch lab with cable-cut chaos + Wireshark PCAPng capture
Rust Library API
use Duration;
use ;
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, ...)
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
RSTto the guest before any hostTcpStreamis ever opened (zero packets leave the machine). - On filesystem deny, the 9P server returns
EACCESbefore touching the host file (coveringopenwithO_RDONLY/O_RDWR,create,write,unlink,renamebypass attempts,truncate, andchmod). - With
--freeze-on-ask,wasmtimeepoch 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:
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 Arc;
use ;
// 1. Boot parent VM with COW ext4 disk + :cow workspace and prepare shared base state
let mut cfg = default;
cfg.data_disk = Some;
cfg.data_disk_snapshot = true;
cfg.mounts.push;
let parent = boot?;
parent.exec?;
// 2. Snapshot disk + :cow workspace (0 host mutations) and fork two counterfactual branches
let snap = parent.snapshot?;
let branch_allow = snap.boot_branch?;
let branch_deny = snap.boot_branch?;
// 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/)
# Two-player LAN mode (prints separate /red and token-protected /blue URLs)
/(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 Ollamahttp://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-rsshines: 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 fakeroot, and triple-layered isolation matter more than raw CPU throughput. - Where other tools win: Userspace binaries run via
kwemusoftwareaarch64emulation (even with Cranelift JIT, CPU-bound workloads are much slower than native). For heavy compilation builds (cargo build,npm ci), prefer/dev/kvmmicroVMs (Firecracker,libkrun) or native OS sandboxing (nono/ Landlock). - Upstream ABI coupling:
unkernel(v0.3.0) is actively evolving; this crate pins and SHA-256-verifiesv0.3.0-261130-3ef745b. - Headless scope: Display/framebuffer, GPU (
virgl/Vulkan), audio, and evdev input are intentionally omitted.
Verification
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.