386 lines
11 KiB
Go
386 lines
11 KiB
Go
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 directory of one program; the sandbox user owns its
|
|
// build output.
|
|
func (e *Executor) NewBox(fileName string, content []byte) (*Box, error) {
|
|
return CreateBox(e.cfg.WorkRoot, fileName, content, Owner{UID: e.cfg.SandboxUID, GID: e.cfg.SandboxGID})
|
|
}
|
|
|
|
// 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)
|
|
}
|