Files

154 lines
4.7 KiB
Go

package sandbox
import (
"bufio"
"bytes"
"math"
"regexp"
"slices"
"strconv"
"time"
)
const (
// nsjailLogFD is the descriptor of the nsjail log pipe in the child.
nsjailLogFD = 3
// addressSpaceLimitMB stays far above the cgroup memory limit, so that
// memory pressure ends in a cgroup OOM kill (memory_limit_exceeded)
// instead of an allocation failure inside the program; it still stops
// absurd reservations.
addressSpaceLimitMB = 4096
// nsjailTimeBackstop is added to the wall-clock limit for nsjail's own
// time limit, which only matters if the supervisor fails to stop a run.
nsjailTimeBackstop = 2 * time.Second
// cpuRlimitBackstop is added to the CPU limit for RLIMIT_CPU; the
// supervisor's cgroup watchdog normally stops a run first.
cpuRlimitBackstop = time.Second
sandboxHostname = "sandbox"
bytesPerMB = 1 << 20
)
// nsjailArgs returns the nsjail command line for one run. Every isolation
// switch is explicit so that a change in nsjail defaults cannot weaken it.
func nsjailArgs(cfg Config, spec Spec, limits Limits, seccompPolicy string) []string {
args := []string{
"--mode", "o",
"--log_fd", strconv.Itoa(nsjailLogFD),
"--hostname", sandboxHostname,
"--cwd", workDir(spec),
// Inside and outside the user namespace the program is the same
// unprivileged ID, never root.
"--user", idMapping(cfg.SandboxUID),
"--group", idMapping(cfg.SandboxGID),
"--time_limit", strconv.Itoa(ceilSeconds(limits.WallTime + nsjailTimeBackstop)),
"--rlimit_as", strconv.Itoa(addressSpaceLimitMB),
"--rlimit_cpu", strconv.Itoa(ceilSeconds(limits.CPUTime + cpuRlimitBackstop)),
"--rlimit_fsize", strconv.Itoa(ceilMB(fileSizeLimit(cfg, limits))),
"--rlimit_nofile", strconv.Itoa(cfg.OpenFiles),
"--rlimit_core", "0",
"--disable_proc",
// A new network namespace is nsjail's default; the empty namespace
// also has no loopback interface.
"--iface_no_lo",
"--seccomp_string", seccompPolicy,
}
for _, mount := range cfg.ReadOnlyMounts {
args = append(args, "--bindmount_ro", mount)
}
for _, mount := range spec.Mounts {
flag := "--bindmount_ro"
if mount.Writable {
flag = "--bindmount"
}
args = append(args, flag, mount.Source+":"+mount.Target)
}
args = append(args,
"--bindmount", "/dev/null",
"--bindmount_ro", "/dev/urandom",
"--mount", "none:"+ScratchPath+":tmpfs:size="+strconv.FormatInt(cfg.TmpfsBytes, 10),
)
for _, variable := range append(slices.Clone(cfg.Env), spec.Env...) {
args = append(args, "--env", variable)
}
args = append(args, "--")
return append(args, spec.Argv...)
}
func workDir(spec Spec) string {
if spec.WorkDir != "" {
return spec.WorkDir
}
return ScratchPath
}
func fileSizeLimit(cfg Config, limits Limits) int64 {
if limits.FileSizeBytes > 0 {
return limits.FileSizeBytes
}
return cfg.FileSizeBytes
}
func idMapping(id int) string {
value := strconv.Itoa(id)
return value + ":" + value + ":1"
}
func ceilSeconds(duration time.Duration) int {
return int(math.Ceil(duration.Seconds()))
}
func ceilMB(size int64) int {
return max(1, int((size+bytesPerMB-1)/bytesPerMB))
}
var (
childExited = regexp.MustCompile(`\) exited with status: (\d+)`)
childSignaled = regexp.MustCompile(`\) terminated with signal: [^(]*\((\d+)\)`)
)
// nsjailReport is what the nsjail log says about the jailed command.
type nsjailReport struct {
exitCode int
signal int
// reported is true when the log names how the command ended.
reported bool
// failure is the first error line of nsjail itself, without timestamps.
failure string
}
const maxFailureExcerpt = 200
// parseNsjailLog reads the nsjail log. A launch failure is reported by error
// ([E]) or fatal ([F]) lines; the log never contains program input or output.
func parseNsjailLog(log []byte) nsjailReport {
var report nsjailReport
scanner := bufio.NewScanner(bytes.NewReader(log))
for scanner.Scan() {
line := scanner.Bytes()
if report.failure == "" && (bytes.HasPrefix(line, []byte("[E]")) || bytes.HasPrefix(line, []byte("[F]"))) {
report.failure = failureExcerpt(line)
}
if match := childExited.FindSubmatch(line); match != nil {
report.exitCode, _ = strconv.Atoi(string(match[1]))
report.reported = true
}
if match := childSignaled.FindSubmatch(line); match != nil {
report.signal, _ = strconv.Atoi(string(match[1]))
report.exitCode = -1
report.reported = true
}
}
return report
}
func failureExcerpt(line []byte) string {
// Drop the "[E][timestamp][pid] " prefix; keep the function and message.
if index := bytes.LastIndexByte(line, ']'); index >= 0 && index+1 < len(line) {
line = bytes.TrimSpace(line[index+1:])
}
if len(line) > maxFailureExcerpt {
line = line[:maxFailureExcerpt]
}
return string(bytes.ToValidUTF8(line, []byte("?")))
}