diff --git a/docs/en/ARCHITECTURE.md b/docs/en/ARCHITECTURE.md index b0af775..bd58428 100644 --- a/docs/en/ARCHITECTURE.md +++ b/docs/en/ARCHITECTURE.md @@ -746,7 +746,9 @@ A checker is set per group: `exact`, `tokens`, `numbers` (numeric tokens are equ Outcomes distinguish `accepted`, `wrong_answer`, `compile_error` (for Python, a syntax check with `compile()` before the tests; for Go, compile and link), `time_limit_exceeded`, `memory_limit_exceeded`, `output_limit_exceeded`, `runtime_error` (including the process limit), and `infrastructure_failure`. Test time is the CPU time of every process of the test, including interpreter startup; memory is the cgroup peak of the test, including nsjail and file cache charged to the test. -Planned and not implemented: deployment of the runner VM with TLS, firewall, and monitoring; calls from the backend and the run queue; service metrics; the full A16 isolation suite built on `runner/testdata/hostile/`. +Planned and not implemented: deployment of the runner VM with TLS, firewall, and monitoring; calls from the backend and the run queue; service metrics; running the A16 suite on the runner VM. + +The A16 hostile-program suite (`make -C runner test-a16`, see [checks](TESTING.md#a16-hostile-program-suite)) is implemented and passes locally. Code practice is enabled only after the suite has passed on the runner VM with the verdict `pass`; any failed case blocks enabling it. ## Matching and explanations diff --git a/docs/en/DEPLOY.md b/docs/en/DEPLOY.md index cebb79f..8ac5fdd 100644 --- a/docs/en/DEPLOY.md +++ b/docs/en/DEPLOY.md @@ -754,6 +754,8 @@ The `runner/Dockerfile` image holds the Go supervisor, nsjail, Python from `pyth The runner runs only in the `lincodex-runner` VM on the `lxdbr-runner` bridge (see [the isolated runner host](#isolated-runner-and-lab-host-lxd)), never on the core host and never with the dev file. TLS (`RUNNER_TLS_CERT_FILE`, `RUNNER_TLS_KEY_FILE`; the process does not start without them) and a token from a secret file (`RUNNER_API_TOKEN_FILE`) are required. Rolling out the VM, issuing the certificate, storing the token for the backend, and monitoring are not implemented yet. +Before practice is enabled, the A16 suite runs on the VM: `make -C runner a16-bundle` on a developer machine, copy `runner/bin/a16-bundle.tar.gz` to the VM, then `sudo sh run-a16.sh` in the unpacked directory with the service's `RUNNER_*` variables. It needs nsjail, Python, and the Go tool directory at the configured paths, a delegated cgroup v2, and a work directory on a tmpfs with `exec`. A non-zero exit status or the verdict `fail` in the report blocks enabling practice. When the runner runs in a container, start the container with an init (`--init` or `init: true`) or under systemd, so that the rare process left after an OOM kill of nsjail is reaped. + | Variable | Default | Purpose | | --- | --- | --- | | `RUNNER_LISTEN_ADDRESS` | `:8443` | HTTP(S) address | diff --git a/docs/en/TESTING.md b/docs/en/TESTING.md index fdb2fc7..c73c120 100644 --- a/docs/en/TESTING.md +++ b/docs/en/TESTING.md @@ -589,13 +589,39 @@ The tests do not run the Make targets against a real stack. A manual check on a | make -C runner lint | golangci-lint for Linux, including the isolation tests | | make -C runner check-generated | The generated ogen server matches the bundle | | make -C runner test-sandbox | Reference solutions and isolation tests in a privileged dev container with real nsjail and cgroup v2 | +| make -C runner test-a16 | The A16 suite only, with a report in `runner/.reports/`; `A16_ENV` passes `RUNNER_*` variables | +| make -C runner a16-bundle | A bundle of the A16 suite for the runner host | | make -C deploy check-runner-dev | Dev switches stay out of production files | First, `test-sandbox` runs the reference solutions of `runner/testdata/judge/manifest.json` on three tasks with one public and three hidden groups: correct and incorrect Python and Go solutions get the expected outcome of every group (`exact` and `tokens`; `numbers` on fractional answers with an absolute and a relative tolerance; `custom` with a Python and a Go checker in nsjail); Go code with a compile error gives `compile_error` with a `main.go:` message and no test runs. The test also checks that a group stops at its first failed test, hidden tests carry no diagnostic, and the run directories and cgroups are removed. -Then `test-sandbox` runs every case of `runner/testdata/hostile/manifest.json` twice: a correct solution is accepted with its time and memory recorded; a syntax error gives `compile_error`; the CPU limit stops an infinite loop, the wall-clock limit a sleep, the cgroup memory limit a memory leak, the output limit endless output, and the process limit a fork bomb (`runtime_error`); network, file system, and privilege probes confirm that there is no network, the root and the source are read-only, runner files are not visible, and the program is not root. After every case and after the series the test checks that the run directory is empty, the run cgroups are gone, and no uid 99999 process is left. It runs without a separate init, so it also confirms that nsjail reaps every stopped process. +Then `test-sandbox` runs the A16 suite (see below). -What the tests do not prove: isolation in the production VM (they have not run there yet), protection against kernel, nsjail, or cgroup vulnerabilities, the absence of side channels, or behavior under load. The full A16 isolation suite is planned separately and will extend the same fixtures. +### A16 hostile-program suite + +`make -C runner test-a16` builds the image and runs only the A16 suite in a privileged dev container without network and without an init; a JSON report is written to `runner/.reports/` (ignored by Git). The cases and expectations are in `runner/testdata/hostile/manifest.json`, with programs in Python and in Go: + +| Category | Attempts | Expectation | +| --- | --- | --- | +| network | TCP, UDP, listen, DNS, raw ICMP, AF_PACKET, and netlink sockets | all refused; the probe prints `blocked` | +| 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`) | +| 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 | + +Baseline cases check that a correct solution is accepted and a syntax error gives `compile_error`. After every case the test checks that the run directory is empty, the run cgroups are gone, no live uid 99999 process is left, and no new unreaped (zombie) process appeared; the suite runs without an init, so this confirms that nsjail reaps every stopped process. + +The report records the runner version (`git describe`), the kernel (`uname`), the cgroup controllers, the nsjail package version and SHA-256, the isolation profile (nsjail arguments of a sample test run, the seccomp policy, cgroup and rlimit limits), the result of every case, and the verdict. Any failed case gives the verdict `fail` and `practice_may_be_enabled: false`: practice must not be enabled until the suite passes on the runner host. + +Checking the suite itself: `TestA16WeakenedProcessLimitIsDetected` raises the process limit to 4096 in a test copy of the configuration and requires the processes cases to fail. The same by hand: `make -C runner test-a16 A16_ENV="RUNNER_SANDBOX_MAX_PROCESSES=4096"` exits with an error and a `fail` report on exactly the three processes cases. + +On the runner host the suite runs from a bundle: `make -C runner a16-bundle` (`A16_GOARCH=amd64` by default) builds `runner/bin/a16-bundle.tar.gz` with the test binary, the fixtures, and `run-a16.sh`; on the VM it is unpacked and started with `sudo sh run-a16.sh [report.json]` and the same `RUNNER_*` variables as the service. The script does not use the network and writes only the report and the work directory. + +What the tests do not prove: isolation in the production VM until the suite has passed there; protection against kernel, nsjail, or cgroup vulnerabilities; the absence of side channels (timing, CPU caches); or behavior under load. ## Future software validation diff --git a/docs/ru/ARCHITECTURE.md b/docs/ru/ARCHITECTURE.md index 3ddbb97..ed7eaee 100644 --- a/docs/ru/ARCHITECTURE.md +++ b/docs/ru/ARCHITECTURE.md @@ -746,7 +746,9 @@ Checker задается для группы: `exact`, `tokens`, `numbers` (чи Исходы различают `accepted`, `wrong_answer`, `compile_error` (для Python - проверка синтаксиса через `compile()` до тестов, для Go - компиляция и линковка), `time_limit_exceeded`, `memory_limit_exceeded`, `output_limit_exceeded`, `runtime_error` (включая лимит процессов) и `infrastructure_failure`. Время теста - CPU всех процессов теста вместе с запуском интерпретатора; память - пик cgroup теста, включая nsjail и файловый кеш, отнесенный к тесту. -Запланировано и не реализовано: развертывание VM исполнителя с TLS, firewall и мониторингом; вызов исполнителя из backend и очередь прогонов; метрики сервиса; полный набор проверок изоляции A16 на базе `runner/testdata/hostile/`. +Запланировано и не реализовано: развертывание VM исполнителя с TLS, firewall и мониторингом; вызов исполнителя из backend и очередь прогонов; метрики сервиса; прогон набора A16 на VM исполнителя. + +Набор враждебных программ A16 (`make -C runner test-a16`, см. [проверки](TESTING.md#набор-враждебных-программ-a16)) реализован и проходит локально. Практика с кодом включается только после того, как набор прошел на VM исполнителя с вердиктом `pass`; любой проваленный случай блокирует включение. ## Подбор и объяснение diff --git a/docs/ru/DEPLOY.md b/docs/ru/DEPLOY.md index 14739b5..d35591c 100644 --- a/docs/ru/DEPLOY.md +++ b/docs/ru/DEPLOY.md @@ -756,6 +756,8 @@ lxd init --preseed < deploy/labs/lxd-preseed.yaml Исполнитель работает только в VM `lincodex-runner` на мосту `lxdbr-runner` (см. [изолированный хост раннера](#изолированный-хост-раннера-и-лабораторий-lxd)), никогда на core-хосте и никогда с dev-файлом. Обязательны TLS (`RUNNER_TLS_CERT_FILE`, `RUNNER_TLS_KEY_FILE`; без них процесс не стартует) и токен из файла секрета (`RUNNER_API_TOKEN_FILE`). Раскатка VM, выпуск сертификата, хранение токена на стороне backend и мониторинг еще не реализованы. +Перед включением практики на VM запускается набор A16: `make -C runner a16-bundle` на машине разработчика, перенос `runner/bin/a16-bundle.tar.gz` на VM, затем `sudo sh run-a16.sh` в распакованном каталоге с переменными `RUNNER_*` сервиса. Нужны nsjail, Python и каталог Go-инструментов по путям конфигурации, делегированная cgroup v2 и рабочий каталог на tmpfs с `exec`. Код выхода не 0 или вердикт `fail` в отчете блокируют включение практики. Если runner работает в контейнере, контейнер запускают с init (`--init` или `init: true`) или под systemd, чтобы редкий процесс, оставшийся после OOM-kill nsjail, был забран. + | Переменная | По умолчанию | Назначение | | --- | --- | --- | | `RUNNER_LISTEN_ADDRESS` | `:8443` | Адрес HTTP(S) | diff --git a/docs/ru/TESTING.md b/docs/ru/TESTING.md index 1b4bb64..62fd1b2 100644 --- a/docs/ru/TESTING.md +++ b/docs/ru/TESTING.md @@ -589,13 +589,39 @@ Vitest работает в Node без DOM, поэтому ограничени | make -C runner lint | golangci-lint для Linux, включая тесты изоляции | | make -C runner check-generated | Сгенерированный ogen-сервер совпадает с bundle | | make -C runner test-sandbox | Эталонные решения и тесты изоляции в привилегированном dev-контейнере с настоящими nsjail и cgroup v2 | +| make -C runner test-a16 | Только набор A16 с отчетом в `runner/.reports/`; `A16_ENV` передает переменные `RUNNER_*` | +| make -C runner a16-bundle | Пакет набора A16 для запуска на хосте исполнителя | | make -C deploy check-runner-dev | Dev-переключатели не попадают в production-файлы | Сначала `test-sandbox` прогоняет эталонные решения `runner/testdata/judge/manifest.json` на трех задачах с одной публичной и тремя скрытыми группами: верные и неверные решения на Python и Go получают ожидаемый исход каждой группы (`exact` и `tokens`; `numbers` на дробных ответах с абсолютным и относительным допуском; `custom` с checker на Python и на Go в nsjail); Go-код с ошибкой компиляции дает `compile_error` с сообщением `main.go:` и ни одного запущенного теста. Тест также проверяет, что группа останавливается на первом проваленном тесте, у скрытых тестов нет диагностики, а каталоги и cgroup прогонов удалены. -Затем `test-sandbox` прогоняет дважды все случаи `runner/testdata/hostile/manifest.json`: верное решение принимается с записанными временем и памятью; синтаксическая ошибка дает `compile_error`; бесконечный цикл останавливает лимит CPU, сон - лимит стены, утечка памяти - лимит памяти cgroup, бесконечный вывод - лимит вывода, fork bomb - лимит процессов (`runtime_error`); пробы сети, файловой системы и привилегий подтверждают, что сети нет, корень и исходник только для чтения, файлы runner не видны, а программа не root. После каждого случая и после серии проверяется, что каталог прогонов пуст, cgroup прогонов удалены и не осталось процессов uid 99999. Тест запускается без отдельного init, поэтому подтверждает, что nsjail забирает каждый остановленный процесс. +Затем `test-sandbox` запускает набор A16 (см. ниже). -Что тесты не доказывают: изоляцию в production VM (там они еще не запускались), защиту от уязвимостей ядра, nsjail или cgroup, отсутствие побочных каналов и устойчивость под нагрузкой. Полный набор проверок A16 запланирован отдельно и расширит те же fixtures. +### Набор враждебных программ A16 + +`make -C runner test-a16` собирает образ и запускает только набор A16 в привилегированном dev-контейнере без сети и без init; отчет JSON записывается в `runner/.reports/` (игнорируется Git). Случаи и ожидания описаны в `runner/testdata/hostile/manifest.json`, программы есть на Python и на Go: + +| Категория | Попытки | Ожидание | +| --- | --- | --- | +| network | TCP, UDP, listen, DNS, raw ICMP, AF_PACKET и netlink-сокеты | все отказаны, проба печатает `blocked` | +| 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`) | +| disk | один большой файл и заполнение `/tmp` | отказ лимита размера файла и размера tmpfs | +| output | бесконечный вывод | лимит вывода (`output_limit_exceeded`) | +| timeout | занятый цикл с игнорированием сигналов, сон, отсоединенный демон в своей сессии | лимит CPU, лимит стены; демон погибает вместе с PID namespace | + +Базовые случаи проверяют, что верное решение принимается, а синтаксическая ошибка дает `compile_error`. После каждого случая тест проверяет, что каталог прогонов пуст, cgroup прогонов удалены, живых процессов uid 99999 нет и не появилось незабранных (zombie); набор работает без init, поэтому это подтверждает, что nsjail забирает каждый остановленный процесс. + +Отчет содержит версию runner (`git describe`), ядро (`uname`), контроллеры cgroup, версию пакета и SHA-256 nsjail, профиль изоляции (аргументы nsjail для тестового прогона, политику seccomp, лимиты cgroup и rlimit), результат каждого случая и вердикт. Любой проваленный случай дает вердикт `fail` и `practice_may_be_enabled: false`: практику нельзя включать, пока набор не прошел на хосте исполнителя. + +Проверка самого набора: `TestA16WeakenedProcessLimitIsDetected` поднимает лимит процессов до 4096 в тестовой копии конфигурации и требует, чтобы случаи категории processes провалились. Тот же эффект вручную: `make -C runner test-a16 A16_ENV="RUNNER_SANDBOX_MAX_PROCESSES=4096"` завершается ошибкой и отчетом `fail` ровно по трем случаям processes. + +На хосте исполнителя набор запускается из пакета: `make -C runner a16-bundle` (по умолчанию `A16_GOARCH=amd64`) собирает `runner/bin/a16-bundle.tar.gz` с тестовым бинарником, fixtures и `run-a16.sh`; на VM его распаковывают и запускают `sudo sh run-a16.sh [report.json]` с теми же переменными `RUNNER_*`, что и у сервиса. Скрипт не обращается к сети и пишет только отчет и рабочий каталог. + +Что тесты не доказывают: изоляцию в production VM, пока набор там не прошел; защиту от уязвимостей ядра, nsjail или cgroup; отсутствие побочных каналов (время, кеш процессора) и устойчивость под нагрузкой. ## Будущая программная валидация diff --git a/runner/.gitignore b/runner/.gitignore index 16c2648..26f6079 100644 --- a/runner/.gitignore +++ b/runner/.gitignore @@ -9,3 +9,4 @@ *.cover *.pprof coverage.* +/.reports/ diff --git a/runner/Dockerfile.sandbox-test b/runner/Dockerfile.sandbox-test index 78a1132..11d593d 100644 --- a/runner/Dockerfile.sandbox-test +++ b/runner/Dockerfile.sandbox-test @@ -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"] diff --git a/runner/Makefile b/runner/Makefile index a9ff70e..bf8208f 100644 --- a/runner/Makefile +++ b/runner/Makefile @@ -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 diff --git a/runner/README.en.md b/runner/README.en.md index 69417b3..bf76b17 100644 --- a/runner/README.en.md +++ b/runner/README.en.md @@ -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). diff --git a/runner/README.md b/runner/README.md index f3adee6..195ebdd 100644 --- a/runner/README.md +++ b/runner/README.md @@ -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#тесты-исполнителя-кода). diff --git a/runner/internal/isolationtest/isolation_test.go b/runner/internal/isolationtest/isolation_test.go index 3d2be5b..9d7dfce 100644 --- a/runner/internal/isolationtest/isolation_test.go +++ b/runner/internal/isolationtest/isolation_test.go @@ -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) } diff --git a/runner/internal/sandbox/profile.go b/runner/internal/sandbox/profile.go new file mode 100644 index 0000000..1a72b82 --- /dev/null +++ b/runner/internal/sandbox/profile.go @@ -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 = "" + profileProgram = "" + profilePolicy = "" +) + +// 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 +} diff --git a/runner/scripts/run-a16.sh b/runner/scripts/run-a16.sh new file mode 100755 index 0000000..6b51d08 --- /dev/null +++ b/runner/scripts/run-a16.sh @@ -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" diff --git a/runner/testdata/hostile/go/disk_fill.go b/runner/testdata/hostile/go/disk_fill.go new file mode 100644 index 0000000..e461696 --- /dev/null +++ b/runner/testdata/hostile/go/disk_fill.go @@ -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") +} diff --git a/runner/testdata/hostile/go/filesystem_probe.go b/runner/testdata/hostile/go/filesystem_probe.go new file mode 100644 index 0000000..ddd0309 --- /dev/null +++ b/runner/testdata/hostile/go/filesystem_probe.go @@ -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) +} diff --git a/runner/testdata/hostile/go/fork_bomb.go b/runner/testdata/hostile/go/fork_bomb.go new file mode 100644 index 0000000..59899cf --- /dev/null +++ b/runner/testdata/hostile/go/fork_bomb.go @@ -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() + } +} diff --git a/runner/testdata/hostile/go/huge_output.go b/runner/testdata/hostile/go/huge_output.go new file mode 100644 index 0000000..1bcb5db --- /dev/null +++ b/runner/testdata/hostile/go/huge_output.go @@ -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) + } +} diff --git a/runner/testdata/hostile/go/ignore_signals.go b/runner/testdata/hostile/go/ignore_signals.go new file mode 100644 index 0000000..838354c --- /dev/null +++ b/runner/testdata/hostile/go/ignore_signals.go @@ -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 { + } +} diff --git a/runner/testdata/hostile/go/memory_leak.go b/runner/testdata/hostile/go/memory_leak.go new file mode 100644 index 0000000..ad57b06 --- /dev/null +++ b/runner/testdata/hostile/go/memory_leak.go @@ -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) + } +} diff --git a/runner/testdata/hostile/go/mount_proc.go b/runner/testdata/hostile/go/mount_proc.go new file mode 100644 index 0000000..74bda0a --- /dev/null +++ b/runner/testdata/hostile/go/mount_proc.go @@ -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) +} diff --git a/runner/testdata/hostile/go/network_probe.go b/runner/testdata/hostile/go/network_probe.go new file mode 100644 index 0000000..35e9d15 --- /dev/null +++ b/runner/testdata/hostile/go/network_probe.go @@ -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, ", ")) +} diff --git a/runner/testdata/hostile/go/orphan_daemon.go b/runner/testdata/hostile/go/orphan_daemon.go new file mode 100644 index 0000000..af591fc --- /dev/null +++ b/runner/testdata/hostile/go/orphan_daemon.go @@ -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") +} diff --git a/runner/testdata/hostile/go/privilege_probe.go b/runner/testdata/hostile/go/privilege_probe.go new file mode 100644 index 0000000..984ece1 --- /dev/null +++ b/runner/testdata/hostile/go/privilege_probe.go @@ -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") +} diff --git a/runner/testdata/hostile/go/ptrace_attach.go b/runner/testdata/hostile/go/ptrace_attach.go new file mode 100644 index 0000000..bd3e853 --- /dev/null +++ b/runner/testdata/hostile/go/ptrace_attach.go @@ -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) +} diff --git a/runner/testdata/hostile/go/sleep_forever.go b/runner/testdata/hostile/go/sleep_forever.go new file mode 100644 index 0000000..0b01ecd --- /dev/null +++ b/runner/testdata/hostile/go/sleep_forever.go @@ -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) +} diff --git a/runner/testdata/hostile/go/sum_correct.go b/runner/testdata/hostile/go/sum_correct.go new file mode 100644 index 0000000..25070a6 --- /dev/null +++ b/runner/testdata/hostile/go/sum_correct.go @@ -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) +} diff --git a/runner/testdata/hostile/go/thread_bomb.go b/runner/testdata/hostile/go/thread_bomb.go new file mode 100644 index 0000000..58278f5 --- /dev/null +++ b/runner/testdata/hostile/go/thread_bomb.go @@ -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) + }() + } +} diff --git a/runner/testdata/hostile/go/unshare_user.go b/runner/testdata/hostile/go/unshare_user.go new file mode 100644 index 0000000..21f55fd --- /dev/null +++ b/runner/testdata/hostile/go/unshare_user.go @@ -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) +} diff --git a/runner/testdata/hostile/manifest.json b/runner/testdata/hostile/manifest.json index 3e5ac4b..caaf996 100644 --- a/runner/testdata/hostile/manifest.json +++ b/runner/testdata/hostile/manifest.json @@ -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" + } } ] } diff --git a/runner/testdata/hostile/python/disk_fill.py b/runner/testdata/hostile/python/disk_fill.py new file mode 100644 index 0000000..71eafc5 --- /dev/null +++ b/runner/testdata/hostile/python/disk_fill.py @@ -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}") diff --git a/runner/testdata/hostile/python/filesystem_probe.py b/runner/testdata/hostile/python/filesystem_probe.py index 303f03b..46109e4 100644 --- a/runner/testdata/hostile/python/filesystem_probe.py +++ b/runner/testdata/hostile/python/filesystem_probe.py @@ -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}") diff --git a/runner/testdata/hostile/python/ignore_signals.py b/runner/testdata/hostile/python/ignore_signals.py new file mode 100644 index 0000000..e63a2d2 --- /dev/null +++ b/runner/testdata/hostile/python/ignore_signals.py @@ -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 diff --git a/runner/testdata/hostile/python/mount_proc.py b/runner/testdata/hostile/python/mount_proc.py new file mode 100644 index 0000000..2e45498 --- /dev/null +++ b/runner/testdata/hostile/python/mount_proc.py @@ -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") diff --git a/runner/testdata/hostile/python/network_probe.py b/runner/testdata/hostile/python/network_probe.py index 4983384..63e8e75 100644 --- a/runner/testdata/hostile/python/network_probe.py +++ b/runner/testdata/hostile/python/network_probe.py @@ -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)) diff --git a/runner/testdata/hostile/python/orphan_daemon.py b/runner/testdata/hostile/python/orphan_daemon.py new file mode 100644 index 0000000..09d1012 --- /dev/null +++ b/runner/testdata/hostile/python/orphan_daemon.py @@ -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() diff --git a/runner/testdata/hostile/python/ptrace_attach.py b/runner/testdata/hostile/python/ptrace_attach.py new file mode 100644 index 0000000..5afdd5d --- /dev/null +++ b/runner/testdata/hostile/python/ptrace_attach.py @@ -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") diff --git a/runner/testdata/hostile/python/unshare_user.py b/runner/testdata/hostile/python/unshare_user.py new file mode 100644 index 0000000..359f806 --- /dev/null +++ b/runner/testdata/hostile/python/unshare_user.py @@ -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")