feat(runner): add the own code runner contract, client and nsjail service

This commit is contained in:
shira committed 2026-10-11 08:23:42 +03:00
1 parent 5e1db37746
commit cdf6bcbb91
109 files changed
+24084 -28

No files matched your search

+353
View File
@@ -0,0 +1,353 @@
package sandbox
import (
"bufio"
"bytes"
"context"
"errors"
"fmt"
"io/fs"
"os"
"path/filepath"
"slices"
"strconv"
"strings"
"syscall"
"time"
)
const (
supervisorCgroup = "supervisor"
jailsCgroup = "jails"
// cpuQuota allows one CPU per run: quota and period in microseconds.
cpuQuota = "100000 100000"
// cgroupDrainTimeout bounds the wait for a killed cgroup to empty.
cgroupDrainTimeout = 5 * time.Second
cgroupDrainPoll = 5 * time.Millisecond
// moveAttempts bounds retries while processes appear in the root cgroup.
moveAttempts = 10
cgroupFileMode = 0o644
cgroupDirMode = 0o755
bytesPerKB = 1 << 10
)
var requiredControllers = []string{"cpu", "memory", "pids"}
// cgroupTree is the cgroup hierarchy owned by the runner:
//
// <root>/supervisor the runner process itself
// <root>/jails/<run> one cgroup per sandboxed run
//
// cgroup v2 forbids processes in a cgroup that delegates controllers to its
// children, so the runner first moves itself out of the root.
type cgroupTree struct {
root string
jails string
}
// prepareCgroups creates the hierarchy below root, enables the controllers,
// and removes run cgroups left by an earlier process.
func prepareCgroups(root string) (*cgroupTree, error) {
controllers, err := os.ReadFile(filepath.Join(root, "cgroup.controllers"))
if err != nil {
return nil, fmt.Errorf("sandbox.prepareCgroups - read controllers: %w", err)
}
available := strings.Fields(string(controllers))
for _, controller := range requiredControllers {
if !slices.Contains(available, controller) {
return nil, fmt.Errorf("sandbox.prepareCgroups - controller %s is not delegated", controller)
}
}
supervisor := filepath.Join(root, supervisorCgroup)
if err := mkdirCgroup(supervisor); err != nil {
return nil, err
}
if err := moveProcesses(root, supervisor); err != nil {
return nil, err
}
enable := "+" + strings.Join(requiredControllers, " +")
if err := writeCgroupFile(root, "cgroup.subtree_control", enable); err != nil {
return nil, err
}
tree := &cgroupTree{root: root, jails: filepath.Join(root, jailsCgroup)}
if err := mkdirCgroup(tree.jails); err != nil {
return nil, err
}
if err := writeCgroupFile(tree.jails, "cgroup.subtree_control", enable); err != nil {
return nil, err
}
if err := tree.removeLeftovers(); err != nil {
return nil, err
}
return tree, nil
}
func mkdirCgroup(path string) error {
if err := os.Mkdir(path, cgroupDirMode); err != nil && !errors.Is(err, fs.ErrExist) {
return fmt.Errorf("sandbox.mkdirCgroup - create %s: %w", filepath.Base(path), err)
}
return nil
}
// moveProcesses moves every process of the from cgroup into the to cgroup.
func moveProcesses(from, to string) error {
for range moveAttempts {
pids, err := readPIDs(from)
if err != nil {
return err
}
if len(pids) == 0 {
return nil
}
for _, pid := range pids {
err := writeCgroupFile(to, "cgroup.procs", strconv.Itoa(pid))
if err != nil && !errors.Is(err, syscall.ESRCH) {
return err
}
}
}
return errors.New("sandbox.moveProcesses - processes keep appearing in the root cgroup")
}
func readPIDs(cgroup string) ([]int, error) {
content, err := os.ReadFile(filepath.Join(cgroup, "cgroup.procs"))
if err != nil {
return nil, fmt.Errorf("sandbox.readPIDs - read procs: %w", err)
}
var pids []int
for field := range strings.FieldsSeq(string(content)) {
pid, err := strconv.Atoi(field)
if err != nil {
return nil, fmt.Errorf("sandbox.readPIDs - parse pid: %w", err)
}
pids = append(pids, pid)
}
return pids, nil
}
// removeLeftovers kills and removes run cgroups of an earlier process.
func (t *cgroupTree) removeLeftovers() error {
entries, err := os.ReadDir(t.jails)
if err != nil {
return fmt.Errorf("sandbox.cgroupTree.removeLeftovers - list: %w", err)
}
for _, entry := range entries {
if !entry.IsDir() {
continue
}
run := &runCgroup{path: filepath.Join(t.jails, entry.Name())}
if err := run.remove(context.Background()); err != nil {
return err
}
}
return nil
}
// leftoverRuns returns the names of run cgroups that still exist.
func (t *cgroupTree) leftoverRuns() ([]string, error) {
entries, err := os.ReadDir(t.jails)
if err != nil {
return nil, fmt.Errorf("sandbox.cgroupTree.leftoverRuns - list: %w", err)
}
var names []string
for _, entry := range entries {
if entry.IsDir() {
names = append(names, entry.Name())
}
}
return names, nil
}
// cgroupLimits are the controller values of one run cgroup.
type cgroupLimits struct {
memoryBytes int64
processes int
}
// runCgroup is the cgroup of one run. dir is an open descriptor of the
// directory for CLONE_INTO_CGROUP.
type runCgroup struct {
path string
dir *os.File
}
func (t *cgroupTree) create(ctx context.Context, name string, limits cgroupLimits) (*runCgroup, error) {
cleanupCtx := context.WithoutCancel(ctx)
path := filepath.Join(t.jails, name)
if err := os.Mkdir(path, cgroupDirMode); err != nil {
return nil, fmt.Errorf("sandbox.cgroupTree.create - create: %w", err)
}
run := &runCgroup{path: path}
settings := []struct{ file, value string }{
{"memory.max", strconv.FormatInt(limits.memoryBytes, 10)},
{"memory.swap.max", "0"},
{"pids.max", strconv.Itoa(limits.processes)},
{"cpu.max", cpuQuota},
}
for _, setting := range settings {
err := writeCgroupFile(path, setting.file, setting.value)
if errors.Is(err, fs.ErrNotExist) && setting.file == "memory.swap.max" {
// A kernel without swap accounting has no swap to limit.
continue
}
if err != nil {
return nil, errors.Join(err, run.remove(cleanupCtx))
}
}
dir, err := os.Open(path)
if err != nil {
return nil, errors.Join(fmt.Errorf("sandbox.cgroupTree.create - open: %w", err), run.remove(cleanupCtx))
}
run.dir = dir
return run, nil
}
// cgroupStats are the counters the supervisor reads during and after a run.
type cgroupStats struct {
cpuUsage time.Duration
oomKills int64
pidsLimits int64
}
func (c *runCgroup) stats() (cgroupStats, error) {
var stats cgroupStats
cpu, err := readKeyedFile(c.path, "cpu.stat")
if err != nil {
return stats, err
}
stats.cpuUsage = time.Duration(cpu["usage_usec"]) * time.Microsecond
memory, err := readKeyedFile(c.path, "memory.events")
if err != nil {
return stats, err
}
stats.oomKills = memory["oom_kill"] + memory["oom_group_kill"]
pids, err := readKeyedFile(c.path, "pids.events")
if err != nil {
return stats, err
}
stats.pidsLimits = pids["max"]
return stats, nil
}
// kill stops every process of the cgroup.
func (c *runCgroup) kill() error {
err := writeCgroupFile(c.path, "cgroup.kill", "1")
if !errors.Is(err, fs.ErrNotExist) {
return err
}
// Kernels before 5.14 have no cgroup.kill; signal each process instead.
pids, err := readPIDs(c.path)
if err != nil {
return err
}
for _, pid := range pids {
if err := syscall.Kill(pid, syscall.SIGKILL); err != nil && !errors.Is(err, syscall.ESRCH) {
return fmt.Errorf("sandbox.runCgroup.kill - signal: %w", err)
}
}
return nil
}
// killExcept kills every process of the cgroup except keep. Killing the
// jailed processes but not nsjail lets nsjail reap its child and report how it
// ended; once the namespace's first process dies, the kernel kills the rest
// of the PID namespace.
func (c *runCgroup) killExcept(keep int) error {
pids, err := readPIDs(c.path)
if err != nil {
return err
}
for _, pid := range pids {
if pid == keep {
continue
}
if err := syscall.Kill(pid, syscall.SIGKILL); err != nil && !errors.Is(err, syscall.ESRCH) {
return fmt.Errorf("sandbox.runCgroup.killExcept - signal: %w", err)
}
}
return nil
}
// remove kills what is left, waits until the cgroup is empty, and deletes it.
func (c *runCgroup) remove(ctx context.Context) error {
if c.dir != nil {
_ = c.dir.Close() // The descriptor only served CLONE_INTO_CGROUP.
c.dir = nil
}
if err := c.kill(); err != nil && !errors.Is(err, fs.ErrNotExist) {
return err
}
ctx, cancel := context.WithTimeout(ctx, cgroupDrainTimeout)
defer cancel()
for {
err := os.Remove(c.path)
if err == nil || errors.Is(err, fs.ErrNotExist) {
return nil
}
if !errors.Is(err, syscall.EBUSY) {
return fmt.Errorf("sandbox.runCgroup.remove - remove: %w", err)
}
select {
case <-ctx.Done():
return fmt.Errorf("sandbox.runCgroup.remove - processes did not exit: %w", ctx.Err())
case <-time.After(cgroupDrainPoll):
}
}
}
func writeCgroupFile(dir, name, value string) error {
path := filepath.Join(dir, name)
// O_TRUNC is not allowed on cgroup files; each write is one operation.
file, err := os.OpenFile(path, os.O_WRONLY, cgroupFileMode)
if err != nil {
return fmt.Errorf("sandbox.writeCgroupFile - open %s: %w", name, err)
}
_, writeErr := file.WriteString(value)
closeErr := file.Close()
if writeErr != nil {
return fmt.Errorf("sandbox.writeCgroupFile - write %s: %w", name, writeErr)
}
if closeErr != nil {
return fmt.Errorf("sandbox.writeCgroupFile - close %s: %w", name, closeErr)
}
return nil
}
// readKeyedFile parses a flat "key value" cgroup file.
func readKeyedFile(dir, name string) (map[string]int64, error) {
content, err := os.ReadFile(filepath.Join(dir, name))
if err != nil {
return nil, fmt.Errorf("sandbox.readKeyedFile - read %s: %w", name, err)
}
values := make(map[string]int64)
scanner := bufio.NewScanner(bytes.NewReader(content))
for scanner.Scan() {
key, value, found := strings.Cut(scanner.Text(), " ")
if !found {
continue
}
number, err := strconv.ParseInt(strings.TrimSpace(value), 10, 64)
if err != nil {
continue
}
values[key] = number
}
return values, nil
}
// peakMemoryKB returns memory.peak in KiB, or 0 when the kernel has no
// such file. It is the exact high-water mark of every process of the run,
// nsjail included, plus file cache charged to the run. Unlike ru_maxrss it
// never includes the runner itself: Go starts nsjail through vfork, so the
// rusage of nsjail inherits the runner's resident set at exec.
func (c *runCgroup) peakMemoryKB() int64 {
content, err := os.ReadFile(filepath.Join(c.path, "memory.peak"))
if err != nil {
return 0
}
peak, err := strconv.ParseInt(strings.TrimSpace(string(content)), 10, 64)
if err != nil {
return 0
}
return peak / bytesPerKB
}
+384
View File
@@ -0,0 +1,384 @@
package sandbox
import (
"bytes"
"context"
"crypto/rand"
"encoding/hex"
"errors"
"fmt"
"io"
"os"
"os/exec"
"sync"
"time"
)
const (
// nsjailProcesses is the supervising nsjail process inside the run
// cgroup; it is added to the process limit of the program.
nsjailProcesses = 1
// maxNsjailLog bounds the nsjail log kept for one run.
maxNsjailLog = 64 << 10
runNameBytes = 8
readChunk = 32 << 10
)
// terminationCanceled marks a run stopped because its context ended.
const terminationCanceled Termination = "canceled"
// Executor runs commands in nsjail. It is safe for concurrent use.
type Executor struct {
cfg Config
cgroups *cgroupTree
policy string
}
// New checks the host and prepares the cgroup hierarchy and the work root.
func New(cfg Config) (*Executor, error) {
if err := platformSupported(); err != nil {
return nil, err
}
if err := validateConfig(cfg); err != nil {
return nil, err
}
info, err := os.Stat(cfg.NsjailPath)
if err != nil {
return nil, fmt.Errorf("sandbox.New - stat nsjail: %w", err)
}
if info.IsDir() || info.Mode().Perm()&0o111 == 0 {
return nil, errors.New("sandbox.New - nsjail is not an executable file")
}
if err := emptyWorkRoot(cfg.WorkRoot); err != nil {
return nil, err
}
tree, err := prepareCgroups(cfg.CgroupRoot)
if err != nil {
return nil, err
}
return &Executor{cfg: cfg, cgroups: tree, policy: seccompPolicy()}, nil
}
func validateConfig(cfg Config) error {
switch {
case cfg.SandboxUID <= 0 || cfg.SandboxGID <= 0:
return errors.New("sandbox.validateConfig - the sandbox user must not be root")
case cfg.MaxProcesses <= 0:
return errors.New("sandbox.validateConfig - the process limit must be positive")
case cfg.TmpfsBytes <= 0 || cfg.FileSizeBytes <= 0 || cfg.OpenFiles <= 0:
return errors.New("sandbox.validateConfig - tmpfs, file size, and open file limits must be positive")
case cfg.StderrCaptureBytes <= 0 || cfg.PollInterval <= 0:
return errors.New("sandbox.validateConfig - stderr capture and poll interval must be positive")
case cfg.MemoryOverheadBytes < 0:
return errors.New("sandbox.validateConfig - the memory overhead must not be negative")
}
return nil
}
// NewBox creates the read-only file directory of a run.
func (e *Executor) NewBox(fileName string, content []byte) (*Box, error) {
return CreateBox(e.cfg.WorkRoot, fileName, content)
}
// Leftovers lists boxes and run cgroups that still exist. After every run
// has finished both lists are empty.
func (e *Executor) Leftovers() (boxes, cgroups []string, err error) {
entries, err := os.ReadDir(e.cfg.WorkRoot)
if err != nil {
return nil, nil, fmt.Errorf("sandbox.Executor.Leftovers - list work root: %w", err)
}
for _, entry := range entries {
boxes = append(boxes, entry.Name())
}
cgroups, err = e.cgroups.leftoverRuns()
return boxes, cgroups, err
}
// Run executes spec under limits. It returns an error only when the sandbox
// itself failed or ctx ended; every outcome caused by the program, including
// a limit, is a Result.
func (e *Executor) Run(ctx context.Context, spec Spec, limits Limits) (result Result, err error) {
cgroup, err := e.cgroups.create(ctx, newRunName(), cgroupLimits{
memoryBytes: limits.MemoryBytes + e.cfg.MemoryOverheadBytes,
processes: e.cfg.MaxProcesses + nsjailProcesses,
})
if err != nil {
return Result{}, err
}
defer func() {
// A cgroup that cannot be removed may still hold processes, so the
// run is not trustworthy.
if removeErr := cgroup.remove(context.WithoutCancel(ctx)); removeErr != nil {
err = errors.Join(err, removeErr)
}
}()
pipes, err := openPipes()
if err != nil {
return Result{}, err
}
defer pipes.closeAll()
// The watchdog stops a canceled run by killing its whole cgroup;
// CommandContext would kill only nsjail. The binary path comes from
// configuration and the arguments are built above.
cmd := exec.Command(e.cfg.NsjailPath, nsjailArgs(e.cfg, spec, limits, e.policy)...) //nolint:noctx,gosec // See the comment above.
// The runner environment, including any secret, never reaches nsjail.
cmd.Env = []string{}
cmd.Stdin = bytes.NewReader(spec.Stdin)
cmd.Stdout = pipes.stdoutWrite
cmd.Stderr = pipes.stderrWrite
cmd.ExtraFiles = []*os.File{pipes.logWrite}
attachToCgroup(cmd, cgroup)
started := time.Now()
if err := cmd.Start(); err != nil {
return Result{}, fmt.Errorf("sandbox.Executor.Run - start nsjail: %w", err)
}
pipes.closeWriteEnds()
stopper := &stopper{cgroup: cgroup, nsjailPID: cmd.Process.Pid}
var readers sync.WaitGroup
var stdout, stderr, nsjailLog []byte
readers.Go(func() {
stdout = readLimited(pipes.stdoutRead, limits.OutputBytes, func() { stopper.stop(TerminationOutput) })
})
readers.Go(func() { stderr = readTail(pipes.stderrRead, e.cfg.StderrCaptureBytes) })
readers.Go(func() { nsjailLog = readLimited(pipes.logRead, maxNsjailLog, func() {}) })
watchdogDone := make(chan struct{})
var watchdog sync.WaitGroup
watchdog.Go(func() { e.watch(ctx, cgroup, limits, stopper, watchdogDone) })
readers.Wait()
waitErr := cmd.Wait()
wallTime := time.Since(started)
close(watchdogDone)
watchdog.Wait()
var exitErr *exec.ExitError
if waitErr != nil && !errors.As(waitErr, &exitErr) {
return Result{}, fmt.Errorf("sandbox.Executor.Run - wait for nsjail: %w", waitErr)
}
stats, err := cgroup.stats()
if err != nil {
return Result{}, err
}
reason := stopper.reason()
if reason == terminationCanceled {
return Result{}, fmt.Errorf("sandbox.Executor.Run - run stopped: %w", context.Cause(ctx))
}
if reason == TerminationNone {
reason = terminationFromStats(stats, limits)
}
result = Result{
Stdout: stdout,
Stderr: stderr,
CPUTime: stats.cpuUsage,
WallTime: wallTime,
PeakMemoryKB: cgroup.peakMemoryKB(),
Termination: reason,
}
if result.PeakMemoryKB == 0 {
// Kernels before 5.19 have no memory.peak.
result.PeakMemoryKB = peakMemoryKB(cmd.ProcessState)
}
return result, applyExitStatus(&result, parseNsjailLog(nsjailLog), cmd.ProcessState)
}
// terminationFromStats finds a limit that stopped the run between two polls
// or that the program reached without being stopped.
func terminationFromStats(stats cgroupStats, limits Limits) Termination {
switch {
case stats.oomKills > 0:
return TerminationMemory
case stats.pidsLimits > 0:
return TerminationProcesses
case stats.cpuUsage > limits.CPUTime:
return TerminationCPUTime
default:
return TerminationNone
}
}
// applyExitStatus fills the exit code and signal from the nsjail log.
func applyExitStatus(result *Result, report nsjailReport, state *os.ProcessState) error {
stoppedBySupervisor := result.Termination != TerminationNone
switch {
case report.failure != "" && !stoppedBySupervisor:
return fmt.Errorf("sandbox.applyExitStatus - nsjail failed: %s", report.failure)
case report.reported:
result.ExitCode = report.exitCode
result.Signal = report.signal
case stoppedBySupervisor:
// nsjail was killed together with the program.
result.ExitCode = -1
result.Signal = signalKill
default:
return fmt.Errorf("sandbox.applyExitStatus - nsjail ended without a report: %s", state.String())
}
return nil
}
// watch enforces the CPU and wall-clock limits and stops a run as soon as
// the cgroup reports an OOM kill or a refused fork.
func (e *Executor) watch(ctx context.Context, cgroup *runCgroup, limits Limits, stopper *stopper, done <-chan struct{}) {
ticker := time.NewTicker(e.cfg.PollInterval)
defer ticker.Stop()
wall := time.NewTimer(limits.WallTime)
defer wall.Stop()
for {
select {
case <-done:
return
case <-ctx.Done():
stopper.stop(terminationCanceled)
case <-wall.C:
stopper.stop(TerminationWallTime)
case <-ticker.C:
stopper.enforceGrace()
stats, err := cgroup.stats()
if err != nil {
// The cgroup is gone only after the run ended.
continue
}
if reason := terminationFromStats(stats, limits); reason != TerminationNone {
stopper.stop(reason)
}
}
}
}
// stopper records the first reason a run was stopped and kills the jailed
// processes. nsjail stays alive to reap its child, so no orphan is left to
// the init process; if nsjail does not exit within stopGrace, the watchdog
// kills the whole cgroup.
type stopper struct {
cgroup *runCgroup
nsjailPID int
mu sync.Mutex
first Termination
stoppedAt time.Time
}
// stopGrace is how long nsjail may take to reap a killed program.
const stopGrace = time.Second
func (s *stopper) stop(reason Termination) {
s.mu.Lock()
defer s.mu.Unlock()
if s.first == TerminationNone {
s.first = reason
s.stoppedAt = time.Now()
}
// Killing again is harmless and covers processes forked meanwhile.
_ = s.cgroup.killExcept(s.nsjailPID) // A failure surfaces when the cgroup is removed.
}
// enforceGrace kills nsjail too when it outlives the grace period.
func (s *stopper) enforceGrace() {
s.mu.Lock()
defer s.mu.Unlock()
if s.first != TerminationNone && time.Since(s.stoppedAt) > stopGrace {
_ = s.cgroup.kill() // A failure surfaces when the cgroup is removed.
}
}
func (s *stopper) reason() Termination {
s.mu.Lock()
defer s.mu.Unlock()
return s.first
}
// readLimited reads r to the end and keeps at most limit bytes; onExceeded
// runs once when more arrives. Reading continues so the writer never blocks.
func readLimited(r io.Reader, limit int64, onExceeded func()) []byte {
var kept bytes.Buffer
var exceeded bool
chunk := make([]byte, readChunk)
for {
n, err := r.Read(chunk)
if n > 0 {
room := limit - int64(kept.Len())
if int64(n) > room {
kept.Write(chunk[:max(room, 0)])
if !exceeded {
exceeded = true
onExceeded()
}
} else {
kept.Write(chunk[:n])
}
}
if err != nil {
return kept.Bytes()
}
}
}
// readTail reads r to the end and keeps its last limit bytes.
func readTail(r io.Reader, limit int) []byte {
var kept []byte
chunk := make([]byte, readChunk)
for {
n, err := r.Read(chunk)
kept = append(kept, chunk[:n]...)
if len(kept) > 2*limit {
kept = append([]byte(nil), kept[len(kept)-limit:]...)
}
if err != nil {
if len(kept) > limit {
kept = kept[len(kept)-limit:]
}
return kept
}
}
}
type runPipes struct {
stdoutRead, stdoutWrite *os.File
stderrRead, stderrWrite *os.File
logRead, logWrite *os.File
}
func openPipes() (*runPipes, error) {
pipes := &runPipes{}
var err error
if pipes.stdoutRead, pipes.stdoutWrite, err = os.Pipe(); err != nil {
return nil, fmt.Errorf("sandbox.openPipes - stdout: %w", err)
}
if pipes.stderrRead, pipes.stderrWrite, err = os.Pipe(); err != nil {
pipes.closeAll()
return nil, fmt.Errorf("sandbox.openPipes - stderr: %w", err)
}
if pipes.logRead, pipes.logWrite, err = os.Pipe(); err != nil {
pipes.closeAll()
return nil, fmt.Errorf("sandbox.openPipes - log: %w", err)
}
return pipes, nil
}
func (p *runPipes) closeWriteEnds() {
for _, file := range []**os.File{&p.stdoutWrite, &p.stderrWrite, &p.logWrite} {
if *file != nil {
_ = (*file).Close() // The child holds its own copy.
*file = nil
}
}
}
func (p *runPipes) closeAll() {
p.closeWriteEnds()
for _, file := range []**os.File{&p.stdoutRead, &p.stderrRead, &p.logRead} {
if *file != nil {
_ = (*file).Close() // Reading has finished.
*file = nil
}
}
}
func newRunName() string {
name := make([]byte, runNameBytes)
_, _ = rand.Read(name) // crypto/rand.Read never fails on supported platforms.
return "run-" + hex.EncodeToString(name)
}
+132
View File
@@ -0,0 +1,132 @@
package sandbox
import (
"bufio"
"bytes"
"math"
"regexp"
"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", ScratchPath,
// 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(cfg.FileSizeBytes)),
"--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)
}
args = append(args,
"--bindmount_ro", spec.BoxDir+":"+BoxPath,
"--bindmount", "/dev/null",
"--bindmount_ro", "/dev/urandom",
"--mount", "none:"+ScratchPath+":tmpfs:size="+strconv.FormatInt(cfg.TmpfsBytes, 10),
)
for _, variable := range cfg.Env {
args = append(args, "--env", variable)
}
args = append(args, "--")
return append(args, spec.Argv...)
}
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("?")))
}
+38
View File
@@ -0,0 +1,38 @@
//go:build linux
package sandbox
import (
"os"
"os/exec"
"syscall"
)
const signalKill = int(syscall.SIGKILL)
func platformSupported() error {
return nil
}
// attachToCgroup starts nsjail directly inside the run cgroup, so no
// instruction of nsjail or of the program runs outside its limits, and kills
// nsjail if the runner dies.
func attachToCgroup(cmd *exec.Cmd, cgroup *runCgroup) {
cmd.SysProcAttr = &syscall.SysProcAttr{
UseCgroupFD: true,
CgroupFD: int(cgroup.dir.Fd()),
Setpgid: true,
Pdeathsig: syscall.SIGKILL,
}
}
// peakMemoryKB returns ru_maxrss of nsjail in KiB, the fallback when the
// kernel has no memory.peak. It overstates small programs because it
// includes the runner's resident set at exec.
func peakMemoryKB(state *os.ProcessState) int64 {
usage, ok := state.SysUsage().(*syscall.Rusage)
if !ok {
return 0
}
return usage.Maxrss
}
+21
View File
@@ -0,0 +1,21 @@
//go:build !linux
package sandbox
import (
"os"
"os/exec"
)
// signalKill is the Linux SIGKILL number reported by stopped runs.
const signalKill = 9
func platformSupported() error {
return ErrUnsupportedPlatform
}
func attachToCgroup(*exec.Cmd, *runCgroup) {}
func peakMemoryKB(*os.ProcessState) int64 {
return 0
}
+103
View File
@@ -0,0 +1,103 @@
// Package sandbox runs one untrusted command inside nsjail.
//
// Every run gets its own cgroup v2 directory with CPU, memory, swap, and
// process limits. The supervisor creates that cgroup itself and starts nsjail
// directly inside it (CLONE_INTO_CGROUP), so the limits cover nsjail and every
// jailed process, the supervisor can read exact OOM, process-limit, and CPU
// counters, and cgroup.kill removes the whole tree. nsjail adds the namespaces
// (no network, own PID, mount, IPC, UTS, user, and cgroup namespaces), the
// read-only file system with a tmpfs work directory, the unprivileged user,
// rlimits, and the seccomp policy.
package sandbox
import (
"errors"
"time"
)
// Termination names the limit that stopped a run.
type Termination string
const (
// TerminationNone means that the program stopped by itself.
TerminationNone Termination = ""
// TerminationCPUTime means the CPU time limit.
TerminationCPUTime Termination = "cpu_time"
// TerminationWallTime means the wall-clock limit.
TerminationWallTime Termination = "wall_time"
// TerminationMemory means the cgroup memory limit.
TerminationMemory Termination = "memory"
// TerminationOutput means the standard output limit.
TerminationOutput Termination = "output"
// TerminationProcesses means the cgroup process limit.
TerminationProcesses Termination = "processes"
)
// Jail paths seen by the jailed program.
const (
// BoxPath is the read-only directory with the files of a run.
BoxPath = "/box"
// ScratchPath is the writable tmpfs and the working directory.
ScratchPath = "/tmp"
)
// ErrUnsupportedPlatform reports that the sandbox needs Linux.
var ErrUnsupportedPlatform = errors.New("sandbox requires Linux with cgroup v2")
// Limits bound one run.
type Limits struct {
CPUTime time.Duration
WallTime time.Duration
MemoryBytes int64
OutputBytes int64
}
// Spec is one command to run in the jail.
type Spec struct {
// Argv is the command inside the jail; Argv[0] is an absolute path.
Argv []string
// Stdin is written to the standard input of the command.
Stdin []byte
// BoxDir is the host directory mounted read-only at BoxPath.
BoxDir string
}
// Result describes a finished run. It never contains host paths.
type Result struct {
Stdout []byte
// Stderr holds at most Config.StderrCaptureBytes of standard error.
Stderr []byte
// ExitCode is the exit status of the command, or -1 when a signal stopped it.
ExitCode int
// Signal is the signal that stopped the command, or 0.
Signal int
CPUTime time.Duration
WallTime time.Duration
PeakMemoryKB int64
Termination Termination
}
// Config holds the host-side sandbox settings shared by every run.
type Config struct {
NsjailPath string
// CgroupRoot is a cgroup v2 directory delegated to the runner.
CgroupRoot string
// WorkRoot holds one directory per run; it is emptied at startup.
WorkRoot string
SandboxUID int
SandboxGID int
// MaxProcesses bounds processes and threads of a run, nsjail excluded.
MaxProcesses int
// MemoryOverheadBytes is added to the memory limit for nsjail itself.
MemoryOverheadBytes int64
TmpfsBytes int64
FileSizeBytes int64
OpenFiles int
StderrCaptureBytes int
// ReadOnlyMounts are host paths mounted read-only at the same place.
ReadOnlyMounts []string
// Env is the complete environment of the jailed command.
Env []string
// PollInterval is how often the supervisor checks the cgroup counters.
PollInterval time.Duration
}
+212
View File
@@ -0,0 +1,212 @@
package sandbox
import (
"bytes"
"os"
"path/filepath"
"slices"
"strings"
"testing"
"time"
)
func testConfig() Config {
return Config{
NsjailPath: "/usr/bin/nsjail",
SandboxUID: 99999,
SandboxGID: 99999,
MaxProcesses: 16,
TmpfsBytes: 16 << 20,
FileSizeBytes: 8 << 20,
OpenFiles: 64,
StderrCaptureBytes: 1024,
ReadOnlyMounts: []string{"/usr", "/lib"},
Env: []string{"LANG=C.UTF-8"},
PollInterval: time.Millisecond,
}
}
// flagValue returns the value after the first occurrence of flag.
func flagValue(t *testing.T, args []string, flag string) string {
t.Helper()
index := slices.Index(args, flag)
if index < 0 || index+1 >= len(args) {
t.Fatalf("flag %s is missing in %q", flag, args)
}
return args[index+1]
}
func TestNsjailArgsKeepEveryIsolationSwitch(t *testing.T) {
t.Parallel()
spec := Spec{Argv: []string{"/usr/local/bin/python3", "-I", "/box/main.py"}, BoxDir: "/work/run-1"}
limits := Limits{CPUTime: 1500 * time.Millisecond, WallTime: 3500 * time.Millisecond, MemoryBytes: 64 << 20, OutputBytes: 1 << 16}
args := nsjailArgs(testConfig(), spec, limits, "POLICY")
for _, forbidden := range []string{
"--disable_clone_newnet", "-N", "--disable_clone_newuser", "--disable_clone_newns", "--disable_clone_newpid",
"--keep_caps", "--cap", "--disable_no_new_privs", "--rw", "--keep_env", "--chroot", "--proc_rw", "--use_pasta",
} {
if slices.Contains(args, forbidden) {
t.Errorf("args contain %s: %q", forbidden, args)
}
}
checks := map[string]string{
"--mode": "o",
"--user": "99999:99999:1",
"--group": "99999:99999:1",
"--cwd": ScratchPath,
"--rlimit_cpu": "3",
"--rlimit_fsize": "8",
"--rlimit_nofile": "64",
"--rlimit_core": "0",
"--time_limit": "6",
"--seccomp_string": "POLICY",
"--mount": "none:/tmp:tmpfs:size=16777216",
}
for flag, want := range checks {
if got := flagValue(t, args, flag); got != want {
t.Errorf("%s = %q, want %q", flag, got, want)
}
}
for _, required := range []string{"--disable_proc", "--iface_no_lo"} {
if !slices.Contains(args, required) {
t.Errorf("args miss %s", required)
}
}
if !slices.Contains(args, "/work/run-1:/box") {
t.Errorf("the box is not mounted at /box: %q", args)
}
separator := slices.Index(args, "--")
if separator < 0 || !slices.Equal(args[separator+1:], spec.Argv) {
t.Errorf("command after -- = %q, want %q", args[separator+1:], spec.Argv)
}
for _, writable := range writableMounts(args) {
if writable != "/dev/null" {
t.Errorf("unexpected writable bind mount %q", writable)
}
}
}
func writableMounts(args []string) []string {
var mounts []string
for index, arg := range args {
if arg == "--bindmount" && index+1 < len(args) {
mounts = append(mounts, args[index+1])
}
}
return mounts
}
func TestSeccompPolicyKillsNamespaceAndDebugSyscalls(t *testing.T) {
t.Parallel()
policy := seccompPolicy()
for _, fragment := range []string{"ptrace", "unshare", "setns", "mount", "bpf", "io_uring_setup", "clone(flags)", "ERRNO(38) { clone3 }", "socket(domain)", "USE runner DEFAULT ALLOW"} {
if !strings.Contains(policy, fragment) {
t.Errorf("policy misses %q", fragment)
}
}
}
func TestParseNsjailLog(t *testing.T) {
t.Parallel()
exited := parseNsjailLog([]byte("[I][2026] Executing '/usr/local/bin/python3'\n[I][2026] pid=12 ([STANDALONE MODE]) exited with status: 3, (PIDs left: 0)\n"))
if !exited.reported || exited.exitCode != 3 || exited.signal != 0 || exited.failure != "" {
t.Fatalf("exited report = %+v", exited)
}
signaled := parseNsjailLog([]byte("[W][2026][11] seccompViolation():291 pid=12 committed a syscall/seccomp violation\n[I][2026] pid=12 ([STANDALONE MODE]) terminated with signal: Bad system call (31), (PIDs left: 0)\n"))
if !signaled.reported || signaled.signal != 31 || signaled.exitCode != -1 || signaled.failure != "" {
t.Fatalf("signaled report = %+v", signaled)
}
failed := parseNsjailLog([]byte("[E][2026-10-10T23:37:27+0000][1] initNsInternal():361 chdir('/tmp'): No such file or directory\n[F][2026][1] runChild():506 Launching child process failed\n"))
if failed.failure != "initNsInternal():361 chdir('/tmp'): No such file or directory" {
t.Fatalf("failure = %q", failed.failure)
}
}
func TestApplyExitStatusSeparatesSandboxFailures(t *testing.T) {
t.Parallel()
var result Result
if err := applyExitStatus(&result, nsjailReport{failure: "execve failed", reported: true, signal: 9}, nil); err == nil {
t.Fatal("a launch failure must be an error")
}
stopped := Result{Termination: TerminationWallTime}
if err := applyExitStatus(&stopped, nsjailReport{}, nil); err != nil || stopped.Signal != signalKill {
t.Fatalf("stopped run = %+v, %v; want SIGKILL without an error", stopped, err)
}
}
func TestReadersBoundWhatTheyKeep(t *testing.T) {
t.Parallel()
exceeded := 0
kept := readLimited(bytes.NewReader(bytes.Repeat([]byte("a"), 100_000)), 10, func() { exceeded++ })
if len(kept) != 10 || exceeded != 1 {
t.Fatalf("readLimited kept %d bytes and reported %d times", len(kept), exceeded)
}
tail := readTail(strings.NewReader(strings.Repeat("x", 100_000)+"END"), 8)
if string(tail) != "xxxxxEND" {
t.Fatalf("readTail = %q", tail)
}
}
func TestCgroupStatsAndTermination(t *testing.T) {
t.Parallel()
dir := t.TempDir()
files := map[string]string{
"cpu.stat": "usage_usec 1500000\nuser_usec 1400000\n",
"memory.events": "low 0\nhigh 0\nmax 4\noom 1\noom_kill 1\noom_group_kill 0\n",
"pids.events": "max 0\n",
}
for name, content := range files {
if err := os.WriteFile(filepath.Join(dir, name), []byte(content), 0o600); err != nil {
t.Fatalf("write %s: %v", name, err)
}
}
stats, err := (&runCgroup{path: dir}).stats()
if err != nil {
t.Fatalf("stats: %v", err)
}
if stats.cpuUsage != 1500*time.Millisecond || stats.oomKills != 1 || stats.pidsLimits != 0 {
t.Fatalf("stats = %+v", stats)
}
limits := Limits{CPUTime: time.Second}
if got := terminationFromStats(stats, limits); got != TerminationMemory {
t.Fatalf("termination = %q, want memory before CPU time", got)
}
if got := terminationFromStats(cgroupStats{pidsLimits: 1}, limits); got != TerminationProcesses {
t.Fatalf("termination = %q, want processes", got)
}
if got := terminationFromStats(cgroupStats{cpuUsage: 2 * time.Second}, limits); got != TerminationCPUTime {
t.Fatalf("termination = %q, want cpu_time", got)
}
}
func TestBoxIsReadOnlyAndRemovable(t *testing.T) {
t.Parallel()
root := t.TempDir()
box, err := CreateBox(root, "main.py", []byte("print(1)"))
if err != nil {
t.Fatalf("CreateBox: %v", err)
}
info, err := os.Stat(filepath.Join(box.Dir(), "main.py"))
if err != nil || info.Mode().Perm() != boxFileMode {
t.Fatalf("source file mode = %v, %v", info.Mode(), err)
}
if err := box.Remove(); err != nil {
t.Fatalf("Remove: %v", err)
}
if entries, err := os.ReadDir(root); err != nil || len(entries) != 0 {
t.Fatalf("root after Remove = %v, %v", entries, err)
}
for _, name := range []string{"", "../main.py", ".hidden", "dir/main.py"} {
if _, err := CreateBox(root, name, nil); err == nil {
t.Errorf("CreateBox accepted file name %q", name)
}
}
}
+62
View File
@@ -0,0 +1,62 @@
package sandbox
import (
"runtime"
"strconv"
"strings"
)
// Linux constants used by the seccomp policy.
const (
afUnix = 1
// cloneNamespaceFlags is CLONE_NEWNS | CLONE_NEWCGROUP | CLONE_NEWUTS |
// CLONE_NEWIPC | CLONE_NEWUSER | CLONE_NEWPID | CLONE_NEWNET.
cloneNamespaceFlags = "0x7e020000"
errnoENOSYS = "38"
errnoEAFNOSUPPORT = "97"
)
// killedSyscalls end the whole process with SIGSYS. An ordinary program
// never needs them; they open kernel attack surface or would let the program
// observe or change the jail: debugging other processes, mounts and
// namespaces, keyrings, eBPF, perf, userfaultfd, io_uring, kernel modules,
// and host clock, name, and swap administration.
var killedSyscalls = []string{
"acct", "add_key", "adjtimex", "bpf", "chroot", "clock_settime",
"delete_module", "finit_module", "fsconfig", "fsmount", "fsopen", "fspick",
"init_module", "io_uring_enter", "io_uring_register", "io_uring_setup",
"kexec_file_load", "kexec_load", "keyctl", "mount", "mount_setattr",
"move_mount", "name_to_handle_at", "open_by_handle_at", "open_tree",
"perf_event_open", "pivot_root", "process_vm_readv", "process_vm_writev",
"ptrace", "quotactl", "reboot", "request_key", "sethostname",
"setdomainname", "setns", "settimeofday", "swapoff", "swapon", "syslog",
"unshare", "userfaultfd",
}
// seccompPolicy returns the kafel policy for the build architecture.
//
// It is a deny list on top of the namespaces, the dropped capabilities, and
// no_new_privs: the program keeps the syscalls an interpreter or a compiled
// program needs, while namespace creation through clone is killed, clone3 is
// reported as missing so that libc falls back to the filtered clone, and
// sockets other than AF_UNIX fail with EAFNOSUPPORT.
func seccompPolicy() string {
killed := append([]string{umountSyscall()}, killedSyscalls...)
var policy strings.Builder
policy.WriteString("POLICY runner {\n")
policy.WriteString(" KILL_PROCESS {\n ")
policy.WriteString(strings.Join(killed, ",\n "))
policy.WriteString(",\n clone(flags) { (flags & " + cloneNamespaceFlags + ") != 0 }\n },\n")
policy.WriteString(" ERRNO(" + errnoENOSYS + ") { clone3 },\n")
policy.WriteString(" ERRNO(" + errnoEAFNOSUPPORT + ") { socket(domain) { domain != " + strconv.Itoa(afUnix) + " } }\n")
policy.WriteString("}\nUSE runner DEFAULT ALLOW\n")
return policy.String()
}
// umountSyscall returns the kafel name of umount2 for the architecture.
func umountSyscall() string {
if runtime.GOARCH == "arm64" {
return "umount"
}
return "umount2"
}
+84
View File
@@ -0,0 +1,84 @@
package sandbox
import (
"errors"
"fmt"
"os"
"path/filepath"
"strings"
)
const (
// The jailed user only reads and traverses the box; it owns nothing.
boxDirMode = 0o555
boxFileMode = 0o444
// ownerOnlyMode lets the supervisor delete the box again.
ownerOnlyMode = 0o700
// workRootMode lets nsjail traverse to a box without listing the root:
// inside its user namespace host root's DAC override does not apply.
workRootMode = 0o711
boxPrefix = "run-"
)
// Box is the host directory with the files of one run. It is mounted
// read-only into every jail of the run and removed with Remove.
type Box struct {
dir string
}
// Dir returns the host path of the box.
func (b *Box) Dir() string {
return b.dir
}
// CreateBox creates a box under root with one file.
func CreateBox(root, fileName string, content []byte) (*Box, error) {
if fileName == "" || fileName != filepath.Base(fileName) || strings.HasPrefix(fileName, ".") {
return nil, fmt.Errorf("sandbox.CreateBox - invalid file name %q", fileName)
}
dir, err := os.MkdirTemp(root, boxPrefix)
if err != nil {
return nil, fmt.Errorf("sandbox.CreateBox - create: %w", err)
}
box := &Box{dir: dir}
if err := os.WriteFile(filepath.Join(dir, fileName), content, boxFileMode); err != nil {
return nil, errors.Join(fmt.Errorf("sandbox.CreateBox - write: %w", err), box.Remove())
}
if err := os.Chmod(dir, boxDirMode); err != nil {
return nil, errors.Join(fmt.Errorf("sandbox.CreateBox - chmod: %w", err), box.Remove())
}
return box, nil
}
// Remove deletes the box and its files.
func (b *Box) Remove() error {
if err := os.Chmod(b.dir, ownerOnlyMode); err != nil && !errors.Is(err, os.ErrNotExist) {
return fmt.Errorf("sandbox.Box.Remove - chmod: %w", err)
}
if err := os.RemoveAll(b.dir); err != nil {
return fmt.Errorf("sandbox.Box.Remove - remove: %w", err)
}
return nil
}
// emptyWorkRoot removes every entry of root, for example boxes of a process
// that crashed, and creates root when it is missing.
func emptyWorkRoot(root string) error {
if err := os.MkdirAll(root, workRootMode); err != nil {
return fmt.Errorf("sandbox.emptyWorkRoot - create: %w", err)
}
if err := os.Chmod(root, workRootMode); err != nil {
return fmt.Errorf("sandbox.emptyWorkRoot - chmod: %w", err)
}
entries, err := os.ReadDir(root)
if err != nil {
return fmt.Errorf("sandbox.emptyWorkRoot - list: %w", err)
}
for _, entry := range entries {
box := &Box{dir: filepath.Join(root, entry.Name())}
if err := box.Remove(); err != nil {
return err
}
}
return nil
}