oficina / equipo Public

vminit: root init, measurements, hooks and the runner launch

Task 8 of hosted runners slice 2. equipo-vm-init replaces the managed
mounts under /etc with the image's copy (empty resolv.conf), reaps
orphans, and serves the lifecycle hooks on Config.HookAddr only. /run
runs once: it measures the runner, vm-init and the sandbox policy into
a root-owned 0444 measured.json, runs the root probes into root.json for
certification, writes the runner's 0600 bootstrap, then starts
hosted-run or hosted-certify as the runner user with no groups, no
ambient capabilities, no_new_privs and an exact five-name environment.
/suspend and /resume answer 409 (S2-6). Mutation checks 28 to 42 are in
HOSTED-SLICE2-PROGRESS.md.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev cb29ccd5b32f3e5509ef77f23edd93b94e978410 parent b3b3056
9 files changed, +2,308 −0
  • cmd/equipo-vm-init/main.go +91 −0
  • docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md +35 −0
  • internal/vminit/hooks.go +356 −0
  • internal/vminit/init.go +272 −0
  • internal/vminit/init_test.go +906 −0
  • internal/vminit/measure.go +105 −0
  • internal/vminit/mounts_linux.go +149 −0
  • internal/vminit/reap_linux.go +144 −0
  • internal/vminit/rootprobe_linux.go +250 −0
diff --git a/cmd/equipo-vm-init/main.go b/cmd/equipo-vm-init/main.go
new file mode 100644
index 00000000..537012e5
--- /dev/null
+++ b/cmd/equipo-vm-init/main.go
@@ -0,0 +1,91 @@
+//go:build linux
+
+// Command equipo-vm-init is the root init of a hosted runner's MicroVM
+// (spec §4 and §7; package vminit). The image starts it as root with
+// every path and address given explicitly:
+//
+// equipo-vm-init -hooks ADDR:PORT -runner-user USER -runner PATH \
+// -state DIR -results DIR -etc-source DIR \
+// -policy FILE [-policy FILE ...] \
+// [-resolver ADDR ...] [-metadata ADDR:PORT ...]
+//
+// -resolver and -metadata name what the certification probes check
+// besides the nameservers the managed resolv.conf lists at boot; a probe
+// with nothing to check fails. It imports no AWS package.
+package main
+
+import (
+ "context"
+ "flag"
+ "fmt"
+ "log"
+ "net/netip"
+ "os"
+ "os/signal"
+ "strings"
+ "syscall"
+
+ "amadan.net/oficina/equipo/internal/vminit"
+)
+
+// list is a repeatable string flag.
+type list []string
+
+func (l *list) String() string { return strings.Join(*l, ",") }
+func (l *list) Set(v string) error { *l = append(*l, v); return nil }
+
+func main() {
+ cfg, err := parse(os.Args[1:])
+ if err != nil {
+ log.Printf("equipo-vm-init: %v", err)
+ os.Exit(2)
+ }
+ ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
+ defer stop()
+ log.Printf("equipo-vm-init: hooks on %s", cfg.HookAddr)
+ if err := vminit.Main(ctx, cfg); err != nil {
+ log.Printf("equipo-vm-init: %v", err)
+ os.Exit(1)
+ }
+}
+
+func parse(args []string) (vminit.Config, error) {
+ fl := flag.NewFlagSet("equipo-vm-init", flag.ContinueOnError)
+ hooks := fl.String("hooks", "", "the hook listener, the image's hooks.port (ADDR:PORT)")
+ var cfg vminit.Config
+ fl.StringVar(&cfg.RunnerUser, "runner-user", "", "the unprivileged account the runner runs as")
+ fl.StringVar(&cfg.RunnerBinary, "runner", "", "equipo-runner's absolute path")
+ fl.StringVar(&cfg.StateDir, "state", "", "the runner's state directory, empty in the image")
+ fl.StringVar(&cfg.ResultsDir, "results", "", "the directory for measured.json and root.json")
+ fl.StringVar(&cfg.Mounts.EtcSource, "etc-source", "", "the image's copy of /etc, bound read-only over /etc")
+ var policies, resolvers, metadata list
+ fl.Var(&policies, "policy", "a sandbox policy file to measure (repeatable)")
+ fl.Var(&resolvers, "resolver", "a managed resolver address the certification probe queries (repeatable)")
+ fl.Var(&metadata, "metadata", "a metadata endpoint ADDR:PORT the certification probe asks (repeatable)")
+ if err := fl.Parse(args); err != nil {
+ return cfg, err
+ }
+ if fl.NArg() != 0 {
+ return cfg, fmt.Errorf("unexpected argument %q", fl.Arg(0))
+ }
+ var err error
+ if cfg.HookAddr, err = netip.ParseAddrPort(*hooks); err != nil {
+ return cfg, fmt.Errorf("-hooks: %w", err)
+ }
+ cfg.PolicyFiles = policies
+ for _, r := range resolvers {
+ a, err := netip.ParseAddr(r)
+ if err != nil {
+ return cfg, fmt.Errorf("-resolver: %w", err)
+ }
+ cfg.Resolvers = append(cfg.Resolvers, a)
+ }
+ for _, m := range metadata {
+ a, err := netip.ParseAddrPort(m)
+ if err != nil {
+ return cfg, fmt.Errorf("-metadata: %w", err)
+ }
+ cfg.Metadata = append(cfg.Metadata, a)
+ }
+ return cfg, nil
+}
diff --git a/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md b/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md
index 508bfa86..b0b0d3a2 100644
--- a/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md
+++ b/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md
@@ -327,3 +327,38 @@ Mutation check (applied by script to `proxytest/harness.go`, restored and checke
27. Disable the `not_live` guard (its case became `false && (...)` with no refusal). Command: `CGO_ENABLED=0 go test ./internal/hostedproxy -run '^TestCertReportThroughProxy$' -count=1`. Observed: FAIL, `e2e_test.go:581: report over an unrevoked certificate of a launch no longer live = 200 , want 403 not_live`, `e2e_test.go:584: the controller accepted 4 reports, want c-1, c-2 and c-3`. Restored.
Also run: the brief's green command ok (0.16 s); `go test ./internal/hostedproxy/... ./cmd/equipo-hosted-proxy -count=1 -race` once, ok (3.4 s and 1.1 s); staticcheck v0.7.0 clean; gofmt clean; `make budget build vet` ok (127 directories within budget).
+
+## Task 8
+
+Root init and the lifecycle hooks. New: `internal/vminit/{init.go,hooks.go,measure.go,mounts_linux.go,reap_linux.go,rootprobe_linux.go,init_test.go}` (package `vminit`, Linux only; 1276 source and 906 test lines, default budgets) and `cmd/equipo-vm-init/main.go` (flags only). No AWS import (TestProviderTypesStayInAdapter passes).
+
+- `Main(ctx, Config)`: checks the config, becomes the subreaper unless PID 1, reads the nameservers of the managed `/etc/resolv.conf`, runs `PlanMounts` then `applyMounts`, starts the reaper, and serves the hooks on `Config.HookAddr` only (`serve`, tested over a real listener on 127.0.0.1). `Config` adds to the brief's fields `PolicyFiles` (measured; at least one), `Resolvers` and `Metadata` (what the certification probes check; no defaults are guessed, a probe with nothing to check fails).
+- Mounts (plan over `fs.FS`, execution a thin `x/sys/unix` layer): detach every mount at or under `/etc` (latest first, then deepest first), bind `MountPlan.EtcSource` over `/etc`, remount it `ro,nosuid,nodev`. The plan refuses an `EtcSource` that is not a clean absolute directory outside `/etc`, or whose `resolv.conf` is not an empty regular file (missing, non-empty, a link, a directory), and an unreadable or malformed mountinfo.
+- Hooks under `/aws/lambda-microvms/runtime/v1/`, POST only (other methods 405, other paths 404). `/run` is claimed once at entry, whatever its outcome (a second answers 409 `run_once`); reads `{"microvmId","runHookPayload"}` (body at most 16 KiB), the VM ID by `isolatedjob.Ref.Valid`, the payload 1 to 4096 bytes of printable ASCII, `hostedwire.DecodeStrict` into `BootstrapV2`, then `Encode` for every field rule (400 `bad_run`); refuses a state directory that is missing, a link or not empty (412 `state_not_empty`); refuses a runner user that maps to uid or gid 0. Then, in order: results directory root's 0755; `measured.json` (runner, `/proc/self/exe`, each policy file and `PolicySetDigest`), O_EXCL|O_NOFOLLOW, 0444, root's; for certification `root.json` likewise; state directory and `StateDir/tmp` the runner's 0700; `StateDir/bootstrap.json` (`RunnerBootstrap{vm_ref, bootstrap}`) 0600 the runner's; then the launch (500 `run_failed` on any failure). The launch runs on a context the provider's disconnect cannot cancel. `/ready` 412 unless the state directory is empty. `/suspend` and `/resume` 409 `no_pause`. `/terminate` sends SIGTERM to the runner's process group while it runs (its pid is forgotten once reaped).
+- Launch: `equipo-runner hosted-run` (checks) or `hosted-certify` (certification); `Credential{uid, gid}` with no groups and setgroups called, no `AmbientCaps`, `Setpgid`, working directory the state directory, environment exactly `HOME`, `PATH`, `TMPDIR`, `EQUIPO_HOSTED_BOOTSTRAP`, `EQUIPO_HOSTED_RESULTS`. Go's `SysProcAttr` has no no_new_privs field, so `launchSpec.NoNewPrivs` carries it and `forkRunner` sets it with `prctl` on a locked, never-unlocked thread and forks from it (the flag dies with that thread); `forkRunner` refuses a spec without it or with ambient capabilities.
+- Reaper: the one waiter (`wait4(-1, WNOHANG)` on SIGCHLD and every 5 s); `start` forks under its lock so an instant exit is still delivered to the watcher; anything else is an orphan, reaped and counted.
+- Root probes (`rootprobe_linux.go`, network behind `RootNet`): `root_vpc_dns_silent` (an A query to each resolver, configured plus the managed resolv.conf's, over UDP and TCP; any reply fails; no resolver known fails), `root_metadata_no_credential` (per endpoint, an IMDSv2 token PUT, then the credentials path without a token and, if one was issued, with it; any 200 with a body fails; none configured fails), `root_resolv_conf_empty` (an empty regular file, not a link). Each `{name, stage:"root", ok, detail}`; details carry lengths, never bodies. A network probe whose context ended fails as `interrupted`.
+
+RED (`CGO_ENABLED=0 go test ./internal/vminit -count=1` against a declarations-only skeleton): every test failed on its assertion, for example `init_test.go:203: first /run = 501 "todo", want 200`, `init_test.go:597: ops =` (TestMountPlanEmptiesResolver), `init_test.go:544: helper: no child processes` (TestRunnerStartsWithNoNewPrivs), `init_test.go:772: all silent: probes = [], want ...`.
+
+GREEN: `go test ./internal/vminit -count=1` ok (18 tests, 0.13 s); `-count=20` ok; `-race` once ok (2.2 s); `GOOS=linux go build ./cmd/equipo-vm-init` ok (with `-o` into scratch, so no binary lands in the tree). TestRunnerStartsWithNoNewPrivs starts a real child; it skips only where the test process already has no_new_privs (inside the agent sandbox), and ran and passed outside it.
+
+Mutation checks (each applied by script, the named test run with `CGO_ENABLED=0 go test ./internal/vminit -run '^<Test>$' -count=1`, then restored and checked byte for byte):
+
+28. Accept a second `/run` (`if false && h.ran`, hooks.go). TestRunHookOnce: FAIL, `init_test.go:209: second /run = 412 "state_not_empty", want 409 "run_once"`, `init_test.go:218: /run after a refused /run = 200 "ok", want 409 "run_once"`, `init_test.go:221: runner launches = 1 and 1, want 1 and 0`. Restored.
+29. Pass the parent environment through (`Env: append(os.Environ(), ...)`, `runnerLaunch`). TestRunnerEnvironmentExact: FAIL, `init_test.go:273: runner environment = AWS_SECRET_ACCESS_KEY=leak EQUIPO_LEAK=1 HOME=/home/equipo HOME=/root ...`. Restored.
+30. Measure after the drop (the `h.sys.start` block moved before the measurements, `launch`). TestMeasurementsRootOwned: FAIL, `init_test.go:334: measured.json at the runner's launch = [map[]], want map[...]`, `init_test.go:349: measured.json made root's at event 2, runner started at 0`, the same for root.json, and `init_test.go:370: /run over an existing measured.json = 500 with 1 launches, want 500 and none`. Restored.
+31. Accept a non-empty image resolv.conf (`|| st.Size() != 0` removed, `PlanMounts`). TestMountPlanEmptiesResolver: FAIL, `init_test.go:628: resolver not empty: plan accepted`. Restored.
+32. Detach nothing under /etc (`if false && (...)`, `PlanMounts`). TestMountPlanEmptiesResolver: FAIL, `init_test.go:597: ops =` and `init_test.go:602: /etc/resolv.conf after the plan comes from "managed:/resolv.conf", want the image's empty copy`. Restored.
+33. Launch spec without no_new_privs (`NoNewPrivs: false`). TestRunnerDropsCapabilities: FAIL, `init_test.go:501: launch without no_new_privs`. Restored.
+34. `forkRunner` skips the prctl. TestRunnerStartsWithNoNewPrivs (outside the sandbox): FAIL, `init_test.go:552: child status lacks "NoNewPrivs:\t1"`. Restored.
+35. `/suspend` and `/resume` answer 200. TestSuspendRefused: FAIL, `init_test.go:440: /suspend = 200 "no_pause", want 409` (and /resume). Restored.
+36. No state check in `/run` (`false && err != nil`). TestRunHookRefusesStateLeft: FAIL, `init_test.go:237: /run with state left = 200 "ok", want 412 "state_not_empty"`, `init_test.go:240: the runner started 1 times ...`, `init_test.go:243: measured.json after a refused /run: <nil>, want it absent`. Restored.
+37. A runner user mapping to root accepted (`if false && (...)`). TestRunnerDropsCapabilities: FAIL, `init_test.go:514: /run with a root runner user = 200 "ok" with 1 launches, want 500 and none`. Restored.
+38. Metadata probe skips the tokenless request once a token is issued (`tokens := []string{token}`). First run: survived (no fake endpoint issued a token yet answered only without one). Added the case "credential, no token needed" (a token PUT answers, the credentials path refuses that token, the tokenless request names a role). Rerun: FAIL, `init_test.go:784: credential, no token needed: probes = [... root_metadata_no_credential OK:true ...]`. Restored.
+39. Metadata probe never uses the token (`_ = token`). TestRootProbes: FAIL, `init_test.go:784: credential, v2: probes = [... OK:true ...]`. Restored.
+40. DNS probe over UDP only. TestRootProbes: FAIL, `init_test.go:791: DNS probe never asked tcp 10.0.0.2:53` and `init_test.go:784: tcp answer: probes = [{root_vpc_dns_silent OK:true ...`. Restored.
+41. DNS probe ignores its context ending (`if false && ctx.Err() != nil`). TestRootProbesInterrupted: FAIL, `init_test.go:807: probe {Name:root_vpc_dns_silent Stage:root OK:true ...} after its context ended, want not ok and interrupted`. Restored.
+42. Metadata probe ignores its context ending. TestRootProbesInterrupted: FAIL, `init_test.go:807: probe {Name:root_metadata_no_credential Stage:root OK:true ...}`. Restored.
+
+Also run: staticcheck v0.7.0 on `./internal/vminit ./cmd/equipo-vm-init` clean; gofmt clean; `go test ./internal/isolatedjob -run TestProviderTypesStayInAdapter -count=1` ok; `make budget build vet` ok (129 directories within budget).
diff --git a/internal/vminit/hooks.go b/internal/vminit/hooks.go
new file mode 100644
index 00000000..913dedce
--- /dev/null
+++ b/internal/vminit/hooks.go
@@ -0,0 +1,356 @@
+//go:build linux
+
+package vminit
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "net/http"
+ "os"
+ "path/filepath"
+ "strings"
+ "sync"
+ "syscall"
+
+ "amadan.net/oficina/equipo/internal/hostedwire"
+ "amadan.net/oficina/equipo/internal/isolatedjob"
+)
+
+// The provider's lifecycle hooks (awsjob doc.go): POSTs under hookPrefix.
+// /ready is called only while the image is built.
+const (
+ hookPrefix = "/aws/lambda-microvms/runtime/v1/"
+ // maxHookBody bounds a hook's body: a bootstrap of MaxBootstrapBytes,
+ // JSON-escaped, inside the provider's envelope.
+ maxHookBody = 16 << 10
+)
+
+// Each refusal answers its reason as the body, so the provider's logs and
+// the tests can tell the rules apart.
+const (
+ reasonRunOnce = "run_once" // a /run after the first
+ reasonBadRun = "bad_run" // the body or its bootstrap breaks a rule
+ reasonStateLeft = "state_not_empty" // the runner's state directory holds something
+ reasonFailed = "run_failed" // measuring, writing or the launch failed
+ reasonNoPause = "no_pause" // /suspend and /resume (decision S2-6)
+)
+
+// RunnerBootstrap is the file vm-init writes for the runner, at
+// EnvBootstrap: the launch's bootstrap and the VM's own ID from the /run
+// hook. It is the runner user's, mode 0600, and the runner deletes it
+// once read (Task 12).
+type RunnerBootstrap struct {
+ VMRef isolatedjob.Ref `json:"vm_ref"`
+ Bootstrap hostedwire.BootstrapV2 `json:"bootstrap"`
+}
+
+// hooks serves the lifecycle hooks. /run happens once: the first call
+// claims it whatever its outcome, since a failed /run ends the VM.
+type hooks struct {
+ cfg Config
+ sys system
+ mux *http.ServeMux
+
+ mu sync.Mutex
+ ran bool
+ runner int // the runner's pid while it runs; 0 before and after
+}
+
+func newHooks(cfg Config, sys system) *hooks {
+ h := &hooks{cfg: cfg, sys: sys, mux: http.NewServeMux()}
+ h.mux.HandleFunc("POST "+hookPrefix+"run", h.run)
+ h.mux.HandleFunc("POST "+hookPrefix+"ready", h.ready)
+ h.mux.HandleFunc("POST "+hookPrefix+"suspend", h.noPause)
+ h.mux.HandleFunc("POST "+hookPrefix+"resume", h.noPause)
+ h.mux.HandleFunc("POST "+hookPrefix+"terminate", h.terminate)
+ return h
+}
+
+func (h *hooks) ServeHTTP(w http.ResponseWriter, r *http.Request) { h.mux.ServeHTTP(w, r) }
+
+func answer(w http.ResponseWriter, code int, text string) {
+ w.Header().Set("Content-Type", "text/plain; charset=utf-8")
+ w.WriteHeader(code)
+ _, _ = io.WriteString(w, text+"\n")
+}
+
+func (h *hooks) runnerPID() int {
+ h.mu.Lock()
+ defer h.mu.Unlock()
+ return h.runner
+}
+
+// run is the /run hook. Its errors are logged by rule, never with the
+// payload, which carries the launch's codes.
+func (h *hooks) run(w http.ResponseWriter, r *http.Request) {
+ h.mu.Lock()
+ if h.ran {
+ h.mu.Unlock()
+ answer(w, http.StatusConflict, reasonRunOnce)
+ return
+ }
+ h.ran = true
+ h.mu.Unlock()
+
+ vm, boot, err := readRun(r.Body)
+ if err != nil {
+ h.sys.logf("vm-init: /run refused: %v", err)
+ answer(w, http.StatusBadRequest, reasonBadRun)
+ return
+ }
+ if err := stateEmpty(h.cfg.StateDir); err != nil {
+ h.sys.logf("vm-init: /run refused: %v", err)
+ answer(w, http.StatusPreconditionFailed, reasonStateLeft)
+ return
+ }
+ // The launch outlives the provider dropping the call: a half-done
+ // /run would leave probes cut short and files without a runner.
+ pid, sub, err := h.launch(context.WithoutCancel(r.Context()), vm, boot)
+ if err != nil {
+ h.sys.logf("vm-init: /run failed: %v", err)
+ answer(w, http.StatusInternalServerError, reasonFailed)
+ return
+ }
+ h.sys.logf("vm-init: runner %s started as pid %d for VM %s, launch %s", sub, pid, vm, boot.LaunchID)
+ answer(w, http.StatusOK, "ok")
+}
+
+// readRun reads the /run body: {"microvmId", "runHookPayload"}, the
+// payload a BootstrapV2 that keeps every rule Encode checks.
+func readRun(body io.Reader) (isolatedjob.Ref, hostedwire.BootstrapV2, error) {
+ var none hostedwire.BootstrapV2
+ raw, err := io.ReadAll(io.LimitReader(body, maxHookBody+1))
+ if err != nil {
+ return "", none, fmt.Errorf("reading the body: %w", err)
+ }
+ if len(raw) > maxHookBody {
+ return "", none, errors.New("the body is too large")
+ }
+ var in struct {
+ MicrovmID string `json:"microvmId"`
+ RunHookPayload string `json:"runHookPayload"`
+ }
+ if err := json.Unmarshal(raw, &in); err != nil {
+ return "", none, errors.New("the body is not the run hook's JSON")
+ }
+ vm := isolatedjob.Ref(in.MicrovmID)
+ if !vm.Valid() {
+ return "", none, errors.New("the VM ID is not 1 to 128 letters, digits and '-'")
+ }
+ p := in.RunHookPayload
+ if p == "" || len(p) > hostedwire.MaxBootstrapBytes || !printableASCII(p) {
+ return "", none, fmt.Errorf("the payload must be 1 to %d bytes of printable ASCII", hostedwire.MaxBootstrapBytes)
+ }
+ var b hostedwire.BootstrapV2
+ if err := hostedwire.DecodeStrict(strings.NewReader(p), &b); err != nil {
+ return "", none, fmt.Errorf("the payload: %w", err)
+ }
+ // Encode checks every field's rule; its output is not needed.
+ if _, err := b.Encode(); err != nil {
+ return "", none, fmt.Errorf("the payload: %w", err)
+ }
+ return vm, b, nil
+}
+
+func printableASCII(s string) bool {
+ for i := 0; i < len(s); i++ {
+ if s[i] < 0x20 || s[i] > 0x7e {
+ return false
+ }
+ }
+ return true
+}
+
+// stateEmpty fails unless dir is a directory (not a link) with nothing
+// in it.
+func stateEmpty(dir string) error {
+ st, err := os.Lstat(dir)
+ if err != nil {
+ return fmt.Errorf("state directory: %w", err)
+ }
+ if !st.IsDir() {
+ return fmt.Errorf("state directory %s is not a directory", dir)
+ }
+ f, err := os.Open(dir)
+ if err != nil {
+ return fmt.Errorf("state directory: %w", err)
+ }
+ defer f.Close()
+ names, err := f.Readdirnames(1)
+ if errors.Is(err, io.EOF) {
+ return nil
+ }
+ if err != nil {
+ return fmt.Errorf("state directory: %w", err)
+ }
+ return fmt.Errorf("state directory %s holds %q", dir, names[0])
+}
+
+// launch does /run's work in its order: everything root measures and
+// probes is written before the runner exists, then the runner's files,
+// then the runner. It returns the runner's pid and subcommand.
+func (h *hooks) launch(ctx context.Context, vm isolatedjob.Ref, boot hostedwire.BootstrapV2) (int, string, error) {
+ acct, err := h.sys.lookup(h.cfg.RunnerUser)
+ if err != nil {
+ return 0, "", fmt.Errorf("runner user: %w", err)
+ }
+ if acct.UID <= 0 || acct.GID <= 0 {
+ return 0, "", fmt.Errorf("runner user %s maps to root's uid or gid", h.cfg.RunnerUser)
+ }
+ if !filepath.IsAbs(acct.Home) {
+ return 0, "", fmt.Errorf("runner user %s has no absolute home", h.cfg.RunnerUser)
+ }
+ sub := SubcommandChecks
+ if boot.Purpose == hostedwire.PurposeCertification {
+ sub = SubcommandCertify
+ }
+
+ // Root's: measurements and, for certification, the root probes, made
+ // while vm-init is the only process that could have changed anything.
+ if err := h.rootDir(h.cfg.ResultsDir); err != nil {
+ return 0, "", err
+ }
+ m, err := measure(h.cfg.RunnerBinary, h.sys.self, h.cfg.PolicyFiles)
+ if err != nil {
+ return 0, "", err
+ }
+ if err := h.writeRootJSON(MeasuredFile, m); err != nil {
+ return 0, "", err
+ }
+ if boot.Purpose == hostedwire.PurposeCertification {
+ probes := rootProbes(ctx, h.sys.net, h.sys.resolvers, h.cfg.Metadata, h.sys.resolvConf)
+ if err := h.writeRootJSON(RootProbeFile, probes); err != nil {
+ return 0, "", err
+ }
+ }
+
+ // The runner's: its state directory, TMPDIR and the bootstrap.
+ if err := h.own(h.cfg.StateDir, acct, 0o700); err != nil {
+ return 0, "", err
+ }
+ tmp := filepath.Join(h.cfg.StateDir, "tmp")
+ if err := os.Mkdir(tmp, 0o700); err != nil {
+ return 0, "", fmt.Errorf("runner TMPDIR: %w", err)
+ }
+ if err := h.own(tmp, acct, 0o700); err != nil {
+ return 0, "", err
+ }
+ raw, err := json.Marshal(RunnerBootstrap{VMRef: vm, Bootstrap: boot})
+ if err != nil {
+ return 0, "", fmt.Errorf("bootstrap file: %w", err)
+ }
+ if err := writeOwned(h.sys.chown, filepath.Join(h.cfg.StateDir, BootstrapFile), raw, 0o600, acct.UID, acct.GID); err != nil {
+ return 0, "", err
+ }
+
+ pid, exited, err := h.sys.start(runnerLaunch(h.cfg, acct, sub))
+ if err != nil {
+ return 0, "", fmt.Errorf("starting the runner: %w", err)
+ }
+ h.mu.Lock()
+ h.runner = pid
+ h.mu.Unlock()
+ go func() {
+ <-exited
+ h.mu.Lock()
+ if h.runner == pid {
+ h.runner = 0
+ }
+ h.mu.Unlock()
+ }()
+ return pid, sub, nil
+}
+
+// runnerLaunch is the runner's launch: as the runner user, no
+// supplementary groups, no ambient capabilities, no_new_privs, its own
+// process group, and an environment of exactly five names.
+func runnerLaunch(cfg Config, a account, sub string) launchSpec {
+ return launchSpec{
+ Path: cfg.RunnerBinary,
+ Args: []string{cfg.RunnerBinary, sub},
+ Env: []string{
+ "HOME=" + a.Home,
+ "PATH=" + runnerPath,
+ "TMPDIR=" + filepath.Join(cfg.StateDir, "tmp"),
+ EnvBootstrap + "=" + filepath.Join(cfg.StateDir, BootstrapFile),
+ EnvResults + "=" + cfg.ResultsDir,
+ },
+ Dir: cfg.StateDir,
+ Sys: &syscall.SysProcAttr{
+ // Groups empty with NoSetGroups false: setgroups(0) clears
+ // root's supplementary groups.
+ Credential: &syscall.Credential{Uid: uint32(a.UID), Gid: uint32(a.GID)},
+ Setpgid: true,
+ },
+ NoNewPrivs: true,
+ }
+}
+
+// rootDir makes dir a directory of root's, 0755: the runner reads it and
+// can change nothing in it.
+func (h *hooks) rootDir(dir string) error {
+ if err := os.MkdirAll(dir, 0o755); err != nil {
+ return fmt.Errorf("results directory: %w", err)
+ }
+ st, err := os.Lstat(dir)
+ if err != nil || !st.IsDir() {
+ return fmt.Errorf("results directory %s is not a directory", dir)
+ }
+ if err := h.sys.chown(dir, 0, 0); err != nil {
+ return fmt.Errorf("results directory: %w", err)
+ }
+ if err := os.Chmod(dir, 0o755); err != nil {
+ return fmt.Errorf("results directory: %w", err)
+ }
+ return nil
+}
+
+// own gives path to the runner user with mode.
+func (h *hooks) own(path string, a account, mode os.FileMode) error {
+ if err := h.sys.chown(path, a.UID, a.GID); err != nil {
+ return fmt.Errorf("giving %s to the runner: %w", path, err)
+ }
+ if err := os.Chmod(path, mode); err != nil {
+ return fmt.Errorf("giving %s to the runner: %w", path, err)
+ }
+ return nil
+}
+
+func (h *hooks) writeRootJSON(name string, v any) error {
+ raw, err := json.MarshalIndent(v, "", " ")
+ if err != nil {
+ return fmt.Errorf("%s: %w", name, err)
+ }
+ return writeOwned(h.sys.chown, filepath.Join(h.cfg.ResultsDir, name), append(raw, '\n'), 0o444, 0, 0)
+}
+
+// ready is the image build's /ready hook: the image may hold no runner
+// state (spec §4).
+func (h *hooks) ready(w http.ResponseWriter, _ *http.Request) {
+ if err := stateEmpty(h.cfg.StateDir); err != nil {
+ h.sys.logf("vm-init: /ready refused: %v", err)
+ answer(w, http.StatusPreconditionFailed, reasonStateLeft)
+ return
+ }
+ answer(w, http.StatusOK, "ok")
+}
+
+// noPause answers /suspend and /resume: a slice 2 VM is never paused
+// (decision S2-6).
+func (h *hooks) noPause(w http.ResponseWriter, _ *http.Request) {
+ answer(w, http.StatusConflict, reasonNoPause)
+}
+
+// terminate signals the runner's process group, if the runner is still
+// running, and answers 200.
+func (h *hooks) terminate(w http.ResponseWriter, _ *http.Request) {
+ if pid := h.runnerPID(); pid > 0 {
+ if err := h.sys.signal(pid, syscall.SIGTERM); err != nil {
+ h.sys.logf("vm-init: /terminate: signalling the runner: %v", err)
+ }
+ }
+ answer(w, http.StatusOK, "ok")
+}
diff --git a/internal/vminit/init.go b/internal/vminit/init.go
new file mode 100644
index 00000000..dc84dfec
--- /dev/null
+++ b/internal/vminit/init.go
@@ -0,0 +1,272 @@
+//go:build linux
+
+// Package vminit is equipo-vm-init, the root init of a hosted runner's
+// MicroVM (spec §4 and §7). As root it replaces the provider's managed
+// mounts under /etc with the image's copy (an empty resolv.conf among
+// it), reaps orphaned processes, and serves the provider's lifecycle
+// hooks on the image's hooks.port. The /run hook measures the runner, vm-init
+// and the sandbox policy into a root-owned results file, runs the
+// root-before-drop probes for a certification launch, writes the bootstrap
+// for the runner user, and only then starts the runner as that user, with
+// no capabilities and no_new_privs. It imports no AWS package.
+//
+// Everything privileged is a plan or a record here (PlanMounts, launchSpec,
+// the system hooks), so tests run unprivileged; the Linux layer that
+// carries it out is thin (applyMounts, forkRunner, the reaper's wait).
+package vminit
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "io/fs"
+ "log"
+ "net"
+ "net/http"
+ "net/netip"
+ "os"
+ "os/user"
+ "path/filepath"
+ "slices"
+ "strconv"
+ "strings"
+ "syscall"
+ "time"
+)
+
+// Config is how the image starts vm-init.
+type Config struct {
+ // HookAddr is the one address the hook server listens on: the
+ // image's hooks.port.
+ HookAddr netip.AddrPort
+ // RunnerUser is the unprivileged account the runner runs as.
+ RunnerUser string
+ // RunnerBinary is equipo-runner's absolute path.
+ RunnerBinary string
+ // StateDir is the runner's state directory: empty in the image
+ // (spec §4), the runner's own from /run on.
+ StateDir string
+ // ResultsDir holds measured.json and root.json, root's and read-only
+ // to the runner.
+ ResultsDir string
+ // Mounts is what root init does to /etc before serving.
+ Mounts MountPlan
+ // PolicyFiles are the sandbox policy files measured with the runner.
+ PolicyFiles []string
+ // Resolvers are managed resolver addresses the certification probe
+ // queries, besides the nameservers the managed resolv.conf named at
+ // boot.
+ Resolvers []netip.Addr
+ // Metadata are the metadata endpoints the certification probe asks
+ // for a credential.
+ Metadata []netip.AddrPort
+}
+
+// The runner's launch.
+const (
+ SubcommandChecks = "hosted-run" // purpose "checks"
+ SubcommandCertify = "hosted-certify" // purpose "certification"
+ // EnvBootstrap names the runner's bootstrap file (RunnerBootstrap).
+ EnvBootstrap = "EQUIPO_HOSTED_BOOTSTRAP"
+ // EnvResults names ResultsDir.
+ EnvResults = "EQUIPO_HOSTED_RESULTS"
+ // BootstrapFile is the bootstrap's name in StateDir.
+ BootstrapFile = "bootstrap.json"
+ // runnerPath is the runner's whole PATH.
+ runnerPath = "/usr/local/bin:/usr/bin:/bin"
+ // selfExe is vm-init's own binary, as measured.
+ selfExe = "/proc/self/exe"
+ // resolvConf is the file root init empties and the probe reads.
+ resolvConf = "/etc/resolv.conf"
+)
+
+// check refuses a config vm-init cannot run safely with.
+func (c Config) check() error {
+ bad := func(format string, a ...any) error { return fmt.Errorf("vminit: config: "+format, a...) }
+ abs := func(p string) bool { return p != "" && filepath.IsAbs(p) && filepath.Clean(p) == p }
+ within := func(p, dir string) bool { return p == dir || strings.HasPrefix(p, dir+"/") }
+ switch {
+ case !c.HookAddr.IsValid() || c.HookAddr.Port() == 0:
+ return bad("hook address must be an address and a port")
+ case c.RunnerUser == "" || strings.ContainsAny(c.RunnerUser, ":/\n"):
+ return bad("runner user must be an account name")
+ case !abs(c.RunnerBinary):
+ return bad("runner binary must be a clean absolute path")
+ case !abs(c.StateDir) || !abs(c.ResultsDir):
+ return bad("state and results directories must be clean absolute paths")
+ case within(c.StateDir, c.ResultsDir) || within(c.ResultsDir, c.StateDir):
+ // The runner owns its state directory, so results inside it
+ // would be the runner's to replace.
+ return bad("state and results directories must not hold each other")
+ case len(c.PolicyFiles) == 0:
+ return bad("at least one sandbox policy file must be measured")
+ }
+ seen := map[string]bool{}
+ for _, p := range c.PolicyFiles {
+ if !abs(p) || seen[p] {
+ return bad("policy files must be distinct clean absolute paths")
+ }
+ seen[p] = true
+ }
+ for _, a := range c.Resolvers {
+ if !a.IsValid() || a.Zone() != "" {
+ return bad("resolver addresses must be addresses without a zone")
+ }
+ }
+ for _, m := range c.Metadata {
+ if !m.IsValid() || m.Port() == 0 || m.Addr().Zone() != "" {
+ return bad("metadata endpoints must be addresses and ports without a zone")
+ }
+ }
+ return nil
+}
+
+// account is the runner user as the system knows it.
+type account struct {
+ UID, GID int
+ Home string
+}
+
+// launchSpec is the runner's launch, whole: what forkRunner starts. Go's
+// SysProcAttr has no no_new_privs field, so NoNewPrivs carries it.
+type launchSpec struct {
+ Path string
+ Args, Env []string
+ Dir string
+ Sys *syscall.SysProcAttr
+ NoNewPrivs bool
+}
+
+// system is every action of the hooks that needs root or the network.
+type system struct {
+ lookup func(name string) (account, error)
+ chown func(path string, uid, gid int) error
+ // start launches the runner; the channel closes when it has exited
+ // and been reaped.
+ start func(launchSpec) (int, <-chan struct{}, error)
+ signal func(pid int, sig syscall.Signal) error // the process group of pid
+ net RootNet
+ // self is vm-init's binary; resolvConf the file the probe reads.
+ self, resolvConf string
+ // resolvers are the managed resolvers the DNS probe queries.
+ resolvers []netip.Addr
+ logf func(format string, a ...any)
+}
+
+// Main is root init: it checks cfg, becomes the subreaper unless it is
+// PID 1, reads the managed resolvers, replaces the managed mounts, starts
+// reaping and serves the hooks on cfg.HookAddr until ctx ends.
+func Main(ctx context.Context, cfg Config) error {
+ if err := cfg.check(); err != nil {
+ return err
+ }
+ if os.Getpid() != 1 {
+ if err := setSubreaper(); err != nil {
+ return fmt.Errorf("vminit: subreaper: %w", err)
+ }
+ }
+ root := os.DirFS("/")
+ // The managed resolv.conf names the resolvers the certification probe
+ // must find silent; read it before the plan hides it.
+ managed := managedResolvers(root)
+ ops, err := PlanMounts(cfg.Mounts, root)
+ if err != nil {
+ return err
+ }
+ if err := applyMounts(ops); err != nil {
+ return err
+ }
+ rp := newReaper(wait4Any, log.Printf)
+ go rp.run(ctx)
+ h := newHooks(cfg, system{
+ lookup: lookupAccount,
+ chown: os.Lchown,
+ start: func(s launchSpec) (int, <-chan struct{}, error) {
+ return rp.start(func() (int, error) { return forkRunner(s) })
+ },
+ signal: func(pid int, sig syscall.Signal) error { return syscall.Kill(-pid, sig) },
+ net: hostNet{},
+ self: selfExe,
+ resolvConf: resolvConf,
+ resolvers: union(cfg.Resolvers, managed),
+ logf: log.Printf,
+ })
+ return serve(ctx, cfg, h)
+}
+
+// serve answers h on cfg.HookAddr, and only there, until ctx ends.
+func serve(ctx context.Context, cfg Config, h http.Handler) error {
+ ln, err := net.Listen("tcp", cfg.HookAddr.String())
+ if err != nil {
+ return fmt.Errorf("vminit: hooks: %w", err)
+ }
+ srv := &http.Server{Handler: h, ReadHeaderTimeout: 10 * time.Second, ReadTimeout: 30 * time.Second}
+ stopped := make(chan struct{})
+ go func() {
+ defer close(stopped)
+ <-ctx.Done()
+ sctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+ _ = srv.Shutdown(sctx)
+ }()
+ err = srv.Serve(ln)
+ if errors.Is(err, http.ErrServerClosed) {
+ <-stopped
+ return nil
+ }
+ return fmt.Errorf("vminit: hooks: %w", err)
+}
+
+// lookupAccount reads the runner user from the image's /etc/passwd.
+func lookupAccount(name string) (account, error) {
+ u, err := user.Lookup(name)
+ if err != nil {
+ return account{}, err
+ }
+ uid, err1 := strconv.Atoi(u.Uid)
+ gid, err2 := strconv.Atoi(u.Gid)
+ if err1 != nil || err2 != nil {
+ return account{}, fmt.Errorf("user %s has a non-numeric uid or gid", name)
+ }
+ return account{UID: uid, GID: gid, Home: u.HomeDir}, nil
+}
+
+// managedResolvers returns the nameservers of the resolv.conf the
+// provider manages, as it stands before PlanMounts replaces it.
+func managedResolvers(root fs.FS) []netip.Addr {
+ b, err := fs.ReadFile(root, strings.TrimPrefix(resolvConf, "/"))
+ if err != nil {
+ return nil
+ }
+ return parseNameservers(b)
+}
+
+// parseNameservers returns the addresses of resolv.conf's nameserver
+// lines, in order, skipping any that do not parse.
+func parseNameservers(b []byte) []netip.Addr {
+ var out []netip.Addr
+ for _, line := range strings.Split(string(b), "\n") {
+ if i := strings.IndexAny(line, "#;"); i >= 0 {
+ line = line[:i]
+ }
+ f := strings.Fields(line)
+ if len(f) < 2 || f[0] != "nameserver" {
+ continue
+ }
+ if a, err := netip.ParseAddr(f[1]); err == nil && a.Zone() == "" {
+ out = append(out, a)
+ }
+ }
+ return out
+}
+
+// union is a and b's addresses, each once, in first-seen order.
+func union(a, b []netip.Addr) []netip.Addr {
+ var out []netip.Addr
+ for _, x := range slices.Concat(a, b) {
+ if !slices.Contains(out, x) {
+ out = append(out, x)
+ }
+ }
+ return out
+}
diff --git a/internal/vminit/init_test.go b/internal/vminit/init_test.go
new file mode 100644
index 00000000..52424968
--- /dev/null
+++ b/internal/vminit/init_test.go
@@ -0,0 +1,906 @@
+//go:build linux
+
+package vminit
+
+import (
+ "bytes"
+ "context"
+ "crypto/sha256"
+ "encoding/base64"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "io/fs"
+ "net"
+ "net/http"
+ "net/http/httptest"
+ "net/netip"
+ "os"
+ "path/filepath"
+ "slices"
+ "strings"
+ "sync"
+ "syscall"
+ "testing"
+ "testing/fstest"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/hostedwire"
+ "amadan.net/rastrillo/rastrillo/budget"
+)
+
+func TestMain(m *testing.M) {
+ // The helper mode of TestRunnerStartsWithNoNewPrivs: the test binary,
+ // started by forkRunner, copies its own /proc status to a file.
+ if out := os.Getenv("VMINIT_TEST_STATUS_TO"); out != "" {
+ st, err := os.ReadFile("/proc/self/status")
+ if err == nil {
+ err = os.WriteFile(out, st, 0o600)
+ }
+ if err != nil {
+ os.Exit(3)
+ }
+ os.Exit(0)
+ }
+ os.Exit(budget.Main(m))
+}
+
+const (
+ testVM = "mvm-0123abcd"
+ runnerUID = 1500
+ runnerGID = 1501
+ runnerHome = "/home/equipo"
+ runnerPID = 4242
+ runnerContent = "the runner binary"
+ selfContent = "equipo-vm-init itself"
+)
+
+// rig is a hooks server whose privileged actions are recorded, not done:
+// ownership changes, the runner launch and signals. Files are real, under
+// t.TempDir().
+type rig struct {
+ t *testing.T
+ cfg Config
+ h *hooks
+
+ mu sync.Mutex
+ events []string // "chown <name> uid:gid" and "start", in order
+ starts []launchSpec // every runner launch
+ atStart []map[string]string // measured.json as it stood at each launch; nil if absent
+ chowns map[string][2]int // last owner given to each path
+ signals []string
+ exited chan struct{}
+ policies []string
+}
+
+func newRig(t *testing.T) *rig {
+ t.Helper()
+ dir := t.TempDir()
+ r := &rig{t: t, chowns: map[string][2]int{}, exited: make(chan struct{})}
+ write := func(rel, content string) string {
+ p := filepath.Join(dir, rel)
+ if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(p, []byte(content), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ return p
+ }
+ state := filepath.Join(dir, "state")
+ if err := os.Mkdir(state, 0o700); err != nil {
+ t.Fatal(err)
+ }
+ r.policies = []string{write("policy/checks.json", `{"policy":"checks"}`), write("policy/net.json", `{"policy":"net"}`)}
+ r.cfg = Config{
+ HookAddr: netip.MustParseAddrPort("127.0.0.1:9001"),
+ RunnerUser: "equipo",
+ RunnerBinary: write("bin/equipo-runner", runnerContent),
+ StateDir: state,
+ ResultsDir: filepath.Join(dir, "results"),
+ Mounts: MountPlan{EtcSource: "/usr/lib/equipo/etc"},
+ PolicyFiles: r.policies,
+ Resolvers: []netip.Addr{netip.MustParseAddr("10.0.0.2")},
+ Metadata: []netip.AddrPort{netip.MustParseAddrPort("169.254.169.254:80")},
+ }
+ resolv := write("etc/resolv.conf", "")
+ sys := system{
+ lookup: func(name string) (account, error) {
+ if name != "equipo" {
+ return account{}, fmt.Errorf("no user %q", name)
+ }
+ return account{UID: runnerUID, GID: runnerGID, Home: runnerHome}, nil
+ },
+ chown: func(path string, uid, gid int) error {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ r.events = append(r.events, fmt.Sprintf("chown %s %d:%d", filepath.Base(path), uid, gid))
+ r.chowns[path] = [2]int{uid, gid}
+ return nil
+ },
+ start: func(spec launchSpec) (int, <-chan struct{}, error) {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ r.events = append(r.events, "start")
+ r.starts = append(r.starts, spec)
+ var m map[string]string
+ if raw, err := os.ReadFile(filepath.Join(r.cfg.ResultsDir, MeasuredFile)); err == nil {
+ if err := json.Unmarshal(raw, &m); err != nil {
+ t.Errorf("measured.json at the launch: %v", err)
+ }
+ }
+ r.atStart = append(r.atStart, m)
+ return runnerPID, r.exited, nil
+ },
+ signal: func(pid int, sig syscall.Signal) error {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ r.signals = append(r.signals, fmt.Sprintf("%d %v", pid, sig))
+ return nil
+ },
+ net: silentNet(),
+ self: write("vm-init", selfContent),
+ resolvConf: resolv,
+ logf: t.Logf,
+ }
+ r.h = newHooks(r.cfg, sys)
+ return r
+}
+
+func (r *rig) post(path string, body []byte) (int, string) {
+ r.t.Helper()
+ req := httptest.NewRequest(http.MethodPost, hookPrefix+path, bytes.NewReader(body))
+ rec := httptest.NewRecorder()
+ r.h.ServeHTTP(rec, req)
+ return rec.Code, strings.TrimSpace(rec.Body.String())
+}
+
+func (r *rig) run(purpose string) (int, string) {
+ r.t.Helper()
+ return r.post("run", runBody(r.t, testVM, bootstrapPayload(r.t, purpose)))
+}
+
+func bootstrapPayload(t *testing.T, purpose string) string {
+ t.Helper()
+ code := base64.RawURLEncoding.EncodeToString(bytes.Repeat([]byte{7}, 32))
+ b := hostedwire.BootstrapV2{
+ Version: hostedwire.BootstrapV2Version, Purpose: purpose, LaunchID: "l-1", AttemptID: "a-1",
+ ProxyCode: code,
+ Proxies: []netip.AddrPort{netip.MustParseAddrPort("10.1.0.5:3128")},
+ ProxyBoot: []netip.AddrPort{netip.MustParseAddrPort("10.1.0.5:3129")},
+ ProxyCAPin: strings.Repeat("ab", 32),
+ Services: []hostedwire.Service{{Host: "instance.example.test", Port: 443, Class: hostedwire.ServiceInstance}},
+ }
+ if purpose == hostedwire.PurposeChecks {
+ b.InstanceCode = code
+ }
+ raw, err := b.Encode()
+ if err != nil {
+ t.Fatal(err)
+ }
+ return string(raw)
+}
+
+func runBody(t *testing.T, vm, payload string) []byte {
+ t.Helper()
+ raw, err := json.Marshal(map[string]string{"microvmId": vm, "runHookPayload": payload})
+ if err != nil {
+ t.Fatal(err)
+ }
+ return raw
+}
+
+func sum(s string) string {
+ h := sha256.Sum256([]byte(s))
+ return hex.EncodeToString(h[:])
+}
+
+func TestRunHookOnce(t *testing.T) {
+ r := newRig(t)
+ if code, body := r.run(hostedwire.PurposeChecks); code != http.StatusOK {
+ t.Fatalf("first /run = %d %q, want 200", code, body)
+ }
+ // The second /run finds the state directory holding the bootstrap, so
+ // the refusal must be the run-once rule's, by its own code.
+ code, body := r.run(hostedwire.PurposeChecks)
+ if code != http.StatusConflict || body != reasonRunOnce {
+ t.Errorf("second /run = %d %q, want 409 %q", code, body, reasonRunOnce)
+ }
+ // A second /run that the first refused is refused too: /run is claimed
+ // once, whatever its outcome.
+ r2 := newRig(t)
+ if code, _ := r2.post("run", []byte(`{"microvmId":"bad id"}`)); code != http.StatusBadRequest {
+ t.Errorf("malformed /run = %d, want 400", code)
+ }
+ if code, body := r2.run(hostedwire.PurposeChecks); code != http.StatusConflict || body != reasonRunOnce {
+ t.Errorf("/run after a refused /run = %d %q, want 409 %q", code, body, reasonRunOnce)
+ }
+ if len(r.starts) != 1 || len(r2.starts) != 0 {
+ t.Errorf("runner launches = %d and %d, want 1 and 0", len(r.starts), len(r2.starts))
+ }
+}
+
+func TestRunHookRefusesStateLeft(t *testing.T) {
+ r := newRig(t)
+ if code, body := r.post("ready", nil); code != http.StatusOK {
+ t.Errorf("/ready with an empty state directory = %d %q, want 200", code, body)
+ }
+ if err := os.WriteFile(filepath.Join(r.cfg.StateDir, "machine.key"), []byte("k"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ if code, body := r.post("ready", nil); code != http.StatusPreconditionFailed || body != reasonStateLeft {
+ t.Errorf("/ready with state left = %d %q, want 412 %q", code, body, reasonStateLeft)
+ }
+ if code, body := r.run(hostedwire.PurposeChecks); code != http.StatusPreconditionFailed || body != reasonStateLeft {
+ t.Errorf("/run with state left = %d %q, want 412 %q", code, body, reasonStateLeft)
+ }
+ if len(r.starts) != 0 {
+ t.Errorf("the runner started %d times over a state directory not empty", len(r.starts))
+ }
+ if _, err := os.Stat(filepath.Join(r.cfg.ResultsDir, MeasuredFile)); !errors.Is(err, fs.ErrNotExist) {
+ t.Errorf("measured.json after a refused /run: %v, want it absent", err)
+ }
+
+ missing := newRig(t)
+ if err := os.Remove(missing.cfg.StateDir); err != nil {
+ t.Fatal(err)
+ }
+ if code, _ := missing.post("ready", nil); code != http.StatusPreconditionFailed {
+ t.Errorf("/ready with no state directory = %d, want 412", code)
+ }
+}
+
+func TestRunnerEnvironmentExact(t *testing.T) {
+ t.Setenv("AWS_SECRET_ACCESS_KEY", "leak")
+ t.Setenv("EQUIPO_LEAK", "1")
+ t.Setenv("HOME", "/root")
+ r := newRig(t)
+ if code, body := r.run(hostedwire.PurposeChecks); code != http.StatusOK {
+ t.Fatalf("/run = %d %q", code, body)
+ }
+ got := slices.Clone(r.starts[0].Env)
+ slices.Sort(got)
+ want := []string{
+ EnvBootstrap + "=" + filepath.Join(r.cfg.StateDir, BootstrapFile),
+ EnvResults + "=" + r.cfg.ResultsDir,
+ "HOME=" + runnerHome,
+ "PATH=" + runnerPath,
+ "TMPDIR=" + filepath.Join(r.cfg.StateDir, "tmp"),
+ }
+ if !slices.Equal(got, want) {
+ t.Errorf("runner environment =\n %s\nwant exactly\n %s", strings.Join(got, "\n "), strings.Join(want, "\n "))
+ }
+}
+
+func TestPurposeSelectsSubcommand(t *testing.T) {
+ for purpose, sub := range map[string]string{
+ hostedwire.PurposeChecks: SubcommandChecks,
+ hostedwire.PurposeCertification: SubcommandCertify,
+ } {
+ t.Run(purpose, func(t *testing.T) {
+ r := newRig(t)
+ if code, body := r.run(purpose); code != http.StatusOK {
+ t.Fatalf("/run = %d %q", code, body)
+ }
+ spec := r.starts[0]
+ if spec.Path != r.cfg.RunnerBinary || !slices.Equal(spec.Args, []string{r.cfg.RunnerBinary, sub}) {
+ t.Errorf("launch = %s %q, want %s [%s %s]", spec.Path, spec.Args, r.cfg.RunnerBinary, r.cfg.RunnerBinary, sub)
+ }
+ _, err := os.Stat(filepath.Join(r.cfg.ResultsDir, RootProbeFile))
+ if purpose == hostedwire.PurposeCertification && err != nil {
+ t.Errorf("certification /run wrote no root.json: %v", err)
+ }
+ if purpose == hostedwire.PurposeChecks && !errors.Is(err, fs.ErrNotExist) {
+ t.Errorf("checks /run: root.json %v, want none", err)
+ }
+ })
+ }
+}
+
+func TestMeasurementsRootOwned(t *testing.T) {
+ r := newRig(t)
+ if code, body := r.run(hostedwire.PurposeCertification); code != http.StatusOK {
+ t.Fatalf("/run = %d %q", code, body)
+ }
+ measured := filepath.Join(r.cfg.ResultsDir, MeasuredFile)
+ files := map[string]string{
+ "policy:" + r.policies[0]: sum(`{"policy":"checks"}`),
+ "policy:" + r.policies[1]: sum(`{"policy":"net"}`),
+ }
+ want := map[string]string{
+ MeasuredRunner: sum(runnerContent),
+ MeasuredVMInit: sum(selfContent),
+ MeasuredSandboxPolicy: PolicySetDigest(map[string]string{r.policies[0]: sum(`{"policy":"checks"}`), r.policies[1]: sum(`{"policy":"net"}`)}),
+ }
+ for k, v := range files {
+ want[k] = v
+ }
+ raw, err := os.ReadFile(measured)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var got map[string]string
+ if err := json.Unmarshal(raw, &got); err != nil {
+ t.Fatal(err)
+ }
+ if fmt.Sprint(got) != fmt.Sprint(want) {
+ t.Errorf("measured.json = %v\nwant %v", got, want)
+ }
+ // Measured before the drop: the file was complete when the runner
+ // started.
+ if len(r.atStart) != 1 || fmt.Sprint(r.atStart[0]) != fmt.Sprint(want) {
+ t.Errorf("measured.json at the runner's launch = %v, want %v", r.atStart, want)
+ }
+ for _, name := range []string{MeasuredFile, RootProbeFile} {
+ p := filepath.Join(r.cfg.ResultsDir, name)
+ st, err := os.Lstat(p)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if st.Mode() != 0o444 {
+ t.Errorf("%s mode %v, want -r--r--r--", name, st.Mode())
+ }
+ if r.chowns[p] != [2]int{0, 0} {
+ t.Errorf("%s owner %v, want root 0:0", name, r.chowns[p])
+ }
+ if i, j := slices.Index(r.events, "chown "+name+" 0:0"), slices.Index(r.events, "start"); i < 0 || j < 0 || i > j {
+ t.Errorf("%s made root's at event %d, runner started at %d: %q", name, i, j, r.events)
+ }
+ }
+ st, err := os.Lstat(r.cfg.ResultsDir)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if st.Mode().Perm() != 0o755 || r.chowns[r.cfg.ResultsDir] != [2]int{0, 0} {
+ t.Errorf("results directory %v owner %v, want 0755 root 0:0", st.Mode(), r.chowns[r.cfg.ResultsDir])
+ }
+
+ // A results directory already holding measured.json is refused: the
+ // file is never one the image or anyone else wrote.
+ r2 := newRig(t)
+ if err := os.MkdirAll(r2.cfg.ResultsDir, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(r2.cfg.ResultsDir, MeasuredFile), []byte(`{}`), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ if code, _ := r2.run(hostedwire.PurposeChecks); code != http.StatusInternalServerError || len(r2.starts) != 0 {
+ t.Errorf("/run over an existing measured.json = %d with %d launches, want 500 and none", code, len(r2.starts))
+ }
+}
+
+func TestBootstrapFileForRunner(t *testing.T) {
+ r := newRig(t)
+ if code, body := r.run(hostedwire.PurposeChecks); code != http.StatusOK {
+ t.Fatalf("/run = %d %q", code, body)
+ }
+ p := filepath.Join(r.cfg.StateDir, BootstrapFile)
+ st, err := os.Lstat(p)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if st.Mode() != 0o600 || r.chowns[p] != [2]int{runnerUID, runnerGID} {
+ t.Errorf("bootstrap file %v owner %v, want 0600 %d:%d", st.Mode(), r.chowns[p], runnerUID, runnerGID)
+ }
+ raw, err := os.ReadFile(p)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var f RunnerBootstrap
+ if err := hostedwire.DecodeStrict(bytes.NewReader(raw), &f); err != nil {
+ t.Fatal(err)
+ }
+ want := bootstrapPayload(t, hostedwire.PurposeChecks)
+ got, err := f.Bootstrap.Encode()
+ if f.VMRef != testVM || err != nil || string(got) != want {
+ t.Errorf("bootstrap file = %s, want vm %s and the payload", raw, testVM)
+ }
+ tmp := filepath.Join(r.cfg.StateDir, "tmp")
+ if st, err := os.Lstat(tmp); err != nil || !st.IsDir() || st.Mode().Perm() != 0o700 || r.chowns[tmp] != [2]int{runnerUID, runnerGID} {
+ t.Errorf("runner TMPDIR %v %v owner %v, want a 0700 directory of the runner's", st, err, r.chowns[tmp])
+ }
+}
+
+func TestRunHookRefusesBadPayload(t *testing.T) {
+ good := bootstrapPayload(t, hostedwire.PurposeChecks)
+ var b hostedwire.BootstrapV2
+ if err := json.Unmarshal([]byte(good), &b); err != nil {
+ t.Fatal(err)
+ }
+ b.Purpose = "shell"
+ other, err := json.Marshal(b)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for name, body := range map[string][]byte{
+ "not json": []byte("run"),
+ "bad vm id": runBody(t, "vm/../1", good),
+ "no vm id": runBody(t, "", good),
+ "unknown purpose": runBody(t, testVM, string(other)),
+ "extra field": runBody(t, testVM, strings.Replace(good, `{`, `{"shell":"sh",`, 1)),
+ "not ascii": runBody(t, testVM, strings.Replace(good, "l-1", "l-é1", 1)),
+ "payload too long": runBody(t, testVM, good+strings.Repeat(" ", hostedwire.MaxBootstrapBytes)),
+ } {
+ r := newRig(t)
+ if code, _ := r.post("run", body); code != http.StatusBadRequest || len(r.starts) != 0 {
+ t.Errorf("%s: /run = %d with %d launches, want 400 and none", name, code, len(r.starts))
+ }
+ }
+}
+
+func TestSuspendRefused(t *testing.T) {
+ r := newRig(t)
+ if code, _ := r.run(hostedwire.PurposeChecks); code != http.StatusOK {
+ t.Fatal("/run failed")
+ }
+ for _, hook := range []string{"suspend", "resume"} {
+ if code, body := r.post(hook, nil); code != http.StatusConflict || body != reasonNoPause {
+ t.Errorf("/%s = %d %q, want 409 %q", hook, code, body, reasonNoPause)
+ }
+ }
+ req := httptest.NewRequest(http.MethodGet, hookPrefix+"run", nil)
+ rec := httptest.NewRecorder()
+ r.h.ServeHTTP(rec, req)
+ if rec.Code != http.StatusMethodNotAllowed {
+ t.Errorf("GET /run = %d, want 405", rec.Code)
+ }
+ if code, _ := r.post("shell", nil); code != http.StatusNotFound {
+ t.Errorf("/shell = %d, want 404", code)
+ }
+ if len(r.signals) != 0 {
+ t.Errorf("suspend or resume signalled the runner: %q", r.signals)
+ }
+}
+
+func TestTerminateSignalsRunner(t *testing.T) {
+ r := newRig(t)
+ if code, _ := r.post("terminate", nil); code != http.StatusOK || len(r.signals) != 0 {
+ t.Errorf("/terminate before /run = %d, signals %q; want 200 and none", code, r.signals)
+ }
+ if code, _ := r.run(hostedwire.PurposeChecks); code != http.StatusOK {
+ t.Fatal("/run failed")
+ }
+ if code, _ := r.post("terminate", nil); code != http.StatusOK {
+ t.Errorf("/terminate = %d, want 200", code)
+ }
+ if want := []string{fmt.Sprintf("%d %v", runnerPID, syscall.SIGTERM)}; !slices.Equal(r.signals, want) {
+ t.Errorf("signals = %q, want %q", r.signals, want)
+ }
+ // Once the runner has exited its pid is forgotten, so a reused pid is
+ // never signalled.
+ close(r.exited)
+ deadline := time.Now().Add(5 * time.Second)
+ for r.h.runnerPID() != 0 && time.Now().Before(deadline) {
+ time.Sleep(time.Millisecond)
+ }
+ if code, _ := r.post("terminate", nil); code != http.StatusOK || len(r.signals) != 1 {
+ t.Errorf("/terminate after the runner exited = %d, signals %q; want 200 and no new signal", code, r.signals)
+ }
+}
+
+func TestRunnerDropsCapabilities(t *testing.T) {
+ r := newRig(t)
+ if code, body := r.run(hostedwire.PurposeChecks); code != http.StatusOK {
+ t.Fatalf("/run = %d %q", code, body)
+ }
+ spec := r.starts[0]
+ sys := spec.Sys
+ if sys == nil || sys.Credential == nil {
+ t.Fatalf("launch has no credential: %+v", sys)
+ }
+ c := sys.Credential
+ if c.Uid != runnerUID || c.Gid != runnerGID || len(c.Groups) != 0 || c.NoSetGroups {
+ t.Errorf("credential = %+v, want uid %d gid %d, no supplementary groups, setgroups called", c, runnerUID, runnerGID)
+ }
+ if len(sys.AmbientCaps) != 0 {
+ t.Errorf("ambient capabilities = %v, want none", sys.AmbientCaps)
+ }
+ if !spec.NoNewPrivs {
+ t.Error("launch without no_new_privs")
+ }
+ if !sys.Setpgid || sys.Cloneflags != 0 || sys.Unshareflags != 0 || sys.UidMappings != nil || sys.Chroot != "" {
+ t.Errorf("launch attributes = %+v, want only its own process group", sys)
+ }
+ if spec.Dir != r.cfg.StateDir {
+ t.Errorf("working directory %q, want the state directory", spec.Dir)
+ }
+
+ // A runner user that maps to root is refused.
+ root := newRig(t)
+ root.h.sys.lookup = func(string) (account, error) { return account{UID: 0, GID: 0, Home: "/root"}, nil }
+ if code, body := root.run(hostedwire.PurposeChecks); code != http.StatusInternalServerError || len(root.starts) != 0 {
+ t.Errorf("/run with a root runner user = %d %q with %d launches, want 500 and none", code, body, len(root.starts))
+ }
+ // forkRunner itself refuses a launch without no_new_privs.
+ if _, err := forkRunner(launchSpec{Path: "/bin/true", Args: []string{"true"}, Sys: &syscall.SysProcAttr{}}); err == nil {
+ t.Error("forkRunner started a process without no_new_privs")
+ }
+}
+
+// TestRunnerStartsWithNoNewPrivs starts a real process through forkRunner
+// (as this user, so no credential) and reads its status. Where the test
+// process already carries no_new_privs (a sandbox), the child would show
+// it whatever forkRunner did, so the test cannot tell and skips.
+func TestRunnerStartsWithNoNewPrivs(t *testing.T) {
+ self, err := os.ReadFile("/proc/self/status")
+ if err != nil {
+ t.Skip("no /proc/self/status")
+ }
+ if strings.Contains(string(self), "\nNoNewPrivs:\t1\n") {
+ t.Skip("this process already has no_new_privs; the child cannot show forkRunner set it")
+ }
+ out := filepath.Join(t.TempDir(), "status")
+ pid, err := forkRunner(launchSpec{
+ Path: os.Args[0], Args: []string{os.Args[0]}, Env: []string{"VMINIT_TEST_STATUS_TO=" + out},
+ Sys: &syscall.SysProcAttr{Setpgid: true}, NoNewPrivs: true,
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ var ws syscall.WaitStatus
+ if _, err := syscall.Wait4(pid, &ws, 0, nil); err != nil || ws.ExitStatus() != 0 {
+ t.Fatalf("helper: %v, status %v", err, ws)
+ }
+ st, err := os.ReadFile(out)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, want := range []string{"\nNoNewPrivs:\t1\n", "\nCapAmb:\t0000000000000000\n"} {
+ if !strings.Contains(string(st), want) {
+ t.Errorf("child status lacks %q", strings.TrimSpace(want))
+ }
+ }
+ // The flag stayed on the throwaway thread: this process still lacks it.
+ if now, _ := os.ReadFile("/proc/self/status"); strings.Contains(string(now), "\nNoNewPrivs:\t1\n") {
+ t.Error("forkRunner left no_new_privs on vm-init")
+ }
+}
+
+func mountinfo(lines ...string) *fstest.MapFile {
+ return &fstest.MapFile{Data: []byte(strings.Join(lines, "\n") + "\n")}
+}
+
+func TestMountPlanEmptiesResolver(t *testing.T) {
+ managed := mountinfo(
+ `22 1 253:1 / / rw,relatime shared:1 - ext4 /dev/vda rw`,
+ `23 22 0:21 / /proc rw,nosuid,nodev,noexec shared:2 - proc proc rw`,
+ `30 22 0:40 /resolv.conf /etc/resolv.conf rw,relatime - virtiofs managed rw`,
+ `31 22 0:40 /hosts /etc/hosts rw,relatime - virtiofs managed rw`,
+ `32 22 0:40 /host\040name /etc/host\040name rw,relatime - virtiofs managed rw`,
+ `33 30 0:40 /resolv.conf /etc/resolv.conf rw,relatime - virtiofs managed rw`,
+ `34 22 0:41 / /etcetera rw - tmpfs tmpfs rw`,
+ `35 22 0:42 / /etc/ssl/private rw - tmpfs tmpfs rw`,
+ )
+ fsys := fstest.MapFS{
+ "proc/self/mountinfo": managed,
+ "usr/lib/equipo/etc/resolv.conf": {Data: nil, Mode: 0o444},
+ "usr/lib/equipo/etc/passwd": {Data: []byte("root:x:0:0::/root:/bin/sh\n")},
+ }
+ plan := MountPlan{EtcSource: "/usr/lib/equipo/etc"}
+ ops, err := PlanMounts(plan, fsys)
+ if err != nil {
+ t.Fatal(err)
+ }
+ want := []MountOp{
+ // Deepest first, then the latest mounted first.
+ {Kind: OpDetach, Target: "/etc/ssl/private"},
+ {Kind: OpDetach, Target: "/etc/resolv.conf"},
+ {Kind: OpDetach, Target: "/etc/host name"},
+ {Kind: OpDetach, Target: "/etc/hosts"},
+ {Kind: OpDetach, Target: "/etc/resolv.conf"},
+ {Kind: OpBind, Source: "/usr/lib/equipo/etc", Target: "/etc"},
+ {Kind: OpRemountReadOnly, Target: "/etc"},
+ }
+ if !slices.Equal(ops, want) {
+ t.Errorf("ops =\n %v\nwant\n %v", ops, want)
+ }
+ // What /etc/resolv.conf is once the plan has run: every managed mount
+ // on it is gone and it comes from the image's copy, empty.
+ if src := viewAfter(ops, managed, "/etc/resolv.conf"); src != "/usr/lib/equipo/etc/resolv.conf" {
+ t.Errorf("/etc/resolv.conf after the plan comes from %q, want the image's empty copy", src)
+ }
+
+ for name, mutate := range map[string]func(fstest.MapFS){
+ "resolver not empty": func(f fstest.MapFS) {
+ f["usr/lib/equipo/etc/resolv.conf"] = &fstest.MapFile{Data: []byte("nameserver 10.0.0.2\n")}
+ },
+ "resolver missing": func(f fstest.MapFS) { delete(f, "usr/lib/equipo/etc/resolv.conf") },
+ "resolver a link": func(f fstest.MapFS) {
+ f["usr/lib/equipo/etc/resolv.conf"] = &fstest.MapFile{Data: []byte("/dev/null"), Mode: fs.ModeSymlink | 0o777}
+ },
+ "resolver a directory": func(f fstest.MapFS) {
+ delete(f, "usr/lib/equipo/etc/resolv.conf")
+ f["usr/lib/equipo/etc/resolv.conf/x"] = &fstest.MapFile{}
+ },
+ "no mountinfo": func(f fstest.MapFS) { delete(f, "proc/self/mountinfo") },
+ "bad mountinfo": func(f fstest.MapFS) {
+ f["proc/self/mountinfo"] = mountinfo("22 1 253:1 /")
+ },
+ } {
+ f := fstest.MapFS{}
+ for k, v := range fsys {
+ f[k] = v
+ }
+ mutate(f)
+ if _, err := PlanMounts(plan, f); err == nil {
+ t.Errorf("%s: plan accepted", name)
+ }
+ }
+ for _, src := range []string{"", "usr/lib/equipo/etc", "/etc", "/etc/copy", "/usr/lib/../etc", "/usr/lib/equipo/missing"} {
+ if _, err := PlanMounts(MountPlan{EtcSource: src}, fsys); err == nil {
+ t.Errorf("EtcSource %q accepted", src)
+ }
+ }
+}
+
+// viewAfter follows ops over the mounts in info and returns the source
+// path a lookup of target would reach: the image's copy if a bind covers
+// it, a managed mount's source if one is still on it, else the root file.
+func viewAfter(ops []MountOp, info *fstest.MapFile, target string) string {
+ type mnt struct{ point, source string }
+ var stack []mnt
+ for _, line := range strings.Split(strings.TrimSpace(string(info.Data)), "\n") {
+ f := strings.Fields(line)
+ stack = append(stack, mnt{unescapeMount(f[4]), "managed:" + f[3]})
+ }
+ for _, op := range ops {
+ switch op.Kind {
+ case OpDetach:
+ for i := len(stack) - 1; i >= 0; i-- {
+ if stack[i].point == op.Target {
+ stack = slices.Delete(stack, i, i+1)
+ break
+ }
+ }
+ case OpBind:
+ stack = append(stack, mnt{op.Target, op.Source})
+ }
+ }
+ best := mnt{"/", "/"}
+ for _, m := range stack {
+ // The last mount on the deepest covering point wins.
+ if (target == m.point || strings.HasPrefix(target, strings.TrimSuffix(m.point, "/")+"/")) && len(m.point) >= len(best.point) {
+ best = m
+ }
+ }
+ if strings.HasPrefix(best.source, "managed:") || best.point == "/" {
+ return best.source
+ }
+ return best.source + strings.TrimPrefix(target, best.point)
+}
+
+// fakeNet answers DNS from replies (keyed "udp 10.0.0.2:53") and HTTP
+// from web; everything else fails as a silent network does.
+type fakeNet struct {
+ replies map[string][]byte
+ web func(*http.Request) (int, string)
+ asked []string
+}
+
+func silentNet() *fakeNet { return &fakeNet{replies: map[string][]byte{}} }
+
+func (n *fakeNet) DNS(_ context.Context, network string, server netip.AddrPort, query []byte) ([]byte, error) {
+ n.asked = append(n.asked, network+" "+server.String())
+ if len(query) < 12 {
+ return nil, errors.New("short query")
+ }
+ if r, ok := n.replies[network+" "+server.String()]; ok {
+ return r, nil
+ }
+ return nil, os.ErrDeadlineExceeded
+}
+
+func (n *fakeNet) Do(req *http.Request) (*http.Response, error) {
+ n.asked = append(n.asked, req.Method+" "+req.URL.String()+" token="+req.Header.Get(imdsTokenHeader))
+ if n.web == nil {
+ return nil, os.ErrDeadlineExceeded
+ }
+ code, body := n.web(req)
+ return &http.Response{StatusCode: code, Body: io.NopCloser(strings.NewReader(body)), Request: req}, nil
+}
+
+func TestRootProbes(t *testing.T) {
+ dir := t.TempDir()
+ empty := filepath.Join(dir, "resolv.conf")
+ if err := os.WriteFile(empty, nil, 0o444); err != nil {
+ t.Fatal(err)
+ }
+ full := filepath.Join(dir, "resolv.full")
+ if err := os.WriteFile(full, []byte("nameserver 10.0.0.2\n"), 0o444); err != nil {
+ t.Fatal(err)
+ }
+ link := filepath.Join(dir, "resolv.link")
+ if err := os.Symlink(empty, link); err != nil {
+ t.Fatal(err)
+ }
+ resolvers := []netip.Addr{netip.MustParseAddr("10.0.0.2"), netip.MustParseAddr("169.254.169.253")}
+ meta := []netip.AddrPort{netip.MustParseAddrPort("169.254.169.254:80")}
+ credsPath := "/latest/meta-data/iam/security-credentials/"
+ imdsV2 := func(req *http.Request) (int, string) {
+ switch {
+ case req.Method == http.MethodPut && req.URL.Path == "/latest/api/token":
+ return 200, "tok"
+ case req.URL.Path == credsPath && req.Header.Get(imdsTokenHeader) == "tok":
+ return 200, "equipo-role"
+ }
+ return 401, ""
+ }
+ imdsV1 := func(req *http.Request) (int, string) {
+ if req.Method == http.MethodGet && req.URL.Path == credsPath && req.Header.Get(imdsTokenHeader) == "" {
+ return 200, "equipo-role\n"
+ }
+ return 404, ""
+ }
+ // A token is issued but the credentials path ignores it; asked with no
+ // token it names the role.
+ junkToken := func(req *http.Request) (int, string) {
+ if req.Method == http.MethodPut {
+ return 200, "junk"
+ }
+ if req.Header.Get(imdsTokenHeader) == "" {
+ return imdsV1(req)
+ }
+ return 401, ""
+ }
+ noRole := func(req *http.Request) (int, string) {
+ if req.Method == http.MethodPut {
+ return 200, "tok"
+ }
+ return 404, "<html>not found</html>"
+ }
+ type want struct{ dns, meta, resolv bool }
+ for name, c := range map[string]struct {
+ net *fakeNet
+ resolvers []netip.Addr
+ meta []netip.AddrPort
+ resolv string
+ want want
+ }{
+ "all silent": {silentNet(), resolvers, meta, empty, want{true, true, true}},
+ "metadata no role": {&fakeNet{replies: map[string][]byte{}, web: noRole}, resolvers, meta, empty, want{true, true, true}},
+ "udp answer": {&fakeNet{replies: map[string][]byte{"udp 169.254.169.253:53": {1, 2, 3}}}, resolvers, meta, empty, want{false, true, true}},
+ "tcp answer": {&fakeNet{replies: map[string][]byte{"tcp 10.0.0.2:53": {1}}}, resolvers, meta, empty, want{false, true, true}},
+ "no resolver known": {silentNet(), nil, meta, empty, want{false, true, true}},
+ "credential, v2": {&fakeNet{replies: map[string][]byte{}, web: imdsV2}, resolvers, meta, empty, want{true, false, true}},
+ "credential, v1": {&fakeNet{replies: map[string][]byte{}, web: imdsV1}, resolvers, meta, empty, want{true, false, true}},
+ "credential, no token needed": {&fakeNet{replies: map[string][]byte{}, web: junkToken}, resolvers, meta, empty, want{true, false, true}},
+ "no metadata known": {silentNet(), resolvers, nil, empty, want{true, false, true}},
+ "resolv.conf full": {silentNet(), resolvers, meta, full, want{true, true, false}},
+ "resolv.conf a link": {silentNet(), resolvers, meta, link, want{true, true, false}},
+ "resolv.conf absent": {silentNet(), resolvers, meta, filepath.Join(dir, "none"), want{true, true, false}},
+ } {
+ res := rootProbes(context.Background(), c.net, c.resolvers, c.meta, c.resolv)
+ got := map[string]bool{}
+ for _, p := range res {
+ if p.Stage != StageRoot || p.Detail == "" {
+ t.Errorf("%s: probe %+v, want stage root and a detail", name, p)
+ }
+ got[p.Name] = p.OK
+ }
+ w := map[string]bool{ProbeVPCDNSSilent: c.want.dns, ProbeMetadataNoCredential: c.want.meta, ProbeResolvConfEmpty: c.want.resolv}
+ if len(res) != 3 || fmt.Sprint(got) != fmt.Sprint(w) {
+ t.Errorf("%s: probes = %+v, want %v", name, res, w)
+ }
+ if name == "all silent" {
+ // Every resolver over both transports, and the metadata
+ // endpoint with and without a token attempt.
+ for _, q := range []string{"udp 10.0.0.2:53", "tcp 10.0.0.2:53", "udp 169.254.169.253:53", "tcp 169.254.169.253:53"} {
+ if !slices.Contains(c.net.asked, q) {
+ t.Errorf("DNS probe never asked %s: %q", q, c.net.asked)
+ }
+ }
+ }
+ }
+}
+
+// TestRootProbesInterrupted: a probe cut short cannot tell silence from
+// the cut, so with its context ended the network probes fail.
+func TestRootProbesInterrupted(t *testing.T) {
+ ctx, cancel := context.WithCancel(context.Background())
+ cancel()
+ res := rootProbes(ctx, silentNet(), []netip.Addr{netip.MustParseAddr("10.0.0.2")},
+ []netip.AddrPort{netip.MustParseAddrPort("169.254.169.254:80")}, "/nonexistent")
+ for _, p := range res[:2] {
+ if p.OK || !strings.Contains(p.Detail, "interrupted") {
+ t.Errorf("probe %+v after its context ended, want not ok and interrupted", p)
+ }
+ }
+}
+
+func TestManagedResolvers(t *testing.T) {
+ got := parseNameservers([]byte("# managed\nnameserver 10.0.0.2\nnameserver fd00:ec2::253\nnameserver bogus\nsearch x\n nameserver 169.254.169.253 # c\n"))
+ want := []netip.Addr{netip.MustParseAddr("10.0.0.2"), netip.MustParseAddr("fd00:ec2::253"), netip.MustParseAddr("169.254.169.253")}
+ if !slices.Equal(got, want) {
+ t.Errorf("nameservers = %v, want %v", got, want)
+ }
+}
+
+func TestReaperDeliversRunnerExit(t *testing.T) {
+ pids := []int{7, 42, 0}
+ r := newReaper(func() (int, syscall.WaitStatus, error) {
+ p := pids[0]
+ pids = pids[1:]
+ return p, 0, nil
+ }, t.Logf)
+ pid, exited, err := r.start(func() (int, error) { return 42, nil })
+ if err != nil || pid != 42 {
+ t.Fatalf("start = %d, %v", pid, err)
+ }
+ r.reapAll()
+ select {
+ case <-exited:
+ default:
+ t.Error("the runner's exit was not delivered")
+ }
+ if r.orphans != 1 || len(pids) != 0 {
+ t.Errorf("orphans reaped = %d, waits left %v; want 1 and none", r.orphans, pids)
+ }
+}
+
+func TestServeListensOnHookAddr(t *testing.T) {
+ ln, err := net.Listen("tcp", "127.0.0.1:0")
+ if err != nil {
+ t.Fatal(err)
+ }
+ addr := netip.MustParseAddrPort(ln.Addr().String())
+ ln.Close()
+ r := newRig(t)
+ r.cfg.HookAddr = addr
+ ctx, cancel := context.WithCancel(context.Background())
+ done := make(chan error, 1)
+ go func() { done <- serve(ctx, r.cfg, r.h) }()
+ var resp *http.Response
+ for i := 0; i < 200; i++ {
+ resp, err = http.Post("http://"+addr.String()+hookPrefix+"suspend", "application/json", nil)
+ if err == nil {
+ break
+ }
+ time.Sleep(10 * time.Millisecond)
+ }
+ if err != nil {
+ t.Fatal(err)
+ }
+ resp.Body.Close()
+ if resp.StatusCode != http.StatusConflict {
+ t.Errorf("/suspend over the listener = %d, want 409", resp.StatusCode)
+ }
+ cancel()
+ if err := <-done; err != nil {
+ t.Errorf("serve after cancel: %v", err)
+ }
+}
+
+func TestConfigChecked(t *testing.T) {
+ base := newRig(t).cfg
+ if err := base.check(); err != nil {
+ t.Fatalf("rig config: %v", err)
+ }
+ for name, mutate := range map[string]func(*Config){
+ "no hook addr": func(c *Config) { c.HookAddr = netip.AddrPort{} },
+ "hook port 0": func(c *Config) { c.HookAddr = netip.MustParseAddrPort("127.0.0.1:0") },
+ "no runner user": func(c *Config) { c.RunnerUser = "" },
+ "relative runner": func(c *Config) { c.RunnerBinary = "bin/equipo-runner" },
+ "relative state": func(c *Config) { c.StateDir = "state" },
+ "no results": func(c *Config) { c.ResultsDir = "" },
+ "results in state": func(c *Config) { c.ResultsDir = filepath.Join(c.StateDir, "results") },
+ "state in results": func(c *Config) { c.StateDir = filepath.Join(c.ResultsDir, "state") },
+ "same dirs": func(c *Config) { c.ResultsDir = c.StateDir },
+ "no policy": func(c *Config) { c.PolicyFiles = nil },
+ "relative policy": func(c *Config) { c.PolicyFiles = []string{"policy.json"} },
+ "policy twice": func(c *Config) { c.PolicyFiles = []string{c.PolicyFiles[0], c.PolicyFiles[0]} },
+ "unclean results": func(c *Config) { c.ResultsDir += "/../results" },
+ "zoned metadata": func(c *Config) { c.Metadata = []netip.AddrPort{netip.MustParseAddrPort("[fe80::1%eth0]:80")} },
+ "invalid resolver": func(c *Config) { c.Resolvers = []netip.Addr{{}} },
+ "metadata port 0": func(c *Config) { c.Metadata = []netip.AddrPort{netip.MustParseAddrPort("169.254.169.254:0")} },
+ "runner user colon": func(c *Config) { c.RunnerUser = "a:b" },
+ } {
+ c := base
+ c.PolicyFiles = slices.Clone(base.PolicyFiles)
+ mutate(&c)
+ if err := c.check(); err == nil {
+ t.Errorf("%s: config accepted", name)
+ }
+ }
+}
diff --git a/internal/vminit/measure.go b/internal/vminit/measure.go
new file mode 100644
index 00000000..e34a9925
--- /dev/null
+++ b/internal/vminit/measure.go
@@ -0,0 +1,105 @@
+//go:build linux
+
+package vminit
+
+import (
+ "crypto/sha256"
+ "encoding/hex"
+ "fmt"
+ "io"
+ "maps"
+ "os"
+ "slices"
+ "syscall"
+)
+
+// The results vm-init writes as root, read-only, before the runner
+// starts. Certification (Task 13) reads both from EnvResults.
+const (
+ // MeasuredFile maps each measured name to its hex SHA-256.
+ MeasuredFile = "measured.json"
+ // RootProbeFile holds the root-before-drop probes ([]ProbeResult).
+ RootProbeFile = "root.json"
+)
+
+// The names in measured.json. Each policy file also appears under
+// MeasuredPolicyPrefix and its path.
+const (
+ MeasuredRunner = "runner" // the runner binary
+ MeasuredVMInit = "vm_init" // vm-init, read from /proc/self/exe
+ MeasuredSandboxPolicy = "sandbox_policy" // PolicySetDigest of the policy files
+ MeasuredPolicyPrefix = "policy:"
+)
+
+// measure hashes the runner, vm-init itself and each policy file.
+func measure(runner, self string, policies []string) (map[string]string, error) {
+ m := map[string]string{}
+ var err error
+ if m[MeasuredRunner], err = fileSHA256(runner); err != nil {
+ return nil, err
+ }
+ if m[MeasuredVMInit], err = fileSHA256(self); err != nil {
+ return nil, err
+ }
+ files := map[string]string{}
+ for _, p := range policies {
+ if files[p], err = fileSHA256(p); err != nil {
+ return nil, err
+ }
+ m[MeasuredPolicyPrefix+p] = files[p]
+ }
+ m[MeasuredSandboxPolicy] = PolicySetDigest(files)
+ return m, nil
+}
+
+// PolicySetDigest is the sandbox policy set's one digest, as a
+// certificate's SandboxPolicy records it: the hex SHA-256 of one line
+// "<hex SHA-256> <path>\n" per file (sha256sum's format), sorted by
+// path. files maps each path to its hex SHA-256.
+func PolicySetDigest(files map[string]string) string {
+ h := sha256.New()
+ for _, p := range slices.Sorted(maps.Keys(files)) {
+ fmt.Fprintf(h, "%s %s\n", files[p], p)
+ }
+ return hex.EncodeToString(h.Sum(nil))
+}
+
+func fileSHA256(path string) (string, error) {
+ f, err := os.Open(path)
+ if err != nil {
+ return "", fmt.Errorf("measuring %s: %w", path, err)
+ }
+ defer f.Close()
+ h := sha256.New()
+ if _, err := io.Copy(h, f); err != nil {
+ return "", fmt.Errorf("measuring %s: %w", path, err)
+ }
+ return hex.EncodeToString(h.Sum(nil)), nil
+}
+
+// writeOwned creates path, which must not exist (and is never followed
+// if it is a link), writes data, syncs it, sets mode, and gives it to
+// uid:gid.
+func writeOwned(chown func(string, int, int) error, path string, data []byte, mode os.FileMode, uid, gid int) error {
+ f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL|syscall.O_NOFOLLOW, 0o600)
+ if err != nil {
+ return fmt.Errorf("writing %s: %w", path, err)
+ }
+ _, err = f.Write(data)
+ if err == nil {
+ err = f.Sync()
+ }
+ if err == nil {
+ err = f.Chmod(mode)
+ }
+ if cerr := f.Close(); err == nil {
+ err = cerr
+ }
+ if err == nil {
+ err = chown(path, uid, gid)
+ }
+ if err != nil {
+ return fmt.Errorf("writing %s: %w", path, err)
+ }
+ return nil
+}
diff --git a/internal/vminit/mounts_linux.go b/internal/vminit/mounts_linux.go
new file mode 100644
index 00000000..8b657bac
--- /dev/null
+++ b/internal/vminit/mounts_linux.go
@@ -0,0 +1,149 @@
+package vminit
+
+import (
+ "cmp"
+ "errors"
+ "fmt"
+ "io/fs"
+ "path/filepath"
+ "slices"
+ "strconv"
+ "strings"
+
+ "golang.org/x/sys/unix"
+)
+
+// MountPlan is what root init does to /etc. The provider bind-mounts its
+// own files under /etc (resolv.conf among them), which point the VM at
+// its resolvers and stop the runner overlaying /etc in the sandbox (spec
+// §7). Root init detaches every mount at or under /etc and binds the
+// image's copy over /etc, read-only.
+type MountPlan struct {
+ // EtcSource is the image's copy of /etc: a clean absolute directory
+ // outside /etc whose resolv.conf is an empty regular file.
+ EtcSource string
+}
+
+// MountOp is one mount action, in a plan's order.
+type MountOp struct {
+ Kind string // OpDetach, OpBind or OpRemountReadOnly
+ Source string // OpBind only
+ Target string
+}
+
+const (
+ OpDetach = "detach" // umount2(Target, MNT_DETACH)
+ OpBind = "bind" // mount --bind Source Target
+ OpRemountReadOnly = "remount-ro" // mount -o remount,bind,ro,nosuid,nodev Target
+)
+
+func (o MountOp) String() string {
+ if o.Kind == OpBind {
+ return fmt.Sprintf("%s %s %s", o.Kind, o.Source, o.Target)
+ }
+ return o.Kind + " " + o.Target
+}
+
+// PlanMounts returns the ops that replace the managed mounts, reading
+// root (the filesystem at /): proc/self/mountinfo for the mounts, and the
+// image's copy of /etc. It refuses a copy whose resolv.conf is not an
+// empty regular file, so after the plan /etc/resolv.conf is empty.
+func PlanMounts(p MountPlan, root fs.FS) ([]MountOp, error) {
+ src := p.EtcSource
+ if src == "" || !filepath.IsAbs(src) || filepath.Clean(src) != src || src == "/" || src == "/etc" || strings.HasPrefix(src, "/etc/") {
+ return nil, fmt.Errorf("vminit: mounts: the /etc copy %q must be a clean absolute path outside /etc", src)
+ }
+ rel := strings.TrimPrefix(src, "/")
+ if st, err := fs.Stat(root, rel); err != nil || !st.IsDir() {
+ return nil, fmt.Errorf("vminit: mounts: the /etc copy %s is not a directory", src)
+ }
+ st, err := fs.Lstat(root, rel+"/resolv.conf")
+ if err != nil || !st.Mode().IsRegular() || st.Size() != 0 {
+ return nil, fmt.Errorf("vminit: mounts: %s/resolv.conf must be an empty regular file", src)
+ }
+ info, err := fs.ReadFile(root, "proc/self/mountinfo")
+ if err != nil {
+ return nil, fmt.Errorf("vminit: mounts: %w", err)
+ }
+ points, err := mountPoints(info)
+ if err != nil {
+ return nil, err
+ }
+ var etc []string
+ for _, m := range points {
+ if m == "/etc" || strings.HasPrefix(m, "/etc/") {
+ etc = append(etc, m)
+ }
+ }
+ // The latest mount first, so a mount stacked on another goes first;
+ // then the deepest first, so no mount is detached from under another.
+ slices.Reverse(etc)
+ slices.SortStableFunc(etc, func(a, b string) int { return cmp.Compare(strings.Count(b, "/"), strings.Count(a, "/")) })
+ var ops []MountOp
+ for _, m := range etc {
+ ops = append(ops, MountOp{Kind: OpDetach, Target: m})
+ }
+ return append(ops,
+ MountOp{Kind: OpBind, Source: src, Target: "/etc"},
+ MountOp{Kind: OpRemountReadOnly, Target: "/etc"},
+ ), nil
+}
+
+// mountPoints returns each mount's mount point from mountinfo, in order.
+func mountPoints(info []byte) ([]string, error) {
+ var out []string
+ for _, line := range strings.Split(string(info), "\n") {
+ if strings.TrimSpace(line) == "" {
+ continue
+ }
+ f := strings.Fields(line)
+ // id parent major:minor root point options [optional...] - type source super
+ sep := slices.Index(f, "-")
+ if len(f) < 10 || sep < 6 || len(f)-sep != 4 {
+ return nil, errors.New("vminit: mounts: a mountinfo line does not parse")
+ }
+ p := unescapeMount(f[4])
+ if !filepath.IsAbs(p) {
+ return nil, errors.New("vminit: mounts: a mount point is not absolute")
+ }
+ out = append(out, p)
+ }
+ return out, nil
+}
+
+// unescapeMount undoes mountinfo's octal escapes (\040 for a space).
+func unescapeMount(s string) string {
+ var b strings.Builder
+ for i := 0; i < len(s); i++ {
+ if s[i] == '\\' && i+4 <= len(s) {
+ if n, err := strconv.ParseUint(s[i+1:i+4], 8, 8); err == nil {
+ b.WriteByte(byte(n))
+ i += 3
+ continue
+ }
+ }
+ b.WriteByte(s[i])
+ }
+ return b.String()
+}
+
+// applyMounts carries out a plan, stopping at the first failure.
+func applyMounts(ops []MountOp) error {
+ for _, op := range ops {
+ var err error
+ switch op.Kind {
+ case OpDetach:
+ err = unix.Unmount(op.Target, unix.MNT_DETACH)
+ case OpBind:
+ err = unix.Mount(op.Source, op.Target, "", unix.MS_BIND, "")
+ case OpRemountReadOnly:
+ err = unix.Mount("", op.Target, "", unix.MS_REMOUNT|unix.MS_BIND|unix.MS_RDONLY|unix.MS_NOSUID|unix.MS_NODEV, "")
+ default:
+ err = errors.New("unknown op")
+ }
+ if err != nil {
+ return fmt.Errorf("vminit: mounts: %s: %w", op, err)
+ }
+ }
+ return nil
+}
diff --git a/internal/vminit/reap_linux.go b/internal/vminit/reap_linux.go
new file mode 100644
index 00000000..d4885a1f
--- /dev/null
+++ b/internal/vminit/reap_linux.go
@@ -0,0 +1,144 @@
+package vminit
+
+import (
+ "context"
+ "errors"
+ "os"
+ "os/signal"
+ "runtime"
+ "sync"
+ "syscall"
+ "time"
+
+ "golang.org/x/sys/unix"
+)
+
+// reaper is the one waiter for vm-init's children: as PID 1 or the
+// subreaper it reaps every process that ends under it, orphans included,
+// and tells start's caller when the runner it started has gone.
+type reaper struct {
+ mu sync.Mutex
+ watched map[int]chan struct{}
+ wait func() (int, syscall.WaitStatus, error) // one non-blocking wait for any child
+ logf func(format string, a ...any)
+ orphans int
+}
+
+func newReaper(wait func() (int, syscall.WaitStatus, error), logf func(string, ...any)) *reaper {
+ return &reaper{watched: map[int]chan struct{}{}, wait: wait, logf: logf}
+}
+
+// start runs fork with the reaper held, so a child that exits at once is
+// reaped only after it is watched; the channel closes when it is reaped.
+func (r *reaper) start(fork func() (int, error)) (int, <-chan struct{}, error) {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ pid, err := fork()
+ if err != nil {
+ return 0, nil, err
+ }
+ ch := make(chan struct{})
+ r.watched[pid] = ch
+ return pid, ch, nil
+}
+
+// reapAll reaps every child that has ended.
+func (r *reaper) reapAll() {
+ for {
+ pid, ws, err := r.wait()
+ if err != nil || pid <= 0 {
+ return
+ }
+ r.mu.Lock()
+ ch, ok := r.watched[pid]
+ delete(r.watched, pid)
+ if !ok {
+ r.orphans++
+ }
+ r.mu.Unlock()
+ if ok {
+ r.logf("vm-init: runner pid %d ended: exit %d, signal %v", pid, ws.ExitStatus(), ws.Signal())
+ close(ch)
+ }
+ }
+}
+
+// run reaps on every SIGCHLD, and every few seconds in case one was
+// missed, until ctx ends.
+func (r *reaper) run(ctx context.Context) {
+ sig := make(chan os.Signal, 1)
+ signal.Notify(sig, syscall.SIGCHLD)
+ defer signal.Stop(sig)
+ tick := time.NewTicker(5 * time.Second)
+ defer tick.Stop()
+ for {
+ r.reapAll()
+ select {
+ case <-ctx.Done():
+ return
+ case <-sig:
+ case <-tick.C:
+ }
+ }
+}
+
+// wait4Any is one wait4(-1, WNOHANG): a pid, 0 when no child has ended,
+// or ECHILD when there are none.
+func wait4Any() (int, syscall.WaitStatus, error) {
+ var ws syscall.WaitStatus
+ for {
+ pid, err := syscall.Wait4(-1, &ws, syscall.WNOHANG, nil)
+ if errors.Is(err, syscall.EINTR) {
+ continue
+ }
+ return pid, ws, err
+ }
+}
+
+// setSubreaper makes vm-init the reaper of its descendants' orphans when
+// it is not PID 1.
+func setSubreaper() error {
+ return unix.Prctl(unix.PR_SET_CHILD_SUBREAPER, 1, 0, 0, 0)
+}
+
+// forkRunner starts s and returns its pid; the reaper waits for it. Go's
+// SysProcAttr cannot set no_new_privs, so a goroutine locks a thread,
+// sets it there and forks from that thread, whose flag the child
+// inherits. The thread is never unlocked, so it ends with the goroutine
+// and vm-init keeps no thread with the flag.
+func forkRunner(s launchSpec) (int, error) {
+ if !s.NoNewPrivs {
+ return 0, errors.New("vminit: refusing a runner launch without no_new_privs")
+ }
+ if s.Sys != nil && len(s.Sys.AmbientCaps) != 0 {
+ return 0, errors.New("vminit: refusing a runner launch with ambient capabilities")
+ }
+ null, err := os.Open(os.DevNull)
+ if err != nil {
+ return 0, err
+ }
+ defer null.Close()
+ attr := &os.ProcAttr{Dir: s.Dir, Env: s.Env, Files: []*os.File{null, os.Stdout, os.Stderr}, Sys: s.Sys}
+ type result struct {
+ pid int
+ err error
+ }
+ done := make(chan result, 1)
+ go func() {
+ runtime.LockOSThread()
+ if err := unix.Prctl(unix.PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0); err != nil {
+ done <- result{err: err}
+ return
+ }
+ p, err := os.StartProcess(s.Path, s.Args, attr)
+ if err != nil {
+ done <- result{err: err}
+ return
+ }
+ pid := p.Pid
+ _ = p.Release()
+ done <- result{pid: pid}
+ }()
+ res := <-done
+ return res.pid, res.err
+}
diff --git a/internal/vminit/rootprobe_linux.go b/internal/vminit/rootprobe_linux.go
new file mode 100644
index 00000000..4a2e7887
--- /dev/null
+++ b/internal/vminit/rootprobe_linux.go
@@ -0,0 +1,250 @@
+package vminit
+
+import (
+ "context"
+ "encoding/binary"
+ "errors"
+ "fmt"
+ "io"
+ "net"
+ "net/http"
+ "net/netip"
+ "os"
+ "strings"
+ "time"
+)
+
+// ProbeResult is one certification probe's outcome. OK means the probe
+// found the property it checks; what each probe must show is for the
+// certification matrix (Task 13) to judge, not the VM.
+type ProbeResult struct {
+ Name string `json:"name"`
+ Stage string `json:"stage"`
+ OK bool `json:"ok"`
+ Detail string `json:"detail"`
+}
+
+// StageRoot marks the probes vm-init runs as root, before the runner
+// starts, for a certification launch.
+const StageRoot = "root"
+
+// The root probes (spec §7: VPC DNS off, no AWS credential reachable).
+const (
+ // ProbeVPCDNSSilent: no managed resolver answers a DNS query, over UDP
+ // or TCP. With no resolver address known it fails.
+ ProbeVPCDNSSilent = "root_vpc_dns_silent"
+ // ProbeMetadataNoCredential: no metadata endpoint names a role for
+ // credentials, with an IMDSv2 token or without one. With no endpoint
+ // configured it fails.
+ ProbeMetadataNoCredential = "root_metadata_no_credential"
+ // ProbeResolvConfEmpty: /etc/resolv.conf is an empty regular file.
+ ProbeResolvConfEmpty = "root_resolv_conf_empty"
+)
+
+// RootNet is the root probes' network, so tests need none.
+type RootNet interface {
+ // DNS sends query to server over network ("udp" or "tcp", which adds
+ // the length prefix) and returns the reply's bytes, or an error when
+ // nothing came back before ctx ends.
+ DNS(ctx context.Context, network string, server netip.AddrPort, query []byte) ([]byte, error)
+ // Do sends one HTTP request, through no proxy, following no redirect.
+ Do(req *http.Request) (*http.Response, error)
+}
+
+const (
+ probeTimeout = 2 * time.Second
+ maxProbeDetail = 1024
+ maxProbeBody = 4096
+ imdsTokenHeader = "X-aws-ec2-metadata-token"
+ imdsTTLHeader = "X-aws-ec2-metadata-token-ttl-seconds"
+ imdsTokenPath = "/latest/api/token"
+ imdsCredsPath = "/latest/meta-data/iam/security-credentials/"
+ // probeName is the name the DNS probe asks for.
+ probeName = "example.com."
+)
+
+// rootProbes runs the three root probes, in a fixed order.
+func rootProbes(ctx context.Context, n RootNet, resolvers []netip.Addr, metadata []netip.AddrPort, resolv string) []ProbeResult {
+ return []ProbeResult{
+ probeDNS(ctx, n, resolvers),
+ probeMetadata(ctx, n, metadata),
+ probeResolvConf(resolv),
+ }
+}
+
+func detail(notes []string) string {
+ s := strings.Join(notes, "; ")
+ if len(s) > maxProbeDetail {
+ s = s[:maxProbeDetail]
+ }
+ return s
+}
+
+func probeDNS(ctx context.Context, n RootNet, resolvers []netip.Addr) ProbeResult {
+ res := ProbeResult{Name: ProbeVPCDNSSilent, Stage: StageRoot}
+ if len(resolvers) == 0 {
+ res.Detail = "no managed resolver address known"
+ return res
+ }
+ query := dnsQuery(probeName)
+ answered := false
+ var notes []string
+ for _, a := range resolvers {
+ for _, network := range []string{"udp", "tcp"} {
+ qctx, cancel := context.WithTimeout(ctx, probeTimeout)
+ reply, err := n.DNS(qctx, network, netip.AddrPortFrom(a, 53), query)
+ cancel()
+ if err == nil && len(reply) > 0 {
+ answered = true
+ notes = append(notes, fmt.Sprintf("%s %s answered %d bytes", network, a, len(reply)))
+ } else {
+ notes = append(notes, fmt.Sprintf("%s %s silent", network, a))
+ }
+ }
+ }
+ // Silence is shown by queries timing out; a probe whose own context
+ // ended cannot tell silence from being cut short, so it fails.
+ if ctx.Err() != nil {
+ answered = true
+ notes = append(notes, "interrupted")
+ }
+ res.OK = !answered
+ res.Detail = detail(notes)
+ return res
+}
+
+// dnsQuery is a one-question A query for name, recursion desired.
+func dnsQuery(name string) []byte {
+ q := []byte{0x45, 0x51, 0x01, 0x00, 0, 1, 0, 0, 0, 0, 0, 0}
+ for _, label := range strings.Split(strings.TrimSuffix(name, "."), ".") {
+ q = append(q, byte(len(label)))
+ q = append(q, label...)
+ }
+ return append(q, 0, 0, 1, 0, 1)
+}
+
+func probeMetadata(ctx context.Context, n RootNet, endpoints []netip.AddrPort) ProbeResult {
+ res := ProbeResult{Name: ProbeMetadataNoCredential, Stage: StageRoot}
+ if len(endpoints) == 0 {
+ res.Detail = "no metadata endpoint configured"
+ return res
+ }
+ found := false
+ var notes []string
+ for _, ep := range endpoints {
+ base := "http://" + ep.String()
+ token := ""
+ code, body, err := fetch(ctx, n, http.MethodPut, base+imdsTokenPath, map[string]string{imdsTTLHeader: "60"})
+ if err == nil && code == http.StatusOK && strings.TrimSpace(body) != "" {
+ token = strings.TrimSpace(body)
+ }
+ tokens := []string{""}
+ if token != "" {
+ tokens = append(tokens, token)
+ }
+ for _, tok := range tokens {
+ how := "without a token"
+ var h map[string]string
+ if tok != "" {
+ how, h = "with a token", map[string]string{imdsTokenHeader: tok}
+ }
+ code, body, err := fetch(ctx, n, http.MethodGet, base+imdsCredsPath, h)
+ switch {
+ case err != nil:
+ notes = append(notes, fmt.Sprintf("%s %s: no answer", ep, how))
+ case code == http.StatusOK && strings.TrimSpace(body) != "":
+ found = true
+ notes = append(notes, fmt.Sprintf("%s %s: a role for credentials (%d bytes)", ep, how, len(body)))
+ default:
+ notes = append(notes, fmt.Sprintf("%s %s: %d, no role", ep, how, code))
+ }
+ }
+ }
+ if ctx.Err() != nil {
+ found = true
+ notes = append(notes, "interrupted")
+ }
+ res.OK = !found
+ res.Detail = detail(notes)
+ return res
+}
+
+// fetch sends one request and reads at most maxProbeBody bytes of the
+// answer. The body is never logged or written out, only its length.
+func fetch(ctx context.Context, n RootNet, method, url string, header map[string]string) (int, string, error) {
+ ctx, cancel := context.WithTimeout(ctx, probeTimeout)
+ defer cancel()
+ req, err := http.NewRequestWithContext(ctx, method, url, nil)
+ if err != nil {
+ return 0, "", err
+ }
+ for k, v := range header {
+ req.Header.Set(k, v)
+ }
+ resp, err := n.Do(req)
+ if err != nil {
+ return 0, "", err
+ }
+ defer resp.Body.Close()
+ b, err := io.ReadAll(io.LimitReader(resp.Body, maxProbeBody))
+ if err != nil {
+ return 0, "", err
+ }
+ return resp.StatusCode, string(b), nil
+}
+
+func probeResolvConf(path string) ProbeResult {
+ res := ProbeResult{Name: ProbeResolvConfEmpty, Stage: StageRoot}
+ st, err := os.Lstat(path)
+ switch {
+ case err != nil:
+ res.Detail = fmt.Sprintf("%s: %v", path, err)
+ case !st.Mode().IsRegular():
+ res.Detail = fmt.Sprintf("%s is not a regular file (%v)", path, st.Mode().Type())
+ case st.Size() != 0:
+ res.Detail = fmt.Sprintf("%s holds %d bytes", path, st.Size())
+ default:
+ res.OK, res.Detail = true, path+" is empty"
+ }
+ return res
+}
+
+// hostNet is RootNet over the VM's own network.
+type hostNet struct{}
+
+func (hostNet) DNS(ctx context.Context, network string, server netip.AddrPort, query []byte) ([]byte, error) {
+ var d net.Dialer
+ c, err := d.DialContext(ctx, network, server.String())
+ if err != nil {
+ return nil, err
+ }
+ defer c.Close()
+ if dl, ok := ctx.Deadline(); ok {
+ _ = c.SetDeadline(dl)
+ }
+ msg := query
+ if network == "tcp" {
+ msg = binary.BigEndian.AppendUint16(nil, uint16(len(query)))
+ msg = append(msg, query...)
+ }
+ if _, err := c.Write(msg); err != nil {
+ return nil, err
+ }
+ buf := make([]byte, 4096)
+ k, err := c.Read(buf)
+ if k > 0 {
+ return buf[:k], nil
+ }
+ if err == nil {
+ err = errors.New("no reply")
+ }
+ return nil, err
+}
+
+func (hostNet) Do(req *http.Request) (*http.Response, error) {
+ c := &http.Client{
+ Transport: &http.Transport{Proxy: nil, DisableKeepAlives: true},
+ CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse },
+ }
+ return c.Do(req)
+}