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 render
4
5import (
6 "bufio"
7 "bytes"
8 "context"
9 "encoding/json"
10 "errors"
11 "fmt"
12 "os"
13 "os/exec"
14 "path/filepath"
15 "regexp"
16 "runtime"
17 "strconv"
18 "strings"
19 "syscall"
20 "time"
21
22 "golang.org/x/sys/unix"
23)
24
25// Descriptors bubblewrap receives beyond the three the sandbox keeps
26// (fdBrowserIn, fdBrowserOut, fdStatus): each bind's is bound by
27// --ro-bind-fd or --bind-fd and closed by bubblewrap once bound, and the
28// info pipe is bubblewrap's own, so the sandbox's first process never
29// holds one.
30const (
31 fdUsr = 6
32 fdFonts = 7
33 fdBinary = 8
34 fdSite = 9
35 // fdInfo is bubblewrap's --info-fd: it writes the sandbox's first
36 // process's PID (the PID namespace's init) there.
37 fdInfo = 10
38)
39
40// bwrapArgs is the sandbox's launch policy (task 1's spike, which ran the
41// browser with its own sandbox on): every namespace unshared, so loopback
42// is the only interface; the verified tree read only as /usr, with the
43// loader paths as links into it, and its fontconfig at /etc/fonts; the
44// runner's binary read only; the site read only; a tmpfs /tmp of at most
45// TmpSize, a fresh /proc and bubblewrap's minimal /dev; the root itself
46// read only. Nothing the sandbox writes outlives it: captures come over
47// the browser's pipe and the runner writes them. No home, environment,
48// credentials or runner state.
49func bwrapArgs(argv ...string) []string {
50 fd := strconv.Itoa
51 return append([]string{
52 "--unshare-all", "--unshare-user",
53 "--die-with-parent", "--new-session", "--clearenv", "--cap-drop", "ALL",
54 "--info-fd", fd(fdInfo),
55 "--ro-bind-fd", fd(fdUsr), "/usr",
56 "--symlink", "usr/lib", "/lib",
57 "--symlink", "usr/lib64", "/lib64",
58 "--symlink", "usr/bin", "/bin",
59 "--ro-bind-fd", fd(fdFonts), "/etc/fonts",
60 "--ro-bind-fd", fd(fdBinary), binaryPath,
61 "--ro-bind-fd", fd(fdSite), SiteDir,
62 "--size", strconv.Itoa(TmpSize), "--tmpfs", "/tmp",
63 "--proc", "/proc",
64 "--dev", "/dev",
65 "--remount-ro", "/",
66 "--chdir", "/",
67 "--", binaryPath,
68 }, argv...)
69}
70
71// Launch verifies the renderer tree against the pin, starts the sandbox
72// and waits until render-sandbox reports the site served and the browser
73// started. ctx bounds the sandbox's whole life: when it ends, everything
74// in the sandbox is killed. A tree that does not verify is a
75// *release.RendererError and nothing starts.
76func Launch(ctx context.Context, cfg LaunchConfig) (*Sandbox, error) {
77 s, err := start(ctx, cfg, Subcommand)
78 if err != nil {
79 return nil, err
80 }
81 if s.state == initGone {
82 // The init ended before it could be held: whatever it said, the
83 // sandbox is over.
84 s.Close()
85 return nil, fmt.Errorf("render: the sandbox ended before it was ready: %s", bytes.TrimSpace(s.stderr.Bytes()))
86 }
87 timer := time.NewTimer(startTimeout(cfg))
88 defer timer.Stop()
89 select {
90 case st := <-s.ready:
91 if st.Event == "ready" && ctx.Err() == nil {
92 s.Site = st.Site
93 return s, nil
94 }
95 err = fmt.Errorf("render: the sandbox failed (%s)", st.Reason)
96 if ctx.Err() != nil {
97 err = ctx.Err()
98 }
99 case <-s.done:
100 select {
101 case st := <-s.ready:
102 err = fmt.Errorf("render: the sandbox ended (%s %s)", st.Event, st.Reason)
103 default:
104 err = errors.New("render: the sandbox ended before it was ready")
105 }
106 case <-timer.C:
107 err = errors.New("render: the sandbox was not ready in time")
108 case <-ctx.Done():
109 err = ctx.Err()
110 }
111 if e := s.Close(); e != nil {
112 err = fmt.Errorf("%w: %w", err, e)
113 }
114 if s.err != nil {
115 err = fmt.Errorf("%w: %v", err, s.err)
116 }
117 return nil, fmt.Errorf("%w: %s", err, bytes.TrimSpace(s.stderr.Bytes()))
118}
119
120func startTimeout(cfg LaunchConfig) time.Duration {
121 if cfg.StartTimeout > 0 {
122 return cfg.StartTimeout
123 }
124 return StartTimeout
125}
126
127// siteURL is the only address render-sandbox may report.
128var siteURL = regexp.MustCompile(`^http://127\.0\.0\.1:[1-9][0-9]{0,4}/$`)
129
130// testBeforeFork, when set, runs just before the launcher forks (a test
131// opens an inheritable descriptor there).
132var testBeforeFork func()
133
134// endBound is how long the sandbox may take to end once its init is
135// killed before Wait and Close report it did not.
136const endBound = 10 * time.Second
137
138// infoGrace is how long, once ctx is done, the launcher still waits for
139// bubblewrap's info: with it the init can be held, killed and shown to
140// have ended; without it the end cannot be shown.
141const infoGrace = 200 * time.Millisecond
142
143// Seams for tests: how a pidfd is opened, a process's parent read and a
144// moment before the init is identified.
145var (
146 pidfdOpen = unix.PidfdOpen
147 readParent = parentOf
148 testBeforeIdentity func(monitor int)
149)
150
151// start starts the sandbox with argv as its first process (a test runs a
152// probe in render-sandbox's place) and returns once it holds a pidfd on
153// the sandbox's PID namespace init, or knows that init has ended. When
154// it can do neither it kills bubblewrap and fails with ErrNotEnded.
155//
156// The runner starts its own binary (the descriptor pinned for /runner)
157// as render-exec, which closes every descriptor it inherited beyond the
158// launch's and executes bubblewrap.
159func start(ctx context.Context, cfg LaunchConfig, argv ...string) (*Sandbox, error) {
160 if err := ctx.Err(); err != nil {
161 return nil, err
162 }
163 for _, p := range []string{cfg.Bwrap, cfg.Binary, cfg.Tree, cfg.Site} {
164 if !filepath.IsAbs(p) || filepath.Clean(p) != p {
165 return nil, fmt.Errorf("render: launch path %q", p)
166 }
167 }
168 usr, fonts, err := verifiedTree(cfg.Tree, cfg.Pin)
169 if err != nil {
170 return nil, err
171 }
172 files := []*os.File{usr, fonts}
173 closeAll := func() {
174 for _, f := range files {
175 f.Close()
176 }
177 files = nil
178 }
179 defer closeAll()
180 var ours []*os.File
181 fail := func(err error) (*Sandbox, error) {
182 for _, f := range ours {
183 f.Close()
184 }
185 return nil, err
186 }
187 pipe := func() (r, w *os.File, err error) {
188 if r, w, err = os.Pipe(); err == nil {
189 ours = append(ours, r, w)
190 }
191 return
192 }
193 browserIn, toBrowser, err := pipe()
194 if err != nil {
195 return fail(err)
196 }
197 fromBrowser, browserOut, err := pipe()
198 if err != nil {
199 return fail(err)
200 }
201 statusRead, statusWrite, err := pipe()
202 if err != nil {
203 return fail(err)
204 }
205 infoRead, infoWrite, err := pipe()
206 if err != nil {
207 return fail(err)
208 }
209 binary, err := pinFile(cfg.Binary)
210 if err != nil {
211 return fail(err)
212 }
213 files = append(files, binary)
214 site, err := pinSite(cfg.Site)
215 if err != nil {
216 return fail(err)
217 }
218 files = append(files, site)
219
220 s := &Sandbox{ToBrowser: toBrowser, FromBrowser: fromBrowser, done: make(chan struct{}), ready: make(chan status, 1), stderr: &bounded{max: 8192}, pidfd: -1}
221 s.stop = s.kill
222 // ExtraFiles start at 3, in the order the policy numbers them.
223 cmd := exec.Command(fmt.Sprintf("/proc/self/fd/%d", fdBinary), append([]string{ExecSubcommand, cfg.Bwrap}, argv...)...)
224 cmd.Args[0] = binaryPath
225 cmd.Env = []string{}
226 cmd.Dir = "/"
227 cmd.ExtraFiles = []*os.File{browserIn, browserOut, statusWrite, usr, fonts, binary, site, infoWrite}
228 cmd.Stdout = s.stderr
229 cmd.Stderr = s.stderr
230 cmd.WaitDelay = 5 * time.Second
231 cmd.SysProcAttr = &syscall.SysProcAttr{Pdeathsig: syscall.SIGKILL}
232 s.cmd = cmd
233 statusDone := make(chan struct{})
234 started := make(chan error, 1)
235 watched := make(chan struct{})
236 go func() {
237 // Pdeathsig follows the thread that forked: keep it until the
238 // wait ends.
239 runtime.LockOSThread()
240 defer runtime.UnlockOSThread()
241 if testBeforeFork != nil {
242 testBeforeFork()
243 }
244 // A request already cancelled starts nothing.
245 if err := ctx.Err(); err != nil {
246 started <- err
247 return
248 }
249 if err := cmd.Start(); err != nil {
250 started <- err
251 return
252 }
253 started <- nil
254 // Reap bubblewrap only once start holds the init's pidfd (or
255 // knows the init ended): until then its PID stays bubblewrap's
256 // child, not a number someone else may be given.
257 <-watched
258 err := cmd.Wait()
259 ended := s.awaitEnd()
260 select {
261 case <-statusDone:
262 case <-time.After(5 * time.Second):
263 }
264 statusRead.Close()
265 if cfg.Stderr != nil {
266 cfg.Stderr.Write(s.stderr.Bytes())
267 }
268 s.mu.Lock()
269 s.err, s.ended = err, ended
270 s.mu.Unlock()
271 close(s.done)
272 }()
273 if err = <-started; err != nil {
274 return fail(fmt.Errorf("render: start bubblewrap: %w", err))
275 }
276 // The child's ends belong to the child now.
277 closeAll()
278 for _, f := range []*os.File{browserIn, browserOut, statusWrite, infoWrite} {
279 f.Close()
280 }
281 go s.readStatus(statusRead, statusDone)
282 monitor := cmd.Process.Pid
283 pid, infoErr := readInfo(ctx, infoRead, startTimeout(cfg))
284 killed := false
285 if infoErr != nil {
286 // No PID in time, or cancelled: kill bubblewrap, then take what
287 // it wrote before it died.
288 cmd.Process.Kill()
289 killed = true
290 infoRead.SetReadDeadline(time.Now().Add(time.Second))
291 if p, err := readMore(infoRead); err == nil {
292 pid = p
293 }
294 }
295 infoRead.Close()
296 if testBeforeIdentity != nil {
297 testBeforeIdentity(monitor)
298 }
299 fd, state := identify(pid, monitor)
300 s.mu.Lock()
301 s.pidfd, s.state = fd, state
302 s.mu.Unlock()
303 // bubblewrap may be reaped now.
304 close(watched)
305 if state == initUnknown {
306 // Without a held init nothing proves the sandbox ended: kill what
307 // can be killed, wait for bubblewrap, and fail closed.
308 if !killed {
309 cmd.Process.Kill()
310 }
311 <-s.done
312 toBrowser.Close()
313 fromBrowser.Close()
314 why := errors.New("render: the sandbox's init could not be identified")
315 if infoErr != nil {
316 why = fmt.Errorf("%w: %w", why, infoErr)
317 }
318 return nil, errors.Join(why, ctxErr(ctx), ErrNotEnded)
319 }
320 // From here a cancelled ctx kills the held init (or bubblewrap, for
321 // an init already gone).
322 unwatch := context.AfterFunc(ctx, s.kill)
323 go func() {
324 <-s.done
325 unwatch()
326 }()
327 if infoErr != nil {
328 // Cancelled or out of time, but the init is held: Close kills it
329 // and shows it ended.
330 s.Close()
331 return nil, errors.Join(fmt.Errorf("render: %w", infoErr), s.ended)
332 }
333 return s, nil
334}
335
336func ctxErr(ctx context.Context) error { return ctx.Err() }
337
338// readInfo reads bubblewrap's --info-fd JSON for the init's PID: at most
339// 4 KiB, within wait, and once ctx is done, within infoGrace more.
340func readInfo(ctx context.Context, info *os.File, wait time.Duration) (int, error) {
341 info.SetReadDeadline(time.Now().Add(wait))
342 stop := context.AfterFunc(ctx, func() { info.SetReadDeadline(time.Now().Add(infoGrace)) })
343 defer stop()
344 pid, err := readMore(info)
345 if err != nil && ctx.Err() != nil {
346 return 0, ctx.Err()
347 }
348 return pid, err
349}
350
351// readMore reads info until it holds a complete JSON object with a
352// child-pid above 1, the pipe ends or its deadline passes.
353func readMore(info *os.File) (int, error) {
354 var buf []byte
355 chunk := make([]byte, 512)
356 for len(buf) < 4096 {
357 n, err := info.Read(chunk)
358 buf = append(buf, chunk[:n]...)
359 var msg struct {
360 ChildPID int `json:"child-pid"`
361 }
362 if json.Unmarshal(buf, &msg) == nil && msg.ChildPID > 1 {
363 return msg.ChildPID, nil
364 }
365 if err != nil {
366 return 0, err
367 }
368 }
369 return 0, errors.New("render: bubblewrap's info is too long")
370}
371
372// identify turns the PID bubblewrap reported for the init into a pidfd
373// known to be the init, or shows the init has ended, or neither.
374//
375// bubblewrap's monitor (monitor) is this process's child and not yet
376// reaped, and it forks the init and nothing else, so a process whose
377// parent is the monitor is the init. If the process at pid, read after
378// the pidfd was opened, has the monitor as parent, it is the init and
379// the pidfd is the init's: the init held pid from before the open, so
380// the pidfd cannot be some later holder's. No process at pid at all
381// (ESRCH, ENOENT) means the init has ended, and the kernel completes an
382// init's exit only after killing and reaping its whole namespace.
383// Anything else (no pidfd, the parent unreadable, another parent, as
384// after the monitor exits and the init is moved to another parent) is
385// unknown.
386func identify(pid, monitor int) (int, initState) {
387 if pid <= 1 {
388 return -1, initUnknown
389 }
390 fd, err := pidfdOpen(pid, 0)
391 if errors.Is(err, unix.ESRCH) {
392 return -1, initGone
393 }
394 if err != nil {
395 return -1, initUnknown
396 }
397 ppid, err := readParent(pid)
398 if err == nil && ppid == monitor {
399 return fd, initHeld
400 }
401 unix.Close(fd)
402 if errors.Is(err, os.ErrNotExist) || errors.Is(err, unix.ESRCH) {
403 return -1, initGone
404 }
405 return -1, initUnknown
406}
407
408// parentOf is pid's parent, from /proc.
409func parentOf(pid int) (int, error) {
410 raw, err := os.ReadFile(fmt.Sprintf("/proc/%d/status", pid))
411 if err != nil {
412 return 0, err
413 }
414 for _, line := range strings.Split(string(raw), "\n") {
415 if v, ok := strings.CutPrefix(line, "PPid:"); ok {
416 return strconv.Atoi(strings.TrimSpace(v))
417 }
418 }
419 return 0, errors.New("render: no parent in /proc status")
420}
421
422// kill kills the sandbox: its PID namespace's init (the kernel then kills
423// every other process in the namespace) and bubblewrap.
424func (s *Sandbox) kill() {
425 s.mu.Lock()
426 if s.pidfd >= 0 {
427 unix.PidfdSendSignal(s.pidfd, unix.SIGKILL, nil, 0)
428 }
429 s.mu.Unlock()
430 s.cmd.Process.Kill()
431}
432
433// awaitEnd waits, once bubblewrap has been reaped, for the namespace's
434// init to have exited. The init's exit completes only after the kernel
435// has killed and reaped every other process in its PID namespace, so
436// once its pidfd is readable nothing of the sandbox runs. Past endBound
437// it is killed again and given one more endBound; then it is reported.
438func (s *Sandbox) awaitEnd() error {
439 s.mu.Lock()
440 fd, state := s.pidfd, s.state
441 s.mu.Unlock()
442 switch {
443 case state == initGone:
444 return nil
445 case state != initHeld || fd < 0:
446 return ErrNotEnded
447 }
448 defer func() {
449 s.mu.Lock()
450 unix.Close(s.pidfd)
451 s.pidfd = -1
452 s.mu.Unlock()
453 }()
454 for try := 0; try < 2; try++ {
455 if pidfdReadable(fd, endBound) {
456 return nil
457 }
458 unix.PidfdSendSignal(fd, unix.SIGKILL, nil, 0)
459 }
460 return ErrNotEnded
461}
462
463// pidfdReadable waits up to d for a pidfd's process to exit.
464func pidfdReadable(fd int, d time.Duration) bool {
465 deadline := time.Now().Add(d)
466 for {
467 left := time.Until(deadline)
468 if left < 0 {
469 left = 0
470 }
471 n, err := unix.Poll([]unix.PollFd{{Fd: int32(fd), Events: unix.POLLIN}}, int(left/time.Millisecond)+1)
472 if err == nil && n > 0 {
473 return true
474 }
475 if err != nil && !errors.Is(err, unix.EINTR) || time.Now().After(deadline) {
476 return false
477 }
478 }
479}
480
481// readStatus reads render-sandbox's status lines: at most 8, each at most
482// 1 KiB of JSON. The first ready or failed goes to s.ready; an exit is
483// how the browser ended. Anything else ends the reading.
484func (s *Sandbox) readStatus(r *os.File, done chan<- struct{}) {
485 defer close(done)
486 scan := bufio.NewScanner(r)
487 scan.Buffer(make([]byte, 1024), 1024)
488 first := true
489 for n := 0; n < 8 && scan.Scan(); n++ {
490 var st status
491 if json.Unmarshal(scan.Bytes(), &st) != nil {
492 return
493 }
494 switch {
495 case first && st.Event == "ready" && siteURL.MatchString(st.Site),
496 first && st.Event == "failed":
497 first = false
498 s.ready <- st
499 case !first && st.Event == "exit":
500 s.mu.Lock()
501 s.exit = BrowserExit{Known: true, Code: st.Code, Signal: st.Signal}
502 s.mu.Unlock()
503 default:
504 return
505 }
506 }
507}
508
509// pinDir opens dir with no symlink anywhere in its path and checks it is
510// a directory this user owns that nobody else can write.
511func pinDir(dir string) (*os.File, unix.Stat_t, error) {
512 var st unix.Stat_t
513 fd, err := unix.Openat2(unix.AT_FDCWD, dir, &unix.OpenHow{Flags: unix.O_PATH | unix.O_DIRECTORY | unix.O_CLOEXEC, Resolve: unix.RESOLVE_NO_SYMLINKS | unix.RESOLVE_NO_MAGICLINKS})
514 if err != nil {
515 return nil, st, fmt.Errorf("render: %s: %w", dir, err)
516 }
517 f := os.NewFile(uintptr(fd), dir)
518 if err = unix.Fstat(fd, &st); err != nil || st.Mode&unix.S_IFMT != unix.S_IFDIR || st.Mode&0o022 != 0 || st.Uid != uint32(os.Geteuid()) {
519 f.Close()
520 return nil, st, fmt.Errorf("render: %s is not a directory only this user can write", dir)
521 }
522 return f, st, nil
523}
524
525// pinSite is the site's directory, as pinDir.
526func pinSite(dir string) (*os.File, error) {
527 f, _, err := pinDir(dir)
528 return f, err
529}
530
531// pinOutDir is Render's output directory, on the runner's side: as
532// pinDir, and also private (0700) and empty.
533func pinOutDir(dir string) (*os.File, error) {
534 f, st, err := pinDir(dir)
535 if err != nil {
536 return nil, err
537 }
538 if st.Mode&0o777 != 0o700 {
539 f.Close()
540 return nil, fmt.Errorf("render: output directory %s is not private", dir)
541 }
542 list, err := unix.Openat(int(f.Fd()), ".", unix.O_RDONLY|unix.O_DIRECTORY|unix.O_CLOEXEC, 0)
543 if err != nil {
544 f.Close()
545 return nil, err
546 }
547 d := os.NewFile(uintptr(list), dir)
548 names, _ := d.Readdirnames(1)
549 d.Close()
550 if len(names) != 0 {
551 f.Close()
552 return nil, fmt.Errorf("render: output directory %s is not empty", dir)
553 }
554 return f, nil
555}
556
557// pinFile resolves path's symlinks on the host, then opens the regular
558// file they name with no symlink followed.
559func pinFile(path string) (*os.File, error) {
560 real, err := filepath.EvalSymlinks(path)
561 if err != nil {
562 return nil, fmt.Errorf("render: %w", err)
563 }
564 fd, err := unix.Openat2(unix.AT_FDCWD, real, &unix.OpenHow{Flags: unix.O_PATH | unix.O_CLOEXEC, Resolve: unix.RESOLVE_NO_SYMLINKS | unix.RESOLVE_NO_MAGICLINKS})
565 if err != nil {
566 return nil, fmt.Errorf("render: %s: %w", path, err)
567 }
568 f := os.NewFile(uintptr(fd), real)
569 var st unix.Stat_t
570 if err = unix.Fstat(fd, &st); err != nil || st.Mode&unix.S_IFMT != unix.S_IFREG {
571 f.Close()
572 return nil, fmt.Errorf("render: %s is not a regular file", path)
573 }
574 return f, nil
575}
576