ghostlan
# ghostlan
`ghostlan` turns a single Linux machine into `1..N` isolated virtual PCs ("ghosts") on a named virtual LAN—with live packet/network fault injection (`tc netem`), optional internet access (`--nat`), isolated per-ghost home/temp directories, headless virtual X11 displays (`Xvfb` + `xdotool`), and a built-in **MCP server** for AI agents.
---
## Why `ghostlan`?
Testing distributed, P2P, media-transport, or desktop apps normally forces you into either:
- **Docker/VMs** — painful for native GUI apps, GPU/audio, X11/Wayland, and fast iteration.
- **Manual `ip netns` bash scripts** — fragile, require `sudo` on every command, and leak namespaces/temp dirs on failure.
`ghostlan` runs **native host binaries** inside isolated Linux network namespaces (`netns`) connected via a Linux bridge, with:
- Normal unprivileged user UID inside every ghost (no root GUI warnings).
- Isolated `HOME`, `TMPDIR`, and `XDG_*` directories per ghost (no `/tmp` lockfile collisions).
- One-time `setcap` setup so both humans and LLM agents run without `sudo`.
---
## Use Cases
- **2-PC / P2P & Media Streaming Tests on One Machine:** Test sender/receiver apps (OBS-to-OBS, VoIP, QUIC/UDP, LAN/mDNS discovery) under real packet loss, jitter, bandwidth caps, and cable unplug/replug (`link down`/`up`).
- **Autonomous LLM E2E Testing (No Babysitting):** Designed from the ground up as an **MCP server** so any AI coding agent (Claude Code, Antigravity, Cursor, Claude Desktop, Windsurf) can run full multi-machine tests end-to-end without `sudo` prompts or hijacking your real desktop.
- **Multi-Instance Isolation Without Docker/VMs:** Run multiple copies of desktop apps that normally collide on `/tmp` lockfiles, `$HOME`/XDG configs, ports, or PipeWire audio—at native speed.
### How Autonomous LLM Testing Works (MCP-First)
1. **Zero `sudo` prompts:** One-time `ghostlan setup --mcp` grants `setcap` and registers `ghostlan mcp` across your installed AI clients.
2. **Visual feedback loop:** With `--gui`, each ghost gets its own headless `Xvfb -auth` display. The agent calls `ghostlan_gui_screenshot` and receives a native PNG directly in MCP, then drives dialogs with `ghostlan_gui_click` / `type` / `key`.
3. **Deterministic waiting & filtering:** Instead of brittle `sleep` + `grep`, the agent uses `ghostlan_gui_wait_window`, `ghostlan_wait_log`, and `ghostlan_logs` (`filter` + `since_line`).
4. **Live fault injection:** The agent calls `ghostlan_netem_set` (loss/delay/jitter/rate), `ghostlan_link` (up/down), and `ghostlan_status` (rx/tx/drop counters) mid-test, then cleans up with `ghostlan_down`.
---
## Requirements & One-Time Setup
### Runtime Dependencies
- **Core:** Linux kernel with `netns` + `nftables` + `tc netem`
- **GUI mode (`--gui`):** `Xvfb`, `xdotool`, `import` (ImageMagick), plus optional `openbox` (auto-started per display when installed for full window-manager focus/dialog support)
- **Isolated audio (`--audio-null`):** `pipewire`, `pipewire-pulse`, `pactl` (each ghost gets its own `XDG_RUNTIME_DIR` + virtual null sink/mic, zero host audio bleed)
### Quick Install (Pre-built Static Binary + `setcap` + MCP)
```bash
curl -fsSL https://raw.githubusercontent.com/saifmukhtar/ghostlan/main/install.sh | sh
```
### Build & Grant Capabilities (From Source)
```bash
go build -o ghostlan ./cmd/ghostlan
./ghostlan setup --mcp
```
`ghostlan setup --mcp` installs `/usr/local/bin/ghostlan` (`0750`, owned by `root:<your-group>`), prompts for `sudo` once to apply `cap_net_admin,cap_sys_admin,cap_dac_override+ep`, and registers `ghostlan` in detected MCP clients. After this, **no `sudo` is needed** at runtime.
---
## Quick Start
```bash
# Create a named virtual LAN "openavx-test" with 2 ghosts (tx, rx),
# headless X11 displays (--gui), and 20ms latency + 5% packet loss defaults:
./ghostlan up openavx-test tx rx --gui --delay 20 --loss 5
# List active LANs
./ghostlan ls
# Check IPs, displays, link state, netem rules, and stats
./ghostlan status openavx-test --json
# Run a one-shot command inside tx
./ghostlan exec openavx-test tx -- ping -c 2 10.99.x.12
# Start a background server in rx and read its logs
./ghostlan start openavx-test rx -- python3 -m http.server 8080
./ghostlan logs openavx-test rx --tail 20
# Inject or clear live network faults
./ghostlan netem set openavx-test tx --loss 15 --delay 80 --jitter 10 --rate 2000
./ghostlan netem clear openavx-test tx
# Simulate unplugging/replugging an Ethernet cable
./ghostlan link down openavx-test rx
./ghostlan link up openavx-test rx
# Tear down everything cleanly (processes, Xvfb, netns, bridge, temp dirs)
./ghostlan down openavx-test
```
> **Shorthand:** Any ghost-targeted command accepts either `<lan> <ghost>` or `<lan>/<ghost>` (e.g., `ghostlan exec openavx-test/tx -- ...`).
---
## Command Reference
### LAN Lifecycle
| Command | What it does |
|---|---|
| `ghostlan up <lan> [count \| g1 g2 ...]` | Create a named LAN (defaults to `ghost1`, `ghost2`). Flags: `--nat`, `--uplink`, `--gui`, `--audio-null`, `--private`, `--dir <path>`, `--screen WxH`, `--loss`, `--delay`, `--jitter`, `--corrupt`, `--duplicate`, `--rate`. |
| `ghostlan ls [--json]` | List all active virtual LANs. |
| `ghostlan status <lan> [--json]` | Show ghost IPs, virtual displays, link state, active `netem`, live interface rx/tx/drop counters, and running process states. |
| `ghostlan down <lan>` | Stop all tracked processes and `Xvfb` displays, delete namespaces/veths/bridge/nftables rules, and remove `/tmp/ghostlan/<lan>`. |
### Process & Command Execution
| Command | What it does |
|---|---|
| `ghostlan exec <lan> <ghost> -- <cmd...>` | Run a one-shot command inside the ghost's `netns` and isolated env, returning its exit code. |
| `ghostlan start <lan> <ghost> -- <cmd...> [--json]` | Launch a detached background process inside the ghost; returns `proc_id` (e.g., `proc-1`), PID, and log path. |
| `ghostlan stop <lan> <ghost> <proc-id>` | Terminate a tracked background process (`SIGTERM`, then `SIGKILL`). |
| `ghostlan logs <lan> <ghost> [--proc id] [--tail N] [--since line] [--filter text]` | Read trailing or filtered `stdout`/`stderr` log lines of a background process. |
| `ghostlan wait-log <lan> <ghost> <pattern> [--proc id] [--timeout 10s]` | Poll a ghost's process log until a line matches `<pattern>`. |
### Network Fault Injection
| Command | What it does |
|---|---|
| `ghostlan netem set <lan> <ghost> [flags]` | Apply live `tc netem` on the ghost's `eth0` (`--loss`, `--delay`, `--jitter`, `--corrupt`, `--duplicate`, `--rate`). |
| `ghostlan netem clear <lan> <ghost>` | Remove active `netem` impairments from the ghost. |
| `ghostlan link up <lan> <ghost>` | Bring the ghost's `eth0` interface up. |
| `ghostlan link down <lan> <ghost>` | Bring the ghost's `eth0` interface down (100% disconnect without killing processes). |
| `ghostlan capture start <lan> <ghost> [out.pcap] [--duration 5] [--max-packets 2000]` | Capture live packets on the ghost's host-side `veth` into a `.pcap` file (requires `CAP_NET_RAW`). |
| `ghostlan capture inspect <pcap-file> [--filter "..."] [--limit 50] [--json]` | Summarize `.pcap` counts and decode packets via `tcpdump -r`. |
### Virtual X11 Display (`--gui`)
| Command | What it does |
|---|---|
| `ghostlan gui windows <lan> <ghost> [--json]` | List visible X11 windows, PIDs, geometries, and titles inside the ghost's `Xvfb`. |
| `ghostlan gui wait-window <lan> <ghost> <title> [--timeout 10s]` | Poll until a window matching `<title>` appears. |
| `ghostlan gui screenshot <lan> <ghost> [out.png] [--window id\|title]` | Capture the ghost's virtual screen (or a specific window) to a PNG file. |
| `ghostlan gui click <lan> <ghost> <x> <y> [--button 1] [--double] [--window id\|title]` | Click at coordinates (screen-relative or window-relative). |
| `ghostlan gui type <lan> <ghost> <text> [--window id\|title]` | Type text into the ghost's display or target window. |
| `ghostlan gui key <lan> <ghost> <key> [--window id\|title]` | Send a key or combo (e.g., `Return`, `ctrl+s`, `Escape`). |
| `ghostlan gui record <lan> <ghost> [out.mp4] [--duration 3]` | Record a short MP4 video (and audio if `--audio-null`) of the ghost's virtual screen (`ffmpeg`). |
| `ghostlan gui motion <lan> <ghost> [--interval 500] [--json]` | Compare two spaced frames to verify video motion vs frozen screen. |
### Isolated Audio (`--audio-null`)
| Command | What it does |
|---|---|
| `ghostlan audio check <lan> <ghost> [--duration 2] [--json]` | Sample `ghostlan_sink.monitor` via `ffmpeg volumedetect` to measure dB levels and detect silence. |
---
## MCP Server (For AI Agents)
`ghostlan` includes a built-in Model Context Protocol (MCP) server exposing all operations as structured tools.
### Stdio Transport (Default — Auto-Started by Any MCP Client)
Add to your MCP client config (Claude Desktop, Claude Code, Cursor, Antigravity, Zed, etc.):
```json
{
"mcpServers": {
"ghostlan": {
"command": "/home/saif/ghostlan/ghostlan",
"args": ["mcp"]
}
}
}
```
### Streamable HTTP Transport (Optional)
```bash
./ghostlan mcp --http 127.0.0.1:8999
```
*(Always bind to `127.0.0.1`, never `0.0.0.0`, since `ghostlan` holds network capabilities.)*
### Available MCP Tools (24)
- **Diagnostics & LAN:** `ghostlan_doctor`, `ghostlan_ls`, `ghostlan_up`, `ghostlan_status`, `ghostlan_down`
- **Processes:** `ghostlan_exec`, `ghostlan_start`, `ghostlan_stop`, `ghostlan_logs`, `ghostlan_wait_log`
- **Network & Capture:** `ghostlan_netem_set`, `ghostlan_netem_clear`, `ghostlan_link`, `ghostlan_capture`, `ghostlan_capture_inspect`
- **GUI & Media:** `ghostlan_gui_windows`, `ghostlan_gui_wait_window`, `ghostlan_gui_screenshot` *(returns native PNG `ImageContent` + path, optional `out_path`)*, `ghostlan_gui_click`, `ghostlan_gui_type`, `ghostlan_gui_key`, `ghostlan_gui_record`, `ghostlan_gui_motion`, `ghostlan_audio_check`
---
## Limitations, Quirks & Workarounds (For Agents)
**Always run `ghostlan_doctor` (or `ghostlan doctor`) first** on a new machine or whenever something fails—it immediately reports whether capabilities (`setcap`), `Xvfb`/`xauth`/`xdotool`/`import`, `openbox`, or `pipewire`/`pactl` are installed and ready.
- **No virtual webcam (`/dev/video*`):** `--gui` provides an isolated X11 display (`Xvfb`) and `--audio-null` provides isolated PipeWire virtual audio sinks (`ghostlan_sink`, `ghostlan_mic`), **not** a V4L2 camera device. For synthetic video, use OBS `color_source`/`xshm_input` or `ffmpeg -f lavfi -i testsrc`.
- **Window Manager in `--gui`:** If `openbox` or `fluxbox` is installed, `ghostlan` auto-starts it inside each ghost's `Xvfb`. If neither is installed, `_NET_ACTIVE_WINDOW` is unavailable and `ghostlan` falls back to `xdotool windowfocus`; if `Escape`/dialog shortcuts don't work on a popup, take a screenshot and click the dialog button directly.
- **No `wait_ms` on `start`/`exec`:** Use `ghostlan_wait_log` (or `ghostlan wait-log`) and `ghostlan_gui_wait_window` instead of fixed `sleep` calls.
- **Raw socket tools (`tcpdump` inside ghost):** Child processes run with `PR_SET_NO_NEW_PRIVS` as your unprivileged user, so `tcpdump` won't capture *inside* a ghost. Use `ghostlan capture start` + `ghostlan capture inspect` (or `ghostlan_capture` / `ghostlan_capture_inspect` in MCP) to capture on the host-side `veth` and decode `.pcap` files instead. Unprivileged ICMP `ping` **does** work inside ghosts.
- **`netem` units & direction:** `--delay` and `--jitter` take integer milliseconds (e.g. `--delay 50`, not `50ms`), and `netem` applies to **egress** on that ghost's `eth0`.
### If Something Fails — What to Check First
| Symptom / Error | What to Check First |
|---|---|
| `insufficient privileges` / `Operation not permitted` | Run `ghostlan_doctor`; if `capabilities` is missing, user must run `ghostlan setup` once. |
| `Xvfb` / `xauth` / `xdotool` / `import` not found | Run `ghostlan_doctor` (`gui_ready`) and ask user to install the missing base X11 packages. |
| Popup/dialog ignores `key` or `_NET_ACTIVE_WINDOW` | Check `wm_ready` in `ghostlan_doctor`; take a screenshot (`ghostlan_gui_screenshot`) and click the button directly. |
| App ignores config written to `<home_dir>/.config/...` | `ghostlan` sets `XDG_CONFIG_HOME=<home_dir>/config` (`xdg_config_home` in `up`/`status`); write there instead of `.config`. |
| `could not determine default IPv4 uplink interface` (`--nat`) | Pass explicit `--uplink <iface>` or check host default IPv4 route. |
| `already exists` / leftover bridge or netns after a crash | Run `ghostlan clean` (CLI) or `ghostlan_down`. |
---
## FAQ
**1. Why `setcap` instead of `sudo`?**
So AI agents and scripts can run `ghostlan` without password prompts, while apps launched inside ghosts still run as your normal unprivileged user (`$UID`)—not `root`.
**2. Do `--gui` windows appear on my real desktop?**
No. Each ghost gets its own headless `Xvfb` display (`:99`, `:100`, …) with `WAYLAND_DISPLAY` unset and X11 backends forced (`QT_QPA_PLATFORM=xcb`, `GDK_BACKEND=x11`, `SDL_VIDEODRIVER=x11`). Your real mouse, keyboard, and desktop are never touched. Use `ghostlan gui screenshot` (or `ghostlan_gui_screenshot` in MCP) to inspect the screen.
**3. Does `--gui` work if my Linux desktop uses Wayland?**
Yes. `Xvfb` is a standalone virtual X11 server, so `xdotool` and `import` work identically whether your host runs Wayland, X11, or a headless SSH session.
**4. Can multiple virtual LANs run at the same time?**
Yes. Each named LAN gets its own bridge (`glbr-<hash>`), unique `veth` names, non-overlapping `/24` subnet (`10.99.<n>.0/24`), and isolated `/tmp/ghostlan/<lan>/` state directory.
**5. How does `--nat` work?**
`--nat` detects your default IPv4 uplink (or uses `--uplink <iface>`), configures a dedicated `ghostlan_<lan>` `nftables` masquerade/forward table, adds a default route inside each ghost, and bind-mounts a per-netns `/etc/resolv.conf` (`1.1.1.1`, `8.8.8.8`) when processes run.
**6. Where do apps store configs inside a ghost?**
Each ghost isolates `HOME`, `XDG_CONFIG_HOME` (`<home_dir>/config`), `XDG_DATA_HOME` (`<home_dir>/data`), and `TMPDIR` (`<home_dir>/tmp`). Check `xdg_config_home` in `ghostlan_up` / `ghostlan_status` rather than writing to `<home_dir>/.config`.
**7. Storage location choices (Default vs `--private` vs `--dir`):**
- **Default (`/tmp/ghostlan/<lan>`):** Fast `tmpfs` (RAM-backed) with maximum temp space—best for normal single-user dev testing.
- **`--private` (`$XDG_RUNTIME_DIR/ghostlan/<lan>`, `0700`):** Also `tmpfs` (RAM-backed), locked to your user (`0700`)—best on shared/multi-user hosts or when handling sensitive tokens/configs.
- **`--dir <path>`:** Stores ghost directories under a custom path (e.g., SSD/disk)—best if a test writes multi-GB recordings or artifacts that won't fit in `tmpfs`.
- **Note for AI Agents / LLMs:** Before calling `ghostlan_up` for a new test environment, ask the user which storage mode they prefer if they haven't specified one (default `/tmp` for normal speed/space, `--private` for strict isolation, or `--dir <path>` for large files).
---
## License
Dual-licensed under either of:
- **MIT License** ([LICENSE-MIT](LICENSE-MIT))
- **Apache License, Version 2.0** ([LICENSE-APACHE](LICENSE-APACHE))
at your option.
TDQS
Scored across 24 tools
Each tool has a distinct resource and action: LAN lifecycle, process control, GUI input, GUI observation, audio, packet capture, and network impairment are cleanly separated. Adjacent tools like screenshot/record/motion and logs/wait_log are distinguishable by their descriptions and intended use.
All tools use the ghostlan_ prefix and snake_case, which is readable, but the suffixes mix bare verbs, nouns, abbreviations, and compound action names. There is no uniform verb_noun convention across the set.
24 tools is heavy for an MCP server, though the broad domain of virtual LANs, GUI automation, process control, and packet capture supports substantial surface area. Some niche tools could be consolidated, but most earn their place.
The set covers LAN lifecycle, process execution, GUI interaction, network impairment, capture inspection, audio checks, and diagnostics with few dead ends. Minor gaps exist around individual ghost management, file transfer, and richer GUI gestures.