oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1// Package containment owns attempt lifetimes through Linux PID namespaces.
2package containment
3
4import (
5 "context"
6 "crypto/rand"
7 "crypto/sha256"
8 "encoding/hex"
9 "encoding/json"
10 "errors"
11 "fmt"
12 "io"
13 "os"
14 "os/exec"
15 "path/filepath"
16 "runtime"
17 "strconv"
18 "strings"
19 "sync"
20 "syscall"
21 "time"
22
23 unix "amadan.net/oficina/equipo/internal/runner/containment/sysunix"
24 "amadan.net/oficina/equipo/internal/runner/egress"
25 "amadan.net/oficina/equipo/internal/runner/provider"
26)
27
28type Config struct {
29 Binary, RunnerBinary, ScratchRoot string
30 ProviderNetworks []provider.NetworkContract
31}
32type Manager struct {
33 waitExit func(context.Context, int) error
34 namespaceDigest string
35 cfg Config
36 // beforePin is a test seam for replacement after attestation.
37 beforePin func()
38 // secretEnv is provider.LaunchSecretEnv (a test seam).
39 secretEnv func(provider.Launch) (map[string]string, error)
40 mu sync.Mutex
41 processes map[string]*process
42}
43
44var _ provider.ProcessHost = (*Manager)(nil)
45var errStartup = errors.New("namespace_startup_failed")
46
47type process struct {
48 killed bool
49 egress *egress.Proxy
50 record Record
51 stdin *os.File
52 stdout, stderr *os.File
53 done chan struct{}
54 fd int
55 mu sync.Mutex
56 proof Proof
57 err error
58}
59
60func (p *process) EgressDenials() uint64 {
61 if p.egress == nil {
62 return 0
63 }
64 return p.egress.Denials()
65}
66
67func (p *process) Record() Record { return p.record }
68func (p *process) Contain(ctx context.Context) error {
69 if err := p.kill(); err != nil {
70 return err
71 }
72 _, err := p.Wait(ctx)
73 return err
74}
75
76func (p *process) ID() string { return p.record.ID }
77func (p *process) Stdin() io.WriteCloser { return p.stdin }
78func (p *process) Stdout() io.ReadCloser { return p.stdout }
79func (p *process) Stderr() io.ReadCloser { return p.stderr }
80func (p *process) Wait(ctx context.Context) (provider.Exit, error) {
81 select {
82 case <-ctx.Done():
83 return provider.Exit{}, ctx.Err()
84 case <-p.done:
85 return p.proof.Exit, p.err
86 }
87}
88func (p *process) kill() error {
89 p.mu.Lock()
90 defer p.mu.Unlock()
91 if p.fd < 0 {
92 return nil
93 }
94 e := unix.PidfdSendSignal(p.fd, unix.SIGKILL, nil, 0)
95 if e == nil {
96 p.killed = true
97 }
98 if e == unix.ESRCH {
99 return nil
100 }
101 return e
102}
103
104func New(cfg Config) (*Manager, error) {
105 for _, path := range []string{cfg.Binary, cfg.RunnerBinary, cfg.ScratchRoot} {
106 f, e := pin(path)
107 if e != nil {
108 return nil, e
109 }
110 f.Close()
111 }
112 info, e := os.Stat(cfg.ScratchRoot)
113 if e != nil || !info.IsDir() || info.Mode().Perm() != 0700 {
114 return nil, errMount
115 }
116 // The pinned build, by its bytes, before it is run even to ask its
117 // version: a version string is only what a program says of itself.
118 want, pinned := BubblewrapPin(runtime.GOARCH)
119 raw, e := os.ReadFile(cfg.Binary)
120 if sum := sha256.Sum256(raw); e != nil || !pinned || hex.EncodeToString(sum[:]) != want {
121 return nil, errors.New("namespace_bubblewrap_digest")
122 }
123 cmd := exec.Command(cfg.Binary, "--version")
124 cmd.Env = []string{"LANG=C"}
125 version, e := cmd.Output()
126 if e != nil || string(version) != "bubblewrap 0.11.0\n" {
127 return nil, errors.New("namespace_bubblewrap_version")
128 }
129 seen := map[string]bool{}
130 for _, c := range cfg.ProviderNetworks {
131 if seen[c.Provider] {
132 return nil, errStartup
133 }
134 if _, e := egress.ProviderPolicy(c, true); e != nil {
135 return nil, e
136 }
137 seen[c.Provider] = true
138 }
139 cfg.ProviderNetworks = append([]provider.NetworkContract(nil), cfg.ProviderNetworks...)
140 f, e := os.Open(cfg.RunnerBinary)
141 if e != nil {
142 return nil, e
143 }
144 current, currentErr := os.Stat("/proc/self/exe")
145 supplied, suppliedErr := f.Stat()
146 if currentErr != nil || suppliedErr != nil || !os.SameFile(current, supplied) {
147 f.Close()
148 return nil, errIdentity
149 }
150 h := sha256.New()
151 _, e = io.Copy(h, f)
152 closeErr := f.Close()
153 if e != nil || closeErr != nil {
154 return nil, errors.Join(e, closeErr)
155 }
156 return &Manager{waitExit: waitPID, cfg: cfg, namespaceDigest: hex.EncodeToString(h.Sum(nil)), processes: make(map[string]*process)}, nil
157}
158func (m *Manager) Start(ctx context.Context, l provider.Launch, argv []string) (provider.Process, error) {
159 return m.StartRecorded(ctx, l, argv, nil)
160}
161
162func (m *Manager) StartRecorded(ctx context.Context, l provider.Launch, argv []string, record func(context.Context, Record) error) (provider.Process, error) {
163 if l.Policy.IsSignIn() {
164 return nil, errStartup
165 }
166 return m.startRecorded(ctx, l, argv, record, nil, false)
167}
168
169// StartTerminal starts a sign-in launch (provider.BuildSignInPolicy) as
170// StartRecorded starts any other, with the harness's stdin and stdout a
171// pseudo-terminal: its Stdin and Stdout are the terminal's master side.
172// Only a sign-in gets a terminal.
173func (m *Manager) StartTerminal(ctx context.Context, l provider.Launch, argv []string, record func(context.Context, Record) error) (provider.Process, error) {
174 if !l.Policy.IsSignIn() {
175 return nil, errStartup
176 }
177 return m.startRecorded(ctx, l, argv, record, nil, true)
178}
179
180func (m *Manager) startRecorded(ctx context.Context, l provider.Launch, argv []string, record func(context.Context, Record) error, probe []string, terminal bool) (provider.Process, error) {
181 if e := ctx.Err(); e != nil {
182 return nil, e
183 }
184 if (l.Selection.Provider != "" && l.Policy.ManifestHash == "") || l.AttemptKey == "" || l.Policy.Hash == "" || len(argv) == 0 || !cleanAbsolute(argv[0]) {
185 return nil, errStartup
186 }
187 if e := l.Policy.ValidateRuntimeBinaries(m.cfg.Binary); e != nil {
188 return nil, e
189 }
190 manifestHash, err := provider.AttestLaunch(l, argv)
191 if err != nil {
192 return nil, err
193 }
194 if probe != nil {
195 argv = probe
196 }
197 if m.beforePin != nil {
198 m.beforePin()
199 }
200 var random [16]byte
201 if _, e := rand.Read(random[:]); e != nil {
202 return nil, e
203 }
204 id := hex.EncodeToString(random[:])
205 dir := filepath.Join(m.cfg.ScratchRoot, "attempt-"+id)
206 e := os.Mkdir(dir, 0700)
207 if e != nil {
208 return nil, e
209 }
210 cleanup := true
211 defer func() {
212 if cleanup {
213 os.RemoveAll(dir)
214 }
215 }()
216 for _, name := range []string{"home", "tmp"} {
217 if e = os.Mkdir(filepath.Join(dir, name), 0700); e != nil {
218 return nil, e
219 }
220 }
221 if l.Policy.IsCheck() || l.Policy.GoToolchain() {
222 for _, key := range []string{"GOCACHE", "GOTMPDIR"} {
223 path := l.Policy.Env[key]
224 if !strings.HasPrefix(path, "/tmp/") || filepath.Clean(path) != path {
225 return nil, errMount
226 }
227 if e = os.MkdirAll(filepath.Join(dir, "tmp", strings.TrimPrefix(path, "/tmp/")), 0700); e != nil {
228 return nil, e
229 }
230 }
231 }
232
233 if l.Policy.IsCheck() {
234 path := filepath.Join(dir, "tmp/xdg/go/telemetry")
235 if e = os.MkdirAll(path, 0700); e != nil {
236 return nil, e
237 }
238 if e = os.WriteFile(filepath.Join(path, "mode"), []byte("off\n"), 0600); e != nil {
239 return nil, e
240 }
241 }
242 mounts, e := m.mountPlan(l, dir)
243 if e != nil {
244 return nil, e
245 }
246 egressHash, e := m.openEgress(ctx, l, dir, mounts)
247 if e != nil {
248 mounts.close()
249 return nil, e
250 }
251 transferred := false
252 defer func() {
253 if !transferred && mounts.proxy != nil {
254 mounts.proxy.Close()
255 }
256 }()
257 boot, e := bootID()
258 if e != nil {
259 mounts.close()
260 return nil, e
261 }
262 secretEnv := provider.LaunchSecretEnv
263 if m.secretEnv != nil {
264 secretEnv = m.secretEnv
265 }
266 secret, e := secretEnv(l)
267 if e == nil {
268 e = mounts.addSecretEnv(secret)
269 }
270 clear(secret)
271 if e != nil {
272 mounts.close()
273 return nil, e
274 }
275 manifestHash, e = m.namespaceManifest(l, argv, manifestHash, dir, mounts)
276 if e != nil {
277 mounts.close()
278 return nil, e
279 }
280 r := Record{ID: id, AttemptKey: l.AttemptKey, BootID: boot, ManifestHash: manifestHash, PolicyHash: l.Policy.Hash, EgressHash: egressHash}
281 r.ParentPID = os.Getpid()
282 r.ParentTicks, _, e = identity(r.ParentPID)
283 if e != nil {
284 mounts.close()
285 return nil, e
286 }
287 if record != nil {
288 if e = record(ctx, r); e != nil {
289 mounts.close()
290 return nil, e
291 }
292 }
293 if e = m.persist(r); e != nil {
294 mounts.close()
295 return nil, e
296 }
297 result := make(chan startResult, 1)
298 // The goroutine that forks also waits. Keeping its OS thread locked prevents
299 // Go's Pdeathsig from firing when an unrelated calling goroutine returns.
300 finished := make(chan struct{})
301 go func() { m.lifecycle(ctx, r, argv, mounts, dir, result, record, terminal); close(finished) }()
302 cleanup = false
303 transferred = true
304 resultValue := <-result
305 if resultValue.err != nil {
306 <-finished
307 return nil, resultValue.err
308 }
309 return resultValue.p, nil
310}
311
312type startResult struct {
313 p *process
314 err error
315}
316
317const HelperProtocol = 3
318const LauncherVersion = provider.LauncherVersion
319
320type readiness struct {
321 Protocol int
322 PID int
323 Namespace string
324}
325
326func pipePair() (*os.File, *os.File, error) { return os.Pipe() }
327func (m *Manager) lifecycle(ctx context.Context, r Record, argv []string, mounts *mounts, dir string, result chan<- startResult, admit func(context.Context, Record) error, terminal bool) {
328 runtime.LockOSThread()
329 defer runtime.UnlockOSThread()
330 cleanupScratch := true
331 startedProcess := false
332 startupVerified := true
333 defer func() {
334 if !startedProcess {
335 proof := Proof{Record: r, Exit: provider.Exit{Code: -1, ObservedAt: time.Now().UTC()}, Verified: startupVerified}
336 if durableJSON(m.cfg.ScratchRoot, r.ID+".exit.json", proof) == nil {
337 m.finishRecovery(proof)
338 }
339 }
340 }()
341 defer func() {
342 if cleanupScratch {
343 os.RemoveAll(dir)
344 }
345 }()
346 defer mounts.close()
347 if mounts.proxy != nil {
348 defer mounts.proxy.Close()
349 }
350 var files []*os.File
351 pipe := func() (*os.File, *os.File, error) {
352 a, b, e := pipePair()
353 if e == nil {
354 files = append(files, a, b)
355 }
356 return a, b, e
357 }
358 defer func() {
359 for _, f := range files {
360 f.Close()
361 }
362 }()
363 statusR, statusW, e := pipe()
364 if e != nil {
365 result <- startResult{err: e}
366 return
367 }
368 releaseR, releaseW, e := pipe()
369 if e != nil {
370 result <- startResult{err: e}
371 return
372 }
373 readyR, readyW, e := pipe()
374 if e != nil {
375 result <- startResult{err: e}
376 return
377 }
378 var inputR, inputW, outputR, outputW *os.File
379 if terminal {
380 // One terminal for the harness's input and output: the slave side
381 // is its stdin and stdout, the master side the caller's.
382 inputW, inputR, e = OpenTerminal()
383 if e == nil {
384 files = append(files, inputW, inputR)
385 var fd int
386 // Under ForkLock, as os/exec does, so no fork in between
387 // inherits the duplicate before it is close-on-exec.
388 syscall.ForkLock.RLock()
389 if fd, e = syscall.Dup(int(inputW.Fd())); e == nil {
390 syscall.CloseOnExec(fd)
391 }
392 syscall.ForkLock.RUnlock()
393 if e == nil {
394 outputR = os.NewFile(uintptr(fd), "terminal")
395 outputW = inputR
396 files = append(files, outputR)
397 }
398 }
399 } else {
400 inputR, inputW, e = pipe()
401 if e == nil {
402 outputR, outputW, e = pipe()
403 }
404 }
405 if e != nil {
406 result <- startResult{err: e}
407 return
408 }
409 errorR, errorW, e := pipe()
410 if e != nil {
411 result <- startResult{err: e}
412 return
413 }
414 args := namespaceArgs(mounts, argv)
415 cmd := exec.Command(fmt.Sprintf("/proc/self/fd/%d", mounts.binaryFD), args...)
416 cmd.Env = []string{}
417 cmd.ExtraFiles = append([]*os.File{statusW, releaseR, readyW}, mounts.files...)
418 cmd.Stdin = inputR
419 cmd.Stdout = outputW
420 cmd.Stderr = errorW
421 cmd.SysProcAttr = parentDeathKill()
422 if e = cmd.Start(); e != nil {
423 result <- startResult{err: e}
424 return
425 }
426 statusW.Close()
427 releaseR.Close()
428 readyW.Close()
429 inputR.Close()
430 outputW.Close()
431 errorW.Close()
432 mounts.close()
433 type started struct {
434 record Record
435 fd int
436 err error
437 decoder *json.Decoder
438 }
439 handshake := make(chan started, 1)
440 go func() {
441 fail := func(e error) { handshake <- started{fd: -1, err: e} }
442 var status struct {
443 PID int `json:"child-pid"`
444 }
445 if e := json.NewDecoder(io.LimitReader(statusR, 4096)).Decode(&status); e != nil || status.PID <= 0 {
446 fail(errStartup)
447 return
448 }
449 var ready readiness
450 decoder := json.NewDecoder(io.LimitReader(readyR, 4096))
451 if e := decoder.Decode(&ready); e != nil || !validReadiness(ready) {
452 fail(errStartup)
453 return
454 }
455 ticks, ns, e := identity(status.PID)
456 if e != nil {
457 fail(e)
458 return
459 }
460 hostNS, e := os.Readlink("/proc/self/ns/pid")
461 if e != nil || ns == hostNS || ready.Namespace != ns {
462 fail(errIdentity)
463 return
464 }
465 r.HostPID = status.PID
466 r.StartTicks = ticks
467 r.NamespaceID = ns
468 fd, e := exactPID(r)
469 if e != nil {
470 fail(e)
471 return
472 }
473 handshake <- started{record: r, fd: fd, decoder: decoder}
474 }()
475 startupCtx, cancel := context.WithTimeout(ctx, 10*time.Second)
476 var s started
477 select {
478 case s = <-handshake:
479 case <-startupCtx.Done():
480 cmd.Process.Kill()
481 statusR.Close()
482 readyR.Close()
483 s = <-handshake
484 s.err = startupCtx.Err()
485 }
486 cancel()
487 if s.err != nil {
488 cmd.Process.Kill()
489 cmd.Wait()
490 if s.fd >= 0 {
491 waitCtx, stopWait := context.WithTimeout(context.Background(), 5*time.Second)
492 waitErr := m.waitExit(waitCtx, s.fd)
493 stopWait()
494 startupVerified = waitErr == nil
495 s.err = errors.Join(s.err, waitErr)
496 unix.Close(s.fd)
497 }
498 diagnostic, _ := io.ReadAll(io.LimitReader(errorR, 4096))
499 result <- startResult{err: fmt.Errorf("%w: %s", s.err, diagnostic)}
500 return
501 }
502 r = s.record
503 p := &process{record: s.record, stdin: inputW, stdout: outputR, stderr: errorR, done: make(chan struct{}), fd: s.fd, egress: mounts.proxy}
504 // Identity is durable before the helper can fork the harness or read input.
505 if e = m.persist(s.record); e == nil && admit != nil {
506 e = admit(ctx, s.record)
507 }
508 if e == nil {
509 _, e = releaseW.Write([]byte{1})
510 }
511 releaseW.Close()
512 if e != nil {
513 p.kill()
514 cmd.Process.Kill()
515 cmd.Wait()
516 waitCtx, stopWait := context.WithTimeout(context.Background(), 5*time.Second)
517 waitErr := m.waitExit(waitCtx, s.fd)
518 stopWait()
519 startupVerified = waitErr == nil
520 e = errors.Join(e, waitErr)
521 unix.Close(s.fd)
522 result <- startResult{err: e}
523 return
524 }
525 m.mu.Lock()
526 m.processes[r.ID] = p
527 m.mu.Unlock()
528 // Returned streams belong to the caller; retain buffered data after Wait.
529 files = []*os.File{statusR, statusW, releaseR, releaseW, readyR, readyW, inputR, outputW, errorW}
530 startedProcess = true
531 result <- startResult{p: p}
532 lifecycleDone := make(chan struct{})
533 var proxyDone <-chan struct{}
534 if p.egress != nil {
535 proxyDone = p.egress.Done()
536 }
537 go func() {
538 select {
539 case <-ctx.Done():
540 p.kill()
541 case <-proxyDone:
542 p.kill()
543 case <-lifecycleDone:
544 }
545 }()
546 e = waitPID(context.Background(), s.fd)
547 waitErr := cmd.Wait()
548 close(lifecycleDone)
549 exit := provider.Exit{Code: -1}
550 // Only the trusted helper can write this outcome frame. The harness never
551 // inherits the pipe. A numeric exit such as 137 must not invent a signal.
552 var outcome provider.Exit
553 if s.decoder.Decode(&outcome) == nil {
554 exit = outcome
555 }
556 p.mu.Lock()
557 if p.killed {
558 exit = provider.Exit{Code: -1, Signal: int(unix.SIGKILL)}
559 }
560 p.mu.Unlock()
561 exit.ObservedAt = time.Now().UTC()
562 var exitError *exec.ExitError
563 if waitErr != nil && !errors.As(waitErr, &exitError) && e == nil {
564 e = waitErr
565 }
566 p.mu.Lock()
567 unix.Close(p.fd)
568 p.fd = -1
569 p.mu.Unlock()
570 p.proof = Proof{Record: s.record, Exit: exit, Verified: e == nil}
571 p.err = e
572 if e == nil {
573 p.err = durableJSON(m.cfg.ScratchRoot, r.ID+".exit.json", p.proof)
574 if p.err != nil {
575 p.proof.Verified = false
576 }
577 }
578 if p.egress != nil {
579 p.egress.Close()
580 }
581 var cleanupErr error
582 p.proof, cleanupErr = m.finishRecovery(p.proof)
583 p.err = errors.Join(p.err, cleanupErr)
584 cleanupScratch = false
585 close(p.done)
586}
587func (m *Manager) Stop(ctx context.Context, id string) (Proof, error) {
588 m.mu.Lock()
589 p := m.processes[id]
590 m.mu.Unlock()
591 if p == nil {
592 return Proof{}, errIdentity
593 }
594 if e := p.kill(); e != nil {
595 return Proof{Record: p.record}, e
596 }
597 select {
598 case <-ctx.Done():
599 return Proof{Record: p.record}, ctx.Err()
600 case <-p.done:
601 return p.proof, p.err
602 }
603}
604
605// Changes to NamespaceMain or its helper protocol require a LauncherVersion bump.
606// NamespaceMain is the internal runner entry point. FD 4 receives the release
607// byte; FD 5 carries readiness and the final harness outcome.
608// Stdin/stdout/stderr are reserved for the harness. PID 1 always stays Go.
609func NamespaceMain(argv []string) int {
610 if os.Getpid() != 1 || len(argv) == 0 {
611 return 125
612 }
613 release := os.NewFile(4, "release")
614 ready := os.NewFile(5, "ready")
615 if release == nil || ready == nil {
616 return 125
617 }
618 ns, e := os.Readlink("/proc/self/ns/pid")
619 if e != nil {
620 return 125
621 }
622 if e = json.NewEncoder(ready).Encode(readiness{PID: os.Getpid(), Namespace: ns, Protocol: HelperProtocol}); e != nil {
623 return 125
624 }
625 var token [1]byte
626 if _, e = io.ReadFull(release, token[:]); e != nil || token[0] != 1 {
627 return 125
628 }
629 release.Close()
630 // The harness shares our UID. Disallow /proc/1/fd reopening and ptrace so
631 // it cannot forge outcome frames or reach future helper-owned relay FDs.
632 if e = unix.Prctl(unix.PR_SET_DUMPABLE, 0, 0, 0, 0); e != nil {
633 return 125
634 }
635 // No mount descriptors, journal handles or startup pipes reach the harness.
636 // CLOEXEC leaves Go's own poller usable until the helper exits.
637 if e = unix.CloseRange(3, ^uint(0), unix.CLOSE_RANGE_CLOEXEC); e != nil {
638 return 125
639 }
640 var relay *namespaceRelay
641 var relayFailed <-chan struct{}
642 if argv[0] == "--egress" {
643 argv = argv[1:]
644 if len(argv) == 0 {
645 return 125
646 }
647 relay, e = startRelay()
648 if e != nil {
649 return 125
650 }
651 defer relay.close()
652 relayFailed = relay.failed
653 }
654 cmd := exec.Command(argv[0], argv[1:]...)
655 cmd.Env = os.Environ()
656 cmd.Stdin = os.Stdin
657 cmd.Stdout = os.Stdout
658 cmd.Stderr = os.Stderr
659 if e = cmd.Start(); e != nil {
660 return 127
661 }
662 type waited struct {
663 status unix.WaitStatus
664 err error
665 }
666 harnessExit := make(chan waited, 1)
667 go func() {
668 for {
669 var status unix.WaitStatus
670 pid, e := unix.Wait4(-1, &status, 0, nil)
671 if e == unix.EINTR {
672 continue
673 }
674 if e != nil {
675 harnessExit <- waited{err: e}
676 return
677 }
678 if pid == cmd.Process.Pid {
679 harnessExit <- waited{status: status}
680 return
681 }
682 }
683 }()
684 var status unix.WaitStatus
685 select {
686 case <-relayFailed:
687 return 125
688 case w := <-harnessExit:
689 if w.err != nil {
690 return 125
691 }
692 status = w.status
693 }
694 _ = cmd.Process.Release()
695 outcome := provider.Exit{Code: status.ExitStatus()}
696 if status.Signaled() {
697 outcome.Code = -1
698 outcome.Signal = int(status.Signal())
699 }
700 if json.NewEncoder(ready).Encode(outcome) != nil {
701 return 125
702 }
703 ready.Close()
704 if status.Signaled() {
705 return 128 + int(status.Signal())
706 }
707 return status.ExitStatus()
708}
709
710func namespaceArgs(mounts *mounts, argv []string) []string {
711 args := provider.NamespaceArguments()
712 args = append(args, mounts.args...)
713 if mounts.secretFD > 0 {
714 args = append(args, "--args", strconv.Itoa(mounts.secretFD))
715 }
716 args = append(args, "--", "/equipo-namespace", "__namespace")
717 if mounts.proxy != nil {
718 args = append(args, "--egress")
719 }
720 args = append(args, argv...)
721 return args
722}
723
724// Hash the actual namespace plan after sources have been pinned, including the
725// generated scratch and socket paths. Directory contents include credentials
726// and workspaces, so only regular runtime files are digested here.
727func (m *Manager) namespaceManifest(l provider.Launch, argv []string, launchHash, dir string, p *mounts) (string, error) {
728 type file struct{ Path, Hash string }
729 files := []file{}
730 pinnedDigest := func(f *os.File) (string, error) {
731 reader, e := os.Open(fmt.Sprintf("/proc/self/fd/%d", f.Fd()))
732 if e != nil {
733 return "", e
734 }
735 defer reader.Close()
736 h := sha256.New()
737 if _, e = io.Copy(h, reader); e != nil {
738 return "", e
739 }
740 return hex.EncodeToString(h.Sum(nil)), nil
741 }
742 for _, f := range p.files {
743 info, e := f.Stat()
744 if e != nil {
745 return "", e
746 }
747 entry := file{Path: f.Name()}
748 if info.Mode().IsRegular() {
749 entry.Hash, e = pinnedDigest(f)
750 if e != nil {
751 return "", e
752 }
753 // Containment's own files (a Research step's CA bundle and
754 // stubs) are recorded by digest; they are not policy files.
755 if !p.own[f] {
756 if e = m.validatePinnedFile(l.Policy, f.Name(), entry.Hash); e != nil {
757 return "", e
758 }
759 }
760 }
761 files = append(files, entry)
762 }
763 for _, path := range []string{m.cfg.Binary, m.cfg.RunnerBinary} {
764 f, e := pin(path)
765 if e != nil {
766 return "", e
767 }
768 hash, e := pinnedDigest(f)
769 if e == nil {
770 e = m.validatePinnedFile(l.Policy, path, hash)
771 }
772 if e != nil {
773 f.Close()
774 return "", e
775 }
776 if path == m.cfg.Binary {
777 p.binaryFD = 6 + len(p.files)
778 p.files = append(p.files, f)
779 } else {
780 f.Close()
781 }
782 files = append(files, file{Path: path, Hash: hash})
783 }
784 raw, e := json.Marshal(struct {
785 LaunchHash, PolicyHash, Scratch string
786 Argv []string
787 Files []file
788 }{launchHash, l.Policy.Hash, dir, namespaceArgs(p, argv), files})
789 if e != nil {
790 return "", e
791 }
792 hash := sha256.Sum256(raw)
793 return hex.EncodeToString(hash[:]), nil
794}
795
796// The trusted namespace executable is pinned when this manager opens. Its bytes
797// remain bound to concrete launch evidence without creating a release hash cycle.
798func (m *Manager) validatePinnedFile(p provider.Policy, path, hash string) error {
799 if path == m.cfg.RunnerBinary {
800 if m.namespaceDigest == "" || hash != m.namespaceDigest {
801 return errStartup
802 }
803 return nil
804 }
805 return p.ValidateFileDigest(path, hash)
806}
807
808func validReadiness(r readiness) bool { return r.PID == 1 && r.Protocol == HelperProtocol }
809