oficina / equipo Public

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

Plain git — no account needed to clone.

Download

Download this file

1//go:build linux
2
3package pause
4
5import (
6 "bytes"
7 "errors"
8 "fmt"
9 "io/fs"
10 "os"
11 "strconv"
12 "strings"
13 "sync"
14 "time"
15
16 "golang.org/x/sys/unix"
17)
18
19// maxMembers bounds the processes one pause holds (each holds a pidfd);
20// a sandbox with more is refused with ErrBusy.
21const maxMembers = 4096
22
23// rescanEvery paces the passes over /proc while the sandbox stops.
24const rescanEvery = time.Millisecond
25
26// Seams for the tests: the watchdog's timer, and a hook called at fixed
27// points of a pass ("scanned": /proc was listed; "retry": a member read
28// running and is about to be sent SIGSTOP again). Both are nil-safe and
29// unset in production.
30var (
31 afterFunc = time.AfterFunc
32 testHook func(point string, pid int)
33 // testUnreadable makes pid's pid namespace unreadable, as another
34 // user's or a non-dumpable process's is (tests only).
35 testUnreadable func(pid int) bool
36)
37
38func hook(point string, pid int) {
39 if testHook != nil {
40 testHook(point, pid)
41 }
42}
43
44// Hold stops every process of the sandbox whose first process is p, calls
45// fn while all of them are stopped, and resumes them on every way out:
46// fn's return, its panic, or the bound passing. bound covers both the
47// stopping and fn. When the bound passes first, the sandbox is resumed at
48// once (fn may still be running); whenever the deadline has passed by the
49// time fn returns, Hold returns ErrBusy, however the watchdog was
50// scheduled. fn gets the deadline so it can give up early.
51//
52// Members are found by pid namespace, not by parent pid: every process
53// whose pid namespace is p's (the sandbox's, pinned open for the pause) or
54// one nested below it, found by walking NS_GET_PARENT up from its own.
55// Each is opened as a pidfd, checked against the start time the scan
56// saw, and signalled through that pidfd only, so SIGSTOP and SIGCONT
57// reach that exact process or none. Every pass first checks that every
58// retained member reads stopped (each thread T or t, or dead) or has
59// exited, and only then lists /proc afresh; the pause is settled when a
60// pass finds both. A process forked before its parent stopped exists by
61// then, so that listing sees it. A /proc read that fails for any reason
62// but the process having gone refuses the pause (ErrBusy).
63//
64// Threat model. The pause is for consistency, not containment: whatever
65// the sandbox does, the copy made inside the pause opens every path with
66// openat2 below the workspace root, through no link, and reads within the
67// caps (thin's copyWorkSite), so neither an escape nor an oversized read
68// depends on the pause holding. What the pause gives is a copy no
69// cooperating process changes while it is made. A process inside the
70// sandbox can still defeat that on purpose (a timer that sends itself
71// SIGCONT, two processes that SIGCONT each other, asynchronous I/O
72// submitted before it stopped): slice 1 installs no seccomp policy against
73// those, because such a sandbox already decides what its work tree holds
74// and can commit anything else afterwards. As defence in depth the copy
75// re-reads, still inside the pause, the identity and times (device,
76// inode, size, mtime, ctime) of every file and directory it read and
77// refuses (busy) on any change.
78func Hold(p Process, bound time.Duration, fn func(deadline time.Time) error) error {
79 deadline := time.Now().Add(bound)
80 h := newHeld()
81 defer h.closeNamespaces()
82 // Every way out resumes, a panic in fn included: deferred calls run
83 // while a panic unwinds, before it goes on up.
84 defer h.resume()
85 watchdog := afterFunc(bound, func() { h.resume() })
86 defer watchdog.Stop()
87 if err := h.stop(p, deadline); err != nil {
88 return err
89 }
90 err := fn(deadline)
91 // The deadline is checked on the monotonic clock, not inferred from
92 // which resume ran first: a watchdog that has not run yet does not
93 // make an overdue copy a paused one.
94 expired := !time.Now().Before(deadline)
95 first := h.resume()
96 if expired || !first {
97 return busy("the work ran past the bound")
98 }
99 return err
100}
101
102// member is one process as the scan saw it: its pid and start time.
103type member struct {
104 pid int
105 start uint64
106}
107
108// nsEntry is a pid namespace already placed: inside the sandbox or not,
109// and the descriptor that keeps it (and so its inode number) alive for the
110// pause.
111type nsEntry struct {
112 inside bool
113 fd int
114}
115
116func newHeld() *held {
117 return &held{members: map[member]int{}, ns: map[uint64]nsEntry{}, sandboxFD: -1, uid: os.Getuid()}
118}
119
120type held struct {
121 // mu serialises every use of a member's pidfd (signals, exit polls)
122 // with resume, which closes them.
123 mu sync.Mutex
124 // members maps every process signalled SIGSTOP to its pidfd.
125 members map[member]int
126 resumed bool
127
128 // The sandbox's pid namespace, ours, and the depth (NSpid fields) of
129 // the sandbox's first process; ns caches each namespace seen.
130 sandbox, ours uint64
131 sandboxFD int
132 rootDepth int
133 uid int
134 ns map[uint64]nsEntry
135}
136
137// resume sends SIGCONT to every process stopped, through its pidfd, and
138// closes them. Only the first call does anything; it reports whether this
139// call was that one.
140func (h *held) resume() bool {
141 h.mu.Lock()
142 defer h.mu.Unlock()
143 if h.resumed {
144 return false
145 }
146 h.resumed = true
147 for _, fd := range h.members {
148 // ESRCH: it exited. Nothing else can fail for a process this
149 // pidfd already stopped.
150 unix.PidfdSendSignal(fd, unix.SIGCONT, nil, 0)
151 unix.Close(fd)
152 }
153 h.members = nil
154 return true
155}
156
157func (h *held) closeNamespaces() {
158 for _, e := range h.ns {
159 unix.Close(e.fd)
160 }
161 if h.sandboxFD >= 0 {
162 unix.Close(h.sandboxFD)
163 }
164}
165
166// stop signals SIGSTOP until the whole sandbox reads stopped.
167func (h *held) stop(p Process, deadline time.Time) error {
168 if err := h.stopRoot(p); err != nil {
169 return err
170 }
171 for {
172 if !time.Now().Before(deadline) {
173 return busy("not all stopped within the bound")
174 }
175 settled, err := h.pass()
176 if err != nil || settled {
177 return err
178 }
179 time.Sleep(rescanEvery)
180 }
181}
182
183// stopRoot pins p (pin) and stops it first.
184func (h *held) stopRoot(p Process) error {
185 fd, start, err := h.pin(p)
186 if err != nil {
187 return err
188 }
189 return h.signal(member{p.PID, start}, fd)
190}
191
192// pin checks that p is still the recorded process (its start time and
193// namespace, read after its pidfd is open, with the pidfd polled after so
194// the pid was not reused in between), keeps the sandbox's pid namespace
195// open for the pause, and returns p's pidfd.
196func (h *held) pin(p Process) (int, uint64, error) {
197 if p.PID <= 0 || p.StartTicks == 0 {
198 return -1, 0, ErrGone
199 }
200 fd, err := unix.PidfdOpen(p.PID, 0)
201 if err != nil {
202 return -1, 0, ErrGone
203 }
204 fail := func(e error) (int, uint64, error) { unix.Close(fd); return -1, 0, e }
205 _, _, start, err := readStat(fmt.Sprintf("/proc/%d/stat", p.PID))
206 if err != nil || start != p.StartTicks {
207 return fail(ErrGone)
208 }
209 nsFD, err := unix.Open(fmt.Sprintf("/proc/%d/ns/pid", p.PID), unix.O_RDONLY|unix.O_CLOEXEC, 0)
210 if err != nil {
211 return fail(ErrGone)
212 }
213 h.sandboxFD = nsFD
214 if h.sandbox, err = inode(nsFD); err != nil || p.Namespace != "" && p.Namespace != fmt.Sprintf("pid:[%d]", h.sandbox) {
215 return fail(ErrGone)
216 }
217 if h.rootDepth = nsDepth(p.PID); h.rootDepth < 2 || exited(fd) {
218 // Not in a pid namespace of its own, or exited (its pid may have
219 // been reused for what was read).
220 return fail(ErrGone)
221 }
222 self, err := unix.Open("/proc/self/ns/pid", unix.O_RDONLY|unix.O_CLOEXEC, 0)
223 if err != nil {
224 return fail(busy("our pid namespace: %v", err))
225 }
226 h.ours, err = inode(self)
227 unix.Close(self)
228 if err != nil || h.ours == h.sandbox {
229 return fail(busy("the sandbox shares our pid namespace"))
230 }
231 return fd, start, nil
232}
233
234// signal keeps fd as m's pidfd and sends it SIGSTOP; it refuses once the
235// sandbox has been resumed, so the watchdog's resume is never undone.
236func (h *held) signal(m member, fd int) error {
237 h.mu.Lock()
238 defer h.mu.Unlock()
239 if h.resumed {
240 unix.Close(fd)
241 return busy("resumed")
242 }
243 if len(h.members) >= maxMembers {
244 unix.Close(fd)
245 return busy("more than %d processes", maxMembers)
246 }
247 // Kept before the signal, so resume covers it whatever happens next.
248 h.members[m] = fd
249 if err := unix.PidfdSendSignal(fd, unix.SIGSTOP, nil, 0); err != nil && err != unix.ESRCH {
250 return busy("SIGSTOP %d: %v", m.pid, err)
251 }
252 return nil
253}
254
255// retry sends SIGSTOP again to a member that read running. The pidfd is
256// looked up, and resumed checked, under the lock resume holds, so the
257// signal never lands after the sandbox's SIGCONT or on a closed (or
258// reused) descriptor.
259func (h *held) retry(m member) error {
260 h.mu.Lock()
261 defer h.mu.Unlock()
262 if h.resumed {
263 return busy("resumed")
264 }
265 fd, ok := h.members[m]
266 if !ok {
267 return busy("member %d not held", m.pid)
268 }
269 if err := unix.PidfdSendSignal(fd, unix.SIGSTOP, nil, 0); err != nil && err != unix.ESRCH {
270 return busy("SIGSTOP %d again: %v", m.pid, err)
271 }
272 return nil
273}
274
275// pass checks every retained member, then lists /proc afresh and stops
276// every new member. It is settled when every retained member read stopped
277// (or exited) and the listing, made after, found no new one.
278func (h *held) pass() (bool, error) {
279 settled := true
280 h.mu.Lock()
281 if h.resumed {
282 h.mu.Unlock()
283 return false, busy("resumed")
284 }
285 retained := make([]member, 0, len(h.members))
286 for m := range h.members {
287 retained = append(retained, m)
288 }
289 h.mu.Unlock()
290 known := map[int]uint64{}
291 for _, m := range retained {
292 known[m.pid] = m.start
293 stopped, err := h.memberStopped(m)
294 if err != nil {
295 return false, err
296 }
297 if !stopped {
298 settled = false
299 hook("retry", m.pid)
300 if err := h.retry(m); err != nil {
301 return false, err
302 }
303 }
304 }
305
306 d, err := os.Open("/proc")
307 if err != nil {
308 return false, busy("open /proc: %v", err)
309 }
310 names, err := d.Readdirnames(-1)
311 d.Close()
312 if err != nil {
313 return false, busy("list /proc: %v", err)
314 }
315 hook("scanned", 0)
316 for _, name := range names {
317 pid, err := strconv.Atoi(name)
318 if err != nil || pid <= 0 {
319 continue
320 }
321 inside, err := h.inSandbox(pid)
322 if errors.Is(err, errVanished) {
323 continue
324 }
325 if err != nil {
326 return false, err
327 }
328 if !inside {
329 continue
330 }
331 _, _, start, err := readStat("/proc/" + name + "/stat")
332 if gone(err) {
333 continue
334 }
335 if err != nil {
336 return false, busy("stat %d: %v", pid, err)
337 }
338 if s, ok := known[pid]; ok && s == start {
339 continue
340 }
341 fd, err := unix.PidfdOpen(pid, 0)
342 if err == unix.ESRCH {
343 continue // exited and reaped since the listing: runs nothing
344 }
345 if err != nil {
346 return false, busy("pidfd %d: %v", pid, err)
347 }
348 if exited(fd) {
349 // A zombie (its parent, stopped, cannot reap it): runs nothing.
350 unix.Close(fd)
351 continue
352 }
353 // The pid may have been reused between the reads and the open:
354 // the pidfd names whatever holds it now. Read again through it,
355 // and look again on the next pass if anything moved.
356 settled = false
357 if _, _, s, err := readStat("/proc/" + name + "/stat"); err != nil || s != start {
358 unix.Close(fd)
359 continue
360 }
361 if inside, err := h.inSandbox(pid); err != nil || !inside || exited(fd) {
362 unix.Close(fd)
363 continue
364 }
365 if err := h.signal(member{pid, start}, fd); err != nil {
366 return false, err
367 }
368 }
369 return settled, nil
370}
371
372// memberStopped: every thread of m reads stopped or dead, or m has exited.
373// It holds the lock for its pidfd's poll; anything unreadable for another
374// reason than the process going refuses the pause.
375func (h *held) memberStopped(m member) (bool, error) {
376 h.mu.Lock()
377 defer h.mu.Unlock()
378 if h.resumed {
379 return false, busy("resumed")
380 }
381 fd, ok := h.members[m]
382 if !ok {
383 return false, busy("member %d not held", m.pid)
384 }
385 if exited(fd) {
386 return true, nil
387 }
388 dir := fmt.Sprintf("/proc/%d/task", m.pid)
389 tasks, err := os.ReadDir(dir)
390 if err != nil {
391 if gone(err) && exited(fd) {
392 return true, nil
393 }
394 return false, busy("threads of %d: %v", m.pid, err)
395 }
396 for _, task := range tasks {
397 state, _, start, err := readStat(dir + "/" + task.Name() + "/stat")
398 if gone(err) {
399 continue // that thread exited
400 }
401 if err != nil {
402 return false, busy("thread %s of %d: %v", task.Name(), m.pid, err)
403 }
404 if task.Name() == strconv.Itoa(m.pid) && start != m.start {
405 // The pid now names another process: m has exited (its pidfd
406 // says so; otherwise refuse).
407 if exited(fd) {
408 return true, nil
409 }
410 return false, busy("pid %d is another process", m.pid)
411 }
412 switch state {
413 case 'T', 't', 'Z', 'X':
414 default:
415 return false, nil
416 }
417 }
418 return true, nil
419}
420
421var errVanished = errors.New("process vanished")
422
423// busy is ErrBusy with what refused the pause, for the log: callers
424// test errors.Is(err, ErrBusy).
425func busy(format string, args ...any) error {
426 return fmt.Errorf("%w: "+format, append([]any{ErrBusy}, args...)...)
427}
428
429// statusName is the Name: line of a /proc status file.
430func statusName(status []byte) string {
431 for _, line := range strings.Split(string(status), "\n") {
432 if rest, ok := strings.CutPrefix(line, "Name:"); ok {
433 return strings.TrimSpace(rest)
434 }
435 }
436 return ""
437}
438
439// gone: a /proc read failed because the process (or thread) is gone.
440func gone(err error) bool {
441 return errors.Is(err, fs.ErrNotExist) || errors.Is(err, unix.ESRCH)
442}
443
444// inSandbox places pid's pid namespace: the sandbox's, one nested below it
445// (by NS_GET_PARENT up to the sandbox's), or neither. A process whose
446// namespace cannot be read (another user's, or one of ours that is not
447// dumpable) is outside when it is not ours (members all run as this user)
448// or sits shallower than the sandbox (NSpid); otherwise the pause is
449// refused. errVanished: the process went while it was read.
450func (h *held) inSandbox(pid int) (bool, error) {
451 path := fmt.Sprintf("/proc/%d/ns/pid", pid)
452 if testUnreadable != nil && testUnreadable(pid) {
453 return h.unreadable(pid)
454 }
455 link, err := os.Readlink(path)
456 if gone(err) {
457 return false, errVanished
458 }
459 if err != nil {
460 return h.unreadable(pid)
461 }
462 var ino uint64
463 if _, err := fmt.Sscanf(link, "pid:[%d]", &ino); err != nil {
464 return false, busy("pid namespace link of %d: %q", pid, link)
465 }
466 switch ino {
467 case h.sandbox:
468 return true, nil
469 case h.ours:
470 return false, nil
471 }
472 // A cached inode is pinned open, so no other namespace has it.
473 if e, ok := h.ns[ino]; ok {
474 return e.inside, nil
475 }
476 fd, err := unix.Open(path, unix.O_RDONLY|unix.O_CLOEXEC, 0)
477 if gone(err) {
478 return false, errVanished
479 }
480 if err != nil {
481 return h.unreadable(pid)
482 }
483 if got, err := inode(fd); err != nil || got != ino {
484 unix.Close(fd)
485 return false, errVanished
486 }
487 inside, err := h.below(fd)
488 if err != nil {
489 unix.Close(fd)
490 return false, err
491 }
492 h.ns[ino] = nsEntry{inside: inside, fd: fd}
493 return inside, nil
494}
495
496// below walks NS_GET_PARENT up from the namespace fd until it reaches the
497// sandbox's (inside), ours or one already placed, or cannot go further
498// (EPERM: above ours; outside).
499func (h *held) below(fd int) (bool, error) {
500 cur := fd
501 defer func() {
502 if cur != fd {
503 unix.Close(cur)
504 }
505 }()
506 for range 64 {
507 parent, err := unix.IoctlRetInt(cur, unix.NS_GET_PARENT)
508 if err == unix.EPERM {
509 return false, nil
510 }
511 if err != nil {
512 return false, busy("NS_GET_PARENT: %v", err)
513 }
514 if cur != fd {
515 unix.Close(cur)
516 }
517 cur = parent
518 ino, err := inode(cur)
519 if err != nil {
520 return false, busy("a parent pid namespace: %v", err)
521 }
522 switch ino {
523 case h.sandbox:
524 return true, nil
525 case h.ours:
526 return false, nil
527 }
528 if e, ok := h.ns[ino]; ok {
529 return e.inside, nil
530 }
531 }
532 return false, busy("namespaces nested too deep")
533}
534
535// unreadable places a process whose namespace cannot be read.
536func (h *held) unreadable(pid int) (bool, error) {
537 raw, err := os.ReadFile(fmt.Sprintf("/proc/%d/status", pid))
538 if gone(err) {
539 return false, errVanished
540 }
541 if err != nil {
542 return false, busy("status of %d: %v", pid, err)
543 }
544 for _, line := range strings.Split(string(raw), "\n") {
545 if rest, ok := strings.CutPrefix(line, "Uid:"); ok {
546 for _, f := range strings.Fields(rest) {
547 if f != strconv.Itoa(h.uid) {
548 return false, nil
549 }
550 }
551 }
552 }
553 if depth := depthOf(raw); depth > 0 && depth < h.rootDepth {
554 return false, nil
555 }
556 return false, busy("%d (%s, depth %d) is ours but its pid namespace is unreadable", pid, statusName(raw), depthOf(raw))
557}
558
559func inode(fd int) (uint64, error) {
560 var st unix.Stat_t
561 if err := unix.Fstat(fd, &st); err != nil {
562 return 0, err
563 }
564 return st.Ino, nil
565}
566
567// exited reports whether the process behind pidfd fd has exited (a pidfd
568// polls readable then).
569func exited(fd int) bool {
570 polls := []unix.PollFd{{Fd: int32(fd), Events: unix.POLLIN}}
571 n, err := unix.Poll(polls, 0)
572 return err == nil && n > 0 && polls[0].Revents&unix.POLLIN != 0
573}
574
575// nsDepth is how many pid namespaces pid sits in, from ours down (the
576// fields of NSpid in /proc/<pid>/status); 0 when it cannot be read.
577func nsDepth(pid int) int {
578 raw, err := os.ReadFile(fmt.Sprintf("/proc/%d/status", pid))
579 if err != nil {
580 return 0
581 }
582 return depthOf(raw)
583}
584
585func depthOf(status []byte) int {
586 for _, line := range strings.Split(string(status), "\n") {
587 if rest, ok := strings.CutPrefix(line, "NSpid:"); ok {
588 return len(strings.Fields(rest))
589 }
590 }
591 return 0
592}
593
594var errStat = errors.New("unreadable stat")
595
596// readStat reads a /proc stat file: the state (field 3), the parent pid
597// (field 4) and the start time in clock ticks (field 22). The command name
598// (field 2) may hold anything, so fields are counted after its last ')'.
599func readStat(path string) (state byte, ppid int, start uint64, err error) {
600 raw, err := os.ReadFile(path)
601 if err != nil {
602 return 0, 0, 0, err
603 }
604 end := bytes.LastIndexByte(raw, ')')
605 if end < 0 {
606 return 0, 0, 0, errStat
607 }
608 f := strings.Fields(string(raw[end+1:]))
609 if len(f) < 20 || len(f[0]) != 1 {
610 return 0, 0, 0, errStat
611 }
612 if ppid, err = strconv.Atoi(f[1]); err != nil {
613 return 0, 0, 0, errStat
614 }
615 if start, err = strconv.ParseUint(f[19], 10, 64); err != nil {
616 return 0, 0, 0, errStat
617 }
618 return f[0][0], ppid, start, nil
619}
620