//go:build linux package render import ( "bufio" "bytes" "context" "encoding/json" "errors" "fmt" "os" "os/exec" "path/filepath" "regexp" "runtime" "strconv" "strings" "syscall" "time" "golang.org/x/sys/unix" ) // Descriptors bubblewrap receives beyond the three the sandbox keeps // (fdBrowserIn, fdBrowserOut, fdStatus): each bind's is bound by // --ro-bind-fd or --bind-fd and closed by bubblewrap once bound, and the // info pipe is bubblewrap's own, so the sandbox's first process never // holds one. const ( fdUsr = 6 fdFonts = 7 fdBinary = 8 fdSite = 9 // fdInfo is bubblewrap's --info-fd: it writes the sandbox's first // process's PID (the PID namespace's init) there. fdInfo = 10 ) // bwrapArgs is the sandbox's launch policy (task 1's spike, which ran the // browser with its own sandbox on): every namespace unshared, so loopback // is the only interface; the verified tree read only as /usr, with the // loader paths as links into it, and its fontconfig at /etc/fonts; the // runner's binary read only; the site read only; a tmpfs /tmp of at most // TmpSize, a fresh /proc and bubblewrap's minimal /dev; the root itself // read only. Nothing the sandbox writes outlives it: captures come over // the browser's pipe and the runner writes them. No home, environment, // credentials or runner state. func bwrapArgs(argv ...string) []string { fd := strconv.Itoa return append([]string{ "--unshare-all", "--unshare-user", "--die-with-parent", "--new-session", "--clearenv", "--cap-drop", "ALL", "--info-fd", fd(fdInfo), "--ro-bind-fd", fd(fdUsr), "/usr", "--symlink", "usr/lib", "/lib", "--symlink", "usr/lib64", "/lib64", "--symlink", "usr/bin", "/bin", "--ro-bind-fd", fd(fdFonts), "/etc/fonts", "--ro-bind-fd", fd(fdBinary), binaryPath, "--ro-bind-fd", fd(fdSite), SiteDir, "--size", strconv.Itoa(TmpSize), "--tmpfs", "/tmp", "--proc", "/proc", "--dev", "/dev", "--remount-ro", "/", "--chdir", "/", "--", binaryPath, }, argv...) } // Launch verifies the renderer tree against the pin, starts the sandbox // and waits until render-sandbox reports the site served and the browser // started. ctx bounds the sandbox's whole life: when it ends, everything // in the sandbox is killed. A tree that does not verify is a // *release.RendererError and nothing starts. func Launch(ctx context.Context, cfg LaunchConfig) (*Sandbox, error) { s, err := start(ctx, cfg, Subcommand) if err != nil { return nil, err } if s.state == initGone { // The init ended before it could be held: whatever it said, the // sandbox is over. s.Close() return nil, fmt.Errorf("render: the sandbox ended before it was ready: %s", bytes.TrimSpace(s.stderr.Bytes())) } timer := time.NewTimer(startTimeout(cfg)) defer timer.Stop() select { case st := <-s.ready: if st.Event == "ready" && ctx.Err() == nil { s.Site = st.Site return s, nil } err = fmt.Errorf("render: the sandbox failed (%s)", st.Reason) if ctx.Err() != nil { err = ctx.Err() } case <-s.done: select { case st := <-s.ready: err = fmt.Errorf("render: the sandbox ended (%s %s)", st.Event, st.Reason) default: err = errors.New("render: the sandbox ended before it was ready") } case <-timer.C: err = errors.New("render: the sandbox was not ready in time") case <-ctx.Done(): err = ctx.Err() } if e := s.Close(); e != nil { err = fmt.Errorf("%w: %w", err, e) } if s.err != nil { err = fmt.Errorf("%w: %v", err, s.err) } return nil, fmt.Errorf("%w: %s", err, bytes.TrimSpace(s.stderr.Bytes())) } func startTimeout(cfg LaunchConfig) time.Duration { if cfg.StartTimeout > 0 { return cfg.StartTimeout } return StartTimeout } // siteURL is the only address render-sandbox may report. var siteURL = regexp.MustCompile(`^http://127\.0\.0\.1:[1-9][0-9]{0,4}/$`) // testBeforeFork, when set, runs just before the launcher forks (a test // opens an inheritable descriptor there). var testBeforeFork func() // endBound is how long the sandbox may take to end once its init is // killed before Wait and Close report it did not. const endBound = 10 * time.Second // infoGrace is how long, once ctx is done, the launcher still waits for // bubblewrap's info: with it the init can be held, killed and shown to // have ended; without it the end cannot be shown. const infoGrace = 200 * time.Millisecond // Seams for tests: how a pidfd is opened, a process's parent read and a // moment before the init is identified. var ( pidfdOpen = unix.PidfdOpen readParent = parentOf testBeforeIdentity func(monitor int) ) // start starts the sandbox with argv as its first process (a test runs a // probe in render-sandbox's place) and returns once it holds a pidfd on // the sandbox's PID namespace init, or knows that init has ended. When // it can do neither it kills bubblewrap and fails with ErrNotEnded. // // The runner starts its own binary (the descriptor pinned for /runner) // as render-exec, which closes every descriptor it inherited beyond the // launch's and executes bubblewrap. func start(ctx context.Context, cfg LaunchConfig, argv ...string) (*Sandbox, error) { if err := ctx.Err(); err != nil { return nil, err } for _, p := range []string{cfg.Bwrap, cfg.Binary, cfg.Tree, cfg.Site} { if !filepath.IsAbs(p) || filepath.Clean(p) != p { return nil, fmt.Errorf("render: launch path %q", p) } } usr, fonts, err := verifiedTree(cfg.Tree, cfg.Pin) if err != nil { return nil, err } files := []*os.File{usr, fonts} closeAll := func() { for _, f := range files { f.Close() } files = nil } defer closeAll() var ours []*os.File fail := func(err error) (*Sandbox, error) { for _, f := range ours { f.Close() } return nil, err } pipe := func() (r, w *os.File, err error) { if r, w, err = os.Pipe(); err == nil { ours = append(ours, r, w) } return } browserIn, toBrowser, err := pipe() if err != nil { return fail(err) } fromBrowser, browserOut, err := pipe() if err != nil { return fail(err) } statusRead, statusWrite, err := pipe() if err != nil { return fail(err) } infoRead, infoWrite, err := pipe() if err != nil { return fail(err) } binary, err := pinFile(cfg.Binary) if err != nil { return fail(err) } files = append(files, binary) site, err := pinSite(cfg.Site) if err != nil { return fail(err) } files = append(files, site) s := &Sandbox{ToBrowser: toBrowser, FromBrowser: fromBrowser, done: make(chan struct{}), ready: make(chan status, 1), stderr: &bounded{max: 8192}, pidfd: -1} s.stop = s.kill // ExtraFiles start at 3, in the order the policy numbers them. cmd := exec.Command(fmt.Sprintf("/proc/self/fd/%d", fdBinary), append([]string{ExecSubcommand, cfg.Bwrap}, argv...)...) cmd.Args[0] = binaryPath cmd.Env = []string{} cmd.Dir = "/" cmd.ExtraFiles = []*os.File{browserIn, browserOut, statusWrite, usr, fonts, binary, site, infoWrite} cmd.Stdout = s.stderr cmd.Stderr = s.stderr cmd.WaitDelay = 5 * time.Second cmd.SysProcAttr = &syscall.SysProcAttr{Pdeathsig: syscall.SIGKILL} s.cmd = cmd statusDone := make(chan struct{}) started := make(chan error, 1) watched := make(chan struct{}) go func() { // Pdeathsig follows the thread that forked: keep it until the // wait ends. runtime.LockOSThread() defer runtime.UnlockOSThread() if testBeforeFork != nil { testBeforeFork() } // A request already cancelled starts nothing. if err := ctx.Err(); err != nil { started <- err return } if err := cmd.Start(); err != nil { started <- err return } started <- nil // Reap bubblewrap only once start holds the init's pidfd (or // knows the init ended): until then its PID stays bubblewrap's // child, not a number someone else may be given. <-watched err := cmd.Wait() ended := s.awaitEnd() select { case <-statusDone: case <-time.After(5 * time.Second): } statusRead.Close() if cfg.Stderr != nil { cfg.Stderr.Write(s.stderr.Bytes()) } s.mu.Lock() s.err, s.ended = err, ended s.mu.Unlock() close(s.done) }() if err = <-started; err != nil { return fail(fmt.Errorf("render: start bubblewrap: %w", err)) } // The child's ends belong to the child now. closeAll() for _, f := range []*os.File{browserIn, browserOut, statusWrite, infoWrite} { f.Close() } go s.readStatus(statusRead, statusDone) monitor := cmd.Process.Pid pid, infoErr := readInfo(ctx, infoRead, startTimeout(cfg)) killed := false if infoErr != nil { // No PID in time, or cancelled: kill bubblewrap, then take what // it wrote before it died. cmd.Process.Kill() killed = true infoRead.SetReadDeadline(time.Now().Add(time.Second)) if p, err := readMore(infoRead); err == nil { pid = p } } infoRead.Close() if testBeforeIdentity != nil { testBeforeIdentity(monitor) } fd, state := identify(pid, monitor) s.mu.Lock() s.pidfd, s.state = fd, state s.mu.Unlock() // bubblewrap may be reaped now. close(watched) if state == initUnknown { // Without a held init nothing proves the sandbox ended: kill what // can be killed, wait for bubblewrap, and fail closed. if !killed { cmd.Process.Kill() } <-s.done toBrowser.Close() fromBrowser.Close() why := errors.New("render: the sandbox's init could not be identified") if infoErr != nil { why = fmt.Errorf("%w: %w", why, infoErr) } return nil, errors.Join(why, ctxErr(ctx), ErrNotEnded) } // From here a cancelled ctx kills the held init (or bubblewrap, for // an init already gone). unwatch := context.AfterFunc(ctx, s.kill) go func() { <-s.done unwatch() }() if infoErr != nil { // Cancelled or out of time, but the init is held: Close kills it // and shows it ended. s.Close() return nil, errors.Join(fmt.Errorf("render: %w", infoErr), s.ended) } return s, nil } func ctxErr(ctx context.Context) error { return ctx.Err() } // readInfo reads bubblewrap's --info-fd JSON for the init's PID: at most // 4 KiB, within wait, and once ctx is done, within infoGrace more. func readInfo(ctx context.Context, info *os.File, wait time.Duration) (int, error) { info.SetReadDeadline(time.Now().Add(wait)) stop := context.AfterFunc(ctx, func() { info.SetReadDeadline(time.Now().Add(infoGrace)) }) defer stop() pid, err := readMore(info) if err != nil && ctx.Err() != nil { return 0, ctx.Err() } return pid, err } // readMore reads info until it holds a complete JSON object with a // child-pid above 1, the pipe ends or its deadline passes. func readMore(info *os.File) (int, error) { var buf []byte chunk := make([]byte, 512) for len(buf) < 4096 { n, err := info.Read(chunk) buf = append(buf, chunk[:n]...) var msg struct { ChildPID int `json:"child-pid"` } if json.Unmarshal(buf, &msg) == nil && msg.ChildPID > 1 { return msg.ChildPID, nil } if err != nil { return 0, err } } return 0, errors.New("render: bubblewrap's info is too long") } // identify turns the PID bubblewrap reported for the init into a pidfd // known to be the init, or shows the init has ended, or neither. // // bubblewrap's monitor (monitor) is this process's child and not yet // reaped, and it forks the init and nothing else, so a process whose // parent is the monitor is the init. If the process at pid, read after // the pidfd was opened, has the monitor as parent, it is the init and // the pidfd is the init's: the init held pid from before the open, so // the pidfd cannot be some later holder's. No process at pid at all // (ESRCH, ENOENT) means the init has ended, and the kernel completes an // init's exit only after killing and reaping its whole namespace. // Anything else (no pidfd, the parent unreadable, another parent, as // after the monitor exits and the init is moved to another parent) is // unknown. func identify(pid, monitor int) (int, initState) { if pid <= 1 { return -1, initUnknown } fd, err := pidfdOpen(pid, 0) if errors.Is(err, unix.ESRCH) { return -1, initGone } if err != nil { return -1, initUnknown } ppid, err := readParent(pid) if err == nil && ppid == monitor { return fd, initHeld } unix.Close(fd) if errors.Is(err, os.ErrNotExist) || errors.Is(err, unix.ESRCH) { return -1, initGone } return -1, initUnknown } // parentOf is pid's parent, from /proc. func parentOf(pid int) (int, error) { raw, err := os.ReadFile(fmt.Sprintf("/proc/%d/status", pid)) if err != nil { return 0, err } for _, line := range strings.Split(string(raw), "\n") { if v, ok := strings.CutPrefix(line, "PPid:"); ok { return strconv.Atoi(strings.TrimSpace(v)) } } return 0, errors.New("render: no parent in /proc status") } // kill kills the sandbox: its PID namespace's init (the kernel then kills // every other process in the namespace) and bubblewrap. func (s *Sandbox) kill() { s.mu.Lock() if s.pidfd >= 0 { unix.PidfdSendSignal(s.pidfd, unix.SIGKILL, nil, 0) } s.mu.Unlock() s.cmd.Process.Kill() } // awaitEnd waits, once bubblewrap has been reaped, for the namespace's // init to have exited. The init's exit completes only after the kernel // has killed and reaped every other process in its PID namespace, so // once its pidfd is readable nothing of the sandbox runs. Past endBound // it is killed again and given one more endBound; then it is reported. func (s *Sandbox) awaitEnd() error { s.mu.Lock() fd, state := s.pidfd, s.state s.mu.Unlock() switch { case state == initGone: return nil case state != initHeld || fd < 0: return ErrNotEnded } defer func() { s.mu.Lock() unix.Close(s.pidfd) s.pidfd = -1 s.mu.Unlock() }() for try := 0; try < 2; try++ { if pidfdReadable(fd, endBound) { return nil } unix.PidfdSendSignal(fd, unix.SIGKILL, nil, 0) } return ErrNotEnded } // pidfdReadable waits up to d for a pidfd's process to exit. func pidfdReadable(fd int, d time.Duration) bool { deadline := time.Now().Add(d) for { left := time.Until(deadline) if left < 0 { left = 0 } n, err := unix.Poll([]unix.PollFd{{Fd: int32(fd), Events: unix.POLLIN}}, int(left/time.Millisecond)+1) if err == nil && n > 0 { return true } if err != nil && !errors.Is(err, unix.EINTR) || time.Now().After(deadline) { return false } } } // readStatus reads render-sandbox's status lines: at most 8, each at most // 1 KiB of JSON. The first ready or failed goes to s.ready; an exit is // how the browser ended. Anything else ends the reading. func (s *Sandbox) readStatus(r *os.File, done chan<- struct{}) { defer close(done) scan := bufio.NewScanner(r) scan.Buffer(make([]byte, 1024), 1024) first := true for n := 0; n < 8 && scan.Scan(); n++ { var st status if json.Unmarshal(scan.Bytes(), &st) != nil { return } switch { case first && st.Event == "ready" && siteURL.MatchString(st.Site), first && st.Event == "failed": first = false s.ready <- st case !first && st.Event == "exit": s.mu.Lock() s.exit = BrowserExit{Known: true, Code: st.Code, Signal: st.Signal} s.mu.Unlock() default: return } } } // pinDir opens dir with no symlink anywhere in its path and checks it is // a directory this user owns that nobody else can write. func pinDir(dir string) (*os.File, unix.Stat_t, error) { var st unix.Stat_t 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}) if err != nil { return nil, st, fmt.Errorf("render: %s: %w", dir, err) } f := os.NewFile(uintptr(fd), dir) 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()) { f.Close() return nil, st, fmt.Errorf("render: %s is not a directory only this user can write", dir) } return f, st, nil } // pinSite is the site's directory, as pinDir. func pinSite(dir string) (*os.File, error) { f, _, err := pinDir(dir) return f, err } // pinOutDir is Render's output directory, on the runner's side: as // pinDir, and also private (0700) and empty. func pinOutDir(dir string) (*os.File, error) { f, st, err := pinDir(dir) if err != nil { return nil, err } if st.Mode&0o777 != 0o700 { f.Close() return nil, fmt.Errorf("render: output directory %s is not private", dir) } list, err := unix.Openat(int(f.Fd()), ".", unix.O_RDONLY|unix.O_DIRECTORY|unix.O_CLOEXEC, 0) if err != nil { f.Close() return nil, err } d := os.NewFile(uintptr(list), dir) names, _ := d.Readdirnames(1) d.Close() if len(names) != 0 { f.Close() return nil, fmt.Errorf("render: output directory %s is not empty", dir) } return f, nil } // pinFile resolves path's symlinks on the host, then opens the regular // file they name with no symlink followed. func pinFile(path string) (*os.File, error) { real, err := filepath.EvalSymlinks(path) if err != nil { return nil, fmt.Errorf("render: %w", err) } 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}) if err != nil { return nil, fmt.Errorf("render: %s: %w", path, err) } f := os.NewFile(uintptr(fd), real) var st unix.Stat_t if err = unix.Fstat(fd, &st); err != nil || st.Mode&unix.S_IFMT != unix.S_IFREG { f.Close() return nil, fmt.Errorf("render: %s is not a regular file", path) } return f, nil }