carlos / platform Public

Clone
git clone https://amadan.net/carlos/platform

Plain git — no account needed to clone.

Download

Download this file

1//go:build linux
2
3package host
4
5import (
6 "context"
7 "crypto/sha256"
8 "encoding/hex"
9 "errors"
10 "fmt"
11 "os"
12 "path/filepath"
13 "strings"
14 "testing"
15 "time"
16)
17
18// The generation census that carlos-system-recover runs, on the two
19// refusals the harness box hit: a non-root service still running the
20// /opt/carlos/carlos an apply renamed over ("(deleted)"), and short-lived
21// tasks the service lookup refused with a bare "permission denied". These
22// drive the production service lookup (generationServiceEnv.reader) over a
23// fake /proc, replacing only systemctl, the unit files' ownership check,
24// the signed-binary proof and the owner uid a non-root test cannot have.
25
26type deletedExeFixture struct {
27 generationProcFixture
28 opt, image string
29 env generationServiceEnv
30 current string // digest the env proves for <opt>/carlos
31 prev string // and for <opt>/carlos.prev; "" is no carlos.prev
32 execStart string
33 mainPID string
34 unit string
35 tt *testing.T
36 // deletedName is the exe link's base name; "" is "carlos (deleted)".
37 deletedName string
38 // imageFile is the open descriptor of the task's current image.
39 imageFile *os.File
40}
41
42func (f *deletedExeFixture) t() *testing.T { return f.tt }
43
44const deletedExeBody = "carlos router build, now renamed over"
45
46func deletedExe(t *testing.T) *deletedExeFixture {
47 t.Helper()
48 g := generationProc(t)
49 f := &deletedExeFixture{generationProcFixture: g, opt: filepath.Join(t.TempDir(), "opt", "carlos"), mainPID: "41", unit: "carlos-relay.service"}
50 if err := os.MkdirAll(f.opt, 0o755); err != nil {
51 t.Fatal(err)
52 }
53 f.execStart = "{ path=" + f.opt + "/carlos ; argv[]=" + f.opt + "/carlos relay ; ignore_errors=no ; start_time=[n/a] ; stop_time=[n/a] ; pid=41 ; code=(null) ; status=0/0 }"
54 generationWrite(t, f.task+"/status", "Tgid:\t41\nUid:\t1001\t1001\t1001\t1001\nKthread:\t0\n")
55 group := "/system.slice/carlos-relay.service"
56 generationWrite(t, f.task+"/cgroup", "0::"+group+"\n")
57 generationWrite(t, f.proc+"/41/cgroup", "0::"+group+"\n")
58 // The image the task runs: open, then unlinked, as the apply's rename
59 // leaves the edge's. The exe link reads "<opt>/carlos (deleted)" and
60 // opens that image, as /proc/<pid>/exe does.
61 f.image = filepath.Join(t.TempDir(), "image")
62 f.writeImage(t, deletedExeBody, 0o755, true)
63 sum := sha256.Sum256([]byte(deletedExeBody))
64 f.current = "not-this-build"
65 f.prev = hex.EncodeToString(sum[:])
66 f.env = generationServiceEnv{proc: f.proc, opt: f.opt, owner: uint32(os.Getuid()),
67 show: func(_ context.Context, unit string) (map[string]string, error) {
68 if unit != f.unit {
69 return nil, fmt.Errorf("systemctl show %s: no such unit", unit)
70 }
71 return map[string]string{"ControlGroup": group, "MainPID": f.mainPID, "ExecStart": f.execStart, "FragmentPath": "/etc/systemd/system/" + unit}, nil
72 },
73 trust: func(string) error { return nil },
74 binary: func(_ context.Context, opt, path string) (rootFloorBinary, error) {
75 switch path {
76 case filepath.Join(opt, "carlos"):
77 return rootFloorBinary{Digest: f.current}, nil
78 case filepath.Join(opt, "carlos.prev"):
79 if f.prev == "" {
80 return rootFloorBinary{}, os.ErrNotExist
81 }
82 return rootFloorBinary{Digest: f.prev}, nil
83 }
84 return rootFloorBinary{}, os.ErrPermission
85 },
86 }
87 return f
88}
89
90// writeImage replaces the task's image with body at mode, unlinked or not.
91func (f *deletedExeFixture) writeImage(t *testing.T, body string, mode os.FileMode, unlink bool) {
92 t.Helper()
93 path := f.image + fmt.Sprint(time.Now().UnixNano())
94 if err := os.WriteFile(path, []byte(body), 0o600); err != nil {
95 t.Fatal(err)
96 }
97 if err := os.Chmod(path, mode); err != nil {
98 t.Fatal(err)
99 }
100 img, err := os.Open(path)
101 if err != nil {
102 t.Fatal(err)
103 }
104 t.Cleanup(func() { img.Close() })
105 f.imageFile = img
106 if unlink {
107 if err := os.Remove(path); err != nil {
108 t.Fatal(err)
109 }
110 }
111 name := f.deletedName
112 if name == "" {
113 name = "carlos (deleted)"
114 }
115 deleted := filepath.Join(f.opt, name)
116 os.Remove(deleted)
117 generationLink(t, fmt.Sprintf("/proc/%d/fd/%d", os.Getpid(), img.Fd()), deleted)
118 os.Remove(f.task + "/exe")
119 generationLink(t, deleted, f.task+"/exe")
120}
121
122// kernelCensus is one census pass through the production lookup, as
123// productionGenerationKernelCensus wires it: classify and recheck.
124func (f *deletedExeFixture) kernelCensus(ctx context.Context) error {
125 service, recheck := f.env.reader(ctx)
126 _, err := (generationKernel{proc: f.proc, service: service, recheck: recheck}).absent(ctx, f.reservation)
127 return err
128}
129
130func (f *deletedExeFixture) census(t *testing.T) error {
131 t.Helper()
132 return f.kernelCensus(t.Context())
133}
134
135func TestRecoverCensusAcceptsADeletedExeOfTheCurrentOrPreviousBuild(t *testing.T) {
136 for _, which := range []string{"previous", "current", "current-no-prev"} {
137 t.Run(which, func(t *testing.T) {
138 f := deletedExe(t)
139 switch which {
140 case "current":
141 f.current, f.prev = f.prev, "other-build"
142 case "current-no-prev":
143 f.current, f.prev = f.prev, ""
144 }
145 if err := f.census(t); err != nil {
146 t.Fatalf("census refused a deleted exe of the %s signed build: %v", which, err)
147 }
148 })
149 }
150}
151
152func TestRecoverCensusAcceptsTheEdgesDeletedExeInSupervise(t *testing.T) {
153 // The harness's b2 task: carlos-edge.service's main process, in its
154 // supervise/ group, still running the pre-apply image, with and
155 // without the guard drop-in (whose ExecStart is the guard and whose
156 // selected program is <opt>/carlos).
157 for _, guarded := range []bool{false, true} {
158 t.Run(map[bool]string{false: "unguarded", true: "guarded"}[guarded], func(t *testing.T) {
159 f := deletedExe(t)
160 f.unit = "carlos-edge.service"
161 if guarded {
162 f.execStart = "{ path=/opt/carlos/system/guard/carlos ; argv[]=/opt/carlos/system/guard/carlos system guard-exec edge ; ignore_errors=no ; start_time=[n/a] ; stop_time=[n/a] ; pid=41 ; code=(null) ; status=0/0 }"
163 binary := f.env.binary
164 f.env.binary = func(ctx context.Context, opt, path string) (rootFloorBinary, error) {
165 if path == "/opt/carlos/system/guard/carlos" {
166 return rootFloorBinary{Digest: "guard"}, nil
167 }
168 b, err := binary(ctx, opt, path)
169 b.File.Inode = 7 // the live <opt>/carlos, not the deleted image
170 return b, err
171 }
172 }
173 base := "/system.slice/carlos-edge.service"
174 generationWrite(t, f.task+"/cgroup", "0::"+base+"/supervise\n")
175 generationWrite(t, f.proc+"/41/cgroup", "0::"+base+"/supervise\n")
176 show := f.env.show
177 f.env.show = func(ctx context.Context, unit string) (map[string]string, error) {
178 props, err := show(ctx, unit)
179 if err == nil {
180 props["ControlGroup"] = base
181 }
182 return props, err
183 }
184 if err := f.census(t); err != nil {
185 t.Fatalf("census refused the edge's deleted signed image: %v", err)
186 }
187 // The same edge running some other deleted image still refuses.
188 f.writeImage(t, "an image no identity signs", 0o755, true)
189 if err := f.census(t); err == nil {
190 t.Fatal("census accepted an unsigned deleted image in the edge")
191 }
192 })
193 }
194}
195
196func TestRecoverCensusRefusesOtherDeletedExes(t *testing.T) {
197 for _, attack := range []string{"unsigned", "no-proof", "linked", "group-writable", "not-router-binary", "other-program", "deleted-helper", "other-path"} {
198 t.Run(attack, func(t *testing.T) {
199 f := deletedExe(t)
200 switch attack {
201 case "unsigned":
202 f.writeImage(t, "some other build", 0o755, true)
203 case "no-proof":
204 f.env.binary = func(context.Context, string, string) (rootFloorBinary, error) {
205 return rootFloorBinary{}, errRootFloorHistory
206 }
207 case "linked":
208 f.writeImage(t, deletedExeBody, 0o755, false)
209 case "group-writable":
210 f.writeImage(t, deletedExeBody, 0o775, true)
211 case "not-router-binary":
212 // The unit runs another program: a deleted <opt>/carlos is
213 // not what it selects.
214 f.execStart = strings.ReplaceAll(f.execStart, f.opt+"/carlos", f.opt+"/helper")
215 case "other-program":
216 f.execStart = strings.ReplaceAll(f.execStart, f.opt+"/carlos", "/usr/bin/carlos")
217 case "other-path":
218 // The unit selects <opt>/carlos, but the task's image was
219 // somewhere else when it was deleted.
220 f.deletedName = "carlos-copy (deleted)"
221 f.writeImage(t, deletedExeBody, 0o755, true)
222 case "deleted-helper":
223 // The unit's own program, deleted, with a signed router
224 // build's bytes: only <opt>/carlos is ever accepted.
225 f.execStart = strings.ReplaceAll(f.execStart, f.opt+"/carlos", f.opt+"/helper")
226 f.deletedName = "helper (deleted)"
227 f.writeImage(t, deletedExeBody, 0o755, true)
228 }
229 err := f.census(t)
230 if err == nil {
231 t.Fatalf("%s: census accepted the deleted exe", attack)
232 }
233 if !errors.Is(err, os.ErrPermission) && attack != "no-proof" {
234 t.Fatalf("%s: refusal %v is not a permission refusal", attack, err)
235 }
236 if !strings.Contains(err.Error(), "deleted exe check refused") {
237 t.Fatalf("%s: refusal %q does not name the deleted exe check", attack, err)
238 }
239 })
240 }
241}
242
243func TestRecoverCensusRefusesADeletedExeNotOwnedByRoot(t *testing.T) {
244 if os.Getuid() == 0 {
245 t.Skip("the fixture's image is root-owned when run as root")
246 }
247 f := deletedExe(t)
248 f.env.owner = 0 // production: the image must be root's
249 if err := f.census(t); err == nil || !strings.Contains(err.Error(), "not an unlinked root-owned file") {
250 t.Fatalf("census = %v, want a refusal of a non-root-owned image", err)
251 }
252}
253
254func TestRecoverCensusStillChecksReferencesOfAnAcceptedDeletedExe(t *testing.T) {
255 for _, ref := range []string{"fd", "mapped", "cwd"} {
256 t.Run(ref, func(t *testing.T) {
257 f := deletedExe(t)
258 b := f.reservation.Binding
259 switch ref {
260 case "fd":
261 generationLink(t, b.Path, f.task+"/fd/3")
262 case "mapped":
263 generationWrite(t, f.task+"/maps", fmt.Sprintf("1000-2000 r-xp 0000 %x:%x %d %s\n", generationMajor(b.Executable.Device), generationMinor(b.Executable.Device), b.Executable.Inode, b.Path))
264 case "cwd":
265 generationRelink(t, b.Tree, f.task+"/cwd")
266 }
267 if err := f.census(t); err == nil {
268 t.Fatalf("a deleted-exe task referencing a retired generation (%s) was accepted", ref)
269 }
270 })
271 }
272}
273
274func TestRecoverCensusRefusalsNameCheckUnitCgroupAndExe(t *testing.T) {
275 for _, tc := range []struct {
276 name, check, unit, group string
277 setup func(*deletedExeFixture)
278 }{
279 {"activating", "main pid", "carlos-relay.service", "/system.slice/carlos-relay.service", func(f *deletedExeFixture) { f.mainPID = "0" }},
280 {"session", "unit", "session-3.scope", "/user.slice/user-1000.slice/session-3.scope", func(f *deletedExeFixture) {
281 generationWrite(f.t(), f.task+"/cgroup", "0::/user.slice/user-1000.slice/session-3.scope\n")
282 }},
283 {"live-exe", "exe", "carlos-relay.service", "/system.slice/carlos-relay.service", func(f *deletedExeFixture) {
284 // A live (not deleted) exe the lookup cannot walk to as a
285 // root-owned file under the task's root.
286 generationRelink(f.t(), f.unrelated, f.task+"/exe")
287 generationRelink(f.t(), "/", f.task+"/root")
288 }},
289 } {
290 t.Run(tc.name, func(t *testing.T) {
291 f := deletedExe(t)
292 f.tt = t
293 tc.setup(f)
294 exe, _ := os.Readlink(f.task + "/exe")
295 err := f.census(t)
296 if err == nil {
297 t.Fatal("census accepted")
298 }
299 for _, want := range []string{"/41/task/41: service: " + tc.check, "service: " + tc.check + " check refused", "unit " + tc.unit, "cgroup " + tc.group, "exe " + exe} {
300 if !strings.Contains(err.Error(), want) {
301 t.Fatalf("refusal %q does not name %q", err, want)
302 }
303 }
304 })
305 }
306}
307
308func TestRecoverCensusRetriesATransientRefusalWithinTheWindow(t *testing.T) {
309 clock := time.Unix(0, 0)
310 var slept []time.Duration
311 now := func() time.Time { return clock }
312 sleep := func(_ context.Context, d time.Duration) error {
313 if clock.Sub(time.Unix(0, 0)) > time.Minute {
314 return errors.New("unbounded retry") // ends a run with no window
315 }
316 slept = append(slept, d)
317 clock = clock.Add(d)
318 return nil
319 }
320
321 // A unit still activating, through the real census pass: it clears on
322 // the fourth pass.
323 f := deletedExe(t)
324 passes := 0
325 inspect := func(ctx context.Context) (string, string, error) {
326 passes++
327 f.mainPID = "0"
328 if passes == 4 {
329 f.mainPID = "41"
330 }
331 err := f.kernelCensus(ctx)
332 return "boot", "digest", err
333 }
334 if _, _, err := generationCensusRetryFor(t.Context(), inspect, 20*time.Second, now, sleep); err != nil {
335 t.Fatalf("a transient refusal did not clear within the window: %v", err)
336 }
337 if passes != 4 || fmt.Sprint(slept) != "[250ms 500ms 1s]" {
338 t.Fatalf("passes=%d slept=%v, want 4 passes after 250ms, 500ms, 1s", passes, slept)
339 }
340
341 // The same refusal, persistent: refused once the next wait would end
342 // past the window, with the last pass's refusal.
343 clock, slept, passes = time.Unix(0, 0), nil, 0
344 persistent := func(ctx context.Context) (string, string, error) {
345 passes++
346 f.mainPID = "0"
347 err := f.kernelCensus(ctx)
348 return "", "", err
349 }
350 _, _, err := generationCensusRetryFor(t.Context(), persistent, 20*time.Second, now, sleep)
351 if err == nil || !strings.Contains(err.Error(), "main pid check refused") {
352 t.Fatalf("persistent refusal = %v", err)
353 }
354 var total time.Duration
355 for _, d := range slept {
356 total += d
357 }
358 if total > 20*time.Second || total < 15*time.Second || passes != len(slept)+1 {
359 t.Fatalf("persistent refusal: %d passes, slept %v (%s), want about 20 s then refuse", passes, slept, total)
360 }
361}
362
363func TestRecoverCensusRetriesOnlyTaskLevelTransients(t *testing.T) {
364 sleep := func(context.Context, time.Duration) error { return nil }
365 for _, tc := range []struct {
366 name string
367 err error
368 retry bool
369 }{
370 {"service", &generationTaskRefusal{task: "/proc/9/task/9", err: fmt.Errorf("service: %w", &generationServiceRefusal{check: "unit", err: os.ErrPermission})}, true},
371 {"exited", &generationTaskRefusal{task: "/proc/9/task/9", err: os.ErrNotExist}, true},
372 {"replaced", &generationTaskRefusal{task: "/proc/9/task/9", err: errGenerationTaskReplaced}, true},
373 {"reference", &generationTaskRefusal{task: "/proc/9/task/9", err: fmt.Errorf("fd: %w", os.ErrPermission)}, false},
374 {"mounts", &generationTaskRefusal{task: "/proc/9/task/9", err: fmt.Errorf("mounts: %w", os.ErrPermission)}, false},
375 {"structural", os.ErrPermission, false},
376 } {
377 t.Run(tc.name, func(t *testing.T) {
378 passes := 0
379 _, _, err := generationCensusRetryFor(t.Context(), func(context.Context) (string, string, error) {
380 passes++
381 if passes == 2 {
382 return "boot", "digest", nil
383 }
384 return "", "", tc.err
385 }, 20*time.Second, time.Now, sleep)
386 if tc.retry && (err != nil || passes != 2) {
387 t.Fatalf("transient %s: passes=%d err=%v", tc.name, passes, err)
388 }
389 if !tc.retry && (err == nil || passes != 1) {
390 t.Fatalf("%s retried: passes=%d err=%v", tc.name, passes, err)
391 }
392 })
393 }
394 // A cancelled wait refuses with the refusal it was waiting out.
395 ctx, cancel := context.WithCancel(t.Context())
396 refusal := &generationTaskRefusal{task: "/proc/9/task/9", err: os.ErrNotExist}
397 _, _, err := generationCensusRetryFor(ctx, func(context.Context) (string, string, error) { return "", "", refusal }, 20*time.Second, time.Now, func(context.Context, time.Duration) error { cancel(); return context.Canceled })
398 if !errors.Is(err, refusal) {
399 t.Fatalf("cancelled wait = %v", err)
400 }
401}
402
403func TestProductionGenerationCensusRefusalsAreTyped(t *testing.T) {
404 // Every refusal of the production census is a generationCensusRefusal,
405 // which is what lets a no-journal recovery defer it. As a non-root test
406 // the census refuses at its first check.
407 if os.Geteuid() == 0 {
408 t.Skip("the census does not refuse at once as root")
409 }
410 _, _, err := productionGenerationKernelCensus(t.Context())
411 var refusal *generationCensusRefusal
412 if !errors.As(err, &refusal) || !onlyCensusRefusal(err) || !errors.Is(err, os.ErrPermission) {
413 t.Fatalf("census refusal = %#v, want a typed census refusal", err)
414 }
415}
416
417// execRace runs one census pass through the production lookup with a hook
418// around each of its rechecks: before(final) runs before the recheck and
419// after(final) after it. The hooks stand in for the task exec'ing (the
420// same PID, the same start time) while the census inspects it.
421func (f *deletedExeFixture) execRace(t *testing.T, after func(final bool, call int), before func(final bool, call int)) error {
422 t.Helper()
423 classify, recheck := f.env.reader(t.Context())
424 calls := 0
425 hooked := func(path string, final bool) error {
426 calls++
427 if before != nil {
428 before(final, calls)
429 }
430 err := recheck(path, final)
431 if after != nil {
432 after(final, calls)
433 }
434 return err
435 }
436 _, err := (generationKernel{proc: f.proc, service: classify, recheck: hooked}).absent(t.Context(), f.reservation)
437 return err
438}
439
440func TestRecoverCensusRefusesATaskThatExecsAfterItsImageWasProven(t *testing.T) {
441 helper := func(f *deletedExeFixture) { generationRelink(t, f.unrelated, f.task+"/exe") }
442 for _, tc := range []struct {
443 name string
444 race func(f *deletedExeFixture) (after, before func(bool, int))
445 }{
446 // The task execs an unsigned helper between the hash and the first
447 // use of the trust.
448 {"after-classification", func(f *deletedExeFixture) (func(bool, int), func(bool, int)) {
449 return nil, func(_ bool, call int) {
450 if call == 1 {
451 helper(f)
452 }
453 }
454 }},
455 // It execs another image that reads the same, "<opt>/carlos
456 // (deleted)" with signed bytes, but is not the inode hashed.
457 {"same-name-other-inode", func(f *deletedExeFixture) (func(bool, int), func(bool, int)) {
458 return nil, func(_ bool, call int) {
459 if call == 1 {
460 f.writeImage(t, deletedExeBody, 0o755, true)
461 }
462 }
463 }},
464 // It execs the helper after the first check and is back on the
465 // proven image by the end: the check at the mounts use sees it.
466 {"between-uses", func(f *deletedExeFixture) (func(bool, int), func(bool, int)) {
467 target, err := os.Readlink(f.task + "/exe")
468 if err != nil {
469 t.Fatal(err)
470 }
471 return func(final bool, call int) {
472 if !final && call == 1 {
473 helper(f)
474 }
475 }, func(final bool, _ int) {
476 if final {
477 generationRelink(t, target, f.task+"/exe")
478 }
479 }
480 }},
481 // The proven image itself is made group-writable mid-inspection.
482 {"image-made-writable", func(f *deletedExeFixture) (func(bool, int), func(bool, int)) {
483 return nil, func(_ bool, call int) {
484 if call == 1 {
485 if err := f.imageFile.Chmod(0o775); err != nil {
486 t.Fatal(err)
487 }
488 }
489 }
490 }},
491 // It execs the helper after the last use, before the end.
492 {"before-the-end", func(f *deletedExeFixture) (func(bool, int), func(bool, int)) {
493 return func(final bool, call int) {
494 if !final && call == 2 {
495 helper(f)
496 }
497 }, nil
498 }},
499 } {
500 t.Run(tc.name, func(t *testing.T) {
501 f := deletedExe(t)
502 if err := f.execRace(t, nil, nil); err != nil {
503 t.Fatalf("census without a race refused: %v", err)
504 }
505 after, before := tc.race(f)
506 err := f.execRace(t, after, before)
507 if err == nil {
508 t.Fatal("census accepted a task that exec'd away from its proven image")
509 }
510 if !strings.Contains(err.Error(), "exe binding check refused") {
511 t.Fatalf("refusal %q does not name the exe binding check", err)
512 }
513 var task *generationTaskRefusal
514 if !errors.As(err, &task) || !task.transient() {
515 t.Fatalf("refusal %v is not a transient task refusal a later pass can clear", err)
516 }
517 })
518 }
519}
520
521func TestRecoverCensusNeedsABindingForATrustedTask(t *testing.T) {
522 // A kernel wired with a lookup but no recheck refuses every task the
523 // lookup trusts.
524 f := deletedExe(t)
525 classify, _ := f.env.reader(t.Context())
526 if _, err := (generationKernel{proc: f.proc, service: classify}).absent(t.Context(), f.reservation); err == nil || !strings.Contains(err.Error(), "no executable binding") {
527 t.Fatalf("census without a recheck = %v", err)
528 }
529}
530
531func TestRecoverCensusDeadlineCountsInspectionTime(t *testing.T) {
532 clock := time.Unix(0, 0)
533 now := func() time.Time { return clock }
534 sleep := func(_ context.Context, d time.Duration) error { clock = clock.Add(d); return nil }
535 transient := &generationTaskRefusal{task: "/proc/9/task/9", err: os.ErrNotExist}
536
537 // A slow pass that succeeds past the deadline refuses.
538 _, _, err := generationCensusRetryFor(t.Context(), func(context.Context) (string, string, error) {
539 clock = clock.Add(25 * time.Second)
540 return "boot", "digest", nil
541 }, 20*time.Second, now, sleep)
542 if !errors.Is(err, errGenerationCensusLate) {
543 t.Fatalf("a pass that ended past the window = %v, want a late refusal", err)
544 }
545
546 // Slow refused passes: inspection time and waits share the deadline,
547 // no pass starts after it, and the census refuses inside it.
548 clock = time.Unix(0, 0)
549 var starts []time.Duration
550 _, _, err = generationCensusRetryFor(t.Context(), func(context.Context) (string, string, error) {
551 starts = append(starts, clock.Sub(time.Unix(0, 0)))
552 clock = clock.Add(6 * time.Second)
553 return "", "", transient
554 }, 20*time.Second, now, sleep)
555 if err == nil {
556 t.Fatal("persistent refusal accepted")
557 }
558 for _, s := range starts {
559 if s >= 20*time.Second {
560 t.Fatalf("a pass started at %s, past the window (%v)", s, starts)
561 }
562 }
563 if end := clock.Sub(time.Unix(0, 0)); end > 26*time.Second {
564 t.Fatalf("census ran to %s with 6 s passes; it must stop at the first pass that ends past 20 s", end)
565 }
566 if len(starts) < 2 {
567 t.Fatalf("passes started at %v: the slow passes were not retried inside the window", starts)
568 }
569
570 // A wait that overruns (a timer firing late) never starts a pass past
571 // the deadline.
572 clock, starts = time.Unix(0, 0), nil
573 oversleep := func(_ context.Context, d time.Duration) error { clock = clock.Add(d + 3*time.Second); return nil }
574 _, _, err = generationCensusRetryFor(t.Context(), func(context.Context) (string, string, error) {
575 starts = append(starts, clock.Sub(time.Unix(0, 0)))
576 return "", "", transient
577 }, 20*time.Second, now, oversleep)
578 if !errors.Is(err, errGenerationCensusLate) {
579 t.Fatalf("overrun wait = %v, want a late refusal", err)
580 }
581 for _, s := range starts {
582 if s >= 20*time.Second {
583 t.Fatalf("a pass started at %s, past the window (%v)", s, starts)
584 }
585 }
586}
587
588func TestRecoverCensusDeadlineReachesTheInspection(t *testing.T) {
589 // On the real clock: the pass's context ends at the deadline, and a pass
590 // that only returns when it does is refused, promptly.
591 start := time.Now()
592 var deadline time.Time
593 var has bool
594 _, _, err := generationCensusRetryFor(t.Context(), func(ctx context.Context) (string, string, error) {
595 deadline, has = ctx.Deadline()
596 select {
597 case <-ctx.Done():
598 case <-time.After(2 * time.Second):
599 }
600 return "boot", "digest", nil
601 }, 50*time.Millisecond, time.Now, generationSleep)
602 if !errors.Is(err, errGenerationCensusLate) {
603 t.Fatalf("a pass blocked to the deadline = %v, want a late refusal", err)
604 }
605 if !has || deadline.Sub(start) > 50*time.Millisecond+10*time.Millisecond {
606 t.Fatalf("pass context deadline = %v (set %t), want the census's", deadline.Sub(start), has)
607 }
608 if took := time.Since(start); took > 2*time.Second {
609 t.Fatalf("census took %s past a 50 ms window", took)
610 }
611 // The lookup's own blocking reads get that context: systemctl show and
612 // the image hash.
613 f := deletedExe(t)
614 var showDeadline bool
615 show := f.env.show
616 f.env.show = func(ctx context.Context, unit string) (map[string]string, error) {
617 _, showDeadline = ctx.Deadline()
618 return show(ctx, unit)
619 }
620 if _, _, err := generationCensusRetryFor(t.Context(), func(ctx context.Context) (string, string, error) {
621 return "boot", "digest", f.kernelCensus(ctx)
622 }, 20*time.Second, time.Now, generationSleep); err != nil {
623 t.Fatal(err)
624 }
625 if !showDeadline {
626 t.Fatal("systemctl show ran without the census deadline")
627 }
628 // The deadline passes after the lookup has started on the task: the
629 // image hash stops.
630 ctx, cancel := context.WithCancel(t.Context())
631 f.env.show = func(ctx context.Context, unit string) (map[string]string, error) {
632 cancel()
633 return show(ctx, unit)
634 }
635 if err := f.kernelCensus(ctx); !errors.Is(err, context.Canceled) || !strings.Contains(err.Error(), "deleted exe check refused") {
636 t.Fatalf("image hash under an ended context = %v", err)
637 }
638}
639
640// guardedEdge makes the fixture's unit the guarded carlos-edge.service:
641// ExecStart is the guard, the selected program <opt>/carlos, and the task
642// is the edge's main process in its supervise/ group.
643func (f *deletedExeFixture) guardedEdge(t *testing.T) {
644 t.Helper()
645 f.unit = "carlos-edge.service"
646 f.execStart = "{ path=/opt/carlos/system/guard/carlos ; argv[]=/opt/carlos/system/guard/carlos system guard-exec edge ; ignore_errors=no ; start_time=[n/a] ; stop_time=[n/a] ; pid=41 ; code=(null) ; status=0/0 }"
647 binary := f.env.binary
648 f.env.binary = func(ctx context.Context, opt, path string) (rootFloorBinary, error) {
649 if path == "/opt/carlos/system/guard/carlos" {
650 return rootFloorBinary{Digest: "guard"}, nil
651 }
652 b, err := binary(ctx, opt, path)
653 b.File.Inode = 7
654 return b, err
655 }
656 base := "/system.slice/carlos-edge.service"
657 generationWrite(t, f.task+"/cgroup", "0::"+base+"/supervise\n")
658 generationWrite(t, f.proc+"/41/cgroup", "0::"+base+"/supervise\n")
659 show := f.env.show
660 f.env.show = func(ctx context.Context, unit string) (map[string]string, error) {
661 props, err := show(ctx, unit)
662 if err == nil {
663 props["ControlGroup"] = base
664 }
665 return props, err
666 }
667}
668
669func TestRecoverCensusDeletedExeOfARootTask(t *testing.T) {
670 // The deleted-exe acceptance also covers a root task of a unit with a
671 // selected image (the guarded edge), and only that among root tasks.
672 // The task runs in a private mount namespace, which the strict root
673 // scan refuses: only a trusted classification lets it pass.
674 root := func(t *testing.T, f *deletedExeFixture) {
675 generationWrite(t, f.task+"/status", "Tgid:\t41\nUid:\t0\t0\t0\t0\nKthread:\t0\n")
676 generationRelink(t, "private-service", f.task+"/ns/mnt")
677 }
678 t.Run("selected-image-signed", func(t *testing.T) {
679 f := deletedExe(t)
680 f.guardedEdge(t)
681 root(t, f)
682 if err := f.census(t); err != nil {
683 t.Fatalf("census refused a root guarded-edge task on its signed deleted image: %v", err)
684 }
685 })
686 t.Run("selected-image-unsigned", func(t *testing.T) {
687 f := deletedExe(t)
688 f.guardedEdge(t)
689 root(t, f)
690 f.writeImage(t, "an image no identity signs", 0o755, true)
691 if err := f.census(t); err == nil {
692 t.Fatal("census accepted a root guarded-edge task on an unsigned deleted image")
693 }
694 })
695 t.Run("no-selected-image", func(t *testing.T) {
696 // A root task of a unit with no selected image keeps main's path
697 // walk, which a deleted exe fails, so the strict root scan applies.
698 f := deletedExe(t)
699 root(t, f)
700 if err := f.census(t); err == nil {
701 t.Fatal("census trusted a root task of an unselected unit on its deleted exe")
702 }
703 })
704 t.Run("selected-image-exec-race", func(t *testing.T) {
705 f := deletedExe(t)
706 f.guardedEdge(t)
707 root(t, f)
708 err := f.execRace(t, nil, func(_ bool, call int) {
709 if call == 1 {
710 generationRelink(t, f.unrelated, f.task+"/exe")
711 }
712 })
713 if err == nil || !strings.Contains(err.Error(), "exe binding check refused") {
714 t.Fatalf("root guarded-edge task that exec'd away = %v", err)
715 }
716 })
717}
718
719// slowImage returns one byte per read and ends ctx after the first.
720type slowImage struct {
721 cancel func()
722 reads int
723}
724
725func (s *slowImage) Read(p []byte) (int, error) {
726 s.reads++
727 if s.reads == 1 {
728 s.cancel()
729 }
730 if len(p) == 0 {
731 return 0, nil
732 }
733 p[0] = 'x'
734 return 1, nil
735}
736
737func TestSignedBinaryProofStopsWhenTheCensusDeadlineEnds(t *testing.T) {
738 // The hash: a slow image whose read outlives the deadline.
739 ctx, cancel := context.WithCancel(t.Context())
740 image := &slowImage{cancel: cancel}
741 if _, err := rootFloorDigest(ctx, image); !errors.Is(err, context.Canceled) || image.reads > 2 {
742 t.Fatalf("digest = %v after %d reads, want it stopped at the deadline", err, image.reads)
743 }
744 // The identity scan: once the deadline has passed it reads no identity.
745 reads := 0
746 ctx, cancel = context.WithCancel(t.Context())
747 cancel()
748 if _, err := rootFloorSignedIdentity(ctx, nil, rootFloorBinary{Digest: "d"}, []string{"a.json"}, func(string) ([]byte, error) { reads++; return nil, nil }); !errors.Is(err, context.Canceled) || reads != 0 {
749 t.Fatalf("identity scan after the deadline = %v after %d reads", err, reads)
750 }
751}
752
753func TestRecoverCensusDeadlineReachesTheSignedBinaryProof(t *testing.T) {
754 // The lookup hands the census's deadline context to the signed-binary
755 // proof, for the deleted image and for the guarded edge's guard and
756 // selected images: a proof that only returns when that context ends
757 // is cut off at the deadline.
758 for _, guarded := range []bool{false, true} {
759 t.Run(map[bool]string{false: "deleted-image", true: "guarded-edge"}[guarded], func(t *testing.T) {
760 f := deletedExe(t)
761 if guarded {
762 f.guardedEdge(t)
763 }
764 proofs := 0
765 f.env.binary = func(ctx context.Context, opt, path string) (rootFloorBinary, error) {
766 proofs++
767 if _, ok := ctx.Deadline(); !ok {
768 t.Error("signed-binary proof ran without the census deadline")
769 }
770 select {
771 case <-ctx.Done():
772 return rootFloorBinary{}, ctx.Err()
773 case <-time.After(5 * time.Second):
774 return rootFloorBinary{}, errors.New("proof outlived the deadline")
775 }
776 }
777 start := time.Now()
778 _, _, err := generationCensusRetryFor(t.Context(), func(ctx context.Context) (string, string, error) {
779 return "boot", "digest", f.kernelCensus(ctx)
780 }, 100*time.Millisecond, time.Now, generationSleep)
781 if !errors.Is(err, errGenerationCensusLate) {
782 t.Fatalf("census = %v, want a late refusal", err)
783 }
784 if took := time.Since(start); took > 2*time.Second {
785 t.Fatalf("census took %s past a 100 ms window: the proof ignored its context", took)
786 }
787 if proofs == 0 {
788 t.Fatal("the proof never ran")
789 }
790 })
791 }
792}
793