test(runner): verify sandbox isolation with a hostile program suite

This commit is contained in:
shira committed 2026-10-11 08:59:59 +03:00
1 parent afee564bf4
commit e858280d91
38 files changed
+1359 -168

No files matched your search

+1
View File
@@ -9,3 +9,4 @@
*.cover
*.pprof
coverage.*
/.reports/
+6 -2
View File
@@ -14,7 +14,10 @@ COPY go.mod go.sum ./
RUN go mod download
COPY . ./
RUN CGO_ENABLED=0 GOOS=linux go test -c -tags sandbox -o /out/isolation.test ./internal/isolationtest \
ARG RUNNER_VERSION=unknown
RUN CGO_ENABLED=0 GOOS=linux go test -c -tags sandbox \
-ldflags "-X lincodex/runner/internal/isolationtest.runnerVersion=${RUNNER_VERSION}" \
-o /out/isolation.test ./internal/isolationtest \
&& CGO_ENABLED=0 GOOS=linux go test -c -tags sandbox -o /out/judge.test ./internal/judgetest
FROM ${RUNNER_IMAGE}
@@ -26,4 +29,5 @@ ENV RUNNER_HOSTILE_FIXTURES=/opt/lincodex-runner-tests/testdata/hostile \
RUNNER_JUDGE_FIXTURES=/opt/lincodex-runner-tests/testdata/judge
HEALTHCHECK NONE
ENTRYPOINT ["/bin/sh", "-c", "set -e; for suite in judge isolation; do /opt/lincodex-runner-tests/$suite.test -test.v -test.count=1; done"]
# With arguments, only the A16 suite runs with them; without, both suites run.
ENTRYPOINT ["/bin/sh", "-c", "set -e; if [ \"$#\" -gt 0 ]; then exec /opt/lincodex-runner-tests/isolation.test -test.v -test.count=1 \"$@\"; fi; for suite in judge isolation; do /opt/lincodex-runner-tests/$suite.test -test.v -test.count=1; done", "sandbox-test"]
+40 -8
View File
@@ -13,6 +13,21 @@ LINT_GOOS ?= linux
GOLANGCI_LINT := bin/golangci-lint
RUNNER_IMAGE ?= lincodex-runner-dev:local
SANDBOX_TEST_IMAGE ?= lincodex-runner-sandbox-test:local
# Recorded in the A16 report; reading Git state changes nothing.
RUNNER_VERSION ?= $(shell git describe --always --dirty --abbrev=12 2>/dev/null || echo unknown)
# A16 report directory; .gitignore keeps reports out of Git.
A16_REPORT_DIR ?= $(CURDIR)/.reports
# Extra RUNNER_* settings for the A16 suite, for example
# A16_ENV="RUNNER_SANDBOX_MAX_PROCESSES=4096" to see a weakened limit fail.
A16_ENV ?=
# Architecture of the A16 bundle for a runner host.
A16_GOARCH ?= amd64
A16_BUNDLE_DIR := bin/a16-bundle
# DEVELOPMENT ONLY: --privileged gives nsjail namespaces and a writable
# cgroup v2 tree inside the Docker Desktop VM; exec on the work tmpfs lets
# built Go solutions run. Production never uses these flags.
SANDBOX_RUN := $(DOCKER) run --rm --privileged --cgroupns=private --network=none \
--tmpfs /var/lib/lincodex-runner/work:size=128m,mode=0711,exec
OGEN_ARGS := -config codegen/ogen.yml --package api --clean ../api/runner/openapi.bundle.yml
##@ Build
@@ -82,15 +97,32 @@ test: ## Run unit tests with the race detector; they need no sandbox
image: ## Build the runner image for local development
$(DOCKER) build --file Dockerfile --tag "$(RUNNER_IMAGE)" .
# DEVELOPMENT ONLY: --privileged gives nsjail namespaces and a writable
# cgroup v2 tree inside the Docker Desktop VM. Production runs the runner on
# its dedicated VM and never uses this target.
.PHONY: sandbox-test-image
sandbox-test-image: image
$(DOCKER) build --file Dockerfile.sandbox-test --build-arg RUNNER_IMAGE="$(RUNNER_IMAGE)" --build-arg RUNNER_VERSION="$(RUNNER_VERSION)" --tag "$(SANDBOX_TEST_IMAGE)" .
.PHONY: test-sandbox
test-sandbox: image ## Run the hostile-program isolation tests in a privileged dev container
$(DOCKER) build --file Dockerfile.sandbox-test --build-arg RUNNER_IMAGE="$(RUNNER_IMAGE)" --tag "$(SANDBOX_TEST_IMAGE)" .
$(DOCKER) run --rm --privileged --cgroupns=private --network=none \
--tmpfs /var/lib/lincodex-runner/work:size=128m,mode=0711,exec \
"$(SANDBOX_TEST_IMAGE)"
test-sandbox: sandbox-test-image ## Run reference solutions and the A16 suite in a privileged dev container
$(SANDBOX_RUN) "$(SANDBOX_TEST_IMAGE)"
.PHONY: test-a16
test-a16: sandbox-test-image ## Run only the A16 hostile-program suite locally and write a report to .reports/
@mkdir -p "$(A16_REPORT_DIR)"
$(SANDBOX_RUN) $(foreach setting,$(A16_ENV),--env $(setting)) \
--volume "$(A16_REPORT_DIR):/reports" \
--env RUNNER_A16_REPORT=/reports/a16-$$(date -u +%Y%m%dT%H%M%SZ).json \
"$(SANDBOX_TEST_IMAGE)" -test.run '^TestA16'
.PHONY: a16-bundle
a16-bundle: ## Build the A16 suite for a runner host (A16_GOARCH, default amd64) into bin/a16-bundle.tar.gz
rm -rf "$(A16_BUNDLE_DIR)"
mkdir -p "$(A16_BUNDLE_DIR)/testdata"
CGO_ENABLED=0 GOOS=linux GOARCH=$(A16_GOARCH) $(GO) test -c -tags sandbox \
-ldflags "-X lincodex/runner/internal/isolationtest.runnerVersion=$(RUNNER_VERSION)" \
-o "$(A16_BUNDLE_DIR)/isolation.test" ./internal/isolationtest
cp -R testdata/hostile "$(A16_BUNDLE_DIR)/testdata/hostile"
cp scripts/run-a16.sh "$(A16_BUNDLE_DIR)/run-a16.sh"
tar -C bin -czf bin/a16-bundle.tar.gz a16-bundle
.PHONY: check
check: ## Run formatting, build, unit, generated drift, and lint checks
+2 -2
View File
@@ -11,8 +11,8 @@ A separate Go service that runs untrusted candidate code in nsjail and checks it
- `internal/judgetest/` and `testdata/judge/` are reference Python and Go solutions with their expected group results.
- `internal/jobs/` keeps runs in memory, makes them idempotent by run ID, and bounds concurrent runs.
- `internal/server/` is the HTTP API on the generated ogen server (`internal/api/`, from `codegen/ogen.yml`).
- `internal/isolationtest/` and `testdata/hostile/` are the isolation tests and the shared hostile programs.
- `internal/isolationtest/`, `testdata/hostile/`, and `scripts/run-a16.sh` are the A16 hostile-program suite in Python and Go, its report, and its run on the runner host.
From the repository root, `make -C runner check` runs formatting, build, unit tests, the generated code check, and lint; `make -C runner test-sandbox` builds the image and runs the isolation tests in a privileged dev container. Local start: `make -C deploy runner-dev-up` (development only).
From the repository root, `make -C runner check` runs formatting, build, unit tests, the generated code check, and lint; `make -C runner test-sandbox` builds the image and runs the reference solutions and the A16 suite in a privileged dev container; `make -C runner test-a16` runs only the A16 suite with a report, and `make -C runner a16-bundle` builds it for the runner host. Local start: `make -C deploy runner-dev-up` (development only).
Production: the service runs only in the dedicated runner VM, never on the core host. More: [deployment](../docs/en/DEPLOY.md#code-runner), [architecture](../docs/en/ARCHITECTURE.md#code-runner), and [checks](../docs/en/TESTING.md#code-runner-tests).
+2 -2
View File
@@ -11,8 +11,8 @@
- `internal/judgetest/` и `testdata/judge/` - эталонные решения на Python и Go с ожидаемыми результатами групп.
- `internal/jobs/` - прогоны в памяти, идемпотентность по run ID и лимит параллельных прогонов.
- `internal/server/` - HTTP API на сгенерированном ogen-сервере (`internal/api/`, из `codegen/ogen.yml`).
- `internal/isolationtest/` и `testdata/hostile/` - тесты изоляции и общие враждебные программы.
- `internal/isolationtest/`, `testdata/hostile/` и `scripts/run-a16.sh` - набор враждебных программ A16 на Python и Go, его отчет и запуск на хосте исполнителя.
Из корня: `make -C runner check` запускает форматирование, сборку, unit-тесты, проверку generated-кода и lint; `make -C runner test-sandbox` собирает образ и запускает тесты изоляции в привилегированном dev-контейнере. Локальный запуск: `make -C deploy runner-dev-up` (только для разработки).
Из корня: `make -C runner check` запускает форматирование, сборку, unit-тесты, проверку generated-кода и lint; `make -C runner test-sandbox` собирает образ и запускает эталонные решения и набор A16 в привилегированном dev-контейнере; `make -C runner test-a16` запускает только набор A16 с отчетом, а `make -C runner a16-bundle` собирает его для хоста исполнителя. Локальный запуск: `make -C deploy runner-dev-up` (только для разработки).
Production: сервис работает только в отдельной VM исполнителя, никогда на core-хосте. Подробнее: [развертывание](../docs/ru/DEPLOY.md#исполнитель-кода), [архитектура](../docs/ru/ARCHITECTURE.md#исполнитель-кода) и [проверки](../docs/ru/TESTING.md#тесты-исполнителя-кода).
+350 -89
View File
@@ -4,13 +4,16 @@ package isolationtest
import (
"bufio"
"bytes"
"encoding/json"
"fmt"
"log/slog"
"os"
"path/filepath"
"runtime"
"strconv"
"strings"
"syscall"
"testing"
"time"
@@ -23,27 +26,23 @@ import (
const (
fixturesEnv = "RUNNER_HOSTILE_FIXTURES"
reportEnv = "RUNNER_A16_REPORT"
defaultFixtures = "../../testdata/hostile"
// seriesRepeats runs the whole manifest this many times before the final
// cleanup check.
seriesRepeats = 2
manifestSchema = "lincodex.runner-hostile-fixtures/v2"
reportSchema = "lincodex.runner-a16-report/v1"
// weakenedProcesses replaces the process limit in the weakened config.
weakenedProcesses = 4096
apkDatabase = "/lib/apk/db/installed"
)
// runnerVersion is set with -ldflags -X by the Make targets.
var runnerVersion = "unknown"
type manifest struct {
Schema string `json:"schema"`
DefaultLimits limits `json:"default_limits"`
Cases []struct {
Name string `json:"name"`
Language string `json:"language"`
Source string `json:"source"`
Input string `json:"input"`
ExpectedOutput string `json:"expected_output"`
Limits *limits `json:"limits"`
Expect struct {
Outcome judge.Outcome `json:"outcome"`
Limit sandbox.Termination `json:"limit"`
} `json:"expect"`
} `json:"cases"`
Schema string `json:"schema"`
DefaultLimits limits `json:"default_limits"`
Categories map[string]string `json:"categories"`
Cases []hostileCase `json:"cases"`
}
type limits struct {
@@ -52,6 +51,61 @@ type limits struct {
OutputLimitKB int64 `json:"output_limit_kb"`
}
type hostileCase struct {
Name string `json:"name"`
Category string `json:"category"`
Language string `json:"language"`
Source string `json:"source"`
Input string `json:"input"`
ExpectedOutput string `json:"expected_output"`
Expect expect `json:"expect"`
}
type expect struct {
Outcome judge.Outcome `json:"outcome"`
Limit sandbox.Termination `json:"limit"`
Signal int `json:"signal,omitempty"`
}
type observed struct {
Outcome judge.Outcome `json:"outcome"`
Limit sandbox.Termination `json:"limit"`
Signal int `json:"signal,omitempty"`
ExitCode *int `json:"exit_code,omitempty"`
CPUMs int64 `json:"cpu_ms"`
WallMs int64 `json:"wall_ms"`
MemoryKB int64 `json:"memory_kb"`
}
type caseReport struct {
Name string `json:"name"`
Category string `json:"category"`
Language string `json:"language"`
Expected expect `json:"expected"`
Observed observed `json:"observed"`
Passed bool `json:"passed"`
Problem string `json:"problem,omitempty"`
}
type report struct {
Schema string `json:"schema"`
GeneratedAt string `json:"generated_at"`
RunnerVersion string `json:"runner_version"`
Kernel map[string]string `json:"kernel"`
CgroupControllers string `json:"cgroup_controllers"`
NsjailPackage string `json:"nsjail_package,omitempty"`
Profile sandbox.Profile `json:"profile"`
Limits limits `json:"limits"`
Categories map[string]string `json:"categories"`
Cases []caseReport `json:"cases"`
NothingLeftAfterRuns bool `json:"nothing_left_after_runs"`
Passed int `json:"passed"`
Failed int `json:"failed"`
Verdict string `json:"verdict"`
PracticeMayBeEnabled bool `json:"practice_may_be_enabled"`
VerdictRule string `json:"verdict_rule"`
}
func fixturesDir() string {
if dir := os.Getenv(fixturesEnv); dir != "" {
return dir
@@ -69,21 +123,31 @@ func loadManifest(t *testing.T) manifest {
if err := json.Unmarshal(content, &loaded); err != nil {
t.Fatalf("decode manifest: %v", err)
}
if loaded.Schema != "lincodex.runner-hostile-fixtures/v1" || len(loaded.Cases) == 0 {
if loaded.Schema != manifestSchema || len(loaded.Cases) == 0 {
t.Fatalf("unexpected manifest %q with %d cases", loaded.Schema, len(loaded.Cases))
}
return loaded
}
// newRunner builds the sandbox from the production configuration path.
func newRunner(t *testing.T) (*sandbox.Executor, *judge.Judge) {
// loadConfig reads the runner configuration the way the service does, so
// the suite tests the deployed settings, including any RUNNER_* override.
func loadConfig(t *testing.T) config.Config {
t.Helper()
t.Setenv("RUNNER_API_TOKEN", strings.Repeat("t", config.MinTokenLength))
t.Setenv("RUNNER_DEV_ALLOW_PLAINTEXT_HTTP", "true")
if os.Getenv("RUNNER_API_TOKEN") == "" && os.Getenv("RUNNER_API_TOKEN_FILE") == "" {
t.Setenv("RUNNER_API_TOKEN", strings.Repeat("t", config.MinTokenLength))
}
if os.Getenv("RUNNER_TLS_CERT_FILE") == "" {
t.Setenv("RUNNER_DEV_ALLOW_PLAINTEXT_HTTP", "true")
}
cfg, err := config.Load()
if err != nil {
t.Fatalf("config: %v", err)
}
return cfg
}
func newRunner(t *testing.T, cfg config.Config) (*sandbox.Executor, *judge.Judge) {
t.Helper()
executor, err := sandbox.New(app.SandboxConfig(cfg))
if err != nil {
t.Fatalf("sandbox: %v", err)
@@ -92,88 +156,199 @@ func newRunner(t *testing.T) (*sandbox.Executor, *judge.Judge) {
return executor, judge.New(executor, logger, app.Languages(cfg)...)
}
func TestHostileProgramsAreStoppedByTheRightLimit(t *testing.T) {
loaded := loadManifest(t)
executor, evaluator := newRunner(t)
func (m manifest) request(t *testing.T, tc hostileCase) judge.Request {
t.Helper()
source, err := os.ReadFile(filepath.Join(fixturesDir(), tc.Source))
if err != nil {
t.Fatalf("read %s: %v", tc.Source, err)
}
return judge.Request{
Language: tc.Language,
Source: string(source),
Limits: judge.Limits{
TimeLimit: time.Duration(m.DefaultLimits.TimeLimitMs) * time.Millisecond,
MemoryBytes: m.DefaultLimits.MemoryLimitMB << 20,
OutputBytes: m.DefaultLimits.OutputLimitKB << 10,
},
Groups: []judge.Group{{
ID: "public",
Visibility: judge.Public,
Checker: checker.Spec{Kind: checker.Exact},
Tests: []judge.Test{{ID: "t1", Input: tc.Input, ExpectedOutput: tc.ExpectedOutput}},
}},
}
}
for round := range seriesRepeats {
for _, tc := range loaded.Cases {
source, err := os.ReadFile(filepath.Join(fixturesDir(), tc.Source))
if err != nil {
t.Fatalf("read %s: %v", tc.Source, err)
}
caseLimits := loaded.DefaultLimits
if tc.Limits != nil {
caseLimits = *tc.Limits
}
request := judge.Request{
Language: tc.Language,
Source: string(source),
Limits: judge.Limits{
TimeLimit: time.Duration(caseLimits.TimeLimitMs) * time.Millisecond,
MemoryBytes: caseLimits.MemoryLimitMB << 20,
OutputBytes: caseLimits.OutputLimitKB << 10,
},
Groups: []judge.Group{{
ID: "public",
Visibility: judge.Public,
Checker: checker.Spec{Kind: checker.Exact},
Tests: []judge.Test{{ID: "t1", Input: tc.Input, ExpectedOutput: tc.ExpectedOutput}},
}},
}
result := evaluator.Run(t.Context(), request)
if result.Outcome != tc.Expect.Outcome {
t.Errorf("round %d %s: outcome %s, want %s (%s)", round, tc.Name, result.Outcome, tc.Expect.Outcome, describe(result))
continue
}
if tc.Expect.Outcome == judge.CompileError {
if result.Compile == nil || result.Compile.Diagnostic == "" {
t.Errorf("round %d %s: compile error without a diagnostic", round, tc.Name)
}
continue
}
test := result.Groups[0].Tests[0]
if test.Limit != tc.Expect.Limit {
t.Errorf("round %d %s: limit %q, want %q (%s)", round, tc.Name, test.Limit, tc.Expect.Limit, describe(result))
}
if test.CPUTime <= 0 || test.WallTime <= 0 || test.MemoryKB <= 0 {
t.Errorf("round %d %s: usage not recorded: cpu %v wall %v memory %d KiB", round, tc.Name, test.CPUTime, test.WallTime, test.MemoryKB)
}
t.Logf("round %d %-16s %-22s limit=%-9q cpu=%v wall=%v memory=%dKiB", round, tc.Name, test.Outcome, test.Limit, test.CPUTime, test.WallTime, test.MemoryKB)
assertNothingLeft(t, executor, tc.Name)
// evaluate runs one case and compares it with its expectation.
func evaluate(t *testing.T, evaluator *judge.Judge, m manifest, tc hostileCase) caseReport {
t.Helper()
result := evaluator.Run(t.Context(), m.request(t, tc))
entry := caseReport{Name: tc.Name, Category: tc.Category, Language: tc.Language, Expected: tc.Expect}
entry.Observed.Outcome = result.Outcome
var problems []string
if result.Outcome != tc.Expect.Outcome {
problems = append(problems, fmt.Sprintf("outcome %s, want %s", result.Outcome, tc.Expect.Outcome))
}
if len(result.Groups) == 1 && len(result.Groups[0].Tests) == 1 {
test := result.Groups[0].Tests[0]
entry.Observed = observed{
Outcome: result.Outcome,
Limit: test.Limit,
ExitCode: test.ExitCode,
CPUMs: test.CPUTime.Milliseconds(),
WallMs: test.WallTime.Milliseconds(),
MemoryKB: test.MemoryKB,
}
if test.Signal != nil {
entry.Observed.Signal = *test.Signal
}
if test.Limit != tc.Expect.Limit {
problems = append(problems, fmt.Sprintf("limit %q, want %q", test.Limit, tc.Expect.Limit))
}
if tc.Expect.Signal != 0 && entry.Observed.Signal != tc.Expect.Signal {
problems = append(problems, fmt.Sprintf("signal %d, want %d", entry.Observed.Signal, tc.Expect.Signal))
}
if result.Outcome != tc.Expect.Outcome && test.Diagnostic != "" {
problems = append(problems, "stderr: "+firstLine(test.Diagnostic))
}
} else if tc.Expect.Outcome != judge.CompileError {
problems = append(problems, "the test did not run")
}
entry.Passed = len(problems) == 0
entry.Problem = strings.Join(problems, "; ")
return entry
}
func TestA16HostileProgramsAreRefused(t *testing.T) {
loaded := loadManifest(t)
cfg := loadConfig(t)
executor, evaluator := newRunner(t, cfg)
result := report{
Schema: reportSchema,
GeneratedAt: time.Now().UTC().Format(time.RFC3339),
RunnerVersion: runnerVersion,
Kernel: kernel(),
Limits: loaded.DefaultLimits,
Categories: loaded.Categories,
NsjailPackage: apkPackageVersion("nsjail"),
VerdictRule: "Any failed case blocks enabling code practice.",
}
if controllers, err := os.ReadFile(filepath.Join(cfg.CgroupRoot, "cgroup.controllers")); err == nil {
result.CgroupControllers = strings.TrimSpace(string(controllers))
}
profile, err := executor.Profile(sandbox.Limits{
CPUTime: time.Duration(loaded.DefaultLimits.TimeLimitMs) * time.Millisecond,
WallTime: 2*time.Duration(loaded.DefaultLimits.TimeLimitMs)*time.Millisecond + 500*time.Millisecond,
MemoryBytes: loaded.DefaultLimits.MemoryLimitMB << 20,
OutputBytes: loaded.DefaultLimits.OutputLimitKB << 10,
})
if err != nil {
t.Fatalf("profile: %v", err)
}
result.Profile = profile
result.NothingLeftAfterRuns = true
for _, tc := range loaded.Cases {
_, zombiesBefore := userProcesses(cfg.SandboxUID)
zombiesBefore = append([]string{}, zombiesBefore...) // Non-nil: check zombies.
entry := evaluate(t, evaluator, loaded, tc)
if leftover := nothingLeft(executor, cfg.SandboxUID, zombiesBefore); leftover != "" {
entry.Passed = false
entry.Problem = strings.TrimPrefix(entry.Problem+"; "+leftover, "; ")
result.NothingLeftAfterRuns = false
}
if entry.Passed {
result.Passed++
} else {
result.Failed++
t.Errorf("%s (%s, %s): %s", tc.Name, tc.Category, tc.Language, entry.Problem)
}
t.Logf("%-22s %-17s %-8s %-22s limit=%-9q signal=%-2d cpu=%dms wall=%dms memory=%dKiB passed=%v",
tc.Name, tc.Category, tc.Language, entry.Observed.Outcome, entry.Observed.Limit, entry.Observed.Signal,
entry.Observed.CPUMs, entry.Observed.WallMs, entry.Observed.MemoryKB, entry.Passed)
result.Cases = append(result.Cases, entry)
}
result.Verdict = "fail"
if result.Failed == 0 && result.NothingLeftAfterRuns {
result.Verdict = "pass"
result.PracticeMayBeEnabled = true
}
t.Logf("A16 verdict: %s (%d passed, %d failed); practice may be enabled: %v", result.Verdict, result.Passed, result.Failed, result.PracticeMayBeEnabled)
writeReport(t, result)
}
// TestA16WeakenedProcessLimitIsDetected weakens one limit in a test copy of
// the configuration and checks that the cases guarding it fail, so a
// regression of that limit cannot pass the suite.
func TestA16WeakenedProcessLimitIsDetected(t *testing.T) {
loaded := loadManifest(t)
cfg := loadConfig(t)
cfg.MaxProcesses = weakenedProcesses
executor, evaluator := newRunner(t, cfg)
guarded := 0
for _, tc := range loaded.Cases {
if tc.Category != "processes" {
continue
}
guarded++
entry := evaluate(t, evaluator, loaded, tc)
t.Logf("weakened %-16s observed %s limit=%q: detected=%v", tc.Name, entry.Observed.Outcome, entry.Observed.Limit, !entry.Passed)
if entry.Passed {
t.Errorf("%s still passes with a process limit of %d", tc.Name, weakenedProcesses)
}
// 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 != "" {
t.Fatalf("%s: %s", tc.Name, leftover)
}
}
assertNothingLeft(t, executor, "series")
if guarded == 0 {
t.Fatal("the manifest has no process limit case")
}
}
func describe(result judge.Result) string {
return fmt.Sprintf("%+v", result)
}
// assertNothingLeft checks that the work directory and the run cgroups are
// gone and that no process of the sandbox user is alive.
func assertNothingLeft(t *testing.T, executor *sandbox.Executor, label string) {
t.Helper()
// 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
// runs without an init, so it proves that nsjail reaps every jailed
// process. A nil baseline checks live processes only.
func nothingLeft(executor *sandbox.Executor, uid int, zombiesBefore []string) string {
boxes, cgroups, err := executor.Leftovers()
if err != nil {
t.Fatalf("%s: leftovers: %v", label, err)
return "leftovers: " + err.Error()
}
if len(boxes) != 0 || len(cgroups) != 0 {
t.Fatalf("%s: left boxes %q and cgroups %q", label, boxes, cgroups)
return fmt.Sprintf("left boxes %q and cgroups %q", boxes, cgroups)
}
if pids := sandboxUserProcesses(t, config.DefaultSandboxUID); len(pids) != 0 {
t.Fatalf("%s: sandbox user processes still alive: %v", label, pids)
live, dead := userProcesses(uid)
if len(live) != 0 {
return fmt.Sprintf("sandbox user processes alive: %v", live)
}
if zombiesBefore != nil {
var added []string
for _, pid := range dead {
if !containsLine(zombiesBefore, pid) {
added = append(added, pid)
}
}
if len(added) != 0 {
return fmt.Sprintf("unreaped sandbox user processes: %v", added)
}
}
return ""
}
func sandboxUserProcesses(t *testing.T, uid int) []string {
t.Helper()
// userProcesses lists processes of uid, split into live and zombie ones.
func userProcesses(uid int) (live, zombies []string) {
entries, err := os.ReadDir("/proc")
if err != nil {
t.Fatalf("list /proc: %v", err)
return []string{"cannot list /proc: " + err.Error()}, nil
}
wanted := "\t" + strconv.Itoa(uid) + "\t"
var pids []string
for _, entry := range entries {
if !entry.IsDir() || strings.Trim(entry.Name(), "0123456789") != "" {
continue
@@ -182,14 +357,100 @@ func sandboxUserProcesses(t *testing.T, uid int) []string {
if err != nil {
continue // The process exited meanwhile.
}
zombie, owned := false, false
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := scanner.Text()
if strings.HasPrefix(line, "State:") && strings.Contains(line, "zombie") {
zombie = true
}
if strings.HasPrefix(line, "Uid:") && strings.Contains(line+"\t", wanted) {
pids = append(pids, entry.Name())
owned = true
}
}
_ = file.Close()
switch {
case owned && zombie:
zombies = append(zombies, entry.Name())
case owned:
live = append(live, entry.Name())
}
}
return pids
return live, zombies
}
func kernel() map[string]string {
var name syscall.Utsname
if err := syscall.Uname(&name); err != nil {
return map[string]string{"error": err.Error()}
}
return map[string]string{
"sysname": utsString(name.Sysname[:]),
"release": utsString(name.Release[:]),
"version": utsString(name.Version[:]),
"machine": utsString(name.Machine[:]),
"goarch": runtime.GOARCH,
}
}
func utsString[T int8 | uint8](field []T) string {
var text strings.Builder
for _, value := range field {
if value == 0 {
break
}
text.WriteByte(byte(value))
}
return text.String()
}
// apkPackageVersion reads a package version from the Alpine database, which
// exists in the runner image; other hosts record only the nsjail digest.
func apkPackageVersion(name string) string {
content, err := os.ReadFile(apkDatabase)
if err != nil {
return ""
}
for record := range bytes.SplitSeq(content, []byte("\n\n")) {
lines := strings.Split(string(record), "\n")
if !containsLine(lines, "P:"+name) {
continue
}
for _, line := range lines {
if version, ok := strings.CutPrefix(line, "V:"); ok {
return name + " " + version
}
}
}
return ""
}
func containsLine(lines []string, wanted string) bool {
for _, line := range lines {
if line == wanted {
return true
}
}
return false
}
func firstLine(text string) string {
line, _, _ := strings.Cut(strings.TrimSpace(text), "\n")
return line
}
func writeReport(t *testing.T, result report) {
t.Helper()
path := os.Getenv(reportEnv)
if path == "" {
return
}
encoded, err := json.MarshalIndent(result, "", " ")
if err != nil {
t.Fatalf("encode report: %v", err)
}
if err := os.WriteFile(path, append(encoded, '\n'), 0o600); err != nil {
t.Fatalf("write report: %v", err)
}
t.Logf("A16 report written to %s", path)
}
+76
View File
@@ -0,0 +1,76 @@
package sandbox
import (
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"os"
)
// Profile describes the isolation applied to every run. Reports record it
// next to their results; it holds no secret.
type Profile struct {
NsjailPath string `json:"nsjail_path"`
NsjailSHA256 string `json:"nsjail_sha256"`
Arguments []string `json:"nsjail_arguments"`
SeccompPolicy string `json:"seccomp_policy"`
CPUQuota string `json:"cgroup_cpu_max"`
MaxProcesses int `json:"max_processes"`
MemoryOverheadBytes int64 `json:"memory_overhead_bytes"`
TmpfsBytes int64 `json:"tmpfs_bytes"`
FileSizeBytes int64 `json:"file_size_bytes"`
OpenFiles int `json:"open_files"`
SandboxUID int `json:"sandbox_uid"`
ReadOnlyMounts []string `json:"read_only_mounts"`
}
// Placeholders of the sample command line in a Profile.
const (
profileBox = "<run>"
profileProgram = "<program>"
profilePolicy = "<seccomp_policy>"
)
// Profile returns the isolation profile with the nsjail command line of a
// sample test run under limits.
func (e *Executor) Profile(limits Limits) (Profile, error) {
digest, err := fileSHA256(e.cfg.NsjailPath)
if err != nil {
return Profile{}, err
}
sample := Spec{
Argv: []string{profileProgram},
Mounts: []Mount{
{Source: profileBox + "/src", Target: BoxPath},
{Source: profileBox + "/out", Target: OutPath},
},
}
return Profile{
NsjailPath: e.cfg.NsjailPath,
NsjailSHA256: digest,
Arguments: nsjailArgs(e.cfg, sample, limits, profilePolicy),
SeccompPolicy: e.policy,
CPUQuota: cpuQuota,
MaxProcesses: e.cfg.MaxProcesses,
MemoryOverheadBytes: e.cfg.MemoryOverheadBytes,
TmpfsBytes: e.cfg.TmpfsBytes,
FileSizeBytes: e.cfg.FileSizeBytes,
OpenFiles: e.cfg.OpenFiles,
SandboxUID: e.cfg.SandboxUID,
ReadOnlyMounts: e.cfg.ReadOnlyMounts,
}, nil
}
func fileSHA256(path string) (string, error) {
file, err := os.Open(path)
if err != nil {
return "", fmt.Errorf("sandbox.fileSHA256 - open: %w", err)
}
defer func() { _ = file.Close() }() // Read-only.
hash := sha256.New()
if _, err := io.Copy(hash, file); err != nil {
return "", fmt.Errorf("sandbox.fileSHA256 - read: %w", err)
}
return hex.EncodeToString(hash.Sum(nil)), nil
}
+28
View File
@@ -0,0 +1,28 @@
#!/bin/sh
# Runs the A16 hostile-program suite on a runner host from the bundle built by
# make -C runner a16-bundle. It needs root on that host (namespaces, user
# mapping, and the delegated cgroup), the runner's nsjail, Python, and Go
# tool directory at the paths of the runner configuration, and an empty work
# directory. It never contacts the network and writes only the report and
# the work directory.
#
# Usage: sudo sh run-a16.sh [report.json]
# Settings come from the same RUNNER_* variables as the runner service,
# for example RUNNER_CGROUP_ROOT, RUNNER_WORK_DIR, and RUNNER_GO_TOOL_DIR.
set -eu
bundle=$(cd "$(dirname "$0")" && pwd)
report=${1:-$bundle/a16-report-$(date -u +%Y%m%dT%H%M%SZ).json}
if [ "$(id -u)" != "0" ]; then
echo "run-a16.sh: run as root on the runner host" >&2
exit 2
fi
export RUNNER_HOSTILE_FIXTURES="$bundle/testdata/hostile"
export RUNNER_A16_REPORT="$report"
# A non-zero status means that at least one case failed: practice must stay
# disabled until a run passes.
"$bundle/isolation.test" -test.v -test.count=1 -test.run '^TestA16'
echo "A16 report: $report"
+46
View File
@@ -0,0 +1,46 @@
// Disk exhaustion: the file size limit and the scratch tmpfs refuse writes.
package main
import (
"fmt"
"os"
)
func main() {
block := make([]byte, 1<<20)
refused := 0
if file, err := os.Create("/tmp/one-big-file"); err == nil {
for range 64 {
if _, err := file.Write(block); err != nil {
refused++
break
}
}
_ = file.Close()
_ = os.Remove("/tmp/one-big-file")
}
for index := range 64 {
file, err := os.Create(fmt.Sprintf("/tmp/part-%d", index))
if err != nil {
refused++
break
}
failed := false
for range 4 {
if _, err := file.Write(block); err != nil {
failed = true
break
}
}
_ = file.Close()
if failed {
refused++
break
}
}
if refused == 2 {
fmt.Println("refused")
return
}
fmt.Println("wrote everything")
}
+43
View File
@@ -0,0 +1,43 @@
// Isolation probe: read-only root, source, and build output; a writable
// scratch directory only; no host, runner, secret, or process files; no
// secret in the environment.
package main
import (
"fmt"
"os"
"strings"
)
func main() {
var writable, visible, leaked []string
for _, path := range []string{"/box/injected", "/out/injected", "/usr/injected", "/injected", "/lib/injected"} {
if err := os.WriteFile(path, []byte("x"), 0o600); err == nil {
writable = append(writable, path)
}
}
if err := os.WriteFile("/tmp/scratch", []byte("ok"), 0o600); err != nil {
fmt.Println("scratch not writable:", err)
return
}
for _, path := range []string{
"/etc/passwd", "/etc/shadow", "/run/secrets", "/run/secrets/runner_api_token", "/opt/lincodex-runner",
"/var/lib/lincodex-runner", "/proc/1", "/proc/self/environ", "/proc/self/mounts", "/sys/fs/cgroup",
"/dev/mem", "/dev/kmsg", "/root", "/home",
} {
if _, err := os.Lstat(path); err == nil {
visible = append(visible, path)
}
}
for _, variable := range os.Environ() {
name, _, _ := strings.Cut(variable, "=")
if strings.Contains(name, "RUNNER") || strings.Contains(name, "TOKEN") || strings.Contains(name, "SECRET") {
leaked = append(leaked, name)
}
}
if len(writable)+len(visible)+len(leaked) == 0 {
fmt.Println("isolated")
return
}
fmt.Println("writable", writable, "visible", visible, "env", leaked)
}
+14
View File
@@ -0,0 +1,14 @@
// Process bomb: every copy starts more copies and ignores failures; the
// cgroup process limit must stop it.
package main
import (
"os"
"os/exec"
)
func main() {
for {
_ = exec.Command(os.Args[0]).Start()
}
}
+14
View File
@@ -0,0 +1,14 @@
// Endless standard output: the output limit must stop it.
package main
import (
"bytes"
"os"
)
func main() {
block := bytes.Repeat([]byte("x"), 65536)
for {
_, _ = os.Stdout.Write(block)
}
}
+14
View File
@@ -0,0 +1,14 @@
// Timeout survival: ignores every catchable signal and spins; only SIGKILL
// from the supervisor stops it.
package main
import (
"os/signal"
"syscall"
)
func main() {
signal.Ignore(syscall.SIGTERM, syscall.SIGINT, syscall.SIGHUP, syscall.SIGXCPU, syscall.SIGALRM, syscall.SIGUSR1)
for {
}
}
+13
View File
@@ -0,0 +1,13 @@
// Unbounded allocation of touched memory: the cgroup memory limit must stop it.
package main
func main() {
var chunks [][]byte
for {
chunk := make([]byte, 1<<20)
for index := range chunk {
chunk[index] = 1
}
chunks = append(chunks, chunk)
}
}
+14
View File
@@ -0,0 +1,14 @@
// Escape attempt: mounting a fresh procfs is killed by the seccomp policy.
package main
import (
"fmt"
"os"
"syscall"
)
func main() {
_ = os.MkdirAll("/tmp/proc", 0o700)
err := syscall.Mount("proc", "/tmp/proc", "proc", 0, "")
fmt.Println("mount returned", err)
}
+52
View File
@@ -0,0 +1,52 @@
// Isolation probe: TCP, UDP, listening, name resolution, and raw, packet,
// and netlink sockets must all fail.
package main
import (
"context"
"fmt"
"net"
"strings"
"syscall"
"time"
)
func main() {
var reached []string
for _, target := range []struct{ network, address string }{
{"tcp", "1.1.1.1:53"}, {"tcp", "127.0.0.1:8443"}, {"tcp6", "[::1]:8443"}, {"udp", "8.8.8.8:53"},
} {
connection, err := net.DialTimeout(target.network, target.address, time.Second)
if err == nil {
// UDP "connects" without traffic; a write proves the route.
if _, writeErr := connection.Write([]byte("x")); writeErr == nil {
reached = append(reached, target.address)
}
_ = connection.Close()
}
}
if listener, err := net.Listen("tcp", "127.0.0.1:0"); err == nil {
reached = append(reached, "listen")
_ = listener.Close()
}
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
if _, err := net.DefaultResolver.LookupHost(ctx, "example.com"); err == nil {
reached = append(reached, "dns")
}
for _, socket := range []struct{ domain, kind, protocol int }{
{syscall.AF_INET, syscall.SOCK_RAW, syscall.IPPROTO_ICMP},
{syscall.AF_PACKET, syscall.SOCK_RAW, 0},
{syscall.AF_NETLINK, syscall.SOCK_RAW, 0},
} {
if fd, err := syscall.Socket(socket.domain, socket.kind, socket.protocol); err == nil {
reached = append(reached, fmt.Sprintf("socket %d", socket.domain))
_ = syscall.Close(fd)
}
}
if len(reached) == 0 {
fmt.Println("blocked")
return
}
fmt.Println("reached " + strings.Join(reached, ", "))
}
+25
View File
@@ -0,0 +1,25 @@
// Timeout survival: a child in its own session outlives the parent; the PID
// namespace must take it down with the run.
package main
import (
"fmt"
"os"
"os/exec"
"syscall"
"time"
)
func main() {
if len(os.Args) > 1 {
time.Sleep(time.Hour)
return
}
child := exec.Command(os.Args[0], "daemon")
child.SysProcAttr = &syscall.SysProcAttr{Setsid: true}
if err := child.Start(); err != nil {
fmt.Println("start failed:", err)
return
}
fmt.Println("parent done")
}
+24
View File
@@ -0,0 +1,24 @@
// Isolation probe: the program is not root and cannot become root, change
// ownership to root, or raise its limits.
package main
import (
"fmt"
"os"
"syscall"
)
func main() {
ok := os.Getuid() != 0 && os.Geteuid() != 0 && os.Getgid() != 0 && os.Getegid() != 0
ok = ok && syscall.Setuid(0) != nil && syscall.Setgid(0) != nil
if err := os.WriteFile("/tmp/owned", nil, 0o600); err == nil {
ok = ok && os.Chown("/tmp/owned", 0, 0) != nil
}
limit := syscall.Rlimit{Cur: 1 << 40, Max: 1 << 40}
ok = ok && syscall.Setrlimit(syscall.RLIMIT_NOFILE, &limit) != nil
if ok {
fmt.Println("unprivileged")
return
}
fmt.Println("privileged")
}
+12
View File
@@ -0,0 +1,12 @@
// Escape attempt: ptrace is killed by the seccomp policy (SIGSYS).
package main
import (
"fmt"
"syscall"
)
func main() {
err := syscall.PtraceAttach(1)
fmt.Println("ptrace returned", err)
}
+8
View File
@@ -0,0 +1,8 @@
// Idle wait: it uses no CPU, so only the wall-clock limit can stop it.
package main
import "time"
func main() {
time.Sleep(time.Hour)
}
+23
View File
@@ -0,0 +1,23 @@
// Correct solution: prints the sum of the integers on standard input.
package main
import (
"bufio"
"fmt"
"os"
"strconv"
)
func main() {
scanner := bufio.NewScanner(os.Stdin)
scanner.Split(bufio.ScanWords)
total := 0
for scanner.Scan() {
value, err := strconv.Atoi(scanner.Text())
if err != nil {
os.Exit(2)
}
total += value
}
fmt.Println(total)
}
+21
View File
@@ -0,0 +1,21 @@
// Thread bomb: goroutines blocked in system calls force the runtime to
// create threads; the cgroup process limit must stop it.
package main
import (
"os"
"syscall"
)
func main() {
var fds [2]int
if err := syscall.Pipe(fds[:]); err != nil {
os.Exit(2)
}
for {
go func() {
buffer := make([]byte, 1)
_, _ = syscall.Read(fds[0], buffer)
}()
}
}
+13
View File
@@ -0,0 +1,13 @@
// Escape attempt: unshare into a new user namespace is killed by the
// seccomp policy.
package main
import (
"fmt"
"syscall"
)
func main() {
err := syscall.Unshare(syscall.CLONE_NEWUSER)
fmt.Println("unshare returned", err)
}
+356 -46
View File
@@ -1,91 +1,401 @@
{
"schema": "lincodex.runner-hostile-fixtures/v1",
"description": "Programs that a sandbox run must stop or contain. Each case runs as one public group with one test; expect.limit is the termination limit, or empty when the program ends by itself.",
"schema": "lincodex.runner-hostile-fixtures/v2",
"description": "A16 hostile-program suite. Every case runs as one public group with one test under default_limits. expect.limit is the termination limit or empty when the program ends by itself; expect.signal, when present, is the signal that must stop it (31 is SIGSYS from the seccomp policy). Probe programs print one word when every attempt was refused.",
"default_limits": {
"time_limit_ms": 1000,
"memory_limit_mb": 64,
"output_limit_kb": 64
},
"categories": {
"baseline": "A correct program still works, and a syntax error stops before any test.",
"network": "TCP, UDP, listening, DNS, raw, packet, and netlink sockets are refused.",
"files_and_secrets": "Host files, runner files, the API token, procfs, sysfs, and secret environment variables are invisible; root, source, and build output are read-only.",
"privileges": "The program is not root and cannot setuid, setgid, chown to root, or raise rlimits.",
"escape": "ptrace, mount (including a fresh procfs), and unshare are killed by seccomp.",
"processes": "Fork and thread bombs are stopped by the cgroup process limit.",
"memory": "Memory exhaustion is stopped by the cgroup memory limit.",
"disk": "Disk exhaustion is refused by the file size limit and the scratch tmpfs size.",
"output": "Endless output is stopped by the output limit.",
"timeout": "Busy loops, ignored signals, idle waits, and detached daemons do not outlive the time limits or the run."
},
"cases": [
{
"name": "correct_sum",
"name": "py_correct_sum",
"category": "baseline",
"language": "python3",
"source": "python/sum_correct.py",
"input": "1 2 3\n",
"expected_output": "6\n",
"expect": {"outcome": "accepted", "limit": ""}
"expect": {
"outcome": "accepted",
"limit": ""
}
},
{
"name": "syntax_error",
"name": "py_syntax_error",
"category": "baseline",
"language": "python3",
"source": "python/syntax_error.py",
"input": "",
"expected_output": "",
"expect": {"outcome": "compile_error", "limit": ""}
"expect": {
"outcome": "compile_error",
"limit": ""
}
},
{
"name": "infinite_loop",
"name": "py_infinite_loop",
"category": "timeout",
"language": "python3",
"source": "python/infinite_loop.py",
"input": "",
"expected_output": "",
"expect": {"outcome": "time_limit_exceeded", "limit": "cpu_time"}
"expect": {
"outcome": "time_limit_exceeded",
"limit": "cpu_time"
}
},
{
"name": "sleep_forever",
"language": "python3",
"source": "python/sleep_forever.py",
"input": "",
"expected_output": "",
"expect": {"outcome": "time_limit_exceeded", "limit": "wall_time"}
},
{
"name": "memory_leak",
"language": "python3",
"source": "python/memory_leak.py",
"input": "",
"expected_output": "",
"expect": {"outcome": "memory_limit_exceeded", "limit": "memory"}
},
{
"name": "huge_output",
"language": "python3",
"source": "python/huge_output.py",
"input": "",
"expected_output": "",
"expect": {"outcome": "output_limit_exceeded", "limit": "output"}
},
{
"name": "fork_bomb",
"language": "python3",
"source": "python/fork_bomb.py",
"input": "",
"expected_output": "",
"expect": {"outcome": "runtime_error", "limit": "processes"}
},
{
"name": "network_probe",
"name": "py_network",
"category": "network",
"language": "python3",
"source": "python/network_probe.py",
"input": "",
"expected_output": "blocked\n",
"expect": {"outcome": "accepted", "limit": ""}
"expect": {
"outcome": "accepted",
"limit": ""
}
},
{
"name": "filesystem_probe",
"name": "py_files_and_secrets",
"category": "files_and_secrets",
"language": "python3",
"source": "python/filesystem_probe.py",
"input": "",
"expected_output": "isolated\n",
"expect": {"outcome": "accepted", "limit": ""}
"expect": {
"outcome": "accepted",
"limit": ""
}
},
{
"name": "privilege_probe",
"name": "py_privileges",
"category": "privileges",
"language": "python3",
"source": "python/privilege_probe.py",
"input": "",
"expected_output": "unprivileged\n",
"expect": {"outcome": "accepted", "limit": ""}
"expect": {
"outcome": "accepted",
"limit": ""
}
},
{
"name": "py_ptrace",
"category": "escape",
"language": "python3",
"source": "python/ptrace_attach.py",
"input": "",
"expected_output": "",
"expect": {
"outcome": "runtime_error",
"limit": "",
"signal": 31
}
},
{
"name": "py_mount_proc",
"category": "escape",
"language": "python3",
"source": "python/mount_proc.py",
"input": "",
"expected_output": "",
"expect": {
"outcome": "runtime_error",
"limit": "",
"signal": 31
}
},
{
"name": "py_unshare_user",
"category": "escape",
"language": "python3",
"source": "python/unshare_user.py",
"input": "",
"expected_output": "",
"expect": {
"outcome": "runtime_error",
"limit": "",
"signal": 31
}
},
{
"name": "py_fork_bomb",
"category": "processes",
"language": "python3",
"source": "python/fork_bomb.py",
"input": "",
"expected_output": "",
"expect": {
"outcome": "runtime_error",
"limit": "processes"
}
},
{
"name": "py_memory_leak",
"category": "memory",
"language": "python3",
"source": "python/memory_leak.py",
"input": "",
"expected_output": "",
"expect": {
"outcome": "memory_limit_exceeded",
"limit": "memory"
}
},
{
"name": "py_disk_fill",
"category": "disk",
"language": "python3",
"source": "python/disk_fill.py",
"input": "",
"expected_output": "refused\n",
"expect": {
"outcome": "accepted",
"limit": ""
}
},
{
"name": "py_huge_output",
"category": "output",
"language": "python3",
"source": "python/huge_output.py",
"input": "",
"expected_output": "",
"expect": {
"outcome": "output_limit_exceeded",
"limit": "output"
}
},
{
"name": "py_ignore_signals",
"category": "timeout",
"language": "python3",
"source": "python/ignore_signals.py",
"input": "",
"expected_output": "",
"expect": {
"outcome": "time_limit_exceeded",
"limit": "cpu_time"
}
},
{
"name": "py_sleep_forever",
"category": "timeout",
"language": "python3",
"source": "python/sleep_forever.py",
"input": "",
"expected_output": "",
"expect": {
"outcome": "time_limit_exceeded",
"limit": "wall_time"
}
},
{
"name": "py_orphan_daemon",
"category": "timeout",
"language": "python3",
"source": "python/orphan_daemon.py",
"input": "",
"expected_output": "parent done\n",
"expect": {
"outcome": "accepted",
"limit": ""
}
},
{
"name": "go_correct_sum",
"category": "baseline",
"language": "go",
"source": "go/sum_correct.go",
"input": "1 2 3\n",
"expected_output": "6\n",
"expect": {
"outcome": "accepted",
"limit": ""
}
},
{
"name": "go_network",
"category": "network",
"language": "go",
"source": "go/network_probe.go",
"input": "",
"expected_output": "blocked\n",
"expect": {
"outcome": "accepted",
"limit": ""
}
},
{
"name": "go_files_and_secrets",
"category": "files_and_secrets",
"language": "go",
"source": "go/filesystem_probe.go",
"input": "",
"expected_output": "isolated\n",
"expect": {
"outcome": "accepted",
"limit": ""
}
},
{
"name": "go_privileges",
"category": "privileges",
"language": "go",
"source": "go/privilege_probe.go",
"input": "",
"expected_output": "unprivileged\n",
"expect": {
"outcome": "accepted",
"limit": ""
}
},
{
"name": "go_ptrace",
"category": "escape",
"language": "go",
"source": "go/ptrace_attach.go",
"input": "",
"expected_output": "",
"expect": {
"outcome": "runtime_error",
"limit": "",
"signal": 31
}
},
{
"name": "go_mount_proc",
"category": "escape",
"language": "go",
"source": "go/mount_proc.go",
"input": "",
"expected_output": "",
"expect": {
"outcome": "runtime_error",
"limit": "",
"signal": 31
}
},
{
"name": "go_unshare_user",
"category": "escape",
"language": "go",
"source": "go/unshare_user.go",
"input": "",
"expected_output": "",
"expect": {
"outcome": "runtime_error",
"limit": "",
"signal": 31
}
},
{
"name": "go_fork_bomb",
"category": "processes",
"language": "go",
"source": "go/fork_bomb.go",
"input": "",
"expected_output": "",
"expect": {
"outcome": "runtime_error",
"limit": "processes"
}
},
{
"name": "go_memory_leak",
"category": "memory",
"language": "go",
"source": "go/memory_leak.go",
"input": "",
"expected_output": "",
"expect": {
"outcome": "memory_limit_exceeded",
"limit": "memory"
}
},
{
"name": "go_disk_fill",
"category": "disk",
"language": "go",
"source": "go/disk_fill.go",
"input": "",
"expected_output": "refused\n",
"expect": {
"outcome": "accepted",
"limit": ""
}
},
{
"name": "go_huge_output",
"category": "output",
"language": "go",
"source": "go/huge_output.go",
"input": "",
"expected_output": "",
"expect": {
"outcome": "output_limit_exceeded",
"limit": "output"
}
},
{
"name": "go_ignore_signals",
"category": "timeout",
"language": "go",
"source": "go/ignore_signals.go",
"input": "",
"expected_output": "",
"expect": {
"outcome": "time_limit_exceeded",
"limit": "cpu_time"
}
},
{
"name": "go_sleep_forever",
"category": "timeout",
"language": "go",
"source": "go/sleep_forever.go",
"input": "",
"expected_output": "",
"expect": {
"outcome": "time_limit_exceeded",
"limit": "wall_time"
}
},
{
"name": "go_orphan_daemon",
"category": "timeout",
"language": "go",
"source": "go/orphan_daemon.go",
"input": "",
"expected_output": "parent done\n",
"expect": {
"outcome": "accepted",
"limit": ""
}
},
{
"name": "go_thread_bomb",
"category": "processes",
"language": "go",
"source": "go/thread_bomb.go",
"input": "",
"expected_output": "",
"expect": {
"outcome": "runtime_error",
"limit": "processes"
}
}
]
}
+22
View File
@@ -0,0 +1,22 @@
# Disk exhaustion: the scratch tmpfs and the file size limit refuse writes
# long before the host is affected.
import os
block = b"x" * (1 << 20)
refused = []
try:
with open("/tmp/one-big-file", "wb") as stream:
for _ in range(64):
stream.write(block)
stream.flush()
except OSError as error:
refused.append("file:" + os.strerror(error.errno))
os.remove("/tmp/one-big-file")
try:
for index in range(64):
with open(f"/tmp/part-{index}", "wb") as stream:
for _ in range(4):
stream.write(block)
except OSError as error:
refused.append("tmpfs:" + os.strerror(error.errno))
print("refused" if len(refused) == 2 else f"wrote everything {refused}")
+13 -5
View File
@@ -1,9 +1,11 @@
# Isolation probe: the root file system and the source are read-only, the
# scratch directory is writable, and runner files are not visible.
# Isolation probe: the root, the source, and the build output are read-only,
# only the scratch directory is writable, and no host file, runner file,
# secret, or process information is visible, neither on disk nor in the
# environment.
import os
writable = []
for path in ("/box/injected", "/usr/injected", "/injected", "/lib/injected"):
for path in ("/box/injected", "/out/injected", "/usr/injected", "/injected", "/lib/injected"):
try:
with open(path, "w") as stream:
stream.write("x")
@@ -12,5 +14,11 @@ for path in ("/box/injected", "/usr/injected", "/injected", "/lib/injected"):
pass
with open("/tmp/scratch", "w") as stream:
stream.write("ok")
visible = [path for path in ("/etc/passwd", "/run/secrets", "/opt/lincodex-runner", "/proc/1") if os.path.exists(path)]
print("isolated" if not writable and not visible else "writable=" + ",".join(writable) + " visible=" + ",".join(visible))
hidden = (
"/etc/passwd", "/etc/shadow", "/etc/hosts", "/run/secrets", "/run/secrets/runner_api_token",
"/opt/lincodex-runner", "/var/lib/lincodex-runner", "/proc/1", "/proc/self/environ",
"/proc/self/mounts", "/sys/fs/cgroup", "/dev/mem", "/dev/kmsg", "/root", "/home",
)
visible = [path for path in hidden if os.path.lexists(path)]
leaked = [name for name in os.environ if "RUNNER" in name or "TOKEN" in name or "SECRET" in name]
print("isolated" if not writable and not visible and not leaked else f"writable={writable} visible={visible} env={leaked}")
+8
View File
@@ -0,0 +1,8 @@
# Timeout survival: ignores every catchable signal and spins; only SIGKILL
# from the supervisor stops it.
import signal
for number in (signal.SIGTERM, signal.SIGINT, signal.SIGHUP, signal.SIGXCPU, signal.SIGALRM, signal.SIGUSR1):
signal.signal(number, signal.SIG_IGN)
while True:
pass
+8
View File
@@ -0,0 +1,8 @@
# Escape attempt: mounting a fresh procfs is killed by the seccomp policy.
import ctypes
import os
os.makedirs("/tmp/proc", exist_ok=True)
libc = ctypes.CDLL(None, use_errno=True)
libc.mount(b"proc", b"/tmp/proc", b"proc", 0, None)
print("mount returned")
+18 -8
View File
@@ -1,13 +1,11 @@
# Isolation probe: every attempt to reach a network must fail.
# Isolation probe: every attempt to reach or sniff a network must fail,
# including raw, packet, and netlink sockets and name resolution.
import socket
attempts = [
(socket.AF_INET, ("1.1.1.1", 53)),
(socket.AF_INET, ("127.0.0.1", 8080)),
(socket.AF_INET6, ("::1", 8080)),
]
attempts = 0
reached = []
for family, address in attempts:
for family, address in ((socket.AF_INET, ("1.1.1.1", 53)), (socket.AF_INET, ("127.0.0.1", 8443)), (socket.AF_INET6, ("::1", 8443))):
attempts += 1
try:
with socket.socket(family, socket.SOCK_STREAM) as connection:
connection.settimeout(1)
@@ -15,4 +13,16 @@ for family, address in attempts:
reached.append(address[0])
except OSError:
pass
print("blocked" if not reached else "reached " + " ".join(reached))
for family, kind, protocol in ((socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP), (getattr(socket, "AF_PACKET", 17), socket.SOCK_RAW, 0), (getattr(socket, "AF_NETLINK", 16), socket.SOCK_RAW, 0)):
attempts += 1
try:
socket.socket(family, kind, protocol).close()
reached.append(f"socket {family}/{kind}")
except OSError:
pass
try:
socket.getaddrinfo("example.com", 443)
reached.append("dns")
except OSError:
pass
print("blocked" if not reached else "reached " + ", ".join(reached))
+13
View File
@@ -0,0 +1,13 @@
# Timeout survival: a detached child in its own session outlives the
# parent; the PID namespace must take it down with the run.
import os
import sys
import time
if os.fork() == 0:
os.setsid()
if os.fork() == 0:
time.sleep(3600)
os._exit(0)
print("parent done")
sys.stdout.flush()
+6
View File
@@ -0,0 +1,6 @@
# Escape attempt: ptrace is killed by the seccomp policy (SIGSYS).
import ctypes
libc = ctypes.CDLL(None, use_errno=True)
libc.ptrace(0, 0, None, None)
print("ptrace returned")
+8
View File
@@ -0,0 +1,8 @@
# Escape attempt: a new user namespace would give capabilities inside it;
# unshare is killed by the seccomp policy.
import ctypes
CLONE_NEWUSER = 0x10000000
libc = ctypes.CDLL(None, use_errno=True)
libc.unshare(CLONE_NEWUSER)
print("unshare returned")