| 1 | //go:build linux |
| 2 | |
| 3 | package render |
| 4 | |
| 5 | import ( |
| 6 | "bufio" |
| 7 | "context" |
| 8 | "encoding/json" |
| 9 | "errors" |
| 10 | "fmt" |
| 11 | "io" |
| 12 | "io/fs" |
| 13 | "net" |
| 14 | "net/http" |
| 15 | "os" |
| 16 | "os/exec" |
| 17 | "os/signal" |
| 18 | "path/filepath" |
| 19 | "runtime" |
| 20 | "strconv" |
| 21 | "strings" |
| 22 | "syscall" |
| 23 | "time" |
| 24 | |
| 25 | "golang.org/x/sys/unix" |
| 26 | ) |
| 27 | |
| 28 | func helperMain(args []string) (int, bool) { |
| 29 | // A bubblewrap that never writes its info: it says it started (its |
| 30 | // PID, in "started" beside it) and sleeps, holding every descriptor. |
| 31 | if len(args) > 0 && filepath.Base(args[0]) == "fake-bwrap-stall" { |
| 32 | os.WriteFile(filepath.Join(filepath.Dir(args[0]), "started"), []byte(strconv.Itoa(os.Getpid())), 0o600) |
| 33 | for { |
| 34 | time.Sleep(time.Hour) |
| 35 | } |
| 36 | } |
| 37 | if len(args) > 1 && filepath.Base(args[0]) == filepath.Base(BrowserPath) && args[1] == "--writer" { |
| 38 | return writerMain(), true |
| 39 | } |
| 40 | if len(args) > 0 && filepath.Base(args[0]) == filepath.Base(BrowserPath) { |
| 41 | return fakeBrowserMain(args[1:]), true |
| 42 | } |
| 43 | if len(args) > 1 { |
| 44 | switch args[1] { |
| 45 | case ExecSubcommand: |
| 46 | return ExecMain(args[2:]), true |
| 47 | case Subcommand: |
| 48 | return SandboxMain(args[2:], os.Stderr), true |
| 49 | case "render-fds": |
| 50 | return fdsMain(args[2:]), true |
| 51 | case "render-probe": |
| 52 | return probeMain(args[2:]), true |
| 53 | } |
| 54 | } |
| 55 | return 0, false |
| 56 | } |
| 57 | |
| 58 | // openFDs lists this process's open descriptors. |
| 59 | func openFDs() []int { |
| 60 | fds, err := openDescriptors() |
| 61 | if err != nil { |
| 62 | return []int{-1} |
| 63 | } |
| 64 | return fds |
| 65 | } |
| 66 | |
| 67 | type redirectResult struct { |
| 68 | // Location is where the in-sandbox server's redirect pointed, as the |
| 69 | // client saw it; Status a response, if one ever came. |
| 70 | Location string |
| 71 | Status int |
| 72 | Err string |
| 73 | // Blocked is a follow that failed to resolve or connect. |
| 74 | Blocked bool |
| 75 | } |
| 76 | |
| 77 | type probeReport struct { |
| 78 | FDs []int |
| 79 | Env []string |
| 80 | Interfaces []string |
| 81 | // Loopback is the error dialing a listener inside the sandbox: "" |
| 82 | // when it connects, so the failures below are the sandbox's. |
| 83 | Loopback string |
| 84 | // Dials is each target's dial error, "" for one that connected. |
| 85 | Dials map[string]string |
| 86 | // Lookup is the error resolving a public name. |
| 87 | Lookup string |
| 88 | // Writes is each write's error, "" for one that worked. |
| 89 | Writes map[string]string |
| 90 | Paths []string |
| 91 | Redirects map[string]redirectResult |
| 92 | // Fill is how much "fill-tmp" wrote to /tmp before a write failed, |
| 93 | // and that failure. |
| 94 | Fill *fillResult |
| 95 | } |
| 96 | |
| 97 | type fillResult struct { |
| 98 | Bytes int64 |
| 99 | Err string |
| 100 | } |
| 101 | |
| 102 | // fillTmp writes to /tmp in 1 MiB pieces until a write fails, at most |
| 103 | // twice TmpSize. |
| 104 | func fillTmp() *fillResult { |
| 105 | f, err := os.Create("/tmp/fill") |
| 106 | if err != nil { |
| 107 | return &fillResult{Err: err.Error()} |
| 108 | } |
| 109 | defer f.Close() |
| 110 | chunk := make([]byte, 1<<20) |
| 111 | r := &fillResult{} |
| 112 | for r.Bytes < 2*TmpSize { |
| 113 | n, err := f.Write(chunk) |
| 114 | r.Bytes += int64(n) |
| 115 | if err != nil { |
| 116 | r.Err = err.Error() |
| 117 | break |
| 118 | } |
| 119 | } |
| 120 | return r |
| 121 | } |
| 122 | |
| 123 | // probeMain runs as the sandbox's first process in render-sandbox's |
| 124 | // place and sends what it sees and reaches, as one NUL-ended JSON |
| 125 | // message, on the browser's pipe (descriptor 4): nothing the sandbox |
| 126 | // writes outlives it. Its arguments are "dial=<host:port>", |
| 127 | // "redirect=<url>" and "fill-tmp". |
| 128 | func probeMain(args []string) int { |
| 129 | r := probeReport{FDs: openFDs(), Env: os.Environ(), Dials: map[string]string{}, Writes: map[string]string{}, Redirects: map[string]redirectResult{}} |
| 130 | ifs, _ := net.Interfaces() |
| 131 | for _, i := range ifs { |
| 132 | r.Interfaces = append(r.Interfaces, i.Name) |
| 133 | } |
| 134 | filepath.WalkDir("/", func(p string, d fs.DirEntry, err error) error { |
| 135 | if err != nil { |
| 136 | return nil |
| 137 | } |
| 138 | if p == "/proc" || p == "/sys" || p == "/dev" || p == "/usr" { |
| 139 | return fs.SkipDir |
| 140 | } |
| 141 | if r.Paths = append(r.Paths, p); len(r.Paths) > 10000 { |
| 142 | return fs.SkipAll |
| 143 | } |
| 144 | return nil |
| 145 | }) |
| 146 | ln, err := net.Listen("tcp", "127.0.0.1:0") |
| 147 | if err != nil { |
| 148 | r.Loopback = err.Error() |
| 149 | } else { |
| 150 | defer ln.Close() |
| 151 | go func() { |
| 152 | for { |
| 153 | c, err := ln.Accept() |
| 154 | if err != nil { |
| 155 | return |
| 156 | } |
| 157 | c.Close() |
| 158 | } |
| 159 | }() |
| 160 | r.Loopback = dialErr(ln.Addr().String()) |
| 161 | } |
| 162 | var redirects []string |
| 163 | fill := false |
| 164 | for _, a := range args { |
| 165 | switch { |
| 166 | case a == "fill-tmp": |
| 167 | fill = true |
| 168 | case strings.HasPrefix(a, "dial="): |
| 169 | r.Dials[a[5:]] = dialErr(a[5:]) |
| 170 | case strings.HasPrefix(a, "redirect="): |
| 171 | redirects = append(redirects, a[9:]) |
| 172 | default: |
| 173 | return 2 |
| 174 | } |
| 175 | } |
| 176 | ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) |
| 177 | _, err = net.DefaultResolver.LookupHost(ctx, "example.com") |
| 178 | cancel() |
| 179 | r.Lookup = errText(err) |
| 180 | for _, target := range redirects { |
| 181 | r.Redirects[target] = followRedirect(target) |
| 182 | } |
| 183 | write := func(name string, op func() error) { r.Writes[name] = errText(op()) } |
| 184 | create := func(p string) func() error { |
| 185 | return func() error { return os.WriteFile(p, []byte("x"), 0o644) } |
| 186 | } |
| 187 | for _, p := range []string{"/site/new", "/usr/new", "/etc/fonts/new", "/new", "/tmp/new"} { |
| 188 | write("create "+p, create(p)) |
| 189 | } |
| 190 | write("mkdir /out", func() error { return os.Mkdir("/out", 0o700) }) |
| 191 | write("open /site/index.html", func() error { |
| 192 | f, err := os.OpenFile("/site/index.html", os.O_WRONLY, 0) |
| 193 | if err == nil { |
| 194 | f.Close() |
| 195 | } |
| 196 | return err |
| 197 | }) |
| 198 | // Opening the running binary to write is "text file busy" first. |
| 199 | write("chmod "+binaryPath, func() error { return os.Chmod(binaryPath, 0o700) }) |
| 200 | write("mkdir /site/d", func() error { return os.Mkdir("/site/d", 0o755) }) |
| 201 | write("chmod /site/index.html", func() error { return os.Chmod("/site/index.html", 0o600) }) |
| 202 | write("remove /site/index.html", func() error { return os.Remove("/site/index.html") }) |
| 203 | if fill { |
| 204 | r.Fill = fillTmp() |
| 205 | } |
| 206 | b, _ := json.Marshal(r) |
| 207 | if _, err := os.NewFile(fdBrowserOut, "report").Write(append(b, 0)); err != nil { |
| 208 | return 1 |
| 209 | } |
| 210 | return 0 |
| 211 | } |
| 212 | |
| 213 | func dialErr(addr string) string { |
| 214 | c, err := net.DialTimeout("tcp", addr, 2*time.Second) |
| 215 | if err == nil { |
| 216 | c.Close() |
| 217 | } |
| 218 | return errText(err) |
| 219 | } |
| 220 | |
| 221 | func errText(err error) string { |
| 222 | if err == nil { |
| 223 | return "" |
| 224 | } |
| 225 | if s := err.Error(); s != "" { |
| 226 | return s |
| 227 | } |
| 228 | return "error" |
| 229 | } |
| 230 | |
| 231 | // followRedirect asks a server inside the sandbox for a page that |
| 232 | // redirects to target, follows the redirect and reports what happened. |
| 233 | func followRedirect(target string) redirectResult { |
| 234 | ln, err := net.Listen("tcp", "127.0.0.1:0") |
| 235 | if err != nil { |
| 236 | return redirectResult{Err: err.Error()} |
| 237 | } |
| 238 | defer ln.Close() |
| 239 | srv := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 240 | http.Redirect(w, r, target, http.StatusFound) |
| 241 | })} |
| 242 | go srv.Serve(ln) |
| 243 | defer srv.Close() |
| 244 | var res redirectResult |
| 245 | client := &http.Client{Timeout: 5 * time.Second, CheckRedirect: func(req *http.Request, via []*http.Request) error { |
| 246 | res.Location = req.URL.String() |
| 247 | return nil |
| 248 | }} |
| 249 | resp, err := client.Get("http://" + ln.Addr().String() + "/page") |
| 250 | if resp != nil { |
| 251 | res.Status = resp.StatusCode |
| 252 | resp.Body.Close() |
| 253 | } |
| 254 | res.Err = errText(err) |
| 255 | var dns *net.DNSError |
| 256 | var op *net.OpError |
| 257 | res.Blocked = err != nil && (errors.As(err, &dns) || errors.As(err, &op) && op.Op == "dial") |
| 258 | return res |
| 259 | } |
| 260 | |
| 261 | type browserReport struct { |
| 262 | Args []string |
| 263 | Env []string |
| 264 | FDs []int |
| 265 | Dir string |
| 266 | } |
| 267 | |
| 268 | // fakeBrowserMain plays the browser: it answers NUL-ended messages on |
| 269 | // its pipe (read on 3, written on 4): "report" replies with what it was |
| 270 | // given (browserReport, as JSON), "get <url>" fetches the URL and |
| 271 | // replies with the status and body, "post <url>" posts to it and |
| 272 | // replies with the status, "hang" never returns, "spawn" starts a writer |
| 273 | // that outlives the browser and replies "spawned", "exit <n>" exits |
| 274 | // with n, anything else is echoed. |
| 275 | func fakeBrowserMain(args []string) int { |
| 276 | r := browserReport{Args: args, Env: os.Environ(), FDs: openFDs()} |
| 277 | r.Dir, _ = os.Getwd() |
| 278 | report, _ := json.Marshal(r) |
| 279 | in, out := os.NewFile(3, "in"), os.NewFile(4, "out") |
| 280 | read := bufio.NewReader(in) |
| 281 | for { |
| 282 | msg, err := read.ReadString(0) |
| 283 | if err != nil { |
| 284 | return 0 |
| 285 | } |
| 286 | msg = strings.TrimSuffix(msg, "\x00") |
| 287 | switch { |
| 288 | case msg == "report": |
| 289 | out.Write(append(report, 0)) |
| 290 | case strings.HasPrefix(msg, "get "): |
| 291 | reply := "error" |
| 292 | if resp, err := http.Get(msg[4:]); err == nil { |
| 293 | body, _ := io.ReadAll(io.LimitReader(resp.Body, 4096)) |
| 294 | resp.Body.Close() |
| 295 | reply = fmt.Sprintf("%d %s", resp.StatusCode, body) |
| 296 | } else { |
| 297 | reply = "error " + err.Error() |
| 298 | } |
| 299 | out.WriteString(reply + "\x00") |
| 300 | case strings.HasPrefix(msg, "post "): |
| 301 | reply := "error" |
| 302 | if resp, err := http.Post(msg[5:], "text/plain", strings.NewReader("x")); err == nil { |
| 303 | resp.Body.Close() |
| 304 | reply = strconv.Itoa(resp.StatusCode) |
| 305 | } |
| 306 | out.WriteString(reply + "\x00") |
| 307 | case msg == "spawn": |
| 308 | // A process in its own session that keeps writing a tick |
| 309 | // to the browser's pipe (its descriptor 3) until it is |
| 310 | // killed. |
| 311 | w := exec.Command(os.Args[0], "--writer") |
| 312 | w.SysProcAttr = &syscall.SysProcAttr{Setsid: true} |
| 313 | w.ExtraFiles = []*os.File{out} |
| 314 | reply := "spawned" |
| 315 | if err := w.Start(); err != nil { |
| 316 | reply = "error " + err.Error() |
| 317 | } |
| 318 | out.WriteString(reply + "\x00") |
| 319 | case msg == "hang": |
| 320 | // A browser that never ends on its own, even when its pipe |
| 321 | // closes: only a kill stops it. |
| 322 | out.WriteString("hanging\x00") |
| 323 | for { |
| 324 | time.Sleep(time.Hour) |
| 325 | } |
| 326 | case strings.HasPrefix(msg, "exit "): |
| 327 | n, _ := strconv.Atoi(msg[5:]) |
| 328 | return n |
| 329 | default: |
| 330 | out.WriteString(msg + "\x00") |
| 331 | } |
| 332 | } |
| 333 | } |
| 334 | |
| 335 | // writerMain is the spawned writer: its 0, 1 and 2 are /dev/null, its 3 |
| 336 | // the browser's pipe, in its own session, deaf to the signals a session |
| 337 | // ending sends, writing a tick to 3 every millisecond whatever the |
| 338 | // write returns. |
| 339 | func writerMain() int { |
| 340 | signal.Ignore(syscall.SIGHUP, syscall.SIGTERM, syscall.SIGINT) |
| 341 | // Many threads make its death take a while, so a Close that does not |
| 342 | // wait for the sandbox to end returns while it still runs. |
| 343 | for i := 0; i < 256; i++ { |
| 344 | go func() { |
| 345 | runtime.LockOSThread() |
| 346 | for { |
| 347 | time.Sleep(time.Hour) |
| 348 | } |
| 349 | }() |
| 350 | } |
| 351 | f := os.NewFile(3, "ticks") |
| 352 | for { |
| 353 | f.Write([]byte{'.'}) |
| 354 | time.Sleep(time.Millisecond) |
| 355 | } |
| 356 | } |
| 357 | |
| 358 | type fdsReport struct { |
| 359 | Err string |
| 360 | FDs []int |
| 361 | CloExec map[int]bool |
| 362 | } |
| 363 | |
| 364 | // fdsMain runs sandboxDescriptors (or, with "each", closeEach(6), the |
| 365 | // /proc fallback) on the descriptors it was started with and prints what |
| 366 | // is left open and which are close-on-exec. |
| 367 | func fdsMain(args []string) int { |
| 368 | var err error |
| 369 | if len(args) == 1 && args[0] == "each" { |
| 370 | err = closeEach(fdStatus + 1) |
| 371 | } else { |
| 372 | err = sandboxDescriptors() |
| 373 | } |
| 374 | r := fdsReport{Err: errText(err), FDs: openFDs(), CloExec: map[int]bool{}} |
| 375 | for _, fd := range r.FDs { |
| 376 | flags, _ := unix.FcntlInt(uintptr(fd), unix.F_GETFD, 0) |
| 377 | r.CloExec[fd] = flags&unix.FD_CLOEXEC != 0 |
| 378 | } |
| 379 | b, _ := json.Marshal(r) |
| 380 | os.Stdout.Write(b) |
| 381 | return 0 |
| 382 | } |
| 383 | |