vminit: Task 8 review 1, conclusive probes, stop intent, results path
Probes pass only on demonstrated denial or timeout; token failures, unexpected statuses, local and read errors are inconclusive. /terminate records a stop under the lock that covers runner creation and its pid, so a stop during launch prevents the start or signals the new runner. /run refuses a results path with any ancestor not a root-only real directory. PolicySetDigest is pinned to sha256sum-computed values. Mutation checks 43 to 55 are in HOSTED-SLICE2-PROGRESS.md.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
5 files changed,
+485
−55
docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md+27 −0internal/vminit/hooks.go+65 −9internal/vminit/init.go+16 −0internal/vminit/init_test.go+284 −10internal/vminit/rootprobe_linux.go+93 −36
diff --git a/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md b/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md| index b0b0d3a2..170e188f 100644 |
| --- a/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md |
| +++ b/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md |
| @@ -362,3 +362,30 @@ Mutation checks (each applied by script, the named test run with `CGO_ENABLED=0 |
| 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). |
| + |
| +### Task 8 review round 1 (t8-r1.md: all four findings fixed) |
| + |
| +1. Probes pass only on demonstrated denial or timeout. `denied(err)` accepts a timeout (`os.ErrDeadlineExceeded`, `context.DeadlineExceeded`, a `net.Error` timeout), `ECONNREFUSED`, `EHOSTUNREACH` and `ENETUNREACH`; anything else (a local error such as `EMFILE`, a cancellation, an empty DNS reply, an unreadable answer, wrapped as `errRead`) is inconclusive. Metadata, per endpoint: the token request must be answered with a token, refused as not offered (403, 404, 405) or denied; each credentials request must answer 404 or be denied (a tokenless 401 counts only when a token was issued); a 200 with a body is a credential; every other outcome is inconclusive. An inconclusive probe is `ok:false` and its detail starts `inconclusive`. `verdict` still fails a probe whose context ended (`interrupted`). New TestRootProbesInconclusive (16 cases: four that pass, twelve inconclusive). The metadata path is still the EC2 layout, unproven until Task 34. |
| +2. `/terminate` during a launch. `hooks.stopping` is set by `/terminate` under `hooks.mu`, the same lock under which `launch` checks it, creates the runner and records its pid. A stop before creation means `/run` answers 409 `terminating` and no runner starts; a stop during creation waits for the pid and signals it. New TestTerminateDuringLaunch blocks `/run` at the bootstrap file's chown (before creation) and inside `start` (during creation), calls `/terminate` there, then releases. TestTerminateSignalsRunner now also checks that `/terminate` before `/run` prevents the launch. |
| +3. Results path. `rootPath` (after `rootDir`, before measuring) walks from `ResultsDir` up to `/` with lstat (`system.owner`; production `lstatOwner`): each must be a directory (a symbolic link anywhere fails), uid 0, not other-writable, and not group-writable unless its group is 0. New TestResultsPathRootOnly: the parent or `/` owned by the runner, the parent group-writable by the runner's group, the grandparent 0777, the results directory not root's, a link on the way; each answers 500 with no launch and no measured.json. |
| +4. PolicySetDigest. New TestPolicySetDigest against values computed with coreutils (`printf '%s %s\n' ... | sha256sum`): one file `86d5e72b...`, two files `7e0a22c2...`, the same over 50 builds of the map; a changed content, path, swapped digests or a missing file changes it. |
| + |
| +Also: TestRunnerStartsWithNoNewPrivs no longer reads this process's own status afterwards. The throwaway goroutine can run on the main thread, which Go parks for good instead of ending, so that status could show the flag. It now starts a second child without forkRunner and requires `NoNewPrivs: 0` there, which is what matters: nothing vm-init forks later inherits the flag. |
| + |
| +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): |
| + |
| +43. Any error is a denial (`denied` returns true after its first check). TestRootProbesInconclusive: FAIL, `init_test.go:931: metadata local error: {... OK:true ...}; want ok false and inconclusive true`, and the same for `dns local error`. Restored. |
| +44. A failed token request is ignored (its `unsure = true` removed). First run: survived (every token-failure case also had a tokenless answer the GET rule rejects). Added the case "token 500, tokenless 404". Rerun: FAIL, `init_test.go:932: token 500, tokenless 404: {... OK:true Detail:... token request inconclusive (500); ... without a token: 404, no role}`. Restored. |
| +45. An unexpected credentials answer is ignored. TestRootProbesInconclusive: FAIL for `credentials 200 empty`, `credentials redirect (302)`, `tokenless 401, no token`, `token issued, then 500`, `credentials unreadable`. Restored. |
| +46. An unreadable answer returned as the bare read error (a timeout). TestRootProbesInconclusive: FAIL, `credentials unreadable: {... without a token: unanswered}; want ok false and inconclusive true`. Restored. |
| +47. A DNS error that is not a denial is ignored. TestRootProbesInconclusive: FAIL for `dns local error`, `dns empty reply`, `dns cancelled`. Restored. |
| +48. No stop-intent check in `launch`. FAIL, `init_test.go:503: /run after /terminate = 200 "ok" with 1 launches, want 409 "terminating" and none`; `TestTerminateDuringLaunch/chown_bootstrap.json: init_test.go:565: /run = 200, want 409`, `init_test.go:573: launches 1, signals []; want 0 and []`. Restored. |
| +49. The runner created outside the lock (`start` before `h.mu.Lock()` and the stop check). TestTerminateDuringLaunch: FAIL, `start: init_test.go:573: launches 1, signals []; want 1 and ["4242 terminated"]` (and the chown case: a runner created and not signalled). Restored. |
| +50. Only the results directory itself is checked (`if true { return nil }`). TestResultsPathRootOnly: FAIL, `parent the runner's: /run = 200 "ok" with 1 launches, want 500 and none` (and `/` the runner's, the group-writable parent, the 0777 grandparent). Restored. |
| +51. The results path check skipped. TestResultsPathRootOnly: FAIL for every case, among them `a link on the way: measured.json written (<nil>) under a path the runner could replace`. Restored. |
| +52. Group write by a group other than root's allowed. TestResultsPathRootOnly: FAIL, `parent group-writable, runner's group: /run = 200 "ok" ...`. Restored. |
| +53. Policy set unsorted (`slices.Collect` in place of `slices.Sorted`). TestPolicySetDigest: FAIL, `init_test.go:1069: run 0: 0a854c75..., want 7e0a22c2...`. Restored. |
| +54. PolicySetDigest returns the two-file constant. TestPolicySetDigest: FAIL, `one file: 7e0a22c2..., want 86d5e72b...` and `content changed`, `path changed`, `digests swapped`, `a file missing: digest unchanged`. Restored. |
| +55. Paths left out of the digest. TestPolicySetDigest: FAIL, `one file: e20b8efb..., want 86d5e72b...`, `run 0: 5256b79f..., want 7e0a22c2...`. Restored. |
| + |
| +Also run: `go test ./internal/vminit -count=1` ok (22 tests); `-count=20` ok; `-race` once ok (3.7 s); `GOOS=linux go build ./cmd/equipo-vm-init` ok; staticcheck v0.7.0 clean; gofmt clean; `make budget build vet` ok (129 directories within budget; `internal/vminit` 1405 source and 1180 test lines). |
diff --git a/internal/vminit/hooks.go b/internal/vminit/hooks.go| index 913dedce..a41177f2 100644 |
| --- a/internal/vminit/hooks.go |
| +++ b/internal/vminit/hooks.go |
| @@ -8,6 +8,7 @@ import ( |
| "errors" |
| "fmt" |
| "io" |
| + "io/fs" |
| "net/http" |
| "os" |
| "path/filepath" |
| @@ -36,6 +37,7 @@ const ( |
| 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) |
| + reasonStopping = "terminating" // /terminate came first: no runner starts |
| ) |
| // RunnerBootstrap is the file vm-init writes for the runner, at |
| @@ -54,9 +56,13 @@ type hooks struct { |
| sys system |
| mux *http.ServeMux |
| - mu sync.Mutex |
| - ran bool |
| - runner int // the runner's pid while it runs; 0 before and after |
| + // mu also covers the runner's creation and the recording of its pid, |
| + // so /terminate either stops a launch before the runner exists or |
| + // finds its pid. |
| + mu sync.Mutex |
| + ran bool |
| + stopping bool // /terminate has been called |
| + runner int // the runner's pid while it runs; 0 before and after |
| } |
| func newHooks(cfg Config, sys system) *hooks { |
| @@ -109,6 +115,11 @@ func (h *hooks) run(w http.ResponseWriter, r *http.Request) { |
| // 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 errors.Is(err, errStopping) { |
| + h.sys.logf("vm-init: /run: %v", err) |
| + answer(w, http.StatusConflict, reasonStopping) |
| + return |
| + } |
| if err != nil { |
| h.sys.logf("vm-init: /run failed: %v", err) |
| answer(w, http.StatusInternalServerError, reasonFailed) |
| @@ -213,6 +224,9 @@ func (h *hooks) launch(ctx context.Context, vm isolatedjob.Ref, boot hostedwire. |
| if err := h.rootDir(h.cfg.ResultsDir); err != nil { |
| return 0, "", err |
| } |
| + if err := h.rootPath(h.cfg.ResultsDir, acct); err != nil { |
| + return 0, "", err |
| + } |
| m, err := measure(h.cfg.RunnerBinary, h.sys.self, h.cfg.PolicyFiles) |
| if err != nil { |
| return 0, "", err |
| @@ -246,13 +260,22 @@ func (h *hooks) launch(ctx context.Context, vm isolatedjob.Ref, boot hostedwire. |
| return 0, "", err |
| } |
| + // Creation and the pid's recording under the one lock /terminate |
| + // takes: a stop before it means no runner, a stop after it finds the |
| + // pid. |
| + h.mu.Lock() |
| + if h.stopping { |
| + h.mu.Unlock() |
| + return 0, "", errStopping |
| + } |
| pid, exited, err := h.sys.start(runnerLaunch(h.cfg, acct, sub)) |
| + if err == nil { |
| + h.runner = pid |
| + } |
| + h.mu.Unlock() |
| 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() |
| @@ -289,6 +312,34 @@ func runnerLaunch(cfg Config, a account, sub string) launchSpec { |
| } |
| } |
| +// errStopping is a launch that /terminate overtook. |
| +var errStopping = errors.New("terminated before the runner started") |
| + |
| +// rootPath fails unless every directory from / down to dir is a real |
| +// directory (no symbolic link anywhere), root's, and writable by no one |
| +// else: otherwise the runner could rename a directory on the way and put |
| +// its own measurements and probe results in place. |
| +func (h *hooks) rootPath(dir string, a account) error { |
| + for p := dir; ; p = filepath.Dir(p) { |
| + uid, gid, mode, err := h.sys.owner(p) |
| + switch { |
| + case err != nil: |
| + return fmt.Errorf("results path: %w", err) |
| + case mode&fs.ModeSymlink != 0 || !mode.IsDir(): |
| + return fmt.Errorf("results path: %s is not a directory", p) |
| + case uid != 0: |
| + return fmt.Errorf("results path: %s is not root's", p) |
| + case mode.Perm()&0o002 != 0, mode.Perm()&0o020 != 0 && gid != 0: |
| + // A group other than root's may hold the runner (a.GID or a |
| + // supplementary group), so its write bit is refused too. |
| + return fmt.Errorf("results path: %s is writable by others than root (group %d, runner group %d)", p, gid, a.GID) |
| + } |
| + if p == "/" { |
| + return nil |
| + } |
| + } |
| +} |
| + |
| // 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 { |
| @@ -344,10 +395,15 @@ 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. |
| +// terminate records that the VM is ending, so a launch not yet started |
| +// never starts, signals the runner's process group if it is running, and |
| +// answers 200. |
| func (h *hooks) terminate(w http.ResponseWriter, _ *http.Request) { |
| - if pid := h.runnerPID(); pid > 0 { |
| + h.mu.Lock() |
| + h.stopping = true |
| + pid := h.runner |
| + h.mu.Unlock() |
| + if pid > 0 { |
| if err := h.sys.signal(pid, syscall.SIGTERM); err != nil { |
| h.sys.logf("vm-init: /terminate: signalling the runner: %v", err) |
| } |
diff --git a/internal/vminit/init.go b/internal/vminit/init.go| index dc84dfec..3b66623f 100644 |
| --- a/internal/vminit/init.go |
| +++ b/internal/vminit/init.go |
| @@ -141,6 +141,8 @@ type launchSpec struct { |
| type system struct { |
| lookup func(name string) (account, error) |
| chown func(path string, uid, gid int) error |
| + // owner is lstat's owner and mode for path, never following a link. |
| + owner func(path string) (uid, gid int, mode fs.FileMode, err error) |
| // start launches the runner; the channel closes when it has exited |
| // and been reaped. |
| start func(launchSpec) (int, <-chan struct{}, error) |
| @@ -181,6 +183,7 @@ func Main(ctx context.Context, cfg Config) error { |
| h := newHooks(cfg, system{ |
| lookup: lookupAccount, |
| chown: os.Lchown, |
| + owner: lstatOwner, |
| start: func(s launchSpec) (int, <-chan struct{}, error) { |
| return rp.start(func() (int, error) { return forkRunner(s) }) |
| }, |
| @@ -231,6 +234,19 @@ func lookupAccount(name string) (account, error) { |
| return account{UID: uid, GID: gid, Home: u.HomeDir}, nil |
| } |
| +// lstatOwner is system.owner on the real filesystem. |
| +func lstatOwner(path string) (int, int, fs.FileMode, error) { |
| + st, err := os.Lstat(path) |
| + if err != nil { |
| + return 0, 0, 0, err |
| + } |
| + sys, ok := st.Sys().(*syscall.Stat_t) |
| + if !ok { |
| + return 0, 0, 0, fmt.Errorf("%s: no owner", path) |
| + } |
| + return int(sys.Uid), int(sys.Gid), st.Mode(), 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 { |
diff --git a/internal/vminit/init_test.go b/internal/vminit/init_test.go| index 52424968..fb6de9e6 100644 |
| --- a/internal/vminit/init_test.go |
| +++ b/internal/vminit/init_test.go |
| @@ -73,12 +73,37 @@ type rig struct { |
| signals []string |
| exited chan struct{} |
| policies []string |
| + // owners overrides the owner and mode the fake lstat gives a path; |
| + // every other directory is root's, 0755. |
| + owners map[string]fakeOwner |
| + // gate, when set, stops the action named at until release closes. |
| + gate *gate |
| +} |
| + |
| +type fakeOwner struct { |
| + uid, gid int |
| + perm fs.FileMode |
| +} |
| + |
| +// gate blocks the rig's action named at ("chown bootstrap.json", |
| +// "start"): it sends on reached, then waits for release. |
| +type gate struct { |
| + at string |
| + reached chan struct{} |
| + release chan struct{} |
| +} |
| + |
| +func (r *rig) pause(event string) { |
| + if g := r.gate; g != nil && strings.HasPrefix(event, g.at) { |
| + g.reached <- struct{}{} |
| + <-g.release |
| + } |
| } |
| func newRig(t *testing.T) *rig { |
| t.Helper() |
| dir := t.TempDir() |
| - r := &rig{t: t, chowns: map[string][2]int{}, exited: make(chan struct{})} |
| + r := &rig{t: t, chowns: map[string][2]int{}, exited: make(chan struct{}), owners: map[string]fakeOwner{}} |
| write := func(rel, content string) string { |
| p := filepath.Join(dir, rel) |
| if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { |
| @@ -114,13 +139,27 @@ func newRig(t *testing.T) *rig { |
| return account{UID: runnerUID, GID: runnerGID, Home: runnerHome}, nil |
| }, |
| chown: func(path string, uid, gid int) error { |
| + event := fmt.Sprintf("chown %s %d:%d", filepath.Base(path), uid, gid) |
| r.mu.Lock() |
| - defer r.mu.Unlock() |
| - r.events = append(r.events, fmt.Sprintf("chown %s %d:%d", filepath.Base(path), uid, gid)) |
| + r.events = append(r.events, event) |
| r.chowns[path] = [2]int{uid, gid} |
| + r.mu.Unlock() |
| + r.pause(event) |
| return nil |
| }, |
| + owner: func(path string) (int, int, fs.FileMode, error) { |
| + st, err := os.Lstat(path) |
| + if err != nil { |
| + return 0, 0, 0, err |
| + } |
| + o, ok := r.owners[path] |
| + if !ok { |
| + o = fakeOwner{0, 0, 0o755} |
| + } |
| + return o.uid, o.gid, st.Mode().Type() | o.perm, nil |
| + }, |
| start: func(spec launchSpec) (int, <-chan struct{}, error) { |
| + defer r.pause("start") |
| r.mu.Lock() |
| defer r.mu.Unlock() |
| r.events = append(r.events, "start") |
| @@ -455,10 +494,16 @@ func TestSuspendRefused(t *testing.T) { |
| } |
| 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) |
| + // A stop before /run: no runner ever starts. |
| + early := newRig(t) |
| + if code, _ := early.post("terminate", nil); code != http.StatusOK || len(early.signals) != 0 { |
| + t.Errorf("/terminate before /run = %d, signals %q; want 200 and none", code, early.signals) |
| + } |
| + if code, body := early.run(hostedwire.PurposeChecks); code != http.StatusConflict || body != reasonStopping || len(early.starts) != 0 { |
| + t.Errorf("/run after /terminate = %d %q with %d launches, want 409 %q and none", code, body, len(early.starts), reasonStopping) |
| } |
| + |
| + r := newRig(t) |
| if code, _ := r.run(hostedwire.PurposeChecks); code != http.StatusOK { |
| t.Fatal("/run failed") |
| } |
| @@ -480,6 +525,101 @@ func TestTerminateSignalsRunner(t *testing.T) { |
| } |
| } |
| +// TestTerminateDuringLaunch stops /run at two points and calls |
| +// /terminate there: before the runner exists (it must never start) and |
| +// while it is being created (the stop must reach its pid). |
| +func TestTerminateDuringLaunch(t *testing.T) { |
| + for _, c := range []struct { |
| + at string |
| + code int |
| + starts int |
| + signals []string |
| + }{ |
| + {"chown bootstrap.json", http.StatusConflict, 0, nil}, |
| + {"start", http.StatusOK, 1, []string{fmt.Sprintf("%d %v", runnerPID, syscall.SIGTERM)}}, |
| + } { |
| + t.Run(c.at, func(t *testing.T) { |
| + r := newRig(t) |
| + r.gate = &gate{at: c.at, reached: make(chan struct{}), release: make(chan struct{})} |
| + runDone := make(chan int, 1) |
| + go func() { |
| + code, _ := r.post("run", runBody(t, testVM, bootstrapPayload(t, hostedwire.PurposeChecks))) |
| + runDone <- code |
| + }() |
| + <-r.gate.reached |
| + termDone := make(chan int, 1) |
| + go func() { |
| + code, _ := r.post("terminate", nil) |
| + termDone <- code |
| + }() |
| + // Before the runner exists /terminate answers at once; while it |
| + // is being created /terminate waits for its pid. Give it the |
| + // chance to answer early either way, then let the launch go on. |
| + select { |
| + case code := <-termDone: |
| + termDone <- code |
| + case <-time.After(200 * time.Millisecond): |
| + } |
| + close(r.gate.release) |
| + if code := <-runDone; code != c.code { |
| + t.Errorf("/run = %d, want %d", code, c.code) |
| + } |
| + if code := <-termDone; code != http.StatusOK { |
| + t.Errorf("/terminate = %d, want 200", code) |
| + } |
| + r.mu.Lock() |
| + defer r.mu.Unlock() |
| + if len(r.starts) != c.starts || !slices.Equal(r.signals, c.signals) { |
| + t.Errorf("launches %d, signals %q; want %d and %q", len(r.starts), r.signals, c.starts, c.signals) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// TestResultsPathRootOnly: the runner must not be able to replace any |
| +// directory on the way to the results, so every one from / down must be |
| +// a real directory of root's that no one else can write. |
| +func TestResultsPathRootOnly(t *testing.T) { |
| + ok := newRig(t) |
| + if code, body := ok.run(hostedwire.PurposeChecks); code != http.StatusOK { |
| + t.Fatalf("/run with a root-only results path = %d %q", code, body) |
| + } |
| + for name, mutate := range map[string]func(r *rig){ |
| + "parent the runner's": func(r *rig) { |
| + r.owners[filepath.Dir(r.cfg.ResultsDir)] = fakeOwner{runnerUID, runnerGID, 0o755} |
| + }, |
| + "root the runner's": func(r *rig) { r.owners["/"] = fakeOwner{runnerUID, 0, 0o755} }, |
| + "parent group-writable, runner's group": func(r *rig) { |
| + r.owners[filepath.Dir(r.cfg.ResultsDir)] = fakeOwner{0, runnerGID, 0o775} |
| + }, |
| + "grandparent world-writable": func(r *rig) { |
| + r.owners[filepath.Dir(filepath.Dir(r.cfg.ResultsDir))] = fakeOwner{0, 0, 0o777} |
| + }, |
| + "results directory not root's": func(r *rig) { r.owners[r.cfg.ResultsDir] = fakeOwner{runnerUID, runnerGID, 0o755} }, |
| + "a link on the way": func(r *rig) { |
| + real := filepath.Join(filepath.Dir(r.cfg.ResultsDir), "real") |
| + link := filepath.Join(filepath.Dir(r.cfg.ResultsDir), "link") |
| + if err := os.Mkdir(real, 0o755); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.Symlink(real, link); err != nil { |
| + t.Fatal(err) |
| + } |
| + r.h.cfg.ResultsDir = filepath.Join(link, "results") |
| + }, |
| + } { |
| + r := newRig(t) |
| + mutate(r) |
| + code, body := r.run(hostedwire.PurposeChecks) |
| + if code != http.StatusInternalServerError || len(r.starts) != 0 { |
| + t.Errorf("%s: /run = %d %q with %d launches, want 500 and none", name, code, body, len(r.starts)) |
| + } |
| + if _, err := os.Stat(filepath.Join(r.h.cfg.ResultsDir, MeasuredFile)); !errors.Is(err, fs.ErrNotExist) { |
| + t.Errorf("%s: measured.json written (%v) under a path the runner could replace", name, err) |
| + } |
| + } |
| +} |
| + |
| func TestRunnerDropsCapabilities(t *testing.T) { |
| r := newRig(t) |
| if code, body := r.run(hostedwire.PurposeChecks); code != http.StatusOK { |
| @@ -552,9 +692,20 @@ func TestRunnerStartsWithNoNewPrivs(t *testing.T) { |
| 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") |
| + // The flag stayed on the throwaway thread: a child vm-init starts any |
| + // other way lacks it. (The throwaway goroutine may have run on the main |
| + // thread, which Go parks for good rather than ending, so this process's |
| + // own status is not the test; what vm-init forks next is.) |
| + plain := filepath.Join(t.TempDir(), "plain") |
| + p, err := os.StartProcess(os.Args[0], []string{os.Args[0]}, &os.ProcAttr{Env: []string{"VMINIT_TEST_STATUS_TO=" + plain}}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if ps, err := p.Wait(); err != nil || !ps.Success() { |
| + t.Fatalf("plain helper: %v %v", err, ps) |
| + } |
| + if st, err := os.ReadFile(plain); err != nil || !strings.Contains(string(st), "\nNoNewPrivs:\t0\n") { |
| + t.Errorf("a child started after forkRunner has no_new_privs (%v): forkRunner left the flag where vm-init runs", err) |
| } |
| } |
| @@ -675,10 +826,20 @@ func viewAfter(ops []MountOp, info *fstest.MapFile, target string) string { |
| // from web; everything else fails as a silent network does. |
| type fakeNet struct { |
| replies map[string][]byte |
| + errs map[string]error // a DNS error other than a timeout, by key |
| web func(*http.Request) (int, string) |
| + doErr error // every HTTP request fails with it |
| asked []string |
| } |
| +// readFails as an HTTP body makes reading the answer time out, as a |
| +// stalled body would: the endpoint answered, so it is no denial. |
| +const readFails = "\x00read fails" |
| + |
| +type failingReader struct{} |
| + |
| +func (failingReader) Read([]byte) (int, error) { return 0, os.ErrDeadlineExceeded } |
| + |
| func silentNet() *fakeNet { return &fakeNet{replies: map[string][]byte{}} } |
| func (n *fakeNet) DNS(_ context.Context, network string, server netip.AddrPort, query []byte) ([]byte, error) { |
| @@ -689,16 +850,89 @@ func (n *fakeNet) DNS(_ context.Context, network string, server netip.AddrPort, |
| if r, ok := n.replies[network+" "+server.String()]; ok { |
| return r, nil |
| } |
| + if err, ok := n.errs[network+" "+server.String()]; ok { |
| + return nil, err |
| + } |
| 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.doErr != nil { |
| + return nil, n.doErr |
| + } |
| 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 |
| + var rd io.Reader = strings.NewReader(body) |
| + if body == readFails { |
| + rd = failingReader{} |
| + } |
| + return &http.Response{StatusCode: code, Body: io.NopCloser(rd), Request: req}, nil |
| +} |
| + |
| +// TestRootProbesInconclusive: a probe passes only on demonstrated denial |
| +// or timeout. A local error, an empty reply, a failed token request, an |
| +// unexpected status or an unreadable answer shows nothing, so the probe |
| +// fails and says "inconclusive". |
| +func TestRootProbesInconclusive(t *testing.T) { |
| + empty := filepath.Join(t.TempDir(), "resolv.conf") |
| + if err := os.WriteFile(empty, nil, 0o444); err != nil { |
| + t.Fatal(err) |
| + } |
| + resolvers := []netip.Addr{netip.MustParseAddr("10.0.0.2")} |
| + meta := []netip.AddrPort{netip.MustParseAddrPort("169.254.169.254:80")} |
| + dnsErr := func(err error) *fakeNet { |
| + return &fakeNet{replies: map[string][]byte{}, errs: map[string]error{"tcp 10.0.0.2:53": err}} |
| + } |
| + web := func(f func(*http.Request) (int, string)) *fakeNet { |
| + return &fakeNet{replies: map[string][]byte{}, web: f} |
| + } |
| + token := func(put int, tokenless, withToken func() (int, string)) func(*http.Request) (int, string) { |
| + return func(req *http.Request) (int, string) { |
| + switch { |
| + case req.Method == http.MethodPut && put == 200: |
| + return 200, "tok" |
| + case req.Method == http.MethodPut: |
| + return put, "" |
| + case req.Header.Get(imdsTokenHeader) == "tok": |
| + return withToken() |
| + } |
| + return tokenless() |
| + } |
| + } |
| + answer := func(code int, body string) func() (int, string) { return func() (int, string) { return code, body } } |
| + for name, c := range map[string]struct { |
| + net *fakeNet |
| + probe string // the probe that must be inconclusive; "" when all pass |
| + }{ |
| + "dns refused": {dnsErr(syscall.ECONNREFUSED), ""}, |
| + "dns no route": {dnsErr(&net.OpError{Op: "dial", Err: os.NewSyscallError("connect", syscall.EHOSTUNREACH)}), ""}, |
| + "imdsv2 required, no role": {web(token(200, answer(401, ""), answer(404, ""))), ""}, |
| + "imdsv1 only, no role": {web(token(404, answer(404, ""), nil)), ""}, |
| + "dns local error": {dnsErr(&net.OpError{Op: "dial", Err: os.NewSyscallError("socket", syscall.EMFILE)}), ProbeVPCDNSSilent}, |
| + "dns empty reply": {&fakeNet{replies: map[string][]byte{"udp 10.0.0.2:53": {}}}, ProbeVPCDNSSilent}, |
| + "dns cancelled": {dnsErr(context.Canceled), ProbeVPCDNSSilent}, |
| + "token 500, tokenless 401": {web(token(500, answer(401, ""), nil)), ProbeMetadataNoCredential}, |
| + "token 500, tokenless 404": {web(token(500, answer(404, ""), nil)), ProbeMetadataNoCredential}, |
| + "token 200 empty": {web(func(req *http.Request) (int, string) { |
| + return map[bool]int{true: 200, false: 401}[req.Method == http.MethodPut], "" |
| + }), ProbeMetadataNoCredential}, |
| + "token issued, then 500": {web(token(200, answer(401, ""), answer(500, ""))), ProbeMetadataNoCredential}, |
| + "tokenless 401, no token": {web(token(404, answer(401, ""), nil)), ProbeMetadataNoCredential}, |
| + "credentials 200 empty": {web(token(404, answer(200, " "), nil)), ProbeMetadataNoCredential}, |
| + "credentials unreadable": {web(token(404, answer(404, readFails), nil)), ProbeMetadataNoCredential}, |
| + "metadata local error": {&fakeNet{replies: map[string][]byte{}, doErr: os.NewSyscallError("socket", syscall.EMFILE)}, ProbeMetadataNoCredential}, |
| + "credentials redirect (302)": {web(token(404, answer(302, ""), nil)), ProbeMetadataNoCredential}, |
| + } { |
| + for _, p := range rootProbes(context.Background(), c.net, resolvers, meta, empty) { |
| + unsure := p.Name == c.probe |
| + if p.OK == unsure || unsure != strings.Contains(p.Detail, "inconclusive") { |
| + t.Errorf("%s: %+v; want ok %v and inconclusive %v", name, p, !unsure, unsure) |
| + } |
| + } |
| + } |
| } |
| func TestRootProbes(t *testing.T) { |
| @@ -809,6 +1043,46 @@ func TestRootProbesInterrupted(t *testing.T) { |
| } |
| } |
| +// TestPolicySetDigest checks PolicySetDigest against a value computed |
| +// outside Go: printf '%s %s\n%s %s\n' <sha256 of checks.json> \ |
| +// /usr/lib/equipo/policy/checks.json <sha256 of net.json> \ |
| +// /usr/lib/equipo/policy/net.json | sha256sum. |
| +func TestPolicySetDigest(t *testing.T) { |
| + const ( |
| + checksPath = "/usr/lib/equipo/policy/checks.json" |
| + netPath = "/usr/lib/equipo/policy/net.json" |
| + checksSum = "53d336bccedb7be25946490a624c3bee8d0f4f2db8473ccdfd08405e7af5f507" // {"policy":"checks"} |
| + netSum = "24dd96ef546c7db937f4d51538832f7ded96360452c9139bdb016d435d601515" // {"policy":"net"} |
| + want = "7e0a22c2b10d78376c7c084c99891529e9f2d54b43460c904934b6d16548c98d" |
| + wantChecks = "86d5e72bca8427c95cccd8c430a0c9fe4a7636a7ceccddcdfb8b9ae3fff39543" // checks.json alone |
| + ) |
| + if sum(`{"policy":"checks"}`) != checksSum || sum(`{"policy":"net"}`) != netSum { |
| + t.Fatal("the fixture's file digests are wrong") |
| + } |
| + if got := PolicySetDigest(map[string]string{checksPath: checksSum}); got != wantChecks { |
| + t.Errorf("one file: %s, want %s", got, wantChecks) |
| + } |
| + // Order independence: whatever order the map gives, the same digest. |
| + for i := 0; i < 50; i++ { |
| + files := map[string]string{netPath: netSum} |
| + files[checksPath] = checksSum |
| + if got := PolicySetDigest(files); got != want { |
| + t.Fatalf("run %d: %s, want %s", i, got, want) |
| + } |
| + } |
| + // Content and path sensitivity. |
| + for name, files := range map[string]map[string]string{ |
| + "content changed": {checksPath: checksSum, netPath: sum(`{"policy":"net2"}`)}, |
| + "path changed": {checksPath: checksSum, "/usr/lib/equipo/policy/net2.json": netSum}, |
| + "digests swapped": {checksPath: netSum, netPath: checksSum}, |
| + "a file missing": {netPath: netSum}, |
| + } { |
| + if got := PolicySetDigest(files); got == want { |
| + t.Errorf("%s: digest unchanged", name) |
| + } |
| + } |
| +} |
| + |
| 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")} |
diff --git a/internal/vminit/rootprobe_linux.go b/internal/vminit/rootprobe_linux.go| index 4a2e7887..f059df08 100644 |
| --- a/internal/vminit/rootprobe_linux.go |
| +++ b/internal/vminit/rootprobe_linux.go |
| @@ -10,13 +10,17 @@ import ( |
| "net/http" |
| "net/netip" |
| "os" |
| + "strconv" |
| "strings" |
| + "syscall" |
| "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. |
| +// demonstrated the property it checks; a probe that could not tell (an |
| +// error that is not a denial, an answer it did not expect) is not OK and |
| +// says "inconclusive". 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"` |
| @@ -30,12 +34,14 @@ 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: every query to every managed resolver, over UDP |
| + // and TCP, timed out or was refused. 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: each metadata endpoint was unreachable, |
| + // or answered 404 for the credentials path, with an IMDSv2 token when |
| + // it issues one. With no endpoint configured it fails. That this is |
| + // the provider's metadata protocol is unproven until Task 34. |
| ProbeMetadataNoCredential = "root_metadata_no_credential" |
| // ProbeResolvConfEmpty: /etc/resolv.conf is an empty regular file. |
| ProbeResolvConfEmpty = "root_resolv_conf_empty" |
| @@ -61,8 +67,14 @@ const ( |
| imdsCredsPath = "/latest/meta-data/iam/security-credentials/" |
| // probeName is the name the DNS probe asks for. |
| probeName = "example.com." |
| + // inconclusive marks a probe that could not tell. |
| + inconclusive = "inconclusive" |
| ) |
| +// errRead marks an answer that arrived but could not be read: the peer |
| +// was reached, so it is never a denial. |
| +var errRead = errors.New("reading the answer") |
| + |
| // 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{ |
| @@ -72,12 +84,38 @@ func rootProbes(ctx context.Context, n RootNet, resolvers []netip.Addr, metadata |
| } |
| } |
| -func detail(notes []string) string { |
| +// denied reports whether err shows the network refused to carry the |
| +// request: a timeout, a refused connection or port, or no route. Any |
| +// other error (a local failure such as EMFILE, a cancellation, a read of |
| +// an answer) shows nothing. |
| +func denied(err error) bool { |
| + if err == nil || errors.Is(err, errRead) || errors.Is(err, context.Canceled) { |
| + return false |
| + } |
| + var ne net.Error |
| + return errors.Is(err, os.ErrDeadlineExceeded) || errors.Is(err, context.DeadlineExceeded) || |
| + (errors.As(err, &ne) && ne.Timeout()) || |
| + errors.Is(err, syscall.ECONNREFUSED) || errors.Is(err, syscall.EHOSTUNREACH) || errors.Is(err, syscall.ENETUNREACH) |
| +} |
| + |
| +// verdict sets res from what the probe saw: OK only with no failure and |
| +// nothing inconclusive, and never once ctx has ended, since a probe cut |
| +// short cannot tell silence from the cut. |
| +func verdict(ctx context.Context, res ProbeResult, failed, unsure bool, notes []string) ProbeResult { |
| + if ctx.Err() != nil { |
| + unsure = true |
| + notes = append(notes, "interrupted") |
| + } |
| + if unsure && !failed { |
| + notes = append([]string{inconclusive}, notes...) |
| + } |
| + res.OK = !failed && !unsure |
| s := strings.Join(notes, "; ") |
| if len(s) > maxProbeDetail { |
| s = s[:maxProbeDetail] |
| } |
| - return s |
| + res.Detail = s |
| + return res |
| } |
| func probeDNS(ctx context.Context, n RootNet, resolvers []netip.Addr) ProbeResult { |
| @@ -87,30 +125,26 @@ func probeDNS(ctx context.Context, n RootNet, resolvers []netip.Addr) ProbeResul |
| return res |
| } |
| query := dnsQuery(probeName) |
| - answered := false |
| + answered, unsure := false, 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 { |
| + switch { |
| + case len(reply) > 0: |
| answered = true |
| notes = append(notes, fmt.Sprintf("%s %s answered %d bytes", network, a, len(reply))) |
| - } else { |
| + case denied(err): |
| notes = append(notes, fmt.Sprintf("%s %s silent", network, a)) |
| + default: |
| + unsure = true |
| + notes = append(notes, fmt.Sprintf("%s %s: %s (%v)", network, a, inconclusive, err)) |
| } |
| } |
| } |
| - // 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 |
| + return verdict(ctx, res, answered, unsure, notes) |
| } |
| // dnsQuery is a one-question A query for name, recursion desired. |
| @@ -123,20 +157,36 @@ func dnsQuery(name string) []byte { |
| return append(q, 0, 0, 1, 0, 1) |
| } |
| +// probeMetadata asks each endpoint for an IMDSv2 token, then for the |
| +// credentials path without a token and, if one was issued, with it. An |
| +// endpoint shows no credential only when the token request was denied, |
| +// refused as not offered (403, 404, 405) or answered with a token, and |
| +// each credentials request was denied or answered 404 (a tokenless 401 |
| +// counts when a token was issued, as IMDSv2 requires one). A 200 with a |
| +// body names a role: a credential. Anything else is inconclusive. |
| 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 |
| + found, unsure := false, 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) != "" { |
| + switch { |
| + case err == nil && code == http.StatusOK && strings.TrimSpace(body) != "": |
| token = strings.TrimSpace(body) |
| + notes = append(notes, fmt.Sprintf("%s token issued", ep)) |
| + case err == nil && (code == http.StatusForbidden || code == http.StatusNotFound || code == http.StatusMethodNotAllowed): |
| + notes = append(notes, fmt.Sprintf("%s token not offered (%d)", ep, code)) |
| + case denied(err): |
| + notes = append(notes, fmt.Sprintf("%s token request unanswered", ep)) |
| + default: |
| + unsure = true |
| + notes = append(notes, fmt.Sprintf("%s token request %s (%s)", ep, inconclusive, outcome(code, err))) |
| } |
| tokens := []string{""} |
| if token != "" { |
| @@ -150,27 +200,34 @@ func probeMetadata(ctx context.Context, n RootNet, endpoints []netip.AddrPort) P |
| } |
| 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) != "": |
| + case err == nil && 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))) |
| + case err == nil && code == http.StatusNotFound: |
| + notes = append(notes, fmt.Sprintf("%s %s: 404, no role", ep, how)) |
| + case err == nil && code == http.StatusUnauthorized && tok == "" && token != "": |
| + notes = append(notes, fmt.Sprintf("%s %s: 401, a token is required", ep, how)) |
| + case denied(err): |
| + notes = append(notes, fmt.Sprintf("%s %s: unanswered", ep, how)) |
| default: |
| - notes = append(notes, fmt.Sprintf("%s %s: %d, no role", ep, how, code)) |
| + unsure = true |
| + notes = append(notes, fmt.Sprintf("%s %s: %s (%s)", ep, how, inconclusive, outcome(code, err))) |
| } |
| } |
| } |
| - if ctx.Err() != nil { |
| - found = true |
| - notes = append(notes, "interrupted") |
| + return verdict(ctx, res, found, unsure, notes) |
| +} |
| + |
| +func outcome(code int, err error) string { |
| + if err != nil { |
| + return err.Error() |
| } |
| - res.OK = !found |
| - res.Detail = detail(notes) |
| - return res |
| + return strconv.Itoa(code) |
| } |
| // fetch sends one request and reads at most maxProbeBody bytes of the |
| -// answer. The body is never logged or written out, only its length. |
| +// answer. The body is never logged or written out, only its length. A |
| +// failed read is errRead, never a denial. |
| 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() |
| @@ -188,7 +245,7 @@ func fetch(ctx context.Context, n RootNet, method, url string, header map[string |
| defer resp.Body.Close() |
| b, err := io.ReadAll(io.LimitReader(resp.Body, maxProbeBody)) |
| if err != nil { |
| - return 0, "", err |
| + return resp.StatusCode, "", fmt.Errorf("%w: %v", errRead, err) |
| } |
| return resp.StatusCode, string(b), nil |
| } |
| @@ -198,7 +255,7 @@ func probeResolvConf(path string) ProbeResult { |
| st, err := os.Lstat(path) |
| switch { |
| case err != nil: |
| - res.Detail = fmt.Sprintf("%s: %v", path, err) |
| + res.Detail = fmt.Sprintf("%s: %s (%v)", path, inconclusive, err) |
| case !st.Mode().IsRegular(): |
| res.Detail = fmt.Sprintf("%s is not a regular file (%v)", path, st.Mode().Type()) |
| case st.Size() != 0: |