|
| 1 | +package sandbox |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "fmt" |
| 6 | + "log/slog" |
| 7 | + "os" |
| 8 | + "os/exec" |
| 9 | + "path/filepath" |
| 10 | + "strings" |
| 11 | + "syscall" |
| 12 | + |
| 13 | + "github.com/grafana/grafana-image-renderer/pkg/sandbox" |
| 14 | + "github.com/urfave/cli/v3" |
| 15 | + "go.opentelemetry.io/otel/trace" |
| 16 | + libcap "kernel.org/pub/linux/libs/security/libcap/cap" |
| 17 | +) |
| 18 | + |
| 19 | +func NewCmd() *cli.Command { |
| 20 | + return &cli.Command{ |
| 21 | + Name: "_internal_sandbox", |
| 22 | + Usage: "Starts the browser in a best-effort sandbox.", |
| 23 | + Hidden: true, |
| 24 | + Commands: []*cli.Command{ |
| 25 | + { |
| 26 | + Name: "supported", |
| 27 | + Usage: "Check if the current environment supports sandboxing. This is best-effort.", |
| 28 | + Action: func(ctx context.Context, c *cli.Command) error { |
| 29 | + if !sandbox.Supported(ctx) { |
| 30 | + return fmt.Errorf("sandboxing is not supported in this environment") |
| 31 | + } |
| 32 | + return nil |
| 33 | + }, |
| 34 | + }, |
| 35 | + { |
| 36 | + Name: "run", |
| 37 | + Usage: "Run a command inside the sandbox.", |
| 38 | + Flags: []cli.Flag{ |
| 39 | + &cli.StringSliceFlag{ |
| 40 | + Name: "mount", |
| 41 | + Usage: "Additional mount points to bind into the sandbox in the form of host_path:container_path(:rw)", |
| 42 | + Validator: func(s []string) error { |
| 43 | + for _, s := range s { |
| 44 | + if _, err := parseBindMount(s); err != nil { |
| 45 | + return fmt.Errorf("invalid --mount value %q: %w", s, err) |
| 46 | + } |
| 47 | + } |
| 48 | + return nil |
| 49 | + }, |
| 50 | + }, |
| 51 | + &cli.StringFlag{ |
| 52 | + Name: "cwd", |
| 53 | + Usage: "The working directory inside the sandbox.", |
| 54 | + Value: "/tmp", |
| 55 | + }, |
| 56 | + &cli.StringFlag{ |
| 57 | + Name: "trace", |
| 58 | + Usage: "The OpenTelemetry trace ID to use in logs. This does not change anything about the browser, only the sandbox's log output.", |
| 59 | + }, |
| 60 | + &cli.StringFlag{ |
| 61 | + Name: "tmp", |
| 62 | + Usage: "The directory to mount as /tmp insidee the sandbox. This is intended to be a read-write bind mount.", |
| 63 | + Required: true, |
| 64 | + }, |
| 65 | + }, |
| 66 | + Action: run, |
| 67 | + }, |
| 68 | + { |
| 69 | + Name: "bootstrap", |
| 70 | + Usage: "Bootstrap the sandbox environment.", |
| 71 | + SkipFlagParsing: true, |
| 72 | + Action: func(ctx context.Context, c *cli.Command) error { |
| 73 | + newRoot, err := os.MkdirTemp("", "") |
| 74 | + if err != nil { |
| 75 | + return fmt.Errorf("failed to create temp dir: %w", err) |
| 76 | + } |
| 77 | + defer func() { _ = os.RemoveAll(newRoot) }() |
| 78 | + |
| 79 | + cmd := exec.CommandContext(ctx, "/proc/self/exe", append([]string{"_internal_sandbox", "run"}, c.Args().Slice()...)...) |
| 80 | + cmd.Dir = newRoot |
| 81 | + cmd.Stdin = os.Stdin |
| 82 | + cmd.Stdout = os.Stdout |
| 83 | + cmd.Stderr = os.Stderr |
| 84 | + cmd.SysProcAttr = &syscall.SysProcAttr{ |
| 85 | + Pdeathsig: syscall.SIGKILL, |
| 86 | + Cloneflags: syscall.CLONE_NEWNS | syscall.CLONE_NEWPID | syscall.CLONE_NEWUSER, |
| 87 | + UidMappings: []syscall.SysProcIDMap{ |
| 88 | + { |
| 89 | + ContainerID: 0, |
| 90 | + HostID: os.Getuid(), |
| 91 | + Size: 1, |
| 92 | + }, |
| 93 | + }, |
| 94 | + GidMappings: []syscall.SysProcIDMap{ |
| 95 | + { |
| 96 | + ContainerID: 0, |
| 97 | + HostID: os.Getgid(), |
| 98 | + Size: 1, |
| 99 | + }, |
| 100 | + }, |
| 101 | + } |
| 102 | + |
| 103 | + return cmd.Run() |
| 104 | + }, |
| 105 | + }, |
| 106 | + }, |
| 107 | + } |
| 108 | +} |
| 109 | + |
| 110 | +func run(ctx context.Context, c *cli.Command) error { |
| 111 | + ctx, err := adoptTrace(ctx, c.String("trace")) |
| 112 | + if err != nil { |
| 113 | + slog.WarnContext(ctx, "failed to adopt trace", "error", err) |
| 114 | + } |
| 115 | + |
| 116 | + var bindMounts []sandbox.BindMount |
| 117 | + for _, s := range c.StringSlice("mount") { |
| 118 | + bm, err := parseBindMount(s) |
| 119 | + if err != nil { |
| 120 | + // should be unreachable, but easy to just return the error :P |
| 121 | + return fmt.Errorf("invalid --mount value %q: %w", s, err) |
| 122 | + } |
| 123 | + bindMounts = append(bindMounts, bm) |
| 124 | + } |
| 125 | + bindMounts = append(bindMounts, sandbox.BindMount{ |
| 126 | + Source: c.String("tmp"), |
| 127 | + Destination: "/tmp", |
| 128 | + ReadWrite: true, |
| 129 | + }) |
| 130 | + |
| 131 | + command := c.Args().Slice() |
| 132 | + if len(command) == 0 { |
| 133 | + return fmt.Errorf("no command specified to run in sandbox") |
| 134 | + } |
| 135 | + |
| 136 | + cwd, err := os.Getwd() |
| 137 | + if err != nil { |
| 138 | + return fmt.Errorf("failed to get current working directory: %w", err) |
| 139 | + } |
| 140 | + |
| 141 | + if err := sandbox.SetupFS(ctx, cwd, bindMounts); err != nil { |
| 142 | + return fmt.Errorf("failed to setup sandbox filesystem: %w", err) |
| 143 | + } |
| 144 | + |
| 145 | + if err := shedCapabilities(); err != nil { |
| 146 | + slog.WarnContext(ctx, "failed to shed capabilities", "error", err) |
| 147 | + } |
| 148 | + |
| 149 | + cmd := exec.CommandContext(ctx, command[0], command[1:]...) |
| 150 | + cmd.Stdin = os.Stdin |
| 151 | + cmd.Stdout = os.Stdout |
| 152 | + cmd.Stderr = os.Stderr |
| 153 | + cmd.Dir = c.String("cwd") |
| 154 | + if cmd.SysProcAttr == nil { |
| 155 | + cmd.SysProcAttr = &syscall.SysProcAttr{} |
| 156 | + } |
| 157 | + cmd.SysProcAttr.Pdeathsig = syscall.SIGKILL |
| 158 | + |
| 159 | + // TODO: Ensure this respects signals properly? |
| 160 | + return cmd.Run() |
| 161 | +} |
| 162 | + |
| 163 | +func parseBindMount(s string) (sandbox.BindMount, error) { |
| 164 | + host, container, found := strings.Cut(s, ":") |
| 165 | + if !found { |
| 166 | + return sandbox.BindMount{}, fmt.Errorf("invalid mount format, expected host_path:container_path(:rw)") |
| 167 | + } |
| 168 | + container, rw, _ := strings.Cut(container, ":") |
| 169 | + |
| 170 | + if !filepath.IsAbs(host) { |
| 171 | + return sandbox.BindMount{}, fmt.Errorf("host path must be absolute: %s", host) |
| 172 | + } else if !filepath.IsAbs(container) { |
| 173 | + return sandbox.BindMount{}, fmt.Errorf("container path must be absolute: %s", container) |
| 174 | + } else if rw != "" && rw != "rw" { |
| 175 | + return sandbox.BindMount{}, fmt.Errorf("invalid mount option (must be rw or absent): %s", rw) |
| 176 | + } |
| 177 | + |
| 178 | + return sandbox.BindMount{ |
| 179 | + Source: host, |
| 180 | + Destination: container, |
| 181 | + ReadWrite: rw == "rw", |
| 182 | + }, nil |
| 183 | +} |
| 184 | + |
| 185 | +func adoptTrace(ctx context.Context, traceID string) (context.Context, error) { |
| 186 | + if traceID == "" { |
| 187 | + return ctx, nil |
| 188 | + } |
| 189 | + tid, err := trace.TraceIDFromHex(traceID) |
| 190 | + if err != nil { |
| 191 | + return ctx, fmt.Errorf("invalid trace ID: %w", err) |
| 192 | + } |
| 193 | + return trace.ContextWithRemoteSpanContext(ctx, trace.NewSpanContext(trace.SpanContextConfig{ |
| 194 | + TraceID: tid, |
| 195 | + Remote: true, |
| 196 | + })), nil |
| 197 | +} |
| 198 | + |
| 199 | +func shedCapabilities() error { |
| 200 | + if err := libcap.DropBound(libcap.SYS_CHROOT, libcap.SYS_ADMIN, libcap.SETPCAP); err != nil { |
| 201 | + return fmt.Errorf("failed to drop capabilities: %w", err) |
| 202 | + } |
| 203 | + return nil |
| 204 | +} |
0 commit comments