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

+3 -1
View File
@@ -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
+2
View File
@@ -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 |
+28 -2
View File
@@ -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
+3 -1
View File
@@ -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`; любой проваленный случай блокирует включение.
## Подбор и объяснение
+2
View File
@@ -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) |
+28 -2
View File
@@ -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; отсутствие побочных каналов (время, кеш процессора) и устойчивость под нагрузкой.
## Будущая программная валидация