diff --git a/docs/en/TESTING.md b/docs/en/TESTING.md index c73c120..397a2fb 100644 --- a/docs/en/TESTING.md +++ b/docs/en/TESTING.md @@ -607,8 +607,8 @@ Then `test-sandbox` runs the A16 suite (see below). | files_and_secrets | `/etc/passwd`, `/etc/shadow`, `/run/secrets` and the API token, runner files, `/proc`, `/sys`, `/dev/mem`, environment variables with `RUNNER`, `TOKEN`, or `SECRET`, writes to the root, the source, and `/out` | nothing is visible or writable except `/tmp` | | privileges | setuid, setgid, chown to root, raising an rlimit | refused; uid and gid are not 0 | | escape | ptrace, mounting a fresh procfs, unsharing a user namespace | the process is killed by seccomp (SIGSYS, `runtime_error`) | -| processes | fork bomb, and a thread bomb in Go | the cgroup process limit (`runtime_error`, limit `processes`) | -| memory | unbounded allocation | the cgroup memory limit (`memory_limit_exceeded`) | +| processes | fork bomb, and a thread bomb in Go (256 goroutines blocked in system calls, so the stacks stay far below the memory limit) | the cgroup process limit (`runtime_error`, limit `processes`) | +| memory | unbounded allocation, and in Go unbounded goroutines parked on a channel (no new threads) | the cgroup memory limit (`memory_limit_exceeded`) | | disk | one large file and filling `/tmp` | refused by the file size limit and the tmpfs size | | output | endless output | the output limit (`output_limit_exceeded`) | | timeout | a busy loop that ignores signals, a sleep, a detached daemon in its own session | the CPU limit, the wall-clock limit; the daemon dies with the PID namespace | diff --git a/docs/ru/TESTING.md b/docs/ru/TESTING.md index 62fd1b2..a871bf0 100644 --- a/docs/ru/TESTING.md +++ b/docs/ru/TESTING.md @@ -607,8 +607,8 @@ Vitest работает в Node без DOM, поэтому ограничени | files_and_secrets | `/etc/passwd`, `/etc/shadow`, `/run/secrets` и токен API, файлы runner, `/proc`, `/sys`, `/dev/mem`, переменные окружения с `RUNNER`, `TOKEN` или `SECRET`, запись в корень, исходник и `/out` | ничего не видно и не записывается, кроме `/tmp` | | privileges | setuid, setgid, chown на root, повышение rlimit | отказ, uid и gid не 0 | | escape | ptrace, mount нового procfs, unshare user namespace | процесс убит seccomp (SIGSYS, `runtime_error`) | -| processes | fork bomb, на Go также thread bomb | лимит процессов cgroup (`runtime_error`, limit `processes`) | -| memory | бесконечное выделение памяти | лимит памяти cgroup (`memory_limit_exceeded`) | +| processes | fork bomb, на Go также thread bomb (256 горутин, заблокированных в системных вызовах, поэтому стеки остаются намного ниже лимита памяти) | лимит процессов cgroup (`runtime_error`, limit `processes`) | +| memory | бесконечное выделение памяти, на Go также бесконечные горутины, ожидающие на канале (без новых потоков) | лимит памяти cgroup (`memory_limit_exceeded`) | | disk | один большой файл и заполнение `/tmp` | отказ лимита размера файла и размера tmpfs | | output | бесконечный вывод | лимит вывода (`output_limit_exceeded`) | | timeout | занятый цикл с игнорированием сигналов, сон, отсоединенный демон в своей сессии | лимит CPU, лимит стены; демон погибает вместе с PID namespace | diff --git a/runner/internal/isolationtest/isolation_test.go b/runner/internal/isolationtest/isolation_test.go index 9d7dfce..b6076b9 100644 --- a/runner/internal/isolationtest/isolation_test.go +++ b/runner/internal/isolationtest/isolation_test.go @@ -32,7 +32,11 @@ const ( reportSchema = "lincodex.runner-a16-report/v1" // weakenedProcesses replaces the process limit in the weakened config. weakenedProcesses = 4096 - apkDatabase = "/lib/apk/db/installed" + // leftoverGrace bounds the wait of the weakened-limit check for killed + // sandbox processes to finish exiting; leftoverPoll is its poll step. + leftoverGrace = 2 * time.Second + leftoverPoll = 20 * time.Millisecond + apkDatabase = "/lib/apk/db/installed" ) // runnerVersion is set with -ldflags -X by the Make targets. @@ -301,8 +305,10 @@ func TestA16WeakenedProcessLimitIsDetected(t *testing.T) { } // Under the weakened limit an OOM kill may hit nsjail itself and // leave a dead, unreaped process to the container's PID 1; only live - // processes count here. - if leftover := nothingLeft(executor, cfg.SandboxUID, nil); leftover != "" { + // processes count here. A process killed with its cgroup can still + // be exiting when the run returns, so the check waits for the + // kernel to finish it before it reports a leftover. + if leftover := nothingLeftWithin(executor, cfg.SandboxUID, leftoverGrace); leftover != "" { t.Fatalf("%s: %s", tc.Name, leftover) } } @@ -311,6 +317,19 @@ func TestA16WeakenedProcessLimitIsDetected(t *testing.T) { } } +// nothingLeftWithin repeats the live-process check of nothingLeft until it +// passes or the grace period ends, and returns the last finding. +func nothingLeftWithin(executor *sandbox.Executor, uid int, grace time.Duration) string { + deadline := time.Now().Add(grace) + for { + leftover := nothingLeft(executor, uid, nil) + if leftover == "" || time.Now().After(deadline) { + return leftover + } + time.Sleep(leftoverPoll) + } +} + // nothingLeft reports run directories, run cgroups, or sandbox user // processes that outlived a run, or an empty string. With a baseline of // earlier zombies, a new exited but unreaped process also counts: the suite diff --git a/runner/internal/sandbox/sandbox_test.go b/runner/internal/sandbox/sandbox_test.go index 86d9c98..68ab16b 100644 --- a/runner/internal/sandbox/sandbox_test.go +++ b/runner/internal/sandbox/sandbox_test.go @@ -126,6 +126,11 @@ func TestSeccompPolicyKillsNamespaceAndDebugSyscalls(t *testing.T) { t.Errorf("policy misses %q", fragment) } } + // Kafel knows umount2 only as "umount" on amd64 and arm64; the name + // umount2 makes nsjail reject the whole policy, so every run would fail. + if !strings.Contains(policy, "umount,") || strings.Contains(policy, "umount2") { + t.Errorf("policy must kill umount2 under its kafel name umount:\n%s", policy) + } } func TestParseNsjailLog(t *testing.T) { diff --git a/runner/internal/sandbox/seccomp.go b/runner/internal/sandbox/seccomp.go index 05899d3..25b16d3 100644 --- a/runner/internal/sandbox/seccomp.go +++ b/runner/internal/sandbox/seccomp.go @@ -1,7 +1,6 @@ package sandbox import ( - "runtime" "strconv" "strings" ) @@ -20,7 +19,9 @@ const ( // 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. +// and host clock, name, and swap administration. Kafel names umount2 (166 on +// amd64, 39 on arm64) "umount" on both architectures and rejects the name +// umount2, so "umount" kills the only unmount syscall these kernels have. var killedSyscalls = []string{ "acct", "add_key", "adjtimex", "bpf", "chroot", "clock_settime", "delete_module", "finit_module", "fsconfig", "fsmount", "fsopen", "fspick", @@ -30,10 +31,11 @@ var killedSyscalls = []string{ "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", + "umount", "unshare", "userfaultfd", } -// seccompPolicy returns the kafel policy for the build architecture. +// seccompPolicy returns the kafel policy; nsjail compiles it for the +// architecture it runs on. // // 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 @@ -41,22 +43,13 @@ var killedSyscalls = []string{ // 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(strings.Join(killedSyscalls, ",\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" -} diff --git a/runner/testdata/hostile/go/goroutine_bomb.go b/runner/testdata/hostile/go/goroutine_bomb.go new file mode 100644 index 0000000..4a8db76 --- /dev/null +++ b/runner/testdata/hostile/go/goroutine_bomb.go @@ -0,0 +1,10 @@ +// Goroutine bomb: unbounded goroutines parked on a channel need no new OS +// threads, so only their stacks grow; the cgroup memory limit must stop it. +package main + +func main() { + block := make(chan struct{}) + for { + go func() { <-block }() + } +} diff --git a/runner/testdata/hostile/go/thread_bomb.go b/runner/testdata/hostile/go/thread_bomb.go index 58278f5..d852511 100644 --- a/runner/testdata/hostile/go/thread_bomb.go +++ b/runner/testdata/hostile/go/thread_bomb.go @@ -1,5 +1,7 @@ -// Thread bomb: goroutines blocked in system calls force the runtime to -// create threads; the cgroup process limit must stop it. +// Thread bomb: 256 goroutines blocked in system calls force the runtime to +// create an OS thread for each; the cgroup process limit must stop it. The +// goroutine count is bounded so that their stacks stay far below the memory +// limit and the process limit is always the one that stops the program. package main import ( @@ -7,15 +9,18 @@ import ( "syscall" ) +const blockedGoroutines = 256 + func main() { var fds [2]int if err := syscall.Pipe(fds[:]); err != nil { os.Exit(2) } - for { + for range blockedGoroutines { go func() { buffer := make([]byte, 1) _, _ = syscall.Read(fds[0], buffer) }() } + select {} } diff --git a/runner/testdata/hostile/manifest.json b/runner/testdata/hostile/manifest.json index caaf996..740110a 100644 --- a/runner/testdata/hostile/manifest.json +++ b/runner/testdata/hostile/manifest.json @@ -325,6 +325,18 @@ "limit": "memory" } }, + { + "name": "go_goroutine_bomb", + "category": "memory", + "language": "go", + "source": "go/goroutine_bomb.go", + "input": "", + "expected_output": "", + "expect": { + "outcome": "memory_limit_exceeded", + "limit": "memory" + } + }, { "name": "go_disk_fill", "category": "disk",