package containment import ( "errors" "fmt" "io/fs" "os" "path/filepath" "sort" "strconv" "strings" "amadan.net/oficina/equipo/internal/runner/egress" "amadan.net/oficina/equipo/internal/runner/provider" "amadan.net/oficina/equipo/internal/runner/provider/gotoolchain" "amadan.net/oficina/equipo/internal/specialist" "golang.org/x/sys/unix" ) var errMount = errors.New("namespace_mount_rejected") type mounts struct { binaryFD int // secretFD is the pipe bubblewrap reads the secret environment from // (--args), 0 when the launch has none. secretFD int proxy *egress.Proxy args []string files []*os.File // own are files containment itself supplies (a Research step's CA // bundle and passwd and group stubs): digested into the namespace // manifest, but not policy files. own map[*os.File]bool } // secretEnvKeys are the only variables a launch may receive outside its // policy: a token connection's token, and the CLI's subprocess scrub; a // Pi or OpenCode launch's key, in its provider's variable // (provider.PiKeyEnvs, provider.OpenCodeKeyEnvs). var secretEnvKeys = func() map[string]bool { keys := map[string]bool{provider.OAuthTokenEnv: true, provider.ScrubEnv: true} for _, name := range provider.PiKeyEnvs { keys[name] = true } for _, name := range provider.OpenCodeKeyEnvs { keys[name] = true } return keys }() // addSecretEnv passes env to bubblewrap through a pipe it reads as // further arguments (--args FD, after --clearenv), so the values are in // no argv, no manifest and no record: the namespace's environment only. func (p *mounts) addSecretEnv(env map[string]string) error { if len(env) == 0 { return nil } keys := make([]string, 0, len(env)) for k := range env { keys = append(keys, k) } sort.Strings(keys) var b []byte for _, k := range keys { v := env[k] if !secretEnvKeys[k] || v == "" || strings.ContainsAny(v, "\x00\n") { return errMount } b = append(b, "--setenv\x00"+k+"\x00"...) b = append(b, v...) b = append(b, 0) } defer clear(b) r, w, err := os.Pipe() if err != nil { return err } // The whole message fits the pipe's buffer: a token is at most 4 KB. _, err = w.Write(b) if cerr := w.Close(); err == nil { err = cerr } if err != nil { r.Close() return err } p.secretFD = 6 + len(p.files) p.files = append(p.files, r) return nil } func (p *mounts) close() { for _, f := range p.files { _ = f.Close() } } func cleanAbsolute(path string) bool { return filepath.IsAbs(path) && filepath.Clean(path) == path && path != "/" } func within(path, root string) bool { return path == root || strings.HasPrefix(path, root+"/") } func overlaps(a, b string) bool { return within(a, b) || within(b, a) } // openat2 rejects symlinks in every component. The retained descriptor, rather // than the submitted path, is the source bubblewrap mounts after validation. func pin(path string) (*os.File, error) { if !cleanAbsolute(path) { return nil, errMount } fd, err := pathNoLinks(path) if err != nil { return nil, fmt.Errorf("%w: %v", errMount, err) } return os.NewFile(uintptr(fd), path), nil } func (p *mounts) bind(source, target string, ro, tree bool) error { f, err := pin(source) if err != nil { return err } return p.bindPinned(f, source, target, ro, tree) } // bindPinned binds an already pinned descriptor, and owns it from here: // it is closed on refusal. func (p *mounts) bindPinned(f *os.File, source, target string, ro, tree bool) error { info, err := f.Stat() if err != nil { f.Close() return err } if (tree && !info.IsDir()) || (!tree && source != "/usr" && !info.Mode().IsRegular()) { f.Close() return errMount } if tree { err = filepath.WalkDir(fmt.Sprintf("/proc/self/fd/%d/.", f.Fd()), func(path string, d fs.DirEntry, e error) error { if e != nil { return e } if d.Type()&(os.ModeSocket|os.ModeNamedPipe|os.ModeDevice) != 0 { return errMount } return nil }) if err != nil { f.Close() return err } } flag := "--bind-fd" if ro { flag = "--ro-bind-fd" } // FDs 3, 4 and 5 are status, release and readiness, respectively. p.args = append(p.args, flag, strconv.Itoa(6+len(p.files)), target) p.files = append(p.files, f) return nil } // signInTmpfs caps each of a sign-in's in-memory home and /tmp. const signInTmpfs = 64 << 20 func (m *Manager) mountPlan(l provider.Launch, dir string) (_ *mounts, err error) { p := &mounts{} defer func() { if err != nil { p.close() } }() // A sign-in has no workspace: an empty read-only one. signIn := l.Policy.IsSignIn() if signIn && (l.Workspace != "" || l.Binding.Home != "" || l.ToolSocket != "") { return nil, errMount } if !signIn && (!cleanAbsolute(l.Workspace) || overlaps(l.Workspace, m.cfg.ScratchRoot)) { return nil, errMount } for _, root := range []string{"/proc", "/sys", "/run", "/dev", "/etc", "/usr"} { if !signIn && overlaps(l.Workspace, root) { return nil, errMount } } home, err := os.UserHomeDir() if err != nil { return nil, err } if !signIn && (within(home, l.Workspace) || l.Workspace == "/home" || filepath.Dir(l.Workspace) == "/home" || l.Workspace == "/tmp" || l.Workspace == "/root") { return nil, errMount } if err = p.bind("/usr", "/usr", true, false); err != nil { return nil, err } research := l.Policy.Research() if research { // A Research step never sees the host /etc (spec §4): a fresh // tmpfs with the CA bundle and passwd and group stubs only. p.args = append(p.args, "--tmpfs", "/etc") if err = p.researchEtc(dir); err != nil { return nil, err } } else { p.args = append(p.args, "--overlay-src", "/etc", "--tmp-overlay", "/etc") } p.args = append(p.args, "--symlink", "usr/bin", "/bin", "--symlink", "usr/lib", "/lib", "--symlink", "usr/lib64", "/lib64", "--proc", "/proc", "--dev", "/dev", "--dir", "/run", "--dir", "/sys", "--dir", "/home/runner", "--tmpfs", "/etc/claude-code", "--tmpfs", "/etc/codex") if l.Policy.IsOpenCode() { // OpenCode reads /etc/opencode over every other configuration // (connectors spec §3, isolated configuration): an empty one. p.args = append(p.args, "--tmpfs", "/etc/opencode") } if l.Policy.Converse() { // The thin coordinator's desk: its own notes, read-only to it. if err = p.bind(l.Workspace, "/workspace", true, true); err != nil { return nil, err } } else if l.Policy.Coordinator() || signIn { p.args = append(p.args, "--tmpfs", "/workspace", "--remount-ro", "/workspace") } else if research { // The runner's empty scratch directory, never a clone or a desk. if err = p.bindEmpty(l.Workspace); err != nil { return nil, err } } else if err = p.bind(l.Workspace, "/workspace", l.Policy.ReadOnlyWorkspace(), true); err != nil { return nil, err } runtimeHome := filepath.Join(dir, "home") if l.Binding.Home != "" { runtimeHome = l.Binding.Home homes := filepath.Join(m.cfg.ScratchRoot, "homes") if !cleanAbsolute(runtimeHome) || filepath.Dir(runtimeHome) != homes || overlaps(runtimeHome, l.Workspace) { return nil, errMount } info, e := os.Stat(runtimeHome) if e != nil || !info.IsDir() || info.Mode().Perm() != 0700 { return nil, errMount } } if signIn { // A sign-in writes nothing to disk: its home and /tmp are the // namespace's own memory, capped, gone with it. The runner takes // the token from the CLI's output, never from a file here. p.args = append(p.args, "--size", strconv.Itoa(signInTmpfs), "--perms", "0700", "--tmpfs", "/home/runner", "--size", strconv.Itoa(signInTmpfs), "--perms", "1777", "--tmpfs", "/tmp") } else { if err = p.bind(runtimeHome, "/home/runner", false, true); err != nil { return nil, err } if err = p.bind(filepath.Join(dir, "tmp"), "/tmp", false, true); err != nil { return nil, err } } if err = p.bind(m.cfg.RunnerBinary, "/equipo-namespace", true, false); err != nil { return nil, err } if l.ResearchDir != "" { // Kept research images reach Engineering and Review only, never a // Research step or any other launch. if research || !l.Policy.ResearchReader() { return nil, fmt.Errorf("%w: research directory refused for this launch", errMount) } near := []string{l.Workspace, m.cfg.ScratchRoot, dir, l.Binding.Home, l.Binding.CredentialHome, l.Binding.RuntimeRoot} if l.ToolSocket != "" { near = append(near, filepath.Dir(l.ToolSocket)) } if err = p.bindResearch(l.ResearchDir, near); err != nil { return nil, err } } if l.RenderDir != "" { // The step's render_page captures reach the Design step only, // read-only: render_page writes them from outside. if !l.Policy.RenderReader() { return nil, fmt.Errorf("%w: render directory refused for this launch", errMount) } near := []string{l.Workspace, m.cfg.ScratchRoot, dir, l.Binding.Home, l.Binding.CredentialHome, l.Binding.RuntimeRoot} if l.ToolSocket != "" { near = append(near, filepath.Dir(l.ToolSocket)) } if err = p.bindKept(l.RenderDir, near, specialist.RenderMount, "render"); err != nil { return nil, err } } targets := map[string]bool{} for _, mount := range l.Policy.Mounts { gateMount := l.Policy.CheckGateMount(mount) if !gateMount && (l.Policy.IsCheck() || gotoolchain.Target(mount.Target)) && (overlaps(mount.Source, m.cfg.ScratchRoot) || mount.Source == "/" || within(home, mount.Source)) { return nil, errMount } target := mount.Target if !mount.ReadOnly || !cleanAbsolute(target) || targets[target] { return nil, errMount } if !gateMount && !(strings.HasPrefix(target, "/opt/") || strings.HasPrefix(target, "/config/") || strings.HasPrefix(target, "/etc/claude-code/") || strings.HasPrefix(target, "/etc/codex/")) { return nil, errMount } for _, existing := range l.Policy.Mounts { if existing.Target != target && overlaps(existing.Target, target) { return nil, errMount } } for _, protected := range []string{"/proc", "/sys", "/run", "/dev"} { if overlaps(mount.Source, protected) { return nil, errMount } } // bind validates and retains the same descriptor; no second path lookup. // A Pi launch's package tree is a directory, its digest checked by // the attestation; every other mount is a pinned file. tree := l.Policy.CheckGateTree(mount) || gotoolchain.Target(target) || l.Policy.IsPi() && target == provider.PiTree if gotoolchain.Target(target) { f, e := l.Policy.OpenGoTree(l.Binding, mount) if e != nil { return nil, e } err = p.bindPinned(f, mount.Source, target, true, tree) } else { err = p.bind(mount.Source, target, true, tree) } if err != nil { return nil, err } if l.Policy.CheckGateTree(mount) { mounted := p.files[len(p.files)-1] if sum, err := provider.TreeSHA256(fmt.Sprintf("/proc/self/fd/%d/.", mounted.Fd())); err != nil || sum != l.Policy.CheckGateTreeSHA(mount) { return nil, errMount } } if l.Policy.IsPi() && target == provider.PiTree { // The tree as mounted, through the descriptor bubblewrap // mounts, not by its path again: one replaced after the // attestation is refused here. source, pin, ok := l.Policy.PiTree() mounted := p.files[len(p.files)-1] if !ok || source != mount.Source { return nil, errMount } if sum, err := provider.TreeSHA256(fmt.Sprintf("/proc/self/fd/%d/.", mounted.Fd())); err != nil || sum != pin { return nil, errMount } } if l.Policy.IsOpenCode() && target == provider.OpenCodeBinary { // The binary as mounted, hashed through the descriptor // bubblewrap mounts: one replaced after the attestation is // refused here. source, pin, ok := l.Policy.OpenCodeBinaryPin() mounted := p.files[len(p.files)-1] if !ok || source != mount.Source { return nil, errMount } // The pinned descriptor is a path one: read the same file // through it, not by its path again. f, err := os.Open(fmt.Sprintf("/proc/self/fd/%d", mounted.Fd())) if err != nil { return nil, errMount } // Held to its seal as well as its bytes: owner, one name, no // write permission, safe ancestors (security round finding 2). sum, err := provider.SealedBinarySHA256(f, source) f.Close() if err != nil || sum != pin { return nil, errMount } } targets[target] = true } if l.ToolSocket != "" { if err = p.bindTool(l.ToolSocket); err != nil { return nil, err } } p.args = append(p.args, "--clearenv", "--setenv", "PATH", "/usr/bin:/bin:/opt", "--setenv", "HOME", "/home/runner", "--setenv", "TMPDIR", "/tmp", "--setenv", "LANG", "C.UTF-8") allowed := map[string]bool{"GIT_CONFIG_GLOBAL": l.Policy.Env["GIT_CONFIG_GLOBAL"] == "/dev/null", "GIT_CONFIG_NOSYSTEM": l.Policy.Env["GIT_CONFIG_NOSYSTEM"] == "1", "LANG": true, "LC_ALL": true, "TERM": true, "CODEX_HOME": true, "CLAUDE_CONFIG_DIR": true, "CLAUDE_SECURESTORAGE_CONFIG_DIR": true, "CLAUDE_TMPDIR": true, "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC": true, "DISABLE_AUTOUPDATER": true} if signIn { // The sign-in's browser opens nothing. if l.Policy.Env["BROWSER"] != provider.SignInBrowser { return nil, errMount } allowed["BROWSER"] = true } if l.Policy.IsPi() { // Pi's config directory in the runtime home, its startup fetches // off, and the extension's gate (provider.BuildPiPolicy). for k, v := range map[string]string{"PI_CODING_AGENT_DIR": provider.PiAgentDir, "PI_OFFLINE": "1", "PI_SKIP_VERSION_CHECK": "1", "PI_TELEMETRY": "0"} { if l.Policy.Env[k] != v { return nil, errMount } allowed[k] = true } for _, name := range []string{"settings.json", "models.json", "mcp.json"} { if err = p.bind(filepath.Join(runtimeHome, "agent", name), "/home/runner/agent/"+name, true, false); err != nil { return nil, err } } allowed["EQUIPO_PI_TOOLS"] = true allowed["EQUIPO_PI_CONFINE"] = l.Policy.Env["EQUIPO_PI_CONFINE"] == "/workspace" allowed["NODE_EXTRA_CA_CERTS"] = provider.TestCAAllowed() } if l.Policy.IsOpenCode() { // OpenCode's configuration, data and state in the runtime home, // and its switches: no project configuration, no Claude Code // compatibility, no catalogue fetch, no update check, no free // models, no file watcher (provider.BuildOpenCodePolicy). for k, v := range provider.OpenCodeEnvSwitches() { if l.Policy.Env[k] != v { return nil, errMount } allowed[k] = true } allowed["NODE_EXTRA_CA_CERTS"] = provider.TestCAAllowed() } if l.Policy.IsCheck() || l.Policy.GoToolchain() { for k, v := range gotoolchain.Environment(l.Selection.Provider) { if l.Policy.Env[k] != v { return nil, errMount } allowed[k] = true } } keys := make([]string, 0, len(l.Policy.Env)) for k := range l.Policy.Env { keys = append(keys, k) } sort.Strings(keys) for _, k := range keys { v := l.Policy.Env[k] if !allowed[k] || strings.ContainsRune(v, 0) { return nil, errMount } if (k == "CODEX_HOME" || k == "CLAUDE_CONFIG_DIR" || k == "CLAUDE_SECURESTORAGE_CONFIG_DIR") && (!cleanAbsolute(v) || !within(v, "/home/runner")) { return nil, errMount } if k == "CLAUDE_TMPDIR" && (!cleanAbsolute(v) || !within(v, "/tmp")) { return nil, errMount } p.args = append(p.args, "--setenv", k, v) } if l.Policy.IsOpenCode() { p.args = append(p.args, "--remount-ro", "/etc/opencode") } p.args = append(p.args, "--remount-ro", "/etc/claude-code", "--remount-ro", "/etc/codex", "--remount-ro", "/etc", "--chdir", "/workspace") return p, nil } // hostCABundle is the host's CA bundle, the one file of the host /etc a // Research step sees. A variable so a test can point it at a symlink. var hostCABundle = "/etc/ssl/certs/ca-certificates.crt" // researchEtc fills a Research step's tmpfs /etc: the host CA bundle, // resolved on the host and pinned as the regular file it names, and // passwd and group stubs written into the attempt directory. All three // are read-only; the masked provider directories follow as for every // launch. func (p *mounts) researchEtc(dir string) error { ca, err := filepath.EvalSymlinks(hostCABundle) if err != nil { return fmt.Errorf("%w: CA bundle: %v", errMount, err) } if err = p.bindOwn(ca, "/etc/ssl/certs/ca-certificates.crt"); err != nil { return err } stubs := filepath.Join(dir, "etc") if err = os.Mkdir(stubs, 0700); err != nil { return err } uid, gid := os.Getuid(), os.Getgid() for name, body := range map[string]string{ "passwd": fmt.Sprintf("runner:x:%d:%d:runner:/home/runner:/usr/sbin/nologin\nnobody:x:65534:65534:nobody:/nonexistent:/usr/sbin/nologin\n", uid, gid), "group": fmt.Sprintf("runner:x:%d:\nnogroup:x:65534:\n", gid), } { path := filepath.Join(stubs, name) f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL|unix.O_NOFOLLOW, 0644) if err != nil { return err } _, err = f.WriteString(body) if cerr := f.Close(); err == nil { err = cerr } if err != nil { return err } if err = p.bindOwn(path, "/etc/"+name); err != nil { return err } } return nil } // bindOwn binds a regular file containment supplies itself, read-only. func (p *mounts) bindOwn(source, target string) error { if err := p.bind(source, target, true, false); err != nil { return err } if p.own == nil { p.own = map[*os.File]bool{} } p.own[p.files[len(p.files)-1]] = true return nil } // bindEmpty binds a Research step's scratch workspace read-write after // checking, through the pinned descriptor, that it is empty. func (p *mounts) bindEmpty(path string) error { f, err := pin(path) if err != nil { return err } entries, err := os.ReadDir(fmt.Sprintf("/proc/self/fd/%d", f.Fd())) if err != nil || len(entries) != 0 { f.Close() return fmt.Errorf("%w: research workspace is not an empty directory", errMount) } return p.bindPinned(f, path, "/workspace", false, true) } // bindResearch binds a task's kept research images read-only at // /research. The directory must be the runner's own, 0700, apart from // every other mount source, and hold nothing but regular files with one // link each (no subdirectory, symlink, device, socket, fifo or hard // link to a file elsewhere). It is checked and bound through one pinned // descriptor, so a path swapped after the checks is not what is bound. func (p *mounts) bindResearch(path string, near []string) error { return p.bindKept(path, near, "/research", "research") } // bindKept binds a runner-made flat directory of regular files // read-only at target, as bindResearch describes; what names it in a // refusal. func (p *mounts) bindKept(path string, near []string, target, what string) error { if !cleanAbsolute(path) { return errMount } for _, other := range near { if other != "" && overlaps(path, other) { return fmt.Errorf("%w: %s directory overlaps another mount", errMount, what) } } for _, root := range []string{"/proc", "/sys", "/run", "/dev", "/etc", "/usr"} { if overlaps(path, root) { return fmt.Errorf("%w: %s directory overlaps another mount", errMount, what) } } f, err := pin(path) if err != nil { return err } fd := int(f.Fd()) var st unix.Stat_t if err = unix.Fstat(fd, &st); err != nil || st.Mode&unix.S_IFMT != unix.S_IFDIR { f.Close() return fmt.Errorf("%w: %s directory is not a directory", errMount, what) } if st.Uid != uint32(os.Getuid()) { f.Close() return fmt.Errorf("%w: %s directory owner is not the runner", errMount, what) } if st.Mode&0o7777 != 0o700 { f.Close() return fmt.Errorf("%w: %s directory mode is not 0700", errMount, what) } entries, err := os.ReadDir(fmt.Sprintf("/proc/self/fd/%d", fd)) if err != nil { f.Close() return fmt.Errorf("%w: %s directory: %v", errMount, what, err) } for _, e := range entries { var est unix.Stat_t if unix.Fstatat(fd, e.Name(), &est, unix.AT_SYMLINK_NOFOLLOW) != nil || est.Mode&unix.S_IFMT != unix.S_IFREG || est.Nlink != 1 || est.Uid != uint32(os.Getuid()) { f.Close() return fmt.Errorf("%w: %s directory entry %q is not a single regular file", errMount, what, e.Name()) } } return p.bindPinned(f, path, target, true, true) }