//go:build linux package webread import ( "bytes" "context" "encoding/json" "fmt" "io" "os" "os/exec" "path/filepath" "runtime" "syscall" "time" "golang.org/x/sys/unix" ) // Launch runs the fetcher, ` webread /out`, under bubblewrap with // the plan on stdin, and waits for it. The sandbox shares the host // network and nothing else: a fresh root with only the binary, the CA // bundle and resolv.conf read-only, and the output directory read-write; // no environment, runner state, credentials or home. The runner then // reads the bundle with ReadBundle. func Launch(ctx context.Context, cfg LaunchConfig, plan Plan) error { return launch(ctx, cfg, plan, "webread") } // launch runs sub, the subcommand (a test runs a probe in its place). func launch(ctx context.Context, cfg LaunchConfig, plan Plan, sub string) error { if err := plan.Validate(); err != nil { return err } if cfg.CABundle == "" { cfg.CABundle = DefaultCABundle } if cfg.ResolvConf == "" { cfg.ResolvConf = "/etc/resolv.conf" } if cfg.Timeout <= 0 { cfg.Timeout = OverallTimeout + 30*time.Second } for _, p := range []string{cfg.Bwrap, cfg.Binary, cfg.OutDir, cfg.CABundle, cfg.ResolvConf} { if !filepath.IsAbs(p) || filepath.Clean(p) != p { return fmt.Errorf("webread: launch path %q", p) } } input, err := json.Marshal(plan) if err != nil { return err } var files []*os.File defer func() { for _, f := range files { f.Close() } }() out, err := pinOutDir(cfg.OutDir) if err != nil { return err } files = append(files, out) for _, p := range []string{cfg.Binary, cfg.CABundle, cfg.ResolvConf} { f, err := pinFile(p) if err != nil { return err } files = append(files, f) } // ExtraFiles start at descriptor 3: out, binary, CA bundle, resolv.conf. args := []string{ "--unshare-all", "--share-net", "--die-with-parent", "--new-session", "--clearenv", "--ro-bind-fd", "4", "/webread", "--ro-bind-fd", "5", "/etc/ssl/certs/ca-certificates.crt", "--ro-bind-fd", "6", "/etc/resolv.conf", "--bind-fd", "3", "/out", "--remount-ro", "/", "--chdir", "/", "--", "/webread", sub, "/out", } ctx, cancel := context.WithTimeout(ctx, cfg.Timeout) defer cancel() stderr := &bounded{max: 4096} cmd := exec.CommandContext(ctx, cfg.Bwrap, args...) cmd.Env = []string{} cmd.Dir = "/" cmd.ExtraFiles = files cmd.Stdin = bytes.NewReader(input) cmd.Stdout = io.Discard cmd.Stderr = stderr cmd.WaitDelay = 5 * time.Second cmd.SysProcAttr = &syscall.SysProcAttr{Pdeathsig: syscall.SIGKILL} // Pdeathsig follows the thread that forked: keep it until the wait ends. runtime.LockOSThread() defer runtime.UnlockOSThread() if err = cmd.Run(); err != nil { if cfg.Stderr != nil { cfg.Stderr.Write(stderr.Bytes()) } return fmt.Errorf("webread: fetcher: %w: %s", err, bytes.TrimSpace(stderr.Bytes())) } return nil } // pinOutDir opens the output directory with no symlink anywhere in its // path and checks it is the runner's own, private and empty. func pinOutDir(dir string) (*os.File, error) { 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, fmt.Errorf("webread: output directory: %w", err) } f := os.NewFile(uintptr(fd), dir) var st unix.Stat_t if err = unix.Fstat(fd, &st); err != nil || st.Mode&unix.S_IFMT != unix.S_IFDIR || st.Mode&0777 != 0700 || st.Uid != uint32(os.Geteuid()) { f.Close() return nil, fmt.Errorf("webread: output directory %s is not private", dir) } list, err := unix.Openat(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("%w: output directory is not empty", ErrBundle) } return f, nil } // pinFile resolves path's symlinks on the host, then opens the file they // name with no symlink followed: the descriptor, not the path, is what // bubblewrap binds. func pinFile(path string) (*os.File, error) { real, err := filepath.EvalSymlinks(path) if err != nil { return nil, fmt.Errorf("webread: %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("webread: %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("webread: %s is not a regular file", path) } return f, nil } // bounded keeps the first max bytes written to it. type bounded struct { bytes.Buffer max int } func (b *bounded) Write(p []byte) (int, error) { if room := b.max - b.Len(); room > 0 { b.Buffer.Write(p[:min(len(p), room)]) } return len(p), nil }