diff --git a/docs/content/docs/contributing/_index.md b/docs/content/docs/contributing/_index.md index 0bf603f0..f74f425e 100644 --- a/docs/content/docs/contributing/_index.md +++ b/docs/content/docs/contributing/_index.md @@ -224,7 +224,7 @@ The sections so far: - `project`: devvm in a new project folder (under `/tmp/devvm-go-e2e/p`) makes a VM from base and opens a shell there, which reads its commands from devvm's input. The folder and the shared tools are mounted and nothing else is, there's no SSH agent, no Docker (no docker layer) and the hostname is the folder's. The ssh config lists it as `devvm-web` with its host keys pinned; through an `~/.ssh/config` of the run's own that includes it under a `Host *` forwarding the agent, `ssh devvm-web` works, forwards no agent (a throwaway one), and refuses a changed host key. `.git` is locked (macOS) and git in the VM can still commit. `devvm stop` stops it and drops its entry, and on macOS reports and locks a submodule git folder the VM added. `TestE2EExecQuoting` in `internal/backend/lima`, which runs only there (`DEVVM_E2E_VM` names the VM), checks that arguments with spaces, quotes, `$`, newlines and globs, a folder and input reach the guest as given. Then a VM from a `devcontainer.json`, with no ports by default: its `forwardPorts` said and not forwarded, none reaching this machine, its `containerEnv` in the shell and its commands, its `postCreateCommand` run once in the folder, its `postStartCommand` at each start (again after `devvm restart`), nothing written to the folder, and a changed file warned about without changing the VM. Then a claude VM with a fake agent config, history, git identity and token in a home of its own: the agent's folder is mounted read-only and linked into the VM's home, its settings are copied and its history isn't, the VM gets the git identity, the timezone and its hostname, and the token itself. Then SSH agents, with a home of their own and throwaway keys: a `--ssh-agent` VM uses a throwaway agent standing for yours; after `devvm ssh-agent add` and `devvm ssh-agent devvm` it keeps yours, in its shell and by name, until a restart, then uses only devvm's own agent's key, in its shells and by name; after `devvm ssh-agent off`, none. - `gc`: a VM from a folder named `img-keep`, which is named like an image, and a fixture layer edited after its build: `devvm gc` deletes the stale image and its record and an old tool image no VM lists (once there's a tools lock), and keeps base and the VM; a second gc finds nothing. - `tools`: first, the shared tools resolve to upstream's newest versions, with devvm's pinned mise (downloaded once), each download with its checksum; the rest of the run doesn't check again (`DEVVM_NO_TOOL_CHECK`). Then a node project's VM: node, npm, pnpm, bun and yarn at the locked versions, each a read-only EROFS image, the share read-only even for root, `npm i -g` into the VM's home, a non-login shell over SSH, an `.nvmrc`'s own version, the tools mounted at boot without devvm, and a second node VM that builds nothing. -- `network`: a claude+codex VM with `--network-policy`, a fake token in devvm's environment and a fake `~/.claude.json` and Codex login in a home of its own. Its proxy runs and the self-check passed; its password was in no host process's arguments while devvm launched it (`ps`, sampled), and the guest has it; `ssh devvm-net` reaches it; direct connections fail, even as root, to an address and to other ports; an allowed host works and others, or other ports, are blocked; DNS fails at once; the host's loopback services are out of reach, directly or through the proxy; the proxy refuses requests without the VM's password; the token is nowhere in the VM, which has devvm's CA, its own placeholder and logins' copies with placeholders only; the proxy puts the token in for its host (for the VM's own placeholder only), an MCP server's header and Codex's key for theirs, over TLS the VM verifies; the host's login files are unchanged. `devvm secret set github --stdin` saves a fake token (in the Keychain on macOS, under the run's service, found through a link to `~/Library/Keychains` in the VM's home) and `secret get` reads it back; `secret use github` binds it to the running proxy at once, and on the next launch the VM has its own placeholder in `GH_TOKEN`, never the token, which the proxy puts in for `api.github.com`; `secret unuse` and `rm` take the binding and the token away. `TestE2ESelfCheck` in `internal/netpolicy` runs the self-check on the VM: it passes, then, once the VM is started outside devvm, it fails and stops the VM. `devvm stop` stops the VM and its proxy at once. `devvm network off` makes its next start direct, without a proxy; `on` while it runs shows it `unenforced` until `devvm restart` starts it confined; `off` while it runs confined keeps it on its proxy until it next starts. +- `network`: a claude+codex VM with `--network-policy`, a fake token in devvm's environment and a fake `~/.claude.json` and Codex login in a home of its own. Its proxy runs and the self-check passed; its password was in no host process's arguments while devvm launched it (`ps`, sampled), and the guest has it; `ssh devvm-net` reaches it; direct connections fail, even as root, to an address and to other ports; an allowed host works and others, or other ports, are blocked; a line in the VM's policy file that reads as a deny but isn't a rule makes the running proxy refuse an allowed host, with no allow command in `devvm network log --blocked`, `devvm network rm` warns of it, and the host works again once it's gone; DNS fails at once; the host's loopback services are out of reach, directly or through the proxy; the proxy refuses requests without the VM's password; the token is nowhere in the VM, which has devvm's CA, its own placeholder and logins' copies with placeholders only; the proxy puts the token in for its host (for the VM's own placeholder only), an MCP server's header and Codex's key for theirs, over TLS the VM verifies; the host's login files are unchanged. `devvm secret set github --stdin` saves a fake token (in the Keychain on macOS, under the run's service, found through a link to `~/Library/Keychains` in the VM's home) and `secret get` reads it back; `secret use github` binds it to the running proxy at once, and on the next launch the VM has its own placeholder in `GH_TOKEN`, never the token, which the proxy puts in for `api.github.com`; `secret unuse` and `rm` take the binding and the token away. `TestE2ESelfCheck` in `internal/netpolicy` runs the self-check on the VM: it passes, then, once the VM is started outside devvm, it fails and stops the VM. `devvm stop` stops the VM and its proxy at once. `devvm network off` makes its next start direct, without a proxy; `on` while it runs shows it `unenforced` until `devvm restart` starts it confined; `off` while it runs confined keeps it on its proxy until it next starts. - `nix`: the nix layer. A copy of `assets/layers/nix.sh` as a layer of the run's own, built behind a company proxy of the run's own, reaches Nix's releases through it and leaves no proxy settings for `nix-daemon` (and not the company proxy's password) anywhere on its image's disk. Then a folder with `package.json`, `flake.nix` and `.envrc` gets a node+nix VM with network policy: Nix and direnv at their pins, a store that's root's, `sandbox` on with no fallback, `trusted-users` root alone and an untrusted user's `--option substituters` ignored, `nix-daemon` with the VM's own proxy in devvm's drop-in alone, `nix run nixpkgs#hello` from Nix's cache, a build in Nix's sandbox, `sudo nix` and `nix` over ssh, the flake's dev shell (nixpkgs at a pinned revision) loaded by direnv in an interactive shell, its `node` ahead of the shared node prompt after prompt and gone outside the folder, nix-direnv's cache in the VM's home with no `.direnv` in the folder, a fixed-output download from a host that isn't allowed refused with `403` and named by `devvm-why`, and after `devvm network off` and `devvm restart`, no drop-in and no proxy for the daemon. - `smolvm` (`--backend smolvm`): the [smolvm backend](../backends/smolvm.md) on smolvm's own machines, which on macOS share yours: the run looks only at machines with its sandbox's label, deletes only those it made, and checks every other machine is as it was. base and a fixture layer built as packs, a rebuild, `images rm`, and a failed script's machine kept stopped; a project VM with its size, the folder read-write and files the VM makes yours, the tools read-only even for root, its hostname, `TestE2EExecQuoting` in `internal/backend/smolvm` (arguments, folder, input, the VM's user and login environment), no Docker (no docker layer), a listed port on the host's loopback, a server on the VM's loopback alone reaching it, an unlisted port not forwarded, smolvm publishing none of the ports, a port added to a running VM reaching this machine at once and gone once removed, the VM never restarted, a new size applied on restart and new ports at once, a listed port a host program has on every address left to it until it's freed, stop, start and rm; a `--ssh-agent` VM using a throwaway agent, and none once turned off and restarted; ssh for editors' emulation ([its checks](../internals/design.md#ssh-for-editors-on-smolvm)): pinned host keys of each VM's own, its own key alone, no forwarding out even past a hostile sshd, `devvm host` and `code`, a VM `--from alpine:3` reached over ssh, a `--clone` VM's push and fetch; network policy's emulation, on a docker VM (no agent's login read): the VM behind its proxy and decider, the proxy's password in no host process's arguments while devvm launched it and in the guest's environment from its proxy file and Docker's daemon, Docker pulling through the proxy, its allow list and closed DNS, allowed and blocked hosts, direct connections failing even as root (to the host's loopback too), DNS failing at once and every probe query (TXT, ANY, AAAA, HTTPS, EDNS0, under `devvm.invalid`) refused in smolvm's decision log with no flow beyond the host's loopback (nettop, macOS), `devvm.invalid` as the log's control, UDP and ICMP getting nowhere, the decider's token nowhere in the VM or a process's arguments, `devvm network log`, `network allow` and `rm` at once, an allow list widened while it runs making it `unenforced`, nothing out with the proxy gone or a decider that answers garbage or nothing, no start without a decider, a start with someone else's decider stopped, and `network off` and `on`, where the direct, DNS and UDP probes get out (their controls); a docker VM `--from alpine:3` with network policy, its Docker restarted by devvm's setup and pulling through the proxy, and a restart over a stale pid file stopping no process but Docker's daemon; a node VM's uncompressed tool images; a nix VM with network policy, whose `nix-daemon` devvm starts with the VM's proxy in `/etc/conf.d/nix-daemon`, running `nix run nixpkgs#hello` through the proxy and a build in Nix's sandbox, then after `devvm network off` and `devvm restart` a daemon without the proxy. - `docker` (`--backend docker`): the [Docker backend](../backends/docker.md), with state under `/tmp/devvm-go-e2e-docker`, on an engine where only what has its sandbox's label is touched, and what hasn't must be as it was at the end. On a Linux engine of the machine's own (on Linux; on macOS in the docker host VM below, from a `devvm` built here for it, its results counted here): doctor, base and a fixture layer built by committing containers, the layer's build reaching the internet and the host's server on every address but not its loopback-only one, a rebuild, `images rm`, a failed script's container kept stopped; a project VM with its CPUs and memory, the folder read-write and what the VM writes yours (uid and gid), its home a volume of its own, the tools' volume read-only even for root, its hostname, no Docker, `devvm size`'s `disk_used`, stop and start keeping its disk; a disk size and the nix layer refused in one line, nothing made; the docker layer ([its checks](../internals/design.md#the-docker-layer-on-docker)): on the Linux engine (Sysbox installed in the docker host VM, pinned) under Sysbox, on its own network, its engine's volumes counted in `devvm size`'s `disk_used`, and refused for a VM that exists; refused with network policy, and on Docker Desktop; ssh for editors', ports' and agent forwarding's emulations ([their checks](../internals/design.md#ssh-for-editors-on-docker)): no port published and no sshd listening, pinned host keys of each VM's own, its own key alone, no forwarding out even past a hostile sshd, `devvm host` and `code`, `devvm _docker-connect` refusing another devvm's container, a VM started outside devvm without ssh, every port and listed ports through devvm's forwarder, never a port of this machine's programs (on its `127.0.0.1`, `::1` or every address) or another VM's, the agent in ssh sessions alone (a throwaway one standing for yours, devvm's, none), a `--clone` VM's push and fetch; an agent VM in a home of its own whose added and removed folders make its container again from a commit, its disk and home kept, the commit before deleted, rm deleting its commit and volumes; a node VM whose tools are linked from Docker's tools volume, read-only even for root. Then on Docker Desktop: doctor naming it and its file sharing, a build refused in one line with nothing made, base and the shared tools copied from the Linux engine's run (Desktop can't build yet; the same paths give them the same label), and the project, agent and node VMs' checks again, with `TestE2EExecQuoting` in `internal/backend/docker`; at the end everything with the sandbox's label is deleted. diff --git a/docs/content/docs/getting-started/install.md b/docs/content/docs/getting-started/install.md index 89b35376..6469d95a 100644 --- a/docs/content/docs/getting-started/install.md +++ b/docs/content/docs/getting-started/install.md @@ -74,7 +74,7 @@ On Linux hosts, devvm has a few limits, such as no `.git` protection, that [Know devvm never installs anything on this machine itself. Every command that needs the backend checks it first, and stops at the first thing that's missing. -`devvm doctor` checks the backend new VMs get, or another one with `--backend NAME`. It lists everything that backend lacks, each with what to do, which is the command that installs it when there's one to run. For the docker backend, it also says which engine devvm uses, and on Docker Desktop which folders Desktop shares ([which engine devvm uses](../backends/docker.md#which-engine-devvm-uses)). It then lists what each backend can do, which it calls the backend's [features](../internals/backends.md#features), each as `native`, `emulated`, `unreviewed` for an emulation that devvm refuses until it's reviewed, or `none`. It also says whether Docker is installed, which only `--from` with [an image only Docker has](../using/from.md#images-only-docker-has) needs. When `HTTPS_PROXY` is set and `~/.config/devvm/ca` has no CA certificates, it says that a proxy that inspects TLS needs its CA there ([a company's CA](../using/settings.md#a-companys-ca)). It warns when another devvm comes first on your `PATH` ([One devvm](#one-devvm)), when the disk that devvm's images and VMs go on has less free space than building base needs, and when this machine has less than the 8 GiB of memory or the 4 CPUs that devvm recommends ([Requirements](#requirements)). Then it says devvm has everything it needs, or it fails. The warnings never make it fail, so a small machine with everything installed passes. +`devvm doctor` checks the backend new VMs get, or another one with `--backend NAME`. It lists everything that backend lacks, each with what to do, which is the command that installs it when there's one to run. For the docker backend, it also says which engine devvm uses, and on Docker Desktop which folders Desktop shares ([which engine devvm uses](../backends/docker.md#which-engine-devvm-uses)). It then lists what each backend can do, which it calls the backend's [features](../internals/backends.md#features), each as `native`, `emulated`, `unreviewed` for an emulation that devvm refuses until it's reviewed, or `none`. It also says whether Docker is installed, which only `--from` with [an image only Docker has](../using/from.md#images-only-docker-has) needs. When `HTTPS_PROXY` is set and `~/.config/devvm/ca` has no CA certificates, it says that a proxy that inspects TLS needs its CA there ([a company's CA](../using/settings.md#a-companys-ca)). It warns when another devvm comes first on your `PATH` ([One devvm](#one-devvm)), when the disk that devvm's images and VMs go on has less free space than building base needs, when this machine has less than the 8 GiB of memory or the 4 CPUs that devvm recommends ([Requirements](#requirements)), and for each line of your policy files that isn't a rule, which VMs' proxies skip ([rules](../safety/network.md#rules)). Then it says devvm has everything it needs, or it fails. The warnings never make it fail, so a small machine with everything installed passes. When `devvm doctor` finds nothing missing, you're ready for [your first VM](first-vm.md). Before you make it, read [staying safe](../safety/_index.md#the-habits), which lists the habits that close most of what devvm leaves open. diff --git a/docs/content/docs/internals/install.md b/docs/content/docs/internals/install.md index 63cbc691..74dee0c5 100644 --- a/docs/content/docs/internals/install.md +++ b/docs/content/docs/internals/install.md @@ -44,7 +44,7 @@ The signature catches an archive or a `SHA256SUMS` that someone replaced, which - `backend` is the backend that doctor checked, the one new VMs get or the one `--backend` names. - `problems` has what that backend is missing, each with its `key`, the `fix` command, and the `message` that `devvm doctor` prints for it. The `fix` is a command whose words are separated by spaces, without shell syntax, or `null` when there's none to run, for example when virtualization is turned off in the firmware. -- `warnings` has the messages of doctor's warnings, which have no keys, because there's nothing for a script to fix. They're about another devvm on `PATH`, low free space, and a machine with less than 8 GiB of memory or fewer than 4 CPUs. +- `warnings` has the messages of doctor's warnings, which have no keys, because there's nothing for a script to fix. They're about another devvm on `PATH`, low free space, a machine with less than 8 GiB of memory or fewer than 4 CPUs, and each line of `~/.config/devvm/policy`, `~/.config/devvm/layers/*.policy` and `~/.local/share/devvm/vms/*.policy` that isn't a rule (`policy_not_rule`). - `docker` says whether Docker is installed, which only `--from` with an image that only Docker has needs. - `features` has, for each backend, how it has each feature, as `native`, `emulated`, `unreviewed` or `none`. The example below shows two of Lima's features. diff --git a/docs/content/docs/internals/network.md b/docs/content/docs/internals/network.md index 3dc91f22..77a42e6c 100644 --- a/docs/content/docs/internals/network.md +++ b/docs/content/docs/internals/network.md @@ -107,6 +107,8 @@ A VM's proxy reads these policy files, in this order, as one list. [Allowlists]( | `~/.local/share/devvm/vms/.policy` | that VM only (`devvm network allow`, `deny` and `rm`) | | `~/.local/share/devvm/run/.secrets.policy` | the hosts of the VM's secrets and logins, on port 443 (devvm writes it) | +The proxy, `devvm network` and `devvm doctor` read every policy file with one parser, `proxy.ParsePolicy`, which returns each line that holds more than a comment, with its number and whether it's a rule. A line is a rule only when `proxy.ValidRule` takes it, which is exactly what `devvm network allow` and `deny` take. Each time the proxy reads a file, it logs each line that isn't a rule, with its file, number and text, quoted, to its own log, `logs/.proxy.log`. It skips such a line, unless the line starts with `!` (`proxy.BrokenDeny`). A broken deny fails closed: while any of the VM's policy files has one, the proxy's policy denies every name and every address, and each request gets `403` and a refused block whose reason names the file and the line, so neither the VM's prompt nor `devvm network log` suggests an allow rule. The VM's links and the proxy's own answers at `devvm.proxy` come before the rules, so they still work, and tunnels already open stay open, as they do for any new deny. Fixing the line lifts it at the proxy's next read of the file, which is the next connection. The proxy reads a file again when its mtime changes, or when it comes back after it was missing, whatever its mtime, and an error other than a missing file keeps its last rules and its broken deny. A leading byte-order mark isn't part of the first line. `netpolicy.PolicyWarnings` warns about each line that isn't a rule, with `policy_broken_deny` for a broken deny and `policy_not_rule` for the others. `netpolicy.Proxy.Prepare` uses it for the VM's policy files at each launch with network policy, `devvm network allow`, `deny` and `rm` for the file they change, and `devvm doctor` for the files you edit: `~/.config/devvm/policy`, your layers' and each VM's own. `devvm network` also marks the line, and `--json` lists it in `not_rules`. A unit test parses every policy file that devvm ships and fails on any line that isn't a rule. + Each change that `devvm network allow`, `deny` or `rm` makes rewrites the file whole, through a link if the file is one, so a proxy never reads half of it. ## The VM's setup diff --git a/docs/content/docs/safety/network.md b/docs/content/docs/safety/network.md index fc8243dd..a0a2aaa2 100644 --- a/docs/content/docs/safety/network.md +++ b/docs/content/docs/safety/network.md @@ -80,11 +80,17 @@ A policy file holds one rule per line. `#` starts a comment, and matching ignore | `RULE:22`, `[fd00::1]:22`, `10.0.0.0/8:8080` | only that port; without a port, 443 and 80 | | `!RULE` | deny: a deny beats any allow | +A rule is plain ASCII with no spaces in it, and a port is a number from 1 to 65535. A host's one trailing dot is dropped, so `example.com.` matches `example.com`. Brackets hold only an IPv6 address, and an address can't follow `*.`. A line that holds anything else, such as `example.com:x`, `a*.example.com` or `! example.com` with a space after the `!`, isn't a rule. + +When a line that isn't a rule starts with `!`, it reads as a deny, but the proxy can't tell what it would deny. So while the line is there, the proxy of every VM that reads the file denies every new connection apart from the VM's [links](#links-between-vms), whatever the other rules allow. Connections that are already open stay open. Each refusal names the file and the line, and it suggests no `devvm network allow` command, because no rule would help. Any other line that isn't a rule is skipped, and the file's other lines still apply. The proxy names each such line in its own log. + +devvm warns about each line that isn't a rule, with the file and the line's number, and the warning for a broken deny says that the proxies deny everything until it's fixed. It warns when you open a VM with network policy whose proxy reads the file, when `devvm network allow`, `deny` or `rm` changes the file, and in `devvm doctor`. `devvm network` also marks the line. Fix the line or remove it, and the change applies from the next connection. + The proxy never dials a denied address, even for an allowed name that resolves to it or to its NAT64 form. A missing file has no rules. A file that changed but can't be read keeps its last rules, so a deny never lapses. ### Changing rules -`devvm network` shows this folder's VM's allowlist after its network policy. It prints each of the VM's policy files that has rules, with the file's path after `#`, and then its rules without their comments: +`devvm network` shows this folder's VM's allowlist after its network policy. It prints each of the VM's policy files that holds more than comments, with the file's path after `#`, and then its rules without their comments. A line that isn't a rule is marked `# not a rule, skipped`, with its line number: ```text on @@ -93,6 +99,7 @@ on github.com # /Users/you/.local/share/devvm/vms/devvm-some-project-71a99b1076d92c.policy example.com + example.com:x # not a rule, skipped (line 2) ``` | | | @@ -108,7 +115,7 @@ If a VM was deleted outside devvm, a new VM with its name never gets its rules. ### devvm network --json -`devvm network --json` prints the VM's network policy and its allowlist as one JSON object, as [output for scripts](../getting-started/commands.md#output-for-scripts) describes. `policy` is `on`, `off` or `unenforced`, and `allowlist` has each policy file that has rules, in the order the proxy reads them, with its path and its rules. With `-g`, the object has only `policy`, which is what new VMs get: `ask`, `on` or `off`. With `--json` the command only shows, so devvm refuses `on`, `off` or `ask` with it. +`devvm network --json` prints the VM's network policy and its allowlist as one JSON object, as [output for scripts](../getting-started/commands.md#output-for-scripts) describes. `policy` is `on`, `off` or `unenforced`, and `allowlist` has each policy file that holds more than comments, in the order the proxy reads them, with its path, its rules and, in `not_rules`, each line that isn't a rule, with its `line` number and its `text`. With `-g`, the object has only `policy`, which is what new VMs get: `ask`, `on` or `off`. With `--json` the command only shows, so devvm refuses `on`, `off` or `ask` with it. ```json { @@ -120,12 +127,19 @@ If a VM was deleted outside devvm, a new VM with its name never gets its rules. "rules": [ "ports.ubuntu.com", "github.com" - ] + ], + "not_rules": [] }, { "file": "/Users/you/.local/share/devvm/vms/devvm-some-project-71a99b1076d92c.policy", "rules": [ "example.com" + ], + "not_rules": [ + { + "line": 2, + "text": "example.com:x" + } ] } ] diff --git a/internal/cli/doctor.go b/internal/cli/doctor.go index 54eaaa05..2830f80e 100644 --- a/internal/cli/doctor.go +++ b/internal/cli/doctor.go @@ -14,6 +14,7 @@ import ( "github.com/w3cj/devvm/assets" "github.com/w3cj/devvm/internal/backend" "github.com/w3cj/devvm/internal/msg" + "github.com/w3cj/devvm/internal/netpolicy" "github.com/w3cj/devvm/internal/paths" "github.com/w3cj/devvm/internal/state" "github.com/w3cj/devvm/internal/trust" @@ -47,6 +48,13 @@ func newDoctorCmd(u *ui.UI) *cobra.Command { Path: onPath{LookPath: exec.LookPath, Executable: os.Executable}, Free: reg.Host.FreeSpace, Host: func() (vm.Host, error) { return vm.ThisHost(reg.Host) }, + Policies: func() []msg.M { + dirs, err := paths.FromEnv() + if err != nil { + return nil + } + return netpolicy.NotRules(dirs) + }, } if asJSON { return printJSON(u, d.report(cmd.Context(), reg.All(), b)) @@ -112,7 +120,8 @@ func (d doctor) report(ctx context.Context, all []backend.Backend, b backend.Bac } // warnings are doctor's warnings, which never make it fail: another devvm -// first on PATH, low free space, a small host. +// first on PATH, low free space, a small host, policy files' lines that +// aren't rules. func (d doctor) warnings(b backend.Backend) []msg.M { var ms []msg.M if m, ok := d.Path.other(); ok { @@ -121,7 +130,11 @@ func (d doctor) warnings(b backend.Backend) []msg.M { if m, low := (backend.Space{Free: d.Free}).Warning(b); low { ms = append(ms, m) } - return append(ms, smallHost(d.Host)...) + ms = append(ms, smallHost(d.Host)...) + if d.Policies != nil { + ms = append(ms, d.Policies()...) + } + return ms } // The host devvm recommends: base asks for 4 CPUs and 8 GiB. @@ -135,6 +148,9 @@ type doctor struct { Path onPath Free func(path string) (uint64, error) // free bytes on path's volume Host func() (vm.Host, error) + // Policies are the warnings for your policy files' lines that aren't + // rules (netpolicy.NotRules); nil for none. + Policies func() []msg.M } // run checks b, the backend new VMs get, and lists all's features. It diff --git a/internal/cli/doctor_test.go b/internal/cli/doctor_test.go index c4ed6624..7784e66e 100644 --- a/internal/cli/doctor_test.go +++ b/internal/cli/doctor_test.go @@ -102,9 +102,10 @@ func TestDoctorReport(t *testing.T) { {Key: "kvm", Msg: msg.NoKVM()}, } d := doctor{ - Path: onPath{LookPath: func(string) (string, error) { return "", exec.ErrNotFound }, Executable: os.Executable}, - Free: func(string) (uint64, error) { return 1 << 40, nil }, - Host: func() (vm.Host, error) { return vm.Host{CPUs: 2, MemoryGiB: 16}, nil }, + Path: onPath{LookPath: func(string) (string, error) { return "", exec.ErrNotFound }, Executable: os.Executable}, + Free: func(string) (uint64, error) { return 1 << 40, nil }, + Host: func() (vm.Host, error) { return vm.Host{CPUs: 2, MemoryGiB: 16}, nil }, + Policies: func() []msg.M { return []msg.M{msg.PolicyNotRule("/p", "2", "a b")} }, } r := d.report(t.Context(), []backend.Backend{b}, b) fix := "brew install lima" @@ -113,7 +114,7 @@ func TestDoctorReport(t *testing.T) { r.Problems[0].Message != want[0].Message || r.Problems[1].Key != "kvm" { t.Errorf("problems %+v, want %+v", r.Problems, want) } - if !slices.Equal(r.Warnings, []string{"host_cpus_few have=2 want=4"}) || r.Backend != "lima" { + if !slices.Equal(r.Warnings, []string{"host_cpus_few have=2 want=4", "policy_not_rule file=/p line=2 rule=a b"}) || r.Backend != "lima" { t.Errorf("warnings %q, backend %q", r.Warnings, r.Backend) } if r.Features["lima"]["ssh"] != "native" || r.Features["lima"]["disk"] != "none" { diff --git a/internal/cli/json_test.go b/internal/cli/json_test.go index e0127231..1dcc9bce 100644 --- a/internal/cli/json_test.go +++ b/internal/cli/json_test.go @@ -105,8 +105,13 @@ func TestJSONShapes(t *testing.T) { {"ports", map[string]string{"ports": "all"}, []string{"ports: string"}}, { "network", - networkOutput{Policy: "on", Allowlist: []policyFileJSON{{File: "/p", Rules: []string{"a.test"}}}}, - []string{"allowlist[].file: string", "allowlist[].rules[]: string", "policy: string"}, + networkOutput{Policy: "on", Allowlist: []policyFileJSON{{ + File: "/p", Rules: []string{"a.test"}, NotRules: []notRuleJSON{{Line: 2, Text: "a b"}}, + }}}, + []string{ + "allowlist[].file: string", "allowlist[].not_rules[].line: number", "allowlist[].not_rules[].text: string", + "allowlist[].rules[]: string", "policy: string", + }, }, {"network -g", map[string]string{"policy": "ask"}, []string{"policy: string"}}, { diff --git a/internal/cli/network.go b/internal/cli/network.go index b4cadc88..368f992e 100644 --- a/internal/cli/network.go +++ b/internal/cli/network.go @@ -104,9 +104,19 @@ type networkOutput struct { Allowlist []policyFileJSON `json:"allowlist"` } +// policyFileJSON is a policy file: its rules, and its lines that aren't +// rules, which its proxy skips. type policyFileJSON struct { - File string `json:"file"` - Rules []string `json:"rules"` + File string `json:"file"` + Rules []string `json:"rules"` + NotRules []notRuleJSON `json:"not_rules"` +} + +// notRuleJSON is a policy file's line that isn't a rule: its number, from +// 1, and its text, comment left out. +type notRuleJSON struct { + Line int `json:"line"` + Text string `json:"text"` } // printNetwork writes the VM's network policy: its line then its rules, @@ -120,7 +130,11 @@ func printNetwork(u *ui.UI, asJSON bool, s vm.NetworkShown) error { } out := networkOutput{Policy: s.Policy, Allowlist: []policyFileJSON{}} for _, f := range s.Rules { - out.Allowlist = append(out.Allowlist, policyFileJSON{File: f.Path, Rules: f.Rules}) + j := policyFileJSON{File: f.Path, Rules: append([]string{}, f.Rules()...), NotRules: []notRuleJSON{}} + for _, l := range f.NotRules() { + j.NotRules = append(j.NotRules, notRuleJSON{Line: l.N, Text: l.Text}) + } + out.Allowlist = append(out.Allowlist, j) } return printJSON(u, out) } diff --git a/internal/msg/docs.go b/internal/msg/docs.go index 1d38f025..34680cda 100644 --- a/internal/msg/docs.go +++ b/internal/msg/docs.go @@ -393,6 +393,8 @@ var docs = map[string]string{ //nolint:gosec // message IDs and pages, not crede "tool_bad_version": "using/toolchains#adding-and-removing-tools", "vm_lacks": "using/toolchains#adding-and-removing-tools", "rule_missing": "safety/network#changing-rules", + "policy_not_rule": "safety/network#rules", + "policy_broken_deny": "safety/network#rules", "usage_error": "using/troubleshooting#a-command-is-refused-before-it-runs", "arg_missing": "using/troubleshooting#a-command-is-refused-before-it-runs", "args_too_many": "using/troubleshooting#a-command-is-refused-before-it-runs", diff --git a/internal/msg/messages_gen.go b/internal/msg/messages_gen.go index 6c0a9b9c..823cd30d 100644 --- a/internal/msg/messages_gen.go +++ b/internal/msg/messages_gen.go @@ -2384,11 +2384,21 @@ func PackingImage(vm string) M { return M{id: "packing_image", vals: []val{{"vm", vm}}} } +// PolicyBrokenDeny is [policy_broken_deny]: "Line {{.line}} of {{.file}}, {{.rule}}, reads as a deny but isn't a rule, so every VM whose proxy reads that file denies everything until it's fixed. Fix the line or remove it." +func PolicyBrokenDeny(file string, line string, rule string) M { + return M{id: "policy_broken_deny", vals: []val{{"file", file}, {"line", line}, {"rule", rule}}} +} + // PolicyFailed is [policy_failed]: "Reading or changing the network policy rules failed: {{.reason}}." func PolicyFailed(reason string) M { return M{id: "policy_failed", vals: []val{{"reason", reason}}} } +// PolicyNotRule is [policy_not_rule]: "Line {{.line}} of {{.file}}, {{.rule}}, isn't a rule, so VMs' proxies skip it. Fix the line or remove it." +func PolicyNotRule(file string, line string, rule string) M { + return M{id: "policy_not_rule", vals: []val{{"file", file}, {"line", line}, {"rule", rule}}} +} + // PortInvalid is [port_invalid]: "{{.value}} isn't a port list. Use all, none, or ports and ranges such as 5173,8000-8010." func PortInvalid(value string) M { return M{id: "port_invalid", vals: []val{{"value", value}}} @@ -3782,7 +3792,9 @@ var specs = map[string]spec{ "output_failed": {fields: []string{"reason"}}, "pack_failed": {fields: []string{"vm"}}, "packing_image": {fields: []string{"vm"}}, + "policy_broken_deny": {fields: []string{"file", "line", "rule"}}, "policy_failed": {fields: []string{"reason"}}, + "policy_not_rule": {fields: []string{"file", "line", "rule"}}, "port_invalid": {fields: []string{"value"}}, "port_not_listed": {fields: []string{"port", "ports"}}, "port_not_published": {fields: []string{"port", "ports"}}, diff --git a/internal/netpolicy/netpolicy_test.go b/internal/netpolicy/netpolicy_test.go index f466354f..0697dd0f 100644 --- a/internal/netpolicy/netpolicy_test.go +++ b/internal/netpolicy/netpolicy_test.go @@ -707,6 +707,29 @@ func TestPrepareCAFails(t *testing.T) { } } +// A launch with network policy warns of each line of the VM's policy files +// that isn't a rule, a broken deny as one. +func TestPrepareWarnsPolicy(t *testing.T) { + d, st := sandbox(t, "base") + p, _ := testProxy(t, d) + var warned []string + p.Warn = func(m msg.M) { warned = append(warned, m.Names()) } + if err := os.MkdirAll(filepath.Dir(VMPolicyFile(d, st.Name())), 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(VMPolicyFile(d, st.Name()), []byte("ok.test\n! bad.test\na b\n"), 0o600); err != nil { + t.Fatal(err) + } + if _, err := p.Prepare(t.Context(), lifelined(), st, false); err != nil { + t.Fatal(names(err)) + } + f := VMPolicyFile(d, st.Name()) + want := []string{"policy_broken_deny file=" + f + " line=2 rule=! bad.test", "policy_not_rule file=" + f + " line=3 rule=a b"} + if !slices.Equal(warned, want) { + t.Errorf("warned %q; want %q", warned, want) + } +} + // Two devvm runs writing a VM's proxy files at once each write them whole: // neither fails, and no temporary file is left. func TestWriteUpstreamAtOnce(t *testing.T) { diff --git a/internal/netpolicy/proxy.go b/internal/netpolicy/proxy.go index 55e1e026..ba671304 100644 --- a/internal/netpolicy/proxy.go +++ b/internal/netpolicy/proxy.go @@ -257,6 +257,9 @@ func (p *Proxy) Prepare(ctx context.Context, b backend.Backend, st *state.VM, ru if err != nil { return none, err } + for _, m := range PolicyWarnings(policies) { + p.Warn(m) + } files := strings.Join(policies, ",") bin, _ := image.SHA256File(p.Self) caSum, _ := image.SHA256File(filepath.Join(ca, "ca.pem")) diff --git a/internal/netpolicy/rules.go b/internal/netpolicy/rules.go index 6109192a..6348c249 100644 --- a/internal/netpolicy/rules.go +++ b/internal/netpolicy/rules.go @@ -7,9 +7,11 @@ import ( "io/fs" "os" "path/filepath" + "strconv" "strings" "github.com/w3cj/devvm/internal/msg" + "github.com/w3cj/devvm/internal/paths" "github.com/w3cj/devvm/internal/proxy" "github.com/w3cj/devvm/internal/state" ) @@ -27,12 +29,6 @@ func Rule(rule string, deny bool) (string, error) { return rule, nil } -// ruleOf is the rule on a policy file's line, without its comment. -func ruleOf(line string) string { - r, _, _ := strings.Cut(line, "#") - return strings.TrimSpace(r) -} - // readRules reads a policy file's lines; a missing file has none. func readRules(path string) ([]string, error) { b, err := os.ReadFile(path) //nolint:gosec // a policy file in devvm's folders @@ -60,8 +56,8 @@ func AddRule(path, rule string) (bool, error) { if err != nil { return false, err } - for _, l := range lines { - if strings.EqualFold(ruleOf(l), rule) { + for _, l := range proxy.ParsePolicy(strings.Join(lines, "\n")) { + if strings.EqualFold(l.Text, rule) { return false, nil } } @@ -75,9 +71,13 @@ func RemoveRule(path, rule string) (bool, error) { if err != nil { return false, err } + drop := map[int]bool{} + for _, l := range proxy.ParsePolicy(strings.Join(lines, "\n")) { + drop[l.N] = strings.EqualFold(l.Text, strings.TrimSpace(rule)) + } kept := lines[:0:0] - for _, l := range lines { - if !strings.EqualFold(ruleOf(l), strings.TrimSpace(rule)) { + for i, l := range lines { + if !drop[i+1] { kept = append(kept, l) } } @@ -87,13 +87,37 @@ func RemoveRule(path, rule string) (bool, error) { return true, writeRules(path, kept) } -// RuleFile is a policy file and its rules, comments left out. +// RuleFile is a policy file and its lines that hold more than a comment, +// each marked whether it's a rule (proxy.ParsePolicy). type RuleFile struct { Path string - Rules []string + Lines []proxy.PolicyLine } -// ReadRules returns each of files that has rules, in order, with them. +// Rules are the file's rules, as written, comments left out. +func (f RuleFile) Rules() []string { + var out []string + for _, l := range f.Lines { + if l.OK { + out = append(out, l.Text) + } + } + return out +} + +// NotRules are the file's lines that aren't rules, which the proxy skips. +func (f RuleFile) NotRules() []proxy.PolicyLine { + var out []proxy.PolicyLine + for _, l := range f.Lines { + if !l.OK { + out = append(out, l) + } + } + return out +} + +// ReadRules returns each of files that holds more than comments, in +// order, with its lines. func ReadRules(files []string) ([]RuleFile, error) { var out []RuleFile for _, f := range files { @@ -101,31 +125,70 @@ func ReadRules(files []string) ([]RuleFile, error) { if err != nil { return nil, err } - var rules []string - for _, l := range lines { - if r := ruleOf(l); r != "" { - rules = append(rules, r) - } - } - if len(rules) > 0 { - out = append(out, RuleFile{Path: f, Rules: rules}) + if pl := proxy.ParsePolicy(strings.Join(lines, "\n")); len(pl) > 0 { + out = append(out, RuleFile{Path: f, Lines: pl}) } } return out, nil } +// notRuleMark follows a line that isn't a rule in WriteRules' output. +const notRuleMark = " # not a rule, skipped" + // WriteRules writes each policy file's rules to w: the file's path after -// #, then its rules, indented. +// #, then its lines, indented, each that isn't a rule marked so, with its +// line number. func WriteRules(w io.Writer, files []RuleFile) error { for _, f := range files { if _, err := fmt.Fprintf(w, "# %s\n", f.Path); err != nil { return err } - for _, r := range f.Rules { - if _, err := fmt.Fprintf(w, " %s\n", r); err != nil { + for _, l := range f.Lines { + text, mark := l.Text, "" + if !l.OK { + // Anything but a rule may hold control characters: dropped. + text, mark = msg.OneLine(l.Text), notRuleMark+" (line "+strconv.Itoa(l.N)+")" + } + if _, err := fmt.Fprintf(w, " %s%s\n", text, mark); err != nil { return err } } } return nil } + +// NotRules returns doctor's warnings (PolicyWarnings) for the policy files +// you edit: every VM's, your layers' and each VM's own. +func NotRules(d paths.Dirs) []msg.M { + files := []string{d.Policy()} + for _, pattern := range []string{filepath.Join(d.Layers(), "*.policy"), filepath.Join(d.VMs(), "*.policy")} { + m, _ := filepath.Glob(pattern) + files = append(files, m...) + } + return PolicyWarnings(files) +} + +// PolicyWarnings returns a warning for each line of files that isn't a +// rule: one the proxy skips, or a broken deny (proxy.BrokenDeny), which +// makes the proxies that read it deny everything. A file it can't read is +// left out. +func PolicyWarnings(files []string) []msg.M { + var out []msg.M + for _, f := range files { + rs, err := ReadRules([]string{f}) + if err != nil { + continue + } + for _, rf := range rs { + for _, l := range rf.NotRules() { + n := strconv.Itoa(l.N) + if proxy.BrokenDeny(l) { + out = append(out, msg.PolicyBrokenDeny(f, n, l.Text)) + } else { + out = append(out, msg.PolicyNotRule(f, n, l.Text)) + } + } + } + } + return out +} diff --git a/internal/netpolicy/rules_test.go b/internal/netpolicy/rules_test.go index 924f50d5..95aeb9f5 100644 --- a/internal/netpolicy/rules_test.go +++ b/internal/netpolicy/rules_test.go @@ -2,12 +2,17 @@ package netpolicy import ( "errors" + "io/fs" "os" "path/filepath" + "slices" "strings" "testing" + "github.com/w3cj/devvm/assets" "github.com/w3cj/devvm/internal/msg" + "github.com/w3cj/devvm/internal/paths" + "github.com/w3cj/devvm/internal/proxy" ) func TestRule(t *testing.T) { @@ -94,28 +99,112 @@ func TestAddRemoveRule(t *testing.T) { if got := content(empty); got != "x.test\n" { t.Errorf("empty file = %q", got) } + + // rm takes every line with the rule, never a commented-out one; lines + // that aren't rules and CRLF endings are kept as they are. + mixed := filepath.Join(dir, "mixed") + if err := os.WriteFile(mixed, []byte("# a.test\na.test\r\nexample.com:x # bad\r\nA.test # again\nb.test"), 0o600); err != nil { + t.Fatal(err) + } + ok, err = AddRule(mixed, "c.test") + step("add beside a line that isn't a rule", ok, true, err) + ok, err = RemoveRule(mixed, "a.test") + step("remove duplicates", ok, true, err) + if got, want := content(mixed), "# a.test\nexample.com:x # bad\r\nb.test\nc.test\n"; got != want { + t.Errorf("mixed file = %q; want %q", got, want) + } } // WriteRules lists the files with rules, comments and blank lines left -// out; missing and comment-only files not at all. +// out, and marks each line that isn't a rule with its number; missing and +// comment-only files not at all. func TestWriteRules(t *testing.T) { dir := t.TempDir() a, b, c := filepath.Join(dir, "a"), filepath.Join(dir, "b"), filepath.Join(dir, "c") - if err := os.WriteFile(a, []byte("# head\n\nx.test # why\n !y.test\n"), 0o600); err != nil { + if err := os.WriteFile(a, []byte("# head\n\nx.test # why\n !y.test\nexample.com:x\na\x1b[31mb\n"), 0o600); err != nil { t.Fatal(err) } if err := os.WriteFile(b, []byte("# only a comment\n"), 0o600); err != nil { t.Fatal(err) } files, err := ReadRules([]string{a, b, c}) - if err != nil || len(files) != 1 || files[0].Path != a || strings.Join(files[0].Rules, " ") != "x.test !y.test" { + if err != nil || len(files) != 1 || files[0].Path != a || strings.Join(files[0].Rules(), " ") != "x.test !y.test" { t.Fatalf("ReadRules = %+v, %v", files, err) } + if bad := files[0].NotRules(); len(bad) != 2 || bad[0].N != 5 || bad[0].Text != "example.com:x" { + t.Errorf("NotRules = %+v", bad) + } var out strings.Builder if err := WriteRules(&out, files); err != nil { t.Fatal(err) } - if want := "# " + a + "\n x.test\n !y.test\n"; out.String() != want { + // A line's control characters are dropped. + if want := "# " + a + "\n x.test\n !y.test\n example.com:x" + notRuleMark + " (line 5)\n" + + " a[31mb" + notRuleMark + " (line 6)\n"; out.String() != want { t.Errorf("WriteRules = %q; want %q", out.String(), want) } } + +// Every policy file devvm ships parses cleanly: each line a rule, a +// comment or nothing. +func TestBuiltinPolicies(t *testing.T) { + n := 0 + err := fs.WalkDir(assets.FS, ".", func(path string, e fs.DirEntry, err error) error { + if err != nil || e.IsDir() || filepath.Ext(path) != ".policy" { + return err + } + n++ + b, err := fs.ReadFile(assets.FS, path) + if err != nil { + return err + } + lines := proxy.ParsePolicy(string(b)) + if len(lines) == 0 { + t.Errorf("%s has no rules", path) + } + for _, l := range lines { + if !l.OK { + t.Errorf("%s:%d isn't a rule: %q", path, l.N, l.Text) + } + } + return nil + }) + if err != nil || n == 0 { + t.Fatalf("%d policy files: %v", n, err) + } +} + +// NotRules warns of each line that isn't a rule in the policy files you +// edit: every VM's, each VM's own and your layers'; one that reads as a +// deny warns that its VMs' proxies deny everything. +func TestNotRules(t *testing.T) { + t.Setenv("DEVVM_MESSAGES", "names") + root := t.TempDir() + d := paths.Dirs{Data: filepath.Join(root, "data"), Config: filepath.Join(root, "config")} + files := map[string]string{ + d.Policy(): "ok.test\na b\n", + filepath.Join(d.Layers(), "pg.policy"): "# pg\n*\n", + VMPolicyFile(d, "devvm-x-0123456789abcd"): "!!x.test\nfine.test\n", + filepath.Join(d.Layers(), "pg.sh"): "not a policy\n", + } + for f, s := range files { + if err := os.MkdirAll(filepath.Dir(f), 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(f, []byte(s), 0o600); err != nil { + t.Fatal(err) + } + } + var got []string + for _, m := range NotRules(d) { + got = append(got, m.Names()) + } + want := []string{ + "policy_not_rule file=" + d.Policy() + " line=2 rule=a b", + "policy_not_rule file=" + filepath.Join(d.Layers(), "pg.policy") + " line=2 rule=*", + "policy_broken_deny file=" + VMPolicyFile(d, "devvm-x-0123456789abcd") + " line=1 rule=!!x.test", + } + if !slices.Equal(got, want) { + t.Errorf("NotRules =\n%q\nwant\n%q", got, want) + } +} diff --git a/internal/proxy/README.md b/internal/proxy/README.md index c2019370..96fa57b8 100644 --- a/internal/proxy/README.md +++ b/internal/proxy/README.md @@ -28,7 +28,7 @@ It returns when the VM's hostagent is gone. | File | What | | --- | --- | | `proxy.go` | `Main` and the flags, the listener, CONNECT and absolute-form handling, the address floor, the log (`Event`, `AllowRule`: `devvm network log` reads it), the `devvm.proxy` endpoints, `-init-ca` | -| `policy.go` | the rule syntax and matching (`ValidRule`: `devvm network allow`, `deny` and `rm` take only these); policy files are re-read when they change | +| `policy.go` | the rule syntax and matching (`ValidRule`: `devvm network allow`, `deny` and `rm` take only these); `ParsePolicy`, the one strict parser of policy files, which `devvm network` and doctor use too: each line that holds more than a comment, with its number and whether it's a rule; policy files are re-read when they change, and each line that isn't a rule is logged and skipped, except one that starts with `!` (`BrokenDeny`), which makes the policy deny everything, as refused blocks naming the file and line, until it's fixed | | `sni.go` | reads a tunnel's ClientHello to check its server name | | `decider.go` | `-decider`: smolvm's mediated-egress protocol (version 2), connections taken over or refused | | `relay.go` | `-listen-unix`, and `-relay`: Docker's relay, bytes passed unread to the proxy's socket | diff --git a/internal/proxy/policy.go b/internal/proxy/policy.go index c0deb9f8..bc43cd6a 100644 --- a/internal/proxy/policy.go +++ b/internal/proxy/policy.go @@ -1,9 +1,13 @@ package proxy import ( + "errors" + "fmt" + "io/fs" "net" "net/netip" "os" + "slices" "strconv" "strings" "sync" @@ -28,27 +32,37 @@ type rule struct { port int // 0: 443 and 80 } -func parseRule(line string) (rule, bool) { - line = strings.ToLower(strings.TrimSpace(strings.SplitN(line, "#", 2)[0])) - if line == "" { +// parseRule reads one rule, strictly: s is the whole rule, without a comment or spaces. It +// refuses anything that wouldn't match as written: a port that isn't 1 to 65535 in digits, a host +// that isn't a plain name (hostOK, with no empty label), a zone, a wildcard other than a leading +// "*." or "**", an address under "*.", an IPv4-mapped prefix shorter than the mapping, anything +// but printable ASCII. A host's one trailing dot is dropped, as requests' are, and a mapped +// prefix is its IPv4 one. +func parseRule(s string) (rule, bool) { + // Printable ASCII alone: no spaces, and nothing strings.ToLower would fold into ASCII (the + // Kelvin sign into k). + if s == "" || strings.ContainsAny(s, "#%") || strings.ContainsFunc(s, func(c rune) bool { return c <= ' ' || c > '~' }) { return rule{}, false } + line := strings.ToLower(s) r := rule{text: line} - if strings.HasPrefix(line, "!") { - r.deny = true - line = strings.TrimSpace(line[1:]) + if rest, ok := strings.CutPrefix(line, "!"); ok { + r.deny, line = true, rest } - // A port suffix: host:port, 1.2.3.4:port, [v6]:port, or cidr:port. - if h, p, err := net.SplitHostPort(line); err == nil { - if n, err := strconv.Atoi(p); err == nil && n > 0 && n < 65536 { - line, r.port = h, n - } - } else if i := strings.LastIndex(line, ":"); i > 0 && strings.Contains(line, "/") && !strings.Contains(line[:i], ":") { - if n, err := strconv.Atoi(line[i+1:]); err == nil && n > 0 && n < 65536 { - line, r.port = line[:i], n - } + line, port, ok := cutPort(line) + if !ok { + return rule{}, false } + r.port = port if p, err := netip.ParsePrefix(line); err == nil { + // An IPv4-mapped prefix is its IPv4 one, as matchAddr unmaps what it judges; one + // shorter than the mapping's 96 bits isn't a rule. + if p.Addr().Is4In6() { + if p.Bits() < 96 { + return rule{}, false + } + p = netip.PrefixFrom(p.Addr().Unmap(), p.Bits()-96) + } r.prefix = p.Masked() return r, true } @@ -56,32 +70,85 @@ func parseRule(line string) (rule, bool) { r.prefix = netip.PrefixFrom(a.Unmap(), a.Unmap().BitLen()) return r, true } - if line == "" || strings.ContainsAny(line, " /\\") { + if line == "**" { + r.host = line + return r, true + } + h := strings.TrimSuffix(line, ".") + name := strings.TrimPrefix(h, "*.") + if _, err := netip.ParseAddr(name); err == nil || strings.ContainsAny(name, "[]*") || + slices.Contains(strings.Split(name, "."), "") || !hostOK(name) { return rule{}, false } - r.host = line + r.host = h return r, true } -// ValidRule reports whether s is one rule, as devvm network allow writes it: a -// host name, *.name, ** or an address or CIDR (no zone), optionally with a -// port and a leading !, and no spaces or comment. AllowRule's rules are -// valid. +// cutPort takes a rule's port off: host:port, 1.2.3.4:port, [v6]:port or cidr:port, the port 1 to +// 65535 in digits. Without one, the rule is as it was and the port 0. false: a port that isn't one. +func cutPort(s string) (string, int, bool) { + h, p, err := net.SplitHostPort(s) + if err == nil && strings.HasPrefix(s, "[") { + if a, err := netip.ParseAddr(h); err != nil || !a.Is6() { + return "", 0, false // brackets hold an IPv6 address alone + } + } + if err != nil { + i := strings.LastIndex(s, ":") + if i <= 0 || !strings.Contains(s, "/") || strings.Contains(s[:i], ":") { + return s, 0, true // no port, or an IPv6 address + } + h, p = s[:i], s[i+1:] + } + n, err := strconv.Atoi(p) + if err != nil || strings.Trim(p, "0123456789") != "" || n < 1 || n > 65535 { + return "", 0, false + } + return h, n, true +} + +// ValidRule reports whether s is one rule, as devvm network allow writes it +// and the proxy takes it from a policy file's line: a host name, *.name, ** +// or an address or CIDR (no zone), optionally with a port and a leading !, +// and no spaces or comment. AllowRule's rules are valid. func ValidRule(s string) bool { - if s == "" || strings.ContainsAny(s, "# \t\r\n%") { - return false + _, ok := parseRule(s) + return ok +} + +// A PolicyLine is a line of a policy file that holds more than a comment. +type PolicyLine struct { + N int // its number, from 1 + Text string // as written, without its comment or the spaces around it + OK bool // whether it's a rule (ValidRule): the proxy skips one that isn't +} + +// ParsePolicy reads a policy file: one rule a line, '#' starting a comment. It returns each line +// that holds more than a comment, in order, each marked whether it's a rule. The proxy, devvm +// network and devvm doctor all read policy files with it. +func ParsePolicy(text string) []PolicyLine { + lines, _ := parsePolicy(text) + return lines +} + +// parsePolicy is ParsePolicy, with the rules of the lines that are rules. +func parsePolicy(text string) ([]PolicyLine, []rule) { + var ( + lines []PolicyLine + rules []rule + ) + for i, l := range strings.Split(strings.TrimPrefix(text, "\xef\xbb\xbf"), "\n") { // a byte-order mark isn't text + s, _, _ := strings.Cut(l, "#") + if s = strings.TrimSpace(s); s == "" { + continue + } + r, ok := parseRule(s) + lines = append(lines, PolicyLine{N: i + 1, Text: s, OK: ok}) + if ok { + rules = append(rules, r) + } } - r, ok := parseRule(s) - switch { - case !ok: - return false - case r.prefix.IsValid(): - return true - case r.host == "**": - return true - } - h := strings.TrimPrefix(r.host, "*.") - return !strings.ContainsAny(h, "[]") && hostOK(h) + return lines, rules } func (r rule) portOK(port int) bool { @@ -125,20 +192,37 @@ type policy struct { files []string mtime map[string]time.Time rules map[string][]rule + // broken is, for each file with one, the first of its lines that starts with ! and isn't a + // rule (BrokenDeny): while any file has one, the policy denies everything. + broken map[string]PolicyLine } func newPolicy(files []string) *policy { - return &policy{files: files, mtime: map[string]time.Time{}, rules: map[string][]rule{}} + return &policy{files: files, mtime: map[string]time.Time{}, rules: map[string][]rule{}, broken: map[string]PolicyLine{}} } -func (p *policy) all() []rule { +// BrokenDeny reports whether l is a line that reads as a deny, starting with !, but isn't a +// rule. Its proxy can't know what it would deny, so it denies everything while the line is there. +func BrokenDeny(l PolicyLine) bool { return !l.OK && strings.HasPrefix(l.Text, "!") } + +// all returns the policy's rules, and while a file has a broken deny (BrokenDeny), why the policy +// denies everything. +func (p *policy) all() ([]rule, string) { p.mu.Lock() defer p.mu.Unlock() var out []rule for _, f := range p.files { st, err := os.Stat(f) - if err != nil { - delete(p.rules, f) // a missing file has no rules + if errors.Is(err, fs.ErrNotExist) { + // A missing file has no rules, and one that comes back is read again, whatever its + // mtime (a rename back, a restore that keeps it). + delete(p.rules, f) + delete(p.broken, f) + delete(p.mtime, f) + continue + } + if err != nil { // keep its last rules and broken deny, as for a read that fails + out = append(out, p.rules[f]...) continue } if !st.ModTime().Equal(p.mtime[f]) { @@ -147,25 +231,53 @@ func (p *policy) all() []rule { out = append(out, p.rules[f]...) continue } - var rs []rule - for _, l := range strings.Split(string(b), "\n") { - if r, ok := parseRule(l); ok { - rs = append(rs, r) - } - } - p.rules[f], p.mtime[f] = rs, st.ModTime() - logf("policy %s: %d rules", f, len(rs)) + p.load(f, string(b)) + p.mtime[f] = st.ModTime() } out = append(out, p.rules[f]...) } - return out + for _, f := range p.files { + if l, ok := p.broken[f]; ok { + return out, fmt.Sprintf("%s:%d isn't a rule but reads as a deny (%q), so this VM's proxy denies everything until it's fixed", f, l.N, l.Text) + } + } + return out, "" +} + +// load takes file f's rules from its text b, logging each line that isn't a rule and noting the +// first broken deny. With p.mu held. +func (p *policy) load(f, b string) { + lines, rs := parsePolicy(b) + delete(p.broken, f) + for _, l := range lines { + switch { + case BrokenDeny(l): + logf("%s:%d: not a rule but reads as a deny, so everything is denied: %q", f, l.N, l.Text) + if _, ok := p.broken[f]; !ok { + p.broken[f] = l + } + case !l.OK: + logf("%s:%d: not a rule, skipped: %q", f, l.N, l.Text) + } + } + p.rules[f] = rs + logf("policy %s: %d rules", f, len(rs)) } // decide whether host:port may be reached. host is a name or an address literal. It returns the // matching rule's text, or why not. func (p *policy) decide(host string, port int) (bool, string) { + ok, why, _ := p.verdict(host, port) + return ok, why +} + +// verdict is decide, and whether a refusal is one no allow rule would lift: a broken deny's. +func (p *policy) verdict(host string, port int) (bool, string, bool) { host = strings.ToLower(strings.TrimSuffix(host, ".")) - rs := p.all() + rs, broken := p.all() + if broken != "" { + return false, broken, true + } addr, err := netip.ParseAddr(strings.Trim(host, "[]")) isAddr := err == nil match := func(r rule) bool { @@ -179,22 +291,26 @@ func (p *policy) decide(host string, port int) (bool, string) { } for _, r := range rs { if r.deny && match(r) { - return false, "denied by " + r.text + return false, "denied by " + r.text, false } } for _, r := range rs { if !r.deny && match(r) { - return true, r.text + return true, r.text, false } } - return false, "not on the allowlist" + return false, "not on the allowlist", false } // byName: an allow rule that names host, as itself or under *.domain, for port: one that's more -// than **, which allows any host. +// than **, which allows any host. None while a deny is broken. func (p *policy) byName(host string, port int) bool { host = strings.ToLower(strings.TrimSuffix(host, ".")) - for _, r := range p.all() { + rs, broken := p.all() + if broken != "" { + return false + } + for _, r := range rs { if !r.deny && r.host != "**" && r.portOK(port) && r.matchHost(host) { return true } @@ -207,7 +323,11 @@ func (p *policy) addrAllowed(a netip.Addr, port int) bool { if p.addrDenied(a, port) { return false } - for _, r := range p.all() { + rs, broken := p.all() + if broken != "" { + return false + } + for _, r := range rs { if !r.deny && r.portOK(port) && r.matchAddr(a) { return true } @@ -215,10 +335,15 @@ func (p *policy) addrAllowed(a netip.Addr, port int) bool { return false } -// addrDenied: a deny rule for address a. A deny beats any allow, including a host rule whose name -// resolves to a, so every address the proxy dials is checked against it. +// addrDenied: a deny rule for address a, or a broken deny (every address). A deny beats any +// allow, including a host rule whose name resolves to a, so every address the proxy dials is +// checked against it. func (p *policy) addrDenied(a netip.Addr, port int) bool { - for _, r := range p.all() { + rs, broken := p.all() + if broken != "" { + return true + } + for _, r := range rs { if r.deny && r.portOK(port) && r.matchAddr(a) { return true } diff --git a/internal/proxy/proxy.go b/internal/proxy/proxy.go index 5b72f543..78f9d1de 100644 --- a/internal/proxy/proxy.go +++ b/internal/proxy/proxy.go @@ -394,6 +394,10 @@ func block(w http.ResponseWriter, e Event) { w.Header().Set("X-Devvm-Blocked", e.Host) w.Header().Set("Content-Type", "text/plain; charset=utf-8") w.WriteHeader(http.StatusForbidden) + if e.Refused { // no rule would allow it: no allow command + fmt.Fprintf(w, "devvm: %s:%d is refused (%s).\n", e.Host, e.Port, e.Reason) + return + } fmt.Fprintf(w, "devvm: %s:%d is blocked (%s). Allow it on the host with: devvm network allow %s\n", e.Host, e.Port, e.Reason, ruleFor(e.Host, e.Port)) } @@ -418,24 +422,41 @@ func AllowRule(host string, port int) (string, bool) { // check runs the policy and the floor; on success it returns the rule that allowed host:port. plain // is a plain HTTP request, which goes through HTTP_PROXY's upstream rather than HTTPS_PROXY's. func check(ctx context.Context, host string, port int, plain bool) (string, string) { - ok, why := pol.decide(host, port) + rule, why, _ := checkRefused(ctx, host, port, plain) + return rule, why +} + +// checkRefused is check, and whether a refusal is one no allow rule would lift (a broken deny's), +// which its event marks Refused. +func checkRefused(ctx context.Context, host string, port int, plain bool) (string, string, bool) { + ok, rule, refused := pol.verdict(host, port) // rule: the allowing rule, or why not if !ok { - return "", why + return "", rule, refused } + if why := floorCheck(ctx, host, port, plain); why != "" { + return "", why, false + } + return rule, "", false +} + +// floorCheck is check past the rules for an allowed host: the address floor, or the company +// proxy's. It returns why not, or "". +func floorCheck(ctx context.Context, host string, port int, plain bool) string { floor := func() error { _, err := resolve(ctx, host, port); return err } if upstreamFor(host, port, plain) != nil { floor = func() error { return floorUpstream(ctx, host, port) } } - if err := floor(); err != nil { - if errors.Is(err, errFloor) { - return "", "it " + err.Error() + "; allow the address itself to reach it" - } - if errors.Is(err, errUnresolved) { - return "", err.Error() - } - return "", "can't resolve it: " + err.Error() + err := floor() + switch { + case err == nil: + return "" + case errors.Is(err, errFloor): + return "it " + err.Error() + "; allow the address itself to reach it" + case errors.Is(err, errUnresolved): + return err.Error() + default: + return "can't resolve it: " + err.Error() } - return why, "" } func handleConnect(w http.ResponseWriter, r *http.Request) { @@ -453,9 +474,9 @@ func handleConnect(w http.ResponseWriter, r *http.Request) { return } e := Event{Host: host, Port: port, Method: "CONNECT"} - rule, why := check(r.Context(), host, port, false) + rule, why, refused := checkRefused(r.Context(), host, port, false) if why != "" { - e.Reason = why + e.Reason, e.Refused = why, refused block(w, e) return } @@ -585,8 +606,8 @@ func handleHTTP(w http.ResponseWriter, r *http.Request) { return } e := Event{Host: host, Port: port, Method: r.Method, Path: r.URL.Path, Agent: r.UserAgent()} - if _, why := check(r.Context(), host, port, scheme == "http"); why != "" { - e.Reason = why + if _, why, refused := checkRefused(r.Context(), host, port, scheme == "http"); why != "" { + e.Reason, e.Refused = why, refused block(w, e) return } diff --git a/internal/proxy/proxy_test.go b/internal/proxy/proxy_test.go index bd40ac73..d651315c 100644 --- a/internal/proxy/proxy_test.go +++ b/internal/proxy/proxy_test.go @@ -15,6 +15,7 @@ import ( "os" "os/exec" "path/filepath" + "slices" "strconv" "strings" "sync" @@ -108,6 +109,193 @@ github.com:22 } } +// ParsePolicy is strict: a line holds one rule, as devvm network allow takes it, a comment, or +// nothing. Every other line is returned as not a rule, with its number, and the proxy skips it. +func TestParsePolicy(t *testing.T) { + text := "# a comment\n" + + "\n" + + "example.com\n" + + " *.github.com # with a comment\n" + + "example.com:x\n" + // a port that isn't one: never a host named "example.com:x" + "api.example.com:0\n" + + "! bad.example.com\n" + // a space after the ! + "!!worse.example.com\n" + + "a b\n" + + "*\n" + + "a*.example.com\n" + + "[::1]\n" + + "fe80::1%eth0\n" + + "x/y\n" + + "example.com:+22\n" + + "*.10.0.0.1\n" + + "a..example.com\n" + + "10.0.0.0/8:8080\n" + + "Example.ORG.\n" + + "\r\n" + + "last.example.com" // no newline at the end + type line struct { + n int + text string + ok bool + } + want := []line{ + {3, "example.com", true}, + {4, "*.github.com", true}, + {5, "example.com:x", false}, + {6, "api.example.com:0", false}, + {7, "! bad.example.com", false}, + {8, "!!worse.example.com", false}, + {9, "a b", false}, + {10, "*", false}, + {11, "a*.example.com", false}, + {12, "[::1]", false}, + {13, "fe80::1%eth0", false}, + {14, "x/y", false}, + {15, "example.com:+22", false}, + {16, "*.10.0.0.1", false}, + {17, "a..example.com", false}, + {18, "10.0.0.0/8:8080", true}, + {19, "Example.ORG.", true}, + {21, "last.example.com", true}, + } + var got []line + for _, l := range ParsePolicy(text) { + got = append(got, line{l.N, l.Text, l.OK}) + } + if !slices.Equal(got, want) { + t.Errorf("ParsePolicy =\n%v\nwant\n%v", got, want) + } + // Each line ParsePolicy takes is ValidRule's, and the other way round. + for _, l := range ParsePolicy(text) { + if ValidRule(l.Text) != l.OK { + t.Errorf("line %d %q: ParsePolicy %v, ValidRule %v", l.N, l.Text, l.OK, ValidRule(l.Text)) + } + } +} + +// The proxy reads its policy files through ParsePolicy: it skips each line that isn't a rule, +// logging the file, the line's number and its text, and keeps the file's rules. A trailing dot +// in a rule names the same host. +func TestPolicySkipsBadLines(t *testing.T) { + var logged strings.Builder + old := logger.Writer() + logger.SetOutput(&logged) + t.Cleanup(func() { logger.SetOutput(old) }) + f := filepath.Join(t.TempDir(), "policy") + must(t, os.WriteFile(f, []byte("**\nexample.com:x\n!example.org.\n!::ffff:10.0.0.0/104\n"), 0o600)) + p := newPolicy([]string{f}) + if ok, why := p.decide("example.org", 443); ok { + t.Errorf("example.org allowed (%s): the deny with a trailing dot was skipped", why) + } + for _, a := range []string{"10.0.0.1", "::ffff:10.0.0.1"} { + if !p.addrDenied(netip.MustParseAddr(a), 443) { + t.Errorf("%s isn't denied by the IPv4-mapped prefix", a) + } + } + if ok, why := p.decide("other.test", 443); !ok { + t.Errorf("other.test blocked: %s", why) + } + if want := f + `:2: not a rule, skipped: "example.com:x"`; !strings.Contains(logged.String(), want) { + t.Errorf("the log has no %q:\n%s", want, logged.String()) + } +} + +// A line that reads as a deny, starting with !, but isn't a rule makes the policy deny +// everything, by name and by address, as a refusal no allow rule would lift, naming the file and +// line; fixing the line lifts it. +func TestPolicyBrokenDeny(t *testing.T) { + var logged strings.Builder + old := logger.Writer() + logger.SetOutput(&logged) + t.Cleanup(func() { logger.SetOutput(old) }) + dir := t.TempDir() + good, f := filepath.Join(dir, "good"), filepath.Join(dir, "policy") + must(t, os.WriteFile(good, []byte("**\n10.0.0.0/8\n"), 0o600)) + must(t, os.WriteFile(f, []byte("ok.test\n! bad.example.com # a space after the !\n"), 0o600)) + p := newPolicy([]string{good, f}) + for _, h := range []string{"bad.example.com", "other.test", "10.0.0.1"} { + ok, why, refused := p.verdict(h, 443) + if ok || !refused || !strings.Contains(why, f+":2 isn't a rule but reads as a deny") { + t.Errorf("%s: allowed %v, refused %v (%s)", h, ok, refused, why) + } + } + if !p.addrDenied(netip.MustParseAddr("10.0.0.1"), 443) || p.byName("ok.test", 443) { + t.Error("an address or a name still allowed past a broken deny") + } + if want := f + `:2: not a rule but reads as a deny, so everything is denied: "! bad.example.com"`; !strings.Contains(logged.String(), want) { + t.Errorf("the log has no %q:\n%s", want, logged.String()) + } + // Through the proxy: 403, refused, with no allow command. + oldPol, oldOut, oldAuth := pol, logOut, proxyAuth + var events strings.Builder + pol, logOut, proxyAuth = p, &events, "" + t.Cleanup(func() { pol, logOut, proxyAuth = oldPol, oldOut, oldAuth }) + req := httptest.NewRequestWithContext(t.Context(), http.MethodConnect, "http://other.test:443", nil) + req.Host = "other.test:443" + w := httptest.NewRecorder() + handler(w, req) + if w.Code != http.StatusForbidden || strings.Contains(w.Body.String(), "network allow") || !strings.Contains(w.Body.String(), "refused") { + t.Errorf("answered %d %q", w.Code, w.Body.String()) + } + if !strings.Contains(events.String(), `"refused":true`) { + t.Errorf("logged %s", events.String()) + } + // An absolute-form request too. + req = httptest.NewRequestWithContext(t.Context(), http.MethodGet, "http://other.test/x", nil) + w = httptest.NewRecorder() + handler(w, req) + if w.Code != http.StatusForbidden || strings.Contains(w.Body.String(), "network allow") { + t.Errorf("absolute form: answered %d %q", w.Code, w.Body.String()) + } + if p.addrAllowed(netip.MustParseAddr("10.0.0.1"), 443) { + t.Error("an address rule passes the floor past a broken deny") + } + // Fixed, everything the rules allow is allowed again. + must(t, os.WriteFile(f, []byte("ok.test\n!bad.example.com\n"), 0o600)) + later := time.Now().Add(2 * time.Second) + must(t, os.Chtimes(f, later, later)) + if ok, why := p.decide("other.test", 443); !ok { + t.Errorf("other.test still blocked once the line was fixed: %s", why) + } + if ok, _ := p.decide("bad.example.com", 443); ok { + t.Error("bad.example.com allowed once its deny was fixed") + } +} + +// A policy file that goes and comes back with the same mtime (renamed back, restored with its +// times) is read again: its denies, a broken one too, hold again. A leading byte-order mark is +// no part of the first line. +func TestPolicyFileBack(t *testing.T) { + dir := t.TempDir() + f, away := filepath.Join(dir, "policy"), filepath.Join(dir, "away") + must(t, os.WriteFile(f, []byte("\xef\xbb\xbf!bad.test\n**\n"), 0o600)) + p := newPolicy([]string{f}) + if ok, _ := p.decide("bad.test", 443); ok { + t.Fatal("bad.test allowed: the byte-order mark hid its deny") + } + must(t, os.Rename(f, away)) + if ok, _ := p.decide("bad.test", 443); ok { + t.Fatal("bad.test allowed with no policy file") + } + must(t, os.Rename(away, f)) + if ok, why := p.decide("bad.test", 443); ok { + t.Errorf("bad.test allowed once its file came back (%s)", why) + } + // The same with a broken deny, its file back with its old mtime. + must(t, os.WriteFile(f, []byte("**\n! bad.test\n"), 0o600)) + later := time.Now().Add(2 * time.Second) + must(t, os.Chtimes(f, later, later)) + if ok, _, refused := p.verdict("other.test", 443); ok || !refused { + t.Fatal("other.test allowed past a broken deny") + } + must(t, os.Rename(f, away)) + p.decide("other.test", 443) + must(t, os.Rename(away, f)) + if ok, _, refused := p.verdict("other.test", 443); ok || !refused { + t.Error("other.test allowed once the file with a broken deny came back") + } +} + func TestPolicyReload(t *testing.T) { f := filepath.Join(t.TempDir(), "policy") must(t, os.WriteFile(f, []byte("a.test\n"), 0o600)) @@ -321,6 +509,21 @@ func TestValidRule(t *testing.T) { {"fe80::1%eth0", false}, {"x/y", false}, {"a\nb", false}, + {"example.com.", true}, + {"example.com:+22", false}, + {"example.com:", false}, + {"*.10.0.0.1", false}, + {"a..example.com", false}, + {".example.com", false}, + {"[example.com]:22", false}, + {"[10.0.0.1]:22", false}, + {"! example.com", false}, + {"example.com ", false}, + {"Kevil.com", false}, // the Kelvin sign, which ToLower folds into k + {"a\x1b[31mb", false}, + {"::ffff:10.0.0.0/104", true}, + {"::ffff:0.0.0.0/80", false}, + {"127.1", false}, } { if got := ValidRule(c.rule); got != c.ok { t.Errorf("ValidRule(%q) = %v; want %v", c.rule, got, c.ok) @@ -521,7 +724,8 @@ func (s *syncBuffer) String() string { } // The rule syntax: whatever a policy file holds, parsing doesn't panic, a rule's text parses -// back to the same rule, and a host rule never holds a space or a slash. +// back to the same rule, a host rule never holds a space or a slash, and ParsePolicy marks a line +// a rule exactly when ValidRule takes it. func FuzzParseRule(f *testing.F) { for _, s := range []string{ "example.com", "*.github.com # c", "github.com:22", "!evil.github.com", "10.1.2.3", @@ -530,6 +734,11 @@ func FuzzParseRule(f *testing.F) { f.Add(s) } f.Fuzz(func(t *testing.T, line string) { + for _, l := range ParsePolicy(line) { + if l.OK != ValidRule(l.Text) || l.Text == "" || strings.ContainsAny(l.Text, "#\n") { + t.Fatalf("%q: line %+v, ValidRule %v", line, l, ValidRule(l.Text)) + } + } r, ok := parseRule(line) if !ok { if ValidRule(line) { @@ -544,6 +753,9 @@ func FuzzParseRule(f *testing.F) { if strings.ContainsAny(r.host, " /\\#") { t.Fatalf("%q: host %q", line, r.host) } + if h := r.host; h != "" && h != "**" && !strings.HasPrefix(h, "*.") && (!hostOK(h) || !r.matchHost(h)) { + t.Fatalf("%q: host %q isn't a host it matches", line, h) + } _ = r.matchHost("example.com") _ = r.matchAddr(netip.MustParseAddr("64:ff9b::a00:1")) }) diff --git a/internal/vm/network.go b/internal/vm/network.go index b7d6216e..5ada2eb5 100644 --- a/internal/vm/network.go +++ b/internal/vm/network.go @@ -245,6 +245,12 @@ func (e Net) PolicyChange(ctx context.Context, rules []string, deny, remove, glo vm = t.f.Name file = netpolicy.VMPolicyFile(e.Dirs, vm) } + // The file's lines that aren't rules, once it's changed (or not). + defer func() { + for _, m := range netpolicy.PolicyWarnings([]string{file}) { + e.Warn(m) + } + }() if remove { for _, r := range rules { switch ok, err := netpolicy.RemoveRule(file, r); { diff --git a/internal/vm/network_test.go b/internal/vm/network_test.go index e9b571d4..08fc562b 100644 --- a/internal/vm/network_test.go +++ b/internal/vm/network_test.go @@ -25,7 +25,7 @@ func TestNetwork(t *testing.T) { shown := func(want string) { t.Helper() s, err := n.Network(t.Context()) - if err != nil || s.Policy != want || len(s.Rules) == 0 || !strings.HasSuffix(s.Rules[0].Path, "/layers/base.policy") || len(s.Rules[0].Rules) == 0 { + if err != nil || s.Policy != want || len(s.Rules) == 0 || !strings.HasSuffix(s.Rules[0].Path, "/layers/base.policy") || len(s.Rules[0].Rules()) == 0 { t.Errorf("Network = %+v, %v; want %s", s, names(err), want) } } diff --git a/locales/en.toml b/locales/en.toml index 7abc831a..804d8efb 100644 --- a/locales/en.toml +++ b/locales/en.toml @@ -1527,6 +1527,14 @@ other = "devvm removed {{.rule}} from every VM's rules." description = "rule is what was typed, quoted" other = "{{.rule}} isn't in {{.file}}." +[policy_not_rule] +description = "doctor's warning for a policy file's line that isn't a rule; line is its number, rule its text, quoted" +other = "Line {{.line}} of {{.file}}, {{.rule}}, isn't a rule, so VMs' proxies skip it. Fix the line or remove it." + +[policy_broken_deny] +description = "a policy file's line that starts with ! but isn't a rule; line is its number, rule its text, quoted" +other = "Line {{.line}} of {{.file}}, {{.rule}}, reads as a deny but isn't a rule, so every VM whose proxy reads that file denies everything until it's fixed. Fix the line or remove it." + [policy_failed] description = "reason is an error from the system, in English" other = "Reading or changing the network policy rules failed: {{.reason}}." diff --git a/testdata/script/network_rules.txtar b/testdata/script/network_rules.txtar index 61f009f7..48e323b0 100644 --- a/testdata/script/network_rules.txtar +++ b/testdata/script/network_rules.txtar @@ -80,11 +80,42 @@ stdout '^# \S*/config/devvm/policy\n \*\.corp\.test\n# \S*/vms/devvm-net-[0-9a- # --json: the same, each file with its rules; it only shows. exec devvm network --json stdout '\A{\n "version": 1,\n "policy": "(on|unenforced)",\n "allowlist": \[\n {\n "file": "\S*/layers/base\.policy",\n "rules": \[\n' -stdout '^ "file": "\S*/vms/devvm-net-[0-9a-f]{14}\.policy",\n "rules": \[\n "!bad\.example\.com",\n "example\.com"\n \]\n' +stdout '^ "file": "\S*/vms/devvm-net-[0-9a-f]{14}\.policy",\n "rules": \[\n "!bad\.example\.com",\n "example\.com"\n \],\n "not_rules": \[\]\n' ! stderr . ! exec devvm network --json off stderr '^devvm: json_shows_only command=devvm network$' +# A line that isn't a rule: devvm network marks it with its number, +# --json lists it, and doctor warns of it. +exec sh -c 'echo "example.com:x # not a port" >> "$GLOBAL"' +exec devvm network +stdout '^# \S*/config/devvm/policy\n \*\.corp\.test\n example\.com:x # not a rule, skipped \(line 4\)\n' +exec devvm network --json +stdout '"rules": \[\n "\*\.corp\.test"\n \],\n "not_rules": \[\n {\n "line": 4,\n "text": "example\.com:x"\n }\n \]\n' +exec devvm doctor +stderr '^devvm: policy_not_rule file=\S*/config/devvm/policy line=4 rule=example\.com:x$' +# Changing the file warns of it too, and a line that reads as a deny but +# isn't a rule warns that the VMs' proxies deny everything: on a change, +# a launch and in doctor. +exec devvm network allow -g ok2.test +stdout '^==> rule_added_global rule=ok2\.test$' +stderr '^devvm: policy_not_rule file=\S*/config/devvm/policy line=4 rule=example\.com:x$' +exec sh -c 'echo "! worse.test" >> "$GLOBAL"' +exec devvm network rm -g ok2.test +stderr '^devvm: policy_broken_deny file=\S*/config/devvm/policy line=5 rule=! worse\.test$' +stderr '^devvm: policy_not_rule file=\S*/config/devvm/policy line=4 rule=example\.com:x$' +# (The stubs leave the VM unenforced, so the launch stops it after warning.) +! exec devvm +stderr '^devvm: policy_broken_deny file=\S*/config/devvm/policy line=5 rule=! worse\.test$' +exec devvm doctor +stderr '^devvm: policy_broken_deny file=\S*/config/devvm/policy line=5 rule=! worse\.test$' +exec sh -c 'grep -v -e "example.com:x" -e "worse.test" "$GLOBAL" > "$WORK/g" && cat "$WORK/g" > "$GLOBAL"' +exec devvm doctor +! stderr 'policy_not_rule|policy_broken_deny' +exec devvm network allow -g ok3.test +! stderr . +exec devvm network rm -g ok3.test + # A VM without network policy: devvm network shows it off, with its # rules, and changing them says they don't apply. mkdir $WORK/off diff --git a/tests/e2e.sh b/tests/e2e.sh index c101068b..d7db4e62 100755 --- a/tests/e2e.sh +++ b/tests/e2e.sh @@ -2016,6 +2016,17 @@ check "devvm network allow applies at once to the running VM's proxy, devvm netw '$D' network rm example.com >/dev/null && [[ \$(limactl shell --workdir / $vm bash -lc 'curl -s -m 20 -o /dev/null -w %{http_code} http://example.com/' > '$vms/$vm.policy' && + { [[ \$(limactl shell --workdir / $vm bash -lc 'curl -s -m 20 -o /dev/null -w %{http_code} http://github.com/' &1 | grep -q '^devvm: policy_broken_deny '; ok=\$?; } ; + cp '$work/vm.policy' '$vms/$vm.policy' && [[ \${ok:-1} == 0 ]] && + limactl shell --workdir / $vm bash -lc 'curl -fsS -m 20 -o /dev/null https://github.com'