This commit is contained in:
DurkaHelper contributors committed 2026-10-10 07:29:48 +03:00
commit 303438d206
217 files changed
+66681

No files matched your search

+157
View File
@@ -0,0 +1,157 @@
# Синтетические интеграционные тесты
[English](README.md) | Русский
<a id="synthetic-integration-tests"></a>
Это developer fixtures, **не инструкция развёртывания**. Для рабочего командного стека используйте [durka.py и инструкцию администратора](../deployment/README-RU.md).
<a id="isolation-and-prerequisites"></a>
## Изоляция и prerequisites
Opt-in Docker-тесты запускаются только в отдельном приватном workspace с синтетическими credentials/data. Нужны разрешённый Linux Docker Engine, кешированные закреплённые образы, уникальные project names и свободные ресурсы. Recovery и fault-injection требуют snapshot хоста. Чужие workloads не исследуются.
<a id="prepare-and-run"></a>
## Подготовка и запуск
Прочитайте help fixture, просмотрите preview, затем примените осознанно. В профилях нет shell-команд. Запускайте из корня репозитория. Результаты остаются в выбранном приватном workspace, а не в Git.
```bash
python3 integration/stack_smoke.py --help
python3 integration/packmate_smoke.py --help
```
<a id="rollback-and-failures"></a>
## Откат и ошибки
Используйте shutdown самого fixture; не глобальный prune или удаление общих volumes. При сбое локальные результаты/данные сохраняются для диагностики. Проверьте точечную очистку перед повтором в новом workspace.
<a id="evidence-boundaries"></a>
## Границы проверки
Синтетический тест не сертифицирует Docker Desktop, захват на соревновании или доступ реальных участников. CI logs и приватные outputs заменяют закоммиченные исторические отчёты. См. [возможности и ограничения](../docs/CAPABILITY_INVENTORY-RU.md).
<a id="packmate-file-only-fixture"></a>
## Fixture Packmate FILE
`packmate_smoke.py` проверяет импорт закрытого синтетического PCAP, authentication и известные потоки. Непрерывный захват он не подтверждает.
<a id="native-postgresql-recovery-drill"></a>
## Нативное восстановление PostgreSQL
`recovery_smoke.py` проверяет native dump/restore в изолированные базы. Не подменяйте его синтетические inputs игровыми volumes.
<a id="published-neo-release-client"></a>
## Опубликованный Neo client
`neo_release_smoke.py` проверяет закреплённый опубликованный client с закреплённым server; latest автоматически не выбирается.
<a id="harmless-neo-task-lifecycle"></a>
## Безвредный цикл Neo
`neo_lifecycle_smoke.py` проверяет безвредную задачу, результат, reconnect и disable. Workers исполняют доверенный код; не передавайте произвольные задачи.
<a id="native-redis-recovery"></a>
## Нативное восстановление Redis
`component_recovery_smoke.py` проверяет persistence/recovery в изолированном fixture. Для настоящих очередей отправки отдельно решают, можно ли replay.
<a id="packmate-authentication-logger-canary"></a>
## Canary логирования Packmate
`packmate_logger_smoke.py` проверяет подавление failed-auth logger через конфигурацию: одноразовый canary и positive control. Все возможные пути логирования этим не сертифицируются.
<a id="whole-stack-synthetic-recovery"></a>
## Восстановление синтетического стека
`stack_recovery_smoke.py` восстанавливает синтетические Farm, Neo и Packmate в новые projects с отключённой автоматической отправкой. Это не разрешение перезаписывать существующий deployment.
<a id="synthetic-live-capture"></a>
## Синтетический LIVE
`packmate_live_smoke.py` наблюдает только свою синтетическую Linux network/namespace. Проверяет TCP/UDP, timeout и restart, но не видимость настоящего Vulnbox или длительную нагрузку.
<a id="network-isolated-offline-runtime-rehearsal"></a>
## Изолированная офлайн-репетиция
`offline_runtime_smoke.py` делает cold start Linux-стека из подготовленных образов и проверяет network denial плюс сохранение синтетических данных. Полный toolchain на пустой ноутбук он не устанавливает. Для обычной подготовки см. [офлайн-работу](../docs/offline-bundles-RU.md).
Аргументы каждого fixture доступны через `--help`; низкоуровневые защитные флаги нужны разработчикам, а не как формы для обычного оператора.
<a id="portable-synthetic-vulnbox-handoff"></a>
## Перенос синтетического PCAP с Vulnbox
`vulnbox_handoff.py` получает небольшой закрытый synthetic PCAP по loopback HTTP,
проверяет формат, отклоняет обрезанный файл и запускает проверку Docker-исходников
до/после ручных изменений тестовых примеров. Privileged containers он не запускает.
macOS workflow принимает необязательный ограниченный synthetic PCAP в base64;
без него файл генерируется локально. Реальный трафик и секреты передавать нельзя.
Это проверка переносимости файлового пути и CLI сканера, **не** прямого доступа к VM,
обработки Packmate, LIVE-видимости или Docker Desktop. Их проверяют отдельно на
разрешённом Linux-узле и настоящем Mac.
<a id="release-candidate-acceptance"></a>
## Приёмка release candidate
Одна последовательность использует fixtures выше; второй инфраструктуры нет. **Это подготовленная процедура, не новый выполненный runtime-прогон.** Запускайте из корня repo под обычным пользователем на разрешённом **native Linux AMD64** Docker host. Это не первая установка Mac; её маршрут — [первый запуск Mac](../docs/MACOS_FIRST_RUN-RU.md). Выполнение этих Linux fixtures через Desktop/эмуляцию — NOT VERIFIED. Published release probe использует Linux client, не native Darwin client.
Нужно заранее: закреплённые clean checkouts в `local/sources/s4dfarm`, `local/sources/neo`, `local/sources/packmate`; кеш Linux AMD64 images из integration/deployment locks; закреплённый Linux Neo archive в `local/downloads/neo_client_2.4.2_linux_amd64.tar.gz`. Подготовка/build зависимостей требует отдельной разрешённой online-фазы. Не подставляйте operator/competition workspace. Недостающие зависимости означают BLOCKED, не разрешение скачать latest.
Выполняйте команды по порядку и остановитесь при первом ненулевом результате; применённые fixtures должны выдавать PASS. Исключение — находка сканера в уязвимом lab (ожидается `1`). Workspace/project IDs и synthetic markers генерируются автоматически; заполнять evidence-карточки и переписывать хеши не нужно. Synthetic-флаги получает только созданный внутренний mock receiver; **реальная отправка выключена**.
```bash
set -euo pipefail
umask 077
mkdir -p local
RC_RUN="$(mktemp -d "$PWD/local/rc-acceptance.XXXXXX")"
PM_DB="$(python3 -c 'import durka; print(durka.kit.PACKMATE_DB)')"
python3 integration/stack_smoke.py prepare --workspace "$RC_RUN/stack" --s4dfarm-source local/sources/s4dfarm --neo-source local/sources/neo --images config/integration-images.lock.json --apply --approval-id rc-synthetic
python3 integration/stack_smoke.py build --workspace "$RC_RUN/stack" --apply --approval-id rc-synthetic
python3 integration/packmate_smoke.py prepare --workspace "$RC_RUN/packmate" --source local/sources/packmate --postgres-image "$PM_DB" --apply --approval-id rc-synthetic
python3 integration/neo_release_smoke.py prepare --workspace "$RC_RUN/client" --archive local/downloads/neo_client_2.4.2_linux_amd64.tar.gz --apply --approval-id rc-synthetic
python3 integration/neo_lifecycle_smoke.py prepare --workspace "$RC_RUN/task" --apply --approval-id rc-synthetic
```
Build может скачивать compiler/package dependencies; закончите его **до** offline-фазы. Одного кеша base images недостаточно. Пути fixture, sources и API проверяются существующими скриптами. Не нужны LIVE capture, privilege, host networking и настоящая цель.
```bash
python3 integration/stack_smoke.py up --workspace "$RC_RUN/stack" --apply --approval-id rc-synthetic
python3 integration/stack_smoke.py smoke --workspace "$RC_RUN/stack" --apply --approval-id rc-synthetic
python3 integration/neo_release_smoke.py smoke --workspace "$RC_RUN/client" --stack-workspace "$RC_RUN/stack" --apply --approval-id rc-synthetic
python3 integration/neo_lifecycle_smoke.py smoke --workspace "$RC_RUN/task" --release-workspace "$RC_RUN/client" --stack-workspace "$RC_RUN/stack" --apply --approval-id rc-synthetic
python3 integration/packmate_smoke.py up --workspace "$RC_RUN/packmate" --apply --approval-id rc-synthetic
python3 integration/packmate_smoke.py smoke --workspace "$RC_RUN/packmate" --apply --approval-id rc-synthetic
python3 scripts/defense_ops.py preflight --profile config/defense-profile.example.json
python3 integration/vulnbox_handoff.py
```
Ожидаем: authenticated API/config Farm и отказ missing/wrong auth; exact release auth Neo, безвредный disabled-first `printf`, single execution, принятие Farm/mock receiver и reconnect worker; auth Packmate, один synthetic stream с точными request/response/directions; Defense CLI и source review/сравнение ручного fixture-патча. Worker-тесты доказывают только свои shell-зависимости, не произвольные Python/JS scripts. Не повторяйте fresh-database Packmate smoke на уже обработанных данных; persistence проверяется отдельно ниже.
Сначала корректно остановите templates, чтобы ограничить одновременную нагрузку; данные/образы остаются в приватных каталогах:
```bash
python3 integration/packmate_smoke.py down --workspace "$RC_RUN/packmate" --apply --approval-id rc-synthetic
python3 integration/stack_smoke.py down --workspace "$RC_RUN/stack" --apply --approval-id rc-synthetic
```
После подтверждения snapshot этого test host выполните recovery в **новые** synthetic projects. Никогда не передавайте `--snapshot-confirmed` без настоящего snapshot. Operator data не копируются. Автоматические submission/capture replay остаются выключенными в восстановленных targets.
```bash
python3 integration/stack_recovery_smoke.py prepare --workspace "$RC_RUN/recovery" --stack-workspace "$RC_RUN/stack" --packmate-workspace "$RC_RUN/packmate" --release-workspace "$RC_RUN/client" --apply --approval-id rc-synthetic
python3 integration/stack_recovery_smoke.py run --workspace "$RC_RUN/recovery" --apply --approval-id rc-synthetic --snapshot-confirmed
```
Ожидаем сохранность settings, synthetic flags, disabled Neo task/state, Packmate services/patterns/streams после контролируемой остановки, native dumps/cold copies и isolated restore. `result.json` содержит время (цели: RPO 300s / RTO 600s), проверки и scoped shutdown. Data/backups остаются. FAIL/PARTIAL/BLOCKED или неудачный cleanup запрещает приёмку.
Для полного **offline startup** используйте `offline_runtime_smoke.py`, не build fixture с доступной сетью. Задайте `RC_TEMPLATE` — ранее подготовленный native Linux AMD64 synthetic deployment из `deployment/toolkit.py` (не competition workspace), и `RC_IMAGES` — его проверенный полный приватный image bundle. Используйте существующие [offline cache utilities](../docs/offline-bundles-RU.md); нужны все runtime/helper images. Без bundle offline acceptance остаётся BLOCKED. Сохраните snapshot host и согласованный local Docker context.
```bash
RC_DAEMON="$(docker info --format '{{.ID}}')"
python3 integration/offline_runtime_smoke.py prepare --workspace "$RC_RUN/offline" --template "$RC_TEMPLATE" --image-bundle "$RC_IMAGES" --daemon-id "$RC_DAEMON" --apply --approval-id rc-synthetic
python3 integration/offline_runtime_smoke.py run --workspace "$RC_RUN/offline" --apply --approval-id rc-synthetic --snapshot-confirmed
python3 integration/offline_runtime_smoke.py down --workspace "$RC_RUN/offline" --apply --approval-id rc-synthetic
```
Ожидаем только подготовленные immutable images, запрет внешней сети внутри своих test resources, полный synthetic Farm/Neo/Packmate cycle, restart/persistence и чистую scoped-остановку. Host/router network не меняются; это не доказывает установку на пустой ноутбук. На Mac выполните отдельную disconnected Desktop rehearsal из first-run guide.
При ошибке остановите только точный owned project через `down` его fixture. Recovery/offline fixtures записывают automatic cleanup; при неудаче проверьте приватный result и точные labelled resources до повтора. Нельзя `prune`, `down -v` и удаление run directory вместо cleanup. Храните результаты приватно; не коммитьте logs/PCAP и не объявляйте Mac ready по Linux PASS.
+140
View File
@@ -0,0 +1,140 @@
# Synthetic integration tests
English | [Русский](README-RU.md)
These are developer fixtures, **not the deployment instructions**. For a working team stack use [durka.py and the admin guide](../deployment/README.md).
## Isolation and prerequisites
Opt-in Docker tests run only in a dedicated private workspace with synthetic credentials/data. Use an approved Linux Docker Engine, cached locked images, unique project names and available resources. Recovery and fault-injection runs require a host snapshot. They do not inspect unrelated workloads.
## Prepare and run
Read a fixture's help, preview preparation, then apply it deliberately. Profiles cannot contain shell commands. Run from the repository root. Results stay in the chosen private workspace, not in Git.
```bash
python3 integration/stack_smoke.py --help
python3 integration/packmate_smoke.py --help
```
## Rollback and failures
Use the fixture's own shutdown; never global prune or deletion of shared volumes. Failed runs retain local results/data for diagnosis. Review exact-resource cleanup before retrying in a fresh workspace.
## Evidence boundaries
A synthetic test is not a certification of Docker Desktop, event capture or real participant access. CI run logs and private run outputs replace committed historical report files. See [capabilities and limits](../docs/CAPABILITY_INVENTORY.md).
## Packmate FILE-only fixture
`packmate_smoke.py` tests closed synthetic PCAP import, authentication and known streams. It cannot establish continuous capture.
## Native PostgreSQL recovery drill
`recovery_smoke.py` checks native dump/restore into isolated databases. Never substitute live competition volumes for its synthetic inputs.
## Published Neo release client
`neo_release_smoke.py` verifies the pinned published client against the pinned server; it does not silently select latest.
## Harmless Neo task lifecycle
`neo_lifecycle_smoke.py` exercises a harmless task, result, reconnect and disable sequence. Workers execute trusted code; do not feed them arbitrary tasks.
## Native Redis recovery
`component_recovery_smoke.py` checks native persistence and recovery in an isolated fixture. Real submission queues need a separate replay decision.
## Packmate authentication logger canary
`packmate_logger_smoke.py` verifies the configuration-only suppression of the failed-auth logger against a disposable canary and positive control. It does not certify every possible log path.
## Whole-stack synthetic recovery
`stack_recovery_smoke.py` restores synthetic farm, Neo and Packmate state into new projects, keeping automatic submission disabled. This is not permission to overwrite an existing deployment.
## Synthetic LIVE capture
`packmate_live_smoke.py` observes only its synthetic Linux network/namespace. It tests TCP/UDP, timeout and restart behavior, not real Vulnbox visibility or sustained load.
## Network-isolated offline runtime rehearsal
`offline_runtime_smoke.py` cold-starts an isolated Linux stack from prepared images and checks network denial plus retained synthetic state. It does not install a complete toolchain on a clean laptop. For normal offline preparation see [offline operation](../docs/offline-bundles.md).
Individual fixtures expose their arguments through `--help`; guarded low-level flags are for developers, not forms an ordinary operator must fill.
## Portable synthetic Vulnbox handoff
`vulnbox_handoff.py` retrieves a small closed synthetic PCAP over loopback HTTP,
validates its framing, rejects truncation, and exercises Docker source review
before and after fixture-only manual edits. It never starts privileged containers.
The macOS workflow accepts an optional bounded synthetic PCAP as base64 input;
otherwise it generates one locally. Do not supply real traffic or secrets.
This tests portable file handling and scanner commands, **not** direct VM access,
Packmate processing, LIVE visibility or Docker Desktop. Test those separately on
an approved Linux host and the actual Mac.
## Release-candidate acceptance
One sequence reuses the fixtures above; no second infrastructure is introduced. **Prepared procedure, not a newly executed runtime result.** Run from the repo root on an approved, non-root **native Linux AMD64** Docker host. It is not the first Mac installation; that route is [First Mac run](../docs/MACOS_FIRST_RUN.md). Desktop/emulated execution of these Linux fixtures is NOT VERIFIED. The published release probe uses the Linux client, not the native Darwin client.
Prerequisites: locked, clean checkouts at `local/sources/s4dfarm`, `local/sources/neo`, `local/sources/packmate`; cached Linux AMD64 images from the integration/deployment locks; the locked Linux Neo archive at `local/downloads/neo_client_2.4.2_linux_amd64.tar.gz`. Preparing/building dependencies requires a separately approved online phase. Do not substitute an operator/competition workspace. Missing prerequisites mean BLOCKED, not permission to fetch latest.
Run commands in order and stop at the first nonzero result; every applied fixture should report PASS. A scanner finding in the vulnerable lab is the exception (expected `1`). Workspace/project IDs and synthetic markers are generated automatically; do not fill evidence cards or copy hashes manually. Only the generated internal mock receiver receives synthetic flags; **real flag submission remains disabled**.
```bash
set -euo pipefail
umask 077
mkdir -p local
RC_RUN="$(mktemp -d "$PWD/local/rc-acceptance.XXXXXX")"
PM_DB="$(python3 -c 'import durka; print(durka.kit.PACKMATE_DB)')"
python3 integration/stack_smoke.py prepare --workspace "$RC_RUN/stack" --s4dfarm-source local/sources/s4dfarm --neo-source local/sources/neo --images config/integration-images.lock.json --apply --approval-id rc-synthetic
python3 integration/stack_smoke.py build --workspace "$RC_RUN/stack" --apply --approval-id rc-synthetic
python3 integration/packmate_smoke.py prepare --workspace "$RC_RUN/packmate" --source local/sources/packmate --postgres-image "$PM_DB" --apply --approval-id rc-synthetic
python3 integration/neo_release_smoke.py prepare --workspace "$RC_RUN/client" --archive local/downloads/neo_client_2.4.2_linux_amd64.tar.gz --apply --approval-id rc-synthetic
python3 integration/neo_lifecycle_smoke.py prepare --workspace "$RC_RUN/task" --apply --approval-id rc-synthetic
```
The build may download compiler/package dependencies; finish it **before** the offline phase. Cached base images alone are insufficient. These fixture paths, sources and API semantics are guarded by the existing scripts. No LIVE capture, privilege, host networking or real target is needed.
```bash
python3 integration/stack_smoke.py up --workspace "$RC_RUN/stack" --apply --approval-id rc-synthetic
python3 integration/stack_smoke.py smoke --workspace "$RC_RUN/stack" --apply --approval-id rc-synthetic
python3 integration/neo_release_smoke.py smoke --workspace "$RC_RUN/client" --stack-workspace "$RC_RUN/stack" --apply --approval-id rc-synthetic
python3 integration/neo_lifecycle_smoke.py smoke --workspace "$RC_RUN/task" --release-workspace "$RC_RUN/client" --stack-workspace "$RC_RUN/stack" --apply --approval-id rc-synthetic
python3 integration/packmate_smoke.py up --workspace "$RC_RUN/packmate" --apply --approval-id rc-synthetic
python3 integration/packmate_smoke.py smoke --workspace "$RC_RUN/packmate" --apply --approval-id rc-synthetic
python3 scripts/defense_ops.py preflight --profile config/defense-profile.example.json
python3 integration/vulnbox_handoff.py
```
Expected: Farm authenticated API/config and rejection of missing/wrong auth; Neo exact release auth, disabled-first harmless `printf`, single execution, farm/mock-receiver acceptance and worker reconnect; Packmate auth, one synthetic stream with exact request/response/directions; Defense CLI and source review/manual fixture-patch comparison. Worker tests only prove their shell dependencies, not arbitrary Python/JS scripts. Do not rerun fresh-database Packmate smoke on already processed data; persistence is checked separately below.
Cleanly stop the templates first to limit resource overlap; data/images stay in their private directories:
```bash
python3 integration/packmate_smoke.py down --workspace "$RC_RUN/packmate" --apply --approval-id rc-synthetic
python3 integration/stack_smoke.py down --workspace "$RC_RUN/stack" --apply --approval-id rc-synthetic
```
After confirming a snapshot of this test host, run recovery into **new** synthetic projects. Never pass `--snapshot-confirmed` without an actual snapshot. No existing operator data is copied. Automatic submission/capture replay stays disabled in restored targets.
```bash
python3 integration/stack_recovery_smoke.py prepare --workspace "$RC_RUN/recovery" --stack-workspace "$RC_RUN/stack" --packmate-workspace "$RC_RUN/packmate" --release-workspace "$RC_RUN/client" --apply --approval-id rc-synthetic
python3 integration/stack_recovery_smoke.py run --workspace "$RC_RUN/recovery" --apply --approval-id rc-synthetic --snapshot-confirmed
```
Expected: settings, synthetic flags, disabled Neo task/state, Packmate services/patterns/streams preserved through controlled stop, native dumps/cold copies and isolated restore. `result.json` records timing (targets: RPO 300s / RTO 600s), all checks and scoped shutdown. Data/backups remain. A FAIL/PARTIAL/BLOCKED or unsuccessful cleanup prevents acceptance.
For full **offline startup**, reuse `offline_runtime_smoke.py`, not the network-capable build fixture. Set `RC_TEMPLATE` to an already prepared native Linux AMD64 synthetic deployment from `deployment/toolkit.py` (never a competition workspace), and `RC_IMAGES` to its verified complete private image bundle. Use the existing [offline cache utilities](../docs/offline-bundles.md); all runtime/helper images must be present. No bundle means offline acceptance remains BLOCKED. Keep the host snapshot and approved local Docker context.
```bash
RC_DAEMON="$(docker info --format '{{.ID}}')"
python3 integration/offline_runtime_smoke.py prepare --workspace "$RC_RUN/offline" --template "$RC_TEMPLATE" --image-bundle "$RC_IMAGES" --daemon-id "$RC_DAEMON" --apply --approval-id rc-synthetic
python3 integration/offline_runtime_smoke.py run --workspace "$RC_RUN/offline" --apply --approval-id rc-synthetic --snapshot-confirmed
python3 integration/offline_runtime_smoke.py down --workspace "$RC_RUN/offline" --apply --approval-id rc-synthetic
```
Expected: prepared immutable images only, denied external networking in owned test resources, full synthetic Farm/Neo/Packmate cycle, restart/persistence and clean scoped shutdown. It does not alter host/router networking or prove a blank-laptop installation. On Mac, perform the separate disconnected Desktop rehearsal in the first-run guide.
If a phase fails, stop only the exact owned project using its fixture's `down`. Recovery/offline fixtures record automatic cleanup; if that fails, inspect their private result and exact labelled resources before retrying. Never `prune`, `down -v` or remove the run directory as a substitute for cleanup. Retain outputs privately; do not commit logs/PCAP or declare target-Mac readiness from Linux PASS.
+196
View File
@@ -0,0 +1,196 @@
#!/usr/bin/env python3
"""Opt-in native Redis RDB recovery using new synthetic source/target only.
No existing deployment or shared database is accepted. This does not validate
Neo's bbolt state, Packmate PostgreSQL or their application-level recovery.
"""
from __future__ import annotations
import argparse
import hashlib
import importlib.util
import json
import os
from pathlib import Path
import re
import secrets
import sys
import time
SPEC = importlib.util.spec_from_file_location("component_release", Path(__file__).with_name("neo_release_smoke.py"))
safe = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(safe)
shared = safe.shared
Error = shared.FixtureError
SCHEMA = "durkahelper.redis-recovery.v1"
LABEL = "io.durkahelper.redis-recovery"
KEY = "durkahelper:synthetic:recovery"
MAX_RDB = 1024 * 1024
NOT_VALIDATED = ["Neo bbolt application recovery", "Packmate application recovery", "real Redis queues", "whole-stack recovery", "Docker Desktop", "competition RPO/RTO"]
def prepare(args):
root = shared.no_links(args.workspace)
if root.exists() or not root.parent.is_dir():
raise Error("recovery workspace must be a new directory under existing parent")
if not args.apply:
return {"status": "NOT_RUN", "action": "prepare", "effects": ["new private synthetic source/restore directories"], "not_validated": NOT_VALIDATED}
if os.name == "nt":
raise Error("native recovery drill requires POSIX ownership")
images = shared.image_map(Path(__file__).resolve().parents[1] / "config/integration-images.lock.json")
root.mkdir(mode=0o700)
for name in ("source", "restore"):
(root / name).mkdir(mode=0o700)
state = {"schema": SCHEMA, "id": "dh-redis-recovery-" + secrets.token_hex(6), "image": images["redis"],
"marker": secrets.token_hex(16), "approval_id": args.approval_id, "uid": os.getuid(), "gid": os.getgid()}
shared.write(root / "fixture.json", shared.canonical(state))
return {"status": "PASS", "action": "prepare", "fixture": state["id"], "not_validated": NOT_VALIDATED}
def fixture(path):
root = shared.no_links(path)
state = json.loads(safe.bounded_read(root / "fixture.json", 16384))
images = shared.image_map(Path(__file__).resolve().parents[1] / "config/integration-images.lock.json")
if (set(state) != {"schema", "id", "image", "marker", "approval_id", "uid", "gid"} or state["schema"] != SCHEMA or
not re.fullmatch(r"dh-redis-recovery-[a-f0-9]{12}", state["id"]) or state["image"] != images["redis"] or
not re.fullmatch(r"[a-f0-9]{32}", state["marker"]) or not re.fullmatch(r"[A-Za-z0-9_.-]{1,80}", state["approval_id"])):
raise Error("invalid Redis recovery fixture identity")
for name in ("source", "restore"):
folder = shared.no_links(root / name)
if not folder.is_dir():
raise Error("recovery data directories must exist")
return root, state
def arguments(root, state, role):
if role not in {"source", "restore"}:
raise Error("invalid synthetic recovery role")
if any(c in str(root) for c in (",", "\n", "\r")):
raise Error("mount delimiter not permitted")
return ["docker", "create", "--name", state["id"] + "-" + role, "--label", LABEL + "=" + state["id"],
"--network", "none", "--user", str(state["uid"]) + ":" + str(state["gid"]), "--read-only", "--cap-drop=ALL",
"--security-opt=no-new-privileges:true", "--memory=128m", "--memory-swap=128m", "--cpus=0.5", "--pids-limit=32",
"--log-driver=none", "--pull=never", "--mount", "type=bind,src=" + str(root / role) + ",dst=/data",
"--entrypoint", "redis-server", state["image"], "--bind", "127.0.0.1", "--protected-mode", "yes", "--dir", "/data",
"--dbfilename", "dump.rdb", "--appendonly", "no", "--save", ""]
def own(state, role):
name = state["id"] + "-" + role
actual = shared.checked(["docker", "inspect", "--format", '{{index .Config.Labels "' + LABEL + '"}}', name], capture=True).decode().strip()
if actual != state["id"]:
raise Error("Redis recovery ownership mismatch")
return name
def cli(state, role, operation, *values):
if operation not in {"PING", "SET", "GET", "DBSIZE", "SAVE"}:
raise Error("unsupported synthetic Redis operation")
return shared.checked(["docker", "exec", own(state, role), "redis-cli", "--raw", operation] + list(values), timeout=10, capture=True).strip()
def ready(state, role):
deadline = time.monotonic() + 30
while time.monotonic() < deadline:
try:
if cli(state, role, "PING") == b"PONG":
return
except Error:
pass
time.sleep(0.5)
raise Error("synthetic Redis readiness timed out")
def cleanup(state, role):
name = own(state, role)
shared.checked(["docker", "rm", "--force", name], timeout=20)
def smoke(args):
root, state = fixture(args.workspace)
if not args.apply:
return {"status": "NOT_RUN", "action": "smoke", "effects": ["new source and restored Redis containers without networking", "native SAVE", "bounded RDB copy"],
"rollback": "remove only exact labelled clients; all data/dump files retained", "not_validated": NOT_VALIDATED}
if not args.snapshot_confirmed:
raise Error("recovery drill requires --snapshot-confirmed")
if os.name == "nt" or (state["uid"], state["gid"]) != (os.getuid(), os.getgid()) or state["uid"] == 0:
raise Error("drill requires the same non-root POSIX workspace owner")
if any(any((root / name).iterdir()) for name in ("source", "restore")) or (root / "dump.rdb").exists():
raise Error("recovery fixture already used; prepare a fresh workspace")
architecture = shared.checked(["docker", "image", "inspect", "--format", "{{.Os}};{{.Architecture}}", state["image"]], capture=True).decode().strip()
if architecture not in {"linux;amd64", "linux;arm64"}:
raise Error("cached pinned Redis image must be a supported Linux architecture")
created, checks = [], {}
try:
shared.checked(arguments(root, state, "source"))
created.append("source")
shared.checked(["docker", "start", own(state, "source")])
ready(state, "source")
if cli(state, "source", "DBSIZE") != b"0":
raise Error("new Redis source contains unexpected data")
write_at = time.monotonic()
checks["synthetic_write"] = cli(state, "source", "SET", KEY, state["marker"]) == b"OK"
if not checks["synthetic_write"] or cli(state, "source", "DBSIZE") != b"1":
raise Error("synthetic source content did not match")
checks["native_save"] = cli(state, "source", "SAVE") == b"OK"
save_at = time.monotonic()
shared.checked(["docker", "stop", "--time", "10", own(state, "source")], timeout=20)
dump = safe.bounded_read(root / "source/dump.rdb", MAX_RDB)
if not dump.startswith(b"REDIS") or len(dump) < 20:
raise Error("native SAVE did not produce a valid bounded RDB header")
checksum = hashlib.sha256(dump).hexdigest()
shared.write(root / "dump.rdb", dump)
recovery_at = time.monotonic()
shared.write(root / "restore/dump.rdb", dump)
shared.checked(arguments(root, state, "restore"))
created.append("restore")
shared.checked(["docker", "start", own(state, "restore")])
ready(state, "restore")
checks["restored_value"] = cli(state, "restore", "GET", KEY) == state["marker"].encode()
checks["restored_key_count"] = cli(state, "restore", "DBSIZE") == b"1"
recovered_at = time.monotonic()
checks["source_dump_unchanged"] = hashlib.sha256(safe.bounded_read(root / "source/dump.rdb", MAX_RDB)).hexdigest() == checksum
rpo = save_at - write_at
rto = recovered_at - recovery_at
checks["synthetic_rpo_under_300s"] = rpo <= 300
checks["synthetic_rto_under_600s"] = rto <= 600
finally:
failures = []
for role in reversed(created):
try:
cleanup(state, role)
except Error:
failures.append(role)
if failures:
raise Error("exact owned Redis cleanup requires attention: " + ", ".join(failures))
return {"schema": "durkahelper.component-recovery-report.v1", "component": "redis", "status": "PASS" if all(checks.values()) else "FAIL",
"checks": checks, "image": state["image"], "architecture": architecture, "dump_sha256": checksum, "dump_bytes": len(dump),
"synthetic_rpo_seconds": round(rpo, 3), "synthetic_rto_seconds": round(rto, 3), "not_validated": NOT_VALIDATED,
"scope": "one synthetic Redis key saved natively and restored into a new isolated database; not real queue recovery",
"rollback": "exact owned containers removed; source, restore and native dump files retained"}
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("action", choices=["prepare", "smoke"])
parser.add_argument("--workspace", required=True)
parser.add_argument("--apply", action="store_true")
parser.add_argument("--approval-id")
parser.add_argument("--snapshot-confirmed", action="store_true")
args = parser.parse_args(argv)
try:
if args.apply and not (args.approval_id and re.fullmatch(r"[A-Za-z0-9_.-]{1,80}", args.approval_id)):
raise Error("mutations require --apply and a non-secret approval identifier")
result = prepare(args) if args.action == "prepare" else smoke(args)
print(json.dumps(result, sort_keys=True, indent=2))
return 1 if result["status"] == "FAIL" else 0
except KeyboardInterrupt:
print(json.dumps({"status": "BLOCKED", "reason": "interrupted; inspect exact fixture identity; data retained", "raw_output": "suppressed"}))
return 2
except (Error, OSError, ValueError, KeyError, TypeError) as error:
print(json.dumps({"status": "BLOCKED", "reason": str(error) if isinstance(error, Error) else type(error).__name__, "raw_output": "suppressed"}))
return 2
if __name__ == "__main__":
sys.exit(main())
+208
View File
@@ -0,0 +1,208 @@
#!/usr/bin/env python3
"""Opt-in harmless Neo lifecycle on an already running synthetic fixture only.
The fixed payload only prints a synthetic flag. It does not contact team IPs,
read credentials, run exploits, alter target services or expose ports. Output is
bounded and suppressed; the original fixture and disabled test entry remain.
"""
from __future__ import annotations
import argparse
import hashlib
import importlib.util
import json
import os
from pathlib import Path
import re
import secrets
import sys
import time
SPEC = importlib.util.spec_from_file_location("lifecycle_release", Path(__file__).with_name("neo_release_smoke.py"))
release = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(release)
shared = release.shared
Error = shared.FixtureError
SCHEMA = "durkahelper.neo-lifecycle.v1"
LABEL = "io.durkahelper.neo-lifecycle"
def payload(flag):
if not re.fullmatch(r"[A-F0-9]{31}=", flag):
raise Error("invalid synthetic flag")
# Upstream checks a flush marker for non-Python scripts; POSIX printf exits
# immediately, so no buffered process survives beyond this fixed payload.
return ("#!/bin/sh\n# flush=True: printf exits immediately\nprintf '%s\\n' '" + flag + "'\n").encode()
def config(identity):
if not re.fullmatch(r"dh-life-[a-f0-9]{12}", identity):
raise Error("invalid lifecycle identity")
return ('host: "neo-server:5005"\ngrpc_auth_key: "fixture-only"\nexploit_dir: "/work/exploits"\nclient_id: "' + identity + '"\n').encode()
def prepare(args):
root = shared.no_links(args.workspace)
if root.exists() or not root.parent.is_dir():
raise Error("lifecycle workspace must be new under existing parent")
if not args.apply:
return {"status": "NOT_RUN", "action": "prepare", "effects": ["private synthetic payload/config workspace"]}
root.mkdir(mode=0o700)
identity = "dh-life-" + secrets.token_hex(6)
flag = secrets.token_hex(16).upper()[:31] + "="
state = {"schema": SCHEMA, "id": identity, "flag": flag, "approval_id": args.approval_id}
shared.write(root / "fixture.json", shared.canonical(state))
shared.write(root / "client.yml", config(identity))
shared.write(root / "synthetic.sh", payload(flag))
for name in ("client.yml", "synthetic.sh"):
(root / name).chmod(0o644)
return {"status": "PASS", "action": "prepare", "fixture": identity, "payload_sha256": hashlib.sha256(payload(flag)).hexdigest()}
def fixture(path):
root = shared.no_links(path)
state = json.loads(release.bounded_read(root / "fixture.json", 16384))
if set(state) != {"schema", "id", "flag", "approval_id"} or state["schema"] != SCHEMA:
raise Error("invalid lifecycle fixture")
if release.bounded_read(root / "client.yml", 4096) != config(state["id"]) or release.bounded_read(root / "synthetic.sh", 4096) != payload(state["flag"]):
raise Error("synthetic lifecycle payload/config changed")
return root, state
def arguments(root, state, binary, image, network, name, action):
allowed = {"worker": ["run", "--jobs", "1", "--endless-jobs", "0"],
"add": ["add", "--id", state["id"], "--disabled", "--interval", "1h", "--timeout", "3s", "/synthetic.sh"],
"single": ["single", state["id"]], "disable": ["disable", state["id"]], "info": ["info"]}
if action not in allowed:
raise Error("unsupported synthetic lifecycle action")
if any(character in str(root) + str(binary) for character in (",", "\n", "\r")):
raise Error("mount delimiters not permitted")
return ["docker", "create", "--name", name, "--label", LABEL + "=" + state["id"],
"--network", network, "--user", "65534:65534", "--read-only", "--cap-drop=ALL", "--security-opt=no-new-privileges:true",
"--memory=128m", "--memory-swap=128m", "--cpus=0.5", "--pids-limit=32", "--log-driver=none", "--pull=never",
"--mount", "type=bind,src=" + str(binary) + ",dst=/neo,readonly",
"--mount", "type=bind,src=" + str(root / "client.yml") + ",dst=/client.yml,readonly",
"--mount", "type=bind,src=" + str(root / "synthetic.sh") + ",dst=/synthetic.sh,readonly",
"--tmpfs", "/work:rw,nosuid,nodev,exec,size=16777216,mode=0700,uid=65534,gid=65534",
"--entrypoint", "/neo", image, "--verbose=false", "--config", "/client.yml"] + allowed[action]
def cleanup(name, identity):
actual = shared.checked(["docker", "inspect", "--format", '{{index .Config.Labels "' + LABEL + '"}}', name], capture=True).decode().strip()
if actual != identity:
raise Error("lifecycle cleanup ownership mismatch")
shared.checked(["docker", "rm", "--force", name], timeout=20)
def run_client(root, state, binary, image, network, action):
name = state["id"] + "-" + action + "-" + secrets.token_hex(4)
created = False
try:
shared.checked(arguments(root, state, binary, image, network, name, action))
created = True
code, output = release.capture(["docker", "start", "--attach", name], timeout=25)
if code:
raise Error("synthetic Neo command failed; raw output suppressed")
return output
finally:
# Exact random name plus owner label only; creation timeouts are reported
# for manual inspection rather than broad cleanup by a name prefix.
if created:
cleanup(name, state["id"])
def accepted(port, flag, identifier, timeout=45):
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
code, data = shared.request(port, "/api/filter_flags?flag=" + flag)
rows = json.loads(data).get("flags", []) if code == 200 else []
if any(row.get("flag") == flag and row.get("status") == "ACCEPTED" and row.get("sploit") == "[neo] " + identifier for row in rows):
return True
time.sleep(1)
return False
def smoke(args):
root, state = fixture(args.workspace)
release_root, _ = release.fixture(args.release_workspace)
stack_root, stack = shared.fixture(args.stack_workspace)
if not args.apply:
return {"status": "NOT_RUN", "action": "smoke", "effects": ["disabled synthetic entry on lab server", "temporary isolated worker", "one synthetic result", "worker restart"],
"rollback": "disable exact synthetic entry; remove only owned clients; retain original stack"}
cmd = shared.compose_command(stack_root, stack)
port = shared.farm_port(cmd)
shared.wait_ready(port)
code, data = shared.request(port, "/api/get_config")
if code != 200 or json.loads(data).get("TEAMS") != {"Synthetic": "192.0.2.1"}:
raise Error("lifecycle requires the unchanged synthetic team map")
network = stack["project"] + "_fixture"
descriptor = shared.checked(["docker", "network", "inspect", "--format", '{{.Internal}};{{index .Labels "com.docker.compose.project"}}', network], capture=True).decode().strip()
if descriptor != "true;" + stack["project"]:
raise Error("lifecycle requires the exact internal fixture network")
image = stack["images"]["alpine"]
architecture = shared.checked(["docker", "image", "inspect", "--format", "{{.Os}};{{.Architecture}}", image], capture=True).decode().strip()
if architecture != "linux;amd64":
raise Error("published lifecycle fixture is Linux amd64 only")
binary = release_root / "neo"
worker = state["id"] + "-worker-" + secrets.token_hex(4)
checks, created, added = {}, False, False
try:
info = run_client(root, state, binary, image, network, "info")
if state["id"].encode() + b'"' in info:
raise Error("lifecycle fixture already used; prepare a fresh identity")
run_client(root, state, binary, image, network, "add")
added = True
checks["disabled_payload_registered"] = True
shared.checked(arguments(root, state, binary, image, network, worker, "worker"))
created = True
shared.checked(["docker", "start", worker])
time.sleep(6)
run_client(root, state, binary, image, network, "single")
checks["synthetic_execution_and_mock_acceptance"] = accepted(port, state["flag"], state["id"])
# Restart only the exact worker; this tests client reconnection, not VM,
# network fault injection, server restore or database recovery.
shared.checked(["docker", "stop", "--time", "10", worker], timeout=20)
shared.checked(["docker", "start", worker])
time.sleep(6)
info = run_client(root, state, binary, image, network, "info")
checks["worker_reconnect"] = state["id"].encode() + b": [" in info
checks["server_retains_disabled_entry"] = state["id"].encode() in info and b"disabled:true" in info
finally:
try:
if added:
run_client(root, state, binary, image, network, "disable")
finally:
if created:
cleanup(worker, state["id"])
return {"schema": "durkahelper.neo-lifecycle-report.v1", "status": "PASS" if all(checks.values()) else "FAIL", "checks": checks,
"release": release.RELEASE, "archive_sha256": release.SHA256, "server_source": shared.PINS["neo"],
"payload_sha256": hashlib.sha256(payload(state["flag"])).hexdigest(),
"not_validated": ["real exploits", "server/database recovery", "Docker Desktop", "ARM64", "TLS", "metrics", "network failure"],
"rollback": "owned clients removed; disabled exact test entry and synthetic results retained on lab stack"}
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("action", choices=["prepare", "smoke"])
for option in ("workspace", "release-workspace", "stack-workspace", "approval-id"):
parser.add_argument("--" + option, required=option == "workspace")
parser.add_argument("--apply", action="store_true")
args = parser.parse_args(argv)
try:
if args.apply and not (args.approval_id and re.fullmatch(r"[A-Za-z0-9_.-]{1,80}", args.approval_id)):
raise Error("mutations require --apply and a non-secret approval identifier")
if args.action == "smoke" and not (args.release_workspace and args.stack_workspace):
raise Error("smoke requires both existing release and synthetic stack workspaces")
result = prepare(args) if args.action == "prepare" else smoke(args)
print(json.dumps(result, sort_keys=True, indent=2))
return 1 if result["status"] == "FAIL" else 0
except KeyboardInterrupt:
print(json.dumps({"status": "BLOCKED", "reason": "interrupted; inspect exact fixture identity; created clients cleaned in finally and test data retained", "raw_output": "suppressed"}))
return 2
except (Error, OSError, ValueError, KeyError, TypeError) as error:
print(json.dumps({"status": "BLOCKED", "reason": str(error) if isinstance(error, Error) else type(error).__name__, "raw_output": "suppressed"}))
return 2
if __name__ == "__main__":
sys.exit(main())
+324
View File
@@ -0,0 +1,324 @@
#!/usr/bin/env python3
"""Opt-in published Neo v2.4.2 Linux amd64 info/authentication smoke.
No exploit execution, source compilation, host networking or privileged client.
Uses a separate private workspace and an already running validated stack fixture.
Raw info output can contain farm credentials and is never printed or persisted.
"""
from __future__ import annotations
import argparse
import hashlib
import importlib.util
import io
import json
import os
from pathlib import Path
import re
import secrets
import stat
import subprocess
import sys
import tarfile
import threading
import time
import urllib.parse
import urllib.request
SPEC = importlib.util.spec_from_file_location("neo_release_shared", Path(__file__).with_name("stack_smoke.py"))
shared = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(shared)
FixtureError = shared.FixtureError
RELEASE = "v2.4.2"
ASSET = "neo_client_2.4.2_linux_amd64.tar.gz"
PREFIX = "neo_client_2.4.2_linux_amd64/"
URL = "https://github.com/C4T-BuT-S4D/neo/releases/download/v2.4.2/" + ASSET
SHA256 = "42a0affe303195693f29f1998ac13fac9238db71e7395674f5141bfc553274de"
SIZE = 5326241
MAX_BINARY = 32 * 1024 * 1024
MAX_OUTPUT = 65536
SCHEMA = "durkahelper.neo-release-fixture.v1"
LABEL = "durkahelper.neo-release"
NOT_VALIDATED = ["exploit execution", "task lifecycle", "metrics", "TLS", "recovery",
"Apple Silicon", "Docker Desktop", "team Ethernet access", "competition adapter"]
def bounded_read(path, limit):
path = shared.no_links(path)
before = path.lstat()
if not stat.S_ISREG(before.st_mode) or before.st_size > limit:
raise FixtureError("input must be a bounded regular file")
fd = os.open(path, os.O_RDONLY | getattr(os, "O_BINARY", 0) |
getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0))
try:
opened = os.fstat(fd)
fields = lambda s: (s.st_dev, s.st_ino, s.st_size, s.st_mtime_ns)
if not stat.S_ISREG(opened.st_mode) or fields(before) != fields(opened):
raise FixtureError("input changed during open")
with os.fdopen(fd, "rb", closefd=False) as stream:
result = stream.read(limit + 1)
if len(result) > limit or fields(opened) != fields(os.fstat(fd)):
raise FixtureError("input changed during read or exceeds limit")
return result
finally:
os.close(fd)
def check_lock(path):
lock = json.loads(bounded_read(path, 1024 * 1024))
neo = lock["components"]["neo"]
assets = [a for a in neo["release"]["assets"] if a["name"] == ASSET]
if (neo["release"]["tag"] != RELEASE or neo["source"]["commit"] != shared.PINS["neo"] or
len(assets) != 1 or any(assets[0].get(k) != v for k, v in {
"url": URL, "published_sha256": SHA256, "size": SIZE,
"os": "linux", "architecture": "amd64"}.items())):
raise FixtureError("toolchain lock does not match the exact reviewed release/source pair")
class ReleaseRedirect(urllib.request.HTTPRedirectHandler):
def redirect_request(self, req, fp, code, msg, headers, newurl):
parsed = urllib.parse.urlsplit(newurl)
if (parsed.scheme != "https" or parsed.hostname not in {"github.com", "release-assets.githubusercontent.com"}
or parsed.username or parsed.password or parsed.port not in {None, 443}):
raise FixtureError("release download redirect outside approved HTTPS hosts")
return super().redirect_request(req, fp, code, msg, headers, newurl)
def download():
opener = urllib.request.build_opener(urllib.request.ProxyHandler({}), ReleaseRedirect())
with opener.open(URL, timeout=20) as response:
if response.status != 200:
raise FixtureError("release download did not return HTTP 200")
data = response.read(SIZE + 1)
return data
def release_binary(data):
# Verify the independently published archive digest before decompression.
if len(data) != SIZE or hashlib.sha256(data).hexdigest() != SHA256:
raise FixtureError("release archive size or SHA-256 mismatch")
allowed = {PREFIX + name for name in ("README.md", "client_config.yml", "exploits/.keep", "neo")}
seen, total, binary = set(), 0, None
with tarfile.open(fileobj=io.BytesIO(data), mode="r:gz") as archive:
for member in archive:
if member.name not in allowed or member.name in seen or not member.isfile():
raise FixtureError("unexpected, duplicate or non-regular release archive member")
seen.add(member.name)
total += member.size
if member.size < 0 or total > MAX_BINARY:
raise FixtureError("expanded release exceeds limit")
if member.name == PREFIX + "neo":
with archive.extractfile(member) as stream:
binary = stream.read(MAX_BINARY + 1)
if len(binary) != member.size:
raise FixtureError("truncated release executable")
if seen != allowed or binary is None:
raise FixtureError("release archive has missing members")
if (len(binary) < 64 or binary[:6] != b"\x7fELF\x02\x01" or
int.from_bytes(binary[18:20], "little") != 62):
raise FixtureError("release executable is not ELF64 Linux amd64")
return binary
def client_config(denied=False):
key = "incorrect-fixture-key" if denied else "fixture-only"
return ('host: "neo-server:5005"\ngrpc_auth_key: "' + key + '"\n'
'exploit_dir: "/tmp/unused"\nclient_id: "synthetic-release-info-client"\n').encode()
def prepare(args):
check_lock(args.lock)
root = shared.no_links(args.workspace)
if any(character in str(root) for character in (",", "\n", "\r")):
raise FixtureError("fixture path cannot contain Docker mount delimiters")
if root.exists() or not root.parent.is_dir():
raise FixtureError("workspace must be new under an existing parent")
if not args.apply:
return {"status": "NOT_RUN", "action": "prepare", "release": RELEASE, "sha256": SHA256,
"effects": ["optional bounded HTTPS download", "new private fixture directory"]}
data = download() if args.download else bounded_read(args.archive, SIZE)
binary = release_binary(data)
root.mkdir(mode=0o700)
state = {"schema": SCHEMA, "id": "dh-neo-release-" + secrets.token_hex(6),
"release": RELEASE, "archive_sha256": SHA256, "approval_id": args.approval_id}
for name, value in ((ASSET, data), ("neo", binary), ("client.yml", client_config()),
("denied.yml", client_config(True)), ("fixture.json", shared.canonical(state))):
shared.write(root / name, value)
# Bind-mounted synthetic files must be readable by the non-root client;
# their containing host workspace remains private mode 0700.
(root / "neo").chmod(0o555)
for name in ("client.yml", "denied.yml"):
(root / name).chmod(0o644)
return {"status": "PASS", "action": "prepare", "fixture": state["id"],
"release": RELEASE, "archive_sha256": SHA256,
"binary_sha256": hashlib.sha256(binary).hexdigest()}
def fixture(workspace):
root = shared.no_links(workspace)
if any(character in str(root) for character in (",", "\n", "\r")):
raise FixtureError("fixture path cannot contain Docker mount delimiters")
state = json.loads(bounded_read(root / "fixture.json", 16384))
if (set(state) != {"schema", "id", "release", "archive_sha256", "approval_id"} or
state["schema"] != SCHEMA or state["release"] != RELEASE or state["archive_sha256"] != SHA256 or
not re.fullmatch(r"dh-neo-release-[a-f0-9]{12}", state["id"]) or
not re.fullmatch(r"[A-Za-z0-9_.-]{1,80}", state["approval_id"])):
raise FixtureError("invalid release fixture identity")
binary = release_binary(bounded_read(root / ASSET, SIZE))
if bounded_read(root / "neo", MAX_BINARY) != binary:
raise FixtureError("release executable changed")
for name, denied in (("client.yml", False), ("denied.yml", True)):
if bounded_read(root / name, 4096) != client_config(denied):
raise FixtureError("synthetic client configuration changed")
return root, state
def container_arguments(root, state, network, image, denied, name):
config = root / ("denied.yml" if denied else "client.yml")
return ["docker", "create", "--name", name, "--label", LABEL + "=" + state["id"],
"--network", network, "--user", "65534:65534", "--read-only", "--cap-drop=ALL",
"--security-opt=no-new-privileges:true", "--memory=128m", "--memory-swap=128m",
"--cpus=0.5", "--pids-limit=32", "--log-driver=none", "--pull=never",
"--mount", "type=bind,src=" + str(root / "neo") + ",dst=/neo,readonly",
"--mount", "type=bind,src=" + str(config) + ",dst=/client.yml,readonly",
"--tmpfs", "/tmp:rw,noexec,nosuid,nodev,size=4194304,mode=0700,uid=65534,gid=65534",
"--entrypoint", "/neo", image, "--verbose=false", "--config", "/client.yml", "info"]
def cleanup(name, identity):
label = shared.checked(["docker", "inspect", "--format",
'{{index .Config.Labels "' + LABEL + '"}}', name], capture=True).decode().strip()
if label != identity:
raise FixtureError("release probe cleanup blocked: container ownership mismatch")
shared.checked(["docker", "rm", "--force", name], timeout=15)
def capture(argv, timeout=25):
"""Bound combined output in memory; never persist potentially sensitive info."""
output = bytearray()
done, overflow = threading.Event(), threading.Event()
process = subprocess.Popen(argv, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
def reader():
try:
while True:
chunk = process.stdout.read(4096)
if not chunk:
break
if len(output) + len(chunk) > MAX_OUTPUT:
overflow.set()
break
output.extend(chunk)
finally:
done.set()
worker = threading.Thread(target=reader, daemon=True)
worker.start()
deadline = time.monotonic() + timeout
try:
while not done.wait(0.05):
if time.monotonic() >= deadline:
raise FixtureError("release client timed out; raw output suppressed")
if overflow.is_set():
raise FixtureError("release client output exceeded limit; raw output suppressed")
return process.wait(timeout=max(0.1, deadline - time.monotonic())), bytes(output)
finally:
if process.poll() is None:
process.kill()
process.wait(timeout=5)
worker.join(timeout=1)
process.stdout.close()
def probe(root, state, network, image, denied):
name = state["id"] + "-" + secrets.token_hex(4)
# Generated exact name plus ownership label makes failure cleanup scoped.
try:
shared.checked(container_arguments(root, state, network, image, denied, name))
except FixtureError as error:
# A timed-out Docker create can still have created this exact container.
# Never broaden cleanup to another name or an unlabelled resource.
try:
cleanup(name, state["id"])
except FixtureError:
raise FixtureError("release client creation failed; inspect exact generated probe " + name +
" before manual cleanup; raw output suppressed") from error
raise
try:
return capture(["docker", "start", "--attach", name])
finally:
cleanup(name, state["id"])
def smoke(args):
root, state = fixture(args.workspace)
stack_root, stack = shared.fixture(args.stack_workspace)
if not args.apply:
return {"status": "NOT_RUN", "action": "smoke", "release": RELEASE,
"effects": ["two temporary info-only clients on validated internal fixture network"],
"not_validated": NOT_VALIDATED}
command = shared.compose_command(stack_root, stack)
shared.wait_ready(shared.farm_port(command))
project, network = stack["project"], stack["project"] + "_fixture"
actual = shared.checked(["docker", "network", "inspect", "--format",
'{{.Internal}};{{index .Labels "com.docker.compose.project"}};{{index .Labels "com.docker.compose.network"}}',
network], capture=True).decode().strip()
if actual != "true;" + project + ";fixture":
raise FixtureError("expected project-owned internal fixture network unavailable")
container = shared.checked(command + ["ps", "--quiet", "neo-server"], capture=True).decode().strip()
if not re.fullmatch(r"[a-f0-9]{64}", container):
raise FixtureError("expected running Neo server unavailable")
server = shared.checked(["docker", "inspect", "--format",
'{{.State.Running}};{{index .Config.Labels "com.docker.compose.project"}};{{index .Config.Labels "com.docker.compose.service"}};{{.Image}}',
container], capture=True).decode().strip().split(";")
if len(server) != 4 or server[:3] != ["true", project, "neo-server"] or not re.fullmatch(r"sha256:[a-f0-9]{64}", server[3]):
raise FixtureError("Neo server ownership or state mismatch")
image = stack["images"]["alpine"]
arch = shared.checked(["docker", "image", "inspect", "--format", "{{.Os}};{{.Architecture}}", image],
capture=True).decode().strip()
if arch != "linux;amd64":
raise FixtureError("release smoke requires cached native Linux amd64 runtime image")
code, valid = probe(root, state, network, image, False)
denied_code, denied = probe(root, state, network, image, True)
checks = {"published_release_info": code == 0 and all(marker in valid for marker in
(b"config:", b"IPs buckets:", b"Exploits:")),
"wrong_key_rejected": denied_code != 0 and b"Unauthenticated" in denied}
return {"schema": "durkahelper.neo-release-smoke.v1", "status": "PASS" if all(checks.values()) else "FAIL",
"release": RELEASE, "archive_sha256": SHA256, "server_source": shared.PINS["neo"],
"server_image_id": server[3], "runtime_image": image, "runtime_architecture": "linux/amd64",
"checks": checks, "not_validated": NOT_VALIDATED,
"scope": "published release-client info/auth against retained-source synthetic server/farm only",
"rollback": "owned one-shot clients removed; existing stack and prepared files retained"}
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("action", choices=["prepare", "smoke"])
parser.add_argument("--workspace", required=True)
parser.add_argument("--stack-workspace")
parser.add_argument("--lock", default=str(Path(__file__).resolve().parents[1] / "config/toolchain.lock.json"))
source = parser.add_mutually_exclusive_group()
source.add_argument("--archive")
source.add_argument("--download", action="store_true")
parser.add_argument("--apply", action="store_true")
parser.add_argument("--approval-id")
args = parser.parse_args(argv)
try:
if args.apply and not (args.approval_id and re.fullmatch(r"[A-Za-z0-9_.-]{1,80}", args.approval_id)):
raise FixtureError("mutations require a non-secret approval identifier")
if args.action == "prepare" and not (args.archive or args.download):
raise FixtureError("prepare requires --archive or explicit --download")
if args.action == "smoke" and not args.stack_workspace:
raise FixtureError("smoke requires an approved --stack-workspace")
result = prepare(args) if args.action == "prepare" else smoke(args)
print(json.dumps(result, sort_keys=True, indent=2))
return 1 if result["status"] == "FAIL" else 0
except (FixtureError, OSError, ValueError, KeyError, TypeError, tarfile.TarError, subprocess.SubprocessError) as error:
reason = str(error) if isinstance(error, FixtureError) else "operation failed: " + type(error).__name__
print(json.dumps({"status": "BLOCKED", "reason": reason, "raw_output": "suppressed"}))
return 2
if __name__ == "__main__":
sys.exit(main())
+562
View File
@@ -0,0 +1,562 @@
#!/usr/bin/env python3
"""Opt-in network-isolated cold start on an existing native Linux Docker Engine.
Uses a prepared maintained deployment as a source/image template, never its data
or operational settings. All new settings, credentials and records are synthetic.
This does not prove clean-daemon installation, native installers, Mac or TEAM-LAN.
"""
from __future__ import annotations
import argparse
import base64
import copy
import hashlib
import importlib.util
import json
import os
from pathlib import Path, PurePosixPath
import re
import secrets
import subprocess
import sys
import time
from types import SimpleNamespace
ROOT = Path(__file__).resolve().parents[1]
def module(name, relative):
spec = importlib.util.spec_from_file_location(name, ROOT / relative)
value = importlib.util.module_from_spec(spec)
spec.loader.exec_module(value)
return value
kit = module("offline_kit", "deployment/toolkit.py")
bundle = module("offline_bundle", "scripts/toolchain_bundle.py")
pcap = module("offline_pcap", "integration/synthetic_pcap.py")
shared, Error = kit.shared, kit.Error
SCHEMA = "durkahelper.offline-runtime.v1"
LABEL = "io.durkahelper.offline-runtime"
PURPOSE = "io.durkahelper.offline-helper"
ROLES = {"postgres", "redis", "neo-redis", "farm", "celery", "front", "neo-server", "neo-worker", "packmate-db", "packmate"}
APPS = ("postgres", "redis", "neo-redis", "farm", "front", "neo-server", "packmate-db", "packmate")
MAX_FILES = 50 * 1024 * 1024
NOT_VALIDATED = ["clean-daemon installation", "complete source/client/license/installer kit", "Mac or ARM64",
"physical LAN", "LIVE capture", "real competition submission", "operator-data recovery"]
# The helper prints only boolean checks and hashes. Fixed endpoints and paths
# prevent using profile input as a URL, shell command or generic network probe.
PROBE = b'''import base64, hashlib, json, socket, sys, time, urllib.error, urllib.request
from pathlib import Path
def canonical(value): return json.dumps(value,sort_keys=True,separators=(",",":")).encode()
def digest(value): return hashlib.sha256(canonical(value)).hexdigest()
class NoRedirect(urllib.request.HTTPRedirectHandler):
def redirect_request(self,*args,**kwargs): return None
def request(component,path,method="GET",body=None,auth=True):
base="http://front" if component=="farm" else "http://packmate:65000"
headers={"Content-Type":"application/json","Accept-Encoding":"identity"}
if auth:
headers["Authorization"]=C["farm_password"] if component=="farm" else "Basic "+base64.b64encode((C["packmate_user"]+":"+C["packmate_password"]).encode()).decode()
req=urllib.request.Request(base+path,headers=headers,method=method,data=None if body is None else canonical(body))
try: response=urllib.request.build_opener(urllib.request.ProxyHandler({}),NoRedirect()).open(req,timeout=3)
except urllib.error.HTTPError as error: response=error
with response:
raw=response.read(1048577)
if len(raw)>1048576: raise ValueError("response too large")
return response.status,raw
def api(component,path,method="GET",body=None):
status,raw=request(component,path,method,body)
if status!=200: raise ValueError("API status rejected")
return json.loads(raw) if raw else None
def farm_summary():
settings=api("farm","/api/get_config")
if settings.get("TEAMS")!={"Synthetic":"192.0.2.1"} or settings.get("SYSTEM_PROTOCOL")!="ructf_http": raise ValueError("non-synthetic farm settings")
if any("PASSWORD" in key or "TOKEN" in key for key in settings): raise ValueError("secret fields exposed")
flags=api("farm","/api/filter_flags?flag="+C["flag"])["flags"]
if len(flags)!=1 or flags[0].get("flag")!=C["flag"] or flags[0].get("status")!="QUEUED" or flags[0].get("sploit")!="synthetic-offline": raise ValueError("queued synthetic record changed")
return {"farm_settings":digest(settings),"farm_queued_flag":digest(flags)}
def pack_summary():
services=api("packmate","/api/service/"); patterns=api("packmate","/api/pattern/")
if len(services)!=1 or services[0].get("port")!=18080 or len(patterns)!=1 or patterns[0].get("value")!=C["marker"] or patterns[0].get("enabled") is not True: raise ValueError("non-synthetic Packmate state")
streams=api("packmate","/api/stream/18080","POST",{"startingFrom":None,"pageSize":10,"favorites":False,"pattern":{"id":patterns[0]["id"]}})
if len(streams)!=1 or streams[0].get("protocol")!="TCP": raise ValueError("synthetic stream missing")
packets=api("packmate","/api/packet/"+str(streams[0]["id"]),"POST",{"startingFrom":None,"pageSize":20})
if not isinstance(packets,list) or len(packets)>20: raise ValueError("invalid packet collection")
found=[(p.get("content"),p.get("incoming")) for p in packets]
if (C["request"],True) not in found or (C["response"],False) not in found: raise ValueError("synthetic packet direction mismatch")
return {"packmate_services":digest(services),"packmate_patterns":digest(patterns),"packmate_streams":digest(streams),"packmate_packets":digest(packets)}
def main(action):
if action=="witness":
listener=socket.socket(); listener.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1); listener.bind(("0.0.0.0",18765)); listener.listen(8); listener.settimeout(1)
deadline=time.monotonic()+1200
while time.monotonic()<deadline:
try:
conn,_=listener.accept()
with conn: conn.sendall(b"offline-witness\\n")
except socket.timeout: pass
return {}
if action in {"network","witness-control"}:
target=sys.argv[2]
socket.inet_aton(target)
reachable=False
try:
with socket.create_connection((target,18765),timeout=2) as conn: reachable=conn.recv(64)==b"offline-witness\\n"
except OSError: pass
if action=="witness-control": return {"owned_witness_reachable":reachable}
routes=Path("/proc/net/route").read_text().splitlines()[1:]
default4=any(len(line.split())>3 and line.split()[1]=="00000000" and int(line.split()[3],16)&1 and not int(line.split()[3],16)&0x200 and line.split()[0]!="lo" for line in routes)
routes6=Path("/proc/net/ipv6_route").read_text().splitlines()
default6=any(len(line.split())>9 and line.split()[0]=="0"*32 and line.split()[1]=="00" and int(line.split()[8],16)&1 and not int(line.split()[8],16)&0x200 and line.split()[9]!="lo" for line in routes6)
return {"no_default_ipv4":not default4,"no_default_ipv6":not default6,"owned_witness_denied":not reachable}
if action=="farm-ready":
data=api("farm","/api/get_config")
return {"synthetic_farm_ready":data.get("TEAMS")=={"Synthetic":"192.0.2.1"} and data.get("SYSTEM_PROTOCOL")=="ructf_http"}
if action=="ready": return {"packmate_ready":isinstance(api("packmate","/api/service/"),list)}
if action=="seed":
if api("packmate","/api/service/")!=[] or api("packmate","/api/pcap/started") is not False: raise ValueError("fresh FILE state required")
api("farm","/api/post_flags","POST",[{"flag":C["flag"],"sploit":"synthetic-offline","team":"Synthetic"}])
api("packmate","/api/service/","POST",{"port":18080,"name":"Synthetic offline HTTP","decryptTls":False,"http":False,"urldecodeHttpRequests":False,"mergeAdjacentPackets":False,"parseWebSockets":False})
api("packmate","/api/pattern/","POST",{"name":"Synthetic offline marker","value":C["marker"],"color":"#123456","searchType":"SUBSTRING","directionType":"BOTH","actionType":"FIND","serviceId":18080})
api("packmate","/api/pcap/start","POST")
deadline=time.monotonic()+45
while True:
try: pack=pack_summary(); break
except (ValueError,OSError):
if time.monotonic()>deadline: raise
time.sleep(1)
return {"hashes":dict(farm_summary(),**pack),"checks":{"farm_unauthenticated_rejected":request("farm","/api/get_config",auth=False)[0]==403,"packmate_unauthenticated_rejected":request("packmate","/api/service/",auth=False)[0]==401}}
if action=="verify": return {"hashes":dict(farm_summary(),**pack_summary()),"checks":{"file_capture_idle_after_cold_start":api("packmate","/api/pcap/started") is False}}
raise ValueError("unknown fixed action")
try:
action=sys.argv[1]
C=json.loads(Path("/probe-config.json").read_text()) if action not in {"network","witness","witness-control"} else {}
print(json.dumps(main(action),sort_keys=True))
except Exception as error:
print(json.dumps({"error_type":type(error).__name__,"raw_output":"suppressed"})); sys.exit(2)
'''
def digest(value):
return hashlib.sha256(value).hexdigest()
def synthetic_profile():
return {"schema": "durkahelper.deployment-profile.v1", "platform": {"os": "linux", "architecture": "amd64", "runtime": "docker-engine"},
"bind_address": "127.0.0.1", "ports": {"farm": 38080, "neo": 35005, "packmate": 35000}, "allow_amd64_emulation": False,
"farm": {"teams": {"Synthetic": "192.0.2.1"}, "flag_format": "[A-Z0-9]{31}=", "protocol": "ructf_http",
"protocol_settings": {"SYSTEM_URL": "http://offline-no-submission.invalid/flags", "SYSTEM_TOKEN": "synthetic-offline-only"},
"submit_limit": 10, "submit_period": 1, "flag_lifetime": 300},
"packmate": {"mode": "FILE", "local_ip": pcap.SERVER_IP, "pcap_file": "synthetic.pcap", "interface": "", "retention_minutes": 60}}
def image_closure(manifest, images):
if set(images) != ROLES or any(not isinstance(value, str) or not re.fullmatch(r"sha256:[a-f0-9]{64}", value) for value in images.values()):
raise Error("template must pin every maintained deployment image by exact local ID")
archives = [item for item in manifest["artifacts"] if item["kind"] == "image"]
if (not 1 <= len(archives) <= 16 or sum(item["size"] for item in archives) > 4 * 1024 ** 3 or
any(item["architecture"] != "linux/amd64" for item in archives)):
raise Error("offline rehearsal requires at most sixteen Linux amd64 image archives totaling at most 4 GiB")
available = {identity for item in archives for identity in item["image_ids"]}
if set(images.values()) != available:
raise Error("verified bundle image inventory must exactly cover runtime/helper identities without extra images")
def compose_spec(state):
spec = kit.compose_spec(synthetic_profile(), state["credentials"], state["project"], shared.image_map(ROOT / "config/integration-images.lock.json"))
spec = kit.runtime_spec(spec, state["images"])
for name in ("celery", "neo-worker"):
del spec["services"][name]
for service in spec["services"].values():
service["restart"] = "no"
service["networks"] = ["offline"]
service["labels"] = {LABEL: state["project"]}
service.pop("ports", None)
service.pop("profiles", None)
# An in-network positive control proves that the denied cross-network
# connection is not simply a stopped witness. It has no external network.
spec["services"]["witness"] = {"image": state["images"]["farm"], "platform": "linux/amd64", "entrypoint": ["python", "-B", "/probe.py"],
"command": ["witness"], "user": "65534:65534", "read_only": True, "cap_drop": ["ALL"],
"security_opt": ["no-new-privileges:true"], "cpus": 0.25, "mem_limit": "64m", "pids_limit": 32,
"logging": {"driver": "none"}, "restart": "no", "labels": {LABEL: state["project"]},
"volumes": ["./probe.py:/probe.py:ro"], "networks": ["witness"]}
spec["networks"] = {name: {"internal": True, "enable_ipv6": False, "driver": "bridge",
"driver_opts": {"com.docker.network.bridge.gateway_mode_ipv4": "isolated"}, "labels": {LABEL: state["project"]}} for name in ("offline", "witness")}
return spec
def generated_files(state):
credentials, profile = state["credentials"], synthetic_profile()
farm = profile["farm"]
config = dict(DEBUG=False, TEAMS=farm["teams"], FLAG_FORMAT=farm["flag_format"], SYSTEM_PROTOCOL=farm["protocol"],
SUBMIT_FLAG_LIMIT=10, SUBMIT_PERIOD=1, FLAG_LIFETIME=300, SERVER_PASSWORD=credentials["farm_password"], TIMEZONE="UTC", **farm["protocol_settings"])
client = ('host: "neo-server:5005"\ngrpc_auth_key: "' + credentials["neo_key"] + '"\nexploit_dir: "/work/exploits"\nclient_id: "' + state["project"] + '"\n').encode()
request, response = pcap.payloads(state["marker"])
helper = {name: credentials[name] for name in ("farm_password", "packmate_user", "packmate_password")}
helper.update(marker=state["marker"], flag=state["flag"], request=base64.b64encode(request).decode(), response=base64.b64encode(response).decode())
return {"compose.json": shared.canonical(compose_spec(state)), "probe.py": PROBE, "probe-config.json": shared.canonical(helper),
"config/farm.py": ("CONFIG = " + repr(config) + "\n").encode(),
"config/neo-server.yml": ('db_path: "/data/db.db"\nredis_url: "redis://neo-redis:6379/0"\nbase_dir: "/data/exploits"\nping_every: "5s"\nsubmit_every: "2s"\ngrpc_auth_key: "' + credentials["neo_key"] + '"\nfarm:\n url: "http://front"\n password: "' + credentials["farm_password"] + '"\n').encode(),
"config/neo-client.yml": client, "config/neo-denied.yml": client.replace(credentials["neo_key"].encode(), b"intentionally-wrong-synthetic-key"),
"config/packmate.properties": kit.properties(profile, credentials).encode(), "pcaps/synthetic.pcap": pcap.make_pcap(state["marker"]),
"synthetic.sh": b"#!/bin/sh\n# flush=True\nprintf '%s\\n' 'offline-disabled-task'\n"}
def validate_state(value):
keys = {"schema", "project", "daemon_id", "images", "credentials", "marker", "flag", "bundle", "bundle_manifest_sha256", "template_receipt_sha256", "files"}
if not isinstance(value, dict) or set(value) != keys or value["schema"] != SCHEMA:
raise Error("invalid offline fixture state")
for name, pattern in (("project", r"dh-offline-[a-f0-9]{12}"), ("daemon_id", r"[A-Za-z0-9:_.-]{8,128}"),
("marker", r"[a-f0-9]{24}"), ("flag", r"[A-F0-9]{31}="),
("bundle_manifest_sha256", r"[a-f0-9]{64}"), ("template_receipt_sha256", r"[a-f0-9]{64}")):
if not isinstance(value[name], str) or not re.fullmatch(pattern, value[name]):
raise Error("invalid offline fixture identifier")
kit.validate_credentials(value["credentials"])
if not isinstance(value["bundle"], str) or not Path(value["bundle"]).is_absolute():
raise Error("offline bundle must be an explicit approved absolute path")
if not isinstance(value["files"], dict) or len(value["files"]) > 20000:
raise Error("invalid offline immutable file inventory")
return value
def prepare(args):
target = kit.safe_path(args.workspace)
if target.exists() or not target.parent.is_dir():
raise Error("offline rehearsal requires a new private workspace")
source, template, spec, platform = kit.workspace(args.template)
if platform["platform"] != synthetic_profile()["platform"]:
raise Error("offline rehearsal currently requires a native Linux amd64 template")
runtime = kit.check_build_receipt(source, spec)
images = {name: service["image"] for name, service in runtime["services"].items()}
manifest = bundle.verify(args.image_bundle)
image_closure(manifest, images)
if not re.fullmatch(r"[A-Za-z0-9:_.-]{8,128}", args.daemon_id or ""):
raise Error("explicit approved Docker daemon identity required")
if not args.apply:
return {"status": "NOT_RUN", "action": "prepare", "effects": "new synthetic configuration/source mounts only", "daemon_contacted": False, "image_closure": "PASS"}
if os.name != "posix" or not sys.platform.startswith("linux") or os.getuid() == 0:
raise Error("offline rehearsal requires a non-root native Linux operator")
state = {"schema": SCHEMA, "project": "dh-offline-" + secrets.token_hex(6), "daemon_id": args.daemon_id,
"images": images, "credentials": {name: ("synthetic-" + secrets.token_hex(6) if name == "packmate_user" else secrets.token_hex(24))
for name in ("farm_password", "database_password", "neo_key", "packmate_user", "packmate_password")},
"marker": secrets.token_hex(12), "flag": secrets.token_hex(16).upper()[:31] + "=", "bundle": str(kit.safe_path(args.image_bundle)),
"bundle_manifest_sha256": digest(kit.read(Path(args.image_bundle) / "manifest.json")),
"template_receipt_sha256": digest(kit.read(source / "build-receipt.json")), "files": {}}
validate_state(state)
target.mkdir(mode=0o700)
total = 0
for name in sorted(template["files"]):
if not name.startswith("sources/"):
continue
data = kit.read(source / name, MAX_FILES)
total += len(data)
if total > MAX_FILES:
raise Error("source mounts exceed offline fixture byte bound")
shared.write(target / name, data)
state["files"][name] = digest(data)
for name, data in generated_files(state).items():
shared.write(target / name, data)
state["files"][name] = digest(data)
if name in {"probe.py", "probe-config.json", "synthetic.sh", "config/neo-client.yml", "config/neo-denied.yml", "config/packmate.properties", "pcaps/synthetic.pcap"}:
(target / name).chmod(0o644)
(target / "pcaps").chmod(0o755)
for name in ("postgres", "redis", "neo-redis", "neo", "packmate-db"):
(target / "data" / name).mkdir(parents=True, mode=0o700)
shared.write(target / "fixture.json", shared.canonical(state))
return {"status": "PASS", "action": "prepare", "template_data": "never read or copied", "capture_submission_worker": "disabled", "not_validated": NOT_VALIDATED}
def fixture(path):
root = kit.safe_path(path)
if os.name == "posix" and (root.stat().st_uid != os.getuid() or root.stat().st_mode & 0o077):
raise Error("offline fixture must be private and owned by the current operator")
state = validate_state(kit.load(root / "fixture.json"))
expected = generated_files(state)
if not set(expected) <= set(state["files"]):
raise Error("offline generated configuration inventory is incomplete")
total = 0
for name, checksum in state["files"].items():
parts = PurePosixPath(name)
if (parts.is_absolute() or ".." in parts.parts or "\\" in name or ":" in name or
(name not in expected and not name.startswith("sources/")) or any(p in {".git", ".ssh"} for p in parts.parts)):
raise Error("unsafe offline fixture member")
candidate = root / name
if any(p.is_symlink() for p in (candidate, *candidate.parents) if p != root and root in p.parents):
raise Error("linked offline fixture member")
data = kit.read(candidate, MAX_FILES)
total += len(data)
if total > MAX_FILES or digest(data) != checksum or (name in expected and data != expected[name]):
raise Error("offline immutable source/configuration changed")
for name in ("data", "data/postgres", "data/redis", "data/neo-redis", "data/neo", "data/packmate-db"):
if (root / name).is_symlink() or not (root / name).is_dir():
raise Error("offline data directory changed")
return root, state
def command(root, state):
return ["docker", "compose", "--project-name", state["project"], "--project-directory", str(root), "--file", str(root / "compose.json")]
def daemon(state):
raw = shared.checked(["docker", "info", "--format", "{{.ID}};{{.OSType}};{{.Architecture}};{{.OperatingSystem}}"], capture=True).decode().strip().split(";", 3)
if len(raw) != 4 or raw[0] != state["daemon_id"] or raw[1] != "linux" or raw[2] not in {"x86_64", "amd64"} or "docker desktop" in raw[3].lower():
raise Error("approved native Linux amd64 Docker Engine required")
def ownership(state):
for kind, listing in (("container", ["ps", "--all", "--quiet", "--no-trunc"]), ("network", ["network", "ls", "--quiet", "--no-trunc"])):
ids = shared.checked(["docker"] + listing + ["--filter", "label=com.docker.compose.project=" + state["project"]], capture=True).decode().split()
if len(ids) > 16 or any(not re.fullmatch(r"[a-f0-9]{64}", value) for value in ids):
raise Error("invalid owned offline resource listing")
template = '{{index ' + ('.Config.Labels' if kind == "container" else '.Labels') + ' "' + LABEL + '"}}'
for identity in ids:
if shared.checked(["docker", kind, "inspect", "--format", template, identity], capture=True).decode().strip() != state["project"]:
raise Error("offline resource ownership mismatch")
def cleanup_helpers(state, name=None):
project = state["project"]
if name is not None and not re.fullmatch(re.escape(project) + r"-helper-[a-f0-9]{8}", name):
raise Error("invalid offline helper identity")
filters = ["--filter", "name=^/" + name + "$"] if name else ["--filter", "label=" + LABEL + "=" + project, "--filter", "label=" + PURPOSE + "=true"]
ids = shared.checked(["docker", "ps", "--all", "--quiet", "--no-trunc"] + filters, capture=True).decode().split()
if len(ids) > (1 if name else 32) or any(not re.fullmatch(r"[a-f0-9]{64}", item) for item in ids):
raise Error("invalid offline helper listing")
template = '{"id":{{json .Id}},"name":{{json .Name}},"owner":{{json (index .Config.Labels "' + LABEL + '")}},"helper":{{json (index .Config.Labels "' + PURPOSE + '")}}}'
for identity in ids:
info = json.loads(shared.checked(["docker", "inspect", "--format", template, identity], capture=True))
if (info.get("id") != identity or info.get("owner") != project or info.get("helper") != "true" or
not re.fullmatch("/" + re.escape(project) + r"-helper-[a-f0-9]{8}", info.get("name", "")) or
(name is not None and info["name"] != "/" + name)):
raise Error("offline helper ownership mismatch")
shared.checked(["docker", "rm", "--force", identity], timeout=20)
def helper(root, state, action, *, network=None, target=None, neo=False):
allowed = {"farm-ready", "ready", "seed", "verify", "network", "witness-control", "neo-info", "neo-denied", "neo-add"}
if action not in allowed:
raise Error("unsupported fixed offline helper action")
if action in {"network", "witness-control"}:
import ipaddress
if ipaddress.ip_address(target).version != 4:
raise Error("owned witness requires an inspected IPv4 address")
name = state["project"] + "-helper-" + secrets.token_hex(4)
args = ["docker", "create", "--name", name, "--label", LABEL + "=" + state["project"], "--label", PURPOSE + "=true",
"--network", network or state["project"] + "_offline", "--user", "65534:65534", "--read-only", "--cap-drop=ALL",
"--security-opt=no-new-privileges:true", "--memory=128m", "--memory-swap=128m", "--cpus=0.5", "--pids-limit=32",
"--log-driver=none", "--pull=never"]
if action.startswith("neo-"):
client = "neo-denied.yml" if action == "neo-denied" else "neo-client.yml"
args += ["--mount", "type=bind,src=" + str(root / "config" / client) + ",dst=/client.yml,readonly",
"--mount", "type=bind,src=" + str(root / "synthetic.sh") + ",dst=/synthetic.sh,readonly",
"--entrypoint", "/usr/local/bin/neo", state["images"]["neo-worker"], "--verbose=false", "--config", "/client.yml"]
args += ["add", "--id", state["project"], "--disabled", "--interval", "1h", "--timeout", "3s", "/synthetic.sh"] if action == "neo-add" else ["info"]
else:
args += ["--mount", "type=bind,src=" + str(root / "probe.py") + ",dst=/probe.py,readonly"]
if action not in {"network", "witness-control"}:
args += ["--mount", "type=bind,src=" + str(root / "probe-config.json") + ",dst=/probe-config.json,readonly"]
args += ["--entrypoint", "python", state["images"]["farm"], "-B", "/probe.py", action]
if target:
args.append(target)
try:
shared.checked(args, timeout=30)
code, raw = shared.capture_probe(["docker", "start", "--attach", name], timeout=65 if action == "seed" else 15)
if action == "neo-denied":
return {"neo_wrong_key_rejected": code != 0 and b"Unauthenticated" in raw}
if code:
raise Error("offline helper failed; raw output suppressed")
if action.startswith("neo-"):
lines = [line.strip() for line in raw.splitlines() if b"exploit_id:" in line]
if action == "neo-add":
return {}
if not lines:
return {"neo_authenticated": True, "task": None}
if len(lines) != 1 or state["project"].encode() not in lines[0] or b"disabled:true" not in lines[0] or b"version:1" not in lines[0]:
raise Error("Neo contains non-synthetic or enabled task state")
return {"neo_authenticated": True, "task": digest(lines[0])}
value = json.loads(raw)
if not isinstance(value, dict) or "error_type" in value:
raise Error("invalid sanitized offline helper result")
return value
finally:
cleanup_helpers(state, name)
def wait_helper(root, state, action, timeout=120):
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
try:
value = helper(root, state, action)
if value and all(v is True for k, v in value.items() if k != "task"):
return value
except Error:
pass
time.sleep(1)
raise Error("offline application readiness timed out")
def container_id(root, state, service):
if service not in APPS + ("witness",):
raise Error("unlisted offline service")
value = shared.checked(command(root, state) + ["ps", "--all", "--quiet", service], capture=True).decode().strip()
if not re.fullmatch(r"[a-f0-9]{64}", value):
raise Error("offline service must resolve to one exact container ID")
return value
def isolation(root, state):
networks = {}
for role in ("offline", "witness"):
template = '{"id":{{json .Id}},"internal":{{json .Internal}},"ipv6":{{json .EnableIPv6}},"driver":{{json .Driver}},"options":{{json .Options}},"owner":{{json (index .Labels "' + LABEL + '")}}}'
value = json.loads(shared.checked(["docker", "network", "inspect", "--format", template, state["project"] + "_" + role], capture=True))
if (value.get("internal") is not True or value.get("ipv6") is not False or value.get("driver") != "bridge" or
value.get("owner") != state["project"] or value.get("options", {}).get("com.docker.network.bridge.gateway_mode_ipv4") != "isolated" or
not re.fullmatch(r"[a-f0-9]{64}", value.get("id", ""))):
raise Error("Docker isolated gateway mode unavailable or network configuration changed")
networks[role] = value["id"]
endpoints = {}
for service in APPS + ("witness",):
identity = container_id(root, state, service)
template = '{"running":{{json .State.Running}},"ports":{{json .HostConfig.PortBindings}},"networks":{{json .NetworkSettings.Networks}},"privileged":{{json .HostConfig.Privileged}},"owner":{{json (index .Config.Labels "' + LABEL + '")}}}'
value = json.loads(shared.checked(["docker", "inspect", "--format", template, identity], capture=True))
role = "witness" if service == "witness" else "offline"
links = value.get("networks", {})
if (value.get("running") is not True or value.get("owner") != state["project"] or value.get("privileged") is not False or
value.get("ports") not in ({}, None) or len(links) != 1 or next(iter(links.values())).get("NetworkID") != networks[role]):
raise Error("actual offline service network/publication/ownership mismatch")
endpoints[service] = (identity, next(iter(links.values()))["IPAddress"])
witness = endpoints["witness"][1]
positive = helper(root, state, "witness-control", network=state["project"] + "_witness", target=witness)
if positive != {"owned_witness_reachable": True}:
raise Error("owned witness positive control failed")
result = {"isolated_networks_verified": True, "owned_witness_positive_control": True}
for service in APPS:
values = helper(root, state, "network", network="container:" + endpoints[service][0], target=witness)
if values != {"no_default_ipv4": True, "no_default_ipv6": True, "owned_witness_denied": True}:
raise Error("offline default-route or cross-network denial check failed")
result[service + "_no_route_and_witness_denied"] = True
return result
def start(root, state):
ownership(state)
shared.checked(command(root, state) + ["up", "--detach", "--no-build", "--pull", "never"] + [name for name in APPS if name != "neo-server"] + ["witness"], timeout=180)
wait_helper(root, state, "farm-ready", 90)
shared.checked(command(root, state) + ["up", "--detach", "--no-build", "--pull", "never", "--no-deps", "neo-server"], timeout=60)
wait_helper(root, state, "neo-info", 60)
wait_helper(root, state, "ready", 120)
def execute(args):
root, state = fixture(args.workspace)
if not args.apply:
return {"status": "NOT_RUN", "action": args.action, "daemon_contacted": False, "effects": "image import, new isolated synthetic stack, cold restart and exact-owned cleanup", "not_validated": NOT_VALIDATED}
if not sys.platform.startswith("linux") or os.getuid() == 0:
raise Error("offline runtime requires a non-root native Linux operator")
daemon(state)
if args.action == "down":
cleanup_helpers(state)
ownership(state)
shared.checked(command(root, state) + ["down", "--timeout", "10"], timeout=90)
return {"status": "PASS", "action": "down", "data_retained": True}
if not args.snapshot_confirmed:
raise Error("cold restart rehearsal requires --snapshot-confirmed")
if (root / "attempt.json").exists() or any(any((root / "data" / name).iterdir()) for name in ("postgres", "redis", "neo-redis", "neo", "packmate-db")):
raise Error("offline run requires fresh never-started fixture data")
manifest = bundle.verify(state["bundle"])
if digest(kit.read(Path(state["bundle"]) / "manifest.json")) != state["bundle_manifest_sha256"]:
raise Error("approved offline bundle manifest changed")
image_closure(manifest, state["images"])
shared.write(root / "attempt.json", shared.canonical({"approval_id": args.approval_id, "snapshot_confirmed": True}))
report = {"schema": SCHEMA, "status": "BLOCKED", "phase": "image-import", "checks": {}, "not_validated": NOT_VALIDATED,
"scope": "network-isolated runtime on preinstalled existing native Linux Engine; not a clean-daemon test",
"synthetic_queue_policy": "QUEUED only; no Celery, Neo worker, receiver or LIVE capture is started"}
began = time.monotonic()
try:
bundle.import_images(SimpleNamespace(root=state["bundle"], apply=True, daemon_id=state["daemon_id"]))
for identity in set(state["images"].values()):
observed = shared.checked(["docker", "image", "inspect", "--format", "{{.Id}};{{.Os}};{{.Architecture}}", identity], capture=True).decode().strip()
if observed != identity + ";linux;amd64":
raise Error("imported offline image identity or architecture mismatch")
report["checks"]["verified_runtime_and_helper_image_closure"] = True
report["phase"] = "initial-start"
start(root, state)
report["checks"].update(isolation(root, state))
report["checks"].update(helper(root, state, "neo-denied"))
report["phase"] = "seed-synthetic-data"
seeded = helper(root, state, "seed")
report["checks"].update(seeded["checks"])
helper(root, state, "neo-add")
neo_before = helper(root, state, "neo-info")["task"]
if not neo_before:
raise Error("disabled Neo synthetic task was not persisted")
for service in ("redis", "neo-redis"):
shared.checked(command(root, state) + ["exec", "-T", service, "redis-cli", "SET", "durkahelper:offline", state["project"]])
report["phase"] = "cold-stop"
ownership(state)
shared.checked(command(root, state) + ["stop", "--timeout", "15"], timeout=120)
if shared.checked(command(root, state) + ["ps", "--status", "running", "--quiet"], capture=True).strip():
raise Error("offline cold stop left a project container running")
report["checks"]["all_services_cold_stopped"] = True
cold_started = time.monotonic()
report["phase"] = "cold-start"
start(root, state)
report["checks"].update({"cold_" + key: value for key, value in isolation(root, state).items()})
restored = helper(root, state, "verify")
report["checks"].update(restored["checks"])
report["checks"]["farm_packmate_state_preserved"] = restored["hashes"] == seeded["hashes"]
report["checks"]["disabled_neo_task_preserved"] = helper(root, state, "neo-info")["task"] == neo_before
for service in ("redis", "neo-redis"):
value = shared.checked(command(root, state) + ["exec", "-T", service, "redis-cli", "--raw", "GET", "durkahelper:offline"], capture=True).decode().strip()
report["checks"][service + "_marker_preserved"] = value == state["project"]
report["cold_start_seconds"] = round(time.monotonic() - cold_started, 3)
report["status"] = "PASS" if all(report["checks"].values()) else "FAIL"
report["phase"] = "complete"
except (Error, bundle.Error, OSError, ValueError, TypeError, KeyError, AttributeError, subprocess.SubprocessError, KeyboardInterrupt) as error:
report["error_type"] = type(error).__name__
report["raw_output"] = "suppressed"
finally:
report["cleanup"] = {}
try:
cleanup_helpers(state)
report["cleanup"]["helpers"] = True
except (Error, OSError, ValueError, KeyboardInterrupt):
report["cleanup"]["helpers"] = False
try:
ownership(state)
shared.checked(command(root, state) + ["down", "--timeout", "10"], timeout=90)
report["cleanup"]["owned_project"] = True
except (Error, OSError, ValueError, KeyboardInterrupt):
report["cleanup"]["owned_project"] = False
if not all(report["cleanup"].values()):
report["status"] = "BLOCKED"
report["total_seconds"] = round(time.monotonic() - began, 3)
report["retained"] = "private synthetic files/data and imported immutable images; no tag changes"
shared.write(root / "result.json", shared.canonical(report))
return report
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("action", choices=["prepare", "run", "down"])
parser.add_argument("--workspace", required=True)
for name in ("template", "image-bundle", "daemon-id", "approval-id"):
parser.add_argument("--" + name)
parser.add_argument("--apply", action="store_true")
parser.add_argument("--snapshot-confirmed", action="store_true")
args = parser.parse_args(argv)
try:
if args.apply and not (args.approval_id and re.fullmatch(r"[A-Za-z0-9_.-]{1,80}", args.approval_id)):
raise Error("mutations require --apply and a non-secret --approval-id")
if args.action == "prepare" and not all((args.template, args.image_bundle, args.daemon_id)):
raise Error("prepare requires --template, --image-bundle and --daemon-id")
result = prepare(args) if args.action == "prepare" else execute(args)
print(json.dumps(result, sort_keys=True))
return {"PASS": 0, "NOT_RUN": 0, "FAIL": 1, "BLOCKED": 2}[result["status"]]
except (Error, bundle.Error, OSError, ValueError, TypeError, KeyError, AttributeError, subprocess.SubprocessError, KeyboardInterrupt) as error:
print(json.dumps({"status": "BLOCKED", "error_type": type(error).__name__, "raw_output": "suppressed"}))
return 2
if __name__ == "__main__":
raise SystemExit(main())
+173
View File
@@ -0,0 +1,173 @@
#!/usr/bin/env python3
"""Opt-in host-interface capture of ONLY a fresh internal synthetic Docker bridge."""
import argparse
import importlib.util
import json
from pathlib import Path
import re
import secrets
import socket
import sys
import time
from types import SimpleNamespace
ROOT = Path(__file__).resolve().parents[1]
def module(name, path):
spec = importlib.util.spec_from_file_location(name, path)
value = importlib.util.module_from_spec(spec)
spec.loader.exec_module(value)
return value
synthetic = module("host_synthetic", ROOT / "integration/packmate_live_smoke.py")
host = module("host_capture", ROOT / "deployment/packmate_host.py")
shared, Error = host.shared, host.Error
# Separate file imports have distinct exception classes; both must stay inside
# the redacted report and scoped-cleanup path.
EXPECTED_ERRORS = (Error, synthetic.Error, OSError, ValueError, KeyError, TypeError, AttributeError, KeyboardInterrupt)
def free_port(excluded):
for _ in range(20):
with socket.socket() as endpoint:
endpoint.bind(("127.0.0.1", 0))
value = endpoint.getsockname()[1]
if value not in excluded:
return value
raise Error("no distinct loopback test port")
def run(args):
root, state = synthetic.fixture(args.workspace)
if not args.apply:
return {"status": "NOT_RUN", "scope": "new internal test bridge only; explicit host-network capture approval required"}
if not sys.platform.startswith("linux") or not args.capture_approved:
raise Error("host synthetic capture requires native Linux and capture approval")
if (root / "deployment").exists() or (root / "result.json").exists():
raise Error("new fixture required")
host.live.daemon({"daemon_id": state["daemon_id"]})
observed = shared.checked(["docker", "image", "inspect", "--format", "{{.Id}};{{.Os}};{{.Architecture}}", state["python_image"]], capture=True).decode().strip().split(";")
if len(observed) != 3 or not re.fullmatch(r"sha256:[a-f0-9]{64}", observed[0]) or observed[1:] != ["linux", "amd64"]:
raise Error("cached pinned Python image required")
image = observed[0]
attempted_network, attempted_containers, prepared = None, [], False
checks, cleanup, metrics, failure, phase = {}, {}, {}, None, "create-owned-bridge"
try:
attempted_network = state["project"]
network = synthetic.identifier(["docker", "network", "create", "--driver", "bridge", "--internal", "--label", synthetic.live.CAPTURE_LABEL + "=" + state["project"], attempted_network])
attempted_containers.append(state["project"] + "-source")
owner = synthetic.identifier(synthetic.private_command(root, state, image, attempted_containers[-1], network, "server.py"))
shared.checked(["docker", "start", owner], timeout=30)
metadata = json.loads(shared.checked(["docker", "network", "inspect", "--format", '{"internal":{{json .Internal}},"containers":{{json .Containers}}}', network], capture=True))
if metadata.get("internal") is not True or set(metadata.get("containers", {})) != {owner}:
raise Error("test bridge must be internal and contain only the exact synthetic server")
service_ip = metadata["containers"][owner]["IPv4Address"].split("/", 1)[0]
iface = "br-" + network[:12]
link = json.loads(shared.checked(["ip", "-json", "link", "show", "dev", iface], capture=True))[0]
ui = free_port(set())
config = host.profile({"schema": host.SCHEMA, "daemon_id": state["daemon_id"], "interface": iface,
"ifindex": link["ifindex"], "interface_mac": link["address"], "local_ip": service_ip,
"bind_address": "127.0.0.1", "ui_port": ui, "db_port": free_port({ui}),
"tcp_timeout_seconds": 4, "udp_timeout_seconds": 3, "timeout_check_seconds": 1,
"retention_minutes": 60, "cleanup_interval_minutes": 1})
secret = {"username": "synthetic-" + secrets.token_hex(6), "password": secrets.token_hex(24), "db_password": secrets.token_hex(24)}
shared.write(root / "profile.json", shared.canonical(config))
shared.write(root / "credentials.json", shared.canonical(secret))
params = SimpleNamespace(workspace=root / "deployment", profile=root / "profile.json", credentials=root / "credentials.json",
apply=True, approval_id=args.approval_id, action="up", host_network_approved=True, interface_scope_approved=True,
capture_approval=iface + ":" + str(link["ifindex"]) + ":" + link["address"],
bootstrap_images=getattr(args, "bootstrap_images", None),
expected_images_sha256=getattr(args, "expected_images_sha256", None))
host.prepare(params)
prepared = True
phase = "start-host-capture"
started_capture = host.execute(params)
if params.bootstrap_images is not None:
checks["fresh_offline_image_bootstrap"] = started_capture["images_sha256"] == params.expected_images_sha256
if not checks["fresh_offline_image_bootstrap"]:
raise Error("bootstrap result does not match the independently approved image receipt")
# A successful first launch creates the local receipt. Restarts
# bind that receipt to the same detached hash, never bootstrap it.
params.bootstrap_images = None
checks["internal_synthetic_interface_only"] = True
checks["capture_started"] = host.live.request(config, secret, "/api/pcap/started") is True
for index, suffix in enumerate(("first", "restarted")):
phase = "traffic-" + suffix
marker = state["marker"] + "-" + suffix
patterns = synthetic.configure(config, secret, marker, index == 0)
started = time.monotonic()
attempted_containers.append(state["project"] + "-" + suffix)
child = synthetic.identifier(synthetic.private_command(root, state, image, attempted_containers[-1], network, "client.py") + [service_ip, marker])
shared.checked(["docker", "start", child], timeout=30)
found = {}
deadline = time.monotonic() + 35
while time.monotonic() < deadline:
found = synthetic.collect(config, secret, patterns, marker)
if all(found.values()):
break
time.sleep(1)
checks.update({suffix + "_" + key: value for key, value in found.items()})
metrics[suffix + "_visible_seconds"] = round(time.monotonic() - started, 3)
if index == 0:
_, deployment = host.workspace(params.workspace)
host.owned(params.workspace, deployment)
shared.checked(host.command(params.workspace, deployment, True) + ["stop", "--timeout", "10", "packmate"], timeout=30)
host.execute(params)
checks["restart_preserved_streams"] = all(synthetic.collect(config, secret, patterns, marker).values())
phase = "complete"
except EXPECTED_ERRORS as error:
failure = type(error).__name__
finally:
if prepared:
try:
host.execute(SimpleNamespace(workspace=root / "deployment", action="down", apply=True))
cleanup["deployment"] = True
except EXPECTED_ERRORS:
cleanup["deployment"] = False
for name in reversed(attempted_containers):
try:
synthetic.reconcile_resource("container", name, state["project"])
cleanup[name.rsplit("-", 1)[-1]] = True
except EXPECTED_ERRORS:
cleanup[name.rsplit("-", 1)[-1]] = False
if attempted_network:
try:
synthetic.reconcile_resource("network", attempted_network, state["project"])
cleanup["network"] = True
except EXPECTED_ERRORS:
cleanup["network"] = False
result = {"schema": "durkahelper.packmate-host-smoke.v1", "status": "BLOCKED" if failure else "PASS" if checks and all(checks.values()) and all(cleanup.values()) else "FAIL",
"phase": phase, "error_type": failure, "checks": checks, "metrics": metrics, "cleanup": cleanup,
"scope": "native Linux host network with capture only on fresh internal synthetic bridge",
"not_validated": ["real Vulnbox", "physical mirror port", "Mac", "team LAN", "long-running loss or hard disk quota"],
"raw_output": "suppressed", "private_data_retained": True}
shared.write(root / "result.json", shared.canonical(result))
return result
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("action", choices=["prepare", "run"])
parser.add_argument("--workspace", required=True)
parser.add_argument("--daemon-id")
parser.add_argument("--approval-id")
parser.add_argument("--bootstrap-images")
parser.add_argument("--expected-images-sha256")
parser.add_argument("--apply", action="store_true")
parser.add_argument("--capture-approved", action="store_true")
args = parser.parse_args(argv)
try:
if args.apply and not (args.approval_id and re.fullmatch(r"[A-Za-z0-9_.-]{1,80}", args.approval_id)):
raise Error("apply requires a non-secret approval ID")
result = synthetic.prepare(args) if args.action == "prepare" else run(args)
print(json.dumps(result, sort_keys=True))
return {"PASS": 0, "NOT_RUN": 0, "FAIL": 1, "BLOCKED": 2}[result["status"]]
except EXPECTED_ERRORS as error:
print(json.dumps({"status": "BLOCKED", "error_type": type(error).__name__, "raw_output": "suppressed"}))
return 2
if __name__ == "__main__":
raise SystemExit(main())
+367
View File
@@ -0,0 +1,367 @@
#!/usr/bin/env python3
"""Opt-in, fresh synthetic TCP/UDP LIVE capture in a dedicated Linux namespace.
No host capture, source patches, package installation or network reconfiguration.
The generated bridge permits egress but the supplied applications send only to
their explicitly supplied synthetic peer. All stages default to preview.
"""
from __future__ import annotations
import argparse
import base64
import importlib.util
import json
import os
from pathlib import Path
import re
import secrets
import sys
import time
from types import SimpleNamespace
ROOT = Path(__file__).resolve().parents[1]
_SPEC = importlib.util.spec_from_file_location("live_deployment", ROOT / "deployment/packmate_live.py")
live = importlib.util.module_from_spec(_SPEC)
_SPEC.loader.exec_module(live)
shared, Error = live.shared, live.Error
SCHEMA = "durkahelper.packmate-live-smoke.v1"
LABEL = "io.durkahelper.live-smoke"
PORTS = {"tcp": 18080, "udp": 18081, "unfinished": 18082}
FRAMING = b'''def read_line(conn, limit=1024):
result=bytearray(); deadline=time.monotonic()+5
while True:
remaining=deadline-time.monotonic()
if remaining<=0: raise TimeoutError("synthetic frame timeout")
conn.settimeout(remaining)
part=conn.recv(limit+1-len(result))
if not part: raise ValueError("synthetic frame truncated")
result.extend(part)
if len(result)>limit: raise ValueError("synthetic frame too large")
if b"\\n" in result:
if result.index(10)!=len(result)-1: raise ValueError("multiple synthetic frames")
return bytes(result)
'''
SERVER = b'''import socket, threading, time
''' + FRAMING + b'''
def tcp(port, hold):
listener=socket.socket(); listener.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1); listener.bind(("0.0.0.0",port)); listener.listen(4)
def answer(conn):
with conn:
data=read_line(conn)
if data.startswith(b"request:"): conn.sendall(b"response:"+data)
if hold: time.sleep(90)
while True:
conn,_=listener.accept(); threading.Thread(target=answer,args=(conn,),daemon=True).start()
def udp():
endpoint=socket.socket(socket.AF_INET,socket.SOCK_DGRAM); endpoint.bind(("0.0.0.0",18081))
while True:
data,addr=endpoint.recvfrom(1024)
if data.startswith(b"request:"): endpoint.sendto(b"response:"+data,addr)
threading.Thread(target=tcp,args=(18080,False),daemon=True).start()
threading.Thread(target=tcp,args=(18082,True),daemon=True).start()
udp()
'''
CLIENT = b'''import socket, sys, time
''' + FRAMING + b'''
host,marker=sys.argv[1:]
def payload(mode): return ("request:"+marker+":"+mode+"\\n").encode("ascii")
deadline=time.monotonic()+15
while True:
try:
tcp=socket.create_connection((host,18080),timeout=2); break
except OSError:
if time.monotonic()>deadline: raise
time.sleep(.2)
with tcp:
data=payload("tcp"); tcp.sendall(data); assert read_line(tcp)==b"response:"+data
udp=socket.socket(socket.AF_INET,socket.SOCK_DGRAM); udp.settimeout(4)
data=payload("udp"); udp.sendto(data,(host,18081)); assert udp.recvfrom(1024)[0]==b"response:"+data
hold=socket.create_connection((host,18082),timeout=4)
data=payload("unfinished"); hold.sendall(data); assert read_line(hold)==b"response:"+data
time.sleep(90)
'''
def validate_state(value):
if (not isinstance(value, dict) or set(value) != {"schema", "project", "marker", "daemon_id", "python_image"} or
value["schema"] != SCHEMA or not re.fullmatch(r"dh-live-test-[a-f0-9]{12}", value.get("project", "")) or
not re.fullmatch(r"[a-f0-9]{24}", value.get("marker", "")) or
not re.fullmatch(r"[A-Za-z0-9:_.-]{8,128}", value.get("daemon_id", "")) or
value["python_image"] != shared.read_json(ROOT / "config/integration-images.lock.json")["python"]):
raise Error("invalid LIVE synthetic fixture identity")
return value
def fixture(path):
root = live.kit.safe_path(path)
state = validate_state(live.kit.load(root / "fixture.json"))
if os.name == "posix" and (root.stat().st_uid != os.getuid() or root.stat().st_mode & 0o077):
raise Error("LIVE fixture requires an owner-only workspace")
for name, content in (("server.py", SERVER), ("client.py", CLIENT)):
if live.kit.read(root / name) != content:
raise Error("synthetic LIVE fixture program changed")
return root, state
def prepare(args):
root = live.kit.safe_path(args.workspace)
if root.exists() or not root.parent.is_dir():
raise Error("LIVE fixture requires a new workspace")
state = validate_state({"schema": SCHEMA, "project": "dh-live-test-" + secrets.token_hex(6),
"marker": secrets.token_hex(12), "daemon_id": args.daemon_id,
"python_image": shared.read_json(ROOT / "config/integration-images.lock.json")["python"]})
if not args.apply:
return {"status": "NOT_RUN", "action": "prepare", "effects": "private synthetic programs and state only", "daemon_contacted": False}
if os.name != "posix":
raise Error("LIVE fixture preparation requires POSIX permissions")
root.mkdir(mode=0o700)
shared.write(root / "fixture.json", shared.canonical(state))
shared.write(root / "server.py", SERVER)
shared.write(root / "client.py", CLIENT)
(root / "server.py").chmod(0o644)
(root / "client.py").chmod(0o644)
return {"status": "PASS", "action": "prepare", "capture_started": False}
def identifier(arguments):
raw = shared.checked(arguments, capture=True).decode().strip()
if not re.fullmatch(r"[a-f0-9]{64}", raw):
raise Error("Docker did not return an exact generated resource ID")
return raw
def private_command(root, state, image, name, network, program, extra=()):
return ["docker", "create", "--name", name, "--label", LABEL + "=" + state["project"],
"--label", live.CAPTURE_LABEL + "=" + state["project"], "--network", network,
"--user", "65534:65534", "--read-only", "--cap-drop=ALL", "--security-opt=no-new-privileges:true",
"--memory=128m", "--memory-swap=128m", "--cpus=0.5", "--pids-limit=32", "--log-driver=none", "--pull=never",
"--mount", "type=bind,src=" + str(root / program) + ",dst=/program.py,readonly"] + list(extra) + [image, "python", "-B", "/program.py"]
def cleanup_container(identity, project):
actual = shared.checked(["docker", "inspect", "--format", '{{index .Config.Labels "' + LABEL + '"}}', identity], capture=True).decode().strip()
if actual != project:
raise Error("synthetic container ownership mismatch; cleanup refused")
shared.checked(["docker", "rm", "--force", identity], timeout=30)
def cleanup_network(identity, project):
actual = shared.checked(["docker", "network", "inspect", "--format", '{{index .Labels "' + live.CAPTURE_LABEL + '"}}', identity], capture=True).decode().strip()
if actual != project:
raise Error("synthetic network ownership mismatch; cleanup refused")
shared.checked(["docker", "network", "rm", identity], timeout=30)
def reconcile_resource(kind, name, project):
"""Resolve pre-registered names after successful OR uncertain create.
A matching name alone never authorizes removal. Inspect the exact returned
ID, name and private label; then pass the immutable ID to the cleanup path.
"""
if kind not in {"container", "network"} or not re.fullmatch(r"dh-live-test-[a-f0-9]{12}", project):
raise Error("invalid synthetic cleanup scope")
allowed = {project} if kind == "network" else {project + suffix for suffix in ("-source", "-first", "-restarted")}
if name not in allowed:
raise Error("unregistered synthetic resource name")
listing = ["docker", "ps", "--all", "--quiet", "--no-trunc"] if kind == "container" else ["docker", "network", "ls", "--quiet", "--no-trunc"]
listing += ["--filter", "name=^" + ("/" if kind == "container" else "") + name + "$"]
identities = shared.checked(listing, capture=True).decode().split()
if len(identities) > 1 or any(not re.fullmatch(r"[a-f0-9]{64}", item) for item in identities):
raise Error("unexpected synthetic cleanup listing")
for identity in identities:
labels = ".Config.Labels" if kind == "container" else ".Labels"
label = LABEL if kind == "container" else live.CAPTURE_LABEL
template = '{"id":{{json .Id}},"name":{{json .Name}},"owner":{{json (index ' + labels + ' "' + label + '")}}}'
metadata = json.loads(shared.checked(["docker", kind, "inspect", "--format", template, identity], capture=True))
if metadata != {"id": identity, "name": ("/" if kind == "container" else "") + name, "owner": project}:
raise Error("synthetic resource name or ownership mismatch; cleanup refused")
(cleanup_container if kind == "container" else cleanup_network)(identity, project)
def collect(config, secret, patterns, marker):
checks = {}
for kind, port in PORTS.items():
found = live.request(config, secret, "/api/stream/" + str(port), "POST",
{"startingFrom": None, "pageSize": 20, "favorites": False, "pattern": None})
# Whole-marker SUBSTRING matches can be packet-local upstream. Do not
# hide a correctly captured TCP stream when its marker crosses packets.
if not isinstance(found, list) or len(found) > 4:
raise Error("synthetic LIVE stream collection exceeded its bound")
checks[kind + "_one_stream"] = False
checks[kind + "_request_incoming"] = False
checks[kind + "_response_outgoing"] = False
checks[kind + "_protocol"] = False
matched = []
request = ("request:" + marker + ":" + kind + "\n").encode("ascii")
for stream in found:
identity = stream.get("id")
if type(identity) is not int or identity <= 0:
raise Error("invalid synthetic LIVE stream ID")
packets = live.request(config, secret, "/api/packet/" + str(identity), "POST", {"startingFrom": None, "pageSize": 256})
if not isinstance(packets, list) or len(packets) > 256:
raise Error("invalid synthetic LIVE packet collection")
directions, counts, previous = {True: bytearray(), False: bytearray()}, {True: 0, False: 0}, 0
for packet in packets:
packet_id, incoming = packet.get("id"), packet.get("incoming")
if type(packet_id) is not int or packet_id <= previous or type(incoming) is not bool:
raise Error("synthetic packets must have strictly ordered IDs and explicit direction")
previous = packet_id
raw = base64.b64decode(packet.get("content", ""), validate=True)
directions[incoming].extend(raw)
if raw:
counts[incoming] += 1
if len(directions[incoming]) > 2048:
raise Error("synthetic packet payload exceeded its bound")
# UDP keeps datagram boundaries; only TCP permits segmentation.
incoming = directions[True] == request and (kind != "udp" or counts[True] == 1)
outgoing = directions[False] == b"response:" + request and (kind != "udp" or counts[False] == 1)
if incoming or outgoing:
matched.append((incoming, outgoing, stream.get("protocol") == ("UDP" if kind == "udp" else "TCP")))
checks[kind + "_one_stream"] = len(matched) == 1
if len(matched) == 1:
checks[kind + "_request_incoming"], checks[kind + "_response_outgoing"], checks[kind + "_protocol"] = matched[0]
return checks
def configure(config, secret, marker, first):
result = {}
for kind, port in PORTS.items():
if first:
created = live.request(config, secret, "/api/service/", "POST", {"port": port, "name": "Synthetic LIVE " + kind,
"decryptTls": False, "http": False, "urldecodeHttpRequests": False, "mergeAdjacentPackets": False, "parseWebSockets": False})
if not isinstance(created, dict) or created.get("port") != port:
raise Error("synthetic LIVE service creation failed")
pattern = live.request(config, secret, "/api/pattern/", "POST", {"name": "Synthetic LIVE marker " + kind,
"value": marker, "color": "#123456", "searchType": "SUBSTRING", "directionType": "BOTH", "actionType": "FIND", "serviceId": port})
identity = pattern.get("id") if isinstance(pattern, dict) else None
if type(identity) is not int or identity < 1 or pattern.get("enabled") is not True:
raise Error("synthetic LIVE pattern creation failed")
result[kind] = identity
return result
def run(args):
root, state = fixture(args.workspace)
if not args.apply:
return {"status": "NOT_RUN", "action": "run", "effects": "fresh isolated TCP/UDP source, clients and LIVE Packmate; exact-owned cleanup",
"requires": "--apply --approval-id --capture-approved", "real_traffic": "NOT_RUN"}
if not sys.platform.startswith("linux") or not args.capture_approved:
raise Error("synthetic LIVE run requires Linux and --capture-approved")
if (root / "deployment").exists() or (root / "result.json").exists():
raise Error("LIVE smoke requires a fresh fixture; previous data cannot produce a PASS")
live.daemon({"daemon_id": state["daemon_id"]})
raw = shared.checked(["docker", "image", "inspect", "--format", "{{.Id}};{{.Os}};{{.Architecture}}", state["python_image"]], capture=True).decode().strip().split(";")
if len(raw) != 3 or not re.fullmatch(r"sha256:[a-f0-9]{64}", raw[0]) or raw[1:] != ["linux", "amd64"]:
raise Error("synthetic LIVE requires the cached pinned native Linux amd64 Python image")
image = raw[0]
network, owner, children, prepared = None, None, [], False
attempted_network, attempted_containers = None, []
checks, metrics, cleanup = {}, {}, {}
phase, failure = "prepare-resources", None
try:
attempted_network = state["project"]
network = identifier(["docker", "network", "create", "--driver", "bridge", "--label", live.CAPTURE_LABEL + "=" + state["project"], attempted_network])
attempted_containers.append(("source", state["project"] + "-source"))
owner = identifier(private_command(root, state, image, attempted_containers[-1][1], network, "server.py", ["--publish", "127.0.0.1::65000/tcp"]))
shared.checked(["docker", "start", owner], timeout=30)
local_ip = shared.checked(["docker", "inspect", "--format", '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}', owner], capture=True).decode().strip()
published = shared.checked(["docker", "port", owner, "65000/tcp"], capture=True).decode().strip()
match = re.fullmatch(r"127\.0\.0\.1:([0-9]{1,5})", published)
if not match:
raise Error("synthetic LIVE owner did not publish exactly a loopback UI port")
config = live.profile({"schema": live.SCHEMA, "daemon_id": state["daemon_id"], "capture_container": owner,
"network_id": network, "capture_scope": state["project"], "interface": "eth0", "local_ip": local_ip,
"bind_address": "127.0.0.1", "ui_port": int(match[1]), "tcp_timeout_seconds": 4, "udp_timeout_seconds": 3,
"timeout_check_seconds": 1, "retention_minutes": 60, "cleanup_interval_minutes": 1})
secret = {"username": "synthetic-" + secrets.token_hex(6), "password": secrets.token_hex(24), "db_password": secrets.token_hex(24)}
shared.write(root / "profile.json", shared.canonical(config))
shared.write(root / "credentials.json", shared.canonical(secret))
params = SimpleNamespace(workspace=root / "deployment", profile=root / "profile.json", credentials=root / "credentials.json",
apply=True, approval_id=args.approval_id, capture_approval=owner, action="up")
live.prepare(params)
prepared = True
phase = "live-start"
live.execute(params)
checks["live_started_automatically"] = live.request(config, secret, "/api/pcap/started") is True
if live.request(config, secret, "/api/service/") != []:
raise Error("synthetic LIVE smoke requires empty initial service state")
for index, suffix in enumerate(("first", "restarted")):
phase = "traffic-" + suffix
marker = state["marker"] + "-" + suffix
patterns = configure(config, secret, marker, index == 0)
started = time.monotonic()
attempted_containers.append(("client_" + str(index), state["project"] + "-" + suffix))
child = identifier(private_command(root, state, image, attempted_containers[-1][1], network, "client.py") + [local_ip, marker])
children.append(child)
shared.checked(["docker", "start", child], timeout=30)
observed = {}
deadline = time.monotonic() + 35
while time.monotonic() < deadline:
observed = collect(config, secret, patterns, marker)
if all(observed.values()):
break
time.sleep(1)
checks.update({suffix + "_" + key: value for key, value in observed.items()})
metrics[suffix + "_all_streams_visible_seconds"] = round(time.monotonic() - started, 3)
checks[suffix + "_timeout_saved_while_connection_open"] = shared.checked(["docker", "inspect", "--format", "{{.State.Running}}", child], capture=True).strip() == b"true" and all(observed.values())
if index == 0:
first_patterns, first_marker = patterns, marker
phase = "restart-capture"
_, deployment = live.workspace(root / "deployment")
live.owned(deployment)
shared.checked(live.command(root / "deployment", deployment, True) + ["stop", "--timeout", "10", "packmate"], timeout=30)
live.execute(params)
checks["restart_preserved_streams"] = all(collect(config, secret, first_patterns, first_marker).values())
phase = "complete"
except (Error, OSError, ValueError, KeyError, TypeError, AttributeError, KeyboardInterrupt) as error:
failure = type(error).__name__
finally:
if prepared:
try:
live.execute(SimpleNamespace(workspace=root / "deployment", action="down", apply=True, capture_approval=None))
cleanup["deployment"] = True
except (Error, OSError, ValueError, KeyboardInterrupt):
cleanup["deployment"] = False
for key, name in reversed(attempted_containers):
try:
reconcile_resource("container", name, state["project"])
cleanup[key] = True
except (Error, OSError, ValueError, KeyboardInterrupt):
cleanup[key] = False
if attempted_network:
try:
reconcile_resource("network", attempted_network, state["project"])
cleanup["network"] = True
except (Error, OSError, ValueError, KeyboardInterrupt):
cleanup["network"] = False
result = {"schema": SCHEMA, "status": "BLOCKED" if failure else "PASS" if checks and all(checks.values()) and all(cleanup.values()) else "FAIL",
"phase": phase, "error_type": failure, "checks": checks, "metrics": metrics, "cleanup": cleanup,
"mode": "LIVE", "network_scope": "generated bridge and synthetic container namespace only; no host capture",
"retention": "age cleanup configured; hard disk bound and long-running cleanup NOT_RUN", "not_validated": live.NOT_VALIDATED,
"raw_output": "suppressed", "private_artifacts_retained": True}
shared.write(root / "result.json", shared.canonical(result))
return result
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("action", choices=["prepare", "run"])
parser.add_argument("--workspace", required=True)
parser.add_argument("--daemon-id")
parser.add_argument("--approval-id")
parser.add_argument("--apply", action="store_true")
parser.add_argument("--capture-approved", action="store_true")
args = parser.parse_args(argv)
try:
if args.apply and not (args.approval_id and re.fullmatch(r"[A-Za-z0-9_.-]{1,80}", args.approval_id)):
raise Error("mutations require --apply and a non-secret --approval-id")
result = prepare(args) if args.action == "prepare" else run(args)
print(json.dumps(result, sort_keys=True))
return {"PASS": 0, "NOT_RUN": 0, "FAIL": 1, "BLOCKED": 2}[result["status"]]
except (Error, OSError, ValueError, TypeError, KeyError, AttributeError, KeyboardInterrupt) as error:
print(json.dumps({"status": "BLOCKED", "error_type": type(error).__name__, "raw_output": "suppressed"}))
return 2
if __name__ == "__main__":
raise SystemExit(main())
+161
View File
@@ -0,0 +1,161 @@
#!/usr/bin/env python3
"""Prove Packmate's configuration-only auth-log suppression with synthetic data.
Creates a fresh FILE fixture only. The control intentionally logs a disposable
failed-password canary; no raw log or credential is printed or exported. A
positive control is required so absence alone cannot produce a false PASS.
"""
from __future__ import annotations
import argparse
import hashlib
import importlib.util
import json
from pathlib import Path
import re
import secrets
import sys
import time
SPEC = importlib.util.spec_from_file_location("logger_packmate", Path(__file__).with_name("packmate_smoke.py"))
pack = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(pack)
safe = pack._sibling("neo_release_smoke")
Error = pack.FixtureError
LOGGER = "ru.serega6531.packmate.configuration.SecurityConfiguration"
SCHEMA = "durkahelper.packmate-logger.v1"
NOTICE = ["other upstream loggers", "real credentials", "LIVE capture", "Docker Desktop", "ARM64"]
def overlay(suppressed):
app = {"logging": {"driver": "json-file", "options": {"max-size": "1m", "max-file": "1"}}}
if suppressed:
# Compose merges mounts by container destination, replacing this single
# config mount; application.properties and the upstream image stay intact.
app["volumes"] = ["./logger.properties:/fixture/application.properties:ro"]
return {"services": {"packmate": app}}
def prepare(args):
root = pack.shared.no_links(args.workspace)
result = pack.prepare(args)
if not args.apply:
return {**result, "effects": ["new synthetic FILE fixture", "bounded positive-control logs",
"configuration-only logger override"], "not_validated": NOTICE}
root, state = pack.fixture(root)
settings = pack.properties(state) + ("logging.level." + LOGGER + "=OFF\n").encode()
pack.shared.write(root / "logger.properties", settings)
(root / "logger.properties").chmod(0o644)
for name, suppressed in (("control.json", False), ("suppressed.json", True)):
pack.shared.write(root / name, pack.shared.canonical(overlay(suppressed)))
pack.shared.write(root / "logger-fixture.json", pack.shared.canonical({
"schema": SCHEMA, "project": state["project"], "settings_sha256": hashlib.sha256(settings).hexdigest()}))
return {"status": "PASS", "action": "prepare", "schema": SCHEMA, "not_validated": NOTICE}
def fixture(path):
root, state = pack.fixture(path)
settings = pack.properties(state) + ("logging.level." + LOGGER + "=OFF\n").encode()
record = json.loads(pack.bounded_bytes(root / "logger-fixture.json"))
if record != {"schema": SCHEMA, "project": state["project"],
"settings_sha256": hashlib.sha256(settings).hexdigest()}:
raise Error("invalid synthetic logger fixture")
if pack.bounded_bytes(root / "logger.properties") != settings:
raise Error("logger configuration changed")
for name, suppressed in (("control.json", False), ("suppressed.json", True)):
if pack.bounded_bytes(root / name) != pack.shared.canonical(overlay(suppressed)):
raise Error("logger overlay changed")
return root, state
def app_identity(command, state):
identity = pack.shared.checked(command + ["ps", "--quiet", "packmate"], capture=True).decode().strip()
if not re.fullmatch(r"[a-f0-9]{64}", identity):
raise Error("expected exactly one test app container")
actual = pack.shared.checked(["docker", "inspect", "--format",
'{{index .Config.Labels "com.docker.compose.project"}}', identity], capture=True).decode().strip()
if actual != state["project"]:
raise Error("logger fixture container ownership mismatch")
return identity
def logs(identity):
code, output = safe.capture(["docker", "logs", "--tail", "200", identity], timeout=10)
if code:
raise Error("bounded synthetic log read failed")
return output
def smoke(args):
root, state = fixture(args.workspace)
if not args.apply:
return {"status": "NOT_RUN", "action": "smoke", "not_validated": NOTICE,
"effects": ["own app/db startup", "failed-auth synthetic control", "own app recreation",
"configuration-only suppression check", "own project shutdown"]}
if any((root / "data/postgres").iterdir()):
raise Error("logger smoke requires a fresh unused synthetic database")
base = pack.compose_command(root, state)
active = pack.shared.checked(["docker", "ps", "-aq", "--filter",
"label=com.docker.compose.project=" + state["project"]], capture=True)
if active.strip():
raise Error("logger project already exists; use a fresh fixture")
pack.image_evidence(state)
checks = {}
started = False
try:
for suppressed in (False, True):
name = "suppressed" if suppressed else "control"
command = base + ["--file", str(root / (name + ".json"))]
started = True # A partial Compose startup still requires scoped cleanup.
pack.shared.checked(command + ["up", "--detach", "--no-build", "--pull", "never"], timeout=180)
port = pack.app_port(command)
pack.wait_ready(port, state)
identity = app_identity(command, state)
canary = ("suppressed-" if suppressed else "control-") + secrets.token_hex(24)
code, _, _ = pack.request(port, {**state, "password": canary}, "/api/service/")
checks[name + "_failed_auth_rejected"] = code == 401
time.sleep(1)
output = logs(identity)
checks[name + "_valid_credential_absent"] = state["password"].encode() not in output
checks[name + "_database_credential_absent"] = state["db_password"].encode() not in output
checks[name + "_logger_behavior"] = (canary.encode() not in output) if suppressed else (canary.encode() in output)
code, _, _ = pack.request(port, state, "/api/service/")
checks[name + "_valid_auth_still_works"] = code == 200
# No upstream/source change: configuration mount alone changes.
if not suppressed:
pack.shared.checked(command + ["stop", "--timeout", "10", "packmate"], timeout=30)
pack.shared.checked(command + ["rm", "--force", "packmate"], timeout=30)
finally:
if started:
# Exact random project, explicit canonical file. No --volumes or prune.
pack.shared.checked(base + ["down", "--timeout", "10"], timeout=60)
return {"schema": "durkahelper.packmate-logger-report.v1", "status": "PASS" if all(checks.values()) else "FAIL",
"checks": checks, "app_image": pack.APP_IMAGE, "logger": LOGGER,
"settings_sha256": hashlib.sha256(("logging.level." + LOGGER + "=OFF\n").encode()).hexdigest(),
"scope": "synthetic invalid-auth control and configuration override; upstream unchanged",
"raw_output": "never exported", "not_validated": NOTICE,
"rollback": "exact test project removed; database and private config retained"}
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("action", choices=["prepare", "smoke"])
parser.add_argument("--workspace", required=True)
parser.add_argument("--source")
parser.add_argument("--postgres-image")
parser.add_argument("--apply", action="store_true")
parser.add_argument("--approval-id")
args = parser.parse_args(argv)
try:
if args.apply and not (args.approval_id and re.fullmatch(r"[A-Za-z0-9_.-]{1,80}", args.approval_id)):
raise Error("mutations require --apply and a non-secret approval ID")
result = prepare(args) if args.action == "prepare" else smoke(args)
print(json.dumps(result, sort_keys=True))
return 1 if result["status"] == "FAIL" else 0
except (Error, OSError, ValueError, TypeError, KeyError, KeyboardInterrupt):
print(json.dumps({"status": "BLOCKED", "details": "suppressed; inspect only the exact test-owned project"}))
return 2
if __name__ == "__main__":
sys.exit(main())
+413
View File
@@ -0,0 +1,413 @@
#!/usr/bin/env python3
"""Opt-in isolated Packmate v4.0 FILE-mode smoke; no LIVE capture or deployment.
All stages default to previews. Prepared fixtures use generated synthetic data
and passwords, a private database backend, and one loopback ephemeral web port.
The app also joins a generated edge bridge and has outbound connectivity.
Pre-pull the exact images before rehearsing disconnected operation.
"""
from __future__ import annotations
import argparse
import base64
import hashlib
import importlib.util
import json
import os
from pathlib import Path
import re
import secrets
import stat
import sys
import time
import urllib.error
import urllib.request
def _sibling(name):
spec = importlib.util.spec_from_file_location("fixture_" + name, Path(__file__).with_name(name + ".py"))
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
shared = _sibling("stack_smoke")
pcap = _sibling("synthetic_pcap")
FixtureError = shared.FixtureError
SOURCE_PIN = "938031f1dedfbedabef5b049368ed5b6ba6a900a"
APP_IMAGE = "registry.gitlab.com/packmate/packmate:v4.0@sha256:faa39ec74a63d84558e08ab949b7724a0a014f6629d105a5212a3afb05c7cbf7"
SCHEMA = "durkahelper.packmate-fixture.v1"
STATE_KEYS = {"schema", "project", "source_contract_commit", "app_image", "postgres_image",
"username", "password", "db_password", "marker", "approval_id"}
MAX_JSON = 1024 * 1024
PORT = 65000
ROLLBACK = "down --workspace SAME_WORKSPACE --apply --approval-id ID; data and images retained"
NETWORK_SCOPE = "database internal backend only; app also joins project edge bridge with outbound connectivity; published web port loopback only"
SAFE_API_PATH = re.compile(r"/api/(?:service/|pattern/|pcap/(?:started|start)|stream/18080|packet/[1-9][0-9]{0,18})\Z")
NOT_VALIDATED = ["LIVE capture", "TLS decryption", "large PCAP performance", "recovery",
"Apple Silicon", "Docker Desktop", "team Ethernet access",
"offline image acquisition", "image-to-source build provenance"]
def bounded_bytes(path, limit=MAX_JSON):
path = shared.no_links(path)
before = path.lstat()
if not stat.S_ISREG(before.st_mode) or before.st_size > limit:
raise FixtureError("fixture input must be a bounded regular file")
# A regular-file lstat can race with FIFO replacement. Nonblocking open
# prevents waiting for a writer before descriptor metadata can reject it.
flags = (os.O_RDONLY | getattr(os, "O_BINARY", 0) | getattr(os, "O_NOFOLLOW", 0) |
getattr(os, "O_NONBLOCK", 0))
descriptor = os.open(path, flags)
try:
opened = os.fstat(descriptor)
if (not stat.S_ISREG(opened.st_mode) or
(before.st_dev, before.st_ino, before.st_size, before.st_mtime_ns) != (
opened.st_dev, opened.st_ino, opened.st_size, opened.st_mtime_ns)):
raise FixtureError("fixture input changed during open")
with os.fdopen(descriptor, "rb", closefd=False) as stream:
data = stream.read(limit + 1)
after = os.fstat(descriptor)
if (len(data) != before.st_size or len(data) > limit or
opened.st_mtime_ns != after.st_mtime_ns or opened.st_size != after.st_size):
raise FixtureError("fixture input changed while reading")
return data
finally:
os.close(descriptor)
def validate_state(state):
if not isinstance(state, dict) or set(state) != STATE_KEYS:
raise FixtureError("invalid Packmate fixture state")
if (state["schema"] != SCHEMA or state["source_contract_commit"] != SOURCE_PIN or
state["app_image"] != APP_IMAGE or
not isinstance(state["postgres_image"], str) or
not re.fullmatch(r"postgres:15\.2@sha256:[a-f0-9]{64}", state["postgres_image"])):
raise FixtureError("fixture must retain the pinned Packmate and PostgreSQL versions")
for name, pattern in (("project", r"dh-packmate-[a-f0-9]{12}"),
("username", r"fixture-[a-f0-9]{12}"),
("password", r"[a-f0-9]{48}"), ("db_password", r"[a-f0-9]{48}"),
("marker", r"[a-f0-9]{24}"), ("approval_id", r"[A-Za-z0-9_.-]{1,80}")):
if not isinstance(state[name], str) or not re.fullmatch(pattern, state[name]):
raise FixtureError("invalid generated fixture identity")
return state
def properties(state):
return ("spring.datasource.password=" + state["db_password"] + "\n" +
"packmate.web.account-login=" + state["username"] + "\n" +
"packmate.web.account-password=" + state["password"] + "\n").encode("ascii")
def compose_spec(state, *, legacy_internal_only=False, legacy_no_jna=False):
def service(**values):
result = {"restart": "no", "cpus": 1.0, "mem_limit": "512m", "pids_limit": 128,
"security_opt": ["no-new-privileges:true"], "logging": {"driver": "none"},
"networks": ["backend"]}
result.update(values)
return result
spec = {
"services": {
"db": service(image=state["postgres_image"],
environment={"POSTGRES_USER": "packmate", "POSTGRES_DB": "packmate",
"POSTGRES_PASSWORD": state["db_password"]},
volumes=["./data/postgres:/var/lib/postgresql/data"],
healthcheck={"test": ["CMD", "pg_isready", "-U", "packmate", "-d", "packmate"],
"interval": "2s", "timeout": "2s", "retries": 30}),
"packmate": service(image=APP_IMAGE, user="65534:65534", read_only=True,
cap_drop=["ALL"], mem_limit="1g", working_dir="/app",
networks=["backend", "edge"],
# JNA extracts its native dispatch library before loading it.
# Docker's default noexec tmpfs makes FILE import fail even
# though the UI is healthy. Allow execution only on this small
# app-owned native-library mount, not on general /tmp.
tmpfs=["/tmp:size=67108864,mode=1777,noexec",
"/jna:size=16777216,mode=0700,uid=65534,gid=65534,nosuid,nodev,exec"],
volumes=["./application.properties:/fixture/application.properties:ro",
"./pcaps:/app/pcaps:ro"],
entrypoint=["java"], command=["-Xms64m", "-Xmx512m", "-XX:ActiveProcessorCount=1",
"-Djna.tmpdir=/jna",
"-Djava.net.preferIPv4Stack=true", "-Djava.net.preferIPv4Addresses=true",
"-jar", "/app/app.jar", "--spring.config.additional-location=file:/fixture/application.properties",
"--spring.datasource.url=jdbc:postgresql://db:5432/packmate",
"--spring.datasource.username=packmate", "--packmate.capture-mode=FILE",
"--packmate.pcap-file=synthetic.pcap", "--packmate.local-ip=" + pcap.SERVER_IP,
"--packmate.cleanup.enabled=false", "--server.port=65000", "--server.address=0.0.0.0"],
ports=[{"target": PORT, "published": "0", "host_ip": "127.0.0.1", "protocol": "tcp"}],
depends_on={"db": {"condition": "service_healthy"}}),
},
# Internal-only bridge membership suppresses published ports on tested
# Engine 29. The app's project-owned edge enables loopback publication;
# it also permits app egress and is NOT an egress-isolation boundary.
"networks": {"backend": {"internal": True}, "edge": {"internal": False}},
}
if legacy_internal_only:
# Cleanup compatibility only; fixture() never accepts this for startup.
spec["networks"] = {"fixture": {"internal": True}}
for service in spec["services"].values():
service["networks"] = ["fixture"]
if legacy_no_jna:
spec["services"]["packmate"]["tmpfs"] = ["/tmp:size=67108864,mode=1777"]
spec["services"]["packmate"]["command"].remove("-Djna.tmpdir=/jna")
return spec
def fixture(workspace, check_payload=True):
workspace = shared.no_links(workspace)
state = validate_state(json.loads(bounded_bytes(workspace / "fixture.json")))
expected = {"compose.json": shared.canonical(compose_spec(state))}
if check_payload:
expected.update({"application.properties": properties(state),
"pcaps/synthetic.pcap": pcap.make_pcap(state["marker"])})
shared.no_links(workspace / "data" / "postgres")
for name, payload in expected.items():
actual = bounded_bytes(workspace / name)
if actual != payload:
if (not check_payload and name == "compose.json" and any(
actual == shared.canonical(compose_spec(state, legacy_internal_only=internal, legacy_no_jna=no_jna))
for internal, no_jna in ((True, False), (True, True), (False, True)))):
continue
raise FixtureError("generated fixture file changed; create a new fixture")
return workspace, state
def prepare(args):
workspace = shared.no_links(args.workspace)
if workspace.exists() or not workspace.parent.is_dir():
raise FixtureError("workspace must be a new directory under an existing parent")
if not args.postgres_image or not re.fullmatch(r"postgres:15\.2@sha256:[a-f0-9]{64}", args.postgres_image):
raise FixtureError("prepare requires the immutable postgres:15.2 repository digest")
if not args.apply:
return {"status": "NOT_RUN", "action": "prepare", "mode": "FILE", "source_contract_commit": SOURCE_PIN,
"app_image": APP_IMAGE, "network_scope": NETWORK_SCOPE,
"effects": ["new private fixture", "synthetic PCAP and generated passwords"]}
if not args.source:
raise FixtureError("prepare --apply requires the reviewed pinned source checkout")
source = shared.no_links(args.source)
if shared.git_read(source, ["rev-parse", "HEAD"]).decode().strip() != SOURCE_PIN:
raise FixtureError("Packmate source HEAD differs from retained API contract pin")
if shared.git_read(source, ["status", "--porcelain", "--untracked-files=all"]):
raise FixtureError("Packmate source checkout must be clean")
state = {"schema": SCHEMA, "project": "dh-packmate-" + secrets.token_hex(6),
"source_contract_commit": SOURCE_PIN, "app_image": APP_IMAGE, "postgres_image": args.postgres_image,
"username": "fixture-" + secrets.token_hex(6), "password": secrets.token_hex(24),
"db_password": secrets.token_hex(24), "marker": secrets.token_hex(12),
"approval_id": args.approval_id}
validate_state(state)
workspace.mkdir(mode=0o700)
shared.write(workspace / "compose.json", shared.canonical(compose_spec(state)))
shared.write(workspace / "application.properties", properties(state))
# Only disposable generated credentials and synthetic capture are readable by
# the nonroot app. The enclosing host fixture remains mode 0700.
(workspace / "application.properties").chmod(0o644)
shared.write(workspace / "pcaps/synthetic.pcap", pcap.make_pcap(state["marker"]))
(workspace / "pcaps").chmod(0o755)
(workspace / "pcaps/synthetic.pcap").chmod(0o644)
(workspace / "data/postgres").mkdir(parents=True, mode=0o700)
shared.write(workspace / "fixture.json", shared.canonical(state))
return {"status": "PASS", "action": "prepare", "project": state["project"], "mode": "FILE",
"pcap_sha256": hashlib.sha256(pcap.make_pcap(state["marker"])).hexdigest(),
"not_validated": NOT_VALIDATED, "network_scope": NETWORK_SCOPE}
def compose_command(workspace, state):
return ["docker", "compose", "--project-name", state["project"], "--project-directory", str(workspace),
"--file", str(workspace / "compose.json")]
def app_port(command):
value = shared.checked(command + ["port", "packmate", str(PORT)], capture=True).decode().strip()
match = re.fullmatch(r"127\.0\.0\.1:([0-9]{1,5})", value)
if not match or not 1 <= int(match[1]) <= 65535:
raise FixtureError("Packmate must publish one loopback ephemeral port")
return int(match[1])
def request(port, state, path, method="GET", body=None, auth="valid"):
if not 1 <= port <= 65535 or not path.startswith("/") or path.startswith("//"):
raise FixtureError("invalid local fixture request")
headers = {"Content-Type": "application/json", "Accept-Encoding": "identity"}
if auth != "none":
password = state["password"] if auth == "valid" else "wrong-generated-fixture-password"
headers["Authorization"] = "Basic " + base64.b64encode(
(state["username"] + ":" + password).encode("ascii")).decode("ascii")
req = urllib.request.Request("http://127.0.0.1:" + str(port) + path, method=method, headers=headers,
data=None if body is None else shared.canonical(body))
opener = urllib.request.build_opener(urllib.request.ProxyHandler({}), shared.NoRedirect())
try:
response = opener.open(req, timeout=5)
except urllib.error.HTTPError as error:
response = error
with response:
content = response.read(MAX_JSON + 1)
if len(content) > MAX_JSON:
raise FixtureError("Packmate HTTP response exceeds limit")
return response.status, content, response.headers.get("WWW-Authenticate", "")
def json_request(port, state, path, method="GET", body=None):
status, content, _ = request(port, state, path, method, body)
if status != 200:
# Only fixture-controlled routes, methods and the numeric status belong
# in diagnostics. Never include response bodies, headers or credentials.
label = (method + " " + path if method in {"GET", "POST"} and
isinstance(path, str) and SAFE_API_PATH.fullmatch(path) else "unlisted request")
code = str(status) if type(status) is int and 100 <= status <= 599 else "invalid"
raise FixtureError("Packmate API request failed: " + label + " returned HTTP " + code +
"; raw response suppressed")
return json.loads(content) if content else None
def wait_ready(port, state, timeout=120):
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
try:
result = json_request(port, state, "/api/service/")
if isinstance(result, list):
return
except (FixtureError, OSError, ValueError, urllib.error.URLError):
pass
time.sleep(1)
raise FixtureError("Packmate readiness timed out")
def image_evidence(state):
result = {}
for role, reference in (("packmate", APP_IMAGE), ("postgres", state["postgres_image"])):
raw = shared.checked(["docker", "image", "inspect", "--format",
'{{.Os}};{{.Architecture}};{{.Id}}', reference], capture=True)
match = re.fullmatch(rb"(linux);(amd64|arm64);(sha256:[a-f0-9]{64})\s*", raw)
if not match:
raise FixtureError("runtime image identity is unavailable")
result[role] = {"reference": reference, "os": match[1].decode(), "architecture": match[2].decode(),
"image_id": match[3].decode()}
return result
def smoke(command, state):
port = app_port(command)
wait_ready(port, state)
checks = {}
for auth in ("none", "wrong"):
code, _, challenge = request(port, state, "/api/service/", auth=auth)
checks["auth_" + auth + "_rejected"] = code == 401 and challenge.lower().startswith("basic")
code, content, _ = request(port, state, "/")
checks["authenticated_ui"] = code == 200 and b"<html" in content.lower()
# A fresh fixture prevents old persisted results from producing a false PASS.
if json_request(port, state, "/api/service/") != [] or json_request(port, state, "/api/pcap/started") is not False:
raise FixtureError("smoke requires a fresh unprocessed fixture database")
service = {"port": pcap.SERVICE_PORT, "name": "DurkaHelper synthetic HTTP", "decryptTls": False,
"http": False, "urldecodeHttpRequests": False, "mergeAdjacentPackets": False,
"parseWebSockets": False}
created = json_request(port, state, "/api/service/", "POST", service)
checks["service_created"] = isinstance(created, dict) and created.get("port") == pcap.SERVICE_PORT
pattern = json_request(port, state, "/api/pattern/", "POST", {
"name": "Synthetic marker", "value": state["marker"], "color": "#123456", "searchType": "SUBSTRING",
"directionType": "BOTH", "actionType": "FIND", "serviceId": pcap.SERVICE_PORT})
pattern_id = pattern.get("id") if isinstance(pattern, dict) else None
if type(pattern_id) is not int or pattern_id < 1 or pattern.get("enabled") is not True:
raise FixtureError("fixture pattern creation was not confirmed")
checks["pattern_created"] = True
json_request(port, state, "/api/pcap/start", "POST")
checks["file_import_started"] = json_request(port, state, "/api/pcap/started") is True
query = {"startingFrom": None, "pageSize": 10, "favorites": False, "pattern": {"id": pattern_id}}
streams = []
deadline = time.monotonic() + 45
while time.monotonic() < deadline:
streams = json_request(port, state, "/api/stream/" + str(pcap.SERVICE_PORT), "POST", query)
if isinstance(streams, list) and streams:
break
time.sleep(1)
checks["filtered_stream_found"] = isinstance(streams, list) and len(streams) == 1
checks["request_exact_and_incoming"] = False
checks["response_exact_and_outgoing"] = False
checks["pattern_matches_both_directions"] = False
if checks["filtered_stream_found"]:
stream = streams[0]
stream_id = stream.get("id")
if type(stream_id) is not int or stream_id < 1:
raise FixtureError("invalid imported stream identifier")
checks["stream_metadata"] = (stream.get("service") == pcap.SERVICE_PORT and stream.get("protocol") == "TCP"
and pattern_id in stream.get("foundPatternsIds", []))
packets = json_request(port, state, "/api/packet/" + str(stream_id), "POST",
{"startingFrom": None, "pageSize": 20})
if not isinstance(packets, list) or len(packets) > 20:
raise FixtureError("invalid imported packet collection")
wanted_request, wanted_response = pcap.payloads(state["marker"])
matched_directions = set()
for packet in packets:
data = base64.b64decode(packet.get("content", ""), validate=True)
incoming = packet.get("incoming")
if data == wanted_request and incoming is True:
checks["request_exact_and_incoming"] = True
if data == wanted_response and incoming is False:
checks["response_exact_and_outgoing"] = True
if any(match.get("patternId") == pattern_id for match in packet.get("matches", [])):
matched_directions.add(incoming)
checks["pattern_matches_both_directions"] = matched_directions == {True, False}
return {"schema": "durkahelper.packmate-smoke.v1", "status": "PASS" if all(checks.values()) else "FAIL",
"checks": checks, "project": state["project"], "source_contract_commit": SOURCE_PIN,
"mode": "FILE", "runtime_images": image_evidence(state), "not_validated": NOT_VALIDATED,
"rollback": ROLLBACK, "network_scope": NETWORK_SCOPE,
"upstream_warning": "failed authentication logs passwords; fixture Docker logs disabled"}
def execute(args):
workspace, state = fixture(args.workspace, check_payload=args.action != "down")
args.validated_project = state["project"]
command = compose_command(workspace, state)
if not args.apply:
return {"status": "NOT_RUN", "action": args.action, "project": state["project"], "mode": "FILE",
"requires": "--apply --approval-id", "rollback": ROLLBACK, "network_scope": NETWORK_SCOPE}
shared.checked(command + ["config", "--quiet"])
if args.action == "pull":
shared.checked(command + ["pull", "--quiet"], timeout=300)
elif args.action == "up":
image_evidence(state) # Fail closed when images have not been pre-pulled.
try:
shared.checked(command + ["up", "--detach", "--no-build", "--pull", "never"], timeout=180)
wait_ready(app_port(command), state)
except (FixtureError, OSError, ValueError, urllib.error.URLError, KeyboardInterrupt):
try:
shared.checked(command + ["down", "--timeout", "10"], timeout=60)
args.rollback_status = "generated project stopped; data retained"
except (FixtureError, KeyboardInterrupt):
args.rollback_status = "automatic stop failed; exact project cleanup required"
raise
elif args.action == "smoke":
return smoke(command, state)
elif args.action == "down":
shared.checked(command + ["down", "--timeout", "10"], timeout=60)
return {"status": "PASS", "action": args.action, "project": state["project"], "mode": "FILE",
"runtime_images": image_evidence(state) if args.action != "down" else {}, "rollback": ROLLBACK,
"network_scope": NETWORK_SCOPE}
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("action", choices=["prepare", "pull", "up", "smoke", "down"])
parser.add_argument("--workspace", required=True)
parser.add_argument("--source", help="reviewed Packmate checkout at the retained source pin")
parser.add_argument("--postgres-image", help="postgres:15.2@sha256:... resolved repository digest")
parser.add_argument("--apply", action="store_true")
parser.add_argument("--approval-id")
args = parser.parse_args(argv)
try:
if args.apply and not (args.approval_id and re.fullmatch(r"[A-Za-z0-9_.-]{1,80}", args.approval_id)):
raise FixtureError("mutations require a non-secret approval identifier")
result = prepare(args) if args.action == "prepare" else execute(args)
print(json.dumps(result, sort_keys=True, indent=2))
return 1 if result["status"] == "FAIL" else 0
except (FixtureError, OSError, ValueError, TypeError, KeyError, AttributeError, urllib.error.URLError, KeyboardInterrupt) as error:
result = {"status": "BLOCKED", "reason":
"fixture operation interrupted; raw output suppressed" if isinstance(error, KeyboardInterrupt)
else str(error) if isinstance(error, FixtureError) else "fixture operation failed: " + type(error).__name__}
if getattr(args, "validated_project", None):
result.update({"project": args.validated_project, "rollback": ROLLBACK,
"rollback_status": getattr(args, "rollback_status", "not automatically performed")})
print(json.dumps(result))
return 2
if __name__ == "__main__":
sys.exit(main())
+380
View File
@@ -0,0 +1,380 @@
#!/usr/bin/env python3
"""Opt-in native PostgreSQL recovery drill for the synthetic S4DFarm fixture.
No production database, overwrite restore, volume deletion or host package
installation is supported. The original fixture must be stopped. Every restore
uses a new isolated database; dump, source and restored data are retained.
"""
from __future__ import annotations
import argparse
import hashlib
import importlib.util
import json
import os
from pathlib import Path
import re
import secrets
import stat
import subprocess
import sys
import threading
import time
SPEC = importlib.util.spec_from_file_location("recovery_stack", Path(__file__).with_name("stack_smoke.py"))
shared = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(shared)
FixtureError = shared.FixtureError
SCHEMA = "durkahelper.postgres-recovery.v1"
MAX_DUMP = 8 * 1024 * 1024
MAX_ROWS = 1000
STATE_KEYS = {"schema", "project", "source_project", "source_workspace", "postgres_image", "approval_id"}
NOT_VALIDATED = ["Redis recovery", "Neo application state recovery", "Packmate recovery", "production restore",
"whole-VM restore", "failure injection", "RPO/RTO target", "Apple Silicon", "Docker Desktop"]
def read_json(path):
path = shared.no_links(path)
before = path.stat()
if not stat.S_ISREG(before.st_mode) or before.st_size > 1024 * 1024:
raise FixtureError("recovery state must be a bounded regular file")
flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0) | getattr(os, "O_BINARY", 0)
descriptor = os.open(path, flags)
with os.fdopen(descriptor, "rb") as stream:
opened = os.fstat(stream.fileno())
if not stat.S_ISREG(opened.st_mode) or (before.st_dev, before.st_ino) != (opened.st_dev, opened.st_ino):
raise FixtureError("recovery state changed during open")
data = stream.read(1024 * 1024 + 1)
after = os.fstat(stream.fileno())
if len(data) > 1024 * 1024 or (opened.st_size, opened.st_mtime_ns) != (after.st_size, after.st_mtime_ns):
raise FixtureError("recovery state changed during read")
return json.loads(data)
def compose_spec(state):
return {"services": {"postgres": {
"image": state["postgres_image"], "restart": "no", "cpus": 1.0, "mem_limit": "512m",
"pids_limit": 128, "security_opt": ["no-new-privileges:true"], "logging": {"driver": "none"},
"environment": {"POSTGRES_USER": "farm", "POSTGRES_PASSWORD": "fixture-recovery-only", "POSTGRES_DB": "farm"},
"volumes": ["./data/postgres:/var/lib/postgresql/data"], "networks": ["recovery"],
"healthcheck": {"test": ["CMD", "pg_isready", "-U", "farm", "-d", "farm"],
"interval": "2s", "timeout": "2s", "retries": 30}}},
"networks": {"recovery": {"internal": True}}}
def fixture(workspace):
workspace = shared.no_links(workspace)
state = read_json(workspace / "fixture.json")
if (not isinstance(state, dict) or set(state) != STATE_KEYS or state["schema"] != SCHEMA
or not re.fullmatch(r"dh-recovery-[a-f0-9]{12}", state.get("project", ""))
or not re.fullmatch(r"dh-smoke-[a-f0-9]{12}", state.get("source_project", ""))
or not re.fullmatch(r"postgres:14\.1-alpine@sha256:[a-f0-9]{64}", state.get("postgres_image", ""))):
raise FixtureError("invalid recovery fixture identity")
if read_json(workspace / "compose.json") != compose_spec(state):
raise FixtureError("recovery Compose isolation settings changed")
shared.no_links(workspace / "data/postgres")
return workspace, state
def command(workspace, state):
return ["docker", "compose", "--project-name", state["project"], "--project-directory", str(workspace),
"--file", str(workspace / "compose.json")]
def prepare(args):
source, original = shared.fixture(args.source_workspace)
workspace = shared.no_links(args.workspace)
if workspace.exists() or not workspace.parent.is_dir() or workspace.is_relative_to(source):
raise FixtureError("recovery workspace must be new and outside the source fixture")
image = original["images"]["postgres"]
if not re.fullmatch(r"postgres:14\.1-alpine@sha256:[a-f0-9]{64}", image):
raise FixtureError("recovery requires the retained farm PostgreSQL image")
if not args.apply:
return {"status": "NOT_RUN", "action": "prepare", "scope": "new synthetic PostgreSQL target only",
"effects": ["new private directory and Compose fixture"], "not_validated": NOT_VALIDATED}
workspace.mkdir(mode=0o700)
state = {"schema": SCHEMA, "project": "dh-recovery-" + secrets.token_hex(6),
"source_project": original["project"], "source_workspace": str(source),
"postgres_image": image, "approval_id": args.approval_id}
(workspace / "data/postgres").mkdir(parents=True, mode=0o700)
shared.write(workspace / "compose.json", shared.canonical(compose_spec(state)))
shared.write(workspace / "fixture.json", shared.canonical(state))
return {"status": "PASS", "action": "prepare", "project": state["project"], "not_validated": NOT_VALIDATED}
def psql(compose, sql):
# Bound capture during reading, not after subprocess.run has buffered it.
argv = compose + ["exec", "-T", "postgres", "psql", "-X", "-v", "ON_ERROR_STOP=1",
"-A", "-t", "-U", "farm", "-d", "farm", "-c", sql]
process = subprocess.Popen(argv, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
data, issues = bytearray(), []
def drain():
try:
while True:
part = process.stdout.read(65536)
if not part:
break
if len(data) + len(part) > MAX_DUMP:
raise FixtureError("synthetic query exceeded size limit")
data.extend(part)
except (OSError, FixtureError) as error:
issues.append(error)
process.kill()
thread = threading.Thread(target=drain, daemon=True)
thread.start()
try:
try:
code = process.wait(timeout=15)
except subprocess.TimeoutExpired as error:
process.kill()
process.wait(timeout=10)
raise FixtureError("synthetic query timed out; test container cleanup required") from error
thread.join(timeout=10)
if thread.is_alive() or issues or code:
raise FixtureError("synthetic query failed or exceeded bounds")
return bytes(data).strip()
finally:
if process.poll() is None:
process.kill()
process.wait(timeout=10)
thread.join(timeout=10)
process.stdout.close()
def ready(compose):
deadline = time.monotonic() + 60
while time.monotonic() < deadline:
try:
# The image initializes databases through a temporary socket-only
# server. TCP readiness waits for its final post-init server.
shared.checked(compose + ["exec", "-T", "postgres", "pg_isready", "-h", "127.0.0.1",
"-U", "farm", "-d", "farm"], timeout=5)
return
except FixtureError:
time.sleep(1)
raise FixtureError("test PostgreSQL readiness timed out")
def summary(compose):
tables = psql(compose, "SELECT table_name FROM information_schema.tables WHERE table_schema='public' "
"AND table_type='BASE TABLE' ORDER BY table_name;")
if tables != b"flags":
raise FixtureError("source/recovered database is not the expected synthetic flags schema")
counts = psql(compose, "SELECT count(*),count(*) FILTER (WHERE status='ACCEPTED'),"
"count(*) FILTER (WHERE sploit IS DISTINCT FROM 'synthetic-smoke' OR team IS DISTINCT FROM 'Synthetic' "
"OR flag !~ '^[A-Z0-9]{31}=$' OR checksystem_response IS DISTINCT FROM 'accepted synthetic fixture') FROM flags;")
if not re.fullmatch(rb"[0-9]+\|[0-9]+\|[0-9]+", counts):
raise FixtureError("invalid synthetic database counts")
total, accepted, foreign = map(int, counts.split(b"|"))
if not 1 <= accepted <= total <= MAX_ROWS or foreign:
raise FixtureError("source/recovered database contains unexpected or non-synthetic data")
rows = json.loads(psql(compose, "SELECT json_agg(row_to_json(f) ORDER BY flag) FROM flags f;"))
if not isinstance(rows, list) or len(rows) != total:
raise FixtureError("source/recovered rows changed during verification")
return {"tables": 1, "flags": total, "accepted": accepted,
"rows_sha256": hashlib.sha256(shared.canonical(rows)).hexdigest()}
def dump_database(compose, destination, limit=MAX_DUMP, timeout=60):
"""Bound disk writes while consuming native pg_dump output; retain partials."""
destination = shared.no_links(destination)
descriptor = os.open(destination, os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_BINARY", 0), 0o600)
issues, result = [], {"bytes": 0, "sha256": None}
process = None
thread = None
try:
process = subprocess.Popen(compose + ["exec", "-T", "postgres", "pg_dump", "-U", "farm", "-d", "farm",
"--format=custom", "--compress=0", "--no-owner", "--no-privileges"],
stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
def drain():
sha = hashlib.sha256()
try:
with os.fdopen(descriptor, "wb", closefd=False) as stream:
while True:
data = process.stdout.read(65536)
if not data:
break
if result["bytes"] + len(data) > limit:
raise FixtureError("native dump exceeds size limit; partial retained")
stream.write(data)
sha.update(data)
result["bytes"] += len(data)
stream.flush()
os.fsync(stream.fileno())
result["sha256"] = sha.hexdigest()
except (OSError, FixtureError) as error:
issues.append(error)
process.kill()
thread = threading.Thread(target=drain, daemon=True)
thread.start()
try:
code = process.wait(timeout=timeout)
except subprocess.TimeoutExpired as error:
process.kill()
process.wait(timeout=10)
raise FixtureError("native dump timed out; source test container cleanup required") from error
thread.join(timeout=10)
if thread.is_alive() or issues or code or result["bytes"] == 0:
raise FixtureError("native dump failed or exceeded bounds; partial retained, not restored")
with destination.open("rb") as stream:
if stream.read(5) != b"PGDMP":
raise FixtureError("native custom-format dump signature is missing")
return result
finally:
if process is not None:
if process.poll() is None:
process.kill()
process.wait(timeout=10)
if thread is not None:
thread.join(timeout=10)
if process.stdout is not None:
process.stdout.close()
os.close(descriptor)
def restore_database(compose, path, expected):
# Never --clean or --create: the caller proved this isolated database empty.
path = shared.no_links(path)
flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0) | getattr(os, "O_BINARY", 0)
with os.fdopen(os.open(path, flags), "rb") as stream:
before = os.fstat(stream.fileno())
if not stat.S_ISREG(before.st_mode) or not 5 <= before.st_size <= MAX_DUMP:
raise FixtureError("restore dump must be a bounded regular file")
digest = hashlib.sha256()
signature = stream.read(5)
digest.update(signature)
size = 5
while True:
data = stream.read(65536)
if not data:
break
size += len(data)
if size > MAX_DUMP:
raise FixtureError("restore dump changed or exceeded bounds")
digest.update(data)
opened = os.fstat(stream.fileno())
if (signature != b"PGDMP" or size != expected["bytes"] or digest.hexdigest() != expected["sha256"]
or (before.st_size, before.st_mtime_ns) != (opened.st_size, opened.st_mtime_ns)):
raise FixtureError("restore dump verification failed; no restore attempted")
stream.seek(0)
try:
process = subprocess.run(compose + ["exec", "-T", "postgres", "pg_restore", "-U", "farm", "-d", "farm",
"--exit-on-error", "--single-transaction", "--no-owner", "--no-privileges"],
stdin=stream, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=60, check=False)
except subprocess.TimeoutExpired as error:
raise FixtureError("restore timed out; new target cleanup required") from error
if process.returncode:
raise FixtureError("native restore failed; original source and dump retained")
after = os.fstat(stream.fileno())
if (before.st_size, before.st_mtime_ns) != (after.st_size, after.st_mtime_ns):
raise FixtureError("dump changed during restore; target result is not trusted")
def drill(args, workspace, state):
if not args.snapshot_confirmed:
raise FixtureError("run --apply requires --snapshot-confirmed for this approved test host")
source, original = shared.fixture(state["source_workspace"])
if original["project"] != state["source_project"] or original["images"]["postgres"] != state["postgres_image"]:
raise FixtureError("source identity changed")
source_command = shared.compose_command(source, original)
target_command = command(workspace, state)
for current in (source_command, target_command):
if shared.checked(current + ["ps", "--all", "--quiet"], capture=True).strip():
raise FixtureError("both test projects must be fully stopped before this exclusive drill")
if any((workspace / "data/postgres").iterdir()):
raise FixtureError("restore target data directory must be empty")
shared.write(workspace / "attempt.json", shared.canonical({"approval_id": args.approval_id, "snapshot_confirmed": True}))
cleanup = {}
report = {"schema": "durkahelper.recovery-result.v1", "status": "BLOCKED", "checks": {},
"not_validated": NOT_VALIDATED, "postgres_image": state["postgres_image"]}
try:
report["phase"] = "source-start"
shared.checked(source_command + ["up", "--detach", "--no-build", "--pull", "never", "postgres"], timeout=120)
ready(source_command)
report["phase"] = "source-summary"
before = summary(source_command)
report["phase"] = "native-dump"
dump = dump_database(source_command, workspace / "farm.dump")
report["phase"] = "source-stability"
if summary(source_command) != before:
raise FixtureError("synthetic source changed during native dump")
report["phase"] = "target-start"
shared.checked(target_command + ["up", "--detach", "--no-build", "--pull", "never", "postgres"], timeout=120)
ready(target_command)
report["phase"] = "target-empty"
empty = psql(target_command, "SELECT count(*) FROM information_schema.tables WHERE table_schema='public' "
"AND table_type='BASE TABLE';") == b"0"
if not empty:
raise FixtureError("new target database is not empty; restore refused")
report["phase"] = "native-restore"
restore_database(target_command, workspace / "farm.dump", dump)
report["phase"] = "restore-verification"
recovered = summary(target_command)
unchanged = summary(source_command) == before
report.update({"source": before, "restored": recovered, "dump": dump, "checks": {
"empty_target_before_restore": empty, "native_restore_matches": recovered == before,
"accepted_flags_preserved": recovered["accepted"] == before["accepted"],
"source_unchanged": unchanged}})
report["status"] = "PASS" if all(report["checks"].values()) else "FAIL"
report["phase"] = "complete"
finally:
# Exact projects only; bind data, images and dump always survive cleanup.
for role, current in (("target", target_command), ("source", source_command)):
try:
shared.checked(current + ["down", "--timeout", "10"], timeout=60)
cleanup[role] = not shared.checked(current + ["ps", "--all", "--quiet"], capture=True).strip()
except FixtureError:
cleanup[role] = False
report["cleanup"] = cleanup
if not all(cleanup.values()):
report["status"] = "BLOCKED"
shared.write(workspace / "result.json", shared.canonical(report))
return report
def execute(args):
workspace, state = fixture(args.workspace)
args.validated_project = state["project"]
if not args.apply:
return {"status": "NOT_RUN", "action": args.action, "project": state["project"],
"requires": "--apply --approval-id; run also requires --snapshot-confirmed",
"retained": ["original source data", "native dump", "restored target data"]}
if args.action == "run":
return drill(args, workspace, state)
compose = command(workspace, state)
shared.checked(compose + ["down", "--timeout", "10"], timeout=60)
return {"status": "PASS", "action": "down", "project": state["project"], "data_retained": True}
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("action", choices=["prepare", "run", "down"])
parser.add_argument("--workspace", required=True)
parser.add_argument("--source-workspace")
parser.add_argument("--apply", action="store_true")
parser.add_argument("--approval-id")
parser.add_argument("--snapshot-confirmed", action="store_true")
args = parser.parse_args(argv)
try:
if args.apply and not (args.approval_id and re.fullmatch(r"[A-Za-z0-9_.-]{1,80}", args.approval_id)):
raise FixtureError("mutations require a non-secret approval identifier")
if args.action == "prepare" and not args.source_workspace:
raise FixtureError("prepare requires the stopped synthetic --source-workspace")
result = prepare(args) if args.action == "prepare" else execute(args)
print(json.dumps(result, sort_keys=True, indent=2))
return {"PASS": 0, "NOT_RUN": 0, "FAIL": 1, "BLOCKED": 2}[result["status"]]
except (FixtureError, OSError, ValueError, KeyError, TypeError, AttributeError, KeyboardInterrupt) as error:
result = {"status": "BLOCKED", "reason": str(error) if isinstance(error, FixtureError)
else "recovery operation failed: " + type(error).__name__}
if getattr(args, "validated_project", None):
result.update({"project": args.validated_project, "retained": "source, dump/partial, target data; inspect local result.json"})
print(json.dumps(result))
return 2
if __name__ == "__main__":
sys.exit(main())
+603
View File
@@ -0,0 +1,603 @@
#!/usr/bin/env python3
"""New synthetic source -> native/cold backups -> new isolated stack restore.
Only immutable files and cached images are reused from validated lab templates.
Existing database files/containers are never read or changed. Restored Celery,
receiver and Neo worker stay disabled: this drill never replays restored queues.
"""
from __future__ import annotations
import argparse
import ast
import base64
import copy
import hashlib
import importlib.util
import io
import json
import os
from pathlib import Path, PurePosixPath
import re
import secrets
import stat
import subprocess
import sys
import tarfile
import threading
import time
def sibling(name):
spec = importlib.util.spec_from_file_location("whole_" + name, Path(__file__).with_name(name + ".py"))
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
stack = sibling("stack_smoke")
pm = sibling("packmate_smoke")
life = sibling("neo_lifecycle_smoke")
Error = stack.FixtureError
SCHEMA = "durkahelper.stack-recovery.v1"
LABEL = "io.durkahelper.stack-recovery"
MAX_BACKUP = 32 * 1024 * 1024
ROLES = ("source-farm", "source-packmate", "target-farm", "target-packmate")
NOT_VALIDATED = ["production data/queues", "automatic queue replay", "VM rollback", "Docker Desktop", "ARM64", "physical LAN", "LIVE capture", "large-data RPO/RTO"]
def read(path, limit=MAX_BACKUP):
# Reuse bounded no-follow regular-file reader; never read shared live DBs.
try:
return life.release.bounded_read(path, limit)
except life.release.FixtureError as error:
raise Error(str(error)) from error
def load(path):
return json.loads(read(path, 4 * 1024 * 1024))
def hash_bytes(value):
return hashlib.sha256(value).hexdigest()
def checked(argv, timeout=60):
"""Bound combined command output while reading, including native dumps."""
data, errors = bytearray(), []
process = subprocess.Popen(argv, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
def drain():
try:
while True:
part = process.stdout.read(65536)
if not part:
break
if len(data) + len(part) > MAX_BACKUP:
raise Error("bounded recovery command exceeded output limit")
data.extend(part)
except (OSError, Error) as error:
errors.append(error)
process.kill()
reader = threading.Thread(target=drain, daemon=True)
reader.start()
try:
try:
code = process.wait(timeout=timeout)
except subprocess.TimeoutExpired as error:
raise Error("recovery command timed out; raw output suppressed") from error
reader.join(timeout=5)
if reader.is_alive() or errors or code:
raise Error("recovery command failed or exceeded bounds; raw output suppressed")
return bytes(data)
finally:
if process.poll() is None:
process.kill()
process.wait(timeout=5)
reader.join(timeout=5)
process.stdout.close()
def image_id(reference):
raw = checked(["docker", "image", "inspect", "--format", "{{.Id}};{{.Os}};{{.Architecture}}", reference]).decode().strip()
if not re.fullmatch(r"sha256:[a-f0-9]{64};linux;amd64", raw):
raise Error("whole-stack drill requires cached native Linux amd64 images")
return raw.split(";")[0]
def owned_spec(spec, project, images, restored=False):
result = copy.deepcopy(spec)
for name, service in result["services"].items():
service["image"] = images[name]
service.pop("build", None)
service["labels"] = {LABEL: project}
service["restart"] = "no"
if restored and name in {"celery", "receiver", "neo-client", "neo-client-denied"}:
service["profiles"] = ["disabled-recovery"]
if restored:
service.get("depends_on", {}).pop("receiver", None)
if restored and name in {"redis", "neo-redis"}:
service["command"] = ["redis-server", "--appendonly", "no", "--save", ""]
for network in result["networks"].values():
network["labels"] = {LABEL: project}
return result
def copy_immutable(source, target, filenames):
total = 0
for name in sorted(filenames):
part = PurePosixPath(name)
if part.is_absolute() or ".." in part.parts or "\\" in name or ":" in name or part.parts[0] == "data":
raise Error("unsafe template member")
if name in {"compose.json", "fixture.json"}:
continue
data = read(stack.no_links(source / name), stack.MAX_SOURCE)
total += len(data)
if total > stack.MAX_SOURCE:
raise Error("template immutable files exceed size bound")
stack.write(target / name, data)
(target / name).chmod(stat.S_IMODE((source / name).stat().st_mode))
def validate_synthetic_template(root):
"""Do not trust a rehashed fixture ledger to authorize a real endpoint."""
try:
tree = ast.parse(read(root / "config/farm.py", 16384).decode("utf-8"))
if len(tree.body) != 1 or not isinstance(tree.body[0], ast.Assign) or len(tree.body[0].targets) != 1 or not isinstance(tree.body[0].targets[0], ast.Name) or tree.body[0].targets[0].id != "CONFIG":
raise ValueError()
config = ast.literal_eval(tree.body[0].value)
except (ValueError, TypeError, SyntaxError, UnicodeError) as error:
raise Error("farm template must contain literal synthetic configuration only") from error
expected = {"DEBUG": False, "TEAMS": {"Synthetic": "192.0.2.1"}, "FLAG_FORMAT": "[A-Z0-9]{31}=",
"SYSTEM_PROTOCOL": "ructf_http", "SYSTEM_URL": "http://receiver:8080/flags", "SYSTEM_TOKEN": "fixture-only",
"SUBMIT_FLAG_LIMIT": 10, "SUBMIT_PERIOD": 1, "FLAG_LIFETIME": 300, "SERVER_PASSWORD": "fixture-only", "TIMEZONE": "UTC"}
if config != expected:
raise Error("farm template differs from the exact synthetic competition settings")
neo = ('db_path: "/data/db.db"\nredis_url: "redis://neo-redis:6379/0"\nbase_dir: "/data/exploits"\nping_every: "5s"\nsubmit_every: "2s"\ngrpc_auth_key: "fixture-only"\nfarm:\n url: "http://front"\n password: "fixture-only"\n').encode()
if read(root / "config/neo-server.yml", 16384) != neo:
raise Error("Neo template differs from the exact synthetic server settings")
if read(root / "receiver.py", 65536) != read(Path(__file__).with_name("synthetic_receiver.py"), 65536):
raise Error("synthetic receiver implementation differs from this harness")
def prepare(args):
farm_root, farm = stack.fixture(args.stack_workspace)
validate_synthetic_template(farm_root)
pm_root, packmate = pm.fixture(args.packmate_workspace)
release_root, _ = life.release.fixture(args.release_workspace)
root = stack.no_links(args.workspace)
if root.exists() or not root.parent.is_dir() or any(root.is_relative_to(p) for p in (farm_root, pm_root, release_root)):
raise Error("recovery workspace must be new and outside all templates")
if not args.apply:
return {"status": "NOT_RUN", "action": "prepare", "effects": ["new private source/target configurations", "read-only cached image identity checks"],
"existing_template_data": "never read or copied", "not_validated": NOT_VALIDATED}
if os.name == "nt" or os.getuid() == 0:
raise Error("drill preparation requires a non-root POSIX operator")
original_farm = load(farm_root / "compose.json")
original_pm = load(pm_root / "compose.json")
farm_images = {name: image_id(svc["image"]) for name, svc in original_farm["services"].items()}
pm_images = {name: image_id(svc["image"]) for name, svc in original_pm["services"].items()}
helper_image = image_id(farm["images"]["alpine"])
root.mkdir(mode=0o700)
project = "dh-whole-" + secrets.token_hex(6)
projects = {role: project + "-" + role for role in ROLES}
for role in ROLES:
target = root / role
target.mkdir(mode=0o700)
is_farm = role.endswith("farm")
copy_immutable(farm_root if is_farm else pm_root, target, farm["files"] if is_farm else ["application.properties", "pcaps/synthetic.pcap"])
if not is_farm:
(target / "pcaps").chmod(0o755)
for directory in (("postgres", "redis", "neo-redis", "neo") if is_farm else ("postgres",)):
(target / "data" / directory).mkdir(parents=True, mode=0o700)
spec = owned_spec(original_farm if is_farm else original_pm, projects[role], farm_images if is_farm else pm_images, role.startswith("target"))
stack.write(target / "compose.json", stack.canonical(spec))
(root / "backups").mkdir(mode=0o700)
(root / "client").mkdir(mode=0o700)
identifier = "dh-life-" + secrets.token_hex(6)
flag = secrets.token_hex(16).upper()[:31] + "="
for name, data in (("neo", read(release_root / "neo")), ("client.yml", life.config(identifier)), ("synthetic.sh", life.payload(flag))):
stack.write(root / "client" / name, data)
(root / "client" / name).chmod(0o555 if name == "neo" else 0o644)
files = {p.relative_to(root).as_posix(): hash_bytes(read(p, stack.MAX_SOURCE)) for p in root.rglob("*") if p.is_file()}
state = {"schema": SCHEMA, "id": project, "projects": projects, "files": files, "helper_image": helper_image,
"packmate": packmate, "task": {"id": identifier, "flag": flag}, "approval_id": args.approval_id,
"uid": os.getuid(), "source_pins": stack.PINS, "release_sha256": life.release.SHA256}
stack.write(root / "recovery.json", stack.canonical(state))
return {"status": "PASS", "action": "prepare", "fixture": project, "existing_template_data": "never read or copied", "not_validated": NOT_VALIDATED}
def fixture(path):
root = stack.no_links(path)
state = load(root / "recovery.json")
if (state.get("schema") != SCHEMA or not re.fullmatch(r"dh-whole-[a-f0-9]{12}", state.get("id", ""))
or state.get("source_pins") != stack.PINS or state.get("release_sha256") != life.release.SHA256
or set(state.get("projects", {})) != set(ROLES) or not 1 <= len(state.get("files", {})) <= 20000):
raise Error("invalid whole-stack recovery identity")
if not re.fullmatch(r"sha256:[a-f0-9]{64}", state.get("helper_image", "")):
raise Error("cold-copy helper must use an immutable local image identity")
for role in ROLES:
if state["projects"][role] != state["id"] + "-" + role:
raise Error("invalid owned project mapping")
for name, digest in state["files"].items():
part = PurePosixPath(name)
if part.is_absolute() or ".." in part.parts or "\\" in name or ":" in name or not re.fullmatch(r"[a-f0-9]{64}", digest):
raise Error("invalid immutable recovery member")
if hash_bytes(read(stack.no_links(root / name), stack.MAX_SOURCE)) != digest:
raise Error("immutable recovery input changed")
for role in ROLES:
folder = stack.no_links(root / role / "data")
if not folder.is_dir():
raise Error("missing owned recovery data directory")
spec = load(root / role / "compose.json")
for service in spec["services"].values():
if service.get("labels") != {LABEL: state["projects"][role]} or not re.fullmatch(r"sha256:[a-f0-9]{64}", service["image"]):
raise Error("invalid immutable recovery service")
return root, state
def command(root, state, role):
if role not in ROLES:
raise Error("invalid recovery role")
return ["docker", "compose", "--project-name", state["projects"][role], "--project-directory", str(root / role),
"--file", str(root / role / "compose.json")]
def ownership(state, role):
project = state["projects"][role]
for kind, prefix in (("container", ["ps", "--all", "--quiet"]), ("network", ["network", "ls", "--quiet"])):
ids = checked(["docker"] + prefix + ["--filter", "label=com.docker.compose.project=" + project]).decode().split()
if len(ids) > 32 or any(not re.fullmatch(r"[a-f0-9]{12,64}", item) for item in ids):
raise Error("invalid owned resource listing")
for identity in ids:
field = ".Config.Labels" if kind == "container" else ".Labels"
label = checked(["docker", kind, "inspect", "--format", '{{index ' + field + ' "' + LABEL + '"}}', identity]).decode().strip()
if label != project:
raise Error("resource ownership mismatch; cleanup refused")
def compose(root, state, role, arguments, timeout=90):
ownership(state, role)
return checked(command(root, state, role) + arguments, timeout)
def psql(cmd, service, database, sql):
return checked(cmd + ["exec", "-T", service, "psql", "-X", "-v", "ON_ERROR_STOP=1", "-A", "-t", "-U", database, "-d", database, "-c", sql], 20).strip()
def ready_db(cmd, service, database):
deadline = time.monotonic() + 60
while time.monotonic() < deadline:
try:
checked(cmd + ["exec", "-T", service, "pg_isready", "-h", "127.0.0.1", "-U", database, "-d", database], 5)
return
except Error:
time.sleep(0.5)
raise Error("owned recovery database readiness timed out")
def database_summary(cmd, service, database):
names = psql(cmd, service, database, "SELECT table_name FROM information_schema.tables WHERE table_schema='public' AND table_type='BASE TABLE' ORDER BY table_name;").decode().split()
if not 1 <= len(names) <= 40 or any(not re.fullmatch(r"[a-z_][a-z0-9_]{0,60}", name) for name in names):
raise Error("unexpected synthetic database schema")
result = {}
for name in names:
# Names originate from a bounded identifier allowlist; order JSON text
# rather than physical rows, so restore layout cannot affect comparison.
data = psql(cmd, service, database, 'SELECT COALESCE(json_agg(j ORDER BY j::text),\'[]\'::json) FROM (SELECT row_to_json(t) AS j FROM "' + name + '" t) s;')
rows = json.loads(data)
if not isinstance(rows, list) or len(rows) > 10000:
raise Error("synthetic table exceeds row bound")
result[name] = {"rows": len(rows), "sha256": hash_bytes(stack.canonical(rows))}
return result
def native_dump(cmd, service, database, path):
data = checked(cmd + ["exec", "-T", service, "pg_dump", "-U", database, "-d", database, "--format=custom", "--compress=0", "--no-owner", "--no-privileges"], 60)
if not data.startswith(b"PGDMP"):
raise Error("native PostgreSQL dump signature missing")
stack.write(path, data)
return {"bytes": len(data), "sha256": hash_bytes(data)}
def restore_pg(cmd, service, database, path, expected):
if psql(cmd, service, database, "SELECT count(*) FROM information_schema.tables WHERE table_schema='public' AND table_type='BASE TABLE';") != b"0":
raise Error("restore target database is not empty")
data = read(path)
if not data.startswith(b"PGDMP") or {"bytes": len(data), "sha256": hash_bytes(data)} != expected:
raise Error("native restore input checksum mismatch")
result = subprocess.run(cmd + ["exec", "-T", service, "pg_restore", "-U", database, "-d", database, "--exit-on-error", "--single-transaction", "--no-owner", "--no-privileges"],
input=data, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=60, check=False)
if result.returncode:
raise Error("native restore failed; new target retained")
def archive_files(data):
if len(data) > MAX_BACKUP:
raise Error("cold archive exceeds byte bound")
result, seen = {}, set()
with tarfile.open(fileobj=io.BytesIO(data), mode="r:") as archive:
total = 0
for member in archive:
name = member.name[2:] if member.name.startswith("./") else member.name
if name in {"", "."} and member.isdir():
continue
path = PurePosixPath(name)
if (path.is_absolute() or ".." in path.parts or "\\" in name or ":" in name or name in seen
or not (member.isfile() or member.isdir()) or len(seen) >= 256):
raise Error("unsafe cold archive member")
seen.add(name)
if member.isdir():
continue
total += member.size
if member.size < 0 or total > MAX_BACKUP:
raise Error("expanded cold archive exceeds bound")
with archive.extractfile(member) as stream:
value = stream.read(MAX_BACKUP + 1)
if len(value) != member.size:
raise Error("truncated cold archive member")
result[name] = value
if not result:
raise Error("cold archive is empty")
return result
def cold_archive(root, state, directory):
source = stack.no_links(root / "source-farm/data" / directory)
if directory not in {"neo", "redis", "neo-redis"} or any(c in str(source) for c in (",", "\n", "\r")):
raise Error("unapproved cold source")
name = state["id"] + "-read-" + secrets.token_hex(4)
created = False
try:
checked(["docker", "create", "--name", name, "--label", LABEL + "=" + state["id"], "--network", "none", "--read-only", "--cap-drop=ALL", "--cap-add=DAC_READ_SEARCH",
"--security-opt=no-new-privileges:true", "--memory=64m", "--cpus=0.5", "--pids-limit=16", "--log-driver=none", "--pull=never",
"--mount", "type=bind,src=" + str(source) + ",dst=/data,readonly", "--entrypoint", "tar", state["helper_image"], "-C", "/data", "-cf", "-", "."])
created = True
result = checked(["docker", "start", "--attach", name])
archive_files(result)
return result
finally:
if created:
label = checked(["docker", "inspect", "--format", '{{index .Config.Labels "' + LABEL + '"}}', name]).decode().strip()
if label != state["id"]:
raise Error("cold-copy helper ownership mismatch")
checked(["docker", "rm", "--force", name])
def packmate_state(cmd, state):
port = pm.app_port(cmd)
pm.wait_ready(port, state)
services = pm.json_request(port, state, "/api/service/")
patterns = pm.json_request(port, state, "/api/pattern/")
if (not isinstance(services, list) or len(services) != 1 or services[0].get("port") != pm.pcap.SERVICE_PORT
or not isinstance(patterns, list) or len(patterns) != 1 or patterns[0].get("value") != state["marker"] or patterns[0].get("enabled") is not True):
raise Error("Packmate contains unexpected non-synthetic settings")
identifier = patterns[0]["id"]
streams = pm.json_request(port, state, "/api/stream/" + str(pm.pcap.SERVICE_PORT), "POST",
{"startingFrom": None, "pageSize": 10, "favorites": False, "pattern": {"id": identifier}})
if not isinstance(streams, list) or len(streams) != 1 or streams[0].get("protocol") != "TCP":
raise Error("Packmate synthetic stream missing or duplicated")
packets = pm.json_request(port, state, "/api/packet/" + str(streams[0]["id"]), "POST", {"startingFrom": None, "pageSize": 20})
wanted = pm.pcap.payloads(state["marker"])
if not isinstance(packets, list) or len(packets) > 20:
raise Error("unexpected synthetic packet collection")
payloads = [(base64.b64decode(packet.get("content", ""), validate=True), packet.get("incoming")) for packet in packets]
if (wanted[0], True) not in payloads or (wanted[1], False) not in payloads:
raise Error("Packmate recovered packet direction/content mismatch")
return {"services": hash_bytes(stack.canonical(services)), "patterns": hash_bytes(stack.canonical(patterns)),
"streams": hash_bytes(stack.canonical(streams)), "packets": hash_bytes(stack.canonical(packets))}
def neo_state(root, state, role, action="info"):
try:
raw = life.run_client(root / "client", state["task"], root / "client/neo", state["helper_image"], state["projects"][role] + "_fixture", action)
except life.Error as error:
raise Error(str(error)) from error
if action != "info":
return None
lines = [line.strip() for line in raw.splitlines() if b"exploit_id:" in line]
if len(lines) != 1 or state["task"]["id"].encode() not in lines[0] or b"disabled:true" not in lines[0] or b"version:1" not in lines[0]:
raise Error("Neo must contain exactly the disabled synthetic task at version 1")
return hash_bytes(lines[0])
def start_farm_apps(root, state, role, *, source):
# Pinned Neo fetches farm configuration once during server startup. Merely
# creating both containers together can leave Neo exited before the farm
# is ready; the restored path needs exactly the same ordering.
services = list(stack.LIVE_SERVICES) if source else ["farm", "front"]
compose(root, state, role, ["up", "--detach", "--no-build", "--pull", "never"] + services, 180)
stack.wait_ready(stack.farm_port(command(root, state, role)))
compose(root, state, role, ["up", "--detach", "--no-build", "--pull", "never", "--no-deps", "neo-server"], 60)
deadline = time.monotonic() + 60
while True:
try:
life.run_client(root / "client", state["task"], root / "client/neo", state["helper_image"],
state["projects"][role] + "_fixture", "info")
return
except life.Error as error:
if time.monotonic() >= deadline:
raise Error("owned Neo server readiness timed out; raw output suppressed") from error
time.sleep(1)
def farm_state(cmd, flag):
port = stack.farm_port(cmd)
stack.wait_ready(port)
status, raw = stack.request(port, "/api/get_config")
config = json.loads(raw)
if status != 200 or config.get("TEAMS") != {"Synthetic": "192.0.2.1"}:
raise Error("farm synthetic configuration mismatch")
status, raw = stack.request(port, "/api/filter_flags?flag=" + flag)
flags = json.loads(raw).get("flags", []) if status == 200 else []
if len(flags) != 1 or flags[0].get("flag") != flag or flags[0].get("status") != "ACCEPTED" or flags[0].get("sploit") != "synthetic-whole-recovery":
raise Error("farm synthetic result missing or changed")
return {"config": hash_bytes(stack.canonical(config)), "flag": hash_bytes(stack.canonical(flags))}
def run(args):
root, state = fixture(args.workspace)
if not args.apply:
return {"status": "NOT_RUN", "action": "run", "effects": ["initialize new synthetic source apps", "native PostgreSQL/Redis backups", "cold Neo copy", "new isolated restore"], "not_validated": NOT_VALIDATED}
if not args.snapshot_confirmed or os.name == "nt" or os.getuid() != state["uid"] or os.getuid() == 0:
raise Error("restore requires --snapshot-confirmed and the same non-root POSIX operator")
if (root / "attempt.json").exists():
raise Error("recovery attempt already exists; prepare a fresh workspace")
for role in ROLES:
ownership(state, role)
if checked(command(root, state, role) + ["ps", "--all", "--quiet"]).strip():
raise Error("new recovery projects must have no containers")
for folder in (root / role / "data").iterdir():
stack.no_links(folder)
if not folder.is_dir() or any(folder.iterdir()):
raise Error("all new source/target data directories must be empty")
stack.write(root / "attempt.json", stack.canonical({"approval_id": args.approval_id, "snapshot_confirmed": True}))
report = {"schema": "durkahelper.stack-recovery-result.v1", "status": "BLOCKED", "phase": "source-start", "checks": {}, "not_validated": NOT_VALIDATED,
"queue_policy": "no target receiver, Celery or Neo worker is started", "existing_template_data": "never read or changed"}
sf, sp, tf, tp = [command(root, state, role) for role in ROLES]
try:
start_farm_apps(root, state, "source-farm", source=True)
compose(root, state, "source-packmate", ["up", "--detach", "--no-build", "--pull", "never"], 180)
port = stack.farm_port(sf)
stack.wait_ready(port)
# New source state only: exactly one explicit synthetic accepted flag.
flag = state["task"]["flag"]
if stack.request(port, "/api/post_flags", "POST", [{"flag": flag, "sploit": "synthetic-whole-recovery", "team": "Synthetic"}])[0] != 200:
raise Error("synthetic farm seed failed")
deadline = time.monotonic() + 45
while True:
try:
farm_before = farm_state(sf, flag)
break
except Error:
if time.monotonic() >= deadline:
raise
time.sleep(1)
report["phase"] = "source-neo-seed"
neo_state(root, state, "source-farm", "add")
neo_before = neo_state(root, state, "source-farm")
report["phase"] = "source-packmate-seed"
packmate_smoke = pm.smoke(sp, state["packmate"])
if packmate_smoke["status"] != "PASS":
raise Error("new synthetic Packmate import did not pass")
pm_before = packmate_state(sp, state["packmate"])
report["phase"] = "quiesce-source"
compose(root, state, "source-farm", ["stop", "--timeout", "15", "celery", "receiver", "neo-server", "farm", "front"])
compose(root, state, "source-packmate", ["stop", "--timeout", "15", "packmate"])
quiesced = time.monotonic()
for service in ("redis", "neo-redis"):
if checked(sf + ["exec", "-T", service, "redis-cli", "SET", "durkahelper:recovery", state["task"]["id"]]).strip() != b"OK":
raise Error("synthetic Redis marker seed failed")
if checked(sf + ["exec", "-T", service, "redis-cli", "SAVE"]).strip() != b"OK":
raise Error("native Redis SAVE failed")
report["phase"] = "native-backups"
farm_rows = database_summary(sf, "postgres", "farm")
pm_rows = database_summary(sp, "db", "packmate")
if set(farm_rows) != {"flags"} or farm_rows["flags"]["rows"] != 1:
raise Error("new farm database is not exactly the seeded synthetic row")
dumps = {"farm": native_dump(sf, "postgres", "farm", root / "backups/farm.dump"),
"packmate": native_dump(sp, "db", "packmate", root / "backups/packmate.dump")}
if database_summary(sf, "postgres", "farm") != farm_rows or database_summary(sp, "db", "packmate") != pm_rows:
raise Error("quiesced source rows changed while backing up")
compose(root, state, "source-farm", ["stop", "--timeout", "15", "postgres", "redis", "neo-redis"])
compose(root, state, "source-packmate", ["stop", "--timeout", "15", "db"])
cold, manifests = {}, {}
for directory in ("neo", "redis", "neo-redis"):
archive = cold_archive(root, state, directory)
stack.write(root / "backups" / (directory + ".tar"), archive)
files = archive_files(archive)
manifests[directory] = {name: hash_bytes(data) for name, data in files.items()}
if directory != "neo":
if "dump.rdb" not in files or not files["dump.rdb"].startswith(b"REDIS"):
raise Error("native Redis RDB missing from cold snapshot")
files = {"dump.rdb": files["dump.rdb"]}
elif "db.db" not in files:
raise Error("Neo bbolt database missing from cold snapshot")
cold[directory] = files
backup_at = time.monotonic()
report["phase"] = "restore-empty-target"
recovery_at = time.monotonic()
for directory, files in cold.items():
for name, data in files.items():
stack.write(root / "target-farm/data" / directory / name, data)
compose(root, state, "target-farm", ["up", "--detach", "--no-build", "--pull", "never", "postgres", "redis", "neo-redis"], 120)
compose(root, state, "target-packmate", ["up", "--detach", "--no-build", "--pull", "never", "db"], 120)
ready_db(tf, "postgres", "farm")
ready_db(tp, "db", "packmate")
restore_pg(tf, "postgres", "farm", root / "backups/farm.dump", dumps["farm"])
farm_rto = time.monotonic() - recovery_at
restore_pg(tp, "db", "packmate", root / "backups/packmate.dump", dumps["packmate"])
report["checks"]["farm_rows_restored"] = database_summary(tf, "postgres", "farm") == farm_rows
report["checks"]["packmate_rows_restored"] = database_summary(tp, "db", "packmate") == pm_rows
for service in ("redis", "neo-redis"):
report["checks"][service + "_native_value_restored"] = checked(tf + ["exec", "-T", service, "redis-cli", "--raw", "GET", "durkahelper:recovery"]).strip() == state["task"]["id"].encode()
redis_rto = time.monotonic() - recovery_at
report["phase"] = "restored-app-verification"
start_farm_apps(root, state, "target-farm", source=False)
compose(root, state, "target-packmate", ["up", "--detach", "--no-build", "--pull", "never", "packmate"], 120)
report["checks"]["farm_config_and_result_restored"] = farm_state(tf, flag) == farm_before
farm_app_rto = time.monotonic() - recovery_at
report["checks"]["neo_disabled_task_restored"] = neo_state(root, state, "target-farm") == neo_before
neo_rto = time.monotonic() - recovery_at
report["checks"]["packmate_settings_packets_restored"] = packmate_state(tp, state["packmate"]) == pm_before
pm_rto = time.monotonic() - recovery_at
report["checks"]["packmate_capture_not_restarted"] = pm.json_request(pm.app_port(tp), state["packmate"], "/api/pcap/started") is False
for service in ("celery", "receiver"):
report["checks"][service + "_not_replayed"] = not checked(tf + ["ps", "--quiet", service]).strip()
for directory in cold:
current = archive_files(cold_archive(root, state, directory))
report["checks"][directory + "_source_cold_unchanged"] = {name: hash_bytes(data) for name, data in current.items()} == manifests[directory]
report["checks"]["source_databases_logically_unchanged_during_backup"] = True
report["backups"] = dumps
report["cold_manifests_sha256"] = {name: hash_bytes(stack.canonical(value)) for name, value in manifests.items()}
preservation = all(report["checks"][key] for key in ("farm_rows_restored", "packmate_rows_restored", "farm_config_and_result_restored", "neo_disabled_task_restored", "packmate_settings_packets_restored"))
report["timings"] = {"quiesced_backup_age_seconds": round(backup_at - quiesced, 3), "synthetic_records_lost": 0 if preservation else None,
"restore_seconds": {"farm_database": round(farm_rto, 3), "farm_application": round(farm_app_rto, 3),
"redis": round(redis_rto, 3), "neo_application": round(neo_rto, 3), "packmate_application": round(pm_rto, 3)}}
report["checks"]["backup_age_under_300s"] = backup_at - quiesced <= 300
report["checks"]["whole_restore_under_600s"] = pm_rto <= 600
report["status"] = "PASS" if all(report["checks"].values()) else "FAIL"
report["phase"] = "complete"
finally:
cleanup = {}
for role in reversed(ROLES):
try:
compose(root, state, role, ["--profile", "disabled-recovery", "down", "--timeout", "15"], 90)
cleanup[role] = not checked(command(root, state, role) + ["ps", "--all", "--quiet"]).strip()
except (Error, OSError, subprocess.SubprocessError):
cleanup[role] = False
report["cleanup"] = cleanup
if not all(cleanup.values()):
report["status"] = "BLOCKED"
report["rollback"] = "exact labelled source/target containers and networks removed; all private data and native/cold backups retained"
stack.write(root / "result.json", stack.canonical(report))
return report
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("action", choices=["prepare", "run"])
parser.add_argument("--workspace", required=True)
for field in ("stack-workspace", "packmate-workspace", "release-workspace", "approval-id"):
parser.add_argument("--" + field)
parser.add_argument("--apply", action="store_true")
parser.add_argument("--snapshot-confirmed", action="store_true")
args = parser.parse_args(argv)
try:
if args.apply and not (args.approval_id and re.fullmatch(r"[A-Za-z0-9_.-]{1,80}", args.approval_id)):
raise Error("mutations require --apply and a non-secret approval identifier")
if args.action == "prepare" and not all((args.stack_workspace, args.packmate_workspace, args.release_workspace)):
raise Error("prepare requires the three strict lab template workspaces")
result = prepare(args) if args.action == "prepare" else run(args)
print(json.dumps(result, sort_keys=True, indent=2))
return {"PASS": 0, "NOT_RUN": 0, "FAIL": 1, "BLOCKED": 2}[result["status"]]
except (Exception, KeyboardInterrupt) as error:
# Upstream helper exception classes differ by isolated import; never
# print their arbitrary payloads. Our own diagnostics are sanitized.
print(json.dumps({"status": "BLOCKED", "reason": str(error) if isinstance(error, Error) else "recovery stopped: " + type(error).__name__,
"raw_output": "suppressed", "retained": "private workspace, source/target data and backups; inspect local result.json"}))
return 2
if __name__ == "__main__":
sys.exit(main())
+601
View File
@@ -0,0 +1,601 @@
#!/usr/bin/env python3
"""Opt-in, isolated S4DFarm/Neo integration fixture. Never a deployment installer.
All commands are previews unless --apply and --approval-id are supplied. Sources
are exported from exact Git commits; dependencies/images must be prepared before
an offline rehearsal. No external competition endpoint is accepted by this fixture.
"""
from __future__ import annotations
import argparse
import hashlib
import io
import json
import os
from pathlib import Path, PurePosixPath
import re
import secrets
import shutil
import stat
import subprocess
import sys
import tarfile
import threading
import time
import urllib.error
import urllib.request
PINS = {
"s4dfarm": "3b8b057c95e0467c6afb3a47648e8b6befd1a815",
"neo": "2f2a4eb63f9715155844284f253ba786d330c9ae",
}
IMAGE_KEYS = {"python", "node", "nginx", "postgres", "redis", "golang", "alpine"}
IMAGE = re.compile(r"[a-z0-9][a-z0-9./:_-]*@sha256:[a-f0-9]{64}\Z")
SCHEMA = "durkahelper.integration-fixture.v1"
MAX_SOURCE = 64 * 1024 * 1024
MAX_HTTP = 1024 * 1024
LIVE_SERVICES = ["postgres", "redis", "neo-redis", "receiver", "farm", "celery", "front"]
# Official npm registry integrity for pnpm 8.15.9, converted from base64 SHA-512
# to Corepack's hexadecimal descriptor. It reads the retained v6 lockfile.
PNPM_VERSION = "8.15.9"
PNPM_SHA512 = ("499434c9d8fdd1a2794ebf4552b3b25c0a633abcee5bb15e7b5de90f32f47b513"
"aca98cd5cfd001c31f0db454bc3804edccd578501e4ca293a6816166bbd9f81")
PNPM_DESCRIPTOR = "pnpm@" + PNPM_VERSION + "+sha512." + PNPM_SHA512
class FixtureError(Exception):
"""A sanitized diagnostic; raw application output must not escape."""
def canonical(value):
return (json.dumps(value, sort_keys=True, indent=2) + "\n").encode("utf-8")
def digest(path):
return hashlib.sha256(path.read_bytes()).hexdigest()
def macos_ancestor_alias(path, item, info):
"""Recognize only root-owned stock macOS aliases, never a selected leaf."""
aliases = {"/var": "/private/var", "/tmp": "/private/tmp", "/etc": "/private/etc"}
target = aliases.get(item.as_posix())
if sys.platform != "darwin" or item == path or target is None or getattr(info, "st_uid", None) != 0:
return None
if os.readlink(item) not in (target, target.lstrip("/")):
return None
return type(path)(target) / path.relative_to(item)
def no_links(path):
"""Reject leaf/user links; canonicalize only trusted macOS system ancestors."""
path = Path(os.path.abspath(path))
for item in (path, *path.parents):
try:
info = item.lstat()
except FileNotFoundError:
continue
if stat.S_ISLNK(info.st_mode):
canonical_path = macos_ancestor_alias(path, item, info)
if canonical_path is not None:
return no_links(canonical_path)
raise FixtureError("fixture paths must not contain links or junctions")
if getattr(info, "st_file_attributes", 0) & 0x400:
raise FixtureError("fixture paths must not contain reparse points")
return path
def read_json(path):
no_links(path)
if not stat.S_ISREG(path.stat().st_mode) or path.stat().st_size > MAX_HTTP:
raise FixtureError("JSON input must be a bounded regular file")
return json.loads(path.read_text(encoding="utf-8"))
def image_map(path):
value = read_json(path)
if not isinstance(value, dict) or set(value) != IMAGE_KEYS:
raise FixtureError("image map must contain exactly: " + ", ".join(sorted(IMAGE_KEYS)))
if not all(isinstance(v, str) and IMAGE.fullmatch(v) for v in value.values()):
raise FixtureError("every base image requires an explicit sha256 repository digest")
return value
def checked(argv, cwd=None, timeout=60, capture=False, environment=None):
"""No shell; never return application stderr or configuration logs."""
try:
result = subprocess.run(argv, cwd=cwd, stdin=subprocess.DEVNULL,
stdout=subprocess.PIPE if capture else subprocess.DEVNULL,
stderr=subprocess.DEVNULL, timeout=timeout, check=False, env=environment)
except subprocess.TimeoutExpired as error:
raise FixtureError("command timed out; daemon work may remain active: " + Path(argv[0]).name) from error
except OSError as error:
raise FixtureError("command unavailable: " + Path(argv[0]).name) from error
if result.returncode:
raise FixtureError("command failed (raw output suppressed): " + Path(argv[0]).name)
if capture:
if len(result.stdout) > MAX_SOURCE:
raise FixtureError("command output exceeds fixture limit")
return result.stdout
return b""
def git_read(source, arguments):
environment = {k: v for k, v in os.environ.items() if not k.upper().startswith("GIT_")}
environment.update({"GIT_ATTR_NOSYSTEM": "1", "GIT_CONFIG_GLOBAL": os.devnull,
"GIT_CONFIG_NOSYSTEM": "1", "GIT_NO_LAZY_FETCH": "1", "GIT_NO_REPLACE_OBJECTS": "1",
"GIT_OPTIONAL_LOCKS": "0", "GIT_TERMINAL_PROMPT": "0", "GIT_LITERAL_PATHSPECS": "1"})
return checked(["git", "-c", "core.fsmonitor=false", "-c", "core.untrackedCache=false",
"-C", str(source)] + arguments, capture=True, environment=environment)
def export_source(source, target, component):
source = no_links(source)
head = git_read(source, ["rev-parse", "HEAD"]).decode().strip()
if head != PINS[component]:
raise FixtureError(component + " source HEAD does not match retained pin")
dirty = git_read(source, ["status", "--porcelain", "--untracked-files=all"])
if dirty:
raise FixtureError(component + " source checkout must be clean")
archive = git_read(source, ["archive", "--format=tar", head])
extract_source(archive, target)
def extract_source(archive, target):
"""Do not trust tar member paths or links, even in the pinned source archive."""
if len(archive) > MAX_SOURCE:
raise FixtureError("source archive exceeds fixture limit")
with tarfile.open(fileobj=io.BytesIO(archive), mode="r:") as tar:
members = tar.getmembers()
total = 0
seen = set()
for member in members:
part = PurePosixPath(member.name)
if (part.is_absolute() or not part.parts or any(p in {"..", ".git", ".ssh"} for p in part.parts)
or "\\" in member.name or ":" in member.name or member.name in seen
or not (member.isfile() or member.isdir())):
raise FixtureError("unsafe source archive member")
seen.add(member.name)
total += member.size
if total > MAX_SOURCE or len(seen) > 10000:
raise FixtureError("expanded source exceeds fixture limit")
for member in members:
path = target.joinpath(*PurePosixPath(member.name).parts)
path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
if member.isdir():
path.mkdir(exist_ok=True, mode=0o700)
else:
with tar.extractfile(member) as src, path.open("xb") as dst:
shutil.copyfileobj(src, dst)
path.chmod(0o700 if member.mode & 0o111 else 0o600)
def write(path, content):
path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
with path.open("xb") as stream:
stream.write(content.encode("utf-8") if isinstance(content, str) else content)
path.chmod(0o600)
def pin_dockerfile(text, replacements):
lines = []
for line in text.splitlines():
if line.upper().startswith("FROM "):
words = line.split()
if words[1] in replacements:
words[1] = replacements[words[1]]
elif words[1] not in {"front-base"}:
raise FixtureError("unexpected Dockerfile base image")
line = " ".join(words)
# Only build-cache mounts are removed for resource-capped legacy builds.
# They do not change application source or resolved dependency versions.
line = re.sub(r"--mount=type=cache,[^\s]+", "", line)
if "--mount=" in line:
raise FixtureError("unexpected build mount")
lines.append(line)
return "\n".join(lines) + "\n"
def compose_spec(project, images, edge=True):
def service(**values):
result = {"restart": "no", "cpus": 1.0, "mem_limit": "512m", "pids_limit": 128,
"security_opt": ["no-new-privileges:true"],
"logging": {"driver": "none"}, "networks": ["fixture"]}
result.update(values)
return result
def build(role):
return {"context": "./sources/s4dfarm/server", "dockerfile": "Dockerfile.fixture." + role}
app_env = {"POSTGRES_DSN": "host=postgres port=5432 user=farm password=fixture-only dbname=farm",
"REDIS_URL": "redis://redis:6379/0", "CELERY_BROKER_URL": "redis://redis:6379/1",
"SERVER_PASSWORD": "fixture-only", "PYTHONDONTWRITEBYTECODE": "1", "FARM_DATA": "/tmp"}
app_volumes = ["./sources/s4dfarm/server/app:/app:ro", "./config/farm.py:/app/config.py:ro"]
depends = {"postgres": {"condition": "service_healthy"}, "redis": {"condition": "service_started"},
"receiver": {"condition": "service_started"}}
neo_image = project + "-neo:fixture"
spec = {
"services": {
"postgres": service(image=images["postgres"], environment={"POSTGRES_USER": "farm",
"POSTGRES_PASSWORD": "fixture-only", "POSTGRES_DB": "farm"},
volumes=["./data/postgres:/var/lib/postgresql/data"],
healthcheck={"test": ["CMD-SHELL", "pg_isready -U farm -d farm"],
"interval": "2s", "timeout": "2s", "retries": 30}),
"redis": service(image=images["redis"], command=["redis-server", "--appendonly", "yes"],
volumes=["./data/redis:/data"]),
"neo-redis": service(image=images["redis"], command=["redis-server", "--appendonly", "yes"],
volumes=["./data/neo-redis:/data"]),
"receiver": service(image=images["python"], user="65534:65534", read_only=True,
cap_drop=["ALL"], command=["python", "-B", "/receiver.py"],
volumes=["./receiver.py:/receiver.py:ro"]),
"farm": service(build=build("server"), image=project + "-farm:fixture", environment=app_env,
volumes=app_volumes, tmpfs=["/tmp"], depends_on=depends),
"celery": service(build=build("celery"), image=project + "-celery:fixture", environment=app_env,
volumes=app_volumes, tmpfs=["/tmp"], depends_on=depends),
"front": service(build=build("front"), image=project + "-front:fixture",
ports=[{"target": 80, "published": "0", "host_ip": "127.0.0.1", "protocol": "tcp"}],
depends_on={"farm": {"condition": "service_started"}}),
"neo-server": service(image=neo_image,
build={"context": "./sources/neo", "dockerfile": "Dockerfile.fixture"},
volumes=["./config/neo-server.yml:/config.yml:ro", "./data/neo:/data"],
ports=[{"target": 5005, "published": "0", "host_ip": "127.0.0.1", "protocol": "tcp"}],
depends_on={"neo-redis": {"condition": "service_started"}}),
"neo-client": service(image=neo_image, profiles=["test"], read_only=True,
cap_drop=["ALL"], volumes=["./config/neo-client.yml:/client.yml:ro"],
entrypoint=["/neo_client"], command=["--verbose=false", "--config", "/client.yml", "info"]),
"neo-client-denied": service(image=neo_image, profiles=["test"], read_only=True,
cap_drop=["ALL"], volumes=["./config/neo-denied.yml:/client.yml:ro"],
entrypoint=["/neo_client"], command=["--verbose=false", "--config", "/client.yml", "info"]),
},
"networks": {"fixture": {"internal": True}},
}
if edge:
# Docker does not publish ports for internal-only containers. Only the
# loopback-published entrypoints join this project-owned normal bridge.
# They can initiate outbound connections; backend services cannot.
spec["networks"]["edge"] = {}
for name in ("front", "neo-server"):
spec["services"][name]["networks"] = ["fixture", "edge"]
return spec
def prepare(args):
images = image_map(Path(args.images))
workspace = no_links(args.workspace)
if workspace.exists() or not workspace.parent.is_dir():
raise FixtureError("workspace must be a new directory under an existing parent")
if not args.apply:
return {"status": "NOT_RUN", "action": "prepare", "source_pins": PINS,
"effects": ["new isolated directory", "export retained tracked sources", "generate synthetic configs"]}
workspace.mkdir(mode=0o700)
for name in PINS:
export_source(getattr(args, name + "_source"), workspace / "sources" / name, name)
project = "dh-smoke-" + secrets.token_hex(6)
replacements = {"python:3.9-slim": images["python"], "node:20-slim": images["node"],
"nginx:1.21.0-alpine": images["nginx"], "golang:1.21-alpine": images["golang"],
"alpine": images["alpine"]}
for role in ("server", "celery", "front"):
root = workspace / "sources/s4dfarm/server"
text = (root / "docker" / role / "Dockerfile").read_text(encoding="utf-8")
text = pin_dockerfile(text, replacements)
if role == "front":
text = text.replace("ENV PNPM_HOME=", 'ENV NODE_OPTIONS="--max-old-space-size=768"\n'
'ENV COREPACK_DEFAULT_TO_LATEST=0\nENV COREPACK_ENABLE_AUTO_PIN=0\nENV PNPM_HOME=')
text = text.replace("RUN corepack enable", "RUN corepack enable && corepack prepare "
+ PNPM_DESCRIPTOR + ' --activate && test "$(pnpm --version)" = "' + PNPM_VERSION + '"')
# Vite preserves mode 0600 from private exported HTML assets. Only
# final public static output must be readable by nginx's worker UID.
text = text.replace("COPY --from=front-build /app/dist /front",
"COPY --from=front-build /app/dist /front\nRUN chmod -R a+rX /front")
write(root / ("Dockerfile.fixture." + role), text)
neo_root = workspace / "sources/neo"
neo_dockerfile = pin_dockerfile((neo_root / "Dockerfile").read_text(encoding="utf-8"), replacements)
neo_dockerfile = neo_dockerfile.replace("ENV CGO_ENABLED=0", "ENV CGO_ENABLED=0\nENV GOMAXPROCS=1\nENV GOFLAGS=-p=1\nENV GOMEMLIMIT=768MiB")
# Build a matched source client for the info/authentication smoke only.
needle = "FROM " + images["alpine"]
neo_dockerfile = neo_dockerfile.replace(needle, "RUN go build -o neo_client cmd/client/main.go\n\n" + needle)
neo_dockerfile = neo_dockerfile.replace("COPY --from=build /app/neo_server /neo_server",
"COPY --from=build /app/neo_server /neo_server\nCOPY --from=build /app/neo_client /neo_client")
write(neo_root / "Dockerfile.fixture", neo_dockerfile)
farm_config = {"DEBUG": False, "TEAMS": {"Synthetic": "192.0.2.1"}, "FLAG_FORMAT": "[A-Z0-9]{31}=",
"SYSTEM_PROTOCOL": "ructf_http", "SYSTEM_URL": "http://receiver:8080/flags",
"SYSTEM_TOKEN": "fixture-only", "SUBMIT_FLAG_LIMIT": 10, "SUBMIT_PERIOD": 1,
"FLAG_LIFETIME": 300, "SERVER_PASSWORD": "fixture-only", "TIMEZONE": "UTC"}
write(workspace / "config/farm.py", "CONFIG = " + repr(farm_config) + "\n")
write(workspace / "config/neo-server.yml", 'db_path: "/data/db.db"\nredis_url: "redis://neo-redis:6379/0"\n'
'base_dir: "/data/exploits"\nping_every: "5s"\nsubmit_every: "2s"\ngrpc_auth_key: "fixture-only"\n'
'farm:\n url: "http://front"\n password: "fixture-only"\n')
client = ('host: "neo-server:5005"\ngrpc_auth_key: "fixture-only"\nexploit_dir: "/tmp/unused"\n'
'client_id: "synthetic-info-client"\n')
write(workspace / "config/neo-client.yml", client)
write(workspace / "config/neo-denied.yml", client.replace("fixture-only", "incorrect-fixture-key"))
# The cap_drop=ALL clients cannot bypass host-owned 0600 bind permissions.
# These are disposable synthetic credentials inside a mode-0700 workspace.
for name in ("neo-client.yml", "neo-denied.yml"):
(workspace / "config" / name).chmod(0o644)
write(workspace / "receiver.py", Path(__file__).with_name("synthetic_receiver.py").read_bytes())
# The unprivileged receiver must be able to read this non-secret synthetic file.
(workspace / "receiver.py").chmod(0o644)
for folder in ("postgres", "redis", "neo-redis", "neo"):
(workspace / "data" / folder).mkdir(parents=True, mode=0o700)
write(workspace / "compose.json", canonical(compose_spec(project, images)))
files = {str(p.relative_to(workspace)).replace("\\", "/"): digest(p)
for p in workspace.rglob("*") if p.is_file()}
state = {"schema": SCHEMA, "project": project, "source_pins": PINS, "images": images,
"files": files, "approval_id": args.approval_id, "build_tools": {"pnpm": PNPM_DESCRIPTOR},
"network_layout": "internal-backend-loopback-edge"}
write(workspace / "fixture.json", canonical(state))
return {"status": "PASS", "action": "prepare", "project": project, "source_pins": PINS,
"limits": "not production configuration; no external competition or team-LAN acceptance",
"network_boundary": "backends internal-only; loopback-published front/neo-server have outbound connectivity"}
def fixture(workspace, check_files=True):
workspace = no_links(workspace)
state = read_json(workspace / "fixture.json")
if (state.get("schema") != SCHEMA or state.get("source_pins") != PINS
or not re.fullmatch(r"dh-smoke-[a-f0-9]{12}", state.get("project", ""))):
raise FixtureError("invalid fixture identity")
files = state.get("files", {}) if check_files else {}
if check_files and (not files or len(files) > 10000):
raise FixtureError("invalid fixture file ledger")
for name, sha in files.items():
part = PurePosixPath(name)
if part.is_absolute() or ".." in part.parts or "\\" in name or ":" in name:
raise FixtureError("invalid fixture file path")
path = no_links(workspace.joinpath(*part.parts))
if not path.is_file() or digest(path) != sha:
raise FixtureError("fixture file changed; create a new fixture")
layout = state.get("network_layout", "legacy-internal-only")
if layout not in {"legacy-internal-only", "internal-backend-loopback-edge"}:
raise FixtureError("invalid fixture network layout")
if read_json(workspace / "compose.json") != compose_spec(state["project"], state["images"],
edge=layout == "internal-backend-loopback-edge"):
raise FixtureError("fixture Compose isolation settings changed")
if check_files:
for folder in ("postgres", "redis", "neo-redis", "neo"):
no_links(workspace / "data" / folder)
return workspace, state
def compose_command(workspace, state):
return ["docker", "compose", "--project-name", state["project"], "--project-directory", str(workspace),
"--file", str(workspace / "compose.json")]
def farm_port(command):
port = checked(command + ["port", "front", "80"], capture=True).decode().strip()
match = re.fullmatch(r"127\.0\.0\.1:([0-9]{1,5})", port)
if not match or not 1 <= int(match[1]) <= 65535:
raise FixtureError("farm must publish only one loopback ephemeral port")
return int(match[1])
class NoRedirect(urllib.request.HTTPRedirectHandler):
def redirect_request(self, req, fp, code, msg, headers, newurl):
return None
def request(port, path, method="GET", body=None, auth=True):
headers = {"Content-Type": "application/json"}
if auth:
headers["Authorization"] = "fixture-only"
req = urllib.request.Request("http://127.0.0.1:" + str(port) + path,
data=None if body is None else canonical(body), headers=headers, method=method)
opener = urllib.request.build_opener(urllib.request.ProxyHandler({}), NoRedirect())
try:
response = opener.open(req, timeout=3)
except urllib.error.HTTPError as error:
response = error
with response:
content = response.read(MAX_HTTP + 1)
if len(content) > MAX_HTTP:
raise FixtureError("fixture HTTP response exceeds limit")
return response.status, content
def wait_ready(port, timeout=60):
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
try:
code, content = request(port, "/api/get_config")
if code == 200 and json.loads(content).get("SYSTEM_PROTOCOL") == "ructf_http":
return
except (OSError, ValueError, urllib.error.URLError):
pass
time.sleep(1)
raise FixtureError("farm readiness timed out")
def stop_probe(container, project, service):
"""Stop only a generated one-shot container after verifying exact ownership."""
labels = checked(["docker", "inspect", "--format",
'{{index .Config.Labels "com.docker.compose.project"}};{{index .Config.Labels "com.docker.compose.service"}}',
container], capture=True).decode().strip()
if labels != project + ";" + service:
raise FixtureError("probe cleanup blocked: container ownership mismatch")
checked(["docker", "stop", "--time", "5", container], timeout=15)
# compose run --rm removes it on exit. Never remove an unverified name afterwards.
def capture_probe(argv, timeout=25):
"""Bound combined Neo output to 64 KiB; keep credentials only in memory."""
output, issues = bytearray(), []
done = threading.Event()
process = subprocess.Popen(argv, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
def reader():
try:
while True:
chunk = process.stdout.read(4096)
if not chunk:
break
if len(output) + len(chunk) > 65536:
issues.append("Neo probe output exceeded limit; raw output suppressed")
break
output.extend(chunk)
except OSError:
issues.append("Neo probe output read failed; raw output suppressed")
finally:
done.set()
worker = threading.Thread(target=reader, daemon=True)
worker.start()
deadline = time.monotonic() + timeout
try:
while not done.wait(0.05):
if time.monotonic() >= deadline:
raise FixtureError("Neo probe timed out; raw output suppressed")
if issues:
raise FixtureError(issues[0])
try:
code = process.wait(timeout=max(0.1, deadline - time.monotonic()))
except subprocess.TimeoutExpired as error:
raise FixtureError("Neo probe timed out; raw output suppressed") from error
return code, bytes(output)
finally:
if process.poll() is None:
process.kill()
process.wait(timeout=5)
worker.join(timeout=1)
process.stdout.close()
def neo_probe(command, service):
project = command[command.index("--project-name") + 1]
container = project + "-probe-" + secrets.token_hex(4)
try:
return capture_probe(command + ["run", "--name", container, "--rm", "--no-deps", "-T", service])
except (FixtureError, KeyboardInterrupt) as error:
condition = "Neo probe interrupted" if isinstance(error, KeyboardInterrupt) else str(error)
try:
stop_probe(container, project, service)
except (FixtureError, KeyboardInterrupt):
raise FixtureError(condition + "; exact owned probe cleanup required: " + container) from error
raise FixtureError(condition + "; owned one-shot container stopped") from error
def smoke(command):
port = farm_port(command)
wait_ready(port)
checks = {}
checks["farm_auth_rejected"] = request(port, "/api/get_config", auth=False)[0] == 403
code, content = request(port, "/api/get_config")
config = json.loads(content)
checks["farm_config"] = code == 200 and config.get("TEAMS") == {"Synthetic": "192.0.2.1"}
checks["farm_config_no_credentials"] = not any("PASSWORD" in k or "TOKEN" in k for k in config)
code, content = request(port, "/", auth=False)
checks["farm_ui"] = code == 200 and b"<html" in content.lower()
flag = secrets.token_hex(16).upper()[:31] + "="
checks["farm_ingest"] = request(port, "/api/post_flags", "POST",
[{"flag": flag, "sploit": "synthetic-smoke", "team": "Synthetic"}])[0] == 200
accepted = False
deadline = time.monotonic() + 45
while time.monotonic() < deadline:
code, content = request(port, "/api/filter_flags?flag=" + flag)
found = json.loads(content).get("flags", []) if code == 200 else []
if any(item.get("flag") == flag and item.get("status") == "ACCEPTED" for item in found):
accepted = True
break
time.sleep(1)
checks["farm_mock_submission_accepted"] = accepted
code, _ = neo_probe(command, "neo-client")
checks["neo_source_client_info"] = code == 0
# Do not classify an arbitrary Docker error/timeout as authentication rejection.
code, denied = neo_probe(command, "neo-client-denied")
checks["neo_wrong_key_rejected"] = code != 0 and b"Unauthenticated" in denied
return {"schema": "durkahelper.integration-smoke.v1", "status": "PASS" if all(checks.values()) else "FAIL",
"checks": checks, "source_pins": PINS, "scope": "isolated synthetic farm and matched-source Neo info/auth only",
"not_validated": ["release client", "exploit execution", "Packmate", "recovery", "offline build",
"Apple Silicon", "Docker Desktop", "team Ethernet access", "competition adapter"]}
def execute(args):
workspace, state = fixture(args.workspace, check_files=args.action != "down")
command = compose_command(workspace, state)
args.validated_project = state["project"]
if not args.apply:
return {"status": "NOT_RUN", "action": args.action, "project": state["project"],
"requires": "--apply --approval-id; Docker daemon; reviewed prepared fixture",
"rollback": "down stops only this generated project; data and images are retained"}
checked(command + ["config", "--quiet"])
if args.action == "build":
environment = dict(os.environ, DOCKER_BUILDKIT="0", COMPOSE_PARALLEL_LIMIT="1")
spec = compose_spec(state["project"], state["images"])
image_ids = {}
for role in ("farm", "celery", "front", "neo-server"):
service = spec["services"][role]
context = workspace / service["build"]["context"]
# Runtime Compose limits do NOT constrain builds. Use a capped legacy
# build per role, serially; fail closed if the engine no longer supports it.
checked(["docker", "build", "--force-rm", "--memory=2g", "--memory-swap=2g", "--cpu-period=100000",
"--cpu-quota=100000", "--tag", service["image"], "--file",
str(context / service["build"]["dockerfile"]), str(context)],
timeout=1800, environment=environment)
image_id = checked(["docker", "image", "inspect", "--format", "{{.Id}}", service["image"]],
capture=True).decode().strip()
if not re.fullmatch(r"sha256:[a-f0-9]{64}", image_id):
raise FixtureError("could not record built image identity")
image_ids[role] = image_id
return {"status": "PASS", "action": "build", "source_pins": PINS, "image_ids": image_ids,
"base_images": state["images"], "build_tools": state.get("build_tools", {}),
"build_limits": "serial; 2GiB memory+swap; one CPU"}
elif args.action == "up":
try:
checked(command + ["up", "--detach", "--no-build"] + LIVE_SERVICES, timeout=180)
wait_ready(farm_port(command))
checked(command + ["up", "--detach", "--no-build", "neo-server"], timeout=60)
except (FixtureError, KeyboardInterrupt):
try:
checked(command + ["down", "--timeout", "10"], timeout=60)
args.rollback_status = "generated project stopped; data retained"
except (FixtureError, KeyboardInterrupt):
args.rollback_status = "automatic stop failed; exact project cleanup required"
raise
elif args.action == "smoke":
result = smoke(command)
result["rollback"] = "down --workspace SAME_WORKSPACE --apply --approval-id ID; data retained"
return result
elif args.action == "down":
# No --volumes, --rmi, --remove-orphans or host-wide prune; retain evidence/data.
checked(command + ["down", "--timeout", "10"], timeout=60)
return {"status": "PASS", "action": args.action, "project": state["project"], "source_pins": PINS}
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("action", choices=["prepare", "build", "up", "smoke", "down"])
parser.add_argument("--workspace", required=True)
parser.add_argument("--s4dfarm-source")
parser.add_argument("--neo-source")
parser.add_argument("--images", help="JSON map of seven immutable base image repository digests")
parser.add_argument("--apply", action="store_true")
parser.add_argument("--approval-id")
args = parser.parse_args(argv)
try:
if args.apply and not (args.approval_id and re.fullmatch(r"[A-Za-z0-9_.-]{1,80}", args.approval_id)):
raise FixtureError("mutations require a non-secret approval identifier")
if args.action == "prepare" and not all([args.images, args.s4dfarm_source, args.neo_source]):
raise FixtureError("prepare requires --images, --s4dfarm-source and --neo-source")
result = prepare(args) if args.action == "prepare" else execute(args)
print(json.dumps(result, sort_keys=True, indent=2))
return 1 if result["status"] == "FAIL" else 0
except (FixtureError, OSError, ValueError, KeyError, TypeError, tarfile.TarError,
subprocess.TimeoutExpired, urllib.error.URLError, KeyboardInterrupt) as error:
message = ("fixture operation interrupted; raw output suppressed" if isinstance(error, KeyboardInterrupt)
else str(error) if isinstance(error, FixtureError) else "fixture operation failed: " + type(error).__name__)
result = {"status": "BLOCKED", "reason": message}
if getattr(args, "validated_project", None):
result.update({"project": args.validated_project,
"rollback": "down --workspace SAME_WORKSPACE --apply --approval-id ID; data retained",
"rollback_status": getattr(args, "rollback_status", "not automatically performed")})
if args.action == "build":
# Killing/interruption of the CLI does not prove daemon-side
# build cancellation. A project down only stops its services.
result.update({"rollback_status": "daemon build cancellation not confirmed; build may remain active",
"rollback": "project down does not cancel Docker builds; inspect/cancel only the verified test build; no broad prune"})
print(json.dumps(result))
return 2
if __name__ == "__main__":
sys.exit(main())
+73
View File
@@ -0,0 +1,73 @@
#!/usr/bin/env python3
"""Generate a tiny synthetic PCAP in memory; never open a capture socket."""
from __future__ import annotations
import ipaddress
import re
import struct
CLIENT_IP = "192.0.2.10"
SERVER_IP = "192.0.2.20"
SERVICE_PORT = 18080
CLIENT_PORT = 40000
EPOCH = 1767225600
def checksum(data):
data = data + (b"\x00" if len(data) % 2 else b"")
total = sum(struct.unpack("!" + "H" * (len(data) // 2), data))
while total >> 16:
total = (total & 0xFFFF) + (total >> 16)
return (~total) & 0xFFFF
def payloads(marker):
if not isinstance(marker, str) or not re.fullmatch(r"[a-f0-9]{24}", marker):
raise ValueError("synthetic marker must contain 24 lowercase hex characters")
request = ("GET /durkahelper-smoke/" + marker + " HTTP/1.1\r\n"
"Host: fixture.invalid\r\nUser-Agent: DurkaHelper-Fixture\r\n"
"Connection: close\r\n\r\n").encode("ascii")
body = ("DURKAHELPER_RESPONSE_" + marker + "\n").encode("ascii")
response = ("HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nContent-Length: " + str(len(body)) +
"\r\nConnection: close\r\n\r\n").encode("ascii") + body
return request, response
def frame(incoming, sequence, acknowledgement, flags, payload=b"", identifier=1):
source_ip, dest_ip = (CLIENT_IP, SERVER_IP) if incoming else (SERVER_IP, CLIENT_IP)
source_port, dest_port = (CLIENT_PORT, SERVICE_PORT) if incoming else (SERVICE_PORT, CLIENT_PORT)
source, dest = ipaddress.ip_address(source_ip).packed, ipaddress.ip_address(dest_ip).packed
tcp = struct.pack("!HHIIBBHHH", source_port, dest_port, sequence, acknowledgement,
5 << 4, flags, 65535, 0, 0)
pseudo = source + dest + struct.pack("!BBH", 0, 6, len(tcp) + len(payload))
tcp = tcp[:16] + struct.pack("!H", checksum(pseudo + tcp + payload)) + tcp[18:]
ip = struct.pack("!BBHHHBBH4s4s", 0x45, 0, 20 + len(tcp) + len(payload), identifier,
0x4000, 64, 6, 0, source, dest)
ip = ip[:10] + struct.pack("!H", checksum(ip)) + ip[12:]
mac_client, mac_server = bytes.fromhex("020000000010"), bytes.fromhex("020000000020")
ethernet = (mac_server + mac_client if incoming else mac_client + mac_server) + b"\x08\x00"
return ethernet + ip + tcp + payload
def make_pcap(marker):
"""One complete TCP conversation; linktype Ethernet, microsecond timestamps."""
request, response = payloads(marker)
client_end, server_end = 1001 + len(request), 5001 + len(response)
conversation = [
(True, 1000, 0, 0x02, b""),
(False, 5000, 1001, 0x12, b""),
(True, 1001, 5001, 0x10, b""),
(True, 1001, 5001, 0x18, request),
(False, 5001, client_end, 0x18, response),
(True, client_end, server_end, 0x11, b""),
(False, server_end, client_end + 1, 0x10, b""),
(False, server_end, client_end + 1, 0x11, b""),
(True, client_end + 1, server_end + 1, 0x10, b""),
]
result = bytearray(struct.pack("<IHHIIII", 0xA1B2C3D4, 2, 4, 0, 0, 65535, 1))
for number, packet in enumerate(conversation):
data = frame(*packet, identifier=number + 1)
result.extend(struct.pack("<IIII", EPOCH, number * 10000, len(data), len(data)))
result.extend(data)
return bytes(result)
+41
View File
@@ -0,0 +1,41 @@
#!/usr/bin/env python3
"""Bounded synthetic receiver for S4DFarm's pinned ructf_http adapter only."""
import json
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import re
class Receiver(BaseHTTPRequestHandler):
def log_message(self, *_args):
pass
def do_PUT(self):
if self.path != "/flags" or self.headers.get("X-Team-Token") != "fixture-only":
self.send_error(403)
return
try:
length = int(self.headers.get("Content-Length", "0"))
if not 1 <= length <= 65536:
raise ValueError()
flags = json.loads(self.rfile.read(length))
if not isinstance(flags, list) or len(flags) > 100:
raise ValueError()
if not all(isinstance(flag, str) and re.fullmatch(r"[A-Z0-9]{31}=", flag) for flag in flags):
raise ValueError()
except (ValueError, UnicodeError):
self.send_error(400)
return
body = json.dumps([{"flag": flag, "msg": "accepted synthetic fixture"} for flag in flags]).encode()
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def setup(self):
super().setup()
self.connection.settimeout(5)
if __name__ == "__main__":
ThreadingHTTPServer(("0.0.0.0", 8080), Receiver).serve_forever()
+174
View File
@@ -0,0 +1,174 @@
#!/usr/bin/env python3
"""Portable synthetic PCAP handoff and Docker review smoke; no Docker required.
An optional workflow input carries ONLY an approved, closed synthetic capture.
The transfer test uses a loopback HTTP server, not a connection to a private VM.
Packmate processing and LIVE capture are validated separately on Linux.
"""
from __future__ import annotations
import argparse
import base64
import hashlib
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import importlib.util
import json
from pathlib import Path
import subprocess
import sys
import tempfile
import threading
import urllib.request
ROOT = Path(__file__).resolve().parents[1]
MAX_CAPTURE = 32768
MARKER = b"d00dc0ded00dc0ded00dc0de"
INPUT = "synthetic_pcap_base64"
BAD_COMPOSE = "services:\n web:\n privileged: true\n volumes:\n - /var/run/docker.sock:/var/run/docker.sock\n"
GOOD_COMPOSE = "services:\n web:\n privileged: false\n read_only: true\n cap_drop: [ALL]\n"
def module(name, relative):
spec = importlib.util.spec_from_file_location(name, ROOT / relative)
value = importlib.util.module_from_spec(spec)
spec.loader.exec_module(value)
return value
def capture_from_event(path):
"""No expressions, URLs, target commands or arbitrary output paths accepted."""
if path is None:
return None
capture = module("handoff_file", "deployment/packmate_file.py")
raw = capture.kit.read(Path(path))
if len(raw) > 131072:
raise ValueError("workflow event exceeds bound")
event = json.loads(raw)
if not isinstance(event, dict):
raise ValueError("workflow event must be an object")
inputs = event.get("inputs", {})
if not isinstance(inputs, dict):
raise ValueError("invalid workflow inputs")
encoded = inputs.get(INPUT, "")
if encoded in ("", None):
return None
if not isinstance(encoded, str) or len(encoded) > 4 * ((MAX_CAPTURE + 2) // 3):
raise ValueError("synthetic capture exceeds bound")
data = base64.b64decode(encoded, validate=True)
if not 24 <= len(data) <= MAX_CAPTURE or MARKER not in data:
raise ValueError("only bounded marked synthetic captures are accepted")
return data
def transfer(data):
"""Exercise portable closed-file retrieval with exact bytes and a timeout."""
class Handler(BaseHTTPRequestHandler):
def log_message(self, *_args):
pass
def do_GET(self):
if self.path != "/synthetic.pcap":
self.send_error(404)
return
self.send_response(200)
self.send_header("Content-Type", "application/vnd.tcpdump.pcap")
self.send_header("Content-Length", str(len(data)))
self.end_headers()
self.wfile.write(data)
server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
try:
opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
with opener.open("http://127.0.0.1:" + str(server.server_port) + "/synthetic.pcap", timeout=5) as response:
result = response.read(MAX_CAPTURE + 1)
if response.status != 200 or result != data:
raise ValueError("closed-capture transfer mismatch")
return result
finally:
server.shutdown()
server.server_close()
thread.join(timeout=5)
def command(arguments, expected):
result = subprocess.run([sys.executable, "-I", "-S", *arguments], cwd=ROOT,
stdin=subprocess.DEVNULL, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, timeout=20, check=False)
if result.returncode != expected or len(result.stdout) > 1048576:
raise ValueError("tool smoke failed; raw output suppressed")
return json.loads(result.stdout)
def run(data=None):
supplied = data is not None
if data is None:
fixture = module("handoff_synthetic", "integration/synthetic_pcap.py")
data = fixture.make_pcap(MARKER.decode("ascii"))
if not isinstance(data, bytes) or not 24 <= len(data) <= MAX_CAPTURE or MARKER not in data:
raise ValueError("only a bounded marked synthetic capture is accepted")
capture = module("handoff_closed_capture", "deployment/packmate_file.py")
with tempfile.TemporaryDirectory(prefix="durka-vulnbox-") as directory:
root = Path(directory).resolve()
incoming = root / "received.pcap"
incoming.write_bytes(transfer(data))
incoming.chmod(0o600)
try:
_, _, summary = capture.inspect_file(incoming)
except capture.Error as error:
raise ValueError("invalid closed synthetic capture") from error
if summary["packet_records"] < 2 or summary["sha256"] != hashlib.sha256(data).hexdigest():
raise ValueError("capture validation mismatch")
truncated = root / "truncated.pcap"
truncated.write_bytes(data[:-1])
try:
capture.inspect_file(truncated)
except capture.Error:
pass
else:
raise ValueError("truncated capture accepted")
sources = root / "service sources"
sources.mkdir()
compose = sources / "compose.yml"
dockerfile = sources / "Dockerfile"
compose.write_text(BAD_COMPOSE, encoding="utf-8")
dockerfile.write_text("FROM example.invalid/synthetic\nUSER root\n", encoding="utf-8")
before = command([str(ROOT / "scripts/defense_scan.py"), str(sources), "--json"], 1)
expected = {"CFG-DOCKER-PRIV", "CFG-DOCKER-SOCKET", "CFG-DOCKER-ROOT"}
if not expected <= {hit["rule"] for hit in before["findings"]}:
raise ValueError("Docker misconfiguration signals missing")
before_path = root / "before.json"
before_path.write_text(json.dumps(before), encoding="utf-8")
# Fixture-only simulated MANUAL edits; the scanner never patches sources.
compose.write_text(GOOD_COMPOSE, encoding="utf-8")
dockerfile.write_text("FROM example.invalid/synthetic\nUSER 65534\n", encoding="utf-8")
after = command([str(ROOT / "scripts/defense_scan.py"), str(sources), "--json"], 0)
after_path = root / "after.json"
after_path.write_text(json.dumps(after), encoding="utf-8")
diff = command([str(ROOT / "scripts/defense_diff.py"), str(before_path), str(after_path), "--json"], 0)
if diff["exit_code"] != 0 or after["partial"]:
raise ValueError("manual patch comparison failed")
return {"status": "PASS", "capture_origin": "approved-synthetic-input" if supplied else "runner-generated-synthetic",
"packet_records": summary["packet_records"], "capture_bytes": len(data),
"checks": ["loopback_closed_file_transfer", "closed_pcap_framing", "truncated_capture_rejected",
"docker_misconfiguration_scan", "manual_fixture_patch_comparison"],
"not_tested": ["remote_VM_connectivity", "Docker_Desktop", "Packmate_import", "LIVE_capture", "team_LAN"],
"raw_capture_output": "suppressed"}
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--event", type=Path, help="GitHub workflow event with optional synthetic PCAP input")
args = parser.parse_args(argv)
try:
result = run(capture_from_event(args.event))
except (ValueError, OSError, KeyError, TypeError, subprocess.SubprocessError) as error:
print(json.dumps({"status": "FAIL", "error_type": type(error).__name__, "raw_output": "suppressed"}))
return 1
print(json.dumps(result, sort_keys=True))
return 0
if __name__ == "__main__":
raise SystemExit(main())