//go:build linux package render import ( "bufio" "context" "encoding/json" "errors" "fmt" "io" "io/fs" "net" "net/http" "os" "os/exec" "os/signal" "path/filepath" "runtime" "strconv" "strings" "syscall" "time" "golang.org/x/sys/unix" ) func helperMain(args []string) (int, bool) { // A bubblewrap that never writes its info: it says it started (its // PID, in "started" beside it) and sleeps, holding every descriptor. if len(args) > 0 && filepath.Base(args[0]) == "fake-bwrap-stall" { os.WriteFile(filepath.Join(filepath.Dir(args[0]), "started"), []byte(strconv.Itoa(os.Getpid())), 0o600) for { time.Sleep(time.Hour) } } if len(args) > 1 && filepath.Base(args[0]) == filepath.Base(BrowserPath) && args[1] == "--writer" { return writerMain(), true } if len(args) > 0 && filepath.Base(args[0]) == filepath.Base(BrowserPath) { return fakeBrowserMain(args[1:]), true } if len(args) > 1 { switch args[1] { case ExecSubcommand: return ExecMain(args[2:]), true case Subcommand: return SandboxMain(args[2:], os.Stderr), true case "render-fds": return fdsMain(args[2:]), true case "render-probe": return probeMain(args[2:]), true } } return 0, false } // openFDs lists this process's open descriptors. func openFDs() []int { fds, err := openDescriptors() if err != nil { return []int{-1} } return fds } type redirectResult struct { // Location is where the in-sandbox server's redirect pointed, as the // client saw it; Status a response, if one ever came. Location string Status int Err string // Blocked is a follow that failed to resolve or connect. Blocked bool } type probeReport struct { FDs []int Env []string Interfaces []string // Loopback is the error dialing a listener inside the sandbox: "" // when it connects, so the failures below are the sandbox's. Loopback string // Dials is each target's dial error, "" for one that connected. Dials map[string]string // Lookup is the error resolving a public name. Lookup string // Writes is each write's error, "" for one that worked. Writes map[string]string Paths []string Redirects map[string]redirectResult // Fill is how much "fill-tmp" wrote to /tmp before a write failed, // and that failure. Fill *fillResult } type fillResult struct { Bytes int64 Err string } // fillTmp writes to /tmp in 1 MiB pieces until a write fails, at most // twice TmpSize. func fillTmp() *fillResult { f, err := os.Create("/tmp/fill") if err != nil { return &fillResult{Err: err.Error()} } defer f.Close() chunk := make([]byte, 1<<20) r := &fillResult{} for r.Bytes < 2*TmpSize { n, err := f.Write(chunk) r.Bytes += int64(n) if err != nil { r.Err = err.Error() break } } return r } // probeMain runs as the sandbox's first process in render-sandbox's // place and sends what it sees and reaches, as one NUL-ended JSON // message, on the browser's pipe (descriptor 4): nothing the sandbox // writes outlives it. Its arguments are "dial=", // "redirect=" and "fill-tmp". func probeMain(args []string) int { r := probeReport{FDs: openFDs(), Env: os.Environ(), Dials: map[string]string{}, Writes: map[string]string{}, Redirects: map[string]redirectResult{}} ifs, _ := net.Interfaces() for _, i := range ifs { r.Interfaces = append(r.Interfaces, i.Name) } filepath.WalkDir("/", func(p string, d fs.DirEntry, err error) error { if err != nil { return nil } if p == "/proc" || p == "/sys" || p == "/dev" || p == "/usr" { return fs.SkipDir } if r.Paths = append(r.Paths, p); len(r.Paths) > 10000 { return fs.SkipAll } return nil }) ln, err := net.Listen("tcp", "127.0.0.1:0") if err != nil { r.Loopback = err.Error() } else { defer ln.Close() go func() { for { c, err := ln.Accept() if err != nil { return } c.Close() } }() r.Loopback = dialErr(ln.Addr().String()) } var redirects []string fill := false for _, a := range args { switch { case a == "fill-tmp": fill = true case strings.HasPrefix(a, "dial="): r.Dials[a[5:]] = dialErr(a[5:]) case strings.HasPrefix(a, "redirect="): redirects = append(redirects, a[9:]) default: return 2 } } ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) _, err = net.DefaultResolver.LookupHost(ctx, "example.com") cancel() r.Lookup = errText(err) for _, target := range redirects { r.Redirects[target] = followRedirect(target) } write := func(name string, op func() error) { r.Writes[name] = errText(op()) } create := func(p string) func() error { return func() error { return os.WriteFile(p, []byte("x"), 0o644) } } for _, p := range []string{"/site/new", "/usr/new", "/etc/fonts/new", "/new", "/tmp/new"} { write("create "+p, create(p)) } write("mkdir /out", func() error { return os.Mkdir("/out", 0o700) }) write("open /site/index.html", func() error { f, err := os.OpenFile("/site/index.html", os.O_WRONLY, 0) if err == nil { f.Close() } return err }) // Opening the running binary to write is "text file busy" first. write("chmod "+binaryPath, func() error { return os.Chmod(binaryPath, 0o700) }) write("mkdir /site/d", func() error { return os.Mkdir("/site/d", 0o755) }) write("chmod /site/index.html", func() error { return os.Chmod("/site/index.html", 0o600) }) write("remove /site/index.html", func() error { return os.Remove("/site/index.html") }) if fill { r.Fill = fillTmp() } b, _ := json.Marshal(r) if _, err := os.NewFile(fdBrowserOut, "report").Write(append(b, 0)); err != nil { return 1 } return 0 } func dialErr(addr string) string { c, err := net.DialTimeout("tcp", addr, 2*time.Second) if err == nil { c.Close() } return errText(err) } func errText(err error) string { if err == nil { return "" } if s := err.Error(); s != "" { return s } return "error" } // followRedirect asks a server inside the sandbox for a page that // redirects to target, follows the redirect and reports what happened. func followRedirect(target string) redirectResult { ln, err := net.Listen("tcp", "127.0.0.1:0") if err != nil { return redirectResult{Err: err.Error()} } defer ln.Close() srv := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { http.Redirect(w, r, target, http.StatusFound) })} go srv.Serve(ln) defer srv.Close() var res redirectResult client := &http.Client{Timeout: 5 * time.Second, CheckRedirect: func(req *http.Request, via []*http.Request) error { res.Location = req.URL.String() return nil }} resp, err := client.Get("http://" + ln.Addr().String() + "/page") if resp != nil { res.Status = resp.StatusCode resp.Body.Close() } res.Err = errText(err) var dns *net.DNSError var op *net.OpError res.Blocked = err != nil && (errors.As(err, &dns) || errors.As(err, &op) && op.Op == "dial") return res } type browserReport struct { Args []string Env []string FDs []int Dir string } // fakeBrowserMain plays the browser: it answers NUL-ended messages on // its pipe (read on 3, written on 4): "report" replies with what it was // given (browserReport, as JSON), "get " fetches the URL and // replies with the status and body, "post " posts to it and // replies with the status, "hang" never returns, "spawn" starts a writer // that outlives the browser and replies "spawned", "exit " exits // with n, anything else is echoed. func fakeBrowserMain(args []string) int { r := browserReport{Args: args, Env: os.Environ(), FDs: openFDs()} r.Dir, _ = os.Getwd() report, _ := json.Marshal(r) in, out := os.NewFile(3, "in"), os.NewFile(4, "out") read := bufio.NewReader(in) for { msg, err := read.ReadString(0) if err != nil { return 0 } msg = strings.TrimSuffix(msg, "\x00") switch { case msg == "report": out.Write(append(report, 0)) case strings.HasPrefix(msg, "get "): reply := "error" if resp, err := http.Get(msg[4:]); err == nil { body, _ := io.ReadAll(io.LimitReader(resp.Body, 4096)) resp.Body.Close() reply = fmt.Sprintf("%d %s", resp.StatusCode, body) } else { reply = "error " + err.Error() } out.WriteString(reply + "\x00") case strings.HasPrefix(msg, "post "): reply := "error" if resp, err := http.Post(msg[5:], "text/plain", strings.NewReader("x")); err == nil { resp.Body.Close() reply = strconv.Itoa(resp.StatusCode) } out.WriteString(reply + "\x00") case msg == "spawn": // A process in its own session that keeps writing a tick // to the browser's pipe (its descriptor 3) until it is // killed. w := exec.Command(os.Args[0], "--writer") w.SysProcAttr = &syscall.SysProcAttr{Setsid: true} w.ExtraFiles = []*os.File{out} reply := "spawned" if err := w.Start(); err != nil { reply = "error " + err.Error() } out.WriteString(reply + "\x00") case msg == "hang": // A browser that never ends on its own, even when its pipe // closes: only a kill stops it. out.WriteString("hanging\x00") for { time.Sleep(time.Hour) } case strings.HasPrefix(msg, "exit "): n, _ := strconv.Atoi(msg[5:]) return n default: out.WriteString(msg + "\x00") } } } // writerMain is the spawned writer: its 0, 1 and 2 are /dev/null, its 3 // the browser's pipe, in its own session, deaf to the signals a session // ending sends, writing a tick to 3 every millisecond whatever the // write returns. func writerMain() int { signal.Ignore(syscall.SIGHUP, syscall.SIGTERM, syscall.SIGINT) // Many threads make its death take a while, so a Close that does not // wait for the sandbox to end returns while it still runs. for i := 0; i < 256; i++ { go func() { runtime.LockOSThread() for { time.Sleep(time.Hour) } }() } f := os.NewFile(3, "ticks") for { f.Write([]byte{'.'}) time.Sleep(time.Millisecond) } } type fdsReport struct { Err string FDs []int CloExec map[int]bool } // fdsMain runs sandboxDescriptors (or, with "each", closeEach(6), the // /proc fallback) on the descriptors it was started with and prints what // is left open and which are close-on-exec. func fdsMain(args []string) int { var err error if len(args) == 1 && args[0] == "each" { err = closeEach(fdStatus + 1) } else { err = sandboxDescriptors() } r := fdsReport{Err: errText(err), FDs: openFDs(), CloExec: map[int]bool{}} for _, fd := range r.FDs { flags, _ := unix.FcntlInt(uintptr(fd), unix.F_GETFD, 0) r.CloExec[fd] = flags&unix.FD_CLOEXEC != 0 } b, _ := json.Marshal(r) os.Stdout.Write(b) return 0 }