diff --git a/AGENTS.md b/AGENTS.md index d7b390bb..5bcd75d2 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -7,7 +7,7 @@ devvm: one isolated VM per project folder, cloned from a base image, with toolch | Path | What | | --- | --- | | `cmd/devvm/` | the entry point: `ui.Main` makes the run's UI and runs the root command with it; the only `os.Exit` | -| `internal/cli/` | Cobra commands, one file each (root = up, `build`/`rebuild`, `images`, `gc`, `layer`, `setup`, `restart`, `update`, `remove`, `adopt`, `rm`, `ls`, `log`, `doctor`, `secret`, `auth`, `ssh-agent`, `ssh`, `code`, `limactl`, `ports`, `size`, `git-protect`, `completion`, hidden `version`, `_msg`, `_qemu`, `_proxy`, `_refresh-tools`); `script_test.go` runs testscript; `docgen/` writes the CLI reference | +| `internal/cli/` | Cobra commands, one file each (root = up, `build`/`rebuild`, `images`, `gc`, `layer`, `setup`, `restart`, `update`, `remove`, `adopt`, `rm`, `ls`, `log`, `doctor`, `secret`, `auth`, `ssh-agent`, `ssh`, `code`, `limactl`, `ports`, `size`, `git-protect`, `completion`, hidden `version`, `_msg`, `_qemu`, `_proxy`, `_smolvm-ports`, `_refresh-tools`); `script_test.go` runs testscript; `docgen/` writes the CLI reference | | `internal/vm/` | `Env` (`env.go`: shared dependencies, finding and starting the folder's VM); `Launch`: a new VM (`up.go`), an existing one (`existing.go`), `ssh.go`, agents' mounts; `Lifecycle` (`lifecycle.go`); `Settings` (`settings.go`, `size.go`, `ports.go`, `sshagent.go`); `Net` (`network.go`, `secret.go`); `--clone` (`clone.go`); the setup it sends (`sync.go`) | | `internal/project/`, `internal/gitprotect/` | a project folder (VM name, unsafe folders, detection, set-id files); `.git` protection | | `internal/sshconfig/`, `internal/sshagent/` | the ssh config for running VMs by name, their pinned host keys, the `~/.ssh/config` Include line; each VM's SSH agent choice, devvm's own agent and its keys | @@ -112,7 +112,7 @@ Still to come: smolvm's emulations, the docker backend; the release keys (`packa - **Linux's `pgrep -f` matches the shell running it** (procps), so e2e's patterns are written `[_]proxy`. mise skips minisign on linux/arm64 (no build). - **smolvm runs an image as a container in an Alpine microVM:** no init system, `exec` enters the container as root with only `HOME` set (no `USER`, no `/etc/environment`), `/dev` has no loop nodes (`mknod`), its EROFS mounts only uncompressed images, Docker needs `-v /var/lib/docker` and installs `systemctl` (tell systemd by `/run/systemd/system`). virtiofs shows host files as the host's uid, so the VM's user has it. - **smolvm packs carry their build VM's network, CPUs and memory;** `--block-private` can't be removed. `update --storage` breaks a registry-image machine, and a pack machine whose pack (stub and `.smolmachine`) is gone. `--state-dir` is Linux only: run it with `SMOLVM_USAGE=0`. On macOS it shares the user's machines (kept under `HOME`: a devvm run with another `HOME` sees others): touch only those with devvm's label. -- **smolvm's network:** allow lists are per address (the gateway `100.96.0.1` is every host loopback port), DNS answers any name under them, forwarded ports reach only servers on `0.0.0.0`, at most 64 per machine (one is devvm's sshd's). +- **smolvm's network:** allow lists are per address (the gateway `100.96.0.1` is every host loopback port), DNS answers any name under them, forwarded ports reach only servers on `0.0.0.0`, at most 64 per machine (one is devvm's sshd's), and take a host port another program has on `*` (`SO_REUSEADDR`, as Go's `net.Listen`: devvm's forwarder uses `platform.ListenExclusive`). - **smolvm base's packages before `assets/layers/base.sh`** come from Ubuntu's live archive, then base.sh pins a snapshot: anything pulling systemd libraries (openssh-server) goes after base's scripts (`sshd.sh`), or Docker's packages can't be installed. Under mediated egress a refused connection still opens in the guest, then resets (test with data, not a connect); TCP and UDP to any port 53 go to its resolver; `--dns` is create-only; a machine once started mediated won't start without a decider until `--no-egress-interceptor`. - **Lima writes `lima.REJECTED.yaml` into the current folder** on an invalid config: run `limactl` outside the repo (devvm runs it from its data folder). diff --git a/assets/smolvm/ports.sh b/assets/smolvm/ports.sh new file mode 100644 index 00000000..fa27b5d3 --- /dev/null +++ b/assets/smolvm/ports.sh @@ -0,0 +1,17 @@ +#!/bin/sh +# Run as the VM's user by its port forwarder on the host (devvm _smolvm-ports), over devvm's ssh, +# for forwarding every port: the TCP sockets listening in the VM, as /proc/net/tcp and tcp6 have +# their local addresses (ADDRESS:PORT, in hex), one per line, each list ended by a line ".". A list +# goes out when it changes, and every 10 s all the same, so the script ends soon after the +# connection does. The forwarder decides what it forwards: this only reports. +set -u +last=x n=0 +while :; do + now=$(cat /proc/net/tcp /proc/net/tcp6 2>/dev/null | awk '$4 == "0A" { print $2 }' | sort -u) + if [ "$now" != "$last" ] || [ "$n" -ge 10 ]; then + printf '%s\n.\n' "$now" || exit 0 + last=$now n=0 + fi + n=$((n + 1)) + sleep 1 +done diff --git a/assets/smolvm/services.sh b/assets/smolvm/services.sh index ca340e20..6b44e4e8 100644 --- a/assets/smolvm/services.sh +++ b/assets/smolvm/services.sh @@ -8,7 +8,7 @@ # ssh: devvm's sshd for ssh and editors, on a config of its own: new host keys (ed25519) at each # start, so no two VMs made from one image share them; USER alone may log in, with KEY (the VM's # own, an authorized_keys line) alone; local forwarding only, no remote forwarding, tunnels or X11 -# (a defence for an honest VM: root here can change it); its sessions get /etc/environment and each +# (a defence for an honest VM: root here can change it), to IPv4 or IPv6; its sessions get /etc/environment and each # VAR from this script's environment (the proxy's under network policy), as devvm's own commands # do. The config holds them, so it's root's alone. devvm asks for it only once it found sshd there. set -eu @@ -58,8 +58,9 @@ if [ "${1:-}" = ssh ]; then umask 077 { echo "# devvm's sshd for ssh and editors, written at each start (services.sh)." + # IPv4 alone to listen on; both to connect to, so forwarding every port reaches servers on ::1. echo "ListenAddress 0.0.0.0:22" - echo "AddressFamily inet" + echo "AddressFamily any" echo "HostKey /etc/ssh/ssh_host_ed25519_key" echo "PidFile /run/devvm-sshd.pid" echo "AllowUsers $user" diff --git a/docs/content/docs/backends.md b/docs/content/docs/backends.md index b822da51..63894734 100644 --- a/docs/content/docs/backends.md +++ b/docs/content/docs/backends.md @@ -17,7 +17,7 @@ Each backend declares how it has each feature: `devvm doctor` lists them for every backend devvm has, an emulation whose review hasn't passed as `unreviewed`. -The smolvm column is tested with smolvm 1.32.2 on an arm64 Mac; Linux hosts are untested. Network policy and ssh for editors are emulated and reviewed; its other emulations are planned. Until each is reviewed, devvm refuses it. +The smolvm column is tested with smolvm 1.32.2 on an arm64 Mac; Linux hosts are untested. Network policy, ssh for editors and every port forwarded are emulated and reviewed; its other emulation is planned. Until each is reviewed, devvm refuses it. | Feature | What it is | Lima | smolvm (experimental) | Docker (planned) | | --- | --- | --- | --- | --- | @@ -31,7 +31,7 @@ The smolvm column is tested with smolvm 1.32.2 on an arm64 Mac; Linux hosts are | `egress-proxy` | network traffic only through devvm's proxy | native: Seatbelt (macOS), QEMU `restrict=on` and a `guestfwd` to the proxy (Linux) ([details](lima.md#confinement)) | emulated (reviewed): an allow list of the host, DNS closed but for one name, and devvm's proxy deciding each connection ([details](smolvm.md#network-policy)) | emulated | | `ssh` | ssh for editors | native: Lima's ssh forward and config | emulated (reviewed): an sshd of devvm's, started after each start with new host keys and the VM's own key alone, and entries that ask for no forwarding out, on a port forwarded from the host's loopback ([details](smolvm.md#ssh-for-editors)) | emulated | | `ports` | the listed ports forwarded to the host's loopback | native: port forward rules ([details](lima.md#ports)) | native for servers listening on all addresses, at most 63 ports, as one of smolvm's 64 is ssh's ([details](smolvm.md#what-devvm-sets-on-a-vm)) | native (recreating the container) | -| `ports-all` | every port forwarded, servers on the VM's loopback included | native | none; planned emulation | emulated | +| `ports-all` | every port forwarded, servers on the VM's loopback included | native | emulated (reviewed): a forwarder of devvm's on the host, over the VM's ssh, for what listens in the VM from port 1024 up, never a port the host has ([details](smolvm.md#every-port)) | emulated | | `agent-forwarding` | ssh-agent forwarding, chosen when the VM is made | native | native | native | | `agent-toggle` | turning a VM's ssh-agent forwarding on or off later | native | none; planned emulation | native | | `cpus` | a VM's CPUs | native | native | native | diff --git a/docs/content/docs/design.md b/docs/content/docs/design.md index cfa3b83d..fa6e5485 100644 --- a/docs/content/docs/design.md +++ b/docs/content/docs/design.md @@ -51,7 +51,7 @@ A backend feature devvm builds from other parts of the backend ([emulated](backe - **sshd in base:** `sshd.sh`, as root after base's scripts, installs `openssh-server` from the archive they left (Ubuntu's snapshot: from the live archive, before them, its systemd libraries were newer than the snapshot's Docker packages could match) and deletes the host keys its package made; `prepare.sh` sets the user's password to `*` (none matches; sshd without PAM refuses a locked `!` account's keys too). Both are in base's key. - **Only when asked for:** the caller sets `Confinement.SSH` at each start of a project VM when `Require` lets `ssh` through (always, now it's reviewed); builds never ask. Without it the start removes the forward and runs no sshd, `SSH` answers `smolvm_no_ssh`, and the ssh config skips any backend whose `ssh` isn't usable (`Review.Allowed`). - **The forward:** `machine update -p PORT:22` while the machine is stopped. `PORT` is `Confinement.SSHPort` (network policy's `ssh_port`), else the one it had while it's free on `127.0.0.1` and `::1`, else a new one, never one of the VM's own forwards: network policy's `ssh_port` avoids every VM's forwards and is picked again when it's one of the VM's, and the backend refuses one that is anyway (`smolvm_ssh_port_forwarded`). smolvm binds it on the host's loopback alone, and forwards reach only servers on all addresses, so sshd listens on `0.0.0.0:22` (IPv4). smolvm forwards at most 64 ports per machine, so a VM's own are at most 63, and port 22 is refused (`smolvm_port_ssh`). -- **sshd, after each start** (`services.sh`, as root): every host key deleted and a new ed25519 one made, so no two VMs from one pack share one, nor a VM's starts; devvm's public key as the only authorized key (`/etc/devvm/ssh/authorized_keys`, root's); a config of devvm's own (`/etc/devvm/ssh/sshd_config`, mode 600, `sshd -f`, checked with `sshd -t` first), whatever the image's says: `AllowUsers` the VM's user, `PermitRootLogin no`, `AuthenticationMethods publickey`, passwords and keyboard-interactive off, `AllowTcpForwarding local`, `AllowStreamLocalForwarding local`, `PermitListen none`, `GatewayPorts no`, `X11Forwarding no`, `PermitTunnel no`, `PermitUserEnvironment no`, `AllowAgentForwarding yes`. A failure stops the VM, but an image without sshd (made before devvm installed one; asked first, with a probe of its own, so no other failure reads as it) starts without ssh, warned (`smolvm_no_sshd`; a VM made after `devvm rebuild` has it). The record says the start's sshd runs (`ssh_up`, cleared before each start, set once `services.sh` is done), and `SSH` answers only then: a devvm that runs meanwhile can't read, and pin, the host keys this start is about to replace. +- **sshd, after each start** (`services.sh`, as root): every host key deleted and a new ed25519 one made, so no two VMs from one pack share one, nor a VM's starts; devvm's public key as the only authorized key (`/etc/devvm/ssh/authorized_keys`, root's); a config of devvm's own (`/etc/devvm/ssh/sshd_config`, mode 600, `sshd -f`, checked with `sshd -t` first), whatever the image's says: `AllowUsers` the VM's user, `PermitRootLogin no`, `AuthenticationMethods publickey`, passwords and keyboard-interactive off, `AllowTcpForwarding local`, `AllowStreamLocalForwarding local`, `PermitListen none`, `GatewayPorts no`, `X11Forwarding no`, `PermitTunnel no`, `PermitUserEnvironment no`, `AllowAgentForwarding yes`; it listens on IPv4 alone (`ListenAddress 0.0.0.0:22`) and connects local forwards to IPv4 or IPv6 (`AddressFamily any`, for [every port](#every-port-on-smolvm)'s servers on `::1`). A failure stops the VM, but an image without sshd (made before devvm installed one; asked first, with a probe of its own, so no other failure reads as it) starts without ssh, warned (`smolvm_no_sshd`; a VM made after `devvm rebuild` has it). The record says the start's sshd runs (`ssh_up`, cleared before each start, set once `services.sh` is done), and `SSH` answers only then: a devvm that runs meanwhile can't read, and pin, the host keys this start is about to replace. - **The sessions' environment:** sshd on its own config runs without PAM, so `SetEnv` gives sessions `/etc/environment` (`BASH_ENV`) and the variables `Start` names (the proxy's, `NO_PROXY`, the CA files'), whose values `services.sh` reads from its own environment: the proxy file's (`--secret-file`) and the machine's, never in arguments. Login shells also read `/etc/profile.d`, as devvm's do. - **The VM's key:** ed25519, made in Go in OpenSSH's format at the VM's first start with ssh, `~/.local/share/devvm/smolvm/vms/.key` (mode 600, one file written whole; its public half is read back from it, never kept apart), deleted with the VM. Its public half, passed to `services.sh`, is that VM's only authorized key: one VM's key logs in to no other. `SSH` returns `127.0.0.1`, the port, the user, and `IdentityFile` with `IdentitiesOnly yes` and `PreferredAuthentications publickey`: the user's agent keys aren't offered to the VM. - **Pinning** is the shared code's, as on Lima: a VM's keys are forgotten before each start and read after it with `cat /etc/ssh/ssh_host_*_key.pub` through `Exec` (smolvm's `machine exec`, which reaches the VM itself, not over the network), and entries check them (`HostKeyAlias`, `StrictHostKeyChecking yes`). @@ -89,9 +89,49 @@ These settings guard against the host's ssh asking for a forward that devvm's en - `--clone`: the clone pushed in over ssh, every branch, nothing of the folder mounted; fetching the VM's commit and pushing a branch through devvm's ssh config; `rm -f` keeping the fetched work; - with network policy: ssh on the VM's `ssh_port`, sessions (a login's or not) with the proxy's settings, an allowed host through the proxy; a local forward to `1.1.1.1:80` or a service on the host's loopback gets nothing back, remote forwarding is refused, a direct connection from a session fails; after `devvm network off`, the same local forward gets an answer (the control); network policy's DNS no-leak check runs with the forward (DNS detection above). +### Every port on smolvm + +**The guarantee:** as on Lima, a VM that forwards every port has each TCP port a server in it listens on, on its loopback or all its addresses, forwarded to the same port on the host's loopback, and only its loopback; and, beyond Lima, never a port a program on the host has on any address when the forward is made, nor one devvm records for a VM. Forwarding gives the VM no way out it doesn't already have (with network policy, nothing past its proxy): every connection starts on the host. Reviewed: the threat check's findings are fixed or listed below (the host key read capped, reports paced, the log limited), and the end-to-end checks prove the rest. Before that, devvm refused it, and a test build's `DEVVM_UNREVIEWED` let the end-to-end checks through ([testing](testing.md#unreviewed-emulations)). + +**What it's built from:** + +- **None of smolvm's forwards:** a VM forwarding every port is made (or set, while stopped) with no `-p` but its ssh's. smolvm's would need each port at create or update, while the machine is stopped, at most 64 of them, and reach only servers on all addresses. +- **Only when allowed:** the caller requires `ports` and `ports-all` when the VM is made or its ports set (`Review.Require`, warned when let through), and again at each start (`Review.Allowed`, else the refusal): a VM made while it was let through doesn't start once it isn't (it always is, now it's reviewed). The backend then runs a forwarder at each start of a VM whose record says every port (`ports_all`). +- **A forwarder per VM, on the host:** `devvm _smolvm-ports`, started detached by `Start` once `services.sh` ran the VM's sshd ([ssh](#ssh-for-editors-on-smolvm)), after stopping any it had (a pid file, checked against the process's arguments, as the proxy's is). `Start` waits up to 10 s for it to say it forwards; one that doesn't is warned about (`smolvm_ports_failed`, its log named) and left to keep trying, and the VM runs on. A VM without ssh forwards nothing, warned (`smolvm_ports_no_ssh`). It ends when the machine's process does (its lifeline, `agent.pid`, the proxy's too: its process gone, or its contents changed by a new start), and `stop` and `Delete` stop it first. +- **Reaching the VM:** one ssh connection, a master (`ssh -F none -M -S `), to the VM's sshd's host loopback port, as the VM's user with the VM's own key alone (`IdentitiesOnly`, `IdentityAgent=none`), its host key read through smolvm (`machine exec … cat /etc/ssh/ssh_host_ed25519_key.pub`, as root, at the start; at most 64 KiB of it, for 30 s, as the VM decides what it prints) into a known_hosts file of the forwarder's own and pinned (`HostKeyAlias`, `StrictHostKeyChecking yes`); no configuration of the user's, and nothing forwarded either way (`ClearAllForwardings`, `PermitRemoteOpen none`, no agent, X11 or tunnel, `ProxyCommand none`). Its control socket is in `~/.local/share/devvm/run` (mode 700), named by a hash of the VM's name, as a socket's path is at most 104 characters. A lost connection is made again every 2 s while the lifeline holds, its forwards closed meanwhile. +- **What listens:** the master's session runs `ports.sh` (`sh -s`, as the VM's user), which prints the local addresses of the VM's listening TCP sockets (`/proc/net/tcp` and `tcp6`, state `0A`) whenever they change, and every 10 s regardless, so it ends soon after the connection does. The forwarder reads it as untrusted: lines over 128 bytes or a report over 4096 lines end the connection, anything that isn't a hex address and port is skipped, and reports are applied 500 ms apart at least (one that comes sooner waits, and the VM's ssh channel with it), so a VM can't make it bind, dial and read devvm's state at its own pace. Its log, which the VM can make it write to (ports coming and going, the session's stderr), takes 200 writes at once and then one every 10 s, each at most 512 bytes, control characters shown as `?`; a start empties it once it's over 1 MiB. A port's connections go to `127.0.0.1` for a server on all IPv4 addresses or that one, `::1` for one on all IPv6 addresses or that one, another `127.x` address for one there alone; servers on other addresses alone aren't forwarded. +- **Which ports:** from 1024 up (below, the host's system services), at most 256 at once, never one that's reserved: the VM's own ssh, proxy and decider ports, and every VM's ssh, proxy and decider ports and listed forwards as their state records them (`netpolicy.UsedPorts`, read again each time a port would be taken; while it can't be read, no new port is). A smolvm VM without network policy keeps its ssh port in its smolvm record alone: smolvm holds it while that VM runs; while it's stopped, another VM's forwarder can take it, and its next start forwards another (its pinned host key refuses any other server). A port it couldn't take is tried again only once the VM's server goes and comes back. +- **Listening:** on `127.0.0.1` and `::1` (IPv4 alone on a host without IPv6), without `SO_REUSEADDR` (`platform.ListenExclusive`): with it, as Go and smolvm bind, macOS lets `127.0.0.1:PORT` be taken while a program has `*:PORT`, and with it that program's loopback connections. Without it, a port another program has on any address is refused. Checked on macOS for a program on `0.0.0.0`, on `::` (IPv4 and IPv6 at once, as Node's and Go's servers listen) or IPv6 alone, and on `127.0.0.1`, with or without `SO_REUSEADDR` of its own. A port held only by ended connections (`TIME_WAIT`, nothing answering on it) is taken as usual, so a server that restarts gets its forward back: one whose bind is refused is dialed, and taken only when that's refused (a full backlog times out, and counts as taken). A port taken on `127.0.0.1` but in use on `::1` is given up, so `localhost` never reaches two programs. +- **Each connection:** a channel of the master's (`ssh -S -W HOST:PORT`, one process per connection, at most 256 at once), which the VM's sshd opens to the VM's own loopback, from inside the VM; so sshd connects to IPv4 or IPv6 (`AddressFamily any`), still listening on IPv4 alone. It has the master's options: without the master (ssh then connects on its own, unasked), it reaches the VM's sshd the same way, never the host's. + +**What keeps a forward from carrying the VM out.** Every connection starts on the host: a program connects to the forwarder's port, and the forwarder asks the VM's sshd to connect to the VM's loopback. The VM opens nothing to the host through it: the master asks for no remote forward, agent, X11 or tunnel, and OpenSSH's client refuses a channel the server opens unasked, whatever sshd root in the VM runs. What the VM sends back goes to the program that connected, as with any forward on Lima. The VM's own connections, sshd's to its loopback included, are its own network's, which network policy confines as before; the forwarder never takes its proxy's or decider's port, so with the proxy gone, a server in the VM can't become the decider smolvm asks (nor another VM's, while that one's is down). + +**What it relies on:** the VM's sshd and the pinned host key (the [ssh](#ssh-for-editors-on-smolvm) emulation's); OpenSSH's client refusing unrequested channels and honoring `-F none`; smolvm binding the ssh forward on the host's loopback alone; the kernel refusing a bind without `SO_REUSEADDR` where another socket has the port (checked on macOS); devvm's state listing every VM's ports. + +**What could break it:** a smolvm release that binds the ssh forward beyond the loopback (still key-only); devvm's state lost or unreadable for a VM whose proxy port is then free (no new port is forwarded while it can't be read). + +**Not covered:** + +- A VM can take a free port on the host's loopback that a program there expects to be its own, from 1024 up (one that isn't running yet, or restarts), as on Lima, and what it serves reaches whatever connects: a page it serves to the user's browser can reach the internet from the host, past network policy. +- A host program that starts on a port while the VM has it forwarded binds it anyway when it listens on all addresses with `SO_REUSEADDR`, as most servers do (checked on macOS), and its loopback connections reach the VM, the forward's address being the narrower one; as with Lima's forwards. Without `SO_REUSEADDR` its bind is refused. +- The VM can make the forwarder dial a host loopback port that's in use, and close the connection at once, sending nothing: its check for a port held only by ended connections. At most once per port every second, as the VM's listener on it goes and comes back. +- Servers on the VM's other addresses alone (its network address, a container's) aren't forwarded. +- Other users on the host reach the forwards (the host's loopback), as on Lima. +- UDP isn't forwarded, as on Lima's default. +- A server that keeps a port while its forward couldn't be made (the host had it) isn't forwarded until it stops and starts again. +- Linux hosts are untested. + +**End-to-end checks** (`tests/e2e.sh --backend smolvm`): + +- the machine's process listens on its ssh forward alone; the forwarder's ssh master reads no config, offers the VM's key alone with its host key pinned, and asks for no forwarding; +- servers on the VM's `127.0.0.1`, `::1`, all IPv4 addresses and all addresses each answer at the host's `127.0.0.1` and `::1`, and the forwarder listens on the host's loopback alone; +- a port a host program has on every address stays the host program's (the VM's server on it isn't forwarded), and a port below 1024 isn't forwarded; so does one on the host's `127.0.0.1` alone, on its `::1` alone (`localhost` never reaches two programs), and on `::`, IPv4 and IPv6 at once; a server on the VM's own network address alone isn't forwarded, nor a port another VM's state lists while it's free (a loopback server is, the control); a server that stops loses its forward, the others stay; +- `devvm stop` stops the forwarder and closes its ports; a new start has a new one, which forwards a server started then; `rm` deletes it and its files; +- with network policy: the self-check passes and a server's port is forwarded; direct connections still fail, even as root, while it forwards; with the proxy and decider gone and the VM listening on their ports, neither is forwarded (a port of its own is, the control), and the next devvm starts the proxy on them again. + ## smolvm -Tried with smolvm 1.32.2 on an arm64 Mac before devvm had the backend ([its column](backends.md#features), [its page](smolvm.md)). The backend has its native features, network policy, emulated ([above](#network-policy-on-smolvm)), and ssh for editors, emulated ([above](#ssh-for-editors-on-smolvm)), both reviewed; the other emulations are to come, each refused until reviewed. +Tried with smolvm 1.32.2 on an arm64 Mac before devvm had the backend ([its column](backends.md#features), [its page](smolvm.md)). The backend has its native features, network policy, emulated ([above](#network-policy-on-smolvm)), ssh for editors, emulated ([above](#ssh-for-editors-on-smolvm)), and every port forwarded, emulated ([above](#every-port-on-smolvm)), all reviewed; agent toggling is to come, refused until it's reviewed. **Network policy.** smolvm's allow lists work per address, not per port, and DNS has its own path: @@ -107,7 +147,8 @@ Tried with smolvm 1.32.2 on an arm64 Mac before devvm had the backend ([its colu - **Ubuntu's container image, not its cloud image:** before the scripts, base gets `ca-certificates`, `sudo`, `bash` and the VM's user (`prepare.sh`). The user has the host's name and uid, as on Lima: virtiofs shows the project folder as the host's uid, so `ubuntu` (uid 1000) couldn't write it; a user with that uid is removed first. `Built.Origin` is the image by its digest. The backend's own scripts that go into base are in its key (`KeyFiles`). - **Network at create:** packs carry the build machine's network, CPUs and memory, and `--block-private` can't be removed from them, so builds use smolvm's default network and `CreateVM` sets everything. The network changes on a stopped VM (`machine update`), so `Start` sets it where it differs. For network policy, the decider's address and token come with `Confinement` (a backend with a decider implements `backend.Decider`), and the proxy is at the gateway. - **ssh-agent forwarding is chosen at create:** `machine update` can't change it, so turning it on or off later is a feature of its own (`agent-toggle`). The agent socket is read at each start. -- **Every port** isn't what smolvm forwards (at most 64, one of them ssh's, servers on all addresses), so `ports-all` is a feature of its own, which new VMs ask for by default. +- **Every port** isn't what smolvm forwards (at most 64, one of them ssh's, servers on all addresses, set only while a machine is stopped), so `ports-all` is a feature of its own, which new VMs ask for by default, emulated by a forwarder of devvm's ([above](#every-port-on-smolvm)). +- **smolvm's forwards share a port:** a listed port's forward takes `127.0.0.1:PORT` and `[::1]:PORT` while a program on the host has `*:PORT`, and that program's connections to them with it (checked on macOS), as a Go listener does (`SO_REUSEADDR`). devvm's forwarder of every port binds without it. - **Lifeline:** smolvm's `agent.pid` has a second line, the start time, so the proxy reads only the first. - **Ports** are set on a stopped VM, so `Confinement.SSHPort` is a forward set before the start, and `Confinement.SSH` says whether to run ssh at all: an emulation runs only once it's let through. - **State:** `--state-dir` is Linux only, so on macOS devvm's machines share the user's smolvm, told apart by a label naming devvm's data folder; devvm acts only on machines with it. smolvm keeps a local usage journal; devvm turns it off (`SMOLVM_USAGE=0`). diff --git a/docs/content/docs/limits.md b/docs/content/docs/limits.md index 1093f68d..a2262dab 100644 --- a/docs/content/docs/limits.md +++ b/docs/content/docs/limits.md @@ -9,4 +9,4 @@ weight: 33 - **Linux hosts** have no `.git` protection: use `--clone` ([details](git-protection.md#linux-hosts)). - **Agent folders** made or deleted on this machine reach a running VM only after a restart; devvm offers one ([details](coding-agents.md#mounts)). - **With Lima:** project paths can't contain commas, folder names in VM names are cut short, disks grow but never shrink ([details](lima.md#limits)). -- **smolvm is experimental:** network policy is emulated, with one narrow DNS channel ([details](smolvm.md#network-policy)); ssh for editors is emulated ([details](smolvm.md#ssh-for-editors)); no every port forwarded, or SSH agent forwarding changed once a VM is made; at most 63 ports; project paths can't contain colons ([details](smolvm.md)). +- **smolvm is experimental:** network policy is emulated, with one narrow DNS channel ([details](smolvm.md#network-policy)); ssh for editors is emulated ([details](smolvm.md#ssh-for-editors)); every port forwarded is emulated, from port 1024 up ([details](smolvm.md#every-port)); no SSH agent forwarding changed once a VM is made; at most 63 listed ports; project paths can't contain colons ([details](smolvm.md)). diff --git a/docs/content/docs/security.md b/docs/content/docs/security.md index 484c10eb..4e988dcd 100644 --- a/docs/content/docs/security.md +++ b/docs/content/docs/security.md @@ -64,7 +64,7 @@ The proxy's CA (`~/.local/share/devvm/ca`) is how it reads traffic to the hosts - **What allowed hosts and tokens permit.** The VM can push with a GitHub token it may use, spend Claude quota, or upload to any host on its allowlist. Use fine-grained tokens and keep allowlists short. - **What a VM made with a token.** The proxy puts the token into any request to that service, so a VM can use it to make credentials of its own. The proxy refuses GitHub REST calls that add a key to your account, a deploy key, a self-hosted runner or a webhook (`403`), but not everything: GitHub's GraphQL API, an OAuth app grant, other services. If a VM may have done that, rotate the token and check the service's keys, tokens and runners. - **Which server an allowed name reaches, on connections the proxy doesn't read.** The proxy checks the name a VM's TLS connection asks for (its SNI), not the `Host` inside the encrypted traffic. A CDN that serves many sites on one address (domain fronting) can route such a connection to a site that isn't on the allowlist. Connections to hosts with a bound token are read, and a request in them that names another host is refused. -- **Ports the VM listens on**, which are forwarded to this machine's `localhost`: all of them, unless you list them with [`--ports`](commands.md#size-and-ports). A VM could take a port a program on the host trusts. +- **Ports the VM listens on**, which are forwarded to this machine's `localhost`: all of them, unless you list them with [`--ports`](commands.md#size-and-ports). A VM could take a port a program on the host trusts while it's free, and what it serves there reaches whatever connects: a page it serves to your browser can reach the internet from your machine, past network policy. On smolvm, devvm's forwarder of every port ([emulated](smolvm.md#every-port)) never takes a port a program on your machine already has on any address, nor ports below 1024 or devvm's own. - **Remote forwards you ask for** into a VM (`RemoteForward` in your ssh config, `ssh -R`): the VM can connect through them to whatever they name on your machine. The VM's sshd refuses them only while root in the VM leaves it so ([ssh into VMs](#ssh-into-vms)). - **What VS Code relays** over Remote-SSH (`devvm code`): ports its programs in the VM listen on, and your GitHub sign-in for git's prompts. devvm turns both off in the VM's VS Code settings each time it sets the VM up, but the VM can turn them back on: set them in your own VS Code settings too ([VS Code](ssh.md#vs-code)). - **Set-id bits on Linux hosts.** Root in a VM can set the set-user-id and set-group-id bits on files in the project folder. On macOS they don't reach the host (virtiofs drops them). On Linux they do, and the files are yours, so a set-user-id one runs as you for anyone else on the machine who runs it. devvm names such files when it creates a VM for the folder (`chmod u-s,g-s FILE` clears them). Don't run programs from the project folder as another user. diff --git a/docs/content/docs/smolvm.md b/docs/content/docs/smolvm.md index 7673ddb8..96b0d9db 100644 --- a/docs/content/docs/smolvm.md +++ b/docs/content/docs/smolvm.md @@ -5,7 +5,7 @@ weight: 32 [smolvm](https://github.com/smol-machines/smolvm) is an experimental backend: each project gets a microVM that runs its image as a container, with no init system. Choose it per VM with `--backend smolvm`, or for every new VM with `devvm setup --backend smolvm`. -It lacks forwarding every port, and turning SSH agent forwarding on or off once a VM is made. [Network policy](#network-policy) and [ssh for editors](#ssh-for-editors) (`devvm ssh`, `devvm code`, `--clone`) are emulated, and reviewed. devvm refuses what it lacks in one line naming the VM ([features](backends.md#features)); those come later, as reviewed emulations. +It lacks turning SSH agent forwarding on or off once a VM is made. [Network policy](#network-policy), [ssh for editors](#ssh-for-editors) (`devvm ssh`, `devvm code`, `--clone`) and [forwarding every port](#every-port), the default for new VMs, are emulated, and reviewed. devvm refuses what it lacks in one line naming the VM ([features](backends.md#features)); that comes later, as a reviewed emulation. ## Requirements @@ -41,7 +41,7 @@ devvm's own scripts for this (`prepare.sh`, `shims.sh`, and `sshd.sh`, which ins - **Mounts:** the project folder (read-write) and agents' folders (read-only) at their host paths, the shared tools at `/mnt/devvm-tools` (read-only), and `/var/lib/docker` on the machine's own disk, which Docker's storage needs. A path with a colon is refused: smolvm splits mounts on colons. Files a VM makes in the project folder are yours on the host, mode 0600. - **Network:** smolvm's own, without network policy: the internet, not the host's loopback. With it, [below](#network-policy). - **Size:** what you ask for, or base's; the disk only grows. -- **Ports:** those you list (`--ports 5173,8000-8010`), each to the same port on the host's `127.0.0.1` and `::1`, at most 63 ports: smolvm forwards 64, and one is the VM's [ssh](#ssh-for-editors). Port 22 is that ssh's, so listing it is refused (`smolvm_port_ssh`). Only servers listening on all addresses (`0.0.0.0`) are reached. `all`, the default, is refused: pass `--ports` or set `devvm ports -g`. +- **Ports:** those you list (`--ports 5173,8000-8010`), each to the same port on the host's `127.0.0.1` and `::1`, at most 63 ports: smolvm forwards 64, and one is the VM's [ssh](#ssh-for-editors). Port 22 is that ssh's, so listing it is refused (`smolvm_port_ssh`). Only servers listening on all addresses (`0.0.0.0`) are reached. `all`, the default, is [emulated](#every-port). - **SSH agent forwarding:** chosen when the VM is made (`--ssh-agent`), and fixed then. At each start smolvm forwards the agent `SSH_AUTH_SOCK` names (devvm's own with `devvm ssh-agent devvm`); with none, the start stops (`smolvm_no_agent`). - **Environment:** the proxy's settings with network policy, as on Lima. The proxy variables come from the VM's proxy file, `~/.local/share/devvm/smolvm/vms/.proxy` (mode 600), which devvm writes at each start with network policy (and removes without): each of devvm's commands in the VM names it (`smolvm machine exec --secret-file`), and smolvm reads it, so the proxy's password is in no process's arguments. A `smolvm machine exec` of your own gets the variables only in a login shell. (`machine create --secret-file` would last, but smolvm ignores it for a VM made from a pack.) @@ -69,6 +69,15 @@ Emulated, and reviewed: `devvm ssh`, `devvm code`, `--clone` and the [ssh config A VM running since a start without ssh (from an older devvm) gets no entry, and `devvm ssh` says to restart it (`smolvm_no_ssh`). A VM whose image has no sshd (made before devvm installed one) starts and runs without ssh, warned (`smolvm_no_sshd`): a VM made after `devvm rebuild` has it. +## Every port + +Emulated, and reviewed ([design](design.md#every-port-on-smolvm)): a VM that forwards every port (`--ports all`, the default) gets none of smolvm's forwards, and a forwarder of devvm's on your machine instead, much as Lima forwards a VM's ports: + +- **What it forwards:** every TCP port from 1024 up that a server in the VM listens on, on the VM's loopback (`127.0.0.1`, `::1`) or all its addresses, to the same port on your machine's `127.0.0.1` and `::1`, within a few seconds of the server starting; the forward goes when the server does. At most 256 at once. +- **What it never takes:** a port a program on your machine has, on any address (that program keeps it, and its connections; the forward waits for the VM's server to stop and start again), and a port devvm records for any VM (its ssh, proxy and decider ports, and the ports VMs list), even while it's free. A program that starts on a port after it's forwarded can still bind it on all addresses, and then its `localhost` connections reach the VM, as on Lima. +- **How it reaches the VM:** over the VM's [ssh](#ssh-for-editors), with the VM's own key and its host key read through smolvm, asking for no forwarding into your machine: the VM learns of each connection only as one to its own loopback, and opens none to your machine. With network policy, the VM still reaches nothing but its proxy. +- **Its process** is `devvm _smolvm-ports`, one per VM, started after the VM's sshd and ended with it; `devvm stop` stops it. Its log is `~/.local/share/devvm/smolvm/vms/.ports.log`. A VM without ssh (an image without sshd) forwards no ports, warned (`smolvm_ports_no_ssh`); one whose forwarder doesn't start runs on, warned with its log (`smolvm_ports_failed`). + ## No init system A machine runs its image as a container, and nothing starts at boot. After each start devvm runs, as root: diff --git a/docs/content/docs/testing.md b/docs/content/docs/testing.md index 0c165394..bcff61eb 100644 --- a/docs/content/docs/testing.md +++ b/docs/content/docs/testing.md @@ -74,10 +74,10 @@ These need real x86_64 hardware. An emulated x86_64 VM on a Mac (`--arch=x86_64` devvm refuses an emulated feature until its review passes, yet the review needs end-to-end checks of it. In a test build, `DEVVM_UNREVIEWED` lets the ones it names through, as `backend:feature` pairs, comma-separated, each time with a warning (`backend_unreviewed_used`). A test build is one made with `-ldflags "-X github.com/w3cj/devvm/internal/backend/registry.unreviewed=allowed"`, as `tests/e2e.sh` and the CLI tests make theirs; releases (GoReleaser, the Homebrew formula) set only the version, so they ignore it: ```sh -DEVVM_UNREVIEWED=smolvm:ssh devvm --backend smolvm --ports none base +DEVVM_UNREVIEWED=smolvm:ports-all devvm --backend smolvm base ``` -It's for tests only, of an emulation before its review: none needs it now (smolvm's network policy and ssh for editors were checked this way, then reviewed). It never makes a feature a backend lacks usable, and `devvm doctor` still shows the feature `unreviewed`. +It's for tests only, of an emulation before its review: none needs it now (smolvm's network policy, ssh for editors and forwarding of every port were checked this way, then reviewed). It never makes a feature a backend lacks usable, and `devvm doctor` still shows the feature `unreviewed`. ## Manual checks diff --git a/internal/backend/smolvm/build.go b/internal/backend/smolvm/build.go index 1119de0a..e5eba174 100644 --- a/internal/backend/smolvm/build.go +++ b/internal/backend/smolvm/build.go @@ -447,7 +447,7 @@ func (s *Smolvm) CreateVM(ctx context.Context, img string, spec backend.VMSpec) } return s.writeRecord(vm, record{ Image: img, Project: spec.Project, AgentDirs: slices.Clone(spec.AgentDirs), Tools: spec.Tools, ToolsAt: spec.ToolsAt, - Forwarding: spec.AgentForwarding, Ports: ports, + Forwarding: spec.AgentForwarding, Ports: ports, PortsAll: spec.Ports.All, }) } diff --git a/internal/backend/smolvm/cli.go b/internal/backend/smolvm/cli.go index 6159f461..34f6d36b 100644 --- a/internal/backend/smolvm/cli.go +++ b/internal/backend/smolvm/cli.go @@ -186,8 +186,9 @@ func (s *Smolvm) update(ctx context.Context, vm string, opts ...string) error { return nil } -// stop stops a machine. +// stop stops a machine, and its port forwarder. func (s *Smolvm) stop(ctx context.Context, vm string) error { + s.Forwards.Stop(vm) if err := s.Runner.Run(ctx, msg.Stopping(vm), s.smolvm(ctx, "machine", "stop", "--name", vm)); err != nil { return backend.Logged(msg.StopFailed(vm)) } @@ -196,9 +197,13 @@ func (s *Smolvm) stop(ctx context.Context, vm string) error { // remove deletes a machine and what devvm keeps for it. func (s *Smolvm) remove(ctx context.Context, vm string) error { + s.Forwards.Stop(vm) if err := s.Runner.Run(ctx, msg.Deleting(vm), s.smolvm(ctx, "machine", "delete", "--name", vm, "-f")); err != nil { return backend.Logged(msg.DeleteFailed(vm)) } + if err := s.Forwards.Remove(vm); err != nil { + return err + } for _, f := range []string{s.Dirs.SmolvmVM(vm), s.proxyFile(vm), s.sshKey(vm)} { if err := os.Remove(f); err != nil && !errors.Is(err, os.ErrNotExist) { return err diff --git a/internal/backend/smolvm/forward.go b/internal/backend/smolvm/forward.go new file mode 100644 index 00000000..3071bbab --- /dev/null +++ b/internal/backend/smolvm/forward.go @@ -0,0 +1,593 @@ +package smolvm + +import ( + "bufio" + "bytes" + "context" + "encoding/hex" + "errors" + "flag" + "fmt" + "io" + "maps" + "net" + "net/netip" + "os" + "os/exec" + "slices" + "strconv" + "strings" + "sync" + "syscall" + "time" + + "github.com/w3cj/devvm/internal/platform" +) + +// Forwarding every port (ports-all) is emulated, and reviewed: +// smolvm forwards only the ports a machine was made or updated with, at +// most 64, and only to servers listening on all of the guest's addresses. +// So a VM that forwards every port gets none of smolvm's, and a forwarder +// of devvm's on the host instead (devvm _smolvm-ports, run detached by +// Start, one per VM): +// +// - it reaches the VM only through the VM's sshd (ssh.go), as the VM's +// user with its own key, the host key read through smolvm at the start +// and pinned: one ssh connection (a master), whose session runs +// ports.sh, which reports what listens in the VM; each forwarded +// connection is a channel of it (ssh -W through the master), which the +// VM's sshd opens to the VM's own loopback; +// - it listens on the host's loopback alone (127.0.0.1 and ::1), on the +// port the VM listens on, for servers on the VM's loopback or all its +// addresses, from 1024 up; never on a port the host has on any address +// (no SO_REUSEADDR: platform.ListenExclusive), nor on a port devvm +// records for any VM (ssh, proxy, decider, listed forwards); +// - every connection starts on the host: the VM opens none to the host +// through it, and the master asks for no forwarding into the host; +// - it ends when the machine's process does (its lifeline, agent.pid), +// and devvm stops it when it stops the VM. + +// Limits on what the VM's report makes the forwarder do. +const ( + minForwardPort = 1024 // privileged ports aren't forwarded + maxForwards = 256 // ports forwarded at once + maxListeners = 4096 // lines in one report + maxRelays = 256 // connections carried at once +) + +// Forwarder forwards a running VM's ports to the host's loopback, as the +// VM reports them (Watch). +type Forwarder struct { + VM string + // Lifeline is the machine's agent.pid: the forwarder ends once what + // it holds changes, or its process is gone. + Lifeline string + // Reserved returns the host ports never forwarded, asked each time a + // port would be; while it fails, none is. + Reserved func() (map[int]bool, error) + // Watch connects to the VM and runs ports.sh there, returning its + // output and how to wait for it; it ends with ctx or the connection. + Watch func(ctx context.Context) (io.ReadCloser, func() error, error) + // Relay carries conn to host:port in the VM until either side ends, + // then closes conn. + Relay func(ctx context.Context, conn net.Conn, host string, port int) + // Listen listens on a host loopback address (HOST:PORT). + Listen func(ctx context.Context, addr string) (net.Listener, error) + // Log gets its lines. + Log io.Writer + // Tick is how often the lifeline is looked at, and how long a lost + // connection waits to be made again. + Tick time.Duration + // Gap is the least time between two reports applied: one that comes + // sooner waits, and the VM's ssh channel with it. + Gap time.Duration + + mu sync.Mutex + ports map[int]*forward + skipped map[int]bool // not forwarded: tried again only once the VM's listener goes and comes back + relays chan struct{} +} + +// forward is a port being forwarded: its host listeners, and the address +// in the VM its connections go to. +type forward struct { + lns []net.Listener + host string +} + +func (f *Forwarder) logf(format string, args ...any) { + _, _ = fmt.Fprintf(f.Log, "devvm ports: "+format+"\n", args...) +} + +// Run forwards the VM's ports until ctx ends or the lifeline does, making +// the connection again whenever it's lost. +func (f *Forwarder) Run(ctx context.Context) error { + life, err := readLifeline(f.Lifeline) + if err != nil || life == "" { + return fmt.Errorf("%s: no lifeline at %s", f.VM, f.Lifeline) + } + ctx, cancel := context.WithCancel(ctx) + defer cancel() + go func() { + defer cancel() + for lifelineHolds(f.Lifeline, life) { + select { + case <-ctx.Done(): + return + case <-time.After(f.Tick): + } + } + f.logf("%s stopped", f.VM) + }() + f.ports, f.skipped, f.relays = map[int]*forward{}, map[int]bool{}, make(chan struct{}, maxRelays) + defer f.closeAll() + for ctx.Err() == nil { + if err := f.session(ctx); err != nil && ctx.Err() == nil { + f.logf("%s: %v", f.VM, err) + } + f.closeAll() + select { + case <-ctx.Done(): + case <-time.After(f.Tick): + } + } + return nil +} + +// session makes one connection to the VM and forwards what it reports +// until it ends. +func (f *Forwarder) session(ctx context.Context) error { + ctx, cancel := context.WithCancel(ctx) + defer cancel() + out, wait, err := f.Watch(ctx) + if err != nil { + return err + } + defer func() { cancel(); _ = wait() }() + sc := bufio.NewScanner(out) + sc.Buffer(make([]byte, 0, 128), 128) + var report []string + var last time.Time + ready := false + for sc.Scan() { + if line := sc.Text(); line != "." { + if len(report) >= maxListeners { + return errors.New("its report is too long") + } + report = append(report, line) + continue + } + if err := waitUntil(ctx, last.Add(f.Gap)); err != nil { + return err + } + last = time.Now() + f.apply(ctx, listeners(report)) + report = report[:0] + if !ready { + f.logf("forwarding %s's ports", f.VM) + ready = true + } + } + if err := sc.Err(); err != nil { + return err + } + return errors.New("the connection ended") +} + +// waitUntil waits until t, or ctx ends. +func waitUntil(ctx context.Context, t time.Time) error { + d := time.Until(t) + if d <= 0 { + return nil + } + select { + case <-ctx.Done(): + return ctx.Err() + case <-time.After(d): + return nil + } +} + +// What the VM can make the forwarder log (logLimit): logBurst writes at +// once, then one per logEvery, each at most logWriteMax bytes. +const ( + logBurst = 200 + logEvery = 10 * time.Second + logWriteMax = 512 +) + +// logLimit is the forwarder's log, which the VM can make it write to (its +// ports, its ssh's errors, and its sshd's stderr): limited, so it can't +// fill the host's disk, and control characters but newlines and tabs +// shown as '?'. +type logLimit struct { + w io.Writer + now func() time.Time + + mu sync.Mutex + tokens int + at time.Time + dropped int +} + +func newLogLimit(w io.Writer, now func() time.Time) *logLimit { + return &logLimit{w: w, now: now, tokens: logBurst, at: now()} +} + +func (l *logLimit) Write(p []byte) (int, error) { + l.mu.Lock() + defer l.mu.Unlock() + if n := int(l.now().Sub(l.at) / logEvery); n > 0 { + l.tokens, l.at = min(logBurst, l.tokens+n), l.at.Add(time.Duration(n)*logEvery) + } + if l.tokens == 0 { + l.dropped++ + return len(p), nil + } + l.tokens-- + var b []byte + if l.dropped > 0 { + b = fmt.Appendf(b, "devvm ports: %d writes not logged\n", l.dropped) + l.dropped = 0 + } + for _, c := range p[:min(len(p), logWriteMax)] { + if c < 0x20 && c != '\n' && c != '\t' || c == 0x7f { + c = '?' + } + b = append(b, c) + } + if len(p) > logWriteMax { + b = append(b, "…\n"...) + } + _, err := l.w.Write(b) + return len(p), err +} + +// apply makes the forwards what the VM reports: port to address in the +// VM. +func (f *Forwarder) apply(ctx context.Context, want map[int]string) { + reserved, rerr := f.Reserved() + if rerr != nil { + f.logf("no new ports forwarded: devvm's ports unknown: %v", rerr) + } + f.mu.Lock() + defer f.mu.Unlock() + for port, fw := range f.ports { + if _, ok := want[port]; !ok { + fw.close() + delete(f.ports, port) + f.logf("port %d: no longer forwarded", port) + } + } + for port := range f.skipped { + if _, ok := want[port]; !ok { + delete(f.skipped, port) + } + } + for _, port := range slices.Sorted(maps.Keys(want)) { + host := want[port] + if fw, ok := f.ports[port]; ok { + fw.host = host + continue + } + if rerr != nil || port < minForwardPort || reserved[port] || f.skipped[port] { + continue + } + f.skipped[port] = true + if len(f.ports) >= maxForwards { + f.logf("port %d: not forwarded: %d forwarded already", port, maxForwards) + continue + } + fw, err := f.open(ctx, port) + if err != nil { + f.logf("port %d: not forwarded: %v", port, err) + continue + } + fw.host = host + f.ports[port] = fw + delete(f.skipped, port) + f.logf("port %d: forwarded", port) + } +} + +// open listens on the port on the host's loopback, IPv4 and IPv6 (a host +// without IPv6 gets IPv4 alone), and serves it. +func (f *Forwarder) open(ctx context.Context, port int) (*forward, error) { + p := strconv.Itoa(port) + l4, err := f.Listen(ctx, net.JoinHostPort("127.0.0.1", p)) + if err != nil { + return nil, err + } + fw := &forward{lns: []net.Listener{l4}} + switch l6, err := f.Listen(ctx, net.JoinHostPort("::1", p)); { + case err == nil: + fw.lns = append(fw.lns, l6) + case errors.Is(err, syscall.EADDRINUSE): + // Another program has it there: localhost would reach either. + fw.close() + return nil, err + } + for _, l := range fw.lns { + go f.serve(ctx, l, port, fw) + } + return fw, nil +} + +// serve relays each connection to a listener to the port in the VM. +func (f *Forwarder) serve(ctx context.Context, l net.Listener, port int, fw *forward) { + for { + conn, err := l.Accept() + if err != nil { + return + } + select { + case f.relays <- struct{}{}: + default: + _ = conn.Close() // too many at once + continue + } + f.mu.Lock() + host := fw.host + f.mu.Unlock() + go func() { + defer func() { <-f.relays }() + f.Relay(ctx, conn, host, port) + }() + } +} + +func (fw *forward) close() { + for _, l := range fw.lns { + _ = l.Close() + } +} + +func (f *Forwarder) closeAll() { + f.mu.Lock() + defer f.mu.Unlock() + for port, fw := range f.ports { + fw.close() + delete(f.ports, port) + } + clear(f.skipped) +} + +// listeners reads ports.sh's report, /proc/net/tcp's local addresses +// (ADDRESS:PORT in hex), as the address in the VM each port's +// connections go to: 127.0.0.1 for a server on all IPv4 addresses or +// that one, ::1 for one on all IPv6 addresses or that one, another +// loopback address for one there alone. Servers on other addresses +// alone aren't forwarded, nor are lines that aren't addresses. +func listeners(report []string) map[int]string { + found := map[int][]netip.Addr{} + for _, line := range report { + a, p, ok := strings.Cut(strings.TrimSpace(line), ":") + if !ok || len(p) != 4 { + continue + } + port, err := strconv.ParseUint(p, 16, 16) + ip, iok := procAddr(a) + if err != nil || port == 0 || !iok { + continue + } + if to, ok := dialAddr(ip); ok { + found[int(port)] = append(found[int(port)], to) + } + } + out := map[int]string{} + v4, v6 := netip.MustParseAddr("127.0.0.1"), netip.IPv6Loopback() + for port, addrs := range found { + switch { + case slices.Contains(addrs, v4): + out[port] = v4.String() + case slices.Contains(addrs, v6): + out[port] = v6.String() + default: + slices.SortFunc(addrs, func(a, b netip.Addr) int { return a.Compare(b) }) + out[port] = addrs[0].String() + } + } + return out +} + +// procAddr reads an address as /proc/net/tcp has it: 4 or 16 bytes in +// hex, each 32-bit word in the host's order (little-endian on devvm's). +func procAddr(h string) (netip.Addr, bool) { + b, err := hex.DecodeString(h) + if err != nil || len(b) != 4 && len(b) != 16 { + return netip.Addr{}, false + } + for i := 0; i < len(b); i += 4 { + b[i], b[i+1], b[i+2], b[i+3] = b[i+3], b[i+2], b[i+1], b[i] + } + a, ok := netip.AddrFromSlice(b) + return a.Unmap(), ok +} + +// dialAddr is where in the VM a forwarded connection to a server on a goes: +// its loopback alone. +func dialAddr(a netip.Addr) (netip.Addr, bool) { + switch { + case a == netip.IPv4Unspecified(): + return netip.MustParseAddr("127.0.0.1"), true + case a == netip.IPv6Unspecified(): + return netip.IPv6Loopback(), true + case a.IsLoopback(): + return a, true + } + return netip.Addr{}, false +} + +// readLifeline returns what a lifeline holds, "" when it's gone. +func readLifeline(path string) (string, error) { + b, err := os.ReadFile(path) //nolint:gosec // smolvm's own file for the machine + if errors.Is(err, os.ErrNotExist) { + return "", nil + } + return strings.TrimSpace(string(b)), err +} + +// lifelineHolds reports whether the lifeline still holds life and its +// process (the first line) runs. +func lifelineHolds(path, life string) bool { + cur, err := readLifeline(path) + if err != nil || cur != life { + return false + } + first, _, _ := strings.Cut(cur, "\n") + pid, err := strconv.Atoi(strings.TrimSpace(first)) + return err == nil && pid > 0 && alive(pid) +} + +// listenLoopback listens on a host loopback address only where the port is +// free on every address (platform.ListenExclusive). A port in use only by +// connections that have ended (TIME_WAIT: nothing answers on it) is taken +// as Go takes any. +func listenLoopback(ctx context.Context, addr string) (net.Listener, error) { + l, err := platform.ListenExclusive(ctx, "tcp", addr) + if err == nil || !errors.Is(err, syscall.EADDRINUSE) { + return l, err + } + d := net.Dialer{Timeout: 300 * time.Millisecond} + if c, derr := d.DialContext(ctx, "tcp", addr); derr == nil { + _ = c.Close() + return nil, err // a program of the host's listens there + } else if !errors.Is(derr, syscall.ECONNREFUSED) { + return nil, err + } + var lc net.ListenConfig + return lc.Listen(ctx, "tcp", addr) +} + +// sshForward is how the forwarder reaches a VM: its sshd's port on the +// host's loopback, the VM's user and key, its pinned host key, and the +// master's control socket. +type sshForward struct { + vm, user, key, knownHosts, control string + port int +} + +// connArgs are ssh's options for reaching the VM: no configuration of the +// user's, the VM's key alone and no agent, its host key pinned, and +// nothing forwarded either way. +func (o sshForward) connArgs() []string { + return []string{ + "-o", "BatchMode=yes", + "-o", "IdentitiesOnly=yes", "-o", "IdentityAgent=none", "-o", "IdentityFile=" + o.key, + "-o", "PreferredAuthentications=publickey", "-o", "AddKeysToAgent=no", + "-o", "UserKnownHostsFile=" + o.knownHosts, "-o", "GlobalKnownHostsFile=/dev/null", + "-o", "HostKeyAlias=" + o.vm, "-o", "StrictHostKeyChecking=yes", "-o", "UpdateHostKeys=no", + "-o", "ForwardAgent=no", "-o", "ForwardX11=no", "-o", "Tunnel=no", "-o", "PermitRemoteOpen=none", + "-o", "ClearAllForwardings=yes", "-o", "PermitLocalCommand=no", "-o", "ProxyCommand=none", "-o", "ProxyJump=none", + "-o", "ConnectTimeout=10", "-o", "LogLevel=ERROR", + "-p", strconv.Itoa(o.port), "-l", o.user, "127.0.0.1", + } +} + +// masterArgs are ssh's arguments for the master connection, ports.sh run +// in its session. +func (o sshForward) masterArgs() []string { + return slices.Concat( + []string{"-F", "none", "-M", "-S", o.control, "-T", "-o", "ControlPersist=no", "-o", "ServerAliveInterval=10", "-o", "ServerAliveCountMax=3"}, + o.connArgs(), []string{"sh -s"}, + ) +} + +// relayArgs are ssh's arguments for one forwarded connection: a channel of +// the master's to host:port in the VM. Without the master, ssh connects +// on its own: to the VM, as the master does, never anywhere else. +func (o sshForward) relayArgs(host string, port int) []string { + return slices.Concat( + []string{"-F", "none", "-S", o.control, "-o", "ControlMaster=no", "-W", net.JoinHostPort(host, strconv.Itoa(port))}, + o.connArgs(), + ) +} + +// watch starts the master, ports.sh fed to its session. +func (o sshForward) watch(script []byte, log io.Writer) func(ctx context.Context) (io.ReadCloser, func() error, error) { + return func(ctx context.Context) (io.ReadCloser, func() error, error) { + if err := os.Remove(o.control); err != nil && !errors.Is(err, os.ErrNotExist) { + return nil, nil, err + } + cmd := exec.CommandContext(ctx, "ssh", o.masterArgs()...) //nolint:gosec // devvm's own arguments + cmd.Stdin, cmd.Stderr = bytes.NewReader(script), log + out, err := cmd.StdoutPipe() + if err != nil { + return nil, nil, err + } + if err := cmd.Start(); err != nil { + return nil, nil, err + } + return out, cmd.Wait, nil + } +} + +// relay carries conn through a channel of the master's. +func (o sshForward) relay(ctx context.Context, conn net.Conn, host string, port int) { + defer func() { _ = conn.Close() }() + cmd := exec.CommandContext(ctx, "ssh", o.relayArgs(host, port)...) //nolint:gosec // devvm's own arguments + in, err := cmd.StdinPipe() + if err != nil { + return + } + out, err := cmd.StdoutPipe() + if err != nil { + return + } + if err := cmd.Start(); err != nil { + return + } + go func() { + _, _ = io.Copy(in, conn) + _ = in.Close() + }() + _, _ = io.Copy(conn, out) + _ = conn.Close() + _ = cmd.Wait() +} + +// ForwardMain runs a VM's forwarder (devvm _smolvm-ports) with its +// arguments: ports.sh is script, reserved the ports devvm records for VMs, +// and its lines go to log. +func ForwardMain(ctx context.Context, args []string, script []byte, reserved func() (map[int]bool, error), log io.Writer) error { + fs := flag.NewFlagSet("_smolvm-ports", flag.ContinueOnError) + fs.SetOutput(log) + var o sshForward + var lifeline, reserve string + fs.StringVar(&o.vm, "vm", "", "the VM") + fs.StringVar(&lifeline, "lifeline", "", "the machine's agent.pid: exit when it changes or its process is gone") + fs.IntVar(&o.port, "port", 0, "the host loopback port the VM's sshd is forwarded from") + fs.StringVar(&o.user, "user", "", "the VM's user") + fs.StringVar(&o.key, "key", "", "the VM's own key") + fs.StringVar(&o.knownHosts, "known-hosts", "", "the VM's host key, as known_hosts has it, under the VM's name") + fs.StringVar(&o.control, "control", "", "the master's control socket") + fs.StringVar(&reserve, "reserve", "", "host ports never forwarded, comma-separated") + if err := fs.Parse(args); err != nil { + return err + } + if o.vm == "" || lifeline == "" || o.port <= 0 || o.user == "" || o.key == "" || o.knownHosts == "" || o.control == "" { + return errors.New("-vm, -lifeline, -port, -user, -key, -known-hosts and -control are needed") + } + own := map[int]bool{} + for p := range strings.SplitSeq(reserve, ",") { + if n, err := strconv.Atoi(strings.TrimSpace(p)); err == nil { + own[n] = true + } + } + log = newLogLimit(log, time.Now) + f := &Forwarder{ + VM: o.vm, Lifeline: lifeline, Log: log, Tick: 2 * time.Second, Gap: 500 * time.Millisecond, + Reserved: func() (map[int]bool, error) { + out, err := reserved() + if out == nil { + out = map[int]bool{} + } + for p := range own { + out[p] = true + } + return out, err + }, + Watch: o.watch(script, log), Relay: o.relay, Listen: listenLoopback, + } + return f.Run(ctx) +} diff --git a/internal/backend/smolvm/forward_test.go b/internal/backend/smolvm/forward_test.go new file mode 100644 index 00000000..b05d7b89 --- /dev/null +++ b/internal/backend/smolvm/forward_test.go @@ -0,0 +1,483 @@ +package smolvm + +import ( + "bufio" + "bytes" + "context" + "errors" + "fmt" + "io" + "maps" + "net" + "os" + "path/filepath" + "slices" + "strconv" + "strings" + "sync" + "testing" + "time" + + "github.com/w3cj/devvm/internal/backend" + "github.com/w3cj/devvm/internal/msg" +) + +// ports.sh's report as the forwarder reads it: each port to the address +// in the VM its connections go to, loopback alone. +func TestListeners(t *testing.T) { + got := listeners([]string{ + "0100007F:0BB8", // 127.0.0.1:3000 + "00000000:1F90", // 0.0.0.0:8080 + "00000000000000000000000001000000:1F90", // [::1]:8080: IPv4 first + "00000000000000000000000001000000:1435", // [::1]:5173 alone + "00000000000000000000000000000000:2328", // [::]:9000 + "0000000000000000FFFF00000100007F:2329", // [::ffff:127.0.0.1]:9001 + "0200007F:232A", // 127.0.0.2:9002 + "0100A8C0:232B", // 192.168.0.1:9003: not loopback + "0000000000000000FFFF00000100A8C0:232C", // [::ffff:192.168.0.1]:9004 + "0100007F:0000", "zz:0BB8", "0100007F", "", // not addresses + "0100007F:00016", "01007F:0BB8", + }) + want := map[int]string{3000: "127.0.0.1", 8080: "127.0.0.1", 5173: "::1", 9000: "::1", 9001: "127.0.0.1", 9002: "127.0.0.2"} + if !maps.Equal(got, want) { + t.Errorf("listeners = %v, want %v", got, want) + } +} + +// freePorts returns n ports free on the host's loopback now. +func freePorts(t *testing.T, n int) []int { + t.Helper() + var out []int + for len(out) < n { + l, err := net.Listen("tcp", "127.0.0.1:0") //nolint:noctx // a test's moment + if err != nil { + t.Fatal(err) + } + p := l.Addr().(*net.TCPAddr).Port + _ = l.Close() + if p >= minForwardPort && !slices.Contains(out, p) { + out = append(out, p) + } + } + return out +} + +// procLine is a listener on port as /proc/net/tcp has it. +func procLine(addr string, port int) string { return fmt.Sprintf("%s:%04X", addr, port) } + +// fakeVM is a VM as the forwarder sees it: its reports, written by the +// test, one connection at a time. +type fakeVM struct { + mu sync.Mutex + reports *io.PipeWriter + watches int + ready chan struct{} +} + +func (v *fakeVM) watch(ctx context.Context) (io.ReadCloser, func() error, error) { + r, w := io.Pipe() + v.mu.Lock() + v.reports = w + v.watches++ + v.mu.Unlock() + go func() { <-ctx.Done(); _ = w.CloseWithError(ctx.Err()) }() + v.ready <- struct{}{} + return r, func() error { return nil }, nil +} + +func (v *fakeVM) report(t *testing.T, lines ...string) { + t.Helper() + v.mu.Lock() + w := v.reports + v.mu.Unlock() + if _, err := io.WriteString(w, strings.Join(append(lines, "."), "\n")+"\n"); err != nil { + t.Fatal(err) + } +} + +// reach connects to a host loopback port and returns what comes back. +func reach(t *testing.T, addr string) string { + d := net.Dialer{Timeout: time.Second} + c, err := d.DialContext(t.Context(), "tcp", addr) + if err != nil { + return "refused" + } + defer func() { _ = c.Close() }() + _ = c.SetDeadline(time.Now().Add(2 * time.Second)) + line, _ := bufio.NewReader(c).ReadString('\n') + return strings.TrimSpace(line) +} + +// eventually waits for addr to answer want. +func eventually(t *testing.T, addr, want string) { + t.Helper() + var got string + for range 100 { + if got = reach(t, addr); got == want { + return + } + time.Sleep(20 * time.Millisecond) + } + t.Errorf("%s: %q, want %q", addr, got, want) +} + +// The forwarder listens on the host's loopback for what the VM reports, +// from 1024 up, never on a reserved port or one the host has on any +// address; forwards go once the VM's listener does, and all of them when +// the connection ends, until it's made again. +func TestForwarder(t *testing.T) { + ports := freePorts(t, 5) + open, v6only, reserved, hosts, gone := ports[0], ports[1], ports[2], ports[3], ports[4] + // The host's own program, on every address. + host, err := net.Listen("tcp", ":"+strconv.Itoa(hosts)) //nolint:noctx // the test's + if err != nil { + t.Fatal(err) + } + defer func() { _ = host.Close() }() + life := filepath.Join(t.TempDir(), "agent.pid") + if err := os.WriteFile(life, []byte(strconv.Itoa(os.Getpid())+"\n123\n"), 0o600); err != nil { + t.Fatal(err) + } + vm := &fakeVM{ready: make(chan struct{}, 4)} + var log bytes.Buffer + var logMu sync.Mutex + f := &Forwarder{ + VM: "devvm-f", Lifeline: life, Tick: 10 * time.Millisecond, Log: lockedWriter{&logMu, &log}, + Reserved: func() (map[int]bool, error) { return map[int]bool{reserved: true}, nil }, + Watch: vm.watch, + Relay: func(_ context.Context, conn net.Conn, h string, p int) { + _, _ = fmt.Fprintf(conn, "to %s\n", net.JoinHostPort(h, strconv.Itoa(p))) + _ = conn.Close() + }, + Listen: listenLoopback, + } + ctx, cancel := context.WithCancel(t.Context()) + done := make(chan error, 1) + go func() { done <- f.Run(ctx) }() + <-vm.ready + vm.report(t, + procLine("0100007F", open), procLine("00000000000000000000000001000000", v6only), + procLine("00000000", reserved), procLine("00000000", hosts), procLine("00000000", gone), + procLine("00000000", 80), procLine("0100A8C0", 9999), + ) + at := func(p int) string { return net.JoinHostPort("127.0.0.1", strconv.Itoa(p)) } + eventually(t, at(open), "to "+at(open)) + eventually(t, net.JoinHostPort("::1", strconv.Itoa(open)), "to "+at(open)) + eventually(t, at(v6only), "to "+net.JoinHostPort("::1", strconv.Itoa(v6only))) + eventually(t, at(gone), "to "+at(gone)) + if got := reach(t, at(reserved)); got != "refused" { + t.Errorf("reserved port: %q", got) + } + if got := reach(t, at(hosts)); strings.HasPrefix(got, "to ") { + t.Errorf("the host's port taken: %q", got) + } + // The VM's listener goes: so does its forward. + vm.report(t, procLine("0100007F", open)) + eventually(t, at(gone), "refused") + eventually(t, at(open), "to "+at(open)) + // The connection ends: every forward goes, then it's made again. + vm.mu.Lock() + _ = vm.reports.Close() + vm.mu.Unlock() + <-vm.ready + eventually(t, at(open), "refused") + vm.report(t, procLine("00000000", open)) + eventually(t, at(open), "to "+at(open)) + // The lifeline changes (the VM started again): it ends. + if err := os.WriteFile(life, []byte(strconv.Itoa(os.Getpid())+"\n456\n"), 0o600); err != nil { + t.Fatal(err) + } + select { + case err := <-done: + if err != nil { + t.Error(err) + } + case <-time.After(5 * time.Second): + t.Error("still running with its lifeline changed") + } + cancel() + eventually(t, at(open), "refused") + logMu.Lock() + defer logMu.Unlock() + for _, want := range []string{"forwarding devvm-f's ports", fmt.Sprintf("port %d: not forwarded", hosts), fmt.Sprintf("port %d: forwarded", open)} { + if !strings.Contains(log.String(), want) { + t.Errorf("log lacks %q:\n%s", want, log.String()) + } + } +} + +type lockedWriter struct { + mu *sync.Mutex + w io.Writer +} + +func (l lockedWriter) Write(b []byte) (int, error) { + l.mu.Lock() + defer l.mu.Unlock() + return l.w.Write(b) +} + +// A VM that reports faster than Gap waits: reports are applied Gap apart. +func TestForwarderGap(t *testing.T) { + life := filepath.Join(t.TempDir(), "agent.pid") + if err := os.WriteFile(life, []byte(strconv.Itoa(os.Getpid())+"\n1\n"), 0o600); err != nil { + t.Fatal(err) + } + vm := &fakeVM{ready: make(chan struct{}, 4)} + var mu sync.Mutex + var applied []time.Time + gap := 100 * time.Millisecond + f := &Forwarder{ + VM: "devvm-f", Lifeline: life, Tick: 10 * time.Millisecond, Gap: gap, Log: io.Discard, + Reserved: func() (map[int]bool, error) { + mu.Lock() + defer mu.Unlock() + applied = append(applied, time.Now()) + return nil, nil + }, + Watch: vm.watch, Listen: listenLoopback, + } + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + go func() { _ = f.Run(ctx) }() + <-vm.ready + for range 5 { + vm.report(t) + } + time.Sleep(gap) + mu.Lock() + defer mu.Unlock() + if len(applied) < 4 { + t.Fatalf("%d reports applied", len(applied)) + } + for i := 1; i < len(applied); i++ { + if d := applied[i].Sub(applied[i-1]); d < gap-10*time.Millisecond { + t.Errorf("reports %d and %d applied %v apart", i-1, i, d) + } + } +} + +// What the VM makes the forwarder log is limited: a burst, then one write +// per logEvery, those dropped counted; control characters shown as '?', +// long writes cut. +func TestLogLimit(t *testing.T) { + var b bytes.Buffer + now := time.Unix(1000, 0) + l := newLogLimit(&b, func() time.Time { return now }) + for range logBurst + 50 { + _, _ = l.Write([]byte("x\n")) + } + if got := strings.Count(b.String(), "x\n"); got != logBurst { + t.Errorf("%d writes logged, want %d", got, logBurst) + } + b.Reset() + now = now.Add(2 * logEvery) + _, _ = l.Write([]byte("a\x1b[2Jb\r\n")) + _, _ = l.Write([]byte(strings.Repeat("y", logWriteMax+10))) + _, _ = l.Write([]byte("dropped\n")) + want := "devvm ports: 50 writes not logged\na?[2Jb?\n" + strings.Repeat("y", logWriteMax) + "…\n" + if b.String() != want { + t.Errorf("log:\n%q\nwant\n%q", b.String(), want) + } +} + +// What a VM prints is kept up to the cap. +func TestCapped(t *testing.T) { + c := &capped{max: 4} + if n, err := c.Write([]byte("abc")); n != 3 || err != nil { + t.Fatal(n, err) + } + if n, _ := c.Write([]byte("defg")); n != 4 || c.String() != "abcd" { + t.Errorf("kept %q", c.String()) + } +} + +// While devvm's ports can't be read, nothing new is forwarded. +func TestForwarderReservedUnknown(t *testing.T) { + p := freePorts(t, 1)[0] + var log bytes.Buffer + f := &Forwarder{ + VM: "devvm-f", Log: &log, ports: map[int]*forward{}, skipped: map[int]bool{}, + Reserved: func() (map[int]bool, error) { return nil, errors.New("unreadable") }, + Listen: listenLoopback, + } + f.apply(t.Context(), map[int]string{p: "127.0.0.1"}) + if len(f.ports) != 0 || !strings.Contains(log.String(), "no new ports forwarded") { + t.Errorf("forwarded %v; log %q", f.ports, log.String()) + } +} + +// A port the host has on any address is refused; one that's free, or held +// only by ended connections, is taken. +func TestListenLoopback(t *testing.T) { + p := freePorts(t, 1)[0] + wild, err := net.Listen("tcp4", "0.0.0.0:"+strconv.Itoa(p)) //nolint:noctx // the test's + if err != nil { + t.Fatal(err) + } + if l, err := listenLoopback(t.Context(), "127.0.0.1:"+strconv.Itoa(p)); err == nil { + _ = l.Close() + t.Error("took a port the host has on every address") + } + _ = wild.Close() + l, err := listenLoopback(t.Context(), "127.0.0.1:"+strconv.Itoa(p)) + if err != nil { + t.Fatal(err) + } + _ = l.Close() +} + +// The master asks for nothing to be forwarded, reads no configuration of +// the user's and offers the VM's key alone; a relay is a channel of it, +// and without it connects to the VM the same way, never elsewhere. +func TestForwarderSSH(t *testing.T) { + o := sshForward{vm: "devvm-v", user: "u", key: "/k", knownHosts: "/kh", control: "/c.ctl", port: 61022} + conn := []string{ + "IdentitiesOnly=yes", "IdentityAgent=none", "IdentityFile=/k", "UserKnownHostsFile=/kh", + "HostKeyAlias=devvm-v", "StrictHostKeyChecking=yes", "ForwardAgent=no", "ForwardX11=no", "Tunnel=no", + "PermitRemoteOpen=none", "ClearAllForwardings=yes", "ProxyCommand=none", + } + for name, tc := range map[string]struct { + args []string + want []string + }{ + "master": {o.masterArgs(), append([]string{"-F none -M -S /c.ctl -T ", " -p 61022 -l u 127.0.0.1 sh -s"}, conn...)}, + "relay": {o.relayArgs("::1", 5173), append([]string{"-F none -S /c.ctl -o ControlMaster=no -W [::1]:5173 ", " -p 61022 -l u 127.0.0.1"}, conn...)}, + } { + got := strings.Join(tc.args, " ") + for _, want := range tc.want { + if !strings.Contains(got, want) { + t.Errorf("%s lacks %q: %s", name, want, got) + } + } + for _, a := range tc.args { + if a == "-R" || a == "-L" || a == "-D" || a == "-A" || a == "-X" || a == "-Y" { + t.Errorf("%s asks for %s", name, a) + } + } + } + if got := o.relayArgs("::1", 5173); got[len(got)-1] != "127.0.0.1" { + t.Errorf("relay runs a command: %q", got) + } +} + +// A VM that forwards every port gets none of smolvm's, and its forwarder +// once its sshd runs: its host key pinned, its ssh's, proxy's and +// decider's ports reserved; stopping or deleting the VM stops it. +func TestStartForwarder(t *testing.T) { + s := newSandbox(t) + vm := "devvm-a-0123456789abcd" + s.image(t, "0123456789ab") + spec := backend.VMSpec{Name: vm, Ports: backend.Ports{All: true}} + if err := s.CreateVM(t.Context(), "0123456789ab", spec); err != nil { + t.Fatal(err) + } + if got := s.calls(t); len(got) != 1 || strings.Contains(got[0], " -p ") { + t.Errorf("create: %q", got) + } + // A short folder for its control socket: a test's temporary one can + // be too long for one. + short, err := os.MkdirTemp("/tmp", "dv") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = os.RemoveAll(short) }) + s.Forwards.Dirs.Data = short + var args []string + s.Forwards.Detach = func(path string, a []string, out *os.File) (int, error) { + args = append([]string{path}, a...) + _, err := fmt.Fprintf(out, "devvm ports: forwarding %s's ports\n", vm) + return os.Getpid(), err + } + running := false + s.Forwards.Args = func(int) ([]string, error) { + if !running { + return nil, errors.New("gone") + } + return []string{"/devvm", forwarderCmd, "-vm", vm}, nil + } + var warned []string + s.Warn = func(m msg.M) { warned = append(warned, m.Names()) } + c := backend.Confinement{SSH: true, Net: backend.NetDirect, ProxyPort: 30001, Decider: "127.0.0.1:30002"} + if err := s.Start(t.Context(), vm, c); err != nil { + t.Fatal(err) + } + if len(warned) != 0 { + t.Errorf("warned %q", warned) + } + r, _ := s.readRecord(vm) + want := []string{ + "/devvm", "_smolvm-ports", "-vm", vm, "-lifeline", filepath.Join(s.stub, "smolvm-data", vm, "agent.pid"), + "-port", "61022", "-user", "u", "-key", s.sshKey(vm), "-known-hosts", s.Forwards.file(vm, ".ports.known_hosts"), + "-control", s.Forwards.control(vm), "-reserve", "61022,30001,30002", + } + if !r.PortsAll || !slices.Equal(args, want) { + t.Errorf("forwarder:\n%q\nwant\n%q", args, want) + } + if b, err := os.ReadFile(s.Forwards.file(vm, ".ports.known_hosts")); err != nil || string(b) != vm+" ssh-ed25519 AAAAstub\n" { + t.Errorf("known_hosts: %q, %v", b, err) + } + if !slices.Contains(s.calls(t), "smolvm machine exec --name "+vm+" -- cat /etc/ssh/ssh_host_ed25519_key.pub") { + t.Errorf("host key not read through smolvm: %q", s.calls(t)) + } + running = true + if _, ok := s.Forwards.pid(vm); !ok { + t.Error("forwarder not found") + } + running = false + + // Without sshd: warned, no forwarder. + if err := s.Stop(t.Context(), vm); err != nil { + t.Fatal(err) + } + s.touch(t, "no-sshd") + args = nil + if err := s.Start(t.Context(), vm, c); err != nil { + t.Fatal(err) + } + if args != nil || !slices.Contains(warned, "smolvm_ports_no_ssh vm="+vm) { + t.Errorf("no sshd: forwarder %q, warned %q", args, warned) + } + if err := os.Remove(filepath.Join(s.stub, "no-sshd")); err != nil { + t.Fatal(err) + } + // A forwarder that never says it forwards: warned, the VM runs on. + if err := s.Stop(t.Context(), vm); err != nil { + t.Fatal(err) + } + warned = nil + s.Forwards.Detach = func(string, []string, *os.File) (int, error) { return os.Getpid(), nil } + if err := s.Start(t.Context(), vm, c); err != nil { + t.Fatal(err) + } + if !slices.Equal(warned, []string{"smolvm_ports_failed log=" + s.Forwards.Log(vm) + " vm=" + vm}) { + t.Errorf("warned %q", warned) + } + + // Listed ports instead: smolvm's, and no forwarder. + if err := s.Stop(t.Context(), vm); err != nil { + t.Fatal(err) + } + s.reset(t) + if err := s.SetPorts(t.Context(), vm, backend.Ports{Ranges: []backend.PortRange{{From: 3000, To: 3000}}}); err != nil { + t.Fatal(err) + } + if r, _ := s.readRecord(vm); r.PortsAll || !slices.Equal(s.calls(t), []string{"smolvm machine update --name " + vm + " -p 3000:3000"}) { + t.Errorf("listed: %+v, %q", r, s.calls(t)) + } + s.reset(t) + if err := s.SetPorts(t.Context(), vm, backend.Ports{All: true}); err != nil { + t.Fatal(err) + } + if r, _ := s.readRecord(vm); !r.PortsAll || !slices.Equal(s.calls(t), []string{"smolvm machine update --name " + vm + " --remove-port 3000:3000"}) { + t.Errorf("all again: %+v, %q", r, s.calls(t)) + } + if err := s.Delete(t.Context(), vm); err != nil { + t.Fatal(err) + } + for _, ext := range []string{".ports.pid", ".ports.known_hosts", ".ports.log"} { + if _, err := os.Stat(s.Forwards.file(vm, ext)); !errors.Is(err, os.ErrNotExist) { + t.Errorf("%s left: %v", ext, err) + } + } +} diff --git a/internal/backend/smolvm/ports.go b/internal/backend/smolvm/ports.go new file mode 100644 index 00000000..c391c870 --- /dev/null +++ b/internal/backend/smolvm/ports.go @@ -0,0 +1,204 @@ +package smolvm + +import ( + "bytes" + "crypto/sha256" + "encoding/hex" + "errors" + "fmt" + "net/netip" + "os" + "path/filepath" + "regexp" + "slices" + "strconv" + "strings" + "syscall" + "time" + + "github.com/w3cj/devvm/internal/paths" + "github.com/w3cj/devvm/internal/state" +) + +// forwarderCmd is the hidden command that runs a VM's forwarder. +const forwarderCmd = "_smolvm-ports" + +// Forwards starts and stops the VMs' port forwarders (forward.go): devvm +// _smolvm-ports, detached, one per VM that forwards every port. +type Forwards struct { + Dirs paths.Dirs + // Self is devvm's binary, which runs as the forwarder. + Self string + // Detach starts a process that outlives devvm (platform.StartDetached). + Detach func(path string, args []string, out *os.File) (int, error) + // Args returns a running process's arguments (platform.ProcessArgs). + Args func(pid int) ([]string, error) + // Tick is how often a start looks for the forwarder to be ready, 20 + // times at most. + Tick time.Duration +} + +// forwardSpec is what a VM's forwarder needs: the machine's lifeline, the +// VM's sshd's host port and user, the VM's key, its host key (TYPE +// BASE64), and the host ports it never forwards. +type forwardSpec struct { + lifeline, user, key, hostKey string + sshPort int + reserve []int +} + +// file is one of the forwarder's files, beside the VM's record. +func (f Forwards) file(vm, ext string) string { + return filepath.Join(filepath.Dir(f.Dirs.SmolvmVM(vm)), vm+ext) +} + +// Log is the VM's forwarder's log. +func (f Forwards) Log(vm string) string { return f.file(vm, ".ports.log") } + +// control is the master's control socket: short, as a socket's path is at +// most 104 characters and ssh adds 17 while it makes it. +func (f Forwards) control(vm string) string { + sum := sha256.Sum256([]byte(vm)) + return filepath.Join(f.Dirs.Run(), "smolvm-"+hex.EncodeToString(sum[:])[:16]+".ctl") +} + +// logMax is the most a forwarder's log keeps from earlier starts: past +// it, a start empties it. +const logMax = 1 << 20 + +// controlMax is the longest control socket path ssh can make. +const controlMax = 104 - 1 - 17 + +// Start starts the VM's forwarder, after any it had, and waits for it to +// say it forwards. One that doesn't is left to keep trying, and its log +// named in the error. +func (f Forwards) Start(vm string, spec forwardSpec) error { + f.Stop(vm) + ctl := f.control(vm) + if len(ctl) > controlMax { + return fmt.Errorf("%s: its path is too long for a socket", ctl) + } + if err := os.MkdirAll(filepath.Dir(ctl), 0o700); err != nil { + return err + } + kh := f.file(vm, ".ports.known_hosts") + if err := state.WriteFile(kh, []byte(vm+" "+spec.hostKey+"\n")); err != nil { + return err + } + out, err := os.OpenFile(f.Log(vm), os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o600) + if err != nil { + return err + } + defer func() { _ = out.Close() }() + fi, err := out.Stat() + if err != nil { + return err + } + before := fi.Size() + if before > logMax { + if err := out.Truncate(0); err != nil { + return err + } + before = 0 + } + var reserve []string + for _, p := range spec.reserve { + if p > 0 { + reserve = append(reserve, strconv.Itoa(p)) + } + } + pid, err := f.Detach(f.Self, []string{ + forwarderCmd, "-vm", vm, "-lifeline", spec.lifeline, "-port", strconv.Itoa(spec.sshPort), "-user", spec.user, + "-key", spec.key, "-known-hosts", kh, "-control", ctl, "-reserve", strings.Join(reserve, ","), + }, out) + if err != nil { + return err + } + if err := state.WriteFile(f.file(vm, ".ports.pid"), []byte(strconv.Itoa(pid)+"\n")); err != nil { + return err + } + want := []byte("forwarding " + vm + "'s ports") + for range 20 { + if b, err := os.ReadFile(f.Log(vm)); err == nil && int64(len(b)) >= before && bytes.Contains(b[before:], want) { + return nil + } + if _, ok := f.pid(vm); !ok { + break + } + time.Sleep(f.Tick) + } + return fmt.Errorf("%s: its forwarder isn't forwarding", vm) +} + +// pid returns the VM's forwarder's pid while it runs. +func (f Forwards) pid(vm string) (int, bool) { + b, err := os.ReadFile(f.file(vm, ".ports.pid")) + if err != nil { + return 0, false + } + pid, err := strconv.Atoi(strings.TrimSpace(string(b))) + if err != nil || pid <= 0 || !alive(pid) { + return 0, false + } + args, err := f.Args(pid) + if err != nil || len(args) < 2 || args[1] != forwarderCmd { + return 0, false + } + if i := slices.Index(args, "-vm"); i < 0 || i+1 >= len(args) || args[i+1] != vm { + return 0, false + } + return pid, true +} + +// Stop stops the VM's forwarder, if it runs, waiting up to two seconds for +// it to end. +func (f Forwards) Stop(vm string) { + pid, ok := f.pid(vm) + if !ok { + return + } + if p, err := os.FindProcess(pid); err == nil { + _ = p.Signal(syscall.SIGTERM) + } + for range 20 { + if !alive(pid) { + return + } + time.Sleep(100 * time.Millisecond) + } +} + +// Remove stops the VM's forwarder and deletes its files. +func (f Forwards) Remove(vm string) error { + f.Stop(vm) + for _, ext := range []string{".ports.pid", ".ports.known_hosts", ".ports.log"} { + if err := os.Remove(f.file(vm, ext)); err != nil && !errors.Is(err, os.ErrNotExist) { + return err + } + } + return nil +} + +// hostKeyLine is an ed25519 public key line, as the VM's sshd has it. +var hostKeyLine = regexp.MustCompile(`^ssh-ed25519 [A-Za-z0-9+/]+=*(\s|$)`) + +// hostKey returns the key type and base64 of the VM's sshd's host key, as +// cat of its .pub file gives them. +func hostKey(out []byte) (string, bool) { + line, _, _ := strings.Cut(strings.TrimSpace(string(out)), "\n") + if !hostKeyLine.MatchString(line) { + return "", false + } + f := strings.Fields(line) + return f[0] + " " + f[1], true +} + +// deciderPort is the port of a decider's address (127.0.0.1:PORT), 0 for +// none. +func deciderPort(addr string) int { + ap, err := netip.ParseAddrPort(addr) + if err != nil { + return 0 + } + return int(ap.Port()) +} diff --git a/internal/backend/smolvm/smolvm.go b/internal/backend/smolvm/smolvm.go index 02e38272..e81414af 100644 --- a/internal/backend/smolvm/smolvm.go +++ b/internal/backend/smolvm/smolvm.go @@ -9,8 +9,9 @@ // (--state-dir) as well. // // Network policy is emulated, reviewed (start.go); ssh for editors is -// emulated, reviewed (ssh.go). What smolvm lacks is refused (Caps): -// forwarding every port, and turning agent forwarding on or off later. +// emulated, reviewed (ssh.go); forwarding every port is emulated, +// reviewed (forward.go). What smolvm lacks is refused (Caps): turning +// agent forwarding on or off later. package smolvm import ( @@ -33,6 +34,7 @@ import ( "slices" "strconv" "strings" + "time" "github.com/w3cj/devvm/internal/backend" "github.com/w3cj/devvm/internal/from" @@ -97,6 +99,8 @@ type Smolvm struct { // whether the run was interrupted. AddCleanup func(f func(context.Context)) (remove func()) Interrupted func() bool + // Forwards runs the port forwarders of VMs that forward every port. + Forwards Forwards } // UI is where the backend prints, the run log its commands run into, the @@ -120,6 +124,12 @@ func New(d paths.Dirs, assets fs.FS, u UI) *Smolvm { if kvm == "" { kvm = "/dev/kvm" } + self, err := os.Executable() + if err == nil { + if r, rerr := filepath.EvalSymlinks(self); rerr == nil { + self = r + } + } return &Smolvm{ Dirs: d, Runner: logRunner{u.LoggedCmd}, OS: runtime.GOOS, Arch: runtime.GOARCH, Assets: assets, Getenv: os.Getenv, User: user.Current, Memory: platform.Memory, @@ -128,6 +138,9 @@ func New(d paths.Dirs, assets fs.FS, u UI) *Smolvm { FreePort: freePort, PortFree: portFree, Info: u.Info, Warn: u.Warn, WithSteps: u.WithSteps, AddCleanup: u.AddCleanup, Interrupted: u.Interrupted, + Forwards: Forwards{ + Dirs: d, Self: self, Detach: platform.StartDetached, Args: platform.ProcessArgs, Tick: 500 * time.Millisecond, + }, } } @@ -136,11 +149,15 @@ func (s *Smolvm) Name() string { return Name } // Caps is what smolvm has natively, egress through devvm's proxy emulated // and reviewed (Start: an allow list of the host, and the proxy deciding -// each connection), and ssh for editors emulated and reviewed (an sshd of -// devvm's, ssh.go). The rest waits for emulations: every port -// forwarded, and agent forwarding turned on or off once a VM is made. +// each connection), ssh for editors emulated and reviewed (an sshd of +// devvm's, ssh.go), and every port forwarded emulated and reviewed (a +// forwarder of devvm's over that ssh, forward.go). Agent forwarding +// turned on or off once a VM is made waits for an emulation. func (s *Smolvm) Caps() backend.Caps { - caps := backend.Caps{backend.FeatureEgressProxy: backend.Emulated(true), backend.FeatureSSH: backend.Emulated(true)} + caps := backend.Caps{ + backend.FeatureEgressProxy: backend.Emulated(true), backend.FeatureSSH: backend.Emulated(true), + backend.FeaturePortsAll: backend.Emulated(true), + } for _, f := range []backend.Feature{ backend.FeatureBuildImage, backend.FeatureBuildConfinement, backend.FeatureFrom, backend.FeatureClone, backend.FeatureProjectMount, backend.FeatureAgentFolders, backend.FeatureToolsShare, backend.FeaturePorts, @@ -183,14 +200,17 @@ func (s *Smolvm) ToolFormat() string { // record is what devvm set on one of its machines, which smolvm machine ls // doesn't show: kept in devvm's data folder (paths.Dirs.SmolvmVM). type record struct { - Image string `json:"image"` // its image's key - Project string `json:"project,omitempty"` - AgentDirs []string `json:"agent_dirs,omitempty"` - Tools string `json:"tools,omitempty"` - ToolsAt string `json:"tools_at,omitempty"` - Forwarding bool `json:"forwarding,omitempty"` - Ports []string `json:"ports,omitempty"` // as -p has them: 5173:5173, 8000-8002:8000-8002 - Env map[string]string `json:"env,omitempty"` + Image string `json:"image"` // its image's key + Project string `json:"project,omitempty"` + AgentDirs []string `json:"agent_dirs,omitempty"` + Tools string `json:"tools,omitempty"` + ToolsAt string `json:"tools_at,omitempty"` + Forwarding bool `json:"forwarding,omitempty"` + Ports []string `json:"ports,omitempty"` // as -p has them: 5173:5173, 8000-8002:8000-8002 + // PortsAll is set when it forwards every port: through its forwarder + // (forward.go), with none of smolvm's. + PortsAll bool `json:"ports_all,omitempty"` + Env map[string]string `json:"env,omitempty"` // Mediated is set once the machine started through devvm's decider: // smolvm then requires one at every start, until devvm removes that. Mediated bool `json:"mediated,omitempty"` @@ -476,11 +496,12 @@ func gibCeil(g float64) string { } // portArgs are -p's values for a project VM's ports p: each range to the -// same ports on the host. All is refused (ports-all), and so is more than -// smolvm forwards besides the VM's ssh, or the guest port its sshd has. +// same ports on the host; none for all, which its forwarder forwards +// (forward.go). More than smolvm forwards besides the VM's ssh is refused, +// and so is the guest port its sshd has. func portArgs(vm string, p backend.Ports) ([]string, error) { if p.All { - return nil, msg.BackendLacks(Name, string(backend.FeaturePortsAll), vm) + return nil, nil } var out []string n := 0 @@ -511,20 +532,22 @@ func (s *Smolvm) SetPorts(ctx context.Context, vm string, p backend.Ports) error if err != nil { return err } - if slices.Equal(want, r.Ports) { + if slices.Equal(want, r.Ports) && r.PortsAll == p.All { return nil } var opts []string - for _, old := range r.Ports { - opts = append(opts, "--remove-port", old) - } - for _, w := range want { - opts = append(opts, "-p", w) + if !slices.Equal(want, r.Ports) { + for _, old := range r.Ports { + opts = append(opts, "--remove-port", old) + } + for _, w := range want { + opts = append(opts, "-p", w) + } } if err := s.update(ctx, vm, opts...); err != nil { return err } - r.Ports = want + r.Ports, r.PortsAll = want, p.All return s.writeRecord(vm, r) } diff --git a/internal/backend/smolvm/smolvm_test.go b/internal/backend/smolvm/smolvm_test.go index 6ec67da8..eef05ae7 100644 --- a/internal/backend/smolvm/smolvm_test.go +++ b/internal/backend/smolvm/smolvm_test.go @@ -11,6 +11,7 @@ import ( "strconv" "strings" "testing" + "time" "github.com/w3cj/devvm/assets" "github.com/w3cj/devvm/internal/backend" @@ -77,6 +78,11 @@ func newSandbox(t *testing.T) sandbox { FreePort: func() (int, error) { return 61022, nil }, PortFree: func(int) bool { return true }, Info: func(msg.M) {}, Warn: func(msg.M) {}, WithSteps: testUI{}.WithSteps, AddCleanup: testUI{}.AddCleanup, Interrupted: testUI{}.Interrupted, + Forwards: Forwards{ + Dirs: d, Self: "/devvm", Tick: time.Millisecond, + Detach: func(string, []string, *os.File) (int, error) { return 0, errors.New("no forwarder here") }, + Args: func(int) ([]string, error) { return nil, errors.New("no process") }, + }, } return sandbox{s, stub} } @@ -159,6 +165,7 @@ func TestCaps(t *testing.T) { none := map[backend.Feature]string{ backend.FeatureEgressProxy: "emulated", // reviewed backend.FeatureSSH: "emulated", // reviewed + backend.FeaturePortsAll: "emulated", // reviewed }[f] if none == "" { none = "none" @@ -174,9 +181,11 @@ func TestCaps(t *testing.T) { if err := r.Require(s, "devvm-x", backend.FeatureSSH); err != nil { t.Errorf("ssh: %v", err) } - err := r.Require(s, "devvm-x", backend.VMSpec{Ports: backend.Ports{All: true}}.Features()...) - if got := names(err); got != "backend_lacks backend=smolvm feature=ports-all vm=devvm-x" { - t.Errorf("every port: %s", got) + if err := r.Require(s, "devvm-x", backend.VMSpec{Ports: backend.Ports{All: true}}.Features()...); err != nil { + t.Errorf("every port: %v", err) + } + if got := names(r.Require(s, "devvm-x", backend.FeatureAgentToggle)); got != "backend_lacks backend=smolvm feature=agent-toggle vm=devvm-x" { + t.Errorf("agent toggle: %s", got) } } @@ -207,8 +216,9 @@ func TestPortArgs(t *testing.T) { if got, err := portArgs("v", backend.Ports{}); err != nil || got != nil { t.Errorf("none: %q, %v", got, err) } - if _, err := portArgs("v", backend.Ports{All: true}); names(err) != "backend_lacks backend=smolvm feature=ports-all vm=v" { - t.Errorf("all: %v", err) + // Every port is its forwarder's: none of smolvm's. + if got, err := portArgs("v", backend.Ports{All: true}); err != nil || got != nil { + t.Errorf("all: %q, %v", got, err) } // One of smolvm's 64 is the VM's ssh. if _, err := portArgs("v", backend.Ports{Ranges: []backend.PortRange{{From: 3000, To: 3062}}}); err != nil { diff --git a/internal/backend/smolvm/start.go b/internal/backend/smolvm/start.go index ff59abe3..351bef00 100644 --- a/internal/backend/smolvm/start.go +++ b/internal/backend/smolvm/start.go @@ -10,11 +10,13 @@ import ( "maps" "net/netip" "os" + "os/exec" "path/filepath" "slices" "strconv" "strings" "syscall" + "time" "github.com/w3cj/devvm/internal/backend" "github.com/w3cj/devvm/internal/msg" @@ -52,7 +54,8 @@ const ( // in no process's arguments. A machine that // forwards an SSH agent forwards c.AgentSocket, or the user's // (SSH_AUTH_SOCK). With c.SSH its ssh is forwarded (sshForward) and -// services.sh runs its sshd; without, the forward goes. +// services.sh runs its sshd; without, the forward goes. A VM that +// forwards every port gets its forwarder once its sshd runs (forward). func (s *Smolvm) Start(ctx context.Context, vm string, c backend.Confinement) error { proxy := c.Net == backend.NetProxy if proxy { @@ -198,11 +201,77 @@ func (s *Smolvm) Start(ctx context.Context, vm string, c backend.Confinement) er if err := s.services(ctx, vm, sshd); err != nil { return err } - if r.SSHPort == 0 { - return nil + if r.SSHPort > 0 { + r.SSHUp, r.NoSSHD = !noSSHD, noSSHD + if err := s.writeRecord(vm, r); err != nil { + return err + } } - r.SSHUp, r.NoSSHD = !noSSHD, noSSHD - return s.writeRecord(vm, r) + if r.PortsAll { + s.forward(ctx, vm, r, c) + } + return nil +} + +// forward starts the forwarder of a VM that forwards every port, once its +// sshd runs (forward.go): its host key read through smolvm, and never on +// its own ssh's, proxy's or decider's port. One that can't start is +// warned about: the VM runs on. +func (s *Smolvm) forward(ctx context.Context, vm string, r record, c backend.Confinement) { + if !r.SSHUp { + s.Warn(msg.SmolvmPortsNoSSH(vm)) + return + } + failed := func() { s.Warn(msg.SmolvmPortsFailed(s.Forwards.Log(vm), vm)) } + out, err := vmOutput(ctx, s.Runner, func(ctx context.Context) *exec.Cmd { + return s.smolvm(ctx, "machine", "exec", "--name", vm, "--", "cat", "/etc/ssh/ssh_host_ed25519_key.pub") + }) + key, ok := hostKey(out) + name, _, uerr := s.user() + if err != nil || !ok || uerr != nil { + failed() + return + } + spec := forwardSpec{ + lifeline: s.Lifeline(ctx, vm), user: name, key: s.sshKey(vm), hostKey: key, sshPort: r.SSHPort, + reserve: []int{r.SSHPort, c.ProxyPort, deciderPort(c.Decider)}, + } + if spec.lifeline == "" || s.Forwards.Start(vm, spec) != nil { + failed() + } +} + +// What devvm reads of what the VM prints, and how long it waits for it: +// root in the VM decides both. +const ( + vmOutputMax = 64 << 10 + vmOutputTimeout = 30 * time.Second +) + +// vmOutput runs the command mk makes, whose output the VM makes, through +// r, returning at most vmOutputMax bytes of it and waiting vmOutputTimeout +// at most. +func vmOutput(ctx context.Context, r Runner, mk func(context.Context) *exec.Cmd) ([]byte, error) { + ctx, cancel := context.WithTimeout(ctx, vmOutputTimeout) + defer cancel() + out := &capped{max: vmOutputMax} + cmd := mk(ctx) + cmd.Stdout, cmd.WaitDelay = out, time.Second + err := r.Attach(cmd) + return out.Bytes(), err +} + +// capped keeps the first max bytes written to it. +type capped struct { + bytes.Buffer + max int +} + +func (w *capped) Write(p []byte) (int, error) { + if room := w.max - w.Len(); room > 0 { + w.Buffer.Write(p[:min(len(p), room)]) + } + return len(p), nil } // sshdProbe answers "sshd" when the machine's image has sshd, else "none". @@ -212,7 +281,9 @@ const sshdProbe = `if [ -x /usr/sbin/sshd ] || command -v sshd >/dev/null 2>&1; // before devvm installed one), asked before services.sh runs, so no other // failure reads as it; one that can't say stops it. func (s *Smolvm) lacksSSHD(ctx context.Context, vm string) (bool, error) { - out, err := s.Runner.Output(s.smolvm(ctx, "machine", "exec", "--name", vm, "--", "sh", "-c", sshdProbe)) + out, err := vmOutput(ctx, s.Runner, func(ctx context.Context) *exec.Cmd { + return s.smolvm(ctx, "machine", "exec", "--name", vm, "--", "sh", "-c", sshdProbe) + }) switch strings.TrimSpace(string(out)) { case "none": return true, nil diff --git a/internal/cli/root.go b/internal/cli/root.go index 2e5d0739..23ef21f1 100644 --- a/internal/cli/root.go +++ b/internal/cli/root.go @@ -40,7 +40,7 @@ func NewRoot(u *ui.UI) *cobra.Command { addUpFlags(root, uf) addVersion(root) root.AddCommand(newBuildCmd(u, g), newRebuildCmd(u, g), newImagesCmd(u, g), newGCCmd(u, g), newLayerCmd(u), newSetupCmd(u), newMsgCmd(u), - newRestartCmd(u, g), newStopCmd(u), newRemoveCmd(u, g), newUpdateCmd(u, g), newAdoptCmd(u), newExportCmd(u), newRmCmd(u), newLsCmd(u), newLogCmd(u), newPolicyCmd(u), newNetworkCmd(u), newSSHCmd(u), newCodeCmd(u), newSSHAgentCmd(u), newGitProtectCmd(u), newPortsCmd(u), newSizeCmd(u), newDoctorCmd(u, g), newLimactlCmd(u), newQEMUCmd(u), newProxyCmd(u), newRefreshToolsCmd(u), newSecretCmd(u), + newRestartCmd(u, g), newStopCmd(u), newRemoveCmd(u, g), newUpdateCmd(u, g), newAdoptCmd(u), newExportCmd(u), newRmCmd(u), newLsCmd(u), newLogCmd(u), newPolicyCmd(u), newNetworkCmd(u), newSSHCmd(u), newCodeCmd(u), newSSHAgentCmd(u), newGitProtectCmd(u), newPortsCmd(u), newSizeCmd(u), newDoctorCmd(u, g), newLimactlCmd(u), newQEMUCmd(u), newProxyCmd(u), newSmolvmPortsCmd(u), newRefreshToolsCmd(u), newSecretCmd(u), newAuthCmd(u), newVersionCmd(u), newCompletionCmd(u)) addCompletions(root, u) return root diff --git a/internal/cli/script_test.go b/internal/cli/script_test.go index e21ab5b1..7ff41a76 100644 --- a/internal/cli/script_test.go +++ b/internal/cli/script_test.go @@ -59,6 +59,8 @@ func sandbox(env *testscript.Env, bin, stubs string) error { // VMs' proxies follow a stub hostagent that's gone before they // look: stop them with the sandbox. _ = exec.CommandContext(context.Background(), "pkill", "-f", "_proxy -listen .* -lifeline "+root+"/").Run() //nolint:gosec,forbidigo // the test's own folder; a cleanup, after the scripts' contexts end + // And smolvm VMs' port forwarders. + _ = exec.CommandContext(context.Background(), "pkill", "-f", "_smolvm-ports -vm .* -lifeline "+root+"/").Run() //nolint:gosec,forbidigo // the test's own folder; a cleanup, after the scripts' contexts end _ = os.RemoveAll(root) }) diff --git a/internal/cli/smolvmports.go b/internal/cli/smolvmports.go new file mode 100644 index 00000000..b8fd86f3 --- /dev/null +++ b/internal/cli/smolvmports.go @@ -0,0 +1,44 @@ +package cli + +import ( + "io/fs" + + "github.com/spf13/cobra" + + "github.com/w3cj/devvm/assets" + "github.com/w3cj/devvm/internal/backend/smolvm" + "github.com/w3cj/devvm/internal/msg" + "github.com/w3cj/devvm/internal/netpolicy" + "github.com/w3cj/devvm/internal/paths" + "github.com/w3cj/devvm/internal/ui" +) + +// newSmolvmPortsCmd is devvm _smolvm-ports: the port forwarder of a smolvm +// VM that forwards every port, which the backend starts detached. Hidden: +// it's not for users. Its flags are the forwarder's own, parsed by +// smolvm.ForwardMain; its log lines are data, written to devvm's stderr. +// It never forwards a port devvm records for a VM (netpolicy.UsedPorts). +func newSmolvmPortsCmd(u *ui.UI) *cobra.Command { + return &cobra.Command{ + Use: "_smolvm-ports [flags]", + Short: "Forward a smolvm VM's ports", + Hidden: true, + DisableFlagParsing: true, + RunE: func(cmd *cobra.Command, args []string) error { + fail := func(err error) { u.Die(msg.SmolvmForwarderFailed(err.Error()).Because(err)) } + d, err := paths.FromEnv() + if err != nil { + fail(err) + } + script, err := fs.ReadFile(assets.FS, "smolvm/ports.sh") + if err != nil { + fail(err) + } + reserved := func() (map[int]bool, error) { return netpolicy.UsedPorts(d) } + if err := smolvm.ForwardMain(cmd.Context(), args, script, reserved, u.Stderr()); err != nil { + fail(err) + } + return nil + }, + } +} diff --git a/internal/msg/docs.go b/internal/msg/docs.go index 6d04eb88..f8340f42 100644 --- a/internal/msg/docs.go +++ b/internal/msg/docs.go @@ -23,6 +23,8 @@ var docs = map[string]string{ //nolint:gosec // message IDs and pages, not crede "smolvm_mount_colon": "smolvm#what-devvm-sets-on-a-vm", "smolvm_too_many_ports": "smolvm#what-devvm-sets-on-a-vm", "smolvm_no_agent": "smolvm#what-devvm-sets-on-a-vm", + "smolvm_ports_no_ssh": "smolvm#every-port", + "smolvm_ports_failed": "smolvm#every-port", "smolvm_port_ssh": "smolvm#ssh-for-editors", "smolvm_no_ssh": "smolvm#ssh-for-editors", "smolvm_no_sshd": "smolvm#ssh-for-editors", diff --git a/internal/msg/messages_gen.go b/internal/msg/messages_gen.go index e3d5a21c..6cc739ae 100644 --- a/internal/msg/messages_gen.go +++ b/internal/msg/messages_gen.go @@ -1584,6 +1584,11 @@ func SmolvmBrokenFix(fix string) M { return M{id: "smolvm_broken_fix", vals: []val{{"fix", fix}}} } +// SmolvmForwarderFailed is [smolvm_forwarder_failed]: "smolvm port forwarder: {{.reason}}" +func SmolvmForwarderFailed(reason string) M { + return M{id: "smolvm_forwarder_failed", vals: []val{{"reason", reason}}} +} + // SmolvmFromRegistryOnly is [smolvm_from_registry_only]: "the smolvm backend builds only from registry images, and {{.image}} is only in Docker: push it to a registry" func SmolvmFromRegistryOnly(image string) M { return M{id: "smolvm_from_registry_only", vals: []val{{"image", image}}} @@ -1644,6 +1649,16 @@ func SmolvmPortSSH(port string, vm string) M { return M{id: "smolvm_port_ssh", vals: []val{{"port", port}, {"vm", vm}}} } +// SmolvmPortsFailed is [smolvm_ports_failed]: "forwarding {{.vm}}'s ports didn't start: see {{.log}}" +func SmolvmPortsFailed(log string, vm string) M { + return M{id: "smolvm_ports_failed", vals: []val{{"log", log}, {"vm", vm}}} +} + +// SmolvmPortsNoSSH is [smolvm_ports_no_ssh]: "{{.vm}} runs without ssh, so none of its ports are forwarded" +func SmolvmPortsNoSSH(vm string) M { + return M{id: "smolvm_ports_no_ssh", vals: []val{{"vm", vm}}} +} + // SmolvmScriptFailed is [smolvm_script_failed]: "{{.script}} failed in {{.vm}}, kept stopped: look inside with smolvm machine start --name {{.vm}}, then smolvm machine shell --name {{.vm}}; the next build, or devvm gc, deletes it" func SmolvmScriptFailed(script string, vm string) M { return M{id: "smolvm_script_failed", vals: []val{{"script", script}, {"vm", vm}}} @@ -2307,6 +2322,7 @@ var specs = map[string]spec{ "size_pending": {fields: []string{"size", "vm"}}, "smolvm_broken": {}, "smolvm_broken_fix": {fields: []string{"fix"}}, + "smolvm_forwarder_failed": {fields: []string{"reason"}}, "smolvm_from_registry_only": {fields: []string{"image"}}, "smolvm_host_unsupported": {fields: []string{"host"}}, "smolvm_machine_foreign": {fields: []string{"vm"}}, @@ -2319,6 +2335,8 @@ var specs = map[string]spec{ "smolvm_old": {fields: []string{"version"}}, "smolvm_old_fix": {fields: []string{"fix", "version"}}, "smolvm_port_ssh": {fields: []string{"port", "vm"}}, + "smolvm_ports_failed": {fields: []string{"log", "vm"}}, + "smolvm_ports_no_ssh": {fields: []string{"vm"}}, "smolvm_script_failed": {fields: []string{"script", "vm"}}, "smolvm_ssh_port_forwarded": {fields: []string{"port", "vm"}}, "smolvm_too_many_ports": {fields: []string{"asked", "max", "vm"}}, diff --git a/internal/netpolicy/netpolicy_test.go b/internal/netpolicy/netpolicy_test.go index c8b15685..134fef57 100644 --- a/internal/netpolicy/netpolicy_test.go +++ b/internal/netpolicy/netpolicy_test.go @@ -166,7 +166,7 @@ func TestChoose(t *testing.T) { } } -// usedPorts lists the ports VMs have; freePort avoids them. +// UsedPorts lists the ports VMs have; freePort avoids them. func TestFreePort(t *testing.T) { d, st := sandbox(t, "base") if err := st.Set(KeySSHPort, "23456"); err != nil { @@ -175,9 +175,9 @@ func TestFreePort(t *testing.T) { if err := st.Set(KeyProxyPort, "34567"); err != nil { t.Fatal(err) } - used, err := usedPorts(d) + used, err := UsedPorts(d) if err != nil || !used[23456] || !used[34567] || len(used) != 2 { - t.Errorf("usedPorts = %v, %v", used, err) + t.Errorf("UsedPorts = %v, %v", used, err) } // And the ports VMs forward, wanted or set: all and none name none. for k, v := range map[string]string{keyPorts: "5173,40000-40002", keyPortsSet: "41000, bad,9-1"} { @@ -185,9 +185,9 @@ func TestFreePort(t *testing.T) { t.Fatal(err) } } - used, err = usedPorts(d) + used, err = UsedPorts(d) if err != nil || len(used) != 7 || !used[5173] || !used[40000] || !used[40002] || !used[41000] { - t.Errorf("usedPorts with forwards = %v, %v", used, err) + t.Errorf("UsedPorts with forwards = %v, %v", used, err) } if err := st.Set(keyPorts, "all"); err != nil { t.Fatal(err) diff --git a/internal/netpolicy/proxy.go b/internal/netpolicy/proxy.go index 4b398d61..7b98f8ff 100644 --- a/internal/netpolicy/proxy.go +++ b/internal/netpolicy/proxy.go @@ -402,7 +402,7 @@ func logged(path string, before int64, want []byte) bool { // freePort returns a loopback port from 20000 to 59999 nothing listens on // and no VM has. func (p *Proxy) freePort() (int, error) { - used, err := usedPorts(p.Dirs) + used, err := UsedPorts(p.Dirs) if err != nil { return 0, err } @@ -415,8 +415,10 @@ func (p *Proxy) freePort() (int, error) { return 0, errors.New("no free port on 127.0.0.1") } -// usedPorts returns the ssh, proxy and decider ports VMs have. -func usedPorts(d paths.Dirs) (map[int]bool, error) { +// UsedPorts returns the ssh, proxy and decider ports VMs have, and the +// ports they list to forward: what a new one avoids, and what a VM that +// forwards every port never takes (smolvm's). +func UsedPorts(d paths.Dirs) (map[int]bool, error) { ents, err := os.ReadDir(d.VMs()) if errors.Is(err, os.ErrNotExist) { return nil, nil diff --git a/internal/platform/listen_other.go b/internal/platform/listen_other.go new file mode 100644 index 00000000..a439d955 --- /dev/null +++ b/internal/platform/listen_other.go @@ -0,0 +1,14 @@ +//go:build !unix + +package platform + +import ( + "context" + "errors" + "net" +) + +// ListenExclusive is unsupported here. +func ListenExclusive(context.Context, string, string) (net.Listener, error) { + return nil, errors.New("listening without address reuse isn't supported on this system") +} diff --git a/internal/platform/listen_unix.go b/internal/platform/listen_unix.go new file mode 100644 index 00000000..ab18490d --- /dev/null +++ b/internal/platform/listen_unix.go @@ -0,0 +1,27 @@ +//go:build unix + +package platform + +import ( + "context" + "net" + "syscall" +) + +// ListenExclusive listens on a TCP address without SO_REUSEADDR, which Go +// sets on every listener: with it, macOS and the BSDs let a listener on +// one address (127.0.0.1:5432) take a port another program has on every +// address (*:5432), and with it that program's connections to that +// address. Without it, the port must be free on every address. +func ListenExclusive(ctx context.Context, network, addr string) (net.Listener, error) { + lc := net.ListenConfig{Control: func(_, _ string, c syscall.RawConn) error { + var serr error + if err := c.Control(func(fd uintptr) { + serr = syscall.SetsockoptInt(int(fd), syscall.SOL_SOCKET, syscall.SO_REUSEADDR, 0) + }); err != nil { + return err + } + return serr + }} + return lc.Listen(ctx, network, addr) +} diff --git a/internal/structure/structure_test.go b/internal/structure/structure_test.go index 232a79ef..51d4ff1e 100644 --- a/internal/structure/structure_test.go +++ b/internal/structure/structure_test.go @@ -26,7 +26,7 @@ func devvm() rules { maxMethods: 24, largeTypes: map[string]large{ "internal/backend/lima.Lima": {64, "a backend: backend.Backend's 27 methods and Lima's own"}, - "internal/backend/smolvm.Smolvm": {68, "a backend: backend.Backend's 27 methods and smolvm's own"}, + "internal/backend/smolvm.Smolvm": {69, "a backend: backend.Backend's 27 methods and smolvm's own"}, "internal/backend/backendtest.Fake": {32, "backend.Backend's 27 methods and what tests ask of it"}, "internal/paths.Dirs": {34, "one method per folder or file devvm uses: a list"}, "internal/ui.UI": {40, "the one terminal: messages, prompts, status line, run log, cleanups, signals"}, diff --git a/internal/vm/env.go b/internal/vm/env.go index ffd92280..289f7cd7 100644 --- a/internal/vm/env.go +++ b/internal/vm/env.go @@ -287,6 +287,14 @@ func (e *Env) start(ctx context.Context, b backend.Backend, st *state.VM, conf b if st.Get(KeyNet) == "" { return conf, msg.VMUnfinished(vm) } + // The ports its backend forwards at each start (every port: an + // emulation on some), which it got when they were set: refused now + // unless they may still be used. + for _, f := range PortsBackend(orAll(st.Get(KeyPortsSet))).Features() { + if !e.Registry.Allowed(b, f) { + return conf, e.Registry.Require(b, vm, f) + } + } if err := e.sshConfig().ForgetHostKeys(vm); err != nil { return conf, err } diff --git a/locales/en.toml b/locales/en.toml index d2d7fffa..1d048953 100644 --- a/locales/en.toml +++ b/locales/en.toml @@ -197,6 +197,12 @@ other = "port {{.port}}, for {{.vm}}'s ssh, is one of its forwarded ports: leave [smolvm_no_agent] other = "{{.vm}} forwards an SSH agent, and SSH_AUTH_SOCK names none: start one, or set it" +[smolvm_ports_no_ssh] +other = "{{.vm}} runs without ssh, so none of its ports are forwarded" + +[smolvm_ports_failed] +other = "forwarding {{.vm}}'s ports didn't start: see {{.log}}" + [creating_from_image] other = "creating {{.vm}} from {{.image}}" @@ -1232,6 +1238,10 @@ other = "{{.vm}} has no network policy, so Claude Code's MCP servers' env values description = "reason is an error from the system or the flag parser, in English" other = "network policy proxy: {{.reason}}" +[smolvm_forwarder_failed] +description = "reason is an error from the system or the flag parser, in English" +other = "smolvm port forwarder: {{.reason}}" + [bad_secret_service] other = "DEVVM_SECRET_SERVICE can only have letters, digits, '.', '_' and '-'" diff --git a/testdata/script/doctor.txtar b/testdata/script/doctor.txtar index c07719dd..a4b99ca8 100644 --- a/testdata/script/doctor.txtar +++ b/testdata/script/doctor.txtar @@ -14,7 +14,7 @@ exec devvm doctor stdout '^FEATURE +LIMA +SMOLVM\n' stdout '^build-image +native +native\n' stdout '^egress-proxy +native +emulated\n' -stdout '^ports-all +native +none\n' +stdout '^ports-all +native +emulated\n' stdout '^agent-toggle +native +none\n' stdout '^disk +native +native\n' stdout '^docker_found\n' diff --git a/testdata/script/smolvm.txtar b/testdata/script/smolvm.txtar index aa81116d..d79c21b3 100644 --- a/testdata/script/smolvm.txtar +++ b/testdata/script/smolvm.txtar @@ -37,13 +37,33 @@ exec sh -c 'ls "$PACKS"/*/image.smolmachine' exec devvm images stdout '^base +ubuntu:26\.04@sha256:a+ +a{12} +[0-9a-f]{12} +current +\S+ +smolvm$' -# A new VM forwards every port by default, which smolvm can't: refused; -# nothing is made. +# A new VM forwards every port by default, which smolvm emulates +# (reviewed): none of smolvm's forwards; once its sshd runs, a forwarder of +# devvm's on the host reaches it over ssh (a master, offering the VM's key +# alone, its host key read through smolvm and pinned), and forwards what +# listens in the VM. +mkdir $WORK/all +cd $WORK/all +exec sh -c 'printf "0100007F:B8DF\n00000000:0050\n" > "$STUB_DIR/guest-ports"; : > "$STUB_LOG"' +exec devvm --backend smolvm --from $PIN --no-network-policy base +! stderr 'backend_unreviewed' +! stderr 'smolvm_ports' +stub_calls +stdout '^smolvm machine create( --state-dir \S+)? --name devvm-all-[0-9a-f]{14} .* -v \S+:/mnt/devvm-tools:ro$' +stdout '^smolvm machine exec( --state-dir \S+)? --name devvm-all-[0-9a-f]{14} -- cat /etc/ssh/ssh_host_ed25519_key\.pub$' +stdout '^ssh -F none -M -S \S+/data/devvm/run/smolvm-[0-9a-f]{16}\.ctl -T .* -o IdentityFile=\S+/smolvm/vms/devvm-all-[0-9a-f]{14}\.key .* -o HostKeyAlias=devvm-all-[0-9a-f]{14} .* -o PermitRemoteOpen=none -o ClearAllForwardings=yes .* -p [0-9]+ -l \S+ 127\.0\.0\.1 sh -s$' +exec sh -c 'cat "$XDG_DATA_HOME"/devvm/smolvm/vms/devvm-all-*.ports.known_hosts' +stdout '^devvm-all-[0-9a-f]{14} ssh-ed25519 AAAAstub$' +exec sh -c 'cat "$XDG_DATA_HOME"/devvm/smolvm/vms/devvm-all-*.ports.log' +stdout '^devvm ports: port 47327: forwarded$' +stdout '^devvm ports: forwarding devvm-all-[0-9a-f]{14}''s ports$' +! stdout 'port 80' +exec devvm stop +exec devvm rm -f +! exec sh -c 'ls "$XDG_DATA_HOME"/devvm/smolvm/vms/devvm-all-*' +rm $STUB_DIR/guest-ports mkdir $WORK/web cd $WORK/web -! exec devvm --backend smolvm --from $PIN --no-network-policy base -stderr '^devvm: backend_lacks backend=smolvm feature=ports-all vm=devvm-web-[0-9a-f]{14}$' -! exists $VMS # Listed ports: made from base's pack with everything set (a pack would # give it its build machine's), started, set up, then the shell. @@ -61,10 +81,7 @@ exec devvm ls stdout '^devvm-web-[0-9a-f]{14} +Running .*image=base +\S+ +off +smolvm +\S+/web$' grep '^Host devvm-web devvm-web-[0-9a-f]{14}$' $XDG_CONFIG_HOME/devvm/ssh_config -# What smolvm lacks, in one line naming the VM: every port, agent -# forwarding changed. -! exec devvm ports all -stderr '^devvm: backend_lacks backend=smolvm feature=ports-all vm=devvm-web-[0-9a-f]{14}$' +# What smolvm lacks, in one line naming the VM: agent forwarding changed. ! exec devvm ssh-agent on stderr '^devvm: backend_lacks backend=smolvm feature=agent-toggle vm=devvm-web-[0-9a-f]{14}$' exec sh -c 'cat "$VMS"/devvm-web-*' diff --git a/testdata/stubs/ssh b/testdata/stubs/ssh index c9cbddb6..6ef82b00 100755 --- a/testdata/stubs/ssh +++ b/testdata/stubs/ssh @@ -3,10 +3,18 @@ # VM. Logs every call to $STUB_LOG, and runs the git command it's given # here, on $STUB_DIR/vmfs/DIR (the VM's files, as the limactl stub keeps # them). With $STUB_DIR/ssh-fails, or for anything else, it fails as ssh -# does. +# does. A master connection (-M, a smolvm VM's port forwarder's) reads the script it's +# fed, answers it with $STUB_DIR/guest-ports (what listens in the VM, as /proc/net/tcp has +# it) and ".", then waits to be stopped. set -euo pipefail echo "ssh $*" >> "$STUB_LOG" [[ ! -e $STUB_DIR/ssh-fails ]] || exit 255 +if [[ " $* " == *" -M "* ]]; then + cat > /dev/null + [[ ! -f $STUB_DIR/guest-ports ]] || cat "$STUB_DIR/guest-ports" + echo . + exec sleep 300 +fi cmd=${*: -1} case $cmd in "git-receive-pack "* | "git-upload-pack "*) diff --git a/tests/e2e.sh b/tests/e2e.sh index bcc99f5e..46cf672c 100755 --- a/tests/e2e.sh +++ b/tests/e2e.sh @@ -24,13 +24,15 @@ # --backend smolvm # the smolvm backend's own section instead (experimental): base and a layer built as # packs, a project VM's mounts, size, ports, Docker and agent forwarding, a node VM's -# shared tools, what it refuses (every port, agent toggling), ssh for editors' -# emulation (pinned host keys of each VM's own, its own key alone, no forwarding out -# even past a hostile sshd, devvm ssh and code, a --clone VM's push and fetch), -# network policy's emulation (nothing but the proxy, DNS kept on this machine, failing -# closed, the policy, ssh opening no way out), and that no machine without the -# sandbox's label is touched. Its machines share your smolvm (macOS): it deletes only -# those it made, with the sandbox's label. +# shared tools, what it refuses (agent toggling), ssh for editors' emulation (pinned +# host keys of each VM's own, its own key alone, no forwarding out even past a hostile +# sshd, devvm ssh and code, a --clone VM's push and fetch), network policy's emulation +# (nothing but the proxy, DNS kept on this machine, failing closed, the policy, ssh +# opening no way out), every port's (servers on the VM's loopback or all its addresses +# reach this machine's loopback alone, never a port of this machine's or devvm's, no +# way out with network policy), +# and that no machine without the sandbox's label is touched. Its machines share your +# smolvm (macOS): it deletes only those it made, with the sandbox's label. # The sandbox: Lima home ~/.lt-e2e-go (or $DEVVM_E2E_LIMA_HOME), state under /tmp/devvm-go-e2e. It refuses # to run against ~/.lima or devvm's own Lima home, deletes only the VMs it created, and uses no real # tokens. devvm is built from this checkout into the sandbox, with its files next to it. @@ -122,7 +124,7 @@ cleanup() { if [[ $backend == smolvm ]]; then # Only a machine with the sandbox's label, and the image's pack. [[ -z $(smol_status "$n") ]] || SMOLVM_USAGE=0 smolvm machine delete --name "$n" -f >/dev/null 2>&1 - rm -f "$XDG_DATA_HOME/devvm/smolvm/vms/$n.json" "$XDG_DATA_HOME/devvm/smolvm/vms/$n.proxy" + rm -f "$XDG_DATA_HOME/devvm/smolvm/vms/$n.json" "$XDG_DATA_HOME/devvm/smolvm/vms/$n.proxy" "$XDG_DATA_HOME/devvm/smolvm/vms/$n.ports."* [[ $n != devvm-img-* ]] || rm -rf "$XDG_DATA_HOME/devvm/smolvm/images/${n#devvm-img-}" else limactl delete -f "$n" >/dev/null 2>&1 @@ -942,13 +944,6 @@ check "a failed script keeps its machine, stopped, and says how to look inside" [[ \$(smol_status devvm-img-$kx) == stopped ]] && '$D' ${S[*]} images rm '$kx' /dev/null 2>&1 && [[ -z \$(smol_status devvm-img-$kx) ]]" rm -f "$layers/e2esmolfail.sh" -section "smolvm: what it refuses" -r=$(newproj smolrefused) -check "every port (the default), in one line naming the VM" bash -c "cd '$r' && - ! DEVVM_MESSAGES=names '$D' ${S[*]} --no-network-policy base '$work/last.log' 2>&1 && - grep -qE '^devvm: backend_lacks backend=smolvm feature=ports-all vm=devvm-smolrefused-[0-9a-f]{14}$' '$work/last.log' && - [[ -z \$(vm_of '$r') ]]" - section "smolvm: a base project" p=$(newproj smolweb); git -C "$p" init -q launch "$p" 'pwd; id -un; echo e2e-shell-ran' "${S[@]}" --no-network-policy --ports 47180 --cpus 2 --memory 3 --disk 120 base @@ -973,8 +968,7 @@ SMOLVM_USAGE=0 smolvm machine exec --name "$vm" -d -- perl -MIO::Socket::INET -e '$s = IO::Socket::INET->new(LocalAddr => "0.0.0.0:47180", Listen => 5, ReuseAddr => 1) or die; while ($c = $s->accept) { close $c }' \ /dev/null 2>&1 check "the listed port reaches this machine's loopback" bash -c 'for i in $(seq 20); do nc -z 127.0.0.1 47180 && exit 0; sleep 1; done; exit 1' -check "every port and turning agent forwarding on are refused in one line" bash -c "cd '$p' && - ! DEVVM_MESSAGES=names '$D' ports all '$work/e' && grep -qx 'devvm: backend_lacks backend=smolvm feature=ports-all vm=$vm' '$work/e' && +check "turning agent forwarding on is refused in one line" bash -c "cd '$p' && ! DEVVM_MESSAGES=names '$D' ssh-agent on '$work/e' && grep -qx 'devvm: backend_lacks backend=smolvm feature=agent-toggle vm=$vm' '$work/e' && grep -qx net=off '$vms/$vm'" check "its process listens on its listed port (the control) and its ssh forward's, nothing else" smol_listens_only "$vm" 47180 "$(sed -n 's/^ *"ssh_port": \([0-9]*\).*/\1/p' "$XDG_DATA_HOME/devvm/smolvm/vms/$vm.json")" @@ -1348,9 +1342,12 @@ smolnet_direct_open() { # or takes every one over and answers it itself, 418 (take: verdict 2, the fail-closed probes' # positive control); its pid in $fake. It fails, naming the port, unless it listens within 10 s. smolnet_fake_decider() { - perl -MIO::Socket::INET -e '$m = shift; $p = shift; $s = IO::Socket::INET->new(LocalAddr => "127.0.0.1:$p", Listen => 16, ReuseAddr => 1) or die "$@\n"; + # Each answer's connection is shut for writing, then read to its end (2 s at most) before it's + # closed: closing it with smolvm's bytes unread would reset it, losing the answer at times. + perl -MIO::Socket::INET -e '$SIG{ALRM} = sub {}; $| = 1; $m = shift; $p = shift; $s = IO::Socket::INET->new(LocalAddr => "127.0.0.1:$p", Listen => 16, ReuseAddr => 1) or die "$@\n"; while ($c = $s->accept) { sysread($c, $b, 4096); print $c "\x07garbage" if $m eq "garbage"; print $c "\x00" if $m eq "allow"; - print $c "\x02HTTP/1.1 418 squatter\r\nContent-Length: 0\r\nConnection: close\r\n\r\n" if $m eq "take"; close $c }' "$1" "$dp" >/dev/null 2>"$work/fake.log" & + print $c "\x02HTTP/1.1 418 squatter\r\nContent-Length: 0\r\nConnection: close\r\n\r\n" if $m eq "take"; $c->flush; + shutdown($c, 1); alarm 2; 1 while sysread($c, $b, 4096); alarm 0; close $c }' "$1" "$dp" >/dev/null 2>"$work/fake.log" & fake=$! for _ in $(seq 20); do lsof -t -a -p "$fake" -iTCP:"$dp" -sTCP:LISTEN >/dev/null 2>&1 && return 0 @@ -1543,6 +1540,154 @@ check "rm -f deletes it, its proxy and its state" bash -c "cd '$np' && ${U[*]} ' kill "$listener" 2>/dev/null; [[ -z ${udp_listener:-} ]] || kill "$udp_listener" 2>/dev/null; listener="" udp_listener="" rm -f "$work/listener.auth" +section "smolvm: every port" +# The emulation's guarantee (reviewed): every port a VM listens on, on its loopback or all its +# addresses, IPv4 or IPv6, reaches this machine's loopback, and only its loopback; never a port this +# machine has on any address, one below 1024, or one devvm records for a VM, even while it's free; +# and forwarding opens the VM no way out (with network policy, nothing past its proxy). +# smolpa_serve VM HOST PORT: a server in the VM, as root, answering "vm-PORT" on HOST (an address of +# the VM's; :: takes IPv4 too), left running. +smolpa_serve() { SMOLVM_USAGE=0 smolvm machine exec --name "$1" -d -- perl -MIO::Socket::IP -e '($h, $p) = @ARGV; + $s = IO::Socket::IP->new(LocalHost => $h, LocalPort => $p, Listen => 5, ReuseAddr => 1, V6Only => ($h eq "::" ? 0 : 1)) or die "$@"; + while ($c = $s->accept) { print $c "vm-$p\n"; close $c }' "$2" "$3" /dev/null 2>&1; } +# smolpa_answers PORT WANT: this machine's 127.0.0.1 and ::1 answer WANT on PORT, within 15 s. +smolpa_answers() { local a b; for _ in $(seq 15); do + a=$(nc -w 2 127.0.0.1 "$1" /dev/null); b=$(nc -6 -w 2 ::1 "$1" /dev/null) + [[ $a == "$2" && $b == "$2" ]] && return 0; sleep 1; done + echo "127.0.0.1: ${a:-nothing}, ::1: ${b:-nothing}"; return 1; } +# smolpa_closed PORT: nothing answers on this machine's loopback on PORT, within 10 s. +smolpa_closed() { for _ in $(seq 10); do + nc -z 127.0.0.1 "$1" 2>/dev/null || nc -6 -z ::1 "$1" 2>/dev/null || return 0; sleep 1; done + echo "port $1 still answers"; return 1; } +# smolpa_forwarder VM: its forwarder's pid. smolpa_log VM: its forwarder's log. +smolpa_forwarder() { pgrep -f -- "[_]smolvm-ports -vm $1 " | head -1; } +smolpa_log() { cat "$XDG_DATA_HOME/devvm/smolvm/vms/$1.ports.log" 2>/dev/null; } +# smolpa_loopback VM PORT...: its forwarder listens on each PORT, and everything it listens on is on +# this machine's loopback alone. +smolpa_loopback() { local vm=$1 pid l p; shift + pid=$(smolpa_forwarder "$vm"); [[ -n $pid ]] || { echo "no forwarder"; return 1; } + l=$(lsof -nP -a -p "$pid" -iTCP -sTCP:LISTEN 2>/dev/null | awk 'NR > 1 { print $9 }' | sort -u); echo "$l" + for p in "$@"; do grep -qx "127\.0\.0\.1:$p" <<<"$l" && grep -qx "\[::1\]:$p" <<<"$l" || return 1; done + ! grep -vE '^(127\.0\.0\.1|\[::1\]):[0-9]+$' <<<"$l"; } +# smolpa_master VM: its forwarder's ssh reads no configuration of yours, offers the VM's key alone, +# pins its host key and asks for no forwarding. +smolpa_master() { local m; m=$(pgrep -fl -- "ssh -F none -M .*HostKeyAlias=$1 " | head -1); echo "$m" + [[ -n $m && $m == *"IdentityAgent=none"* && $m == *"StrictHostKeyChecking=yes"* && $m == *"ClearAllForwardings=yes"* && + $m == *"PermitRemoteOpen=none"* && $m == *"ForwardAgent=no"* ]] && ! grep -qE ' -[RLDAXY]( |$)' <<<"$m"; } +export -f smolpa_answers smolpa_closed smolpa_forwarder smolpa_log +pa=$(newproj smolall) +(cd "$pa" && printf 'exit\n' | DEVVM_MESSAGES=names "$D" "${S[@]}" --no-network-policy --no-git-protect base >"$work/last.log" 2>&1) +vm=$(vm_of "$pa"); [[ -z $vm ]] || created+=("$vm") +check "the VM forwards every port (the default), with a forwarder of devvm's, none of smolvm's but its ssh's" bash -c " + [[ -n '$vm' && \$(smol_status '$vm') == running ]] && ! grep -q backend_unreviewed '$work/last.log' && + ! grep -q smolvm_ports '$work/last.log' && [[ -n \$(smolpa_forwarder '$vm') ]] && smolpa_log '$vm' | grep -q \"forwarding $vm's ports\"" +check "... its machine's process listening on its ssh forward alone" smol_listens_only "$vm" "$(sed -n 's/^ *"ssh_port": \([0-9]*\).*/\1/p' "$XDG_DATA_HOME/devvm/smolvm/vms/$vm.json")" +check "... its ssh master reading no config of yours, the VM's key alone, its host key pinned, no forwarding asked for" smolpa_master "$vm" +smolpa_serve "$vm" 127.0.0.1 47391; smolpa_serve "$vm" ::1 47392; smolpa_serve "$vm" 0.0.0.0 47393; smolpa_serve "$vm" :: 47394 +check "a server on the VM's loopback alone reaches this machine's, at 127.0.0.1 and ::1" smolpa_answers 47391 vm-47391 +check "... one on its IPv6 loopback alone" smolpa_answers 47392 vm-47392 +check "... one on all its IPv4 addresses, and one on all its addresses" bash -c "smolpa_answers 47393 vm-47393 && smolpa_answers 47394 vm-47394" +check "the forwarder listens on this machine's loopback alone" smolpa_loopback "$vm" 47391 47392 47393 47394 +# This machine's own program, on every address, and the VM's server on the same port. +perl -MIO::Socket::INET -e '$s = IO::Socket::INET->new(LocalAddr => "0.0.0.0:47395", Listen => 5, ReuseAddr => 1) or die; + while ($c = $s->accept) { print $c "host-47395\n"; close $c }' /dev/null 2>&1 & +hostprog=$! +sleep 0.5 +smolpa_serve "$vm" 127.0.0.1 47395; smolpa_serve "$vm" 0.0.0.0 1023 +check "a port this machine has on any address stays its own, and one below 1024 isn't forwarded" bash -c " + for _ in \$(seq 15); do smolpa_log '$vm' | grep -q 'port 47395: not forwarded' && break; sleep 1; done + smolpa_log '$vm' | grep -q 'port 47395: not forwarded' && [[ \$(nc -w 2 127.0.0.1 47395 /dev/null; wait "$hostprog" 2>/dev/null; hostprog="" +# smolpa_hostserve ADDR PORT: this machine's own program on ADDR (:: takes IPv4 too, as Node's and +# Go's servers do), answering "host-PORT", left running; its pid in hostprogs. +hostprogs=() +smolpa_hostserve() { perl -MIO::Socket::IP -e '($h, $p) = @ARGV; + $s = IO::Socket::IP->new(LocalHost => $h, LocalPort => $p, Listen => 5, ReuseAddr => 1, V6Only => ($h eq "::" ? 0 : 1)) or die "$@"; + while ($c = $s->accept) { print $c "host-$p\n"; close $c }' "$1" "$2" /dev/null 2>&1 & + hostprogs+=($!); } +# smolpa_hosts_kept: each of this machine's programs keeps its port, the VM's server on it isn't +# forwarded, and localhost never reaches two programs: on 127.0.0.1 alone (::1 stays closed), on +# ::1 alone (127.0.0.1 stays closed), and on every address, IPv4 and IPv6 at once. +smolpa_hosts_kept() { local vm=$1 p + for _ in $(seq 15); do + smolpa_log "$vm" | grep -q 'port 47403: not forwarded' && smolpa_log "$vm" | grep -q 'port 47402: not forwarded' && break; sleep 1; done + smolpa_log "$vm" | grep -E 'port 4740[123]' + for p in 47401 47402 47403; do smolpa_log "$vm" | grep -q "port $p: not forwarded" || { echo "port $p: no refusal logged"; return 1; }; done + if [[ $(nc -w 2 127.0.0.1 47401 /dev/null; then + echo "47401 not the host's alone"; return 1; fi + if [[ $(nc -6 -w 2 ::1 47402 /dev/null; then + echo "47402 not the host's alone"; return 1; fi + [[ $(nc -w 2 127.0.0.1 47403 /dev/null; wait "${hostprogs[@]}" 2>/dev/null; hostprogs=() +# smolpa_not_loopback VM: a server on the VM's own network address alone isn't forwarded, nor a +# port devvm records for another VM (its listed ports), free on this machine; one on the VM's +# loopback, started after them, is (the control). +smolpa_not_loopback() { local vm=$1 ip r=0 + ip=$(SMOLVM_USAGE=0 smolvm machine exec --name "$vm" -- perl -MIO::Socket::INET -e \ + 'print IO::Socket::INET->new(PeerAddr => "100.96.0.1:9", Proto => "udp")->sockhost' /dev/null) + [[ $ip =~ ^[0-9.]+$ && $ip != 127.* ]] || { echo "the VM's address: ${ip:-none}"; return 1; } + printf 'net=off\nports=47406\n' > "$vms/devvm-e2e-reserved" + smolpa_serve "$vm" "$ip" 47404; smolpa_serve "$vm" 0.0.0.0 47406; sleep 2; smolpa_serve "$vm" 127.0.0.1 47405 + smolpa_answers 47405 vm-47405 || { echo "the control isn't forwarded"; r=1; } + smolpa_closed 47404 && smolpa_closed 47406 || r=1 + ! smolpa_log "$vm" | grep -E 'port (47404|47406)' || r=1 + rm -f "$vms/devvm-e2e-reserved"; return "$r"; } +check "a server on the VM's own address alone isn't forwarded, nor a port another VM lists, while it's free (a loopback server is, the control)" smolpa_not_loopback "$vm" +check "a server that stops: its forward goes; the others stay" bash -c " + SMOLVM_USAGE=0 smolvm machine exec --name '$vm' -- pkill -f '0.0.0.0 47393' /dev/null 2>&1 && + [[ -z \$(smolpa_forwarder '$vm') ]] && smolpa_closed 47391 && smolpa_closed 47394" +check "started again, it has a new forwarder, which forwards a server started then" bash -c "cd '$pa' && + printf 'exit\n' | '$D' >'$work/last.log' 2>&1 && [[ -n \$(smolpa_forwarder '$vm') ]] && + SMOLVM_USAGE=0 smolvm machine exec --name '$vm' -d -- perl -MIO::Socket::IP -e '\$s = IO::Socket::IP->new(LocalHost => q(127.0.0.1), LocalPort => 47396, Listen => 5) or die; while (\$c = \$s->accept) { print \$c qq(vm-47396\n); close \$c }' /dev/null 2>&1 && + smolpa_answers 47396 vm-47396" +check "rm deletes it, its forwarder and its files" bash -c "cd '$pa' && '$D' rm -f /dev/null 2>&1 && + [[ -z \$(smol_status '$vm') && -z \$(smolpa_forwarder '$vm') ]] && ! ls '$XDG_DATA_HOME/devvm/smolvm/vms/$vm'.ports.* 2>/dev/null && smolpa_closed 47396" + +# With network policy: forwarding works, and opens the VM no way out; the forwarder never takes the +# VM's proxy or decider port, even with the proxy gone. A service on this machine's own loopback +# (which answers 407) for the direct probes. +echo listener-key > "$work/listener.auth" +"$D" _proxy -listen 127.0.0.1:18765 -auth-file "$work/listener.auth" >/dev/null 2>&1 & +listener=$! +pn=$(newproj smolallnet) +(cd "$pn" && printf 'exit\n' | DEVVM_MESSAGES=names "$D" "${S[@]}" --network-policy --no-git-protect base >"$work/last.log" 2>&1) +vm=$(vm_of "$pn"); [[ -z $vm ]] || created+=("$vm") +pp=$(sed -n 's/^proxy_port=//p' "$vms/$vm" 2>/dev/null) +dp=$(sed -n 's/^decider_port=//p' "$vms/$vm" 2>/dev/null) +smolpa_serve "$vm" 127.0.0.1 47397 +check "with network policy, every port forwarded too, and the self-check passed" bash -c " + [[ -n '$vm' && -n '$pp' && -n '$dp' ]] && grep -qx net_check=ok '$vms/$vm' && smolpa_answers 47397 vm-47397" +check "... direct connections still fail while it forwards, even as root: an address, other ports, IPv6, the host's loopback" smolnet_direct "$vm" +# smolpa_reserved VM: with its proxy and decider gone, the VM listens on their ports: neither is +# forwarded (nothing answers there); the next devvm starts the proxy on them again. +smolpa_reserved() { + local pid + pid=$(pgrep -f -- "[_]proxy -listen 127.0.0.1:$pp -vm $1 ") + [[ -n $pid ]] || { echo "no proxy"; return 1; } + kill "$pid" || return 1 + smolpa_closed "$pp" || return 1 + smolpa_closed "$dp" || return 1 + smolpa_serve "$1" 0.0.0.0 "$pp"; smolpa_serve "$1" 0.0.0.0 "$dp"; smolpa_serve "$1" 127.0.0.1 47398 + smolpa_answers 47398 vm-47398 || { echo "the control: a port of its own isn't forwarded"; return 1; } + if nc -z 127.0.0.1 "$pp" 2>/dev/null || nc -z 127.0.0.1 "$dp" 2>/dev/null || smolpa_log "$1" | grep -qE "port ($pp|$dp): forwarded"; then + echo "the proxy's or decider's port was forwarded"; smolpa_log "$1" | tail -5; return 1 + fi + (cd "$pn" && printf 'exit\n' | "$D" >"$work/last.log" 2>&1) && grep -qx net_check=ok "$vms/$1" && + pgrep -f -- "[_]proxy -listen 127.0.0.1:$pp -vm $1 " >/dev/null; } +check "with its proxy and decider gone, the VM listening on their ports: neither is forwarded (a port of its own is, the control); devvm starts the proxy on them again" smolpa_reserved "$vm" +check "rm -f deletes it, its proxy and its forwarder" bash -c "cd '$pn' && '$D' rm -f /dev/null 2>&1 && + [[ -z \$(smol_status '$vm') && -z \$(smolpa_forwarder '$vm') ]] && smolpa_closed 47397" +kill "$listener" 2>/dev/null; listener="" +rm -f "$work/listener.auth" + section "smolvm: shared tools" t=$(newproj smoltools); echo '{}' > "$t/package.json" launch "$t" 'node -v' "${S[@]}" --no-network-policy --ports none --no-git-protect