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 webread
4
5import (
6 "bytes"
7 "context"
8 "encoding/json"
9 "fmt"
10 "io"
11 "os"
12 "os/exec"
13 "path/filepath"
14 "runtime"
15 "syscall"
16 "time"
17
18 "golang.org/x/sys/unix"
19)
20
21// Launch runs the fetcher, `<Binary> webread /out`, under bubblewrap with
22// the plan on stdin, and waits for it. The sandbox shares the host
23// network and nothing else: a fresh root with only the binary, the CA
24// bundle and resolv.conf read-only, and the output directory read-write;
25// no environment, runner state, credentials or home. The runner then
26// reads the bundle with ReadBundle.
27func Launch(ctx context.Context, cfg LaunchConfig, plan Plan) error {
28 return launch(ctx, cfg, plan, "webread")
29}
30
31// launch runs sub, the subcommand (a test runs a probe in its place).
32func launch(ctx context.Context, cfg LaunchConfig, plan Plan, sub string) error {
33 if err := plan.Validate(); err != nil {
34 return err
35 }
36 if cfg.CABundle == "" {
37 cfg.CABundle = DefaultCABundle
38 }
39 if cfg.ResolvConf == "" {
40 cfg.ResolvConf = "/etc/resolv.conf"
41 }
42 if cfg.Timeout <= 0 {
43 cfg.Timeout = OverallTimeout + 30*time.Second
44 }
45 for _, p := range []string{cfg.Bwrap, cfg.Binary, cfg.OutDir, cfg.CABundle, cfg.ResolvConf} {
46 if !filepath.IsAbs(p) || filepath.Clean(p) != p {
47 return fmt.Errorf("webread: launch path %q", p)
48 }
49 }
50 input, err := json.Marshal(plan)
51 if err != nil {
52 return err
53 }
54 var files []*os.File
55 defer func() {
56 for _, f := range files {
57 f.Close()
58 }
59 }()
60 out, err := pinOutDir(cfg.OutDir)
61 if err != nil {
62 return err
63 }
64 files = append(files, out)
65 for _, p := range []string{cfg.Binary, cfg.CABundle, cfg.ResolvConf} {
66 f, err := pinFile(p)
67 if err != nil {
68 return err
69 }
70 files = append(files, f)
71 }
72 // ExtraFiles start at descriptor 3: out, binary, CA bundle, resolv.conf.
73 args := []string{
74 "--unshare-all", "--share-net", "--die-with-parent", "--new-session", "--clearenv",
75 "--ro-bind-fd", "4", "/webread",
76 "--ro-bind-fd", "5", "/etc/ssl/certs/ca-certificates.crt",
77 "--ro-bind-fd", "6", "/etc/resolv.conf",
78 "--bind-fd", "3", "/out",
79 "--remount-ro", "/",
80 "--chdir", "/",
81 "--", "/webread", sub, "/out",
82 }
83 ctx, cancel := context.WithTimeout(ctx, cfg.Timeout)
84 defer cancel()
85 stderr := &bounded{max: 4096}
86 cmd := exec.CommandContext(ctx, cfg.Bwrap, args...)
87 cmd.Env = []string{}
88 cmd.Dir = "/"
89 cmd.ExtraFiles = files
90 cmd.Stdin = bytes.NewReader(input)
91 cmd.Stdout = io.Discard
92 cmd.Stderr = stderr
93 cmd.WaitDelay = 5 * time.Second
94 cmd.SysProcAttr = &syscall.SysProcAttr{Pdeathsig: syscall.SIGKILL}
95 // Pdeathsig follows the thread that forked: keep it until the wait ends.
96 runtime.LockOSThread()
97 defer runtime.UnlockOSThread()
98 if err = cmd.Run(); err != nil {
99 if cfg.Stderr != nil {
100 cfg.Stderr.Write(stderr.Bytes())
101 }
102 return fmt.Errorf("webread: fetcher: %w: %s", err, bytes.TrimSpace(stderr.Bytes()))
103 }
104 return nil
105}
106
107// pinOutDir opens the output directory with no symlink anywhere in its
108// path and checks it is the runner's own, private and empty.
109func pinOutDir(dir string) (*os.File, error) {
110 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})
111 if err != nil {
112 return nil, fmt.Errorf("webread: output directory: %w", err)
113 }
114 f := os.NewFile(uintptr(fd), dir)
115 var st unix.Stat_t
116 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()) {
117 f.Close()
118 return nil, fmt.Errorf("webread: output directory %s is not private", dir)
119 }
120 list, err := unix.Openat(fd, ".", unix.O_RDONLY|unix.O_DIRECTORY|unix.O_CLOEXEC, 0)
121 if err != nil {
122 f.Close()
123 return nil, err
124 }
125 d := os.NewFile(uintptr(list), dir)
126 names, _ := d.Readdirnames(1)
127 d.Close()
128 if len(names) != 0 {
129 f.Close()
130 return nil, fmt.Errorf("%w: output directory is not empty", ErrBundle)
131 }
132 return f, nil
133}
134
135// pinFile resolves path's symlinks on the host, then opens the file they
136// name with no symlink followed: the descriptor, not the path, is what
137// bubblewrap binds.
138func pinFile(path string) (*os.File, error) {
139 real, err := filepath.EvalSymlinks(path)
140 if err != nil {
141 return nil, fmt.Errorf("webread: %w", err)
142 }
143 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})
144 if err != nil {
145 return nil, fmt.Errorf("webread: %s: %w", path, err)
146 }
147 f := os.NewFile(uintptr(fd), real)
148 var st unix.Stat_t
149 if err = unix.Fstat(fd, &st); err != nil || st.Mode&unix.S_IFMT != unix.S_IFREG {
150 f.Close()
151 return nil, fmt.Errorf("webread: %s is not a regular file", path)
152 }
153 return f, nil
154}
155
156// bounded keeps the first max bytes written to it.
157type bounded struct {
158 bytes.Buffer
159 max int
160}
161
162func (b *bounded) Write(p []byte) (int, error) {
163 if room := b.max - b.Len(); room > 0 {
164 b.Buffer.Write(p[:min(len(p), room)])
165 }
166 return len(p), nil
167}
168