//go:build linux package pause import ( "bytes" "errors" "fmt" "io/fs" "os" "strconv" "strings" "sync" "time" "golang.org/x/sys/unix" ) // maxMembers bounds the processes one pause holds (each holds a pidfd); // a sandbox with more is refused with ErrBusy. const maxMembers = 4096 // rescanEvery paces the passes over /proc while the sandbox stops. const rescanEvery = time.Millisecond // Seams for the tests: the watchdog's timer, and a hook called at fixed // points of a pass ("scanned": /proc was listed; "retry": a member read // running and is about to be sent SIGSTOP again). Both are nil-safe and // unset in production. var ( afterFunc = time.AfterFunc testHook func(point string, pid int) // testUnreadable makes pid's pid namespace unreadable, as another // user's or a non-dumpable process's is (tests only). testUnreadable func(pid int) bool ) func hook(point string, pid int) { if testHook != nil { testHook(point, pid) } } // Hold stops every process of the sandbox whose first process is p, calls // fn while all of them are stopped, and resumes them on every way out: // fn's return, its panic, or the bound passing. bound covers both the // stopping and fn. When the bound passes first, the sandbox is resumed at // once (fn may still be running); whenever the deadline has passed by the // time fn returns, Hold returns ErrBusy, however the watchdog was // scheduled. fn gets the deadline so it can give up early. // // Members are found by pid namespace, not by parent pid: every process // whose pid namespace is p's (the sandbox's, pinned open for the pause) or // one nested below it, found by walking NS_GET_PARENT up from its own. // Each is opened as a pidfd, checked against the start time the scan // saw, and signalled through that pidfd only, so SIGSTOP and SIGCONT // reach that exact process or none. Every pass first checks that every // retained member reads stopped (each thread T or t, or dead) or has // exited, and only then lists /proc afresh; the pause is settled when a // pass finds both. A process forked before its parent stopped exists by // then, so that listing sees it. A /proc read that fails for any reason // but the process having gone refuses the pause (ErrBusy). // // Threat model. The pause is for consistency, not containment: whatever // the sandbox does, the copy made inside the pause opens every path with // openat2 below the workspace root, through no link, and reads within the // caps (thin's copyWorkSite), so neither an escape nor an oversized read // depends on the pause holding. What the pause gives is a copy no // cooperating process changes while it is made. A process inside the // sandbox can still defeat that on purpose (a timer that sends itself // SIGCONT, two processes that SIGCONT each other, asynchronous I/O // submitted before it stopped): slice 1 installs no seccomp policy against // those, because such a sandbox already decides what its work tree holds // and can commit anything else afterwards. As defence in depth the copy // re-reads, still inside the pause, the identity and times (device, // inode, size, mtime, ctime) of every file and directory it read and // refuses (busy) on any change. func Hold(p Process, bound time.Duration, fn func(deadline time.Time) error) error { deadline := time.Now().Add(bound) h := newHeld() defer h.closeNamespaces() // Every way out resumes, a panic in fn included: deferred calls run // while a panic unwinds, before it goes on up. defer h.resume() watchdog := afterFunc(bound, func() { h.resume() }) defer watchdog.Stop() if err := h.stop(p, deadline); err != nil { return err } err := fn(deadline) // The deadline is checked on the monotonic clock, not inferred from // which resume ran first: a watchdog that has not run yet does not // make an overdue copy a paused one. expired := !time.Now().Before(deadline) first := h.resume() if expired || !first { return busy("the work ran past the bound") } return err } // member is one process as the scan saw it: its pid and start time. type member struct { pid int start uint64 } // nsEntry is a pid namespace already placed: inside the sandbox or not, // and the descriptor that keeps it (and so its inode number) alive for the // pause. type nsEntry struct { inside bool fd int } func newHeld() *held { return &held{members: map[member]int{}, ns: map[uint64]nsEntry{}, sandboxFD: -1, uid: os.Getuid()} } type held struct { // mu serialises every use of a member's pidfd (signals, exit polls) // with resume, which closes them. mu sync.Mutex // members maps every process signalled SIGSTOP to its pidfd. members map[member]int resumed bool // The sandbox's pid namespace, ours, and the depth (NSpid fields) of // the sandbox's first process; ns caches each namespace seen. sandbox, ours uint64 sandboxFD int rootDepth int uid int ns map[uint64]nsEntry } // resume sends SIGCONT to every process stopped, through its pidfd, and // closes them. Only the first call does anything; it reports whether this // call was that one. func (h *held) resume() bool { h.mu.Lock() defer h.mu.Unlock() if h.resumed { return false } h.resumed = true for _, fd := range h.members { // ESRCH: it exited. Nothing else can fail for a process this // pidfd already stopped. unix.PidfdSendSignal(fd, unix.SIGCONT, nil, 0) unix.Close(fd) } h.members = nil return true } func (h *held) closeNamespaces() { for _, e := range h.ns { unix.Close(e.fd) } if h.sandboxFD >= 0 { unix.Close(h.sandboxFD) } } // stop signals SIGSTOP until the whole sandbox reads stopped. func (h *held) stop(p Process, deadline time.Time) error { if err := h.stopRoot(p); err != nil { return err } for { if !time.Now().Before(deadline) { return busy("not all stopped within the bound") } settled, err := h.pass() if err != nil || settled { return err } time.Sleep(rescanEvery) } } // stopRoot pins p (pin) and stops it first. func (h *held) stopRoot(p Process) error { fd, start, err := h.pin(p) if err != nil { return err } return h.signal(member{p.PID, start}, fd) } // pin checks that p is still the recorded process (its start time and // namespace, read after its pidfd is open, with the pidfd polled after so // the pid was not reused in between), keeps the sandbox's pid namespace // open for the pause, and returns p's pidfd. func (h *held) pin(p Process) (int, uint64, error) { if p.PID <= 0 || p.StartTicks == 0 { return -1, 0, ErrGone } fd, err := unix.PidfdOpen(p.PID, 0) if err != nil { return -1, 0, ErrGone } fail := func(e error) (int, uint64, error) { unix.Close(fd); return -1, 0, e } _, _, start, err := readStat(fmt.Sprintf("/proc/%d/stat", p.PID)) if err != nil || start != p.StartTicks { return fail(ErrGone) } nsFD, err := unix.Open(fmt.Sprintf("/proc/%d/ns/pid", p.PID), unix.O_RDONLY|unix.O_CLOEXEC, 0) if err != nil { return fail(ErrGone) } h.sandboxFD = nsFD if h.sandbox, err = inode(nsFD); err != nil || p.Namespace != "" && p.Namespace != fmt.Sprintf("pid:[%d]", h.sandbox) { return fail(ErrGone) } if h.rootDepth = nsDepth(p.PID); h.rootDepth < 2 || exited(fd) { // Not in a pid namespace of its own, or exited (its pid may have // been reused for what was read). return fail(ErrGone) } self, err := unix.Open("/proc/self/ns/pid", unix.O_RDONLY|unix.O_CLOEXEC, 0) if err != nil { return fail(busy("our pid namespace: %v", err)) } h.ours, err = inode(self) unix.Close(self) if err != nil || h.ours == h.sandbox { return fail(busy("the sandbox shares our pid namespace")) } return fd, start, nil } // signal keeps fd as m's pidfd and sends it SIGSTOP; it refuses once the // sandbox has been resumed, so the watchdog's resume is never undone. func (h *held) signal(m member, fd int) error { h.mu.Lock() defer h.mu.Unlock() if h.resumed { unix.Close(fd) return busy("resumed") } if len(h.members) >= maxMembers { unix.Close(fd) return busy("more than %d processes", maxMembers) } // Kept before the signal, so resume covers it whatever happens next. h.members[m] = fd if err := unix.PidfdSendSignal(fd, unix.SIGSTOP, nil, 0); err != nil && err != unix.ESRCH { return busy("SIGSTOP %d: %v", m.pid, err) } return nil } // retry sends SIGSTOP again to a member that read running. The pidfd is // looked up, and resumed checked, under the lock resume holds, so the // signal never lands after the sandbox's SIGCONT or on a closed (or // reused) descriptor. func (h *held) retry(m member) error { h.mu.Lock() defer h.mu.Unlock() if h.resumed { return busy("resumed") } fd, ok := h.members[m] if !ok { return busy("member %d not held", m.pid) } if err := unix.PidfdSendSignal(fd, unix.SIGSTOP, nil, 0); err != nil && err != unix.ESRCH { return busy("SIGSTOP %d again: %v", m.pid, err) } return nil } // pass checks every retained member, then lists /proc afresh and stops // every new member. It is settled when every retained member read stopped // (or exited) and the listing, made after, found no new one. func (h *held) pass() (bool, error) { settled := true h.mu.Lock() if h.resumed { h.mu.Unlock() return false, busy("resumed") } retained := make([]member, 0, len(h.members)) for m := range h.members { retained = append(retained, m) } h.mu.Unlock() known := map[int]uint64{} for _, m := range retained { known[m.pid] = m.start stopped, err := h.memberStopped(m) if err != nil { return false, err } if !stopped { settled = false hook("retry", m.pid) if err := h.retry(m); err != nil { return false, err } } } d, err := os.Open("/proc") if err != nil { return false, busy("open /proc: %v", err) } names, err := d.Readdirnames(-1) d.Close() if err != nil { return false, busy("list /proc: %v", err) } hook("scanned", 0) for _, name := range names { pid, err := strconv.Atoi(name) if err != nil || pid <= 0 { continue } inside, err := h.inSandbox(pid) if errors.Is(err, errVanished) { continue } if err != nil { return false, err } if !inside { continue } _, _, start, err := readStat("/proc/" + name + "/stat") if gone(err) { continue } if err != nil { return false, busy("stat %d: %v", pid, err) } if s, ok := known[pid]; ok && s == start { continue } fd, err := unix.PidfdOpen(pid, 0) if err == unix.ESRCH { continue // exited and reaped since the listing: runs nothing } if err != nil { return false, busy("pidfd %d: %v", pid, err) } if exited(fd) { // A zombie (its parent, stopped, cannot reap it): runs nothing. unix.Close(fd) continue } // The pid may have been reused between the reads and the open: // the pidfd names whatever holds it now. Read again through it, // and look again on the next pass if anything moved. settled = false if _, _, s, err := readStat("/proc/" + name + "/stat"); err != nil || s != start { unix.Close(fd) continue } if inside, err := h.inSandbox(pid); err != nil || !inside || exited(fd) { unix.Close(fd) continue } if err := h.signal(member{pid, start}, fd); err != nil { return false, err } } return settled, nil } // memberStopped: every thread of m reads stopped or dead, or m has exited. // It holds the lock for its pidfd's poll; anything unreadable for another // reason than the process going refuses the pause. func (h *held) memberStopped(m member) (bool, error) { h.mu.Lock() defer h.mu.Unlock() if h.resumed { return false, busy("resumed") } fd, ok := h.members[m] if !ok { return false, busy("member %d not held", m.pid) } if exited(fd) { return true, nil } dir := fmt.Sprintf("/proc/%d/task", m.pid) tasks, err := os.ReadDir(dir) if err != nil { if gone(err) && exited(fd) { return true, nil } return false, busy("threads of %d: %v", m.pid, err) } for _, task := range tasks { state, _, start, err := readStat(dir + "/" + task.Name() + "/stat") if gone(err) { continue // that thread exited } if err != nil { return false, busy("thread %s of %d: %v", task.Name(), m.pid, err) } if task.Name() == strconv.Itoa(m.pid) && start != m.start { // The pid now names another process: m has exited (its pidfd // says so; otherwise refuse). if exited(fd) { return true, nil } return false, busy("pid %d is another process", m.pid) } switch state { case 'T', 't', 'Z', 'X': default: return false, nil } } return true, nil } var errVanished = errors.New("process vanished") // busy is ErrBusy with what refused the pause, for the log: callers // test errors.Is(err, ErrBusy). func busy(format string, args ...any) error { return fmt.Errorf("%w: "+format, append([]any{ErrBusy}, args...)...) } // statusName is the Name: line of a /proc status file. func statusName(status []byte) string { for _, line := range strings.Split(string(status), "\n") { if rest, ok := strings.CutPrefix(line, "Name:"); ok { return strings.TrimSpace(rest) } } return "" } // gone: a /proc read failed because the process (or thread) is gone. func gone(err error) bool { return errors.Is(err, fs.ErrNotExist) || errors.Is(err, unix.ESRCH) } // inSandbox places pid's pid namespace: the sandbox's, one nested below it // (by NS_GET_PARENT up to the sandbox's), or neither. A process whose // namespace cannot be read (another user's, or one of ours that is not // dumpable) is outside when it is not ours (members all run as this user) // or sits shallower than the sandbox (NSpid); otherwise the pause is // refused. errVanished: the process went while it was read. func (h *held) inSandbox(pid int) (bool, error) { path := fmt.Sprintf("/proc/%d/ns/pid", pid) if testUnreadable != nil && testUnreadable(pid) { return h.unreadable(pid) } link, err := os.Readlink(path) if gone(err) { return false, errVanished } if err != nil { return h.unreadable(pid) } var ino uint64 if _, err := fmt.Sscanf(link, "pid:[%d]", &ino); err != nil { return false, busy("pid namespace link of %d: %q", pid, link) } switch ino { case h.sandbox: return true, nil case h.ours: return false, nil } // A cached inode is pinned open, so no other namespace has it. if e, ok := h.ns[ino]; ok { return e.inside, nil } fd, err := unix.Open(path, unix.O_RDONLY|unix.O_CLOEXEC, 0) if gone(err) { return false, errVanished } if err != nil { return h.unreadable(pid) } if got, err := inode(fd); err != nil || got != ino { unix.Close(fd) return false, errVanished } inside, err := h.below(fd) if err != nil { unix.Close(fd) return false, err } h.ns[ino] = nsEntry{inside: inside, fd: fd} return inside, nil } // below walks NS_GET_PARENT up from the namespace fd until it reaches the // sandbox's (inside), ours or one already placed, or cannot go further // (EPERM: above ours; outside). func (h *held) below(fd int) (bool, error) { cur := fd defer func() { if cur != fd { unix.Close(cur) } }() for range 64 { parent, err := unix.IoctlRetInt(cur, unix.NS_GET_PARENT) if err == unix.EPERM { return false, nil } if err != nil { return false, busy("NS_GET_PARENT: %v", err) } if cur != fd { unix.Close(cur) } cur = parent ino, err := inode(cur) if err != nil { return false, busy("a parent pid namespace: %v", err) } switch ino { case h.sandbox: return true, nil case h.ours: return false, nil } if e, ok := h.ns[ino]; ok { return e.inside, nil } } return false, busy("namespaces nested too deep") } // unreadable places a process whose namespace cannot be read. func (h *held) unreadable(pid int) (bool, error) { raw, err := os.ReadFile(fmt.Sprintf("/proc/%d/status", pid)) if gone(err) { return false, errVanished } if err != nil { return false, busy("status of %d: %v", pid, err) } for _, line := range strings.Split(string(raw), "\n") { if rest, ok := strings.CutPrefix(line, "Uid:"); ok { for _, f := range strings.Fields(rest) { if f != strconv.Itoa(h.uid) { return false, nil } } } } if depth := depthOf(raw); depth > 0 && depth < h.rootDepth { return false, nil } return false, busy("%d (%s, depth %d) is ours but its pid namespace is unreadable", pid, statusName(raw), depthOf(raw)) } func inode(fd int) (uint64, error) { var st unix.Stat_t if err := unix.Fstat(fd, &st); err != nil { return 0, err } return st.Ino, nil } // exited reports whether the process behind pidfd fd has exited (a pidfd // polls readable then). func exited(fd int) bool { polls := []unix.PollFd{{Fd: int32(fd), Events: unix.POLLIN}} n, err := unix.Poll(polls, 0) return err == nil && n > 0 && polls[0].Revents&unix.POLLIN != 0 } // nsDepth is how many pid namespaces pid sits in, from ours down (the // fields of NSpid in /proc//status); 0 when it cannot be read. func nsDepth(pid int) int { raw, err := os.ReadFile(fmt.Sprintf("/proc/%d/status", pid)) if err != nil { return 0 } return depthOf(raw) } func depthOf(status []byte) int { for _, line := range strings.Split(string(status), "\n") { if rest, ok := strings.CutPrefix(line, "NSpid:"); ok { return len(strings.Fields(rest)) } } return 0 } var errStat = errors.New("unreadable stat") // readStat reads a /proc stat file: the state (field 3), the parent pid // (field 4) and the start time in clock ticks (field 22). The command name // (field 2) may hold anything, so fields are counted after its last ')'. func readStat(path string) (state byte, ppid int, start uint64, err error) { raw, err := os.ReadFile(path) if err != nil { return 0, 0, 0, err } end := bytes.LastIndexByte(raw, ')') if end < 0 { return 0, 0, 0, errStat } f := strings.Fields(string(raw[end+1:])) if len(f) < 20 || len(f[0]) != 1 { return 0, 0, 0, errStat } if ppid, err = strconv.Atoi(f[1]); err != nil { return 0, 0, 0, errStat } if start, err = strconv.ParseUint(f[19], 10, 64); err != nil { return 0, 0, 0, errStat } return f[0][0], ppid, start, nil }