// Package containment owns attempt lifetimes through Linux PID namespaces. package containment import ( "context" "crypto/rand" "crypto/sha256" "encoding/hex" "encoding/json" "errors" "fmt" "io" "os" "os/exec" "path/filepath" "runtime" "strconv" "strings" "sync" "syscall" "time" unix "amadan.net/oficina/equipo/internal/runner/containment/sysunix" "amadan.net/oficina/equipo/internal/runner/egress" "amadan.net/oficina/equipo/internal/runner/provider" ) type Config struct { Binary, RunnerBinary, ScratchRoot string ProviderNetworks []provider.NetworkContract } type Manager struct { waitExit func(context.Context, int) error namespaceDigest string cfg Config // beforePin is a test seam for replacement after attestation. beforePin func() // secretEnv is provider.LaunchSecretEnv (a test seam). secretEnv func(provider.Launch) (map[string]string, error) mu sync.Mutex processes map[string]*process } var _ provider.ProcessHost = (*Manager)(nil) var errStartup = errors.New("namespace_startup_failed") type process struct { killed bool egress *egress.Proxy record Record stdin *os.File stdout, stderr *os.File done chan struct{} fd int mu sync.Mutex proof Proof err error } func (p *process) EgressDenials() uint64 { if p.egress == nil { return 0 } return p.egress.Denials() } func (p *process) Record() Record { return p.record } func (p *process) Contain(ctx context.Context) error { if err := p.kill(); err != nil { return err } _, err := p.Wait(ctx) return err } func (p *process) ID() string { return p.record.ID } func (p *process) Stdin() io.WriteCloser { return p.stdin } func (p *process) Stdout() io.ReadCloser { return p.stdout } func (p *process) Stderr() io.ReadCloser { return p.stderr } func (p *process) Wait(ctx context.Context) (provider.Exit, error) { select { case <-ctx.Done(): return provider.Exit{}, ctx.Err() case <-p.done: return p.proof.Exit, p.err } } func (p *process) kill() error { p.mu.Lock() defer p.mu.Unlock() if p.fd < 0 { return nil } e := unix.PidfdSendSignal(p.fd, unix.SIGKILL, nil, 0) if e == nil { p.killed = true } if e == unix.ESRCH { return nil } return e } func New(cfg Config) (*Manager, error) { for _, path := range []string{cfg.Binary, cfg.RunnerBinary, cfg.ScratchRoot} { f, e := pin(path) if e != nil { return nil, e } f.Close() } info, e := os.Stat(cfg.ScratchRoot) if e != nil || !info.IsDir() || info.Mode().Perm() != 0700 { return nil, errMount } // The pinned build, by its bytes, before it is run even to ask its // version: a version string is only what a program says of itself. want, pinned := BubblewrapPin(runtime.GOARCH) raw, e := os.ReadFile(cfg.Binary) if sum := sha256.Sum256(raw); e != nil || !pinned || hex.EncodeToString(sum[:]) != want { return nil, errors.New("namespace_bubblewrap_digest") } cmd := exec.Command(cfg.Binary, "--version") cmd.Env = []string{"LANG=C"} version, e := cmd.Output() if e != nil || string(version) != "bubblewrap 0.11.0\n" { return nil, errors.New("namespace_bubblewrap_version") } seen := map[string]bool{} for _, c := range cfg.ProviderNetworks { if seen[c.Provider] { return nil, errStartup } if _, e := egress.ProviderPolicy(c, true); e != nil { return nil, e } seen[c.Provider] = true } cfg.ProviderNetworks = append([]provider.NetworkContract(nil), cfg.ProviderNetworks...) f, e := os.Open(cfg.RunnerBinary) if e != nil { return nil, e } current, currentErr := os.Stat("/proc/self/exe") supplied, suppliedErr := f.Stat() if currentErr != nil || suppliedErr != nil || !os.SameFile(current, supplied) { f.Close() return nil, errIdentity } h := sha256.New() _, e = io.Copy(h, f) closeErr := f.Close() if e != nil || closeErr != nil { return nil, errors.Join(e, closeErr) } return &Manager{waitExit: waitPID, cfg: cfg, namespaceDigest: hex.EncodeToString(h.Sum(nil)), processes: make(map[string]*process)}, nil } func (m *Manager) Start(ctx context.Context, l provider.Launch, argv []string) (provider.Process, error) { return m.StartRecorded(ctx, l, argv, nil) } func (m *Manager) StartRecorded(ctx context.Context, l provider.Launch, argv []string, record func(context.Context, Record) error) (provider.Process, error) { if l.Policy.IsSignIn() { return nil, errStartup } return m.startRecorded(ctx, l, argv, record, nil, false) } // StartTerminal starts a sign-in launch (provider.BuildSignInPolicy) as // StartRecorded starts any other, with the harness's stdin and stdout a // pseudo-terminal: its Stdin and Stdout are the terminal's master side. // Only a sign-in gets a terminal. func (m *Manager) StartTerminal(ctx context.Context, l provider.Launch, argv []string, record func(context.Context, Record) error) (provider.Process, error) { if !l.Policy.IsSignIn() { return nil, errStartup } return m.startRecorded(ctx, l, argv, record, nil, true) } func (m *Manager) startRecorded(ctx context.Context, l provider.Launch, argv []string, record func(context.Context, Record) error, probe []string, terminal bool) (provider.Process, error) { if e := ctx.Err(); e != nil { return nil, e } if (l.Selection.Provider != "" && l.Policy.ManifestHash == "") || l.AttemptKey == "" || l.Policy.Hash == "" || len(argv) == 0 || !cleanAbsolute(argv[0]) { return nil, errStartup } if e := l.Policy.ValidateRuntimeBinaries(m.cfg.Binary); e != nil { return nil, e } manifestHash, err := provider.AttestLaunch(l, argv) if err != nil { return nil, err } if probe != nil { argv = probe } if m.beforePin != nil { m.beforePin() } var random [16]byte if _, e := rand.Read(random[:]); e != nil { return nil, e } id := hex.EncodeToString(random[:]) dir := filepath.Join(m.cfg.ScratchRoot, "attempt-"+id) e := os.Mkdir(dir, 0700) if e != nil { return nil, e } cleanup := true defer func() { if cleanup { os.RemoveAll(dir) } }() for _, name := range []string{"home", "tmp"} { if e = os.Mkdir(filepath.Join(dir, name), 0700); e != nil { return nil, e } } if l.Policy.IsCheck() || l.Policy.GoToolchain() { for _, key := range []string{"GOCACHE", "GOTMPDIR"} { path := l.Policy.Env[key] if !strings.HasPrefix(path, "/tmp/") || filepath.Clean(path) != path { return nil, errMount } if e = os.MkdirAll(filepath.Join(dir, "tmp", strings.TrimPrefix(path, "/tmp/")), 0700); e != nil { return nil, e } } } if l.Policy.IsCheck() { path := filepath.Join(dir, "tmp/xdg/go/telemetry") if e = os.MkdirAll(path, 0700); e != nil { return nil, e } if e = os.WriteFile(filepath.Join(path, "mode"), []byte("off\n"), 0600); e != nil { return nil, e } } mounts, e := m.mountPlan(l, dir) if e != nil { return nil, e } egressHash, e := m.openEgress(ctx, l, dir, mounts) if e != nil { mounts.close() return nil, e } transferred := false defer func() { if !transferred && mounts.proxy != nil { mounts.proxy.Close() } }() boot, e := bootID() if e != nil { mounts.close() return nil, e } secretEnv := provider.LaunchSecretEnv if m.secretEnv != nil { secretEnv = m.secretEnv } secret, e := secretEnv(l) if e == nil { e = mounts.addSecretEnv(secret) } clear(secret) if e != nil { mounts.close() return nil, e } manifestHash, e = m.namespaceManifest(l, argv, manifestHash, dir, mounts) if e != nil { mounts.close() return nil, e } r := Record{ID: id, AttemptKey: l.AttemptKey, BootID: boot, ManifestHash: manifestHash, PolicyHash: l.Policy.Hash, EgressHash: egressHash} r.ParentPID = os.Getpid() r.ParentTicks, _, e = identity(r.ParentPID) if e != nil { mounts.close() return nil, e } if record != nil { if e = record(ctx, r); e != nil { mounts.close() return nil, e } } if e = m.persist(r); e != nil { mounts.close() return nil, e } result := make(chan startResult, 1) // The goroutine that forks also waits. Keeping its OS thread locked prevents // Go's Pdeathsig from firing when an unrelated calling goroutine returns. finished := make(chan struct{}) go func() { m.lifecycle(ctx, r, argv, mounts, dir, result, record, terminal); close(finished) }() cleanup = false transferred = true resultValue := <-result if resultValue.err != nil { <-finished return nil, resultValue.err } return resultValue.p, nil } type startResult struct { p *process err error } const HelperProtocol = 3 const LauncherVersion = provider.LauncherVersion type readiness struct { Protocol int PID int Namespace string } func pipePair() (*os.File, *os.File, error) { return os.Pipe() } func (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) { runtime.LockOSThread() defer runtime.UnlockOSThread() cleanupScratch := true startedProcess := false startupVerified := true defer func() { if !startedProcess { proof := Proof{Record: r, Exit: provider.Exit{Code: -1, ObservedAt: time.Now().UTC()}, Verified: startupVerified} if durableJSON(m.cfg.ScratchRoot, r.ID+".exit.json", proof) == nil { m.finishRecovery(proof) } } }() defer func() { if cleanupScratch { os.RemoveAll(dir) } }() defer mounts.close() if mounts.proxy != nil { defer mounts.proxy.Close() } var files []*os.File pipe := func() (*os.File, *os.File, error) { a, b, e := pipePair() if e == nil { files = append(files, a, b) } return a, b, e } defer func() { for _, f := range files { f.Close() } }() statusR, statusW, e := pipe() if e != nil { result <- startResult{err: e} return } releaseR, releaseW, e := pipe() if e != nil { result <- startResult{err: e} return } readyR, readyW, e := pipe() if e != nil { result <- startResult{err: e} return } var inputR, inputW, outputR, outputW *os.File if terminal { // One terminal for the harness's input and output: the slave side // is its stdin and stdout, the master side the caller's. inputW, inputR, e = OpenTerminal() if e == nil { files = append(files, inputW, inputR) var fd int // Under ForkLock, as os/exec does, so no fork in between // inherits the duplicate before it is close-on-exec. syscall.ForkLock.RLock() if fd, e = syscall.Dup(int(inputW.Fd())); e == nil { syscall.CloseOnExec(fd) } syscall.ForkLock.RUnlock() if e == nil { outputR = os.NewFile(uintptr(fd), "terminal") outputW = inputR files = append(files, outputR) } } } else { inputR, inputW, e = pipe() if e == nil { outputR, outputW, e = pipe() } } if e != nil { result <- startResult{err: e} return } errorR, errorW, e := pipe() if e != nil { result <- startResult{err: e} return } args := namespaceArgs(mounts, argv) cmd := exec.Command(fmt.Sprintf("/proc/self/fd/%d", mounts.binaryFD), args...) cmd.Env = []string{} cmd.ExtraFiles = append([]*os.File{statusW, releaseR, readyW}, mounts.files...) cmd.Stdin = inputR cmd.Stdout = outputW cmd.Stderr = errorW cmd.SysProcAttr = parentDeathKill() if e = cmd.Start(); e != nil { result <- startResult{err: e} return } statusW.Close() releaseR.Close() readyW.Close() inputR.Close() outputW.Close() errorW.Close() mounts.close() type started struct { record Record fd int err error decoder *json.Decoder } handshake := make(chan started, 1) go func() { fail := func(e error) { handshake <- started{fd: -1, err: e} } var status struct { PID int `json:"child-pid"` } if e := json.NewDecoder(io.LimitReader(statusR, 4096)).Decode(&status); e != nil || status.PID <= 0 { fail(errStartup) return } var ready readiness decoder := json.NewDecoder(io.LimitReader(readyR, 4096)) if e := decoder.Decode(&ready); e != nil || !validReadiness(ready) { fail(errStartup) return } ticks, ns, e := identity(status.PID) if e != nil { fail(e) return } hostNS, e := os.Readlink("/proc/self/ns/pid") if e != nil || ns == hostNS || ready.Namespace != ns { fail(errIdentity) return } r.HostPID = status.PID r.StartTicks = ticks r.NamespaceID = ns fd, e := exactPID(r) if e != nil { fail(e) return } handshake <- started{record: r, fd: fd, decoder: decoder} }() startupCtx, cancel := context.WithTimeout(ctx, 10*time.Second) var s started select { case s = <-handshake: case <-startupCtx.Done(): cmd.Process.Kill() statusR.Close() readyR.Close() s = <-handshake s.err = startupCtx.Err() } cancel() if s.err != nil { cmd.Process.Kill() cmd.Wait() if s.fd >= 0 { waitCtx, stopWait := context.WithTimeout(context.Background(), 5*time.Second) waitErr := m.waitExit(waitCtx, s.fd) stopWait() startupVerified = waitErr == nil s.err = errors.Join(s.err, waitErr) unix.Close(s.fd) } diagnostic, _ := io.ReadAll(io.LimitReader(errorR, 4096)) result <- startResult{err: fmt.Errorf("%w: %s", s.err, diagnostic)} return } r = s.record p := &process{record: s.record, stdin: inputW, stdout: outputR, stderr: errorR, done: make(chan struct{}), fd: s.fd, egress: mounts.proxy} // Identity is durable before the helper can fork the harness or read input. if e = m.persist(s.record); e == nil && admit != nil { e = admit(ctx, s.record) } if e == nil { _, e = releaseW.Write([]byte{1}) } releaseW.Close() if e != nil { p.kill() cmd.Process.Kill() cmd.Wait() waitCtx, stopWait := context.WithTimeout(context.Background(), 5*time.Second) waitErr := m.waitExit(waitCtx, s.fd) stopWait() startupVerified = waitErr == nil e = errors.Join(e, waitErr) unix.Close(s.fd) result <- startResult{err: e} return } m.mu.Lock() m.processes[r.ID] = p m.mu.Unlock() // Returned streams belong to the caller; retain buffered data after Wait. files = []*os.File{statusR, statusW, releaseR, releaseW, readyR, readyW, inputR, outputW, errorW} startedProcess = true result <- startResult{p: p} lifecycleDone := make(chan struct{}) var proxyDone <-chan struct{} if p.egress != nil { proxyDone = p.egress.Done() } go func() { select { case <-ctx.Done(): p.kill() case <-proxyDone: p.kill() case <-lifecycleDone: } }() e = waitPID(context.Background(), s.fd) waitErr := cmd.Wait() close(lifecycleDone) exit := provider.Exit{Code: -1} // Only the trusted helper can write this outcome frame. The harness never // inherits the pipe. A numeric exit such as 137 must not invent a signal. var outcome provider.Exit if s.decoder.Decode(&outcome) == nil { exit = outcome } p.mu.Lock() if p.killed { exit = provider.Exit{Code: -1, Signal: int(unix.SIGKILL)} } p.mu.Unlock() exit.ObservedAt = time.Now().UTC() var exitError *exec.ExitError if waitErr != nil && !errors.As(waitErr, &exitError) && e == nil { e = waitErr } p.mu.Lock() unix.Close(p.fd) p.fd = -1 p.mu.Unlock() p.proof = Proof{Record: s.record, Exit: exit, Verified: e == nil} p.err = e if e == nil { p.err = durableJSON(m.cfg.ScratchRoot, r.ID+".exit.json", p.proof) if p.err != nil { p.proof.Verified = false } } if p.egress != nil { p.egress.Close() } var cleanupErr error p.proof, cleanupErr = m.finishRecovery(p.proof) p.err = errors.Join(p.err, cleanupErr) cleanupScratch = false close(p.done) } func (m *Manager) Stop(ctx context.Context, id string) (Proof, error) { m.mu.Lock() p := m.processes[id] m.mu.Unlock() if p == nil { return Proof{}, errIdentity } if e := p.kill(); e != nil { return Proof{Record: p.record}, e } select { case <-ctx.Done(): return Proof{Record: p.record}, ctx.Err() case <-p.done: return p.proof, p.err } } // Changes to NamespaceMain or its helper protocol require a LauncherVersion bump. // NamespaceMain is the internal runner entry point. FD 4 receives the release // byte; FD 5 carries readiness and the final harness outcome. // Stdin/stdout/stderr are reserved for the harness. PID 1 always stays Go. func NamespaceMain(argv []string) int { if os.Getpid() != 1 || len(argv) == 0 { return 125 } release := os.NewFile(4, "release") ready := os.NewFile(5, "ready") if release == nil || ready == nil { return 125 } ns, e := os.Readlink("/proc/self/ns/pid") if e != nil { return 125 } if e = json.NewEncoder(ready).Encode(readiness{PID: os.Getpid(), Namespace: ns, Protocol: HelperProtocol}); e != nil { return 125 } var token [1]byte if _, e = io.ReadFull(release, token[:]); e != nil || token[0] != 1 { return 125 } release.Close() // The harness shares our UID. Disallow /proc/1/fd reopening and ptrace so // it cannot forge outcome frames or reach future helper-owned relay FDs. if e = unix.Prctl(unix.PR_SET_DUMPABLE, 0, 0, 0, 0); e != nil { return 125 } // No mount descriptors, journal handles or startup pipes reach the harness. // CLOEXEC leaves Go's own poller usable until the helper exits. if e = unix.CloseRange(3, ^uint(0), unix.CLOSE_RANGE_CLOEXEC); e != nil { return 125 } var relay *namespaceRelay var relayFailed <-chan struct{} if argv[0] == "--egress" { argv = argv[1:] if len(argv) == 0 { return 125 } relay, e = startRelay() if e != nil { return 125 } defer relay.close() relayFailed = relay.failed } cmd := exec.Command(argv[0], argv[1:]...) cmd.Env = os.Environ() cmd.Stdin = os.Stdin cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr if e = cmd.Start(); e != nil { return 127 } type waited struct { status unix.WaitStatus err error } harnessExit := make(chan waited, 1) go func() { for { var status unix.WaitStatus pid, e := unix.Wait4(-1, &status, 0, nil) if e == unix.EINTR { continue } if e != nil { harnessExit <- waited{err: e} return } if pid == cmd.Process.Pid { harnessExit <- waited{status: status} return } } }() var status unix.WaitStatus select { case <-relayFailed: return 125 case w := <-harnessExit: if w.err != nil { return 125 } status = w.status } _ = cmd.Process.Release() outcome := provider.Exit{Code: status.ExitStatus()} if status.Signaled() { outcome.Code = -1 outcome.Signal = int(status.Signal()) } if json.NewEncoder(ready).Encode(outcome) != nil { return 125 } ready.Close() if status.Signaled() { return 128 + int(status.Signal()) } return status.ExitStatus() } func namespaceArgs(mounts *mounts, argv []string) []string { args := provider.NamespaceArguments() args = append(args, mounts.args...) if mounts.secretFD > 0 { args = append(args, "--args", strconv.Itoa(mounts.secretFD)) } args = append(args, "--", "/equipo-namespace", "__namespace") if mounts.proxy != nil { args = append(args, "--egress") } args = append(args, argv...) return args } // Hash the actual namespace plan after sources have been pinned, including the // generated scratch and socket paths. Directory contents include credentials // and workspaces, so only regular runtime files are digested here. func (m *Manager) namespaceManifest(l provider.Launch, argv []string, launchHash, dir string, p *mounts) (string, error) { type file struct{ Path, Hash string } files := []file{} pinnedDigest := func(f *os.File) (string, error) { reader, e := os.Open(fmt.Sprintf("/proc/self/fd/%d", f.Fd())) if e != nil { return "", e } defer reader.Close() h := sha256.New() if _, e = io.Copy(h, reader); e != nil { return "", e } return hex.EncodeToString(h.Sum(nil)), nil } for _, f := range p.files { info, e := f.Stat() if e != nil { return "", e } entry := file{Path: f.Name()} if info.Mode().IsRegular() { entry.Hash, e = pinnedDigest(f) if e != nil { return "", e } // Containment's own files (a Research step's CA bundle and // stubs) are recorded by digest; they are not policy files. if !p.own[f] { if e = m.validatePinnedFile(l.Policy, f.Name(), entry.Hash); e != nil { return "", e } } } files = append(files, entry) } for _, path := range []string{m.cfg.Binary, m.cfg.RunnerBinary} { f, e := pin(path) if e != nil { return "", e } hash, e := pinnedDigest(f) if e == nil { e = m.validatePinnedFile(l.Policy, path, hash) } if e != nil { f.Close() return "", e } if path == m.cfg.Binary { p.binaryFD = 6 + len(p.files) p.files = append(p.files, f) } else { f.Close() } files = append(files, file{Path: path, Hash: hash}) } raw, e := json.Marshal(struct { LaunchHash, PolicyHash, Scratch string Argv []string Files []file }{launchHash, l.Policy.Hash, dir, namespaceArgs(p, argv), files}) if e != nil { return "", e } hash := sha256.Sum256(raw) return hex.EncodeToString(hash[:]), nil } // The trusted namespace executable is pinned when this manager opens. Its bytes // remain bound to concrete launch evidence without creating a release hash cycle. func (m *Manager) validatePinnedFile(p provider.Policy, path, hash string) error { if path == m.cfg.RunnerBinary { if m.namespaceDigest == "" || hash != m.namespaceDigest { return errStartup } return nil } return p.ValidateFileDigest(path, hash) } func validReadiness(r readiness) bool { return r.PID == 1 && r.Protocol == HelperProtocol }