commit 303438d20654e78409390bb1c2fbb9cced347da8 Author: DurkaHelper contributors Date: Sat Oct 10 07:28:09 2026 +0300 init diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..3a802d2 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,3 @@ +* text=auto +*.sh text eol=lf +*.py text eol=lf diff --git a/.github/ISSUE_TEMPLATE/bug_report-RU.md b/.github/ISSUE_TEMPLATE/bug_report-RU.md new file mode 100644 index 0000000..964d6cf --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report-RU.md @@ -0,0 +1,38 @@ +--- +name: Сообщение об ошибке (RU) +about: Сообщить о воспроизводимой проблеме toolkit без приватных данных +title: "[Bug] " +labels: "" +assignees: "" +--- + + +## Проверка безопасности + +[English](bug_report.md) | Русский + +Не публикуйте credentials, приватные адреса, профили оператора, настоящие flags, traffic, raw logs или конфиденциальные исходники. При проблеме безопасности прочитайте [SECURITY.md](../../SECURITY-RU.md) до отправки публичного сообщения. + + +## Ожидаемое и фактическое поведение + +Опишите задуманный результат команды и то, что произошло вместо него. Статическая находка — сигнал для review, а не доказательство эксплуатируемости сервиса. + + +## Воспроизведение + +Приведите минимальный синтетический пример, точную очищенную команду, exit code и ограниченный очищенный текст ошибки. Укажите, был ли это preview или явно применённое действие. Не запускайте destructive tests только ради воспроизведения issue. + + +## Окружение + +- Commit/version DurkaHelper: +- OS и архитектура: +- Версии Python и ripgrep: +- Только для deployment: версии Docker/Compose и архитектура image: +- Последний известный рабочий commit, если известен: + + +## Область и восстановление + +Что было затронуто? Сработал ли документированный ограниченный rollback? Укажите, относится ли проблема к native core, synthetic fixture или сопровождаемому deployment. diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 0000000..4c36dac --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,39 @@ +--- +name: Bug report +about: Report a reproducible toolkit problem without private data +title: "[Bug] " +labels: "" +assignees: "" +--- + +English | [Русский](bug_report-RU.md) + +## Safety check + +Do not post credentials, private addresses, operator profiles, real flags, +traffic, raw logs or confidential source. For a security issue, read +[SECURITY.md](../../SECURITY.md) before submitting a public report. + +## Expected and actual behavior + +Describe the command's intended result and what happened instead. A static +finding is a review signal, not proof that a service is exploitable. + +## Reproduction + +Provide the smallest synthetic example, exact sanitized command, exit code and +bounded sanitized error. State whether this was a preview or an explicitly +applied action. Do not run destructive tests just to reproduce an issue. + +## Environment + +- DurkaHelper commit/version: +- OS and architecture: +- Python and ripgrep versions: +- For deployment only: Docker/Compose versions and image architecture: +- Last known working commit, if known: + +## Scope and recovery + +What was affected? Did the documented scoped rollback work? State whether the +problem concerns native core, a synthetic fixture or the maintained deployment. diff --git a/.github/ISSUE_TEMPLATE/false_positive-RU.md b/.github/ISSUE_TEMPLATE/false_positive-RU.md new file mode 100644 index 0000000..681b87c --- /dev/null +++ b/.github/ISSUE_TEMPLATE/false_positive-RU.md @@ -0,0 +1,32 @@ +--- +name: Ложное срабатывание или пропуск сканера (RU) +about: Улучшить детектор с помощью небольшого синтетического примера +title: "[Scanner] RULE-ID: " +labels: "" +assignees: "" +--- + + +## Правило и окружение + +[English](false_positive.md) | Русский + +- Rule ID и commit/version сканера: +- Версия language/runtime: +- Detection engine, если известен: +- Context schema и относящаяся к проблеме настройка приоритета без секретов, если есть: + + +## Минимальный синтетический пример + +Приведите код, который можно публиковать. Удалите реальные credentials, identifiers, приватные адреса и чужие исходники. Не прикладывайте полный scan report или настоящий репозиторий, если достаточно небольшого примера. + + +## Ожидаемый результат и обоснование + +Объясните, должно ли правило срабатывать на примере и почему. Добавьте противоположный безопасный или небезопасный пример и соответствующее документированное ограничение детектора. Для проблем aliasing или shadowing включите окружающие binding statements. + + +## Воспроизведение и предлагаемое покрытие + +Укажите очищенную команду и наблюдаемые rule IDs/exit code. Предложите независимые positive и negative tests; не ограничивайтесь изменением regex. Проблемы безопасности в самом toolkit описываются согласно [SECURITY.md](../../SECURITY-RU.md). diff --git a/.github/ISSUE_TEMPLATE/false_positive.md b/.github/ISSUE_TEMPLATE/false_positive.md new file mode 100644 index 0000000..dd09da5 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/false_positive.md @@ -0,0 +1,34 @@ +--- +name: Scanner false positive or false negative +about: Improve a detector using a small synthetic example +title: "[Scanner] RULE-ID: " +labels: "" +assignees: "" +--- + +English | [Русский](false_positive-RU.md) + +## Rule and environment + +- Rule ID and scanner commit/version: +- Language/runtime version: +- Detection engine, if known: +- Context schema and relevant non-secret priority setting, if any: + +## Minimal synthetic example + +Include code that may be published. Remove real credentials, identifiers, +private addresses and source owned by others. Do not attach a full scan report +or real repository when a small example will do. + +## Expected result and reasoning + +Explain whether the example should match and why. Include a contrasting safe or +unsafe case and the relevant documented detector limitation. For aliasing or +shadowing issues, include the surrounding binding statements. + +## Reproduction and proposed coverage + +Give the sanitized command and observed rule IDs/exit code. Suggest independent +positive and negative tests; do not rely only on changing a regex. Security +issues in the toolkit itself follow [SECURITY.md](../../SECURITY.md). diff --git a/.github/ISSUE_TEMPLATE/rule_request-RU.md b/.github/ISSUE_TEMPLATE/rule_request-RU.md new file mode 100644 index 0000000..6c41df4 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/rule_request-RU.md @@ -0,0 +1,29 @@ +--- +name: Запрос нового правила обнаружения (RU) +about: Предложить ограниченный сигнал для review с независимыми тестами +title: "[Rule request] " +labels: "" +assignees: "" +--- + + +## Семейство, языки и существующее покрытие + +[English](rule_request.md) | Русский + +Укажите семейство безопасности, затронутые формы языка/API и подходящий CWE, если применимо. С какими существующими правилами есть пересечение? Предпочитайте расширение поддерживаемого детектора дублированию сигнала или увеличению рекламного счётчика правил. + + +## Обнаруживаемая форма и ограничения + +Опишите точный локальный синтаксис, который можно обнаружить без исполнения кода, сетевого доступа или новых core dependencies. Отделяйте deployment risks от подтверждённых уязвимостей. Перечислите случаи, требующие ручного, межпроцедурного review или проверки бизнес-логики. + + +## Независимые примеры + +Для каждой заявленной формы приведите как минимум два независимо написанных положительных и два безопасных/context-negative синтетических примера. Где применимо, включите comments, strings, одноимённые пользовательские функции, alias rebinding и более безопасные альтернативы. + + +## Исправление и источники + +Объясните безопасное исправление с сохранением поведения service/checker и способ его проверки. Дайте ссылки на авторитетную документацию языка/API. Не отправляйте приватный игровой код, flags, secrets, logs или traffic. См. [участие в разработке](../../CONTRIBUTING-RU.md). diff --git a/.github/ISSUE_TEMPLATE/rule_request.md b/.github/ISSUE_TEMPLATE/rule_request.md new file mode 100644 index 0000000..c431a40 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/rule_request.md @@ -0,0 +1,34 @@ +--- +name: Detection rule request +about: Propose a bounded review signal with independent tests +title: "[Rule request] " +labels: "" +assignees: "" +--- + +English | [Русский](rule_request-RU.md) + +## Family, languages and existing coverage + +State the security family, affected language/API forms and relevant CWE when +applicable. Which existing rules overlap? Prefer extending a supported detector +to duplicating a signal or increasing a headline rule count. + +## Detectable shape and limits + +Describe the exact local syntax that can be detected without executing code, +network access or new core dependencies. Separate deployment risks from confirmed +vulnerabilities. List cases that require manual, interprocedural or business-logic +review. + +## Independent examples + +Provide at least two independently written positive and two safe/context-negative +synthetic examples for each claimed form. Include comments, strings, same-name +user functions, alias rebinding and safer alternatives where relevant. + +## Remediation and sources + +Explain a safe fix that preserves service/checker behavior and how to test it. +Link authoritative language/API documentation. Do not submit private competition +code, flags, secrets, logs or traffic. See [contributing](../../CONTRIBUTING.md). diff --git a/.github/PULL_REQUEST_TEMPLATE-RU.md b/.github/PULL_REQUEST_TEMPLATE-RU.md new file mode 100644 index 0000000..30cba27 --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE-RU.md @@ -0,0 +1,28 @@ + +## Результат и область изменений + +[English](PULL_REQUEST_TEMPLATE.md) | Русский + +Опишите видимый пользователю результат, сохранённую совместимость и явные ограничения. Ссылайтесь на issues, не копируя приватные данные оператора. + + +## Проверки + +- [ ] Запущены targeted tests и полный локальный suite; указаны точные результаты/skips. +- [ ] Сохранены поведение CLI `0/1/2`, read-only defaults и сопоставимость scope. +- [ ] У новых и изменённых правил есть независимые positive/negative cases и честно описанные ограничения. +- [ ] Проходят проверки счётчиков каталога, стабильных anchors, локальных ссылок, английского текста и парных русских переводов; команды и примеры остаются идентичными. +- [ ] Не добавлены исполнение цели, скрытый сетевой доступ или раскрытие секретов. +- [ ] Изменения требуют разрешения, проверяют ownership и имеют ограниченный rollback. +- [ ] Offline packaging и publication checks охватывают изменённые материалы. +- [ ] Закреплённые версии сторонних исходников и образов, происхождение и лицензии остаются явными. + + +## Платформы и границы свидетельств + +Перечислите точные commits, platforms и выполненные tests. Невыполненные сценарии Mac, Docker Desktop, физических клиентов, непрерывного захвата и offline start отметьте NOT_RUN или BLOCKED. Не переносите на них выводы из синтетических Linux-проверок. + + +## Релиз и безопасность + +Опишите требования migration/rollback, нерешённые условия релиза и действия оператора. Подтвердите отсутствие приватных endpoints, credentials, raw logs или PCAP в diff, предназначенной для публикации истории, screenshots, artifacts и обсуждении. Сообщение об уязвимости следует [SECURITY.md](../SECURITY-RU.md), а не публичной демонстрации эксплойта. diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 0000000..b272950 --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,32 @@ + +English | [Русский](PULL_REQUEST_TEMPLATE-RU.md) + +## Outcome and scope + +Describe the user-visible result, preserved compatibility and explicit limits. +Link issues without copying private operator data. + +## Verification + +- [ ] Targeted tests and the full local suite were run; exact results/skips are listed. +- [ ] CLI `0/1/2` behavior, read-only defaults and scope comparability are preserved. +- [ ] New/changed rules have independent positive/negative cases and honest limits. +- [ ] Catalog counts, stable anchors, local links, English prose and paired Russian translation checks pass; commands/examples stay identical. +- [ ] No target execution, hidden network access or expanded secrets were added. +- [ ] Mutations require approval, validate ownership and have scoped rollback. +- [ ] Offline packaging and publication checks cover the changed material. +- [ ] Third-party source/image pins, provenance and licenses remain explicit. + +## Platform and evidence boundaries + +List exact commits, platforms and tests performed. Mark unexecuted Mac, +Docker Desktop, physical-client, continuous-capture and offline-start scenarios +NOT_RUN or BLOCKED. Do not promote synthetic/Linux evidence into those claims. + +## Release and safety + +Document migration/rollback needs, unresolved release gates and operator actions. +Confirm that diff, history selected for publication, screenshots, artifacts and +discussion contain no private endpoints, credentials, raw logs or PCAP. A +vulnerability report follows [SECURITY.md](../SECURITY.md), not a public exploit +demonstration. diff --git a/.github/workflows/macos-arm64.yml b/.github/workflows/macos-arm64.yml new file mode 100644 index 0000000..5d4b20a --- /dev/null +++ b/.github/workflows/macos-arm64.yml @@ -0,0 +1,208 @@ +name: macOS ARM64 validation + +on: + workflow_dispatch: + inputs: + synthetic_pcap_base64: + description: Optional closed synthetic PCAP (base64, <=32 KiB; never real traffic) + required: false + default: '' + type: string + +permissions: + contents: read + +concurrency: + group: macos-arm64-${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + validate: + name: macOS 15 ARM64 / Python 3.10.11 + runs-on: macos-15 + timeout-minutes: 15 + defaults: + run: + shell: bash + env: + PYTHONUTF8: "1" + PYTHONDONTWRITEBYTECODE: "1" + steps: + - name: Require an ARM64 runner + run: | + set -euo pipefail + test "$(uname -m)" = "arm64" + + - name: Check out repository + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Set up Python 3.10.11 ARM64 + uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 + with: + python-version: "3.10.11" + architecture: arm64 + check-latest: false + + - name: Install pinned ripgrep ARM64 in the job directory + run: | + set -euo pipefail + rg_root="ripgrep-15.1.0-aarch64-apple-darwin" + rg_dir="$(mktemp -d "$RUNNER_TEMP/durkahelper-ripgrep.XXXXXX")" + curl --fail --silent --show-error --location --proto '=https' \ + --connect-timeout 10 --max-time 120 --retry 2 --max-filesize 5242880 \ + --output "$rg_dir/release.tar.gz" \ + "https://github.com/BurntSushi/ripgrep/releases/download/15.1.0/$rg_root.tar.gz" + python -c 'import hashlib, pathlib, sys; archive = pathlib.Path(sys.argv[1]); assert archive.stat().st_size <= 5242880; assert hashlib.sha256(archive.read_bytes()).hexdigest() == "378e973289176ca0c6054054ee7f631a065874a352bf43f0fa60ef079b6ba715", "ripgrep release checksum mismatch"' "$rg_dir/release.tar.gz" + tar -xzf "$rg_dir/release.tar.gz" -C "$rg_dir" "$rg_root/rg" + test -x "$rg_dir/$rg_root/rg" + "$rg_dir/$rg_root/rg" --version + printf '%s\n' "$rg_dir/$rg_root" >> "$GITHUB_PATH" + + - name: Verify runtime prerequisites + run: | + set -euo pipefail + python -c 'import platform, sys; assert sys.version_info[:3] == (3, 10, 11), sys.version; assert platform.machine() == "arm64", platform.machine()' + command -v rg + rg --version + python -c 'import subprocess; import re; version = subprocess.check_output(["rg", "--version"], text=True).splitlines()[0]; assert re.fullmatch(r"ripgrep 15\.1\.0(?: \(rev [0-9a-f]+\))?", version), version' + + - name: Run Defense unit tests + run: | + set -euo pipefail + python -m unittest discover -s tests -p 'test_*.py' -v 2>&1 | tee "$RUNNER_TEMP/unittest.log" + if rg -n ' \.\.\. skipped |^OK \(skipped=' "$RUNNER_TEMP/unittest.log"; then + echo "macOS acceptance forbids skipped tests" >&2 + exit 1 + fi + + - name: Smoke-test current command-line tools + run: | + set -euo pipefail + + test "$(python -X utf8 -I -S scripts/defense_scan.py --version)" = "1.8.0" + test "$(python -X utf8 -I -S scripts/defense_ops.py --version)" = "2.2.0" + # http_probe imports the adjacent, tracked common.py helper. + python -X utf8 -E -s -S scripts/http_probe.py --help > /dev/null + python -X utf8 -I -S scripts/defense_diff.py --help > /dev/null + python -X utf8 -I -S durka.py --help > /dev/null + python -X utf8 -I -S durka.py doctor --help > /dev/null + # Hosted CI has no prepared Desktop stack/config/client. BLOCKED is + # expected; only the actual native host and sanitized report are checked. + set +e + python -X utf8 -I -S durka.py doctor --json > "$RUNNER_TEMP/doctor.json" + doctor_status=$? + set -e + test "$doctor_status" -eq 2 + python -c 'import json, sys; data = json.load(open(sys.argv[1], encoding="utf-8")); checks = {r["check"]: r["status"] for r in data["checks"]}; assert data["read_only"] is True and data["competition_ready"] is False; assert checks["macOS ARM64"] == "READY" and checks["Python"] == "READY"; assert data["status"] == "BLOCKED"' "$RUNNER_TEMP/doctor.json" + python -X utf8 -I -S scripts/log_summary.py --help > /dev/null + python -X utf8 -I -S scripts/backup_config.py --help > /dev/null + python -X utf8 -I -S scripts/toolchain_bundle.py --help > /dev/null + python -X utf8 -I -S scripts/toolchain_inventory.py --help > /dev/null + python -X utf8 -I -S deployment/recovery_activation.py --help > /dev/null + python -X utf8 -I -S deployment/packmate_host.py --help > /dev/null + python -X utf8 -I -S deployment/packmate_file.py --help > /dev/null + python -X utf8 -I -S deployment/toolkit.py --help > /dev/null + python -X utf8 -I -S scripts/scanner_coverage.py --check + python -X utf8 -I -S scripts/publication_check.py --allowlist config/publication-allowlist.json + + python -X utf8 -I -S scripts/defense_scan.py --list-rules > "$RUNNER_TEMP/rules.txt" + python -c 'import pathlib, sys; assert len(pathlib.Path(sys.argv[1]).read_text(encoding="utf-8").splitlines()) == 174' "$RUNNER_TEMP/rules.txt" + + python -X utf8 -I -S scripts/defense_scan.py --explain PY-EVAL > "$RUNNER_TEMP/explain.json" + python -c 'import json, sys; data = json.load(open(sys.argv[1], encoding="utf-8")); assert data["id"] == "PY-EVAL"' "$RUNNER_TEMP/explain.json" + + set +e + python -X utf8 -I -S scripts/defense_scan.py lab --context config/scanner-context.example.json --json > "$RUNNER_TEMP/scan.json" + scan_status=$? + set -e + test "$scan_status" -eq 0 || test "$scan_status" -eq 1 + python -c 'import json, sys; data = json.load(open(sys.argv[1], encoding="utf-8")); assert data["tool"] == "DurkaHelper defense_scan"; assert data["offline"] is True; assert data["partial"] is False' "$RUNNER_TEMP/scan.json" + + python -X utf8 -I -S scripts/defense_diff.py "$RUNNER_TEMP/scan.json" "$RUNNER_TEMP/scan.json" --json > "$RUNNER_TEMP/diff.json" + python -c 'import json, sys; data = json.load(open(sys.argv[1], encoding="utf-8")); assert data["tool"] == "DurkaHelper defense_diff"; assert data["exit_code"] == 0' "$RUNNER_TEMP/diff.json" + + ops_dir="$RUNNER_TEMP/defense-ops-source" + mkdir -p "$ops_dir" + python -X utf8 -I -S scripts/defense_ops.py preflight \ + --profile config/defense-profile.example.json > "$ops_dir/preflight.json" + python -X utf8 -I -S scripts/defense_ops.py snapshot \ + --profile config/defense-profile.example.json \ + --root . \ + --output "$ops_dir/snapshot.json" > "$ops_dir/snapshot-command.json" + python -X utf8 -I -S scripts/defense_ops.py compare \ + "$ops_dir/snapshot.json" "$ops_dir/snapshot.json" > "$ops_dir/comparison.json" + python -c 'import json, pathlib, sys; root = pathlib.Path(sys.argv[1]); preflight = json.loads((root / "preflight.json").read_text(encoding="utf-8")); snapshot = json.loads((root / "snapshot.json").read_text(encoding="utf-8")); comparison = json.loads((root / "comparison.json").read_text(encoding="utf-8")); assert preflight["exit_code"] == 0 and preflight["partial"] is False; assert snapshot["partial"] is False; assert comparison["exit_code"] == 0 and comparison["comparable"] is True and comparison["summary"]["drift_count"] == 0' "$ops_dir" + + - name: Exercise synthetic Vulnbox file handoff and Docker review + run: | + set -euo pipefail + # Read event JSON in Python, never interpolate input into shell code. + # No SSH, private VM connection, Docker runtime or capture privileges. + python -X utf8 -I -S integration/vulnbox_handoff.py --event "$GITHUB_EVENT_PATH" + + - name: Build and smoke-test required offline bundle + run: | + set -euo pipefail + + test -f scripts/build_offline_bundle.py + bundle="$RUNNER_TEMP/durkahelper-offline.tar.gz" + extract_dir="$RUNNER_TEMP/durkahelper-offline" + python scripts/build_offline_bundle.py --output "$bundle" + test -s "$bundle" + python scripts/build_offline_bundle.py --verify "$bundle" + + mkdir -p "$extract_dir" + tar -xzf "$bundle" -C "$extract_dir" + scanner_path="$(python -c 'import pathlib, sys; paths = list(pathlib.Path(sys.argv[1]).rglob("scripts/defense_scan.py")); assert len(paths) == 1, paths; print(paths[0])' "$extract_dir")" + bundle_root="$(python -c 'import pathlib, sys; print(pathlib.Path(sys.argv[1]).resolve().parents[1])' "$scanner_path")" + + test -f "$bundle_root/rules/defense.json" + ( + cd "$bundle_root" + test ! -e .git + python -m unittest discover -s tests -p 'test_*.py' -v 2>&1 | tee "$RUNNER_TEMP/bundle-unittest.log" + if rg -n ' \.\.\. skipped |^OK \(skipped=' "$RUNNER_TEMP/bundle-unittest.log"; then + echo "macOS offline-bundle acceptance forbids skipped tests" >&2 + exit 1 + fi + test "$(python -X utf8 -I -S scripts/defense_scan.py --version)" = "1.8.0" + test "$(python -X utf8 -I -S scripts/defense_ops.py --version)" = "2.2.0" + python -X utf8 -I -S scripts/scanner_coverage.py --check + python -X utf8 -I -S scripts/defense_scan.py --list-rules > "$RUNNER_TEMP/bundle-rules.txt" + python -c 'import pathlib, sys; assert len(pathlib.Path(sys.argv[1]).read_text(encoding="utf-8").splitlines()) == 174' "$RUNNER_TEMP/bundle-rules.txt" + + bundle_ops_dir="$RUNNER_TEMP/defense-ops-bundle" + mkdir -p "$bundle_ops_dir" + python -X utf8 -I -S scripts/defense_ops.py preflight \ + --profile config/defense-profile.example.json > "$bundle_ops_dir/preflight.json" + python -X utf8 -I -S scripts/defense_ops.py snapshot \ + --profile config/defense-profile.example.json \ + --root . \ + --output "$bundle_ops_dir/snapshot.json" > "$bundle_ops_dir/snapshot-command.json" + python -X utf8 -I -S scripts/defense_ops.py compare \ + "$bundle_ops_dir/snapshot.json" "$bundle_ops_dir/snapshot.json" > "$bundle_ops_dir/comparison.json" + python -c 'import json, pathlib, sys; root = pathlib.Path(sys.argv[1]); preflight = json.loads((root / "preflight.json").read_text(encoding="utf-8")); snapshot = json.loads((root / "snapshot.json").read_text(encoding="utf-8")); comparison = json.loads((root / "comparison.json").read_text(encoding="utf-8")); assert preflight["exit_code"] == 0 and preflight["partial"] is False; assert snapshot["partial"] is False; assert comparison["exit_code"] == 0 and comparison["comparable"] is True and comparison["summary"]["drift_count"] == 0' "$bundle_ops_dir" + ) + + - name: Record validation evidence + if: ${{ always() }} + env: + RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} + run: | + architecture="$(uname -m)" + python_version="$(python --version 2>&1 || true)" + ripgrep_version="$(rg --version 2>/dev/null | head -n 1 || true)" + { + echo '## macOS ARM64 validation evidence' + echo + echo '| Field | Value |' + echo '|---|---|' + printf '| Run | [%s](%s) |\n' "$GITHUB_RUN_ID" "$RUN_URL" + printf '| Commit | `%s` |\n' "$GITHUB_SHA" + printf '| Architecture | `%s` |\n' "$architecture" + printf '| Python | `%s` |\n' "${python_version:-unavailable}" + printf '| ripgrep | `%s` |\n' "${ripgrep_version:-unavailable}" + printf '| Runner image | `%s` / `%s` |\n' "${ImageOS:-unknown}" "${ImageVersion:-unknown}" + } >> "$GITHUB_STEP_SUMMARY" diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ae17863 --- /dev/null +++ b/.gitignore @@ -0,0 +1,18 @@ +.env +.env.* +!.env.example +.ssh/ +.venv/ +__pycache__/ +*.py[cod] +artifacts/ +.codex-remote-attachments/ +docs/validation/ +local/ +upstream/ +*.pcap +*.pcapng +*.db +*.sqlite* +*.log +.DS_Store diff --git a/CHANGELOG-RU.md b/CHANGELOG-RU.md new file mode 100644 index 0000000..8cff94d --- /dev/null +++ b/CHANGELOG-RU.md @@ -0,0 +1,25 @@ +# История изменений + +[English](CHANGELOG.md) | Русский + + + +## В разработке + +- Последовательные workflow администратора на двух языках: развёртывание, ручные патчи, исполнение Neo, отправка Farm и Packmate LIVE/FILE; единый выбор конфига и настоящие кнопки FILE UI. +- SSH-развёртывание Linux LIVE с read-only doctor и отдельным офлайн-bundle AMD64; Python на целевой машине не требуется. +- Чистые игровые данные из проверенных кешированных зависимостей без скачиваний/сборок; приватные вложения исключены из публикации исходников и core-архивов. Готовность release candidate и проверенный публичный доступ — разные условия. + +- Единая точка входа `durka.py` и один приватный конфиг для подготовки, запуска, статуса, остановки, сканирования и импорта закрытого PCAP. +- Инструкции администратора и участника объясняют связку S4DFarm, Neo, Packmate и Defense-инструментов. +- Офлайн-архивы core исключают runtime-данные и приватную конфигурацию оператора. +- Сканер 1.8.0: 174 офлайн-правила для ревью, контекст инфраструктуры и сравнимые отчёты. +- Расширены Flask config/routes/logging, Psycopg composition, PostgreSQL grants и JS driver/CORS/session; добавлено 156 независимых fixtures. Патчи остаются ручными. +- Defense operations 2.2.0: baseline/drift, health checks, восстановление в staging и аудит deployment-политик. +- Закреплённый deployment, нативные backup/recovery helpers и отдельный Linux LIVE-захват. +- Английская документация и соседние русские переводы; 294 раздела по исправлению уязвимостей. + + +## Политика релизов + +См. [версионирование](docs/development-RU.md#versioning). Core CI проверяет нативные инструменты, а не Docker Desktop, конкретный ноутбук или сеть соревнования. diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..0c2c932 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,22 @@ +# Changelog + +English | [Русский](CHANGELOG-RU.md) + +## Unreleased + +- Ordered bilingual administrator workflows for deployment, manual patching, Neo execution, Farm submission and Packmate LIVE/FILE; consistent config selection and actual FILE UI controls. +- SSH-operated Linux LIVE deployment with read-only doctor and a separate offline AMD64 image bundle; no target Python requirement. +- Clean event state from verified cached dependencies without downloads/builds; private attachments are excluded from source publication and core archives. Release-candidate readiness and verified public access are separate gates. + +- One entry point, `durka.py`, and one private config for setup, startup, status, shutdown, scanning and closed-PCAP import. +- Admin and participant guides explain how S4DFarm, Neo, Packmate and Defense tools work together. +- Offline core archives exclude runtime data and private operator configuration. +- Scanner 1.8.0: 174 offline review rules, infrastructure context and comparable reports. +- Expanded Flask config/routes/logging, Psycopg composition, PostgreSQL grants and JS driver/CORS/session boundaries; 156 additional independent fixtures. Patches remain manual. +- Defense operations 2.2.0: baseline/drift, health checks, staging recovery and deployment-policy audit. +- Pinned deployment, native backup/recovery helpers and separate Linux LIVE capture support. +- English documentation and adjacent Russian translations; 294 remediation sections. + +## Release policy + +See [versioning](docs/development.md#versioning). Core CI checks the native tools, not Docker Desktop, a particular laptop or the event network. diff --git a/CONTRIBUTING-RU.md b/CONTRIBUTING-RU.md new file mode 100644 index 0000000..827ee80 --- /dev/null +++ b/CONTRIBUTING-RU.md @@ -0,0 +1,29 @@ + +# Участие в разработке + +[English](CONTRIBUTING.md) | Русский + +Начните с [разработки и покрытия правил](docs/development-RU.md). Изменения должны улучшать качество защитных сигналов или надёжность работы оператора, не исполняя сканируемый код и не ослабляя гарантии офлайн-работы и безопасности. + +1. Создайте отдельную ветку для конкретной задачи и сохраните посторонние изменения. +2. Перед исправлением воспроизведите дефект на безвредных fixtures. +3. Сохраняйте совместимость ядра со стандартной библиотекой Python 3.10+. +4. Запустите полный набор unit tests и целевые проверки покрытия. +5. Вместе с кодом обновляйте английскую документацию, парные переводы `-RU.md` и точные ограничения детекторов; сохраняйте команды, rule IDs и anchors. +6. Проверьте [чеклист релиза и публикации](docs/release-checklist-RU.md). + +У каждой Markdown-страницы есть соседняя русская копия `-RU.md`. Английская версия остаётся основной; обе версии доступны офлайн. Сохраняйте переключатель языка, направляйте локальные ссылки перевода на русские страницы и обновляйте обе версии вместе. Команды и примеры кода должны оставаться идентичными. + +Не коммитьте реальные учётные данные, логи, захваты пакетов, профили оператора, адреса целей или пользовательские данные. Используйте минимальные синтетические примеры; никогда не указывайте действующую приватную цель в issue. + + +## Правила и примеры + +Для каждого нового или существенно изменённого правила нужны как минимум два независимо написанных положительных и два безопасных/context-negative примера. Покройте все заявленные языковые формы, комментарии и строковые примеры, aliases/shadowing и безопасные альтернативы. Строки «до/после», скопированные только из метаданных правила, не являются независимым свидетельством. + +Сохраняйте существующие rule IDs и явные anchors каталога. Изменённая семантика должна входить в scope отчёта, чтобы несовместимые сканирования нельзя было сравнить с ложным результатом «чисто». Описывайте, какие выводы правило сделать не может. + + +## Review и релизы + +Записывайте точные закреплённые версии исходников и образов, а также платформы, на которых выполнялись проверки. Не приравнивайте CI к приёмке на целевом компьютере, Docker Desktop, физических клиентах, захвату трафика или офлайн-стеку. Для чувствительных сообщений следуйте [политике безопасности](SECURITY-RU.md) и сохраняйте указание авторства upstream. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..b115002 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,26 @@ +# Contributing + +English | [Русский](CONTRIBUTING-RU.md) + +Start with [development and rule coverage](docs/development.md). Changes should improve defensive signal quality or operator reliability without executing scanned code or weakening offline/safety guarantees. + +1. Create a focused branch and preserve unrelated work. +2. Reproduce defects with inert fixtures before fixing them. +3. Keep Python 3.10+ standard-library compatibility in the core. +4. Run the full unit suite and targeted coverage checks. +5. Update English documentation, its paired `-RU.md` translations and exact detector limitations with the code. +6. Review the [release/publication checklist](docs/release-checklist.md). + +Every Markdown page has an adjacent `-RU.md` Russian translation. English remains the primary version; both are included in offline bundles. Update pairs together, keep commands, rule IDs and original section anchors unchanged, and preserve the language switch and Russian-to-Russian local links. Documentation checks verify pairs, executable examples and navigation. + +Do not commit real credentials, logs, packet captures, operator profiles, target endpoints or user data. Use minimal synthetic cases; never post a working private target in an issue. + +## Rules and examples + +Each new or materially changed rule needs at least two independently authored positives and two safe/context-negative examples. Cover every claimed language form, comments/string examples, aliases/shadowing and safe alternatives. Before/after strings copied from rule metadata alone are not independent evidence. + +Preserve existing rule IDs and explicit catalog anchors. Changed semantics must participate in report scope so incompatible scans cannot become a false-clean comparison. Describe what the rule cannot infer. + +## Review and releases + +Record exact source/image pins and executed platforms. Do not equate CI with target-machine, Docker Desktop, physical-client, capture or offline-stack acceptance. Follow the [security policy](SECURITY.md) for sensitive reports and retain upstream attribution. diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..5d74879 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 DurkaHelper contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README-RU.md b/README-RU.md new file mode 100644 index 0000000..946ff1b --- /dev/null +++ b/README-RU.md @@ -0,0 +1,100 @@ + +# DurkaHelper + +[English](README.md) | Русский + +Офлайн-инструменты Defense для Attack/Defense CTF: разбор исходников, исследование трафика, проверка патчей и запуск общих командных инструментов из одного репозитория. + + +## Что за что отвечает + +| Инструмент | Для чего нужен | +|---|---| +| **Сканер DurkaHelper** | Найти подозрительный код/конфигурацию в **локальной копии исходников** и открыть инструкцию исправления. Удалённые хосты не сканирует, патчи не применяет. | +| **Packmate** | Смотреть запросы/ответы и искать по трафику. На Docker Desktop — закрытые PCAP; LIVE — на разрешённом Linux-узле, который видит нужный трафик. | +| **S4DFarm** | Собирать флаги, показывать их статус и отправлять в систему соревнования. | +| **Neo** | Распределять командные скрипты между исполнителями и целями; передавать найденные флаги в S4DFarm. | + +Защищаемые сервисы остаются на Vulnbox. Проверенные патчи применяйте там обычным способом развёртывания сервиса. Ферма обслуживает флаги, а не распространение патчей. + + +## Быстрый старт + +Для разбора исходников достаточно Python 3.10+; устанавливать пакеты через pip не нужно: + +```bash +git clone https://github.com/Nyarlad/DurkaHelper.git +cd DurkaHelper +python3 durka.py scan /path/to/service --patches +``` + +Код завершения 1 означает находки для проверки. Начните с одного сервиса и [базы исправлений](docs/vulnerabilities/README-RU.md). Находка — повод проверить код, а не доказанная уязвимость. + +Чтобы поднять общие инструменты, запустите Docker Desktop на macOS или Docker Engine с Compose на Linux: + +```bash +python3 durka.py init +``` + +Заполните `local/durka.json`: LAN-адрес для доступа команды, адреса команд/сервисов, формат флага и настройки отправки соревнования. Пароли и ключ Neo генерируются автоматически. Файл приватный; `local/` исключён из Git. + +Для участников и native workers Neo нужен реальный Ethernet IPv4. Loopback подходит для демо на одном ноутбуке со встроенным worker. + +```bash +python3 durka.py setup +python3 durka.py up +python3 durka.py status +``` + +`setup` скачивает закреплённые исходники/образы и собирает стек; выполните его до отключения Интернета. `up` поднимает ферму, координатор Neo и Packmate. Исполнение скриптов и отправка флагов включаются отдельно, когда всё готово: + +```bash +python3 durka.py worker +python3 durka.py submit +``` + +Перед отправкой прочитайте [инструкцию администратора](docs/MACOS_FULL_DEPLOYMENT_AND_TESTING-RU.md). Поддерживаемый адаптер — `ructf_http`; для другого протокола нужен совместимый адаптер. На Apple Silicon Packmate работает через эмуляцию amd64: прогоните стек на своём ноутбуке. + + +## Во время игры + +1. Админ поднимает инструменты и передаёт LAN-адреса и учётные данные. +2. Защитники копируют исходники сервиса, сканируют их и изучают подозрительный трафик. +3. Применяют небольшой патч на Vulnbox, проверяют сервис/checker и повторяют скан. +4. Авторы скриптов тестируют работу, загружают её в Neo и смотрят флаги в S4DFarm. +5. Админ следит за доступностью, диском и backup. Для завершения — `python3 durka.py down`. + +Основные маршруты: [workflow администратора 01–05](docs/ADMIN_WORKFLOWS-RU.md), [инструкция участника](docs/participant-guide-RU.md), [памятка админа для печати](docs/TEAM_LAN_ADMIN_CHEATSHEET-RU.md). Справочники: [индекс документации](docs/README-RU.md). + + +## Найти, исправить и проверить + +**294 раздела, 174 правила сканера.** Это число рецептов проверки и сигналов, а не отдельных доказанных эксплойтов. + +| Язык / уровень | Разделов | +|---|---:| +| [Python](docs/vulnerabilities/python-RU.md) | 40 | +| [JavaScript / TypeScript](docs/vulnerabilities/javascript-RU.md) | 28 | +| [PHP](docs/vulnerabilities/php-RU.md) | 23 | +| [Go](docs/vulnerabilities/go-RU.md) | 19 | +| [Java](docs/vulnerabilities/java-RU.md) | 18 | +| [C# / .NET](docs/vulnerabilities/csharp-RU.md) | 20 | +| [C / C++](docs/vulnerabilities/c-cpp-RU.md) | 28 | +| [Ruby / Rails](docs/vulnerabilities/ruby-RU.md) | 18 | +| [Rust](docs/vulnerabilities/rust-RU.md) | 18 | +| [SQL / базы данных](docs/vulnerabilities/sql-RU.md) | 18 | +| [Конфигурация / границы доверия](docs/vulnerabilities/configuration-RU.md) | 64 | + + +## Разработка + +Тесты и synthetic-стенды нужны разработчикам; перед каждым игровым действием полный suite запускать не требуется. + +```bash +python3 -m unittest discover -s tests +python3 scripts/scanner_coverage.py --check +``` + +[Вклад в проект](CONTRIBUTING-RU.md) · [Безопасность](SECURITY-RU.md) · [Изменения](CHANGELOG-RU.md) · [Возможности](docs/CAPABILITY_INVENTORY-RU.md) + +Работайте только с разрешёнными системами. Учётные данные, исходники, флаги и PCAP держите приватно. DurkaHelper распространяется по [MIT](LICENSE), внешние инструменты — по [своим лицензиям](THIRD_PARTY_NOTICES-RU.md). diff --git a/README.md b/README.md new file mode 100644 index 0000000..fcafe7a --- /dev/null +++ b/README.md @@ -0,0 +1,94 @@ +# DurkaHelper + +English | [Русский](README-RU.md) + +Offline Defense Toolkit for Attack/Defense CTF: review source, investigate traffic, verify patches and run the team's shared tools from one repository. + +## What does what + +| Tool | Use it for | +|---|---| +| **DurkaHelper scanner** | Find suspicious code/configuration in a **local source copy** and open a fix guide. It does not scan remote hosts or apply patches. | +| **Packmate** | Read requests/responses and search traffic. Closed PCAP files on Docker Desktop; LIVE capture on an approved Linux observation point. | +| **S4DFarm** | Collect flags, track their status and submit them to the competition. | +| **Neo** | Distribute team scripts across workers and targets; send discovered flags to S4DFarm. | + +Protected services stay on the Vulnbox. Apply reviewed patches there through your normal service deployment procedure. The farm handles flags, not patch distribution. + +## Quick start + +For source review, only Python 3.10+ is needed; no pip installation: + +```bash +git clone https://github.com/Nyarlad/DurkaHelper.git +cd DurkaHelper +python3 durka.py scan /path/to/service --patches +``` + +Exit 1 means findings to review. Start with one service and the [fix catalog](docs/vulnerabilities/README.md). A finding is a review signal, not proof of a vulnerability. + +To host the shared tools, start Docker Desktop on macOS or Docker Engine with Compose on Linux: + +```bash +python3 durka.py init +``` + +Edit `local/durka.json`: your LAN bind address, team/service addresses, flag format and competition submission settings. Passwords and the Neo key are generated for you. Keep this file private; `local/` is ignored by Git. + +Use an actual Ethernet IPv4 for teammate access and native Neo workers. Loopback is suitable for a laptop-only demo with the bundled worker. + +```bash +python3 durka.py setup +python3 durka.py up +python3 durka.py status +``` + +`setup` downloads pinned sources/images and builds the stack; do it before going offline. `up` starts the farm, Neo coordinator and Packmate. Enable script execution and flag submission separately when ready: + +```bash +python3 durka.py worker +python3 durka.py submit +``` + +Read the [administrator setup](docs/MACOS_FULL_DEPLOYMENT_AND_TESTING.md) before submission. The maintained farm adapter is `ructf_http`; another protocol needs a compatible adapter. Packmate uses amd64 emulation on Apple Silicon: rehearse on the actual laptop. + +## During the game + +1. Admin starts the tools and shares LAN URLs and credentials. +2. Defenders copy service source, scan it and investigate suspicious traffic. +3. Apply a small patch to the Vulnbox, check the service/checker and repeat the scan. +4. Script writers test their work, submit it to Neo and watch flags in S4DFarm. +5. Admin watches availability, disk and backups. Finish with `python3 durka.py down`. + +Main routes: [administrator workflows 01–05](docs/ADMIN_WORKFLOWS.md), [participant guide](docs/participant-guide.md), [printable admin cheat sheet](docs/TEAM_LAN_ADMIN_CHEATSHEET.md). References: [documentation index](docs/README.md). + +## Find, fix and verify + +**294 sections, 174 scanner rules.** Counts describe review recipes and signals, not distinct verified exploits. + +| Language / layer | Sections | +|---|---:| +| [Python](docs/vulnerabilities/python.md) | 40 | +| [JavaScript / TypeScript](docs/vulnerabilities/javascript.md) | 28 | +| [PHP](docs/vulnerabilities/php.md) | 23 | +| [Go](docs/vulnerabilities/go.md) | 19 | +| [Java](docs/vulnerabilities/java.md) | 18 | +| [C# / .NET](docs/vulnerabilities/csharp.md) | 20 | +| [C / C++](docs/vulnerabilities/c-cpp.md) | 28 | +| [Ruby / Rails](docs/vulnerabilities/ruby.md) | 18 | +| [Rust](docs/vulnerabilities/rust.md) | 18 | +| [SQL / databases](docs/vulnerabilities/sql.md) | 18 | +| [Configuration / trust boundaries](docs/vulnerabilities/configuration.md) | 64 | + +## Development + +Tests and synthetic fixtures are for contributors; participants need not run the full suite before each game action. + +```bash +python3 -m unittest discover -s tests +python3 scripts/scanner_coverage.py --check +``` + +[Contributing](CONTRIBUTING.md) · [Security](SECURITY.md) · [Changelog](CHANGELOG.md) · [Capabilities](docs/CAPABILITY_INVENTORY.md) + +Use authorized systems and keep credentials, source, flags and captures private. DurkaHelper is [MIT licensed](LICENSE); external tools keep their [own licenses](THIRD_PARTY_NOTICES.md). diff --git a/SECURITY-RU.md b/SECURITY-RU.md new file mode 100644 index 0000000..102bcee --- /dev/null +++ b/SECURITY-RU.md @@ -0,0 +1,24 @@ + +# Политика безопасности + +[English](SECURITY.md) | Русский + +Используйте DurkaHelper только для разрешённого защитного review и инфраструктуры соревнований. Считайте деревья исходников, конфигурацию и отчёты недоверенными и чувствительными входными данными. Ядро не исполняет сканируемые исходники, не применяет патчи автоматически и не запускает эксплуатацию уязвимостей. + + +## Как сообщить о проблеме безопасности + +**Не публикуйте** учётные данные, приватные адреса, реальные захваты трафика или неочищенный эксплойт против настоящего сервиса в публичном issue. + +Проверенный приватный канал сообщений — **условие публикации**. Прежде чем открыть репозиторий, сопровождающий должен включить и проверить GitHub private vulnerability reporting либо описать здесь другой согласованный приватный канал. Этот репозиторий не утверждает, что приватные сообщения уже включены, и не указывает непроверенный email. + +Если на странице Security в GitHub есть **Report a vulnerability**, перед отправкой убедитесь, что кнопка открывает приватную форму. Иначе запросите приватный контакт через публичный issue без содержательных подробностей; не включайте чувствительные данные до подтверждения канала. + +Укажите затронутый commit, платформу, минимальное синтетическое воспроизведение, ожидаемое и наблюдаемое поведение, а также последствия. Удалите секреты из имён файлов, вывода и вложений. + + +## Поддерживаемая граница безопасности + +Поддерживается только текущая сопровождаемая ревизия; перенос исправлений на старые закреплённые версии toolchain не обещается. У внешних интеграций сохраняются собственные upstream-политики и лицензии. Закрепление версии повышает воспроизводимость, но не обеспечивает постоянное устранение уязвимостей. + +Особенно важно сообщать об исполнении исходников, раскрытии секретов, path traversal, обходе защиты от symlink/race, небезопасном восстановлении или перезаписи, обходе сравнения scope, непреднамеренном создании Docker-ресурсов и false negatives проверки публикации. Чистый статический scan или поиск секретов не доказывает безопасность. diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..338de03 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,21 @@ +# Security policy + +English | [Русский](SECURITY-RU.md) + +Use DurkaHelper only for authorized defensive review and competition infrastructure. Treat source trees, configuration and reports as untrusted/sensitive input. The core does not execute scanned source, auto-apply patches or run exploitation probes. + +## Reporting a security issue + +Do **not** post credentials, private endpoints, live captures or an unredacted exploit against a real service in a public issue. + +A verified private reporting channel is a **publication gate**. Before making the repository public, the maintainer must enable and test GitHub private vulnerability reporting or document another approved private channel here. This repository does not assert that private reporting is currently enabled, and it provides no unverified email address. + +If GitHub's Security page offers **Report a vulnerability**, verify that it opens the private reporting flow before submitting. If it does not, request a private contact using a content-free public issue; do not include sensitive details until the channel is confirmed. + +Include the affected commit, platform, minimal synthetic reproduction, expected/observed behavior and impact. Remove secrets from filenames, output and attachments. + +## Supported security boundary + +Only the current maintained revision is supported; there is no promise of backports to old toolchain pins. External integrations keep their own upstream policies and licenses. A pin improves reproducibility, not ongoing vulnerability remediation. + +Report especially: source execution, secret disclosure, path traversal, symlink/race bypass, unsafe restore/overwrite, scope-comparison bypass, unintended Docker resources and publication-check false negatives. A clean static scan or secret scan is not a proof of safety. diff --git a/THIRD_PARTY_NOTICES-RU.md b/THIRD_PARTY_NOTICES-RU.md new file mode 100644 index 0000000..016984b --- /dev/null +++ b/THIRD_PARTY_NOTICES-RU.md @@ -0,0 +1,18 @@ + +# Уведомления о сторонних компонентах + +[English](THIRD_PARTY_NOTICES.md) | Русский + +Собственный код DurkaHelper распространяется по [лицензии MIT](LICENSE). У сторонних проектов, скопированных примеров и ссылочных материалов сохраняются собственные условия и указание авторства. + +| Компонент | Происхождение | +|---|---| +| S4DFarm | [Закреплённые исходники](https://github.com/C4T-BuT-S4D/S4DFarm/tree/3b8b057c95e0467c6afb3a47648e8b6befd1a815) | +| Neo | [Закреплённые исходники сервера](https://github.com/C4T-BuT-S4D/neo/tree/2f2a4eb63f9715155844284f253ba786d330c9ae), релиз v2.4.2, записанный в lock | +| Packmate | [Закреплённые исходники](https://gitlab.com/packmate/Packmate/-/tree/938031f1dedfbedabef5b049368ed5b6ba6a900a); overlay развёртывания не меняет upstream-код | +| Зависимости контейнеров и runtime | Точные идентификаторы в [toolchain lock](config/toolchain.lock.json) и [integration image lock](config/integration-images.lock.json) | +| Разборы A/D и документация API | Ссылки на источники и авторство сохранены в [каталоге](docs/vulnerabilities/README-RU.md) | + +Наличие checkout исходников, контейнерного образа или кешированного пакета не означает автоматического разрешения на распространение. Перед публикацией внешнего офлайн-toolchain составьте реестр лицензий, уведомлений, обязательств по предоставлению исходников и разрешений на распространение бинарников. Лицензирование и установка Docker Desktop зависят от применимых к оператору условий; DurkaHelper не распространяет Docker Desktop. + +Инструмент артефактов записывает заявленные метаданные происхождения и лицензий, но не выносит юридическое заключение. До завершения review внешние кеши и экспорты образов остаются приватными артефактами оператора. При обезличивании операторских данных не удаляйте указание авторства. diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md new file mode 100644 index 0000000..cc29ffa --- /dev/null +++ b/THIRD_PARTY_NOTICES.md @@ -0,0 +1,17 @@ +# Third-party notices + +English | [Русский](THIRD_PARTY_NOTICES-RU.md) + +DurkaHelper's own code is licensed under the [MIT License](LICENSE). Third-party projects, copied examples and references retain their own terms and attribution. + +| Component | Provenance | +|---|---| +| S4DFarm | [Pinned source](https://github.com/C4T-BuT-S4D/S4DFarm/tree/3b8b057c95e0467c6afb3a47648e8b6befd1a815) | +| Neo | [Pinned server source](https://github.com/C4T-BuT-S4D/neo/tree/2f2a4eb63f9715155844284f253ba786d330c9ae), release v2.4.2 as recorded in the lock | +| Packmate | [Pinned source](https://gitlab.com/packmate/Packmate/-/tree/938031f1dedfbedabef5b049368ed5b6ba6a900a); upstream code is not modified by the deployment overlay | +| Container/runtime dependencies | Exact identities in [toolchain lock](config/toolchain.lock.json) and [integration image lock](config/integration-images.lock.json) | +| A/D case studies and API documentation | Source links and attribution retained in the [catalog](docs/vulnerabilities/README.md) | + +A source checkout, container image or cached package is not automatically cleared for redistribution. Before publishing an offline external-toolchain bundle, inventory its licenses, notices, source-offer obligations and permission to distribute binaries. Keep Docker Desktop licensing/installation subject to the operator's applicable terms; it is not redistributed by DurkaHelper. + +The artifact tool records declared provenance/license metadata but does not make a legal determination. Until review is complete, external caches and image exports remain private operator artifacts. Do not remove attribution while anonymizing operator-specific data. diff --git a/config/backup.example.json b/config/backup.example.json new file mode 100644 index 0000000..169bb66 --- /dev/null +++ b/config/backup.example.json @@ -0,0 +1,12 @@ +{ + "files": [ + { + "path": "service.json", + "allow": [ + ["service", "name"], + ["http", "port"], + ["logging", "level"] + ] + } + ] +} diff --git a/config/defense-profile.example.json b/config/defense-profile.example.json new file mode 100644 index 0000000..e78e191 --- /dev/null +++ b/config/defense-profile.example.json @@ -0,0 +1,46 @@ +{ + "schema": "durkahelper.profile.v1", + "name": "synthetic-defense-ops", + "snapshot": { + "adapters": [ + "platform" + ], + "include": [ + "lab/fixtures/defense_ops/*.json" + ], + "exclude": [], + "max_files": 32, + "max_file_bytes": 262144, + "max_total_bytes": 1048576 + }, + "health": [ + { + "name": "synthetic-loopback-health", + "url": "http://127.0.0.1:8080/health", + "status": 200, + "contains": "ok", + "timeout": 2.0 + } + ], + "backup": { + "entries": [ + { + "path": "lab/fixtures/defense_ops", + "kind": "tree" + } + ], + "exclude": [], + "max_files": 32, + "max_file_bytes": 262144, + "max_total_bytes": 1048576 + }, + "evidence": { + "allow_extensions": [ + ".json", + ".jsonl" + ], + "max_files": 32, + "max_file_bytes": 262144, + "max_total_bytes": 1048576 + } +} diff --git a/config/durka.example.json b/config/durka.example.json new file mode 100644 index 0000000..2633380 --- /dev/null +++ b/config/durka.example.json @@ -0,0 +1,26 @@ +{ + "schema": "durkahelper.operator.v1", + "paths": {"sources": "local/sources", "workspace": "local/workspace"}, + "profile": { + "schema": "durkahelper.deployment-profile.v1", + "platform": {"os": "darwin", "architecture": "arm64", "runtime": "docker-desktop"}, + "bind_address": "127.0.0.1", + "ports": {"farm": 8080, "neo": 5005, "packmate": 65000}, + "allow_amd64_emulation": true, + "farm": { + "teams": {"Example": "192.0.2.1"}, + "flag_format": "[A-Z0-9]{31}=", + "protocol": "ructf_http", + "protocol_settings": {"SYSTEM_URL": "http://receiver.example.invalid/flags", "SYSTEM_TOKEN": "REPLACE_WITH_COMPETITION_TOKEN"}, + "submit_limit": 10, "submit_period": 2, "flag_lifetime": 300 + }, + "packmate": {"mode": "FILE", "local_ip": "192.0.2.1", "pcap_file": "capture.pcap", "interface": "", "retention_minutes": 60} + }, + "credentials": { + "farm_password": "REPLACE_GENERATED_BY_INIT", + "database_password": "REPLACE_GENERATED_BY_INIT", + "neo_key": "REPLACE_GENERATED_BY_INIT", + "packmate_user": "operator", + "packmate_password": "REPLACE_GENERATED_BY_INIT" + } +} diff --git a/config/integration-images.lock.json b/config/integration-images.lock.json new file mode 100644 index 0000000..714929e --- /dev/null +++ b/config/integration-images.lock.json @@ -0,0 +1,9 @@ +{ + "python": "python:3.9-slim@sha256:2d97f6910b16bd338d3060f261f53f144965f755599aab1acda1e13cf1731b1b", + "postgres": "postgres:14.1-alpine@sha256:578ca5c8452c08a4e0f5e65b55dce5e1812fe63c8fee40ea837641031598e51e", + "redis": "redis:7.2.0-alpine@sha256:fd5de2340bc46cbc2241975ab027797c350dec6fd86349e3ac384e3a41be6fee", + "node": "node:20-slim@sha256:2cf067cfed83d5ea958367df9f966191a942351a2df77d6f0193e162b5febfc0", + "nginx": "nginx:1.21.0-alpine@sha256:cc8c413c74aba9fef9dae7f3da736725136bad1e3f24fbc93788aea1944f51c4", + "golang": "golang:1.21-alpine@sha256:2414035b086e3c42b99654c8b26e6f5b1b1598080d65fd03c7f499552ff4dc94", + "alpine": "alpine:3.22@sha256:5291449c3df73caf6ed85e649dec1b9e818b39a5d8c871e97afc13e9cd5e8fa8" +} diff --git a/config/publication-allowlist.json b/config/publication-allowlist.json new file mode 100644 index 0000000..88059eb --- /dev/null +++ b/config/publication-allowlist.json @@ -0,0 +1,8 @@ +[ + { + "path": "tests/test_ops_deployment_audit.py", + "category": "url-credentials", + "fingerprint": "a13515591db1985e9bc17173247956f3a0d4d96d363a6ff5c232b77d4c00db50", + "reason": "Reserved example.invalid URL containing a synthetic CANARY; verifies that credential-bearing image references are rejected without echoing their value." + } +] diff --git a/config/scanner-context.example.json b/config/scanner-context.example.json new file mode 100644 index 0000000..1eaabd3 --- /dev/null +++ b/config/scanner-context.example.json @@ -0,0 +1,5 @@ +{ + "schema": "durkahelper.scanner-context.v1", + "infrastructure": ["docker-desktop", "compose", "vulnbox", "team-lan", "s4dfarm", "neo", "packmate"], + "role": "both" +} diff --git a/config/services.example.json b/config/services.example.json new file mode 100644 index 0000000..cd174be --- /dev/null +++ b/config/services.example.json @@ -0,0 +1,4 @@ +[ + {"name": "local health", "url": "http://127.0.0.1:8080/health", "status": 200, "contains": "ok"}, + {"name": "local version", "url": "http://127.0.0.1:8080/version", "status": 200, "contains": "demo"} +] diff --git a/config/toolchain.lock.json b/config/toolchain.lock.json new file mode 100644 index 0000000..375588f --- /dev/null +++ b/config/toolchain.lock.json @@ -0,0 +1,483 @@ +{ + "schema": "durkahelper.toolchain-lock.v1", + "reviewed_on": "2026-10-09", + "ci_target": { + "architecture": "arm64", + "evidence": [ + ".github/workflows/macos-arm64.yml", + "https://github.com/actions/python-versions/releases/tag/3.10.11-11114431484" + ], + "os": "macos-15", + "python": "3.10.11", + "status": "EXISTING" + }, + "components": { + "container-runtime": { + "architectures": [ + { + "arch": "arm64", + "os": "macos", + "status": "BLOCKED" + }, + { + "arch": "amd64", + "os": "linux", + "status": "EXISTING" + } + ], + "evidence": [ + "https://github.com/C4T-BuT-S4D/S4DFarm/blob/3b8b057c95e0467c6afb3a47648e8b6befd1a815/compose.yml", + "https://github.com/C4T-BuT-S4D/neo/blob/2f2a4eb63f9715155844284f253ba786d330c9ae/compose.yml", + "https://gitlab.com/packmate/Packmate/-/blob/938031f1dedfbedabef5b049368ed5b6ba6a900a/docker-compose.yml" + ], + "reason": "Docker Desktop is the selected candidate for the target Apple Silicon Mac. Exact version, license eligibility, platform approval, image compatibility and multi-client LAN acceptance remain unverified. Its managed Linux VM does not imply Linux host-network or capture parity.", + "status": "BLOCKED", + "version": null + }, + "durkahelper": { + "architectures": [ + { + "arch": "any", + "os": "source", + "status": "EXISTING" + }, + { + "arch": "arm64", + "os": "macos", + "status": "EXISTING" + }, + { + "arch": "amd64", + "os": "linux", + "status": "EXISTING" + } + ], + "dependency_model": "python-standard-library-only", + "evidence": [ + "README.md", + ".github/workflows/macos-arm64.yml" + ], + "status": "EXISTING", + "tools": [ + { + "name": "defense_scan", + "status": "EXISTING", + "version": "1.8.0" + }, + { + "name": "defense_ops", + "status": "PARTIAL", + "version": "2.2.0" + } + ], + "version": null, + "version_status": "UNVERIFIED" + }, + "github-actions-checkout": { + "architectures": [ + { + "arch": "any", + "os": "github-hosted-runner", + "status": "EXISTING" + } + ], + "evidence": [ + "https://github.com/actions/checkout/commit/3d3c42e5aac5ba805825da76410c181273ba90b1", + "https://github.com/actions/checkout/releases/tag/v7.0.1" + ], + "source": { + "commit": "3d3c42e5aac5ba805825da76410c181273ba90b1", + "repository": "https://github.com/actions/checkout", + "tag": "v7.0.1" + }, + "status": "EXISTING", + "version": "7.0.1" + }, + "github-actions-setup-python": { + "architectures": [ + { + "arch": "any", + "os": "github-hosted-runner", + "status": "EXISTING" + } + ], + "evidence": [ + "https://github.com/actions/setup-python/commit/5fda3b95a4ea91299a34e894583c3862153e4b97", + "https://github.com/actions/setup-python/releases/tag/v7.0.0" + ], + "source": { + "commit": "5fda3b95a4ea91299a34e894583c3862153e4b97", + "repository": "https://github.com/actions/setup-python", + "tag": "v7.0.0" + }, + "status": "EXISTING", + "version": "7.0.0" + }, + "neo": { + "architectures": [ + { + "arch": "arm64", + "os": "darwin", + "status": "UNVERIFIED" + }, + { + "arch": "amd64", + "os": "darwin", + "status": "UNVERIFIED" + }, + { + "arch": "arm64", + "os": "linux", + "status": "UNVERIFIED" + }, + { + "arch": "amd64", + "os": "linux", + "status": "EXISTING" + } + ], + "evidence": [ + "https://github.com/C4T-BuT-S4D/neo/commit/2f2a4eb63f9715155844284f253ba786d330c9ae", + "https://github.com/C4T-BuT-S4D/neo/commit/4eee7b9cd6dc1773ad5a0015808072416ad08964", + "https://github.com/C4T-BuT-S4D/neo/releases/tag/v2.4.2", + "https://github.com/C4T-BuT-S4D/neo/releases/download/v2.4.2/checksums.txt" + ], + "images": { + "items": [ + { + "digest": "sha256:c20b46bba1d93b9ca6fca27bd76289697a019f7a0ed55db19a9cef523e3c1dde", + "repository": "ghcr.io/c4t-but-s4d/neo_env", + "manifest_platforms": [ + "linux/amd64" + ], + "status": "EXISTING", + "tag": "v2.4.2" + }, + { + "digest": "sha256:75deed498a6451f702d88f05495af8c7006707ac223ad4b2e7def0d947b622bc", + "repository": "ghcr.io/c4t-but-s4d/neo_env_light", + "manifest_platforms": [ + "linux/amd64", + "linux/arm64" + ], + "status": "EXISTING", + "tag": "v2.4.2" + }, + { + "digest": "sha256:4bc9f5b55fbaa89b8158aab4cf206125612a74abce86c65873bedf1f12a5ceac", + "repository": "ghcr.io/c4t-but-s4d/neo_env_sage", + "manifest_platforms": [ + "linux/amd64" + ], + "status": "EXISTING", + "tag": "v2.4.2" + }, + { + "digest": "sha256:fd5de2340bc46cbc2241975ab027797c350dec6fd86349e3ac384e3a41be6fee", + "repository": "redis", + "status": "EXISTING", + "tag": "7.2.0-alpine", + "evidence": "config/integration-images.lock.json" + }, + { + "digest": null, + "repository": "grafana/grafana-oss", + "status": "UNVERIFIED", + "tag": "10.0.3" + }, + { + "digest": null, + "repository": "victoriametrics/victoria-metrics", + "status": "UNVERIFIED", + "tag": "v1.92.1" + } + ], + "reason": "Registry descriptors resolved for neo_env, neo_env_light and neo_env_sage v2.4.2. Only light advertises linux/arm64; its Linux amd64 worker passed the harmless synthetic lifecycle. ARM64 runtime and full/Sage task environments remain unverified. Redis is pinned in the integration image lock; optional monitoring images remain unresolved and are not required by the maintained deployment.", + "status": "PARTIAL" + }, + "release": { + "assets": [ + { + "architecture": "any", + "name": "checksums.txt", + "os": "any", + "published_sha256": null, + "size": 582, + "status": "UNVERIFIED", + "url": "https://github.com/C4T-BuT-S4D/neo/releases/download/v2.4.2/checksums.txt" + }, + { + "architecture": "amd64", + "name": "neo_client_2.4.2_darwin_amd64.zip", + "os": "darwin", + "published_sha256": "340ec1366dbc0c198eb58fe4ec4fb805ee33d124aeece5e8545837f30087d600", + "size": 5569910, + "status": "EXISTING", + "url": "https://github.com/C4T-BuT-S4D/neo/releases/download/v2.4.2/neo_client_2.4.2_darwin_amd64.zip" + }, + { + "architecture": "arm64", + "name": "neo_client_2.4.2_darwin_arm64.zip", + "os": "darwin", + "published_sha256": "b620558b699ca0f70d33a9bef070a6870f07d666d9e60a9d308ee7b757fd424d", + "size": 5370016, + "status": "EXISTING", + "url": "https://github.com/C4T-BuT-S4D/neo/releases/download/v2.4.2/neo_client_2.4.2_darwin_arm64.zip" + }, + { + "architecture": "amd64", + "name": "neo_client_2.4.2_linux_amd64.tar.gz", + "os": "linux", + "published_sha256": "42a0affe303195693f29f1998ac13fac9238db71e7395674f5141bfc553274de", + "size": 5326241, + "status": "EXISTING", + "url": "https://github.com/C4T-BuT-S4D/neo/releases/download/v2.4.2/neo_client_2.4.2_linux_amd64.tar.gz" + }, + { + "architecture": "arm64", + "name": "neo_client_2.4.2_linux_arm64.tar.gz", + "os": "linux", + "published_sha256": "3891f91b383cd26ca0f37151565791b38771dd227daabcbb67d91a093b997691", + "size": 4916523, + "status": "EXISTING", + "url": "https://github.com/C4T-BuT-S4D/neo/releases/download/v2.4.2/neo_client_2.4.2_linux_arm64.tar.gz" + }, + { + "architecture": "unspecified", + "name": "neo_client_env_2.4.2.zip", + "os": "container-host", + "published_sha256": "30491c40d99f7e90bc1699d1bc962bda83f6c5ba6b92c5f8d82660fed5954708", + "size": 5676, + "status": "EXISTING", + "url": "https://github.com/C4T-BuT-S4D/neo/releases/download/v2.4.2/neo_client_env_2.4.2.zip" + }, + { + "architecture": "any", + "name": "neo_server_2.4.2.zip", + "os": "source", + "published_sha256": "14cfbacbfc3a4d7b4ce8462448c2036e5ca210145df437e32e34bc627580573d", + "size": 134121, + "status": "EXISTING", + "url": "https://github.com/C4T-BuT-S4D/neo/releases/download/v2.4.2/neo_server_2.4.2.zip" + } + ], + "published_at": "2023-10-23T14:19:13Z", + "status": "EXISTING", + "tag": "v2.4.2", + "tag_commit": "4eee7b9cd6dc1773ad5a0015808072416ad08964" + }, + "setup": { + "reason": "Retained-source server and published v2.4.2 Linux amd64 client passed synthetic info/auth, harmless fixed task execution, worker reconnect and retained disabled entry. New-project recovery preserved Neo bbolt/Redis state with worker stopped, and maintained deployment passed authenticated startup. Arbitrary task dependencies, TLS, real queues, ARM64 and Docker Desktop remain unverified; source and release pins intentionally differ.", + "status": "PARTIAL" + }, + "source": { + "commit": "2f2a4eb63f9715155844284f253ba786d330c9ae", + "repository": "https://github.com/C4T-BuT-S4D/neo", + "tag": null + }, + "status": "PARTIAL", + "submodules": { + "evidence": "https://api.github.com/repos/C4T-BuT-S4D/neo/git/trees/2f2a4eb63f9715155844284f253ba786d330c9ae?recursive=1", + "items": [], + "status": "EXISTING" + }, + "version": "2.4.2" + }, + "packmate": { + "architectures": [ + { + "arch": "amd64", + "os": "linux", + "status": "EXISTING" + }, + { + "arch": "arm64", + "os": "macos", + "status": "UNVERIFIED" + } + ], + "evidence": [ + "https://gitlab.com/packmate/Packmate/-/commit/938031f1dedfbedabef5b049368ed5b6ba6a900a", + "https://gitlab.com/packmate/Packmate/-/blob/938031f1dedfbedabef5b049368ed5b6ba6a900a/.gitmodules", + "https://gitlab.com/packmate/Packmate/-/blob/938031f1dedfbedabef5b049368ed5b6ba6a900a/docs/SETUP.md", + "https://gitlab.com/packmate/packmate-frontend/-/commit/8f23d97100f11cd6671bb62aca5ce9b6a898b865", + "https://gitlab.com/packmate/starter/-/commit/25a2517dceb567a1571cd3666cfaadee0b66779b" + ], + "images": { + "items": [ + { + "digest": "sha256:faa39ec74a63d84558e08ab949b7724a0a014f6629d105a5212a3afb05c7cbf7", + "repository": "registry.gitlab.com/packmate/packmate", + "manifest_platforms": [ + "linux/amd64" + ], + "status": "EXISTING", + "tag": "v4.0" + }, + { + "digest": "sha256:78a275d4c891f7b3a33d3f1a78eda9f1d744954d9e20122bfdc97cdda25cddaf", + "repository": "postgres", + "manifest_platforms": [ + "linux/amd64", + "linux/arm64/v8" + ], + "status": "EXISTING", + "tag": "15.2" + } + ], + "reason": "Exact v4.0 app and PostgreSQL15.2 registry digests resolved and pulled on Linux amd64. App is a single amd64 manifest; native ARM64 image is absent. Emulation, image-to-source provenance and real Mac runtime remain unverified.", + "status": "PARTIAL" + }, + "setup": { + "evidence": "https://gitlab.com/packmate/Packmate/-/blob/938031f1dedfbedabef5b049368ed5b6ba6a900a/docs/SETUP.md", + "reason": "Retained SETUP/API reviewed. Unchanged image passed synthetic FILE import, configuration-only failed-auth logger canary and native PostgreSQL recovery. Maintained FILE deployment passed 11 checks. Scoped Linux container-namespace LIVE passed 28 checks plus five cleanups after framing/cleanup fixes at 81e2c5064b3530c365ae001e9fe36aa797706fd0. Ordered TCP payload checks do not prove packet-spanning pattern semantics. Real observation-point permission, packet visibility, long-running loss/storage, Docker Desktop and Mac remain separate gates.", + "status": "PARTIAL" + }, + "source": { + "commit": "938031f1dedfbedabef5b049368ed5b6ba6a900a", + "repository": "https://gitlab.com/packmate/Packmate", + "tag": "v4.0" + }, + "starter": { + "commit": "25a2517dceb567a1571cd3666cfaadee0b66779b", + "repository": "https://gitlab.com/packmate/starter", + "status": "UNVERIFIED" + }, + "status": "PARTIAL", + "submodules": { + "items": [ + { + "commit": "8f23d97100f11cd6671bb62aca5ce9b6a898b865", + "path": "frontend", + "repository": "https://gitlab.com/packmate/packmate-frontend", + "status": "EXISTING" + } + ], + "status": "EXISTING" + }, + "version": "4.0", + "version_status": "EXISTING" + }, + "python": { + "architectures": [ + { + "arch": "arm64", + "asset": "python-3.10.11-darwin-arm64.tar.gz", + "os": "darwin", + "status": "UNVERIFIED" + } + ], + "asset": { + "digest": null, + "size": 40749885, + "status": "UNVERIFIED", + "url": "https://github.com/actions/python-versions/releases/download/3.10.11-11114431484/python-3.10.11-darwin-arm64.tar.gz" + }, + "evidence": [ + "https://github.com/actions/python-versions/releases/tag/3.10.11-11114431484", + ".github/workflows/macos-arm64.yml" + ], + "status": "UNVERIFIED", + "version": "3.10.11" + }, + "ripgrep": { + "architectures": [ + { + "arch": "arm64", + "os": "macos", + "status": "EXISTING" + } + ], + "evidence": [ + ".github/workflows/macos-arm64.yml", + "https://github.com/BurntSushi/ripgrep/releases/tag/15.1.0" + ], + "asset": { + "url": "https://github.com/BurntSushi/ripgrep/releases/download/15.1.0/ripgrep-15.1.0-aarch64-apple-darwin.tar.gz", + "sha256": "378e973289176ca0c6054054ee7f631a065874a352bf43f0fa60ef079b6ba715", + "status": "UNVERIFIED" + }, + "reason": "Pinned ARM64 release is checksum-checked and was executed by the current hosted macOS core workflow. The actual Mac remains a separate gate.", + "status": "EXISTING", + "version": "15.1.0" + }, + "s4dfarm": { + "architectures": [ + { + "arch": "amd64", + "os": "linux-container-host", + "status": "EXISTING" + }, + { + "arch": "arm64", + "os": "macos-container-host", + "status": "UNVERIFIED" + } + ], + "evidence": [ + "https://github.com/C4T-BuT-S4D/S4DFarm/commit/3b8b057c95e0467c6afb3a47648e8b6befd1a815", + "https://github.com/C4T-BuT-S4D/S4DFarm/blob/3b8b057c95e0467c6afb3a47648e8b6befd1a815/compose.yml", + "https://github.com/C4T-BuT-S4D/S4DFarm/blob/3b8b057c95e0467c6afb3a47648e8b6befd1a815/server/app/config.py" + ], + "images": { + "items": [ + { + "digest": "sha256:578ca5c8452c08a4e0f5e65b55dce5e1812fe63c8fee40ea837641031598e51e", + "repository": "postgres", + "status": "EXISTING", + "tag": "14.1-alpine", + "evidence": "config/integration-images.lock.json" + }, + { + "digest": "sha256:fd5de2340bc46cbc2241975ab027797c350dec6fd86349e3ac384e3a41be6fee", + "repository": "redis", + "status": "EXISTING", + "tag": "7.2.0-alpine", + "evidence": "config/integration-images.lock.json" + }, + { + "digest": null, + "repository": null, + "roles": [ + "celery", + "farm", + "front" + ], + "status": "EXISTING", + "tag": null, + "identity_kind": "local-docker-image-id", + "identity_source": "private deployment build-receipt.v2", + "reason": "No published repository digest is invented for locally built images; exact IDs belong to the private receipt/export manifest." + } + ], + "reason": "Seven base-image digests are fixed in config/integration-images.lock.json. Maintained Linux amd64 deployment built successfully and build-receipt.v2 pinned all ten service roles to local immutable IDs. Export/verify/import passed for nine unique runtime IDs without rewriting tags. This proves the declared image inventory, not layer-secret review, redistribution, ARM64 runtime or a complete disconnected cold start; source/client/license/native-installer kit remains incomplete.", + "lab_base_image_lock": "config/integration-images.lock.json", + "status": "PARTIAL", + "evidence": [ + "docs/CAPABILITY_INVENTORY.md" + ] + }, + "setup": { + "evidence": [ + "https://github.com/C4T-BuT-S4D/S4DFarm/blob/3b8b057c95e0467c6afb3a47648e8b6befd1a815/server/app/config.py", + "https://github.com/C4T-BuT-S4D/S4DFarm/tree/3b8b057c95e0467c6afb3a47648e8b6befd1a815/server/app/protocols" + ], + "reason": "The retained default protocol names an absent adapter and remains broken. The maintained deployment explicitly requires reviewed ructf_http and passed only synthetic configuration/startup; a compatible competition-specific protocol/endpoint must still be confirmed.", + "status": "BROKEN" + }, + "source": { + "commit": "3b8b057c95e0467c6afb3a47648e8b6befd1a815", + "repository": "https://github.com/C4T-BuT-S4D/S4DFarm", + "tag": null + }, + "status": "PARTIAL", + "submodules": { + "evidence": "https://api.github.com/repos/C4T-BuT-S4D/S4DFarm/git/trees/3b8b057c95e0467c6afb3a47648e8b6befd1a815?recursive=1", + "items": [], + "status": "EXISTING" + }, + "version": null, + "version_status": "UNVERIFIED" + } + } +} diff --git a/deployment/README-RU.md b/deployment/README-RU.md new file mode 100644 index 0000000..9879a14 --- /dev/null +++ b/deployment/README-RU.md @@ -0,0 +1,109 @@ + +# Deployment kit + +[English](README.md) | Русский + +Для обычной работы используйте `durka.py`. Он связывает поддерживаемый deployment S4DFarm/Neo/Packmate, генерирует приватные пароли и автоматически обрабатывает внутренние ID/checksum образов. + + +## Настроить и запустить + +```bash +python3 durka.py init +``` + +Заполните `local/durka.json`: Ethernet bind, список команд, формат флага, receiver/token и IP сервиса для Packmate. Подготовьте при доступном Интернете: + +```bash +python3 durka.py setup +python3 durka.py up +python3 durka.py status +``` + +`setup` получает закреплённые исходники/образы и собирает четыре поддерживаемых source-компонента. `up` поднимает ферму, координатор Neo и Packmate FILE UI. Отправку и исполнение Neo не включает. + +```bash +python3 durka.py worker +python3 durka.py submit +``` + +Worker включайте после подготовки доверенных скриптов/зависимостей. Отправку — после проверки адаптера/receiver соревнования. Поддерживается только `ructf_http`; это не выбор протокола для неизвестного соревнования. + + +## Изменить настройки площадки + +Если изменились LAN-адреса, команды, отправка или IP сервиса Packmate, остановите стек, отредактируйте конфиг, примените настройки и снова запустите: + +```bash +python3 durka.py down +python3 durka.py configure +python3 durka.py up +``` + +Редактируйте `local/durka.json` между первой и второй командой. Данные сохраняются, используются кешированные образы; скачивания/пересборки нет. Замена платформы или учётных данных требует отдельной подготовки. + + +## Трафик и остановка + +```bash +python3 durka.py traffic import /path/to/closed-capture.pcap +python3 durka.py down +``` + +Импорт заменяет **закрытый** PCAP, сохраняет предыдущий и перезапускает только Packmate. Зарегистрируйте сервис/шаблон и один раз нажмите жёлтую кнопку обработки со стрелкой вниз в UI. `down` сохраняет данные и образы. + +На Apple Silicon текущий Packmate работает через amd64-эмуляцию. LAN и скорость проверяются на целевой машине. Разрешённый Linux LIVE и ручной capture описаны в [трафике](../docs/traffic-capture-RU.md). Обычный Docker Desktop deployment — только FILE. + + +## Расширенные инструменты + +Они остаются для специальных операций, автоматизации и диагностики; это не дополнительные шаги знакомства с тулсетом: + +| Скрипт | Назначение | +|---|---| +| `toolkit.py` | Прямой preview/prepare/build/preflight/start/stop | +| `packmate_file.py` | Ограниченная замена PCAP с сохранением старого файла и app-only restart | +| `packmate_host.py` | Разрешённый native Linux host-interface LIVE | +| `packmate_live.py` | Разрешённый существующий Linux container-namespace LIVE | +| `recovery.py` | Native backup стека, проверка и изолированный restore БД | +| `recovery_activation.py` | Restore/check/activation нового приложения-кандидата | + +Прямые скрипты записи имеют явные `--apply`/confirmation-параметры; точные входы смотрите в help операции. Общий prune хоста не выполняется. + + + +## Backup и recovery + +Backup стека содержит секреты и native данные/состояние; храните вне Git и трансляции. Нужны окно обслуживания без параллельной записи и восстанавливаемый snapshot машины. + +```bash +python3 deployment/recovery.py backup --help +python3 deployment/recovery.py verify --help +python3 deployment/recovery.py restore-native-stage --help +``` + +Backup останавливает запись, делает PostgreSQL native dumps, Redis snapshots и копирует остановленное состояние Neo/Redis. **Исходный стек остаётся остановленным для записи**, в том числе после прерывания. Restore создаёт новое изолированное хранилище, а не переписывает source. Образы и входной PCAP сохраняйте отдельно. + + + +## Восстановление приложений + +```bash +python3 deployment/recovery_activation.py recover --help +python3 deployment/recovery_activation.py verify --help +python3 deployment/recovery_activation.py activate --help +``` + +Процедура берёт проверенные backup/stage, восстанавливает PostgreSQL и Neo в нового кандидата, проверяет вход/restart и оставляет его остановленным. **Все Redis-очереди/кеш/сессии кандидата удаляются**, чтобы не повторить старую работу; оригинальные RDB остаются в backup. Не используйте этот вариант, если эти значения должны сохраниться. + +Activation отделена от restore и ничего не запускает. После принятия поднимите только выбранного кандидата, проверьте полезные действия и включите отправку/worker отдельно. Не запускайте source и замену на одинаковых endpoint. + + + +## Linux container-namespace LIVE + +`packmate_live.py` работает с разрешённым существующим, запущенным single-bridge container namespace на native Linux amd64 Engine. У owner/network должны быть capture-label и опубликованный UI. Используется NET_RAW, а не privileged; БД доступна соседям bridge. Mirroring и общий захват хоста Vulnbox он не настраивает. + +Для разрешённого host/mirror интерфейса используйте `packmate_host.py`. [Инструкция захвата](../docs/traffic-capture-RU.md) объясняет выбор и профиль. Ни один launcher не добавляет видимость пакетов Docker Desktop. + +[Установка админа](../docs/MACOS_FULL_DEPLOYMENT_AND_TESTING-RU.md) · [Шпаргалка админа](../docs/TEAM_LAN_ADMIN_CHEATSHEET-RU.md) diff --git a/deployment/README.md b/deployment/README.md new file mode 100644 index 0000000..b15b677 --- /dev/null +++ b/deployment/README.md @@ -0,0 +1,101 @@ +# Deployment kit + +English | [Русский](README-RU.md) + +Use `durka.py` for normal operation. It connects the maintained S4DFarm/Neo/Packmate deployment, generates private credentials and handles internal image IDs/checksums automatically. + +## Configure and start + +```bash +python3 durka.py init +``` + +Edit `local/durka.json`: Ethernet bind, competition teams, flag format, receiver/token and Packmate service-side IP. Then prepare while connected: + +```bash +python3 durka.py setup +python3 durka.py up +python3 durka.py status +``` + +`setup` fetches the pinned sources/images and builds the four maintained source components. `up` starts the farm, Neo coordinator and Packmate FILE UI. It starts neither submission nor Neo execution. + +```bash +python3 durka.py worker +python3 durka.py submit +``` + +Enable the worker after preparing trusted scripts/dependencies. Enable submission after checking the competition adapter/receiver. Only `ructf_http` is maintained; this does not select the protocol for an unknown competition. + +## Change event settings + +For changed LAN addresses, team maps, submission settings or Packmate service IP, stop the stack, edit the local config, apply configuration, then start again: + +```bash +python3 durka.py down +python3 durka.py configure +python3 durka.py up +``` + +Edit `local/durka.json` between the first and second command. This preserves data and uses cached images; it does not rebuild/download. Platform or credential replacement needs separate preparation. + +## Traffic and shutdown + +```bash +python3 durka.py traffic import /path/to/closed-capture.pcap +python3 durka.py down +``` + +Import replaces a **closed** PCAP, preserves the previous file and restarts only Packmate. Register the service/pattern and click the yellow downward-arrow processing button once in its UI. `down` retains data and images. + +On Apple Silicon the current Packmate image uses amd64 emulation. Shared LAN and performance must be checked on the intended machine. For permitted Linux LIVE and manual capture, see [traffic capture](../docs/traffic-capture.md). Ordinary Docker Desktop deployment is FILE-only. + +## Advanced tools + +These remain available for dedicated operations, automation and troubleshooting; they are not extra onboarding steps: + +| Script | Purpose | +|---|---| +| `toolkit.py` | Preview/prepare/build/preflight/start/stop the maintained deployment directly | +| `packmate_file.py` | Bounded PCAP replacement, prior-file retention and app-only restart | +| `packmate_host.py` | Approved native Linux host-interface LIVE | +| `packmate_live.py` | Approved existing Linux container-namespace LIVE | +| `recovery.py` | Native stack backup, verification and isolated database restore | +| `recovery_activation.py` | New application candidate restore/check/activation | + +Direct mutating scripts have explicit `--apply`/confirmation flags; use their help for the operation's exact inputs. They never perform a host-wide prune. + + +## Backup and recovery + +Backups for this stack contain secrets and native database/state data; keep them outside Git and broadcasts. Use an exclusive maintenance window and a recoverable machine snapshot. + +```bash +python3 deployment/recovery.py backup --help +python3 deployment/recovery.py verify --help +python3 deployment/recovery.py restore-native-stage --help +``` + +Backup pauses writers, dumps PostgreSQL natively, snapshots Redis and copies stopped Neo/Redis state. **The source stays quiesced**, including after an interrupted attempt. Restore creates new isolated storage; it does not overwrite the source. Retain images and input PCAP separately. + + +## Application recovery + +```bash +python3 deployment/recovery_activation.py recover --help +python3 deployment/recovery_activation.py verify --help +python3 deployment/recovery_activation.py activate --help +``` + +Application recovery consumes the verified backup/stage, restores PostgreSQL and Neo into a new candidate, checks authenticated startup/restart and leaves it stopped. **All candidate Redis queues/cache/sessions are discarded** to avoid replay; original RDBs stay in the backup. Do not use this policy if those values must be preserved. + +Activation is separate from restore and starts no services. After acceptance, start only the chosen candidate, verify useful application scenarios and deliberately enable submission/worker. Never run the original and replacement on the same endpoints. + + +## Linux container-namespace LIVE + +`packmate_live.py` serves an approved existing, running single-bridge container namespace on native Linux amd64 Engine. The owner/network need the expected capture ownership label and UI publication. It uses NET_RAW, not privileged mode; the database is reachable by peers on that bridge. It does not configure mirroring or general Vulnbox host capture. + +Use `packmate_host.py` for an approved host/mirror interface instead. [Capture instructions](../docs/traffic-capture.md) explain the choice and exact profile. None of these launchers adds packet visibility to Docker Desktop. + +[Administrator setup](../docs/MACOS_FULL_DEPLOYMENT_AND_TESTING.md) · [Admin cheat sheet](../docs/TEAM_LAN_ADMIN_CHEATSHEET.md) diff --git a/deployment/credentials.example.json b/deployment/credentials.example.json new file mode 100644 index 0000000..bfa3012 --- /dev/null +++ b/deployment/credentials.example.json @@ -0,0 +1,7 @@ +{ + "farm_password": "REPLACE_WITH_A_UNIQUE_RANDOM_VALUE", + "database_password": "REPLACE_WITH_A_UNIQUE_RANDOM_VALUE", + "neo_key": "REPLACE_WITH_A_UNIQUE_RANDOM_VALUE", + "packmate_user": "operator", + "packmate_password": "REPLACE_WITH_A_UNIQUE_RANDOM_VALUE" +} diff --git a/deployment/doctor.py b/deployment/doctor.py new file mode 100644 index 0000000..eed4eba --- /dev/null +++ b/deployment/doctor.py @@ -0,0 +1,213 @@ +"""Read-only host checks for the first Apple Silicon deployment. + +Only local metadata and explicit read-only CLI operations are used. In +particular, this module never starts Desktop, executes Neo, or fetches images. +""" +from __future__ import annotations + +import json +import os +from pathlib import Path +import platform +import re +import shutil +import stat +import struct +import subprocess +import sys +from types import SimpleNamespace + +GIB = 1024 ** 3 + + +def query(argv, empty_ok=False): + """Caller supplies fixed read-only commands; suppress all raw diagnostics.""" + try: + result = subprocess.run(argv, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, + stderr=subprocess.PIPE, timeout=10, check=False) + if len(result.stdout) > 65536 or len(result.stderr) > 65536: + return None + if result.returncode and not (empty_ok and result.returncode == 1 and not result.stderr and not result.stdout): + return None + return result.stdout.decode('utf-8', errors='strict').strip() + except (OSError, ValueError, UnicodeError, subprocess.SubprocessError): + return None + + +def neo_arm64(path, kit): + """Inspect a regular Mach-O header, never execute a downloaded program.""" + path = kit.shared.no_links(Path(path).absolute()) + before = path.lstat() + if not stat.S_ISREG(before.st_mode) or not 32 <= before.st_size <= 64 * 1024 * 1024: + return False + descriptor = os.open(path, os.O_RDONLY | getattr(os, 'O_NOFOLLOW', 0) | getattr(os, 'O_NONBLOCK', 0)) + try: + opened = os.fstat(descriptor) + raw = os.read(descriptor, 4096) + after = os.fstat(descriptor) + current = path.lstat() + if (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): + return False + if (opened.st_dev, opened.st_ino, opened.st_size, opened.st_mtime_ns) != (current.st_dev, current.st_ino, current.st_size, current.st_mtime_ns): + return False + if (opened.st_size, opened.st_mtime_ns) != (after.st_size, after.st_mtime_ns): + return False + if os.name != 'nt' and not opened.st_mode & 0o111: + return False + if raw[:4] == b'\xcf\xfa\xed\xfe': + return struct.unpack_from('I', raw, 4)[0] + width = 20 if raw[:4] == b'\xca\xfe\xba\xbe' else 32 + if not 1 <= count <= 16 or len(raw) < 8 + width * count: + return False + for index in range(count): + position = 8 + width * index + cpu = struct.unpack_from('>I', raw, position)[0] + offset, size = struct.unpack_from('>II' if width == 20 else '>QQ', raw, position + 8) + if cpu == 0x0100000C and offset >= 8 + width * count and size >= 32 and offset + size <= opened.st_size: + os.lseek(descriptor, offset, os.SEEK_SET) + header = os.read(descriptor, 32) + return (header[:4] == b'\xcf\xfa\xed\xfe' and struct.unpack_from('= (3, 10) else 'BLOCKED', + '.'.join(map(str, sys.version_info[:3])), 'Python 3.10+ is required; installation is a separate approved step.') + git = query(['git', '--version']) if shutil.which('git') else None + git_match = re.fullmatch(r'git version (\d+)\.(\d+)\.[\w. ()-]+', git or '') + add('Git', 'READY' if git_match and tuple(map(int, git_match.groups())) >= (2, 30) else 'BLOCKED', + git if git_match else 'Git unavailable or version could not be verified.', 'Prepare Git 2.30+ before setup.') + + value, paths = None, {'workspace': operator.ROOT / 'local/workspace'} + try: + value, paths = operator.load_config(config) + cfg = operator.config_path(config) + private = os.name == 'nt' or (not cfg.stat().st_mode & 0o077 and not cfg.parent.stat().st_mode & 0o077) + expected = {'os': 'darwin', 'architecture': 'arm64', 'runtime': 'docker-desktop'} + add('Local configuration', 'READY' if private and value['profile']['platform'] == expected else 'BLOCKED', + 'Schema valid; values and credentials are not printed.', + 'Use a private config/directory and the Darwin ARM64 Docker Desktop profile; see the first-run guide.') + add('Submission safety', 'WARNING', 'Maintained adapter: ructf_http. Do not run submit during acceptance.', + 'Keep the example endpoint/token until protocol compatibility is reviewed; other protocols need separate validation.') + except (kit.Error, OSError, ValueError, TypeError, KeyError): + add('Local configuration', 'BLOCKED', 'Missing, invalid, linked or unreadable operator configuration; raw values suppressed.', + 'After approval: python3 durka.py init; edit local/durka.json using the first-run guide.') + + available = bool(shutil.which('docker')) + add('Docker CLI', 'READY' if available else 'BLOCKED', 'Available.' if available else 'Not found.', + 'Install/start Docker Desktop only after approval; doctor does not start it.') + desktop = mac and (Path('/Applications/Docker.app').is_dir() or (Path.home() / 'Applications/Docker.app').is_dir()) + add('Docker Desktop application', 'READY' if desktop else 'NOT VERIFIED', + 'Application directory found (not a running-engine test).' if desktop else 'Standard application location not confirmed.', + 'Check the approved installation and Desktop version manually.') + engine = None + local = False + if available: + # Never inspect a remotely selected daemon as evidence about this laptop. + endpoint = os.environ.get('DOCKER_HOST') if not os.environ.get('DOCKER_CONTEXT') else None + if not endpoint: + endpoint = query(['docker', 'context', 'inspect', '--format', '{{.Endpoints.docker.Host}}']) + local = bool(endpoint and endpoint.startswith('unix://') and not endpoint[7:].startswith('@')) + add('Docker endpoint', 'READY' if local else 'BLOCKED', + 'Local Unix socket selected.' if local else 'Local daemon not confirmed; remote queries skipped.', + 'Select the local Desktop context yourself; do not use a remote Engine for this check.') + if local: + # Select fields, never dump daemon configuration, proxies or credentials. + text = query(['docker', 'info', '--format', '{"os":{{json .OSType}},"arch":{{json .Architecture}},"desktop":{{json .OperatingSystem}},"cpus":{{.NCPU}},"memory":{{.MemTotal}}}']) + try: + parsed = json.loads(text or '') + if (isinstance(parsed, dict) and parsed.get('os') == 'linux' and parsed.get('arch') in ('aarch64', 'arm64') + and isinstance(parsed.get('cpus'), int) and not isinstance(parsed['cpus'], bool) + and isinstance(parsed.get('memory'), int) and not isinstance(parsed['memory'], bool) + and isinstance(parsed.get('desktop'), str) and 'docker desktop' in parsed['desktop'].lower()): + engine = parsed + except (ValueError, TypeError, KeyError): + pass + add('Docker Desktop Engine', 'READY' if engine else 'BLOCKED', + 'Responsive Linux ARM64 Desktop Engine.' if engine else 'Desktop Engine is stopped, unavailable, or not confirmed as local ARM64.', + 'Open the approved Docker Desktop app and retry; raw Docker output is suppressed.') + compose = query(['docker', 'compose', 'version', '--short']) if available else None + compose_match = re.fullmatch(r'v?(\d+)\.(\d+)\.\d+(?:[-+][\w.-]+)?', compose or '') + add('Compose', 'READY' if compose_match and int(compose_match[1]) >= 2 else 'BLOCKED', + compose if compose_match else 'Compose version unavailable.', 'Docker Compose v2+ is required.') + add('Docker resources', 'NOT VERIFIED' if engine is None else 'READY' if engine['cpus'] >= 4 and engine['memory'] >= 8 * GIB else 'WARNING', + 'CPU/RAM allocation unavailable.' if engine is None else f"{engine['cpus']} CPUs / {engine['memory'] / GIB:.1f} GiB allocated.", + 'Start with 4 CPUs / 8 GiB on a 16 GiB laptop; measure stack load before increasing limits.') + try: + location = paths['workspace'] + while not location.exists(): + if location.parent == location: + raise OSError('workspace filesystem unavailable') + location = location.parent + free = shutil.disk_usage(location).free + add('Disk space', 'BLOCKED' if free < 10 * GIB else 'WARNING' if free < 96 * GIB else 'READY', + f'{free / GIB:.1f} GiB free on the workspace filesystem.', + 'Plan at least 96 GiB for Desktop images/data plus separate backup space; VM disk capacity remains a manual check.') + except (OSError, ValueError): + add('Disk space', 'NOT VERIFIED', 'Workspace filesystem capacity unavailable.', 'Check free space and Desktop disk quota manually.') + + ports = sorted(value['profile']['ports'].values()) if value else [8080, 5005, 65000] + listeners = query(['lsof', '-nP', '-a', '-iTCP:' + ','.join(map(str, ports)), '-sTCP:LISTEN', '-Fn'], empty_ok=True) if mac and shutil.which('lsof') else None + add('Required TCP ports', 'NOT VERIFIED' if listeners is None else 'WARNING' if listeners else 'READY', + ', '.join(map(str, ports)) + (': listeners detected; names/addresses suppressed.' if listeners else ': no visible listeners.' if listeners is not None else ': not checked.'), + 'If already running, these may be your services. Resolve conflicts without killing unrelated processes; LAN access still needs two-device testing.') + + prepared = False + if value and engine and local: + try: + operator.pending(paths['workspace']) + root, _, _, _ = operator.check_config(paths['workspace'], value) + result = kit.execute(SimpleNamespace(action='preflight', workspace=str(root), runtime=True, apply=False)) + prepared = result.get('runtime') == 'PASS' + except (kit.Error, OSError, ValueError, TypeError, KeyError, subprocess.SubprocessError): + pass + add('Prepared runtime / cached image platforms', 'READY' if prepared else 'BLOCKED', + 'Existing runtime preflight passed: configuration, ownership, immutable cached images and platforms match.' if prepared else 'Not verified; missing cache/build receipt, changed config, or runtime check failed.', + 'After approval and with Internet: setup. If prepared already, use the existing deployment preflight to diagnose; do not rebuild/delete data blindly.') + add('Packmate emulation', 'WARNING', 'Pinned Packmate is Linux AMD64; Apple Silicon uses emulation. FILE is not continuous LIVE capture.', + 'Measure import latency/storage on the Mac. LIVE needs an approved Linux traffic source; closed PCAP transfer is a fallback only.') + try: + binary = Path(neo_client) if neo_client else operator.ROOT / 'local/neo-client/neo' + client = neo_arm64(binary, kit) + except (kit.Error, OSError, ValueError, TypeError, struct.error): + client = False + add('Neo Darwin ARM64 client', 'READY' if client else 'BLOCKED', + 'Executable ARM64 Mach-O present; header check only, version/auth not proven.' if client else 'Native client missing, non-executable, linked or wrong format/architecture.', + 'Prepare the locked v2.4.2 Darwin ARM64 release before going offline; pass --neo-client PATH if installed elsewhere. Never print neo info on a shared screen.') + add('Offline / real Mac acceptance', 'NOT VERIFIED', 'Cached-image inspection is not an offline cold start. Hosted CI does not prove Desktop, LAN or local policy compatibility.', + 'Complete MACOS_FIRST_RUN-RU.md and the isolated stack procedure; keep submission disabled. Workers need every script dependency inside their selected image.') + statuses = {row['status'] for row in rows} + status = 'BLOCKED' if 'BLOCKED' in statuses else 'WARNING' if 'WARNING' in statuses else 'NOT VERIFIED' if 'NOT VERIFIED' in statuses else 'READY' + return dict(tool='DurkaHelper doctor', read_only=True, status=status, competition_ready=False, + exit_code=2 if status == 'BLOCKED' else 1 if status in ('WARNING', 'NOT VERIFIED') else 0, checks=rows) + + +def run(operator, args): + report = inspect(operator, args.config, args.neo_client) + if args.json: + print(json.dumps(report, ensure_ascii=True, sort_keys=True, indent=2)) + else: + print('DurkaHelper doctor: ' + report['status'] + ' (read-only; not competition certification)') + for row in report['checks']: + print(row['status'] + ' | ' + row['check'] + ': ' + row['detail']) + if row['status'] != 'READY': + print(' Next: ' + row['guidance']) + return report['exit_code'] diff --git a/deployment/packmate_file.py b/deployment/packmate_file.py new file mode 100644 index 0000000..b276823 --- /dev/null +++ b/deployment/packmate_file.py @@ -0,0 +1,294 @@ +#!/usr/bin/env python3 +"""Safely replace one closed PCAP in an existing maintained FILE deployment. + +Only Packmate is stopped/restarted. Its database is retained and must already +be running. Processing is NOT started: configure services/patterns, then press +Start once in the UI. A FILE session must be restarted between closed files. +""" +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 struct +import sys + +SPEC = importlib.util.spec_from_file_location("file_recovery_activation", Path(__file__).with_name("recovery_activation.py")) +activation = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(activation) +rec, kit, ops, Error = activation.rec, activation.kit, activation.ops, activation.Error +MAX_BYTES = 512 * 1024 * 1024 +MAX_BLOCK = 16 * 1024 * 1024 +SCHEMA = "durkahelper.closed-pcap-replacement.v1" + + +def pcap_summary(descriptor): + """Bound framing/hash validation, not traffic analysis or content acceptance.""" + before = os.fstat(descriptor) + if not stat.S_ISREG(before.st_mode) or not 24 <= before.st_size <= MAX_BYTES: + raise Error("closed capture must be a bounded regular file (24 bytes to 512 MiB)") + os.lseek(descriptor, 0, os.SEEK_SET) + digest, size, packets = hashlib.sha256(), 0, 0 + with os.fdopen(os.dup(descriptor), "rb") as stream: + def read(count, eof=False): + nonlocal size + value = stream.read(count) + size += len(value) + if size > MAX_BYTES or (len(value) != count and not (eof and not value)): + raise Error("capture framing is truncated or exceeds byte bounds") + digest.update(value) + return value + + def discard(count): + while count: + take = min(count, 65536) + read(take) + count -= take + + magic = read(4) + classic = {b"\xd4\xc3\xb2\xa1": ("<", 1000000), b"\xa1\xb2\xc3\xd4": (">", 1000000), + b"\x4d\x3c\xb2\xa1": ("<", 1000000000), b"\xa1\xb2\x3c\x4d": (">", 1000000000)} + if magic in classic: + endian, resolution = classic[magic] + major, minor, zone, accuracy, snaplen, linktype = struct.unpack(endian + "HHIIII", read(20)) + if (major, minor) != (2, 4) or not 1 <= snaplen <= MAX_BLOCK: + raise Error("unsupported PCAP version or snapshot length") + while True: + header = read(16, eof=True) + if not header: + break + seconds, fraction, captured, original = struct.unpack(endian + "IIII", header) + if captured > min(snaplen, original) or fraction >= resolution: + raise Error("invalid PCAP packet lengths or timestamp framing") + discard(captured) + packets += 1 + if packets > 2_000_000: + raise Error("PCAP packet count exceeds bound") + kind = "PCAP" + elif magic == b"\x0a\x0d\x0d\x0a": + endian, blocks, block_type = None, 0, magic + while block_type: + length_raw = read(4) + if block_type == magic: + bom = read(4) + endian = {b"\x4d\x3c\x2b\x1a": "<", b"\x1a\x2b\x3c\x4d": ">"}.get(bom) + if endian is None: + raise Error("invalid PCAPNG byte order marker") + length = struct.unpack(endian + "I", length_raw)[0] + if not 28 <= length <= MAX_BLOCK or length % 4: + raise Error("invalid PCAPNG section length") + version = read(4) + if struct.unpack(endian + "HH", version) != (1, 0): + raise Error("unsupported PCAPNG section version") + discard(length - 20) + else: + length = struct.unpack(endian + "I", length_raw)[0] + if not 12 <= length <= MAX_BLOCK or length % 4: + raise Error("invalid PCAPNG block length") + number = struct.unpack(endian + "I", block_type)[0] + if number in {2, 3, 6}: + packets += 1 + discard(length - 12) + if struct.unpack(endian + "I", read(4))[0] != length: + raise Error("PCAPNG block footer mismatch") + blocks += 1 + if blocks > 2_000_000: + raise Error("PCAPNG block count exceeds bound") + block_type = read(4, eof=True) + kind = "PCAPNG" + else: + raise Error("input is not a supported closed PCAP/PCAPNG container") + if ops._stat_identity(before) != ops._stat_identity(os.fstat(descriptor)) or size != before.st_size: + raise Error("capture changed while validating; close the writer and record a new checksum") + return before, {"format": kind, "bytes": size, "sha256": digest.hexdigest(), "packet_records": packets, + "validation": "container framing only; upstream import acceptance not run"} + + +def inspect_file(path, expected=None): + source = ops._canonical_input_leaf(Path(path)) + descriptor = ops._open_anchored_regular(source.parent, source.name, ops._root_anchor_identity(source.parent.stat())) + try: + metadata, summary = pcap_summary(descriptor) + finally: + os.close(descriptor) + if expected is not None and summary["sha256"] != expected: + raise Error("closed capture does not match independently recorded SHA-256") + return source, metadata, summary + + +def gates(args): + if not args.approval_id or not re.fullmatch(r"[A-Za-z0-9_.-]{1,80}", args.approval_id): + raise Error("replacement requires a non-secret approval ID") + if not args.closed_pcap_confirmed or not args.maintenance_confirmed: + raise Error("replacement requires closed capture and exclusive file-maintenance confirmations") + if os.name != "posix" or os.geteuid() == 0: + raise Error("FILE replacement requires a non-root POSIX operator") + rec.daemon(args.daemon_id) + + +def stage_files(root, source, summary, previous, previous_summary): + target = root / ("pcap-import-" + secrets.token_hex(8)) + staging = ops._StagingDirectory.create(target, ".closed-pcap-") + try: + for source_path, destination, expected in ((source, "incoming.pcap", summary), (previous, "previous.pcap", previous_summary)): + metadata, digest = ops._copy_stable(source_path.parent, source_path.name, (staging, destination), MAX_BYTES, + [0, MAX_BYTES], ops._root_anchor_identity(source_path.parent.stat())) + if metadata.st_size != expected["bytes"] or digest != expected["sha256"]: + raise Error("closed capture changed while creating immutable replacement/rollback copies") + receipt = {"schema": SCHEMA, "configured_file": previous.name, "incoming": summary, "previous": previous_summary} + staging.write_new_bytes("replacement.json", ops._canonical(receipt)) + ops._publish_directory(staging, target) + finally: + staging.cleanup() + return target + + +def cutover(root, configured_name, transaction, expected_previous, expected_new): + """Descriptor-anchored cutover, with a retained immutable rollback copy.""" + folder = ops._canonical_root_directory(root / "pcaps") + anchor = ops._root_anchor_identity(folder.stat()) + directory = os.open(folder, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW) + source_fd = new_fd = old_fd = None + temporary = ".pcap-next-" + secrets.token_hex(12) + new_identity = None + try: + if ops._root_anchor_identity(os.fstat(directory)) != anchor: + raise Error("configured capture directory changed") + old_fd = os.open(configured_name, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=directory) + old_meta, old_summary = pcap_summary(old_fd) + if old_summary != expected_previous: + raise Error("previous configured capture changed before cutover") + source_fd = ops._open_anchored_regular(transaction, "incoming.pcap", ops._root_anchor_identity(transaction.stat())) + _, source_summary = pcap_summary(source_fd) + if source_summary != expected_new: + raise Error("immutable incoming capture changed before cutover") + os.lseek(source_fd, 0, os.SEEK_SET) + new_fd = os.open(temporary, os.O_RDWR | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600, dir_fd=directory) + new_identity = ops._root_anchor_identity(os.fstat(new_fd)) + copied = 0 + for chunk in iter(lambda: os.read(source_fd, 65536), b""): + copied += len(chunk) + if copied > min(MAX_BYTES, expected_new["bytes"]): + raise Error("immutable incoming capture grew during copy") + ops._write_all(new_fd, chunk) + os.fchmod(new_fd, 0o644) + os.fsync(new_fd) + _, staged_summary = pcap_summary(new_fd) + if staged_summary != expected_new: + raise Error("incoming copy changed before cutover") + named = os.stat(configured_name, dir_fd=directory, follow_symlinks=False) + if (ops._stat_identity(named) != ops._stat_identity(old_meta) or + ops._stat_identity(os.fstat(old_fd)) != ops._stat_identity(old_meta) or + ops._root_anchor_identity(os.stat(temporary, dir_fd=directory, follow_symlinks=False)) != new_identity or + ops._root_anchor_identity(folder.stat()) != anchor): + raise Error("capture path changed before cutover; rollback retained") + replace_error = None + try: + os.replace(temporary, configured_name, src_dir_fd=directory, dst_dir_fd=directory) + except BaseException as error: + replace_error = error + named = os.stat(configured_name, dir_fd=directory, follow_symlinks=False) + if ops._root_anchor_identity(named) != new_identity: + if replace_error is not None: + raise replace_error + raise Error("capture destination changed at cutover; app must remain stopped; rollback retained") + descriptor = os.open(configured_name, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=directory) + try: + final_meta, final_summary = pcap_summary(descriptor) + if ops._root_anchor_identity(final_meta) != new_identity or final_summary != expected_new: + raise Error("capture destination bytes changed at cutover; app must remain stopped") + finally: + os.close(descriptor) + os.fsync(directory) + finally: + for descriptor in (source_fd, new_fd, old_fd): + if descriptor is not None: + os.close(descriptor) + if new_identity is not None: + try: + named = os.stat(temporary, dir_fd=directory, follow_symlinks=False) + if ops._root_anchor_identity(named) == new_identity: + os.unlink(temporary, dir_fd=directory) + except FileNotFoundError: + pass + os.close(directory) + + +def replace(args): + if not isinstance(args.expected_sha256, str) or not re.fullmatch(r"[a-f0-9]{64}", args.expected_sha256): + raise Error("an independently recorded lower-case SHA-256 is required") + root, state, runtime, profile, _ = rec.source_workspace(args.workspace) + source, _, summary = inspect_file(args.pcap, args.expected_sha256) + previous, _, previous_summary = inspect_file(root / "pcaps" / profile["packmate"]["pcap_file"]) + if source == previous: + raise Error("incoming capture must be separate from the configured current file") + if not args.apply: + return {"status": "NOT_RUN", "action": "replace", "daemon_contacted": False, "incoming": summary, + "effects": ["stop only Packmate", "retain private previous capture", "atomic file replacement", "restart only Packmate"], + "processing": "NOT_RUN; configure service/patterns then press Start once"} + gates(args) + context = (root, state["project"], runtime, args.daemon_id, kit.LABEL) + current = rec.owned(*context, exclusive=False) + if not current.get("packmate-db", {}).get("running"): + raise Error("owned Packmate database must already be running; this helper never starts dependencies") + kit.image_preflight({"services": {"packmate": runtime["services"]["packmate"]}}, profile) + transaction = None + succeeded = False + try: + rec.stop(context, ("packmate",), exclusive=False) + transaction = stage_files(root, source, summary, previous, previous_summary) + if rec.source_workspace(root)[2] != runtime: + raise Error("maintained deployment changed during file replacement") + current = rec.owned(*context, exclusive=False) + if current.get("packmate", {}).get("running") or not current.get("packmate-db", {}).get("running"): + raise Error("Packmate was restarted or database stopped while staging; no file replaced") + cutover(root, previous.name, transaction, previous_summary, summary) + current = rec.owned(*context, exclusive=False) + if current.get("packmate", {}).get("running") or not current.get("packmate-db", {}).get("running"): + raise Error("candidate Packmate was restarted or database stopped during maintenance") + rec.run(kit.command(root, state, runtime=True) + ["up", "--detach", "--no-deps", "--no-build", "--pull", "never", "packmate"], timeout=120) + activation.packmate_ready(root, profile) + current = rec.owned(*context, exclusive=False) + if not current.get("packmate", {}).get("running") or not current.get("packmate-db", {}).get("running"): + raise Error("Packmate readiness is not bound to owned running resources") + inspect_file(previous, summary["sha256"]) + succeeded = True + finally: + if not succeeded: + rec.stop(context, ("packmate",), exclusive=False) + return {"status": "PASS", "action": "replace", "authenticated_ready": True, "capture_started": False, + "incoming": summary, "processing": "NOT_RUN; configure services/patterns then press Start once", + "database": "retained; importing overlapping captures may create duplicate stored traffic", + "rollback": {"relative_input": transaction.name + "/previous.pcap", "sha256": previous_summary["sha256"], + "procedure": "run this same explicit replacement command with previous.pcap and its checksum"}, + "limits": ["container framing checked, not upstream packet compatibility", "FILE is not continuous LIVE capture"]} + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("action", choices=("replace",)) + for name in ("workspace", "pcap", "expected-sha256"): + parser.add_argument("--" + name, required=True) + for name in ("approval-id", "daemon-id"): + parser.add_argument("--" + name) + for name in ("apply", "closed-pcap-confirmed", "maintenance-confirmed"): + parser.add_argument("--" + name, action="store_true") + args = parser.parse_args(argv) + try: + print(json.dumps(replace(args), sort_keys=True, indent=2)) + return 0 + except (Exception, KeyboardInterrupt) as error: + print(json.dumps({"status": "BLOCKED", "reason": str(error) if isinstance(error, Error) else + "closed capture replacement rejected: " + type(error).__name__, "raw_output": "suppressed", + "rollback": "inspect private pcap-import-* copies; do not delete them; restart only after a verified replacement"})) + return 2 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/deployment/packmate_host.py b/deployment/packmate_host.py new file mode 100644 index 0000000..98d4dde --- /dev/null +++ b/deployment/packmate_host.py @@ -0,0 +1,439 @@ +#!/usr/bin/env python3 +"""Opt-in native Linux host-interface Packmate; never a Desktop capture fallback. + +The entire selected interface must be approved: unchanged upstream briefly uses +a broad TCP/UDP filter at startup. Host networking and NET_RAW are explicit +trust-boundary expansions. No interface, route or firewall is modified here. +""" +from __future__ import annotations + +import argparse +import hashlib +import importlib.util +import ipaddress +import json +import os +from pathlib import Path +import re +import secrets +import stat +import sys + +SPEC = importlib.util.spec_from_file_location("host_live", Path(__file__).with_name("packmate_live.py")) +live = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(live) +kit, shared, Error = live.kit, live.shared, live.Error +SCHEMA = "durkahelper.packmate-host.v1" +LABEL = "io.durkahelper.packmate-host" + + +def profile(value): + keys = {"schema", "daemon_id", "interface", "ifindex", "interface_mac", "local_ip", + "bind_address", "ui_port", "db_port", "tcp_timeout_seconds", "udp_timeout_seconds", + "timeout_check_seconds", "retention_minutes", "cleanup_interval_minutes"} + if not isinstance(value, dict) or set(value) != keys or value["schema"] != SCHEMA: + raise Error("invalid host capture profile") + if not isinstance(value["daemon_id"], str) or not re.fullmatch(r"[A-Za-z0-9:_.-]{8,128}", value["daemon_id"]): + raise Error("exact approved Engine identity required") + if not isinstance(value["interface"], str) or not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,14}", value["interface"]): + raise Error("one explicit Linux interface is required; any is not supported") + if value["interface"] == "any": + raise Error("any-interface capture is forbidden") + if type(value["ifindex"]) is not int or not 1 <= value["ifindex"] <= 2**31 - 1: + raise Error("exact interface index required") + if not isinstance(value["interface_mac"], str) or not re.fullmatch(r"(?:[a-f0-9]{2}:){5}[a-f0-9]{2}", value["interface_mac"]): + raise Error("exact interface hardware address required") + for key in ("local_ip", "bind_address"): + address = ipaddress.ip_address(value[key]) + if address.version != 4 or address.is_unspecified or address.is_multicast or address.is_link_local: + raise Error("explicit unicast IPv4 required") + for key, lower, upper in (("ui_port", 1024, 65535), ("db_port", 1024, 65535), + ("tcp_timeout_seconds", 1, 600), ("udp_timeout_seconds", 1, 600), + ("timeout_check_seconds", 1, 60), ("retention_minutes", 1, 1440), + ("cleanup_interval_minutes", 1, 60)): + if type(value[key]) is not int or not lower <= value[key] <= upper: + raise Error("invalid bounded host capture setting") + if value["ui_port"] == value["db_port"]: + raise Error("UI and loopback database ports must differ") + return value + + +def properties(config, secret): + # Reuse the pinned upstream field names and exact logger mitigation. + pairs = dict(line.split("=", 1) for line in live.properties(config, secret, "unused").decode("ascii").splitlines()) + pairs.update({"spring.datasource.url": "jdbc:postgresql://127.0.0.1:" + str(config["db_port"]) + "/packmate", + "server.address": config["bind_address"], "server.port": str(config["ui_port"])}) + return "".join(key + "=" + str(value) + "\n" for key, value in sorted(pairs.items())).encode("ascii") + + +def compose_spec(config, secret, project, images=None): + images = images or {"packmate": kit.PACKMATE, "db": kit.PACKMATE_DB} + base = {"restart": "no", "cpus": 1.0, "mem_limit": "512m", "pids_limit": 128, + "security_opt": ["no-new-privileges:true"], "logging": {"driver": "none"}, "labels": {LABEL: project}} + db = dict(base, image=images["db"], platform="linux/amd64", + environment={"POSTGRES_DB": "packmate", "POSTGRES_USER": "packmate", "POSTGRES_PASSWORD": secret["db_password"]}, + volumes=["./data/postgres:/var/lib/postgresql/data"], networks=["database"], + ports=[{"target": 5432, "published": str(config["db_port"]), "host_ip": "127.0.0.1", "protocol": "tcp"}], + healthcheck={"test": ["CMD", "pg_isready", "-U", "packmate", "-d", "packmate"], + "interval": "2s", "timeout": "2s", "retries": 45}) + app = dict(base, image=images["packmate"], platform="linux/amd64", user="0:0", read_only=True, + cap_drop=["ALL"], cap_add=["NET_RAW"], network_mode="host", mem_limit="1536m", + tmpfs=["/tmp:size=67108864,mode=1777,noexec,nosuid,nodev", "/jna:size=16777216,mode=0700,nosuid,nodev,exec"], + volumes=["./application.properties:/configuration/application.properties:ro"], entrypoint=["java"], + command=["-Xms64m", "-Xmx768m", "-XX:ActiveProcessorCount=1", "-Djna.tmpdir=/jna", + "-Djava.net.preferIPv4Stack=true", "-jar", "/app/app.jar", + "--spring.config.additional-location=file:/configuration/application.properties"], + depends_on={"db": {"condition": "service_healthy"}}) + return {"services": {"db": db, "packmate": app}, "networks": {"database": {"labels": {LABEL: project}}}} + + +def prepare(args): + config, secret = profile(kit.load(args.profile)), live.credentials(kit.load(args.credentials)) + root = kit.safe_path(args.workspace) + if root.exists() or not root.parent.is_dir(): + raise Error("new workspace with existing private parent required") + if not args.apply: + return {"status": "NOT_RUN", "action": "prepare", "daemon_contacted": False, + "capture_started": False, "requires": "approved entire interface, host networking and NET_RAW"} + if os.name != "posix": + raise Error("host capture preparation requires POSIX") + if root.parent.stat().st_uid != os.getuid() or root.parent.stat().st_mode & 0o077: + raise Error("workspace parent must be owned and mode 0700") + state = {"schema": SCHEMA, "project": "dh-host-" + secrets.token_hex(6), "profile": config, "credentials": secret} + root.mkdir(mode=0o700) + shared.write(root / "state.json", shared.canonical(state)) + shared.write(root / "compose.json", shared.canonical(compose_spec(config, secret, state["project"]))) + shared.write(root / "application.properties", properties(config, secret)) + # Root with DAC_OVERRIDE dropped cannot read the operator-owned 0600 file. + # Only this individually mounted file is readable by the container; its + # parent remains 0700, and the credential ledger is never made public. + (root / "application.properties").chmod(0o644) + (root / "data").mkdir(mode=0o700) + (root / "data/postgres").mkdir(mode=0o700) + return {"status": "PASS", "action": "prepare", "capture_started": False} + + +def workspace(path): + root = kit.safe_path(path) + if not root.is_dir() or (os.name == "posix" and (root.stat().st_uid != os.getuid() or root.stat().st_mode & 0o077)): + raise Error("private owned workspace required") + state = kit.load(root / "state.json") + if (not isinstance(state, dict) or set(state) != {"schema", "project", "profile", "credentials"} or + state["schema"] != SCHEMA or not isinstance(state["project"], str) or + not re.fullmatch(r"dh-host-[a-f0-9]{12}", state["project"])): + raise Error("invalid host capture state") + profile(state["profile"]) + live.credentials(state["credentials"]) + for name, expected in {"compose.json": shared.canonical(compose_spec(state["profile"], state["credentials"], state["project"])), + "application.properties": properties(state["profile"], state["credentials"])}.items(): + if kit.read(root / name) != expected: + raise Error("immutable host capture configuration changed") + for name in ("data", "data/postgres"): + if (root / name).is_symlink() or not (root / name).is_dir(): + raise Error("host capture data must remain ordinary directories") + return root, state + + +def interface(config): + data = json.loads(shared.checked(["ip", "-json", "link", "show", "dev", config["interface"]], capture=True)) + if (not isinstance(data, list) or len(data) != 1 or data[0].get("ifname") != config["interface"] or + data[0].get("ifindex") != config["ifindex"] or data[0].get("address") != config["interface_mac"] or + "UP" not in data[0].get("flags", [])): + raise Error("approved interface identity or UP state changed") + + +def local_engine(): + """Host-interface approval must refer to this kernel, never a remote daemon.""" + if any(os.environ.get(name) for name in ("DOCKER_HOST", "DOCKER_CONTEXT", "DOCKER_TLS_VERIFY", "DOCKER_CERT_PATH")): + raise Error("host capture refuses Docker endpoint override variables; use the local standard Engine context") + endpoint = json.loads(shared.checked(["docker", "context", "inspect", "--format", "{{json .Endpoints.docker}}"], capture=True)) + if not isinstance(endpoint, dict) or endpoint.get("Host") != "unix:///var/run/docker.sock": + raise Error("host capture requires the local standard Unix Docker socket, not a remote context") + metadata = Path("/var/run/docker.sock").lstat() + if not stat.S_ISSOCK(metadata.st_mode) or metadata.st_uid != 0: + raise Error("host capture requires a real root-owned local Docker socket") + observed = json.loads(shared.checked(["docker", "info", "--format", + '{"security":{{json .SecurityOptions}},"kernel":{{json .KernelVersion}}}'], capture=True)) + if (not isinstance(observed, dict) or not isinstance(observed.get("security"), list) or + any(not isinstance(value, str) or "rootless" in value.lower() for value in observed["security"]) or + observed.get("kernel") != os.uname().release): + raise Error("host capture requires the local rootful Engine on this kernel") + + +def image_ids(images): + if not isinstance(images, dict) or set(images) != {"packmate", "db"} or any( + not isinstance(v, str) or not re.fullmatch(r"sha256:[a-f0-9]{64}", v) for v in images.values()): + raise Error("invalid cached host capture image receipt") + return images + + +def receipt_images(root): + return image_ids(kit.load(root / "images.json")) + + +def fresh_runtime(root): + # lexists, rather than exists, also rejects a dangling symlink. A partial + # previous publication is deliberately not repaired or overwritten here. + if any(os.path.lexists(root / name) for name in ("images.json", "runtime-compose.json")): + raise Error("bootstrap requires a fresh workspace without runtime or image receipt") + + +def bootstrap_receipt(root, path, expected_sha256): + """Detached operator approval binds IDs reviewed against the pinned refs. + + The receipt does not prove upstream provenance on its own. It is portable + between approved daemons only after the independently recorded hash is + checked; Docker is never contacted while validating this input. + """ + fresh_runtime(root) + if not isinstance(expected_sha256, str) or not re.fullmatch(r"[a-f0-9]{64}", expected_sha256): + raise Error("bootstrap requires an independently approved canonical image receipt SHA-256") + source = kit.safe_path(path) + before = source.lstat() + if (not stat.S_ISREG(before.st_mode) or before.st_size > 4096 or before.st_nlink != 1 or + (os.name == "posix" and (before.st_uid != os.getuid() or before.st_mode & 0o077))): + raise Error("bootstrap receipt must be a private owned bounded regular file") + + def stamp(metadata): + return (metadata.st_dev, metadata.st_ino, metadata.st_size, metadata.st_mtime_ns, + metadata.st_ctime_ns, metadata.st_mode, metadata.st_uid, metadata.st_nlink) + + def unique(pairs): + result = {} + for key, value in pairs: + if key in result: + raise Error("duplicate bootstrap receipt key") + result[key] = value + return result + + content = kit.read(source, limit=4096) + if stamp(source.lstat()) != stamp(before): + raise Error("bootstrap receipt changed while reading") + images = image_ids(json.loads(content, object_pairs_hook=unique)) + if len(set(images.values())) != 2: + raise Error("bootstrap requires distinct application and database image IDs") + if hashlib.sha256(shared.canonical(images)).hexdigest() != expected_sha256: + raise Error("bootstrap receipt differs from independently approved canonical checksum") + return images, (stamp(before), content) + + +def publish_bootstrap(root, payload, identities): + """No-replace publication, retaining descriptors until both paths verify. + + On an interrupted or raced publication, keep partial files for inspection; + they are never repaired automatically and cannot trigger container startup. + """ + fresh_runtime(root) + parent = root.lstat() + descriptors = [] + try: + for name, content in (("runtime-compose.json", payload), ("images.json", shared.canonical(identities))): + current = root.lstat() + if (not stat.S_ISDIR(current.st_mode) or + (current.st_dev, current.st_ino) != (parent.st_dev, parent.st_ino)): + raise Error("bootstrap workspace changed during publication") + path = root / name + descriptor = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | + getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_BINARY", 0), 0o600) + descriptors.append((descriptor, path, content)) + with os.fdopen(descriptor, "wb", closefd=False) as stream: + stream.write(content) + stream.flush() + os.fsync(descriptor) + for descriptor, path, content in descriptors: + held, named = os.fstat(descriptor), path.lstat() + if (not stat.S_ISREG(named.st_mode) or named.st_nlink != 1 or + (held.st_dev, held.st_ino) != (named.st_dev, named.st_ino) or + kit.read(path) != content): + raise Error("bootstrap publication changed; partial workspace retained for inspection") + current = root.lstat() + if not stat.S_ISDIR(current.st_mode) or (current.st_dev, current.st_ino) != (parent.st_dev, parent.st_ino): + raise Error("bootstrap workspace changed during publication") + finally: + for descriptor, _, _ in descriptors: + os.close(descriptor) + + +def owned(root, state, images=None): + """Validate exact project IDs, immutable images and mounts without foreign logs.""" + project = state["project"] + if not isinstance(project, str) or not re.fullmatch(r"dh-host-[a-f0-9]{12}", project): + raise Error("invalid host capture ownership project") + def listing(argv, maximum): + values = shared.checked(argv, capture=True).decode().split() + if len(values) > maximum or len(set(values)) != len(values) or any(not re.fullmatch(r"[a-f0-9]{64}", item) for item in values): + raise Error("unexpected host capture resource inventory") + return values + + identifiers = listing(["docker", "ps", "--all", "--quiet", "--no-trunc", "--filter", "label=com.docker.compose.project=" + project], 2) + images = (image_ids(images) if images is not None else receipt_images(root)) if identifiers else None + current = {} + fmt = ('{"id":{{json .Id}},"labels":{{json .Config.Labels}},"image":{{json .Image}},' + '"running":{{json .State.Running}},"mounts":{{json .Mounts}},"networks":{{json .NetworkSettings.Networks}},' + '"mode":{{json .HostConfig.NetworkMode}},"ports":{{json .HostConfig.PortBindings}},' + '"privileged":{{json .HostConfig.Privileged}},"readonly":{{json .HostConfig.ReadonlyRootfs}},' + '"caps":{{json .HostConfig.CapAdd}},"drop":{{json .HostConfig.CapDrop}}}') + physical = project + "_database" + for identity in identifiers: + value = json.loads(shared.checked(["docker", "container", "inspect", "--format", fmt, identity], capture=True)) + labels, mounts = value.get("labels") or {}, value.get("mounts") + service = labels.get("com.docker.compose.service") + if (value.get("id") != identity or labels.get("com.docker.compose.project") != project or + labels.get(LABEL) != project or service not in {"db", "packmate"} or service in current or + value.get("image") != images[service] or value.get("privileged") is not False or + type(value.get("running")) is not bool or not isinstance(mounts, list)): + raise Error("host capture resource ownership, service or image mismatch") + expected = {"/configuration/application.properties": (str(root / "application.properties"), False)} if service == "packmate" else { + "/var/lib/postgresql/data": (str(root / "data/postgres"), True)} + actual = {item.get("Destination"): (item.get("Source"), item.get("RW")) for item in mounts if item.get("Type") == "bind"} + tmpfs = {"/tmp", "/jna"} if service == "packmate" else set() + if (actual != expected or any(item.get("Type") != "bind" and not (item.get("Type") == "tmpfs" and + item.get("Destination") in tmpfs) for item in mounts)): + raise Error("host capture bind mounts differ from the private workspace") + if service == "packmate": + if (value.get("mode") != "host" or set(value.get("networks") or {}) != {"host"} or + value.get("ports") not in (None, {}) or value.get("readonly") is not True or + value.get("caps") not in (["NET_RAW"], ["CAP_NET_RAW"]) or value.get("drop") != ["ALL"]): + raise Error("host capture runtime privilege or network boundary changed") + else: + ports = {"5432/tcp": [{"HostIp": "127.0.0.1", "HostPort": str(state["profile"]["db_port"])}]} + if value.get("mode") != physical or set(value.get("networks") or {}) != {physical} or value.get("ports") != ports: + raise Error("host capture database network or loopback publication changed") + current[service] = value + networks = listing(["docker", "network", "ls", "--quiet", "--no-trunc", "--filter", "label=com.docker.compose.project=" + project], 1) + # A name collision without our ownership labels must be rejected before up. + exact = listing(["docker", "network", "ls", "--quiet", "--no-trunc", "--filter", "name=^" + re.escape(physical) + "$"], 1) + if set(exact) != set(networks): + raise Error("host capture database network name or ownership collision") + for identity in networks: + fmt = '{"id":{{json .Id}},"name":{{json .Name}},"labels":{{json .Labels}},"containers":{{json .Containers}},"internal":{{json .Internal}}}' + value = json.loads(shared.checked(["docker", "network", "inspect", "--format", fmt, identity], capture=True)) + labels = value.get("labels") or {} + expected_members = {current["db"]["id"]} if current.get("db", {}).get("running") else set() + if (value.get("id") != identity or value.get("name") != physical or labels.get(LABEL) != project or + labels.get("com.docker.compose.project") != project or value.get("internal") is not False or + not isinstance(value.get("containers"), dict) or set(value["containers"]) != expected_members): + raise Error("host capture database network isolation or membership changed") + if "db" in current and current["db"]["networks"][physical].get("NetworkID") != identity: + raise Error("host capture database network identity mismatch") + if "db" in current and not networks: + raise Error("host capture database network missing") + return current + + +def runtime(root, state, expected_images_sha256=None, bootstrap_images=None): + receipt = root / "images.json" + bootstrap_identity = None + if bootstrap_images is not None: + images, bootstrap_identity = bootstrap_receipt(root, bootstrap_images, expected_images_sha256) + elif receipt.exists(): + images = receipt_images(root) + checksum = hashlib.sha256(shared.canonical(images)).hexdigest() + if expected_images_sha256 is not None and expected_images_sha256 != checksum: + raise Error("host capture image receipt differs from independently approved checksum") + # An operator-recorded checksum enables tag-free Docker save/load. If + # none is supplied, independently resolve the pinned upstream refs on + # each launch; a mutable receipt alone never authorizes another image. + if expected_images_sha256 is None: + for name, reference in {"packmate": kit.PACKMATE, "db": kit.PACKMATE_DB}.items(): + observed = shared.checked(["docker", "image", "inspect", "--format", "{{.Id}}", reference], capture=True).decode().strip() + if observed != images[name]: + raise Error("host capture image receipt differs from pinned upstream image") + else: + images = {"packmate": kit.PACKMATE, "db": kit.PACKMATE_DB} + if expected_images_sha256 is not None: + raise Error("no cached image receipt exists to bind the independently approved checksum") + identities = {} + for name, reference in images.items(): + observed = shared.checked(["docker", "image", "inspect", "--format", "{{.Id}};{{.Os}};{{.Architecture}}", reference], 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"] or + (reference.startswith("sha256:") and reference != observed[0])): + raise Error("host capture image identity or architecture mismatch") + identities[name] = observed[0] + payload = shared.canonical(compose_spec(state["profile"], state["credentials"], state["project"], identities)) + if bootstrap_images is not None: + # The source and both destination names must still match the approved + # preflight after Docker inspection. No partial state is overwritten. + verified, current_identity = bootstrap_receipt(root, bootstrap_images, expected_images_sha256) + if current_identity != bootstrap_identity or verified != identities: + raise Error("bootstrap receipt changed during image inspection") + publish_bootstrap(root, payload, identities) + elif receipt.exists(): + if kit.read(root / "runtime-compose.json") != payload: + raise Error("host capture runtime changed") + else: + shared.write(root / "runtime-compose.json", payload) + shared.write(receipt, shared.canonical(identities)) + return hashlib.sha256(shared.canonical(identities)).hexdigest() + + +def command(root, state, runtime=False): + return ["docker", "compose", "--project-name", state["project"], "--project-directory", str(root), + "--file", str(root / ("runtime-compose.json" if runtime else "compose.json"))] + + +def execute(args): + root, state = workspace(args.workspace) + config = state["profile"] + bootstrap = getattr(args, "bootstrap_images", None) + if bootstrap is not None: + if args.action != "up": + raise Error("bootstrap images are accepted only for the first up") + bootstrap_receipt(root, bootstrap, getattr(args, "expected_images_sha256", None)) + if not args.apply: + return {"status": "NOT_RUN", "action": args.action, "daemon_contacted": False, + "capture_scope": "entire approved host interface; upstream startup filter is TCP/UDP"} + if not sys.platform.startswith("linux"): + raise Error("host capture requires native Linux, not Docker Desktop") + if args.action == "up" and not (args.host_network_approved and args.interface_scope_approved and + args.capture_approval == config["interface"] + ":" + str(config["ifindex"]) + ":" + config["interface_mac"]): + raise Error("up requires exact interface capture approval, whole-interface scope and host-network approval") + local_engine() + live.daemon(config) + owned(root, state) + if args.action == "down": + shared.checked(command(root, state) + ["down", "--timeout", "10"], timeout=60) + return {"status": "PASS", "action": "down", "data_retained": True, "interface_unchanged": True} + interface(config) + checksum = runtime(root, state, getattr(args, "expected_images_sha256", None), bootstrap) + shared.checked(command(root, state, True) + ["config", "--quiet"]) + shared.checked(command(root, state, True) + ["up", "--detach", "--no-build", "--pull", "never"], timeout=180) + live.ready(config, state["credentials"]) + current = owned(root, state) + if set(current) != {"db", "packmate"} or not all(value["running"] for value in current.values()): + raise Error("host capture readiness is not bound to exactly two owned running services") + return {"status": "PASS", "action": "up", "authenticated_capture_started": True, + "traffic_correctness": "NOT_RUN", "retention": "age policy, not a hard disk quota", + "network_scope": "explicit host network; DB published only on IPv4 loopback", + "not_validated": ["actual event interface", "physical team LAN", "sustained load", "hard storage bound"], + "images_sha256": checksum, "offline_note": "record this checksum independently for tag-free restart approval", + "rollback": "down with same workspace, apply and approval ID; data retained"} + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("action", choices=["prepare", "up", "down"]) + parser.add_argument("--workspace", required=True) + for name in ("profile", "credentials", "approval-id", "capture-approval", "expected-images-sha256", "bootstrap-images"): + parser.add_argument("--" + name) + for name in ("apply", "host-network-approved", "interface-scope-approved"): + parser.add_argument("--" + name, 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 non-secret --approval-id") + if args.action == "prepare" and not (args.profile and args.credentials): + raise Error("prepare requires private profile and credentials") + if args.bootstrap_images is not None and args.action != "up": + raise Error("bootstrap images are accepted only for the first up") + result = prepare(args) if args.action == "prepare" else execute(args) + print(json.dumps(result, sort_keys=True)) + return 0 + except (Error, OSError, ValueError, KeyError, TypeError, AttributeError, KeyboardInterrupt) as error: + print(json.dumps({"status": "BLOCKED", "reason": str(error) if isinstance(error, Error) else "host capture operation rejected; raw details suppressed", + "rollback": "down only this workspace with apply/approval; databases retained; inspect partial resources before retry"})) + return 2 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/deployment/packmate_live.py b/deployment/packmate_live.py new file mode 100644 index 0000000..9a12621 --- /dev/null +++ b/deployment/packmate_live.py @@ -0,0 +1,309 @@ +#!/usr/bin/env python3 +"""Explicitly approved Linux container-namespace LIVE capture, unchanged Packmate. + +The namespace owner must already publish the selected UI port and carry the +approved ownership label. Its single user-defined bridge is shared with the +private (unpublished) database: every bridge peer is inside the trust boundary. +Host capture, Docker Desktop and automatic network changes are unsupported. +""" +from __future__ import annotations + +import argparse +import base64 +import hashlib +import importlib.util +import ipaddress +import json +import os +from pathlib import Path +import re +import secrets +import sys +import time +import urllib.error +import urllib.request + +_SPEC = importlib.util.spec_from_file_location("live_toolkit", Path(__file__).with_name("toolkit.py")) +kit = importlib.util.module_from_spec(_SPEC) +_SPEC.loader.exec_module(kit) +shared, Error = kit.shared, kit.Error +SCHEMA = "durkahelper.packmate-live.v1" +LABEL = "io.durkahelper.packmate-live" +CAPTURE_LABEL = "io.durkahelper.capture-scope" +PORT = 65000 +API = re.compile(r"/(?:$|api/(?:service/|pattern/|pcap/(?:started|start|stop)|stream/[1-9][0-9]{0,4}|packet/[1-9][0-9]{0,18}))\Z") +NOT_VALIDATED = ["host or mirrored-interface capture", "Docker Desktop", "team LAN", "real Vulnbox traffic", + "packet loss under load", "hard storage quota", "60 minute sustained capture", "actual Mac"] + + +def profile(value): + keys = {"schema", "daemon_id", "capture_container", "network_id", "capture_scope", "interface", "local_ip", + "bind_address", "ui_port", "tcp_timeout_seconds", "udp_timeout_seconds", "timeout_check_seconds", + "retention_minutes", "cleanup_interval_minutes"} + if not isinstance(value, dict) or set(value) != keys or value["schema"] != SCHEMA: + raise Error("invalid LIVE profile; only explicitly approved container namespace mode is supported") + for key, pattern in (("daemon_id", r"[A-Za-z0-9:_.-]{8,128}"), ("capture_container", r"[a-f0-9]{64}"), + ("network_id", r"[a-f0-9]{64}"), ("capture_scope", r"[A-Za-z0-9_.-]{1,80}")): + if not isinstance(value[key], str) or not re.fullmatch(pattern, value[key]): + raise Error("invalid LIVE identity") + # A single ordinary bridge endpoint has eth0. Multi-network, host, loopback, + # interface aliases and guessed mirrored interfaces require separate review. + if value["interface"] != "eth0": + raise Error("this profile supports only a reviewed single-bridge eth0 namespace") + for key in ("local_ip", "bind_address"): + address = ipaddress.ip_address(value[key]) + if address.version != 4 or address.is_unspecified or address.is_multicast or address.is_link_local: + raise Error("LIVE addresses must be explicit unicast IPv4 addresses") + if key == "local_ip" and address.is_loopback: + raise Error("capture local IP must be the inspected bridge endpoint") + for key, maximum in (("ui_port", 65535), ("tcp_timeout_seconds", 600), ("udp_timeout_seconds", 600), + ("timeout_check_seconds", 60), ("retention_minutes", 1440), ("cleanup_interval_minutes", 60)): + if type(value[key]) is not int or not 1 <= value[key] <= maximum: + raise Error("invalid LIVE bounded policy value") + return value + + +def credentials(value): + if not isinstance(value, dict) or set(value) != {"username", "password", "db_password"}: + raise Error("invalid LIVE credential fields") + for key, text in value.items(): + pattern = r"[A-Za-z0-9_.-]{4,64}" if key == "username" else r"[A-Za-z0-9_.-]{20,128}" + if not isinstance(text, str) or not re.fullmatch(pattern, text) or text.startswith("REPLACE_"): + raise Error("LIVE requires privately generated credentials") + return value + + +def properties(config, secret, project): + pairs = {"spring.datasource.url": "jdbc:postgresql://" + project + "-db:5432/packmate", + "spring.datasource.username": "packmate", "spring.datasource.password": secret["db_password"], + "packmate.web.account-login": secret["username"], "packmate.web.account-password": secret["password"], + "packmate.capture-mode": "LIVE", "packmate.interface-name": config["interface"], + "packmate.local-ip": config["local_ip"], "packmate.timeout.tcp-stream-timeout": config["tcp_timeout_seconds"], + "packmate.timeout.udp-stream-timeout": config["udp_timeout_seconds"], + "packmate.timeout.check-interval": config["timeout_check_seconds"], "packmate.cleanup.enabled": "true", + "packmate.cleanup.threshold": config["retention_minutes"], "packmate.cleanup.interval": config["cleanup_interval_minutes"], + "server.port": PORT, "server.address": config["local_ip"], "logging.level." + kit.LOGGER: "OFF"} + return "".join(key + "=" + str(value) + "\n" for key, value in sorted(pairs.items())).encode("ascii") + + +def compose_spec(config, secret, project, images=None): + images = images or {"packmate": kit.PACKMATE, "db": kit.PACKMATE_DB} + base = {"restart": "no", "cpus": 1.0, "mem_limit": "512m", "pids_limit": 128, + "security_opt": ["no-new-privileges:true"], "logging": {"driver": "none"}, "labels": {LABEL: project}} + database = dict(base, image=images["db"], platform="linux/amd64", + environment={"POSTGRES_DB": "packmate", "POSTGRES_USER": "packmate", "POSTGRES_PASSWORD": secret["db_password"]}, + volumes=["./data/postgres:/var/lib/postgresql/data"], networks={"capture": {"aliases": [project + "-db"]}}, + healthcheck={"test": ["CMD", "pg_isready", "-U", "packmate", "-d", "packmate"], + "interval": "2s", "timeout": "2s", "retries": 45}) + # Linux libpcap opens AF_PACKET sockets with NET_RAW. UID 0 with ALL dropped + # and only NET_RAW added is used because nonroot Docker cap_add does not + # reliably retain effective capabilities for the unmodified upstream Java. + app = dict(base, image=images["packmate"], platform="linux/amd64", user="0:0", read_only=True, + cap_drop=["ALL"], cap_add=["NET_RAW"], mem_limit="1536m", + network_mode="container:" + config["capture_container"], + tmpfs=["/tmp:size=67108864,mode=1777,noexec,nosuid,nodev", "/jna:size=16777216,mode=0700,nosuid,nodev,exec"], + volumes=["./application.properties:/configuration/application.properties:ro"], entrypoint=["java"], + command=["-Xms64m", "-Xmx768m", "-XX:ActiveProcessorCount=1", "-Djna.tmpdir=/jna", + "-Djava.net.preferIPv4Stack=true", "-jar", "/app/app.jar", + "--spring.config.additional-location=file:/configuration/application.properties"], + depends_on={"db": {"condition": "service_healthy"}}) + return {"services": {"db": database, "packmate": app}, + "networks": {"capture": {"external": True, "name": config["network_id"]}}} + + +def validate_state(value): + if (not isinstance(value, dict) or set(value) != {"schema", "project", "profile", "credentials"} or + value["schema"] != SCHEMA or not re.fullmatch(r"dh-live-[a-f0-9]{12}", value.get("project", ""))): + raise Error("invalid LIVE ownership state") + profile(value["profile"]) + credentials(value["credentials"]) + return value + + +def workspace(path): + root = kit.safe_path(path) + if not root.is_dir(): + raise Error("LIVE workspace missing") + if os.name == "posix" and (root.stat().st_uid != os.getuid() or root.stat().st_mode & 0o077): + raise Error("LIVE workspace must be private and owned by the current user") + state = validate_state(kit.load(root / "state.json")) + expected = {"compose.json": shared.canonical(compose_spec(state["profile"], state["credentials"], state["project"])), + "application.properties": properties(state["profile"], state["credentials"], state["project"])} + for name, content in expected.items(): + if kit.read(root / name) != content: + raise Error("LIVE immutable configuration changed; prepare a new workspace") + if (root / "data").is_symlink() or (root / "data/postgres").is_symlink() or not (root / "data/postgres").is_dir(): + raise Error("LIVE database data must remain an ordinary owned path") + return root, state + + +def prepare(args): + config, secret = profile(kit.load(args.profile)), credentials(kit.load(args.credentials)) + root = kit.safe_path(args.workspace) + if root.exists() or not root.parent.is_dir(): + raise Error("LIVE workspace must be a new directory with an existing parent") + if not args.apply: + return {"status": "NOT_RUN", "action": "prepare", "mode": "LIVE", "daemon_contacted": False, + "effects": "new private workspace only; no capture or Docker operation"} + if os.name != "posix": + raise Error("LIVE preparation requires POSIX private permissions") + state = {"schema": SCHEMA, "project": "dh-live-" + secrets.token_hex(6), "profile": config, "credentials": secret} + root.mkdir(mode=0o700) + shared.write(root / "state.json", shared.canonical(state)) + shared.write(root / "compose.json", shared.canonical(compose_spec(config, secret, state["project"]))) + shared.write(root / "application.properties", properties(config, secret, state["project"])) + (root / "application.properties").chmod(0o644) + (root / "data/postgres").mkdir(mode=0o700, parents=True) + return {"status": "PASS", "action": "prepare", "mode": "LIVE", "capture_started": False, + "retention": "age policy only, not a hard storage quota", "not_validated": NOT_VALIDATED} + + +def daemon(config): + raw = shared.checked(["docker", "info", "--format", "{{.ID}};{{.OSType}};{{.Architecture}};{{.OperatingSystem}}"], capture=True).decode().strip().split(";", 3) + if len(raw) != 4 or raw[0] != config["daemon_id"] or raw[1] != "linux" or raw[2] not in {"x86_64", "amd64"} or "docker desktop" in raw[3].lower(): + raise Error("LIVE requires the approved native Linux amd64 Docker Engine, not Docker Desktop") + + +def capture_scope(config): + template = '{"id":{{json .Id}},"running":{{json .State.Running}},"mode":{{json .HostConfig.NetworkMode}},"networks":{{json .NetworkSettings.Networks}},"ports":{{json .NetworkSettings.Ports}},"owner":{{json (index .Config.Labels "' + CAPTURE_LABEL + '")}}}' + item = json.loads(shared.checked(["docker", "container", "inspect", "--format", template, config["capture_container"]], capture=True)) + if (item.get("id") != config["capture_container"] or item.get("running") is not True or + item.get("owner") != config["capture_scope"] or item.get("mode") in {"host", "none", "default", "bridge"} or + str(item.get("mode", "")).startswith("container:") or not isinstance(item.get("networks"), dict) or len(item["networks"]) != 1): + raise Error("capture namespace identity, ownership, running state or network scope mismatch") + endpoint = next(iter(item["networks"].values())) + if endpoint.get("NetworkID") != config["network_id"] or endpoint.get("IPAddress") != config["local_ip"]: + raise Error("capture bridge endpoint changed") + if item.get("ports", {}).get(str(PORT) + "/tcp") != [{"HostIp": config["bind_address"], "HostPort": str(config["ui_port"])}]: + raise Error("namespace owner must already publish exactly the approved Packmate UI binding") + template = '{"id":{{json .Id}},"driver":{{json .Driver}},"owner":{{json (index .Labels "' + CAPTURE_LABEL + '")}}}' + network = json.loads(shared.checked(["docker", "network", "inspect", "--format", template, config["network_id"]], capture=True)) + if network != {"id": config["network_id"], "driver": "bridge", "owner": config["capture_scope"]}: + raise Error("capture bridge ownership or driver mismatch") + + +def owned(state): + project = state["project"] + identifiers = shared.checked(["docker", "ps", "--all", "--quiet", "--filter", "label=com.docker.compose.project=" + project], capture=True).decode().split() + if len(identifiers) > 4 or any(not re.fullmatch(r"[a-f0-9]{12,64}", item) for item in identifiers): + raise Error("unexpected LIVE resource listing") + for identity in identifiers: + owner = shared.checked(["docker", "inspect", "--format", '{{index .Config.Labels "' + LABEL + '"}}', identity], capture=True).decode().strip() + if owner != project: + raise Error("LIVE resource owner mismatch; operation refused") + + +def runtime(root, state): + receipt_path = root / "images.json" + if receipt_path.exists(): + images = kit.load(receipt_path) + if not isinstance(images, dict) or set(images) != {"packmate", "db"} or any(not isinstance(v, str) or not re.fullmatch(r"sha256:[a-f0-9]{64}", v) for v in images.values()): + raise Error("invalid LIVE immutable image receipt") + else: + images = {"packmate": kit.PACKMATE, "db": kit.PACKMATE_DB} + identities = {} + for name, reference in images.items(): + raw = shared.checked(["docker", "image", "inspect", "--format", "{{.Id}};{{.Os}};{{.Architecture}}", reference], 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"] or (reference.startswith("sha256:") and reference != raw[0]): + raise Error("LIVE cached image identity or architecture mismatch") + identities[name] = raw[0] + spec = compose_spec(state["profile"], state["credentials"], state["project"], identities) + payload = shared.canonical(spec) + if receipt_path.exists(): + if kit.read(root / "runtime-compose.json") != payload: + raise Error("LIVE runtime Compose differs from immutable image receipt") + else: + shared.write(root / "runtime-compose.json", payload) + shared.write(receipt_path, shared.canonical(identities)) + return spec + + +def command(root, state, runtime=False): + return ["docker", "compose", "--project-name", state["project"], "--project-directory", str(root), + "--file", str(root / ("runtime-compose.json" if runtime else "compose.json"))] + + +def request(config, secret, path, method="GET", body=None, auth=True): + if method not in {"GET", "POST"} or not isinstance(path, str) or not API.fullmatch(path): + raise Error("unlisted LIVE API operation") + headers = {"Content-Type": "application/json", "Accept-Encoding": "identity"} + if auth: + headers["Authorization"] = "Basic " + base64.b64encode((secret["username"] + ":" + secret["password"]).encode("ascii")).decode("ascii") + req = urllib.request.Request("http://" + config["bind_address"] + ":" + str(config["ui_port"]) + path, + headers=headers, method=method, 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=3) + except urllib.error.HTTPError as error: + response = error + with response: + raw = response.read(1024 * 1024 + 1) + if len(raw) > 1024 * 1024: + raise Error("LIVE API response exceeded bound") + if response.status != 200: + raise Error("LIVE API did not return HTTP 200; body suppressed") + return json.loads(raw) if raw else None + + +def ready(config, secret, timeout=120): + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + try: + if isinstance(request(config, secret, "/api/service/"), list) and request(config, secret, "/api/pcap/started") is True: + return + except (Error, OSError, ValueError, urllib.error.URLError): + pass + time.sleep(1) + raise Error("authenticated LIVE capture readiness timed out; inspect owned deployment or run down") + + +def execute(args): + root, state = workspace(args.workspace) + config = state["profile"] + if not args.apply: + return {"status": "NOT_RUN", "action": args.action, "mode": "LIVE", "daemon_contacted": False, + "capture_scope": "explicitly approved container namespace only", "retention": "age policy, not hard storage quota"} + if not sys.platform.startswith("linux"): + raise Error("LIVE operations require a native Linux host") + if args.action == "up" and args.capture_approval != config["capture_container"]: + raise Error("LIVE startup requires --capture-approval matching the exact approved container ID") + daemon(config) + owned(state) + if args.action == "down": + shared.checked(command(root, state) + ["down", "--timeout", "10"], timeout=60) + return {"status": "PASS", "action": "down", "capture_owner_unchanged": True, "database_data_retained": True} + capture_scope(config) + runtime(root, state) + shared.checked(command(root, state, True) + ["config", "--quiet"]) + shared.checked(command(root, state, True) + ["up", "--detach", "--no-build", "--pull", "never"], timeout=180) + ready(config, state["credentials"]) + return {"status": "PASS", "action": "up", "mode": "LIVE", "authenticated_capture_started": True, + "traffic_correctness": "NOT_RUN", "network_scope": "approved bridge peers can reach authenticated DB; no host DB publication", + "retention": "upstream age cleanup enabled; not a hard disk quota", "not_validated": NOT_VALIDATED, + "rollback": "down --workspace SAME_WORKSPACE --apply --approval-id ID; namespace owner/network/data retained"} + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("action", choices=["prepare", "up", "down"]) + parser.add_argument("--workspace", required=True) + for name in ("profile", "credentials", "approval-id", "capture-approval"): + parser.add_argument("--" + name) + 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-id") + if args.action == "prepare" and not (args.profile and args.credentials): + raise Error("prepare requires private profile and credentials JSON") + result = prepare(args) if args.action == "prepare" else execute(args) + print(json.dumps(result, sort_keys=True)) + return 0 + except (Error, OSError, ValueError, KeyError, TypeError, AttributeError, KeyboardInterrupt) as error: + print(json.dumps({"status": "BLOCKED", "reason": str(error) if isinstance(error, Error) else "LIVE operation rejected; raw details suppressed", + "rollback": "inspect exact owned project; down retains namespace owner, network and database data"})) + return 2 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/deployment/packmate_remote.py b/deployment/packmate_remote.py new file mode 100644 index 0000000..c320c99 --- /dev/null +++ b/deployment/packmate_remote.py @@ -0,0 +1,514 @@ +#!/usr/bin/env python3 +"""Operator-side SSH deployment of existing Packmate host LIVE, including offline images. + +Python runs ONLY on the operator workstation. The target needs native Linux +amd64, local rootful Docker/Compose, sh, tar, ip, ss, stat, df and sha256sum. +No package installs, remote pulls, firewall changes or foreign cleanup. +""" +from __future__ import annotations + +import argparse +import contextlib +import hashlib +import importlib.util +import io +import json +import os +from pathlib import Path, PurePosixPath +import re +import secrets +import shlex +import socket +import stat +import subprocess +import sys +import tarfile +import time + +SPEC = importlib.util.spec_from_file_location("remote_host_live", Path(__file__).with_name("packmate_host.py")) +host = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(host) +kit, shared, Error = host.kit, host.shared, host.Error +SCHEMA = "durkahelper.packmate-remote.v1" +REFS = {"packmate": kit.PACKMATE, "db": kit.PACKMATE_DB} +DEFAULT = "local/packmate-remote.json" + + +def ssh_settings(value): + if not isinstance(value, dict) or set(value) != {"target", "port", "key", "known_hosts", "docker"}: + raise Error("invalid SSH settings") + if not isinstance(value["target"], str) or not re.fullmatch(r"[a-z_][a-z0-9_-]{0,31}@[A-Za-z0-9][A-Za-z0-9.-]{0,252}", value["target"]): + raise Error("SSH target must be USER@HOST, not a command") + if type(value["port"]) is not int or not 1 <= value["port"] <= 65535: + raise Error("invalid SSH port") + for field in ("key", "known_hosts"): + if value[field] is not None and (not isinstance(value[field], str) or not Path(value[field]).is_absolute()): + raise Error("SSH key and known_hosts paths must be absolute") + if not isinstance(value["docker"], str) or not re.fullmatch(r"(?:docker|/[A-Za-z0-9_./-]+)", value["docker"]): + raise Error("Docker must be docker or an absolute approved wrapper path; no shell commands") + return value + + +def remote_path(value): + if not isinstance(value, str) or not re.fullmatch(r"/(?:home/[a-z_][a-z0-9_-]*|root)/[A-Za-z0-9_.-]+(?:/[A-Za-z0-9_.-]+)*", value): + raise Error("use a dedicated absolute directory below /home/USER or /root") + if any(part in {".", ".."} for part in value.split("/")): + raise Error("remote directory traversal is forbidden") + return PurePosixPath(value) + + +def settings(value): + if not isinstance(value, dict) or set(value) != {"schema", "ssh", "workspace", "project", "profile", "credentials", "images"} or value["schema"] != SCHEMA: + raise Error("invalid remote LIVE configuration") + ssh_settings(value["ssh"]) + remote_path(value["workspace"]) + user = value["ssh"]["target"].split("@", 1)[0] + prefix = "/root/" if user == "root" else "/home/" + user + "/" + if not value["workspace"].startswith(prefix): + raise Error("workspace must be inside the SSH user's own home directory") + if not re.fullmatch(r"dh-host-[a-f0-9]{12}", value.get("project", "")): + raise Error("invalid owned project") + host.profile(value["profile"]) + host.live.credentials(value["credentials"]) + if value["images"] is not None: + host.image_ids(value["images"]) + return value + + +def private_config(path): + path = kit.safe_path(path) + metadata = path.stat() + if os.name == "posix" and (metadata.st_uid != os.getuid() or metadata.st_mode & 0o077): + raise Error("local LIVE config must be owned and mode 0600") + return path, settings(kit.load(path)) + + +def write_config(path, value, replace=False): + path = kit.safe_path(path) + path.parent.mkdir(mode=0o700, parents=True, exist_ok=True) + if not replace: + shared.write(path, shared.canonical(value)) + return + temporary = path.with_name(path.name + "." + secrets.token_hex(6) + ".tmp") + shared.write(temporary, shared.canonical(value)) + os.replace(temporary, path) + + +class SSH: + def __init__(self, config): + self.config = ssh_settings(config) + + def argv(self): + value = self.config + args = ["ssh", "-T", "-p", str(value["port"]), "-o", "BatchMode=yes", "-o", "StrictHostKeyChecking=yes", + "-o", "UpdateHostKeys=no", "-o", "PermitLocalCommand=no", + "-o", "ConnectTimeout=8", "-o", "ServerAliveInterval=10", "-o", "ServerAliveCountMax=2"] + if value["key"]: + args += ["-i", value["key"], "-o", "IdentitiesOnly=yes"] + if value["known_hosts"]: + args += ["-o", "UserKnownHostsFile=" + value["known_hosts"]] + return args + + def shell(self, script, data=None, stream=None, timeout=60): + try: + result = subprocess.run(self.argv() + [self.config["target"], script], input=data, + stdin=stream if stream is not None else (subprocess.DEVNULL if data is None else None), + stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, timeout=timeout, check=False) + except (OSError, subprocess.SubprocessError) as error: + raise Error("SSH unavailable or timed out; partial owned state is retained") from error + if result.returncode or len(result.stdout) > 1024 * 1024: + raise Error("SSH operation failed; check host trust, ssh-agent, approved wrapper and target prerequisites; raw output suppressed") + return result.stdout + + def checked(self, argv, cwd=None, timeout=60, capture=False, environment=None): + if argv[0] not in {"docker", "ip"} or cwd is not None or environment is not None: + raise Error("unlisted remote operation") + command = ([self.config["docker"]] + argv[1:]) if argv[0] == "docker" else argv + raw = self.shell('test -z "${DOCKER_HOST}${DOCKER_CONTEXT}${DOCKER_TLS_VERIFY}${DOCKER_CERT_PATH}" && ' + shlex.join(command), timeout=timeout) + return raw if capture else b"" + + @contextlib.contextmanager + def route(self): + original = shared.checked + shared.checked = self.checked + try: + yield + finally: + shared.checked = original + + def engine(self): + raw = self.shell("set -eu; test -S /var/run/docker.sock; test ! -L /var/run/docker.sock; " + "stat -c %u /var/run/docker.sock; uname -s; uname -m; uname -r").decode().splitlines() + if len(raw) != 4 or raw[:2] != ["0", "Linux"] or raw[2] not in {"x86_64", "amd64"}: + raise Error("native Linux amd64 with root-owned Docker socket required") + endpoint = json.loads(self.checked(["docker", "context", "inspect", "--format", "{{json .Endpoints.docker}}"], capture=True)) + info = json.loads(self.checked(["docker", "info", "--format", "{{json .}}"], capture=True)) + if (endpoint.get("Host") != "unix:///var/run/docker.sock" or info.get("KernelVersion") != raw[3] or + info.get("OSType") != "linux" or info.get("Architecture") not in {"x86_64", "amd64"} or + "docker desktop" in info.get("OperatingSystem", "").lower() or + any("rootless" in item.lower() for item in info.get("SecurityOptions", []))): + raise Error("local native rootful Engine required; Desktop/remote Docker contexts unsupported") + compose = self.checked(["docker", "compose", "version", "--short"], capture=True).decode().strip() + if not re.fullmatch(r"v?2\.[0-9]+\.[0-9]+(?:[A-Za-z0-9_.+-]*)", compose): + raise Error("Docker Compose v2 required") + info["durka_compose_version"] = compose + return info + + +def inspect_images(check, refs, *, platform=None): + images = {} + for name, reference in refs.items(): + command = ["docker", "image", "inspect"] + if platform is not None: + command += ["--platform", platform] + row = check(command + ["--format", "{{.Id}};{{.Os}};{{.Architecture}}", reference], capture=True).decode().strip().split(";") + if len(row) != 3 or not re.fullmatch(r"sha256:[a-f0-9]{64}", row[0]) or row[1:] != ["linux", "amd64"]: + raise Error("cached image missing or not Linux amd64; prepare the offline bundle first") + if reference.startswith("sha256:") and row[0] != reference: + raise Error("cached image identity changed") + images[name] = row[0] + return host.image_ids(images) + + +def digest_file(path): + path = kit.safe_path(path) + before = path.stat() + if not stat.S_ISREG(before.st_mode) or before.st_size > 8 * 1024**3: + raise Error("image archive must be a regular file at most 8 GiB") + digest = hashlib.sha256() + with path.open("rb") as stream: + for block in iter(lambda: stream.read(1024 * 1024), b""): + digest.update(block) + stamp = lambda item: (item.st_dev, item.st_ino, item.st_size, item.st_mtime_ns, item.st_ctime_ns) + if stamp(path.stat()) != stamp(before): + raise Error("image archive changed while reading") + return path, digest.hexdigest() + + +def bundle(path): + root = kit.safe_path(path) + value = kit.load(root / "manifest.json") + if (not isinstance(value, dict) or set(value) != {"schema", "refs", "images", "sha256"} or + value["schema"] != "durkahelper.packmate-images.v1" or value["refs"] != REFS): + raise Error("bundle is not for the retained pinned Packmate/PostgreSQL pair") + host.image_ids(value["images"]) + archive, checksum = digest_file(root / "images.tar") + if checksum != value["sha256"]: + raise Error("offline archive checksum mismatch; do not load") + return archive, value["images"] + + +def make_bundle(args): + root = kit.safe_path(args.output) + if root.exists(): + raise Error("bundle output must be a new directory; existing files are preserved") + if not args.apply: + return {"status": "NOT_RUN", "action": "bundle", "downloads": bool(args.download)} + root.mkdir(mode=0o700, parents=True) + if args.download: + for reference in REFS.values(): + shared.checked(["docker", "pull", "--platform", "linux/amd64", reference], timeout=900) + # Multi-platform stores on ARM Macs retain both PostgreSQL variants. Pulling + # AMD64 does not change the native default used by image inspect or save. + images = inspect_images(shared.checked, REFS, platform="linux/amd64") + # Containerd may expose a platform child ID through inspect without making + # that ID addressable by save. Resolve the retained digest-pinned names and + # let the exporter select the verified AMD64 variant; never use floating tags. + shared.checked(["docker", "image", "save", "--platform", "linux/amd64", "--output", str(root / "images.tar"), *REFS.values()], timeout=900) + (root / "images.tar").chmod(0o600) + _, checksum = digest_file(root / "images.tar") + shared.write(root / "manifest.json", shared.canonical({"schema": "durkahelper.packmate-images.v1", "refs": REFS, + "images": images, "sha256": checksum})) + return {"status": "PASS", "action": "bundle", "offline_bundle": str(root), "target_platform": "linux/amd64"} + + +def init(args): + path = kit.safe_path(args.config) + if path.exists(): + raise Error("LIVE config already exists; no overwrite") + ssh = ssh_settings({"target": args.host, "port": args.ssh_port, "key": str(Path(args.key).expanduser().absolute()) if args.key else None, + "known_hosts": str(Path(args.known_hosts).expanduser().absolute()) if args.known_hosts else None, "docker": args.docker}) + remote_path(args.remote_dir) + if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,14}", args.interface or "") or args.interface == "any": + raise Error("one approved interface is required") + client = SSH(ssh) + info = client.engine() + rows = json.loads(client.checked(["ip", "-json", "link", "show", "dev", args.interface], capture=True)) + if len(rows) != 1 or "UP" not in rows[0].get("flags", []): + raise Error("selected interface not UP") + config = host.profile({"schema": host.SCHEMA, "daemon_id": info["ID"], "interface": args.interface, + "ifindex": rows[0]["ifindex"], "interface_mac": rows[0]["address"], "local_ip": args.service_ip, + "bind_address": args.bind, "ui_port": args.ui_port, "db_port": args.db_port, + "tcp_timeout_seconds": 30, "udp_timeout_seconds": 10, "timeout_check_seconds": 5, + "retention_minutes": 60, "cleanup_interval_minutes": 1}) + value = {"schema": SCHEMA, "ssh": ssh, "workspace": args.remote_dir, "project": "dh-host-" + secrets.token_hex(6), + "profile": config, "credentials": {"username": "operator", "password": secrets.token_hex(24), + "db_password": secrets.token_hex(24)}, "images": None} + write_config(path, settings(value)) + return {"status": "PASS", "action": "init", "config": str(path), "remote_changed": False, + "interface": config["interface"], "next": "doctor; then up with explicit capture approvals"} + + +def discover(args): + """Read-only target doctor before a local configuration exists.""" + client = SSH({"target": args.host, "port": args.ssh_port, "key": str(Path(args.key).expanduser().absolute()) if args.key else None, + "known_hosts": str(Path(args.known_hosts).expanduser().absolute()) if args.known_hosts else None, "docker": args.docker}) + for port in (args.ui_port, args.db_port): + if type(port) is not int or not 1024 <= port <= 65535: + raise Error("doctor ports must be between 1024 and 65535") + if args.interface and (not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,14}", args.interface) or args.interface == "any"): + raise Error("doctor requires an ordinary interface name, not any") + info = client.engine() + rows = json.loads(client.checked(["ip", "-json", "address", "show"] + (["dev", args.interface] if args.interface else []), capture=True)) + interfaces = [{"name": row["ifname"], "index": row["ifindex"], "mac": row.get("address"), "up": "UP" in row.get("flags", []), + "ipv4": [item["local"] for item in row.get("addr_info", []) if item.get("family") == "inet"]} for row in rows] + disk_path = remote_path(args.remote_dir) if args.remote_dir else PurePosixPath("/home/" + args.host.split("@", 1)[0]) + raw = client.shell(path_guard(disk_path) + "for x in sh tar ip ss stat df sha256sum cut awk; do command -v $x >/dev/null; done; " + "awk '/MemAvailable:/ {print $2}' /proc/meminfo; p=" + shlex.quote(str(disk_path)) + "; " + 'while test ! -d "$p"; do p=${p%/*}; test -n "$p" || p=/; done; df -Pk "$p" | awk \'NR==2 {print $4}\'').decode().split() + available, disk = [int(item) for item in raw] + ports = client.shell("ss -H -ltn '( sport = :" + str(args.ui_port) + " or sport = :" + str(args.db_port) + " )'").strip() + images = "CACHED_AMD64_VERIFIED" + try: + inspect_images(client.checked, REFS) + except Error: + images = "MISSING_OR_WRONG_PLATFORM" + blockers = [] + if ports: + blockers.append("requested_ports_occupied") + if available < 3072 * 1024: + blockers.append("available_ram_below_3_gib") + if disk < 5 * 1024**2: + blockers.append("free_disk_below_5_gib") + if args.interface and not any(row["up"] for row in interfaces): + blockers.append("selected_interface_not_up") + return {"status": "BLOCKED" if blockers else ("WARNING" if images != "CACHED_AMD64_VERIFIED" else "PASS"), "blockers": blockers, + "action": "doctor", "read_only": True, "engine_id": info["ID"], "engine": "native-linux-amd64", + "linux": info.get("OperatingSystem"), "kernel": info.get("KernelVersion"), "docker_version": info.get("ServerVersion"), + "compose_version": info.get("durka_compose_version"), "cpus": info.get("NCPU"), + "interfaces": interfaces, "available_ram_mib": available // 1024, "free_disk_mib": disk // 1024, + "requested_ports": {"ui": args.ui_port, "db_loopback": args.db_port, "occupied": bool(ports)}, + "images": images, "python_on_target": "NOT_REQUIRED", "capture_permission": "NOT_VERIFIED", + "next": "choose the permitted interface/service IP/UI bind; resolve ports/resources; init config; prepare offline bundle if needed", + "traffic_visibility": "NOT_VERIFIED: network placement and a known request/response must be checked manually"} + + +def path_guard(root): + # Reject symlink ancestors before ANY reads/writes in the target directory. + return "set -eu; " + "; ".join("test ! -L " + shlex.quote(str(parent)) for parent in [*reversed(root.parents), root]) + "; " + + +def files(value): + state = {"schema": host.SCHEMA, "project": value["project"], "profile": value["profile"], "credentials": value["credentials"]} + return {"state.json": shared.canonical(state), "images.json": shared.canonical(value["images"]), + "runtime-compose.json": shared.canonical(host.compose_spec(value["profile"], value["credentials"], value["project"], value["images"])), + "application.properties": host.properties(value["profile"], value["credentials"])} + + +def verify_workspace(client, value): + root = remote_path(value["workspace"]) + script = path_guard(root) + "if test ! -e " + shlex.quote(str(root)) + "; then printf MISSING; else " + script += "test -d " + shlex.quote(str(root)) + "; test \"$(stat -c %u:%a " + shlex.quote(str(root)) + ")\" = \"$(id -u):700\"; " + for name, content in files(value).items(): + path = shlex.quote(str(root / name)) + mode = "644" if name == "application.properties" else "600" + script += "test -f " + path + "; test ! -L " + path + "; " + script += "test \"$(stat -c %u:%a:%h " + path + ")\" = \"$(id -u):" + mode + ":1\"; " + script += "test \"$(sha256sum " + path + " | cut -d ' ' -f 1)\" = " + hashlib.sha256(content).hexdigest() + "; " + for name in ("data", "data/postgres"): + script += "test -d " + shlex.quote(str(root / name)) + "; test ! -L " + shlex.quote(str(root / name)) + "; " + script += "printf PRESENT; fi" + return client.shell(script).decode() == "PRESENT" + + +def upload(client, value): + root = remote_path(value["workspace"]) + payload = io.BytesIO() + with tarfile.open(fileobj=payload, mode="w") as archive: + for name, content in files(value).items(): + entry = tarfile.TarInfo(name) + entry.size, entry.mode = len(content), 0o644 if name == "application.properties" else 0o600 + archive.addfile(entry, io.BytesIO(content)) + script = path_guard(root) + "umask 077; test ! -e " + shlex.quote(str(root)) + "; " + script += "mkdir -p " + shlex.quote(str(root.parent)) + "; mkdir " + shlex.quote(str(root)) + "; " + script += "tar -xf - -C " + shlex.quote(str(root)) + "; chmod 644 " + shlex.quote(str(root / "application.properties")) + "; " + script += "mkdir -p " + shlex.quote(str(root / "data/postgres")) + client.shell(script, data=payload.getvalue()) + if not verify_workspace(client, value): + raise Error("remote transfer incomplete; retain partial workspace for inspection") + + +def doctor(client, value): + info = client.engine() + if info["ID"] != value["profile"]["daemon_id"]: + raise Error("approved Docker Engine identity changed; review before reinitializing") + host.interface(value["profile"]) + addresses = json.loads(client.checked(["ip", "-json", "address", "show"], capture=True)) + if not any(item.get("local") == value["profile"]["bind_address"] and item.get("family") == "inet" + for row in addresses for item in row.get("addr_info", [])): + raise Error("UI bind address is not assigned to this Linux host") + current = host.owned(remote_path(value["workspace"]), value, images=value["images"]) + if current and not verify_workspace(client, value): + raise Error("running owned resources have no matching workspace") + root = remote_path(value["workspace"]) + script = path_guard(root) + "for x in sh tar ip ss stat df sha256sum cut awk; do command -v $x >/dev/null; done; " + script += "awk '/MemAvailable:/ {print $2}' /proc/meminfo; p=" + shlex.quote(str(root)) + "; " + script += 'while test ! -d "$p"; do p=${p%/*}; test -n "$p" || p=/; done; df -Pk "$p" | awk \'NR==2 {print $4}\'' + available, disk = [int(item) for item in client.shell(script).decode().split()] + if available < (1024 if current else 3072) * 1024 or disk < 5 * 1024**2: + raise Error("insufficient free resources: need 3 GiB RAM before startup and 5 GiB disk") + ports = client.shell("ss -H -ltn '( sport = :" + str(value["profile"]["ui_port"]) + " or sport = :" + str(value["profile"]["db_port"]) + " )'").strip() + if ports and not (set(current) == {"db", "packmate"} and all(item["running"] for item in current.values())): + raise Error("requested ports are occupied; stop/reconfigure ONLY the known conflicting deployment yourself") + return {"status": "PASS", "action": "doctor", "read_only": True, "python_on_target": "NOT_REQUIRED", + "engine": "native-linux-amd64", "interface": value["profile"]["interface"], "ifindex": value["profile"]["ifindex"], + "linux": info.get("OperatingSystem"), "kernel": info.get("KernelVersion"), "docker_version": info.get("ServerVersion"), + "compose_version": info.get("durka_compose_version"), "cpus": info.get("NCPU"), + "available_ram_mib": available // 1024, "free_disk_mib": disk // 1024, + "owned_services": {key: item["running"] for key, item in current.items()}, + "capture_permission": "NOT_VERIFIED until explicit approved up", "traffic_correctness": "NOT_TESTED"} + + +@contextlib.contextmanager +def tunnel(client, profile): + with socket.socket() as sock: + sock.bind(("127.0.0.1", 0)) + port = sock.getsockname()[1] + command = client.argv() + ["-N", "-o", "ExitOnForwardFailure=yes", "-L", + "127.0.0.1:" + str(port) + ":" + profile["bind_address"] + ":" + str(profile["ui_port"]), client.config["target"]] + process = subprocess.Popen(command, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + try: + for _ in range(30): + if process.poll() is not None: + raise Error("SSH readiness tunnel failed; forwarding must be permitted") + try: + with socket.create_connection(("127.0.0.1", port), timeout=0.2): + break + except OSError: + time.sleep(0.1) + else: + raise Error("SSH readiness tunnel did not open") + yield {"bind_address": "127.0.0.1", "ui_port": port} + finally: + process.terminate() + try: + process.wait(timeout=5) + except subprocess.TimeoutExpired: + process.kill() + process.wait() + + +def run(args): + if args.action == "bundle": + return make_bundle(args) + if args.action == "init": + return init(args) + if args.action == "doctor" and args.host: + return discover(args) + path, value = private_config(args.config) + if args.action == "password": + if sys.platform != "darwin": + raise Error("clipboard helper is Mac-only; use the private credentials.password field without screen sharing") + subprocess.run(["/usr/bin/pbcopy"], input=value["credentials"]["password"].encode("ascii"), check=True) + return {"status": "PASS", "action": "password", "username": value["credentials"]["username"], "password": "COPIED_NOT_PRINTED"} + if args.action in {"up", "down"} and not args.apply: + return {"status": "NOT_RUN", "action": args.action, "requires": "--apply; up also requires whole-interface and host-network approvals"} + if args.action == "up" and not (args.host_network_approved and args.interface_scope_approved): + raise Error("up requires --host-network-approved --interface-scope-approved for the configured entire interface") + client = SSH(value["ssh"]) + with client.route(): + if args.action == "down": + info = client.engine() + if info["ID"] != value["profile"]["daemon_id"] or value["images"] is None or not verify_workspace(client, value): + raise Error("down requires the original Engine and intact owned workspace") + host.owned(remote_path(value["workspace"]), value, images=value["images"]) + client.checked(host.command(remote_path(value["workspace"]), value, runtime=True) + ["down", "--timeout", "10"], timeout=90) + return {"status": "PASS", "action": "down", "data_retained": True} + report = doctor(client, value) + if args.action == "status": + return dict(report, action="status", url="http://" + value["profile"]["bind_address"] + ":" + str(value["profile"]["ui_port"])) + archive = None + if args.bundle: + archive, images = bundle(args.bundle) + else: + try: + images = inspect_images(client.checked, REFS if value["images"] is None else value["images"]) + except Error: + if args.action == "doctor": + return dict(report, status="WARNING", images="MISSING_OR_WRONG_PLATFORM", next="prepare bundle and pass --bundle; no downloads on target") + raise + if args.action == "doctor": + return dict(report, images="OFFLINE_BUNDLE_VERIFIED" if archive else "CACHED_AMD64_VERIFIED", remote_changed=False) + if value["images"] is not None and images != value["images"]: + raise Error("image identities differ from this deployment; do not upgrade implicitly") + if archive: + try: + inspect_images(client.checked, images) + except Error: + with archive.open("rb") as stream: + client.shell('test -z "${DOCKER_HOST}${DOCKER_CONTEXT}${DOCKER_TLS_VERIFY}${DOCKER_CERT_PATH}" && ' + + shlex.join([value["ssh"]["docker"], "image", "load"]), stream=stream, timeout=900) + _, rechecked = bundle(args.bundle) + if rechecked != images: + raise Error("offline bundle changed during transfer; startup blocked") + inspect_images(client.checked, images) + value["images"] = images + write_config(path, value, replace=True) + if not verify_workspace(client, value): + upload(client, value) + host.owned(remote_path(value["workspace"]), value, images=images) + host.interface(value["profile"]) + doctor(client, value) + command = host.command(remote_path(value["workspace"]), value, runtime=True) + client.checked(command + ["config", "--quiet"]) + client.checked(command + ["up", "--detach", "--no-build", "--pull", "never"], timeout=180) + with tunnel(client, value["profile"]) as endpoint: + host.live.ready(endpoint, value["credentials"]) + current = host.owned(remote_path(value["workspace"]), value, images=images) + if set(current) != {"db", "packmate"} or not all(item["running"] for item in current.values()): + raise Error("exactly two owned running services required") + return {"status": "PASS", "action": "up", "authenticated_capture_started": True, "traffic_correctness": "NOT_TESTED", + "url": "http://" + value["profile"]["bind_address"] + ":" + str(value["profile"]["ui_port"]), + "username": value["credentials"]["username"], "password_command": "durka.py traffic live password --config " + str(path), + "retention": "age cleanup, not hard disk quota", "rollback": "traffic live down --config SAME_CONFIG --apply"} + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("action", choices=["init", "doctor", "preflight", "bundle", "up", "status", "down", "password"]) + parser.add_argument("--config", default=DEFAULT, help="private remote LIVE config; separate from the local farm config") + parser.add_argument("--host", help="approved USER@HOST") + parser.add_argument("--key", help="existing SSH identity; load encrypted identities into ssh-agent first") + parser.add_argument("--known-hosts", help="existing verified known_hosts; never auto-accept host keys") + parser.add_argument("--ssh-port", type=int, default=22) + parser.add_argument("--docker", default="docker", help="docker or absolute path of existing approved wrapper") + parser.add_argument("--remote-dir", help="new dedicated directory on Linux; never overwrites existing deployment") + parser.add_argument("--interface", help="entire approved Linux capture interface, never any") + parser.add_argument("--service-ip", help="service-side IPv4 in captured traffic") + parser.add_argument("--bind", help="explicit Linux UI IPv4") + parser.add_argument("--ui-port", type=int, default=65000) + parser.add_argument("--db-port", type=int, default=55432) + parser.add_argument("--bundle", help="prepared local offline image directory") + parser.add_argument("--output", help="new local offline image directory for bundle") + for flag in ("apply", "download", "host-network-approved", "interface-scope-approved"): + parser.add_argument("--" + flag, action="store_true") + args = parser.parse_args(argv) + try: + if args.action == "preflight": + args.action = "doctor" + if args.action == "init" and not all((args.host, args.remote_dir, args.interface, args.service_ip, args.bind)): + raise Error("init requires --host --remote-dir --interface --service-ip --bind") + if args.action == "bundle" and not args.output: + raise Error("bundle requires --output NEW_DIRECTORY") + result = run(args) + print(json.dumps(result, sort_keys=True)) + return 2 if result.get("status") == "BLOCKED" else 0 + except (Error, OSError, ValueError, TypeError, KeyError, subprocess.SubprocessError, KeyboardInterrupt) as error: + print(json.dumps({"status": "BLOCKED", "action": args.action, + "reason": str(error) if isinstance(error, Error) else "operation failed (" + type(error).__name__ + "); raw details suppressed", + "rollback": "retain partial files/data; down only the matching config with --apply; no automatic removal"})) + return 2 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/deployment/profile.example.json b/deployment/profile.example.json new file mode 100644 index 0000000..dbc5cc3 --- /dev/null +++ b/deployment/profile.example.json @@ -0,0 +1,15 @@ +{ + "schema": "durkahelper.deployment-profile.v1", + "platform": {"os": "darwin", "architecture": "arm64", "runtime": "docker-desktop"}, + "bind_address": "127.0.0.1", + "ports": {"farm": 8080, "neo": 5005, "packmate": 65000}, + "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://receiver.example.invalid/flags", "SYSTEM_TOKEN": "REPLACE_WITH_PRIVATE_COMPETITION_TOKEN"}, + "submit_limit": 10, "submit_period": 2, "flag_lifetime": 300 + }, + "packmate": {"mode": "FILE", "local_ip": "192.0.2.1", "pcap_file": "capture.pcap", "interface": "", "retention_minutes": 60} +} diff --git a/deployment/recovery.py b/deployment/recovery.py new file mode 100644 index 0000000..e996a43 --- /dev/null +++ b/deployment/recovery.py @@ -0,0 +1,1306 @@ +#!/usr/bin/env python3 +"""Private native backup and quarantine restore for maintained deployments. + +Preview never contacts Docker. Apply requires an approved daemon, a snapshot +and an exclusive maintenance window. The source is NEVER resumed automatically. +Quarantine stages cannot be opened by toolkit.up; promotion is a manual gate. +""" +from __future__ import annotations + +import argparse +import copy +import hashlib +import importlib.util +import json +import os +from pathlib import Path, PurePosixPath +import re +import secrets +import stat +import struct +import subprocess +import sys +import tarfile +import threading +import time + +ROOT = Path(__file__).resolve().parents[1] + + +def module(name, path): + spec = importlib.util.spec_from_file_location(name, ROOT / path) + value = importlib.util.module_from_spec(spec) + spec.loader.exec_module(value) + return value + + +kit = module("recovery_toolkit", "deployment/toolkit.py") +bundle = module("recovery_archive", "scripts/toolchain_bundle.py") +ops = bundle.ops +Error = ops.DefenseError +SCHEMA = "durkahelper.deployment-backup.v1" +STAGE_SCHEMA = "durkahelper.deployment-recovery-stage.v1" +STAGE_VERIFY_SCHEMA = "durkahelper.deployment-recovery-verification.v1" +PROMOTION_SCHEMA = "durkahelper.deployment-promotion-plan.v1" +ACCEPTANCE_SCHEMA = "durkahelper.deployment-promotion-acceptance.v1" +LABEL = "io.durkahelper.recovery" +HELPER_LABEL = "io.durkahelper.recovery-purpose" +BACKENDS = {"postgres": "farm", "packmate-db": "packmate", "redis": None, "neo-redis": None} +WRITERS = ("neo-worker", "celery", "front", "packmate", "neo-server", "farm") +COLD = ("redis", "neo-redis", "neo") +MAX_FILE = 1024 ** 3 +MAX_TOTAL = 8 * 1024 ** 3 +MAX_FILES = 20000 +CHUNK = 1024 * 1024 +RESUME = "python3 deployment/toolkit.py up --workspace --apply --approval-id " +LIMITS = ["application-level farm/Neo/Packmate acceptance NOT_RUN", "automatic queue replay disabled", + "promotion to a live deployment requires manual review", "physical Mac and large-data RPO/RTO NOT_RUN", + "custom PostgreSQL roles/grants outside maintained credentials are not supported", "Redis TTL expiration continues during recovery"] +PROMOTION_BLOCKERS = ["component_native_data_restore", "runtime_uid_gid_mapping", + "application_acceptance", "operator_activation"] +PROMOTION_ROLLBACK = ( + "leave candidate non-runnable; keep backup and verified recovery stage stopped and unchanged" +) + + +def _promotion_acceptance_contract(): + return { + "schema": ACCEPTANCE_SCHEMA, + "checks": { + "component_native_data_restore": "PASS|FAIL", + "filesystem_ownership": "PASS|FAIL", + "farm_authenticated": "PASS|FAIL", + "neo_authenticated": "PASS|FAIL", + "packmate_file": "PASS|FAIL", + "restart_reconnect": "PASS|FAIL", + }, + "submission_enabled": False, + "worker_enabled": False, + "capture_enabled": False, + "rollback_confirmed": True, + } + + +def sha(data): + return hashlib.sha256(data).hexdigest() + + +def run(argv, *, sink=None, stdin=None, collect=True, limit=1024 * 1024, timeout=60): + """Bound output before buffering; never echo commands, credentials or stderr.""" + data, errors = bytearray(), [] + result = {"bytes": 0, "sha256": None, "prefix": b""} + digest = hashlib.sha256() + process = subprocess.Popen(argv, stdin=stdin if stdin is not None else subprocess.DEVNULL, + stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) + + def drain(): + try: + while True: + chunk = process.stdout.read(65536) + if not chunk: + break + result["bytes"] += len(chunk) + if result["bytes"] > limit: + raise Error("recovery command exceeded its byte budget") + digest.update(chunk) + if len(result["prefix"]) < 32: + result["prefix"] = (result["prefix"] + chunk)[:32] + if sink is not None: + ops._write_all(sink, chunk) + elif collect: + data.extend(chunk) + except (OSError, Error) as error: + errors.append(error) + process.kill() + + reader = threading.Thread(target=drain, daemon=True) + reader.start() + try: + code = process.wait(timeout=timeout) + reader.join(timeout=5) + if code or errors or reader.is_alive(): + raise Error("recovery command failed or exceeded bounds; output suppressed") + result["sha256"] = digest.hexdigest() + return bytes(data) if collect and sink is None else result + finally: + if process.poll() is None: + process.kill() + process.wait(timeout=5) + reader.join(timeout=5) + process.stdout.close() + + +def daemon(identity): + if not isinstance(identity, str) or not re.fullmatch(r"[A-Za-z0-9:_.-]{8,128}", identity): + raise Error("an explicitly approved Docker daemon ID is required") + if run(["docker", "info", "--format", "{{.ID}}"]).decode().strip() != identity: + raise Error("Docker daemon identity mismatch") + + +def require_apply(args): + if not args.approval_id or not re.fullmatch(r"[A-Za-z0-9_.-]{1,80}", args.approval_id): + raise Error("apply requires a non-secret approval ID") + if not args.snapshot_confirmed or not args.maintenance_confirmed: + raise Error("apply requires snapshot and exclusive maintenance confirmation") + if os.name != "posix" or os.geteuid() == 0: + raise Error("recovery mutations require a non-root POSIX operator") + daemon(args.daemon_id) + + +def require_promotion_apply(args): + """Require explicit human review without treating an acknowledgement as a health check.""" + require_apply(args) + if not getattr(args, "queue_reviewed", False) or not getattr(args, "ttl_reviewed", False): + raise Error("promotion requires explicit queue/replay and TTL-expiry review acknowledgements") + if not isinstance(getattr(args, "stage_project", None), str) or not re.fullmatch( + r"dh-recovery-[a-f0-9]{12}", args.stage_project): + raise Error("promotion requires the exact recovery stage project identity") + for name in ("target_uid", "target_gid"): + value = getattr(args, name, None) + if type(value) is not int or not 0 <= value <= 2 ** 31 - 1: + raise Error("promotion requires explicit numeric target UID and GID") + if (hasattr(os, "geteuid") and args.target_uid != os.geteuid()) or ( + hasattr(os, "getegid") and args.target_gid != os.getegid()): + raise Error("candidate owner UID/GID must match the non-root operator") + + +def private_root(path): + root = ops._canonical_root_directory(Path(path)) + if os.name == "posix" and (root.stat().st_uid != os.geteuid() or root.stat().st_mode & 0o077): + raise Error("recovery roots must be owner-only private directories") + return root + + +def new_target(path, source): + target = ops._safe_output_parent(Path(path)) + # Resolve Windows short-name aliases consistently on both sides. Validate + # the selected existing source leaf before resolving its spelling. + source = ops._canonical_input_leaf(Path(source)) + # File identities also handle an 8.3 alias on the selected source directory + # without requiring a realpath call denied by some Windows sandboxes. + boundaries = {ops._root_anchor_identity(boundary.stat()) for boundary in (source, ROOT)} + contained = any(ops._root_anchor_identity(parent.stat()) in boundaries for parent in target.parents) + if contained or target.is_relative_to(source) or source.is_relative_to(target) or target.is_relative_to(ROOT): + raise Error("destination must be new, outside source and repository") + return target + + +def source_workspace(path): + root, state, spec, profile = kit.workspace(path) + private_root(root) + runtime = maintained_runtime(root, state, spec, profile) + files = set(state["files"]) | {"deployment.json", "runtime-compose.json", "build-receipt.json"} + allowed = {"deployment.json", "compose.json", "profile.json", "model.json", "policy.json", "runtime-compose.json", "build-receipt.json", "operator-paths.json"} + if any(name not in allowed and not name.startswith(("config/", "sources/")) for name in files): + raise Error("unexpected private deployment inventory member") + return root, state, runtime, profile, sorted(files) + + +def maintained_runtime(root, state, spec, profile): + runtime = kit.check_build_receipt(root, spec) + if profile["packmate"]["mode"] != "FILE" or set(runtime["services"]) != set(BACKENDS) | set(WRITERS): + raise Error("only the maintained FILE deployment service set is supported") + if any(s.get("labels") != {kit.LABEL: state["project"]} for s in runtime["services"].values()): + raise Error("maintained deployment labels changed") + # Regeneration rejects rehashed custom Compose commands, mounts and networks. + env = spec["services"]["postgres"]["environment"] + neo_text = kit.read(root / "config/neo-client.yml").decode() + match = re.search(r'^grpc_auth_key: "([A-Za-z0-9_.-]{20,128})"$', neo_text, re.M) + pairs = dict(line.split("=", 1) for line in kit.read(root / "config/packmate.properties").decode().splitlines()) + if match is None: + raise Error("maintained Neo credentials are missing") + credentials = kit.validate_credentials({"database_password": env["POSTGRES_PASSWORD"], + "farm_password": spec["services"]["farm"]["environment"]["SERVER_PASSWORD"], "neo_key": match[1], + "packmate_user": pairs.get("packmate.web.account-login"), "packmate_password": pairs.get("packmate.web.account-password")}) + images = kit.shared.image_map(ROOT / "config/integration-images.lock.json") + if spec != kit.compose_spec(profile, credentials, state["project"], images): + raise Error("deployment differs from the maintained Compose contract") + return runtime + + +def ids(output): + values = output.decode().split() + if len(values) > 256 or any(not re.fullmatch(r"[a-f0-9]{64}", item) for item in values): + raise Error("invalid or oversized Docker resource listing") + return values + + +def exact_network_ids(name): + """List only the exact named network without inspecting substring matches.""" + output = run(["docker", "network", "ls", "--no-trunc", "--filter", "name=" + name, + "--format", "{{.ID}} {{.Name}}"]) + lines = output.decode().splitlines() + if len(lines) > 256: + raise Error("invalid or oversized Docker network listing") + result = [] + for line in lines: + fields = line.split() + if (len(fields) != 2 or not re.fullmatch(r"[a-f0-9]{64}", fields[0]) or + not re.fullmatch(r"[A-Za-z0-9_.-]{1,128}", fields[1])): + raise Error("invalid Docker network listing") + if fields[1] == name: + result.append(fields[0]) + return result + + +def _expected_network_names(project, runtime): + definitions = runtime.get("networks") + if not isinstance(definitions, dict) or not definitions: + raise Error("deployment network contract is missing") + result = {} + for logical, definition in definitions.items(): + if (not isinstance(logical, str) or not re.fullmatch(r"[a-z0-9][a-z0-9_.-]{0,62}", logical) or + not isinstance(definition, dict)): + raise Error("invalid deployment network contract") + physical = definition.get("name", project + "_" + logical) + if not isinstance(physical, str) or not re.fullmatch(r"[A-Za-z0-9_.-]{1,128}", physical): + raise Error("invalid deployment network name") + if physical in result.values(): + raise Error("duplicate deployment network name") + result[logical] = physical + return result + + +def _service_networks(service, expected): + configured = service.get("networks") + if isinstance(configured, list): + logical = configured + elif isinstance(configured, dict): + logical = list(configured) + else: + raise Error("invalid service network contract") + if len(logical) != len(set(logical)) or any(name not in expected for name in logical): + raise Error("invalid service network contract") + return {expected[name] for name in logical} + + +def owned(root, project, runtime, daemon_id, label=kit.LABEL, *, exclusive=True, + require_no_networks=False, strict_networks=False): + """Inspect only IDs/ownership/mounts; never fetch argv, environment or logs.""" + daemon(daemon_id) + listing = ["docker", "ps", "--all", "--quiet", "--no-trunc"] + if not exclusive: + listing += ["--filter", "label=com.docker.compose.project=" + project] + listed = ids(run(listing)) + result = {} + expected_paths = [str(root / "data" / name) for name in (*BACKENDS, "neo")] + fmt = ('{"id":{{json .Id}},"labels":{{json .Config.Labels}},"image":{{json .Image}},' + '"running":{{json .State.Running}},"mounts":{{json .Mounts}},' + '"networks":{{json .NetworkSettings.Networks}}}') + for identity in listed: + value = json.loads(run(["docker", "container", "inspect", "--format", fmt, identity])) + labels, mounts = value.get("labels") or {}, value.get("mounts") + if value.get("id") != identity or not isinstance(mounts, list): + raise Error("invalid container identity or mounts") + member = labels.get("com.docker.compose.project") == project + if not member: + if exclusive and any(m.get("Type") == "bind" and any( + Path(m.get("Source", "/")).is_relative_to(Path(p)) or Path(p).is_relative_to(Path(m.get("Source", "/"))) + for p in expected_paths) for m in mounts): + raise Error("database paths are shared with a non-owned container") + continue + name = labels.get("com.docker.compose.service") + if labels.get(label) != project or name not in runtime["services"] or name in result or value.get("image") != runtime["services"][name]["image"]: + raise Error("deployment container ownership or immutable image mismatch") + expected = {} + for volume in runtime["services"][name].get("volumes", []): + source, destination, *flags = volume.split(":") + if not source.startswith("./") or ".." in PurePosixPath(source).parts: + raise Error("external or non-relative maintained mount") + expected[destination] = (str(root / source[2:]), "ro" not in flags) + actual = {m["Destination"]: (m["Source"], m["RW"]) for m in mounts if m.get("Type") == "bind"} + tmpfs = {v.split(":", 1)[0] for v in runtime["services"][name].get("tmpfs", [])} + if actual != expected or any(m.get("Type") != "bind" and not (m.get("Type") == "tmpfs" and m.get("Destination") in tmpfs) for m in mounts): + raise Error("deployment mounted paths differ from the maintained workspace") + result[name] = value + expected_networks = _expected_network_names(project, runtime) + labelled = ids(run(["docker", "network", "ls", "--quiet", "--no-trunc", "--filter", + "label=com.docker.compose.project=" + project])) + exact = [] + if require_no_networks or strict_networks: + for name in expected_networks.values(): + exact.extend(exact_network_ids(name)) + network_ids = list(dict.fromkeys(labelled + exact)) + networks = {} + network_format = ('{"id":{{json .Id}},"name":{{json .Name}},"labels":{{json .Labels}},' + '"internal":{{json .Internal}},"containers":{{json .Containers}}}') + for identity in network_ids: + value = json.loads(run(["docker", "network", "inspect", "--format", network_format, identity])) + labels = value.get("labels") or {} + if (value.get("id") != identity or not isinstance(value.get("name"), str) or + identity in labelled and labels.get("com.docker.compose.project") != project or + identity in exact and value.get("name") not in expected_networks.values()): + raise Error("deployment network identity changed during inspection") + if labels.get(label) != project or labels.get("com.docker.compose.project") != project: + raise Error("deployment network ownership or membership mismatch") + if value["name"] in networks: + raise Error("deployment network name or count mismatch") + networks[value["name"]] = value + if require_no_networks and networks: + raise Error("promotion project identity already has Docker resources") + if strict_networks: + if set(result) != set(runtime["services"]) or set(networks) != set(expected_networks.values()): + raise Error("deployment network name or count mismatch") + for logical, physical in expected_networks.items(): + value = networks[physical] + expected_internal = runtime["networks"][logical].get("internal", False) + # Docker keeps a stopped container's configured network identity in + # container inspect, but removes its endpoint from network inspect + # .Containers. Bind the live endpoint set to running containers; + # the attachment identity for every stopped container is checked + # separately below. + expected_members = {container["id"] for name, container in result.items() + if container["running"] and + physical in _service_networks(runtime["services"][name], expected_networks)} + members = value.get("containers") + if (type(expected_internal) is not bool or type(value.get("internal")) is not bool or + value["internal"] is not expected_internal or not isinstance(members, dict) or + set(members) != expected_members): + raise Error("deployment network isolation or membership mismatch") + by_id = {value["id"]: name for name, value in networks.items()} + for name, container in result.items(): + attachments = container.get("networks") + expected_attachments = _service_networks(runtime["services"][name], expected_networks) + if not isinstance(attachments, dict) or set(attachments) != expected_attachments: + raise Error("deployment container network attachment mismatch") + if any(not isinstance(value, dict) or by_id.get(value.get("NetworkID")) != physical + for physical, value in attachments.items()): + raise Error("deployment container network identity mismatch") + elif any(not set(value.get("containers") or {}) <= {v["id"] for v in result.values()} + for value in networks.values()): + raise Error("deployment network ownership or membership mismatch") + return result + + +def wait_strict_owned(context, timeout=10.0): + """Wait briefly for Compose endpoint metadata to converge after `up`.""" + deadline = time.monotonic() + timeout + while True: + try: + return owned(*context, exclusive=False, strict_networks=True) + except Error: + if time.monotonic() >= deadline: + raise Error("recovery project network state did not converge") + time.sleep(0.1) + + +def stop(source, names, *, exclusive=True, strict_networks=False): + root, project, runtime, identity, label = source + current = owned(root, project, runtime, identity, label, exclusive=exclusive, + strict_networks=strict_networks) + selected = [current[name]["id"] for name in names if name in current and current[name]["running"]] + if selected: + run(["docker", "stop", "--time", "20"] + selected, timeout=90) + after = owned(root, project, runtime, identity, label, exclusive=exclusive, + strict_networks=strict_networks) + if any(after.get(name, {}).get("running") for name in names): + raise Error("owned service did not stop; source must remain quiesced") + + +def pg_summary(identity, database): + base = ["docker", "exec", identity, "psql", "-X", "-v", "ON_ERROR_STOP=1", "-A", "-t", "-U", database, "-d", database, "-c"] + names = run(base + ["SELECT table_name FROM information_schema.tables WHERE table_schema='public' AND table_type='BASE TABLE' ORDER BY table_name;"]).decode().split() + # S4DFarm creates its public tables lazily, so an initialized PostgreSQL + # database can legitimately have no application tables yet. + if len(names) > 256 or any(not re.fullmatch(r"[a-z_][a-z0-9_]{0,62}", name) for name in names): + raise Error("unsupported application database schema") + result = {} + for name in names: + value = run(base + ['COPY (SELECT row_to_json(t)::text FROM "' + name + '" t ORDER BY row_to_json(t)::text) TO STDOUT;'], collect=False, limit=MAX_FILE, timeout=120) + result[name] = {"bytes": value["bytes"], "sha256": value["sha256"]} + return result + + +def stream_file(staging, name, argv): + fd = staging.open_new_file(name) + try: + result = run(argv, sink=fd, collect=False, limit=MAX_FILE, timeout=300) + os.fsync(fd) + staging._finalize_file_record(name, fd) + return result + finally: + os.close(fd) + + +def cleanup_helpers(project, daemon_id, name=None): + daemon(daemon_id) + pattern = r"dh-cold-[a-f0-9]{24}" + if name is not None and not re.fullmatch(pattern, name): + raise Error("invalid registered recovery helper name") + argv = ["docker", "ps", "--all", "--quiet", "--no-trunc"] + argv += (["--filter", "name=^/" + name + "$"] if name else + ["--filter", "label=" + LABEL + "=" + project, "--filter", "label=" + HELPER_LABEL + "=cold-read"]) + found = ids(run(argv)) + if len(found) > (1 if name else 16): + raise Error("unexpected recovery helper listing") + template = '{"id":{{json .Id}},"name":{{json .Name}},"owner":{{json (index .Config.Labels "' + LABEL + '")}},"purpose":{{json (index .Config.Labels "' + HELPER_LABEL + '")}}}' + for identity in found: + value = json.loads(run(["docker", "inspect", "--format", template, identity])) + actual_name = value.get("name") + if (value.get("id") != identity or value.get("owner") != project or value.get("purpose") != "cold-read" or + not isinstance(actual_name, str) or not re.fullmatch("/" + pattern, actual_name) or + name is not None and actual_name != "/" + name): + raise Error("recovery helper ownership mismatch; cleanup refused") + run(["docker", "rm", "--force", identity], timeout=20) + + +def helper(root, project, image, directory, daemon_id, *, staging=None, check=False): + if directory not in COLD: + raise Error("unsupported cold-copy directory") + daemon(daemon_id) + source = kit.safe_path(root / "data" / directory) + if source != root / "data" / directory or (root / "data").is_symlink() or root.is_symlink() or source.is_symlink() or not source.is_dir(): + raise Error("cold-copy source must be a real owned directory") + name = "dh-cold-" + secrets.token_hex(12) + argv = ["docker", "create", "--name", name, "--label", LABEL + "=" + project, + "--label", HELPER_LABEL + "=cold-read", "--network", "none", "--read-only", + "--cap-drop=ALL", "--cap-add=DAC_READ_SEARCH", "--security-opt=no-new-privileges:true", "--memory=128m", + "--cpus=0.5", "--pids-limit=32", "--log-driver=none", "--pull=never", + "--mount", "type=bind,src=" + str(source) + ",dst=/data,readonly", "--entrypoint", + "redis-check-rdb" if check else "tar", image] + argv += ["/data/dump.rdb"] if check else ["-C", "/data", "-cf", "-", "."] + # Register the name before create; an interrupted CLI may still create the + # daemon-side container. Reconcile ownership even without a returned ID. + try: + identity = run(argv).decode().strip() + if not re.fullmatch(r"[a-f0-9]{64}", identity): + raise Error("cold helper creation returned an invalid identity") + if check: + run(["docker", "start", "--attach", identity]) + return None + return stream_file(staging, "cold/" + directory + ".tar", ["docker", "start", "--attach", identity]) + finally: + cleanup_helpers(project, daemon_id, name) + + +def cold_members(path, *, staging=None, directory=None, source_root=None, expected=None): + """Validate the whole tar before any bounded descriptor-anchored extraction.""" + result, total = {}, 0 + path = Path(path) + source_root = path.parent if source_root is None else source_root + relative = path.relative_to(source_root).as_posix() + fd = ops._open_anchored_regular(source_root, relative, ops._root_anchor_identity(source_root.stat())) + with os.fdopen(fd, "rb") as stream: + before = os.fstat(fd) + if before.st_size > MAX_FILE: + raise Error("cold backup archive exceeds bounds") + digest = hashlib.sha256() + for chunk in iter(lambda: stream.read(CHUNK), b""): + digest.update(chunk) + if expected is not None and expected != {"bytes": before.st_size, "sha256": digest.hexdigest()}: + raise Error("cold backup changed before use") + stream.seek(0) + bundle._preflight_image_tar(stream) + with tarfile.open(fileobj=stream, mode="r:") as archive: + for member in archive: + name = member.name[2:] if member.name.startswith("./") else member.name + if name in {"", "."} and member.isdir(): + continue + normalized = PurePosixPath(name) + if (name in {"", ".", ".."} or normalized.is_absolute() or normalized.as_posix() != name or ".." in normalized.parts or + "\\" in name or ":" in name or name in result or not (member.isfile() or member.isdir()) or member.issparse()): + raise Error("unsafe cold backup archive member") + if member.isdir(): + continue + total += member.size + if total > MAX_FILE or len(result) >= MAX_FILES: + raise Error("cold backup exceeds bounds") + digest, prefix = hashlib.sha256(), b"" + with archive.extractfile(member) as source: + while True: + chunk = source.read(CHUNK) + if not chunk: + break + digest.update(chunk) + prefix = (prefix + chunk)[:32] + result[name] = {"bytes": member.size, "sha256": digest.hexdigest()} + if name == "dump.rdb" and not prefix.startswith(b"REDIS"): + raise Error("Redis native snapshot header missing") + if name == "db.db" and (len(prefix) < 24 or struct.unpack_from(" MAX_TOTAL or len(result) >= MAX_FILES: + raise Error("private recovery inventory exceeds bounds") + result[name] = {"bytes": metadata.st_size, "sha256": digest} + return result + + +def backup(args): + root, state, runtime, profile, files = source_workspace(args.workspace) + target = new_target(args.output, root) + if not args.apply: + return {"status": "NOT_RUN", "action": "backup", "effects": ["pause capture and writers", "native PG/Redis snapshots", "cold Neo/Redis state", "private source/config/receipt copy"], "source_auto_resume": False} + require_apply(args) + kit.check_build_receipt(root, kit.load(root / "compose.json"), kit.image_preflight(runtime, profile)) + # Retry also reconciles helpers whose create completed after interruption. + cleanup_helpers(state["project"], args.daemon_id) + source = (root, state["project"], runtime, args.daemon_id, kit.LABEL) + anchor = ops._root_anchor_identity(root.stat()) + current = owned(*source) + if any(name not in current or not current[name]["running"] for name in BACKENDS): + raise Error("native backup requires all four owned database services running") + staging = ops._StagingDirectory.create(target, ".native-backup-") + started = time.monotonic() + try: + stop(source, WRITERS) + current = owned(*source) + summaries = {} + for name, database in BACKENDS.items(): + identity = current[name]["id"] + if database: + summaries[name] = pg_summary(identity, database) + result = stream_file(staging, "dumps/" + name + ".dump", ["docker", "exec", identity, "pg_dump", "-U", database, "-d", database, + "--format=custom", "--compress=0", "--no-owner", "--no-privileges"]) + if not result["prefix"].startswith(b"PGDMP") or summaries[name] != pg_summary(identity, database): + raise Error("native dump invalid or quiesced database changed") + elif run(["docker", "exec", identity, "redis-cli", "--raw", "SAVE"]).strip() != b"OK": + raise Error("native Redis SAVE failed") + stop(source, BACKENDS) + cold = {} + for directory in COLD: + if root.is_symlink() or ops._root_anchor_identity(root.stat()) != anchor: + raise Error("source workspace identity changed during backup") + owned(*source) + if directory != "neo": + helper(root, state["project"], runtime["services"]["redis"]["image"], directory, args.daemon_id, check=True) + helper(root, state["project"], runtime["services"]["redis"]["image"], directory, args.daemon_id, staging=staging) + cold[directory] = cold_members(staging.path / "cold" / (directory + ".tar"), directory=directory, source_root=staging.path) + total = [0, MAX_TOTAL] + for name in files: + _metadata, digest = ops._copy_stable(root, name, (staging, "private/" + name), MAX_FILE, total, anchor) + if name in state["files"] and digest != state["files"][name]: + raise Error("source immutable file changed before backup") + source_workspace(root) + if any(item["running"] for item in owned(*source).values()): + raise Error("source resumed during backup; no complete backup published") + manifest = {"schema": SCHEMA, "source_project": state["project"], "daemon_id": args.daemon_id, + "files": inventory(staging), "cold": cold, "databases": summaries, "source_quiesced": True} + staging.write_new_bytes("backup.json", ops._canonical(manifest)) + ops._publish_directory(staging, target) + finally: + staging.cleanup() + return {"status": "PASS", "action": "backup", "capture_paused": True, "source_left_quiesced": True, + "resume": RESUME, "warning": "review protocols and expired queues before separately enabling submission/worker", + "private_only": True, "backup_seconds": round(time.monotonic() - started, 3), "limits": LIMITS} + + +def verify_backup(path): + root = private_root(path) + value, _ = ops._read_json(root / "backup.json", 8 * 1024 * 1024) + fields = {"schema", "source_project", "daemon_id", "files", "cold", "databases", "source_quiesced"} + ops._strict_keys(value, fields, fields, "native backup") + if (value["schema"] != SCHEMA or value["source_quiesced"] is not True or + not re.fullmatch(r"dh-deploy-[a-f0-9]{12}", value["source_project"]) or not isinstance(value["files"], dict) or + not isinstance(value["daemon_id"], str) or not re.fullmatch(r"[A-Za-z0-9:_.-]{8,128}", value["daemon_id"]) or + not 1 <= len(value["files"]) <= MAX_FILES or set(value["cold"]) != set(COLD) or set(value["databases"]) != {"postgres", "packmate-db"}): + raise Error("invalid private recovery manifest") + anchor, total = ops._root_anchor_identity(root.stat()), 0 + for name, expected in value["files"].items(): + ops._portable_relative_posix(name, "backup member") + if not name.startswith(("private/", "dumps/", "cold/")) or set(expected) != {"bytes", "sha256"}: + raise Error("invalid native backup member") + metadata, digest = ops._hash_anchored_regular(root, name, anchor, MAX_FILE) + total += metadata.st_size + if expected != {"bytes": metadata.st_size, "sha256": digest} or total > MAX_TOTAL: + raise Error("native backup checksum or byte budget mismatch") + required = {"dumps/postgres.dump", "dumps/packmate-db.dump", "private/compose.json", "private/profile.json", + "private/build-receipt.json", "private/runtime-compose.json", "private/deployment.json"} | {"cold/" + d + ".tar" for d in COLD} + if not required <= set(value["files"]): + raise Error("native backup inventory incomplete") + for directory in COLD: + relative = "cold/" + directory + ".tar" + if cold_members(root / relative, directory=directory, source_root=root, expected=value["files"][relative]) != value["cold"][directory]: + raise Error("cold state inventory mismatch") + actual, entries = set(), 0 + for base, directories, names in os.walk(root, followlinks=False): + for name in directories + names: + entries += 1 + if entries > MAX_FILES * 2: + raise Error("recovery filesystem inventory exceeds bounds") + p = Path(base) / name + mode = p.lstat().st_mode + if not (stat.S_ISDIR(mode) or stat.S_ISREG(mode)): + raise Error("unexpected recovery filesystem entry") + if stat.S_ISREG(mode): + actual.add(p.relative_to(root).as_posix()) + if actual != set(value["files"]) | {"backup.json"}: + raise Error("unlisted private recovery files") + state = kit.load(root / "private/deployment.json") + if state.get("source_pins") != kit.shared.PINS or state.get("project") != value["source_project"]: + raise Error("backup source provenance mismatch") + maintained_runtime(root / "private", state, kit.load(root / "private/compose.json"), kit.validate_profile(kit.load(root / "private/profile.json"))) + for name, digest in state["files"].items(): + if value["files"].get("private/" + name, {}).get("sha256") != digest: + raise Error("backup private source/config provenance mismatch") + return root, value + + +def _stage_verification_payload(state, checks): + body = {"schema": STAGE_VERIFY_SCHEMA, "project": state["project"], + "daemon_id": state["daemon_id"], "backup_sha256": state["backup_sha256"], + "compose_sha256": state["compose_sha256"], "stage_stopped": True, + "writers_enabled": False, "checks": dict(sorted(checks.items()))} + return dict(body, verification_sha256=sha(ops._canonical(body))) + + +def write_stage_verification(root, state, checks): + """Publish a no-replace verification only after restore checks and a stopped-state inspection.""" + if set(checks) != set(BACKENDS) or not all(value is True for value in checks.values()): + raise Error("a complete successful native check set is required") + root = private_root(root) + payload = ops._canonical(_stage_verification_payload(state, checks)) + if os.name != "posix" or not hasattr(os, "O_DIRECTORY") or not hasattr(os, "O_NOFOLLOW"): + raise Error("secure stage verification publication requires POSIX directory descriptors") + before = ops._root_anchor_identity(root.stat()) + directory = os.open(root, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW) + temporary = ".recovery-verification-" + secrets.token_hex(16) + ".tmp" + final = "recovery-verification.json" + descriptor = None + temporary_anchor = None + committed = False + try: + if ops._root_anchor_identity(os.fstat(directory)) != before: + raise Error("recovery stage changed before verification publication") + descriptor = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL | + os.O_NOFOLLOW, 0o600, dir_fd=directory) + created = os.fstat(descriptor) + if not stat.S_ISREG(created.st_mode): + raise Error("recovery verification staging file is not regular") + temporary_anchor = ops._root_anchor_identity(created) + ops._write_all(descriptor, payload) + os.fchmod(descriptor, 0o600) + os.fsync(descriptor) + metadata = os.fstat(descriptor) + named = os.stat(temporary, dir_fd=directory, follow_symlinks=False) + if (not stat.S_ISREG(metadata.st_mode) or ops._stat_identity(metadata) != ops._stat_identity(named) or + stat.S_IMODE(metadata.st_mode) != 0o600 or + ops._root_anchor_identity(root.stat()) != before): + raise Error("recovery verification file changed during publication") + os.close(descriptor) + descriptor = None + # Complete every fallible validation and durability operation before + # the hard-link commit. link(2) is atomic and cannot replace an + # existing attestation. + os.fsync(directory) + try: + os.link(temporary, final, src_dir_fd=directory, dst_dir_fd=directory, + follow_symlinks=False) + except BaseException: + # Reconcile an interrupted link: if the final name is our exact + # inode, publication committed and must report success. + try: + published = os.stat(final, dir_fd=directory, follow_symlinks=False) + except OSError: + raise + if (not stat.S_ISREG(published.st_mode) or + ops._root_anchor_identity(published) != temporary_anchor): + raise + committed = True + else: + committed = True + finally: + if descriptor is not None: + try: + os.close(descriptor) + except OSError: + pass + if temporary_anchor is not None: + try: + named = os.stat(temporary, dir_fd=directory, follow_symlinks=False) + if ops._root_anchor_identity(named) == temporary_anchor: + os.unlink(temporary, dir_fd=directory) + except OSError: + pass + if committed: + # The link is the commit point. Durability and removal of the + # temporary name are best-effort after that point so a complete, + # acceptable final attestation is never reported as a failure. + try: + os.fsync(directory) + except OSError: + pass + try: + os.close(directory) + except OSError: + if not committed: + raise + + +def verify_stage(path, manifest, runtime, profile, expected_project=None): + """Verify restore attestation/spec/private files; DB directory bytes are not re-hashed.""" + root = private_root(path) + state, _ = ops._read_json(root / "recovery-stage.json", 1024 * 1024) + fields = {"schema", "project", "daemon_id", "compose_sha256", "backup_sha256"} + ops._strict_keys(state, fields, fields, "recovery stage") + project = state["project"] + if (state["schema"] != STAGE_SCHEMA or not isinstance(project, str) or + not re.fullmatch(r"dh-recovery-[a-f0-9]{12}", project) or + expected_project is not None and project != expected_project or + state["daemon_id"] != manifest.get("daemon_id") or + state["backup_sha256"] != sha(ops._canonical(manifest))): + raise Error("recovery stage identity or backup binding mismatch") + spec, _ = ops._read_json(root / "recovery-compose.json", 8 * 1024 * 1024) + expected_spec = stage_spec(runtime, project) + if spec != expected_spec or state["compose_sha256"] != sha(ops._canonical(spec)): + raise Error("recovery stage Compose contract changed") + verification, _ = ops._read_json(root / "recovery-verification.json", 1024 * 1024) + verify_fields = {"schema", "project", "daemon_id", "backup_sha256", "compose_sha256", + "stage_stopped", "writers_enabled", "checks", "verification_sha256"} + ops._strict_keys(verification, verify_fields, verify_fields, "recovery stage verification") + body = {name: verification[name] for name in verify_fields if name != "verification_sha256"} + if (verification["schema"] != STAGE_VERIFY_SCHEMA or verification["project"] != project or + verification["daemon_id"] != state["daemon_id"] or + verification["backup_sha256"] != state["backup_sha256"] or + verification["compose_sha256"] != state["compose_sha256"] or + verification["stage_stopped"] is not True or verification["writers_enabled"] is not False or + not isinstance(verification["checks"], dict) or set(verification["checks"]) != set(BACKENDS) or + not all(value is True for value in verification["checks"].values()) or + verification["verification_sha256"] != sha(ops._canonical(body))): + raise Error("recovery stage verification is stale, incomplete or tampered") + # Bound the filesystem shape and reject links/devices. Database content is + # not re-hashed here: the checksummed native restore attestation is only a + # bound record of the earlier restore checks, not a current byte inventory. + entries = 0 + allowed = {"private", "data", "recovery-compose.json", "recovery-stage.json", "recovery-verification.json"} + def walk_error(_error): + raise Error("recovery stage filesystem cannot be inspected safely") + + # Component-native databases own the contents of these directories and can + # legitimately make them unreadable to the non-root operator. Promotion + # never consumes or certifies those bytes: validate the exact data-root + # entries themselves, then deliberately prune their contents below. + expected_data_roots = set((*BACKENDS, "neo")) + try: + with os.scandir(root / "data") as stream: + data_roots = list(stream) + except OSError: + raise Error("recovery stage data roots cannot be inspected safely") + if ({entry.name for entry in data_roots} != expected_data_roots or + any(not entry.is_dir(follow_symlinks=False) for entry in data_roots)): + raise Error("recovery stage data-root contract changed") + + for base, directories, names in os.walk(root, followlinks=False, onerror=walk_error): + if Path(base) == root and "data" in directories: + directories.remove("data") + for name in directories + names: + entries += 1 + if entries > MAX_FILES * 2: + raise Error("recovery stage filesystem inventory exceeds bounds") + candidate = Path(base) / name + relative = candidate.relative_to(root) + metadata = candidate.lstat() + if relative.parts[0] not in allowed or not (stat.S_ISDIR(metadata.st_mode) or stat.S_ISREG(metadata.st_mode)): + raise Error("unexpected recovery stage filesystem entry") + for folder in ("private", "data", *("data/" + name for name in (*BACKENDS, "neo"))): + candidate = root / folder + if candidate.is_symlink() or not candidate.is_dir(): + raise Error("recovery stage data layout is incomplete") + anchor = ops._root_anchor_identity(root.stat()) + for name, expected in manifest.get("files", {}).items(): + if not name.startswith("private/"): + continue + metadata, digest = ops._hash_anchored_regular(root, name, anchor, MAX_FILE) + if expected != {"bytes": metadata.st_size, "sha256": digest}: + raise Error("recovery stage private source differs from backup") + return root, state, spec, verification, runtime, profile + + +def stage_spec(runtime, project): + spec = {"services": {}, "networks": {"quarantine": {"internal": True, "labels": {LABEL: project}}}} + for name in BACKENDS: + service = copy.deepcopy(runtime["services"][name]) + for field in ("ports", "depends_on", "profiles", "build"): + service.pop(field, None) + service.update(labels={LABEL: project}, networks=["quarantine"], restart="no") + if name in {"redis", "neo-redis"}: + service["command"] = ["redis-server", "--appendonly", "no", "--save", ""] + spec["services"][name] = service + return spec + + +def stage_command(root, project): + return ["docker", "compose", "--project-name", project, "--project-directory", str(root), "--file", str(root / "recovery-compose.json")] + + +def restore(args): + root, manifest = verify_backup(args.backup) + target = new_target(args.output, root) + if not args.apply: + return {"status": "NOT_RUN", "action": "restore-native-stage", "writers_enabled": False, + "effects": ["new quarantine deployment", "native restore/checks", "stop quarantine databases"], "limits": LIMITS} + require_apply(args) + started = time.monotonic() + runtime = kit.load(root / "private/runtime-compose.json") + profile = kit.validate_profile(kit.load(root / "private/profile.json")) + kit.check_build_receipt(root / "private", kit.load(root / "private/compose.json"), kit.image_preflight(runtime, profile)) + project = "dh-recovery-" + secrets.token_hex(6) + spec = stage_spec(runtime, project) + staging = ops._StagingDirectory.create(target, ".native-restore-") + try: + anchor, total = ops._root_anchor_identity(root.stat()), [0, MAX_TOTAL] + for name in manifest["files"]: + if name.startswith("private/"): + metadata, digest = ops._copy_stable(root, name, (staging, name), MAX_FILE, total, anchor) + if manifest["files"][name] != {"bytes": metadata.st_size, "sha256": digest}: + raise Error("private restore source changed before copying") + for directory in (*BACKENDS, "neo"): + staging.mkdir("data/" + directory) + for directory in COLD: + relative = "cold/" + directory + ".tar" + if cold_members(root / relative, staging=staging, directory=directory, source_root=root, expected=manifest["files"][relative]) != manifest["cold"][directory]: + raise Error("cold restore source changed before extraction") + staging.write_new_bytes("recovery-compose.json", ops._canonical(spec)) + state = {"schema": STAGE_SCHEMA, "project": project, "daemon_id": args.daemon_id, + "compose_sha256": sha(ops._canonical(spec)), "backup_sha256": sha(ops._canonical(manifest))} + staging.write_new_bytes("recovery-stage.json", ops._canonical(state)) + ops._publish_directory(staging, target) + finally: + staging.cleanup() + context = (target, project, spec, args.daemon_id, LABEL) + checks = {} + try: + if owned(*context, exclusive=False, require_no_networks=True): + raise Error("new recovery project already has containers") + run(stage_command(target, project) + ["up", "--detach", "--no-build", "--pull", "never"], timeout=180) + current = wait_strict_owned(context) + for name, database in BACKENDS.items(): + identity = current[name]["id"] + if database: + deadline = time.monotonic() + 60 + while True: + try: + # The official image briefly starts a socket-only + # initialization server before the final postmaster. + # TCP readiness excludes that transient server so a + # restore cannot race its shutdown. + run(["docker", "exec", identity, "pg_isready", "-h", "127.0.0.1", + "-U", database, "-d", database], timeout=5) + break + except Error: + if time.monotonic() >= deadline: + raise Error("quarantine database readiness timed out") + time.sleep(0.5) + if run(["docker", "exec", identity, "psql", "-X", "-A", "-t", "-U", database, "-d", database, "-c", + "SELECT count(*) FROM information_schema.tables WHERE table_schema='public' AND table_type='BASE TABLE';"]).strip() != b"0": + raise Error("quarantine restore target is not empty") + relative = "dumps/" + name + ".dump" + fd = ops._open_anchored_regular(root, relative, ops._root_anchor_identity(root.stat())) + try: + before = os.fstat(fd) + digest = hashlib.sha256() + for chunk in iter(lambda: os.read(fd, CHUNK), b""): + digest.update(chunk) + if manifest["files"][relative] != {"bytes": before.st_size, "sha256": digest.hexdigest()}: + raise Error("native restore dump changed before use") + os.lseek(fd, 0, os.SEEK_SET) + run(["docker", "exec", "-i", identity, "pg_restore", "-U", database, "-d", database, "--exit-on-error", "--single-transaction", "--no-owner", "--no-privileges"], stdin=fd, timeout=300) + if ops._stat_identity(before) != ops._stat_identity(os.fstat(fd)): + raise Error("restore dump changed during use") + finally: + os.close(fd) + checks[name] = pg_summary(identity, database) == manifest["databases"][name] + else: + deadline = time.monotonic() + 60 + while True: + try: + if run(["docker", "exec", identity, "redis-cli", "--raw", "PING"], timeout=5).strip() != b"PONG": + raise Error("Redis not ready") + break + except Error: + if time.monotonic() >= deadline: + raise Error("quarantine Redis readiness timed out") + time.sleep(0.5) + checks[name] = True + run(["docker", "exec", identity, "redis-check-rdb", "/data/dump.rdb"]) + if not all(checks.values()): + raise Error("restored database integrity differs from backup") + finally: + stop(context, BACKENDS, exclusive=False) + verify_backup(root) + stopped = owned(*context, exclusive=False, strict_networks=True) + if set(stopped) != set(BACKENDS) or any(value["running"] for value in stopped.values()): + raise Error("recovery stage stopped-state confirmation failed") + write_stage_verification(target, state, checks) + return {"status": "PASS", "action": "restore-native-stage", "checks": checks, + "stage_left_stopped": True, "writers_enabled": False, "private_only": True, + "restore_seconds": round(time.monotonic() - started, 3), + "rollback": "source and backup untouched; only new quarantine databases stopped; all stage data retained", "limits": LIMITS} + + +def reproject_spec(spec, project): + """Create a new project identity without changing commands, mounts or image provenance.""" + if not re.fullmatch(r"dh-deploy-[a-f0-9]{12}", project): + raise Error("invalid promotion project identity") + result = copy.deepcopy(spec) + for name, service in result["services"].items(): + service["labels"] = {kit.LABEL: project} + if "build" in service: + service["image"] = project + "-" + name + ":pinned" + for network in result["networks"].values(): + network["labels"] = {kit.LABEL: project} + return result + + +def _promotion_scaffold(spec, profile, project): + """Return non-runnable candidate metadata; executable Compose artifacts stay absent.""" + projected = reproject_spec(spec, project) + model = kit.model(projected, profile) + return { + "workspace/profile.json": ops._canonical(profile), + "workspace/model.json": ops._canonical(model), + "workspace/policy.json": ops._canonical(kit.policy(profile, model)), + } + + +def _separate_promotion_target(target, *sources): + target = Path(target) + for source in sources: + source = ops._canonical_input_leaf(Path(source)) + if target == source or target.is_relative_to(source) or source.is_relative_to(target): + raise Error("promotion candidate must be new and independent from backup and stage") + if target.is_relative_to(ROOT): + raise Error("promotion candidate must remain outside the repository") + return target + + +def _promotion_inputs(args, target): + backup_root, manifest = verify_backup(args.backup) + private = backup_root / "private" + source_state = kit.load(private / "deployment.json") + source_spec = kit.load(private / "compose.json") + profile = kit.validate_profile(kit.load(private / "profile.json")) + runtime = maintained_runtime(private, source_state, source_spec, profile) + if manifest["daemon_id"] != args.daemon_id: + raise Error("approved daemon differs from the independently verified backup") + stage = verify_stage(args.stage, manifest, runtime, profile, args.stage_project) + if stage[1]["daemon_id"] != args.daemon_id: + raise Error("approved daemon differs from the verified recovery stage") + _separate_promotion_target(target, backup_root, stage[0]) + return backup_root, manifest, source_state, source_spec, runtime, profile, stage + + +def _promotion_plan_body(project, source_state, manifest, stage_state, verification, + files, args): + return {"schema": PROMOTION_SCHEMA, "status": "PARTIAL", "project": project, + "source_project": source_state["project"], "stage_project": stage_state["project"], + "daemon_id": args.daemon_id, "backup_sha256": sha(ops._canonical(manifest)), + "stage_verification_sha256": verification["verification_sha256"], + "candidate_files": files, + "owner": {"uid": args.target_uid, "gid": args.target_gid, + "directory_mode": "0700", "private_file_mode": "0600", + "container_config_file_mode": "0644", + "runtime_data_ownership": "REQUIRES_COMPONENT_NATIVE_RESTORE"}, + "acknowledgements": {"queue_replay_reviewed": True, "ttl_expiry_reviewed": True}, + "disabled": {"submission": True, "worker": True, "capture": True, + "automatic_queue_replay": True}, + "stage_data_contract": {"bytes_consumed": False, "database_directories_rehashed": False, + "native_restore_attestation": "BOUND_ONLY"}, + "candidate_contract": {"compose_spec": "ABSENT", "runtime_spec": "ABSENT", + "build_receipt": "ABSENT", "deployment_state": "PENDING_ONLY"}, + "toolkit_runnable": False, + "expected_application_acceptance": _promotion_acceptance_contract(), + "rollback": PROMOTION_ROLLBACK, + "blocked_on": PROMOTION_BLOCKERS} + + +def prepare_promotion(args): + """Seal a new non-runnable candidate; never copy live DB files or start applications.""" + # Reject overwrite before reading any private source selected by the caller. + target = ops._safe_output_parent(Path(args.output)) + backup_root, manifest, source_state, source_spec, runtime, profile, stage = _promotion_inputs(args, target) + if not args.apply: + return {"status": "PARTIAL", "action": "prepare-promotion", "candidate_created": False, + "writers_enabled": False, "capture_enabled": False, "submission_enabled": False, + "stage_data_consumed": False, "stage_database_bytes_certified": False, + "blocked_on": PROMOTION_BLOCKERS, + "next": "rerun with apply gates to seal a new non-runnable candidate"} + require_promotion_apply(args) + private = backup_root / "private" + stage_context = (stage[0], stage[1]["project"], stage[2], args.daemon_id, LABEL) + current = owned(*stage_context, exclusive=False, strict_networks=True) + if set(current) != set(BACKENDS) or any(value["running"] for value in current.values()): + raise Error("verified recovery stage must retain exactly four stopped owned databases") + staging = None + published = False + try: + identities = kit.image_preflight(runtime, profile) + kit.check_build_receipt(private, source_spec, identities) + project = "dh-deploy-" + secrets.token_hex(6) + projected_spec = reproject_spec(source_spec, project) + projected_runtime = kit.runtime_spec(projected_spec, identities) + candidate_context = (target / "workspace", project, projected_runtime, args.daemon_id, kit.LABEL) + if owned(*candidate_context, require_no_networks=True): + raise Error("promotion project identity already has Docker resources") + staging = ops._StagingDirectory.create(target, ".promotion-") + total = [0, MAX_TOTAL] + backup_anchor = ops._root_anchor_identity(backup_root.stat()) + for name, expected in sorted(manifest["files"].items()): + if not name.startswith(("private/config/", "private/sources/")): + continue + destination = "workspace/" + name[len("private/"):] + metadata, digest = ops._copy_stable(backup_root, name, (staging, destination), MAX_FILE, + total, backup_anchor) + if expected != {"bytes": metadata.st_size, "sha256": digest}: + raise Error("promotion source changed while sealing candidate") + mode = 0o644 if destination in {"workspace/config/neo-client.yml", + "workspace/config/packmate.properties"} else 0o600 + staging.set_file_metadata(destination, mode) + for directory in ("workspace/data", *("workspace/data/" + name for name in (*BACKENDS, "neo")), + "workspace/pcaps"): + staging.mkdir(directory) + generated = _promotion_scaffold(source_spec, profile, project) + for name, data in generated.items(): + staging.write_new_bytes(name, data) + workspace_files = {name[len("workspace/"):]: value["sha256"] for name, value in inventory(staging).items() + if name.startswith("workspace/") and not name.startswith("workspace/data/") and + not name.startswith("workspace/pcaps/")} + pending = {"schema": kit.SCHEMA, "project": project, "files": workspace_files, + "source_pins": kit.shared.PINS, "approval_id": args.approval_id} + staging.write_new_bytes("workspace/deployment.pending.json", ops._canonical(pending)) + candidate_files = inventory(staging) + body = _promotion_plan_body(project, source_state, manifest, stage[1], stage[3], + candidate_files, args) + plan = dict(body, plan_sha256=sha(ops._canonical(body))) + staging.write_new_bytes("promotion-plan.json", ops._canonical(plan)) + # Independently re-verify both immutable inputs immediately before the + # one-way no-replace publication. Nothing runnable is published. + verified_root, verified_manifest = verify_backup(backup_root) + if verified_root != backup_root or verified_manifest != manifest: + raise Error("backup identity changed during promotion preparation") + verify_stage(stage[0], manifest, runtime, profile, args.stage_project) + # This is the last Docker operation. A published candidate is therefore + # always paired with an unambiguous successful return, and the stage is + # confirmed stopped immediately before the filesystem commit. + stop(stage_context, BACKENDS, exclusive=False, strict_networks=True) + ops._publish_directory(staging, target) + published = True + finally: + if staging is not None: + try: + staging.cleanup() + except OSError: + if not published: + raise + return {"status": "PARTIAL", "action": "prepare-promotion", "candidate_created": True, + "project": project, "toolkit_runnable": False, "compose_runnable": False, + "runnable_artifacts_present": False, "writers_enabled": False, + "capture_enabled": False, "submission_enabled": False, + "stage_data_consumed": False, "stage_database_bytes_certified": False, + "blocked_on": PROMOTION_BLOCKERS, + "rollback": "candidate is non-runnable; backup and stopped recovery stage are retained"} + + +def _verify_acceptance(path, plan): + value, _ = ops._read_json(Path(path), 1024 * 1024) + fields = {"schema", "project", "plan_sha256", "checks", "submission_enabled", + "worker_enabled", "capture_enabled", "rollback_confirmed"} + ops._strict_keys(value, fields, fields, "promotion acceptance") + check_names = {"component_native_data_restore", "filesystem_ownership", "farm_authenticated", + "neo_authenticated", "packmate_file", "restart_reconnect"} + if (value["schema"] != ACCEPTANCE_SCHEMA or value["project"] != plan["project"] or + value["plan_sha256"] != plan["plan_sha256"] or not isinstance(value["checks"], dict) or + set(value["checks"]) != check_names or + any(result != "PASS" for result in value["checks"].values()) or + value["submission_enabled"] is not False or value["worker_enabled"] is not False or + value["capture_enabled"] is not False or value["rollback_confirmed"] is not True): + raise Error("promotion acceptance record is incomplete or not bound to this candidate") + return value + + +def verify_promotion(args): + """Verify the sealed candidate and optional human/app record without activating it.""" + candidate = private_root(args.output) + backup_root, manifest, source_state, source_spec, runtime, profile, stage = _promotion_inputs(args, candidate) + plan, _ = ops._read_json(candidate / "promotion-plan.json", 8 * 1024 * 1024) + fields = {"schema", "status", "project", "source_project", "stage_project", "daemon_id", + "backup_sha256", "stage_verification_sha256", "candidate_files", "owner", + "acknowledgements", "disabled", "stage_data_contract", "candidate_contract", + "toolkit_runnable", "expected_application_acceptance", "rollback", "blocked_on", + "plan_sha256"} + ops._strict_keys(plan, fields, fields, "promotion plan") + body = {name: plan[name] for name in fields if name != "plan_sha256"} + if (plan["schema"] != PROMOTION_SCHEMA or plan["status"] != "PARTIAL" or + not isinstance(plan["project"], str) or not re.fullmatch(r"dh-deploy-[a-f0-9]{12}", plan["project"]) or + plan["source_project"] != manifest["source_project"] or + plan["stage_project"] != stage[1]["project"] or plan["daemon_id"] != args.daemon_id or + plan["backup_sha256"] != sha(ops._canonical(manifest)) or + plan["stage_verification_sha256"] != stage[3]["verification_sha256"] or + not isinstance(plan["candidate_files"], dict) or not 1 <= len(plan["candidate_files"]) <= MAX_FILES or + plan["toolkit_runnable"] is not False or plan["blocked_on"] != PROMOTION_BLOCKERS or + plan["acknowledgements"] != {"queue_replay_reviewed": True, "ttl_expiry_reviewed": True} or + plan["disabled"] != {"submission": True, "worker": True, "capture": True, + "automatic_queue_replay": True} or + plan["stage_data_contract"] != {"bytes_consumed": False, "database_directories_rehashed": False, + "native_restore_attestation": "BOUND_ONLY"} or + plan["candidate_contract"] != {"compose_spec": "ABSENT", "runtime_spec": "ABSENT", + "build_receipt": "ABSENT", + "deployment_state": "PENDING_ONLY"} or + plan["expected_application_acceptance"] != _promotion_acceptance_contract() or + plan["rollback"] != PROMOTION_ROLLBACK or + plan["plan_sha256"] != sha(ops._canonical(body))): + raise Error("promotion plan binding or checksum mismatch") + candidate_metadata = candidate.stat() + expected_owner = {"uid": candidate_metadata.st_uid, "gid": candidate_metadata.st_gid, + "directory_mode": "0700", "private_file_mode": "0600", + "container_config_file_mode": "0644", + "runtime_data_ownership": "REQUIRES_COMPONENT_NATIVE_RESTORE"} + if plan["owner"] != expected_owner or stat.S_IMODE(candidate_metadata.st_mode) != 0o700: + raise Error("promotion candidate ownership contract mismatch") + forbidden = {"compose.json", "runtime-compose.json", "build-receipt.json", "deployment.json", + "compose.yaml", "compose.yml", "docker-compose.yaml", "docker-compose.yml"} + if (any((candidate / "workspace" / name).exists() for name in forbidden) or + not (candidate / "workspace/deployment.pending.json").is_file()): + raise Error("promotion candidate runnable-state contract changed") + expected_material = { + name: {"bytes": len(data), "sha256": sha(data)} + for name, data in _promotion_scaffold(source_spec, profile, plan["project"]).items() + } + for name, record in manifest["files"].items(): + if name.startswith(("private/config/", "private/sources/")): + expected_material["workspace/" + name[len("private/"):]] = record + expected_names = set(expected_material) | {"workspace/deployment.pending.json"} + if set(plan["candidate_files"]) != expected_names: + raise Error("promotion candidate contains runnable or unexpected artifacts") + if any(plan["candidate_files"][name] != record for name, record in expected_material.items()): + raise Error("promotion candidate metadata or source binding mismatch") + expected_directories = {"workspace", "workspace/data", "workspace/pcaps"} | { + "workspace/data/" + name for name in (*BACKENDS, "neo")} + for name in expected_names: + expected_directories.update(str(parent) for parent in PurePosixPath(name).parents + if str(parent) != ".") + anchor = ops._root_anchor_identity(candidate.stat()) + actual = set() + actual_directories = set() + def walk_error(_error): + raise Error("promotion candidate filesystem cannot be inspected safely") + + for base, directories, names in os.walk(candidate, followlinks=False, onerror=walk_error): + for name in directories + names: + item = Path(base) / name + metadata = item.lstat() + if not (stat.S_ISDIR(metadata.st_mode) or stat.S_ISREG(metadata.st_mode)): + raise Error("promotion candidate contains a special entry") + if metadata.st_uid != plan["owner"]["uid"] or metadata.st_gid != plan["owner"]["gid"]: + raise Error("promotion candidate entry ownership changed") + if stat.S_ISDIR(metadata.st_mode) and stat.S_IMODE(metadata.st_mode) != 0o700: + raise Error("promotion candidate directory permissions changed") + if stat.S_ISDIR(metadata.st_mode): + actual_directories.add(item.relative_to(candidate).as_posix()) + else: + actual.add(item.relative_to(candidate).as_posix()) + if actual != set(plan["candidate_files"]) | {"promotion-plan.json"}: + raise Error("promotion candidate inventory changed") + if actual_directories != expected_directories: + raise Error("promotion candidate directory scaffold changed") + for name, expected in plan["candidate_files"].items(): + ops._portable_relative_posix(name, "promotion candidate member") + if set(expected) != {"bytes", "sha256"}: + raise Error("invalid promotion candidate inventory record") + metadata, digest = ops._hash_anchored_regular(candidate, name, anchor, MAX_FILE) + if expected != {"bytes": metadata.st_size, "sha256": digest}: + raise Error("promotion candidate file changed") + expected_mode = 0o644 if name in {"workspace/config/neo-client.yml", + "workspace/config/packmate.properties"} else 0o600 + if stat.S_IMODE(metadata.st_mode) != expected_mode: + raise Error("promotion candidate file permissions changed") + pending, pending_raw = ops._read_json(candidate / "workspace/deployment.pending.json", 8 * 1024 * 1024) + pending_fields = {"schema", "project", "files", "source_pins", "approval_id"} + ops._strict_keys(pending, pending_fields, pending_fields, "pending deployment") + expected_pending_files = {name[len("workspace/"):]: record["sha256"] + for name, record in plan["candidate_files"].items() + if name.startswith("workspace/") and + name != "workspace/deployment.pending.json"} + if (pending["schema"] != kit.SCHEMA or pending["project"] != plan["project"] or + pending["source_pins"] != kit.shared.PINS or pending["files"] != expected_pending_files or + not isinstance(pending["approval_id"], str) or + not re.fullmatch(r"[A-Za-z0-9_.-]{1,80}", pending["approval_id"])): + raise Error("pending deployment ownership contract changed") + if (pending_raw != ops._canonical(pending) or + plan["candidate_files"]["workspace/deployment.pending.json"] != + {"bytes": len(pending_raw), "sha256": sha(pending_raw)}): + raise Error("pending deployment record changed") + acceptance = None + if getattr(args, "acceptance", None): + acceptance = _verify_acceptance(args.acceptance, plan) + return {"status": "PARTIAL", "action": "verify-promotion", "candidate_integrity": "PASS", + "application_acceptance_record": "RECORDED_NOT_INDEPENDENTLY_EXECUTED" if acceptance else "NOT_RUN", + "toolkit_runnable": False, "compose_runnable": False, + "runnable_artifacts_present": False, "writers_enabled": False, "capture_enabled": False, + "submission_enabled": False, + "stage_data_consumed": False, "stage_database_bytes_certified": False, + "blocked_on": ["independent_runtime_acceptance", "operator_activation"] if acceptance else PROMOTION_BLOCKERS, + "rollback": "backup and verified stopped stage remain the rollback source"} + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("action", choices=["backup", "verify", "restore-native-stage", "cleanup-helpers", + "prepare-promotion", "verify-promotion"]) + for name in ("workspace", "backup", "output", "approval-id", "daemon-id", "stage", "stage-project", + "acceptance"): + parser.add_argument("--" + name) + for name in ("target-uid", "target-gid"): + parser.add_argument("--" + name, type=int) + for name in ("apply", "snapshot-confirmed", "maintenance-confirmed", "queue-reviewed", "ttl-reviewed"): + parser.add_argument("--" + name, action="store_true") + args = parser.parse_args(argv) + try: + if args.action == "backup" and args.workspace and args.output: + result = backup(args) + elif args.action == "restore-native-stage" and args.backup and args.output: + result = restore(args) + elif args.action == "prepare-promotion" and args.backup and args.stage and args.output and args.stage_project: + result = prepare_promotion(args) + elif args.action == "verify-promotion" and args.backup and args.stage and args.output and args.stage_project: + result = verify_promotion(args) + elif args.action == "verify" and args.backup: + verify_backup(args.backup) + result = {"status": "PASS", "action": "verify", "private_only": True, "runtime": "NOT_RUN"} + elif args.action == "cleanup-helpers" and args.workspace: + _root, state, _runtime, _profile, _files = source_workspace(args.workspace) + if args.apply: + require_apply(args) + cleanup_helpers(state["project"], args.daemon_id) + result = {"status": "PASS" if args.apply else "NOT_RUN", "action": "cleanup-helpers", + "scope": "only exact owned cold-read helpers; no source services/data affected"} + else: + raise Error("required source/backup/output paths missing") + print(json.dumps(result, sort_keys=True)) + return 2 if result.get("status") == "PARTIAL" else 0 + except (Exception, KeyboardInterrupt) as error: + print(json.dumps({"status": "BLOCKED", "error": type(error).__name__, "raw_output": "suppressed", + "source_auto_resume": False, "resume_after_review": RESUME, + "retained": "source and existing backups are never removed; inspect any newly published quarantine stage"})) + return 2 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/deployment/recovery_activation.py b/deployment/recovery_activation.py new file mode 100644 index 0000000..5b2c537 --- /dev/null +++ b/deployment/recovery_activation.py @@ -0,0 +1,557 @@ +#!/usr/bin/env python3 +"""Restore applications into a NEW stopped deployment; never overwrite a source. + +The separate inert promotion scaffold is intentionally not consumed or changed. +Redis is reset in the NEW deployment only, with an explicit data-loss gate: +its original queues, cache and session values remain in the verified backup. +Application acceptance precedes a second, receipt-bound activation approval. +""" +from __future__ import annotations + +import argparse +import base64 +import copy +import hashlib +import importlib.util +import json +import os +from pathlib import Path +import re +import secrets +import stat +import struct +import sys +import time +import urllib.error +import urllib.request + +SPEC = importlib.util.spec_from_file_location("activation_recovery", Path(__file__).with_name("recovery.py")) +rec = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(rec) +kit, ops, Error = rec.kit, rec.ops, rec.Error +SCHEMA = "durkahelper.application-recovery.v1" +ACCEPTANCE = "durkahelper.application-recovery-acceptance.v1" +APPS = ("farm", "front", "neo-server", "packmate") +ACTIVE = tuple(rec.BACKENDS) + APPS +EMPTY_PCAP = struct.pack("= deadline: + raise Error("candidate native database readiness timed out") + time.sleep(0.5) + + +def restore_pg(backup, manifest, identity, name, database): + base = ["docker", "exec", identity, "psql", "-X", "-A", "-t", "-U", database, "-d", database, "-c"] + if rec.run(base + ["SELECT count(*) FROM information_schema.tables WHERE table_schema='public' AND table_type='BASE TABLE';"]).strip() != b"0": + raise Error("application recovery database is not empty") + relative = "dumps/" + name + ".dump" + fd = ops._open_anchored_regular(backup, relative, ops._root_anchor_identity(backup.stat())) + try: + before = os.fstat(fd) + digest = hashlib.sha256() + for chunk in iter(lambda: os.read(fd, rec.CHUNK), b""): + digest.update(chunk) + if manifest["files"][relative] != {"bytes": before.st_size, "sha256": digest.hexdigest()}: + raise Error("native application restore dump changed before use") + os.lseek(fd, 0, os.SEEK_SET) + rec.run(["docker", "exec", "-i", identity, "pg_restore", "-U", database, "-d", database, + "--exit-on-error", "--single-transaction", "--no-owner", "--no-privileges"], stdin=fd, timeout=300) + if ops._stat_identity(before) != ops._stat_identity(os.fstat(fd)): + raise Error("native application restore dump changed during use") + finally: + os.close(fd) + if rec.pg_summary(identity, database) != manifest["databases"][name]: + raise Error("restored application database differs from verified native backup") + + +def runtime_ownership(current): + owners = {} + for name, database in rec.BACKENDS.items(): + identity = current[name]["id"] + account = "postgres" if database else "redis" + uid = rec.run(["docker", "exec", identity, "id", "-u", account]).decode().strip() + gid = rec.run(["docker", "exec", identity, "id", "-g", account]).decode().strip() + if not all(re.fullmatch(r"[0-9]{1,10}", value) and 0 < int(value) < 2 ** 31 for value in (uid, gid)): + raise Error("invalid native database runtime UID/GID") + path = "/var/lib/postgresql/data" if database else "/data" + actual = rec.run(["docker", "exec", identity, "stat", "-c", "%u:%g:%a", path]).decode().strip().split(":") + # Official Redis's entrypoint can change only the owner, retaining the + # operator's group. A 0700 root is accessible by its runtime UID only; + # no broad group permission or recursive chmod is required. + if (len(actual) != 3 or actual[0] != uid or + not re.fullmatch(r"[0-9]{1,10}", actual[1]) or actual[2] != "700"): + raise Error("component-native data ownership differs from its runtime account") + owners[name] = actual[0] + ":" + actual[1] + owners.update({"neo-server": "0:0", "packmate": "65534:65534"}) + return owners + + +def stopped_epochs(context): + current = stopped(context, strict=True) + result = {} + for name, item in sorted(current.items()): + value = json.loads(rec.run(["docker", "inspect", "--format", + '{"id":{{json .Id}},"running":{{json .State.Running}},"started":{{json .State.StartedAt}},' + '"finished":{{json .State.FinishedAt}},"restarts":{{json .RestartCount}}}', item["id"]])) + if (set(value) != {"id", "running", "started", "finished", "restarts"} or value["id"] != item["id"] or + value["running"] is not False or type(value["restarts"]) is not int or value["restarts"] < 0 or + any(not isinstance(value[key], str) or not re.fullmatch(r"[0-9T:.Z+-]{20,40}", value[key]) + for key in ("started", "finished"))): + raise Error("candidate stopped-container epoch changed during inspection") + result[name] = value + return result + + +def packmate_ready(root, profile, timeout=120): + pairs = dict(line.split("=", 1) for line in kit.read(root / "config/packmate.properties").decode().splitlines()) + credentials = (pairs["packmate.web.account-login"] + ":" + pairs["packmate.web.account-password"]).encode("ascii") + headers = {"Authorization": "Basic " + base64.b64encode(credentials).decode("ascii"), "Accept-Encoding": "identity"} + opener = urllib.request.build_opener(urllib.request.ProxyHandler({}), kit.shared.NoRedirect()) + url = "http://" + profile["bind_address"] + ":" + str(profile["ports"]["packmate"]) + deadline = time.monotonic() + timeout + while True: + try: + values = [] + for path in ("/api/service/", "/api/pcap/started"): + with opener.open(urllib.request.Request(url + path, headers=headers), timeout=5) as response: + data = response.read(1024 * 1024 + 1) + if response.status != 200 or len(data) > 1024 * 1024: + raise Error("Packmate recovery response rejected; raw data suppressed") + values.append(json.loads(data)) + if not isinstance(values[0], list) or values[1] is not False: + raise Error("Packmate application or stopped-capture acceptance failed") + return + except (OSError, ValueError, urllib.error.URLError): + if time.monotonic() >= deadline: + raise Error("authenticated Packmate recovery readiness timed out") + time.sleep(0.5) + + +def start_and_check(root, state, runtime, profile): + context = (root, state["project"], selected(runtime), state["daemon_id"], kit.LABEL) + rec.owned(*context, exclusive=False) + rec.run(command(root, state) + ["up", "--detach", "--no-build", "--pull", "never", "farm", "front", "packmate"], timeout=180) + kit.wait_farm(profile, runtime) + rec.run(command(root, state) + ["up", "--detach", "--no-build", "--pull", "never", "neo-server"], timeout=60) + kit.wait_neo(root, state, runtime) + packmate_ready(root, profile) + observed = rec.wait_strict_owned(context) + if set(observed) != set(ACTIVE) or not all(value["running"] for value in observed.values()): + raise Error("application recovery running service set mismatch") + + +def acceptance(root, state): + value = kit.load(root / "recovery-acceptance.json") + fields = {"schema", "project", "recovery_sha256", "checks", "runtime_owners", "redis_policy", "stopped_containers", + "candidate_stopped", "submission_enabled", "worker_enabled", "capture_enabled", "seconds"} + ops._strict_keys(value, fields, fields, "application recovery acceptance") + if (value["schema"] != ACCEPTANCE or value["project"] != state["project"] or + value["recovery_sha256"] != rec.sha(ops._canonical(state)) or + not isinstance(value["checks"], dict) or set(value["checks"]) != CHECKS or + not all(result is True for result in value["checks"].values()) or + value["redis_policy"] != state["redis_policy"] or value["candidate_stopped"] is not True or + any(value[key] is not False for key in ("submission_enabled", "worker_enabled", "capture_enabled")) or + not isinstance(value["runtime_owners"], dict) or set(value["runtime_owners"]) != set(rec.BACKENDS) | {"neo-server", "packmate"} or + any(not isinstance(owner, str) or not re.fullmatch(r"[0-9]{1,10}:[0-9]{1,10}", owner) + for owner in value["runtime_owners"].values()) or + not isinstance(value["stopped_containers"], dict) or set(value["stopped_containers"]) != set(ACTIVE) or + type(value["seconds"]) not in (int, float) or not 0 <= value["seconds"] <= 86400): + raise Error("application recovery acceptance is incomplete or not bound to this candidate") + return value + + +def recover(args): + target = ops._safe_output_parent(Path(args.output)) + data, source = inputs(args, target) + if not args.apply: + return {"status": "NOT_RUN", "action": "recover", "source_auto_resume": False, + "redis_policy": "DISCARD_CANDIDATE_ALL_STATE_BACKUP_RETAINED", "limits": LIMITS, + "effects": ["new native restore", "app authentication and restart checks", "leave candidate stopped and not toolkit-runnable"]} + require_gates(args) + stage = data[6] + stage_context = (stage[0], stage[1]["project"], stage[2], args.daemon_id, rec.LABEL) + stopped(source) + stopped(stage_context, strict=True) + started = time.monotonic() + root, state, pending, runtime, profile = prepare_files(args, target, data) + context = (root, state["project"], selected(runtime), args.daemon_id, kit.LABEL) + checks = {} + try: + stopped(source) + stopped(stage_context, strict=True) + rec.run(command(root, state) + ["up", "--detach", "--no-build", "--pull", "never"] + list(rec.BACKENDS), timeout=180) + current = rec.owned(*context, exclusive=False) + if set(current) != set(rec.BACKENDS): + raise Error("candidate native restore service set mismatch") + for name, database in rec.BACKENDS.items(): + identity = current[name]["id"] + ready(identity, database) + if database: + restore_pg(data[0], data[1], identity, name, database) + checks[name] = True + elif rec.run(["docker", "exec", identity, "redis-cli", "--raw", "DBSIZE"]).strip() != b"0": + raise Error("candidate Redis contains state; refusing queue replay") + checks["candidate_redis_empty"] = True + owners = runtime_ownership(current) + checks["runtime_ownership"] = True + start_and_check(root, state, runtime, profile) + rec.stop(context, APPS, exclusive=False) + start_and_check(root, state, runtime, profile) + checks.update({name: True for name in ("farm_authenticated", "neo_authenticated", "packmate_authenticated", + "packmate_capture_stopped", "restart_reconnect")}) + finally: + # Reconcile an interrupted Compose create by exact project ownership. + # A cleanup failure is BLOCKED; no acceptance or runnable manifest exists. + try: + kit.cleanup_readiness_probes(state) + finally: + # A probe reconciliation failure must not skip stopping the + # separately owned application stack. Either failure stays BLOCKED. + rec.stop(context, ACTIVE, exclusive=False) + epochs = stopped_epochs(context) + stopped(source) + stopped(stage_context, strict=True) + checks.update(source_stopped=True, stage_stopped=True) + if rec.verify_backup(data[0])[1] != data[1]: + raise Error("backup changed during application acceptance") + workspace(root) + record = {"schema": ACCEPTANCE, "project": state["project"], "recovery_sha256": rec.sha(ops._canonical(state)), + "checks": checks, "runtime_owners": owners, "stopped_containers": epochs, + "redis_policy": state["redis_policy"], "candidate_stopped": True, + "submission_enabled": False, "worker_enabled": False, "capture_enabled": False, + "seconds": round(time.monotonic() - started, 3)} + ops._atomic_write_new(root / "recovery-acceptance.json", ops._canonical(record)) + return {"status": "PASS", "action": "recover", "application_acceptance": "PASS", "toolkit_runnable": False, + "candidate_stopped": True, "acceptance_sha256": rec.sha(ops._canonical(record)), "checks": checks, + "limits": LIMITS, "next": "review acceptance; explicitly activate with its checksum; then separately toolkit up", + "rollback": "source, backup, stage and candidate retained stopped; no data removed"} + + +def activate(args): + root, state, pending, runtime, profile = workspace(args.output) + data, source = inputs(args, root) + record = acceptance(root, state) + if (state["backup_sha256"] != rec.sha(ops._canonical(data[1])) or + state["stage_verification_sha256"] != data[6][3]["verification_sha256"] or + state["daemon_id"] != args.daemon_id): + raise Error("activation provenance differs from verified recovery inputs") + if (root / "deployment.json").exists(): + raise Error("candidate is already activated; no manifest overwritten") + if not args.apply: + return {"status": "NOT_RUN", "action": "activate", "acceptance_sha256": rec.sha(ops._canonical(record)), + "effects": ["publish maintained deployment ownership manifest", "no services started"], "limits": LIMITS} + require_gates(args) + if not args.activation_confirmed or args.acceptance_sha256 != rec.sha(ops._canonical(record)): + raise Error("activation requires --activation-confirmed and the reviewed --acceptance-sha256") + stage = data[6] + stopped(source) + stopped((stage[0], stage[1]["project"], stage[2], args.daemon_id, rec.LABEL), strict=True) + if stopped_epochs((root, state["project"], selected(runtime), args.daemon_id, kit.LABEL)) != record["stopped_containers"]: + raise Error("candidate restarted or changed after application acceptance; recover into a fresh candidate") + kit.check_build_receipt(root, kit.load(root / "compose.json"), kit.image_preflight(runtime, profile)) + workspace(root) + # The no-replace hard link is the final commit. A lost completion response + # is reconciled by inode identity, never by mere file contents. + anchor = ops._root_anchor_identity(root.stat()) + directory = os.open(root, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW) + descriptor = None + try: + if ops._root_anchor_identity(os.fstat(directory)) != anchor: + raise Error("candidate root changed before activation commit") + descriptor = os.open("deployment.pending.json", os.O_RDONLY | os.O_NOFOLLOW, dir_fd=directory) + metadata = os.fstat(descriptor) + raw = b"" + while True: + part = os.read(descriptor, 65536) + if not part: + break + raw += part + if len(raw) > 8 * 1024 * 1024: + raise Error("pending manifest exceeds activation bound") + before = os.stat("deployment.pending.json", dir_fd=directory, follow_symlinks=False) + if (not stat.S_ISREG(before.st_mode) or before.st_uid != args.target_uid or + ops._stat_identity(before) != ops._stat_identity(metadata) or + ops._stat_identity(os.fstat(descriptor)) != ops._stat_identity(metadata) or + raw != ops._canonical(pending) or rec.sha(raw) != state["pending_sha256"]): + raise Error("pending deployment identity changed before activation") + link_error = None + try: + os.link("deployment.pending.json", "deployment.json", src_dir_fd=directory, dst_dir_fd=directory, follow_symlinks=False) + except BaseException as error: + link_error = error + # Hold the verified source descriptor through the commit. link(2) + # resolves its source NAME afresh, so a successful syscall alone does + # not prove it linked the inode we verified before the call. + published = None + final_descriptor = None + try: + published = os.stat("deployment.json", dir_fd=directory, follow_symlinks=False) + final_descriptor = os.open("deployment.json", os.O_RDONLY | os.O_NOFOLLOW, dir_fd=directory) + final_metadata = os.fstat(final_descriptor) + final_raw = b"" + while True: + part = os.read(final_descriptor, 65536) + if not part: + break + final_raw += part + if len(final_raw) > 8 * 1024 * 1024: + raise Error("published activation manifest exceeds bounds") + if (not stat.S_ISREG(published.st_mode) or + ops._stat_identity(final_metadata) != ops._stat_identity(published) or + ops._root_anchor_identity(published) != ops._root_anchor_identity(os.fstat(descriptor)) or + final_raw != raw or rec.sha(final_raw) != state["pending_sha256"] or + ops._stat_identity(os.fstat(final_descriptor)) != ops._stat_identity(final_metadata) or + ops._root_anchor_identity(root.stat()) != anchor): + raise Error("activation source changed at commit; candidate manifest rejected") + except BaseException: + if published is not None and link_error is None: + # Remove only the exact new destination just inspected. Never + # remove a concurrently replaced destination by pathname alone. + try: + named = os.stat("deployment.json", dir_fd=directory, follow_symlinks=False) + if ops._root_anchor_identity(named) == ops._root_anchor_identity(published): + os.unlink("deployment.json", dir_fd=directory) + except OSError: + pass + if link_error is not None: + raise link_error + raise + finally: + if final_descriptor is not None: + try: + os.close(final_descriptor) + except OSError: + pass + finally: + if descriptor is not None: + try: + os.close(descriptor) + except OSError: + pass + try: + os.fsync(directory) + except OSError: + pass + try: + os.close(directory) + except OSError: + pass + return {"status": "PASS", "action": "activate", "toolkit_runnable": True, "candidate_stopped": True, + "services_started": False, "limits": LIMITS, + "next": "toolkit up on this NEW workspace; submission and worker remain separate explicit decisions", + "rollback": "toolkit down on this candidate only; source and backup unchanged"} + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("action", choices=("recover", "verify", "activate", "stop")) + parser.add_argument("--output", required=True) + for name in ("workspace", "backup", "stage", "stage-project", "daemon-id", "approval-id", "acceptance-sha256"): + parser.add_argument("--" + name) + for name in ("apply", "snapshot-confirmed", "maintenance-confirmed", "queue-reviewed", "ttl-reviewed", + "discard-candidate-redis-state", "activation-confirmed"): + parser.add_argument("--" + name, action="store_true") + for name in ("target-uid", "target-gid"): + parser.add_argument("--" + name, type=int) + args = parser.parse_args(argv) + try: + if args.action in {"recover", "activate"}: + if not all((args.workspace, args.backup, args.stage, args.stage_project, args.daemon_id)): + raise Error("recover/activate require source workspace, backup, stage, exact stage project and daemon ID") + result = recover(args) if args.action == "recover" else activate(args) + else: + root, state, pending, runtime, profile = workspace(args.output) + if args.action == "verify": + record = acceptance(root, state) + result = {"status": "PASS", "configuration_integrity": "PASS", "runtime": "NOT_RUN", + "acceptance_sha256": rec.sha(ops._canonical(record)), "limits": LIMITS} + elif not args.apply: + result = {"status": "NOT_RUN", "action": "stop", "effects": ["stop only owned candidate services; retain data"]} + else: + rec.require_apply(args) + if args.daemon_id != state["daemon_id"]: + raise Error("stop daemon differs from candidate identity") + try: + kit.cleanup_readiness_probes(state) + finally: + rec.stop((root, state["project"], selected(runtime), args.daemon_id, kit.LABEL), ACTIVE, exclusive=False) + result = {"status": "PASS", "action": "stop", "data_retained": True} + print(json.dumps(result, sort_keys=True, indent=2)) + return 0 + except (Exception, KeyboardInterrupt) as error: + print(json.dumps({"status": "BLOCKED", "reason": str(error) if isinstance(error, Error) else + "recovery rejected: " + type(error).__name__, "raw_output": "suppressed", + "rollback": "inspect exact candidate with stop; retain all source/backup/stage data"})) + return 2 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/deployment/toolkit.py b/deployment/toolkit.py new file mode 100644 index 0000000..5eb51e1 --- /dev/null +++ b/deployment/toolkit.py @@ -0,0 +1,593 @@ +#!/usr/bin/env python3 +"""Pinned, private S4DFarm/Neo/Packmate deployment. Preview is the default. + +Never run this against an untrusted Docker daemon or untrusted source checkout. +No secrets, expanded Compose model or upstream command output are printed. +""" +from __future__ import annotations + +import argparse +import copy +import hashlib +import importlib.util +import ipaddress +import json +import os +from pathlib import Path +import re +import secrets +import stat +import subprocess +import sys +import time +import urllib.error +import urllib.request + +ROOT = Path(__file__).resolve().parents[1] +SPEC = importlib.util.spec_from_file_location("deployment_shared", ROOT / "integration/stack_smoke.py") +shared = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(shared) +Error = shared.FixtureError +SCHEMA = "durkahelper.deployment.v1" +LABEL = "io.durkahelper.deployment" +PROBE_LABEL = "io.durkahelper.readiness-probe" +LIGHT = "ghcr.io/c4t-but-s4d/neo_env_light:v2.4.2@sha256:75deed498a6451f702d88f05495af8c7006707ac223ad4b2e7def0d947b622bc" +PACKMATE = "registry.gitlab.com/packmate/packmate:v4.0@sha256:faa39ec74a63d84558e08ab949b7724a0a014f6629d105a5212a3afb05c7cbf7" +PACKMATE_DB = "postgres:15.2@sha256:78a275d4c891f7b3a33d3f1a78eda9f1d744954d9e20122bfdc97cdda25cddaf" +LOGGER = "ru.serega6531.packmate.configuration.SecurityConfiguration" +BUILD_SERVICES = ("farm", "celery", "front", "neo-server") +SERVICES = ("postgres", "redis", "neo-redis", "farm", "front", "neo-server", "packmate-db", "packmate") +NOT_VALIDATED = ["Docker Desktop", "physical team LAN", "continuous capture", + "competition protocol", "component recovery", "full offline cold start"] + + +def safe_path(path): + """Allow ordinary macOS ancestor aliases, reject a linked leaf/reparse point.""" + raw = Path(os.path.abspath(path)) + if raw.is_symlink() or getattr(raw.lstat() if raw.exists() else None, "st_file_attributes", 0) & 0x400: + raise Error("linked deployment paths are not allowed") + resolved = shared.no_links(raw) if os.name == "nt" else raw.parent.resolve(strict=True) / raw.name + if any(c in str(resolved) for c in (",", "\r", "\n", "$")): + raise Error("deployment path contains unsupported delimiter") + return resolved + + +def read(path, limit=1024 * 1024): + path = safe_path(path) + before = path.lstat() + if not stat.S_ISREG(before.st_mode) or before.st_size > limit: + raise Error("input must be a bounded regular file") + fd = os.open(path, os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) | + getattr(os, "O_NONBLOCK", 0) | getattr(os, "O_BINARY", 0)) + try: + same = lambda s: (s.st_dev, s.st_ino, s.st_size, s.st_mtime_ns) + opened = os.fstat(fd) + if not stat.S_ISREG(opened.st_mode) or same(opened) != same(before): + raise Error("input changed while opening") + with os.fdopen(fd, "rb", closefd=False) as stream: + result = stream.read(limit + 1) + if len(result) > limit or same(opened) != same(os.fstat(fd)) or same(opened) != same(path.lstat()): + raise Error("input changed while reading") + return result + finally: + os.close(fd) + + +def load(path): + def unique(pairs): + result = {} + for key, value in pairs: + if key in result: + raise Error("duplicate JSON key") + result[key] = value + return result + return json.loads(read(path), object_pairs_hook=unique) + + +def validate_profile(value): + required = {"schema", "platform", "bind_address", "ports", "allow_amd64_emulation", "farm", "packmate"} + if not isinstance(value, dict) or set(value) != required or value["schema"] != "durkahelper.deployment-profile.v1": + raise Error("invalid deployment profile schema or fields") + platform = value["platform"] + if platform not in ({"os": "linux", "architecture": "amd64", "runtime": "docker-engine"}, + {"os": "linux", "architecture": "arm64", "runtime": "docker-engine"}, + {"os": "darwin", "architecture": "arm64", "runtime": "docker-desktop"}): + raise Error("unsupported deployment platform") + ip = ipaddress.ip_address(value["bind_address"]) + if ip.version != 4 or ip.is_unspecified or ip.is_multicast or ip.is_link_local: + raise Error("bind_address must be an explicit unicast IPv4 address, never wildcard") + ports = value["ports"] + if (not isinstance(ports, dict) or set(ports) != {"farm", "neo", "packmate"} or + any(type(p) is not int or not 1024 <= p <= 65535 for p in ports.values()) or len(set(ports.values())) != 3): + raise Error("three distinct unprivileged UI/API ports are required") + if type(value["allow_amd64_emulation"]) is not bool: + raise Error("allow_amd64_emulation must be boolean") + pm = value["packmate"] + if not isinstance(pm, dict) or set(pm) != {"mode", "local_ip", "pcap_file", "interface", "retention_minutes"}: + raise Error("invalid Packmate profile") + if pm["mode"] not in {"FILE", "LIVE"}: + raise Error("Packmate mode must be FILE or LIVE") + ipaddress.ip_address(pm["local_ip"]) + if not isinstance(pm["pcap_file"], str) or not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,100}\.pcap", pm["pcap_file"]): + raise Error("pcap_file must be a simple .pcap filename") + if not isinstance(pm["interface"], str) or not re.fullmatch(r"[A-Za-z0-9_.:-]{0,32}", pm["interface"]): + raise Error("invalid capture interface") + if type(pm["retention_minutes"]) is not int or not 5 <= pm["retention_minutes"] <= 1440: + raise Error("capture retention must be 5..1440 minutes") + farm = value["farm"] + required_farm = {"teams", "flag_format", "protocol", "protocol_settings", "submit_limit", "submit_period", "flag_lifetime"} + if not isinstance(farm, dict) or set(farm) != required_farm: + raise Error("invalid farm profile") + if not isinstance(farm["teams"], dict) or not 1 <= len(farm["teams"]) <= 512: + raise Error("explicit bounded competition team map required") + for name, addr in farm["teams"].items(): + if not re.fullmatch(r"[A-Za-z0-9 _.-]{1,80}", name): + raise Error("invalid team label") + ipaddress.ip_address(addr) + if not isinstance(farm["flag_format"], str) or not 1 <= len(farm["flag_format"]) <= 512: + raise Error("explicit bounded competition flag format required") + # Only the reviewed JSON-scalar adapter configuration is accepted. This is + # not a claim that ructf_http is correct for any particular competition. + if farm["protocol"] != "ructf_http" or set(farm["protocol_settings"]) != {"SYSTEM_URL", "SYSTEM_TOKEN"}: + raise Error("only reviewed ructf_http adapter supported; other competition protocols need an adapter review") + import urllib.parse + endpoint = urllib.parse.urlsplit(farm["protocol_settings"]["SYSTEM_URL"]) + if endpoint.scheme not in {"http", "https"} or not endpoint.hostname or endpoint.username or endpoint.password: + raise Error("competition endpoint must be explicit HTTP(S), without embedded credentials") + for name in ("submit_limit", "submit_period", "flag_lifetime"): + if type(farm[name]) is not int or not 1 <= farm[name] <= 86400: + raise Error("invalid competition timing/limit setting") + if not isinstance(farm["protocol_settings"]["SYSTEM_TOKEN"], str) or not 1 <= len(farm["protocol_settings"]["SYSTEM_TOKEN"]) <= 512: + raise Error("competition token must be supplied privately") + return value + + +def validate_credentials(value): + if not isinstance(value, dict) or set(value) != {"farm_password", "database_password", "neo_key", "packmate_user", "packmate_password"}: + raise Error("invalid credential fields") + for name, text in value.items(): + pattern = r"[A-Za-z0-9_.-]{4,64}" if name == "packmate_user" else r"[A-Za-z0-9_.-]{20,128}" + if not isinstance(text, str) or not re.fullmatch(pattern, text) or text.startswith("REPLACE_"): + raise Error("credentials require safe generated ASCII values; passwords/key at least 20 characters") + return value + + +def compose_spec(profile, credentials, project, images): + spec = shared.compose_spec(project, images) + for name in ("receiver", "neo-client", "neo-client-denied"): + del spec["services"][name] + for name, service in spec["services"].items(): + service["labels"] = {LABEL: project} + service["restart"] = "unless-stopped" + service["platform"] = "linux/" + profile["platform"]["architecture"] + if "build" in service: + service["image"] = project + "-" + name + ":pinned" + if name in {"farm", "celery"}: + service["networks"] = ["fixture", "edge"] + service["environment"]["POSTGRES_DSN"] = "host=postgres port=5432 user=farm password=" + credentials["database_password"] + " dbname=farm" + service["environment"]["SERVER_PASSWORD"] = credentials["farm_password"] + service["depends_on"].pop("receiver", None) + if name == "postgres": + service["environment"]["POSTGRES_PASSWORD"] = credentials["database_password"] + if name in {"redis", "neo-redis"}: + service["healthcheck"] = {"test": ["CMD", "redis-cli", "ping"], "interval": "5s", "timeout": "2s", "retries": 12} + # Submission is opt-in so a restored deployment cannot send old queued data. + spec["services"]["celery"]["profiles"] = ["submission"] + for service, label in (("front", "farm"), ("neo-server", "neo")): + port = spec["services"][service]["ports"][0] + port.update(host_ip=profile["bind_address"], published=str(profile["ports"][label])) + spec["services"]["neo-worker"] = { + "image": LIGHT, "platform": "linux/" + profile["platform"]["architecture"], + "entrypoint": ["/usr/local/bin/neo"], "command": ["--verbose=false", "--config", "/client.yml", "run", "--jobs", "1"], + "user": "65534:65534", "read_only": True, "cap_drop": ["ALL"], "init": True, + "security_opt": ["no-new-privileges:true"], "cpus": 1.0, "mem_limit": "512m", "pids_limit": 64, + "volumes": ["./config/neo-client.yml:/client.yml:ro"], + "tmpfs": ["/work:rw,nosuid,nodev,size=268435456,mode=0700,uid=65534,gid=65534,exec"], + "working_dir": "/work", "networks": ["fixture", "edge"], "restart": "no", "profiles": ["worker"], + "labels": {LABEL: project}, "logging": {"driver": "none"}} + base = {"restart": "unless-stopped", "cpus": 1.0, "mem_limit": "512m", "pids_limit": 128, + "security_opt": ["no-new-privileges:true"], "logging": {"driver": "none"}, "labels": {LABEL: project}} + spec["services"]["packmate-db"] = dict(base, image=PACKMATE_DB, networks=["fixture"], + environment={"POSTGRES_USER": "packmate", "POSTGRES_DB": "packmate", "POSTGRES_PASSWORD": credentials["database_password"]}, + volumes=["./data/packmate-db:/var/lib/postgresql/data"], + healthcheck={"test": ["CMD", "pg_isready", "-U", "packmate", "-d", "packmate"], "interval": "5s", "timeout": "2s", "retries": 24}) + spec["services"]["packmate"] = dict(base, image=PACKMATE, platform="linux/amd64", user="65534:65534", + read_only=True, cap_drop=["ALL"], mem_limit="1536m", networks=["fixture", "edge"], + tmpfs=["/tmp:size=67108864,mode=1777,noexec,nosuid,nodev", "/jna:size=16777216,mode=0700,uid=65534,gid=65534,nosuid,nodev,exec"], + volumes=["./config/packmate.properties:/configuration/application.properties:ro", "./pcaps:/app/pcaps:ro"], + entrypoint=["java"], command=["-Xms64m", "-Xmx768m", "-XX:ActiveProcessorCount=1", "-Djna.tmpdir=/jna", "-jar", "/app/app.jar", + "--spring.config.additional-location=file:/configuration/application.properties"], + ports=[{"target": 65000, "published": str(profile["ports"]["packmate"]), "host_ip": profile["bind_address"], "protocol": "tcp"}], + depends_on={"packmate-db": {"condition": "service_healthy"}}) + for network in spec["networks"].values(): + network["labels"] = {LABEL: project} + return spec + + +def properties(profile, credentials): + pm = profile["packmate"] + pairs = {"spring.datasource.url": "jdbc:postgresql://packmate-db:5432/packmate", "spring.datasource.username": "packmate", + "spring.datasource.password": credentials["database_password"], "packmate.web.account-login": credentials["packmate_user"], + "packmate.web.account-password": credentials["packmate_password"], "packmate.capture-mode": pm["mode"], + "packmate.pcap-file": pm["pcap_file"], "packmate.local-ip": pm["local_ip"], "packmate.interface-name": pm["interface"], + "packmate.cleanup.enabled": "true" if pm["mode"] == "LIVE" else "false", + "packmate.cleanup.threshold": str(pm["retention_minutes"]), "server.port": "65000", "server.address": "0.0.0.0", + "logging.level." + LOGGER: "OFF"} + return "".join(key + "=" + value + "\n" for key, value in sorted(pairs.items())) + + +def model(spec, profile, image_ids=None): + services = [] + for name, service in sorted(spec["services"].items()): + mounts = [] + for mount in service.get("volumes", []): + source, target, *flags = mount.split(":") + scope = "approved-data" if source.startswith(("./data/", "./pcaps")) else "approved-config" + mounts.append({"kind": "bind", "target": target, "source_scope": scope, "read_only": "ro" in flags}) + for mount in service.get("tmpfs", []): + mounts.append({"kind": "tmpfs", "target": mount.split(":")[0], "source_scope": "approved-data", "read_only": False}) + role = "backend" if name in {"postgres", "redis", "neo-redis", "packmate-db"} else "worker" if name in {"celery", "neo-worker"} else "ui" if name in {"front", "packmate"} else "api" + services.append({"id": name, "role": role, "image": (image_ids or {}).get(name, service["image"]), + "architectures": ["amd64"] if name == "packmate" else [profile["platform"]["architecture"]], + "mode": "file" if name == "packmate" else "none", + "ports": [{"host_ip": p["host_ip"], "host_port": int(p["published"]), "container_port": p["target"], "protocol": p["protocol"]} for p in service.get("ports", [])], + "mounts": mounts, "privileged": False, "network_mode": "bridge", "capabilities": [], + "nonroot": service.get("user", "0").split(":")[0] != "0" if "user" in service else None, + "healthcheck": bool(service.get("healthcheck")), "memory_limit_mb": int(service["mem_limit"][:-1]), + "cpu_limit": service["cpus"], "restart": service["restart"]}) + return {"schema": "durkahelper.deployment-model.v1", "source_sha256": hashlib.sha256(shared.canonical(spec)).hexdigest(), + "platform": profile["platform"], "services": services} + + +def policy(profile, deployment_model): + return {"schema": "durkahelper.deployment-policy.v1", "team_lan": not ipaddress.ip_address(profile["bind_address"]).is_loopback, + "approved_bind_addresses": [profile["bind_address"]], + "approved_publications": [dict(service=s["id"], **{k: v for k, v in p.items() if k != "host_ip"}) for s in deployment_model["services"] for p in s["ports"]], + "approved_images": sorted({s["image"] for s in deployment_model["services"] if "@sha256:" in s["image"] or re.fullmatch(r"sha256:[a-f0-9]{64}", s["image"])}), + "require_healthcheck": True, "require_resource_limits": True, "require_nonroot": True, + "require_restart": True, "allow_amd64_emulation": profile["allow_amd64_emulation"], "approved_live_capture": []} + + +def write_build_files(workspace, images): + 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" + value = shared.pin_dockerfile(read(root / "docker" / role / "Dockerfile").decode(), replacements) + if role == "front": + value = value.replace("ENV PNPM_HOME=", 'ENV NODE_OPTIONS="--max-old-space-size=768"\nENV COREPACK_DEFAULT_TO_LATEST=0\nENV COREPACK_ENABLE_AUTO_PIN=0\nENV PNPM_HOME=') + value = value.replace("RUN corepack enable", 'RUN corepack enable && corepack prepare ' + shared.PNPM_DESCRIPTOR + ' --activate && test "$(pnpm --version)" = "' + shared.PNPM_VERSION + '"') + value = value.replace("COPY --from=front-build /app/dist /front", "COPY --from=front-build /app/dist /front\nRUN chmod -R a+rX /front") + shared.write(root / ("Dockerfile.fixture." + role), value) + root = workspace / "sources/neo" + value = shared.pin_dockerfile(read(root / "Dockerfile").decode(), replacements) + value = value.replace("ENV CGO_ENABLED=0", "ENV CGO_ENABLED=0\nENV GOMAXPROCS=1\nENV GOFLAGS=-p=1\nENV GOMEMLIMIT=768MiB") + shared.write(root / "Dockerfile.fixture", value) + + +def neo_farm_url(profile): + """Neo advertises this same URL to workers; bridge DNS is not LAN DNS.""" + if ipaddress.ip_address(profile["bind_address"]).is_loopback: + # Laptop-only demo with the bundled container worker, not LAN clients. + return "http://front" + return "http://" + profile["bind_address"] + ":" + str(profile["ports"]["farm"]) + + +def prepare(args): + profile = validate_profile(load(args.profile)) + credentials = validate_credentials(load(args.credentials)) + root = safe_path(args.workspace) + if root.exists(): + raise Error("deployment workspace must be new; existing data is never overwritten") + if not args.apply: + return {"status": "NOT_RUN", "action": "prepare", "source_pins": shared.PINS, + "effects": ["private source/config/data directory", "no downloads or Docker operations"], "not_validated": NOT_VALIDATED} + if os.name == "nt": + raise Error("private deployment creation requires POSIX permissions; Windows is preview/test only") + if profile["packmate"]["mode"] == "LIVE": + raise Error("LIVE needs a separately approved Linux capture namespace and database routing; this bridge deployment is FILE-only") + if profile["platform"]["architecture"] == "arm64" and not profile["allow_amd64_emulation"]: + raise Error("pinned Packmate image is amd64-only; explicit emulation acceptance required") + images = shared.image_map(ROOT / "config/integration-images.lock.json") + root.mkdir(mode=0o700) + project = "dh-deploy-" + secrets.token_hex(6) + for component in shared.PINS: + shared.export_source(getattr(args, component + "_source"), root / "sources" / component, component) + write_build_files(root, images) + for folder in ("postgres", "redis", "neo-redis", "neo", "packmate-db"): + (root / "data" / folder).mkdir(parents=True, mode=0o700) + (root / "pcaps").mkdir(mode=0o755) + farm = profile["farm"] + config = dict(DEBUG=False, TEAMS=farm["teams"], FLAG_FORMAT=farm["flag_format"], SYSTEM_PROTOCOL=farm["protocol"], + SUBMIT_FLAG_LIMIT=farm["submit_limit"], SUBMIT_PERIOD=farm["submit_period"], FLAG_LIFETIME=farm["flag_lifetime"], + SERVER_PASSWORD=credentials["farm_password"], TIMEZONE="UTC", **farm["protocol_settings"]) + shared.write(root / "config/farm.py", "CONFIG = " + repr(config) + "\n") + shared.write(root / "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: "' + neo_farm_url(profile) + '"\n password: "' + credentials["farm_password"] + '"\n') + shared.write(root / "config/neo-client.yml", 'host: "neo-server:5005"\ngrpc_auth_key: "' + credentials["neo_key"] + '"\nexploit_dir: "/work/exploits"\nclient_id: "deployment-worker"\n') + shared.write(root / "config/packmate.properties", properties(profile, credentials)) + for filename in ("neo-client.yml", "packmate.properties"): + (root / "config" / filename).chmod(0o644) # Individually mounted for UID 65534; private 0700 parent. + spec = compose_spec(profile, credentials, project, images) + shared.write(root / "compose.json", shared.canonical(spec)) + shared.write(root / "profile.json", shared.canonical(profile)) + deployment_model = model(spec, profile) + shared.write(root / "model.json", shared.canonical(deployment_model)) + shared.write(root / "policy.json", shared.canonical(policy(profile, deployment_model))) + files = {p.relative_to(root).as_posix(): hashlib.sha256(read(p, shared.MAX_SOURCE)).hexdigest() + for p in root.rglob("*") if p.is_file()} + shared.write(root / "deployment.json", shared.canonical({"schema": SCHEMA, "project": project, "files": files, + "source_pins": shared.PINS, "approval_id": args.approval_id})) + return {"status": "PASS", "action": "prepare", "project": project, "not_validated": NOT_VALIDATED, + "submission": "disabled; enable only after protocol and restored-queue review", "rollback": "retain private workspace; no services started"} + + +def workspace(path): + root = safe_path(path) + if os.name != "nt" and root.stat().st_mode & 0o077: + raise Error("deployment workspace must have private 0700 permissions") + state = load(root / "deployment.json") + if (not isinstance(state, dict) or set(state) != {"schema", "project", "files", "source_pins", "approval_id"} or + state["schema"] != SCHEMA or not re.fullmatch(r"dh-deploy-[a-f0-9]{12}", state["project"]) or state["source_pins"] != shared.PINS): + raise Error("invalid deployment ownership manifest") + if not isinstance(state["files"], dict) or not 1 <= len(state["files"]) <= 20000: + raise Error("invalid deployment file manifest") + for name, checksum in state["files"].items(): + if (not isinstance(name, str) or Path(name).is_absolute() or "\\" in name or ":" in name or + any(part in {"..", "."} for part in name.split("/")) or not re.fullmatch(r"[a-f0-9]{64}", checksum)): + raise Error("invalid deployment manifest member") + # Parent aliases are allowed for the operator's workspace, never inside it. + 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 deployment member") + if hashlib.sha256(read(candidate, shared.MAX_SOURCE)).hexdigest() != checksum: + raise Error("deployment immutable configuration/source changed; prepare a new deployment") + for folder in ("data", "data/postgres", "data/redis", "data/neo-redis", "data/neo", "data/packmate-db", "pcaps"): + if (root / folder).is_symlink() or not (root / folder).is_dir(): + raise Error("deployment data path must be a real directory") + return root, state, load(root / "compose.json"), validate_profile(load(root / "profile.json")) + + +def command(root, state, runtime=False): + return ["docker", "compose", "--project-name", state["project"], "--project-directory", str(root), "--file", str(root / ("runtime-compose.json" if runtime else "compose.json"))] + + +def owned_resources(state): + """All matched resources must carry BOTH the Compose and private owner labels.""" + project = state["project"] + for kind, listing in (("container", ["ps", "--all", "--quiet"]), ("network", ["network", "ls", "--quiet"])): + output = shared.checked(["docker"] + listing + ["--filter", "label=com.docker.compose.project=" + project], capture=True).decode().split() + if len(output) > 64 or any(not re.fullmatch(r"[a-f0-9]{12,64}", item) for item in output): + raise Error("unexpected project resource listing") + for identity in output: + fmt = '{{index .Config.Labels "' + LABEL + '"}}' if kind == "container" else '{{index .Labels "' + LABEL + '"}}' + actual = shared.checked(["docker", kind, "inspect", "--format", fmt, identity], capture=True).decode().strip() + if actual != project: + raise Error("ownership mismatch; refusing to affect project resources") + + +def image_preflight(spec, profile, require_build=True): + checks = {} + for name, svc in spec["services"].items(): + if "build" in svc and not require_build: + continue + actual = shared.checked(["docker", "image", "inspect", "--format", "{{.Id}};{{.Os}};{{.Architecture}}", svc["image"]], capture=True).decode().strip().split(";") + expected = "amd64" if name == "packmate" else profile["platform"]["architecture"] + if len(actual) != 3 or not re.fullmatch(r"sha256:[a-f0-9]{64}", actual[0]) or actual[1:] != ["linux", expected]: + raise Error("cached image architecture mismatch or invalid image identity") + checks[name] = actual[0] + return checks + + +def runtime_spec(spec, identities): + result = copy.deepcopy(spec) + if set(identities) != set(spec["services"]) or any(not isinstance(value, str) or not re.fullmatch(r"sha256:[a-f0-9]{64}", value) for value in identities.values()): + raise Error("every runtime service requires an exact immutable local image identity") + for name, identity in identities.items(): + result["services"][name]["image"] = identity + result["services"][name].pop("build", None) + return result + + +def check_build_receipt(root, spec, identities=None): + receipt = load(root / "build-receipt.json") + if receipt.get("schema") == "durkahelper.deployment-build.v1": + raise Error("legacy receipt does not pin all runtime images; prepare and build a new deployment before offline use") + if (set(receipt) != {"schema", "compose_sha256", "runtime_sha256", "images"} or receipt["schema"] != "durkahelper.deployment-build.v2" + or receipt["compose_sha256"] != hashlib.sha256(shared.canonical(spec)).hexdigest() + or set(receipt["images"]) != set(spec["services"])): + raise Error("build receipt does not match this deployment") + runtime = runtime_spec(spec, receipt["images"]) + if (load(root / "runtime-compose.json") != runtime or + hashlib.sha256(read(root / "runtime-compose.json")).hexdigest() != receipt["runtime_sha256"]): + raise Error("runtime Compose changed after immutable build receipt") + if identities is not None and identities != receipt["images"]: + raise Error("runtime image identities differ from immutable receipt") + return runtime + + +def wait_farm(profile, spec, timeout=60): + """Authenticate with the private configured password without emitting it.""" + url = "http://" + profile["bind_address"] + ":" + str(profile["ports"]["farm"]) + "/api/get_config" + opener = urllib.request.build_opener(urllib.request.ProxyHandler({}), shared.NoRedirect()) + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + request = urllib.request.Request(url, headers={"Authorization": spec["services"]["farm"]["environment"]["SERVER_PASSWORD"]}) + try: + with opener.open(request, timeout=3) as response: + raw = response.read(1024 * 1024 + 1) + if len(raw) > 1024 * 1024: + raise Error("farm readiness response exceeded its bound") + data = json.loads(raw) + if response.status == 200 and isinstance(data, dict) and data.get("TEAMS") == profile["farm"]["teams"] and data.get("SYSTEM_PROTOCOL") == profile["farm"]["protocol"]: + return + except (OSError, ValueError, urllib.error.URLError): + pass + time.sleep(0.5) + raise Error("authenticated farm readiness timed out; services retained for scoped down") + + +def cleanup_readiness_probes(state, name=None): + """Reconcile uncertain creates by exact name and both private labels. + + The down path also finds probes whose Docker create outlived an interrupted + CLI. Never infer ownership from a matching name alone or delete by a name. + """ + project = state["project"] + if not re.fullmatch(r"dh-deploy-[a-f0-9]{12}", project): + raise Error("invalid readiness project identity") + pattern = re.escape(project) + r"-readiness-[a-f0-9]{8}" + if name is not None and not re.fullmatch(pattern, name): + raise Error("invalid readiness probe name") + command = ["docker", "ps", "--all", "--quiet", "--no-trunc"] + if name is not None: + command += ["--filter", "name=^/" + name + "$"] + else: + command += ["--filter", "label=" + LABEL + "=" + project, + "--filter", "label=" + PROBE_LABEL + "=neo"] + identifiers = shared.checked(command, capture=True).decode().split() + if len(identifiers) > (1 if name else 64) or any(not re.fullmatch(r"[a-f0-9]{64}", item) for item in identifiers): + raise Error("unexpected readiness probe resource listing") + template = '{"id":{{json .Id}},"name":{{json .Name}},"owner":{{json (index .Config.Labels "' + LABEL + '")}},"purpose":{{json (index .Config.Labels "' + PROBE_LABEL + '")}}}' + for identity in identifiers: + observed = json.loads(shared.checked(["docker", "inspect", "--format", template, identity], capture=True)) + actual_name = observed.get("name", "") + if (observed.get("id") != identity or observed.get("owner") != project or observed.get("purpose") != "neo" or + not isinstance(actual_name, str) or not re.fullmatch("/" + pattern, actual_name) or + (name is not None and actual_name != "/" + name)): + raise Error("readiness probe ownership mismatch; cleanup refused") + shared.checked(["docker", "rm", "--force", identity], timeout=20) + + +def wait_neo(root, state, runtime, timeout=60): + """Info-only authenticated probe, nonroot and scoped to the owned bridge.""" + project = state["project"] + name = project + "-readiness-" + secrets.token_hex(4) + image = runtime["services"]["neo-worker"]["image"] + # The name is registered before issuing create: a cancelled CLI can leave + # a successful daemon-side create whose response was never observed. + attempted = False + try: + attempted = True + shared.checked(["docker", "create", "--name", name, "--label", LABEL + "=" + project, + "--label", PROBE_LABEL + "=neo", + "--network", project + "_fixture", "--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 / "config/neo-client.yml") + ",dst=/client.yml,readonly", + "--entrypoint", "/usr/local/bin/neo", image, "--verbose=false", "--config", "/client.yml", "info"], timeout=20) + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + try: + shared.checked(["docker", "start", "--attach", name], timeout=min(10, max(1, deadline - time.monotonic()))) + return + except Error: + time.sleep(0.5) + raise Error("authenticated Neo readiness timed out; services retained for scoped down") + finally: + if attempted: + cleanup_readiness_probes(state, name) + + +def execute(args): + root, state, spec, profile = workspace(args.workspace) + cmd = command(root, state) + if args.action == "model": + return model(check_build_receipt(root, spec), profile) if (root / "build-receipt.json").exists() else model(spec, profile) + if args.action == "preflight": + result = {"status": "PASS", "action": "preflight", "configuration_integrity": "PASS", + "runtime": "NOT_RUN", "not_validated": NOT_VALIDATED, "competition_ready": False} + if args.runtime: + runtime = check_build_receipt(root, spec) + shared.checked(command(root, state, runtime=True) + ["config", "--quiet"]) + owned_resources(state) + result["cached_image_ids"] = image_preflight(runtime, profile) + check_build_receipt(root, spec, result["cached_image_ids"]) + result["runtime"] = "PASS" + return result + if not args.apply: + return {"status": "NOT_RUN", "action": args.action, "project": state["project"], + "effects": ["project-scoped Docker operation"], "rollback": "down retains data and images"} + if os.name == "nt": + raise Error("deployment mutations require POSIX permissions") + owned_resources(state) + shared.checked(cmd + ["config", "--quiet"]) + if args.action == "build": + if not args.connected_preparation: + raise Error("build requires --connected-preparation; prepare dependencies before offline rehearsal") + if (root / "build-receipt.json").exists(): + raise Error("deployment already built; prepare a new workspace instead of overwriting its receipt") + for name in BUILD_SERVICES: + svc = spec["services"][name] + build = svc["build"] + shared.checked(["docker", "build", "--platform", svc["platform"], "--memory", "1536m", "--memory-swap", "1536m", + "--cpu-period", "100000", "--cpu-quota", "100000", "--tag", svc["image"], "--file", + str(root / build["context"] / build["dockerfile"]), str(root / build["context"])], timeout=1800, + environment=dict(os.environ, DOCKER_BUILDKIT="0")) + # Docker save/load by ID deliberately loses tags and RepoDigests. Pin + # *every* service to its verified platform-specific configuration ID, + # including databases and externally published runtime images. + identities = image_preflight(spec, profile) + runtime = runtime_spec(spec, identities) + runtime_data = shared.canonical(runtime) + shared.write(root / "runtime-compose.json", runtime_data) + runtime_model = model(runtime, profile) + shared.write(root / "runtime-model.json", shared.canonical(runtime_model)) + shared.write(root / "runtime-policy.json", shared.canonical(policy(profile, runtime_model))) + shared.write(root / "build-receipt.json", shared.canonical({"schema": "durkahelper.deployment-build.v2", + "compose_sha256": hashlib.sha256(shared.canonical(spec)).hexdigest(), "runtime_sha256": hashlib.sha256(runtime_data).hexdigest(), "images": identities})) + return {"status": "PASS", "action": "build", "image_ids": identities, + "rollback": "images retained; interrupted builds may require inspection of exact build identity"} + if args.action == "down": + cleanup_readiness_probes(state) + shared.checked(cmd + ["--profile", "submission", "--profile", "worker", "down", "--timeout", "15"], timeout=90) + return {"status": "PASS", "action": "down", "rollback": "data and images retained; up recreates only this project"} + runtime = check_build_receipt(root, spec) + check_build_receipt(root, spec, image_preflight(runtime, profile)) + cmd = command(root, state, runtime=True) + if args.action == "up": + pcap = safe_path(root / "pcaps" / profile["packmate"]["pcap_file"]) + if not pcap.is_file() or pcap.is_symlink(): + raise Error("FILE mode requires an operator-provided closed regular PCAP before startup") + # The retained Neo server fetches farm configuration once at startup. + # Compose's service_started condition is insufficient for that contract. + shared.checked(cmd + ["up", "--detach", "--no-build", "--pull", "never"] + [name for name in SERVICES if name != "neo-server"], timeout=180) + wait_farm(profile, spec) + shared.checked(cmd + ["up", "--detach", "--no-build", "--pull", "never", "neo-server"], timeout=60) + wait_neo(root, state, runtime) + elif args.action == "enable-submission": + if not args.protocol_reviewed or not args.queue_reviewed: + raise Error("submission requires --protocol-reviewed and --queue-reviewed") + shared.checked(cmd + ["--profile", "submission", "up", "--detach", "--no-build", "--pull", "never", "celery"], timeout=60) + elif args.action == "worker": + shared.checked(cmd + ["--profile", "worker", "up", "--detach", "--no-build", "--pull", "never", "neo-worker"], timeout=60) + return {"status": "PASS", "action": args.action, "readiness": {"farm_authenticated": "PASS", "neo_authenticated": "PASS", "packmate": "NOT_RUN", "team_lan": "NOT_RUN"} if args.action == "up" else "NOT_RUN", "not_validated": NOT_VALIDATED, + "rollback": "run down with the same workspace and approval; no volumes or data are deleted"} + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("action", choices=["prepare", "preflight", "model", "build", "up", "down", "worker", "enable-submission"]) + parser.add_argument("--workspace", required=True) + for option in ("profile", "credentials", "s4dfarm-source", "neo-source", "approval-id"): + parser.add_argument("--" + option) + for option in ("apply", "runtime", "connected-preparation", "protocol-reviewed", "queue-reviewed"): + parser.add_argument("--" + option, 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.profile, args.credentials, args.s4dfarm_source, args.neo_source)): + raise Error("prepare requires profile, credentials and both pinned source checkout paths") + result = prepare(args) if args.action == "prepare" else execute(args) + print(json.dumps(result, sort_keys=True, indent=2)) + return 0 + except KeyboardInterrupt: + print(json.dumps({"status": "BLOCKED", "reason": "interrupted; inspect exact owned project before retry; data retained"})) + return 2 + except (Error, OSError, ValueError, KeyError, TypeError, AttributeError, subprocess.SubprocessError) as error: + reason = str(error) if isinstance(error, Error) else "operation rejected: " + type(error).__name__ + print(json.dumps({"status": "BLOCKED", "reason": reason, "raw_output": "suppressed"})) + return 2 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/docs/ADMIN_WORKFLOWS-RU.md b/docs/ADMIN_WORKFLOWS-RU.md new file mode 100644 index 0000000..0d245e1 --- /dev/null +++ b/docs/ADMIN_WORKFLOWS-RU.md @@ -0,0 +1,170 @@ + +# Рабочие процессы администратора + +[English](ADMIN_WORKFLOWS.md) | Русский + +Практический маршрут для одного администратора и доверенной команды. Карточки и ручное переписывание hashes не требуются. Сохраните этот checkout, русские инструкции и приватные зависимости для офлайн-работы. [Короткая памятка для печати](TEAM_LAN_ADMIN_CHEATSHEET-RU.md). + + +## Роли и правила выполнения команд + +DurkaHelper готовит и управляет стеком. S4DFarm собирает результаты и отправляет их жюри. Координатор Neo хранит задания и планирует исполнение; **workers выполняют их и отправляют совпадающие с форматом значения stdout прямо в ферму**. Участники подключают управляющие клиенты к одному координатору; отдельный worker каждому не нужен. Packmate анализирует трафик. Сканер проверяет локальные копии исходников; патчи применяются вручную штатным механизмом развёртывания сервиса. + +Команды ниже выполняются **из корня DurkaHelper на Mac/Linux администратора**, кроме явно обозначенного терминала Neo. Выберите один конфиг и указывайте его во всех командах стека: + +```bash +DURKA_CONFIG=local/competition.json +``` + +В каждом новом терминале задайте переменную снова. `local/durka.json` — конфиг CLI по умолчанию, встречающийся в старых тематических примерах; не запустите случайно второе окружение. Примерные адреса предназначены для документации, а не работы на соревновании. `doctor`, `status` и `scan` — read-only; `init`, `setup`, `configure`, `up`, `worker`, `submit`, импорт и `down` меняют приватные файлы или собственные сервисы. Не используйте общий prune, Docker reset или `down -v`. + + +## Workflow 01 — Развёртывание и подготовка офлайн + +**Нужно заранее:** одобренные Python 3.10+, Git 2.30+, Docker Desktop/Engine с Compose v2; свободные диск и RAM; список команд, IP сервисов, формат флага, параметры жюри и разрешённый LAN-адрес от организаторов. Первая подготовка требует Интернета. Время: 30–60 минут впервые; около 5 минут для подготовленного запуска. [Первый запуск Mac](MACOS_FIRST_RUN-RU.md) описывает установку; [полный гайд](MACOS_FULL_DEPLOYMENT_AND_TESTING-RU.md) служит справочником. + +Только для новой установки: + +```bash +python3 durka.py --config "$DURKA_CONFIG" init +``` + +Откройте этот приватный JSON редактором. Сохраните сгенерированные credentials. В `profile.bind_address` укажите настоящий LAN IPv4 администратора для команды/native workers; выберите свободные `profile.ports.farm/neo/packmate`. Заполните `profile.farm.teams`, `flag_format`, `protocol_settings.SYSTEM_URL/SYSTEM_TOKEN`, `submit_limit`, `submit_period` и `flag_lifetime` по данным организаторов. `protocol: ructf_http` подходит только совместимому HTTP-интерфейсу. FILE `profile.packmate.local_ip` — **IP стороны сервиса в захваченных пакетах**, не адрес администратора. После подготовки не меняйте пути sources/workspace и платформу. + +```bash +python3 durka.py --config "$DURKA_CONFIG" doctor +python3 durka.py --config "$DURKA_CONFIG" setup +python3 durka.py --config "$DURKA_CONFIG" up +python3 durka.py --config "$DURKA_CONFIG" status +``` + +`setup` скачивает/собирает закреплённые зависимости: выполните его до поездки, не во время офлайн-игры. `up` использует подготовленные образы и запускает БД → Farm → координатор Neo → Packmate. Worker и отправка включаются отдельно. Откройте напечатанные URL Farm/Packmate, войдите, проверьте список команд и повторите с другого устройства. Внутренние БД не являются интерфейсами команды. У Neo нет web-dashboard. Передавайте UI credentials и ключ Neo приватно, вне публичных скриншотов. + +**Уже подготовлено:** пропустите `init/setup`. Чтобы применить настройки организаторов, остановите native worker и собственный стек, измените тот же JSON, затем: + +```bash +python3 durka.py --config "$DURKA_CONFIG" configure +python3 durka.py --config "$DURKA_CONFIG" up +python3 durka.py --config "$DURKA_CONFIG" status +``` + +`configure` требует остановленного стека и не меняет credentials, платформу или структуру хранилищ. При ошибке обновления оставьте стек остановленным и используйте `configure --rollback`. При проблемах LAN проверяйте фактические bind/IP, порты и согласованные настройки application firewall; не отключайте защиту сети целиком. + +**Офлайн-проверка:** сохраните кеш исходников, образы/данные Docker, приватные конфиг/workspace, совместимый Neo binary и все зависимости скриптов. Отдельный Linux LIVE bundle готовится в Workflow 05. Разрешённым способом уберите Интернет, оставив нужную LAN; выполните `down`, `up`, `status`, войдите в оба UI, запустите безвредное задание Neo, просканируйте локальную копию и импортируйте закрытый PCAP. Это проверка перезапуска подготовленной машины, не установки на пустую машину. [Офлайн-подготовка и чистое окружение игры](offline-bundles-RU.md). + + +## Workflow 02 — Сканирование, патч и проверка + +**Нужно:** разрешённая локальная копия исходников, порядок запуска/checker сервиса и ответственный за rollback. Рабочий каталог — корень репозитория; время 10–30 минут на небольшой патч, в зависимости от сервиса. + +```bash +python3 durka.py scan /path/to/service --patches +``` + +Exit `1` — сигналы для разбора; `2` — неполный/некорректный вход. Прочитайте связанную рекомендацию, подтвердите применимость, сохраните оригиналы изменяемых файлов и при необходимости консистентный native backup БД. Примените один минимальный патч **вручную**. Прогоните regression tests сервиса, обычные login/read/write сценарии, старые данные и настоящий checker соревнования; повторите скан. Чистый скан или `/health` недостаточны. Единой restart-команды для всех Vulnbox нет: используйте механизм конкретного сервиса, а не `down/up` тулсета. + +При регрессии восстановите предыдущие код/образ с сохранением текущих игровых данных. Не накатывайте старую БД поверх записей новых раундов. [Проверка патча](patch-validation-RU.md) содержит подробности; расширенные records для `patch-check` необязательны в этом ручном маршруте. [Backup/recovery](../deployment/README-RU.md#native-backup-and-quarantine-restore) относится к стеку тулсета, а не любому защищаемому сервису. + + +## Workflow 03 — Скрипты и исполнение Neo + +**Нужно:** совместимый Neo v2.4.2 client, приватный конфиг с реальными host/key координатора, согласованные ID заданий и разрешённый список команд. У каждого worker должны быть настоящий интерпретатор, пакеты, вспомогательные файлы и маршруты к Farm и разрешённым сервисам. Встроенный light-worker предоставляет shell, не произвольные Python/Sage packages. Время: 10–15 минут для первого безвредного задания. [Установка Neo и полные примеры](neo-RU.md). + +В **отдельном терминале**, из корня репозитория, можно запустить shell-only worker: + +```bash +python3 durka.py --config "$DURKA_CONFIG" worker +``` + +Или из каталога распакованного **Neo client** запустите один подготовленный native worker; для администрирования заданий оба одновременно не нужны: + +```bash +./neo --verbose=false --config client_config.yml run --jobs 1 --endless-jobs 0 +``` + +Используйте приватный клиентский конфиг с уникальным worker `client_id` и корректным каталогом заданий. В чистом deployment можно вместо него использовать с подготовленным binary сгенерированный `config/neo-native.yml`; после смены LAN исправьте host либо передайте `--host LAN_IP:NEO_PORT`. Внешним workers недоступно внутреннее имя Farm из loopback-профиля. + +В каталоге **Neo client автора** создайте безвредный `exploits/ready.sh` из гайда Neo, затем: + +```bash +chmod u+x exploits/ready.sh +./neo --verbose=false --config client_config.yml add --id ready-author-a --disabled --interval 1m --timeout 3s exploits/ready.sh +./neo --verbose=false --config client_config.yml single ready-author-a +./neo --verbose=false --config client_config.yml tail --count 20 ready-author-a +``` + +Перед `single` дождитесь скачивания нового задания worker и перезапуска его execution loops. Ожидается `worker ready for ...`, не флаг. `single` охватывает **все настроенные команды**, не включает повторение. Каждый автор использует отдельный общий ID. После успешного разрешённого одиночного прогона намеренно проверьте расписание: + +```bash +./neo --verbose=false --config client_config.yml enable ready-author-a +./neo --verbose=false --config client_config.yml tail --count 20 ready-author-a +./neo --verbose=false --config client_config.yml disable ready-author-a +``` + +Дождитесь следующих запусков с интервалом в минуту перед отключением. Cron не нужен; закрытие управляющего клиента не отключает задание. После отключения новых запусков остановите native worker через Ctrl+C; уже исполняемые задания могут завершиться. При сбое сначала проверьте наличие/скачивание worker, интерпретатор и маршруты. Не показывайте raw `neo info` или debug logs на экране: они могут раскрыть credentials. + + +## Workflow 04 — Ферма и отправка жюри + +**Нужно:** согласованные endpoint/token жюри, точные regex флага, lifetime и rate limits; легитимное синтетическое либо предоставленное организаторами тестовое значение. Время: 5–10 минут. С placeholders отправку не включайте. [Справочник фермы](s4dfarm-RU.md). + +Совместимый интерфейс ForcAD использует **HTTP PUT `/flags`**, JSON-массив флагов и заголовок `X-Team-Token`. Настройте полный URL организатора и приватный token через Workflow 01; не переносите путь, лимиты или token с другого соревнования. Поддерживаемый adapter — `ructf_http`; другой протокол требует отдельной проверки, не непроверенной подмены адаптера. + +Убедитесь, что разрешённый тестовый stdout worker появился в Farm, затем из корня репозитория включите отправку: + +```bash +python3 durka.py --config "$DURKA_CONFIG" submit +``` + +`QUEUED` подтверждает только приём в ферму. Проверьте окончательный статус **и ответ receiver**, а также жюри/scoreboard, если доступно. Invalid, duplicate и expired проверяйте на контролируемом синтетическом жюри; не делайте массовую повторную отправку на реальном событии. Deduplication Farm может подавить второе одинаковое значение до HTTP-запроса. `SKIPPED` бывает локальной политикой очереди, не ответом ForcAD. Если очередь зависла, проверьте включение отправки, endpoint/token, lifetime, rate limits и связь worker → Farm. Не печатайте tokens при диагностике. + +Чтобы безопасно остановить отправку, отключите новые задания Neo, остановите native workers и выполните `down` выбранного стека. После `up` отправка включается явно снова. Перед включением проверьте восстановленные очереди: нельзя слепо переотправлять просроченные данные. + + +## Workflow 05 — Packmate LIVE или FILE + +**Нужно:** разрешённый источник трафика. Mac на обычном Ethernet не видит весь трафик Vulnbox. FILE анализирует закрытые файлы, **не является непрерывным LIVE**. Время: 10–20 минут для подготовленного Linux LIVE; 3–5 минут на FILE import. [Варианты трафика](traffic-capture-RU.md) и [инструкция удалённого LIVE](packmate-remote-RU.md). + +На машине администратора при наличии Интернета один раз подготовьте **отдельную пару Linux AMD64 образов**. ARM64-образ БД с Mac не заменяет её: + +```bash +python3 durka.py traffic live bundle --output local/packmate-live-ready --download --apply +``` + +Уже успешный bundle сохраните; команда требует нового output path. Python на целевой машине не нужен. Linux LIVE требует rootful Docker/Compose, проверенную SSH identity, явно разрешённый **интерфейс целиком** и согласие на host networking + NET_RAW. Privileged container, NET_ADMIN и Docker socket mount не нужны. Сначала выполните read-only discovery с настоящими разрешёнными host/key: + +```bash +python3 durka.py traffic live doctor --host example@vulnbox.example --key ~/.ssh/ctf_capture +``` + +`--docker /absolute/approved-wrapper` нужен только если обычный `docker` недоступен пользователю; passwordless sudo не выбирается автоматически. Doctor не меняет права/firewall. Проверьте SSH fingerprint по доверенному каналу. Затем создайте новый приватный конфиг цели с фактическими результатами doctor: + +```bash +python3 durka.py traffic live init --host example@vulnbox.example --key ~/.ssh/ctf_capture --remote-dir /home/example/durka-packmate-live --interface eth0 --service-ip 192.0.2.10 --bind 192.0.2.20 --ui-port 65000 --db-port 55432 +``` + +**Конфигурация заполняется здесь, до `up`:** при необходимости измените `local/packmate-remote.json`. В его `profile` находятся interface, IP стороны сервиса, Linux UI bind/ports, TCP/UDP timeouts и retention. `bind` назначен Linux, не Mac. БД доступна только через loopback. **Названия сервисов, порты и шаблоны поиска регистрируются отдельно в UI Packmate**. Сгенерированные application properties/Compose не редактируйте. Правка JSON после deployment не перенастраивает работающую установку; перед созданием замены прочитайте удалённый гайд. + +```bash +python3 durka.py traffic live doctor --bundle local/packmate-live-ready +python3 durka.py traffic live up --bundle local/packmate-live-ready --apply --host-network-approved --interface-scope-approved +python3 durka.py traffic live status +``` + +Это переносит и загружает готовые образы без Интернета на цели, затем запускает только собственный project. Меняются удалённые приватные файлы/контейнеры, используются одобренные capture privileges. Откройте напечатанный URL, войдите с данными приватного конфига; на Mac `traffic live password` копирует пароль, не печатая его. Зарегистрируйте реальные порты обоих сервисов. Выполните обычный известный запрос: проверьте запрос/ответ, направление относительно сервиса, timestamps и checker health, затем перезапуск capture через собственные `down --apply` / `up ...`. Retention ограничивает возраст, не жёсткий размер диска; следите за диском. Readiness/authentication PASS сами по себе не доказывают захват. + +Для FILE получите **закрытый** PCAP разрешённым порядком захвата/передачи. Из checkout администратора: + +```bash +python3 durka.py --config "$DURKA_CONFIG" traffic import /path/to/closed-capture.pcap +python3 durka.py --config "$DURKA_CONFIG" status +``` + +Выберите/зарегистрируйте сервис в локальном UI Packmate и один раз нажмите **жёлтую кнопку обработки со стрелкой вниз**; не ищите подпись Start или Load PCAPs. Дождитесь обработки, найдите известный запрос и ответ, затем повторите с другим закрытым файлом. Import сохраняет предыдущий файл и перезапускает только Packmate. Пусто: проверьте IP сервиса, порт/шаблон, известный marker, состояние обработки и timestamps потоков; не предполагается наличие фильтра времени. На Apple Silicon Packmate использует AMD64 emulation; измерьте задержку локально. + +**Остановка/восстановление:** остановите новые входные данные, сохраните нужные приватные данные, выполните `traffic live down --apply` только для этого настроенного Linux capture; `durka.py --config "$DURKA_CONFIG" down` — для локального стека. Оба сохраняют данные/образы. Не удаляйте live-файлы БД. Если LIVE запрещён или трафик не виден, используйте FILE как резерв и отмечайте отсутствие continuous capture. [Native recovery и отдельный restore](../deployment/README-RU.md#native-backup-and-quarantine-restore) и [офлайн-гайд](offline-bundles-RU.md) описывают восстановление; restore нужно проверить отдельно, прежде чем полагаться на него. + + +## Финальные проверки оператора + +Войдите с каждого участвующего устройства; выполните полезное действие UI и переподключение. Проверьте фактическую среду каждого скрипта, приём Farm → жюри, разрешённый LIVE либо closed FILE, офлайн-перезапуск под обычной нагрузкой. Маршруты события, capture permission и настройки организаторов проверяются на конкретном соревновании. Linux tests и hosted macOS CI не доказывают совместимость Docker Desktop, командной LAN или локальных правил. Невыполненные проверки — **NOT TESTED**, не готовность. diff --git a/docs/ADMIN_WORKFLOWS.md b/docs/ADMIN_WORKFLOWS.md new file mode 100644 index 0000000..2cdd83c --- /dev/null +++ b/docs/ADMIN_WORKFLOWS.md @@ -0,0 +1,162 @@ +# Administrator workflows + +English | [Русский](ADMIN_WORKFLOWS-RU.md) + +The practical route for one administrator and a trusted team. No evidence cards or manually copied hashes are required. Keep this checkout, its Russian pages and private dependencies available offline. [Printable quick reference](TEAM_LAN_ADMIN_CHEATSHEET.md). + +## Roles and command conventions + +DurkaHelper prepares and controls the stack. S4DFarm collects results and submits them to the jury. Neo's coordinator stores tasks and schedules execution; **workers execute them and send matching stdout values directly to the farm**. Participants use control clients connected to the same coordinator; they do not each need a worker. Packmate analyzes traffic. The scanner reviews local source copies; patches are applied manually through the service's own deployment mechanism. + +Commands below run in the **DurkaHelper repository root on the administrator's Mac/Linux machine**, except the explicitly marked Neo terminal. Choose one config and use it on every stack command: + +```bash +DURKA_CONFIG=local/competition.json +``` + +Set this variable again in each new terminal. `local/durka.json` is the CLI default and appears in older topic examples; do not accidentally operate a second deployment. Example addresses are documentation values, not working event targets. Read-only commands are `doctor`, `status` and `scan`; `init`, `setup`, `configure`, `up`, `worker`, `submit`, imports and `down` change private files or owned services. Never use global prune, Docker reset or `down -v`. + +## Workflow 01 — Deploy and prepare offline + +**Before:** approved Python 3.10+, Git 2.30+, Docker Desktop/Engine with Compose v2; sufficient disk and RAM; organizer's team map, service IPs, flag format, jury settings and permitted LAN address. First-time preparation needs Internet. Allow 30–60 minutes initially; about 5 minutes for a prepared start. [First Mac run](MACOS_FIRST_RUN.md) covers installation; [full guide](MACOS_FULL_DEPLOYMENT_AND_TESTING.md) is the reference. + +For a new installation only: + +```bash +python3 durka.py --config "$DURKA_CONFIG" init +``` + +Edit that private JSON in an editor. Preserve generated credentials. Set `profile.bind_address` to the administrator's actual LAN IPv4 for team/native-worker access; choose free `profile.ports.farm/neo/packmate`. Set `profile.farm.teams`, `flag_format`, `protocol_settings.SYSTEM_URL/SYSTEM_TOKEN`, `submit_limit`, `submit_period` and `flag_lifetime` from the organizers. Keep `protocol: ructf_http` only for the compatible HTTP interface. Set FILE `profile.packmate.local_ip` to the **service-side IP in captured packets**, not the administrator's address. Leave source/workspace paths and platform unchanged after preparation. + +```bash +python3 durka.py --config "$DURKA_CONFIG" doctor +python3 durka.py --config "$DURKA_CONFIG" setup +python3 durka.py --config "$DURKA_CONFIG" up +python3 durka.py --config "$DURKA_CONFIG" status +``` + +`setup` downloads/builds pinned dependencies; do it before travel, not during an offline game. `up` uses prepared images and starts databases → Farm → Neo coordinator → Packmate. Worker and submission are separate opt-ins. Open the printed Farm/Packmate URLs, authenticate, check the team map and repeat from a second device. Internal databases are not team interfaces. Neo has no web dashboard. Share UI credentials and the Neo key privately, away from public screenshots. + +**Already prepared:** skip `init/setup`. To apply organizer settings, stop the native worker and owned stack, edit the same JSON, then: + +```bash +python3 durka.py --config "$DURKA_CONFIG" configure +python3 durka.py --config "$DURKA_CONFIG" up +python3 durka.py --config "$DURKA_CONFIG" status +``` + +`configure` requires a stopped stack and cannot change credentials, platform or storage layout. If its update fails, keep the stack stopped and use `configure --rollback`. If LAN fails, check actual bind/IP, ports and approved application firewall settings; do not disable network security globally. + +**Offline checkpoint:** retain the source cache, Docker images/data, private config/workspace, compatible Neo binary and every script dependency. Prepare the separate Linux LIVE bundle in Workflow 05. Using a permitted arrangement with Internet absent but required LAN intact, run `down`, `up`, `status`; authenticate both UIs, run a harmless Neo task, scan a local copy and import a closed PCAP. This proves restart on the prepared machine, not installation on a blank machine. [Offline preparation and clean event state](offline-bundles.md). + +## Workflow 02 — Scan, patch and verify + +**Before:** an authorized local source copy, service startup/checker procedure and rollback owner. Run from the repository root; allow 10–30 minutes per small patch, depending on the service. + +```bash +python3 durka.py scan /path/to/service --patches +``` + +Exit `1` means review findings; `2` means incomplete/invalid input. Read the linked remediation, confirm applicability and preserve original changed files plus a consistent native database backup when needed. Apply one minimal patch **manually**. Run the service's regression tests, normal login/read/write scenarios, old-data checks and actual competition checker; repeat the scan. A clean scan or `/health` alone is insufficient. No generic restart command exists for every Vulnbox: use the supplied service mechanism, not the toolkit's `down/up`. + +If functionality regresses, restore previous code/image while preserving current game data. Do not restore an old database over new-round records. [Patch validation](patch-validation.md) gives detailed checks; its advanced `patch-check` records are optional for this manual route. [Backup/recovery](../deployment/README.md#native-backup-and-quarantine-restore) applies to the toolkit stack, not every protected service. + +## Workflow 03 — Prepare scripts and Neo execution + +**Before:** compatible Neo v2.4.2 client, private config with actual coordinator host/key, agreed task IDs and allowed team list. Every worker needs the script's actual interpreter, packages, auxiliary files and routes to both Farm and permitted services. The bundled light worker supplies shell, not arbitrary Python/Sage packages. Allow 10–15 minutes for the first harmless task. [Neo installation and complete examples](neo.md). + +In a **separate terminal**, a shell-only worker can be started from the repository root: + +```bash +python3 durka.py --config "$DURKA_CONFIG" worker +``` + +Alternatively, in the extracted **Neo client directory**, start one prepared native worker; do not start both merely to administer tasks: + +```bash +./neo --verbose=false --config client_config.yml run --jobs 1 --endless-jobs 0 +``` + +Use a private client config with a unique worker `client_id` and valid task directory. A generated clean deployment's `config/neo-native.yml` can be used with the prepared binary instead; after a LAN change update its host or pass `--host LAN_IP:NEO_PORT`. Outside workers cannot use the container-only Farm hostname from a loopback profile. + +In the author's **Neo client directory**, create the harmless `exploits/ready.sh` from the Neo guide, then: + +```bash +chmod u+x exploits/ready.sh +./neo --verbose=false --config client_config.yml add --id ready-author-a --disabled --interval 1m --timeout 3s exploits/ready.sh +./neo --verbose=false --config client_config.yml single ready-author-a +./neo --verbose=false --config client_config.yml tail --count 20 ready-author-a +``` + +Wait for the worker to download the new task and restart its execution loops before `single`. Expected: `worker ready for ...`, not a flag. `single` covers **all configured teams**, without enabling recurrence. Each author uses a distinct shared ID. After a successful permitted single run, deliberately test scheduling: + +```bash +./neo --verbose=false --config client_config.yml enable ready-author-a +./neo --verbose=false --config client_config.yml tail --count 20 ready-author-a +./neo --verbose=false --config client_config.yml disable ready-author-a +``` + +Observe subsequent one-minute runs before disabling. No cron is needed; closing the control client does not disable a task. Stop a native worker with Ctrl+C after disabling future work; already running jobs may finish. For failures, first check worker presence/download, interpreter and routes. Avoid raw `neo info` or debug logs on screen: they may disclose credentials. + +## Workflow 04 — Farm and jury submission + +**Before:** approved jury endpoint/token, exact flag regex, lifetime and rate limits; a legitimate synthetic or organizer-provided test value. Allow 5–10 minutes. Do not enable against placeholders. [Farm reference](s4dfarm.md). + +ForcAD's compatible interface uses **HTTP PUT `/flags`**, a JSON array of flags and the `X-Team-Token` header. Configure the full organizer-provided URL and private token via Workflow 01; do not assume the path, limits or token from another event. The maintained adapter is `ructf_http`; another protocol requires separate validation, not an untested adapter substitution. + +Confirm the worker's permitted test output appears in Farm, then enable submission from the repository root: + +```bash +python3 durka.py --config "$DURKA_CONFIG" submit +``` + +`QUEUED` proves ingestion only. Verify the final status **and receiver response**, plus jury/scoreboard confirmation where provided. Use a controlled synthetic jury to check invalid, duplicate and expired results; do not mass-resubmit to a real event. Farm deduplication may suppress a second identical value before any HTTP request. `SKIPPED` can be local queue policy, not a ForcAD response. If queued indefinitely, check enabled submission, endpoint/token, lifetime, rate limits and worker-to-Farm reachability. Never print tokens during diagnostics. + +To stop submission safely, disable future Neo tasks, stop native workers and run the selected stack's `down`. Restart with `up`; submission must be explicitly enabled again. Review restored queues before enabling: expired recovered data must not be replayed blindly. + +## Workflow 05 — Packmate LIVE or FILE + +**Before:** an authorized traffic source. A Mac on ordinary Ethernet does not see all Vulnbox traffic. FILE is closed-file analysis, **not continuous LIVE**. Allow 10–20 minutes for a prepared Linux LIVE deployment; 3–5 minutes per FILE import. [Traffic choices](traffic-capture.md) and [remote LIVE instructions](packmate-remote.md). + +On the administrator's machine, while online, prepare the **separate Linux AMD64 image pair** once. A Mac's ARM64 database image is not a substitute: + +```bash +python3 durka.py traffic live bundle --output local/packmate-live-ready --download --apply +``` + +Keep an already successful bundle; this command requires a new output path. Target Python is not required. Linux LIVE needs rootful Docker/Compose, verified SSH identity, an explicitly permitted **whole interface**, and approval for host networking + NET_RAW. No privileged container, NET_ADMIN or Docker socket mount is required. First run read-only discovery, using the actual authorized host/key: + +```bash +python3 durka.py traffic live doctor --host example@vulnbox.example --key ~/.ssh/ctf_capture +``` + +Use `--docker /absolute/approved-wrapper` only if ordinary `docker` is unavailable to that user; passwordless sudo is not automatically selected. No permission/firewall changes are made by doctor. Verify the SSH fingerprint through a trusted channel. Then initialize a new private target config using actual doctor results: + +```bash +python3 durka.py traffic live init --host example@vulnbox.example --key ~/.ssh/ctf_capture --remote-dir /home/example/durka-packmate-live --interface eth0 --service-ip 192.0.2.10 --bind 192.0.2.20 --ui-port 65000 --db-port 55432 +``` + +**Configuration happens here, before `up`:** edit `local/packmate-remote.json` if necessary. Its `profile` holds interface, service-side IP, Linux UI bind/ports, TCP/UDP timeouts and retention. `bind` is an address assigned to Linux, not the Mac. The database is loopback-only. Service **names, ports and search patterns are registered separately in the Packmate UI**. Do not edit generated application properties/Compose files. Editing JSON after deployment does not reconfigure the running installation; see the remote guide before creating a replacement. + +```bash +python3 durka.py traffic live doctor --bundle local/packmate-live-ready +python3 durka.py traffic live up --bundle local/packmate-live-ready --apply --host-network-approved --interface-scope-approved +python3 durka.py traffic live status +``` + +This transfers and loads prepared images without target Internet, then starts only the owned project. It changes remote private files/containers and uses approved capture privileges. Open its printed URL, authenticate using the private config; on Mac `traffic live password` copies the password without printing it. Register both services' real ports. Produce a normal known request: verify its request/response, service-side direction, timestamps and checker health, then test capture restart using scoped `down --apply` / `up ...`. Retention limits age, not hard disk capacity; watch disk usage. Readiness/authentication PASS alone does not prove captured traffic. + +For FILE, obtain a **closed** PCAP through the permitted capture/transfer procedure. On the administrator's repository checkout: + +```bash +python3 durka.py --config "$DURKA_CONFIG" traffic import /path/to/closed-capture.pcap +python3 durka.py --config "$DURKA_CONFIG" status +``` + +Select/register the service in the local Packmate UI and click the **yellow downward-arrow processing button** once; do not look for a Start or Load PCAPs label. Wait for processing, find the known request and matching response, then repeat with another closed file. The import retains the previous file and restarts only Packmate. Empty results: check service IP, port/pattern, known marker, processing state and stream timestamps; do not assume a time-filter UI exists. Packmate uses AMD64 emulation on Apple Silicon; measure latency locally. + +**Shutdown/recovery:** stop new input, preserve required private data, run `traffic live down --apply` for that configured Linux capture only; run `durka.py --config "$DURKA_CONFIG" down` for the local stack. Both retain persistent data/images. Never delete live database files. If LIVE is forbidden or has no traffic visibility, use FILE as a fallback and label continuous capture unavailable. [Native recovery and quarantined restore](../deployment/README.md#native-backup-and-quarantine-restore) and [offline guide](offline-bundles.md) cover recovery; test restore separately before relying on it. + +## Final operator checks + +Authenticate each participating device; exercise a useful UI action and reconnect. Verify each actual script environment, Farm-to-jury acceptance, authorized LIVE or closed FILE flow, offline restart under normal load. Event routes, capture permission and organizer settings require event-specific verification. Linux tests and hosted macOS CI do not prove Docker Desktop, team LAN or local policy compatibility. Keep unperformed checks **NOT TESTED**, not ready. diff --git a/docs/CAPABILITY_INVENTORY-RU.md b/docs/CAPABILITY_INVENTORY-RU.md new file mode 100644 index 0000000..5d0e91a --- /dev/null +++ b/docs/CAPABILITY_INVENTORY-RU.md @@ -0,0 +1,28 @@ +# Возможности и ограничения + +[English](CAPABILITY_INVENTORY.md) | Русский + + + +Для установки используйте [основную инструкцию](MACOS_FULL_DEPLOYMENT_AND_TESTING-RU.md), для работы — [шпаргалку администратора](TEAM_LAN_ADMIN_CHEATSHEET-RU.md). + +| Инструмент | Что делает | Важное ограничение | +|---|---|---| +| Сканер DurkaHelper | Проверяет локальные исходники/конфиги; 174 правила и справочник из 294 разделов | Находки требуют ревью; нет удалённой эксплуатации или автоматических патчей | +| Defense operations | Baseline, изменения файлов, health, сравнение патчей, восстановление файлов в staging | Явная область проверки; HTTP health не заменяет checker соревнования | +| S4DFarm | Принимает флаги и отправляет их на соревнование | Поддерживается существующий адаптер ructf_http; патчи ферма не распространяет | +| Neo | Координирует командные скрипты и workers | Включайте только доверенные задачи; зависимости скрипта должны быть в worker | +| Packmate FILE | Ищет request/response в закрытом PCAP | Не непрерывный захват; опубликованный образ на Apple Silicon использует amd64 | +| Packmate LIVE | Захватывает трафик в разрешённой Linux-точке наблюдения | Подключённый к LAN Mac не видит автоматически весь трафик Vulnbox | +| Deployment helpers | Готовят закреплённые компоненты, сохраняют данные, останавливают только свой проект | Нужен Docker runtime; на Windows поддерживается core, а не этот deployment | +| Recovery helpers | Нативные dumps и восстановление в отдельный candidate | Нет слепой перезаписи production или повтора очереди | +| Офлайн-работа | Core без скачиваний; подготовленный deployment без pulls/builds | Внешний runtime нужно установить и кешировать заранее; одной копии репозитория мало | + + +## Поддержка + +Core использует Python 3.10+ и только стандартную библиотеку. Тестами покрыты Windows, Linux x86-64 и hosted macOS ARM64; Docker-интеграция проверяется на Linux x86-64. Реальный Mac, Docker Desktop, видимость трафика и устройства команды требуют локальной репетиции. Логи CI находятся в GitHub Actions, а не в отчётах внутри репозитория. + +Версии и идентификаторы образов сопровождаются в [toolchain.lock.json](../config/toolchain.lock.json). Проверки выполняются автоматически: оператор не заполняет SHA-формы. + +Чистый scan не доказывает безопасность сервиса. Успех в лаборатории не доказывает, что сеть соревнования разрешает захват или что все участники имеют доступ к инструментам. diff --git a/docs/CAPABILITY_INVENTORY.md b/docs/CAPABILITY_INVENTORY.md new file mode 100644 index 0000000..56240a9 --- /dev/null +++ b/docs/CAPABILITY_INVENTORY.md @@ -0,0 +1,25 @@ +# Capabilities and limits + +English | [Русский](CAPABILITY_INVENTORY-RU.md) + +Use the [main guide](MACOS_FULL_DEPLOYMENT_AND_TESTING.md) for setup and the [admin sheet](TEAM_LAN_ADMIN_CHEATSHEET.md) during operation. + +| Tool | What it does | Important limit | +|---|---|---| +| DurkaHelper scanner | Reviews local source/configuration; 174 rules and a 294-section remediation guide | Findings need review; no remote exploit or automatic patching | +| Defense operations | Baseline, file drift, health, patch comparison, staged file recovery | Explicit scope; HTTP health is not a competition checker | +| S4DFarm | Receives flags and submits them to the competition | Only the existing ructf_http adapter is maintained; it does not distribute patches | +| Neo | Coordinates team scripts and workers | Enable trusted tasks deliberately; script dependencies must exist in the worker | +| Packmate FILE | Searches request/response streams from a closed PCAP | Not continuous capture; published image uses amd64 on Apple Silicon | +| Packmate LIVE | Captures at an authorized Linux observation point | A LAN-connected Mac does not automatically see Vulnbox traffic | +| Deployment helpers | Prepare pinned components, preserve data, stop only their own project | Docker runtime required; Windows supports the core, not this deployment | +| Recovery helpers | Native dumps and isolated candidate restores | No blind production overwrite or queue replay | +| Offline operation | Core without downloads; prepared deployment without pulls/builds | Install/cache the external runtime first; copying the repository alone is not enough | + +## Support + +The core is Python 3.10+ standard-library-only. Windows, Linux x86-64 and hosted macOS ARM64 are covered by tests; Docker-based integration is exercised on Linux x86-64. The actual Mac, Docker Desktop, traffic visibility and team devices still need a local rehearsal. CI logs live in GitHub Actions, not as reports inside this repository. + +Versions and image identities are maintained in [toolchain.lock.json](../config/toolchain.lock.json). They are checked automatically: operators do not fill SHA forms. + +A passing scan is not proof that a service is secure. A passing lab is not proof that the event network permits capture or that every participant can reach the tools. diff --git a/docs/MACOS_FIRST_RUN-RU.md b/docs/MACOS_FIRST_RUN-RU.md new file mode 100644 index 0000000..433c40b --- /dev/null +++ b/docs/MACOS_FIRST_RUN-RU.md @@ -0,0 +1,107 @@ + +# Первый запуск на Mac + +[English](MACOS_FIRST_RUN.md) | Русский + +Это короткий маршрут оператора, а не заявление о готовности ноутбука. Все шаги с runtime Mac ниже имеют статус **PENDING: требуется проверка на реальном Mac**. Выполняйте их только после согласования Docker Desktop, локальных сервисов, Ethernet. Подробная установка, поля конфигурации и backup описаны в [полном руководстве](MACOS_FULL_DEPLOYMENT_AND_TESTING-RU.md). + + +## 1. Preflight без изменений + +Из корня репозитория, через нативный ARM64 Python: + +```bash +python3 durka.py doctor +``` + +`doctor` не устанавливает, не скачивает, не выполняет pull/build, не запускает сервисы, не меняет конфигурацию и не исполняет Neo. Он проверяет фактическую macOS/архитектуру, Python 3.10+, Git 2.30+, локальный Desktop Engine, Compose v2+, ресурсы, нужные порты и подготовленные образы. Пароли и имена процессов не выводятся. `READY` относится к конкретной проверке, не ко всему соревнованию. + +Коды: `0` — все проверки готовы; `1` — предупреждения/неподтверждённые проверки; `2` — блокер. До setup отсутствие конфига/образов/клиента ожидаемо. Эмуляция Packmate остаётся предупреждением, offline/LAN — `NOT VERIFIED` даже при совпадении кеша. Занятые порты могут принадлежать уже поднятому стеку; не убивайте чужой процесс ради снятия предупреждения. + +Если Python/Git отсутствуют, сначала подготовьте согласованные установки. Сверьте реальные версии macOS и Docker Desktop с требованиями разрешённой установки; ранее названная версия не является проверкой. Запустите Desktop вручную после согласования. Начните с 4 CPU / 8 ГиБ RAM и бюджета диска 96 ГиБ, затем измерьте нагрузку. + + +## 2. Первая подготовка с Интернетом + +Этот шаг записывает приватный конфиг и подготавливает зависимости. Держите конфиг/пароли приватными. + +```bash +python3 durka.py init +``` + +Отредактируйте `local/durka.json`: оставьте `bind_address` равным `127.0.0.1`, выберите Darwin ARM64/Desktop, режим FILE и задайте `profile.packmate.local_ip` равным `192.0.2.20` для synthetic PCAP ниже. Оставьте пример URL/token фермы; **не выполняйте `submit`**. Поддерживаемый adapter — `ructf_http`, что не означает совместимость с любым соревнованием. Другие протоколы требуют отдельной проверки. + +После согласования, при доступном Интернете: + +```bash +python3 durka.py setup +``` + +Подготовьте закреплённый Neo **v2.4.2 Darwin ARM64** по [инструкции Neo](neo-RU.md). Разместите executable в `local/neo-client/neo` либо укажите настоящий путь через `doctor --neo-client PATH`. Сохраните release/config/tasks офлайн. Doctor проверяет executable Mach-O ARM64 header, но не аутентифицирует клиент и не доказывает его версию. Используйте закреплённый release, не произвольный бинарник с подходящим header. + + +## 3. Поднять и проверить инструменты + +```bash +python3 durka.py doctor +python3 durka.py up +python3 durka.py status +``` + +Порядок задаёт kit: базы → S4DFarm → координатор Neo → Packmate. Worker и отправка на соревнование остаются выключены. Ожидаем работающие сервисы и адреса Farm/Packmate. Neo — координатор скриптов, не веб-панель. Ферма собирает флаги, не раскатывает патчи. Packmate FILE ищет в закрытом capture, не снимает трафик LAN. + +Войдите в Farm с данными из приватного конфига и проверьте team/config view. Startup уже аутентифицирует `/api/get_config`; одна login-страница не проверяет API. Войдите в Packmate. Не выводите `neo info`, expanded Compose config или raw logs на трансляцию. + + +## 4. Synthetic-проверки полного пути + +Создайте новый закрытый capture существующим fixture и импортируйте. Команды записывают только локальный synthetic-файл и меняют input Packmate этого deployment; старый input/data сохраняются. + +```bash +python3 -c 'from integration.synthetic_pcap import make_pcap; from pathlib import Path; p = Path("local/first-run.pcap"); f = p.open("xb"); f.write(make_pcap("0123456789abcdef01234567")); f.close(); p.chmod(0o600)' +python3 durka.py traffic import local/first-run.pcap +python3 durka.py scan lab --patches +python3 scripts/defense_ops.py preflight --profile config/defense-profile.example.json +python3 integration/vulnbox_handoff.py +``` + +В Packmate добавьте сервис на порту **18080**, substring pattern `0123456789abcdef01234567`, затем один раз нажмите жёлтую кнопку разбора FILE со стрелкой вниз в боковой панели, а не ищите надпись «Start». Найдите GET `/durkahelper-smoke/…` и ответ `DURKAHELPER_RESPONSE_…` с верными направлениями. На намеренно уязвимом lab scanner ожидаемо возвращает `1`, это не поломка установки; Defense preflight и handoff должны вернуть `0`/PASS. + +Выполните [безвредную readiness-задачу Neo](neo-RU.md#first-harmless-task), затем явно запустите `python3 durka.py worker` и однократно выполните эту disabled-задачу. Ожидайте readiness-сообщение в ограниченном `tail`; нет запроса к цели и принятого флага. В выбранном worker image должны быть реальные зависимости скрипта: default light image не является универсальной средой Python/Sage. После проверки остановите worker вместе с deployment. + +[Изолированная complete-stack процедура](../integration/README-RU.md#release-candidate-acceptance) дополнительно проверяет synthetic Neo→Farm→mock receiver, отказ auth, native restore и точные payload Packmate. Это Linux AMD64 fixture, не доказательство Desktop или нативного Darwin client. Не направляйте его в операторский workspace или реальный endpoint отправки. + + +## 5. Offline, restart и нагрузка + +Сохраните Ethernet/LAN, но отключите Интернет согласованным способом. Не сбрасывайте Desktop и не чистите образы. Выполните cold start подготовленных сервисов: + +```bash +python3 durka.py down +python3 durka.py up +python3 durka.py status +``` + +Ожидаем отсутствие downloads/builds; сохраняются настройки Farm, disabled-задача Neo и service/pattern/старые streams Packmate. FILE parsing не возобновляется автоматически: нажимайте кнопку разбора FILE только для намеренной обработки текущего capture. Повторите безвредную задачу Neo после явного запуска worker. Новые PCAP импортируются отдельно, это не бесконечный FILE pipe. Следуйте [offline-инструкции](offline-bundles-RU.md) и [native backup/recovery](MACOS_FULL_DEPLOYMENT_AND_TESTING-RU.md) до появления ценных данных; сохранённый каталог не является backup. + +Запустите подготовленный стек под обычной нагрузкой минимум на 60 минут; проверьте отзывчивость, рост диска, memory pressure и повторный импорт PCAP. Hosted macOS CI не доказывает Docker Desktop, LAN и совместимость с локальными правилами. + + +## 6. Ошибки и безопасная остановка + +При ошибке не идите дальше: `status`, затем `doctor`; откройте [troubleshooting](MACOS_FULL_DEPLOYMENT_AND_TESTING-RU.md). Изменение конфига после setup требует `down` → edit → `configure` → `up`; при прерванной конфигурации может понадобиться `configure --rollback`. Недостающие образы подготовьте при Интернете, не во время игры. Клиент неверной архитектуры замените проверенным клиентом, не запускайте через непроверенный обход. + +```bash +python3 durka.py down +``` + +Останавливается только свой deployment, включая worker; данные и образы остаются. Нельзя `down -v`, общий `prune`, широкое удаление и Desktop reset. Native dumps или консистентную остановленную копию восстанавливают в новое изолированное окружение, не поверх live database files. + + +## Оставшиеся ручные gates + +- Реальный Mac: согласованная установка, auth/execution нативного клиента, полный стек в Desktop, offline start, recovery и обычная нагрузка. +- Домашний Ethernet: Mac и второй PC должны войти и выполнить полезные действия в Farm/Neo/Packmate, затем reconnect после restart; localhost/TCP connect недостаточны. Используйте [шпаргалку админа](TEAM_LAN_ADMIN_CHEATSHEET-RU.md). +- Только на площадке: повторите доступ участников и доступность checker по офлайн [game-day checklist](game-day-RU.md). AI и изменения кода не должны требоваться. +- Capture: подготовьте и [разрешённый Linux LIVE, и передачу закрытого PCAP](traffic-capture-RU.md). Mac на коммутаторе не видит трафик Vulnbox автоматически. Один FILE fallback не закрывает continuous-capture requirement. +- Протокол: проверьте adapter настоящего соревнования до включения отправки; replay восстановленных очередей остаётся выключен до проверки. diff --git a/docs/MACOS_FIRST_RUN.md b/docs/MACOS_FIRST_RUN.md new file mode 100644 index 0000000..e7da609 --- /dev/null +++ b/docs/MACOS_FIRST_RUN.md @@ -0,0 +1,99 @@ +# First Mac run + +English | [Русский](MACOS_FIRST_RUN-RU.md) + +This is the short operator route, not a claim that this machine is ready. All Mac runtime steps below are **PENDING real-Mac acceptance**. Run them only after approval for Docker Desktop, local services, Ethernet access. Installation details, configuration fields and backup procedures live in the [full guide](MACOS_FULL_DEPLOYMENT_AND_TESTING.md). + +## 1. Read-only preflight + +From the repository root, using native ARM64 Python: + +```bash +python3 durka.py doctor +``` + +`doctor` does not install, download, pull, build, start services, change configuration or execute Neo. It checks the actual macOS/architecture, Python 3.10+, Git 2.30+, local Desktop Engine, Compose v2+, resources, configured ports and prepared runtime images. It never prints credentials or listener names. `READY` applies to the named check, not the whole competition. + +Exit codes: `0` all checks ready; `1` warnings/unverified checks; `2` a blocker. Missing config/images/client before setup is expected. Packmate emulation remains a warning, and offline/LAN acceptance remains `NOT VERIFIED` even when cached images match. Occupied ports may belong to your already-running stack; do not kill another process to clear a warning. + +If Python/Git are absent, prepare them using approved installers first. Check the actual macOS and Docker Desktop versions against the approved installation requirements; a previously reported version is not evidence. Start Desktop manually after approval. Start with 4 CPUs / 8 GiB RAM and a 96 GiB disk budget, then measure rather than assume performance. + +## 2. First setup while online + +This step writes private configuration and prepares dependencies. Keep the config/passwords private. + +```bash +python3 durka.py init +``` + +Edit `local/durka.json`: keep `bind_address` at `127.0.0.1`, choose the Darwin ARM64/Desktop profile, FILE mode and `profile.packmate.local_ip` set to `192.0.2.20` for the synthetic capture below. Keep the example farm submission URL/token; **do not run `submit`**. The farm's maintained adapter is `ructf_http`, not an assertion about any event's protocol. Other protocols require separate compatibility validation. + +After approval, with Internet available: + +```bash +python3 durka.py setup +``` + +Prepare the locked Neo **v2.4.2 Darwin ARM64** client using [Neo installation](neo.md). Put its executable at `local/neo-client/neo`, or pass its actual path to `doctor --neo-client PATH`. Keep the release/config/task directory available offline. Doctor checks an executable Mach-O ARM64 header; it does not authenticate the client or prove its version. Use only the locked release, not an arbitrary binary with a matching header. + +## 3. Start and check the tools + +```bash +python3 durka.py doctor +python3 durka.py up +python3 durka.py status +``` + +Order is handled by the kit: databases → S4DFarm → Neo coordinator → Packmate. Worker and competition submission remain disabled. Expected: services are running and Farm/Packmate addresses are printed. Neo is a script coordinator, not a web dashboard. Farm collects flags; it does not deploy patches. Packmate FILE searches a closed capture, not live LAN packets. + +Log in to Farm using the private config and confirm its team/config view. Startup already authenticates `/api/get_config`; a login screen alone is not an API test. Log in to Packmate. Never print `neo info`, expanded Compose config or raw logs on a broadcast. + +## 4. Synthetic end-to-end checks + +Generate a new closed capture with the existing fixture, then import it. These commands write only a local synthetic file and change this deployment's Packmate input; previous input/data are retained. + +```bash +python3 -c 'from integration.synthetic_pcap import make_pcap; from pathlib import Path; p = Path("local/first-run.pcap"); f = p.open("xb"); f.write(make_pcap("0123456789abcdef01234567")); f.close(); p.chmod(0o600)' +python3 durka.py traffic import local/first-run.pcap +python3 durka.py scan lab --patches +python3 scripts/defense_ops.py preflight --profile config/defense-profile.example.json +python3 integration/vulnbox_handoff.py +``` + +In Packmate add service port **18080**, a substring pattern `0123456789abcdef01234567`, then press the yellow downward-arrow FILE-processing button in the sidebar once; do not look for a literal "Start" label. Find the GET `/durkahelper-smoke/…` and response `DURKAHELPER_RESPONSE_…`, with correct directions. Scanner findings on the deliberately vulnerable lab mean expected exit `1`, not installation failure; Defense preflight and handoff should exit `0`/report PASS. + +Use the [harmless Neo readiness task](neo.md#first-harmless-task), then explicitly start `python3 durka.py worker` and run that disabled task once. Expect the readiness message in its bounded `tail`; no target request and no accepted flag. The selected worker image must contain the script's actual dependencies: the default light image is not a generic Python/Sage environment. Stop the worker with the deployment when finished. + +The [isolated complete-stack procedure](../integration/README.md#release-candidate-acceptance) additionally checks synthetic Neo→Farm→mock receiver, auth failures, native restore and known Packmate payloads. It is a Linux AMD64 fixture, not proof about Desktop or the native Darwin client. Do not point it at your operator workspace or real submission endpoint. + +## 5. Offline, restart and workload rehearsal + +Keep Ethernet/LAN but disconnect Internet using an approved arrangement. Do not reset Desktop or prune images. Cold-start the prepared services: + +```bash +python3 durka.py down +python3 durka.py up +python3 durka.py status +``` + +Expected: no downloads/builds; Farm settings, disabled Neo task and Packmate service/pattern/previous streams persist. FILE parsing does not automatically resume: press the FILE-processing button only when intentionally processing the current capture. Repeat the harmless Neo task after explicitly starting the worker. New PCAP imports are deliberate replacements, not an endless FILE pipe. Follow [offline operation](offline-bundles.md) and [native backup/recovery](MACOS_FULL_DEPLOYMENT_AND_TESTING.md) before adding valuable data; retaining a directory is not a backup. + +Run the prepared stack under normal workload for at least 60 minutes; check responsiveness, disk growth, memory pressure and repeated PCAP imports. Hosted macOS CI does not prove Docker Desktop, LAN or local policy compatibility. + +## 6. Failures and safe shutdown + +On failure stop progressing: `status`, then `doctor`; use the [troubleshooting guide](MACOS_FULL_DEPLOYMENT_AND_TESTING.md). A config edit after setup needs `down` → edit → `configure` → `up`; interrupted configuration may require `configure --rollback`. Missing images must be prepared while online, not fixed mid-game. A wrong-architecture client must be replaced with the reviewed client, not run through an unplanned workaround. + +```bash +python3 durka.py down +``` + +This stops only the owned deployment, including its worker, retaining data and images. Do not use `down -v`, global `prune`, broad deletion or Desktop reset. Native dumps or a consistent stopped copy must be restored into a new isolated environment, never over live database files. + +## Remaining manual gates + +- Real Mac: approved installation, native client authentication/execution, complete-stack Desktop checks, offline startup, recovery load. +- Home Ethernet rehearsal: Mac plus a second PC must authenticate and perform useful Farm/Neo/Packmate actions, then reconnect after restart; localhost/TCP connect alone is insufficient. Use the [admin cheat sheet](TEAM_LAN_ADMIN_CHEATSHEET.md). +- Event-only: repeat participant access and checker availability using the offline [game-day checklist](game-day.md). No AI or code changes should be required. +- Capture: prepare both [approved Linux LIVE and closed-PCAP transfer](traffic-capture.md). A Mac on the switch does not automatically see Vulnbox traffic. FILE fallback alone does not satisfy a continuous-capture requirement. +- Protocol: validate the actual competition adapter before enabling real submission; keep replay of recovered queues disabled until reviewed. diff --git a/docs/MACOS_FULL_DEPLOYMENT_AND_TESTING-RU.md b/docs/MACOS_FULL_DEPLOYMENT_AND_TESTING-RU.md new file mode 100644 index 0000000..f05686f --- /dev/null +++ b/docs/MACOS_FULL_DEPLOYMENT_AND_TESTING-RU.md @@ -0,0 +1,167 @@ + +# Установка и работа командных инструментов на macOS + +[English](MACOS_FULL_DEPLOYMENT_AND_TESTING.md) | Русский + +Маршрут админа: от клонирования до работающего командного стека. Участникам нужна [инструкция участника](participant-guide-RU.md). Все команды ниже выполняются из корня репозитория DurkaHelper. + +Первое развёртывание выполняйте по короткой [first-run инструкции](MACOS_FIRST_RUN-RU.md), начиная с read-only `python3 durka.py doctor`. Полное руководство — справочник настроек/recovery, а не доказательство пройденной репетиции на реальном Mac. + + +## 1. Как устроено + +DurkaHelper запускается нативно в Python. Docker Desktop поднимает S4DFarm, координатор/worker Neo и Packmate FILE. Защищаемые сервисы остаются на Vulnbox в Ethernet-сети. Ноутбук обслуживает инструменты, а не развёртывание защищаемых сервисов. + +Ферма = флаги и отправка. Neo = распределение/исполнение скриптов. Packmate = анализ трафика. Сканер = разбор локальных исходников. [Схема связей](team-setup-RU.md). + + +## 2. Установить необходимое + +Установите Git, Python 3.10+ и Docker Desktop разрешённым для вашей машины способом. Запустите Docker Desktop и проверьте: + +```bash +uname -m +python3 --version +git --version +docker version +docker compose version +``` + +Apple Silicon должен показать `arm64`. Закреплённый образ Packmate существует только для amd64, поэтому используется эмуляция Docker Desktop. Начальный бюджет — 4 CPU, 8 GiB RAM и 96 GiB диска Docker; уточните его по своей нагрузке. Оставьте место на диске хоста для PCAP и backup. + + + +## 3. Клонировать и заполнить конфиг + +```bash +git clone https://github.com/Nyarlad/DurkaHelper.git +cd DurkaHelper +python3 durka.py init +``` + +Откройте `local/durka.json` в редакторе. Пароли/ключ уже сгенерированы. Измените: + +| Настройка | Что указать | +|---|---| +| `profile.bind_address` | Ethernet IPv4 для доступа команды; `127.0.0.1` оставьте только для прогона на одном ноутбуке | +| `profile.ports` | По умолчанию ферма 8080, Neo 5005, Packmate 65000; меняйте, если порт занят | +| `profile.farm.teams` | Названия команд и реальные адреса сервисов/Vulnbox | +| `profile.farm.flag_format` | Regex флага от организаторов | +| `profile.farm.protocol_settings` | URL/token отправки соревнования | +| `profile.farm.submit_limit / submit_period / flag_lifetime` | Лимиты и время соревнования | +| `profile.packmate.local_ip` | IP стороны сервиса, представленный в PCAP | +| `credentials` | Сгенерированные пароль фермы, ключ Neo и логин/пароль Packmate; выдавайте только нужное | + +Для native workers участников нужен настоящий Ethernet bind: координатор передаёт им LAN URL фермы. Loopback-демо поддерживает внутренний маршрут фермы только для встроенного worker. + +Текущий адаптер — `ructf_http`. Для другого протокола не включайте отправку, пока не будет совместимого адаптера. Инструменты и просмотр трафика можно запустить с выключенной отправкой. + +В `local/` лежат приватный конфиг, скачанные исходники, данные стека и captures. Не показывайте его в Git. Для домашнего прогона настройки отправки могут оставаться примерами, пока сама отправка выключена. + +На соревновании остановите стек, отредактируйте LAN/команды/отправку/Packmate, примените конфигурацию и запустите снова. Данные/образы сохраняются; скачивания и пересборка не нужны: + +```bash +python3 durka.py down +python3 durka.py configure +python3 durka.py up +``` + +Редактируйте `local/durka.json` между `down` и `configure`. Замена платформы или credentials — отдельная подготовка. + + +## 4. Подготовить при доступном Интернете + +```bash +python3 durka.py setup +``` + +Команда получает закреплённые версии исходников/образов, готовит приватный workspace и собирает ферму/Neo. Это может занять несколько минут. Проверки версий и образов выполняются автоматически; переписывать checksum руками не нужно. + +Выполняйте подготовку на машине, с которой будете работать. Linux amd64-кеш не содержит нативные зависимости Mac и не подтверждает скорость Apple Silicon. До отключения сохраните Docker Desktop, Python, репозиторий, образы, клиент Neo и нужные скрипты/зависимости. + + +## 5. Поднять и проверить доступ + +```bash +python3 durka.py up +python3 durka.py status +``` + +Запуск включает UI/API фермы, координатор Neo и UI Packmate. Создаётся пустой PCAP, поэтому интерфейс работает до первого capture. Отправка флагов и worker пока выключены. + +Откройте URL фермы и Packmate из `status`; войдите с данными приватного конфига. Затем откройте те же LAN-адреса с другой физической машины. `localhost` у участника указывает на его машину, а не на ваш ноутбук. + +Передайте участникам только нужные URL/пароль фермы, URL/логин Packmate и адрес/ключ Neo. Database/Redis/Docker не раздаются команде. Если macOS запросит входящие соединения, разрешите нужное приложение в рамках своей политики; не отключайте firewall. + + +## 6. Трафик и скрипты + +Для первого маршрута на Mac получите закрытый разрешённый PCAP и импортируйте: + +```bash +python3 durka.py traffic import /path/to/closed-capture.pcap +``` + +Откройте Packmate, зарегистрируйте сервис и шаблон поиска, затем один раз начните обработку. Найдите известные запрос и ответ. Для следующих файлов используйте ту же команду импорта. Она заменяет активный файл, сохраняя предыдущий. Все варианты, Linux/Vulnbox LIVE и ограниченный ручной захват — в [работе с трафиком](traffic-capture-RU.md). + +Для исполнения командных скриптов установите совместимый клиент Neo v2.4.2 авторам скриптов и следуйте [Neo](neo-RU.md). Когда скрипты готовы, запустите worker админа: + +```bash +python3 durka.py worker +``` + +Встроенный light-worker содержит shell, но не полный Python/Sage. До использования подготовьте совместимые workers с реальными зависимостями скриптов. Им нужны маршруты до координатора, фермы и разрешённых сервисов-целей. + + +## 7. Включить отправку и защищать + +После проверки реального адаптера, endpoint, формата флага и списка команд: + +```bash +python3 durka.py submit +``` + +Смотрите accepted/rejected/expired в ферме. Доступный UI ещё не означает принятие флагов соревнованием. + +Для каждого сервиса скопируйте исходники с Vulnbox в приватный рабочий каталог и запустите скан: + +```bash +python3 durka.py scan /path/to/service --patches +``` + +Прочитайте связанную инструкцию, сохраните оригинал, примените небольшой патч на Vulnbox и проверьте доступность/checker. Повторите скан исходников. Сканер читает файлы; по SSH в цели не заходит, код не запускает и фиксы не развёртывает. + + +## 8. Прогнать офлайн и под нагрузкой + +Дома используйте Mac и отдельный ПК в проводной LAN: войдите в ферму/Packmate, подключите Neo, импортируйте известный трафик, выполните безвредный скрипт и переподключитесь после перезапуска своего приложения. Затем отключите Интернет, сохранив LAN, и повторите запуск/работу. + +Проверьте инструменты под обычной нагрузкой не менее 60 минут. Следите за памятью/CPU Docker, ростом PCAP/БД и свободным диском. На событии повторите проверку доступа каждого устройства и выберите подготовленный разрешённый источник трафика. + + +## 9. Backup, остановка и восстановление + +`down` останавливает deployment и сохраняет данные/образы. Это не backup. Перед рискованным патчем сохраните оригинальные файлы сервиса и используйте native dump его БД. + +Для общего FILE-стека [native backup и recovery](../deployment/README-RU.md#native-backup-and-quarantine-restore) используют dumps и новый изолированный restore. Backup намеренно останавливает запись в исходный стек. Recovery очищает Redis-очереди/кеш/сессии нового кандидата, чтобы не переотправить старую работу; используйте процедуру, только если эта потеря приемлема. + +```bash +python3 durka.py down +``` + +Сначала остановите задания/захват, затем стек. Для обычного shutdown не используйте `docker compose down -v` или общий `docker system prune`. + + +## 10. Частые проблемы + +| Симптом | Следующий шаг | +|---|---| +| Docker недоступен | Запустить Docker Desktop, дождаться Engine, повторить `status` | +| UI работает локально, с ПК нет | Проверить Ethernet bind/IP, точный URL/порт, политику входящих соединений macOS и разрешённый LAN-путь | +| Флаги есть, отправки нет | Включить её только после проверки адаптера, URL/token и expiry | +| Задание Neo падает | Наличие worker, интерпретатор/зависимости и маршруты до цели | +| Packmate пустой | IP сервиса, регистрация сервиса/шаблона, закрытый capture и известный трафик | +| Apple Silicon тормозит | Эмуляция и ресурсы Docker; уменьшить capture/нагрузку или использовать разрешённый Linux-узел | +| Заканчивается диск | Остановить новый захват/импорт, сохранить нужное и удалить только определённые старые приватные файлы | + +Для удаления выполните `down`, сохраните нужные backups, затем удалите только свой остановленный deployment/source/data из `local/`. Удаление Docker Desktop и общих образов — отдельная задача администрирования машины. diff --git a/docs/MACOS_FULL_DEPLOYMENT_AND_TESTING.md b/docs/MACOS_FULL_DEPLOYMENT_AND_TESTING.md new file mode 100644 index 0000000..10fe8de --- /dev/null +++ b/docs/MACOS_FULL_DEPLOYMENT_AND_TESTING.md @@ -0,0 +1,156 @@ +# Set up and run the team tools on macOS + +English | [Русский](MACOS_FULL_DEPLOYMENT_AND_TESTING-RU.md) + +This is the administrator's route from checkout to a usable team stack. Participants use the [participant guide](participant-guide.md). All commands below run from the DurkaHelper repository root. + +For the first deployment, follow the shorter [first-run procedure](MACOS_FIRST_RUN.md), starting with read-only `python3 durka.py doctor`. This full guide is the configuration/recovery reference, not proof of a completed real-Mac rehearsal. + +## 1. Know the layout + +DurkaHelper runs natively in Python. Docker Desktop runs S4DFarm, the Neo coordinator/worker and Packmate FILE. Protected services stay on the Vulnbox over Ethernet. The laptop hosts tools, not the protected service deployment. + +Farm = flags and submission. Neo = script distribution/execution. Packmate = traffic analysis. Scanner = local source review. [Connection diagram](team-setup.md). + +## 2. Install prerequisites + +Install Git, Python 3.10+ and Docker Desktop through the software source permitted on your machine. Start Docker Desktop and check: + +```bash +uname -m +python3 --version +git --version +docker version +docker compose version +``` + +Apple Silicon should report `arm64`. Packmate's retained image is amd64-only, so this stack uses Docker Desktop's amd64 emulation. A starting resource budget is 4 CPUs, 8 GiB RAM and 96 GiB Docker disk; adjust after measuring your workload. Have enough host disk for PCAP and backups. + + +## 3. Clone and configure + +```bash +git clone https://github.com/Nyarlad/DurkaHelper.git +cd DurkaHelper +python3 durka.py init +``` + +Open `local/durka.json` in your editor. Passwords/key are already generated. Change these values: + +| Setting | Put here | +|---|---| +| `profile.bind_address` | Your Ethernet IPv4 for team access; keep `127.0.0.1` only for a laptop-only rehearsal | +| `profile.ports` | Farm 8080, Neo 5005 and Packmate 65000 by default; change only if occupied | +| `profile.farm.teams` | Competition team names and actual service/Vulnbox addresses | +| `profile.farm.flag_format` | Organizer's flag regex | +| `profile.farm.protocol_settings` | Submission URL/token from the competition | +| `profile.farm.submit_limit / submit_period / flag_lifetime` | Competition limits and timing | +| `profile.packmate.local_ip` | The service-side IP represented in your PCAP | +| `credentials` | Generated farm password, Neo key and Packmate login/password; distribute only the needed values | + +Native teammate workers require the actual Ethernet bind: the coordinator advertises that LAN farm URL to them. A loopback demo supports only the in-stack worker's internal farm route. + +The current adapter is `ructf_http`. Do not enable submission for a different protocol until it has a compatible adapter. You can start the tools and inspect traffic while submission remains off. + +`local/` holds private configuration, downloaded sources, deployment data and incoming captures. Keep it out of Git. For a home rehearsal, submission settings can stay as examples while submission remains off. + +At the event, stop the stack, edit the LAN/team/submission/Packmate settings, apply configuration and start. Data/images remain; no download or rebuild is needed: + +```bash +python3 durka.py down +python3 durka.py configure +python3 durka.py up +``` + +Edit `local/durka.json` between `down` and `configure`. Changing platform or credentials is separate preparation. + +## 4. Prepare while Internet is available + +```bash +python3 durka.py setup +``` + +This fetches the exact source versions, pulls pinned images, prepares the private workspace and builds the farm/Neo components. It can take several minutes. Version and image checks run automatically; no manual checksum copying is required. + +Do this on the machine you will use. A Linux amd64 cache does not contain native Mac prerequisites or establish Apple Silicon performance. Keep Docker Desktop, Python, the repository, cached images, the Neo client and your scripts/dependencies available before disconnecting. + +## 5. Start and check access + +```bash +python3 durka.py up +python3 durka.py status +``` + +Start includes farm UI/API, Neo coordinator and Packmate UI. It creates an empty PCAP so the UI can start before the first capture. Submission and the worker remain off. + +Open the farm and Packmate URLs printed by `status`; log in with values from your private config. Then open those same LAN URLs from another physical machine. `localhost` on a teammate's machine points at that teammate, not at your laptop. + +Give teammates only the farm URL/password, Packmate URL/login and Neo address/key they need. Database/Redis/Docker endpoints are not shared. If macOS asks about incoming connections, permit the relevant application under your allowed policy; do not disable the firewall. + +## 6. Traffic and scripts + +For the initial Mac route, obtain a closed authorized PCAP and import it: + +```bash +python3 durka.py traffic import /path/to/closed-capture.pcap +``` + +Open Packmate, register the service and search pattern, then start processing once. Find a known request and response. For repeated files, use the same import command. It replaces the active file while preserving the previous one. Full options, Linux/Vulnbox LIVE and bounded manual capture are in [traffic capture](traffic-capture.md). + +For team script execution, install a compatible Neo v2.4.2 client on each script writer's machine and follow [Neo](neo.md). When scripts are ready, start the administrator's worker: + +```bash +python3 durka.py worker +``` + +The bundled light worker has a shell, not a complete Python/Sage environment. Add compatible workers with your actual script dependencies before relying on them. Workers need routes to the coordinator, farm and permitted service targets. + +## 7. Enable submission and defend + +After checking the real adapter, endpoint, flag format and team map: + +```bash +python3 durka.py submit +``` + +Watch accepted/rejected/expired statuses in the farm. A reachable UI does not prove the competition accepts flags. + +For each service, copy source from the Vulnbox to your private working directory and scan: + +```bash +python3 durka.py scan /path/to/service --patches +``` + +Review the linked fix recipe, back up the original, apply a small patch on the Vulnbox and verify availability/checker behavior. Rerun the source scan. The scanner reads files; it does not SSH into targets, execute their code or deploy a fix. + +## 8. Rehearse offline and with load + +At home, use the Mac and a separate PC on wired LAN: log in to farm/Packmate, connect Neo, import known traffic, run one harmless script and reconnect after a scoped restart. Then disconnect Internet while keeping LAN and repeat startup/use. + +Run the tools under normal workload for at least 60 minutes. Watch Docker memory, CPU, PCAP/database growth and available disk. At the event, repeat the access test on each teammate's device and choose the prepared permitted capture path. + +## 9. Backup, stop and recover + +`down` stops this deployment and retains its data/images. It is not a backup. Before a risky service patch, retain that service's original files and use its database's native dump procedure. + +For the shared maintained FILE stack, [native backup and recovery](../deployment/README.md#native-backup-and-quarantine-restore) uses native database dumps and a new isolated restore. Backup intentionally pauses the source. Recovery resets the new candidate's Redis queues/cache/sessions to prevent replay; use that procedure only when this loss is acceptable. + +```bash +python3 durka.py down +``` + +Stop script activity/capture first; then stop the stack if applicable. Never use `docker compose down -v` or broad `docker system prune` as routine shutdown. + +## 10. Common problems + +| Symptom | Next action | +|---|---| +| Docker cannot connect | Start Docker Desktop, wait for Engine, rerun `status` | +| UI works locally, not from the PC | Correct Ethernet bind/IP, exact URL/port, macOS incoming-connection policy and allowed LAN path | +| Farm has flags but no submissions | Enable submission only after checking adapter, URL/token and expiry | +| Neo task fails | Check worker presence, interpreter/dependencies and target routes | +| Packmate is empty | Correct service-side IP, service/pattern registration, closed capture and known traffic | +| Apple Silicon is slow | Check emulation and Docker resources; reduce capture volume/workload or use an allowed Linux capture node | +| Disk is filling | Stop new capture/import, retain needed data and remove only identified old private files | + +For removal, run `down`, retain needed backups and then delete only your stopped `local/` deployment/source/data directories. Removing Docker Desktop or shared images is a separate machine administration task. diff --git a/docs/README-RU.md b/docs/README-RU.md new file mode 100644 index 0000000..89dac69 --- /dev/null +++ b/docs/README-RU.md @@ -0,0 +1,36 @@ + +# Документация + +[English](README.md) | Русский + +Начните со своей роли. У английских страниц есть русский перевод рядом; обе версии доступны офлайн. + + +## Основные маршруты + +| Ваша задача | Что читать | +|---|---| +| Поднять общие инструменты | [Последовательные workflow 01–05](ADMIN_WORKFLOWS-RU.md) → [памятка для печати](TEAM_LAN_ADMIN_CHEATSHEET-RU.md); [первый запуск Mac](MACOS_FIRST_RUN-RU.md) для установки | +| Защищать сервис или писать скрипты | [Инструкция участника](participant-guide-RU.md) → [шпаргалка защитника](defense-cheatsheet-RU.md) | +| Разобраться с трафиком | [Захват/импорт](traffic-capture-RU.md) → [Packmate](packmate-RU.md) | +| Запустить Linux LIVE с ноутбука | [SSH doctor, офлайн-образы и запуск](packmate-remote-RU.md) | +| Проверить находку | [Справочник сканера](offline-scanner-RU.md) → [база исправлений](vulnerabilities/README-RU.md) | + + +## Как связан стек + +[Схема команды](team-setup-RU.md) объясняет связи. [S4DFarm](s4dfarm-RU.md) собирает/отправляет флаги; [Neo](neo-RU.md) распределяет скрипты; [Packmate](packmate-RU.md) помогает разбирать трафик. Патчи Vulnbox применяются обычным способом развёртывания сервиса. + +Основная точка входа — `python3 durka.py`. Конфигурация хранится в исключённом из Git `local/durka.json`; обязательных evidence-форм и ручного переписывания checksum в этом маршруте нет. + + +## Справочники + +| Тема | Страницы | +|---|---| +| Defense | [Процесс](defense-RU.md), [разбор исходников](code-review-RU.md), [проверка патчей](patch-validation-RU.md), [игровой день](game-day-RU.md) | +| Развёртывание | [Справочник kit](../deployment/README-RU.md), [подготовка офлайн](offline-bundles-RU.md), [локальные утилиты](local-tools-RU.md) | +| Разработка | [Вклад в проект](../CONTRIBUTING-RU.md), [новые правила](development-RU.md), [synthetic lab](../lab/README-RU.md), [integration-стенды](../integration/README-RU.md), [релиз](release-checklist-RU.md) | +| Проект | [Текущие возможности](CAPABILITY_INVENTORY-RU.md), [правила соревнований](competition-rules-RU.md), [лицензии](../THIRD_PARTY_NOTICES-RU.md) | + +Расширенные скрипты сохраняют preview и явные параметры для записи/restore. Открывайте эти справочники по необходимости; это не дополнительные шаги для каждого участника. diff --git a/docs/README.md b/docs/README.md new file mode 100644 index 0000000..684156f --- /dev/null +++ b/docs/README.md @@ -0,0 +1,32 @@ +# Documentation + +English | [Русский](README-RU.md) + +Start with your role. English pages have a Russian translation alongside; both are available offline. + +## Main routes + +| You are… | Read this | +|---|---| +| Hosting shared tools | [Ordered workflows 01–05](ADMIN_WORKFLOWS.md) → [printable admin cheat sheet](TEAM_LAN_ADMIN_CHEATSHEET.md); [first Mac run](MACOS_FIRST_RUN.md) for installation | +| Defending a service or writing scripts | [Participant guide](participant-guide.md) → [defense cheat sheet](defense-cheatsheet.md) | +| Investigating traffic | [Capture/import workflow](traffic-capture.md) → [Packmate](packmate.md) | +| Deploying Linux LIVE from a laptop | [SSH doctor, offline images and startup](packmate-remote.md) | +| Reviewing a finding | [Scanner reference](offline-scanner.md) → [fix catalog](vulnerabilities/README.md) | + +## How the stack fits together + +[Team topology](team-setup.md) explains the connections. [S4DFarm](s4dfarm.md) collects/submits flags; [Neo](neo.md) distributes scripts; [Packmate](packmate.md) lets defenders inspect traffic. Vulnbox patches use your normal service deployment workflow. + +The ordinary entrypoint is `python3 durka.py`. Configuration belongs in ignored `local/durka.json`; this route has no mandatory evidence forms or manually copied checksums. + +## References + +| Subject | Pages | +|---|---| +| Defense | [Workflow](defense.md), [source review](code-review.md), [patch verification](patch-validation.md), [game day](game-day.md) | +| Deployment | [Kit reference](../deployment/README.md), [offline preparation](offline-bundles.md), [local utilities](local-tools.md) | +| Development | [Contributor guide](../CONTRIBUTING.md), [rule development](development.md), [synthetic lab](../lab/README.md), [integration fixtures](../integration/README.md), [release checklist](release-checklist.md) | +| Project | [Current capabilities](CAPABILITY_INVENTORY.md), [competition rules](competition-rules.md), [licenses](../THIRD_PARTY_NOTICES.md) | + +Advanced scripts retain previews and explicit parameters for filesystem/restore operations. Read their references when needed; they are not extra setup steps for every participant. diff --git a/docs/TEAM_LAN_ADMIN_CHEATSHEET-RU.md b/docs/TEAM_LAN_ADMIN_CHEATSHEET-RU.md new file mode 100644 index 0000000..458b16d --- /dev/null +++ b/docs/TEAM_LAN_ADMIN_CHEATSHEET-RU.md @@ -0,0 +1,97 @@ + +# Шпаргалка администратора + +[English](TEAM_LAN_ADMIN_CHEATSHEET.md) | Русский + +Вы поднимаете общую ферму, координатор Neo и Packmate. После настройки для обычной работы нужны эти команды, а не форма валидации. Распечатайте страницу и сохраните [workflow 01–05](ADMIN_WORKFLOWS-RU.md) офлайн. + + +## Запуск + +Запустите Docker Desktop/Engine и подключите Ethernet. Из корня репозитория: + +```bash +DURKA_CONFIG=local/competition.json +python3 durka.py --config "$DURKA_CONFIG" up +python3 durka.py --config "$DURKA_CONFIG" status +``` + +Откройте ферму и Packmate. Войдите, затем повторите с отдельного ПК или устройства участника. URL используют реальный Ethernet-адрес; `localhost` работает только для вас. В каждом терминале задайте переменную с настоящим путём подготовленного конфига. Смена игровых настроек: остановить native workers, down, изменить этот конфиг, configure, затем up; всегда с тем же --config. + + +## Выдать доступ + +| Что передать участникам | Откуда взять | +|---|---| +| URL и пароль фермы | URL из `status`; `credentials.farm_password` в выбранном приватном конфиге | +| Neo host:port и ключ | Адрес из `status`; `credentials.neo_key` | +| URL, логин и пароль Packmate | URL из `status`; `credentials.packmate_user / packmate_password` | +| Доступ к Vulnbox/сервису | Разрешённый команде порядок доступа к сервисам | + +Передайте учётные данные приватно, отдельно от трансляции/скриншотов. Пароли БД и Docker-доступ участникам не нужны. Их страница — [инструкция участника](participant-guide-RU.md). + + +## Включить работу + +Когда скрипты/зависимости готовы: + +```bash +python3 durka.py --config "$DURKA_CONFIG" worker +``` + +Когда протокол, endpoint/token и список команд соревнования правильные: + +```bash +python3 durka.py --config "$DURKA_CONFIG" submit +``` + +Координатор раздаёт задания; workers выполняют и отправляют совпадающий stdout в Farm; Farm отправляет жюри. Встроенный worker — shell-only. Авторы используют один координатор и разные ID: регистрация выключенным → дождаться скачивания worker → single → проверить → намеренно включить → отключить. [Точные примеры Neo](neo-RU.md#one-shot-and-scheduled-harmless-example). QUEUED не означает приём жюри. Патчи применяются штатным механизмом сервиса. + + +## Трафик + +Для закрытого PCAP: + +```bash +python3 durka.py --config "$DURKA_CONFIG" traffic import /path/to/closed-capture.pcap +``` + +В Packmate зарегистрируйте сервис/порт/шаблон и один раз нажмите жёлтую кнопку обработки со стрелкой вниз. [Workflow 05](ADMIN_WORKFLOWS-RU.md#workflow-05--packmate-live-or-file) описывает LIVE doctor, офлайн-bundle и развёртывание. Capture settings — в приватном local/packmate-remote.json; порты/шаблоны сервисов — в UI. Ethernet на Mac не обеспечивает видимость; FILE не является LIVE. + + +## Проверить команду + +Дома используйте Mac и отдельный ПК. На соревновании повторите с каждым рабочим устройством: + +- Войти в ферму и Packmate по LAN-адресам. +- Найти один и тот же известный запрос/ответ в Packmate. +- Подключить клиент Neo, выполнить согласованный безвредный скрипт и увидеть результат. +- Переподключиться после обрыва клиента или перезапуска своего приложения. +- Держать обычную нагрузку; следить за памятью и диском. + +Заполнять форму не требуется. Исправьте ошибки до использования этого устройства/маршрута. + + +## Если что-то сломалось + +| Симптом | Что проверить | +|---|---| +| Все UI недоступны | `status`, Ethernet IP/bind, Docker и опубликованные порты | +| Не работает только одно устройство | Его URL, маршрут, учётные данные и версия клиента | +| Флаги ждут в ферме | Отправка включена? Адаптер/token/expiry правильные? | +| Скрипты Neo падают | Есть worker? Интерпретатор/зависимости? Маршруты? | +| Packmate пустой | Известный трафик, правильный IP сервиса, регистрация и источник файла/LIVE | +| Быстро растёт диск | Остановить новый capture; сохранить нужное и удалить только выбранные старые приватные данные | + +Перед рискованными изменениями нужен backup. [Native recovery стека](../deployment/README-RU.md#native-backup-and-quarantine-restore) останавливает запись и восстанавливает в новое хранилище; не копируйте live-файлы БД обычным backup. + + +## Завершение + +Остановите новые скрипты/захват, сохраните backups, затем: + +```bash +python3 durka.py --config "$DURKA_CONFIG" down +``` + +Данные и образы сохраняются. Не используйте общий prune и `down -v`. [Полная установка](MACOS_FULL_DEPLOYMENT_AND_TESTING-RU.md). diff --git a/docs/TEAM_LAN_ADMIN_CHEATSHEET.md b/docs/TEAM_LAN_ADMIN_CHEATSHEET.md new file mode 100644 index 0000000..c335c78 --- /dev/null +++ b/docs/TEAM_LAN_ADMIN_CHEATSHEET.md @@ -0,0 +1,89 @@ +# Administrator cheat sheet + +English | [Русский](TEAM_LAN_ADMIN_CHEATSHEET-RU.md) + +You host the shared farm, Neo coordinator and Packmate. Once configured, ordinary game operation needs these commands, not a validation form. Print this page and keep [workflows 01–05](ADMIN_WORKFLOWS.md) offline. + +## Start + +Start Docker Desktop/Engine and connect Ethernet. From the repository root: + +```bash +DURKA_CONFIG=local/competition.json +python3 durka.py --config "$DURKA_CONFIG" up +python3 durka.py --config "$DURKA_CONFIG" status +``` + +Open the farm and Packmate URLs. Log in, then repeat from the separate PC or a teammate's device. The URLs use your actual Ethernet address; `localhost` is only for you. Set the variable in every terminal and select your actual prepared config. For changed event settings: stop native workers, down, edit this config, configure, then up; use the same --config. + +## Share access + +| Give teammates | Where it comes from | +|---|---| +| Farm URL and password | URL from `status`; `credentials.farm_password` in the selected private config | +| Neo host:port and key | Address from `status`; `credentials.neo_key` | +| Packmate URL, login and password | URL from `status`; `credentials.packmate_user / packmate_password` | +| Vulnbox/service access | The team's authorized service-access procedure | + +Send credentials privately, separately from broadcast/screenshots. Do not share database passwords or Docker access. Participants use the [participant guide](participant-guide.md). + +## Enable work + +When scripts/dependencies are ready: + +```bash +python3 durka.py --config "$DURKA_CONFIG" worker +``` + +When competition protocol, endpoint/token and team map are correct: + +```bash +python3 durka.py --config "$DURKA_CONFIG" submit +``` + +The coordinator assigns tasks; workers execute and send matching stdout to Farm; Farm submits to the jury. The bundled worker is shell-only. Authors share a coordinator and use distinct task IDs: register disabled → wait for worker download → single → inspect → enable deliberately → disable. [Exact Neo examples](neo.md#one-shot-and-scheduled-harmless-example). QUEUED is not acceptance. Patches use the service's normal deployment. + +## Traffic + +For a closed PCAP: + +```bash +python3 durka.py --config "$DURKA_CONFIG" traffic import /path/to/closed-capture.pcap +``` + +In Packmate, register the service/port/pattern and click the yellow downward-arrow processing button once. [Workflow 05](ADMIN_WORKFLOWS.md#workflow-05--packmate-live-or-file) covers LIVE doctor, offline bundle and deployment. Capture settings are in private local/packmate-remote.json; service ports/patterns are in the UI. Mac Ethernet alone does not provide visibility; FILE is not LIVE. + +## Check the team + +At home, use the Mac and a separate PC. At the event, repeat with every participating device: + +- Log into farm and Packmate using the LAN URLs. +- Find the same known request/response in Packmate. +- Authenticate the Neo client, execute a harmless agreed script and confirm its result. +- Reconnect after a client interruption or scoped restart. +- Run normal workload; watch memory and disk. + +No form is required. Fix failures before relying on that device/path. + +## If something breaks + +| Symptom | Check | +|---|---| +| All UIs unreachable | `status`, Ethernet IP/bind, Docker and published ports | +| Only one device fails | Its URL, route, credentials and client version | +| Flags wait in farm | Submission enabled? Correct adapter/token/expiry? | +| Neo scripts fail | Worker present? Interpreter/dependencies? Routes? | +| Packmate empty | Known traffic, correct service IP, registration and file/LIVE source | +| Disk grows rapidly | Stop incoming capture; retain needed files and prune only selected old private data | + +Back up before risky changes. [Native stack recovery](../deployment/README.md#native-backup-and-quarantine-restore) pauses writers and restores to new storage; never copy live database files as ordinary backups. + +## Finish + +Stop new scripts/capture, retain backups, then: + +```bash +python3 durka.py --config "$DURKA_CONFIG" down +``` + +Data and images remain. Avoid broad prune and `down -v`. [Full setup](MACOS_FULL_DEPLOYMENT_AND_TESTING.md). diff --git a/docs/code-review-RU.md b/docs/code-review-RU.md new file mode 100644 index 0000000..08b7f5f --- /dev/null +++ b/docs/code-review-RU.md @@ -0,0 +1,33 @@ + +# Review своего сервиса + +[English](code-review.md) | Русский + +Работайте с локальной копией исходников, которую вам разрешено проверять. Используйте [сканер](offline-scanner-RU.md) и [каталог](vulnerabilities/README-RU.md), чтобы найти конкретные места для review. + + +## Определите запуск и зависимости + +Свидетельство: `REVIEWED`; эффект `READ-ONLY`; рабочий каталог — checkout сервиса. Требование: ripgrep. Ожидается: список возможных манифестов без исполнения кода. Пути в выводе могут быть приватными. Rollback: не нужен. + +~~~bash +rg --files -g 'Dockerfile*' -g '*compose*' -g '*requirements*' -g '*lock*' \ + -g 'pyproject.toml' -g 'package.json' -g 'composer.json' -g 'go.mod' \ + -g 'pom.xml' -g '*gradle*' -g '*.csproj' -g 'Cargo.toml' -g 'Gemfile' \ + -g 'Makefile' -g 'CMakeLists.txt' +~~~ + +Проследите entrypoint → процесс → конфигурация → маршруты → данные. Никогда не запускайте неизвестные install hooks или исходники только ради их изучения. Сверьте lockfiles с фактически развёрнутым образом и runtime. + + +## Проследите запрос + +1. Источник ввода: body, URL, cookie, header, сохранённая запись, задача или файл. +2. Проверенный субъект и разрешение на конкретный объект. +3. Разбор, нормализация, сериализация, шаблоны и преобразования типов. +4. Чувствительная операция и её фактические аргументы. +5. Исключения, callbacks, awaits и альтернативные пути к той же операции. + +Ручные рецепты rg показывают, с чего начать; отсутствие совпадений не подтверждает безопасность. Сопоставьте обычный собственный запрос с разрешёнными логами/PCAP, затем воспроизведите один инвариант на изолированной копии. У запрещённой операции не должно быть запрещённого побочного эффекта. + +После минимального совместимого патча повторите регрессионный тест, обычный пользовательский сценарий и чтение старых записей. Следуйте [процедуре deployment и rollback](patch-validation-RU.md). diff --git a/docs/code-review.md b/docs/code-review.md new file mode 100644 index 0000000..8745259 --- /dev/null +++ b/docs/code-review.md @@ -0,0 +1,30 @@ +# Review an owned service + +English | [Русский](code-review-RU.md) + +Work on a local authorized source copy. Use the [scanner](offline-scanner.md) and [catalog](vulnerabilities/README.md) to locate concrete review points. + +## Identify startup and dependencies + +Evidence: `REVIEWED`; effect `READ-ONLY`; cwd the service checkout. Prerequisite: ripgrep. Expected: candidate manifests, not executed code. Output paths may be private. Rollback: none. + +~~~bash +rg --files -g 'Dockerfile*' -g '*compose*' -g '*requirements*' -g '*lock*' \ + -g 'pyproject.toml' -g 'package.json' -g 'composer.json' -g 'go.mod' \ + -g 'pom.xml' -g '*gradle*' -g '*.csproj' -g 'Cargo.toml' -g 'Gemfile' \ + -g 'Makefile' -g 'CMakeLists.txt' +~~~ + +Trace entrypoint → process → configuration → routes → data. Never run unknown install hooks or source merely to inspect it. Compare lockfiles with the actual deployed image/runtime. + +## Trace a request + +1. Input source: body, URL, cookie, header, stored record, task or file. +2. Verified actor and permission for the specific object. +3. Parsing, normalization, serialization, templates and casts. +4. Sensitive operation and its actual arguments. +5. Exceptions, callbacks, awaits and alternative paths to the same operation. + +Manual rg recipes identify where to start; zero matches do not establish safety. Correlate a normal owned request from approved logs/PCAP, then reproduce one invariant on an isolated copy. A denied operation must have no forbidden side effect. + +After a compatible minimal patch, repeat the regression test, normal user workflow and reading of old records. Follow [deployment and rollback](patch-validation.md). diff --git a/docs/competition-rules-RU.md b/docs/competition-rules-RU.md new file mode 100644 index 0000000..ebe4ffe --- /dev/null +++ b/docs/competition-rules-RU.md @@ -0,0 +1,23 @@ + +# Область и правила соревнования + +[English](competition-rules.md) | Русский + +DurkaHelper не содержит настроек конкретного турнира. Перед использованием проверьте действующие правила организаторов и официальные разъяснения; разрешение на одном мероприятии не переносится на другое. + +| Область | Что подтвердить перед применением | +|---|---| +| Подготовленные материалы | Локальные скрипты, копии исходников и доступ к репозиториям | +| AI / внешние API | Различия ограничений при подготовке и во время соревнования; сканер не обращается к AI | +| Изменения сервисов | Разрешения на изменения кода, конфигурации, зависимостей, restart и migrations | +| Сетевая политика | Разрешённые порты, фильтрация, proxies и изменения контейнерной сети | +| Зарезервированная инфраструктура | Аккаунты организаторов, checkers, мониторинг и защищённые каталоги | +| Размещение | Разрешённые локальные hosts/containers и источники запросов | +| Трафик/данные | Разрешение на захват, точка наблюдения, хранение/передача и ограничения ресурсов | +| Коммуникации | Каналы команды, внешняя помощь и публикация | +| Протокол отправки | Endpoint/transport, аутентификация, формат флагов, ответы, квоты, tick/lifetime | +| Доступность | Семантика checker, SLA, сохранение старых данных и окна для патчей | + +Рецепт усиления безопасности не даёт разрешения менять чужую инфраструктуру. Если настройка защищена, исправляйте в разрешённых границах приложения с сохранением функциональности; уточняйте спорные изменения до их применения. + +Описанная соревновательная топология использует проводную LAN без VPN. Не предполагайте, что разрешено менять адресацию, конфигурацию коммутатора, firewall или параметры захвата. Офлайн-сканер не отправляет запросов; у health probes и инфраструктурных инструментов явно указаны другие эффекты. diff --git a/docs/competition-rules.md b/docs/competition-rules.md new file mode 100644 index 0000000..7644544 --- /dev/null +++ b/docs/competition-rules.md @@ -0,0 +1,22 @@ +# Competition scope and rules + +English | [Русский](competition-rules-RU.md) + +DurkaHelper contains no tournament-specific settings. Confirm current organizer rules and official clarifications before use; permission at one event does not transfer to another. + +| Area | Confirm before applying | +|---|---| +| Prepared material | Local scripts, source copies and repository access | +| AI / external APIs | Preparation versus competition-time restrictions; the scanner calls no AI | +| Service changes | Code, configuration, dependencies, restart and migration permissions | +| Network policy | Allowed ports, filtering, proxies and container-network changes | +| Reserved infrastructure | Organizer accounts, checkers, monitoring and protected directories | +| Placement | Permitted local hosts/containers and allowed request sources | +| Traffic/data | Capture permission, observation point, storage/transfer and resource bounds | +| Communication | Team channels, outside help and publication | +| Submission protocol | Endpoint/transport, authentication, flag format, responses, quotas, tick/lifetime | +| Availability | Checker semantics, SLA, legacy-data retention and patch windows | + +A hardening recipe is not permission to alter someone else's infrastructure. If a setting is protected, fix within the authorized application boundary while preserving functionality; clarify uncertain changes before applying them. + +The documented competition topology uses wired LAN without VPN. Do not assume permission to change addressing, switch configuration, firewall or capture settings. The offline scanner makes no requests; health probes and infrastructure tools have explicitly different effects. diff --git a/docs/defense-RU.md b/docs/defense-RU.md new file mode 100644 index 0000000..3b729d1 --- /dev/null +++ b/docs/defense-RU.md @@ -0,0 +1,44 @@ + +# Рабочий процесс оператора защиты + +[English](defense.md) | Русский + +[Шпаргалка](defense-cheatsheet-RU.md) · [Каталог](vulnerabilities/README-RU.md) · [Проверка патчей](patch-validation-RU.md) + + +## До первого изменения + +Подтвердите разрешённую область и [контракт соревнования](competition-rules-RU.md). Назначьте одного ответственного за deployment каждого сервиса. Запишите фактическую ревизию кода/образа, механизм запуска, источники конфигурации, нужные порты, расположение данных и способ rollback. + +Выполните обычную пользовательскую операцию и сохраните синтетические или разрешённые старые записи для регрессионных проверок. Исправный health endpoint не доказывает работу входа, авторизации, сохранения данных или совместимость с checker. + +Создайте ограниченный [baseline](local-tools-RU.md#defense-operations), scan исходников и согласованный health profile. Сохраняйте read-only копии исходников; никогда не используйте общий inventory процессов/контейнеров для раскрытия посторонних workloads. + + +## Повторяющийся цикл + +1. Следите за статусом checker, явно заданными health checks и поведением приложения. +2. Сравнивайте snapshots для выявления изменений файлов, конфигурации, процессов и listeners. +3. Локально изучайте минимальный нужный интервал логов и трафика. +4. Проследите подозрительную операцию до инварианта в исходниках. +5. Добавьте падающий регрессионный тест и внесите минимальный совместимый патч. +6. Повторите проверки владельца/другого пользователя/анонимного пользователя, старых данных и доступности. +7. Разверните через отрепетированный процесс; наблюдайте и откатите код/образ при регрессии. + +Не меняйте попутно ключи, схемы, runtime и не удаляйте функциональность. Старые данные, созданные в последующих раундах, должны пережить rollback кода. + + +## Разбор подозрений и свидетельства + +Находка сканера или подозрительно выглядящий запрос — гипотеза, а не доказательство компрометации. Сравните с нормальным трафиком, timestamps и фактическими изменениями состояния. Приватно сохраняйте только необходимые свидетельства; записывайте нормализованные события и очищенные hashes через [timeline/evidence tools](local-tools-RU.md#patch-evidence-timelines-and-export). + +Не публикуйте raw logs, PCAP, cookies, flags, request bodies, Neo info или expanded Compose configuration. Диагностические терминалы и интерфейсы с секретами остаются приватными. + + +## Восстановление + +Проверьте резервную копию, прежде чем на неё полагаться. Восстановите в новую изолированную staging-среду и проверьте данные и функциональность до любого согласованного production-действия. Используйте нативные dumps БД или контролируемые консистентные cold copies; копия живого файла БД не является надёжным backup. + +Начальные цели репетиции: RPO пять минут и RTO десять минут, измеряемые для каждого компонента. Синтетические прогоны длительностью меньше секунды не доказывают достижение этих целей на реальном объёме данных. Submission и workers остаются остановленными до review восстановленных и просроченных очередей. + +При неполных свидетельствах указывайте partial/blocked вместо «безопасно». Для эксплуатационных сбоев используйте [runbook игрового дня](game-day-RU.md), для доступа к общим инструментам — [шпаргалку администратора](TEAM_LAN_ADMIN_CHEATSHEET-RU.md). diff --git a/docs/defense-cheatsheet-RU.md b/docs/defense-cheatsheet-RU.md new file mode 100644 index 0000000..2c9987e --- /dev/null +++ b/docs/defense-cheatsheet-RU.md @@ -0,0 +1,21 @@ + +# Краткая шпаргалка защитника + +[English](defense-cheatsheet.md) | Русский + +Перед изменением уточните разрешённый сервис, порядок запуска/пути данных, checker и ответственного за rollback. Сохраните предыдущие код/образ и подходящий backup. Карточка и ручное переписывание hashes не требуются. + +| Ситуация | Действие | +|---|---| +| Первый доступ | Обычный пользовательский сценарий, образец старых данных, inventory/baseline, scan исходников | +| Сигнал сканера | Откройте точную ссылку каталога; проследите ввод → проверка → опасная операция | +| Подозрительный запрос | Сравните с нормальным трафиком в коротком временном окне; не публикуйте raw evidence | +| Предложен патч | Один падающий regression test, минимальное изменение, проверки своего/чужого/анонимного пользователя и старых данных | +| Deployment | Один ответственный, точный собственный сервис, сохранённый предыдущий образ/код и актуальные данные | +| Регрессия доступности | Сохраните причину; выполните отрепетированный rollback кода, не перезаписывайте новые раунды старой БД | +| Нет трафика | Проверьте разрешённую точку захвата; общая LAN не означает видимость пакетов | +| Неясный результат | Partial/blocked, никогда не ложное «чисто» | + +[Сканер](offline-scanner-RU.md) · [Рецепты по языкам](vulnerabilities/README-RU.md) · [Чеклист патча](patch-validation-RU.md) · [Игровой день](game-day-RU.md) · [Шпаргалка администратора](TEAM_LAN_ADMIN_CHEATSHEET-RU.md) + +Никогда не используйте общий prune, down -v, непроверенную ротацию учётных данных, широкие изменения firewall или произвольное исполнение исходников как быстрый обход проблемы. Согласованные изменения состояния требуют rollback. Игровые checkers важнее удобного зелёного /health endpoint. diff --git a/docs/defense-cheatsheet.md b/docs/defense-cheatsheet.md new file mode 100644 index 0000000..5dc66fb --- /dev/null +++ b/docs/defense-cheatsheet.md @@ -0,0 +1,20 @@ +# Defender quick sheet + +English | [Русский](defense-cheatsheet-RU.md) + +Before a change, know the authorized service, startup/data paths, checker and rollback owner. Keep the previous code/image and a suitable backup. No service card or manually copied hashes are required. + +| Situation | Action | +|---|---| +| First access | Normal user journey, old-data sample, inventory/baseline, source scan | +| Scanner signal | Open the exact catalog link; trace input → validation → sink | +| Suspicious request | Compare normal traffic and small timestamp window; do not publish raw evidence | +| Proposed patch | One failing regression, minimal change, own/other/anonymous and old-data checks | +| Deployment | One owner, exact owned service, retained previous image/code and current data | +| Availability regression | Preserve cause; apply rehearsed code rollback, not an old DB over new rounds | +| Missing traffic | Verify authorized capture point; same LAN does not imply packet visibility | +| Unclear result | Partial/blocked, never false-clean | + +[Scanner](offline-scanner.md) · [Language recipes](vulnerabilities/README.md) · [Patch checklist](patch-validation.md) · [Game day](game-day.md) · [Admin quick sheet](TEAM_LAN_ADMIN_CHEATSHEET.md) + +Never use broad prune, down -v, unreviewed credential rotation, blanket firewall changes or arbitrary source execution as a shortcut. Approved state changes need a rollback. Competition checkers outrank a convenient green /health endpoint. diff --git a/docs/defense.md b/docs/defense.md new file mode 100644 index 0000000..5725c3a --- /dev/null +++ b/docs/defense.md @@ -0,0 +1,39 @@ +# Defense operator workflow + +English | [Русский](defense-RU.md) + +[Quick sheet](defense-cheatsheet.md) · [Catalog](vulnerabilities/README.md) · [Patch verification](patch-validation.md) + +## Before the first change + +Confirm authorized scope and the [competition contract](competition-rules.md). Assign one deployment owner per service. Record the actual code/image revision, startup mechanism, configuration sources, required ports, data locations and rollback method. + +Run a normal user operation and retain synthetic/authorized old records for regression checks. A healthy endpoint does not prove login, authorization, persistence or checker compatibility. + +Create a scoped [baseline](local-tools.md#defense-operations), source scan and approved health profile. Preserve read-only source copies; never use broad process/container inventory to expose unrelated workloads. + +## Repeated loop + +1. Observe checker status, explicit health checks and application behavior. +2. Compare snapshots for file/configuration/process/listener drift. +3. Review the smallest relevant log/traffic interval locally. +4. Trace a suspicious operation to an invariant in source. +5. Add a failing regression test and make the smallest compatible patch. +6. Repeat owner/other-user/anonymous, legacy-data and availability checks. +7. Deploy through the rehearsed path; monitor and roll back the code/image if regression occurs. + +Do not rotate keys, migrate schemas, replace runtimes or remove functionality as incidental changes. Old data created in later rounds must survive code rollback. + +## Triage and evidence + +A scanner finding or suspicious-looking request is a hypothesis, not proof of compromise. Compare with normal traffic, timestamps and actual state changes. Preserve only required evidence privately; record normalized events and sanitized hashes using [timeline/evidence tools](local-tools.md#patch-evidence-timelines-and-export). + +Do not publish raw logs, PCAP, cookies, flags, request bodies, Neo info or expanded Compose configuration. Keep diagnostic terminals and secret-bearing interfaces private. + +## Recovery + +Verify the backup before relying on it. Restore into a new isolated staging environment and check data/functionality before any approved production action. Use database-native dumps or controlled consistent cold copies; copying a live database file is not a reliable backup. + +Initial rehearsal objectives are RPO five minutes and RTO ten minutes, measured per component. Synthetic subsecond drills do not prove these objectives for real data volumes. Submission and workers remain stopped until restored/expired queues are reviewed. + +When evidence is incomplete, report partial/blocked rather than safe. Use the [game-day runbook](game-day.md) for operational failures and the [admin sheet](TEAM_LAN_ADMIN_CHEATSHEET.md) for shared-tool access. diff --git a/docs/development-RU.md b/docs/development-RU.md new file mode 100644 index 0000000..57a649e --- /dev/null +++ b/docs/development-RU.md @@ -0,0 +1,64 @@ + +# Разработка, контракты и покрытие правил + +[English](development.md) | Русский + +[Руководство для участников](../CONTRIBUTING-RU.md) · [Релизный чеклист](release-checklist-RU.md) + + +## Архитектура + +Ядро остаётся на стандартной библиотеке Python 3.10+. Сканирование исходников, сравнение отчётов, защитные операции, упаковка и синтетические интеграции имеют отдельные entrypoints. Никогда не импортируйте целевой сервис, не выполняйте его install hooks или shell-команды из профиля и не включайте онлайн-обновления незаметно. + +| Область | Источник истины | +|---|---| +| Поведение и метаданные сканера | [defense_scan.py](../scripts/defense_scan.py), [набор правил](../rules/defense.json) | +| Scope/context | [scope v2](../schemas/scanner-scope.v2.schema.json), [context v1](../schemas/scanner-context.v1.schema.json) | +| Операции | [defense_ops.py](../scripts/defense_ops.py), [profile](../schemas/profile.v1.schema.json), [snapshot](../schemas/snapshot.v1.schema.json), [comparison](../schemas/comparison.v1.schema.json) | +| Recovery/evidence | [backup manifest](../schemas/backup-manifest.v1.schema.json), [events](../schemas/event.v1.schema.json), [validation records](../schemas/validation-record.v1.schema.json) | +| Политика deployment | [model](../schemas/deployment-model.v1.schema.json), [policy](../schemas/deployment-policy.v1.schema.json), [audit](../schemas/deployment-audit.v1.schema.json) | +| Внешние артефакты | [v2 complete-target/image-export manifest](../schemas/toolchain-manifest.v2.schema.json), [устаревший v1 inventory](../schemas/toolchain-manifest.v1.schema.json), [pins](../config/toolchain.lock.json) | + +Профили декларативны. Адаптеры платформ используют фиксированные read-only команды, прошедшие review. Invalid/partial/incomparable input завершается кодом 2; обычные находки и проваленные проверки — кодом 1. Запись новых артефактов требует явного пути; операционные изменения требуют явного разрешения и ограниченного rollback. + + +## Добавление или изменение правила + +1. Опишите инвариант, языковой API и ссылки на первоисточники. +2. При одинаковой семантике расширяйте существующий ID/семейство; не дублируйте детектор ради увеличения счётчика. +3. Напишите на английском title, reason, fix, check, limitations, family, подходящий CWE, review priority и signal kind. Сохраняйте существующие IDs и anchors каталога. +4. Добавьте независимо написанные positive и safe/context-negative строки в corpus fixtures. Для каждой заявленной языковой формы нужны как минимум два разных положительных и два отрицательных примера. +5. Проверьте комментарии/строковые примеры, aliases/rebinding/shadowing, одноимённые пользовательские функции и безопасные альтернативы, соответствующие движку. +6. Добавьте или обновите точный контракт детектора и рекомендации по патчу в связанном разделе каталога. +7. Запустите targeted tests, ledger, полный suite и относящиеся к изменению платформенные проверки. + +Авторские примеры правила «до/после» не считаются независимыми свидетельствами. Повторяющиеся строки исходников не увеличивают покрытие. Новые правила должны соответствовать независимой цели; пробелы старых правил остаются видимыми и не заменяются придуманным покрытием. + +Текущий реестр: 174 правила, 251 пара правило-язык и 347 независимых fixture-записей. Эти числа не утверждают, что каждая старая пара соответствует новой цели. + +Свидетельство: `REVIEWED`; эффект `READ-ONLY` для coverage и временный `WORKSPACE-WRITE` для unit tests. Рабочий каталог — корень; нужны Python 3.10+ и ripgrep. Ожидается отсутствие новых обязательных пробелов покрытия, падающих тестов и сломанных локальных ссылок. + +```bash +python3 scripts/scanner_coverage.py --check --json +python3 -m unittest discover -s tests -v +``` + +Тестовый код никогда не исполняет уязвимые fixture-строки. Контейнерные fixtures запускаются отдельно по выбору и требуют согласованных daemon/workspace. Дорогие regex, malformed documents, oversized files, path/race failures, поведение no-network/no-exec и вывод без секретов входят в обязательную регрессию. + + +## Версионирование + +Версии CLI обозначают поведение, а не обещание прохождения всех deployment gates. Сохраняйте обратно совместимые flags и стабильные rule IDs. Расширение вывода может потребовать minor version; изменение смысла требует нового schema/scope-контракта и согласованного обновления потребителей. + +Scanner 1.8.0 сохраняет scope v2 и повышает semantic revision до bounded-source-signals.v3. Readers читают старую семантику v2, но старый/новый scope несопоставимы (exit 2). Перед проверкой патча пересканируйте обе стороны одной версией сканера и с одинаковым контекстом. Любое изменение scope или очистки метаданных должно одновременно обновлять defense_diff, patch-check, tests и docs. + +Toolchain manifest v2 различает `complete-target` и намеренно частичный scope `image-export`, привязывая полноту к сопровождаемому контракту deployment. Исторические v1 image и mixed inventories читаются только как частичные устаревшие данные и не могут быть собраны как полный комплект. При переносе полных комплектов требуется независимо сохранённый ожидаемый digest манифеста. Структурно полный и аутентифицированный манифест всё ещё требует независимой репетиции офлайн-runtime и проверки лицензий. + +Человекочитаемые статусы проверки: PASS/FAIL/PARTIAL/BLOCKED/NOT_RUN/SKIPPED_NOT_APPLICABLE; validation-record.v1 использует их варианты в нижнем регистре. Не превращайте not_run в pass. + + +## Свидетельства и CI + +Записывайте commit/tree, platform/interpreter, версии инструментов, команды, scope, результаты и ограничения. Проверяйте точно распакованный bundle, а не только checkout. Исторические свидетельства — неизменяемый контекст, а не сертификация следующего commit. + +Ручной macOS ARM64 workflow — один ограниченный job на standard runner с минимальными permissions и закреплёнными action SHAs. Он проверяет архитектуру, тесты ядра, CLI и упаковку; он не обращается к приватным тестовым хостам и не валидирует Docker Desktop или физических LAN-клиентов. Используйте только включённую квоту и перед dispatch проверяйте, что платные расходы отключены. diff --git a/docs/development.md b/docs/development.md new file mode 100644 index 0000000..4b726f3 --- /dev/null +++ b/docs/development.md @@ -0,0 +1,65 @@ +# Development, contracts and rule coverage + +English | [Русский](development-RU.md) + +[Contributor guide](../CONTRIBUTING.md) · [Release checklist](release-checklist.md) + +## Architecture + +The core remains Python 3.10+ standard library. Source scanning, report comparison, defensive operations, packaging and synthetic integration are separate entrypoints. Never import a target service, execute its install hooks, evaluate profile shell commands or silently enable online updates. + +| Area | Source of truth | +|---|---| +| Scanner behavior / metadata | [defense_scan.py](../scripts/defense_scan.py), [rule pack](../rules/defense.json) | +| Scope/context | [scope v2](../schemas/scanner-scope.v2.schema.json), [context v1](../schemas/scanner-context.v1.schema.json) | +| Operations | [defense_ops.py](../scripts/defense_ops.py), [profile](../schemas/profile.v1.schema.json), [snapshot](../schemas/snapshot.v1.schema.json), [comparison](../schemas/comparison.v1.schema.json) | +| Recovery/evidence | [backup manifest](../schemas/backup-manifest.v1.schema.json), [events](../schemas/event.v1.schema.json), [validation records](../schemas/validation-record.v1.schema.json) | +| Deployment policy | [model](../schemas/deployment-model.v1.schema.json), [policy](../schemas/deployment-policy.v1.schema.json), [audit](../schemas/deployment-audit.v1.schema.json) | +| External artifacts | [v2 complete-target/image-export manifest](../schemas/toolchain-manifest.v2.schema.json), [legacy v1 inventory](../schemas/toolchain-manifest.v1.schema.json), [pins](../config/toolchain.lock.json) | + +Profiles are declarative. Platform adapters use fixed reviewed read-only commands. Invalid/partial/incomparable input exits 2; ordinary findings/check failures exit 1. New artifact writes require explicit destinations; operational mutations use explicit approval and scoped rollback. + +## Add or change a rule + +1. State the invariant, language-specific API and primary-source references. +2. Prefer extending an existing ID/family when semantics are the same; do not duplicate a detector to inflate counts. +3. Write English title, reason, fix, check, limitations, family, applicable CWE, review priority and signal kind. Preserve existing IDs and catalog anchors. +4. Add independently written positive and safe/context-negative strings to the fixture corpus. Every claimed language form needs at least two distinct positives and two negatives. +5. Test comments/string examples, aliases/rebinding/shadowing, similarly named user functions and safe alternatives appropriate to the engine. +6. Add/update the exact detector contract and patch guidance in the linked catalog section. +7. Run targeted tests, the ledger, the full suite and relevant platform checks. + +Authored rule before/after examples do not count as independent evidence. Duplicate source strings do not increase coverage. New rules require the independent target; legacy gaps stay visible rather than receiving invented coverage. + +Current inventory: 174 rules, 251 rule-language pairs and 347 independent fixture records. These numbers are not a statement that every legacy pair meets the new target. + +Evidence: `REVIEWED`; effect `READ-ONLY` for coverage and temporary `WORKSPACE-WRITE` for unit tests. Cwd root; Python 3.10+ and ripgrep. Expected: no new required coverage gaps, test failures or broken local links. + +```bash +python3 scripts/scanner_coverage.py --check --json +python3 -m unittest discover -s tests -v +``` + +Test code never executes vulnerable fixture strings. Container fixtures are separately opt-in and require an approved daemon/workspace. Expensive regex, malformed documents, oversized files, path/race failures, no-network/no-exec behavior and secret-safe output are regression requirements. + +## Versioning + +CLI versions identify behavior, not a promise that all deployment gates passed. Preserve backward-compatible flags and stable rule IDs. Additive outputs may require a minor version; changed meaning requires a new schema/scope contract and coordinated consumers. + +Scanner 1.8.0 retains scope v2 and advances its semantic revision to bounded-source-signals.v3. Readers accept historical v2 semantics, but old/new semantic scopes are incomparable (exit 2). Rescan both sides with the same scanner/context before patch verification. Any change to scope or metadata sanitization must update defense_diff, patch-check, tests and docs together. + +Toolchain manifest v2 distinguishes `complete-target` from the deliberately +partial `image-export` scope and binds completeness to the maintained deployment +contract. Historical v1 image and mixed inventories remain readable only as +partial legacy data and cannot be assembled as a full kit. Transported complete +kits require an independently retained expected manifest digest. A structurally +complete and authenticated manifest still needs an independent offline runtime +rehearsal and license review. + +Human validation statuses use PASS/FAIL/PARTIAL/BLOCKED/NOT_RUN/SKIPPED_NOT_APPLICABLE; validation-record.v1 uses the lowercase equivalents. Do not coerce not_run into pass. + +## Evidence and CI + +Record commit/tree, platform/interpreter, tool versions, commands, scope, results and limitations. Test the exact extracted bundle, not just the checkout. Historical evidence is immutable context, not certification of a later commit. + +The manual macOS ARM64 workflow is one bounded standard-runner job with minimal permissions and pinned action SHAs. It verifies architecture, core tests, CLI and packaging; it neither accesses private test hosts nor validates Docker Desktop or physical LAN clients. Use included quota only and verify spending remains disabled before dispatch. diff --git a/docs/game-day-RU.md b/docs/game-day-RU.md new file mode 100644 index 0000000..0b995e6 --- /dev/null +++ b/docs/game-day-RU.md @@ -0,0 +1,59 @@ + +# Runbook игрового дня + +[English](game-day.md) | Русский + +Это краткое руководство по работе после успешной [репетиции развёртывания](MACOS_FULL_DEPLOYMENT_AND_TESTING-RU.md). Соблюдайте область разрешений организаторов и назначайте одного ответственного за deployment каждого сервиса. + + +## Получение сервиса + +Найдите настоящие пути его исходников, запуска, конфигурации и данных, а также неизменяемую ревизию. Держите проекты игровых сервисов отдельно от проектов командных S4DFarm/Neo/Packmate. + +Свидетельство: `REVIEWED`; эффект `READ-ONLY`; рабочий каталог — фактический Compose-каталог разрешённого сервиса. Требование: правильный daemon/project и согласованный доступ. Ожидается: список и состояние сервисов только этого проекта; локальный вывод может раскрывать пути. Rollback: не нужен. + +```bash +pwd +docker compose config --services +docker compose ps -a +``` + +Если при deployment используются явные параметры project/file, используйте те же самые параметры. Не печатайте expanded configuration. Выполните один обычный пользовательский сценарий и сохраните разрешённый образец старых данных. Затем создайте ограниченный baseline и scan исходников. + + +## Сбой доступности + +Сохраните время сбоя и последнее изменение. Изучайте только состояние затронутого проекта, здоровье зависимостей и ограниченные приватные логи; логи могут содержать секреты и должны оставаться вне публичного экспорта evidence. На общих системах избегайте общих списков всех контейнеров и процессов хоста. + +| Симптом | Следующая проверка | +|---|---| +| Компонент остановлен или перезапускается | Причина выхода, параметры запуска, готовность зависимостей | +| UI работает, но действия не проходят | База данных, persistence, точный API и аутентификация | +| На хосте работает, teammate не подключается | Ethernet-адрес, опубликованный порт, политика хоста, путь клиента | +| Сбой начался после патча | Точный diff и отрепетированный rollback кода/образа | +| Health проходит, checker падает | Настоящая семантика checker, обычный сценарий и старые данные | +| Очередь не движется | Согласованный протокол, лимиты, ответ receiver и состояние submission | +| Neo не подключается | Правильная версия клиента, адрес/key coordinator и доступность farm | +| Packmate не показывает streams | Видимость источника, режим, регистрация сервиса и временное окно | + +Перезапуск не восстанавливает потерянные данные. Не используйте down -v, не удаляйте volumes и не меняйте сеть на основании подозрения. Перед перезапуском разберитесь с сохранением данных. + + +## Подозрительный трафик + +Используйте согласованную точку наблюдения и короткий временной интервал. Сравните request/response, method/path, типы параметров, size/status и события приложения с нормальным поведением. Сохраняйте только необходимые приватные свидетельства. + +Общая LAN не означает видимость пакетов. UI Packmate без известного request/response не подтверждает рабочий захват. Импорт FILE — запасной вариант, а не доказательство непрерывного LIVE-анализа. + + +## Цикл патча + +[Review кода](code-review-RU.md) → [рецепт каталога](vulnerabilities/README-RU.md) → [regression/deployment/rollback](patch-validation-RU.md). Сохраняйте нормальное поведение и текущие данные; не удаляйте нужную функцию только ради исчезновения сигнала. + +Для явно заданных health checks приватно адаптируйте [services.example.json](../config/services.example.json); никогда не вставляйте пароли в URL. Свидетельство: `REVIEWED`; эффект `READ-ONLY` GETs; рабочий каталог — корень; ожидается true для всех настроенных проверок. + +```bash +python3 scripts/http_probe.py local/services.json --timeout 2 --workers 2 +``` + +Это проверяет настроенное HTTP-поведение, а не Neo gRPC, полноценный вход или семантику игрового checker. Форматы и ограничения описаны в [локальных инструментах](local-tools-RU.md). При сбоях общей инфраструктуры используйте [шпаргалку администратора](TEAM_LAN_ADMIN_CHEATSHEET-RU.md). diff --git a/docs/game-day.md b/docs/game-day.md new file mode 100644 index 0000000..97c8f5a --- /dev/null +++ b/docs/game-day.md @@ -0,0 +1,54 @@ +# Game-day runbook + +English | [Русский](game-day-RU.md) + +This is the short operating guide after a successful [deployment rehearsal](MACOS_FULL_DEPLOYMENT_AND_TESTING.md). Follow organizer scope and keep one deployment owner per service. + +## Receive a service + +Identify its real source/startup/configuration/data paths and immutable revision. Keep game-service projects separate from the team's S4DFarm/Neo/Packmate projects. + +Evidence: `REVIEWED`; effect `READ-ONLY`; cwd the authorized service's actual Compose directory. Prerequisite: correct daemon/project and approved access. Expected: only that project's service list/state; local output may reveal paths. Rollback: none. + +```bash +pwd +docker compose config --services +docker compose ps -a +``` + +If deployment uses explicit project/file options, use those exact same options. Do not print expanded configuration. Execute one normal user scenario and save an authorized old-data sample. Then establish the scoped baseline and source scan. + +## Availability failure + +Preserve the failure timestamp and last change. Inspect only the affected project's state, dependency health and bounded private logs; logs can contain secrets and must stay out of public evidence exports. Avoid unscoped host-wide container/process listings on shared systems. + +| Symptom | Next check | +|---|---| +| Stopped/restarting component | Exit reason, startup settings, dependency readiness | +| UI works but actions fail | Database, persistence, exact API/authentication | +| Host works but teammate cannot connect | Ethernet address, published port, host policy, client path | +| Failure started after patch | Exact diff and rehearsed code/image rollback | +| Health passes but checker fails | Real checker semantics, normal scenario and old data | +| Queue is not moving | Approved protocol, limits, receiver response and submission state | +| Neo cannot connect | Correct client version, coordinator address/key and farm reachability | +| Packmate has no streams | Source visibility, mode, service registration and time window | + +Restarting does not repair lost data. Do not use down -v, delete volumes or mutate networking on suspicion. Understand persistence before restarting. + +## Suspicious traffic + +Use an approved observation point and a short timestamp range. Compare request/response, method/path, parameter types, size/status and application events with normal behavior. Retain only the needed private evidence. + +Same LAN does not imply packet visibility. A Packmate UI with no known request/response is not a working capture setup. FILE import is a fallback, not proof of continuous LIVE analysis. + +## Patch loop + +[Review code](code-review.md) → [catalog recipe](vulnerabilities/README.md) → [regression/deployment/rollback](patch-validation.md). Preserve normal behavior and current data; do not remove a required feature merely to silence a signal. + +For explicit health checks, privately adapt [services.example.json](../config/services.example.json); never put passwords in URLs. Evidence: `REVIEWED`; effect `READ-ONLY` GETs; cwd root; expected all configured checks true. + +```bash +python3 scripts/http_probe.py local/services.json --timeout 2 --workers 2 +``` + +This checks configured HTTP behavior, not Neo gRPC, full login or game checker semantics. [Local tools](local-tools.md) document formats and limits. Shared infrastructure failures use the [administrator sheet](TEAM_LAN_ADMIN_CHEATSHEET.md). diff --git a/docs/local-tools-RU.md b/docs/local-tools-RU.md new file mode 100644 index 0000000..ba02d80 --- /dev/null +++ b/docs/local-tools-RU.md @@ -0,0 +1,95 @@ + +# Локальные инструменты и справочник CLI + +[English](local-tools.md) | Русский + +Расширенный справочник CLI, Python 3.10+, только стандартная библиотека. Для обычной установки используйте [полную инструкцию](MACOS_FULL_DEPLOYMENT_AND_TESTING-RU.md), для scan — [справочник сканера](offline-scanner-RU.md). Результаты храните приватно. См. [возможности и ограничения](CAPABILITY_INVENTORY-RU.md). + + +## Защитные операции + +`scripts/defense_ops.py` 2.2.0 использует декларативный [profile.v1](../schemas/profile.v1.schema.json); профили не содержат shell-команд. Начните с [синтетического примера](../config/defense-profile.example.json) и явно выберите свои root, files, checks и limits. + + +```bash +python3 scripts/defense_ops.py preflight --profile config/defense-profile.example.json +python3 scripts/defense_ops.py snapshot --profile config/defense-profile.example.json \ + --root . --output ../private-results/baseline.json +python3 scripts/defense_ops.py compare ../private-results/baseline.json ../private-results/current.json +``` + +Адаптеры охватывают platform, processes, listeners, services и ограниченные Compose metadata там, где это поддерживается. Отсутствующие инструменты/права или неполный сбор означают partial, а не свидетельствуют об отсутствии изменений. Сравнение baseline требует одинакового scope. + +Health проверяет только явно настроенные HTTP GET endpoints, без неявных proxies или redirects. Он проверяет status и ограниченное содержимое, а не полное поведение приложения. + + +```bash +python3 scripts/defense_ops.py health --profile config/defense-profile.example.json +``` + + +## Backup и восстановление в staging + +Копируются только явно выбранные regular files/trees и заранее созданные native database dumps. Живые файлы БД не являются поддерживаемым способом backup. Инструмент ограничивает количество и объём, проверяет стабильность источника и SHA-256. + + +```bash +python3 scripts/defense_ops.py backup create --profile config/defense-profile.example.json \ + --root . --output ../private-results/backup-01 +python3 scripts/defense_ops.py backup verify ../private-results/backup-01 +python3 scripts/defense_ops.py restore-stage ../private-results/backup-01 \ + --target ../private-results/restore-01 +python3 scripts/defense_ops.py restore-stage ../private-results/backup-01 \ + --target ../private-results/restore-01 --apply --approval-id restore-rehearsal-01 +``` + +Staging target должен быть новым/пустым согласно prechecks; перезапись production отсутствует. Symlinks, traversal, специальные файлы, tampering, нестабильные входы и неподдерживаемая безопасная публикация приводят к отказу. Windows не поддерживает POSIX-путь изменения данных. + + +## Аудит deployment + +`audit-deployment` проверяет заявленные allowlisted metadata по явной policy: roles, image pins/architecture, ports, mounts, privileges и требования health/resources. Он не запускает Compose, не исследует live daemon и не разбирает произвольный YAML. Используйте [deployment kit](../deployment/README-RU.md), чтобы создать очищенные model/policy из доверенной конфигурации. + + +```bash +python3 scripts/defense_ops.py audit-deployment \ + --model ../private-deployment/run-01/runtime-model.json \ + --policy ../private-deployment/run-01/runtime-policy.json +``` + +Не редактируйте model вручную, чтобы скрыть риски. Post-build source hash связывает точные bytes runtime Compose; policy намеренно показывает нерешённые проблемы root-user, отсутствия health и эмуляции. + + +## Свидетельства патча, timeline и экспорт + +[Проверка патчей](patch-validation-RU.md) объясняет строгую привязку evidence. Статусы Validation-record — значения schema в нижнем регистре: pass, fail, partial, blocked, not_run и skipped_not_applicable. Запись not_run не является pass. + +Timeline принимает нормализованные записи [event.v1](../schemas/event.v1.schema.json), а не произвольные raw application logs. Evidence export копирует только поддерживаемые structured/sanitized records, исключает raw PCAP/config/credentials и проверяет checksums. + + +```bash +python3 scripts/defense_ops.py timeline --events ../private-results/events.jsonl \ + --output ../private-results/timeline.json +python3 scripts/defense_ops.py evidence --profile config/defense-profile.example.json \ + --input ../private-results/baseline.json --output ../private-results/evidence-01 +``` + + +## Небольшие самостоятельные утилиты + +| Утилита | Назначение / ограничения | +|---|---| +| [http_probe.py](../scripts/http_probe.py) | Явные одноразовые GET; по умолчанию четыре workers, socket timeout три секунды, body 1 MiB; без proxies/redirects, обычная TLS verification | +| [log_summary.py](../scripts/log_summary.py) | Только ограниченные JSONL-счётчики; необязательные поля level/integer status, число malformed records, без вывода message/header/body | +| [backup_config.py](../scripts/backup_config.py) | Allowlisted scalar JSON fields и SHA-256; без databases, volumes или полного восстановления | +| [health_service.py](../lab/health_service.py) | Синтетический loopback-сервис /health и /version | + +Эффект: probes `READ-ONLY`, log summary `READ-ONLY`, config backup `WORKSPACE-WRITE`. Рабочий каталог — корень. Это демонстрационные входы; для probe сначала [запустите лабораторию](../lab/README-RU.md). + +```bash +python3 scripts/http_probe.py config/services.example.json +python3 scripts/log_summary.py lab/fixtures/events.jsonl +python3 scripts/backup_config.py config/backup.example.json --root lab/fixtures +``` + +HTTP probe завершается кодом 0/все ожидаемые ответы, 1/провал проверки, 2/неверная конфигурация. Log summary возвращает 1 при malformed input, а не просто при HTTP error statuses. Config backup создаёт новый каталог artifacts/config-backups/config-*; никогда не заменяйте полную конфигурацию сервиса этим частичным экспортом. Секрет под произвольным именем поля нельзя надёжно обнаружить — локально проверяйте allowlist и значения. diff --git a/docs/local-tools.md b/docs/local-tools.md new file mode 100644 index 0000000..0a188de --- /dev/null +++ b/docs/local-tools.md @@ -0,0 +1,89 @@ +# Local tools and CLI reference + +English | [Русский](local-tools-RU.md) + +Advanced CLI reference, Python 3.10+, standard library only. For normal setup use the [complete deployment guide](MACOS_FULL_DEPLOYMENT_AND_TESTING.md); for scanning use the [scanner reference](offline-scanner.md). Keep outputs private. See [capabilities and limits](CAPABILITY_INVENTORY.md). + +## Defense operations + +`scripts/defense_ops.py` 2.2.0 uses declarative [profile.v1](../schemas/profile.v1.schema.json); profiles contain no shell commands. Start from the [synthetic example](../config/defense-profile.example.json) and explicitly select your own root, files, checks and limits. + + +```bash +python3 scripts/defense_ops.py preflight --profile config/defense-profile.example.json +python3 scripts/defense_ops.py snapshot --profile config/defense-profile.example.json \ + --root . --output ../private-results/baseline.json +python3 scripts/defense_ops.py compare ../private-results/baseline.json ../private-results/current.json +``` + +Adapters cover platform, processes, listeners, services and scoped Compose metadata where supported. Missing tools/permissions or incomplete collection is partial, never evidence that nothing changed. Baseline comparison requires matching scope. + +Health only checks explicitly configured HTTP GET endpoints, without ambient proxies or redirects. It validates status and bounded content, not complete application behavior. + + +```bash +python3 scripts/defense_ops.py health --profile config/defense-profile.example.json +``` + +## Backup and staging restore + +Only explicitly selected regular files/trees and already-created native database dumps are copied. Live database files are not a supported backup mechanism. The tool bounds counts/bytes, checks source stability and verifies SHA-256. + + +```bash +python3 scripts/defense_ops.py backup create --profile config/defense-profile.example.json \ + --root . --output ../private-results/backup-01 +python3 scripts/defense_ops.py backup verify ../private-results/backup-01 +python3 scripts/defense_ops.py restore-stage ../private-results/backup-01 \ + --target ../private-results/restore-01 +python3 scripts/defense_ops.py restore-stage ../private-results/backup-01 \ + --target ../private-results/restore-01 --apply --approval-id restore-rehearsal-01 +``` + +The staging target must be new/empty as required by prechecks; no production overwrite exists. Symlinks, traversal, special files, tampering, unstable inputs and unsupported secure publication fail closed. Windows does not support the POSIX mutation path. + +## Deployment audit + +`audit-deployment` checks declared, allowlisted metadata against explicit policy: roles, image pins/architecture, ports, mounts, privileges and health/resource expectations. It does not run Compose, inspect the live daemon or parse arbitrary YAML. Use the [deployment kit](../deployment/README.md) to generate the sanitized model/policy from trusted configuration. + + +```bash +python3 scripts/defense_ops.py audit-deployment \ + --model ../private-deployment/run-01/runtime-model.json \ + --policy ../private-deployment/run-01/runtime-policy.json +``` + +Do not hand-edit the model to conceal risks. A post-build source hash binds the exact runtime Compose bytes; the policy intentionally exposes unresolved root-user, missing health and emulation issues. + +## Patch evidence, timelines and export + +[Patch verification](patch-validation.md) explains strict evidence binding. Validation-record statuses are lowercase schema values: pass, fail, partial, blocked, not_run and skipped_not_applicable. A not_run entry is not a pass. + +Timeline accepts normalized [event.v1](../schemas/event.v1.schema.json) records, not arbitrary raw application logs. Evidence export copies only supported structured/sanitized records, excludes raw PCAP/config/credentials and verifies checksums. + + +```bash +python3 scripts/defense_ops.py timeline --events ../private-results/events.jsonl \ + --output ../private-results/timeline.json +python3 scripts/defense_ops.py evidence --profile config/defense-profile.example.json \ + --input ../private-results/baseline.json --output ../private-results/evidence-01 +``` + +## Small standalone utilities + +| Utility | Purpose / limits | +|---|---| +| [http_probe.py](../scripts/http_probe.py) | Explicit one-shot GETs; default four workers, three-second socket timeout, 1 MiB body; no proxies/redirects, normal TLS verification | +| [log_summary.py](../scripts/log_summary.py) | Bounded JSONL counters only; optional level/integer status fields, malformed counts, no message/header/body output | +| [backup_config.py](../scripts/backup_config.py) | Allowlisted scalar JSON fields and SHA-256; no databases, volumes or full restoration | +| [health_service.py](../lab/health_service.py) | Synthetic loopback /health and /version service | + +Effect: probes `READ-ONLY`, log summary `READ-ONLY`, config backup `WORKSPACE-WRITE`. Cwd root. These are demo inputs; [start the lab](../lab/README.md) first for the probe. + +```bash +python3 scripts/http_probe.py config/services.example.json +python3 scripts/log_summary.py lab/fixtures/events.jsonl +python3 scripts/backup_config.py config/backup.example.json --root lab/fixtures +``` + +HTTP probe exits 0/all expected responses, 1/check failure, 2/invalid configuration. Log summary exits 1 for malformed input, not merely HTTP error statuses. Config backup writes a fresh artifacts/config-backups/config-* directory; never replace a full service configuration with this partial export. A secret under an arbitrary field name cannot be detected reliably—review the allowlist and values locally. diff --git a/docs/neo-RU.md b/docs/neo-RU.md new file mode 100644 index 0000000..8b0950d --- /dev/null +++ b/docs/neo-RU.md @@ -0,0 +1,169 @@ + +# Neo: распределить и выполнить командные скрипты + +[English](neo.md) | Русский + +Neo хранит командные скрипты на координаторе и распределяет исполнение между подключёнными workers и командами из списка фермы. Workers передают подходящие флаги в S4DFarm. Это полезно, когда одному ноутбуку не нужно запускать каждый скрипт против каждой цели. Защитные патчи Neo не развёртывает. + + +## Администратор + +`python3 durka.py up` запускает координатор. `python3 durka.py worker` — встроенный light-worker. Участникам передайте LAN-адрес координатора из `status` и приватный `credentials.neo_key`. + +Из окружения worker должны быть доступны координатор, ферма и разрешённые цели. Light-image содержит shell; для Python/Sage и других зависимостей нужны отдельно подготовленные совместимые workers. Ферму запускайте перед Neo. + +Перед выдачей native clients/workers настройте настоящий Ethernet bind. Loopback-демо использует встроенный worker и внутренний URL фермы; внешним workers этот container-only адрес недоступен. + + +## Установить клиент + +Используйте [релиз v2.4.2](https://github.com/C4T-BuT-S4D/neo/releases/tag/v2.4.2), совпадающий с поддерживаемой версией клиента/worker: + +| Машина | Файл | +|---|---| +| Apple Silicon Mac | `neo_client_2.4.2_darwin_arm64.zip` | +| Intel Mac | `neo_client_2.4.2_darwin_amd64.zip` | +| Linux amd64 | `neo_client_2.4.2_linux_amd64.tar.gz` | +| Linux arm64 | `neo_client_2.4.2_linux_arm64.tar.gz` | + +Скачайте/распакуйте до соревнования. В архиве есть `neo`, `client_config.yml` и каталог `exploits`. Команды ниже запускаются из распакованного каталога. Нативного клиента Windows в релизе нет; используйте разрешённое Linux-окружение/worker. + +Отредактируйте `client_config.yml`: + +```yaml +host: ":5005" +grpc_auth_key: "" +exploit_dir: "exploits" +``` + +Замените placeholders; конфиг приватный. Если macOS запросит разрешение, используйте обычную процедуру допуска приложений. Не показывайте ключ в скриншотах и аргументах shell. + +```bash +./neo --verbose=false --config client_config.yml --help +``` + + +## Первое безвредное задание + +Создайте в редакторе `exploits/ready.sh`: + +```sh +#!/bin/sh +# flush=True: printf writes immediately; this task makes no target request. +printf 'worker ready for %s\n' "$1" +``` + +Разрешите исполнение и запустите локально: + +```bash +chmod u+x exploits/ready.sh +./exploits/ready.sh 192.0.2.1 +``` + +Зарегистрируйте **выключенным**, чтобы не запустить периодическую работу: + +```bash +./neo --verbose=false --config client_config.yml add \ + --id ready --disabled --interval 1h --timeout 3s exploits/ready.sh +``` + +Попросите админа включить worker, затем единичный прогон: + +```bash +./neo --verbose=false --config client_config.yml single ready +./neo --verbose=false --config client_config.yml tail --count 20 ready +``` + +`single` выполняется один раз на **всех настроенных командах**. Пример только печатает readiness и не обращается к ним. Это не флаг; accepted flags в ферме появляться не должны. Ищите ready-сообщение; периодическое исполнение остаётся выключенным. + + +## Настоящие скрипты и периодическое исполнение + +Скрипт получает IP цели первым аргументом. Нужны доступный interpreter/shebang и flush stdout; флаги нужного формата идут в ферму. Сначала локальный тест. Не загружайте недоверенные скрипты в workers. + +Зарегистрируйте скрипт с явными ID, interval и timeout той же disabled-first командой `add`. После успешного разрешённого single-прогона включите или выключите этот ID: + +```bash +./neo --verbose=false --config client_config.yml enable +./neo --verbose=false --config client_config.yml disable +``` + +При добавлении существующего ID Neo спрашивает перед заменой версии. До периодического исполнения проверьте реальные зависимости worker, scope и правила соревнования. CLI задают [upstream-команды](https://github.com/C4T-BuT-S4D/neo/tree/2f2a4eb63f9715155844284f253ba786d330c9ae/cmd/client). + +Собственный совместимый native-worker: + +```bash +./neo --verbose=false --config client_config.yml run --jobs 1 +``` + +Команда работает на переднем плане; остановка Ctrl+C. Сначала подготовьте зависимости этого окружения. Поведение native Mac/runtime нужно прогнать на самой машине. + + +## Командный workflow: клиенты, координатор и workers + +Один бинарник `neo` выполняет две роли: команды `add`, `single`, `enable`, `disable`, `tail` — это управляющий клиент; `run` превращает процесс в исполняющий worker. Координатор хранит скрипты/настройки и распределяет цели между workers. Сам сервер скрипты не исполняет. + +```text +Author A's client ──┐ +Author B's client ──┼──> coordinator ──> connected worker(s) ──> script stdout +Admin's client ────┘ │ + └──> S4DFarm queue ──> jury +``` + +Worker выделяет из stdout значения, подходящие под настроенный формат флага, и отправляет их прямо в ферму. Адрес/данные входа фермы и настройки команд он получает от координатора. Поэтому одного доступа к координатору недостаточно: исполняющий worker должен видеть ещё и ферму. Приём в ферму и отправка из неё жюрейке — отдельные действия; `QUEUED` не означает `ACCEPTED`. + +1. **Админ:** из корня DurkaHelper запускает существующий стек через `python3 durka.py up`. Приватно выдаёт адрес/ключ координатора. Запускает один подготовленный worker: встроенный `python3 durka.py worker` либо native `./neo ... run` ниже. Для управления заданиями оба одновременно не нужны. Light Docker-worker не содержит произвольные зависимости скриптов. +2. **Каждый автор:** использует приватный клиентский конфиг с тем же координатором. Выбирает разные ID заданий, например `ready-author-a` и `ready-author-b`: ID общие, а не отдельные для каждого участника. Каждому worker задаёт отдельный `client_id`. Общий ключ даёт доступ доверенной команде, а не персональную read-only роль. +3. **Регистрация:** загружает скрипт выключенным. До единичного прогона ждёт загрузки скрипта worker и перезапуска его рабочих циклов. Зависимости и вспомогательные файлы нужны в окружении worker, а не только на ноутбуке автора. +4. **Наблюдение:** проверяет вывод задания, затем запись и статус в ферме. Закрытие управляющего клиента автора не останавливает включённое задание, пока координатор и worker работают. Выключать нужно конкретное задание явно. +5. **Отправка:** админ отдельно включает согласованный receiver фермы. Успех подтверждается ответом жюрейки; напечатанного значения или записи в очереди недостаточно. + + +### Безвредный пример: один раз и по расписанию + +Используйте `ready.sh` из [первого безвредного задания](#first-harmless-task). Команды выполняются из распакованного каталога клиента Neo на машине админа **или** участника, с её приватным `client_config.yml`. Они меняют общие задания, поэтому используйте свой согласованный ID. + +```bash +./neo --verbose=false --config client_config.yml add \ + --id ready-author-a --disabled --interval 1m --timeout 3s exploits/ready.sh +``` + +Админ запускает совместимый worker в **отдельном терминале**, из его распакованного каталога клиента: + +```bash +./neo --verbose=false --config client_config.yml run --jobs 1 --endless-jobs 0 +``` + +После сообщений о загрузке скрипта и готовности рабочих циклов автор или админ запускает один прогон: + +```bash +./neo --verbose=false --config client_config.yml single ready-author-a +./neo --verbose=false --config client_config.yml tail --count 20 ready-author-a +``` + +Ожидается `worker ready for ...`; это не флаг. `single` охватывает настроенный список команд и не включает расписание. Для осознанной проверки периодического запуска: + +```bash +./neo --verbose=false --config client_config.yml enable ready-author-a +# Observe subsequent runs; the configured interval is one minute. +./neo --verbose=false --config client_config.yml tail --count 20 ready-author-a +./neo --verbose=false --config client_config.yml disable ready-author-a +``` + +Cron не нужен. Интервал относится к зарегистрированному заданию, а не к терминалу автора. Native-worker останавливается через Ctrl+C; выключение задания прекращает будущие периодические прогоны, но уже начатая работа может завершиться. Чтобы выполнять на физической машине координатора, запустите там отдельный worker: один сервер исполнителем не является. + + +## Диагностика + +| Симптом | Что проверить | +|---|---| +| Не проходит вход | Точный LAN-адрес/порт координатора и общий ключ | +| Задание ждёт | Worker запущен и его job slots не исчерпаны | +| Только что добавленное задание не найдено | Дождитесь загрузки worker и перезапуска рабочих циклов, затем повторите единичный прогон | +| Ошибка скрипта/interpreter | Shebang, executable file и зависимости именно исполняющего worker | +| Результат есть, флагов нет | Формат флага и route/authentication worker→farm | +| Ферма rejected/expired | Receiver adapter, token, tick/lifetime и актуальный список команд | + +Сырой `info` и debug могут содержать пароль фермы. Используйте `--verbose=false` и не показывайте диагностику в трансляции/публичных reports. Логи скриптов тоже могут содержать приватные данные. + +[Инструкция участника](participant-guide-RU.md) · [Ферма](s4dfarm-RU.md) · [Установка админа](MACOS_FULL_DEPLOYMENT_AND_TESTING-RU.md) diff --git a/docs/neo.md b/docs/neo.md new file mode 100644 index 0000000..ce3a6ff --- /dev/null +++ b/docs/neo.md @@ -0,0 +1,161 @@ +# Neo: distribute and run team scripts + +English | [Русский](neo-RU.md) + +Neo saves team scripts on a coordinator and distributes executions across connected workers and the farm's team list. Workers send matching flags to S4DFarm. It is useful when one laptop should not run every script for every target. It does not deploy defensive patches. + +## Administrator + +`python3 durka.py up` starts the coordinator. `python3 durka.py worker` starts the bundled light worker. Give participants the LAN coordinator address from `status` and the private `credentials.neo_key`. + +Workers need the coordinator, farm and permitted targets reachable from their environment. The light image includes a shell; Python/Sage or other dependencies need separately prepared compatible workers. Start the farm before Neo. + +Configure an actual Ethernet bind before sharing with native clients/workers. A loopback demo uses the in-stack worker and an internal farm URL; outside workers cannot use that container-only address. + +## Install a client + +Use the [v2.4.2 release](https://github.com/C4T-BuT-S4D/neo/releases/tag/v2.4.2), matching the maintained client/worker version: + +| Machine | Asset | +|---|---| +| Apple Silicon Mac | `neo_client_2.4.2_darwin_arm64.zip` | +| Intel Mac | `neo_client_2.4.2_darwin_amd64.zip` | +| Linux amd64 | `neo_client_2.4.2_linux_amd64.tar.gz` | +| Linux arm64 | `neo_client_2.4.2_linux_arm64.tar.gz` | + +Download/extract before leaving for the event. The archive contains `neo`, `client_config.yml` and an `exploits` directory. Run the commands below from that extracted directory. Windows has no native client in this release; use a permitted Linux environment/worker. + +Edit `client_config.yml`: + +```yaml +host: ":5005" +grpc_auth_key: "" +exploit_dir: "exploits" +``` + +Replace the placeholders; keep the config private. Follow the normal application approval procedure on macOS if prompted. Never put the key in a screenshot or shell argument. + +```bash +./neo --verbose=false --config client_config.yml --help +``` + +## First harmless task + +Create `exploits/ready.sh` in your editor with: + +```sh +#!/bin/sh +# flush=True: printf writes immediately; this task makes no target request. +printf 'worker ready for %s\n' "$1" +``` + +Make it executable and run locally: + +```bash +chmod u+x exploits/ready.sh +./exploits/ready.sh 192.0.2.1 +``` + +Register it **disabled** so it does not start recurring work: + +```bash +./neo --verbose=false --config client_config.yml add \ + --id ready --disabled --interval 1h --timeout 3s exploits/ready.sh +``` + +Ask the admin to start the worker, then request one run: + +```bash +./neo --verbose=false --config client_config.yml single ready +./neo --verbose=false --config client_config.yml tail --count 20 ready +``` + +`single` runs once on **all configured teams**. This example only prints readiness and does not contact them. Its output is not a flag and should not produce accepted flags in the farm. Look for the ready message; recurring execution remains disabled. + +## Real scripts and recurring execution + +Scripts receive the target IP as their first argument. Use an available interpreter/shebang and flush stdout; flags matching the configured format go to the farm. Test locally first. Never load untrusted scripts into workers. + +Register your script with an explicit ID, interval and timeout using the same disabled-first `add` command. After a permitted single run succeeds, enable or disable that exact ID: + +```bash +./neo --verbose=false --config client_config.yml enable +./neo --verbose=false --config client_config.yml disable +``` + +Adding an existing ID prompts before replacing its version. Check actual worker dependencies, scope and competition rules before enabling recurring execution. The maintained [upstream commands](https://github.com/C4T-BuT-S4D/neo/tree/2f2a4eb63f9715155844284f253ba786d330c9ae/cmd/client) define the CLI. + +To contribute your own compatible native worker: + +```bash +./neo --verbose=false --config client_config.yml run --jobs 1 +``` + +This runs in the foreground; stop it with Ctrl+C. Prepare dependencies in that environment first. Native Mac/runtime behavior still needs a rehearsal on the actual machine. + +## Team workflow: clients, coordinator and workers + +The same `neo` binary has two roles: commands such as `add`, `single`, `enable`, `disable` and `tail` are a control client; `run` turns that process into an execution worker. The coordinator stores scripts/configuration and assigns targets to workers. It does not execute scripts itself. + +```text +Author A's client ──┐ +Author B's client ──┼──> coordinator ──> connected worker(s) ──> script stdout +Admin's client ────┘ │ + └──> S4DFarm queue ──> jury +``` + +Workers extract values matching the configured flag format from stdout and send them directly to the farm. The coordinator supplies the farm URL/authentication and team configuration. Reaching the coordinator alone is therefore insufficient: the executing worker must also reach the farm. Farm ingestion and farm-to-jury submission are separate operations; `QUEUED` is not `ACCEPTED`. + +1. **Admin:** start the existing stack with `python3 durka.py up` from the DurkaHelper checkout. Share the coordinator address/key privately. Start one prepared worker: either the bundled `python3 durka.py worker`, or native `./neo ... run` below. Do not start both merely to manage tasks. The light Docker worker does not supply arbitrary script dependencies. +2. **Each author:** use a private client config pointing to that same coordinator. Use distinct task IDs, for example `ready-author-a` and `ready-author-b`; task IDs are shared, not private per participant. Set a distinct `client_id` for each worker. The shared key is trusted-team access, not a read-only participant role. +3. **Register:** upload a script disabled. Wait until the worker has downloaded it and its execution loops have restarted before requesting a single run. Dependencies and auxiliary files must exist in the worker's environment, not merely on the uploading laptop. +4. **Observe:** inspect task output and then the farm entry/status. Closing an author's control client does not stop an enabled task while the coordinator and worker remain running. Disable that exact task explicitly. +5. **Submission:** the admin separately enables the farm's approved receiver. Confirm the receiver's accepted response; a printed value or queue entry alone does not prove acceptance. + +### One-shot and scheduled harmless example + +Use the `ready.sh` from [First harmless task](#first-harmless-task). Run these commands from the extracted Neo client directory on either the admin's machine or a participant's machine, with that machine's private `client_config.yml`. They modify shared task state, so use your own agreed ID. + +```bash +./neo --verbose=false --config client_config.yml add \ + --id ready-author-a --disabled --interval 1m --timeout 3s exploits/ready.sh +``` + +The administrator starts a compatible worker in a **separate terminal**, from its own extracted client directory: + +```bash +./neo --verbose=false --config client_config.yml run --jobs 1 --endless-jobs 0 +``` + +After its download/loop-ready messages, the author or admin requests one run: + +```bash +./neo --verbose=false --config client_config.yml single ready-author-a +./neo --verbose=false --config client_config.yml tail --count 20 ready-author-a +``` + +Expect `worker ready for ...`; this is not a flag. `single` covers the configured team list and does not enable recurrence. To test scheduling deliberately: + +```bash +./neo --verbose=false --config client_config.yml enable ready-author-a +# Observe subsequent runs; the configured interval is one minute. +./neo --verbose=false --config client_config.yml tail --count 20 ready-author-a +./neo --verbose=false --config client_config.yml disable ready-author-a +``` + +No cron job is needed. The interval belongs to the registered task, not to the author's terminal. A native worker stops with Ctrl+C; a disabled task stops future scheduled runs, but already running work may finish. To execute on the coordinator's physical machine, run a worker there as a separate process: the server alone is not an executor. + +## Troubleshooting + +| Symptom | Check | +|---|---| +| Cannot authenticate | Exact coordinator LAN address/port and shared key | +| Job remains waiting | A worker is running and has not exhausted its job slots | +| Newly added task is not found | Wait for its worker download and execution-loop restart, then retry one run | +| Script/interpreter failure | Shebang, executable file and dependencies on the executing worker | +| Results exist but flags do not arrive | Correct flag format and worker-to-farm route/authentication | +| Farm rejects/expires flags | Receiver adapter, token, tick/lifetime and current team map | + +Raw `info` and debug output can include the farm password. Use `--verbose=false` and keep diagnostics off broadcasts/public reports. Script logs can also contain sensitive data. + +[Participant guide](participant-guide.md) · [Farm](s4dfarm.md) · [Admin setup](MACOS_FULL_DEPLOYMENT_AND_TESTING.md) diff --git a/docs/offline-bundles-RU.md b/docs/offline-bundles-RU.md new file mode 100644 index 0000000..0a3a3dd --- /dev/null +++ b/docs/offline-bundles-RU.md @@ -0,0 +1,66 @@ +# Офлайн-работа + +[English](offline-bundles.md) | Русский + + + +## Подготовьте машину заранее + +Сканеру нужен Python 3.10+; полному стеку — ещё Docker и кешированные образы. Установите их при наличии Интернета. Пройдите [установку на Mac](MACOS_FULL_DEPLOYMENT_AND_TESTING-RU.md), завершите `durka.py setup`, поднимите стек и проверьте его до выезда. + +Сохраните репозиторий, приватный каталог `local/` и Docker data. Перед офлайн-запуском не удаляйте образы, не сбрасывайте Docker Desktop и не запускайте cleanup/prune. Setup может скачивать и собирать; обычный запуск использует подготовленные образы и не должен незаметно делать pull. + + +## Репетиция без Интернета + + +### Чистое окружение соревнования после репетиции + +Не удаляйте подготовленный workspace до создания замены. Сначала остановите native Neo worker (`Ctrl+C`) и выполните `down` с учебным конфигом. Сохраните кеш закреплённых исходников и Docker-образы. На том же подготовленном Mac/Linux: + +```bash +python3 durka.py --config local/event.json prepare-clean --from-config local/rehearsal.json +python3 durka.py --config local/event.json prepare-clean --from-config local/rehearsal.json --apply +``` + +Первая команда — read-only preview. Вторая создаёт **новые** приватный конфиг и `local/event-workspace`, используя проверенные сохранённые образы и локальные закреплённые исходники. Она ничего не скачивает, не собирает, не запускает контейнеры, не копирует прежние базы/задания/захваты и не удаляет репетицию. Создаются новые локальные пароли, placeholders для жюрейки/команд, пустые данные и пустой FILE-захват. Прежние локальные порты сохраняются; начальный bind нового стека — `127.0.0.1`. Отсутствующие образы, грязный/отсутствующий кеш исходников, работающий исходный deployment, удалённый Docker endpoint или существующие выходные пути блокируют подготовку. Частичный кандидат после сбоя сохраняется для проверки; повторяйте с новым именем конфига. + +Заполните `local/event.json`: реальный LAN bind, команды, IP Vulnbox, формат флага и согласованные параметры отправки ForcAD. Затем выполните `configure`, `up` и `doctor` с `--config local/event.json`. Worker и отправка включаются отдельно; не включайте их с placeholders. Новый native Neo конфиг — `local/event-workspace/config/neo-native.yml`; используйте подготовленный бинарник, а не прежний учебный клиентский конфиг. После изменения LAN bind передайте Neo переопределение `--host MAC_LAN_IP:NEO_PORT` вместе с новым конфигом. Зависимости каждого скрипта готовятся отдельно. + +Проверьте новую установку и запуск без Интернета до удаления учебных конфига/workspace. Сохраните репозиторий, закреплённый кеш исходников, образы, Neo binary и отдельный Linux LIVE bundle. Для фактического разрешённого узла/интерфейса создайте новый LIVE-конфиг: заполненный учебный конфиг непереносим. Это **чистые данные приложений на уже подготовленной машине**, а не офлайн-установщик для пустого Mac. Не используйте Docker prune/reset или широкое удаление `local/`. + +Оставьте Ethernet/LAN, но отключите Интернет своим разрешённым способом. Не меняйте сеть соревнования. + +```bash +python3 durka.py down +python3 durka.py up +python3 durka.py status +``` + +Откройте Farm и Packmate, проверьте Neo безвредным скриптом, просканируйте локальную копию сервиса и импортируйте закрытый синтетический PCAP. Остановите и запустите стек снова. Если что-то пытается скачиваться, исправьте подготовку ещё дома. Ручной PCAP-анализ остаётся доступен, когда LIVE-захват запрещён. + +Это офлайн-перезапуск подготовленной машины, а не установка на пустую. Экспорт Docker images сам по себе не включает Python, Docker Desktop, локальный конфиг, лицензии или Neo client. + + +## Необязательный архив core + +Сопровождающий может создать архив только tracked-исходников из закоммиченного checkout. Родительский каталог должен существовать, путь архива должен быть новым. + +```bash +python3 scripts/build_offline_bundle.py --output ../offline-kit/durkahelper-core.tar.gz +python3 scripts/build_offline_bundle.py --verify ../offline-kit/durkahelper-core.tar.gz +``` + +В core-архив не входят ключи, локальные данные, логи и PCAP. Сторонних runtimes/images в нём тоже нет. Проверка автоматическая; для обычной работы переписывать хеш не нужно. + + +## Перенос внешнего кеша + +Для другой машины есть расширенные утилиты export/import: они сохраняют закреплённые образы и проверяют входную inventory. Это не часть обычного запуска. + +```bash +python3 scripts/toolchain_inventory.py --help +python3 scripts/toolchain_bundle.py --help +``` + +Низкоуровневые команды намеренно требуют независимо доверенного входа для импортируемых архивов. Не обходите эту проверку и не выдавайте частичный экспорт образов за полный установочный комплект. Заполненные inventories храните приватно. Перед распространением проверьте [лицензии](../THIRD_PARTY_NOTICES-RU.md); [developer fixtures](../integration/README-RU.md) проверяют изолированный cold start. diff --git a/docs/offline-bundles.md b/docs/offline-bundles.md new file mode 100644 index 0000000..a7dbdbb --- /dev/null +++ b/docs/offline-bundles.md @@ -0,0 +1,60 @@ +# Offline operation + +English | [Русский](offline-bundles-RU.md) + +## Prepare the machine once + +The scanner needs Python 3.10+; the full stack also needs Docker and cached images. Install these while connected. Follow the [Mac setup](MACOS_FULL_DEPLOYMENT_AND_TESTING.md), finish `durka.py setup`, start the stack, and test it before leaving for the event. + +Keep your repository, private `local/` directory and Docker data. Do not delete Docker images, reset Docker Desktop or run cleanup/prune before an offline start. Setup can download/build; normal startup uses prepared image identities and must not silently pull. + +## Rehearse without Internet + +### Prepare clean event state after a rehearsal + +Do not delete the prepared workspace before creating its replacement. First stop the native Neo worker (`Ctrl+C`) and run `down` with the rehearsal config. Keep the pinned source cache and Docker images. On that same prepared Mac/Linux machine: + +```bash +python3 durka.py --config local/event.json prepare-clean --from-config local/rehearsal.json +python3 durka.py --config local/event.json prepare-clean --from-config local/rehearsal.json --apply +``` + +The first command is a read-only preview. The second writes a **new** private config and `local/event-workspace`, using verified existing image identities and local pinned source checkouts. It does not download, build, start containers, copy old databases/tasks/captures, or delete the rehearsal. It generates fresh local passwords, placeholder jury/team settings, empty persistent state and an empty FILE capture. The previous local ports are retained; the new bind is initially `127.0.0.1`. Missing images, dirty/missing source cache, a running source deployment, remote Docker endpoints or existing output paths block preparation. A failed partial candidate is retained for inspection; choose a new config filename before retrying. + +Fill `local/event.json` with the actual LAN bind, team map, Vulnbox IP, flag format and approved ForcAD submission settings. Then run `configure`, `up` and `doctor` with `--config local/event.json`. Worker execution and submission remain opt-in; do not enable them with placeholder settings. The new native Neo config is `local/event-workspace/config/neo-native.yml`; use the prepared native binary, not the previous rehearsal client config. After changing the LAN bind, pass Neo's `--host MAC_LAN_IP:NEO_PORT` override to the new config. Prepare each script's dependencies separately. + +Verify the new installation and disconnected startup before removing the old rehearsal config/workspace. Retain the repository, pinned source cache, cached images, Neo binary and separate Linux LIVE image bundle. Re-create the LIVE target config for the actual authorized host/interface; its populated rehearsal config is not portable. This prepares **fresh application state on an already prepared machine**, not an offline installer for a blank Mac. Do not use Docker prune/reset or broad deletion of `local/`. + +Keep Ethernet/LAN access, but disconnect the Internet using your own permitted arrangement. Do not change event networking. + +```bash +python3 durka.py down +python3 durka.py up +python3 durka.py status +``` + +Open Farm and Packmate, test Neo with a harmless script, scan a local service copy and import a closed synthetic PCAP. Stop and start again. If anything attempts a download, fix the preparation while still at home. Manual PCAP analysis remains available when LIVE capture is not permitted. + +This is an offline restart on a prepared machine, not installation on an empty machine. Exporting Docker images alone does not include Python, Docker Desktop, local config, licenses or Neo client binaries. + +## Optional core archive + +Maintainers can create a tracked-only source archive from a committed checkout. The output parent must exist and the archive path must be new. + +```bash +python3 scripts/build_offline_bundle.py --output ../offline-kit/durkahelper-core.tar.gz +python3 scripts/build_offline_bundle.py --verify ../offline-kit/durkahelper-core.tar.gz +``` + +The core archive excludes keys, local data, logs and PCAP. It does not contain third-party runtimes/images. Verification is automatic; no hash needs to be transcribed for ordinary operation. + +## Moving an external cache + +For transport to another machine, advanced export/import utilities preserve pinned image identities and verify the incoming inventory. They are not part of routine startup. + +```bash +python3 scripts/toolchain_inventory.py --help +python3 scripts/toolchain_bundle.py --help +``` + +These lower-level commands deliberately require an independently trusted input for imported archives. Do not bypass that check or treat a partial image export as a complete installation kit. Keep populated inventories private. Review [third-party licenses](../THIRD_PARTY_NOTICES.md) before redistribution; the [developer fixtures](../integration/README.md) exercise isolated cold-start behavior. diff --git a/docs/offline-scanner-RU.md b/docs/offline-scanner-RU.md new file mode 100644 index 0000000..2547392 --- /dev/null +++ b/docs/offline-scanner-RU.md @@ -0,0 +1,121 @@ + +# Офлайн-сканер исходников + +[English](offline-scanner.md) | Русский + +[Каталог](vulnerabilities/README-RU.md) · [Рабочий процесс оператора](defense-RU.md) · [Разработка](development-RU.md) + +Scanner 1.8.0 использует 174 локальных правила: 30 Python AST, 143 regex и одно правило ограниченного анализа JS-токенов. Подсказки конкретных frameworks также расширяют существующие правила. Это детерминированный помощник для review с ограничениями ресурсов; он не является базой CVE, dependency resolver, детектором эксплойтов или движком межпроцедурного taint-анализа. + + +## Первый безопасный scan + +Свидетельство: `REVIEWED`; исторические прогоны записываются отдельно. Эффект: `READ-ONLY` (перенаправление stdout создаёт выбранный вами файл вывода). Рабочий каталог: корень DurkaHelper. Требования: Python 3.10+, разрешённая локальная копия сервиса и приватный каталог вывода. Входной код не исполняется, сетевых запросов нет. Rollback: не нужен; проверяйте вывод перед передачей другим. + +```bash +python3 -I -S scripts/defense_scan.py /path/to/service --patches +python3 -I -S scripts/defense_scan.py /path/to/service --json +python3 -I -S scripts/defense_scan.py --list-rules +python3 -I -S scripts/defense_scan.py --explain PY-SQL +``` + +Используйте показанный выше isolated/no-site режим интерпретатора, чтобы не загружать Python startup files, контролируемые целью. Сканер загружает свой доверенный rule pack, а не правила из сканируемого каталога. Не устанавливайте зависимости и не импортируйте цель только ради её изучения. + + +## Как читать находку + +Каждая находка содержит путь относительно root и физическую строку, стабильный rule ID, статическое объяснение, шаблон исправления, рекомендации проверки и точную ссылку на каталог. Новые metadata добавляют family, применимый CWE, review priority, signal kind и limitations. Это классификация для review, а не доказательство достижимости или эксплуатируемости. + +Находки не включают raw source lines, argv, environment или обнаруженные значения секретов. Имена файлов и hashes всё равно могут быть чувствительными. Текстовый вывод безопасно представляет неподдерживаемые консолью символы; JSON переносим. + +Корректное исправление может сохранить сигнал: например, проверенный dynamic URL или bounded reader всё ещё может совпадать с правилом. И наоборот, удаление или перенос кода может убрать совпадение, не исправляя авторизацию. Изучайте настоящий путь source-to-sink и проверяйте поведение. + + +## Контекст инфраструктуры + +Необязательный [пример context](../config/scanner-context.example.json) строго не содержит секретов: + +```json +{ + "schema": "durkahelper.scanner-context.v1", + "infrastructure": ["docker-desktop", "compose", "vulnbox", "team-lan", "s4dfarm", "neo", "packmate"], + "role": "both" +} +``` + +Свидетельство: `REVIEWED`; эффект `READ-ONLY`; рабочий каталог и требования те же, что для первого scan. Ожидается: те же применимые правила остаются включёнными, но получают контекстные приоритеты и объяснения. Это не подразумевает runtime discovery или разрешение на действия. + +```bash +python3 -I -S scripts/defense_scan.py /path/to/service \ + --context config/scanner-context.example.json --json +``` + +Допустимые роли: defender, administrator и both. Context никогда не отключает правила, не выполняет команды, не разрешает сетевые операции и не раскрывает состояние работающего Docker. Его нормализованный смысл входит в scope fingerprint отчёта. + + +## Входы и ограничения + +Поддерживаемые семейства исходников и конфигурации: Python, JavaScript/TypeScript, PHP, Go, Java, C#/.NET, C/C++, Ruby, Rust, SQL, templates, Dockerfiles, shell и распространённые форматы конфигурации. Язык определяется по имени файла; поддерживаемое имя не доказывает язык или версию runtime. + +По умолчанию: 1 MiB на файл, 20 000 файлов, 10 000 находок. Сканер исключает распространённые dependency/build/cache-каталоги и похожие на секреты имена файлов, например форматы private keys и .env, не являющиеся примерами. Явные исключения записываются в scope. Оцените, требуется ли отдельный разрешённый review для excluded/generated/vendor code. + +Свидетельство: `REVIEWED`; эффект `READ-ONLY`; рабочий каталог — корень. Эти параметры меняют покрытие и, следовательно, сопоставимость: + +```bash +python3 -I -S scripts/defense_scan.py /path/to/service \ + --exclude generated --max-bytes 1048576 --max-files 20000 --max-findings 10000 --json +``` + +Symlink leaves, nonregular files, нечитаемые или нестабильные файлы, parsing failures и превышенные limits дают incomplete/partial, а не ложный clean success. Обычные ancestor links macOS отличаются от небезопасных input leaves. Никогда не ослабляйте эти защиты ради зелёного отчёта. + +Regex-сканирование использует ограниченные перекрывающиеся окна: до 12 физических строк и 8 192 символов в окне с перекрытием в шесть строк. Слишком длинные физические строки пропускаются с partial issue. Шаблоны за границей окна, неизвестные wrappers и сгенерированные строки могут быть пропущены. У новых code-only детекторов есть лексические исключения; старые regex-детекторы всё ещё могут находить совпадения в комментариях или строковых примерах. + +Python-анализ — ограниченный синтаксический обход AST с ограниченным отслеживанием import aliases/scalars и консервативной инвалидацией. Он не разрешает произвольные types, branches, dynamic imports или значения между function calls. Ошибки parse/node-limit сообщаются. Обработка aliases в JavaScript ограничена; это не полный parser или scope/taint engine. + + +## JSON, scope и сравнение + +Отчёты включают tool version, timestamp, offline flag, scope, findings, issues, skipped counts, scanned counts, partial и exit code. Scope v2 связывает canonical root identity, rule fingerprint, path semantics, exclusions, limits и scanner context. Порядок context нормализуется перед hashing. Сравнения между версиями или scope не взаимозаменяемы. + +Свидетельство: `REVIEWED`; эффект `READ-ONLY`. Рабочий каталог — корень; нужны два приватных JSON-отчёта заведомо сопоставимых scans. Ожидается: множества new/existing/not-observed либо exit 2 при неполном сравнении. Входные файлы не изменяются. + +```bash +python3 -I -S scripts/defense_diff.py before-scan.json after-scan.json --json +``` + +Старые отчёты остаются читаемыми там, где это поддержано, но отсутствующий scope, различия v1/v2, изменения версии или partial reports не позволяют получить безусловно сопоставимый результат. Сопоставление использует path/line/rule: перенос строки может выглядеть как удалённый и добавленный сигнал. «Not observed» никогда не означает «уязвимость исправлена». + +| Exit | Значение | +|---|---| +| 0 | Полный поддерживаемый scan без находок либо полное сравнение без новых сигналов, требующих действий | +| 1 | Находки или новые сигналы, требующие review | +| 2 | Invalid, partial, blocked или incomparable result; также отсутствие поддерживаемых входов | + + +## Покрытие и следующие шаги + +Свидетельство: `REVIEWED`; эффект `READ-ONLY`; рабочий каталог — корень. Проверка анализирует только безвредные строки; snippets не исполняются. + +```bash +python3 scripts/scanner_coverage.py --check +python3 scripts/scanner_coverage.py --json +``` + +Ledger показывает пары rule/language, независимо написанные positives/negatives и честно отмеченные пробелы старых правил. Примеры «до/после» из metadata не считаются независимыми свидетельствами. Для исправлений используйте [каталог](vulnerabilities/README-RU.md) и [проверку патчей](patch-validation-RU.md); для контейнерной политики — [deployment audit](local-tools-RU.md#deployment-audit), не утверждая, что YAML regex доказывает runtime safety. + + + +## Границы framework и базы данных + +| Область | Расширенные сигналы | Ручная проверка | +|---|---|---| +| Flask | Явные debugger/session settings; auth order включая put/patch/delete; credentials в app.logger | Проверяйте зарегистрированный HTTP endpoint, не только вызов функции. Сохраняйте HttpOnly; не включайте Secure поверх HTTP-only checker. | +| Psycopg | SQL(не-литерал), сырые/неизвестные части format/join/as_string; известный quoting подавляет этот сигнал | Bind values через реальный драйвер. Identifier экранирует имя, но не разрешает выбирать любую таблицу. | +| PostgreSQL | ROLE/USER bypass, значимые PUBLIC grants, роли доступа к файлам/программам сервера | Проверьте runtime-роль, наследование и ownership. Меняйте только согласованные права сервиса; проверьте запросы, миграции и восстановление. | +| JS/TS | SQL из request в известных pg/mysql bindings, reflective credentialed cors, отключённый session HttpOnly, прямые credentials в логах | Bind values, allowlist origins, сохраните HttpOnly и логируйте категории. Проверьте ошибки auth, sessions, реальные response headers и checker. | + +JS-подсказки используют ограниченные токены, не полноценный парсер: 100 000 токенов на файл, 128 вложенных delimiters, 2 048 токенов на выражение. Распознаются точные default/namespace imports и прямые конструкторы драйверов. Наблюдаемое переприсваивание/parameter shadowing консервативно отключает binding во всём файле. Именованные импорты, неоднозначные regex, templates, динамические keys/spreads, полученные соединения, custom loggers и потоки между файлами проверяются вручную. Helper redact() не считается доверенным и не исполняется: его результат вне прямого поиска значений. + +Сигналы Docker privilege/socket/root-user остаются включены. Проверьте локальные Compose/Dockerfile, затем deployment-model audit для bind, backend exposure, mounts, image pins и runtime policy. Скан исходников не проверяет работающий daemon. LIVE и закрытый PCAP описаны в [захвате трафика](traffic-capture-RU.md). + +Версия 1.8.0 повышает semantic revision до v3. Старые revision-v2 отчёты читаются, но старое/новое сравнение завершается exit 2. Перед проверкой патча пересканируйте обе копии одной версией и с одинаковым контекстом; карточки с digest вручную заполнять не нужно. diff --git a/docs/offline-scanner.md b/docs/offline-scanner.md new file mode 100644 index 0000000..cdbae37 --- /dev/null +++ b/docs/offline-scanner.md @@ -0,0 +1,112 @@ +# Offline source scanner + +English | [Русский](offline-scanner-RU.md) + +[Catalog](vulnerabilities/README.md) · [Operator workflow](defense.md) · [Development](development.md) + +Scanner 1.8.0 uses 174 local rules: 30 Python AST, 143 regex and one bounded JavaScript-token rule. Framework-specific token hints also extend existing rules. It is a bounded, deterministic review assistant—not a CVE database, dependency resolver, exploit detector or interprocedural taint engine. + +## Safe first scan + +Evidence: `REVIEWED`; historical execution is recorded separately. Effect: `READ-ONLY` (stdout redirection creates your chosen output file). Cwd: DurkaHelper root. Prerequisites: Python 3.10+, an authorized local service copy and a private output directory. No input code executes and no network requests occur. Rollback: none; review output before sharing it. + +```bash +python3 -I -S scripts/defense_scan.py /path/to/service --patches +python3 -I -S scripts/defense_scan.py /path/to/service --json +python3 -I -S scripts/defense_scan.py --list-rules +python3 -I -S scripts/defense_scan.py --explain PY-SQL +``` + +Use the interpreter's isolated/no-site mode shown above to avoid loading target-controlled Python startup files. The scanner loads its own trusted rule pack, not rules supplied by the scanned directory. Do not install dependencies or import the target just to inspect it. + +## Reading a finding + +Each finding includes a root-relative path and physical line, stable rule ID, static explanation, fix template, verification guidance and an exact catalog link. New metadata adds family, CWE where applicable, review priority, signal kind and limitations. These are review classifications, not proof of reachability or exploitability. + +Findings do not include raw source lines, argv, environment or discovered secret values. Filenames and hashes can still be sensitive. Text output safely represents unsupported console characters; JSON is portable. + +A correct fix can retain a signal: for example a validated dynamic URL or bounded reader may still match. Conversely, deleting or moving code may remove a match without fixing authorization. Review the real source-to-sink path and verify behavior. + +## Infrastructure context + +The optional [context example](../config/scanner-context.example.json) is strictly non-secret: + +```json +{ + "schema": "durkahelper.scanner-context.v1", + "infrastructure": ["docker-desktop", "compose", "vulnbox", "team-lan", "s4dfarm", "neo", "packmate"], + "role": "both" +} +``` + +Evidence: `REVIEWED`; effect `READ-ONLY`; same cwd/prerequisites as the first scan. Expected: the same applicable rules remain enabled, with contextual priorities/explanations. No runtime discovery or permission is implied. + +```bash +python3 -I -S scripts/defense_scan.py /path/to/service \ + --context config/scanner-context.example.json --json +``` + +Allowed roles are defender, administrator and both. Context never disables rules, executes commands, authorizes network operations or reveals running Docker state. Its normalized meaning participates in the report scope fingerprint. + +## Inputs and limits + +Supported source/configuration families include Python, JavaScript/TypeScript, PHP, Go, Java, C#/.NET, C/C++, Ruby, Rust, SQL, templates, Dockerfiles, shell and common configuration formats. Language detection is filename-based; a supported filename does not prove runtime language or version. + +Defaults: 1 MiB per file, 20,000 files, 10,000 findings. The scanner excludes common dependency/build/cache directories and secret-like filenames such as private-key formats and non-example .env files. Explicit exclusions are recorded in scope. Review whether excluded/generated/vendor code needs a separate authorized review. + +Evidence: `REVIEWED`; effect `READ-ONLY`; cwd root. These options change coverage and therefore comparability: + +```bash +python3 -I -S scripts/defense_scan.py /path/to/service \ + --exclude generated --max-bytes 1048576 --max-files 20000 --max-findings 10000 --json +``` + +Symlink leaves, nonregular files, unreadable/unstable files, parsing failures and exceeded limits produce incomplete/partial results, not false-clean success. Normal macOS ancestor links are distinguished from unsafe input leaves. Never relax these protections to make a report green. + +Regex scanning uses bounded overlapping windows: up to 12 physical lines and 8,192 characters per window, with six-line overlap. Oversized physical lines are omitted with a partial issue. Patterns spread beyond the window, unknown wrappers and generated strings can be missed. New code-only detectors have lexical exclusions; older regex detectors may still match comments or string examples. + +Python analysis is bounded syntactic AST traversal, with limited import-alias/scalar tracking and conservative invalidation. It does not resolve arbitrary types, branches, dynamic imports or values across function calls. Parse/node-limit failures are reported. JavaScript alias handling is bounded rather than a complete parser or scope/taint engine. + +## JSON, scope and comparison + +Reports include tool version, timestamp, offline flag, scope, findings, issues, skipped counts, scanned counts, partial and exit code. Scope v2 binds canonical root identity, rule fingerprint, path semantics, exclusions, limits and scanner context. Context ordering is normalized before hashing. Cross-version or cross-scope comparisons are not interchangeable. + +Evidence: `REVIEWED`; effect `READ-ONLY`. Cwd: root; prerequisites two private JSON reports from intentionally comparable scans. Expected: new/existing/not-observed sets, or exit 2 when comparison is incomplete. No input files are changed. + +```bash +python3 -I -S scripts/defense_diff.py before-scan.json after-scan.json --json +``` + +Older reports remain readable where supported, but missing scope, v1/v2 differences, version changes or partial reports prevent an unqualified comparable result. Matching uses path/line/rule: moving a line can appear as a removed and added signal. “Not observed” never means “vulnerability fixed.” + +| Exit | Meaning | +|---|---| +| 0 | Complete supported scan without findings; or complete comparison without actionable new signals | +| 1 | Findings/new signals needing review | +| 2 | Invalid, partial, blocked or incomparable result; also no supported input | + +## Coverage and next steps + +Evidence: `REVIEWED`; effect `READ-ONLY`; cwd root. The check evaluates inert strings only; it does not execute the snippets. + +```bash +python3 scripts/scanner_coverage.py --check +python3 scripts/scanner_coverage.py --json +``` + +The ledger reports rule/language pairs, independently authored positives/negatives and honest legacy gaps. Metadata before/after examples do not count as independent evidence. For fixes use the [catalog](vulnerabilities/README.md) and [patch verification](patch-validation.md); for container policy use [deployment auditing](local-tools.md#deployment-audit), not a claim that YAML regex proves runtime safety. + +## Framework and database boundaries + +| Area | Expanded signals | Manual verification | +|---|---|---| +| Flask | Explicit debugger/session config; auth order including put/patch/delete; credentials in app.logger | Test the registered HTTP endpoint, not just a function call. Keep HttpOnly; do not force Secure onto an HTTP-only checker. | +| Psycopg | SQL(nonliteral), raw/unknown format/join/as_string pieces; known quoting compositions suppress this signal | Bind values using the deployed driver. Identifier quotes a name but does not authorize selection of any table. | +| PostgreSQL | ROLE/USER bypass, meaningful PUBLIC grants, server file/program roles | Inspect the real runtime role, inheritance and ownership. Change only approved service rights; retest queries, migrations and recovery. | +| JS/TS | Request SQL to recognized pg/mysql bindings, reflective credentialed cors, disabled session HttpOnly, direct credential logging | Bind values, allowlist origins, retain HttpOnly and log categories. Test failed auth, sessions, real response headers and the checker. | + +JS hints use bounded tokens, not a complete parser: 100,000 tokens per file, 128 nested delimiters, 2,048 tokens per inspected expression. Exact default/namespace imports and direct driver constructors are recognized. Observed reassignment/parameter shadowing disables a binding conservatively file-wide. Named imports, regex ambiguity, templates, dynamic keys/spreads, acquired connections, custom loggers and cross-file flows remain manual. A helper called redact() is not trusted or executed: its return value lies outside direct-value detection. + +Docker privilege/socket/root-user signals remain enabled. Scan local Compose/Dockerfile sources, then use deployment-model auditing for binds, backend exposure, mounts, image pins and runtime policy. Neither source scan verifies the running daemon. See [traffic capture](traffic-capture.md) for LIVE and closed-PCAP routes. + +Version 1.8.0 advances semantic revision to v3. Old revision-v2 reports remain readable but old/new comparison exits 2. Rescan both copies with the same scanner/context before patch verification; no manual digest cards are required. diff --git a/docs/packmate-RU.md b/docs/packmate-RU.md new file mode 100644 index 0000000..bd03640 --- /dev/null +++ b/docs/packmate-RU.md @@ -0,0 +1,74 @@ + +# Packmate: разбор трафика + +[English](packmate.md) | Русский + +Packmate показывает запросы/ответы и ищет по содержимому потоков. Он помогает защитнику распознать атаку и проверить изменение нужного поведения после патча. DurkaHelper даёт конфигурацию и launch/import; upstream-исходники не меняются. + + +## Где настроить сервисы и поиск в UI + +Порт веб-интерфейса задаётся при deployment (`--ui-port` для SSH LIVE). +Это **не порт анализируемого приложения**. Интерфейс захвата и IP стороны +сервиса задаются в приватном deployment-конфиге, не в форме создания сервиса. +Шестерёнка справа открывает дополнительные настройки UI. + +1. На верхней панели нажмите **+**: заполните **Name** и **Port** приложения. + Для нескольких портов создайте отдельную запись на каждый. Без регистрации + сервиса потоки не сохраняются. Для обычного HTTP расшифровка TLS не нужна. +2. Выберите созданный сервис на верхней панели. В LIVE новые потоки появляются + автоматически; кнопка запуска анализа есть только в FILE. +3. Для подсветки откройте **Patterns → +**. Укажите узнаваемый синтетический + текст, например `DEMO-`, поиск подстроки, оба направления и действие + **Highlight**, не **Ignore**. При необходимости выберите конкретный сервис. +4. Откройте новый поток и проверьте запрос и ответ. Новый pattern действует на + последующие потоки; **Lookback** применяет его к уже сохранённым. + **Pause** приостанавливает отображение в вашем браузере, не сам захват. + +Эти действия изменяют настройки Packmate в его БД, а не приложение или сеть. +Если UI пустой, сначала проверьте регистрацию порта и отсутствие фильтра по +pattern; затем IP стороны сервиса и наличие разрешённого трафика. +Элементы сверены с [upstream UI guide закреплённой версии](https://gitlab.com/packmate/Packmate/-/blob/938031f1dedfbedabef5b049368ed5b6ba6a900a/docs/USAGE_EN.md). + + +## FILE на ноутбуке + +```bash +python3 durka.py up +python3 durka.py traffic import /path/to/closed-capture.pcap +python3 durka.py status +``` + +Откройте URL Packmate. Логин/пароль — `credentials.packmate_user / packmate_password` из приватного конфига админа. + +1. [Зарегистрируйте сервис и шаблон поиска в UI](#ui-services-and-patterns). +2. Проверьте `profile.packmate.local_ip`: это IP стороны сервиса **в capture**, а не адрес ноутбука. +3. В боковой панели один раз нажмите жёлтую кнопку разбора FILE со стрелкой вниз + и найдите известные запрос/ответ с правильным направлением. Не ищите буквальную + надпись «Start» или форму загрузки: сам файл уже передан import-командой. +4. Для следующего закрытого файла повторите import; перезапустится только Packmate, БД/предыдущий файл сохранятся. + +EOF не сбрасывает started upstream. Не меняйте активный файл вручную под работающим parser. Трафик может содержать пароли, cookies и флаги; не показывайте в публичных artifacts. + +Import не меняет `local_ip`: он должен совпадать с реальным IP стороны сервиса +в данном PCAP, а не адресом из другого демопримера. Если конфиг FILE требует +изменения после setup, используйте [процедуру down → edit → configure → up](MACOS_FIRST_RUN-RU.md#6-failures-and-safe-shutdown), +затем повторите import и нажмите кнопку разбора FILE. + + +## LIVE на Linux + +LIVE требует разрешения и точки наблюдения, которая видит пакеты Vulnbox: сам Vulnbox или разрешённый Linux mirror/capture node. Обычный deployment Docker Desktop — только FILE. + +Выберите и прогоните [вариант захвата](traffic-capture-RU.md) до игры. Бесконечный FILE pipe не равен LIVE: timeout незавершённых потоков/periodic cleanup привязаны к LIVE upstream. Ноутбук на том же switch не видит весь трафик автоматически. + + +## Ресурсы и диагностика + +Текущий образ Packmate только amd64; Apple Silicon использует эмуляцию. Следите за CPU, памятью, ростом БД/capture и диском. Очистка LIVE по возрасту — не жёсткая disk quota; у FILE нет периодической LIVE-очистки. + +UI пустой: регистрация сервиса, pattern, IP стороны сервиса, время и известный capture. Направление TCP/UDP и содержимое полезнее статуса работающего контейнера. + +Конфиг подавляет конкретный upstream authentication-failure logger, который иначе печатает введённые пароли. Используйте сгенерированную конфигурацию; не запускайте stock-логирование с приватными credentials. + +[Работа с трафиком](traffic-capture-RU.md) · [Инструкция участника](participant-guide-RU.md) · [Upstream setup](https://gitlab.com/packmate/Packmate/-/blob/938031f1dedfbedabef5b049368ed5b6ba6a900a/docs/SETUP.md) diff --git a/docs/packmate-remote-RU.md b/docs/packmate-remote-RU.md new file mode 100644 index 0000000..ba9c863 --- /dev/null +++ b/docs/packmate-remote-RU.md @@ -0,0 +1,194 @@ + +# Packmate LIVE: запуск с ноутбука по SSH + +[English](packmate-remote.md) | Русский + +Все команды ниже выполняются **на ноутбуке из корня DurkaHelper**. На Vulnbox +Python не нужен: программа переносит готовые конфиги и запускает Docker Compose. +Это не заменяет [FILE import](traffic-capture-RU.md#file-on-the-laptop) на Mac. + + +## Что требуется + +- На ноутбуке: Python 3.10+, SSH; Docker нужен только для подготовки образов. + Для комплекта требуется Docker CLI/Engine API 1.49+ с явным + [выбором платформы](https://docs.docker.com/reference/cli/docker/image/inspect/). +- На источнике трафика: native Linux **amd64**, локальный rootful Docker Engine, + Compose v2, `sh`, `tar`, `ip`, `ss`, `stat`, `df`, `sha256sum`, `cut`, `awk`. +- Работающий доступ по ключу и заранее проверенный SSH host key. Программа не + принимает новый host key автоматически. Для ключа с passphrase сначала выполните + `ssh-add ~/.ssh/ctf_capture` — парольная фраза не передаётся программе. +- Разрешение на **весь выбранный интерфейс**, host networking и NET_RAW. + Не используются privileged, NET_ADMIN, Docker socket mounts или установка пакетов. +- Минимум 3 GiB доступной RAM и 5 GiB свободного диска перед запуском. Контейнеры + ограничены суммарно 2 CPU / 2 GiB RAM. Очистка по возрасту — не жёсткая disk quota. + +Неизменённый upstream Packmate кратко использует широкий TCP/UDP startup filter. +Mac на обычном switch не видит автоматически трафик Vulnbox. Выбор интерфейса +определяет разрешённый источник трафика; программа не создаёт зеркало и не меняет +firewall или маршруты вручную. Docker создаёт только сети своего deployment. + + +## 1. Read-only doctor — до настройки + +Замените example hostname и путь ключа. Если используется уже одобренный Docker +wrapper, передайте его абсолютный путь через `--docker`; shell-команды не допускаются. + +```bash +python3 durka.py traffic live doctor \ + --host example@vulnbox.example --key ~/.ssh/ctf_capture \ + --ui-port 65000 --db-port 55432 +``` + +Doctor собирает Engine ID, архитектуру, интерфейсы/IP, RAM, диск, доступность +Compose/утилит, наличие amd64-образов и занятость двух портов. **Ничего не пишет +на Vulnbox, не скачивает и не запускает.** PASS означает пригодность проверенных +предпосылок, а не доказанную видимость трафика. WARNING для отсутствующих образов +исправляется офлайн-комплектом. BLOCKED означает проблему доступа, платформы, +ресурсов или портов; чужие процессы/контейнеры не останавливайте. + + +## 2. Подготовить офлайн-образы до соревнования + +При доступном Интернете на ноутбуке и запущенном Docker: + +```bash +python3 durka.py traffic live bundle \ + --output local/packmate-live-images --download --apply +``` + +Скачиваются **два закреплённых Linux amd64 образа**, даже на ARM64 Mac. Если они +уже кешированы, уберите `--download`. Каталог должен быть новым. В нём находятся +`images.tar` и автоматический manifest; вручную SHA заполнять не нужно. Сохраните +оба файла вместе. Обычный ARM64 PostgreSQL из Mac-стека не заменяет amd64 образ. +Проверка и экспорт явно выбирают Linux amd64, даже если в кеше одновременно +есть ARM64-вариант; работающий Mac-стек не изменяется. +Команда изменяет только локальные файлы и image cache, не запускает контейнеры. +Не коммитьте архивы образов; перед публичным распространением отдельно проверьте upstream licenses. + + +## 3. Создать один приватный конфиг + +Примерные значения заменяются результатом doctor и правилами площадки: + +```bash +python3 durka.py traffic live init \ + --host example@vulnbox.example --key ~/.ssh/ctf_capture \ + --remote-dir /home/example/durka-packmate-live \ + --interface eth0 --service-ip 192.0.2.10 --bind 192.0.2.20 \ + --ui-port 65000 --db-port 55432 +``` + +`--service-ip` — IP стороны защищаемого сервиса **в захватываемом трафике**; +`--bind` — назначенный Linux-хосту IP для UI. Они могут различаться. +Interface index/MAC и Engine ID подставляются автоматически. Создаётся только +локальный `local/packmate-remote.json` с новыми паролями; источник не меняется. +Не публикуйте этот файл и не показывайте его публично. Повторный init не перезаписывает +конфиг. Другой deployment: отдельные `--config` и `--remote-dir`. + + +## Где находится deployment-конфиг + +На ноутбуке: `local/packmate-remote.json` (либо файл из `--config`). +Он отдельный от farm/FILE-конфига. Пароли внутри: не показывайте файл публично +и не коммитьте его. В секции `profile` находятся: + +| Поле | Назначение | Значение по умолчанию при init | +|---|---|---| +| `interface` | Разрешённый Linux-интерфейс захвата | Выбирается через `--interface` | +| `local_ip` | IP стороны сервиса в пакетах; определяет направление | `--service-ip` | +| `bind_address`, `ui_port` | Linux-адрес и порт веб-интерфейса | `--bind`, порт 65000 | +| `db_port` | PostgreSQL, только IPv4 loopback | 55432 | +| `tcp_timeout_seconds`, `udp_timeout_seconds` | Таймауты потоков | 30 / 10 секунд | +| `timeout_check_seconds` | Период проверки таймаутов | 5 секунд | +| `retention_minutes`, `cleanup_interval_minutes` | Возраст удаления и период очистки | 60 / 1 минут | + +Порты приложений и поисковые patterns задаются отдельно [в UI](packmate-RU.md#ui-services-and-patterns). +На Linux `workspace/application.properties` и `runtime-compose.json` генерируются +из этого конфига автоматически. Вручную на источнике их не редактируйте. + +Адреса/порты/интерфейс выбирайте при `init`; таймауты и retention в `profile` +можно настроить **до первого up**, сохранив права файла 0600. Engine ID, +index/MAC интерфейса, project и images — автоматические проверки, не параметры +для обхода ошибки doctor. Credentials не меняйте отдельно от существующей БД. + +После deployment конфиг и runtime проверяются на точное соответствие. +Изменение локального JSON **не обновляет** работающий Packmate: текущий launcher +не поддерживает in-place reconfiguration. Сохраните исходный конфиг для безопасного +`down`; другое deployment создавайте через отдельные `--config` и новый +`--remote-dir`, проверив свободные порты и разрешения. Старые данные сохраняются, +но история БД автоматически в новый workspace не переносится. + + +## 4. Проверить и запустить + +```bash +python3 durka.py traffic live doctor --bundle local/packmate-live-images +python3 durka.py traffic live up --bundle local/packmate-live-images \ + --apply --host-network-approved --interface-scope-approved +``` + +Вторая команда **изменяет источник**: при необходимости загружает переданные +образы, создаёт только новый приватный workspace и два своих контейнера. +Интернет на Vulnbox не используется: нет pull/build/install, запуск всегда +`--no-build --pull never`. Если закреплённые образы уже есть на источнике, +`--bundle` можно убрать. Непроверенные/изменившиеся образы не принимаются. + +Ожидается `status: PASS`, `authenticated_capture_started: true`, адрес UI. +Авторизованная готовность проверяется через временный SSH tunnel; SSH forwarding +должен быть разрешён. **Это ещё не подтверждение корректности трафика.** +Проверка интерфейса/Engine повторяется; старый workspace не перезаписывается. + + +## 5. Войти и проверить транзакцию + +На Mac скопировать пароль, не выводя его на экран: + +```bash +python3 durka.py traffic live password +``` + +Логин `operator`, пароль вставьте из буфера в UI по адресу из `up`. Команда +изменяет только буфер Mac. На других ОС используйте приватное поле +`credentials.password` без трансляции экрана. Зарегистрируйте сервисы/шаблоны +в UI [по пошаговой инструкции](packmate-RU.md#ui-services-and-patterns), найдите известные **request и response**, проверьте направление, время, +повторный запрос и доступность приложения. Статус контейнера этого не заменяет. + + +## 6. Остановка и повторный старт + +```bash +python3 durka.py traffic live status +python3 durka.py traffic live down --apply +python3 durka.py traffic live up --bundle local/packmate-live-images \ + --apply --host-network-approved --interface-scope-approved +``` + +`down` останавливает только проект этого конфига и сохраняет PostgreSQL/настройки. +Не использует `down -v`, `prune` или удаление каталогов. Проверки ownership не дают +ему остановить чужой проект. Старый запуск другим helper не присваивается автоматически. + + +## Если не получилось + +- SSH failed: сначала проверьте обычный SSH, fingerprint и `ssh-add`; ключ не + копируйте на Vulnbox. Программа работает без интерактивных password prompts. +- Порты заняты: выберите свободные при init или самостоятельно остановите + **только известный свой** старый deployment. Firewall автоматически не меняется. +- Missing/wrong-platform images: подготовьте комплект именно Linux amd64. +- Interface/Engine changed: заново проверьте источник и разрешённый scope; + не обходите проверку редактированием идентификаторов наугад. +- Readiness timeout: свои контейнеры могли уже запуститься. Выполните `status`, + затем при необходимости `down --apply`; данные сохраняются. +- Неполный перенос: каталог сохраняется для диагностики, автоматически не + удаляется и не перезаписывается. Новый workspace допустим только после проверки + частичных ресурсов. Нет автоматической переустановки. +- Нет Docker/Compose или разрешения: LIVE этим путём BLOCKED. Используйте FILE + только при наличии разрешённого закрытого PCAP; это не continuous capture. + +Python-free target обеспечивается отсутствием вызовов Python на источнике. +Успешный Linux deployment не подтверждает Docker Desktop LIVE, реальную +сеть площадки, нагрузку или disk quota. Проверка известной транзакции остаётся +ручным обязательным шагом. + +[Выбор LIVE/FILE](traffic-capture-RU.md) · [Packmate](packmate-RU.md) diff --git a/docs/packmate-remote.md b/docs/packmate-remote.md new file mode 100644 index 0000000..ffd801f --- /dev/null +++ b/docs/packmate-remote.md @@ -0,0 +1,182 @@ +# Packmate LIVE: deploy from the laptop over SSH + +English | [Русский](packmate-remote-RU.md) + +Run every command below **on the laptop, from the DurkaHelper repository root**. +Python is not required on the Vulnbox: the program transfers rendered configuration +and runs Docker Compose. This does not replace [FILE import](traffic-capture.md#file-on-the-laptop) on Mac. + +## Requirements + +- Laptop: Python 3.10+ and SSH; Docker is needed only to prepare image bundles. + Bundle preparation requires Docker CLI/Engine API 1.49+ for explicit + [platform selection](https://docs.docker.com/reference/cli/docker/image/inspect/). +- Traffic source: native Linux **amd64**, local rootful Docker Engine, Compose v2, + `sh`, `tar`, `ip`, `ss`, `stat`, `df`, `sha256sum`, `cut`, `awk`. +- Working key authentication and a verified SSH host key. No automatic host-key + acceptance. For a passphrase-protected identity, first run `ssh-add ~/.ssh/ctf_capture`; + the program does not receive the passphrase. +- Approval for the **entire selected interface**, host networking and NET_RAW. + No privileged containers, NET_ADMIN, Docker socket mounts or package installation. +- At least 3 GiB available RAM and 5 GiB free disk before startup. Combined limits + are 2 CPU / 2 GiB RAM. Age cleanup is not a hard storage quota. + +Unmodified upstream Packmate briefly uses a broad TCP/UDP startup filter. +A Mac on an ordinary switch does not automatically see Vulnbox traffic. Placement +defines permitted traffic visibility; the program does not create mirroring or +manually change firewall/routes. Docker creates only this deployment's networks. + +## 1. Read-only doctor, before configuration + +Replace the example hostname and identity path. For an already approved Docker +wrapper, pass its absolute path using `--docker`; shell commands are not accepted. + +```bash +python3 durka.py traffic live doctor \ + --host example@vulnbox.example --key ~/.ssh/ctf_capture \ + --ui-port 65000 --db-port 55432 +``` + +Doctor reports Engine identity, architecture, interfaces/IPs, RAM/disk, Compose +and utility availability, cached amd64 images and the two requested ports. +**No target writes, downloads or startup.** PASS covers checked prerequisites, not +traffic visibility. WARNING for missing images requires an offline bundle. BLOCKED +means access/platform/resource/port issues; do not stop unrelated workloads. + +## 2. Prepare offline images before the event + +With laptop Internet access and Docker running: + +```bash +python3 durka.py traffic live bundle \ + --output local/packmate-live-images --download --apply +``` + +This downloads **two pinned Linux amd64 images**, including on an ARM64 Mac. Omit +`--download` if both are cached. The output directory must be new. Keep `images.tar` +and the automatic manifest together; no manual SHA forms are required. An ARM64 +PostgreSQL image from the Mac stack does not substitute for the amd64 image. +Inspection and archive export explicitly select Linux amd64, even when the +image cache also contains ARM64 variants; the running Mac stack is not changed. +Only local files and the image cache change; no containers start. +Do not commit image archives; review upstream licenses separately before public redistribution. + +## 3. Create one private configuration + +Replace example values using doctor results and event rules: + +```bash +python3 durka.py traffic live init \ + --host example@vulnbox.example --key ~/.ssh/ctf_capture \ + --remote-dir /home/example/durka-packmate-live \ + --interface eth0 --service-ip 192.0.2.10 --bind 192.0.2.20 \ + --ui-port 65000 --db-port 55432 +``` + +`--service-ip` is the protected service-side IP **in the captured traffic**; +`--bind` is the Linux host's assigned UI IP. They may differ. Interface index/MAC +and Engine identity are filled automatically. Only the local +`local/packmate-remote.json` is created, with generated passwords; the source is +unchanged. Never publish this private file. Init does not overwrite. +Use separate `--config` and `--remote-dir` for another deployment. + +## Where the deployment configuration lives + +On the laptop: `local/packmate-remote.json`, or the file selected by `--config`. +This is separate from the farm/FILE configuration. It contains passwords: keep +it private and out of Git. The `profile` section includes: + +| Field | Purpose | Default at init | +|---|---|---| +| `interface` | Approved Linux capture interface | Selected through `--interface` | +| `local_ip` | Service-side IP in packets; determines direction | `--service-ip` | +| `bind_address`, `ui_port` | Linux web-interface address and port | `--bind`, port 65000 | +| `db_port` | PostgreSQL on IPv4 loopback only | 55432 | +| `tcp_timeout_seconds`, `udp_timeout_seconds` | Stream timeouts | 30 / 10 seconds | +| `timeout_check_seconds` | Timeout-check interval | 5 seconds | +| `retention_minutes`, `cleanup_interval_minutes` | Deletion age and cleanup interval | 60 / 1 minutes | + +Application ports and search patterns are configured separately [in the UI](packmate.md#ui-services-and-patterns). +Linux `workspace/application.properties` and `runtime-compose.json` are generated +automatically from this configuration. Do not edit those files manually. + +Choose addresses/ports/interface during `init`; tune `profile` timeouts and +retention **before the first up**, retaining mode 0600. Engine ID, interface +index/MAC, project and images are automatic checks, not settings to bypass a +doctor error. Do not rotate credentials independently of an existing database. + +After deployment, configuration and runtime must match exactly. Editing local +JSON **does not update** running Packmate: this launcher has no in-place +reconfiguration. Retain the original config for safe `down`; create another +deployment using a separate `--config` and new `--remote-dir`, checking free +ports and approvals. Old data is retained, but database history is not +automatically migrated into the new workspace. + +## 4. Check and start + +```bash +python3 durka.py traffic live doctor --bundle local/packmate-live-images +python3 durka.py traffic live up --bundle local/packmate-live-images \ + --apply --host-network-approved --interface-scope-approved +``` + +The second command **changes the source**: loads transferred images if needed, +creates only a new private workspace and two owned containers. No target Internet +is used: no pull/build/install; startup always uses `--no-build --pull never`. +Omit `--bundle` if the pinned images are already cached on the source. Changed or +unverified images are refused. + +Expect `status: PASS`, `authenticated_capture_started: true` and the UI URL. +Authenticated readiness is checked through a temporary SSH tunnel, requiring +permitted SSH forwarding. **Traffic correctness is still unverified.** Engine and +interface identity are rechecked; an old workspace is not overwritten. + +## 5. Login and inspect a transaction + +On Mac, copy the password without printing it: + +```bash +python3 durka.py traffic live password +``` + +Username is `operator`; paste the password into the UI at the URL returned by `up`. +Only the Mac clipboard changes. On other operating systems use the private +`credentials.password` field without screen broadcasting. Register services/patterns +in the UI [using the step-by-step guide](packmate.md#ui-services-and-patterns), find known **request and response**, check direction/time/repetition and +application health. A running container is not sufficient evidence. + +## 6. Stop and start again + +```bash +python3 durka.py traffic live status +python3 durka.py traffic live down --apply +python3 durka.py traffic live up --bundle local/packmate-live-images \ + --apply --host-network-approved --interface-scope-approved +``` + +Down stops only this configuration's project and retains PostgreSQL/settings. +No `down -v`, prune or directory deletion. Ownership checks prevent foreign-project +shutdown. Deployments created by older helpers are not automatically adopted. + +## Troubleshooting + +- SSH failed: verify ordinary SSH, fingerprint and `ssh-add`. Do not copy the key + to the Vulnbox. The program does not use interactive password prompts. +- Ports occupied: choose free ports at init or manually stop **only a known owned** + older deployment. Firewall is not automatically changed. +- Missing/wrong-platform images: prepare the Linux amd64 bundle. +- Engine/interface changed: review the source and permitted scope; do not guess + replacement identifiers to bypass checks. +- Readiness timeout: owned containers may already be running. Use `status`, then + `down --apply` if necessary; data remains. +- Incomplete transfer: the directory remains for inspection, with no automatic + deletion/overwrite. Inspect partial resources before selecting another workspace. + No automatic reinstall. +- No Docker/Compose or approval: this LIVE path is BLOCKED. FILE requires an + authorized closed PCAP and does not provide continuous capture. + +The Python-free target path makes no target Python calls. Linux success does not +validate Docker Desktop LIVE, the event network, sustained load or a hard disk +quota. A known transaction remains a mandatory manual acceptance step. + +[LIVE/FILE selection](traffic-capture.md) · [Packmate](packmate.md) diff --git a/docs/packmate.md b/docs/packmate.md new file mode 100644 index 0000000..5b08ae3 --- /dev/null +++ b/docs/packmate.md @@ -0,0 +1,69 @@ +# Packmate: inspect traffic + +English | [Русский](packmate-RU.md) + +Packmate displays requests/responses and searches stream contents. It helps defenders recognize attacks and check whether a patch changed the relevant behavior. DurkaHelper supplies its configuration and launch/import tools; upstream source remains unchanged. + +## UI services and patterns + +The web-interface port is chosen during deployment (`--ui-port` for SSH LIVE). +It is **not the monitored application's port**. The capture interface and +service-side IP belong in the private deployment configuration, not the service +creation form. The gear at the top right opens additional UI settings. + +1. Click **+** in the top navigation bar and enter the application's **Name** + and **Port**. Create an entry for each port. Unregistered services do not + have their streams saved. Ordinary HTTP does not need TLS decryption. +2. Select the service in the top bar. LIVE streams appear automatically; the + analysis-start button is only available in FILE mode. +3. For highlighting, open **Patterns → +**. Choose recognizable synthetic text, + such as `DEMO-`, substring search, both directions and **Highlight**, not + **Ignore**. Select a particular service if needed. +4. Open a new stream and verify its request and response. New patterns apply + to subsequent streams; **Lookback** applies them to saved streams. + **Pause** pauses your browser's display, not packet capture. + +These actions change Packmate's database settings, not the application or +network. For an empty UI, first check the registered port and clear any pattern +filter; then check the service-side IP and availability of authorized traffic. +The controls were reviewed against the [pinned upstream UI guide](https://gitlab.com/packmate/Packmate/-/blob/938031f1dedfbedabef5b049368ed5b6ba6a900a/docs/USAGE_EN.md). + +## FILE on the laptop + +```bash +python3 durka.py up +python3 durka.py traffic import /path/to/closed-capture.pcap +python3 durka.py status +``` + +Open the printed Packmate URL. Use `credentials.packmate_user / packmate_password` from the admin's private config. + +1. [Register the service and a search pattern in the UI](#ui-services-and-patterns). +2. Check `profile.packmate.local_ip`: it is the service-side IP **in the capture**, not the laptop's address. +3. Press the yellow downward-arrow FILE-processing button in the sidebar once + and find a known request and response in the correct direction. Do not look + for a literal "Start" label or an upload form: the import command already supplied the file. +4. For a new closed file, run the import command again; it restarts only Packmate and preserves its database/previous file. + +EOF does not reset upstream's started state. Do not replace the active file manually underneath a running parser. Imported traffic can contain passwords, cookies and flags; keep it out of public artifacts. + +Import does not change `local_ip`: it must match the actual service-side IP in +this PCAP, not an address copied from another demo. To change a FILE config after +setup, follow [down → edit → configure → up](MACOS_FIRST_RUN.md#6-failures-and-safe-shutdown), +then repeat the import and press the FILE-processing button. + +## LIVE on Linux + +LIVE needs permission and an observation point that actually sees the Vulnbox's packets: the Vulnbox itself or an approved Linux mirror/capture node. Docker Desktop's normal deployment is FILE-only. + +Choose and rehearse a [capture path](traffic-capture.md) before the game. An endless FILE pipe is not LIVE: incomplete-flow timeout/periodic cleanup are tied to upstream LIVE mode. A laptop on the same switch does not see all traffic automatically. + +## Resources and troubleshooting + +The current Packmate image is amd64-only; Apple Silicon uses emulation. Watch CPU, memory, database/capture growth and free disk. LIVE age cleanup is not a hard disk quota; FILE has no periodic LIVE cleanup. + +Empty UI: verify service registration, pattern, service-side IP, time range and a known capture. TCP/UDP direction and payload are better checks than a running container. + +The maintained configuration suppresses upstream's specific authentication-failure logger that otherwise prints attempted passwords. Use the generated config; do not run stock upstream logging with private credentials. + +[Traffic workflow](traffic-capture.md) · [Participant guide](participant-guide.md) · [Upstream setup](https://gitlab.com/packmate/Packmate/-/blob/938031f1dedfbedabef5b049368ed5b6ba6a900a/docs/SETUP.md) diff --git a/docs/participant-guide-RU.md b/docs/participant-guide-RU.md new file mode 100644 index 0000000..9b6441b --- /dev/null +++ b/docs/participant-guide-RU.md @@ -0,0 +1,47 @@ + +# Инструкция участника + +[English](participant-guide.md) | Русский + +Ферму устанавливать и конфиг админа заполнять не нужно. Получите у админа LAN URL/логины фермы и Packmate; авторам скриптов также нужны адрес/ключ координатора Neo. + + +## Защитить сервис + +1. Получите разрешённую локальную копию исходников сервиса Vulnbox. +2. Из каталога DurkaHelper запустите скан: + +```bash +python3 durka.py scan /path/to/service --patches +``` + +3. Откройте связанную [инструкцию исправления](vulnerabilities/README-RU.md), проверьте применимость сигнала и изучите нужные запрос/ответ в Packmate. +4. Сохраните оригинальные файлы/native database backup, нужные сервису. Примените один небольшой фикс обычным способом доступа/деплоя команды на Vulnbox. +5. Проверьте нормальное использование и checker соревнования, включая restart/сохранность данных, где нужно. Повторите скан исходников. + +Сканер делает offline source review: удалённые Vulnbox не прощупывает, их код не исполняет. Exit 1 — находки; exit 2 — некорректный/неполный вход, который нужно проверить. Чистый отчёт не заменяет доступность и ручную проверку авторизации/бизнес-логики. + + +## Разобрать трафик + +Откройте LAN URL Packmate и войдите. Выберите свой сервис, ищите подозрительное значение/путь и изучайте запрос вместе с ответом. Для FILE попросите админа зарегистрировать сервис/шаблон до начала обработки. + +Если трафика нет, проверьте timestamps потоков, IP стороны сервиса и порт/шаблон и то, импортировал ли админ закрытый файл или выбрал разрешённый LIVE-источник. Не предполагается наличие фильтра времени в UI. Один Ethernet на Mac не захватывает всю LAN автоматически. [Работа с трафиком](traffic-capture-RU.md). + + +## Написать и распределить скрипты + +Neo — исполнитель/распределитель скриптов. Ферма собирает полученные флаги. Начните с локального теста на разрешённой цели и явно определите зависимости. + +Скрипт получает IP цели первым аргументом; флаги печатает в stdout без буферизации. Диагностику отделяйте от флагов. Shebang должен указывать интерпретатор, доступный у каждого worker. Встроенный light-worker содержит shell, а не Python/Sage и произвольные пакеты. + +[Настройка Neo и первое задание](neo-RU.md) описывает совместимый клиент. Сначала зарегистрируйте доверенный скрипт выключенным, затем запросите единичный прогон до периодического исполнения. `single` Neo запускает один раз на **всех настроенных командах**, поэтому сверьте scope/список с админом. + +Следите за исполнением и флагами/статусом в ферме. Ферма/Neo не являются автоматическим установщиком защитных патчей. + + +## Если нет доступа + +Используйте LAN-адрес админа, а не `localhost`. Если ошибка только у вас — URL/порт, credentials и версия Neo. Если у всех — админ проверяет `python3 durka.py status` и LAN bind. + +Не показывайте приватные исходники, credentials, флаги и трафик в общей трансляции. [Шпаргалка защитника](defense-cheatsheet-RU.md) · [Связи инструментов](team-setup-RU.md). diff --git a/docs/participant-guide.md b/docs/participant-guide.md new file mode 100644 index 0000000..b865d3d --- /dev/null +++ b/docs/participant-guide.md @@ -0,0 +1,42 @@ +# Participant guide + +English | [Русский](participant-guide-RU.md) + +You do not need to install the farm or fill the administrator's config. Ask the admin for the farm/Packmate LAN URLs and logins; script writers also need the Neo coordinator address/key. + +## Defend a service + +1. Obtain an authorized local source copy of your Vulnbox service. +2. From the DurkaHelper checkout, scan it: + +```bash +python3 durka.py scan /path/to/service --patches +``` + +3. Open the linked [fix recipe](vulnerabilities/README.md), check whether the signal applies and inspect the relevant request/response in Packmate. +4. Save the original files/native database backup needed by that service. Apply one small fix through the team's normal Vulnbox access/deployment procedure. +5. Check legitimate use and the competition checker, including restart/data persistence where relevant. Repeat the source scan. + +The scanner is offline source review: it neither probes remote Vulnboxes nor executes their code. Exit 1 means findings; exit 2 means invalid/partial input needing attention. A clean report does not replace an availability check or manual authorization/business-logic review. + +## Inspect traffic + +Open Packmate's LAN URL and log in. Select your service, search a suspicious value/path and examine both request and response. Ask the admin to register the service/pattern before FILE processing. + +If traffic is missing, check stream timestamps, service-side IP and port/pattern and whether the admin has imported a closed file or chosen a permitted LIVE source. Do not assume a time-filter UI exists. A Mac connected to Ethernet does not capture the whole LAN automatically. [Traffic guide](traffic-capture.md). + +## Write and distribute scripts + +Neo is the script runner/distributor. The farm collects the resulting flags. Start with a local test against an allowed target and make dependencies explicit. + +The script receives the target IP as its first command-line argument; print flags to stdout without buffering. Keep diagnostics distinct from flags. Include a shebang for the interpreter available on each worker. The bundled light worker has a shell, not Python/Sage and arbitrary packages. + +Follow [Neo setup and first task](neo.md) to configure a compatible client. Register a trusted script disabled first, then request a single run before enabling recurring execution. Neo's `single` runs once on **all configured teams**, so check the team map/scope with the admin. + +Watch execution output and the flags/status in the farm. Do not use the farm/Neo as an automatic defensive patch installer. + +## If access fails + +Use the admin's LAN address, not `localhost`. If only your device fails, compare URL/port, credentials and Neo version. If everyone fails, ask the admin to check `python3 durka.py status` and the LAN bind. + +Keep private source, credentials, flags and traffic out of shared screen broadcasts. [Defender cheat sheet](defense-cheatsheet.md) · [Tool connections](team-setup.md). diff --git a/docs/patch-validation-RU.md b/docs/patch-validation-RU.md new file mode 100644 index 0000000..0588485 --- /dev/null +++ b/docs/patch-validation-RU.md @@ -0,0 +1,89 @@ + +# Проверка патчей, deployment и rollback + +[English](patch-validation.md) | Русский + +[Шпаргалка защитника](defense-cheatsheet-RU.md) · [Каталог](vulnerabilities/README-RU.md) + +За deployment каждого сервиса отвечает один человек. Все начальные проверки выполняются на изолированной локальной копии разрешённого сервиса. Адаптируйте production-команды только после подтверждения его фактического контракта запуска и данных. Обычный ручной маршрут: сохранить оригиналы, применить небольшой патч, прогнать regression/normal-user/checker проверки и повторить скан. Карточки и ручное переписывание hashes не нужны; раздел 4 — необязательная расширенная проверка evidence, не условие ручного исправления. + + +## 1. Сохраните исходное состояние + +Запишите ревизию кода и локальный diff, неизменяемый image ID, источники конфигурации, текущие данные и способ rollback. Это разные активы: откат кода не должен восстанавливать старую БД поверх записей новых раундов. + +Свидетельство: `REVIEWED`; эффект `READ-ONLY`; рабочий каталог — checkout сервиса с Git. Ожидается: фактическая ревизия и существующие изменения. Вывод может содержать приватные пути; не транслируйте его. Rollback: не нужен. + +```bash +git status --short +git rev-parse HEAD +git diff --check +``` + +Без Git приватно скопируйте только изменяемые файлы подходящими backup tools; проверка checksum может быть автоматической. Никогда не используйте общий git add, reset --hard или git clean как универсальный рабочий процесс. [Файловый backup](local-tools-RU.md#backup-and-staging-restore) ограничен, но базы данных требуют нативных консистентных dumps или проверенной процедуры копирования в остановленном состоянии. + + +## 2. Обязательная матрица поведения + +| Проверка | Успешный результат | +|---|---| +| Регрессия дефекта | Один и тот же тест безопасного поведения падает до и проходит после | +| Обычный пользователь | Работают login, create/read/update и ожидаемый sharing | +| Авторизация | Владелец проходит; другой пользователь/tenant и анонимный caller получают отказ без side effects | +| Старые данные | Записи до патча сохраняют формат и доступность | +| Persistence | Новые записи переживают согласованный изолированный restart | +| Альтернативные пути | Lists, exports, files, jobs и затронутые routes соблюдают то же правило | +| Границы ввода | Empty/wrong-type/Unicode/maximum values соответствуют контракту | +| Отказ зависимости | Ограниченный, очищенный отказ без авторизации по умолчанию | +| Checker | Сохраняются настоящая семантика турнира и SLA | + +Проверяйте отсутствие запрещённых эффектов, а не только status codes: denied reads не содержат чужого body, denied writes оставляют rows неизменными, blocked URLs никогда не вызывают HTTP client. [PY-SQL](vulnerabilities/python-RU.md#py-sql) содержит небольшой пример приватной заметки; проверяйте интеграцию route/session вместе с helper. + + +## 3. Учитывайте механизм deployment + +| Механизм | Необходимое действие / ловушка | +|---|---| +| Source bind mount | Обновляйте только проверенные файлы; restart нужен только если его требует процесс | +| Код скопирован в image | Соберите новый закреплённый image и пересоздайте собственный сервис; один restart не пересобирает image | +| Native binary | Проверьте architecture/libraries/permissions и совместимость данных | +| API и workers | Согласованно обновите зависимые процессы; старые workers могут сохранить старое поведение | + +Изучите entrypoints на предмет destructive initialization/migrations и найдите persistent data. Не перенастраивайте игровые сети, не удаляйте volumes и не пересобирайте посторонние компоненты ради source patch. + +До production-одобрения отрепетируйте точную rollback-команду на копии. Она должна восстанавливать code/image с сохранением текущих данных. Держите старый image локально; изменяемый тег latest не является целью rollback. + + +## 4. Привяжите свидетельства к этому патчу + +Соберите before/after snapshots и scans с одним предполагаемым scope, затем health и фактические regression-test records. Результат из другого прогона не подтверждает статус этого патча. + +[Schema validation-record](../schemas/validation-record.v1.schema.json) использует lowercase statuses. Attributes каждой записи должны содержать точный SHA-256 входов before_snapshot, after_snapshot, before_scanner, after_scanner и health под соответствующими ключами *_sha256, а также один общий run_id. Время записи должно быть позже зависимых evidence. + +Если deployment audit обязателен, включите его audit/model/policy hashes в ту же запись. Аудит пересчитывается по model/policy; его source hash должен соответствовать точной runtime configuration, зафиксированной в after-snapshot. Он проверяет заявленную конфигурацию, а не фактическое состояние работающего daemon. + +Свидетельство: `REVIEWED`; эффект `READ-ONLY`; рабочий каталог — корень. Требования: подлинные приватные evidence по примерным путям, актуальные hashes/timestamps и совпадающий scope. Ожидается: 0/pass, 1/regression или 2/incomplete. Никогда не придумывайте pass records только ради выполнения условия приёмки. Rollback: не нужен. + +```bash +python3 scripts/defense_ops.py patch-check \ + --before ../private-results/before.json --after ../private-results/after.json \ + --before-scanner ../private-results/before-scan.json \ + --after-scanner ../private-results/after-scan.json \ + --health-result ../private-results/health.json \ + --validation-record ../private-results/regression.json \ + --deployment-audit ../private-results/deployment-audit.json \ + --deployment-model ../private-deployment/run-01/runtime-model.json \ + --deployment-policy ../private-deployment/run-01/runtime-policy.json \ + --require-deployment-audit +``` + +Для изменений только исходников без deployment audit явно уберите все четыре deployment arguments. Обязательные health/scanner/validation evidence всё равно нужны. Отсутствующие, устаревшие, partial, not-run, несовпадающие или несопоставимые свидетельства не могут дать clean pass. + +Для ожидаемого drift требуется явно проверенная [approved-drift record](../schemas/approved-drift.v1.schema.json), привязанная к обоим snapshot hashes и точным классифицированным изменениям; передайте её через --approved-drift. Общее wildcard-разрешение не поддерживается. + + +## 5. Примените, наблюдайте, при необходимости откатите + +После явного разрешения используйте только отрепетированный путь deployment собственного сервиса. Сразу повторите health, фактические операции пользователей/checker и чтение старых данных, затем наблюдайте полный релевантный интервал раунда. При сбое сохраните очищенную incident timeline. + +Сначала откатите code/image по записанному плану. Восстановление данных — отдельное решение с серьёзными последствиями: старый dump может стереть данные нового раунда. Не меняйте попутно ключи, schemas или runtime. diff --git a/docs/patch-validation.md b/docs/patch-validation.md new file mode 100644 index 0000000..f68e38a --- /dev/null +++ b/docs/patch-validation.md @@ -0,0 +1,83 @@ +# Patch verification, deployment and rollback + +English | [Русский](patch-validation-RU.md) + +[Defender quick sheet](defense-cheatsheet.md) · [Catalog](vulnerabilities/README.md) + +One person owns deployment for each service. All initial checks use an isolated local copy of an authorized service. Adapt production commands only after confirming its actual startup/data contract. For the ordinary manual route: preserve originals, apply one small patch, run regression/normal-user/checker tests and scan again. No cards or manually transcribed hashes are required; section 4 is an optional advanced automated evidence gate, not a prerequisite for manual patching. + +## 1. Preserve the before-state + +Record code revision/local diff, immutable image ID, configuration sources, current data and rollback method. These are different assets: reverting code must not restore an old database over new-round records. + +Evidence: `REVIEWED`; effect `READ-ONLY`; cwd service checkout with Git. Expected: actual revision and existing modifications. Output may contain private paths; do not broadcast it. Rollback: none. + +```bash +git status --short +git rev-parse HEAD +git diff --check +``` + +Without Git, privately copy only the files being changed with suitable backup tools; checksum verification can be automatic. Never use broad git add, reset --hard or git clean as a generic workflow. [File backup](local-tools.md#backup-and-staging-restore) is bounded, but databases require native consistent dumps or a verified stopped-copy procedure. + +## 2. Required behavioral matrix + +| Check | Passing result | +|---|---| +| Defect regression | The same safe-behavior test fails before and passes after | +| Normal user | Login, create/read/update and expected sharing work | +| Authorization | Owner succeeds; another user/tenant and anonymous caller fail without side effects | +| Old data | Pre-patch records retain their format and accessibility | +| Persistence | New records survive an approved isolated restart | +| Alternative paths | Lists, exports, files, jobs and affected routes enforce the same rule | +| Input boundaries | Empty/wrong-type/Unicode/maximum values follow the contract | +| Dependency failure | Bounded, sanitized failure without default authorization | +| Checker | Actual tournament semantics and SLA remain satisfied | + +Check absence of forbidden effects, not only status codes: denied reads contain no foreign body, denied writes leave rows unchanged and blocked URLs never call the HTTP client. [PY-SQL](vulnerabilities/python.md#py-sql) provides a small private-note example; test route/session integration as well as its helper. + +## 3. Match the deployment mechanism + +| Mechanism | Required action / pitfall | +|---|---| +| Source bind mount | Update only reviewed files; restart only if the process needs it | +| Code copied into an image | Build a new pinned image and recreate the owned service; restart alone does not rebuild | +| Native binary | Verify architecture/libraries/permissions and data compatibility | +| API plus workers | Update dependent processes consistently; old workers may retain old behavior | + +Inspect entrypoints for destructive initialization/migrations and locate persistent data. Do not reconfigure game networks, remove volumes or rebuild unrelated components to apply a source patch. + +Before production approval, rehearse the exact rollback command on a copy. It must restore code/image while preserving current data. Keep the old image locally; a mutable latest tag is not a rollback target. + +## 4. Bound evidence to this patch + +Collect before/after snapshots and scans with the same intended scope, followed by health and actual regression-test records. A result reused from another run cannot establish this patch's status. + +The [validation-record schema](../schemas/validation-record.v1.schema.json) uses lowercase statuses. Each record's attributes must contain the exact SHA-256 of before_snapshot, after_snapshot, before_scanner, after_scanner and health inputs under their corresponding *_sha256 keys, plus one common run_id. Record time must follow the dependent evidence. + +If deployment audit is required, include its audit/model/policy hashes in the same record. The audit is recomputed from model/policy; its source hash must correspond to the exact runtime configuration captured in the after-snapshot. It checks declared configuration, not running-daemon truth. + +Evidence: `REVIEWED`; effect `READ-ONLY`; cwd root. Prerequisites: genuine private evidence at the example paths, current hashes/timestamps and matching scope. Expected: 0/pass, 1/regression or 2/incomplete. Never fabricate pass records merely to satisfy this gate. Rollback: none. + +```bash +python3 scripts/defense_ops.py patch-check \ + --before ../private-results/before.json --after ../private-results/after.json \ + --before-scanner ../private-results/before-scan.json \ + --after-scanner ../private-results/after-scan.json \ + --health-result ../private-results/health.json \ + --validation-record ../private-results/regression.json \ + --deployment-audit ../private-results/deployment-audit.json \ + --deployment-model ../private-deployment/run-01/runtime-model.json \ + --deployment-policy ../private-deployment/run-01/runtime-policy.json \ + --require-deployment-audit +``` + +For source-only changes without deployment audit, omit all four deployment arguments explicitly. Required health/scanner/validation evidence still applies. Missing, stale, partial, not-run, mismatched or incomparable evidence cannot yield a clean pass. + +Expected drift needs an explicitly reviewed [approved-drift record](../schemas/approved-drift.v1.schema.json), bound to both snapshot hashes and the exact categorized changes; pass it with --approved-drift. A broad wildcard approval is not supported. + +## 5. Apply, observe, revert if necessary + +After explicit approval, use only the rehearsed owned-service deployment path. Immediately repeat health, actual user/checker operations and old-data reads, then monitor a full relevant round window. Preserve a sanitized incident timeline if failure occurs. + +Rollback code/image first according to the recorded plan. Data restoration is a separate high-impact decision: an old dump may erase new-round data. Do not rotate keys, migrate schemas or replace runtimes as incidental fixes. diff --git a/docs/release-checklist-RU.md b/docs/release-checklist-RU.md new file mode 100644 index 0000000..9689158 --- /dev/null +++ b/docs/release-checklist-RU.md @@ -0,0 +1,61 @@ + +# Чеклист релиза и публикации + +[English](release-checklist.md) | Русский + +Чеклист сопровождающего, а не форма оператора. Для развёртывания используйте [инструкцию Mac](MACOS_FULL_DEPLOYMENT_AND_TESTING-RU.md). Готовность к публикации и к соревнованию учитываются отдельно. + + +## Исходники и тесты + +- [ ] Одобренный source commit и чистое tracked tree; без посторонних изменений. +- [ ] Полный unit suite и coverage ledger проходят, включая docs links/anchors, английский текст и соответствие парных русских переводов; команды и примеры остаются идентичными. +- [ ] Новые и изменённые правила соответствуют независимому positive/negative coverage языков. +- [ ] Точно распакованный core bundle проходит; archive manifest/checksums проверены. +- [ ] Внешние kits проходят строгий verifier; частичный экспорт образов не выдаётся за полный toolchain. Релиз только core не заявляет наличие сторонних runtimes. +- [ ] Результаты Linux integration и macOS ARM64 CI относятся к явно указанным commits. +- [ ] Заявленная поддержка соответствует текущей странице возможностей; generated outputs остаются вне Git. + + +## Безопасность публикации + +Запускайте из корня репозитория. Эти read-only проверки показывают категории и расположения, а не найденные значения секретов. + +```bash +python3 scripts/publication_check.py --root . --allowlist config/publication-allowlist.json +python3 scripts/publication_check.py --root . --history --ref HEAD \ + --allowlist config/publication-allowlist.json +``` + +- [ ] Проверьте каждый ref, предназначенный для публикации, а не только HEAD; checker принимает повторяющиеся явные --ref arguments. +- [ ] При необходимости используйте игнорируемый приватный denylist для строк локальных endpoints/identities; никогда не коммитьте его. +- [ ] Отдельно проверьте candidate archives, screenshots, CI artifacts и PR material. Проверка текста/истории не является OCR скриншотов и не доказывает безопасность удалённых артефактов. +- [ ] Нет keys/tokens, заполненных profiles, raw logs/PCAP, игровых данных, личных путей или описания частного deployment оператора. +- [ ] Синтетические исключения точны, узки и обоснованы; никогда не исключайте целиком tests/docs. +- [ ] Сохраняйте законное авторство, citations и license attribution. +- [ ] Подтвердите работающий приватный канал сообщений об уязвимостях согласно [SECURITY](../SECURITY-RU.md). +- [ ] Правомерность распространения сторонних binaries/images проверена; иначе распространяйте только core. +- [ ] Заявления version/changelog/support соответствуют точному релизу. + +Изменение видимости репозитория, удаление refs, переписывание истории или публикация сторонних артефактов — отдельные осознанные действия. Не автоматизируйте их как косметическую уборку. + + +## Релиз-кандидат и публичный доступ + +`RELEASE_CANDIDATE_READY` означает фиксированный source commit и core-архив, прошедшие применимые релизные проверки, с указанными оставшимися platform/event gates. Это не означает публичность репозитория или сертификацию игровой среды. + +`PUBLIC_RELEASE_VERIFIED` дополнительно требует явного разрешения владельца на публикацию и успешного анонимного доступа к выбранному репозиторию, README, workflow оператора и скачиванию исходников. До разрешения проверьте все открываемые ветки/историю, PR material и CI assets; сохраните законную историю и тестовые fixtures. Нельзя молча удалять исторические материалы или переписывать commits ради зелёной проверки. + +Если правила соревнования требуют публичность, это обязательное условие до игры. Приватный release candidate его не закрывает. [Workflow администратора](ADMIN_WORKFLOWS-RU.md) — рабочий маршрут; локальные результаты проверок остаются приватными. + + +## Условия готовности к соревнованию + +- [ ] Проверены архитектура реального целевого Mac, точные версии OS/Desktop и ресурсный бюджет. +- [ ] Отрепетированы functional paths farm/coordinator/worker/Packmate и native recovery. +- [ ] Нет нерешённого P0 failure, partial result или непринятого blocker. +- [ ] Полный offline cold start проходит без скрытых downloads. +- [ ] Каждое физическое устройство teammate проходит полезные сценарии с аутентификацией и reconnect. +- [ ] Разрешённый непрерывный capture видит известный двусторонний трафик при ограниченном storage. +- [ ] Не менее 60 минут совместной нагрузки toolchain; в источнике захвата нет секретов. +- [ ] Новый оператор может пройти английское руководство без AI. diff --git a/docs/release-checklist.md b/docs/release-checklist.md new file mode 100644 index 0000000..9ef0c9f --- /dev/null +++ b/docs/release-checklist.md @@ -0,0 +1,56 @@ +# Release and publication checklist + +English | [Русский](release-checklist-RU.md) + +Maintainer checklist, not an operator form. For deployment use the [Mac guide](MACOS_FULL_DEPLOYMENT_AND_TESTING.md). Publication readiness and competition readiness are separate. + +## Source and tests + +- [ ] Approved source commit and clean tracked tree; no unrelated changes. +- [ ] Full unit suite and coverage ledger pass, including English prose, paired Russian translations, identical code examples and links/anchors in both languages. +- [ ] New/changed rules meet independent positive/negative language coverage. +- [ ] Exact extracted core bundle passes; archive manifest/checksums verified. +- [ ] External kits pass the strict verifier; partial image exports are not advertised as a complete toolchain. A core-only release does not claim to contain third-party runtimes. +- [ ] Linux integration results and macOS ARM64 CI refer to explicit commits. +- [ ] Support claims match the current capability page; generated run outputs remain outside Git. + +## Publication safety + +Run from the repository root. These read-only checks report categories and locations, not matched secret values. + +```bash +python3 scripts/publication_check.py --root . --allowlist config/publication-allowlist.json +python3 scripts/publication_check.py --root . --history --ref HEAD \ + --allowlist config/publication-allowlist.json +``` + +- [ ] Inspect every ref intended for publication, not only HEAD; the checker accepts repeated explicit --ref arguments. +- [ ] Use an ignored private denylist for local endpoint/identity strings when appropriate; never commit it. +- [ ] Review candidate archives, screenshots, CI artifacts and PR material separately. Text/history checking is not screenshot OCR or a proof that remote artifacts are safe. +- [ ] No keys/tokens, populated profiles, raw logs/PCAP, game data, personal paths or operator-specific deployment narrative. +- [ ] Synthetic exceptions are exact, narrow and justified; never broadly exempt tests/docs. +- [ ] Preserve legitimate authorship, citations and license attribution. +- [ ] Confirm a working private vulnerability-reporting channel as required by [SECURITY](../SECURITY.md). +- [ ] Third-party binary/image redistribution is reviewed; otherwise distribute core only. +- [ ] Version/changelog/support claims match the exact release. + +Changing repository visibility, deleting refs, rewriting history or publishing third-party artifacts are separate deliberate actions. Do not automate them as a cosmetic cleanup. + +## Release candidate and public access + +`RELEASE_CANDIDATE_READY` means a fixed source commit and its core archive passed the applicable release checks, with remaining platform/event gates disclosed. It does not mean the repository is public or the competition environment is certified. + +`PUBLIC_RELEASE_VERIFIED` additionally requires the owner's explicit publication approval and successful anonymous access to the intended repository, README, operator workflows and source download. Review all exposed branches/history, PR material and CI assets before that approval; retain legitimate history and test fixtures. Never silently delete historical material or rewrite commits to make a check green. + +Public availability is a pre-event gate wherever required by the competition rules. A private release candidate does not satisfy that requirement. The [administrator workflows](ADMIN_WORKFLOWS.md) are the operational route; local validation outputs remain private. + +## Competition gate + +- [ ] Actual target-Mac architecture, exact OS/Desktop version and resource budget verified. +- [ ] Farm/coordinator/worker/Packmate functional paths and native recovery rehearsed. +- [ ] No unresolved P0 failure, partial result or unaccepted blocker. +- [ ] Full offline cold start succeeds without hidden downloads. +- [ ] Every physical teammate device passes authenticated useful scenarios and reconnect. +- [ ] Approved continuous capture sees known bidirectional traffic with bounded storage. +- [ ] At least 60 minutes of combined toolchain load; no secret-bearing capture source. +- [ ] A new operator can follow the English or Russian guide without AI; both routes remain complete. diff --git a/docs/s4dfarm-RU.md b/docs/s4dfarm-RU.md new file mode 100644 index 0000000..d298081 --- /dev/null +++ b/docs/s4dfarm-RU.md @@ -0,0 +1,36 @@ + +# S4DFarm: флаги и отправка + +[English](s4dfarm.md) | Русский + +S4DFarm собирает флаги команды, ставит их в очередь отправки и показывает accepted/rejected/expired. Neo автоматически передаёт найденные флаги. **Патчи сервисов ферма не распространяет.** + + +## Запуск через DurkaHelper + +```bash +python3 durka.py up +python3 durka.py status +``` + +Откройте URL фермы; пароль — `credentials.farm_password` в приватном `local/durka.json`. Передайте участникам LAN URL/пароль, а не конфигурацию PostgreSQL/Redis. + + +## Настроить соревнование + +В `local/durka.json` задайте реальные команды, regex флага, лимиты/время отправки и URL/token в `profile.farm.protocol_settings`. Kit поддерживает `ructf_http`; отсутствующий upstream default adapter не используется. + +Отправка изначально выключена. После проверки соответствия receiver соревнованию: + +```bash +python3 durka.py submit +``` + +Смотрите конечный статус легитимного флага. Работающий UI, очередь или успешный вход Neo ещё не доказывают принятие. Если очередь стоит: отправка включена, адаптер/token, expiry и ответы receiver. + + +## Изменить конфиг или восстановить + +Настройки площадки: остановить, отредактировать приватный конфиг, выполнить `python3 durka.py configure`, затем запустить. Не переотправляйте старые/просроченные очереди после recovery. [Native recovery](../deployment/README-RU.md#native-backup-and-quarantine-restore) восстанавливает в новое хранилище и намеренно очищает Redis кандидата. + +Точные версии — в [toolchain lock](../config/toolchain.lock.json); подготовка DurkaHelper использует их автоматически. [Установка админа](MACOS_FULL_DEPLOYMENT_AND_TESTING-RU.md) · [Neo](neo-RU.md) · [Upstream](https://github.com/C4T-BuT-S4D/S4DFarm) diff --git a/docs/s4dfarm.md b/docs/s4dfarm.md new file mode 100644 index 0000000..326e46c --- /dev/null +++ b/docs/s4dfarm.md @@ -0,0 +1,32 @@ +# S4DFarm: flags and submission + +English | [Русский](s4dfarm-RU.md) + +S4DFarm collects flags from the team, queues them for submission and shows accepted/rejected/expired results. Neo sends discovered flags to it automatically. **It does not distribute service patches.** + +## Start through DurkaHelper + +```bash +python3 durka.py up +python3 durka.py status +``` + +Open the printed farm URL; the password is `credentials.farm_password` in private `local/durka.json`. Give teammates that LAN URL/password, not the PostgreSQL/Redis configuration. + +## Configure the competition + +In `local/durka.json`, set the actual team map, flag regex, submit limits/timing and `profile.farm.protocol_settings` URL/token. The kit currently supports `ructf_http`; the upstream's absent default adapter is not used. + +Submission starts disabled. After checking that the receiver matches the competition: + +```bash +python3 durka.py submit +``` + +Watch a legitimate flag's final status. A running UI, queue entry or successful Neo login does not prove submission acceptance. If queues stall, check submission enabled, adapter/token, expiry and receiver responses. + +## Change configuration or recover + +For event settings: stop, edit the private config, run `python3 durka.py configure`, then start. Keep old/expired recovered queues from replaying. The [native recovery procedure](../deployment/README.md#native-backup-and-quarantine-restore) restores into new storage and deliberately clears candidate Redis state. + +Exact upstream versions live in the [toolchain lock](../config/toolchain.lock.json); DurkaHelper preparation handles them. [Admin setup](MACOS_FULL_DEPLOYMENT_AND_TESTING.md) · [Neo](neo.md) · [Upstream](https://github.com/C4T-BuT-S4D/S4DFarm) diff --git a/docs/team-setup-RU.md b/docs/team-setup-RU.md new file mode 100644 index 0000000..2f155d5 --- /dev/null +++ b/docs/team-setup-RU.md @@ -0,0 +1,39 @@ + +# Как связаны командные инструменты + +[English](team-setup.md) | Русский + +Один администратор поднимает общий стек. Участники открывают его LAN-интерфейсы и подключают клиенты Neo. Защищаемые сервисы остаются на Vulnbox. + +```text +Teammates ──Ethernet──> Farm UI/API ──> competition flag receiver + ├───────────> Neo coordinator ──> workers ──> permitted targets + └───────────> Packmate UI +Vulnbox traffic ──> approved Linux LIVE, or closed PCAP ──> Packmate FILE +Service source copy ──> DurkaHelper scan ──> reviewed patch ──> Vulnbox +``` + + +## Кто за что отвечает + +Админ отвечает за общий конфиг, запуск, учётные данные, отправку и backups. Защитники — за review, патчи и regression-тесты сервиса. Авторы — за свои скрипты/зависимости и результаты в ферме. Workers Neo выполняют доверенный командный код. + +Ферма отправляет **флаги**, Neo распределяет **скрипты**. Патчи сервисов они автоматически не развёртывают. Используйте обычный доступ/деплой Vulnbox вашей команды. + +Автор загружает скрипт в общий координатор Neo; подготовленный worker исполняет его и передаёт подходящие результаты stdout прямо в ферму. Несколько авторов могут пользоваться одним worker: каждому запускать свой не обязательно. См. [workflow клиентов/workers и примеры разового запуска и расписания](neo-RU.md#team-workflow-clients-coordinator-and-workers). Отправка из фермы включается отдельно; попадание в очередь ещё не подтверждает приём жюрейкой. + + +## Адреса + +Используйте Ethernet IPv4 админа и порты из `python3 durka.py status`. По умолчанию: ферма 8080, Neo 5005, Packmate 65000. Участникам не нужны `localhost`, Docker DNS и `host.docker.internal`. + +Database, Redis и Docker остаются приватными. Клиентам/workers Neo нужен доступ к координатору и ферме; workers также нужны разрешённые маршруты до целей. Используйте только разрешённые площадкой порты и доступ. + + +## Первая проверка + +Дома проверьте машину админа и отдельный ПК. На площадке каждый участник должен войти, выполнить полезное действие и переподключиться. Ethernet link или открытого TCP-порта недостаточно. + +Ноутбук не видит автоматически весь трафик коммутируемой LAN. Выберите [разрешённый LIVE или импорт PCAP](traffic-capture-RU.md). + +[Установка админа](MACOS_FULL_DEPLOYMENT_AND_TESTING-RU.md) · [Шпаргалка админа](TEAM_LAN_ADMIN_CHEATSHEET-RU.md) · [Инструкция участника](participant-guide-RU.md) diff --git a/docs/team-setup.md b/docs/team-setup.md new file mode 100644 index 0000000..7344762 --- /dev/null +++ b/docs/team-setup.md @@ -0,0 +1,35 @@ +# How the team's tools connect + +English | [Русский](team-setup-RU.md) + +One administrator hosts the shared stack. Teammates open its LAN UIs and connect Neo clients. Protected services remain on the Vulnbox. + +```text +Teammates ──Ethernet──> Farm UI/API ──> competition flag receiver + ├───────────> Neo coordinator ──> workers ──> permitted targets + └───────────> Packmate UI +Vulnbox traffic ──> approved Linux LIVE, or closed PCAP ──> Packmate FILE +Service source copy ──> DurkaHelper scan ──> reviewed patch ──> Vulnbox +``` + +## Who owns what + +The admin owns shared configuration, startup, credentials, submission and backups. Defenders own review, patches and service regression tests. Script authors own their scripts/dependencies and confirm results in the farm. Neo workers execute trusted team code. + +The farm submits **flags**; Neo distributes **scripts**. Neither automatically deploys service patches. Use the team's existing Vulnbox access/deployment procedure. + +An author uploads to the shared Neo coordinator; a prepared worker executes the script and sends matching stdout results directly to the farm. Authors can share one worker and need not run one each. See the [client/worker workflow and one-shot/scheduled examples](neo.md#team-workflow-clients-coordinator-and-workers). The farm's submission process is enabled separately; queue ingestion is not jury acceptance. + +## Addresses + +Use the admin's Ethernet IPv4 and the ports printed by `python3 durka.py status`. Defaults: farm 8080, Neo 5005, Packmate 65000. Teammates do not use `localhost`, Docker service names or `host.docker.internal`. + +Database, Redis and Docker endpoints stay private. Neo clients/workers need access to both coordinator and farm; workers additionally need allowed routes to targets. Use only ports and access permitted by the event. + +## First check + +At home, test the admin machine and a separate PC. At the venue, have each teammate log in, perform a useful action and reconnect. A connected Ethernet link or open TCP port alone is not enough. + +The laptop does not automatically see all traffic on a switched LAN. Choose [approved LIVE or PCAP import](traffic-capture.md). + +[Administrator setup](MACOS_FULL_DEPLOYMENT_AND_TESTING.md) · [Admin cheat sheet](TEAM_LAN_ADMIN_CHEATSHEET.md) · [Participant guide](participant-guide.md) diff --git a/docs/traffic-capture-RU.md b/docs/traffic-capture-RU.md new file mode 100644 index 0000000..b79866b --- /dev/null +++ b/docs/traffic-capture-RU.md @@ -0,0 +1,129 @@ + +# Трафик: LIVE или импорт PCAP + +[English](traffic-capture.md) | Русский + +Подготовьте оба пути до соревнования. На месте выберите разрешённый организаторами; обычный FILE import не требует изменения кода. + + +## Выбрать вариант + +| Что доступно | Использовать | +|---|---| +| Разрешено запустить capture на Vulnbox/native Linux и виден трафик его интерфейса | Packmate LIVE на этом Linux-узле | +| Предоставлен разрешённый Linux mirror/capture интерфейс | Packmate LIVE там; зеркало дают организаторы | +| Только закрытые PCAP или разрешённый SSH/tcpdump | Передать закрытые файлы и использовать Packmate FILE на ноутбуке | +| Разрешённого источника нет | Продолжить разбор исходников; анализ трафика недоступен | + +Mac на том же Ethernet switch не видит автоматически пакеты Vulnbox. Поддерживаемый маршрут Docker Desktop — только FILE. Бесконечный FILE pipe не заменяет LIVE: upstream привязывает timeout незавершённых потоков и periodic cleanup к LIVE. + + +## FILE на ноутбуке + +Поднимите стек, получите **закрытый** capture и импортируйте: + +```bash +python3 durka.py up +python3 durka.py traffic import /path/to/closed-capture.pcap +python3 durka.py status +``` + +Команда сама проверяет файл, сохраняет предыдущий capture и перезапускает только Packmate. БД и другие инструменты продолжают работать. Ручные SHA/карточки не нужны. + +В Packmate зарегистрируйте сервис/шаблон, проверьте IP стороны сервиса в конфиге и один раз нажмите жёлтую кнопку разбора FILE со стрелкой вниз в боковой панели. Найдите известные запрос/ответ. Подробности и отличие от загрузки файла — в [инструкции UI](packmate-RU.md#file-on-the-laptop). Каждый новый файл — той же import-командой и кнопкой разбора. EOF не сбрасывает upstream parser; не копируйте новый capture поверх активного FILE. + +Передача на носителе тоже подходит. Captures приватные: внутри могут быть cookies, учётные данные и флаги. + + +## Получить закрытый файл на Linux + +Лучше использовать файлы организаторов. Если capture разрешён и `tcpdump`/`timeout` уже установлены, запускайте в приватном каталоге источника. Замените все placeholders разрешённым интерфейсом/сервисом/портами и **новым** именем файла: + +```bash +umask 077 +timeout --signal=INT 60 tcpdump -i -p -nn -s 65535 \ + -c 1000 -w .pcap \ + 'host and (tcp port or udp port )' +``` + +Дождитесь завершения процесса до передачи. Это до 60 секунд или 1 000 пакетов, примерно 66 MB плюс overhead формата. Код `timeout` 124 может быть ожидаемым; другие ошибки захвата нужно проверить. Рецепт основан на [tcpdump manual](https://github.com/the-tcpdump-group/tcpdump/blob/master/tcpdump.1.in); это проверенная по инструкции процедура, а не тест интерфейса вашей площадки. + +При существующем разрешённом SSH identity и доверенном host key: + +```bash +scp -o StrictHostKeyChecking=yes -P \ + @: ./incoming-01.pcap +python3 durka.py traffic import ./incoming-01.pcap +``` + +Эти две команды запускаются на ноутбуке из корня репозитория. Сохраните source до успешного импорта/использования. Файл, в который ещё идёт запись, не передавайте. + + +## Host-interface LIVE + +Для обычного запуска с ноутбука используйте [SSH deployment с doctor и офлайн-образами](packmate-remote-RU.md). +Python на Vulnbox не требуется. Ниже — низкоуровневый Linux helper для расширенных ручных процедур. + +Это ветка Linux-админа, отдельная от Docker Desktop. Требуются native Linux amd64, стандартный локальный rootful Docker Engine, кешированные закреплённые образы Packmate/PostgreSQL и разрешение на **весь выбранный интерфейс**. Закреплённый upstream при запуске кратко применяет широкий TCP/UDP filter. + +Launcher использует host networking и NET_RAW; не privileged и не NET_ADMIN. БД остаётся на IPv4 loopback; firewall, маршруты и switch не меняются. + +Посмотрите нужные Engine/interface: + +```bash +docker info --format '{{.ID}}' +ip -json link show +``` + +Укажите увиденные Engine ID/interface name/index/MAC и реальные адреса в приватном `local/packmate-host.json`: + +```json +{ + "schema": "durkahelper.packmate-host.v1", + "daemon_id": "REPLACE_ENGINE_ID", + "interface": "eth0", "ifindex": 2, "interface_mac": "02:00:00:00:00:01", + "local_ip": "192.0.2.10", "bind_address": "192.0.2.20", + "ui_port": 65000, "db_port": 55432, + "tcp_timeout_seconds": 30, "udp_timeout_seconds": 10, + "timeout_check_seconds": 5, "retention_minutes": 60, + "cleanup_interval_minutes": 1 +} +``` + +Это примеры значений. `local_ip` — IP стороны сервиса в трафике; `bind_address` — адрес UI для команды. Отдельный приватный credentials JSON содержит `username`, `password`, `db_password`; пароли — разные сгенерированные safe ASCII длиной 20–128. Файлы должны лежать в owner-only каталоге. + +На разрешённом Linux-хосте подготовьте новый workspace и запустите: + +```bash +python3 deployment/packmate_host.py prepare \ + --workspace ../private-deployment/host-live-01 \ + --profile local/packmate-host.json \ + --credentials local/packmate-host-credentials.json \ + --apply --approval-id host-live-prepare +python3 deployment/packmate_host.py up \ + --workspace ../private-deployment/host-live-01 \ + --capture-approval '::' \ + --host-network-approved --interface-scope-approved \ + --apply --approval-id host-live-start +``` + +Зарегистрируйте сервисы/шаблоны в UI и проверьте известные TCP/UDP запросы/ответы, направление, задержку, незавершённые потоки и restart. Видимость пакетов обеспечивается разрешённым размещением host/mirror. Очистка по возрасту — не жёсткая disk quota: следите за ростом хранилища. + +Остановить только этот capture deployment с сохранением данных: + +```bash +python3 deployment/packmate_host.py down \ + --workspace ../private-deployment/host-live-01 \ + --apply --approval-id host-live-stop +``` + +Для разрешённого существующего container namespace — отдельный [container LIVE reference](../deployment/README-RU.md#approved-linux-container-namespace-live). Прямые helpers поддерживают контролируемые cache/bootstrap операции; для другого offline-хоста смотрите их `--help`. + + +## Проверить до использования + +Найдите известную транзакцию, а не только работающий UI. Проверьте оба направления, время, характерные TCP/UDP, рост диска и restart. Остановите capture при неверном scope, утечке секретов или приближении к пределу диска. + +FILE — отложенный анализ. Если необходим непрерывный анализ, одних закрытых файлов недостаточно. Прогоните оба разрешённых пути и подготовьте capture-зависимости/образы до выезда. + +[Packmate](packmate-RU.md) · [Шпаргалка админа](TEAM_LAN_ADMIN_CHEATSHEET-RU.md) diff --git a/docs/traffic-capture.md b/docs/traffic-capture.md new file mode 100644 index 0000000..293edaa --- /dev/null +++ b/docs/traffic-capture.md @@ -0,0 +1,123 @@ +# Traffic: LIVE or PCAP import + +English | [Русский](traffic-capture-RU.md) + +Prepare both routes before the event. Choose the one the organizers permit; no code changes are needed for normal FILE import. + +## Choose a route + +| What is available | Use | +|---|---| +| You may run capture on the Vulnbox/native Linux node and see its interface traffic | Packmate LIVE on that Linux node | +| An approved Linux mirror/capture interface is provided | Packmate LIVE there; organizers provide the mirror | +| Only closed PCAP files or authorized SSH/tcpdump access | Transfer closed files and use Packmate FILE on the laptop | +| No permitted traffic source | Continue source review; traffic analysis is unavailable | + +A Mac on the same Ethernet switch does not automatically see Vulnbox packets. Docker Desktop's maintained route is FILE-only. An endless FILE pipe is not a substitute for LIVE: this upstream ties incomplete-flow timeouts and periodic cleanup to LIVE. + +## FILE on the laptop + +Start the stack, obtain a **closed** capture and import: + +```bash +python3 durka.py up +python3 durka.py traffic import /path/to/closed-capture.pcap +python3 durka.py status +``` + +The command checks the file internally, retains the prior capture and restarts only Packmate. Its database and other tools remain running. No manual SHA/card is needed. + +In Packmate: register the service/pattern, check the service-side IP in the configuration and press the yellow downward-arrow FILE-processing button in the sidebar once. Find a known request and response. See the [UI guide](packmate.md#file-on-the-laptop) for the distinction between importing and processing. Repeat the import command and processing button for each new file. EOF does not reset the upstream parser; do not copy a new capture directly over a running FILE input. + +Manual media delivery is valid too. Keep captures private: they can contain cookies, credentials and flags. + +## Capture a closed file on Linux + +Prefer organizer-provided files. If you have permitted capture access and existing `tcpdump`/`timeout`, run this from a private directory on the source. Replace all placeholders with the approved interface/service/ports and a **new** filename: + +```bash +umask 077 +timeout --signal=INT 60 tcpdump -i -p -nn -s 65535 \ + -c 1000 -w .pcap \ + 'host and (tcp port or udp port )' +``` + +Wait for the process to exit before transferring. This records up to 60 seconds or 1,000 packets, approximately 66 MB plus format overhead. `timeout` exit 124 may be expected; other capture errors need checking. The recipe follows the [tcpdump manual](https://github.com/the-tcpdump-group/tcpdump/blob/master/tcpdump.1.in) and is a reviewed procedure, not a test of your event interface. + +With an existing approved SSH identity and trusted host key: + +```bash +scp -o StrictHostKeyChecking=yes -P \ + @: ./incoming-01.pcap +python3 durka.py traffic import ./incoming-01.pcap +``` + +Run these two commands on the laptop from the repository root. Keep the source until import/use succeeds. Never transfer a file still being written. + +## Host-interface LIVE + +For normal laptop-operated startup use [SSH deployment with doctor and offline images](packmate-remote.md). +No Python is required on the Vulnbox. The low-level Linux helper below remains available for advanced manual procedures. + +This is the Linux administrator's branch, separate from Docker Desktop. Requirements: native Linux amd64, standard local rootful Docker Engine, cached pinned Packmate/PostgreSQL images and permission for the **entire selected interface**. The pinned upstream briefly uses a broad TCP/UDP filter during startup. + +The launcher uses host networking and NET_RAW; not privileged or NET_ADMIN. It leaves the database on IPv4 loopback and does not change firewall, routes or switch configuration. + +Inspect the intended Engine/interface: + +```bash +docker info --format '{{.ID}}' +ip -json link show +``` + +Put the observed Engine ID/interface name/index/MAC and actual addresses in a private `local/packmate-host.json`: + +```json +{ + "schema": "durkahelper.packmate-host.v1", + "daemon_id": "REPLACE_ENGINE_ID", + "interface": "eth0", "ifindex": 2, "interface_mac": "02:00:00:00:00:01", + "local_ip": "192.0.2.10", "bind_address": "192.0.2.20", + "ui_port": 65000, "db_port": 55432, + "tcp_timeout_seconds": 30, "udp_timeout_seconds": 10, + "timeout_check_seconds": 5, "retention_minutes": 60, + "cleanup_interval_minutes": 1 +} +``` + +These values are examples. `local_ip` means the service-side IP in the traffic; `bind_address` serves the team's UI. Use a separate private credentials JSON with `username`, `password`, `db_password`; passwords are distinct generated 20–128 character safe ASCII values. Keep these files under an owner-only directory. + +On the approved Linux host, prepare a new workspace and start: + +```bash +python3 deployment/packmate_host.py prepare \ + --workspace ../private-deployment/host-live-01 \ + --profile local/packmate-host.json \ + --credentials local/packmate-host-credentials.json \ + --apply --approval-id host-live-prepare +python3 deployment/packmate_host.py up \ + --workspace ../private-deployment/host-live-01 \ + --capture-approval '::' \ + --host-network-approved --interface-scope-approved \ + --apply --approval-id host-live-start +``` + +Register services/patterns in the UI and verify known TCP/UDP requests/responses, direction, delay, unfinished flows and restart. Packet visibility must come from the approved host/mirror placement. Age cleanup is not a hard disk quota: watch storage growth. + +To stop only this capture deployment and retain data: + +```bash +python3 deployment/packmate_host.py down \ + --workspace ../private-deployment/host-live-01 \ + --apply --approval-id host-live-stop +``` + +For an already approved existing container namespace, use the separate [container LIVE reference](../deployment/README.md#approved-linux-container-namespace-live). Direct helpers also support controlled cache/bootstrap operations; see their `--help` when preparing a different offline host. + +## Check before relying on traffic + +Find a known transaction, not just a running UI. Check both directions, timestamps, representative TCP/UDP, storage growth and restart. Stop capture if it observes the wrong scope, exposes secrets or approaches disk limits. + +FILE is delayed analysis. If continuous analysis is required, a closed-file fallback alone does not satisfy that requirement. Rehearse both allowed paths and keep capture dependencies/images ready before leaving. + +[Packmate](packmate.md) · [Admin cheat sheet](TEAM_LAN_ADMIN_CHEATSHEET.md) diff --git a/docs/vulnerabilities/README-RU.md b/docs/vulnerabilities/README-RU.md new file mode 100644 index 0000000..9638492 --- /dev/null +++ b/docs/vulnerabilities/README-RU.md @@ -0,0 +1,50 @@ + + +# Каталог уязвимостей и исправлений + +[English](README.md) | Русский + +Для каждого языка — отдельный файл; SQL и конфигурация рассматриваются отдельно. Инструкции доступны локально и работают без Интернета; ссылки на первичные источники находятся рядом с соответствующими случаями. + +**294 раздела, 174 правила сканера.** Число разделов не равно числу независимых CWE: реализации на разных языках отличаются. + +| Язык / уровень | Разделы | +|---|---:| +| [Python](python-RU.md) | 40 | +| [JavaScript / TypeScript](javascript-RU.md) | 28 | +| [PHP](php-RU.md) | 23 | +| [Go](go-RU.md) | 19 | +| [Java](java-RU.md) | 18 | +| [C# / .NET](csharp-RU.md) | 20 | +| [C / C++](c-cpp-RU.md) | 28 | +| [Ruby / Rails](ruby-RU.md) | 18 | +| [Rust](rust-RU.md) | 18 | +| [SQL / базы данных](sql-RU.md) | 18 | +| [Конфигурация / границы доверия](configuration-RU.md) | 64 | + + + +## Найти и исправить + +1. Запустите [офлайн-сканер](../offline-scanner-RU.md) на локальной копии сервиса, которую вам разрешено проверять. +2. Откройте ссылку на конкретный раздел для каждой находки. +3. Просмотрите разделы языка и конфигурации, предназначенные только для ручной проверки; их команды rg находят код для анализа, а не подтверждённые уязвимости. +4. Внесите совместимое исправление и проверьте поведение для владельца и другого пользователя, старые данные и checker соревнования. Используйте [проверку патча](../patch-validation-RU.md). + +Каждый раздел построен по схеме **Поиск → Уязвимый вариант → Исправление → Проверка**. +Покрытие: **174 автоматических сигнала и 120 разделов только для ручной проверки**. +Две темы, ранее проверявшиеся только вручную, теперь имеют намеренно узкие автоматические сигналы; ручной поиск остаётся необходимым для остальных форм. + +Пустой отчёт не доказывает безопасность. Пользовательские wrappers, сгенерированный код, defaults конкретных версий и бизнес-логика требуют ручного анализа. Сканер не импортирует и не исполняет код цели и не обращается к сетевой базе уязвимостей. + + + +## Границы применимости примеров + +Функции вроде validateOwnedResource и evaluateAllowedExpression обозначают логику, которую нужно реализовать самостоятельно; это не готовые зависимости. Шаблоны патчей никогда не применяются автоматически. Сохраняйте штатное поведение, границы авторизации, старые данные и совместимость с checker. + +Отделяйте данные от кода и аргументов. Массив argv без shell всё ещё допускает опасные опции вызываемой программы; проверяйте собственный контракт утилиты. Парсер или проверка типа не заменяет авторизацию. Корректное исправление может сохранить синтаксический сигнал сканера. + +Исторические A/D-примеры сохраняют зафиксированные версии источников и авторство. Проверка семантики исходников не доказывает, что каждый пример запускался на всех поддерживаемых runtime. Каталог не предлагает устанавливать устаревшие версии, упомянутые для объяснения исторического поведения. + +См. [покрытие и разработку правил](../development-RU.md): независимые положительные и отрицательные fixtures и заявленные ограничения детекторов. diff --git a/docs/vulnerabilities/README.md b/docs/vulnerabilities/README.md new file mode 100644 index 0000000..f11609c --- /dev/null +++ b/docs/vulnerabilities/README.md @@ -0,0 +1,44 @@ +# Vulnerability and remediation catalog + +English | [Русский](README-RU.md) + +One file per language, with SQL and configuration reviewed separately. Recipes are local and usable offline; primary references remain beside their relevant cases. + +**294 sections, 174 scanner rules.** A section count is not a count of independent CWEs: language-specific implementations differ. + +| Language / layer | Sections | +|---|---:| +| [Python](python.md) | 40 | +| [JavaScript / TypeScript](javascript.md) | 28 | +| [PHP](php.md) | 23 | +| [Go](go.md) | 19 | +| [Java](java.md) | 18 | +| [C# / .NET](csharp.md) | 20 | +| [C / C++](c-cpp.md) | 28 | +| [Ruby / Rails](ruby.md) | 18 | +| [Rust](rust.md) | 18 | +| [SQL / databases](sql.md) | 18 | +| [Configuration / trust boundaries](configuration.md) | 64 | + +## Find and fix + +1. Run the [offline scanner](../offline-scanner.md) against an authorized local service checkout. +2. Open each finding's exact section link. +3. Review manual-only language and configuration sections; their rg searches identify code to trace, not confirmed vulnerabilities. +4. Implement a compatible fix and verify owner/other-user behavior, legacy data and the competition checker. Use [patch verification](../patch-validation.md). + +Every section follows **Search → Vulnerable example → Fix → Verification**. +Coverage: **174 automatic signals and 120 manual-only sections**. +Two formerly manual topics now have deliberately narrow automatic signals; their manual searches remain necessary for uncovered forms. + +An empty report does not prove safety. Custom wrappers, generated code, version-specific defaults and business logic need manual review. The scanner does not import or execute the target or consult an online vulnerability feed. + +## Example boundaries + +Helpers such as validateOwnedResource and evaluateAllowedExpression represent logic you must implement; they are not ready-made dependencies. Patch templates are never applied automatically. Preserve normal behavior, authorization boundaries, legacy data and checker compatibility. + +Keep data separate from code and arguments. A shell-free argv array still permits dangerous options accepted by the invoked program; validate the utility's own contract. A parser or type assertion is not authorization. Correct fixes may retain syntactic findings. + +Historical A/D cases retain their source pins and attribution. Reviewed source semantics are not proof that every example has run under every supported language runtime. The catalog does not prescribe installing obsolete versions mentioned to explain historical behavior. + +See [coverage and rule development](../development.md) for independent positive/negative fixtures and declared detector limits. diff --git a/docs/vulnerabilities/c-cpp-RU.md b/docs/vulnerabilities/c-cpp-RU.md new file mode 100644 index 0000000..cc4200d --- /dev/null +++ b/docs/vulnerabilities/c-cpp-RU.md @@ -0,0 +1,946 @@ + + +# C / C++: поиск и исправление + +[English](c-cpp.md) | Русский + +[Вся база](README-RU.md) · [Сканер](../offline-scanner-RU.md) · [Проверка патча](../patch-validation-RU.md) + +28 разделов. Формат: **Поиск → Уязвимый вариант → Исправление → Проверка**. +Команды `rg` выполняются в корне локальной копии сервиса и только читают файлы. Субъект/владелец определяется по проверенной сессии, а не данным запроса. Примеры нужно адаптировать к реальным API и контракту. + +Автоматические находки — ограниченные синтаксические сигналы для проверки. AST-анализ не разрешает типы и не отслеживает данные между функциями; regex не заменяет парсер языка. Комментарии, строки и одноимённые пользовательские API могут давать совпадения. Проверьте фактическое исполнение, входные данные, авторизацию и границы доверия. + + + +## Содержание + +- [C-BOUNDS — Неограниченное копирование C/C++](#c-bounds) +- [C-FORMAT — Переменная как format string](#c-format) +- [C-SHELL — Shell в C/C++](#c-shell) +- [C-PRNG — Обычный PRNG/LCG в возможном секрете](#c-prng) +- [C-SNPRINTF-FORMAT — Переменная как формат ограниченного printf](#c-snprintf-format) +- [C-RECV-TERMINATOR — Результат recv/read используется как индекс](#c-recv-terminator) +- [C-ATOI — atoi без проверки результата](#c-atoi) +- [C-REALLOC — Перезапись единственного указателя realloc](#c-realloc) +- [C-SIZE-OVERFLOW — Переполнение арифметики размера](#c-size-overflow) +- [CPP-LIFETIME — Указатель/view переживает владельца](#cpp-lifetime) +- [C-PARTIAL-IO — TCP не сохраняет границы сообщений](#c-partial-io) +- [C-SIGNED-LENGTH — Знаковая длина становится большим size_t](#c-signed-length) +- [C-DOUBLE-FREE — Несколько владельцев освобождают один объект](#c-double-free) +- [C-UNINITIALIZED — Выдача padding и незаполненного хвоста](#c-uninitialized) +- [C-TEMPFILE-RACE — Предсказуемое имя и check-then-open](#c-tempfile-race) +- [C-JIT-RETURN — Не все пути JIT-функции завершаются](#c-jit-return) +- [C-HEADER-SECRET — Особая ветка по заголовку меняет секрет](#c-header-secret) +- [C-OBJECT-TOCTOU — Проверили объект, затем заново прочитали изменяемую ссылку](#c-object-toctou) +- [C-EXEC-FAILURE — Ошибка exec оставляет дочерний процесс на серверном пути](#c-exec-failure) +- [CPP-CACHED-LIFETIME — Кэш хранит указатель после освобождения объекта](#cpp-cached-lifetime) +- [C-BLOCK-TAIL — Обработка блока по четыре байта портит хвост буфера](#c-block-tail) +- [C-ALLOC-FAILURE — Ошибка выделения памяти превращается в запись по NULL](#c-alloc-failure) +- [C-FD-NUL — Утечка fd усиливает off-by-one в read_line](#c-fd-nul) +- [C-REENTRANCY-AUTH — Callback между auth-проверкой и подписью](#c-reentrancy-auth) +- [C-BUILTIN-TYPES — Не проверен тип аргумента в одной перегрузке builtin](#c-builtin-types) +- [C-HASH-INDEX — Индекс хеш-таблицы сдвинут за верхнюю границу](#c-hash-index) +- [C-STRNCPY — strncpy может оставить строку без NUL](#c-strncpy) +- [C-COPY-LENGTH — Длина копирования берётся напрямую из strlen источника](#c-copy-length) + + + + + +## C-BOUNDS. Неограниченное копирование C/C++ + +**Поиск:** скрипт, правило C-BOUNDS. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain C-BOUNDS. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API. + +**Уязвимый вариант:** + +~~~c +strcpy(destination, source); +~~~ + +**Исправление:** Проверять ёмкость/длину до копирования. snprintf проверять по результату; механический strncpy не решает всё. + +~~~c +size_t n = strlen(source); +if (n >= capacity) return ERROR; +memcpy(destination, source, n + 1); +~~~ + +**Проверка:** Пустой/граничный/слишком большой вход; ASan/UBSan если доступны. + +
+Развёрнутый пример и ограничения + +```c +/* Vulnerable: capacity and available source length are unchecked. */ +char dst[64]; +memcpy(dst, src, client_len); +dst[client_len] = '\0'; +``` + +**Патч для поля протокола, которое является C-строкой без встроенного NUL:** + + +```c +#include +#include +#include + +bool copy_text(char *dst, size_t capacity, const char *src, + size_t available, size_t requested) { + if (dst == NULL || src == NULL || capacity == 0) return false; + if (requested > available || requested >= capacity) return false; + if (memchr(src, '\0', requested) != NULL) return false; + memmove(dst, src, requested); + dst[requested] = '\0'; + return true; +} +``` + +`available` — фактически доступные байты, не заявленный клиентом размер. +Знаковую длину проверить на отрицательность **до** перевода в `size_t`. +`memmove` допускает перекрытие; при отказе функция не меняет dst. Вызывающий +код обязан обработать `false`, а не отправлять прежнее содержимое буфера. + +**Проверить:** пустая строка, capacity−1, capacity, недостаточный src, +нулевая вместимость, NUL внутри текста; при отказе буфер не изменён. +Для бинарных данных встроенный NUL допустим: нужен иной контракт с явной длиной. +Молчаливое усечение через `strncpy` может испортить ID/данные checker. + +
+ + + + + +## C-FORMAT. Переменная как format string + +**Поиск:** скрипт, правило C-FORMAT. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain C-FORMAT. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API. + +**Уязвимый вариант:** + +~~~c +printf(message); +~~~ + +**Исправление:** Фиксированный формат и проверенные аргументы; бинарным данным явная длина. + +~~~c +printf("%s", message); +~~~ + +**Проверка:** Символы процента печатаются текстом. + +
+Развёрнутый пример и ограничения + +```c +/* Vulnerable: message controls the format and argument interpretation. */ +printf(message); +``` + +**Патч, если message — корректная NUL-терминированная строка:** + + +```c +#include +#include + +bool write_message(FILE *out, const char *message) { + if (out == NULL || message == NULL) return false; + return fputs(message, out) != EOF; +} +``` + +Альтернатива — `fprintf(out, "%s", message)` с фиксированным форматом. +Для сетевого буфера с известной длиной использовать проверенный размер и +`fwrite`, не предполагать наличие NUL. Ошибку записи обработать отдельно. + +**Проверить:** строка с `%s`, `%%` и Unicode выводится буквально; пустая строка +допустима; текст не получает лишний перевод строки, если это важно протоколу. + +
+ + + + + +## C-SHELL. Shell в C/C++ + +**Поиск:** скрипт, правило C-SHELL. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain C-SHELL. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API. + +**Уязвимый вариант:** + +~~~c +system(command); +~~~ + +**Исправление:** execve/posix_spawn с фиксированной программой/argv; проверить аргументы и ошибки. + +~~~c +run_fixed_tool(validated_filename); // fixed executable + argv inside +~~~ + +**Проверка:** Спецсимволы не интерпретируются shell. + + + + + +## C-PRNG. Обычный PRNG/LCG в возможном секрете + +**Поиск:** скрипт, правило C-PRNG. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain C-PRNG. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API. + +**Уязвимый вариант:** + +~~~c +srand((unsigned)time(NULL)); +token = rand(); +~~~ + +**Исправление:** Для секрета системный CSPRNG/поддержанная криптобиблиотека, проверка результата. Обычная игровая случайность может использовать PRNG. + +~~~c +if (!fill_from_os_csprng(token, sizeof token)) return ERROR; // implement using supported OS/library API +~~~ + +**Проверка:** Нет seed от времени/const и предсказуемого fallback; формат токена совместим. + +**Вариант A/D:** Идентификатор доступа из LCG со временем в seed. **ENOWARS / piratesay, автор.** Идентификатор разрешал сменить пользователя, +а генератор зависел от времени старта. + +**Патч:** системный CSPRNG и серверная привязка credential к пользователю. +Скрытый константный seed не является надёжным исправлением. +**Тест:** новые идентификаторы/старые сессии по плану перехода, ошибка источника +энтропии без fallback. **Поиск:** C-PRNG; самодельные генераторы требуют чтения. + +[исходник/разбор 1](https://github.com/enowars/enowars8-service-piratesay/blob/32973478dbe903d0a2446539ecbddf3b1c334e60/documentation/README.md); [исходник/разбор 2](https://github.com/enowars/enowars8-service-piratesay/blob/32973478dbe903d0a2446539ecbddf3b1c334e60/service_source/src/cli.c); [исходник/разбор 3](https://github.com/enowars/enowars8-service-piratesay/blob/32973478dbe903d0a2446539ecbddf3b1c334e60/service_source/src/session.c). + + + + + +## C-SNPRINTF-FORMAT. Переменная как формат ограниченного printf + +**Поиск:** скрипт, правило C-SNPRINTF-FORMAT. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain C-SNPRINTF-FORMAT. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API. + +**Уязвимый вариант:** + +~~~c +snprintf(out, capacity, message); +~~~ + +**Исправление:** Фиксированный формат. Лимит размера буфера не делает недоверенную format string безопасной; проследить собственные wrappers/macros. + +~~~c +snprintf(out, capacity, "%s", message); +~~~ + +**Проверка:** Проценты выводятся как текст; длина/усечение обработаны; внутренний wrapper может оставаться сигналом. + +**Вариант A/D:** Format string внутри «безопасной» обёртки. **ENOWARS / piratesay, автор.** Ограниченная запись в буфер и фильтрация +нескольких спецификаторов не мешали следующему слою снова интерпретировать +пользовательский текст как формат. + +**Патч:** фиксированный формат на последнем sink, данные отдельным аргументом; +проследить macro → wrapper → printf-family. **Тест:** проценты печатаются +буквально, усечение обрабатывается. **Поиск:** C-FORMAT, C-SNPRINTF-FORMAT; +произвольные имена обёрток автоматически не распознаются. + +[исходник/разбор 1](https://github.com/enowars/enowars8-service-piratesay/blob/32973478dbe903d0a2446539ecbddf3b1c334e60/documentation/README.md); [исходник/разбор 2](https://github.com/enowars/enowars8-service-piratesay/blob/32973478dbe903d0a2446539ecbddf3b1c334e60/service_source/src/cli.c); [исходник/разбор 3](https://github.com/enowars/enowars8-service-piratesay/blob/32973478dbe903d0a2446539ecbddf3b1c334e60/service_source/src/session.c). + + + + + +## C-RECV-TERMINATOR. Результат recv/read используется как индекс + +**Поиск:** скрипт, правило C-RECV-TERMINATOR. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain C-RECV-TERMINATOR. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API. + +**Уязвимый вариант:** + +~~~c +n = recv(fd, buffer, sizeof buffer, 0); +buffer[n] = '\0'; +~~~ + +**Исправление:** Оставить место для NUL, проверить отрицательную длину/EOF до индексации, учитывать неполное чтение. Сигнал может остаться на правильном коде. + +~~~c +ssize_t n = recv(fd, buffer, sizeof buffer - 1, 0); +if (n <= 0) return ERROR; +buffer[n] = '\0'; +~~~ + +**Проверка:** recv=-1, EOF, полный буфер, короткое чтение и обычное сообщение. + + + + + +## C-ATOI. atoi без проверки результата + +**Поиск:** скрипт, правило C-ATOI. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain C-ATOI. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API. + +**Уязвимый вариант:** + +~~~c +int size = atoi(input); +~~~ + +**Исправление:** Полный разбор числа: знак, диапазон, end pointer и errno; проверить арифметику до allocation/copy. + +~~~c +// use strtol/strtoull with errno, end pointer, sign and application bounds checks +~~~ + +**Проверка:** Пусто, хвост текста, отрицательное число, overflow, граничный допустимый размер. + +**Основание:** [первичный материал](https://cmu-sei.github.io/secure-coding-standards/sei-cert-c-coding-standard/rules/error-handling-err/err34-c/). + + + + + +## C-REALLOC. Перезапись единственного указателя realloc + +**Поиск:** скрипт, правило C-REALLOC. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain C-REALLOC. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API. + +**Уязвимый вариант:** + +~~~c +buffer = realloc(buffer, size); +~~~ + +**Исправление:** Проверенный ненулевой size, временный указатель и обработка ошибки. Отдельно обработать size=0 по контракту, не полагаться на переносимую семантику realloc(p,0). + +~~~c +void *next = realloc(buffer, size); +if (next == NULL) { /* preserve buffer; handle error */ } +else { buffer = next; } +~~~ + +**Проверка:** Fault injection allocation error сохраняет старый buffer; нет утечки/double free. + +**Основание:** [первичный материал](https://cmu-sei.github.io/secure-coding-standards/sei-cert-c-coding-standard/recommendations/memory-management-mem/mem04-c/). + + + + + +## C-SIZE-OVERFLOW. Переполнение арифметики размера + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'malloc|calloc|resize|reserve|sizeof|memcpy' . +~~~ + +Перед умножением/сложением проверить SIZE_MAX и application limit; знак до cast. + +**Уязвимый вариант:** + +malloc(count * sizeof(Item)) выделяет меньше, чем последующее копирование после overflow. + +**Исправление:** Проверенное умножение/сложение и фактическая capacity; отдельно обработать ноль и allocation failure. + +**Проверка:** Ноль, граница, переполнение произведения/суммы, отрицательный вход и прежний буфер. + +
+Развёрнутый пример и ограничения + +```c +/* Vulnerable: count * sizeof(Item) can overflow. */ +Item *items = malloc(count * sizeof(*items)); +``` + +**Патч проверки арифметики и согласованного лимита:** + + +```c +#include +#include +#include + +bool array_bytes(size_t count, size_t item_size, size_t max_bytes, size_t *out) { + if (out == NULL || item_size == 0) return false; + if (count > SIZE_MAX / item_size) return false; + size_t total = count * item_size; + if (total > max_bytes) return false; + *out = total; + return true; +} +``` + +Перед `malloc` вызвать с `sizeof(*items)` и лимитом по контракту; проверить +результат выделения. Нулевой count обрабатывать отдельно согласно протоколу: +не выводить ошибку только из того, что `malloc(0)` вернул NULL. Размер out при +отказе не использовать. При добавлении заголовка/терминатора проверить также +сложение; эта функция проверяет только произведение. + +**Проверить:** ноль, единица, ровно допустимый бюджет, превышение бюджета, +произведение больше SIZE_MAX; ошибка не ведёт к копированию в старый/NULL-буфер. + +
+ + + + + +## CPP-LIFETIME. Указатель/view переживает владельца + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'c_str\(|string_view|span|return.*data|return.*&' . +~~~ + +Найти владельца данных и его destruction/reallocation; проверить async callback и lambda captures. + +**Уязвимый вариант:** + +Возвращён c_str временной string или string_view локального буфера. + +**Исправление:** Вернуть владеющий объект/копию; при async передать владение до завершения, view сам по себе lifetime не продлевает. + +**Проверка:** Результат существует после возврата, следующий вызов его не портит, async дожидается окончания. + +
+Развёрнутый пример и ограничения + +```cpp +// Vulnerable: the temporary string dies before the returned pointer is used. +const char* make_label(const std::string& name) { + return (std::string("hello ") + name).c_str(); +} +``` + +**Патч: вернуть владеющий объект, а не указатель в уничтоженное хранилище:** + + +```cpp +#include + +std::string make_label(const std::string& name) { + return std::string("hello ") + name; +} +``` + +Вызывающий код хранит `std::string label = make_label(name);`. Его `c_str()` +можно передать синхронному API, которое не удерживает указатель дольше жизни +строки. Для асинхронной операции нужно передать владение/копию. `string_view` +сам по себе не продлевает жизнь строки и не является исправлением. + +**Проверить:** результат существует после выхода из функции; последовательные +вызовы не меняют прошлые результаты; пустое имя и Unicode; асинхронный путь +удерживает данные до завершения операции. + +
+ + + + + +## C-PARTIAL-IO. TCP не сохраняет границы сообщений + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'recv|read\(|send|write\(|Content-Length|length' . +~~~ + +Сверить frame length с накопленными байтами и циклы short read/write, EINTR/EOF. + +**Уязвимый вариант:** + +Один recv принят за целый запрос; send передал только часть приватного ответа, следующий кадр склеился. + +**Исправление:** Явный framing и ограниченный накопительный буфер, проверка частичных операций и timeout; не менять протокол checker. + +**Проверка:** Фрагментация по каждому байту, два кадра вместе, EOF посредине и обычное сообщение. + + + + + +## C-SIGNED-LENGTH. Знаковая длина становится большим size_t + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'ssize_t|size_t|uint32_t|int.*len|memcpy|recv' . +~~~ + +Проследить все casts между чтением/разбором и allocation/index. + +**Уязвимый вариант:** + +Отрицательный read или пользовательский int приводится к unsigned до проверки. + +**Исправление:** Проверить error/sign/range до преобразования, сверить вместимость источника и приёмника. + +**Проверка:** read=-1, EOF, отрицательное поле, максимум и нормальный payload. + + + + + +## C-DOUBLE-FREE. Несколько владельцев освобождают один объект + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'free\(|delete|unique_ptr|shared_ptr|goto.*fail' . +~~~ + +Пройти success/error cleanup и передачу владения; найти два shared_ptr из одного raw pointer. + +**Уязвимый вариант:** + +Error path и внешний caller освобождают объект дважды, либо reset уничтожает ещё используемый объект. + +**Исправление:** Единый owner/RAII и явная передача владения; обнуление одного alias не исправляет остальные. + +**Проверка:** Ошибка на каждом шаге создания, повторный cleanup, нормальный жизненный цикл. + + + + + +## C-UNINITIALIZED. Выдача padding и незаполненного хвоста + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'malloc|struct|send|write|sizeof|memcpy' . +~~~ + +Сравнить реально заполненные поля с sizeof отправляемого struct и padding. + +**Уязвимый вариант:** + +send(fd, &record, sizeof record, ...) выдаёт padding либо остаток предыдущего содержимого. + +**Исправление:** Явная сериализация полей и длины, инициализация буфера; не публиковать native layout как протокол. + +**Проверка:** Разные компиляторы/layout, короткий ввод, отсутствие незаполненных байтов в ответе. + + + + + +## C-TEMPFILE-RACE. Предсказуемое имя и check-then-open + +**Поиск:** скрипт, правило C-TEMPFILE-RACE. Запуск: python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain C-TEMPFILE-RACE. Regex: tmpnam/tempnam/mktemp. Самописные схемы имени, reopen после mkstemp и TOCTOU по каталогу остаются ручными. + +Дополнительный ручной поиск для непокрытых форм: + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'tmpnam|mktemp|access\(|stat\(|fopen|open\(' . +~~~ + +Проследить промежуток existence check → open и права родительского каталога. + +**Уязвимый вариант:** + +Имя в общем /tmp проверено, затем открыто с перезаписью по подменённой ссылке. + +**Исправление:** Атомарное создание mkstemp/open с O_EXCL и нужной политикой links, private temp dir, restrictive mode; descriptor-based работа. + +**Проверка:** Коллизия имени, symlink, параллельное создание, ошибка записи и cleanup. + + +**Сигнал сканера — пример до:** + +~~~native +char name[L_tmpnam]; +tmpnam(name); +FILE *f = fopen(name, "w"); +~~~ + +**Шаблон исправления:** + +~~~native +char name[] = "/tmp/app-XXXXXX"; +int fd = mkstemp(name); +if (fd < 0) return ERROR; +unlink(name); +/* use fd; close(fd) on every exit */ +~~~ + +Первичная документация: [документация 1](https://pubs.opengroup.org/onlinepubs/9799919799/functions/mkstemp.html). + + + + + +## C-JIT-RETURN. Не все пути JIT-функции завершаются + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'return|emit|jit|compile|bytecode' . +~~~ + +Построить выходы CFG функции: условный return не закрывает другую ветвь и fall-through. + +**Уязвимый вариант:** + +**Основание:** dcs, авторский разбор RuCTF: условный return ошибочно считался +достаточным; выполнение продолжалось за телом функции. +**Искать:** самодельные VM/JIT/DSL, проверка return через поиск узла вместо +анализа достижимости, размещение констант рядом с инструкциями. + +**Исправление:** анализ графа потока: каждый достижимый выход обязан возвращать +значение либо завершаться определённой ошибкой. Разделять код и данные, +проверять индексы/типы до генерации. + +**Проверка:** обе ветви условия, вложенные +условия, пустая функция и штатные вычисления. Запретить JIT целиком можно +только если сохранён функциональный контракт. + +**Вариант A/D:** Основание и версия: [исходник/разбор 1](https://github.com/HackerDom/ructf-finals-2023/blob/a7442769909e08c39716cb18d3d1c3a99324bbf8/writeups/dcs/README.md). + +**Основание:** [первичный материал](https://github.com/HackerDom/ructf-finals-2023/blob/a7442769909e08c39716cb18d3d1c3a99324bbf8/writeups/dcs/README.md). + + + + + +## C-HEADER-SECRET. Особая ветка по заголовку меняет секрет + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'getenv|HTTP_USER_AGENT|SECRET_KEY|constructor' . +~~~ + +Прочитать init/constructor и ветви debug/test: клиентский заголовок не должен менять ключ. + +**Уязвимый вариант:** + +**Основание:** reversaar, анализ C-исходника saarCTF: специальный путь, +связанный с HTTP_USER_AGENT, изменял SECRET_KEY. +**Искать:** constructor/init-хуки, getenv заголовков, magic constants, +debug/test/admin-ветки в release, скрытые переключатели подписи. + +**Исправление:** удалить именно посторонний переход состояния; конфигурация секретов +не зависит от клиентского запроса. Просмотреть код запуска, не только маршруты. + +**Проверка:** разные заголовки не меняют ключ, права и формат хранения; обычная +инициализация сохранена. Сканер не содержит сигнатуры конкретного magic value; +связь входа с секретом проверяется вручную. + +**Вариант A/D:** Основание и версия: [исходник/разбор 1](https://github.com/saarsec/saarctf-2024/blob/3a06d18974ca177c6dd251a11bdf9b4b334f382a/reversaar/service/src/array.c). + +**Основание:** [первичный материал](https://github.com/saarsec/saarctf-2024/blob/3a06d18974ca177c6dd251a11bdf9b4b334f382a/reversaar/service/src/array.c). + + + + + +## C-OBJECT-TOCTOU. Проверили объект, затем заново прочитали изменяемую ссылку + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'background|fork|exec|open|read' . +~~~ + +Найти повторное чтение изменяемого объекта после проверки и внешнего вызова; сверить identity/snapshot. + +**Уязвимый вариант:** + +**RuCTF / memos, автор.** Между проверкой доступа к фону и чтением фона +выполнялась внешняя операция; другой запрос мог заменить выбранный объект. + +**Исправление:** работать с тем же проверенным снимком/дескриптором, либо атомарно +проверять версию перед использованием. + +**Проверка:** контролируемое чередование +двух запросов через барьер, штатная длительная обработка. + +**Вариант A/D:** Основание и версия: [исходник/разбор 1](https://github.com/HackerDom/ructf-2023/blob/0cc333e44f2ba6908ff6c5d613146e3b00173315/writeups/memos/README.md). + +**Основание:** [первичный материал](https://github.com/HackerDom/ructf-2023/blob/0cc333e44f2ba6908ff6c5d613146e3b00173315/writeups/memos/README.md). + + + + + +## C-EXEC-FAILURE. Ошибка exec оставляет дочерний процесс на серверном пути + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'fork|execve|execvp|waitpid' . +~~~ + +Пройти ветвь каждого отрицательного возврата fork/exec и завершение child, включая аргументы сверх лимита. + +**Уязвимый вариант:** + +**RuCTF / memos, автор.** После неудачного execve дочерний процесс мог продолжить +логику сервиса. + +**Исправление:** проверять fork/exec/wait; после ошибки exec в дочерней ветви завершаться +через _exit с ошибкой, закрывая лишние дескрипторы. + +**Проверка:** исполняемый файл +недоступен, аргументы превышают лимит, fork неуспешен — второй сервер не возникает. + +**Вариант A/D:** Основание и версия: [исходник/разбор 1](https://github.com/HackerDom/ructf-2023/blob/0cc333e44f2ba6908ff6c5d613146e3b00173315/writeups/memos/README.md). + +**Основание:** [первичный материал](https://github.com/HackerDom/ructf-2023/blob/0cc333e44f2ba6908ff6c5d613146e3b00173315/writeups/memos/README.md). + + + + + +## CPP-CACHED-LIFETIME. Кэш хранит указатель после освобождения объекта + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'cache|delete|free|flush|shared_ptr|weak_ptr' . +~~~ + +Найти владельца cached pointer и момент освобождения; проследить вызов метода после eviction. + +**Уязвимый вариант:** + +**RuCTF / perune, автор.** Последующий обход кэша вызывал виртуальный метод +у освобождённого объекта. + +**Исправление:** явное владение, удаление всех ссылок при destruction, безопасные +handles/weak references или проверяемый generation ID. + +**Проверка:** разные порядки +создания/удаления/flush, доступный sanitizer; не считать отсутствие падения +доказательством. + +**Вариант A/D:** Основание и версия: [исходник/разбор 1](https://github.com/HackerDom/ructf-2023/blob/0cc333e44f2ba6908ff6c5d613146e3b00173315/writeups/perune/readme.md). + +**Основание:** [первичный материал](https://github.com/HackerDom/ructf-2023/blob/0cc333e44f2ba6908ff6c5d613146e3b00173315/writeups/perune/readme.md). + + + + + +## C-BLOCK-TAIL. Обработка блока по четыре байта портит хвост буфера + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'xor|chacha|uint32_t|length|remaining' . +~~~ + +Проверить обработку остатка длины 1–3 байта при шаге четыре; сопоставить фактическую allocation. + +**Уязвимый вариант:** + +**ECSC / Diese HSM, автор.** XOR проходил за конец при длине, не кратной слову. + +**Исправление:** полные блоки плюс отдельный ограниченный хвост, проверка выравнивания. + +**Проверка:** длины 0–9, края буфера, canary и допустимые nonce. + +**Вариант A/D:** Основание и версия: [исходник/разбор 1](https://github.com/ECSC2024/ECSC2024-CTF-AD/blob/2a92e17384ad228072a84fb076a35066fe2ffeff/sources/Diese/README.md); [исходник/разбор 2](https://github.com/ECSC2024/ECSC2024-CTF-AD/blob/2a92e17384ad228072a84fb076a35066fe2ffeff/sources/Diese/webapp/src/classes/Utils.class.php); [исходник/разбор 3](https://github.com/ECSC2024/ECSC2024-CTF-AD/blob/2a92e17384ad228072a84fb076a35066fe2ffeff/sources/Diese/hsm/src/msg.c). + +**Основание:** [первичный материал](https://github.com/ECSC2024/ECSC2024-CTF-AD/blob/2a92e17384ad228072a84fb076a35066fe2ffeff/sources/Diese/README.md). + + + + + +## C-ALLOC-FAILURE. Ошибка выделения памяти превращается в запись по NULL + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'malloc|calloc|alloc|memcpy' . +~~~ + +Проследить NULL/ошибку allocation до первой записи, включая собственный allocator и адресное пространство firmware. + +**Уязвимый вариант:** + +**ECSC / Diese HSM, автор + код.** Результат allocator не проверяется; +в firmware адрес 0 доступен. + +**Исправление:** checked size arithmetic, лимит сообщения, обработка allocation failure +во всей цепочке. + +**Проверка:** отказ каждого выделения и усечённый пакет. + +**Вариант A/D:** Основание и версия: [исходник/разбор 1](https://github.com/ECSC2024/ECSC2024-CTF-AD/blob/2a92e17384ad228072a84fb076a35066fe2ffeff/sources/Diese/README.md); [исходник/разбор 2](https://github.com/ECSC2024/ECSC2024-CTF-AD/blob/2a92e17384ad228072a84fb076a35066fe2ffeff/sources/Diese/webapp/src/classes/Utils.class.php); [исходник/разбор 3](https://github.com/ECSC2024/ECSC2024-CTF-AD/blob/2a92e17384ad228072a84fb076a35066fe2ffeff/sources/Diese/hsm/src/msg.c). + +**Основание:** [первичный материал](https://github.com/ECSC2024/ECSC2024-CTF-AD/blob/2a92e17384ad228072a84fb076a35066fe2ffeff/sources/Diese/README.md). + + + + + +## C-FD-NUL. Утечка fd усиливает off-by-one в read_line + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'read_line|open|close|fopen|fclose' . +~~~ + +Просмотреть закрытие fd в ветвях login error и запись NUL при заполненном буфере. + +**Уязвимый вариант:** + +**ECSC / CookingNonna, автор.** Неудачный login оставлял fd, а терминатор +мог записаться за полный буфер. + +**Исправление:** единый cleanup для всех отказов; резервировать байт под NUL, проверять +read/EOF и возвращаемые значения open относительно -1. + +**Проверка:** capacity 0/1/max, длинная строка, серия отказов без роста fd. + +**Вариант A/D:** Основание и версия: [исходник/разбор 1](https://github.com/ECSC2024/ECSC2024-CTF-AD/blob/2a92e17384ad228072a84fb076a35066fe2ffeff/sources/CookingNonna/README.md). + +**Основание:** [первичный материал](https://github.com/ECSC2024/ECSC2024-CTF-AD/blob/2a92e17384ad228072a84fb076a35066fe2ffeff/sources/CookingNonna/README.md). + + + + + +## C-REENTRANCY-AUTH. Callback между auth-проверкой и подписью + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'callback|SignToken|Len|ByRef' . +~~~ + +Найти вызов пользовательской функции после owner-check; проверить, может ли она менять подписываемые аргументы. + +**Уязвимый вариант:** + +**ICC / MaScroll, автор.** Переопределяемый Len мог изменить аргумент по ссылке +после проверки владельца. + +**Исправление:** валидировать неизменяемую копию, не вызывать пользовательский код +между проверкой и чувствительной операцией. + +**Проверка:** callback изменяет исходный объект, но подписывается только проверенный. + +**Вариант A/D:** Основание и версия: [исходник/разбор 1](https://github.com/CybersecNatLab/ICC2023-AD-CTF/blob/8ffa184ff2ce8f648258ed3c02ee2270e8e1c56c/sources/MaScroll/README.md). + +**Основание:** [первичный материал](https://github.com/CybersecNatLab/ICC2023-AD-CTF/blob/8ffa184ff2ce8f648258ed3c02ee2270e8e1c56c/sources/MaScroll/README.md). + + + + + +## C-BUILTIN-TYPES. Не проверен тип аргумента в одной перегрузке builtin + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'FastRand|CryptoRand|variant|overload|builtin' . +~~~ + +Сравнить типы всех аргументов каждой перегрузки, включая общий первый аргумент и error path. + +**Уязвимый вариант:** + +**ICC / MaScroll, автор.** Вариант вызова генератора пропускал проверку типа, +а ошибка памяти затрагивала криптографическое состояние. + +**Исправление:** единая проверка type/arity/length для всех перегрузок, корректные +владение и буферы. + +**Проверка:** матрица типов и числа аргументов; +ошибка не меняет состояние RNG/подписи. + +**Вариант A/D:** Основание и версия: [исходник/разбор 1](https://github.com/CybersecNatLab/ICC2023-AD-CTF/blob/8ffa184ff2ce8f648258ed3c02ee2270e8e1c56c/sources/MaScroll/README.md). + +**Основание:** [первичный материал](https://github.com/CybersecNatLab/ICC2023-AD-CTF/blob/8ffa184ff2ce8f648258ed3c02ee2270e8e1c56c/sources/MaScroll/README.md). + + + + + +## C-HASH-INDEX. Индекс хеш-таблицы сдвинут за верхнюю границу + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'TABLE_SIZE|capacity|hash|table\[' . +~~~ + +Для каждой ветви вычислить min/max индекса и размер массива; проверить insert/find и переключение структур. + +**Уязвимый вариант:** + +**DEF CON / bisbee, код + header.** Формула остаток по TABLE_SIZE плюс один +используется для массива из TABLE_SIZE элементов. + +**Исправление:** индекс в диапазоне [0, capacity), согласованный со всеми операциями; +проверить перенос между list и hashmap и счётчики при обновлении. + +**Проверка:** первый/последний bucket, collision, повторное обновление, переключение +представления. + +**Вариант A/D:** Основание и версия: [исходник/разбор 1](https://github.com/Nautilus-Institute/finals-2024/blob/f17456fed4ff40e6f4f1237ed4b82c242e52ec67/bisbee/src/service/src/main.rs); [исходник/разбор 2](https://github.com/Nautilus-Institute/finals-2024/blob/f17456fed4ff40e6f4f1237ed4b82c242e52ec67/bisbee/src/db/kv.c); [исходник/разбор 3](https://github.com/Nautilus-Institute/finals-2024/blob/f17456fed4ff40e6f4f1237ed4b82c242e52ec67/bisbee/src/db/kv.h); [исходник/разбор 4](https://github.com/Nautilus-Institute/finals-2024/blob/f17456fed4ff40e6f4f1237ed4b82c242e52ec67/bisbee/src/db/kv_hashmap.c); [исходник/разбор 5](https://github.com/Nautilus-Institute/finals-2024/blob/f17456fed4ff40e6f4f1237ed4b82c242e52ec67/bisbee/src/db/kv_hashmap.h); [исходник/разбор 6](https://github.com/Nautilus-Institute/finals-2024/blob/f17456fed4ff40e6f4f1237ed4b82c242e52ec67/bisbee/src/db/kv_list.c). + +**Основание:** [первичный материал](https://github.com/Nautilus-Institute/finals-2024/blob/f17456fed4ff40e6f4f1237ed4b82c242e52ec67/bisbee/src/service/src/main.rs). + + + + + +## C-STRNCPY. strncpy может оставить строку без NUL + +**Поиск:** скрипт, правило C-STRNCPY. Запуск: python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain C-STRNCPY. Regex: strncpy. Наличие последующего NUL и фактическая ёмкость анализируются вручную; memcpy без проверки длины не является исправлением. + +**Уязвимый вариант:** strncpy при длинном входе не добавляет терминатор; последующее строковое API читает за буфером. + +~~~native +strncpy(out, input, sizeof out); +puts(out); +~~~ + +**Исправление:** Выбрать контракт: отклонять слишком длинный вход или явно обрезать с местом для NUL. Для бинарных данных передавать длину вместо строкового API. + +~~~native +size_t n = bounded_input_length; +if (n >= sizeof out) return ERROR; +memcpy(out, input, n); +out[n] = '\0'; +~~~ + +**Проверка:** Вход длиной capacity-1/capacity/capacity+1 и пустой не вызывает чтения за границей; тихое усечение не меняет identity. + +Первичная документация: [документация 1](https://pubs.opengroup.org/onlinepubs/9799919799/functions/strncpy.html). + + + + + +## C-COPY-LENGTH. Длина копирования берётся напрямую из strlen источника + +**Поиск:** правило сканера C-COPY-LENGTH. Точный контракт детектора: `--explain C-COPY-LENGTH`. Regex с лексическими исключениями: memcpy/memmove с простыми первыми двумя аргументами и strlen/strnlen непосредственно в выражении длины. Не доказывает отсутствие предшествующих проверок или фактические размеры буферов; одноимённые пользовательские API и макросы требуют проверки. + +**Уязвимый вариант:** + +~~~native +memcpy(dest, input, strlen(input) + 1); +~~~ + +**Исправление:** Перед копированием проверьте доступную для чтения длину источника и ёмкость назначения, включая завершающий символ и переполнение арифметики. + +~~~native +size_t n = validated_length; +if (n >= capacity) return ERROR; +memcpy(dest, input, n + 1); +~~~ + +**Проверка:** Проверьте пустой ввод, границы ёмкости, отсутствие завершающего символа и переполнение; по возможности используйте санитайзеры. + +[Первичный источник 1](https://pubs.opengroup.org/onlinepubs/9799919799/functions/memcpy.html) diff --git a/docs/vulnerabilities/c-cpp.md b/docs/vulnerabilities/c-cpp.md new file mode 100644 index 0000000..814c7fc --- /dev/null +++ b/docs/vulnerabilities/c-cpp.md @@ -0,0 +1,824 @@ +# C / C++: find, fix and verify + +English | [Русский](c-cpp-RU.md) + +[Catalog](README.md) · [Scanner](../offline-scanner.md) · [Patch verification](../patch-validation.md) + +28 sections. Each follows **Search → Vulnerable example → Fix → Verification**. +Run `rg` from a local service checkout; searches only read files. Derive the actor/owner from a verified session, not request data. Adapt examples to the actual API and contract. + +## Contents + +- [C-BOUNDS — Unbounded C/C++ copy](#c-bounds) +- [C-FORMAT — Variable used as a format string](#c-format) +- [C-SHELL — C/C++ shell execution](#c-shell) +- [C-PRNG — Ordinary PRNG/LCG near a possible secret](#c-prng) +- [C-SNPRINTF-FORMAT — Variable format in bounded printf](#c-snprintf-format) +- [C-RECV-TERMINATOR — recv/read result used as an index](#c-recv-terminator) +- [C-ATOI — atoi without checked conversion](#c-atoi) +- [C-REALLOC — Overwriting the only pointer with realloc](#c-realloc) +- [C-SIZE-OVERFLOW — Size arithmetic overflow](#c-size-overflow) +- [CPP-LIFETIME — A pointer or view outlives its owner](#cpp-lifetime) +- [C-PARTIAL-IO — TCP does not preserve message boundaries](#c-partial-io) +- [C-SIGNED-LENGTH — Signed lengths become huge size_t values](#c-signed-length) +- [C-DOUBLE-FREE — Multiple owners free the same object](#c-double-free) +- [C-UNINITIALIZED — Exposing padding or uninitialized tails](#c-uninitialized) +- [C-TEMPFILE-RACE — Temporary filename without atomic creation](#c-tempfile-race) +- [C-JIT-RETURN — Not every JIT function path terminates](#c-jit-return) +- [C-HEADER-SECRET — A special header branch changes a secret](#c-header-secret) +- [C-OBJECT-TOCTOU — Re-reading mutable references after authorization](#c-object-toctou) +- [C-EXEC-FAILURE — Failed exec leaves a child on the server path](#c-exec-failure) +- [CPP-CACHED-LIFETIME — Cached pointers survive object destruction](#cpp-cached-lifetime) +- [C-BLOCK-TAIL — Four-byte block processing corrupts the tail](#c-block-tail) +- [C-ALLOC-FAILURE — Allocation failure becomes a NULL write](#c-alloc-failure) +- [C-FD-NUL — Descriptor leaks amplify a read_line off-by-one](#c-fd-nul) +- [C-REENTRANCY-AUTH — A callback runs between authorization and signing](#c-reentrancy-auth) +- [C-BUILTIN-TYPES — One builtin overload omits argument-type checks](#c-builtin-types) +- [C-HASH-INDEX — Hash-table indices exceed the upper boundary](#c-hash-index) +- [C-STRNCPY — strncpy may omit NUL termination](#c-strncpy) +- [C-COPY-LENGTH — Copy length comes directly from source strlen](#c-copy-length) + + + +## C-BOUNDS. Unbounded C/C++ copy + +**Search:** scanner rule C-BOUNDS. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain C-BOUNDS` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries. + +**Vulnerable example:** + +~~~c +strcpy(destination, source); +~~~ + +**Fix:** Check length/capacity before copying and check snprintf's result; mechanical strncpy replacement is insufficient. + +~~~c +size_t n = strlen(source); +if (n >= capacity) return ERROR; +memcpy(destination, source, n + 1); +~~~ + +**Verification:** Test empty, boundary and oversized input; use ASan/UBSan where available. + +
+Expanded example and limitations + +```c +/* Vulnerable: capacity and available source length are unchecked. */ +char dst[64]; +memcpy(dst, src, client_len); +dst[client_len] = '\0'; +``` + +**Patch for a protocol field defined as a C string without embedded NUL:** + + + +```c +#include +#include +#include + +bool copy_text(char *dst, size_t capacity, const char *src, + size_t available, size_t requested) { + if (dst == NULL || src == NULL || capacity == 0) return false; + if (requested > available || requested >= capacity) return false; + if (memchr(src, '\0', requested) != NULL) return false; + memmove(dst, src, requested); + dst[requested] = '\0'; + return true; +} +``` + +available means bytes actually accessible, not the client's claimed size. Reject negative signed lengths **before** conversion to size_t. memmove permits overlap; failure leaves dst unchanged. The caller must handle false rather than transmit old buffer contents. + +**Check:** Empty string, capacity−1, capacity, insufficient source, zero capacity and embedded NUL; rejection leaves the buffer unchanged. Binary data may contain NUL and needs a different explicit-length contract. Silent strncpy truncation can corrupt identifiers or checker data. + +
+ + + +## C-FORMAT. Variable used as a format string + +**Search:** scanner rule C-FORMAT. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain C-FORMAT` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries. + +**Vulnerable example:** + +~~~c +printf(message); +~~~ + +**Fix:** Use a fixed format and checked arguments; pass explicit lengths for binary data. + +~~~c +printf("%s", message); +~~~ + +**Verification:** Percent characters print without interpreting directives. + +
+Expanded example and limitations + +```c +/* Vulnerable: message controls the format and argument interpretation. */ +printf(message); +``` + +**Patch when message is a valid NUL-terminated string:** + + + +```c +#include +#include + +bool write_message(FILE *out, const char *message) { + if (out == NULL || message == NULL) return false; + return fputs(message, out) != EOF; +} +``` + +Alternatively use fprintf(out, "%s", message) with a fixed format. For length-delimited network buffers use validated length and fwrite rather than assuming NUL termination. Handle write errors separately. + +**Check:** %s, %% and Unicode print literally; empty strings work; avoid extra newlines if the protocol forbids them. + +
+ + + +## C-SHELL. C/C++ shell execution + +**Search:** scanner rule C-SHELL. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain C-SHELL` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries. + +**Vulnerable example:** + +~~~c +system(command); +~~~ + +**Fix:** Use execve/posix_spawn with fixed program and validated argv; handle errors. + +~~~c +run_fixed_tool(validated_filename); // fixed executable + argv inside +~~~ + +**Verification:** Metacharacters are not interpreted by a shell. + + + +## C-PRNG. Ordinary PRNG/LCG near a possible secret + +**Search:** scanner rule C-PRNG. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain C-PRNG` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries. + +**Vulnerable example:** + +~~~c +srand((unsigned)time(NULL)); +token = rand(); +~~~ + +**Fix:** Use system CSPRNG/supported crypto and check results; ordinary non-security randomness may use a PRNG. + +~~~c +if (!fill_from_os_csprng(token, sizeof token)) return ERROR; // implement using supported OS/library API +~~~ + +**Verification:** No predictable seed/fallback exists; token format stays compatible. + +**A/D variant:** Access identifiers from a time-seeded LCG. **ENOWARS / piratesay, author write-up.** An identifier permitted user switching while its generator depended on startup time. + +**Patch:** System CSPRNG and server-side credential/user binding. A hidden constant seed is not a sound fix. **Test:** New IDs and old sessions according to migration policy; entropy failure without fallback. **Search:** C-PRNG; inspect custom generators manually. + +[source/write-up 1](https://github.com/enowars/enowars8-service-piratesay/blob/32973478dbe903d0a2446539ecbddf3b1c334e60/documentation/README.md); [source/write-up 2](https://github.com/enowars/enowars8-service-piratesay/blob/32973478dbe903d0a2446539ecbddf3b1c334e60/service_source/src/cli.c); [source/write-up 3](https://github.com/enowars/enowars8-service-piratesay/blob/32973478dbe903d0a2446539ecbddf3b1c334e60/service_source/src/session.c). + + + +## C-SNPRINTF-FORMAT. Variable format in bounded printf + +**Search:** scanner rule C-SNPRINTF-FORMAT. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain C-SNPRINTF-FORMAT` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries. + +**Vulnerable example:** + +~~~c +snprintf(out, capacity, message); +~~~ + +**Fix:** Use a fixed format; buffer limits do not secure untrusted format strings. Trace wrappers/macros. + +~~~c +snprintf(out, capacity, "%s", message); +~~~ + +**Verification:** Percent characters stay text, truncation is handled; legitimate wrappers may still match. + +**A/D variant:** Format strings in a 'safe' wrapper. **ENOWARS / piratesay, author write-up.** Bounded writes and filtering a few specifiers did not stop another layer interpreting user text as a format. + +**Patch:** Fixed format at the final sink, data passed separately; trace macro → wrapper → printf-family. **Test:** Literal percent signs and handled truncation. **Search:** C-FORMAT, C-SNPRINTF-FORMAT; arbitrary wrapper names are not recognized automatically. + +[source/write-up 1](https://github.com/enowars/enowars8-service-piratesay/blob/32973478dbe903d0a2446539ecbddf3b1c334e60/documentation/README.md); [source/write-up 2](https://github.com/enowars/enowars8-service-piratesay/blob/32973478dbe903d0a2446539ecbddf3b1c334e60/service_source/src/cli.c); [source/write-up 3](https://github.com/enowars/enowars8-service-piratesay/blob/32973478dbe903d0a2446539ecbddf3b1c334e60/service_source/src/session.c). + + + +## C-RECV-TERMINATOR. recv/read result used as an index + +**Search:** scanner rule C-RECV-TERMINATOR. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain C-RECV-TERMINATOR` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries. + +**Vulnerable example:** + +~~~c +n = recv(fd, buffer, sizeof buffer, 0); +buffer[n] = '\0'; +~~~ + +**Fix:** Reserve NUL space, handle negative/EOF results before indexing, and handle short reads. Correct code may still match. + +~~~c +ssize_t n = recv(fd, buffer, sizeof buffer - 1, 0); +if (n <= 0) return ERROR; +buffer[n] = '\0'; +~~~ + +**Verification:** Test errors, EOF, full buffer, short reads and normal messages. + + + +## C-ATOI. atoi without checked conversion + +**Search:** scanner rule C-ATOI. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain C-ATOI` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries. + +**Vulnerable example:** + +~~~c +int size = atoi(input); +~~~ + +**Fix:** Use checked conversion with end-pointer, range and errno validation; define the accepted numeric grammar. + +~~~c +// use strtol/strtoull with errno, end pointer, sign and application bounds checks +~~~ + +**Verification:** Empty, trailing junk, signs and overflow fail; permitted boundary values work. + +**Reference:** [primary source](https://cmu-sei.github.io/secure-coding-standards/sei-cert-c-coding-standard/rules/error-handling-err/err34-c/). + + + +## C-REALLOC. Overwriting the only pointer with realloc + +**Search:** scanner rule C-REALLOC. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain C-REALLOC` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries. + +**Vulnerable example:** + +~~~c +buffer = realloc(buffer, size); +~~~ + +**Fix:** Keep the original pointer until allocation succeeds; handle zero size and overflow according to the intended contract. + +~~~c +void *next = realloc(buffer, size); +if (next == NULL) { /* preserve buffer; handle error */ } +else { buffer = next; } +~~~ + +**Verification:** Allocation failure leaks no original allocation and does not cause invalid access. + +**Reference:** [primary source](https://cmu-sei.github.io/secure-coding-standards/sei-cert-c-coding-standard/recommendations/memory-management-mem/mem04-c/). + + + +## C-SIZE-OVERFLOW. Size arithmetic overflow + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'malloc|calloc|resize|reserve|sizeof|memcpy' . +~~~ + +Check SIZE_MAX and the application limit before multiplying/adding; check sign before casting. + +**Vulnerable example:** + +`malloc(count * sizeof(Item))` allocates less than the later copy requires after overflow. + +**Fix:** Checked multiplication/addition and actual capacity; handle zero and allocation failure separately. + +**Verification:** Zero, boundaries, product/sum overflow, negative inputs and existing buffers. + +
+Expanded example and limitations + +```c +/* Vulnerable: count * sizeof(Item) can overflow. */ +Item *items = malloc(count * sizeof(*items)); +``` + +**Patch for arithmetic and the agreed size limit:** + + + +```c +#include +#include +#include + +bool array_bytes(size_t count, size_t item_size, size_t max_bytes, size_t *out) { + if (out == NULL || item_size == 0) return false; + if (count > SIZE_MAX / item_size) return false; + size_t total = count * item_size; + if (total > max_bytes) return false; + *out = total; + return true; +} +``` + +Call this before malloc with sizeof(*items) and a contractual limit; check allocation success. Handle count zero explicitly: malloc(0) returning NULL does not alone imply failure. Never use out after rejection. Adding headers/terminators needs a separate addition check; this function checks only multiplication. + +**Check:** Zero, one, exact budget, budget overflow and products above SIZE_MAX; errors never copy into stale/NULL buffers. + +
+ + + +## CPP-LIFETIME. A pointer or view outlives its owner + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'c_str\(|string_view|span|return.*data|return.*&' . +~~~ + +Identify the data owner and destruction/reallocation points; inspect async callbacks and lambda captures. + +**Vulnerable example:** + +A temporary string's c_str or a local buffer's string_view is returned. + +**Fix:** Return an owning object/copy; transfer ownership through async completion. A view does not extend lifetime. + +**Verification:** Results survive return, later calls do not corrupt them, and async work retains data until completion. + +
+Expanded example and limitations + +```cpp +// Vulnerable: the temporary string dies before the returned pointer is used. +const char* make_label(const std::string& name) { + return (std::string("hello ") + name).c_str(); +} +``` + +**Patch: return an owning object, not a pointer into destroyed storage:** + + + +```cpp +#include + +std::string make_label(const std::string& name) { + return std::string("hello ") + name; +} +``` + +The caller stores std::string label = make_label(name). Its c_str may be passed to a synchronous API that does not retain the pointer past the string's lifetime. Async operations need ownership/copies. string_view alone neither prolongs lifetime nor fixes this issue. + +**Check:** Results remain valid after return and subsequent calls, including empty names and Unicode; async paths retain data through completion. + +
+ + + +## C-PARTIAL-IO. TCP does not preserve message boundaries + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'recv|read\(|send|write\(|Content-Length|length' . +~~~ + +Compare frame length with accumulated bytes and review short-read/write loops, EINTR and EOF. + +**Vulnerable example:** + +One recv is treated as a complete request, or a partial send causes the next frame to merge with a private response. + +**Fix:** Explicit framing, bounded accumulation, partial-operation handling and timeouts; retain the checker protocol. + +**Verification:** Byte-by-byte fragmentation, two coalesced frames, mid-frame EOF and normal messages. + + + +## C-SIGNED-LENGTH. Signed lengths become huge size_t values + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'ssize_t|size_t|uint32_t|int.*len|memcpy|recv' . +~~~ + +Trace every cast between reading/parsing and allocation/indexing. + +**Vulnerable example:** + +A negative read result or client integer is converted to unsigned before validation. + +**Fix:** Check errors, sign and range before conversion; verify source/destination capacity. + +**Verification:** read=-1, EOF, negative fields, maximum and normal payloads. + + + +## C-DOUBLE-FREE. Multiple owners free the same object + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'free\(|delete|unique_ptr|shared_ptr|goto.*fail' . +~~~ + +Trace success/error cleanup and ownership transfers; look for two shared_ptr instances built from one raw pointer. + +**Vulnerable example:** + +An error path and its caller both free an object, or reset destroys an object still in use. + +**Fix:** One explicit owner/RAII with explicit ownership transfer; clearing one alias does not repair others. + +**Verification:** Failure at every construction step, repeated cleanup and normal lifecycle. + + + +## C-UNINITIALIZED. Exposing padding or uninitialized tails + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'malloc|struct|send|write|sizeof|memcpy' . +~~~ + +Compare initialized fields with transmitted struct sizeof and padding. + +**Vulnerable example:** + +`send(fd, &record, sizeof record, ...)` exposes padding or previous contents. + +**Fix:** Explicit field/length serialization and initialized buffers; never use native layout as an implicit wire protocol. + +**Verification:** Different compiler/layout choices, short input and no uninitialized response bytes. + + + +## C-TEMPFILE-RACE. Temporary filename without atomic creation + +**Search:** scanner rule C-TEMPFILE-RACE. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain C-TEMPFILE-RACE` for details. Regex: tmpnam/tempnam/mktemp. Custom filename schemes, reopening after mkstemp and directory TOCTOU need manual review. + +Additional manual search for forms outside automatic coverage: + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'tmpnam|mktemp|access\(|stat\(|fopen|open\(' . +~~~ + +Trace existence-check → open and parent-directory permissions. + +**Vulnerable example:** + +A shared temporary filename is checked, then opened for overwrite through a replaced symlink. + +**Fix:** Create a private file atomically, retain its fd, check errors/modes and close/remove it on all paths. + +**Verification:** Concurrent operations get separate fds; existing files/symlinks are not overwritten. + +**Scanner example before:** + +~~~native +char name[L_tmpnam]; +tmpnam(name); +FILE *f = fopen(name, "w"); +~~~ + +**Fix template:** + +~~~native +char name[] = "/tmp/app-XXXXXX"; +int fd = mkstemp(name); +if (fd < 0) return ERROR; +unlink(name); +/* use fd; close(fd) on every exit */ +~~~ + +Primary documentation: [reference 1](https://pubs.opengroup.org/onlinepubs/9799919799/functions/mkstemp.html). + + + +## C-JIT-RETURN. Not every JIT function path terminates + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'return|emit|jit|compile|bytecode' . +~~~ + +Map function control-flow exits; a conditional return does not cover the other branch or fall-through. + +**Vulnerable example:** + +**Reference:** dcs, RuCTF author write-up: a conditional return was mistakenly considered sufficient and execution continued beyond the function. **Search:** Custom VMs/JITs/DSLs, searching for a return node rather than reachability analysis, and constants placed next to instructions. + +**Fix:** Control-flow analysis requiring every reachable exit to return a value or terminate with a defined error. Separate code/data and validate indices/types before generation. + +**Verification:** Both conditional branches, nesting, empty functions and normal computations. Disabling JIT entirely is acceptable only if the functional contract remains intact. + +**A/D variant:** Source and version: [source/write-up 1](https://github.com/HackerDom/ructf-finals-2023/blob/a7442769909e08c39716cb18d3d1c3a99324bbf8/writeups/dcs/README.md). + +**Reference:** [primary source](https://github.com/HackerDom/ructf-finals-2023/blob/a7442769909e08c39716cb18d3d1c3a99324bbf8/writeups/dcs/README.md). + + + +## C-HEADER-SECRET. A special header branch changes a secret + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'getenv|HTTP_USER_AGENT|SECRET_KEY|constructor' . +~~~ + +Read init/constructor and debug/test branches; client headers must not change keys. + +**Vulnerable example:** + +**Reference:** reversaar, saarCTF C-source analysis: a special HTTP_USER_AGENT-linked path modified SECRET_KEY. **Search:** Constructor/init hooks, header getenv, magic constants, debug/test/admin branches in release builds and hidden signing switches. + +**Fix:** Remove the unintended transition specifically; secret configuration must not depend on requests. Inspect startup code, not only routes. + +**Verification:** Different headers do not change keys, privileges or storage format; normal initialization survives. There is no scanner signature for the specific magic value; manually trace input-to-secret relationships. + +**A/D variant:** Source and version: [source/write-up 1](https://github.com/saarsec/saarctf-2024/blob/3a06d18974ca177c6dd251a11bdf9b4b334f382a/reversaar/service/src/array.c). + +**Reference:** [primary source](https://github.com/saarsec/saarctf-2024/blob/3a06d18974ca177c6dd251a11bdf9b4b334f382a/reversaar/service/src/array.c). + + + +## C-OBJECT-TOCTOU. Re-reading mutable references after authorization + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'background|fork|exec|open|read' . +~~~ + +Find repeated mutable-object reads after checks/external calls; compare object identity and snapshots. + +**Vulnerable example:** + +**RuCTF / memos, author write-up.** An external operation occurred between checking background access and reading it; another request could replace the selected object. + +**Fix:** Use the same validated snapshot/descriptor or atomically check its version before use. + +**Verification:** Barrier-controlled request interleaving and legitimate long-running operations. + +**A/D variant:** Source and version: [source/write-up 1](https://github.com/HackerDom/ructf-2023/blob/0cc333e44f2ba6908ff6c5d613146e3b00173315/writeups/memos/README.md). + +**Reference:** [primary source](https://github.com/HackerDom/ructf-2023/blob/0cc333e44f2ba6908ff6c5d613146e3b00173315/writeups/memos/README.md). + + + +## C-EXEC-FAILURE. Failed exec leaves a child on the server path + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'fork|execve|execvp|waitpid' . +~~~ + +Trace every fork/exec error and child termination, including oversized argument vectors. + +**Vulnerable example:** + +**RuCTF / memos, author write-up.** A child could continue server logic after execve failed. + +**Fix:** Check fork/exec/wait; on child-side exec failure close extra descriptors and terminate with failing _exit. + +**Verification:** Missing executables, excessive arguments and fork failure never create a second server. + +**A/D variant:** Source and version: [source/write-up 1](https://github.com/HackerDom/ructf-2023/blob/0cc333e44f2ba6908ff6c5d613146e3b00173315/writeups/memos/README.md). + +**Reference:** [primary source](https://github.com/HackerDom/ructf-2023/blob/0cc333e44f2ba6908ff6c5d613146e3b00173315/writeups/memos/README.md). + + + +## CPP-CACHED-LIFETIME. Cached pointers survive object destruction + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'cache|delete|free|flush|shared_ptr|weak_ptr' . +~~~ + +Identify the cached pointer's owner and destruction point; trace method calls after eviction. + +**Vulnerable example:** + +**RuCTF / perune, author write-up.** Subsequent cache traversal called a virtual method on a freed object. + +**Fix:** Explicit ownership, removal of every reference at destruction, safe handles/weak references or validated generation IDs. + +**Verification:** Different create/delete/flush orderings and available sanitizers; absence of a crash proves nothing by itself. + +**A/D variant:** Source and version: [source/write-up 1](https://github.com/HackerDom/ructf-2023/blob/0cc333e44f2ba6908ff6c5d613146e3b00173315/writeups/perune/readme.md). + +**Reference:** [primary source](https://github.com/HackerDom/ructf-2023/blob/0cc333e44f2ba6908ff6c5d613146e3b00173315/writeups/perune/readme.md). + + + +## C-BLOCK-TAIL. Four-byte block processing corrupts the tail + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'xor|chacha|uint32_t|length|remaining' . +~~~ + +Check one-to-three-byte remainders with a four-byte stride against actual allocation. + +**Vulnerable example:** + +**ECSC / Diese HSM, author write-up.** XOR crossed the end when length was not word-aligned. + +**Fix:** Complete blocks followed by a separately bounded tail; check alignment. + +**Verification:** Lengths 0–9, buffer boundaries, canaries and valid nonces. + +**A/D variant:** Source and version: [source/write-up 1](https://github.com/ECSC2024/ECSC2024-CTF-AD/blob/2a92e17384ad228072a84fb076a35066fe2ffeff/sources/Diese/README.md); [source/write-up 2](https://github.com/ECSC2024/ECSC2024-CTF-AD/blob/2a92e17384ad228072a84fb076a35066fe2ffeff/sources/Diese/webapp/src/classes/Utils.class.php); [source/write-up 3](https://github.com/ECSC2024/ECSC2024-CTF-AD/blob/2a92e17384ad228072a84fb076a35066fe2ffeff/sources/Diese/hsm/src/msg.c). + +**Reference:** [primary source](https://github.com/ECSC2024/ECSC2024-CTF-AD/blob/2a92e17384ad228072a84fb076a35066fe2ffeff/sources/Diese/README.md). + + + +## C-ALLOC-FAILURE. Allocation failure becomes a NULL write + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'malloc|calloc|alloc|memcpy' . +~~~ + +Trace NULL/allocation failures to the first write, including custom allocators and firmware address spaces. + +**Vulnerable example:** + +**ECSC / Diese HSM, author and source.** An allocator result was unchecked while address zero was accessible in firmware. + +**Fix:** Checked size arithmetic, message limits and allocation-failure handling across the entire chain. + +**Verification:** Failure at every allocation and truncated packets. + +**A/D variant:** Source and version: [source/write-up 1](https://github.com/ECSC2024/ECSC2024-CTF-AD/blob/2a92e17384ad228072a84fb076a35066fe2ffeff/sources/Diese/README.md); [source/write-up 2](https://github.com/ECSC2024/ECSC2024-CTF-AD/blob/2a92e17384ad228072a84fb076a35066fe2ffeff/sources/Diese/webapp/src/classes/Utils.class.php); [source/write-up 3](https://github.com/ECSC2024/ECSC2024-CTF-AD/blob/2a92e17384ad228072a84fb076a35066fe2ffeff/sources/Diese/hsm/src/msg.c). + +**Reference:** [primary source](https://github.com/ECSC2024/ECSC2024-CTF-AD/blob/2a92e17384ad228072a84fb076a35066fe2ffeff/sources/Diese/README.md). + + + +## C-FD-NUL. Descriptor leaks amplify a read_line off-by-one + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'read_line|open|close|fopen|fclose' . +~~~ + +Inspect descriptor closure on login failures and NUL writes when buffers are full. + +**Vulnerable example:** + +**ECSC / CookingNonna, author write-up.** Failed login leaked an fd while a terminator could be written beyond a full buffer. + +**Fix:** Unified cleanup for every failure; reserve NUL space, check read/EOF and compare open results with -1. + +**Verification:** Capacities 0/1/max, long lines and repeated failures without descriptor growth. + +**A/D variant:** Source and version: [source/write-up 1](https://github.com/ECSC2024/ECSC2024-CTF-AD/blob/2a92e17384ad228072a84fb076a35066fe2ffeff/sources/CookingNonna/README.md). + +**Reference:** [primary source](https://github.com/ECSC2024/ECSC2024-CTF-AD/blob/2a92e17384ad228072a84fb076a35066fe2ffeff/sources/CookingNonna/README.md). + + + +## C-REENTRANCY-AUTH. A callback runs between authorization and signing + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'callback|SignToken|Len|ByRef' . +~~~ + +Find user callbacks after ownership checks; determine whether they can mutate the signed arguments. + +**Vulnerable example:** + +**ICC / MaScroll, author write-up.** An overridable Len changed a reference argument after its owner check. + +**Fix:** Validate an immutable copy; do not invoke user code between verification and the sensitive operation. + +**Verification:** A callback changes the original, but only the checked copy is signed. + +**A/D variant:** Source and version: [source/write-up 1](https://github.com/CybersecNatLab/ICC2023-AD-CTF/blob/8ffa184ff2ce8f648258ed3c02ee2270e8e1c56c/sources/MaScroll/README.md). + +**Reference:** [primary source](https://github.com/CybersecNatLab/ICC2023-AD-CTF/blob/8ffa184ff2ce8f648258ed3c02ee2270e8e1c56c/sources/MaScroll/README.md). + + + +## C-BUILTIN-TYPES. One builtin overload omits argument-type checks + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'FastRand|CryptoRand|variant|overload|builtin' . +~~~ + +Compare every overload's argument types, including the common first argument and error paths. + +**Vulnerable example:** + +**ICC / MaScroll, author write-up.** One generator call form skipped type checks; the resulting memory error affected cryptographic state. + +**Fix:** Uniform type/arity/length validation for every overload, with correct ownership and buffers. + +**Verification:** Type/argument-count matrix; errors never modify RNG or signing state. + +**A/D variant:** Source and version: [source/write-up 1](https://github.com/CybersecNatLab/ICC2023-AD-CTF/blob/8ffa184ff2ce8f648258ed3c02ee2270e8e1c56c/sources/MaScroll/README.md). + +**Reference:** [primary source](https://github.com/CybersecNatLab/ICC2023-AD-CTF/blob/8ffa184ff2ce8f648258ed3c02ee2270e8e1c56c/sources/MaScroll/README.md). + + + +## C-HASH-INDEX. Hash-table indices exceed the upper boundary + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'TABLE_SIZE|capacity|hash|table\[' . +~~~ + +Calculate min/max indices and array size for every branch; inspect insert/find and representation changes. + +**Vulnerable example:** + +**DEF CON / bisbee, source and header.** A remainder modulo TABLE_SIZE plus one indexed a TABLE_SIZE-element array. + +**Fix:** Keep indices in [0, capacity), consistently across operations; review list/hashmap migration and update counters. + +**Verification:** First/last buckets, collisions, repeated updates and representation switching. + +**A/D variant:** Source and version: [source/write-up 1](https://github.com/Nautilus-Institute/finals-2024/blob/f17456fed4ff40e6f4f1237ed4b82c242e52ec67/bisbee/src/service/src/main.rs); [source/write-up 2](https://github.com/Nautilus-Institute/finals-2024/blob/f17456fed4ff40e6f4f1237ed4b82c242e52ec67/bisbee/src/db/kv.c); [source/write-up 3](https://github.com/Nautilus-Institute/finals-2024/blob/f17456fed4ff40e6f4f1237ed4b82c242e52ec67/bisbee/src/db/kv.h); [source/write-up 4](https://github.com/Nautilus-Institute/finals-2024/blob/f17456fed4ff40e6f4f1237ed4b82c242e52ec67/bisbee/src/db/kv_hashmap.c); [source/write-up 5](https://github.com/Nautilus-Institute/finals-2024/blob/f17456fed4ff40e6f4f1237ed4b82c242e52ec67/bisbee/src/db/kv_hashmap.h); [source/write-up 6](https://github.com/Nautilus-Institute/finals-2024/blob/f17456fed4ff40e6f4f1237ed4b82c242e52ec67/bisbee/src/db/kv_list.c). + +**Reference:** [primary source](https://github.com/Nautilus-Institute/finals-2024/blob/f17456fed4ff40e6f4f1237ed4b82c242e52ec67/bisbee/src/service/src/main.rs). + + + +## C-STRNCPY. strncpy may omit NUL termination + +**Search:** scanner rule C-STRNCPY. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain C-STRNCPY` for details. Regex: strncpy. Review later NUL termination and actual capacity; memcpy without length checks is not a fix. + +**Vulnerable example:** strncpy does not terminate sufficiently long input; later string APIs read beyond the buffer. + +~~~native +strncpy(out, input, sizeof out); +puts(out); +~~~ + +**Fix:** Choose reject-too-long or explicit bounded truncation with NUL space; use explicit lengths for binary data. + +~~~native +size_t n = bounded_input_length; +if (n >= sizeof out) return ERROR; +memcpy(out, input, n); +out[n] = '\0'; +~~~ + +**Verification:** Test empty/capacity-1/capacity/capacity+1; truncation cannot change identity. + +Primary documentation: [reference 1](https://pubs.opengroup.org/onlinepubs/9799919799/functions/strncpy.html). + + + +## C-COPY-LENGTH. Copy length comes directly from source strlen + +**Search:** scanner rule C-COPY-LENGTH. Use `--explain C-COPY-LENGTH` for the exact detector contract. Regex with lexical exclusions: memcpy/memmove with simple first two arguments and strlen/strnlen directly as length. Does not prove missing preceding checks or actual buffer sizes; custom same-named APIs and macros require review. + +**Vulnerable example:** + +~~~native +memcpy(dest, input, strlen(input) + 1); +~~~ + +**Fix:** Validate readable source length and destination capacity before copying, including terminator and arithmetic overflow. + +~~~native +size_t n = validated_length; +if (n >= capacity) return ERROR; +memcpy(dest, input, n + 1); +~~~ + +**Verification:** Test empty input, capacity boundaries, missing terminator and overflow using sanitizers where available. + +[Primary reference 1](https://pubs.opengroup.org/onlinepubs/9799919799/functions/memcpy.html) diff --git a/docs/vulnerabilities/configuration-RU.md b/docs/vulnerabilities/configuration-RU.md new file mode 100644 index 0000000..28db3fe --- /dev/null +++ b/docs/vulnerabilities/configuration-RU.md @@ -0,0 +1,1861 @@ + + +# Общие мисконфиги и границы доступа: поиск и исправление + +[English](configuration.md) | Русский + +[Вся база](README-RU.md) · [Сканер](../offline-scanner-RU.md) · [Проверка патча](../patch-validation-RU.md) + +64 разделов. Формат: **Поиск → Уязвимый вариант → Исправление → Проверка**. +Команды `rg` выполняются в корне локальной копии сервиса и только читают файлы. Субъект/владелец определяется по проверенной сессии, а не данным запроса. Примеры нужно адаптировать к реальным API и контракту. + +Автоматические находки — ограниченные синтаксические сигналы для проверки. AST-анализ не разрешает типы и не отслеживает данные между функциями; regex не заменяет парсер языка. Комментарии, строки и одноимённые пользовательские API могут давать совпадения. Проверьте фактическое исполнение, входные данные, авторизацию и границы доверия. + + + +## Содержание + +- [CFG-SECRET — Литерал секрета/default key](#cfg-secret) +- [CFG-DEBUG — Debug в конфигурации](#cfg-debug) +- [CFG-CORS — Широкая CORS-политика](#cfg-cors) +- [CFG-DOCKER-PRIV — Привилегированный контейнер](#cfg-docker-priv) +- [CFG-DOCKER-SOCKET — Docker socket доступен сервису](#cfg-docker-socket) +- [CFG-DOCKER-ROOT — Явный USER root](#cfg-docker-root) +- [CFG-WORLD-WRITE — Широкие права записи](#cfg-world-write) +- [CFG-NGINX-LIST — Листинг каталога nginx](#cfg-nginx-list) +- [CFG-NGINX-ALIAS — Проверить границы nginx alias](#cfg-nginx-alias) +- [CFG-POSTGRES-TRUST — PostgreSQL trust](#cfg-postgres-trust) +- [CFG-REDIS-PROTECTION — Отключён protected-mode Redis](#cfg-redis-protection) +- [TPL-RAW — Неэкранированный вывод шаблона](#tpl-raw) +- [SRC-MIXED-IDENTIFIER — Смешение Latin/Cyrillic/Greek в одном слове](#src-mixed-identifier) +- [SRC-BIDI-CONTROL — Управление направлением текста в исходнике](#src-bidi-control) +- [CFG-REDIS-ACL — Redis ACL-пользователь без пароля](#cfg-redis-acl) +- [CFG-MONGO-NOAUTH — MongoDB authorization явно отключена](#cfg-mongo-noauth) +- [CFG-CAPABILITIES — Широкие capabilities контейнера](#cfg-capabilities) +- [CFG-BUILD-SECRET — Секрет в ARG/ENV Dockerfile](#cfg-build-secret) +- [CFG-NGINX-AUTH-OFF — Вложенный location отключает auth_request](#cfg-nginx-auth-off) +- [CFG-FILE-MODE — Права конфигов, каталога данных и ACL](#cfg-file-mode) +- [CFG-BIND-MOUNT — Writable mount раскрывает хост или соседние данные](#cfg-bind-mount) +- [CFG-K8S-RBAC — ServiceAccount и wildcard RBAC](#cfg-k8s-rbac) +- [CFG-NGINX-LOCATION — Нормализация URI и разные location](#cfg-nginx-location) +- [CFG-STATIC-SECRETS — Static root публикует .git, backup, БД и логи](#cfg-static-secrets) +- [CFG-COOKIE-FLAGS — Явно ослабленные флаги session cookies](#cfg-cookie-flags) +- [CFG-TRUSTED-HEADERS — Backend доверяет клиентскому user/role/IP](#cfg-trusted-headers) +- [CFG-CACHE-AUTH — Общий HTTP cache сохраняет персональный ответ](#cfg-cache-auth) +- [CFG-DEBUG-ENDPOINT — Диагностика доступна как публичный API](#cfg-debug-endpoint) +- [CFG-ERROR-SECRET — Логи содержат credentials/тела приватных запросов](#cfg-error-secret) +- [CFG-RESOURCE-LIMITS — Лимиты тела, decompression и multipart](#cfg-resource-limits) +- [CFG-UPLOAD-EXEC — Upload становится исполняемым или active content](#cfg-upload-exec) +- [CFG-HTTP-PARSER — Proxy и backend расходятся в framing](#cfg-http-parser) +- [CFG-CORS-CREDENTIALS — CORS отражает Origin вместе с credentials](#cfg-cors-credentials) +- [CFG-RESET-TOKEN — Recovery/share token без purpose и одноразовости](#cfg-reset-token) +- [CFG-OBJECT-POLICY — Прямой доступ к объекту через альтернативный endpoint](#cfg-object-policy) +- [CFG-DEPLOYED-CONFIG — Проверен пример, запущен другой конфиг](#cfg-deployed-config) +- [CFG-MEDIA-CONVERTER — Загрузка ресурсов из медиадокумента](#cfg-media-converter) +- [CFG-FORMAT-TRANSITION — Инъекция через промежуточный YAML](#cfg-format-transition) +- [CFG-PRINCIPAL-CONTEXT — Клиент изменяет контекст авторизации](#cfg-principal-context) +- [CFG-AUTH-TOCTOU — TOCTOU и повторное использование ID](#cfg-auth-toctou) +- [CFG-CUSTOM-CRYPTO — Алгебраическая утечка самодельной криптографии](#cfg-custom-crypto) +- [CFG-SHARED-BACKEND-KEY — Один служебный credential для всех дочерних окружений](#cfg-shared-backend-key) +- [CFG-WINDOWS-NAMES — Имя файла имеет иной смысл в Windows](#cfg-windows-names) +- [CFG-PROXY-REDIRECT — Reverse proxy следует redirect внутрь доверенного сервиса](#cfg-proxy-redirect) +- [CFG-PROTOCOL-KEY — Вырожденное значение в криптопротоколе](#cfg-protocol-key) +- [CFG-AGGREGATE-KEY — Некорректная агрегация публичных ключей](#cfg-aggregate-key) +- [CFG-K8S-HOST — Контейнер разделяет host namespace](#cfg-k8s-host) +- [CFG-UNCONFINED — Отключён профиль seccomp/AppArmor](#cfg-unconfined) +- [CFG-PRIV-ESCALATION — Разрешено повышение привилегий процесса](#cfg-priv-escalation) +- [CFG-ACTUATOR — Spring Actuator публикует все endpoints](#cfg-actuator) +- [CFG-H2-CONSOLE — Веб-консоль H2 включена](#cfg-h2-console) +- [CFG-TLS-UPSTREAM — Proxy не проверяет TLS upstream](#cfg-tls-upstream) +- [CFG-SSH-EMPTY-PASSWORD — SSHD допускает пустой пароль](#cfg-ssh-empty-password) +- [CFG-SUDO-ALL — Неограниченный sudo без пароля](#cfg-sudo-all) +- [CFG-JWT-KEY-SELECTION — Недоверенный kid/jku выбирает ключ проверки](#cfg-jwt-key-selection) +- [CFG-SIGNED-REQUEST — Подпись не связана с действием или допускает повтор](#cfg-signed-request) +- [CFG-RATE-LIMIT-IDENTITY — Ключ rate limit выбирает отправитель](#cfg-rate-limit-identity) +- [CFG-TOKEN-REVOCATION — Смена пароля или роли не отзывает полномочия](#cfg-token-revocation) +- [CFG-FAIL-OPEN — Ошибка проверки превращается в разрешение](#cfg-fail-open) +- [CFG-LDAP-FILTER — Строковая сборка LDAP filter или DN](#cfg-ldap-filter) +- [CFG-CI-TRUST — Недоверенные данные и код пересекают границу CI](#cfg-ci-trust) +- [CFG-DOCKER-TCP — Docker daemon слушает на всех TCP-интерфейсах](#cfg-docker-tcp) +- [CFG-FLOATING-IMAGE — Явный тег образа latest](#cfg-floating-image) +- [TPL-AUTOESCAPE-OFF — Блок шаблона отключает автоматическое экранирование](#tpl-autoescape-off) + + + + + +## CFG-SECRET. Литерал секрета/default key + +**Поиск:** скрипт, правило CFG-SECRET. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain CFG-SECRET. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API. + +**Уязвимый вариант:** + +~~~text +JWT_SECRET = "development" +~~~ + +**Исправление:** Проверить, используется ли fallback; секрет из защищённого конфига. Ротация только с планом для текущих сессий/данных. + +~~~text +JWT_SECRET = load_existing_secret() +~~~ + +**Проверка:** Нет общего fallback; законные данные/сессии сохранены. + +**Вариант A/D:** Общий секрет подписи. **Основание:** lost_museum, авторский разбор RuCTF: фиксированный общий JWT key. +**Искать:** литералы ключей, defaults, одинаковые ключи разных ролей/команд. +Сканер: CFG-SECRET, частичное покрытие имён. + +**Патч:** собственный секрет через конфиг и явная политика ротации. +Нельзя просто сменить ключ и потерять все легитимные сессии. При временном +чтении старого ключа учитывать, что его компрометация остаётся действующей: +потребуется безопасная серверная миграция/перепроверка, а не бесконечный fallback. +**Тест:** новая и старая сессия по плану перехода, неверная подпись, срок, +назначение; не выводить ключ в логи. + +[исходник/разбор 1](https://github.com/HackerDom/ructf-finals-2023/blob/a7442769909e08c39716cb18d3d1c3a99324bbf8/writeups/lost_museum/README.md). + +**Вариант A/D:** Default key и смешение назначений токенов. **Основание:** explorers CTF Cup, наблюдения по config/auth/API. +В настройках есть буквальный jwt_key по умолчанию; env мог его заменить. +Один JWT-помощник используется для разных схем claims. Это повод проверить +границы, не воспроизведённый обход авторизации. + +**Патч:** обязательный конфиг ключа; проверять typ/purpose/audience и обязательные +поля на каждом принимающем маршруте. Нельзя трактовать отсутствие user_id как +валидного субъекта. **Тест:** токен общего доступа не становится auth-токеном +и наоборот; неверный/пустой subject отклоняется; штатный share работает. +Сканер: CFG-SECRET для литерала, назначение токена — ручной анализ. + +[исходник/разбор 1](https://github.com/C4T-BuT-S4D/ctfcup-2023-ad/blob/53d6b9b7369448ac6c5d7d8e9458f66b25271e8a/services/explorers/src/app/config.py); [исходник/разбор 2](https://github.com/C4T-BuT-S4D/ctfcup-2023-ad/blob/53d6b9b7369448ac6c5d7d8e9458f66b25271e8a/services/explorers/src/app/auth.py). + + + + + +## CFG-DEBUG. Debug в конфигурации + +**Поиск:** скрипт, правило CFG-DEBUG. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain CFG-DEBUG. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API. + +**Уязвимый вариант:** + +~~~text +DEBUG=true +~~~ + +**Исправление:** Отключить debug в игровом профиле; серверные логи без секретов. + +~~~text +DEBUG=false +~~~ + +**Проверка:** Ошибки не раскрывают консоль/stack trace. + + + + + +## CFG-CORS. Широкая CORS-политика + +**Поиск:** правило сканера CFG-CORS. Подробности: `--explain CFG-CORS`. Старый поиск wildcard в headers/config без определения типа. JS-токены дополнительно распознают default import/require cors с inline origin:true и credentials:true, строковыми ключами и учётом последних присваиваний. Наблюдаемые shadows/reassignments отключают новую подсказку. Вычисляемые ключи, переменные, wrappers, фактическая политика ответа и другие языки требуют ручной проверки. + +**Уязвимый вариант:** + +~~~text +Access-Control-Allow-Origin: * +~~~ + +**Исправление:** Явные разрешённые origins и Vary: Origin, если нужен cross-origin; auth/CSRF отдельно. Звёздочка сама по себе не обходит auth. + +~~~text +Access-Control-Allow-Origin: https://ui.example.invalid +~~~ + +**Проверка:** Разрешённый браузерный клиент работает; чужой origin не читает приватный ответ. + + + + + +## CFG-DOCKER-PRIV. Привилегированный контейнер + +**Поиск:** скрипт, правило CFG-DOCKER-PRIV. Запуск: python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain CFG-DOCKER-PRIV. Regex: privileged:true и cap_add с SYS_ADMIN/ALL, включая quoted JSON keys. Block capabilities покрывает CFG-CAPABILITIES; эффективный Docker/Kubernetes config проверить вручную. + +**Уязвимый вариант:** + +~~~text +privileged: true +~~~ + +**Исправление:** Определить необходимые capabilities; ограничивать только разрешённый собственный сервис, не инфраструктуру организаторов. + +~~~text +privileged: false +~~~ + +**Проверка:** Сервис/checker работает без лишних полномочий. + + + + + +## CFG-DOCKER-SOCKET. Docker socket доступен сервису + +**Поиск:** скрипт, правило CFG-DOCKER-SOCKET. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain CFG-DOCKER-SOCKET. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API. + +**Уязвимый вариант:** + +~~~text +- /var/run/docker.sock:/var/run/docker.sock +~~~ + +**Исправление:** Убрать ненужный mount после проверки зависимости и правил; не менять служебные контейнеры автоматически. + +~~~text +- app-data:/srv/data +~~~ + +**Проверка:** Штатная функция и разрешённые инструменты работают. + + + + + +## CFG-DOCKER-ROOT. Явный USER root + +**Поиск:** скрипт, правило CFG-DOCKER-ROOT. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain CFG-DOCKER-ROOT. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API. + +**Уязвимый вариант:** + +~~~text +USER root +~~~ + +**Исправление:** Подготовленный непривилегированный пользователь и права на необходимые каталоги; отсутствие USER правило не проверяет. + +~~~text +USER app +~~~ + +**Проверка:** Тома, порты, запись данных и restart работают. + + + + + +## CFG-WORLD-WRITE. Широкие права записи + +**Поиск:** скрипт, правило CFG-WORLD-WRITE. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain CFG-WORLD-WRITE. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API. + +**Уязвимый вариант:** + +~~~text +chmod -R 777 /srv/app +~~~ + +**Исправление:** Определить владельца/группу и минимальные права; без рекурсивной замены вслепую. + +~~~text +chmod 750 /srv/app +~~~ + +**Проверка:** Процесс пишет нужные данные; посторонние не меняют код. + + + + + +## CFG-NGINX-LIST. Листинг каталога nginx + +**Поиск:** скрипт, правило CFG-NGINX-LIST. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain CFG-NGINX-LIST. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API. + +**Уязвимый вариант:** + +~~~text +autoindex on; +~~~ + +**Исправление:** Отключить ненужный листинг, если он не является частью функциональности. + +~~~text +autoindex off; +~~~ + +**Проверка:** Загрузка файла работает; служебный каталог не раскрывается. + + + + + +## CFG-NGINX-ALIAS. Проверить границы nginx alias + +**Поиск:** скрипт, правило CFG-NGINX-ALIAS. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain CFG-NGINX-ALIAS. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API. + +**Уязвимый вариант:** + +~~~text +location /files { alias /srv/files/; } +~~~ + +**Исправление:** Согласовать location /files/ и alias /srv/files/; проверить нормализацию/auth. Корректный alias также даёт сигнал. + +~~~text +location /files/ { root /srv; } # verify mapping and auth +~~~ + +**Проверка:** Граничные URL не выходят из корня; старые URL работают. + + + + + +## CFG-POSTGRES-TRUST. PostgreSQL trust + +**Поиск:** скрипт, правило CFG-POSTGRES-TRUST. Запуск: python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain CFG-POSTGRES-TRUST. Regex: POSTGRES_HOST_AUTH_METHOD=trust, включая JSON; pg_hba local/host/hostssl/hostnossl/hostgssenc/hostnogssenc с trust, CIDR или отдельной IPv4-маской. Проверить порядок HBA и какие записи реально применяются. + +**Уязвимый вариант:** + +~~~text +POSTGRES_HOST_AUTH_METHOD: trust +~~~ + +**Исправление:** Поддержанный метод auth и согласованные credentials своего приложения; не менять сеть/аккаунты организаторов. + +~~~text +POSTGRES_HOST_AUTH_METHOD: scram-sha-256 +~~~ + +**Проверка:** Сервис подключается; неизвестные credentials не принимаются. + + + + + +## CFG-REDIS-PROTECTION. Отключён protected-mode Redis + +**Поиск:** скрипт, правило CFG-REDIS-PROTECTION. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain CFG-REDIS-PROTECTION. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API. + +**Уязвимый вариант:** + +~~~text +protected-mode no +~~~ + +**Исправление:** Проверить ACL/credentials/bind и необходимый доступ; инфраструктурные изменения сверить с правилами, не блокировать игровой трафик. + +~~~text +protected-mode yes +~~~ + +**Проверка:** Приложение подключается с нужными правами. + + + + + +## TPL-RAW. Неэкранированный вывод шаблона + +**Поиск:** скрипт, правило TPL-RAW. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain TPL-RAW. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API. + +**Уязвимый вариант:** + +~~~text +{{ message | safe }} +~~~ + +**Исправление:** Штатный экранированный вывод текста; для богатого HTML sanitizer и тест контекста. + +~~~text +{{ message }} +~~~ + +**Проверка:** Разметка пользователя — текст; штатная верстка сохранена. + + + + + +## SRC-MIXED-IDENTIFIER. Смешение Latin/Cyrillic/Greek в одном слове + +**Поиск:** скрипт, правило SRC-MIXED-IDENTIFIER. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain SRC-MIXED-IDENTIFIER. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API. + +**Уязвимый вариант:** + +~~~text +uuіd = input_value +~~~ + +**Исправление:** Проверить code points и все ссылки на переменную; дать различимые имена и использовать проверенное значение. Не переименовывать слепой заменой по файлу. + +~~~text +validated_uuid = parse_uuid(input_value) +~~~ + +**Проверка:** Ветвь валидации и потребитель используют одно значение; тест с недопустимым вводом. Совпадения в строках/комментариях могут быть безвредны. + +**Вариант A/D:** Unicode-двойник и использование непроверенного ID. **ENOWARS / replme, автор + патч.** Похожая буква в имени переменной оставляла +оригинальный UUID необработанным; файловая операция использовала его вместо +объекта, уже проверенного middleware. + +**Патч:** использовать ID из авторизованного объекта, однозначные имена переменных, +проверку имени файла/корня. **Тест:** другой query-ID не меняет разрешённый объект; +некорректный UUID отвергается. **Поиск:** SRC-MIXED-IDENTIFIER; +SRC-BIDI-CONTROL — дополнительная общая проверка, не факт об этом сервисе. + +[исходник/разбор 1](https://github.com/enowars/enowars8-service-replme/blob/3cdec50dd9a57f43f1c57f7b049319774a00e6c2/documentation/documentation/src/main.tex); [исходник/разбор 2](https://github.com/enowars/enowars8-service-replme/blob/3cdec50dd9a57f43f1c57f7b049319774a00e6c2/documentation/documentation/src/path-traversal.patch); [исходник/разбор 3](https://github.com/enowars/enowars8-service-replme/blob/3cdec50dd9a57f43f1c57f7b049319774a00e6c2/documentation/documentation/src/crc.patch); [исходник/разбор 4](https://github.com/enowars/enowars8-service-replme/blob/3cdec50dd9a57f43f1c57f7b049319774a00e6c2/service/backend/util/encoding.go); [исходник/разбор 5](https://github.com/enowars/enowars8-service-replme/blob/3cdec50dd9a57f43f1c57f7b049319774a00e6c2/service/backend/controller/repl.go); [исходник/разбор 6](https://github.com/enowars/enowars8-service-replme/blob/3cdec50dd9a57f43f1c57f7b049319774a00e6c2/service/image/service/user.go). + + + + + +## SRC-BIDI-CONTROL. Управление направлением текста в исходнике + +**Поиск:** скрипт, правило SRC-BIDI-CONTROL. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain SRC-BIDI-CONTROL. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API. + +**Уязвимый вариант:** + +~~~text +# direction ‮ marker +~~~ + +**Исправление:** Показать Unicode code points и реальный порядок токенов, убрать ненужные управляющие символы. Легитимный текст локализации проверить отдельно. + +~~~text +# explicit plain-text comment +~~~ + +**Проверка:** Реальный поток управления совпадает с отображением; символ не восстановился при копировании. + + + + + +## CFG-REDIS-ACL. Redis ACL-пользователь без пароля + +**Поиск:** скрипт, правило CFG-REDIS-ACL. Запуск: python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain CFG-REDIS-ACL. Regex выбирает строку user, затем ограниченный разбор полной физической строки до 8192 символов: lowercase user, один ASCII space перед непустым username, обычные spaces между модификаторами. on/off/reset и nopass/resetpass/>password/#64lowerhex учитываются по порядку; сигнал только когда обе итоговые flags явно true. Имена, пароли и key/channel patterns не считаются flags. Кавычки, escapes, внутренние tabs, selectors и неизвестные операции остаются ручными; длинная строка даёт partial. Это не эффективный ACL: строки/include/runtime, валидность grants, сила пароля и существующие соединения проверяются вручную. + +**Уязвимый вариант:** + +~~~text +user default on nopass ~* &* +@all +~~~ + +**Исправление:** Сначала подготовить именованного пользователя приложения с +отдельным сгенерированным credential и минимальными командами/ключами/каналами. +Передать credential клиентам защищённым способом, переключить их на явную +аутентификацию и проверить переподключение всех пулов. Только после этого +отключать ненужный `default`. Для сервиса, который должен сохранить `default`, +согласованно настроить его пароль и обновить клиентов вместо отключения. +Финальная строка после перехода клиентов на подготовленного пользователя `app`: + +~~~text +user default off +~~~ + +Само `off` запрещает новую аутентификацию, но уже аутентифицированные соединения +не обрывает. Их судьбу предусмотреть в переходе, сохранив административный доступ +и возможность отката. У `default on nopass` новое соединение уже аутентифицировано; +для именованного пользователя `nopass` допускает любой пароль при AUTH. +[Redis: ACL и поведение on/off](https://redis.io/docs/latest/operate/oss_and_stack/management/security/acl/). + +**Проверка:** Штатный клиент успешно проходит AUTH и переподключается; аноним +и соседний namespace не получают защищённые данные. Проверить команды, +транзакции, Pub/Sub и фоновые процессы, затем старые соединения и перезапуск. +Отсутствие CFG-REDIS-ACL означает только отсутствие распознанного сочетания +`on` + `nopass`, а не надёжный пароль или корректные полномочия. + +ACL-директивы применяются последовательно. `off` после `on`, `resetpass` +после `nopass` или `reset` меняют итог; `nopass` после добавления пароля вновь +разрешает вход без проверки пароля. `>password` и корректный `#` с 64 строчными +hex-символами снимают `nopass`. Даже токен `>` с пустым паролем его снимает: +исчезновение сигнала не является исправлением аутентификации. +`~nopass` — шаблон ключа, а не парольная директива. +[Реализация ACL Redis 7.2.7](https://github.com/redis/redis/blob/7.2.7/src/acl.c). + +Сканер разбирает ограниченное общее подмножество строк `redis.conf` и aclfile. +Полные токены и их порядок учитываются внутри одной строки; состояние между +строками и фактическая успешность загрузки не устанавливаются. Кавычки, +экранирование, внутренние TAB и selectors требуют ручного просмотра: +токенизация основного конфига и aclfile различается. Не дописывать inline +комментарий к ACL-строке: `#` может начинать токен хеша, а не комментарий. +Также проверить include, +`requirepass`, повторные определения и runtime `ACL SETUSER`/`ACL LOAD`. +[Парсер конфигурации Redis 7.2.7](https://github.com/redis/redis/blob/7.2.7/src/config.c). + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -o -e '(^[[:blank:]]*(user|aclfile|include|requirepass)[[:blank:]])|ACL[[:blank:]]+(SETUSER|LOAD|SAVE|GETUSER|LIST)' . +~~~ + +Команда выводит только имена директив и позиции, без аргументов с credentials. +Локально проследить загружаемые файлы и все изменения нужного пользователя. +В разрешённом окружении администратору сверить эффективные flags/команды/ключи/ +каналы через `ACL GETUSER app` и отдельную проверку нового подключения с верным +и неверным паролем. Ответ GETUSER содержит также хеши: не переносить их и поля +паролей в отчёт, логи и shell history. Наличие `requirepass` в одном файле +не доказывает, что оно действует в запущенном процессе. +[Redis: ACL GETUSER](https://redis.io/docs/latest/commands/acl-getuser/). + + + + + +## CFG-MONGO-NOAUTH. MongoDB authorization явно отключена + +**Поиск:** скрипт, правило CFG-MONGO-NOAUTH. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain CFG-MONGO-NOAUTH. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API. + +**Уязвимый вариант:** + +~~~text +security: + authorization: disabled +~~~ + +**Исправление:** Для своего сервиса подготовить роли/учётные данные до включения auth; приложению только нужная БД и действия. + +~~~text +security: + authorization: enabled +~~~ + +**Проверка:** Перезапуск, переподключение, обычные CRUD; анониму отказ. Не менять аккаунты организаторов. + +**Основание:** [первичный материал](https://www.mongodb.com/docs/manual/core/authorization/). + + + + + +## CFG-CAPABILITIES. Широкие capabilities контейнера + +**Поиск:** скрипт, правило CFG-CAPABILITIES. Запуск: python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain CFG-CAPABILITIES. Regex: cap_add или capabilities.add с SYS_ADMIN/ALL, flow/block list. capabilities.drop:[ALL] сам по себе не является выдачей прав. Это ограниченное текстовое окно, не YAML parser; вложенность, merge/anchor и применённый securityContext вручную. + +**Уязвимый вариант:** + +~~~text +cap_add: [SYS_ADMIN] +~~~ + +**Исправление:** У своего сервиса удалить лишние capabilities, вернуть только доказанно необходимые. Проверить uid, порты и права томов до выкладки. + +~~~text +cap_drop: [ALL] +~~~ + +**Проверка:** Запуск и checker после изменения; required syscall не сломан. Не применять к launcher/инфраструктуре организаторов. + +**Основание:** [первичный материал](https://docs.docker.com/engine/security/). + + + + + +## CFG-BUILD-SECRET. Секрет в ARG/ENV Dockerfile + +**Поиск:** скрипт, правило CFG-BUILD-SECRET. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain CFG-BUILD-SECRET. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API. + +**Уязвимый вариант:** + +~~~text +ARG API_TOKEN=example +~~~ + +**Исправление:** Build secret mount вместо ARG/ENV/слоя; уже опубликованный секрет заменить согласованно, удаление следующей инструкцией не очищает прошлый слой. + +~~~text +RUN --mount=type=secret,id=api_token build-with-secret +~~~ + +**Проверка:** Сборка без утечки в history/logs; runtime получает свой секрет отдельно. Команда в примере — placeholder. + +**Основание:** [первичный материал](https://docs.docker.com/build/building/secrets/). + + + + + +## CFG-NGINX-AUTH-OFF. Вложенный location отключает auth_request + +**Поиск:** скрипт, правило CFG-NGINX-AUTH-OFF. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain CFG-NGINX-AUTH-OFF. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API. + +**Уязвимый вариант:** + +~~~text +location /export/ { auth_request off; } +~~~ + +**Исправление:** Проверить effective location и одинаковую политику для download/export/internal redirect. Публичные пути оставлять по контракту. + +~~~text +location /export/ { auth_request /verify; } +~~~ + +**Проверка:** Авторизованный экспорт работает, анонимный/чужой — нет. Не менять сетевую схему. + +**Основание:** [первичный материал](https://nginx.org/en/docs/http/ngx_http_auth_request_module.html). + + + + + +## CFG-FILE-MODE. Права конфигов, каталога данных и ACL + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'chmod|chown|umask|setfacl|mode:|permissions' . +~~~ + +В локальном/разрешённом окружении проверить ls -ld для файла и всех родителей; на Linux также getfacl. Сопоставить uid/gid процесса. + +**Уязвимый вариант:** + +Секрет читается соседним пользователем или parent dir позволяет заменить защищённый файл. + +**Исправление:** Минимальные права файла и родителей, отдельный writable data dir, private temp; не делать chmod -R 777 и не ломать uid тома. + +**Проверка:** Приложение читает нужное/пишет данные после restart; посторонний local user доступа не получает. + + + + + +## CFG-BIND-MOUNT. Writable mount раскрывает хост или соседние данные + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'volumes:|bind|source:|target:|read_only|hostPath' . +~~~ + +Сопоставить Compose/K8s mount со своим runtime inventory: host source, container target, ro/rw и propagation. + +**Уязвимый вариант:** + +Приложение может менять код, конфиги или каталог хоста через ненужный writable mount. + +**Исправление:** Только необходимые пути, read-only где запись не нужна, отдельный data volume; сохранить runtime permissions. + +**Проверка:** Старт/запись/checker и restart работают; код/чужой каталог не меняется. + +**Основание:** [первичный материал](https://docs.docker.com/engine/storage/bind-mounts/). + + + + + +## CFG-K8S-RBAC. ServiceAccount и wildcard RBAC + +**Поиск:** скрипт, правило CFG-K8S-RBAC. Запуск: python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain CFG-K8S-RBAC. Regex: name:cluster-admin. Не связывает roleRef с subjects и не ищет эквивалентную wildcard роль; остальные RBAC случаи искать вручную. + +Дополнительный ручной поиск для непокрытых форм: + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'automountServiceAccountToken|serviceAccountName|ClusterRole|verbs:|resources:' . +~~~ + +Найти pod → serviceAccount → RoleBinding/ClusterRoleBinding; проверить доступ к secrets, exec и bind/escalate. + +**Уязвимый вариант:** + +Бизнес-pod получает административный token, хотя Kubernetes API не нужен. + +**Исправление:** Для своей управляемой установки — Role с минимальными правами и RoleBinding в нужном namespace. Проверить subjects, verbs, resources, names и полномочия impersonate/bind/escalate. Выключить ненужный automount; ограничения admission отдельно. + +**Проверка:** Runtime-пользователь выполняет только нужные операции, не читает чужие Secrets и не выдаёт права; приложение запускается. Не менять cluster организаторов. + +**Основание:** [первичный материал](https://kubernetes.io/docs/concepts/security/rbac-good-practices/). + + +**Сигнал сканера — пример до:** + +~~~config +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: ClusterRole + name: cluster-admin +~~~ + +**Шаблон исправления:** + +~~~config +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: Role + name: notes-read-config +~~~ + +Первичная документация: [документация 1](https://kubernetes.io/docs/reference/access-authn-authz/rbac/). + + + + + +## CFG-NGINX-LOCATION. Нормализация URI и разные location + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'location|alias|root|try_files|rewrite|proxy_pass' . +~~~ + +Для своего конфига пройти выбор exact/prefix/regex location и internal redirect; сравнить URI, увиденный backend. + +**Уязвимый вариант:** + +Auth проверяет один путь, proxy/filesystem получает иной после нормализации или fallback. + +**Исправление:** Однозначные маршруты/границы root и auth на реальном ресурсе; согласованные правила decoding между слоями. + +**Проверка:** Slash/encoding/normal path, regex location и fallback не меняют права. + +**Основание:** [первичный материал](https://nginx.org/en/docs/http/ngx_http_core_module.html). + + + + + +## CFG-STATIC-SECRETS. Static root публикует .git, backup, БД и логи + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'static|document_root|root |alias |send_from_directory|FileServer' . +~~~ + +Сверить содержимое именно public root, symlinks и fallback; поиск файлов: rg --files --hidden -g !.git. + +**Уязвимый вариант:** + +Из корня проекта раздаются config, backup.sql, SQLite/WAL, архивы или credentials. + +**Исправление:** Отдельный public build directory, приватное хранение вне него и authenticated download; не надеяться только на запрет одного расширения. + +**Проверка:** Assets работают, скрытые файлы/backup/ссылка наружу не выдаются. + +**Основание:** [первичный материал](https://cheatsheetseries.owasp.org/cheatsheets/File_Upload_Cheat_Sheet.html). + + + + + + + +## CFG-COOKIE-FLAGS. Явно ослабленные флаги session cookies + +**Поиск:** правило сканера CFG-COOKIE-FLAGS. Подробности: `--explain CFG-COOKIE-FLAGS`. Regex исключает комментарии/строки: обычные Django SESSION_COOKIE_HTTPONLY/SESSION_COOKIE_SECURE/CSRF_COOKIE_SECURE=false/0. Python AST: известный Flask config[index]/update/from_mapping с отключёнными session HttpOnly/Secure. JS-токены: default import express-session с inline cookie.httpOnly:false. Динамическая конфигурация и defaults проверяются вручную. JS secure:false сам по себе не новый сигнал; учитывайте HTTPS и HTTP-checker. + +Дополнительный ручной поиск форм, которые не покрывает автоматическое правило: + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'Set-Cookie|HttpOnly|SameSite|Secure|cookie.domain|cookie.path' . +~~~ + +Сопоставьте фактический Set-Cookie с топологией HTTP/TLS/proxy; Domain/Path не заменяют авторизацию. + +**Уязвимый вариант:** + +Приватные cookies передаются ненужным hosts/путям, без необходимости доступны JavaScript или исчезают из-за неверной настройки Secure. + +**Исправление:** Сохраняйте HttpOnly для сессионных cookies и используйте Secure, если согласованный транспорт сервиса поддерживает HTTPS; включение Secure при checker, работающем только по HTTP, требует согласованного изменения транспорта. + +**Проверка:** Скрипты не читают сессионные cookies; сессии работают по предусмотренному транспорту, а secure cookies не отправляются по незашифрованному соединению. + + +**Пример для сканера до исправления:** + +~~~config +SESSION_COOKIE_HTTPONLY = False +~~~ + +**Шаблон исправления:** + +~~~config +SESSION_COOKIE_HTTPONLY = True +~~~ + + + + + +## CFG-TRUSTED-HEADERS. Backend доверяет клиентскому user/role/IP + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'X-User|X-Role|X-Forwarded|Forwarded|Remote-User|X-Original' . +~~~ + +Проследить кто устанавливает/очищает заголовок и доступен ли backend в обход доверенного proxy. + +**Уязвимый вариант:** + +Приложение считает присланный X-User подтверждённой identity. + +**Исправление:** Прикладная проверка credential/trusted peer и очистка forwarded identity по реальной архитектуре; один секретный header не универсальный auth. + +**Проверка:** Прямой запрос и поддельный header не дают права; штатный proxy проходит. + + + + + +## CFG-CACHE-AUTH. Общий HTTP cache сохраняет персональный ответ + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'proxy_cache|Cache-Control|Vary|Authorization|Set-Cookie|cache_key' . +~~~ + +Сверить cache key, условия bypass и ответы с cookie/auth; сравнить два пользователя на одном URL. + +**Уязвимый вариант:** + +Приватный body кешируется только по URI и выдаётся другой сессии. + +**Исправление:** Не кешировать персональные ответы общим ключом; private/no-store по контракту либо полная изоляция контекста и корректная инвалидация. + +**Проверка:** A затем B на том же URL, logout/смена роли, штатный публичный cache. + + + + + +## CFG-DEBUG-ENDPOINT. Диагностика доступна как публичный API + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'actuator|swagger|debug|pprof|metrics|heapdump|console|env' . +~~~ + +Перечислить реально зарегистрированные endpoint и доступ к каждому; имя /health само по себе нормально. + +**Уязвимый вариант:** + +Env/heapdump/config console раскрывает секреты или позволяет изменить приложение. + +**Исправление:** Отключить ненужную диагностику своего сервиса либо прикладная авторизация; оставить требуемый health и monitoring организаторов. + +**Проверка:** Health/checker остаются, анонимный env/dump/control недоступен. + + + + + +## CFG-ERROR-SECRET. Логи содержат credentials/тела приватных запросов + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'logger|logging|console.log|print|Authorization|password|token' . +~~~ + +Найти логирование whole request/config/exception, debug trace и куда попадает журнал. + +**Уязвимый вариант:** + +Пароль, подпись или приватный body пишутся без необходимости и доступны через log endpoint/volume. + +**Исправление:** Структурные поля без секретов, redaction до сериализации, минимальный доступ/retention; сохранить полезные коды ошибок. + +**Проверка:** Ошибочные запросы диагностируются без секретных значений и stacktrace в API. + + + + + +## CFG-RESOURCE-LIMITS. Лимиты тела, decompression и multipart + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'bodyLimit|maxRequest|client_max_body_size|multipart|decompress|timeout' . +~~~ + +Сверить limit до чтения, после распаковки и на каждую часть/всё сообщение; приложение и proxy могут отличаться. + +**Уязвимый вариант:** + +Небольшой compressed input создаёт большое тело; число частей/заголовков не ограничено. + +**Исправление:** Бюджеты по контракту для фактических байтов, parts, времени и результата; cleanup при отказе. + +**Проверка:** Лимит±1, без Content-Length, compressed body, много частей и легитимный максимум. + + + + + +## CFG-UPLOAD-EXEC. Upload становится исполняемым или active content + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'upload|media|public|cgi|fastcgi|Content-Type|Content-Disposition' . +~~~ + +Сопоставить место записи, правила web server и mime браузера; имя/Content-Type клиента не доказательство типа. + +**Уязвимый вариант:** + +Загруженный документ исполняется сервером или открывается active HTML в origin приложения. + +**Исправление:** Приватное неисполняемое хранение, server filename, проверка типа и policy выдачи; для скачивания безопасные headers. + +**Проверка:** Upload/download и previews работают; файл не становится серверным кодом/чужим origin-сценарием. + +**Основание:** [первичный материал](https://cheatsheetseries.owasp.org/cheatsheets/File_Upload_Cheat_Sheet.html). + + + + + +## CFG-HTTP-PARSER. Proxy и backend расходятся в framing + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'Content-Length|Transfer-Encoding|http_parser|proxy_http_version|keepalive' . +~~~ + +Проверить версии HTTP parsers и политику противоречивых длины/кодирования; тестировать только изолированный стенд. + +**Уязвимый вариант:** + +Слои по-разному определяют конец запроса, следующий запрос попадает в иной контекст. + +**Исправление:** Совместимые исправленные parsers, единая строгая политика framing и отказ неоднозначным сообщениям; не пытаться чинить regex по payload. + +**Проверка:** Обычные keepalive/chunked, противоречивый framing и закрытие соединения без смешения ответов. + + + + + +## CFG-CORS-CREDENTIALS. CORS отражает Origin вместе с credentials + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'Access-Control-Allow-Origin|allow_credentials|origin:|credentials:|CORS' . +~~~ + +Сверить response к разрешённому и постороннему Origin; wildcard с credentials обычно блокируется браузером, reflection опаснее. + +**Уязвимый вариант:** + +Любой origin получает своё имя обратно и разрешение credentialed чтения приватного API. + +**Исправление:** Точная серверная allowlist origin, корректный Vary и credential policy; CORS не авторизует запросы вне браузера. + +**Проверка:** Штатный frontend работает; чужой/null origin не получает credentialed чтение. + + + + + +## CFG-RESET-TOKEN. Recovery/share token без purpose и одноразовости + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'reset|recover|invite|share|token|expires|used_at' . +~~~ + +Проследить выдачу/проверку токена и атомарность consume; сравнить login/share/reset audiences. + +**Уязвимый вариант:** + +Токен другого действия или уже использованный token повторно меняет доступ. + +**Исправление:** CSPRNG/подпись с purpose/resource/subject/expiry, одноразовый consume в транзакции где это требуется; сохранение legit share. + +**Проверка:** Повторное/параллельное использование, чужой объект/назначение, срок и штатная операция. + + + + + +## CFG-OBJECT-POLICY. Прямой доступ к объекту через альтернативный endpoint + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'owner|tenant|download|export|delete|share|attachment|job' . +~~~ + +Для одной сущности пройти все операции и вложенные пути, включая background jobs; ID непредсказуемый не значит разрешённый. + +**Уязвимый вариант:** + +UI/read защищены, export/download/delete обращаются по ID без проверки owner. + +**Исправление:** Единая resource policy на каждой операции, субъект из verified session; sharing сохранить явным правилом. + +**Проверка:** Два пользователя/tenant: своё можно, чужое нельзя по каждому endpoint. + +**Основание:** [первичный материал](https://cheatsheetseries.owasp.org/cheatsheets/Authorization_Cheat_Sheet.html). + + + + + +## CFG-DEPLOYED-CONFIG. Проверен пример, запущен другой конфиг + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'env_file|environment:|include|args:|command:|config|settings' . +~~~ + +Сопоставить entrypoint, includes, override-файлы и эффективную конфигурацию. Вывод конфигов может содержать секреты — читать локально. + +**Уязвимый вариант:** + +Исправили sample config, runtime получает небезопасный override из env/volume. + +**Исправление:** Менять реально используемый источник, проверить precedence и restart; секреты не добавлять в репозиторий. + +**Проверка:** После restart эффективное значение исправлено, старая копия не вернулась. + + + + + +## CFG-MEDIA-CONVERTER. Загрузка ресурсов из медиадокумента + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'ffmpeg|magick|convert|thumbnail' . +~~~ + +Проверить, какие дополнительные файлы/URL читает сам декодер после загрузки документа. + +**Уязвимый вариант:** + +**Основание:** bookster, авторский разбор RuCTF. Старый FFmpeg при создании +превью мог обрабатывать ссылки из загруженного медиаконтейнера. + +**Искать:** FFmpeg, ImageMagick, PDF/SVG/XML-конвертеры, thumbnail/preview, +встроенные playlist/URL; различать входной файл и дополнительные ресурсы, +которые парсер читает сам. Проверки URL только в HTTP-обработчике недостаточно. + +**Исправление:** исправленная совместимая сборка, явный разрешённый набор +протоколов/декодеров, ограниченные input/output и ресурсы процесса. Не отключать +предусмотренные форматы или превью целиком. Сетевой firewall не подменяет патч. + +**Проверка:** все разрешённые форматы, повреждённый файл, вложенная ссылка на +локальный ресурс, лимиты времени/памяти. + +**Вариант A/D:** Основание и версия: [исходник/разбор 1](https://github.com/HackerDom/ructf-finals-2023/blob/a7442769909e08c39716cb18d3d1c3a99324bbf8/writeups/bookster/README.md). + +**Основание:** [первичный материал](https://github.com/HackerDom/ructf-finals-2023/blob/a7442769909e08c39716cb18d3d1c3a99324bbf8/writeups/bookster/README.md). + + + + + +## CFG-FORMAT-TRANSITION. Инъекция через промежуточный YAML + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'yaml|unmarshal|safe_load|template' . +~~~ + +Проследить текст → шаблон → YAML → объект update; типизировать данные на каждой границе. + +**Уязвимый вариант:** + +**Основание:** lost_museum, авторский разбор RuCTF. Шаблон генерировал YAML, +который затем разбирался в map для операции MongoDB. + +**Искать:** форматирование структурированных документов строками, затем +unmarshal/parse и передача всех полей в БД. safe_load не исправляет добавление +нежелательных полей: это иной класс ошибки, чем небезопасные YAML-конструкторы. + +**Исправление:** типизированная структура → сериализатор; затем явная проекция полей +для update, owner/role только с сервера. Не давать клиенту менять структуру +MongoDB-операции. + +**Проверка:** переносы строк, двоеточия, вложенные поля и обычный +текст; изменение только разрешённого поля. + +**Вариант A/D:** Основание и версия: [исходник/разбор 1](https://github.com/HackerDom/ructf-finals-2023/blob/a7442769909e08c39716cb18d3d1c3a99324bbf8/writeups/lost_museum/README.md). + +**Основание:** [первичный материал](https://github.com/HackerDom/ructf-finals-2023/blob/a7442769909e08c39716cb18d3d1c3a99324bbf8/writeups/lost_museum/README.md). + + + + + +## CFG-PRINCIPAL-CONTEXT. Клиент изменяет контекст авторизации + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'userspace|principal|currentUser|tenant' . +~~~ + +Проследить каждую запись субъекта: DSL и параметры не должны менять server-auth context. + +**Уязвимый вариант:** + +**Основание:** scp, авторский разбор RuCTF: DSL позволял менять userspace, +использовавшийся для контроля видимости. +**Искать:** присваивания currentUser, userspace, principal, tenant из выражений, +параметров или промежуточного состояния; переключатели режима auth. + +**Исправление:** субъект запроса берётся из проверенной сессии, хранится отдельно от +изменяемого контекста DSL. Все чувствительные операции сверяют его серверную +версию. + +**Проверка:** выражение не меняет principal; собственные объекты доступны, +чужие скрыты при любом порядке выражений. + +**Вариант A/D:** Основание и версия: [исходник/разбор 1](https://github.com/HackerDom/ructf-finals-2023/blob/a7442769909e08c39716cb18d3d1c3a99324bbf8/writeups/scp/README.md). + +**Основание:** [первичный материал](https://github.com/HackerDom/ructf-finals-2023/blob/a7442769909e08c39716cb18d3d1c3a99324bbf8/writeups/scp/README.md). + + + + + +## CFG-AUTH-TOCTOU. TOCTOU и повторное использование ID + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'owner|tenant|middleware|await|UPDATE|DELETE' . +~~~ + +Найти ожидание/смену состояния между проверкой и записью; проверить owner/version в атомарном запросе. + +**Уязвимый вариант:** + +**Основание:** stalker, авторский разбор RuCTF. ORM-снимок прав создавался до +ожидания тела запроса; удаление и повторное создание записей меняло смысл ID. + +**Искать:** объект/список ID в middleware → await/I/O → запись без новой проверки; +кэшированные связи ORM; ID, уникальный лишь в части составного ключа. + +**Исправление:** условие владельца проверять атомарно в самом UPDATE/DELETE/SHARE; +транзакция/версия строки при необходимости, стабильная уникальность ID. +Миграцию схемы проводить с сохранением записей. + +**Проверка:** детерминированное чередование запросов: проверка → удаление/создание → +мутация; чужая запись не изменяется. Проверить rollback и параллельный штатный +сценарий. + +**Вариант A/D:** Основание и версия: [исходник/разбор 1](https://github.com/HackerDom/ructf-finals-2023/blob/a7442769909e08c39716cb18d3d1c3a99324bbf8/writeups/stalker/README.md). + +**Основание:** [первичный материал](https://github.com/HackerDom/ructf-finals-2023/blob/a7442769909e08c39716cb18d3d1c3a99324bbf8/writeups/stalker/README.md). + + + + + +## CFG-CUSTOM-CRYPTO. Алгебраическая утечка самодельной криптографии + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'encrypt|decrypt|matrix|modulus|nonce' . +~~~ + +Выписать зависимость вход/выход и где входит секрет; проверить сохраняемые алгебраические отношения с владельцем протокола. + +**Уязвимый вариант:** + +**Основание:** solaris, авторский разбор RuCTF: матричная схема сохраняла +математические зависимости, связанные с секретом. +**Искать:** авторские комбинации RSA/матриц/арифметики, неизменяемые +соотношения между входом и выходом, недостаточная случайность. + +**Исправление:** сначала определить контракт и математический источник утечки. +Для обычного шифрования/аутентификации — стандартная библиотечная конструкция +с правильным nonce и версией формата; у крипто-задачи это может потребовать +специального исправления алгоритма. **Не переносить уменьшение размера ключа +из challenge-specific решения в общий hardening.** + +**Проверка:** неизменённая функция для штатного клиента, старые данные и отсутствие +найденного инварианта. + +**Вариант A/D:** Основание и версия: [исходник/разбор 1](https://github.com/HackerDom/ructf-finals-2023/blob/a7442769909e08c39716cb18d3d1c3a99324bbf8/writeups/solaris/README.md). + +**Основание:** [первичный материал](https://github.com/HackerDom/ructf-finals-2023/blob/a7442769909e08c39716cb18d3d1c3a99324bbf8/writeups/solaris/README.md). + + + + + +## CFG-SHARED-BACKEND-KEY. Один служебный credential для всех дочерних окружений + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'API_KEY|apikey|credential|environment|token' . +~~~ + +Проследить выдачу общего ключа в дочерние окружения и проверку его resource/audience на backend. + +**Уязвимый вариант:** + +**ENOWARS / replme, автор.** Компрометация одного дочернего backend раскрывала +общий ключ доверия к другим. + +**Исправление:** минимальные полномочия и привязка credential к конкретному ресурсу; +не полагаться только на внутренний адрес. + +**Проверка:** credential окружения A +не авторизует действие в B. + +**Вариант A/D:** Основание и версия: [исходник/разбор 1](https://github.com/enowars/enowars8-service-replme/blob/3cdec50dd9a57f43f1c57f7b049319774a00e6c2/documentation/documentation/src/main.tex); [исходник/разбор 2](https://github.com/enowars/enowars8-service-replme/blob/3cdec50dd9a57f43f1c57f7b049319774a00e6c2/documentation/documentation/src/path-traversal.patch); [исходник/разбор 3](https://github.com/enowars/enowars8-service-replme/blob/3cdec50dd9a57f43f1c57f7b049319774a00e6c2/documentation/documentation/src/crc.patch); [исходник/разбор 4](https://github.com/enowars/enowars8-service-replme/blob/3cdec50dd9a57f43f1c57f7b049319774a00e6c2/service/backend/util/encoding.go); [исходник/разбор 5](https://github.com/enowars/enowars8-service-replme/blob/3cdec50dd9a57f43f1c57f7b049319774a00e6c2/service/backend/controller/repl.go); [исходник/разбор 6](https://github.com/enowars/enowars8-service-replme/blob/3cdec50dd9a57f43f1c57f7b049319774a00e6c2/service/image/service/user.go). + +**Основание:** [первичный материал](https://github.com/enowars/enowars8-service-replme/blob/3cdec50dd9a57f43f1c57f7b049319774a00e6c2/documentation/documentation/src/main.tex). + + + + + +## CFG-WINDOWS-NAMES. Имя файла имеет иной смысл в Windows + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'filename|basename|glob|FindFirstFile|ToLower' . +~~~ + +Сравнить имя в проверке/БД с фактическим Windows lookup: case, wildcard, trailing dot/space и streams. + +**Уязвимый вариант:** + +**ICC / MaScroll, автор.** Имена в БД и файловой системе расходились по +регистру и допустимым символам. + +**Исправление:** серверные storage ID, единая политика имён для фактической ОС, +проверка владельца. + +**Проверка:** регистр, wildcard/служебные символы, разделители; +старые файлы доступны. + +**Вариант A/D:** Основание и версия: [исходник/разбор 1](https://github.com/CybersecNatLab/ICC2023-AD-CTF/blob/8ffa184ff2ce8f648258ed3c02ee2270e8e1c56c/sources/MaScroll/README.md). + +**Основание:** [первичный материал](https://github.com/CybersecNatLab/ICC2023-AD-CTF/blob/8ffa184ff2ce8f648258ed3c02ee2270e8e1c56c/sources/MaScroll/README.md). + + + + + +## CFG-PROXY-REDIRECT. Reverse proxy следует redirect внутрь доверенного сервиса + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'proxy_pass|redirect|Location|logout|internal' . +~~~ + +Проследить redirect во внутреннем HTTP-клиенте и повторную проверку назначения; internal location сам по себе не auth backend. + +**Уязвимый вариант:** + +**ICC / NorthernFiles, автор.** Open redirect вместе с конфигурацией proxy +делал внутренний endpoint доступным по цепочке. + +**Исправление:** безопасный redirect и явный контракт proxy; внутренний выдающий токены +endpoint сам проверяет полномочия. + +**Проверка:** внешние/внутренние redirect и +штатный logout. + +**Вариант A/D:** Основание и версия: [исходник/разбор 1](https://github.com/CybersecNatLab/ICC2023-AD-CTF/blob/8ffa184ff2ce8f648258ed3c02ee2270e8e1c56c/sources/NorthernFiles/README.md). + +**Основание:** [первичный материал](https://github.com/CybersecNatLab/ICC2023-AD-CTF/blob/8ffa184ff2ce8f648258ed3c02ee2270e8e1c56c/sources/NorthernFiles/README.md). + + + + + +## CFG-PROTOCOL-KEY. Вырожденное значение в криптопротоколе + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'public_key|pubkey|group|identity|point' . +~~~ + +Проверить декодирование и принадлежность ключа допустимой группе, запрет вырожденных элементов по конкретному протоколу. + +**Уязвимый вариант:** + +**ICC / NorthernFiles, автор.** Допустимый по типу вход приводил согласование +ключа к тривиальному значению. + +**Исправление:** протокольная проверка элементов группы и вырожденных состояний; +использовать проверенную реализацию, где совместимо. + +**Проверка:** neutral/invalid elements, отрицательные сценарии и interop с клиентом. + +**Вариант A/D:** Основание и версия: [исходник/разбор 1](https://github.com/CybersecNatLab/ICC2023-AD-CTF/blob/8ffa184ff2ce8f648258ed3c02ee2270e8e1c56c/sources/NorthernFiles/README.md). + +**Основание:** [первичный материал](https://github.com/CybersecNatLab/ICC2023-AD-CTF/blob/8ffa184ff2ce8f648258ed3c02ee2270e8e1c56c/sources/NorthernFiles/README.md). + + + + + +## CFG-AGGREGATE-KEY. Некорректная агрегация публичных ключей + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'aggregate|coefficient|pubkey|subset' . +~~~ + +Сверить вычисление коэффициентов и proof-of-possession с выбранной схемой; оценить стоимость проверки наборов. + +**Уязвимый вариант:** + +**ICC / UberPendragon, автор.** Линейная функция коэффициентов не давала +ожидаемой защиты от rogue keys. + +**Исправление:** проверенная схема агрегации; при неизменяемом клиенте — обоснованная +проверка вырожденных наборов по конкретному протоколу с ограниченной стоимостью. + +**Проверка:** обычные группы, повторяющиеся ключи, вырожденный aggregate и нагрузка. + +**Вариант A/D:** Основание и версия: [исходник/разбор 1](https://github.com/CybersecNatLab/ICC2023-AD-CTF/blob/8ffa184ff2ce8f648258ed3c02ee2270e8e1c56c/sources/UberPendragon/README.md). + +**Основание:** [первичный материал](https://github.com/CybersecNatLab/ICC2023-AD-CTF/blob/8ffa184ff2ce8f648258ed3c02ee2270e8e1c56c/sources/UberPendragon/README.md). + + + + + +## CFG-K8S-HOST. Контейнер разделяет host namespace + +**Поиск:** скрипт, правило CFG-K8S-HOST. Запуск: python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain CFG-K8S-HOST. Regex: hostPID/hostIPC/hostNetwork:true, Compose pid/ipc/network_mode:host. Не анализирует admission policy или фактический pod. + +**Уязвимый вариант:** Доступ к namespaces хоста расширяет последствия компрометации workload. + +~~~config +hostPID: true +hostIPC: true +hostNetwork: true +~~~ + +**Исправление:** Отключить ненужные host namespaces; требуемую связь реализовать в разрешённой topology игры и проверить probes/порты. + +~~~config +hostPID: false +hostIPC: false +hostNetwork: false +~~~ + +**Проверка:** Сервис и checker доступны; workload не видит процессы/IPC хоста и не получает неожиданные host-сокеты. + +Первичная документация: [документация 1](https://kubernetes.io/docs/concepts/security/pod-security-standards/). + + + + + +## CFG-UNCONFINED. Отключён профиль seccomp/AppArmor + +**Поиск:** скрипт, правило CFG-UNCONFINED. Запуск: python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain CFG-UNCONFINED. Regex: seccomp/apparmor=unconfined или :unconfined; Kubernetes type:Unconfined. Чужой YAML ключ type может дать ложный сигнал. + +**Уязвимый вариант:** Unconfined снимает слой ограничения системных вызовов/доступов контейнера. + +~~~config +security_opt: + - seccomp:unconfined + - apparmor:unconfined +~~~ + +**Исправление:** Вернуть стандартный или минимальный совместимый профиль; нужные исключения задавать узко. + +~~~config +security_opt: + - no-new-privileges:true +# Keep the runtime default seccomp/AppArmor profiles. +~~~ + +**Проверка:** Основные операции и checker работают; фактический контейнер применяет выбранный профиль. + +Первичная документация: [документация 1](https://docs.docker.com/engine/security/seccomp/). + + + + + +## CFG-PRIV-ESCALATION. Разрешено повышение привилегий процесса + +**Поиск:** скрипт, правило CFG-PRIV-ESCALATION. Запуск: python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain CFG-PRIV-ESCALATION. Regex: явное allowPrivilegeEscalation:true. Отсутствие поля, defaults и взаимодействие с privileged/CAP_SYS_ADMIN вручную. + +**Уязвимый вариант:** Разрешение privilege escalation оставляет пути через setuid/file capabilities. + +~~~config +allowPrivilegeEscalation: true +~~~ + +**Исправление:** Выключить allowPrivilegeEscalation, убрать privileged/CAP_SYS_ADMIN и лишние capabilities; проверить реально необходимые операции. + +~~~config +allowPrivilegeEscalation: false +~~~ + +**Проверка:** Нужные операции работают с ограничениями; runtime securityContext соответствует manifest. + +Первичная документация: [документация 1](https://kubernetes.io/docs/tasks/configure-pod-container/security-context/). + + + + + +## CFG-ACTUATOR. Spring Actuator публикует все endpoints + +**Поиск:** скрипт, правило CFG-ACTUATOR. Запуск: python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain CFG-ACTUATOR. Regex: плоское свойство или environment MANAGEMENT_ENDPOINTS_WEB_EXPOSURE_INCLUDE с *. Вложенный YAML и активные profiles искать вручную по endpoints/exposure/include. + +**Уязвимый вариант:** Широкая публикация management endpoints может раскрыть runtime/config или предоставить управление. + +~~~config +management.endpoints.web.exposure.include=* +~~~ + +**Исправление:** Оставить необходимые endpoints и ограничить доступ management plane; health details и пользовательский SecurityFilterChain проверить отдельно. + +~~~config +management.endpoints.web.exposure.include=health +~~~ + +**Проверка:** Checker/health работает; env, heapdump, loggers, shutdown и другие ненужные endpoints недоступны без разрешённого admin-доступа. + +Первичная документация: [документация 1](https://docs.spring.io/spring-boot/reference/actuator/endpoints.html). + + + + + +## CFG-H2-CONSOLE. Веб-консоль H2 включена + +**Поиск:** скрипт, правило CFG-H2-CONSOLE. Запуск: python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain CFG-H2-CONSOLE. Regex: spring.h2.console.enabled/SPRING_H2_CONSOLE_ENABLED=true. Вложенный YAML, aliases и разные profiles вручную. + +**Уязвимый вариант:** Консоль базы является отдельной административной поверхностью с собственным auth и JDBC-вводом. + +~~~config +spring.h2.console.enabled=true +~~~ + +**Исправление:** Отключить в runtime profile или выделить защищённый локальный admin-доступ; не отключать auth/CSRF всей программы ради консоли. + +~~~config +spring.h2.console.enabled=false +~~~ + +**Проверка:** Приложение работает с БД, endpoint консоли не доступен из игровой сети. + +Первичная документация: [документация 1](https://docs.spring.io/spring-boot/reference/data/sql.html#data.sql.h2-web-console). + + + + + +## CFG-TLS-UPSTREAM. Proxy не проверяет TLS upstream + +**Поиск:** скрипт, правило CFG-TLS-UPSTREAM. Запуск: python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain CFG-TLS-UPSTREAM. Regex: proxy_ssl_verify/grpc_ssl_verify off. Отсутствие директивы, inheritance и эффективные значения требуют просмотра полного nginx config. + +**Уязвимый вариант:** HTTPS до upstream без проверки сертификата не подтверждает, что это нужный backend. + +~~~config +proxy_ssl_verify off; +~~~ + +**Исправление:** Включить verify, доверенный CA и корректное имя/SNI; проверить цепочку и число промежуточных CA для своего upstream. + +~~~config +proxy_ssl_verify on; +proxy_ssl_trusted_certificate /etc/nginx/trusted-ca.pem; +proxy_ssl_server_name on; +proxy_ssl_name notes.internal; +~~~ + +**Проверка:** Правильный backend доступен, чужой сертификат/hostname отвергается без HTTP fallback. + +Первичная документация: [документация 1](https://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_ssl_verify). + + + + + +## CFG-SSH-EMPTY-PASSWORD. SSHD допускает пустой пароль + +**Поиск:** скрипт, правило CFG-SSH-EMPTY-PASSWORD. Запуск: python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain CFG-SSH-EMPTY-PASSWORD. Regex: PermitEmptyPasswords yes. Стандартное имя sshd_config поддержано; включаемые файлы произвольного имени перед сканом нужно явно учитывать вручную. + +**Уязвимый вариант:** При доступной password authentication аккаунт с пустым паролем может стать входом на хост. + +~~~config +PermitEmptyPasswords yes +~~~ + +**Исправление:** Запретить пустые пароли, проверить Match-блоки/PAM и аккаунты; до применения сохранить действующий канал доступа. + +~~~config +PermitEmptyPasswords no +~~~ + +**Проверка:** Разрешённый способ входа работает; пустой пароль не принимается в каждом применимом Match-контексте. + +Первичная документация: [документация 1](https://man.openbsd.org/sshd_config#PermitEmptyPasswords). + + + + + +## CFG-SUDO-ALL. Неограниченный sudo без пароля + +**Поиск:** скрипт, правило CFG-SUDO-ALL. Запуск: python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain CFG-SUDO-ALL. Regex: NOPASSWD:ALL. Aliases, include-файлы, wildcard argv и опасные разрешённые бинарники требуют ручного просмотра; файл sudoers распознаётся. + +**Уязвимый вариант:** NOPASSWD:ALL превращает выполнение кода runtime пользователя в доступ ко всем разрешённым Runas целям. + +~~~config +app ALL=(ALL:ALL) NOPASSWD: ALL +~~~ + +**Исправление:** Убрать sudo у сервисного пользователя; редкие операции вынести в минимальный helper без произвольных argv, shell и редактируемых зависимостей. + +~~~config +# Runtime user has no sudo grant. +# Provision required resources before service startup. +~~~ + +**Проверка:** Сервис работает без sudo; эффективный список прав runtime не содержит ALL или команды с выходом в shell. + +Первичная документация: [документация 1](https://www.sudo.ws/docs/man/sudoers.man/). + + + + + +## CFG-JWT-KEY-SELECTION. Недоверенный kid/jku выбирает ключ проверки + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'kid|jku|x5u|jwks|JWK|keyfunc|getKey|IssuerSigningKeyResolver' . +~~~ + +Проследить, откуда берутся issuer, URL набора ключей, локальный путь и ключ по kid. Сравнить доверенный registry с полями ещё не проверенного токена; проверить cache key по issuer и kid. + +**Уязвимый вариант:** Токен сам задаёт адрес JWKS/файл ключа или kid другого issuer, а валидатор принимает найденный материал как доверенный. + +**Исправление:** Закрепить допустимый issuer и его JWKS/ключи серверной конфигурацией; kid использовать только как точный индекс внутри этого issuer. Ограничить допустимые алгоритмы, типы ключей, кеш и ротацию. Не доверять встроенному jku/x5u. + +**Проверка:** Штатная ротация ключа работает; неизвестный kid, kid другого issuer и пользовательский URL не меняют доверенную область. Ошибка загрузки ключей не разрешает вход. + +Основание: [первичная документация/материал](https://www.rfc-editor.org/rfc/rfc8725.html). Описание и рецепт адаптации составлены для этой базы. + + + + + +## CFG-SIGNED-REQUEST. Подпись не связана с действием или допускает повтор + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'signature|signed_url|signedUrl|nonce|expires|timestamp|hmac|Content-Digest' . +~~~ + +Выписать точный набор подписываемых байтов: метод, путь, query, body, получатель, назначение, срок. Проверить нормализацию на signer/verifier и атомарность одноразового nonce. + +**Уязвимый вариант:** Верная подпись для чтения принимается при изменении данных, body можно заменить, либо одноразовый webhook/платёж применяют повторно. + +**Исправление:** Подписывать канонический контракт с action/purpose, получателем и необходимыми компонентами запроса; ограничить срок и clock skew. Для одноразовых операций атомарно фиксировать использованный nonce/idempotency key вместе с изменением. + +**Проверка:** Изменение метода/пути/body/получателя ломает проверку. Два одновременных повтора дают один эффект; штатные разрешённые retries возвращают согласованный результат. + +Основание: [первичная документация/материал](https://www.rfc-editor.org/rfc/rfc9421.html). Описание и рецепт адаптации составлены для этой базы. + + + + + +## CFG-RATE-LIMIT-IDENTITY. Ключ rate limit выбирает отправитель + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'rate.?limit|throttle|X-Forwarded-For|X-Real-IP|req\.ip|remote_addr|client_ip' . +~~~ + +Сопоставить ключ лимита с реальной границей доверия proxy. Проверить регистр/Unicode имени, маршрут-алиасы, отдельные воркеры, истечение счётчика и отказ backend. + +**Уязвимый вариант:** Лимит привязан к произвольному заголовку, одному из вариантов имени аккаунта или локальной памяти каждого worker; смена представления сбрасывает бюджет. + +**Исправление:** Нормализовать идентификатор одинаково с auth; принимать proxy headers только от доверенных hop. Применять атомарный общий бюджет по нужным субъектам/операциям, сохранив доступность легитимных общих IP. + +**Проверка:** Смена заголовка и формы идентификатора не создаёт новый бюджет; параллельные workers соблюдают лимит; допустимый checker traffic проходит. + +Основание: [первичная документация/материал](https://expressjs.com/en/guide/behind-proxies.html). Описание и рецепт адаптации составлены для этой базы. + + + + + +## CFG-TOKEN-REVOCATION. Смена пароля или роли не отзывает полномочия + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'logout|revoke|revocation|token_version|session_version|password_changed|security_stamp|refresh_token' . +~~~ + +Проследить login, refresh, logout, смену пароля, удаление аккаунта и изменение роли. Проверить, когда API перечитывает полномочия, как проверяется session/token version и какие кеши остаются. + +**Уязвимый вариант:** Удалённый администратор продолжает пользоваться старым JWT/session; отозванный refresh восстанавливает доступ. + +**Исправление:** Определить срок действия и отзыв по контракту: session version/denylist/короткие access tokens с проверяемым refresh. Ротацию refresh выполнять атомарно, инвалидировать связанные кеши. + +**Проверка:** После выбранного события отзыва старые access/refresh перестают давать доступ в обещанный срок на всех workers; штатный повтор входа работает. + +Основание: [первичная документация/материал](https://cheatsheetseries.owasp.org/cheatsheets/Session_Management_Cheat_Sheet.html). Описание и рецепт адаптации составлены для этой базы. + + + + + +## CFG-FAIL-OPEN. Ошибка проверки превращается в разрешение + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'catch|except|finally|recover|fallback|default.*allow|on_error|unwrap_or|Result' . +~~~ + +Для auth/signature/ACL-проверки проследить все исключения, timeout, nil/None/null и ветви cleanup. Проверить catch/finally, вызываемый следующий middleware и значение по умолчанию. + +**Уязвимый вариант:** Ошибка БД или валидатора возвращает allow/default principal; handler продолжает работу после записи 401; finally перезаписывает отказ. + +**Исправление:** По умолчанию отказывать до выполнения побочного эффекта. Различать отказ авторизации и временную недоступность, завершать цепочку обработки; ошибки логировать без секретов. + +**Проверка:** Искусственная ошибка/timeout auth backend, неверный тип и nil результат не дают данных и не изменяют состояние; штатная проверка проходит. + +Основание: [первичная документация/материал](https://cheatsheetseries.owasp.org/cheatsheets/Authorization_Cheat_Sheet.html). Описание и рецепт адаптации составлены для этой базы. + + + + + +## CFG-LDAP-FILTER. Строковая сборка LDAP filter или DN + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'ldap_search|ldap\.search|search_s|SearchFilter|DirContext|LdapName|Filter\.create|escape_filter' . +~~~ + +Проследить сборку search filter отдельно от DN: это разные грамматики. Проверить bind/search, wildcard, пустой пароль и выбор записи при нескольких совпадениях. + +**Уязвимый вариант:** Имя пользователя подставляют в LDAP expression как синтаксис; расширенный фильтр выбирает другую запись или несколько записей, первая из которых считается пользователем. + +**Исправление:** Использовать builder/parameter API либо escape именно для filter value; DN строить штатным DN builder. Требовать ровно ожидаемое совпадение и корректный bind, не считать поиск аутентификацией. + +**Проверка:** Специальные символы остаются частью значения; ноль/много совпадений и пустые credentials не дают вход; штатный пользователь проходит. + +Основание: [первичная документация/материал](https://www.rfc-editor.org/rfc/rfc4515.html). Описание и рецепт адаптации составлены для этой базы. + + + + + +## CFG-CI-TRUST. Недоверенные данные и код пересекают границу CI + +**Поиск:** вручную; отдельного правила сканера нет. CFG-CI-TRUST — идентификатор +раздела, а не автоматического сигнала. Найти workflows и composite actions: + +~~~bash +rg -n --hidden -g '*.yml' -g '*.yaml' -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'pull_request_target|workflow_run|permissions:|secrets\.|allow-unsafe-pr-checkout|checkout@|download-artifact@|head\.sha|git fetch|gh pr checkout|run:|script:|uses: \./' . +rg -n --hidden -g '*.yml' -g '*.yaml' -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e '\$\{\{[^}]*github\.(event|head_ref)' . +~~~ + +Открыть весь найденный job и вызываемые actions/reusable workflows. Проследить +последовательно: кто задаёт event field/ref/artifact → где значение становится +shell/JS-кодом, зависимостью или исполняемым файлом → какие permissions, secrets, +окружение и runner получает этот шаг. Само имя события не доказывает дефект. +Многострочные выражения, косвенные outputs и входы composite actions требуют +просмотра даже без совпадения команды поиска. + +**Уязвимый вариант:** первая граница — подстановка данных события прямо в +исходник `run`/`script`. Кавычки вокруг expression не защищают: выражение +подставляется до разбора shell. + +~~~yaml +- name: Show title + shell: bash + run: printf '%s\n' "${{ github.event.pull_request.title }}" +~~~ + +Реальный случай с `workflow_run.head_branch` разобран в +[GHSL-2025-099](https://securitylab.github.com/advisories/GHSL-2025-099_cross-platform-actions_action/). +Он относился к workflow репозитория action; это не утверждение об уязвимости +каждого проекта, использующего этот action. + +Вторая граница — исполнение PR-кода в привилегированном job: + +~~~yaml +on: pull_request_target +permissions: + contents: write +jobs: + checks: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + with: + ref: ${{ github.event.pull_request.head.sha }} + allow-unsafe-pr-checkout: true + - run: make test + env: + SERVICE_TOKEN: ${{ secrets.SERVICE_TOKEN }} +~~~ + +PR может менять не только тест, но и Makefile, install hook или локальный action. +У `workflow_run` аналогичная ошибка — скачать artifact предыдущего PR-run и +выполнить содержащийся в нём скрипт. Верный run ID и статус success подтверждают +происхождение результата, но не доверенность его содержимого. +[GitHub: доверие к pull_request_target и workflow_run](https://docs.github.com/en/actions/reference/security/securely-using-pull_request_target). +Реальная цепочка PR → привилегированный workflow → выполнение PR-кода описана +в [исследовании Gradio GHSL-2024-150 — GHSL-2024-157](https://securitylab.github.com/advisories/GHSL-2024-150_GHSL-2024-157_Gradio/). + +В `checkout` v7 опасный checkout fork PR при `pull_request_target` и при +`workflow_run`, чей `workflow_run.event` относится к `pull_request*`, по умолчанию +блокируется; пример выше явно отключает защиту. Это не защита любого +`workflow_run`. Защита перенесена в поддерживаемые major-ветки, +но старый закреплённый SHA сам не обновляется. Проверить фактический commit и +backport; получение кода через `git fetch`, сторонний action или artifact эта +проверка не заменяет. +[Изменение checkout](https://github.blog/changelog/2026-06-18-safer-pull_request_target-defaults-for-github-actions-checkout/). +Дополнительно проверить фактически применимую event policy репозитория: +её наличие и режим нельзя вывести только из workflow YAML. +[GitHub: event policy](https://docs.github.com/en/actions/reference/security/securely-using-pull_request_target#default-policy-for-pull_request_target). + +**Исправление:** для значения события сохранить разделение данных и кода: + +~~~yaml +- name: Show title + env: + PR_TITLE: ${{ github.event.pull_request.title }} + shell: bash + run: printf '%s\n' "$PR_TITLE" +~~~ + +Формат `printf` фиксирован, значение передаётся одним аргументом. Последующий +`eval`, `bash -c` или конструирование JS снова нарушат границу. Передача через +`with` безопасна лишь при соответствующем поведении принимающего action. +[GitHub: защита от script injection](https://docs.github.com/en/actions/reference/security/secure-use#good-practices-for-mitigating-script-injection-attacks). + +Для обычных проверок PR использовать непривилегированный workflow без secrets: + +~~~yaml +on: pull_request +permissions: + contents: read +jobs: + checks: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + with: + persist-credentials: false + - run: make test +~~~ + +`persist-credentials: false` отдельно не исправляет выполнение PR-кода с +привилегиями. Если нужны комментарии, метки или публикация отчёта, отделить +доверенный job: он принимает ограниченный JSON/text, проверяет размер, схему, +repo/run/head SHA и назначение PR, не исполняет и не импортирует artifact. +Скачивать данные отдельно от доверенного workspace. Тесты с private registry/API +потребуют отдельного дизайна; передавать их секреты произвольному PR нельзя. +`pull_request_target` только для меток/комментариев может быть обоснован. +[GitHub Security Lab: разделение стадий](https://securitylab.github.com/resources/github-actions-preventing-pwn-requests/). + +**Проверка:** статически подтвердить путь данных и минимальные эффективные права +с учётом настроек репозитория. В разрешённом тестовом CI проверить fork PR, +новый SHA после approval, название с кавычками/переводами строк как данные, +чужой run ID, неверную схему и oversized artifact. Штатные проверки и публикация +отчёта должны сохраниться; PR-код не получает secrets или постоянный self-hosted +runner с доступом к внутренним ресурсам. Эти workflows в рамках проверки базы +не запускались; офлайн-сканер не определяет effective permissions и связи Actions. + + + + + +## CFG-DOCKER-TCP. Docker daemon слушает на всех TCP-интерфейсах + +**Поиск:** правило сканера CFG-DOCKER-TCP. Точный контракт детектора: `--explain CFG-DOCKER-TCP`. Regex с лексическими исключениями: dockerd, после которого на той же строке стоят -H/--host tcp://0.0.0.0 или [::]. Не оценивает TLS-флаги, JSON-конфигурацию daemon, именованные интерфейсы и shell-подстановки; listener с TLS тоже требует проверки. + +**Уязвимый вариант:** + +~~~shell +dockerd -H tcp://0.0.0.0:2375 +~~~ + +**Исправление:** Предпочитайте локальный доступ к Docker. Если удалённое управление необходимо, используйте аутентифицированный зашифрованный транспорт и явно ограниченный интерфейс управления; не публикуйте его как командный UI. + +~~~shell +dockerd -H unix:///var/run/docker.sock +~~~ + +**Проверка:** Несогласованные LAN-клиенты не могут управлять Docker; согласованное администрирование остаётся доступным без раскрытия credentials. + +[Первичный источник 1](https://docs.docker.com/reference/cli/dockerd/#daemon-socket-option) + + + + + +## CFG-FLOATING-IMAGE. Явный тег образа latest + +**Поиск:** правило сканера CFG-FLOATING-IMAGE. Точный контракт детектора: `--explain CFG-FLOATING-IMAGE`. Regex с лексическими исключениями: Docker FROM или обычный YAML-ключ image с незаключённым в кавычки image:latest без digest. YAML в кавычках, образы без тега, другие изменяемые теги, подстановки ARG и фактическая архитектура требуют аудита модели deployment. + +**Уязвимый вариант:** + +~~~docker +FROM example.invalid/app:latest +~~~ + +**Исправление:** Зафиксируйте согласованную версию исходников и digest образа для нужной архитектуры; заполните offline-инвентарь образов и проверьте импортированные образы. + +~~~docker +FROM example.invalid/app@sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +~~~ + +**Проверка:** Повторные offline-запуски используют согласованные байты и архитектуру; не происходит неявного pull или отката к latest. + +[Первичный источник 1](https://docs.docker.com/reference/dockerfile/#from) + + + + + +## TPL-AUTOESCAPE-OFF. Блок шаблона отключает автоматическое экранирование + +**Поиск:** правило сканера TPL-AUTOESCAPE-OFF. Точный контракт детектора: `--explain TPL-AUTOESCAPE-OFF`. Regex с исключением HTML/Jinja-комментариев: блоки Jinja/Twig autoescape false и Django autoescape off. Не оценивает defaults шаблонизатора, внешние блоки и доверенность значений. + +**Уязвимый вариант:** + +~~~template +{% autoescape false %}{{ message }}{% endautoescape %} +~~~ + +**Исправление:** Сохраняйте автоматическое экранирование недоверенного текста; явно очищайте разрешённый HTML и проверяйте контекст вывода. + +~~~template +{{ message }} +~~~ + +**Проверка:** Пользовательские теги и атрибуты остаются данными; разрешённое форматирование продолжает работать. + +[Первичный источник 1](https://jinja.palletsprojects.com/en/stable/templates/#autoescape-overrides) diff --git a/docs/vulnerabilities/configuration.md b/docs/vulnerabilities/configuration.md new file mode 100644 index 0000000..5dbc11d --- /dev/null +++ b/docs/vulnerabilities/configuration.md @@ -0,0 +1,1583 @@ +# Configuration and trust boundaries: find, fix and verify + +English | [Русский](configuration-RU.md) + +[Catalog](README.md) · [Scanner](../offline-scanner.md) · [Patch verification](../patch-validation.md) + +64 sections. Each follows **Search → Vulnerable example → Fix → Verification**. +Run `rg` from a local service checkout; searches only read files. Derive the actor/owner from a verified session, not request data. Adapt examples to the actual API and contract. + +## Contents + +- [CFG-SECRET — Literal secret or default key](#cfg-secret) +- [CFG-DEBUG — Debug enabled in configuration](#cfg-debug) +- [CFG-CORS — Broad CORS policy](#cfg-cors) +- [CFG-DOCKER-PRIV — Privileged container](#cfg-docker-priv) +- [CFG-DOCKER-SOCKET — Docker socket exposed to a service](#cfg-docker-socket) +- [CFG-DOCKER-ROOT — Explicit Docker USER root](#cfg-docker-root) +- [CFG-WORLD-WRITE — Broad write permissions](#cfg-world-write) +- [CFG-NGINX-LIST — nginx directory listing](#cfg-nginx-list) +- [CFG-NGINX-ALIAS — Review nginx alias boundaries](#cfg-nginx-alias) +- [CFG-POSTGRES-TRUST — PostgreSQL trust](#cfg-postgres-trust) +- [CFG-REDIS-PROTECTION — Redis protected-mode disabled](#cfg-redis-protection) +- [TPL-RAW — Unescaped template output](#tpl-raw) +- [SRC-MIXED-IDENTIFIER — Mixed Latin/Cyrillic/Greek identifier](#src-mixed-identifier) +- [SRC-BIDI-CONTROL — Bidirectional text control in source](#src-bidi-control) +- [CFG-REDIS-ACL — Redis ACL user without a password](#cfg-redis-acl) +- [CFG-MONGO-NOAUTH — MongoDB authorization disabled](#cfg-mongo-noauth) +- [CFG-CAPABILITIES — Broad container capabilities](#cfg-capabilities) +- [CFG-BUILD-SECRET — Secret in Dockerfile ARG/ENV](#cfg-build-secret) +- [CFG-NGINX-AUTH-OFF — Nested nginx location disables auth_request](#cfg-nginx-auth-off) +- [CFG-FILE-MODE — Configuration, data-directory and ACL permissions](#cfg-file-mode) +- [CFG-BIND-MOUNT — Writable mounts expose hosts or neighboring data](#cfg-bind-mount) +- [CFG-K8S-RBAC — Workload bound to cluster-admin](#cfg-k8s-rbac) +- [CFG-NGINX-LOCATION — URI normalization and location selection](#cfg-nginx-location) +- [CFG-STATIC-SECRETS — Static roots expose .git, backups, databases and logs](#cfg-static-secrets) +- [CFG-COOKIE-FLAGS — Explicitly weakened session cookie flags](#cfg-cookie-flags) +- [CFG-TRUSTED-HEADERS — Backends trust client-supplied user, role or IP](#cfg-trusted-headers) +- [CFG-CACHE-AUTH — Shared HTTP caches retain personalized responses](#cfg-cache-auth) +- [CFG-DEBUG-ENDPOINT — Diagnostics become public APIs](#cfg-debug-endpoint) +- [CFG-ERROR-SECRET — Logs expose credentials or private request bodies](#cfg-error-secret) +- [CFG-RESOURCE-LIMITS — Body, decompression and multipart limits](#cfg-resource-limits) +- [CFG-UPLOAD-EXEC — Uploads become executable or active content](#cfg-upload-exec) +- [CFG-HTTP-PARSER — Proxy and backend disagree on framing](#cfg-http-parser) +- [CFG-CORS-CREDENTIALS — CORS reflects Origin with credentials](#cfg-cors-credentials) +- [CFG-RESET-TOKEN — Recovery or share tokens lack purpose or one-time use](#cfg-reset-token) +- [CFG-OBJECT-POLICY — Alternative endpoints expose an object directly](#cfg-object-policy) +- [CFG-DEPLOYED-CONFIG — Reviewing an example instead of effective configuration](#cfg-deployed-config) +- [CFG-MEDIA-CONVERTER — Media documents load additional resources](#cfg-media-converter) +- [CFG-FORMAT-TRANSITION — Injection through intermediate YAML](#cfg-format-transition) +- [CFG-PRINCIPAL-CONTEXT — Clients modify authorization context](#cfg-principal-context) +- [CFG-AUTH-TOCTOU — Authorization races and identifier reuse](#cfg-auth-toctou) +- [CFG-CUSTOM-CRYPTO — Algebraic leakage in custom cryptography](#cfg-custom-crypto) +- [CFG-SHARED-BACKEND-KEY — One credential spans all child environments](#cfg-shared-backend-key) +- [CFG-WINDOWS-NAMES — Filenames have different Windows meanings](#cfg-windows-names) +- [CFG-PROXY-REDIRECT — Reverse proxies follow redirects into trusted services](#cfg-proxy-redirect) +- [CFG-PROTOCOL-KEY — Degenerate values in cryptographic protocols](#cfg-protocol-key) +- [CFG-AGGREGATE-KEY — Incorrect public-key aggregation](#cfg-aggregate-key) +- [CFG-K8S-HOST — Container shares host namespaces](#cfg-k8s-host) +- [CFG-UNCONFINED — seccomp/AppArmor profile disabled](#cfg-unconfined) +- [CFG-PRIV-ESCALATION — Process privilege escalation allowed](#cfg-priv-escalation) +- [CFG-ACTUATOR — Spring Actuator exposes every endpoint](#cfg-actuator) +- [CFG-H2-CONSOLE — H2 web console enabled](#cfg-h2-console) +- [CFG-TLS-UPSTREAM — Proxy does not verify upstream TLS](#cfg-tls-upstream) +- [CFG-SSH-EMPTY-PASSWORD — SSHD permits empty passwords](#cfg-ssh-empty-password) +- [CFG-SUDO-ALL — Unrestricted passwordless sudo](#cfg-sudo-all) +- [CFG-JWT-KEY-SELECTION — Untrusted kid/jku selects verification keys](#cfg-jwt-key-selection) +- [CFG-SIGNED-REQUEST — Signatures are not bound to operations or preventable replays](#cfg-signed-request) +- [CFG-RATE-LIMIT-IDENTITY — Senders choose their rate-limit identity](#cfg-rate-limit-identity) +- [CFG-TOKEN-REVOCATION — Password or role changes fail to revoke access](#cfg-token-revocation) +- [CFG-FAIL-OPEN — Verification errors become permission](#cfg-fail-open) +- [CFG-LDAP-FILTER — LDAP filters or DNs built as strings](#cfg-ldap-filter) +- [CFG-CI-TRUST — Untrusted data and code cross CI trust boundaries](#cfg-ci-trust) +- [CFG-DOCKER-TCP — Docker daemon listens on every TCP interface](#cfg-docker-tcp) +- [CFG-FLOATING-IMAGE — Explicit latest image tag](#cfg-floating-image) +- [TPL-AUTOESCAPE-OFF — Template block disables autoescaping](#tpl-autoescape-off) + + + +## CFG-SECRET. Literal secret or default key + +**Search:** scanner rule CFG-SECRET. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain CFG-SECRET` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries. + +**Vulnerable example:** + +~~~text +JWT_SECRET = "development" +~~~ + +**Fix:** Check active fallbacks; read secrets from private configuration. Rotate with migration/rollback for sessions and data. + +~~~text +JWT_SECRET = load_existing_secret() +~~~ + +**Verification:** No shared fallback remains; legitimate sessions/data stay recoverable. + +**A/D variant:** Shared signing secret. **Reference:** lost_museum, RuCTF author write-up: a fixed shared JWT key. **Search:** Key literals, defaults and identical keys across roles/teams. Scanner: CFG-SECRET, with partial name coverage. + +**Patch:** An independently configured secret and explicit rotation policy. Do not simply change keys and invalidate every legitimate session. Temporarily accepting an old compromised key leaves its compromise active: use safe server-side migration/reverification, not indefinite fallback. **Test:** Old/new sessions according to migration policy, wrong signatures, expiry and purpose; never log keys. + +[source/write-up 1](https://github.com/HackerDom/ructf-finals-2023/blob/a7442769909e08c39716cb18d3d1c3a99324bbf8/writeups/lost_museum/README.md). + +**A/D variant:** Default keys and mixed token purposes. **Reference:** explorers, CTF Cup config/auth/API review. Configuration contained a default jwt_key literal that environment could override. One JWT helper served different claim schemas. This calls for boundary review; it is not a reproduced authorization bypass. + +**Patch:** Require key configuration; validate typ/purpose/audience and required fields at every receiver. A missing user_id is not a valid principal. **Test:** Share tokens cannot become authentication tokens or vice versa; invalid/empty subjects fail and legitimate sharing works. Scanner: CFG-SECRET for literals; purpose requires manual analysis. + +[source/write-up 1](https://github.com/C4T-BuT-S4D/ctfcup-2023-ad/blob/53d6b9b7369448ac6c5d7d8e9458f66b25271e8a/services/explorers/src/app/config.py); [source/write-up 2](https://github.com/C4T-BuT-S4D/ctfcup-2023-ad/blob/53d6b9b7369448ac6c5d7d8e9458f66b25271e8a/services/explorers/src/app/auth.py). + + + +## CFG-DEBUG. Debug enabled in configuration + +**Search:** scanner rule CFG-DEBUG. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain CFG-DEBUG` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries. + +**Vulnerable example:** + +~~~text +DEBUG=true +~~~ + +**Fix:** Disable runtime debug and keep private diagnostics without secrets. + +~~~text +DEBUG=false +~~~ + +**Verification:** Errors expose neither console nor stack trace. + + + +## CFG-CORS. Broad CORS policy + +**Search:** scanner rule CFG-CORS. Use `--explain CFG-CORS` for the exact detector contract. Legacy wildcard header/config heuristic (untyped). JS bounded tokens also detect default imported/required cors with inline origin:true and credentials:true, literal quoted keys and last-write-wins fields. Observed shadows/reassignments suppress the new hint. Computed keys, variables, wrappers, actual response policy and other languages remain manual. + +**Vulnerable example:** + +~~~text +Access-Control-Allow-Origin: * +~~~ + +**Fix:** Allowlist actual origins and use Vary: Origin where needed; authentication and CSRF remain separate. A wildcard alone is not an auth bypass. + +~~~text +Access-Control-Allow-Origin: https://ui.example.invalid +~~~ + +**Verification:** Authorized browsers work; unrelated origins cannot read private responses. + + + +## CFG-DOCKER-PRIV. Privileged container + +**Search:** scanner rule CFG-DOCKER-PRIV. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain CFG-DOCKER-PRIV` for details. Regex: privileged:true and cap_add with SYS_ADMIN/ALL, including quoted JSON keys. CFG-CAPABILITIES covers block capabilities; inspect effective Docker/Kubernetes config. + +**Vulnerable example:** + +~~~text +privileged: true +~~~ + +**Fix:** Identify minimum capabilities and change only authorized owned services, not organizer infrastructure. + +~~~text +privileged: false +~~~ + +**Verification:** Service/checker works without unnecessary privileges. + + + +## CFG-DOCKER-SOCKET. Docker socket exposed to a service + +**Search:** scanner rule CFG-DOCKER-SOCKET. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain CFG-DOCKER-SOCKET` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries. + +**Vulnerable example:** + +~~~text +- /var/run/docker.sock:/var/run/docker.sock +~~~ + +**Fix:** Remove unnecessary mounts after checking dependencies/rules; never alter unrelated containers automatically. + +~~~text +- app-data:/srv/data +~~~ + +**Verification:** Required service and approved management operations work. + + + +## CFG-DOCKER-ROOT. Explicit Docker USER root + +**Search:** scanner rule CFG-DOCKER-ROOT. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain CFG-DOCKER-ROOT` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries. + +**Vulnerable example:** + +~~~text +USER root +~~~ + +**Fix:** Prepare an unprivileged user and directory permissions; missing USER is not detected by this rule. + +~~~text +USER app +~~~ + +**Verification:** Volumes, ports, writes and restart work. + + + +## CFG-WORLD-WRITE. Broad write permissions + +**Search:** scanner rule CFG-WORLD-WRITE. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain CFG-WORLD-WRITE` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries. + +**Vulnerable example:** + +~~~text +chmod -R 777 /srv/app +~~~ + +**Fix:** Set intended owner/group and minimum modes; do not recursively replace permissions blindly. + +~~~text +chmod 750 /srv/app +~~~ + +**Verification:** Service can write data; others cannot change code. + + + +## CFG-NGINX-LIST. nginx directory listing + +**Search:** scanner rule CFG-NGINX-LIST. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain CFG-NGINX-LIST` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries. + +**Vulnerable example:** + +~~~text +autoindex on; +~~~ + +**Fix:** Disable listing unless it is required functionality. + +~~~text +autoindex off; +~~~ + +**Verification:** Downloads work; private directory contents are not enumerated. + + + +## CFG-NGINX-ALIAS. Review nginx alias boundaries + +**Search:** scanner rule CFG-NGINX-ALIAS. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain CFG-NGINX-ALIAS` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries. + +**Vulnerable example:** + +~~~text +location /files { alias /srv/files/; } +~~~ + +**Fix:** Align location /files/ with alias /srv/files/; review normalization/auth. Correct aliases also trigger review. + +~~~text +location /files/ { root /srv; } # verify mapping and auth +~~~ + +**Verification:** Boundary URLs stay inside the root; old public URLs work. + + + +## CFG-POSTGRES-TRUST. PostgreSQL trust + +**Search:** scanner rule CFG-POSTGRES-TRUST. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain CFG-POSTGRES-TRUST` for details. Regex: POSTGRES_HOST_AUTH_METHOD=trust including JSON; pg_hba local/host/hostssl/hostnossl/hostgssenc/hostnogssenc with trust and CIDR or separate IPv4 netmask. Inspect HBA order and actual matching entries. + +**Vulnerable example:** + +~~~text +POSTGRES_HOST_AUTH_METHOD: trust +~~~ + +**Fix:** Use supported auth and coordinated application credentials; do not change organizer accounts/network. + +~~~text +POSTGRES_HOST_AUTH_METHOD: scram-sha-256 +~~~ + +**Verification:** Application connects; unknown credentials fail. + + + +## CFG-REDIS-PROTECTION. Redis protected-mode disabled + +**Search:** scanner rule CFG-REDIS-PROTECTION. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain CFG-REDIS-PROTECTION` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries. + +**Vulnerable example:** + +~~~text +protected-mode no +~~~ + +**Fix:** Review ACL, credentials, bind and clients against game rules without blocking required traffic. + +~~~text +protected-mode yes +~~~ + +**Verification:** Application connects with minimum required permissions. + + + +## TPL-RAW. Unescaped template output + +**Search:** scanner rule TPL-RAW. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain TPL-RAW` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries. + +**Vulnerable example:** + +~~~text +{{ message | safe }} +~~~ + +**Fix:** Use normal escaped text output or a context-tested sanitizer for permitted HTML. + +~~~text +{{ message }} +~~~ + +**Verification:** User markup stays text and layout remains intact. + + + +## SRC-MIXED-IDENTIFIER. Mixed Latin/Cyrillic/Greek identifier + +**Search:** scanner rule SRC-MIXED-IDENTIFIER. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain SRC-MIXED-IDENTIFIER` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries. + +**Vulnerable example:** + +~~~text +uuіd = input_value +~~~ + +**Fix:** Inspect code points/references and use distinguishable names and the validated value; never blindly rename text. + +~~~text +validated_uuid = parse_uuid(input_value) +~~~ + +**Verification:** Validation and consumption use the same value; invalid input fails. Strings/comments may be harmless. + +**A/D variant:** Unicode lookalikes and unchecked identifiers. **ENOWARS / replme, author and patch.** A similar-looking variable letter left the original UUID unchecked; a filesystem operation used it rather than the middleware-authorized object. + +**Patch:** Use the authorized object's ID, unambiguous variable names and filename/root checks. **Test:** Another query ID cannot change the authorized object; malformed UUIDs fail. **Search:** SRC-MIXED-IDENTIFIER; SRC-BIDI-CONTROL is an additional general check, not a claim about this service. + +[source/write-up 1](https://github.com/enowars/enowars8-service-replme/blob/3cdec50dd9a57f43f1c57f7b049319774a00e6c2/documentation/documentation/src/main.tex); [source/write-up 2](https://github.com/enowars/enowars8-service-replme/blob/3cdec50dd9a57f43f1c57f7b049319774a00e6c2/documentation/documentation/src/path-traversal.patch); [source/write-up 3](https://github.com/enowars/enowars8-service-replme/blob/3cdec50dd9a57f43f1c57f7b049319774a00e6c2/documentation/documentation/src/crc.patch); [source/write-up 4](https://github.com/enowars/enowars8-service-replme/blob/3cdec50dd9a57f43f1c57f7b049319774a00e6c2/service/backend/util/encoding.go); [source/write-up 5](https://github.com/enowars/enowars8-service-replme/blob/3cdec50dd9a57f43f1c57f7b049319774a00e6c2/service/backend/controller/repl.go); [source/write-up 6](https://github.com/enowars/enowars8-service-replme/blob/3cdec50dd9a57f43f1c57f7b049319774a00e6c2/service/image/service/user.go). + + + +## SRC-BIDI-CONTROL. Bidirectional text control in source + +**Search:** scanner rule SRC-BIDI-CONTROL. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain SRC-BIDI-CONTROL` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries. + +**Vulnerable example:** + +~~~text +# direction ‮ marker +~~~ + +**Fix:** Inspect actual Unicode/token order and remove unnecessary controls; review legitimate localization separately. + +~~~text +# explicit plain-text comment +~~~ + +**Verification:** Rendered and actual flow agree; copying does not restore controls. + + + +## CFG-REDIS-ACL. Redis ACL user without a password + +**Search:** scanner rule CFG-REDIS-ACL. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain CFG-REDIS-ACL` for details. Regex selects user lines, then a bounded parser reads the physical line up to 8192 characters: lowercase user, one ASCII space before a nonempty username and ordinary modifier spaces. on/off/reset and nopass/resetpass/>password/#64lowerhex are processed in order; both final flags must be explicitly true. Names, passwords and key/channel patterns are not flags. Quotes, escapes, internal tabs, selectors and unknown operations need review; long lines are partial. This is not effective ACL analysis: inspect includes/runtime, grant validity, password strength and existing connections. + +**Vulnerable example:** + +~~~text +user default on nopass ~* &* +@all +~~~ + +**Fix:** First provision credentials and minimum commands/keys/channels for an app user; migrate clients and test AUTH/reconnect. Only then remove nopass or disable default. An empty > value is not a secure password. + +~~~text +user default off +~~~ + +off prevents new authentication but does not terminate already authenticated connections. Plan their treatment while preserving administration and rollback. default on nopass makes new connections already authenticated; a named user's nopass accepts any AUTH password. [Redis ACL on/off behavior](https://redis.io/docs/latest/operate/oss_and_stack/management/security/acl/). + +**Verification:** New app-user connections work before disabling default; new anonymous connections then fail. Check existing connections, namespaces, Pub/Sub and transactions. + +ACL directives apply in order. off after on, resetpass after nopass, or reset changes the result; nopass after adding a password re-enables unchecked authentication. >password and a valid # followed by 64 lowercase hex characters clear nopass. Even > with an empty password clears it: disappearance of the signal does not fix authentication. ~nopass is a key pattern, not a password directive. [Redis 7.2.7 ACL implementation](https://github.com/redis/redis/blob/7.2.7/src/acl.c). + +The scanner parses a bounded common subset of redis.conf/aclfile lines. It tracks complete tokens/order within one line, not cross-line state or successful loading. Quotes, escaping, internal tabs and selectors need review because main-config/aclfile tokenization differs. Do not append inline comments to ACL lines: # may begin a password-hash token. Also review includes, requirepass, repeated definitions and runtime ACL SETUSER/ACL LOAD. [Redis 7.2.7 config parser](https://github.com/redis/redis/blob/7.2.7/src/config.c). + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -o -e '(^[[:blank:]]*(user|aclfile|include|requirepass)[[:blank:]])|ACL[[:blank:]]+(SETUSER|LOAD|SAVE|GETUSER|LIST)' . +~~~ + +The command prints directive names/locations only, not credential arguments. Privately trace loaded files and every update to the selected user. An authorized administrator should inspect effective flags/commands/keys/channels with ACL GETUSER app and test a new connection with correct/incorrect credentials. GETUSER also returns hashes: never copy them/password fields into reports, logs or shell history. requirepass in one file does not prove it applies to the running process. [Redis ACL GETUSER](https://redis.io/docs/latest/commands/acl-getuser/). + + + +## CFG-MONGO-NOAUTH. MongoDB authorization disabled + +**Search:** scanner rule CFG-MONGO-NOAUTH. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain CFG-MONGO-NOAUTH` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries. + +**Vulnerable example:** + +~~~text +security: + authorization: disabled +~~~ + +**Fix:** Prepare application credentials and least-privilege roles before enabling auth on an owned service. + +~~~text +security: + authorization: enabled +~~~ + +**Verification:** Restart/reconnect and CRUD work; anonymous access fails. Do not alter organizer accounts. + +**Reference:** [primary source](https://www.mongodb.com/docs/manual/core/authorization/). + + + +## CFG-CAPABILITIES. Broad container capabilities + +**Search:** scanner rule CFG-CAPABILITIES. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain CFG-CAPABILITIES` for details. Regex: cap_add or capabilities.add with SYS_ADMIN/ALL in flow/block lists. capabilities.drop:[ALL] alone is not a grant. Bounded text windows are not YAML parsing; review nesting, merges/anchors and actual securityContext. + +**Vulnerable example:** + +~~~text +cap_add: [SYS_ADMIN] +~~~ + +**Fix:** Remove unnecessary capabilities only on owned services; retain proven requirements and verify user/port/volume permissions. + +~~~text +cap_drop: [ALL] +~~~ + +**Verification:** Startup/checker and required syscalls work; do not apply this to organizer launchers. + +**Reference:** [primary source](https://docs.docker.com/engine/security/). + + + +## CFG-BUILD-SECRET. Secret in Dockerfile ARG/ENV + +**Search:** scanner rule CFG-BUILD-SECRET. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain CFG-BUILD-SECRET` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries. + +**Vulnerable example:** + +~~~text +ARG API_TOKEN=example +~~~ + +**Fix:** Use build secret mounts instead of ARG/ENV/layers. Rotate published secrets deliberately; later deletion does not erase an earlier layer. + +~~~text +RUN --mount=type=secret,id=api_token build-with-secret +~~~ + +**Verification:** Build history/logs disclose no secret; runtime secrets are separate. The sample build command is a placeholder. + +**Reference:** [primary source](https://docs.docker.com/build/building/secrets/). + + + +## CFG-NGINX-AUTH-OFF. Nested nginx location disables auth_request + +**Search:** scanner rule CFG-NGINX-AUTH-OFF. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain CFG-NGINX-AUTH-OFF` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries. + +**Vulnerable example:** + +~~~text +location /export/ { auth_request off; } +~~~ + +**Fix:** Review location selection/inheritance and remove unintended auth bypass while preserving intended public endpoints. + +~~~text +location /export/ { auth_request /verify; } +~~~ + +**Verification:** Protected resources require authentication through every matching location; health/login works. + +**Reference:** [primary source](https://nginx.org/en/docs/http/ngx_http_auth_request_module.html). + + + +## CFG-FILE-MODE. Configuration, data-directory and ACL permissions + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'chmod|chown|umask|setfacl|mode:|permissions' . +~~~ + +In an authorized environment inspect ls -ld for the file and every parent; on Linux also inspect getfacl. Compare process uid/gid. + +**Vulnerable example:** + +Another local user can read secrets, or a writable parent permits replacing a protected file. + +**Fix:** Minimal file/parent permissions, separate writable data and private temporary storage; never chmod -R 777 or break volume ownership. + +**Verification:** The app reads required config and writes data after restart; unrelated local users gain no access. + + + +## CFG-BIND-MOUNT. Writable mounts expose hosts or neighboring data + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'volumes:|bind|source:|target:|read_only|hostPath' . +~~~ + +Match Compose/Kubernetes mounts to the authorized runtime inventory: host source, container destination, read/write mode and propagation. + +**Vulnerable example:** + +An unnecessary writable mount lets the application modify host code, configuration or directories. + +**Fix:** Only necessary paths, read-only where possible and separate data volumes; preserve required runtime permissions. + +**Verification:** Startup, writes, checker and restart work without changing code or unrelated directories. + +**Reference:** [primary source](https://docs.docker.com/engine/storage/bind-mounts/). + + + +## CFG-K8S-RBAC. Workload bound to cluster-admin + +**Search:** scanner rule CFG-K8S-RBAC. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain CFG-K8S-RBAC` for details. Regex: name:cluster-admin. Does not connect roleRef to subjects or find equivalent wildcard roles; inspect remaining RBAC manually. + +Additional manual search for forms outside automatic coverage: + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'automountServiceAccountToken|serviceAccountName|ClusterRole|verbs:|resources:' . +~~~ + +Trace pod → serviceAccount → RoleBinding/ClusterRoleBinding; review secrets, exec and bind/escalate permissions. + +**Vulnerable example:** + +A business pod receives an administrative token despite not needing Kubernetes API access. + +**Fix:** Use a least-privilege Role and namespaced RoleBinding; review subjects, verbs, resources, names and impersonate/bind/escalate. + +**Verification:** Runtime identity can perform only required operations, not read foreign Secrets or grant rights. + +**Reference:** [primary source](https://kubernetes.io/docs/concepts/security/rbac-good-practices/). + +**Scanner example before:** + +~~~config +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: ClusterRole + name: cluster-admin +~~~ + +**Fix template:** + +~~~config +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: Role + name: notes-read-config +~~~ + +Primary documentation: [reference 1](https://kubernetes.io/docs/reference/access-authn-authz/rbac/). + + + +## CFG-NGINX-LOCATION. URI normalization and location selection + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'location|alias|root|try_files|rewrite|proxy_pass' . +~~~ + +For the authorized configuration trace exact/prefix/regex locations and internal redirects; compare the URI the backend receives. + +**Vulnerable example:** + +Authorization checks one path while proxy/filesystem normalization or fallback selects another. + +**Fix:** Unambiguous routes/root boundaries and authorization on the actual resource; consistent decoding policies across layers. + +**Verification:** Slash/encoding variants, normal paths, regex locations and fallbacks never change permissions. + +**Reference:** [primary source](https://nginx.org/en/docs/http/ngx_http_core_module.html). + + + +## CFG-STATIC-SECRETS. Static roots expose .git, backups, databases and logs + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'static|document_root|root |alias |send_from_directory|FileServer' . +~~~ + +Inspect the actual public root, symlinks and fallback routes; locate files with rg --files --hidden -g !.git. + +**Vulnerable example:** + +The project root serves config, backup.sql, SQLite/WAL, archives or credentials. + +**Fix:** A separate public build directory, private storage outside it and authenticated downloads; blocking one extension is insufficient. + +**Verification:** Assets work; hidden files, backups and outward links are never served. + +**Reference:** [primary source](https://cheatsheetseries.owasp.org/cheatsheets/File_Upload_Cheat_Sheet.html). + + + +## CFG-COOKIE-FLAGS. Explicitly weakened session cookie flags + +**Search:** scanner rule CFG-COOKIE-FLAGS. Use `--explain CFG-COOKIE-FLAGS` for the exact detector contract. Regex with lexical exclusions: bare Django SESSION_COOKIE_HTTPONLY/SESSION_COOKIE_SECURE/CSRF_COOKIE_SECURE=false/0. Python AST: known Flask config subscript/update/from_mapping with disabled session HttpOnly/Secure. JS bounded tokens: default imported express-session with inline cookie.httpOnly:false. Dynamic configs/defaults remain manual. JS secure:false alone is not a new signal; HTTPS/checker compatibility must be reviewed. + +Additional manual search for forms outside automatic coverage: + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'Set-Cookie|HttpOnly|SameSite|Secure|cookie.domain|cookie.path' . +~~~ + +Compare effective Set-Cookie with actual HTTP/TLS/proxy topology; Domain/Path are not authorization. + +**Vulnerable example:** + +Private cookies reach unnecessary hosts/paths, are unnecessarily accessible to JavaScript or disappear because Secure is misconfigured. + +**Fix:** Keep session cookies HttpOnly and use Secure where the approved service transport supports HTTPS; changing Secure on an HTTP-only checker requires a coordinated transport decision. + +**Verification:** Scripts cannot read session cookies; sessions work over the intended transport and secure cookies are not sent over plaintext. + + +**Scanner example before:** + +~~~config +SESSION_COOKIE_HTTPONLY = False +~~~ + +**Fix template:** + +~~~config +SESSION_COOKIE_HTTPONLY = True +~~~ + + + + +## CFG-TRUSTED-HEADERS. Backends trust client-supplied user, role or IP + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'X-User|X-Role|X-Forwarded|Forwarded|Remote-User|X-Original' . +~~~ + +Trace which component sets/clears headers and whether the backend is reachable around the trusted proxy. + +**Vulnerable example:** + +The application accepts client X-User as verified identity. + +**Fix:** Application credentials or authenticated trusted peers, with forwarded identity sanitized according to topology; one secret header is not universal authentication. + +**Verification:** Direct requests and forged headers confer no rights; legitimate proxy traffic works. + + + +## CFG-CACHE-AUTH. Shared HTTP caches retain personalized responses + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'proxy_cache|Cache-Control|Vary|Authorization|Set-Cookie|cache_key' . +~~~ + +Review cache keys, bypass conditions and cookie/authenticated responses; compare two users at the same URL. + +**Vulnerable example:** + +A private response cached solely by URI is returned to another session. + +**Fix:** Never share personalized responses under a common key; contractual private/no-store or full context isolation with correct invalidation. + +**Verification:** User A then B at the same URL, logout/role changes and normal public caching. + + + +## CFG-DEBUG-ENDPOINT. Diagnostics become public APIs + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'actuator|swagger|debug|pprof|metrics|heapdump|console|env' . +~~~ + +List actually registered endpoints and access policy for each; /health alone is not suspicious. + +**Vulnerable example:** + +Environment, heap dumps or configuration consoles expose secrets or application control. + +**Fix:** Disable unnecessary diagnostics in the owned service or enforce application authorization; preserve required health/organizer monitoring. + +**Verification:** Health/checker work; anonymous environment/dump/control access fails. + + + +## CFG-ERROR-SECRET. Logs expose credentials or private request bodies + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'logger|logging|console.log|print|Authorization|password|token' . +~~~ + +Find whole-request/config/exception logging, debug traces and every log destination. + +**Vulnerable example:** + +Passwords, signatures or private bodies are unnecessarily logged and exposed through endpoints/volumes. + +**Fix:** Secret-free structured fields, redaction before serialization and minimal access/retention; preserve useful error codes. + +**Verification:** Failed requests remain diagnosable without secret values or API stack traces. + + + +## CFG-RESOURCE-LIMITS. Body, decompression and multipart limits + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'bodyLimit|maxRequest|client_max_body_size|multipart|decompress|timeout' . +~~~ + +Check limits before reads, after decompression, per part and per complete message; proxy and app limits may differ. + +**Vulnerable example:** + +Small compressed input expands into a huge body, or parts/headers are unbounded. + +**Fix:** Contractual budgets for actual bytes, parts, time and output; cleanup on failure. + +**Verification:** Limit±1, missing Content-Length, compressed bodies, many parts and the legitimate maximum. + + + +## CFG-UPLOAD-EXEC. Uploads become executable or active content + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'upload|media|public|cgi|fastcgi|Content-Type|Content-Disposition' . +~~~ + +Compare storage paths, server handlers and browser MIME behavior; client filename/Content-Type does not prove type. + +**Vulnerable example:** + +An uploaded document executes server-side or opens as active HTML within the app origin. + +**Fix:** Private nonexecutable storage, server-generated filenames, type validation and serving policy; safe download headers. + +**Verification:** Upload/download/previews work without turning files into server code or cross-user origin scripts. + +**Reference:** [primary source](https://cheatsheetseries.owasp.org/cheatsheets/File_Upload_Cheat_Sheet.html). + + + +## CFG-HTTP-PARSER. Proxy and backend disagree on framing + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'Content-Length|Transfer-Encoding|http_parser|proxy_http_version|keepalive' . +~~~ + +Check HTTP parser versions and contradictory length/encoding handling; test only an isolated environment. + +**Vulnerable example:** + +Layers disagree about request boundaries and a following request enters another context. + +**Fix:** Compatible patched parsers, one strict framing policy and rejection of ambiguity; do not attempt payload-regex repairs. + +**Verification:** Normal keepalive/chunked behavior, conflicting framing and safe connection closure without mixed responses. + + + +## CFG-CORS-CREDENTIALS. CORS reflects Origin with credentials + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'Access-Control-Allow-Origin|allow_credentials|origin:|credentials:|CORS' . +~~~ + +Compare allowed and foreign Origin responses; browsers normally block wildcard+credentials, while arbitrary reflection is more dangerous. + +**Vulnerable example:** + +Every origin receives its own name reflected and permission to read private authenticated APIs. + +**Fix:** Exact server-side origin allowlist, correct Vary and credential policy; CORS does not authorize nonbrowser requests. + +**Verification:** The normal frontend works; foreign/null origins cannot read credentialed responses. + + + +## CFG-RESET-TOKEN. Recovery or share tokens lack purpose or one-time use + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'reset|recover|invite|share|token|expires|used_at' . +~~~ + +Trace issuance/verification and atomic consumption; compare login/share/reset audiences. + +**Vulnerable example:** + +A token for another operation or an already consumed token changes access again. + +**Fix:** CSPRNG/signatures bound to purpose/resource/subject/expiry, with transactional one-time consumption where required; preserve legitimate sharing. + +**Verification:** Replays/concurrent use, foreign objects/purposes, expiry and normal operation. + + + +## CFG-OBJECT-POLICY. Alternative endpoints expose an object directly + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'owner|tenant|download|export|delete|share|attachment|job' . +~~~ + +Trace every operation and nested path for one entity, including background jobs; unpredictable IDs are not permission. + +**Vulnerable example:** + +UI/read paths are protected, but export/download/delete look up IDs without owner checks. + +**Fix:** One resource policy enforced for every operation, actor from verified session and explicit intended sharing. + +**Verification:** Two users/tenants can access their own resources and never each other's through any endpoint. + +**Reference:** [primary source](https://cheatsheetseries.owasp.org/cheatsheets/Authorization_Cheat_Sheet.html). + + + +## CFG-DEPLOYED-CONFIG. Reviewing an example instead of effective configuration + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'env_file|environment:|include|args:|command:|config|settings' . +~~~ + +Compare entrypoint, includes, overrides and effective configuration. Expanded output may contain secrets; inspect it only privately. + +**Vulnerable example:** + +A sample is fixed while runtime environment/volumes supply an unsafe override. + +**Fix:** Change the actual source of configuration, verify precedence and restart; keep secrets out of Git. + +**Verification:** Correct effective values survive restart; the old copy never silently returns. + + + +## CFG-MEDIA-CONVERTER. Media documents load additional resources + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'ffmpeg|magick|convert|thumbnail' . +~~~ + +Determine which additional files/URLs the decoder reads after receiving a document. + +**Vulnerable example:** + +**Reference:** bookster, RuCTF author write-up. An older FFmpeg could follow resources embedded in uploaded media while producing previews. + +**Search:** FFmpeg, ImageMagick, PDF/SVG/XML conversion, thumbnails/previews and embedded playlists/URLs. Separate the input file from additional resources the parser fetches; HTTP-handler URL checks alone are insufficient. + +**Fix:** Compatible patched builds, explicit allowed protocols/decoders, constrained input/output and process resources. Preserve promised formats/previews. Network firewall policy does not replace the fix. + +**Verification:** Every allowed format, malformed files, embedded local-resource links and time/memory budgets. + +**A/D variant:** Source and version: [source/write-up 1](https://github.com/HackerDom/ructf-finals-2023/blob/a7442769909e08c39716cb18d3d1c3a99324bbf8/writeups/bookster/README.md). + +**Reference:** [primary source](https://github.com/HackerDom/ructf-finals-2023/blob/a7442769909e08c39716cb18d3d1c3a99324bbf8/writeups/bookster/README.md). + + + +## CFG-FORMAT-TRANSITION. Injection through intermediate YAML + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'yaml|unmarshal|safe_load|template' . +~~~ + +Trace text → template → YAML → update object; type data at each boundary. + +**Vulnerable example:** + +**Reference:** lost_museum, RuCTF author write-up. A template generated YAML subsequently parsed into a MongoDB mutation map. + +**Search:** String-formatted structured documents followed by unmarshal/parse and wholesale database updates. safe_load does not prevent unwanted fields; this differs from unsafe YAML constructors. + +**Fix:** Typed structure → serializer, then explicit update-field projection; server-derived owner/role. Clients must not control MongoDB operation structure. + +**Verification:** Newlines, colons, nested fields and normal text change only the intended field. + +**A/D variant:** Source and version: [source/write-up 1](https://github.com/HackerDom/ructf-finals-2023/blob/a7442769909e08c39716cb18d3d1c3a99324bbf8/writeups/lost_museum/README.md). + +**Reference:** [primary source](https://github.com/HackerDom/ructf-finals-2023/blob/a7442769909e08c39716cb18d3d1c3a99324bbf8/writeups/lost_museum/README.md). + + + +## CFG-PRINCIPAL-CONTEXT. Clients modify authorization context + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'userspace|principal|currentUser|tenant' . +~~~ + +Trace every principal write; DSLs and request parameters must not mutate server authorization context. + +**Vulnerable example:** + +**Reference:** scp, RuCTF author write-up: a DSL modified userspace used for visibility control. **Search:** currentUser/userspace/principal/tenant assignments from expressions, parameters or intermediate state, and authorization-mode switches. + +**Fix:** Derive the actor from a verified session and store it apart from mutable DSL state. Sensitive operations check the server-owned context. + +**Verification:** Expressions cannot change principal; owned objects remain accessible and foreign objects hidden regardless of expression order. + +**A/D variant:** Source and version: [source/write-up 1](https://github.com/HackerDom/ructf-finals-2023/blob/a7442769909e08c39716cb18d3d1c3a99324bbf8/writeups/scp/README.md). + +**Reference:** [primary source](https://github.com/HackerDom/ructf-finals-2023/blob/a7442769909e08c39716cb18d3d1c3a99324bbf8/writeups/scp/README.md). + + + +## CFG-AUTH-TOCTOU. Authorization races and identifier reuse + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'owner|tenant|middleware|await|UPDATE|DELETE' . +~~~ + +Find waits/state changes between checking and writing; require owner/version conditions in atomic mutations. + +**Vulnerable example:** + +**Reference:** stalker, RuCTF author write-up. ORM authorization snapshots were taken before waiting for the request body; deletion/recreation changed identifier meaning. + +**Search:** Middleware objects/ID lists → await/I/O → unchecked mutation, cached ORM relationships and IDs unique only within part of a composite key. + +**Fix:** Check ownership atomically in UPDATE/DELETE/SHARE itself, using transactions/row versions as needed and stable ID uniqueness. Preserve data during schema migration. + +**Verification:** Deterministic check → delete/recreate → mutate interleaving never changes foreign records. Also test rollback and normal concurrency. + +**A/D variant:** Source and version: [source/write-up 1](https://github.com/HackerDom/ructf-finals-2023/blob/a7442769909e08c39716cb18d3d1c3a99324bbf8/writeups/stalker/README.md). + +**Reference:** [primary source](https://github.com/HackerDom/ructf-finals-2023/blob/a7442769909e08c39716cb18d3d1c3a99324bbf8/writeups/stalker/README.md). + + + +## CFG-CUSTOM-CRYPTO. Algebraic leakage in custom cryptography + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'encrypt|decrypt|matrix|modulus|nonce' . +~~~ + +Write down input/output relationships and where secrets enter; review preserved algebraic relations with the protocol owner. + +**Vulnerable example:** + +**Reference:** solaris, RuCTF author write-up: a matrix construction preserved mathematical relations tied to a secret. **Search:** Custom RSA/matrix/arithmetic combinations, invariant input/output relations and insufficient randomness. + +**Fix:** First identify the functional contract and mathematical leak. For ordinary encryption/authentication use standard library constructions with proper nonces and versioned formats. A cryptographic challenge may need an algorithm-specific repair. **Never generalize challenge-specific key-size reductions into security hardening.** + +**Verification:** Normal client behavior and old data remain intact while the identified invariant disappears. + +**A/D variant:** Source and version: [source/write-up 1](https://github.com/HackerDom/ructf-finals-2023/blob/a7442769909e08c39716cb18d3d1c3a99324bbf8/writeups/solaris/README.md). + +**Reference:** [primary source](https://github.com/HackerDom/ructf-finals-2023/blob/a7442769909e08c39716cb18d3d1c3a99324bbf8/writeups/solaris/README.md). + + + +## CFG-SHARED-BACKEND-KEY. One credential spans all child environments + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'API_KEY|apikey|credential|environment|token' . +~~~ + +Trace shared-key distribution and backend resource/audience validation. + +**Vulnerable example:** + +**ENOWARS / replme, author write-up.** Compromising one child backend exposed a key trusted by the others. + +**Fix:** Least privilege and credentials scoped to individual resources; do not rely solely on internal addresses. + +**Verification:** Environment A's credential never authorizes actions in B. + +**A/D variant:** Source and version: [source/write-up 1](https://github.com/enowars/enowars8-service-replme/blob/3cdec50dd9a57f43f1c57f7b049319774a00e6c2/documentation/documentation/src/main.tex); [source/write-up 2](https://github.com/enowars/enowars8-service-replme/blob/3cdec50dd9a57f43f1c57f7b049319774a00e6c2/documentation/documentation/src/path-traversal.patch); [source/write-up 3](https://github.com/enowars/enowars8-service-replme/blob/3cdec50dd9a57f43f1c57f7b049319774a00e6c2/documentation/documentation/src/crc.patch); [source/write-up 4](https://github.com/enowars/enowars8-service-replme/blob/3cdec50dd9a57f43f1c57f7b049319774a00e6c2/service/backend/util/encoding.go); [source/write-up 5](https://github.com/enowars/enowars8-service-replme/blob/3cdec50dd9a57f43f1c57f7b049319774a00e6c2/service/backend/controller/repl.go); [source/write-up 6](https://github.com/enowars/enowars8-service-replme/blob/3cdec50dd9a57f43f1c57f7b049319774a00e6c2/service/image/service/user.go). + +**Reference:** [primary source](https://github.com/enowars/enowars8-service-replme/blob/3cdec50dd9a57f43f1c57f7b049319774a00e6c2/documentation/documentation/src/main.tex). + + + +## CFG-WINDOWS-NAMES. Filenames have different Windows meanings + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'filename|basename|glob|FindFirstFile|ToLower' . +~~~ + +Compare validated/database names with actual Windows lookup: case, wildcard, trailing dots/spaces and alternate streams. + +**Vulnerable example:** + +**ICC / MaScroll, author write-up.** Database/filesystem names disagreed on case and allowed characters. + +**Fix:** Server-generated storage IDs, one policy for the actual operating system and separate ownership checks. + +**Verification:** Case, wildcards/special characters and separators; old files stay accessible. + +**A/D variant:** Source and version: [source/write-up 1](https://github.com/CybersecNatLab/ICC2023-AD-CTF/blob/8ffa184ff2ce8f648258ed3c02ee2270e8e1c56c/sources/MaScroll/README.md). + +**Reference:** [primary source](https://github.com/CybersecNatLab/ICC2023-AD-CTF/blob/8ffa184ff2ce8f648258ed3c02ee2270e8e1c56c/sources/MaScroll/README.md). + + + +## CFG-PROXY-REDIRECT. Reverse proxies follow redirects into trusted services + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'proxy_pass|redirect|Location|logout|internal' . +~~~ + +Trace redirects in internal HTTP clients and repeated destination checks; internal locations alone do not authenticate backend access. + +**Vulnerable example:** + +**ICC / NorthernFiles, author write-up.** An open redirect combined with proxy configuration exposed an internal endpoint through a chain. + +**Fix:** Safe redirects and an explicit proxy contract; internal token issuers must independently authorize requests. + +**Verification:** Internal/external redirects and normal logout. + +**A/D variant:** Source and version: [source/write-up 1](https://github.com/CybersecNatLab/ICC2023-AD-CTF/blob/8ffa184ff2ce8f648258ed3c02ee2270e8e1c56c/sources/NorthernFiles/README.md). + +**Reference:** [primary source](https://github.com/CybersecNatLab/ICC2023-AD-CTF/blob/8ffa184ff2ce8f648258ed3c02ee2270e8e1c56c/sources/NorthernFiles/README.md). + + + +## CFG-PROTOCOL-KEY. Degenerate values in cryptographic protocols + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'public_key|pubkey|group|identity|point' . +~~~ + +Validate decoding, group membership and rejection of degenerate elements according to the actual protocol. + +**Vulnerable example:** + +**ICC / NorthernFiles, author write-up.** Type-valid input reduced key agreement to a trivial value. + +**Fix:** Protocol-specific group-element/degenerate-state validation; use a reviewed implementation where compatible. + +**Verification:** Neutral/invalid elements, negative cases and client interoperability. + +**A/D variant:** Source and version: [source/write-up 1](https://github.com/CybersecNatLab/ICC2023-AD-CTF/blob/8ffa184ff2ce8f648258ed3c02ee2270e8e1c56c/sources/NorthernFiles/README.md). + +**Reference:** [primary source](https://github.com/CybersecNatLab/ICC2023-AD-CTF/blob/8ffa184ff2ce8f648258ed3c02ee2270e8e1c56c/sources/NorthernFiles/README.md). + + + +## CFG-AGGREGATE-KEY. Incorrect public-key aggregation + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'aggregate|coefficient|pubkey|subset' . +~~~ + +Compare coefficients and proof-of-possession with the chosen scheme; bound set-validation cost. + +**Vulnerable example:** + +**ICC / UberPendragon, author write-up.** Linear coefficients failed to provide expected rogue-key protection. + +**Fix:** A reviewed aggregation scheme; where clients cannot change, justified protocol-specific rejection of degenerate sets with bounded cost. + +**Verification:** Ordinary groups, duplicate keys, degenerate aggregates and load. + +**A/D variant:** Source and version: [source/write-up 1](https://github.com/CybersecNatLab/ICC2023-AD-CTF/blob/8ffa184ff2ce8f648258ed3c02ee2270e8e1c56c/sources/UberPendragon/README.md). + +**Reference:** [primary source](https://github.com/CybersecNatLab/ICC2023-AD-CTF/blob/8ffa184ff2ce8f648258ed3c02ee2270e8e1c56c/sources/UberPendragon/README.md). + + + +## CFG-K8S-HOST. Container shares host namespaces + +**Search:** scanner rule CFG-K8S-HOST. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain CFG-K8S-HOST` for details. Regex: hostPID/hostIPC/hostNetwork:true and Compose pid/ipc/network_mode:host. No admission-policy or running-pod analysis. + +**Vulnerable example:** Host-namespace access broadens the impact of workload compromise. + +~~~config +hostPID: true +hostIPC: true +hostNetwork: true +~~~ + +**Fix:** Disable unnecessary host namespaces; implement required connectivity within approved competition topology and verify probes/ports. + +~~~config +hostPID: false +hostIPC: false +hostNetwork: false +~~~ + +**Verification:** Service/checker works without host process/IPC visibility or unintended sockets. + +Primary documentation: [reference 1](https://kubernetes.io/docs/concepts/security/pod-security-standards/). + + + +## CFG-UNCONFINED. seccomp/AppArmor profile disabled + +**Search:** scanner rule CFG-UNCONFINED. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain CFG-UNCONFINED` for details. Regex: seccomp/apparmor=unconfined or :unconfined and Kubernetes type:Unconfined. Unrelated YAML type keys may match. + +**Vulnerable example:** Unconfined removes a layer of syscall/access restrictions. + +~~~config +security_opt: + - seccomp:unconfined + - apparmor:unconfined +~~~ + +**Fix:** Restore the default or minimum compatible profile with narrow exceptions. + +~~~config +security_opt: + - no-new-privileges:true +# Keep the runtime default seccomp/AppArmor profiles. +~~~ + +**Verification:** Normal operations/checker work and the effective container applies the profile. + +Primary documentation: [reference 1](https://docs.docker.com/engine/security/seccomp/). + + + +## CFG-PRIV-ESCALATION. Process privilege escalation allowed + +**Search:** scanner rule CFG-PRIV-ESCALATION. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain CFG-PRIV-ESCALATION` for details. Regex: explicit allowPrivilegeEscalation:true. Review missing fields, defaults and interactions with privileged/CAP_SYS_ADMIN. + +**Vulnerable example:** Permitted privilege escalation preserves setuid/file-capability paths. + +~~~config +allowPrivilegeEscalation: true +~~~ + +**Fix:** Disable allowPrivilegeEscalation and remove privileged/CAP_SYS_ADMIN and unnecessary capabilities. + +~~~config +allowPrivilegeEscalation: false +~~~ + +**Verification:** Required operations work and effective securityContext matches the manifest. + +Primary documentation: [reference 1](https://kubernetes.io/docs/tasks/configure-pod-container/security-context/). + + + +## CFG-ACTUATOR. Spring Actuator exposes every endpoint + +**Search:** scanner rule CFG-ACTUATOR. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain CFG-ACTUATOR` for details. Regex: flat property or MANAGEMENT_ENDPOINTS_WEB_EXPOSURE_INCLUDE with *. Inspect nested YAML and active profiles using endpoints/exposure/include. + +**Vulnerable example:** Broad management-endpoint exposure can disclose runtime/configuration or grant control. + +~~~config +management.endpoints.web.exposure.include=* +~~~ + +**Fix:** Expose only necessary endpoints and restrict management access; inspect health details/custom SecurityFilterChain separately. + +~~~config +management.endpoints.web.exposure.include=health +~~~ + +**Verification:** Health/checker works; env, heapdump, loggers, shutdown and unnecessary endpoints require approved admin access. + +Primary documentation: [reference 1](https://docs.spring.io/spring-boot/reference/actuator/endpoints.html). + + + +## CFG-H2-CONSOLE. H2 web console enabled + +**Search:** scanner rule CFG-H2-CONSOLE. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain CFG-H2-CONSOLE` for details. Regex: spring.h2.console.enabled/SPRING_H2_CONSOLE_ENABLED=true. Inspect nested YAML, aliases and active profiles. + +**Vulnerable example:** A database console is a separate administrative surface with its own authentication and JDBC input. + +~~~config +spring.h2.console.enabled=true +~~~ + +**Fix:** Disable in the runtime profile or provide protected local admin access; never remove application-wide auth/CSRF for it. + +~~~config +spring.h2.console.enabled=false +~~~ + +**Verification:** Database operations work; console is not exposed to the game network. + +Primary documentation: [reference 1](https://docs.spring.io/spring-boot/reference/data/sql.html#data.sql.h2-web-console). + + + +## CFG-TLS-UPSTREAM. Proxy does not verify upstream TLS + +**Search:** scanner rule CFG-TLS-UPSTREAM. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain CFG-TLS-UPSTREAM` for details. Regex: proxy_ssl_verify/grpc_ssl_verify off. Missing directives, inheritance and effective values require complete nginx config review. + +**Vulnerable example:** Upstream HTTPS without certificate verification does not identify the intended backend. + +~~~config +proxy_ssl_verify off; +~~~ + +**Fix:** Enable verification, trusted CA and correct name/SNI; validate chain/intermediate depth for the actual upstream. + +~~~config +proxy_ssl_verify on; +proxy_ssl_trusted_certificate /etc/nginx/trusted-ca.pem; +proxy_ssl_server_name on; +proxy_ssl_name notes.internal; +~~~ + +**Verification:** Correct backend works; wrong certificate/host fails without HTTP fallback. + +Primary documentation: [reference 1](https://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_ssl_verify). + + + +## CFG-SSH-EMPTY-PASSWORD. SSHD permits empty passwords + +**Search:** scanner rule CFG-SSH-EMPTY-PASSWORD. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain CFG-SSH-EMPTY-PASSWORD` for details. Regex: PermitEmptyPasswords yes. Recognizes sshd_config; include files with arbitrary names require explicit review. + +**Vulnerable example:** When password authentication is available, an empty-password account can permit host access. + +~~~config +PermitEmptyPasswords yes +~~~ + +**Fix:** Disallow empty passwords; review Match/PAM/accounts while retaining a working administration channel before applying changes. + +~~~config +PermitEmptyPasswords no +~~~ + +**Verification:** Approved login works; empty passwords fail in every applicable Match context. + +Primary documentation: [reference 1](https://man.openbsd.org/sshd_config#PermitEmptyPasswords). + + + +## CFG-SUDO-ALL. Unrestricted passwordless sudo + +**Search:** scanner rule CFG-SUDO-ALL. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain CFG-SUDO-ALL` for details. Regex: NOPASSWD:ALL. Review aliases, includes, wildcard argv and dangerous allowed binaries; recognizes sudoers. + +**Vulnerable example:** NOPASSWD:ALL turns runtime-user code execution into access to every permitted Runas target. + +~~~config +app ALL=(ALL:ALL) NOPASSWD: ALL +~~~ + +**Fix:** Remove runtime sudo; move rare privileged operations into a minimal helper without arbitrary argv, shell or writable dependencies. + +~~~config +# Runtime user has no sudo grant. +# Provision required resources before service startup. +~~~ + +**Verification:** Service works without sudo; effective rights contain neither ALL nor shell-escaping commands. + +Primary documentation: [reference 1](https://www.sudo.ws/docs/man/sudoers.man/). + + + +## CFG-JWT-KEY-SELECTION. Untrusted kid/jku selects verification keys + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'kid|jku|x5u|jwks|JWK|keyfunc|getKey|IssuerSigningKeyResolver' . +~~~ + +Trace issuer, key-set URLs, local paths and kid lookup. Compare trusted registries against unverified token fields; scope cache keys by issuer and kid. + +**Vulnerable example:** A token supplies a JWKS URL/key file or another issuer's kid, and the validator trusts the result. + +**Fix:** Pin allowed issuers and their JWKS/keys server-side; kid is only an exact index within that issuer. Restrict algorithms/key types, caching and rotation; do not trust token-supplied jku/x5u. + +**Verification:** Legitimate rotation works; unknown/cross-issuer kid and client URLs cannot change the trust domain. Key-fetch failure never authorizes. + +Reference: [primary documentation](https://www.rfc-editor.org/rfc/rfc8725.html). The explanation and adaptation recipe were written for this catalog. + + + +## CFG-SIGNED-REQUEST. Signatures are not bound to operations or preventable replays + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'signature|signed_url|signedUrl|nonce|expires|timestamp|hmac|Content-Digest' . +~~~ + +List exact signed bytes: method, path, query, body, recipient, purpose and lifetime. Compare signer/verifier normalization and atomic one-use nonce handling. + +**Vulnerable example:** A read signature authorizes mutation, bodies can be replaced, or a one-use webhook/payment is replayed. + +**Fix:** Sign a canonical contract binding action/purpose, recipient and required request components; bound expiry/clock skew. Atomically record one-use nonces/idempotency keys with the mutation. + +**Verification:** Method/path/body/recipient changes invalidate signatures. Concurrent replays produce one effect; permitted retries return the agreed result. + +Reference: [primary documentation](https://www.rfc-editor.org/rfc/rfc9421.html). The explanation and adaptation recipe were written for this catalog. + + + +## CFG-RATE-LIMIT-IDENTITY. Senders choose their rate-limit identity + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'rate.?limit|throttle|X-Forwarded-For|X-Real-IP|req\.ip|remote_addr|client_ip' . +~~~ + +Compare limit keys with the actual trusted-proxy boundary. Test case/Unicode names, route aliases, multiple workers, expiry and backend failure. + +**Vulnerable example:** Limits use arbitrary headers, one account spelling or worker-local memory; changing representation resets the budget. + +**Fix:** Normalize identity consistently with authentication; trust proxy headers only from approved hops. Use atomic shared budgets for intended actors/operations while preserving legitimate shared-IP access. + +**Verification:** Header/identity-form changes do not create a fresh budget; parallel workers honor limits and permitted checker traffic works. + +Reference: [primary documentation](https://expressjs.com/en/guide/behind-proxies.html). The explanation and adaptation recipe were written for this catalog. + + + +## CFG-TOKEN-REVOCATION. Password or role changes fail to revoke access + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'logout|revoke|revocation|token_version|session_version|password_changed|security_stamp|refresh_token' . +~~~ + +Trace login, refresh, logout, password changes, account deletion and role updates. Determine when APIs reload privileges, validate session/token versions and invalidate caches. + +**Vulnerable example:** A deleted administrator retains an old JWT/session, or a revoked refresh token restores access. + +**Fix:** Contractual expiry/revocation via session versions, denylists or short-lived access tokens with verified refresh. Rotate refresh tokens atomically and invalidate related caches. + +**Verification:** After the chosen revocation event, old access/refresh tokens fail within the promised interval on every worker; legitimate re-login works. + +Reference: [primary documentation](https://cheatsheetseries.owasp.org/cheatsheets/Session_Management_Cheat_Sheet.html). The explanation and adaptation recipe were written for this catalog. + + + +## CFG-FAIL-OPEN. Verification errors become permission + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'catch|except|finally|recover|fallback|default.*allow|on_error|unwrap_or|Result' . +~~~ + +Trace every auth/signature/ACL exception, timeout, nil/None/null and cleanup branch. Inspect catch/finally, next middleware and defaults. + +**Vulnerable example:** Database/validator failure returns allow/default principal, a handler continues after 401, or finally overrides denial. + +**Fix:** Deny by default before side effects. Distinguish authorization denial from temporary unavailability and terminate the processing chain; log errors without secrets. + +**Verification:** Synthetic backend errors/timeouts, wrong types and nil results neither expose data nor mutate state; normal checks pass. + +Reference: [primary documentation](https://cheatsheetseries.owasp.org/cheatsheets/Authorization_Cheat_Sheet.html). The explanation and adaptation recipe were written for this catalog. + + + +## CFG-LDAP-FILTER. LDAP filters or DNs built as strings + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'ldap_search|ldap\.search|search_s|SearchFilter|DirContext|LdapName|Filter\.create|escape_filter' . +~~~ + +Trace search filters separately from DNs: their grammars differ. Check bind/search, wildcard handling, empty passwords and multiple-match selection. + +**Vulnerable example:** Usernames become LDAP syntax; broadened filters select another record or several records with the first treated as the user. + +**Fix:** Builders/parameter APIs or escaping specifically for filter values; construct DNs with a DN builder. Require exactly the intended match and a valid bind; search is not authentication. + +**Verification:** Special characters remain values; zero/multiple matches and empty credentials cannot authenticate; normal users work. + +Reference: [primary documentation](https://www.rfc-editor.org/rfc/rfc4515.html). The explanation and adaptation recipe were written for this catalog. + + + +## CFG-CI-TRUST. Untrusted data and code cross CI trust boundaries + +**Search:** manual review; no separate scanner rule. CFG-CI-TRUST is a catalog ID, not an automatic signal. Locate workflows and composite actions: + +~~~bash +rg -n --hidden -g '*.yml' -g '*.yaml' -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'pull_request_target|workflow_run|permissions:|secrets\.|allow-unsafe-pr-checkout|checkout@|download-artifact@|head\.sha|git fetch|gh pr checkout|run:|script:|uses: \./' . +rg -n --hidden -g '*.yml' -g '*.yaml' -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e '\$\{\{[^}]*github\.(event|head_ref)' . +~~~ + +Read complete jobs and called actions/reusable workflows. Trace event/ref/artifact control → conversion into shell/JavaScript, dependencies or executables → effective permissions, secrets, environment and runner. An event name alone proves no flaw. Multiline expressions, indirect outputs and composite-action inputs need review even without search matches. + +**Vulnerable example:** The first boundary is interpolating event data directly into run/script source. Quoting an expression does not protect it: interpolation occurs before shell parsing. + +~~~yaml +- name: Show title + shell: bash + run: printf '%s\n' "${{ github.event.pull_request.title }}" +~~~ + +A real workflow_run.head_branch case is documented in [GHSL-2025-099](https://securitylab.github.com/advisories/GHSL-2025-099_cross-platform-actions_action/). It affected a workflow in the action repository, not necessarily every project using the action. + +The second boundary is executing PR code in a privileged job: + +~~~yaml +on: pull_request_target +permissions: + contents: write +jobs: + checks: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + with: + ref: ${{ github.event.pull_request.head.sha }} + allow-unsafe-pr-checkout: true + - run: make test + env: + SERVICE_TOKEN: ${{ secrets.SERVICE_TOKEN }} +~~~ + +PRs can change tests, Makefiles, install hooks and local actions. An analogous workflow_run error downloads a prior PR artifact and executes its script. Correct run IDs and successful status establish provenance, not content trust. [GitHub pull_request_target/workflow_run trust](https://docs.github.com/en/actions/reference/security/securely-using-pull_request_target). A real PR → privileged workflow → PR-code execution chain appears in [Gradio GHSL-2024-150 through GHSL-2024-157](https://securitylab.github.com/advisories/GHSL-2024-150_GHSL-2024-157_Gradio/). + +checkout v7 blocks unsafe fork-PR checkout by default for pull_request_target and workflow_run whose workflow_run.event matches pull_request*; the example explicitly disables protection. It does not protect every workflow_run. Protection was backported to supported major versions, but pinned old SHAs do not update themselves. Check the exact commit/backport; git fetch, third-party actions and artifacts bypass this checkout-specific boundary. [checkout change](https://github.blog/changelog/2026-06-18-safer-pull_request_target-defaults-for-github-actions-checkout/). Also inspect effective repository event policy; workflow YAML alone cannot establish whether it applies. [GitHub event policy](https://docs.github.com/en/actions/reference/security/securely-using-pull_request_target#default-policy-for-pull_request_target). + +**Fix:** Keep event data separate from executable source: + +~~~yaml +- name: Show title + env: + PR_TITLE: ${{ github.event.pull_request.title }} + shell: bash + run: printf '%s\n' "$PR_TITLE" +~~~ + +The printf format is fixed and the value is one argument. Later eval, bash -c or JavaScript construction breaks the boundary again. Passing data through with is safe only if the receiving action handles it safely. [GitHub script-injection guidance](https://docs.github.com/en/actions/reference/security/secure-use#good-practices-for-mitigating-script-injection-attacks). + +Run ordinary PR checks in an unprivileged, secret-free workflow: + +~~~yaml +on: pull_request +permissions: + contents: read +jobs: + checks: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + with: + persist-credentials: false + - run: make test +~~~ + +persist-credentials:false alone does not fix privileged PR-code execution. Separate trusted jobs for comments, labels or report publication: accept bounded schema-validated JSON/text, verify repo/run/head SHA/PR destination, and never execute/import artifacts. Download data outside the trusted workspace. Private-registry/API tests need a separate design; arbitrary PR code must not receive their secrets. pull_request_target limited to labels/comments can be justified. [GitHub Security Lab stage separation](https://securitylab.github.com/resources/github-actions-preventing-pwn-requests/). + +**Verification:** Statically trace data and minimal effective permissions including repository settings. In an authorized test CI exercise fork PRs, new SHAs after approval, quoted/newline-containing titles as data, foreign run IDs, malformed schemas and oversized artifacts. Preserve normal checks/report publication; PR code receives neither secrets nor a persistent self-hosted runner with internal access. These workflows were not executed during the catalog review; the offline scanner does not determine effective permissions or Actions relationships. + + + +## CFG-DOCKER-TCP. Docker daemon listens on every TCP interface + +**Search:** scanner rule CFG-DOCKER-TCP. Use `--explain CFG-DOCKER-TCP` for the exact detector contract. Regex with lexical exclusions: dockerd followed on the same line by -H/--host tcp://0.0.0.0 or [::]. Does not evaluate TLS flags, JSON daemon configuration, named interfaces or shell expansions; a TLS-protected listener still requires review. + +**Vulnerable example:** + +~~~shell +dockerd -H tcp://0.0.0.0:2375 +~~~ + +**Fix:** Prefer local Docker access. Required remote management needs authenticated encrypted transport and a deliberately restricted management interface; never publish it as a team UI. + +~~~shell +dockerd -H unix:///var/run/docker.sock +~~~ + +**Verification:** Unapproved LAN clients cannot control Docker; approved administration remains possible without exposing credentials. + +[Primary reference 1](https://docs.docker.com/reference/cli/dockerd/#daemon-socket-option) + + + +## CFG-FLOATING-IMAGE. Explicit latest image tag + +**Search:** scanner rule CFG-FLOATING-IMAGE. Use `--explain CFG-FLOATING-IMAGE` for the exact detector contract. Regex with lexical exclusions: Docker FROM or a bare YAML image key using an unquoted image:latest with no digest. Quoted YAML, untagged images, other mutable tags, ARG expansion and resolved architecture need deployment-model audit. + +**Vulnerable example:** + +~~~docker +FROM example.invalid/app:latest +~~~ + +**Fix:** Record the approved source version and architecture-specific image digest; populate the offline image inventory and verify imported images. + +~~~docker +FROM example.invalid/app@sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +~~~ + +**Verification:** Repeated offline starts use the approved bytes and architecture; no implicit pull or latest fallback occurs. + +[Primary reference 1](https://docs.docker.com/reference/dockerfile/#from) + + + +## TPL-AUTOESCAPE-OFF. Template block disables autoescaping + +**Search:** scanner rule TPL-AUTOESCAPE-OFF. Use `--explain TPL-AUTOESCAPE-OFF` for the exact detector contract. Regex excluding HTML/Jinja comments: Jinja/Twig autoescape false and Django autoescape off blocks. Does not evaluate template engine defaults, enclosing blocks or whether values are trusted. + +**Vulnerable example:** + +~~~template +{% autoescape false %}{{ message }}{% endautoescape %} +~~~ + +**Fix:** Retain autoescaping for untrusted text; sanitize supported HTML explicitly and review the output context. + +~~~template +{{ message }} +~~~ + +**Verification:** User tags/attributes remain data and allowed formatting still works. + +[Primary reference 1](https://jinja.palletsprojects.com/en/stable/templates/#autoescape-overrides) diff --git a/docs/vulnerabilities/csharp-RU.md b/docs/vulnerabilities/csharp-RU.md new file mode 100644 index 0000000..16c0bdf --- /dev/null +++ b/docs/vulnerabilities/csharp-RU.md @@ -0,0 +1,688 @@ + + +# C# / .NET: поиск и исправление + +[English](csharp.md) | Русский + +[Вся база](README-RU.md) · [Сканер](../offline-scanner-RU.md) · [Проверка патча](../patch-validation-RU.md) + +20 разделов. Формат: **Поиск → Уязвимый вариант → Исправление → Проверка**. +Команды `rg` выполняются в корне локальной копии сервиса и только читают файлы. Субъект/владелец определяется по проверенной сессии, а не данным запроса. Примеры нужно адаптировать к реальным API и контракту. + +Автоматические находки — ограниченные синтаксические сигналы для проверки. AST-анализ не разрешает типы и не отслеживает данные между функциями; regex не заменяет парсер языка. Комментарии, строки и одноимённые пользовательские API могут давать совпадения. Проверьте фактическое исполнение, входные данные, авторизацию и границы доверия. + + + +## Содержание + +- [CS-DESERIALIZE — Типы при десериализации .NET](#cs-deserialize) +- [CS-ENUM — Enum.TryParse требует проверки диапазона](#cs-enum) +- [CS-SQL — Динамический SQL .NET](#cs-sql) +- [CS-GUID-BYTES — Байтовый Guid на границе протокола](#cs-guid-bytes) +- [CS-PROCESS — Создание процесса .NET](#cs-process) +- [CS-IGNORE-FILTERS — Отключение global query filters](#cs-ignore-filters) +- [CS-ALLOWANON — Маршрут с AllowAnonymous](#cs-allowanon) +- [CS-MASS-ASSIGN — Клиентская сущность целиком обновляет БД](#cs-mass-assign) +- [CS-XML — XML settings и внешние ресурсы](#cs-xml) +- [CS-HTML-RAW — Html.Raw и IHtmlContent обходят encoding](#cs-html-raw) +- [CS-PATH — Path.Combine и GetFullPath не проверяют owner](#cs-path) +- [CS-ARCHIVE — ZipArchive entry выходит из каталога](#cs-archive) +- [CS-CLAIMS — Неполная проверка JWT/claims](#cs-claims) +- [CS-ASYNC-VOID — async void скрывает ошибку auth](#cs-async-void) +- [CS-REGEX-TIMEOUT — Regex без бюджета на недоверенном вводе](#cs-regex-timeout) +- [CS-AUTH-FILTER-REDUCE — Упрощение фильтра удаляет обязательное условие доступа](#cs-auth-filter-reduce) +- [CS-COLLIDING-PRINCIPAL — Нормализованная сумма символов вместо уникального user ID](#cs-colliding-principal) +- [CS-JWT-VALIDATION — Ослаблены параметры проверки токенов .NET](#cs-jwt-validation) +- [CS-TLS-VALIDATION — HTTPS validation callback всегда разрешает](#cs-tls-validation) +- [CS-LDAP-FILTER — Фильтр DirectorySearcher собирается конкатенацией](#cs-ldap-filter) + + + + + +## CS-DESERIALIZE. Типы при десериализации .NET + +**Поиск:** скрипт, правило CS-DESERIALIZE. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain CS-DESERIALIZE. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API. + +**Уязвимый вариант:** + +~~~csharp +var formatter = new BinaryFormatter(); +~~~ + +**Исправление:** Явные DTO и поддержанный сериализатор, например System.Text.Json, с проверками схемы и размера; убрать неограниченное создание runtime-типов и мигрировать старые данные. + +~~~csharp +var value = JsonSerializer.Deserialize(json); // validate fields +~~~ + +**Проверка:** Произвольный тип не создаётся; старые записи мигрируют. + +**Вариант A/D:** Десериализация запускает побочные эффекты сеттеров. **FAUST / todo-list, код + патч организаторов.** TypeNameHandling.Objects +позволяет выбрать runtime-тип; у модели Filter установка полей вызывает запись +в БД. Проверка результата после создания объекта может быть слишком поздней. + +**Патч:** конкретный DTO без внешнего выбора типа, явная валидация и отдельная +операция сохранения. **Тест:** неизвестный тип не создаёт ни объект, ни запись; +штатный импорт/экспорт сохранён. **Поиск:** CS-DESERIALIZE. + +[исходник/разбор 1](https://github.com/fausecteam/faustctf-2024-todo-list-service/blob/e9ee8b8807c64eeb6f71a72e16f709a558525d2c/patches/deserialize.patch); [исходник/разбор 2](https://github.com/fausecteam/faustctf-2024-todo-list-service/blob/e9ee8b8807c64eeb6f71a72e16f709a558525d2c/patches/TodoController.cs); [исходник/разбор 3](https://github.com/fausecteam/faustctf-2024-todo-list-service/blob/e9ee8b8807c64eeb6f71a72e16f709a558525d2c/service/service/Services/Serializer.cs); [исходник/разбор 4](https://github.com/fausecteam/faustctf-2024-todo-list-service/blob/e9ee8b8807c64eeb6f71a72e16f709a558525d2c/service/service/Services/UserManager.cs); [исходник/разбор 5](https://github.com/fausecteam/faustctf-2024-todo-list-service/blob/e9ee8b8807c64eeb6f71a72e16f709a558525d2c/service/service/Models/Filter.cs). + + + + + +## CS-ENUM. Enum.TryParse требует проверки диапазона + +**Поиск:** скрипт, правило CS-ENUM. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain CS-ENUM. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API. + +**Уязвимый вариант:** + +~~~csharp +bool ok = Enum.TryParse(input, out FilterKind kind); +~~~ + +**Исправление:** После TryParse проверять Enum.IsDefined или явный набор; для Flags — разрешённая маска. Сигнал останется при правильном inline-патче. + +~~~csharp +if (!TryParseAllowedFilter(input, out FilterKind kind)) return BadRequest(); // helper validates named allowlist +~~~ + +**Проверка:** Необъявленные числа/неразрешённые биты отвергаются; штатные фильтры доступны. + +**Вариант A/D:** Числовое значение enum вне разрешённого набора. **Основание:** sneakers, авторский разбор RuCTF. TryParse может принять число, +которому не соответствует объявленное имя. +Сканер: CS-ENUM, в том числе на уже исправленных вызовах. + +~~~csharp +if (!Enum.TryParse(input, out var kind) || + !Enum.IsDefined(typeof(FilterKind), kind)) + return BadRequest(); +~~~ + +Для Flags требуется отдельная разрешённая маска и политика комбинаций. +**Тест:** все допустимые имена, необъявленные числа, отрицательные/слишком +большие значения и комбинации. Это проверка значения, а не замена auth. + +[исходник/разбор 1](https://github.com/HackerDom/ructf-finals-2023/blob/a7442769909e08c39716cb18d3d1c3a99324bbf8/writeups/sneakers/README.md). + + + + + +## CS-SQL. Динамический SQL .NET + +**Поиск:** скрипт, правило CS-SQL. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain CS-SQL. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API. + +**Уязвимый вариант:** + +~~~csharp +context.Notes.FromSqlRaw("SELECT * FROM notes WHERE name=" + name); +~~~ + +**Исправление:** Параметризованный API конкретной ORM или провайдера и разрешённый набор идентификаторов; различать Raw и интерполируемый overload. + +~~~csharp +context.Notes.FromSqlRaw("SELECT * FROM notes WHERE name={0}", name); +~~~ + +**Проверка:** Кавычки — данные; owner_id сохраняется. + +
+Развёрнутый пример и ограничения + +```csharp +// Vulnerable: interpolation has already put client data into SQL source. +var rows = await db.Notes + .FromSqlRaw($"SELECT * FROM Notes WHERE Title = '{title}'") + .ToListAsync(ct); +``` + +**Минимальный патч для простого поиска — LINQ с ограничением владельца:** + +```csharp +using Microsoft.EntityFrameworkCore; + +var rows = await db.Notes + .Where(n => n.OwnerId == currentUserId && n.Title == title) + .ToListAsync(ct); +``` + +Если сырой SQL нужен, `FromSqlInterpolated` принимает интерполированное выражение +как `FormattableString` и параметризует значения. Не преобразовывать его сначала +в обычную `string` и не возвращать затем в `FromSqlRaw`. Метод `FromSql` появился +в EF Core 7; выбрать API своей версии. Имена колонок требуют фиксированного выбора. + +**Проверить:** имя с апострофом/Unicode ищется буквально, чужие записи отсутствуют, +пагинация и старые данные работают. Кастомный провайдер и перевод LINQ проверить +на используемой БД, не только на in-memory substitute. + +
+ + + + + +## CS-GUID-BYTES. Байтовый Guid на границе протокола + +**Поиск:** скрипт, правило CS-GUID-BYTES. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain CS-GUID-BYTES. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API. + +**Уязвимый вариант:** + +~~~csharp +var value = new Guid(wireBytes); +~~~ + +**Исправление:** Согласовать порядок байтов с другой стороной; использовать canonical text либо явное преобразование по протоколу, не разворачивать весь массив наугад. + +~~~csharp +var value = Guid.ParseExact(wireText, "D"); +~~~ + +**Проверка:** Несимметричные известные UUID совпадают в C#/Python; DB и cache сравнивают тот же ID. + + + + + +## CS-PROCESS. Создание процесса .NET + +**Поиск:** скрипт, правило CS-PROCESS. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain CS-PROCESS. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API. + +**Уязвимый вариант:** + +~~~csharp +Process.Start("sh", "-c " + command); +~~~ + +**Исправление:** Библиотечная операция либо фиксированный executable и ArgumentList. UseShellExecute=false не отменяет явный sh/cmd; учитывать option injection. + +~~~csharp +var digest = SHA256.HashData(Encoding.UTF8.GetBytes(text)); +~~~ + +**Проверка:** Кавычки — данные, штатный формат результата совпадает. + +
+Развёрнутый пример и ограничения + +```csharp +// Vulnerable on Linux: UseShellExecute=false does not prevent explicit /bin/sh. +var psi = new System.Diagnostics.ProcessStartInfo("/bin/sh") { UseShellExecute = false }; +psi.ArgumentList.Add("-c"); +psi.ArgumentList.Add("printf '%s' '" + text + "' | sha256sum"); +System.Diagnostics.Process.Start(psi); +``` + +**Патч для SHA-256 текста, .NET 6+:** + +```csharp +using System.Security.Cryptography; +using System.Text; + +static string DigestText(string text) +{ + ArgumentNullException.ThrowIfNull(text); + byte[] sum = SHA256.HashData(Encoding.UTF8.GetBytes(text)); + return Convert.ToHexString(sum).ToLowerInvariant(); +} +``` + +Сохранить внешний формат результата и кодировку. Для действительно необходимого +процесса задавать executable и `ArgumentList` отдельно; пользователь всё ещё +не должен выбирать опасные опции программы. SHA-256 содержимого не подходит +как самостоятельное хранение паролей. + +**Проверить:** известный digest, пустой текст, Unicode, кавычки и переводы строк; +нет дочернего процесса и утечки его окружения при ошибке. + +
+ +**Основание:** [первичный материал](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.processstartinfo.argumentlist). + + + + + +## CS-IGNORE-FILTERS. Отключение global query filters + +**Поиск:** скрипт, правило CS-IGNORE-FILTERS. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain CS-IGNORE-FILTERS. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API. + +**Уязвимый вариант:** + +~~~csharp +var rows = db.Notes.IgnoreQueryFilters().ToList(); +~~~ + +**Исправление:** Не отключать tenant/auth-фильтр ради soft-delete. Если bypass нужен администратору, явная авторизация и нужное ограничение в самом запросе. + +~~~csharp +var rows = db.Notes.Where(n => n.OwnerId == userId).ToList(); +~~~ + +**Проверка:** Два tenant, удалённая запись и export; проверять SQL реального провайдера. + +**Основание:** [первичный материал](https://learn.microsoft.com/en-us/ef/core/querying/filters). + + + + + +## CS-ALLOWANON. Маршрут с AllowAnonymous + +**Поиск:** скрипт, правило CS-ALLOWANON. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain CS-ALLOWANON. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API. + +**Уязвимый вариант:** + +~~~csharp +[AllowAnonymous] +public IActionResult PrivateNote() => View(); +~~~ + +**Исправление:** Проверить effective metadata endpoint и ownership. AllowAnonymous может отменить требование Authorize; login/health могут быть публичными по контракту. + +~~~csharp +[Authorize] +public IActionResult PrivateNote() => View(); +~~~ + +**Проверка:** Публичный login работает; приватный endpoint и вложенные операции требуют нужные права. + +**Основание:** [первичный материал](https://learn.microsoft.com/en-us/aspnet/core/security/authorization/simple). + + + + + +## CS-MASS-ASSIGN. Клиентская сущность целиком обновляет БД + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'Update\(|TryUpdateModelAsync|Bind\(|FromBody|SaveChanges' . +~~~ + +Сверить DTO, entity и изменяемые поля; не передаётся ли второй объект клиента после безопасной загрузки. + +**Уязвимый вариант:** + +db.Update(clientNote) применяет OwnerId/Role из JSON. + +**Исправление:** DTO редактируемых полей, загрузка по ID+owner, явные присваивания; concurrency token если права могут меняться. + +**Проверка:** Своё меняется, чужое и owner нет; null/отсутствующее поле различаются по контракту. + +
+Развёрнутый пример и ограничения + +```csharp +// Vulnerable: the supplied entity may contain OwnerId and administrative fields. +db.Update(clientNote); +await db.SaveChangesAsync(ct); +``` + +**Патч:** отдельный DTO редактируемых полей и загрузка принадлежащей пользователю +сущности. Тип DTO объявляется в проекте: + +```csharp +public sealed record EditNoteRequest(string? Title, string? Body); +``` + +Фрагмент действия контроллера с параметрами `id` и `EditNoteRequest dto`: + +```csharp +if (dto.Title is null || dto.Body is null) + return BadRequest(); + +var note = await db.Notes.SingleOrDefaultAsync( + n => n.Id == id && n.OwnerId == currentUserId, ct); +if (note is null) + return NotFound(); + +note.Title = dto.Title; +note.Body = dto.Body; +await db.SaveChangesAsync(ct); +return NoContent(); +``` + +Показан контракт полного обновления обоих полей, не JSON Merge Patch. При +частичном обновлении отдельно различать отсутствующее поле и явный `null`. +Не передавать в `Update` второй объект из запроса после загрузки безопасного. +Если владельца можно менять конкурентно, проверка при чтении и последующая +запись требуют подходящей транзакции/условного обновления/concurrency token. + +**Проверить:** владелец меняет title/body; чужая запись и её владелец не меняются; +присланный OwnerId не применяется; пустая строка сохраняется, если разрешена; +неверный тип отвергается. Неизвестные JSON-поля могут игнорироваться сериализатором — +не обещать их автоматический отказ без отдельной настройки. + +
+ +**Основание:** [первичный материал](https://learn.microsoft.com/en-us/aspnet/core/mvc/models/model-binding). + + + + + +## CS-XML. XML settings и внешние ресурсы + +**Поиск:** скрипт, правило CS-XML. Запуск: python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain CS-XML. Regex: DtdProcessing.Parse, XmlResolver=new XmlUrlResolver, ProhibitDtd=false. Точные defaults зависят от framework/API; отсутствие опасной строки не доказывает безопасность. + +Дополнительный ручной поиск для непокрытых форм: + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'XmlReaderSettings|DtdProcessing|XmlResolver|XmlDocument|XslCompiledTransform' . +~~~ + +Проверить явные settings и версию .NET; безопасные defaults нельзя переносить на каждый старый API. + +**Уязвимый вариант:** + +Разрешённый DTD/resolver загружает внешние ресурсы либо раздувает документ. + +**Исправление:** DtdProcessing.Prohibit при ненужном DTD, XmlResolver=null и лимиты входа; передать настройки фактически используемому XmlReader. Для XSLT отдельно запретить ненужные document/script. + +**Проверка:** Допустимый XML читается, внешние обращения отсутствуют, oversized expansion ограничен. + +**Основание:** [первичный материал](https://learn.microsoft.com/en-us/dotnet/api/system.xml.xmlreadersettings). + + +**Сигнал сканера — пример до:** + +~~~csharp +var settings = new XmlReaderSettings { DtdProcessing = DtdProcessing.Parse, XmlResolver = new XmlUrlResolver() }; +~~~ + +**Шаблон исправления:** + +~~~csharp +var settings = new XmlReaderSettings { DtdProcessing = DtdProcessing.Prohibit, XmlResolver = null, MaxCharactersInDocument = 1048576 }; +~~~ + +Первичная документация: [документация 1](https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca3075). + + + + + +## CS-HTML-RAW. Html.Raw и IHtmlContent обходят encoding + +**Поиск:** скрипт, правило CS-HTML-RAW. Запуск: python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain CS-HTML-RAW. Regex: Html.Raw и new HtmlString. Проверенный sanitizer не выводится из наличия вызова; доверенная статическая разметка может быть допустима. + +Дополнительный ручной поиск для непокрытых форм: + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'Html.Raw|HtmlString|IHtmlContent|WriteLiteral' . +~~~ + +Определить происхождение строки и реальный HTML/JS/attribute контекст Razor. + +**Уязвимый вариант:** + +Html.Raw(model.Text) выводит пользовательский HTML как доверенный. + +**Исправление:** Штатный Razor encoding; sanitizer только когда rich text нужен, отдельная сериализация JS. + +**Проверка:** Недоверенные теги, атрибуты и URL не могут выполнить скрипт; разрешённый текст и нужное форматирование отображаются корректно. + + +**Сигнал сканера — пример до:** + +~~~csharp +@Html.Raw(Model.About) +~~~ + +**Шаблон исправления:** + +~~~csharp +@Model.About +~~~ + +Первичная документация: [документация 1](https://learn.microsoft.com/en-us/aspnet/core/security/cross-site-scripting). + + + + + +## CS-PATH. Path.Combine и GetFullPath не проверяют owner + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'Path.Combine|GetFullPath|File.Read|File.Write|PhysicalFile' . +~~~ + +Сравнить полный путь/root с учётом ОС, separator и symlink; проверить право на выбранный ID. + +**Уязвимый вариант:** + +Абсолютный второй путь заменяет root либо строковый StartsWith путает соседний каталог. + +**Исправление:** Серверное имя, корректный containment по компонентам, политика symlink; запись открывать без гонки подмены. + +**Проверка:** Windows/Linux варианты, общий префикс, ссылка наружу, собственный/чужой файл. + + + + + +## CS-ARCHIVE. ZipArchive entry выходит из каталога + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'ZipArchive|ExtractToFile|ExtractToDirectory|FullName' . +~~~ + +Проверить конкретную версию API и собственный цикл по entries; наличие безопасного helper не защищает ручную запись. + +**Уязвимый вариант:** + +entry.FullName используется как путь без containment/лимита. + +**Исправление:** Валидация root, links и фактического объёма, отдельное временное дерево и атомарная публикация. + +**Проверка:** Штатный архив, absolute/traversal, дубли entry, превышение объёма. + +**Основание:** [первичный материал](https://cheatsheetseries.owasp.org/cheatsheets/File_Upload_Cheat_Sheet.html). + + + + + +## CS-CLAIMS. Неполная проверка JWT/claims + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'TokenValidationParameters|ValidateIssuer|ValidateAudience|RequireExpirationTime|FindFirst' . +~~~ + +Сверить серверный issuer/audience/key/algorithm и трактовку отсутствующих claims; подпись не задаёт права объекта. + +**Уязвимый вариант:** + +Токен другого назначения принимается как auth либо отсутствующий subject превращается в default пользователя. + +**Исправление:** Явный validation contract библиотеки, обязательный subject/purpose и resource auth; ротация ключа без бесконечного legacy fallback. + +**Проверка:** Неверные issuer/audience/срок/назначение и валидная сессия со старыми данными. + + + + + +## CS-ASYNC-VOID. async void скрывает ошибку auth + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'async void|Task.Run|Authorize|async Task|GetAwaiter' . +~~~ + +Проследить, что caller дожидается проверки; исключения из фонового действия не должны оставлять успешный ответ. + +**Уязвимый вариант:** + +Auth/запись запускается без await, обработчик продолжает выдачу данных. + +**Исправление:** Task-returning pipeline и await; fail closed при ошибке и request-scoped cancellation. + +**Проверка:** False/error/delay проверки не возвращают защищённые данные; корректный путь завершается. + + + + + +## CS-REGEX-TIMEOUT. Regex без бюджета на недоверенном вводе + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'new Regex|Regex.Match|Regex.IsMatch|Regex.Replace' . +~~~ + +Проверить timeout overload/NonBacktracking своего runtime и длину входа. + +**Уязвимый вариант:** + +Сложное выражение исчерпывает worker на длинном почти совпадающем тексте. + +**Исправление:** Ограничить размер, упростить pattern; поддержанный timeout/NonBacktracking, обработать RegexMatchTimeoutException как отказ. + +**Проверка:** Timeout не превращается в разрешение; обычные строки и допустимые regex-конструкции работают. + + + + + +## CS-AUTH-FILTER-REDUCE. Упрощение фильтра удаляет обязательное условие доступа + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'Distinct|Remove|Reduce|AdminFilter|Equals' . +~~~ + +Сравнить обязательное условие доступа до и после упрощения дерева запроса; проверить структурное равенство фильтров. + +**Уязвимый вариант:** + +**Основание:** sneakers, авторский разбор RuCTF. Равенство объектов-фильтров и +упрощение выражения могли убрать AdminFilter. + +**Искать:** distinct/remove/set/dedup/reduce над AST запросов; структурное +равенство record вместо ожидаемой идентичности; объединение клиентских и +серверных фильтров. + +**Исправление:** обязательное условие auth добавлять вне +пользовательского упрощения и проверять перед исполнением. Изменение record +на class из одного разбора не универсальный рецепт. + +**Проверка:** эквивалентные/повторённые/вложенные фильтры не расширяют права; +порядок предикатов не влияет на доступ. + +**Вариант A/D:** Основание и версия: [исходник/разбор 1](https://github.com/HackerDom/ructf-finals-2023/blob/a7442769909e08c39716cb18d3d1c3a99324bbf8/writeups/sneakers/README.md). + +**Основание:** [первичный материал](https://github.com/HackerDom/ructf-finals-2023/blob/a7442769909e08c39716cb18d3d1c3a99324bbf8/writeups/sneakers/README.md). + + + + + +## CS-COLLIDING-PRINCIPAL. Нормализованная сумма символов вместо уникального user ID + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'UserId|UserName|ToLower|Reverse|Sum' . +~~~ + +Сопоставить нормализованное имя, вычисленный ID и ключ owner во всех export/read/update. + +**Уязвимый вариант:** + +**FAUST / todo-list, код + патч организаторов.** Преобразования имени и сумма +символов используются как идентификатор владельца; разные имена могут совпасть. + +**Исправление:** авторизация по стабильному уникальному principal из доверенного +хранилища, согласованная миграция записей. Исправить все пути чтения/экспорта. + +**Проверка:** два имени с одинаковым старым ID не получают общий доступ. + +**Вариант A/D:** Основание и версия: [исходник/разбор 1](https://github.com/fausecteam/faustctf-2024-todo-list-service/blob/e9ee8b8807c64eeb6f71a72e16f709a558525d2c/patches/deserialize.patch); [исходник/разбор 2](https://github.com/fausecteam/faustctf-2024-todo-list-service/blob/e9ee8b8807c64eeb6f71a72e16f709a558525d2c/patches/TodoController.cs); [исходник/разбор 3](https://github.com/fausecteam/faustctf-2024-todo-list-service/blob/e9ee8b8807c64eeb6f71a72e16f709a558525d2c/service/service/Services/Serializer.cs); [исходник/разбор 4](https://github.com/fausecteam/faustctf-2024-todo-list-service/blob/e9ee8b8807c64eeb6f71a72e16f709a558525d2c/service/service/Services/UserManager.cs); [исходник/разбор 5](https://github.com/fausecteam/faustctf-2024-todo-list-service/blob/e9ee8b8807c64eeb6f71a72e16f709a558525d2c/service/service/Models/Filter.cs). + +**Основание:** [первичный материал](https://github.com/fausecteam/faustctf-2024-todo-list-service/blob/e9ee8b8807c64eeb6f71a72e16f709a558525d2c/patches/deserialize.patch). + + + + + +## CS-JWT-VALIDATION. Ослаблены параметры проверки токенов .NET + +**Поиск:** скрипт, правило CS-JWT-VALIDATION. Запуск: python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain CS-JWT-VALIDATION. Regex: явные false для ValidateLifetime/Issuer/Audience, RequireSignedTokens/ExpirationTime. ValidateIssuerSigningKey=false отдельно не трактуется как отсутствие криптографической проверки. + +**Уязвимый вариант:** Отключение lifetime/issuer/audience или требования подписи может принять токен вне назначенного контракта. + +~~~csharp +new TokenValidationParameters { ValidateLifetime = false, ValidateAudience = false, RequireSignedTokens = false }; +~~~ + +**Исправление:** Проверять обязательную подпись, ключ, время, издателя и получателя; custom validators должны сохранять эти инварианты. + +~~~csharp +new TokenValidationParameters { ValidateLifetime = true, ValidateAudience = true, ValidAudience = "notes", ValidateIssuer = true, ValidIssuer = "auth", RequireSignedTokens = true, RequireExpirationTime = true, IssuerSigningKey = trustedKey }; +~~~ + +**Проверка:** Неподписанный, просроченный и чужой токен не авторизует; штатный токен принимается. + +Первичная документация: [документация 1](https://learn.microsoft.com/en-us/dotnet/api/microsoft.identitymodel.tokens.tokenvalidationparameters). + + + + + +## CS-TLS-VALIDATION. HTTPS validation callback всегда разрешает + +**Поиск:** скрипт, правило CS-TLS-VALIDATION. Запуск: python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain CS-TLS-VALIDATION. Regex: DangerousAcceptAnyServerCertificateValidator и простая true-lambda для certificate callbacks. Произвольные методы и body-lambda требуют ручного анализа. + +**Уязвимый вариант:** Callback, безусловно принимающий сертификат, обходит стандартную проверку TLS. + +~~~csharp +handler.ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator; +~~~ + +**Исправление:** Использовать стандартную проверку и доверенный CA; custom trust реализовать без безусловного true. + +~~~csharp +var handler = new HttpClientHandler(); +var client = new HttpClient(handler); +~~~ + +**Проверка:** Корректный сертификат работает, чужое имя/CA и истечение дают ошибку. + +Первичная документация: [документация 1](https://learn.microsoft.com/en-us/dotnet/api/system.net.http.httpclienthandler.dangerousacceptanyservercertificatevalidator). + + + + + +## CS-LDAP-FILTER. Фильтр DirectorySearcher собирается конкатенацией + +**Поиск:** правило сканера CS-LDAP-FILTER. Точный контракт детектора: `--explain CS-LDAP-FILTER`. Regex с лексическими исключениями: new DirectorySearcher, первый аргумент которого — строковый литерал, объединённый с идентификатором. Не проверяет присваивания Filter, интерполированные строки, реализации вспомогательных функций и произвольные aliases типов. + +**Уязвимый вариант:** + +~~~csharp +var query = new DirectorySearcher("(uid=" + name + ")"); +~~~ + +**Исправление:** Используйте проверенный конструктор LDAP-фильтров с экранированием для контекста фильтра и фиксированной политикой атрибутов и области поиска; вспомогательная функция реализуется в приложении. + +~~~csharp +var query = new DirectorySearcher(BuildReviewedLdapFilter(name)); // helper implements filter-context escaping +~~~ + +**Проверка:** Метасимволы не добавляют условия и не расширяют результат; поддерживаемые поисковые запросы остаются совместимыми. + +[Первичный источник 1](https://learn.microsoft.com/en-us/dotnet/api/system.directoryservices.directorysearcher.filter) diff --git a/docs/vulnerabilities/csharp.md b/docs/vulnerabilities/csharp.md new file mode 100644 index 0000000..a36538d --- /dev/null +++ b/docs/vulnerabilities/csharp.md @@ -0,0 +1,607 @@ +# C# / .NET: find, fix and verify + +English | [Русский](csharp-RU.md) + +[Catalog](README.md) · [Scanner](../offline-scanner.md) · [Patch verification](../patch-validation.md) + +20 sections. Each follows **Search → Vulnerable example → Fix → Verification**. +Run `rg` from a local service checkout; searches only read files. Derive the actor/owner from a verified session, not request data. Adapt examples to the actual API and contract. + +## Contents + +- [CS-DESERIALIZE — Type-controlled .NET deserialization](#cs-deserialize) +- [CS-ENUM — Enum.TryParse requires an allowed-value check](#cs-enum) +- [CS-SQL — Dynamic .NET SQL](#cs-sql) +- [CS-GUID-BYTES — Byte-order Guid protocol boundary](#cs-guid-bytes) +- [CS-PROCESS — .NET process creation](#cs-process) +- [CS-IGNORE-FILTERS — Global query filters disabled](#cs-ignore-filters) +- [CS-ALLOWANON — AllowAnonymous route](#cs-allowanon) +- [CS-MASS-ASSIGN — Client entities update the database wholesale](#cs-mass-assign) +- [CS-XML — XML parser permits DTD or external resolver](#cs-xml) +- [CS-HTML-RAW — HTML output without escaping](#cs-html-raw) +- [CS-PATH — Path.Combine and GetFullPath do not check ownership](#cs-path) +- [CS-ARCHIVE — ZipArchive entries escape the directory](#cs-archive) +- [CS-CLAIMS — Incomplete JWT or claims validation](#cs-claims) +- [CS-ASYNC-VOID — async void hides authorization errors](#cs-async-void) +- [CS-REGEX-TIMEOUT — Untrusted regex input without a budget](#cs-regex-timeout) +- [CS-AUTH-FILTER-REDUCE — Simplification removes a mandatory authorization condition](#cs-auth-filter-reduce) +- [CS-COLLIDING-PRINCIPAL — A normalized character sum replaces a unique user ID](#cs-colliding-principal) +- [CS-JWT-VALIDATION — Weakened .NET token validation](#cs-jwt-validation) +- [CS-TLS-VALIDATION — HTTPS validation callback always accepts](#cs-tls-validation) +- [CS-LDAP-FILTER — DirectorySearcher filter concatenates a value](#cs-ldap-filter) + + + +## CS-DESERIALIZE. Type-controlled .NET deserialization + +**Search:** scanner rule CS-DESERIALIZE. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain CS-DESERIALIZE` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries. + +**Vulnerable example:** + +~~~csharp +var formatter = new BinaryFormatter(); +~~~ + +**Fix:** Use explicit DTOs and a supported serializer with schema/size checks; remove unrestricted type activation and migrate legacy data. + +~~~csharp +var value = JsonSerializer.Deserialize(json); // validate fields +~~~ + +**Verification:** Unknown types fail before side effects; valid records parse. + +**A/D variant:** Deserialization triggers setter side effects. **FAUST / todo-list, source and organizer patch.** TypeNameHandling.Objects permits runtime-type selection; setting Filter model fields writes to the database. Checking the result after object construction may be too late. + +**Patch:** A concrete DTO without external type selection, explicit validation and a separate persistence operation. **Test:** Unknown types create neither objects nor rows; normal import/export remains compatible. **Search:** CS-DESERIALIZE. + +[source/write-up 1](https://github.com/fausecteam/faustctf-2024-todo-list-service/blob/e9ee8b8807c64eeb6f71a72e16f709a558525d2c/patches/deserialize.patch); [source/write-up 2](https://github.com/fausecteam/faustctf-2024-todo-list-service/blob/e9ee8b8807c64eeb6f71a72e16f709a558525d2c/patches/TodoController.cs); [source/write-up 3](https://github.com/fausecteam/faustctf-2024-todo-list-service/blob/e9ee8b8807c64eeb6f71a72e16f709a558525d2c/service/service/Services/Serializer.cs); [source/write-up 4](https://github.com/fausecteam/faustctf-2024-todo-list-service/blob/e9ee8b8807c64eeb6f71a72e16f709a558525d2c/service/service/Services/UserManager.cs); [source/write-up 5](https://github.com/fausecteam/faustctf-2024-todo-list-service/blob/e9ee8b8807c64eeb6f71a72e16f709a558525d2c/service/service/Models/Filter.cs). + + + +## CS-ENUM. Enum.TryParse requires an allowed-value check + +**Search:** scanner rule CS-ENUM. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain CS-ENUM` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries. + +**Vulnerable example:** + +~~~csharp +bool ok = Enum.TryParse(input, out FilterKind kind); +~~~ + +**Fix:** Validate allowed named values; parsing success alone does not prove enum membership. + +~~~csharp +if (!TryParseAllowedFilter(input, out FilterKind kind)) return BadRequest(); // helper validates named allowlist +~~~ + +**Verification:** Unnamed numeric values and unsupported flags fail; supported filters work. + +**A/D variant:** Numeric enum values outside the allowed set. **Reference:** sneakers, RuCTF author write-up. TryParse may accept a number with no declared name. Scanner: CS-ENUM, including already-corrected call sites. + +~~~csharp +if (!Enum.TryParse(input, out var kind) || + !Enum.IsDefined(typeof(FilterKind), kind)) + return BadRequest(); +~~~ + +Flags require an explicit allowed mask and combination policy. **Test:** Every allowed name, undeclared numbers, negative/oversized values and combinations. Value validation is not authorization. + +[source/write-up 1](https://github.com/HackerDom/ructf-finals-2023/blob/a7442769909e08c39716cb18d3d1c3a99324bbf8/writeups/sneakers/README.md). + + + +## CS-SQL. Dynamic .NET SQL + +**Search:** scanner rule CS-SQL. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain CS-SQL` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries. + +**Vulnerable example:** + +~~~csharp +context.Notes.FromSqlRaw("SELECT * FROM notes WHERE name=" + name); +~~~ + +**Fix:** Use provider-supported parameters and allowlisted identifiers. + +~~~csharp +context.Notes.FromSqlRaw("SELECT * FROM notes WHERE name={0}", name); +~~~ + +**Verification:** Quotes cannot change SQL structure; tenant restrictions remain. + +
+Expanded example and limitations + +```csharp +// Vulnerable: interpolation has already put client data into SQL source. +var rows = await db.Notes + .FromSqlRaw($"SELECT * FROM Notes WHERE Title = '{title}'") + .ToListAsync(ct); +``` + +**Minimal patch for a simple search: owner-scoped LINQ:** + +```csharp +using Microsoft.EntityFrameworkCore; + +var rows = await db.Notes + .Where(n => n.OwnerId == currentUserId && n.Title == title) + .ToListAsync(ct); +``` + +When raw SQL is necessary, FromSqlInterpolated receives a FormattableString and parameterizes values. Do not first convert it to string and then pass it to FromSqlRaw. FromSql appeared in EF Core 7; select the installed version's API. Column names require fixed selection. + +**Check:** Apostrophes/Unicode remain literal search data, foreign rows are absent, and pagination/old records work. Test custom providers and LINQ translation against the actual database, not only an in-memory substitute. + +
+ + + +## CS-GUID-BYTES. Byte-order Guid protocol boundary + +**Search:** scanner rule CS-GUID-BYTES. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain CS-GUID-BYTES` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries. + +**Vulnerable example:** + +~~~csharp +var value = new Guid(wireBytes); +~~~ + +**Fix:** Agree on byte order with peers; use canonical text or explicit conversion, not arbitrary reversal. + +~~~csharp +var value = Guid.ParseExact(wireText, "D"); +~~~ + +**Verification:** Asymmetric UUID vectors agree across C#/Python, database and cache. + + + +## CS-PROCESS. .NET process creation + +**Search:** scanner rule CS-PROCESS. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain CS-PROCESS` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries. + +**Vulnerable example:** + +~~~csharp +Process.Start("sh", "-c " + command); +~~~ + +**Fix:** Prefer a library operation or fixed executable plus ArgumentList. UseShellExecute=false does not neutralize explicit sh/cmd or option injection. + +~~~csharp +var digest = SHA256.HashData(Encoding.UTF8.GetBytes(text)); +~~~ + +**Verification:** Quotes stay data and expected output format is preserved. + +
+Expanded example and limitations + +```csharp +// Vulnerable on Linux: UseShellExecute=false does not prevent explicit /bin/sh. +var psi = new System.Diagnostics.ProcessStartInfo("/bin/sh") { UseShellExecute = false }; +psi.ArgumentList.Add("-c"); +psi.ArgumentList.Add("printf '%s' '" + text + "' | sha256sum"); +System.Diagnostics.Process.Start(psi); +``` + +**Patch for text SHA-256, .NET 6+:** + +```csharp +using System.Security.Cryptography; +using System.Text; + +static string DigestText(string text) +{ + ArgumentNullException.ThrowIfNull(text); + byte[] sum = SHA256.HashData(Encoding.UTF8.GetBytes(text)); + return Convert.ToHexString(sum).ToLowerInvariant(); +} +``` + +Preserve external formatting and encoding. If a process is genuinely required, separate executable and ArgumentList; users must still not select dangerous program options. Content SHA-256 is not standalone password storage. + +**Check:** Known digest, empty text, Unicode, quotes/newlines; no child process or environment leakage on failure. + +
+ +**Reference:** [primary source](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.processstartinfo.argumentlist). + + + +## CS-IGNORE-FILTERS. Global query filters disabled + +**Search:** scanner rule CS-IGNORE-FILTERS. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain CS-IGNORE-FILTERS` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries. + +**Vulnerable example:** + +~~~csharp +var rows = db.Notes.IgnoreQueryFilters().ToList(); +~~~ + +**Fix:** Do not disable tenant/auth filters merely for soft-delete; admin bypass requires explicit authorization and query restrictions. + +~~~csharp +var rows = db.Notes.Where(n => n.OwnerId == userId).ToList(); +~~~ + +**Verification:** Test two tenants, deleted records and exports against the actual provider SQL. + +**Reference:** [primary source](https://learn.microsoft.com/en-us/ef/core/querying/filters). + + + +## CS-ALLOWANON. AllowAnonymous route + +**Search:** scanner rule CS-ALLOWANON. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain CS-ALLOWANON` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries. + +**Vulnerable example:** + +~~~csharp +[AllowAnonymous] +public IActionResult PrivateNote() => View(); +~~~ + +**Fix:** Review effective endpoint metadata/ownership; AllowAnonymous may override Authorize. Login/health may be intentionally public. + +~~~csharp +[Authorize] +public IActionResult PrivateNote() => View(); +~~~ + +**Verification:** Public login works; private endpoints and nested operations require authorization. + +**Reference:** [primary source](https://learn.microsoft.com/en-us/aspnet/core/security/authorization/simple). + + + +## CS-MASS-ASSIGN. Client entities update the database wholesale + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'Update\(|TryUpdateModelAsync|Bind\(|FromBody|SaveChanges' . +~~~ + +Compare DTOs, entities and mutable fields; ensure a second client object is not used after safely loading the owned one. + +**Vulnerable example:** + +`db.Update(clientNote)` applies OwnerId/Role from JSON. + +**Fix:** Editable-fields DTO, lookup by ID+owner and explicit assignment; use concurrency tokens if ownership can change. + +**Verification:** Owned fields change; another user's record/owner does not. Distinguish absent fields from null according to contract. + +
+Expanded example and limitations + +```csharp +// Vulnerable: the supplied entity may contain OwnerId and administrative fields. +db.Update(clientNote); +await db.SaveChangesAsync(ct); +``` + +**Patch:** Separate editable-fields DTO and an owner-scoped entity lookup. Declare the DTO in the project: + +```csharp +public sealed record EditNoteRequest(string? Title, string? Body); +``` + +Controller action fragment with parameters `id` and `EditNoteRequest dto`: + +```csharp +if (dto.Title is null || dto.Body is null) + return BadRequest(); + +var note = await db.Notes.SingleOrDefaultAsync( + n => n.Id == id && n.OwnerId == currentUserId, ct); +if (note is null) + return NotFound(); + +note.Title = dto.Title; +note.Body = dto.Body; +await db.SaveChangesAsync(ct); +return NoContent(); +``` + +This is a full update of both fields, not JSON Merge Patch. For partial updates distinguish omitted fields from explicit null. Do not pass a second request object to Update after safely loading the first. Concurrent ownership changes require a suitable transaction, conditional mutation or concurrency token. + +**Check:** Owners edit title/body; foreign records/owners remain unchanged; supplied OwnerId is ignored; empty strings persist if allowed; wrong types fail. Unknown JSON fields may be ignored by the serializer—do not promise rejection without explicit configuration. + +
+ +**Reference:** [primary source](https://learn.microsoft.com/en-us/aspnet/core/mvc/models/model-binding). + + + +## CS-XML. XML parser permits DTD or external resolver + +**Search:** scanner rule CS-XML. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain CS-XML` for details. Regex: DtdProcessing.Parse, XmlResolver=new XmlUrlResolver and ProhibitDtd=false. Defaults depend on framework/API; absence of a match is not proof of safety. + +Additional manual search for forms outside automatic coverage: + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'XmlReaderSettings|DtdProcessing|XmlResolver|XmlDocument|XslCompiledTransform' . +~~~ + +Review explicit settings and the actual .NET version; modern safe defaults do not apply to every older API. + +**Vulnerable example:** + +An enabled DTD/resolver fetches external resources or expands the document. + +**Fix:** Prohibit DTD, remove external resolver and bound input; pass these settings to the actual XmlReader. + +**Verification:** Ordinary XML works; external resources/DTD fail and size is bounded. + +**Reference:** [primary source](https://learn.microsoft.com/en-us/dotnet/api/system.xml.xmlreadersettings). + +**Scanner example before:** + +~~~csharp +var settings = new XmlReaderSettings { DtdProcessing = DtdProcessing.Parse, XmlResolver = new XmlUrlResolver() }; +~~~ + +**Fix template:** + +~~~csharp +var settings = new XmlReaderSettings { DtdProcessing = DtdProcessing.Prohibit, XmlResolver = null, MaxCharactersInDocument = 1048576 }; +~~~ + +Primary documentation: [reference 1](https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca3075). + + + +## CS-HTML-RAW. HTML output without escaping + +**Search:** scanner rule CS-HTML-RAW. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain CS-HTML-RAW` for details. Regex: Html.Raw and new HtmlString. Sanitization is not inferred from a call; trusted static markup may be legitimate. + +Additional manual search for forms outside automatic coverage: + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'Html.Raw|HtmlString|IHtmlContent|WriteLiteral' . +~~~ + +Determine data origin and Razor's actual HTML, JavaScript or attribute context. + +**Vulnerable example:** + +`Html.Raw(model.Text)` treats user-controlled HTML as trusted. + +**Fix:** Use regular Razor output or an allowlisted HTML sanitizer for supported rich text; consider URL/JS context. + +**Verification:** Untrusted tags, attributes and URLs cannot execute script; permitted text renders. + +**Scanner example before:** + +~~~csharp +@Html.Raw(Model.About) +~~~ + +**Fix template:** + +~~~csharp +@Model.About +~~~ + +Primary documentation: [reference 1](https://learn.microsoft.com/en-us/aspnet/core/security/cross-site-scripting). + + + +## CS-PATH. Path.Combine and GetFullPath do not check ownership + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'Path.Combine|GetFullPath|File.Read|File.Write|PhysicalFile' . +~~~ + +Compare full path/root with OS, separator and symlink semantics; authorize the selected ID. + +**Vulnerable example:** + +An absolute second path replaces the root, or string StartsWith accepts a similarly named sibling directory. + +**Fix:** Server-side names, component-aware containment and symlink policy; open writes without replacement races. + +**Verification:** Windows/Linux forms, shared prefixes, outward links and own/foreign files. + + + +## CS-ARCHIVE. ZipArchive entries escape the directory + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'ZipArchive|ExtractToFile|ExtractToDirectory|FullName' . +~~~ + +Review the actual API version and custom entry loop; a safe helper does not protect separately implemented writes. + +**Vulnerable example:** + +`entry.FullName` becomes a path without containment or size limits. + +**Fix:** Validate root/links and actual expanded volume; use a separate temporary tree and atomic publication. + +**Verification:** Ordinary archives, absolute/traversal names, duplicate entries and expanded-size overflow. + +**Reference:** [primary source](https://cheatsheetseries.owasp.org/cheatsheets/File_Upload_Cheat_Sheet.html). + + + +## CS-CLAIMS. Incomplete JWT or claims validation + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'TokenValidationParameters|ValidateIssuer|ValidateAudience|RequireExpirationTime|FindFirst' . +~~~ + +Review server-side issuer/audience/key/algorithm policy and missing claims; a signature does not authorize an object. + +**Vulnerable example:** + +A token intended for another purpose is accepted for authentication, or missing subject becomes a default user. + +**Fix:** Explicit library validation contract, required subject/purpose and resource authorization; rotate keys without indefinite legacy fallback. + +**Verification:** Wrong issuer/audience/expiry/purpose plus valid sessions and old data. + + + +## CS-ASYNC-VOID. async void hides authorization errors + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'async void|Task.Run|Authorize|async Task|GetAwaiter' . +~~~ + +Ensure callers await verification; background exceptions must not leave successful responses. + +**Vulnerable example:** + +Authorization or writes start without await while the handler continues returning data. + +**Fix:** A Task-returning pipeline with await, fail-closed errors and request-scoped cancellation. + +**Verification:** False/error/delayed checks never return protected data; legitimate requests complete. + + + +## CS-REGEX-TIMEOUT. Untrusted regex input without a budget + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'new Regex|Regex.Match|Regex.IsMatch|Regex.Replace' . +~~~ + +Review timeout overloads/NonBacktracking support in the installed runtime and input length limits. + +**Vulnerable example:** + +A complex expression consumes a worker on a long near-match. + +**Fix:** Bound size, simplify patterns, use supported timeout/NonBacktracking modes and treat RegexMatchTimeoutException as rejection. + +**Verification:** Timeout never becomes permission; ordinary strings and required regex constructs still work. + + + +## CS-AUTH-FILTER-REDUCE. Simplification removes a mandatory authorization condition + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'Distinct|Remove|Reduce|AdminFilter|Equals' . +~~~ + +Compare mandatory access conditions before and after query-tree simplification; inspect structural equality of filters. + +**Vulnerable example:** + +**Reference:** sneakers, RuCTF author write-up. Filter-object equality and expression simplification could remove AdminFilter. + +**Search:** distinct/remove/set/dedup/reduce on query ASTs, record structural equality where identity was expected, and combinations of client/server filters. + +**Fix:** Add mandatory authorization outside user-controlled simplification and verify it before execution. Changing record to class in one write-up is not a universal remedy. + +**Verification:** Equivalent, duplicate and nested filters never broaden access; predicate order does not affect permissions. + +**A/D variant:** Source and version: [source/write-up 1](https://github.com/HackerDom/ructf-finals-2023/blob/a7442769909e08c39716cb18d3d1c3a99324bbf8/writeups/sneakers/README.md). + +**Reference:** [primary source](https://github.com/HackerDom/ructf-finals-2023/blob/a7442769909e08c39716cb18d3d1c3a99324bbf8/writeups/sneakers/README.md). + + + +## CS-COLLIDING-PRINCIPAL. A normalized character sum replaces a unique user ID + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'UserId|UserName|ToLower|Reverse|Sum' . +~~~ + +Compare normalized names, computed IDs and owner keys across export/read/update. + +**Vulnerable example:** + +**FAUST / todo-list, source and organizer patch.** Name transformations and character sums identify owners; different names can collide. + +**Fix:** Authorize with stable unique principals from trusted storage and migrate existing records coherently. Fix every read/export path. + +**Verification:** Two names sharing the old ID never share access. + +**A/D variant:** Source and version: [source/write-up 1](https://github.com/fausecteam/faustctf-2024-todo-list-service/blob/e9ee8b8807c64eeb6f71a72e16f709a558525d2c/patches/deserialize.patch); [source/write-up 2](https://github.com/fausecteam/faustctf-2024-todo-list-service/blob/e9ee8b8807c64eeb6f71a72e16f709a558525d2c/patches/TodoController.cs); [source/write-up 3](https://github.com/fausecteam/faustctf-2024-todo-list-service/blob/e9ee8b8807c64eeb6f71a72e16f709a558525d2c/service/service/Services/Serializer.cs); [source/write-up 4](https://github.com/fausecteam/faustctf-2024-todo-list-service/blob/e9ee8b8807c64eeb6f71a72e16f709a558525d2c/service/service/Services/UserManager.cs); [source/write-up 5](https://github.com/fausecteam/faustctf-2024-todo-list-service/blob/e9ee8b8807c64eeb6f71a72e16f709a558525d2c/service/service/Models/Filter.cs). + +**Reference:** [primary source](https://github.com/fausecteam/faustctf-2024-todo-list-service/blob/e9ee8b8807c64eeb6f71a72e16f709a558525d2c/patches/deserialize.patch). + + + +## CS-JWT-VALIDATION. Weakened .NET token validation + +**Search:** scanner rule CS-JWT-VALIDATION. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain CS-JWT-VALIDATION` for details. Regex: explicit false for ValidateLifetime/Issuer/Audience and RequireSignedTokens/ExpirationTime. ValidateIssuerSigningKey=false alone is not treated as missing signature verification. + +**Vulnerable example:** Disabling lifetime/issuer/audience validation or signature requirements accepts tokens outside the intended contract. + +~~~csharp +new TokenValidationParameters { ValidateLifetime = false, ValidateAudience = false, RequireSignedTokens = false }; +~~~ + +**Fix:** Validate signature, key, time, issuer and audience; custom validators must retain these invariants. + +~~~csharp +new TokenValidationParameters { ValidateLifetime = true, ValidateAudience = true, ValidAudience = "notes", ValidateIssuer = true, ValidIssuer = "auth", RequireSignedTokens = true, RequireExpirationTime = true, IssuerSigningKey = trustedKey }; +~~~ + +**Verification:** Unsigned, expired and foreign tokens fail; valid tokens pass. + +Primary documentation: [reference 1](https://learn.microsoft.com/en-us/dotnet/api/microsoft.identitymodel.tokens.tokenvalidationparameters). + + + +## CS-TLS-VALIDATION. HTTPS validation callback always accepts + +**Search:** scanner rule CS-TLS-VALIDATION. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain CS-TLS-VALIDATION` for details. Regex: DangerousAcceptAnyServerCertificateValidator and simple true-lambdas for certificate callbacks. Arbitrary methods and block-bodied lambdas need manual review. + +**Vulnerable example:** An unconditional certificate-accepting callback bypasses standard TLS validation. + +~~~csharp +handler.ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator; +~~~ + +**Fix:** Use default certificate checks and trusted CA; custom trust must not unconditionally accept. + +~~~csharp +var handler = new HttpClientHandler(); +var client = new HttpClient(handler); +~~~ + +**Verification:** Valid certificates work; wrong host/CA and expiry fail. + +Primary documentation: [reference 1](https://learn.microsoft.com/en-us/dotnet/api/system.net.http.httpclienthandler.dangerousacceptanyservercertificatevalidator). + + + +## CS-LDAP-FILTER. DirectorySearcher filter concatenates a value + +**Search:** scanner rule CS-LDAP-FILTER. Use `--explain CS-LDAP-FILTER` for the exact detector contract. Regex with lexical exclusions: new DirectorySearcher with a first string literal concatenated with an identifier. Does not inspect Filter assignments, interpolated strings, helper implementations or arbitrary type aliases. + +**Vulnerable example:** + +~~~csharp +var query = new DirectorySearcher("(uid=" + name + ")"); +~~~ + +**Fix:** Use a reviewed LDAP filter builder with filter-context escaping and fixed attribute/scope policy; the helper is application-specific. + +~~~csharp +var query = new DirectorySearcher(BuildReviewedLdapFilter(name)); // helper implements filter-context escaping +~~~ + +**Verification:** Metacharacters cannot add conditions or broaden results; supported lookups remain compatible. + +[Primary reference 1](https://learn.microsoft.com/en-us/dotnet/api/system.directoryservices.directorysearcher.filter) diff --git a/docs/vulnerabilities/go-RU.md b/docs/vulnerabilities/go-RU.md new file mode 100644 index 0000000..ff71393 --- /dev/null +++ b/docs/vulnerabilities/go-RU.md @@ -0,0 +1,682 @@ + + +# Go: поиск и исправление + +[English](go.md) | Русский + +[Вся база](README-RU.md) · [Сканер](../offline-scanner-RU.md) · [Проверка патча](../patch-validation-RU.md) + +19 разделов. Формат: **Поиск → Уязвимый вариант → Исправление → Проверка**. +Команды `rg` выполняются в корне локальной копии сервиса и только читают файлы. Субъект/владелец определяется по проверенной сессии, а не данным запроса. Примеры нужно адаптировать к реальным API и контракту. + +Автоматические находки — ограниченные синтаксические сигналы для проверки. AST-анализ не разрешает типы и не отслеживает данные между функциями; regex не заменяет парсер языка. Комментарии, строки и одноимённые пользовательские API могут давать совпадения. Проверьте фактическое исполнение, входные данные, авторизацию и границы доверия. + + + +## Содержание + +- [GO-SQL — Динамический SQL Go](#go-sql) +- [GO-HASH-SUM — Непустой аргумент hash.Sum](#go-hash-sum) +- [GO-HTML — Обход autoescape Go](#go-html) +- [GO-TLS — InsecureSkipVerify](#go-tls) +- [GO-SHELL — Go exec.Command запускает shell](#go-shell) +- [GO-CRC — CRC используется как идентификатор/контроль доверия](#go-crc) +- [GO-MATH-RAND — math/rand рядом с возможным секретом](#go-math-rand) +- [GO-READALL-BODY — ReadAll тела запроса](#go-readall-body) +- [GO-PPROF — pprof регистрируется на HTTP mux](#go-pprof) +- [GO-FILESERVER — FileServer публикует дерево файлов](#go-fileserver) +- [GO-AUTH-RETURN — После http.Error выполнение продолжается](#go-auth-return) +- [GO-JSON-FIELDS — JSON в entity и неоднозначные ключи](#go-json-fields) +- [GO-RACE — Общие map/slice и check-then-use](#go-race) +- [GO-ERROR-DEFAULT — Игнорирование ошибки даёт нулевого субъекта](#go-error-default) +- [GO-SSRF — Go HTTP client и redirects](#go-ssrf) +- [GO-ZIP-PATH — filepath.Join не обеспечивает containment](#go-zip-path) +- [GO-TLS-MIN — Явно разрешён устаревший TLS](#go-tls-min) +- [GO-JWT-UNVERIFIED — JWT без подписи или проверки claims](#go-jwt-unverified) +- [GO-UPLOAD-PATH — Имя multipart-файла напрямую включается в путь](#go-upload-path) + + + + + +## GO-SQL. Динамический SQL Go + +**Поиск:** скрипт, правило GO-SQL. Запуск: python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain GO-SQL. Regex: Query/QueryRow/Exec/Prepare и Context-варианты с конкатенацией или fmt.Sprintf. Простой context expression поддержан; сложный синтаксис/aliases fmt и заранее собранный SQL вручную. + +**Уязвимый вариант:** + +~~~go +db.Query("SELECT id FROM notes WHERE name=" + name) +~~~ + +**Исправление:** Передавать значения аргументами; placeholder зависит от драйвера. Идентификаторы выбирать из разрешённого набора. + +~~~go +db.Query("SELECT id FROM notes WHERE name=$1", name) +~~~ + +**Проверка:** Кавычки — данные; права сохранены. + +
+Развёрнутый пример и ограничения + +```go +// Vulnerable: client input becomes SQL syntax. +q := fmt.Sprintf("SELECT body FROM notes WHERE id = '%s'", inputID) +err := db.QueryRowContext(ctx, q).Scan(&body) +``` + +**Патч для приватной заметки:** + +```go +import ( + "context" + "database/sql" +) + +func ReadPrivateNote(ctx context.Context, db *sql.DB, userID, noteID int64) (string, error) { + var body string + err := db.QueryRowContext(ctx, + "SELECT body FROM notes WHERE id = $1 AND owner_id = $2", + noteID, userID, + ).Scan(&body) + return body, err +} +``` + +До вызова разобрать ID через проверяемое преобразование, не игнорировать ошибку +парсинга. `sql.ErrNoRows` перевести в штатное отсутствие доступного объекта; +при любой иной ошибке не выдавать `body` как успешный результат. Для MySQL/другого +драйвера проверить синтаксис маркеров — он может отличаться. + +**Проверить:** своё, чужое, отсутствующий объект; неверный ID; отмена/таймаут +контекста; старые записи. В списках проверять ошибку `rows.Err()` после обхода. + +
+ + + + + +## GO-HASH-SUM. Непустой аргумент hash.Sum + +**Поиск:** скрипт, правило GO-HASH-SUM. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain GO-HASH-SUM. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API. + +**Уязвимый вариант:** + +~~~go +digest := h.Sum(record.Hash[:]) +~~~ + +**Исправление:** Hash.Sum(b) добавляет digest к b, не хеширует b: сначала Write(data), потом Sum(nil). Проверить длину/все подписанные поля. + +~~~go +h.Write(record.Hash[:]) +digest := h.Sum(nil) +~~~ + +**Проверка:** Результаты совпадают с известными тестовыми векторами; старые форматы digest мигрируют явно. Изменение каждого подписанного поля нарушает подпись. + +**Вариант A/D:** Sum не хеширует свой аргумент. **Основание:** certified-transparency, анализ трёх файлов saarCTF. +Checksum передавал Hash в Sum; ToHash копировал первые 32 байта результата. +Из семантики Go следует: эти байты могли быть исходным Hash, а не digest +ранее записанных Size/Timestamp. Полный сервис мы не воспроизводили. +Сканер: GO-HASH-SUM. + +~~~go +// Before: return ToHash(h.Sum(record.Hash[:])) +// After: include data in hash state, then extract only the digest. +h.Write(record.Hash[:]) +return ToHash(h.Sum(nil)) +~~~ + +**Тест:** изменить по одному Size, Timestamp, Hash: каждая старая подпись должна +перестать приниматься. Согласовать переход формата подписей и старые данные. +Непустой Sum не всегда ошибка: buf[:0] может использоваться для выделенной +заранее памяти. Поэтому сигнал требует чтения потребителя результата. + +[исходник/разбор 1](https://github.com/saarsec/saarctf-2024/blob/3a06d18974ca177c6dd251a11bdf9b4b334f382a/certified-transparency/service/pkg/models/serialization.go); [исходник/разбор 2](https://github.com/saarsec/saarctf-2024/blob/3a06d18974ca177c6dd251a11bdf9b4b334f382a/certified-transparency/service/pkg/models/models.go); [исходник/разбор 3](https://github.com/saarsec/saarctf-2024/blob/3a06d18974ca177c6dd251a11bdf9b4b334f382a/certified-transparency/service/pkg/signatures.go). + + + + + +## GO-HTML. Обход autoescape Go + +**Поиск:** скрипт, правило GO-HTML. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain GO-HTML. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API. + +**Уязвимый вариант:** + +~~~go +value := template.HTML(input) +~~~ + +**Исправление:** Обычная строка в html/template; sanitizer только для предусмотренного богатого HTML. + +~~~go +value := input // string passed to html/template +~~~ + +**Проверка:** Теги и кавычки пользователя отображаются текстом; предусмотренное форматирование работает. + +
+Развёрнутый пример и ограничения + +```go +// Vulnerable when message is client-controlled. +err := page.Execute(w, template.HTML(message)) +``` + +**Патч для вывода обычного текста:** + +```go +import ( + "html/template" + "io" +) + +func RenderMessage(w io.Writer, message string) error { + page, err := template.New("message").Parse("

{{.}}

") + if err != nil { + return err + } + return page.Execute(w, message) +} +``` + +Шаблон фиксирован; данные — обычная строка. Использовать `html/template`, а не +`text/template`, для HTML. Не заменять ошибку типом `template.JS`/`template.URL`: +эти типы тоже выражают доверие к данным. В реальном приложении фиксированный +шаблон можно разобрать один раз при старте. Если возможна ошибка рендеринга, +учесть частично записанный HTTP-ответ: при необходимости сначала рендерить в буфер. + +**Проверить:** разметка и кавычки отображаются текстом, Unicode сохранён; +сервис не стал компилировать сам message; допустимое форматирование по контракту работает. + +
+ + + + + +## GO-TLS. InsecureSkipVerify + +**Поиск:** скрипт, правило GO-TLS. Запуск: python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain GO-TLS. Regex: InsecureSkipVerify: true и присваивание .InsecureSkipVerify = true, включая переносы строк; ==/!= и false не сигналят. Наличие VerifyConnection не снимает review: тип объекта, достижимость, callback и итоговую конфигурацию проверить вручную. Комментарии и строки могут совпадать. + +**Уязвимый вариант:** + +~~~go +cfg := tls.Config{InsecureSkipVerify: true} +~~~ + +**Исправление:** Вернуть штатную проверку сертификата и имени сервера; при необходимости настроить RootCAs/ServerName. Проверить пользовательские callbacks проверки. + +~~~go +cfg := tls.Config{InsecureSkipVerify: false} +~~~ + +**Проверка:** Корректный сервер доступен; неверный сертификат отвергается. + +Опасная настройка может появиться после создания конфига: + +~~~go +cfg := &tls.Config{} +cfg.InsecureSkipVerify = true +~~~ + +Для обычного TLS-клиента вернуть `false` и настроить `RootCAs`/`ServerName` +для нужного сервера. Проверить доверенный сертификат, неизвестный CA, +несовпадающее имя и истёкший срок, сохранив доступ к штатному внутреннему CA. + +При `InsecureSkipVerify: true` приложение может реализовать собственную +проверку в `VerifyConnection`. Если она полноценно проверяет требуемую цепочку +и имя, флаг может быть обоснован; наличие callback само по себе этого не +доказывает. Сканер не анализирует его тело и сохраняет сигнал после такого +исправления. Сравнение `cfg.InsecureSkipVerify == true` не изменяет настройку +и отдельно не получает GO-TLS. [Go: tls.Config](https://pkg.go.dev/crypto/tls#Config). + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'InsecureSkipVerify|VerifyConnection|VerifyPeerCertificate|RootCAs|ServerName|TLSClientConfig' . +~~~ + +Связать конфигурацию с используемым transport, проследить все присваивания +и возвраты ошибки в callback, включая возобновлённые TLS-сессии. Значение из +переменной и эффективная конфигурация остаются ручной проверкой. Regex может +совпасть с комментарием или текстовым примером; это не подтверждение выполнения. + + + + + +## GO-SHELL. Go exec.Command запускает shell + +**Поиск:** скрипт, правило GO-SHELL. Запуск: python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain GO-SHELL. Regex: любой receiver.Command/CommandContext с буквальным shell и -c/-lc/-ec. Простой context expression, включая r.Context(), поддержан; вложенная запятая внутри context expression может скрыть вызов. Тип receiver и доверенность команды вручную. + +**Уязвимый вариант:** + +~~~go +cmd := exec.Command("sh", "-c", command) +~~~ + +**Исправление:** Фиксированный executable + argv. Для утилиты, читающей запись со stdin, передать её без shell и проверить разделители формата. + +~~~go +cmd := exec.Command("/usr/bin/file", "--", filename) +~~~ + +**Проверка:** Спецсимволы остаются данными, опасные опции/разделители отвергаются; штатные допустимые аргументы работают. + +
+Развёрнутый пример и ограничения + +```go +// Vulnerable: exec.Command starts a shell that parses input text. +out, err := exec.Command("sh", "-c", "printf '%s' '"+message+"' | sha256sum").Output() +``` + +**Патч для SHA-256 содержимого:** + +```go +import ( + "crypto/sha256" + "encoding/hex" +) + +func DigestText(message string) string { + sum := sha256.Sum256([]byte(message)) + return hex.EncodeToString(sum[:]) +} +``` + +Go-строка — байты; пример сохраняет их как есть. Если протокол требует именно +UTF-8, его корректность проверить отдельно. Сохранить внешний формат ответа, +который мог отличаться от сырого вывода `sha256sum`. Это не хеширование паролей. + +**Проверить:** известный digest, пустая строка, Unicode, кавычки и переводы строк; +нет запуска процесса. Для действительно нужной внешней команды задавать executable +и аргументы отдельно, ограничивать время через контекст; аргументы всё ещё может +интерпретировать сама программа. + +
+ +**Вариант A/D:** Shell спрятан во внутреннем backend. **ENOWARS / replme, автор.** Внутренний обработчик помещал пароль в shell-команду. +**Патч:** вызывать фиксированную утилиту без shell; данные передавать stdin +с проверкой разделителей её формата. Ограничивать пароль только буквами +без проверки контракта нельзя. **Тест:** пробелы и допустимые символы работают, +разделители записи отвергаются. **Поиск:** GO-SHELL; проследить весь вызов. + +[исходник/разбор 1](https://github.com/enowars/enowars8-service-replme/blob/3cdec50dd9a57f43f1c57f7b049319774a00e6c2/documentation/documentation/src/main.tex); [исходник/разбор 2](https://github.com/enowars/enowars8-service-replme/blob/3cdec50dd9a57f43f1c57f7b049319774a00e6c2/documentation/documentation/src/path-traversal.patch); [исходник/разбор 3](https://github.com/enowars/enowars8-service-replme/blob/3cdec50dd9a57f43f1c57f7b049319774a00e6c2/documentation/documentation/src/crc.patch); [исходник/разбор 4](https://github.com/enowars/enowars8-service-replme/blob/3cdec50dd9a57f43f1c57f7b049319774a00e6c2/service/backend/util/encoding.go); [исходник/разбор 5](https://github.com/enowars/enowars8-service-replme/blob/3cdec50dd9a57f43f1c57f7b049319774a00e6c2/service/backend/controller/repl.go); [исходник/разбор 6](https://github.com/enowars/enowars8-service-replme/blob/3cdec50dd9a57f43f1c57f7b049319774a00e6c2/service/image/service/user.go). + + + + + +## GO-CRC. CRC используется как идентификатор/контроль доверия + +**Поиск:** скрипт, правило GO-CRC. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain GO-CRC. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API. + +**Уязвимый вариант:** + +~~~go +resource := service.CRC.Calculate(username) +~~~ + +**Исправление:** CRC не граница между пользователями. Для отображения ресурса — серверный уникальный ID/криптохеш + отдельная проверка владельца; для MAC — HMAC, не простой хеш. + +~~~go +resource := sha256.Sum256([]byte(username)) +~~~ + +**Проверка:** Разные пользователи не делят ресурс; коллизия не меняет владельца; есть миграция прежних ключей. + +**Вариант A/D:** CRC как граница между ресурсами пользователей. **ENOWARS / replme, автор + патч.** CRC имени выбирал контейнер; +коллизия объединяла чужие ресурсы. + +**Патч:** серверный уникальный ID либо криптографическое отображение, отдельная +проверка владельца и миграция существующих ресурсов. Криптохеш не заменяет auth. +**Тест:** одинаковый checksum двух имён не даёт общий ресурс. +**Поиск:** GO-CRC; PY-CRC покрывает аналогичный риск в Python. + +[исходник/разбор 1](https://github.com/enowars/enowars8-service-replme/blob/3cdec50dd9a57f43f1c57f7b049319774a00e6c2/documentation/documentation/src/main.tex); [исходник/разбор 2](https://github.com/enowars/enowars8-service-replme/blob/3cdec50dd9a57f43f1c57f7b049319774a00e6c2/documentation/documentation/src/path-traversal.patch); [исходник/разбор 3](https://github.com/enowars/enowars8-service-replme/blob/3cdec50dd9a57f43f1c57f7b049319774a00e6c2/documentation/documentation/src/crc.patch); [исходник/разбор 4](https://github.com/enowars/enowars8-service-replme/blob/3cdec50dd9a57f43f1c57f7b049319774a00e6c2/service/backend/util/encoding.go); [исходник/разбор 5](https://github.com/enowars/enowars8-service-replme/blob/3cdec50dd9a57f43f1c57f7b049319774a00e6c2/service/backend/controller/repl.go); [исходник/разбор 6](https://github.com/enowars/enowars8-service-replme/blob/3cdec50dd9a57f43f1c57f7b049319774a00e6c2/service/image/service/user.go). + + + + + +## GO-MATH-RAND. math/rand рядом с возможным секретом + +**Поиск:** скрипт, правило GO-MATH-RAND. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain GO-MATH-RAND. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API. + +**Уязвимый вариант:** + +~~~go +import "math/rand" +rand.Seed(time.Now().UnixMilli()) +~~~ + +**Исправление:** Токены/секреты генерировать crypto/rand с обработкой ошибок. Перестановка алфавита/скрытый seed не заменяет CSPRNG. + +~~~go +import "crypto/rand" +_, err := rand.Read(token) +if err != nil { return err } +~~~ + +**Проверка:** Источник энтропии и длина достаточны; ошибка генератора не создаёт предсказуемый fallback. + +**Вариант A/D:** Go-токен с seed от времени. **RuCTF / werk, автор.** Обычный math/rand и время создания ограничивали +непредсказуемость токена. +**Патч:** crypto/rand, достаточная длина и проверка ошибок; перестановка алфавита +не устраняет слабость генератора. **Тест:** контракт токена и отказ генератора +без предсказуемой замены. **Поиск:** GO-MATH-RAND, включая alias импорта; +кастомный PRNG анализировать отдельно. + +[исходник/разбор 1](https://github.com/HackerDom/ructf-2023/blob/0cc333e44f2ba6908ff6c5d613146e3b00173315/writeups/werk/README.md). + + + + + +## GO-READALL-BODY. ReadAll тела запроса + +**Поиск:** скрипт, правило GO-READALL-BODY. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain GO-READALL-BODY. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API. + +**Уязвимый вариант:** + +~~~go +body, err := io.ReadAll(r.Body) +~~~ + +**Исправление:** Ограничить тело до чтения, корректно обработать превышение лимита. Правило не отслеживает ранее установленный MaxBytesReader. + +~~~go +r.Body = http.MaxBytesReader(w, r.Body, 1<<20) +body, err := io.ReadAll(r.Body) +if err != nil { return } // map to an appropriate client error +~~~ + +**Проверка:** Лимит-1/лимит/лимит+1, stream без Content-Length; штатный максимальный документ работает. + + + + + +## GO-PPROF. pprof регистрируется на HTTP mux + +**Поиск:** скрипт, правило GO-PPROF. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain GO-PPROF. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API. + +**Уязвимый вариант:** + +~~~go +import _ "net/http/pprof" +~~~ + +**Исправление:** Не публиковать DefaultServeMux с debug handlers как бизнес-API. Разделить mux и прикладную авторизацию диагностического endpoint. + +~~~go +// use a separate authenticated diagnostics mux when diagnostics is required +~~~ + +**Проверка:** Обычный API работает; аноним не получает профиль/heap. Импорт сам по себе не доказывает доступность. + +**Основание:** [первичный материал](https://pkg.go.dev/net/http/pprof). + + + + + +## GO-FILESERVER. FileServer публикует дерево файлов + +**Поиск:** скрипт, правило GO-FILESERVER. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain GO-FILESERVER. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API. + +**Уязвимый вариант:** + +~~~go +http.Handle("/", http.FileServer(http.Dir("."))) +~~~ + +**Исправление:** Отдельный public root без секретов/БД, права на приватные файлы вне static handler; проверить symlink и directory listing. + +~~~go +http.Handle("/assets/", http.StripPrefix("/assets/", http.FileServer(http.Dir("./public")))) +~~~ + +**Проверка:** Assets доступны; .env/исходники/чужие файлы и ссылка наружу недоступны. + +**Основание:** [первичный материал](https://pkg.go.dev/net/http#FileServer). + + + + + +## GO-AUTH-RETURN. После http.Error выполнение продолжается + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'http.Error|WriteHeader|StatusForbidden|StatusUnauthorized' . +~~~ + +Пройти код после каждой ветви отказа, deferred effects и goroutines. + +**Уязвимый вариант:** + +http.Error(w, ..., 403) записывает ответ, но не прекращает handler; затем данные читаются/меняются. + +**Исправление:** Явный return до побочного эффекта; auth-result обязателен на всех путях, включая helper. + +**Проверка:** Отказ не меняет БД и не дописывает приватный body; свой запрос работает. + + + + + +## GO-JSON-FIELDS. JSON в entity и неоднозначные ключи + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'json.NewDecoder|json.Unmarshal|Decode\(|DisallowUnknownFields' . +~~~ + +Сверить exported поля entity, теги и повторные/разнорегистровые ключи; DisallowUnknownFields не решает дубли. + +**Уязвимый вариант:** + +Decode в модель принимает Owner/Role либо парсеры по-разному выбирают повторный ключ. + +**Исправление:** Отдельный DTO, разрешённые поля, проверка EOF и типов; при подписи строгая политика дублей/канонизации. + +**Проверка:** Лишнее auth-поле, второй JSON-документ, null и повторные ключи; штатный payload. + + + + + +## GO-RACE. Общие map/slice и check-then-use + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'map\[|sync.Mutex|RWMutex|go func|LoadOrStore|owner' . +~~~ + +Определить владельца shared state; блокировка должна охватывать проверку и изменение, не отдельные обращения. + +**Уязвимый вариант:** + +Две goroutine проходят проверку баланса/прав и затем обе изменяют состояние. + +**Исправление:** Атомарная операция/критическая секция либо транзакция БД; не удерживать глобальный lock на медленном I/O. + +**Проверка:** Barrier-тест инварианта и race detector на подготовленном стенде; отсутствие race-отчёта не доказывает отсутствие логической гонки. + + + + + +## GO-ERROR-DEFAULT. Игнорирование ошибки даёт нулевого субъекта + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'ParseInt|Atoi|Unmarshal|Verify|Find|_, _|err' . +~~~ + +Найти игнорируемые ошибки parse/auth/DB; проверить, не означает ли zero ID глобальный/default объект. + +**Уязвимый вариант:** + +id, _ := strconv.Atoi(input) превращает неправильный ввод в 0, который имеет особые права. + +**Исправление:** Проверять ошибку и допустимый диапазон до операции; различать not found и backend failure. + +**Проверка:** Неправильный ID/таймаут БД не авторизуют и не возвращают чужое; допустимый ноль по контракту обработан явно. + + + + + +## GO-SSRF. Go HTTP client и redirects + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'http.Get|Client.Do|NewRequest|CheckRedirect|DialContext' . +~~~ + +Проследить custom transport, redirect policy, DNS и повторное использование соединения. + +**Уязвимый вариант:** + +URL проверен до Client.Do, но redirect/transport уводит запрос к другому назначению. + +**Исправление:** Фиксированные назначения либо единая policy URL/redirect/соединения, timeouts и лимит body; не блокировать легитимную private сеть без контракта. + +**Проверка:** Mock redirect/DNS/timeout, обычный upstream, oversized response. + +**Основание:** [первичный материал](https://cheatsheetseries.owasp.org/cheatsheets/Server_Side_Request_Forgery_Prevention_Cheat_Sheet.html). + + + + + +## GO-ZIP-PATH. filepath.Join не обеспечивает containment + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'archive/zip|archive/tar|filepath.Join|EvalSymlinks|MkdirAll' . +~~~ + +Найти имена entries и ссылок; сравнить очищенный путь с root и фактическую операцию открытия. + +**Уязвимый вариант:** + +Join(root, entry) используется для записи без проверки выхода/ссылок. + +**Исправление:** Проверить relative path и тип entry, безопасное открытие внутри каталога с политикой symlink, лимиты и уборка. + +**Проверка:** Вложенный допустимый путь, выход наружу, link entry и изменение родителя между проверкой и записью. + +**Основание:** [первичный материал](https://cheatsheetseries.owasp.org/cheatsheets/File_Upload_Cheat_Sheet.html). + + + + + +## GO-TLS-MIN. Явно разрешён устаревший TLS + +**Поиск:** скрипт, правило GO-TLS-MIN. Запуск: python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain GO-TLS-MIN. Regex: MinVersion:tls.VersionSSL30/TLS10/TLS11 и присваивание .MinVersion = этим константам, включая переносы строк; ==/!=, TLS12/TLS13 и 0 не сигналят. VersionSSL30 — устаревшая настройка, современный Go не поддерживает SSLv3. Тип объекта, итоговую конфигурацию и версию Go проверять вручную; числовые версии, import aliases, переменные и настройки listener вне Go не вычисляются. + +**Уязвимый вариант:** Настройка понижает минимум для используемого TLS-клиента +или сервера, если версия и режим runtime допускают эти старые протоколы. + +~~~go +cfg := &tls.Config{} +cfg.MinVersion = tls.VersionTLS10 +~~~ + +**Исправление:** Выбрать минимум TLS 1.2/1.3 по совместимости checker и peer; +сохранить проверку сертификата. Настроить Config до передачи TLS-функции: +после начала использования его менять нельзя. + +~~~go +cfg := &tls.Config{} +cfg.MinVersion = tls.VersionTLS12 +~~~ + +**Проверка:** Штатные peers соединяются; TLS ниже выбранного минимума отвергнут. +Проверить итоговый Config, обработку ошибки соединения и старых клиентов до +выкладки: поднятие минимума может нарушить совместимость. + +Поле литерала `MinVersion: tls.VersionTLS10` и отдельное присваивание +`cfg.MinVersion = tls.VersionTLS10` требуют одинакового просмотра. +Сравнения `==`/`!=` не меняют настройку и не получают этот сигнал. +`TLS12`/`TLS13` и `0` также не сигналят; `0` означает default конкретного runtime, +а не подтверждённую политику безопасности. + +`VersionSSL30` остаётся сигналом устаревшей настройки: наличие константы +не означает, что современный Go поддерживает SSLv3. +Версия, режим runtime и последующие переопределения влияют на реальное поведение. +[Go: tls.Config](https://pkg.go.dev/crypto/tls#Config), +[контракт MinVersion в Go 1.24](https://github.com/golang/go/blob/go1.24.0/src/crypto/tls/common.go#L756). + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'MinVersion|MaxVersion|TLSClientConfig|GetConfigForClient|crypto/tls|GODEBUG|GOFIPS140' . +~~~ + +Связать объект с реальным TLS-клиентом/listener и проверить все изменения, +возвращаемые callbacks конфигурации, aliases импорта, числовые константы и +значения из окружения. Regex не устанавливает тип объекта или достижимость +настройки и может совпасть с комментарием. Семантика сверена по первичным +исходникам; Go runtime и TLS-соединения в этой проверке не запускались. + + + + + +## GO-JWT-UNVERIFIED. JWT без подписи или проверки claims + +**Поиск:** скрипт, правило GO-JWT-UNVERIFIED. Запуск: python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain GO-JWT-UNVERIFIED. Regex: ParseUnverified и WithoutClaimsValidation; не доказывает использование результата для auth. Пример относится к golang-jwt/jwt/v5. + +**Уязвимый вариант:** Разобранный токен не равен проверенному; ошибка или отключённая валидация не должны вести к авторизации. + +~~~go +token, _, err := parser.ParseUnverified(raw, &claims) +~~~ + +**Исправление:** Использовать валидирующий API с доверенным keyfunc, алгоритмами и claims; проверять err до использования token/claims. + +~~~go +token, err := jwt.ParseWithClaims(raw, &claims, trustedKeyFunc, jwt.WithValidMethods([]string{"RS256"}), jwt.WithIssuer("auth"), jwt.WithAudience("notes"), jwt.WithExpirationRequired()) +if err != nil || !token.Valid { return ErrUnauthorized } +~~~ + +**Проверка:** Подпись/срок/адресат проверяются; nil token при ошибке не вызывает panic; штатный токен принимается. + +Первичная документация: [документация 1](https://pkg.go.dev/github.com/golang-jwt/jwt/v5). + + + + + +## GO-UPLOAD-PATH. Имя multipart-файла напрямую включается в путь + +**Поиск:** правило сканера GO-UPLOAD-PATH. Точный контракт детектора: `--explain GO-UPLOAD-PATH`. Regex с лексическими исключениями: filepath.Join с простым первым аргументом и прямым header/fileHeader/file.Filename во втором. MIME-парсер может нормализовать имя файла; правило не доказывает traversal, тип импортированного объекта или отсутствие предшествующей валидации. + +**Уязвимый вариант:** + +~~~go +path := filepath.Join(root, header.Filename) +~~~ + +**Исправление:** Выбирайте серверное имя хранения без перезаписи существующих файлов, вне исполняемых и публичных корней; проверяйте права на скачивание, размер и тип загрузки. + +~~~go +path := filepath.Join(root, serverGeneratedID) +~~~ + +**Проверка:** Другие разделители, traversal, коллизии и запросы от другого владельца не меняют выбранный путь хранения; обычные загрузки работают. + +[Первичный источник 1](https://pkg.go.dev/mime/multipart#FileHeader) diff --git a/docs/vulnerabilities/go.md b/docs/vulnerabilities/go.md new file mode 100644 index 0000000..8bdf463 --- /dev/null +++ b/docs/vulnerabilities/go.md @@ -0,0 +1,577 @@ +# Go: find, fix and verify + +English | [Русский](go-RU.md) + +[Catalog](README.md) · [Scanner](../offline-scanner.md) · [Patch verification](../patch-validation.md) + +19 sections. Each follows **Search → Vulnerable example → Fix → Verification**. +Run `rg` from a local service checkout; searches only read files. Derive the actor/owner from a verified session, not request data. Adapt examples to the actual API and contract. + +## Contents + +- [GO-SQL — Dynamic Go SQL](#go-sql) +- [GO-HASH-SUM — Non-empty argument to hash.Sum](#go-hash-sum) +- [GO-HTML — Go autoescape bypass](#go-html) +- [GO-TLS — InsecureSkipVerify](#go-tls) +- [GO-SHELL — Go exec.Command launches a shell](#go-shell) +- [GO-CRC — CRC near an identifier or trust boundary](#go-crc) +- [GO-MATH-RAND — math/rand near a possible secret](#go-math-rand) +- [GO-READALL-BODY — ReadAll on a request body](#go-readall-body) +- [GO-PPROF — pprof registered on an HTTP mux](#go-pprof) +- [GO-FILESERVER — FileServer publishes a file tree](#go-fileserver) +- [GO-AUTH-RETURN — Execution continues after http.Error](#go-auth-return) +- [GO-JSON-FIELDS — JSON entities and ambiguous keys](#go-json-fields) +- [GO-RACE — Shared map/slice state and check-then-use](#go-race) +- [GO-ERROR-DEFAULT — Ignored errors produce a zero principal](#go-error-default) +- [GO-SSRF — HTTP clients and redirects](#go-ssrf) +- [GO-ZIP-PATH — filepath.Join does not enforce containment](#go-zip-path) +- [GO-TLS-MIN — Obsolete minimum TLS version](#go-tls-min) +- [GO-JWT-UNVERIFIED — JWT without signature or claims verification](#go-jwt-unverified) +- [GO-UPLOAD-PATH — Multipart filename used directly in a joined path](#go-upload-path) + + + +## GO-SQL. Dynamic Go SQL + +**Search:** scanner rule GO-SQL. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain GO-SQL` for details. Regex: Query/QueryRow/Exec/Prepare and Context forms with concatenation or fmt.Sprintf. Simple context expressions are supported; review complex syntax, fmt aliases and preassembled SQL. + +**Vulnerable example:** + +~~~go +db.Query("SELECT id FROM notes WHERE name=" + name) +~~~ + +**Fix:** Bind values using actual driver placeholders; allowlist identifiers. + +~~~go +db.Query("SELECT id FROM notes WHERE name=$1", name) +~~~ + +**Verification:** Quotes remain values; legitimate queries and ownership checks work. + +
+Expanded example and limitations + +```go +// Vulnerable: client input becomes SQL syntax. +q := fmt.Sprintf("SELECT body FROM notes WHERE id = '%s'", inputID) +err := db.QueryRowContext(ctx, q).Scan(&body) +``` + +**Patch for a private note:** + +```go +import ( + "context" + "database/sql" +) + +func ReadPrivateNote(ctx context.Context, db *sql.DB, userID, noteID int64) (string, error) { + var body string + err := db.QueryRowContext(ctx, + "SELECT body FROM notes WHERE id = $1 AND owner_id = $2", + noteID, userID, + ).Scan(&body) + return body, err +} +``` + +Parse the ID with a checked conversion before this call. Map sql.ErrNoRows to the normal unavailable-object response; never return body as success for other errors. Verify placeholder syntax for MySQL or another driver. + +**Check:** Owner, other user, missing object, invalid ID, context cancellation/timeout and old records. After list iteration check rows.Err(). + +
+ + + +## GO-HASH-SUM. Non-empty argument to hash.Sum + +**Search:** scanner rule GO-HASH-SUM. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain GO-HASH-SUM` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries. + +**Vulnerable example:** + +~~~go +digest := h.Sum(record.Hash[:]) +~~~ + +**Fix:** Use Write to hash bytes and Sum(nil) for the digest; Sum appends a digest instead of hashing its argument. + +~~~go +h.Write(record.Hash[:]) +digest := h.Sum(nil) +~~~ + +**Verification:** Known vectors match; legacy digest formats are migrated deliberately. + +**A/D variant:** Sum does not hash its argument. **Reference:** certified-transparency, analysis of three saarCTF source files. Checksum passed Hash to Sum; ToHash copied the first 32 output bytes. Go semantics mean those bytes could be the original Hash rather than the digest of previously written Size/Timestamp. The full service was not reproduced. Scanner: GO-HASH-SUM. + +~~~go +// Before: return ToHash(h.Sum(record.Hash[:])) +// After: include data in hash state, then extract only the digest. +h.Write(record.Hash[:]) +return ToHash(h.Sum(nil)) +~~~ + +**Test:** Change Size, Timestamp and Hash individually; each old signature must fail. Plan signature-format migration and legacy-data compatibility. A nonempty Sum argument is not always wrong: buf[:0] can reuse preallocated storage. Inspect the consumer of the result. + +[source/write-up 1](https://github.com/saarsec/saarctf-2024/blob/3a06d18974ca177c6dd251a11bdf9b4b334f382a/certified-transparency/service/pkg/models/serialization.go); [source/write-up 2](https://github.com/saarsec/saarctf-2024/blob/3a06d18974ca177c6dd251a11bdf9b4b334f382a/certified-transparency/service/pkg/models/models.go); [source/write-up 3](https://github.com/saarsec/saarctf-2024/blob/3a06d18974ca177c6dd251a11bdf9b4b334f382a/certified-transparency/service/pkg/signatures.go). + + + +## GO-HTML. Go autoescape bypass + +**Search:** scanner rule GO-HTML. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain GO-HTML` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries. + +**Vulnerable example:** + +~~~go +value := template.HTML(input) +~~~ + +**Fix:** Pass strings to html/template; use trusted HTML only after a reviewed sanitizer if needed. + +~~~go +value := input // string passed to html/template +~~~ + +**Verification:** User tags/quotes render as text; intended formatting works. + +
+Expanded example and limitations + +```go +// Vulnerable when message is client-controlled. +err := page.Execute(w, template.HTML(message)) +``` + +**Patch for rendering ordinary text:** + +```go +import ( + "html/template" + "io" +) + +func RenderMessage(w io.Writer, message string) error { + page, err := template.New("message").Parse("

{{.}}

") + if err != nil { + return err + } + return page.Execute(w, message) +} +``` + +The template is fixed and the data is an ordinary string. Use html/template, not text/template, for HTML. Do not replace the problem with template.JS/template.URL, which also assert trust. A fixed template may be parsed once at startup. Account for partial HTTP responses on render failure; buffer first where necessary. + +**Check:** Markup/quotes display as text, Unicode survives, message itself is never compiled, and contractual formatting remains available. + +
+ + + +## GO-TLS. InsecureSkipVerify + +**Search:** scanner rule GO-TLS. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain GO-TLS` for details. Regex: InsecureSkipVerify:true and .InsecureSkipVerify=true assignments including newlines; ==, != and false do not match. VerifyConnection does not suppress review: inspect object type, reachability, callback and effective config. Comments/strings may match. + +**Vulnerable example:** + +~~~go +cfg := tls.Config{InsecureSkipVerify: true} +~~~ + +**Fix:** Use normal certificate/hostname verification and the required CA; review custom verification callbacks. + +~~~go +cfg := tls.Config{InsecureSkipVerify: false} +~~~ + +**Verification:** Correct peers work and invalid certificates fail. + +Dangerous configuration can be assigned after construction: + +~~~go +cfg := &tls.Config{} +cfg.InsecureSkipVerify = true +~~~ + +For an ordinary TLS client restore false and configure RootCAs/ServerName for the intended server. Test trusted certificates, unknown CAs, wrong names and expiry, preserving the legitimate internal CA. + +With InsecureSkipVerify: true, an application may implement its own VerifyConnection validation. The flag can be justified only if that callback fully checks the required chain and name; a callback's mere presence proves nothing. The scanner does not analyze its body and retains the signal. Comparing cfg.InsecureSkipVerify == true does not change configuration and does not independently trigger GO-TLS. [Go: tls.Config](https://pkg.go.dev/crypto/tls#Config). + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'InsecureSkipVerify|VerifyConnection|VerifyPeerCertificate|RootCAs|ServerName|TLSClientConfig' . +~~~ + +Connect the configuration to the transport actually used; trace every assignment and callback error return, including resumed TLS sessions. Variable values and effective configuration need manual review. Regex can match comments/examples; a match does not establish execution. + + + +## GO-SHELL. Go exec.Command launches a shell + +**Search:** scanner rule GO-SHELL. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain GO-SHELL` for details. Regex: any receiver.Command/CommandContext with literal shell and -c/-lc/-ec. Simple context expressions including r.Context() work; nested commas may hide a call. Inspect receiver type and command trust. + +**Vulnerable example:** + +~~~go +cmd := exec.Command("sh", "-c", command) +~~~ + +**Fix:** Use fixed executable plus argv. Pass stdin records without a shell and validate their separators. + +~~~go +cmd := exec.Command("/usr/bin/file", "--", filename) +~~~ + +**Verification:** Metacharacters stay data; dangerous options/separators fail; supported arguments work. + +
+Expanded example and limitations + +```go +// Vulnerable: exec.Command starts a shell that parses input text. +out, err := exec.Command("sh", "-c", "printf '%s' '"+message+"' | sha256sum").Output() +``` + +**Patch for a content SHA-256 digest:** + +```go +import ( + "crypto/sha256" + "encoding/hex" +) + +func DigestText(message string) string { + sum := sha256.Sum256([]byte(message)) + return hex.EncodeToString(sum[:]) +} +``` + +Go strings contain bytes; this example preserves them unchanged. Validate UTF-8 separately if the protocol requires it. Preserve the external response format, which may differ from raw sha256sum output. This is not password hashing. + +**Check:** Known digest, empty string, Unicode, quotes/newlines and no subprocess. If an external command is genuinely required, separate executable/arguments and bound runtime with context; the program may still interpret arguments as options. + +
+ +**A/D variant:** Shell hidden in an internal backend. **ENOWARS / replme, author write-up.** An internal handler interpolated a password into a shell command. **Patch:** Call a fixed utility without shell; pass data over stdin while validating its format delimiters. Do not arbitrarily restrict passwords to letters without checking the contract. **Test:** Spaces/permitted characters work; record delimiters fail. **Search:** GO-SHELL and the complete call chain. + +[source/write-up 1](https://github.com/enowars/enowars8-service-replme/blob/3cdec50dd9a57f43f1c57f7b049319774a00e6c2/documentation/documentation/src/main.tex); [source/write-up 2](https://github.com/enowars/enowars8-service-replme/blob/3cdec50dd9a57f43f1c57f7b049319774a00e6c2/documentation/documentation/src/path-traversal.patch); [source/write-up 3](https://github.com/enowars/enowars8-service-replme/blob/3cdec50dd9a57f43f1c57f7b049319774a00e6c2/documentation/documentation/src/crc.patch); [source/write-up 4](https://github.com/enowars/enowars8-service-replme/blob/3cdec50dd9a57f43f1c57f7b049319774a00e6c2/service/backend/util/encoding.go); [source/write-up 5](https://github.com/enowars/enowars8-service-replme/blob/3cdec50dd9a57f43f1c57f7b049319774a00e6c2/service/backend/controller/repl.go); [source/write-up 6](https://github.com/enowars/enowars8-service-replme/blob/3cdec50dd9a57f43f1c57f7b049319774a00e6c2/service/image/service/user.go). + + + +## GO-CRC. CRC near an identifier or trust boundary + +**Search:** scanner rule GO-CRC. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain GO-CRC` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries. + +**Vulnerable example:** + +~~~go +resource := service.CRC.Calculate(username) +~~~ + +**Fix:** CRC is not an ownership boundary. Use unique server-owned IDs plus authorization or HMAC for authenticity. + +~~~go +resource := sha256.Sum256([]byte(username)) +~~~ + +**Verification:** Collisions cannot change ownership; old IDs have a migration path. + +**A/D variant:** CRC as the boundary between users' resources. **ENOWARS / replme, author and patch.** A name's CRC selected a container; collisions merged unrelated resources. + +**Patch:** Server-generated unique IDs or a cryptographic mapping, separate ownership checks and migration of existing resources. A cryptographic hash is not authorization. **Test:** Equal checksums for different names must not share a resource. **Search:** GO-CRC; PY-CRC covers the analogous Python risk. + +[source/write-up 1](https://github.com/enowars/enowars8-service-replme/blob/3cdec50dd9a57f43f1c57f7b049319774a00e6c2/documentation/documentation/src/main.tex); [source/write-up 2](https://github.com/enowars/enowars8-service-replme/blob/3cdec50dd9a57f43f1c57f7b049319774a00e6c2/documentation/documentation/src/path-traversal.patch); [source/write-up 3](https://github.com/enowars/enowars8-service-replme/blob/3cdec50dd9a57f43f1c57f7b049319774a00e6c2/documentation/documentation/src/crc.patch); [source/write-up 4](https://github.com/enowars/enowars8-service-replme/blob/3cdec50dd9a57f43f1c57f7b049319774a00e6c2/service/backend/util/encoding.go); [source/write-up 5](https://github.com/enowars/enowars8-service-replme/blob/3cdec50dd9a57f43f1c57f7b049319774a00e6c2/service/backend/controller/repl.go); [source/write-up 6](https://github.com/enowars/enowars8-service-replme/blob/3cdec50dd9a57f43f1c57f7b049319774a00e6c2/service/image/service/user.go). + + + +## GO-MATH-RAND. math/rand near a possible secret + +**Search:** scanner rule GO-MATH-RAND. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain GO-MATH-RAND` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries. + +**Vulnerable example:** + +~~~go +import "math/rand" +rand.Seed(time.Now().UnixMilli()) +~~~ + +**Fix:** Use crypto/rand and handle errors; alphabet shuffling/hidden seeds do not create a CSPRNG. + +~~~go +import "crypto/rand" +_, err := rand.Read(token) +if err != nil { return err } +~~~ + +**Verification:** Entropy/length suffice and failure never creates a predictable fallback. + +**A/D variant:** Go tokens seeded from time. **RuCTF / werk, author write-up.** math/rand and creation time constrained token unpredictability. **Patch:** crypto/rand, adequate length and error handling; permuting an alphabet does not fix a weak generator. **Test:** Token contract and generator failure without predictable fallback. **Search:** GO-MATH-RAND including import aliases; review custom PRNGs separately. + +[source/write-up 1](https://github.com/HackerDom/ructf-2023/blob/0cc333e44f2ba6908ff6c5d613146e3b00173315/writeups/werk/README.md). + + + +## GO-READALL-BODY. ReadAll on a request body + +**Search:** scanner rule GO-READALL-BODY. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain GO-READALL-BODY` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries. + +**Vulnerable example:** + +~~~go +body, err := io.ReadAll(r.Body) +~~~ + +**Fix:** Limit the body before reading and handle excess size; the rule does not track earlier MaxBytesReader calls. + +~~~go +r.Body = http.MaxBytesReader(w, r.Body, 1<<20) +body, err := io.ReadAll(r.Body) +if err != nil { return } // map to an appropriate client error +~~~ + +**Verification:** Test limit-1/limit/limit+1 and streams without Content-Length. + + + +## GO-PPROF. pprof registered on an HTTP mux + +**Search:** scanner rule GO-PPROF. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain GO-PPROF` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries. + +**Vulnerable example:** + +~~~go +import _ "net/http/pprof" +~~~ + +**Fix:** Do not expose DefaultServeMux debug handlers as the business API; separate muxes and authorize diagnostic endpoints. + +~~~go +// use a separate authenticated diagnostics mux when diagnostics is required +~~~ + +**Verification:** Normal API works; anonymous clients cannot obtain profiles/heap. Import alone does not prove exposure. + +**Reference:** [primary source](https://pkg.go.dev/net/http/pprof). + + + +## GO-FILESERVER. FileServer publishes a file tree + +**Search:** scanner rule GO-FILESERVER. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain GO-FILESERVER` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries. + +**Vulnerable example:** + +~~~go +http.Handle("/", http.FileServer(http.Dir("."))) +~~~ + +**Fix:** Use a dedicated public root without secrets/databases; authorize private files separately and review symlinks/listing. + +~~~go +http.Handle("/assets/", http.StripPrefix("/assets/", http.FileServer(http.Dir("./public")))) +~~~ + +**Verification:** Assets work; .env, source, foreign files and outward symlinks are unavailable. + +**Reference:** [primary source](https://pkg.go.dev/net/http#FileServer). + + + +## GO-AUTH-RETURN. Execution continues after http.Error + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'http.Error|WriteHeader|StatusForbidden|StatusUnauthorized' . +~~~ + +Trace execution after each denial, including deferred effects and goroutines. + +**Vulnerable example:** + +`http.Error(w, ..., 403)` writes a response but does not stop the handler; subsequent code reads or mutates data. + +**Fix:** Explicit return before side effects; require a checked authorization result on every path, including helpers. + +**Verification:** Denial does not mutate the database or append private response data; authorized requests work. + + + +## GO-JSON-FIELDS. JSON entities and ambiguous keys + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'json.NewDecoder|json.Unmarshal|Decode\(|DisallowUnknownFields' . +~~~ + +Review exported entity fields, tags, duplicate keys and case variants; DisallowUnknownFields does not solve duplicates. + +**Vulnerable example:** + +Decoding into the model accepts Owner/Role, or parsers choose different duplicate keys. + +**Fix:** Dedicated DTO, allowlisted fields, EOF/type validation; signed input requires an explicit duplicate-key/canonicalization policy. + +**Verification:** Extra authorization fields, second JSON documents, nulls, duplicate keys and ordinary payloads. + + + +## GO-RACE. Shared map/slice state and check-then-use + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'map\[|sync.Mutex|RWMutex|go func|LoadOrStore|owner' . +~~~ + +Identify the shared-state owner; a lock must cover the check and mutation, not only individual accesses. + +**Vulnerable example:** + +Two goroutines both pass balance/authorization checks and mutate state. + +**Fix:** An atomic operation/critical section or database transaction; avoid global locks across slow I/O. + +**Verification:** Barrier-based invariant tests and race detector in an isolated environment. No race report does not prove the absence of logical races. + + + +## GO-ERROR-DEFAULT. Ignored errors produce a zero principal + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'ParseInt|Atoi|Unmarshal|Verify|Find|_, _|err' . +~~~ + +Find ignored parse/auth/database errors; determine whether zero identifies a global/default object. + +**Vulnerable example:** + +`id, _ := strconv.Atoi(input)` turns invalid input into zero with special privileges. + +**Fix:** Check errors and range before use; distinguish not-found from backend failure. + +**Verification:** Invalid IDs/database timeouts never authorize or expose another user's data; explicitly handle zero if it is valid by contract. + + + +## GO-SSRF. HTTP clients and redirects + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'http.Get|Client.Do|NewRequest|CheckRedirect|DialContext' . +~~~ + +Trace custom transports, redirect policies, DNS and connection reuse. + +**Vulnerable example:** + +The URL is checked before Client.Do, but redirect/transport behavior reaches another destination. + +**Fix:** Fixed destinations or a unified URL/redirect/connection policy, timeouts and body limits. Do not prohibit legitimate private-network destinations without checking the contract. + +**Verification:** Mock redirects/DNS/timeouts, normal upstream and oversized responses. + +**Reference:** [primary source](https://cheatsheetseries.owasp.org/cheatsheets/Server_Side_Request_Forgery_Prevention_Cheat_Sheet.html). + + + +## GO-ZIP-PATH. filepath.Join does not enforce containment + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'archive/zip|archive/tar|filepath.Join|EvalSymlinks|MkdirAll' . +~~~ + +Inspect entry/link names; compare the cleaned path with the root and the actual open operation. + +**Vulnerable example:** + +`Join(root, entry)` writes without checking escapes or symlinks. + +**Fix:** Validate relative paths and entry types, use safe directory-relative opening with a symlink policy, limits and cleanup. + +**Verification:** Valid nested paths, escapes, link entries and parent replacement between check and write. + +**Reference:** [primary source](https://cheatsheetseries.owasp.org/cheatsheets/File_Upload_Cheat_Sheet.html). + + + +## GO-TLS-MIN. Obsolete minimum TLS version + +**Search:** scanner rule GO-TLS-MIN. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain GO-TLS-MIN` for details. Regex: MinVersion:tls.VersionSSL30/TLS10/TLS11 and assignments, including newlines; ==, !=, TLS12/TLS13 and 0 do not signal. SSL30 is obsolete and unsupported by modern Go. Review object/effective config/version; numbers, aliases, variables and external listener settings are not evaluated. + +**Vulnerable example:** The setting lowers the minimum of the TLS client/server actually using it, if that runtime version/mode supports the old protocols. + +~~~go +cfg := &tls.Config{} +cfg.MinVersion = tls.VersionTLS10 +~~~ + +**Fix:** Choose TLS 1.2/1.3 minimum compatible with checker/peers while retaining certificate checks. + +~~~go +cfg := &tls.Config{} +cfg.MinVersion = tls.VersionTLS12 +~~~ + +**Verification:** Normal peers connect; versions below the chosen minimum fail. + +Both MinVersion: tls.VersionTLS10 and cfg.MinVersion = tls.VersionTLS10 need review. Comparisons ==/!= do not change settings and do not trigger this signal. TLS12/TLS13 and 0 do not trigger it either; 0 selects the runtime default, not a verified security policy. + +VersionSSL30 remains a legacy-configuration signal: the constant's existence does not mean modern Go supports SSLv3. Runtime version/mode and later overrides affect actual behavior. [Go: tls.Config](https://pkg.go.dev/crypto/tls#Config), [Go 1.24 MinVersion contract](https://github.com/golang/go/blob/go1.24.0/src/crypto/tls/common.go#L756). + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'MinVersion|MaxVersion|TLSClientConfig|GetConfigForClient|crypto/tls|GODEBUG|GOFIPS140' . +~~~ + +Connect the object to the real TLS client/listener; review mutations, configuration callbacks, import aliases, numeric constants and environment-derived values. Regex establishes neither type nor reachability and may match comments. Semantics were reviewed against primary sources; this catalog review did not execute Go or TLS connections. + + + +## GO-JWT-UNVERIFIED. JWT without signature or claims verification + +**Search:** scanner rule GO-JWT-UNVERIFIED. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain GO-JWT-UNVERIFIED` for details. Regex: ParseUnverified and WithoutClaimsValidation; does not prove authentication uses the result. The example targets golang-jwt/jwt/v5. + +**Vulnerable example:** Parsed does not mean verified; errors or disabled validation must never authorize a JWT. + +~~~go +token, _, err := parser.ParseUnverified(raw, &claims) +~~~ + +**Fix:** Use a validating API with trusted keyfunc, algorithms and claims; check err before using token/claims. + +~~~go +token, err := jwt.ParseWithClaims(raw, &claims, trustedKeyFunc, jwt.WithValidMethods([]string{"RS256"}), jwt.WithIssuer("auth"), jwt.WithAudience("notes"), jwt.WithExpirationRequired()) +if err != nil || !token.Valid { return ErrUnauthorized } +~~~ + +**Verification:** Signature/expiry/audience checks work, error nil tokens do not panic and valid tokens pass. + +Primary documentation: [reference 1](https://pkg.go.dev/github.com/golang-jwt/jwt/v5). + + + +## GO-UPLOAD-PATH. Multipart filename used directly in a joined path + +**Search:** scanner rule GO-UPLOAD-PATH. Use `--explain GO-UPLOAD-PATH` for the exact detector contract. Regex with lexical exclusions: filepath.Join with a simple first argument and a direct header/fileHeader/file.Filename second argument. The MIME parser may normalize filenames; the rule does not prove traversal, imported types or missing earlier validation. + +**Vulnerable example:** + +~~~go +path := filepath.Join(root, header.Filename) +~~~ + +**Fix:** Choose a non-overwriting server-side storage name outside executable/public roots; authorize downloads and enforce upload size/type. + +~~~go +path := filepath.Join(root, serverGeneratedID) +~~~ + +**Verification:** Alternate separators, traversal, collisions and other-owner requests cannot change the chosen storage path; ordinary uploads work. + +[Primary reference 1](https://pkg.go.dev/mime/multipart#FileHeader) diff --git a/docs/vulnerabilities/java-RU.md b/docs/vulnerabilities/java-RU.md new file mode 100644 index 0000000..052b3d5 --- /dev/null +++ b/docs/vulnerabilities/java-RU.md @@ -0,0 +1,596 @@ + + +# Java: поиск и исправление + +[English](java.md) | Русский + +[Вся база](README-RU.md) · [Сканер](../offline-scanner-RU.md) · [Проверка патча](../patch-validation-RU.md) + +18 разделов. Формат: **Поиск → Уязвимый вариант → Исправление → Проверка**. +Команды `rg` выполняются в корне локальной копии сервиса и только читают файлы. Субъект/владелец определяется по проверенной сессии, а не данным запроса. Примеры нужно адаптировать к реальным API и контракту. + +Автоматические находки — ограниченные синтаксические сигналы для проверки. AST-анализ не разрешает типы и не отслеживает данные между функциями; regex не заменяет парсер языка. Комментарии, строки и одноимённые пользовательские API могут давать совпадения. Проверьте фактическое исполнение, входные данные, авторизацию и границы доверия. + + + +## Содержание + +- [JAVA-OBJECT — Java ObjectInputStream](#java-object) +- [JAVA-RNG — java.util.Random в возможном секрете](#java-rng) +- [JAVA-SQL — Динамический JDBC SQL](#java-sql) +- [JAVA-PROCESS — Запуск процесса Java](#java-process) +- [JAVA-JACKSON-TYPES — Jackson default typing](#java-jackson-types) +- [JAVA-XML — XML parser требует явной политики внешних ресурсов](#java-xml) +- [JAVA-EXPRESSION — Клиентский текст парсится как SpEL](#java-expression) +- [JAVA-PATH — Path resolve без ограничения корня](#java-path) +- [JAVA-ZIP-SLIP — ZipEntry становится выходным путём](#java-zip-slip) +- [JAVA-SPRING-BIND — Spring binding в domain entity](#java-spring-bind) +- [JAVA-SECURITY-MATCHER — Порядок matchers и method security](#java-security-matcher) +- [JAVA-THREADLOCAL — ThreadLocal переносит пользователя следующему запросу](#java-threadlocal) +- [JAVA-REGEX-DOS — Регулярное выражение блокирует поток](#java-regex-dos) +- [JAVA-JNDI — Недоверенное имя JNDI lookup](#java-jndi) +- [JAVA-ERROR-LEAK — Stack trace и SQL в API-ошибке](#java-error-leak) +- [JAVA-HOSTNAME-VERIFY — Hostname verifier принимает любой сервер](#java-hostname-verify) +- [JAVA-SPRING-CSRF — CSRF отключён в Spring Security](#java-spring-csrf) +- [JAVA-LDAP-FILTER — Фильтр поиска JNDI собирается конкатенацией](#java-ldap-filter) + + + + + +## JAVA-OBJECT. Java ObjectInputStream + +**Поиск:** скрипт, правило JAVA-OBJECT. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain JAVA-OBJECT. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API. + +**Уязвимый вариант:** + +~~~java +ObjectInputStream in = new ObjectInputStream(stream); +~~~ + +**Исправление:** Внешний вход — типизированный формат со схемой; legacy — план миграции и фильтрации типов. + +~~~java +Message value = parseValidatedMessage(stream); +~~~ + +**Проверка:** Произвольный граф классов не загружается. + + + + + +## JAVA-RNG. java.util.Random в возможном секрете + +**Поиск:** скрипт, правило JAVA-RNG. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain JAVA-RNG. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API. + +**Уязвимый вариант:** + +~~~java +Random rng = new Random(); +~~~ + +**Исправление:** Для секретов SecureRandom.nextBytes без предсказуемого seed; хеширование малого пространства не добавляет энтропию. + +~~~java +SecureRandom rng = new SecureRandom(); +~~~ + +**Проверка:** Нет предсказуемого seed или резервного генератора; challenge/token имеет достаточную энтропию и совместимый формат, штатные токены работают. + +**Вариант A/D:** Публичный PRNG и секретный challenge. **Основание:** 8-bit-oracle, разбор автора и Java-код saarCTF. +Один java.util.Random использовался в публичных значениях и challenge. +Хеш 32-битного значения не создаёт большего пространства секретов. +Сканер: JAVA-RNG; наличие Random вне security-контекста допустимо. + +**Патч:** SecureRandom.nextBytes достаточной длины без предсказуемого seed; +публичная статистика не использует состояние генератора секретов. +**Тест:** формат и одноразовость challenge, длина/источник случайности, +сохранение обычного потока проверки. Не считать статистический тест доказательством +криптографической стойкости. + +[исходник/разбор 1](https://github.com/saarsec/saarctf-2024/blob/3a06d18974ca177c6dd251a11bdf9b4b334f382a/8-bit-oracle/README.md); [исходник/разбор 2](https://github.com/saarsec/saarctf-2024/blob/3a06d18974ca177c6dd251a11bdf9b4b334f382a/8-bit-oracle/service/_8BitOracle/src/Util.java). + + + + + +## JAVA-SQL. Динамический JDBC SQL + +**Поиск:** скрипт, правило JAVA-SQL. Запуск: python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain JAVA-SQL. Regex: executeQuery/executeUpdate/execute/prepareStatement/prepareCall с конкатенацией или String.format. PreparedStatement не защищает уже собранный SQL; переменные SQL и formatter wrappers вручную. + +**Уязвимый вариант:** + +~~~java +statement.executeQuery("SELECT id FROM notes WHERE name=" + name); +~~~ + +**Исправление:** PreparedStatement + setString/setLong; identifiers фиксировать. + +~~~java +PreparedStatement q = connection.prepareStatement("SELECT id FROM notes WHERE name=?"); +q.setString(1, name); +q.executeQuery(); +~~~ + +**Проверка:** Кавычки остаются данными; проверка владельца сохраняется. + +
+Развёрнутый пример и ограничения + +```java +// Vulnerable: inputId is interpolated into SQL without an owner constraint. +ResultSet rs = statement.executeQuery("SELECT body FROM notes WHERE id = '" + inputId + "'"); +``` + +**Патч JDBC для приватной заметки:** + +```java +import java.sql.*; +import java.util.Optional; + +final class NoteReader { + static Optional read(Connection db, Long userId, long noteId) throws SQLException { + if (userId == null) throw new SecurityException("authentication required"); + try (PreparedStatement st = db.prepareStatement( + "SELECT body FROM notes WHERE id = ? AND owner_id = ?")) { + st.setLong(1, noteId); + st.setLong(2, userId); + try (ResultSet rows = st.executeQuery()) { + return rows.next() ? Optional.of(rows.getString("body")) : Optional.empty(); + } + } + } +} +``` + +Пример предполагает `body NOT NULL`. Если схема разрешает NULL, сохранить +его семантику отдельно от отсутствующей строки. Закрываются statement/result set, +но не переданное соединение: его жизненным циклом управляет вызывающий код. +Входной ID парсится с обработкой ошибок. `PreparedStatement` с уже склеенной +SQL-строкой не исправляет проблему. + +**Проверить:** своё/чужое/аноним; неверный и отсутствующий ID; прежние данные; +ошибка БД не выдаёт успешный пустой ответ. + +
+ + + + + +## JAVA-PROCESS. Запуск процесса Java + +**Поиск:** скрипт, правило JAVA-PROCESS. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain JAVA-PROCESS. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API. + +**Уязвимый вариант:** + +~~~java +Runtime.getRuntime().exec(command); +~~~ + +**Исправление:** Предпочитать библиотечную операцию либо фиксированную программу с проверенными argv и ограничениями времени и вывода. ProcessBuilder не всегда shell, но shell -c и выбор executable клиентом опасны. + +~~~java +runValidatedConversion(inputPath); // fixed executable and validated argv inside +~~~ + +**Проверка:** Клиент не меняет программу/опасные опции; конвертация работает. + +
+Развёрнутый пример и ограничения + +```java +// Vulnerable: ProcessBuilder does not protect an explicit shell command. +Process p = new ProcessBuilder("sh", "-c", "printf '%s' '" + text + "' | sha256sum").start(); +``` + +**Патч для SHA-256 строки:** + +```java +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; + +final class ContentDigest { + static String of(String text) throws NoSuchAlgorithmException { + byte[] sum = MessageDigest.getInstance("SHA-256").digest(text.getBytes(StandardCharsets.UTF_8)); + return HexFormat.of().formatHex(sum); + } +} +``` + +`HexFormat` требует Java 17; на старом runtime использовать существующее +проверенное кодирование hex, не обновлять весь сервис ради этого примера. +Не делить один изменяемый `MessageDigest` между потоками. Сохранить ожидаемый +формат ответа; этот digest не заменяет алгоритм хранения паролей. + +**Проверить:** известный digest, пустой текст, Unicode и кавычки; `null` отклонён +на входе API; внешняя программа не запускается. + +
+ + + + + +## JAVA-JACKSON-TYPES. Jackson default typing + +**Поиск:** скрипт, правило JAVA-JACKSON-TYPES. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain JAVA-JACKSON-TYPES. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API. + +**Уязвимый вариант:** + +~~~java +mapper.enableDefaultTyping(); +~~~ + +**Исправление:** Конкретные DTO; если полиморфизм необходим — ограниченный набор подтипов/валидатор своей версии, не package-wide allowlist. + +~~~java +// deserialize into a fixed DTO without client-selected implementation types +~~~ + +**Проверка:** Неизвестный тип отвергается до побочных эффектов; старый допустимый документ читается. + +**Основание:** [первичный материал](https://github.com/FasterXML/jackson-docs/wiki/JacksonPolymorphicDeserialization). + + + + + +## JAVA-XML. XML parser требует явной политики внешних ресурсов + +**Поиск:** скрипт, правило JAVA-XML. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain JAVA-XML. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API. + +**Уязвимый вариант:** + +~~~java +var f = DocumentBuilderFactory.newInstance(); +~~~ + +**Исправление:** Ограничить DTD/entities/schema/XSLT для конкретного factory, включить лимиты. Неподдержанный security feature не игнорировать. + +~~~java +var f = DocumentBuilderFactory.newInstance(); +f.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, ""); +f.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, ""); +// also configure DTD/entity policy and parser-specific limits +~~~ + +**Проверка:** Parser не читает внешние файлы/URL; допустимый XML и лимиты работают. + +**Основание:** [первичный материал](https://docs.oracle.com/en/java/javase/17/security/java-api-xml-processing-jaxp-security-guide.html). + + + + + +## JAVA-EXPRESSION. Клиентский текст парсится как SpEL + +**Поиск:** скрипт, правило JAVA-EXPRESSION. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain JAVA-EXPRESSION. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API. + +**Уязвимый вариант:** + +~~~java +parser.parseExpression(input).getValue(context); +~~~ + +**Исправление:** Фиксированные операции и аргументы; если DSL нужен, минимальная грамматика и возможности evaluation context. Не отдавать полный reflection клиенту. + +~~~java +lookupAllowedOperation(operationId, validatedArguments); +~~~ + +**Проверка:** Запрещённые операции не достигают runtime; разрешённые вычисления сохранены. + +**Основание:** [первичный материал](https://docs.spring.io/spring-framework/reference/core/expressions.html). + + + + + +## JAVA-PATH. Path resolve без ограничения корня + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'resolve\(|readAllBytes|new File|Paths.get|toRealPath' . +~~~ + +Сравнить Path root и target после нормализации/разрешения ссылки; проверить ownership и гонку открытия. + +**Уязвимый вариант:** + +Files.readAllBytes(base.resolve(name)) читает имя клиента без границы. + +**Исправление:** Серверное имя из авторизованного ID либо Path containment, отдельная политика symlink и безопасное открытие; лимит чтения. + +**Проверка:** Соседний каталог с общим префиксом, absolute path, symlink, чужой объект и штатный файл. + +
+Развёрнутый пример и ограничения + +```java +// Vulnerable: name can move the read outside the permitted directory. +byte[] data = Files.readAllBytes(base.resolve(name)); +``` + +**Патч для существующих файлов в доверенном неизменяемом дереве:** + +```java +import java.io.IOException; +import java.nio.file.*; + +final class FileBoundary { + static Path existingFile(Path base, String name) throws IOException { + if (name == null || name.isEmpty()) throw new IllegalArgumentException("path required"); + Path relative = Path.of(name); + if (relative.isAbsolute()) throw new IllegalArgumentException("relative path required"); + Path root = base.toRealPath(); + Path target = root.resolve(relative).toRealPath(); + if (!target.startsWith(root) || !Files.isRegularFile(target)) { + throw new IllegalArgumentException("outside allowed directory"); + } + return target; + } +} +``` + +Здесь `startsWith` — метод **Path**, не строковое сравнение. `toRealPath` требует +существования и учитывает symlink. Если дерево может меняться между проверкой +и открытием, остаётся TOCTOU: нужен подход с безопасным открытием относительно +каталога, поддержанный платформой. Этот фрагмент не предназначен для записи +или распаковки архивов. Проверка права на файл и лимит чтения требуются отдельно. + +**Проверить:** разрешённый файл, соседний каталог с похожим именем, абсолютный +путь, ссылка наружу, отсутствие файла, файл другого пользователя. + +
+ +**Основание:** [первичный материал](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/nio/file/Path.html). + + + + + +## JAVA-ZIP-SLIP. ZipEntry становится выходным путём + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'ZipInputStream|ZipFile|getName\(|resolve\(' . +~~~ + +Пройти каждый entry → target → write, включая имена каталогов и metadata links. + +**Уязвимый вариант:** + +Имя из архива присоединено к каталогу без containment и контроля фактического дерева. + +**Исправление:** Валидировать все пути/типы, не следовать недоверенным ссылкам, ограничить размер/entries и публиковать после успеха. + +**Проверка:** Обычный архив, absolute/traversal entry, превышение объёма и уборка при отказе. + +**Основание:** [первичный материал](https://cheatsheetseries.owasp.org/cheatsheets/File_Upload_Cheat_Sheet.html). + + + + + +## JAVA-SPRING-BIND. Spring binding в domain entity + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e '@ModelAttribute|@RequestBody|DataBinder|setAllowedFields|BeanUtils' . +~~~ + +Сверить публичные setters, nested properties и поля владельца с данными запроса. + +**Уязвимый вариант:** + +Binder пишет owner/admin/status в entity до проверки доступа. + +**Исправление:** Отдельный request DTO с разрешёнными полями и явное копирование после auth; ограничения вложенных путей. + +**Проверка:** Служебные поля и nested update не меняются; допустимое частичное обновление работает. + + + + + +## JAVA-SECURITY-MATCHER. Порядок matchers и method security + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'SecurityFilterChain|requestMatchers|permitAll|PreAuthorize|EnableMethodSecurity' . +~~~ + +Проверить первый подходящий matcher, все HTTP-методы, dispatch types и включение method security. + +**Уязвимый вариант:** + +Широкий permitAll срабатывает раньше приватного правила; аннотация метода не активна. + +**Исправление:** Явная политика маршрутов с отказом по умолчанию для приватной области, проверка ресурса в service; согласовать публичные endpoint. + +**Проверка:** Аноним, обычный user и admin проходят ожидаемые маршруты/методы; error/forward не обходят auth. + + + + + +## JAVA-THREADLOCAL. ThreadLocal переносит пользователя следующему запросу + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'ThreadLocal|SecurityContext|Executor|CompletableFuture|remove\(' . +~~~ + +Сверить set/remove в finally и передачу контекста в thread pool. + +**Уязвимый вариант:** + +Поток переиспользуется после исключения с прежним principal. + +**Исправление:** Штатный security-context lifecycle или явная очистка; async task получает минимальный неизменяемый контекст. + +**Проверка:** Последовательные разные пользователи на одном worker и исключение между установкой/очисткой. + + + + + +## JAVA-REGEX-DOS. Регулярное выражение блокирует поток + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'Pattern.compile|Matcher|matches\(|replaceAll' . +~~~ + +Проверить вложенные квантификаторы и почти совпадающие длинные строки; timeout запроса не обязательно прерывает matcher. + +**Уязвимый вариант:** + +Backtracking на вводе клиента занимает worker вне установленного HTTP timeout. + +**Исправление:** Упростить паттерн/детерминированный parser, ограничить длину, при нужде совместимый движок с ограниченной сложностью. + +**Проверка:** Длинный неуспешный match завершается в бюджете; обычный формат и Unicode сохранены. + + + + + +## JAVA-JNDI. Недоверенное имя JNDI lookup + +**Поиск:** скрипт, правило JAVA-JNDI. Запуск: python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain JAVA-JNDI. Regex: InitialContext.doLookup или ctx/context/initialContext.lookup с нестроковым аргументом. Произвольные имена объектов и косвенные вызовы искать вручную. + +Дополнительный ручной поиск для непокрытых форм: + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'InitialContext|JndiTemplate|lookup\(|NamingManager' . +~~~ + +Проследить имя/provider URL и локальные object factories; ограничения удалённого codebase не отменяют остальные эффекты. + +**Уязвимый вариант:** + +Клиент выбирает ресурс/службу для lookup с привилегиями приложения. + +**Исправление:** Закрытая серверная карта доверенных локальных имён, ограниченные providers/factories и совместимый исправленный runtime. Обновление JDK не заменяет проверку входных данных. + +**Проверка:** Чужая схема/имя не вызывает lookup; штатный datasource работает. + + +**Сигнал сканера — пример до:** + +~~~java +Object value = context.lookup(requestName); +~~~ + +**Шаблон исправления:** + +~~~java +Object value = context.lookup("java:comp/env/jdbc/Notes"); +~~~ + +Первичная документация: [документация 1](https://docs.oracle.com/en/java/javase/21/docs/api/java.naming/javax/naming/InitialContext.html). + + + + + +## JAVA-ERROR-LEAK. Stack trace и SQL в API-ошибке + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'printStackTrace|getMessage\(|ResponseEntity|ExceptionHandler' . +~~~ + +Сравнить локальный журнал и клиентский body для ошибок auth/SQL/parser. + +**Уязвимый вариант:** + +Клиент получает SQL, пути, connection string или секретные параметры из exception. + +**Исправление:** Штатная кодированная ошибка и correlation ID; чувствительные значения редактировать до логирования. + +**Проверка:** Диагностика остаётся локально, ответы ошибок не содержат приватных данных. + + + + + +## JAVA-HOSTNAME-VERIFY. Hostname verifier принимает любой сервер + +**Поиск:** скрипт, правило JAVA-HOSTNAME-VERIFY. Запуск: python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain JAVA-HOSTNAME-VERIFY. Regex: NoopHostnameVerifier/ALLOW_ALL_HOSTNAME_VERIFIER и setHostnameVerifier с простой true-lambda; сложные callbacks и TrustManager требуют ручного анализа. + +**Уязвимый вариант:** Проверка цепочки сертификата без имени не подтверждает нужный сервер. + +~~~java +builder.setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE); +~~~ + +**Исправление:** Вернуть стандартный verifier и доверенный trust store; не подменять его callback, всегда возвращающим true. + +~~~java +builder.setSSLHostnameVerifier(new DefaultHostnameVerifier()); +~~~ + +**Проверка:** Сертификат доверенного CA для другого hostname отклоняется; свой endpoint работает. + +Первичная документация: [документация 1](https://hc.apache.org/httpcomponents-client-5.5.x/current/httpclient5/apidocs/org/apache/hc/client5/http/ssl/NoopHostnameVerifier.html). + + + + + +## JAVA-SPRING-CSRF. CSRF отключён в Spring Security + +**Поиск:** скрипт, правило JAVA-SPRING-CSRF. Запуск: python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain JAVA-SPRING-CSRF. Regex: csrf().disable(), csrf(x -> x.disable()) и csrf(AbstractHttpConfigurer::disable). Отдельные security chains и матчеры просматривать вручную. + +**Уязвимый вариант:** Cookie-auth операции могут потерять CSRF-защиту при глобальном disable. + +~~~java +http.csrf(csrf -> csrf.disable()); +~~~ + +**Исправление:** Сохранить защиту браузерных запросов; исключения ограничить конкретным bearer/webhook контрактом и проверить отсутствие cookie fallback. + +~~~java +http.csrf(Customizer.withDefaults()); +~~~ + +**Проверка:** Штатный запрос с CSRF работает, cookie POST без токена отвергнут; разрешённый API сценарий не сломан. + +Первичная документация: [документация 1](https://docs.spring.io/spring-security/reference/servlet/exploits/csrf.html). + + + + + +## JAVA-LDAP-FILTER. Фильтр поиска JNDI собирается конкатенацией + +**Поиск:** правило сканера JAVA-LDAP-FILTER. Точный контракт детектора: `--explain JAVA-LDAP-FILTER`. Regex с лексическими исключениями: ctx/context/dirContext.search с простым первым аргументом и напрямую склеенным строковым фильтром. Не разрешает тип получателя, заранее собранные фильтры, wrappers и предшествующее экранирование. + +**Уязвимый вариант:** + +~~~java +ctx.search(base, "(uid=" + name + ")", controls); +~~~ + +**Исправление:** Используйте аргументы фильтра JNDI с фиксированным фильтром; сохраняйте явную область поиска и авторизацию. + +~~~java +ctx.search(base, "(uid={0})", new Object[] { name }, controls); +~~~ + +**Проверка:** Метасимволы фильтра остаются значениями; недоступные пользователю записи не раскрываются, а допустимые поиски работают. + +[Первичный источник 1](https://docs.oracle.com/javase/jndi/tutorial/ldap/search/search.html) diff --git a/docs/vulnerabilities/java.md b/docs/vulnerabilities/java.md new file mode 100644 index 0000000..360f343 --- /dev/null +++ b/docs/vulnerabilities/java.md @@ -0,0 +1,533 @@ +# Java: find, fix and verify + +English | [Русский](java-RU.md) + +[Catalog](README.md) · [Scanner](../offline-scanner.md) · [Patch verification](../patch-validation.md) + +18 sections. Each follows **Search → Vulnerable example → Fix → Verification**. +Run `rg` from a local service checkout; searches only read files. Derive the actor/owner from a verified session, not request data. Adapt examples to the actual API and contract. + +## Contents + +- [JAVA-OBJECT — Java ObjectInputStream](#java-object) +- [JAVA-RNG — java.util.Random near a possible secret](#java-rng) +- [JAVA-SQL — Dynamic JDBC SQL](#java-sql) +- [JAVA-PROCESS — Java process execution](#java-process) +- [JAVA-JACKSON-TYPES — Jackson default typing](#java-jackson-types) +- [JAVA-XML — XML parser needs an external-resource policy](#java-xml) +- [JAVA-EXPRESSION — Client text parsed as SpEL](#java-expression) +- [JAVA-PATH — Path resolve without a root boundary](#java-path) +- [JAVA-ZIP-SLIP — ZipEntry becomes an output path](#java-zip-slip) +- [JAVA-SPRING-BIND — Spring binds request data into a domain entity](#java-spring-bind) +- [JAVA-SECURITY-MATCHER — Matcher ordering and method security](#java-security-matcher) +- [JAVA-THREADLOCAL — ThreadLocal leaks the previous request's user](#java-threadlocal) +- [JAVA-REGEX-DOS — A regular expression blocks a worker](#java-regex-dos) +- [JAVA-JNDI — Dynamic JNDI lookup name](#java-jndi) +- [JAVA-ERROR-LEAK — Stack traces and SQL in API errors](#java-error-leak) +- [JAVA-HOSTNAME-VERIFY — Hostname verifier accepts every peer](#java-hostname-verify) +- [JAVA-SPRING-CSRF — Spring Security CSRF disabled](#java-spring-csrf) +- [JAVA-LDAP-FILTER — JNDI search filter assembled by concatenation](#java-ldap-filter) + + + +## JAVA-OBJECT. Java ObjectInputStream + +**Search:** scanner rule JAVA-OBJECT. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain JAVA-OBJECT` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries. + +**Vulnerable example:** + +~~~java +ObjectInputStream in = new ObjectInputStream(stream); +~~~ + +**Fix:** Prefer constrained DTO parsing over native object deserialization; migrate trusted legacy data separately. + +~~~java +Message value = parseValidatedMessage(stream); +~~~ + +**Verification:** Unknown types cannot be constructed; ordinary messages stay compatible. + + + +## JAVA-RNG. java.util.Random near a possible secret + +**Search:** scanner rule JAVA-RNG. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain JAVA-RNG` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries. + +**Vulnerable example:** + +~~~java +Random rng = new Random(); +~~~ + +**Fix:** Use SecureRandom and sufficient token length for secrets. + +~~~java +SecureRandom rng = new SecureRandom(); +~~~ + +**Verification:** No predictable seed or fallback exists; valid tokens work. + +**A/D variant:** Public PRNG output and secret challenges. **Reference:** 8-bit-oracle, the author's write-up and saarCTF Java source. One java.util.Random instance generated both public values and challenges. Hashing a 32-bit value does not enlarge its secret space. Scanner: JAVA-RNG; Random outside a security context can be legitimate. + +**Patch:** Use sufficiently long SecureRandom.nextBytes output without predictable seeds; public statistics must not share secret-generator state. +**Test:** Challenge format and one-time use, randomness source/length and the normal verification workflow. Statistical tests do not prove cryptographic strength. + +[Source/write-up 1](https://github.com/saarsec/saarctf-2024/blob/3a06d18974ca177c6dd251a11bdf9b4b334f382a/8-bit-oracle/README.md); [source/write-up 2](https://github.com/saarsec/saarctf-2024/blob/3a06d18974ca177c6dd251a11bdf9b4b334f382a/8-bit-oracle/service/_8BitOracle/src/Util.java). + + + +## JAVA-SQL. Dynamic JDBC SQL + +**Search:** scanner rule JAVA-SQL. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain JAVA-SQL` for details. Regex: executeQuery/executeUpdate/execute/prepareStatement/prepareCall with concatenation or String.format. PreparedStatement does not secure already-built SQL; inspect SQL variables and formatter wrappers. + +**Vulnerable example:** + +~~~java +statement.executeQuery("SELECT id FROM notes WHERE name=" + name); +~~~ + +**Fix:** Bind values with PreparedStatement, not already-concatenated SQL; allowlist identifiers. + +~~~java +PreparedStatement q = connection.prepareStatement("SELECT id FROM notes WHERE name=?"); +q.setString(1, name); +q.executeQuery(); +~~~ + +**Verification:** Quotes stay data and ownership remains enforced. + +
+Expanded example and limitations + +```java +// Vulnerable: inputId is interpolated into SQL without an owner constraint. +ResultSet rs = statement.executeQuery("SELECT body FROM notes WHERE id = '" + inputId + "'"); +``` + +**JDBC patch for a private note:** + +```java +import java.sql.*; +import java.util.Optional; + +final class NoteReader { + static Optional read(Connection db, Long userId, long noteId) throws SQLException { + if (userId == null) throw new SecurityException("authentication required"); + try (PreparedStatement st = db.prepareStatement( + "SELECT body FROM notes WHERE id = ? AND owner_id = ?")) { + st.setLong(1, noteId); + st.setLong(2, userId); + try (ResultSet rows = st.executeQuery()) { + return rows.next() ? Optional.of(rows.getString("body")) : Optional.empty(); + } + } + } +} +``` + +The example assumes `body NOT NULL`. If NULL is allowed, distinguish it from a missing row. The statement/result set are closed, but not the caller-owned connection. Parse incoming IDs with error handling. PreparedStatement around an already concatenated query does not fix injection. + +**Check:** Owner, other user, anonymous caller; invalid/missing IDs; old data; database errors must not become successful empty responses. + +
+ + + +## JAVA-PROCESS. Java process execution + +**Search:** scanner rule JAVA-PROCESS. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain JAVA-PROCESS` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries. + +**Vulnerable example:** + +~~~java +Runtime.getRuntime().exec(command); +~~~ + +**Fix:** Use a library operation or fixed executable with validated argv and bounded time/output. + +~~~java +runValidatedConversion(inputPath); // fixed executable and validated argv inside +~~~ + +**Verification:** Arguments cannot choose another operation; output stays compatible. + +
+Expanded example and limitations + +```java +// Vulnerable: ProcessBuilder does not protect an explicit shell command. +Process p = new ProcessBuilder("sh", "-c", "printf '%s' '" + text + "' | sha256sum").start(); +``` + +**Patch for a string's SHA-256 digest:** + +```java +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; + +final class ContentDigest { + static String of(String text) throws NoSuchAlgorithmException { + byte[] sum = MessageDigest.getInstance("SHA-256").digest(text.getBytes(StandardCharsets.UTF_8)); + return HexFormat.of().formatHex(sum); + } +} +``` + +`HexFormat` requires Java 17; on older runtimes use the existing reviewed hex encoder rather than upgrading the entire service for this example. Never share mutable MessageDigest state across threads. Preserve the response format; this digest is not a password-storage algorithm. + +**Check:** Known digest, empty text, Unicode and quotes; reject null at the API boundary; no external program runs. + +
+ + + +## JAVA-JACKSON-TYPES. Jackson default typing + +**Search:** scanner rule JAVA-JACKSON-TYPES. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain JAVA-JACKSON-TYPES` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries. + +**Vulnerable example:** + +~~~java +mapper.enableDefaultTyping(); +~~~ + +**Fix:** Prefer explicit DTOs; required polymorphism needs a narrow type set/validator for the installed version, not a package-wide allowlist. + +~~~java +// deserialize into a fixed DTO without client-selected implementation types +~~~ + +**Verification:** Unknown types fail before side effects; valid documents remain readable. + +**Reference:** [primary source](https://github.com/FasterXML/jackson-docs/wiki/JacksonPolymorphicDeserialization). + + + +## JAVA-XML. XML parser needs an external-resource policy + +**Search:** scanner rule JAVA-XML. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain JAVA-XML` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries. + +**Vulnerable example:** + +~~~java +var f = DocumentBuilderFactory.newInstance(); +~~~ + +**Fix:** Restrict DTD/entities/schema/XSLT on the actual factory and set limits; never silently ignore unsupported security options. + +~~~java +var f = DocumentBuilderFactory.newInstance(); +f.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, ""); +f.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, ""); +// also configure DTD/entity policy and parser-specific limits +~~~ + +**Verification:** Parser reads no external files/URLs; ordinary XML and size limits work. + +**Reference:** [primary source](https://docs.oracle.com/en/java/javase/17/security/java-api-xml-processing-jaxp-security-guide.html). + + + +## JAVA-EXPRESSION. Client text parsed as SpEL + +**Search:** scanner rule JAVA-EXPRESSION. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain JAVA-EXPRESSION` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries. + +**Vulnerable example:** + +~~~java +parser.parseExpression(input).getValue(context); +~~~ + +**Fix:** Use fixed operations/arguments or a restricted DSL and evaluation context; never expose arbitrary reflection. + +~~~java +lookupAllowedOperation(operationId, validatedArguments); +~~~ + +**Verification:** Disallowed operations cannot reach runtime; approved calculations work. + +**Reference:** [primary source](https://docs.spring.io/spring-framework/reference/core/expressions.html). + + + +## JAVA-PATH. Path resolve without a root boundary + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'resolve\(|readAllBytes|new File|Paths.get|toRealPath' . +~~~ + +Compare root and target Paths after normalization/link resolution; check ownership and open-time races. + +**Vulnerable example:** + +`Files.readAllBytes(base.resolve(name))` reads a client-selected name without a boundary. + +**Fix:** Derive a server-side filename from an authorized ID, or enforce Path containment with an explicit symlink policy and safe opening; bound reads. + +**Verification:** Sibling directory with a shared prefix, absolute path, symlink, another owner's object and a legitimate file. + +
+Expanded example and limitations + +```java +// Vulnerable: name can move the read outside the permitted directory. +byte[] data = Files.readAllBytes(base.resolve(name)); +``` + +**Patch for existing files in a trusted immutable tree:** + +```java +import java.io.IOException; +import java.nio.file.*; + +final class FileBoundary { + static Path existingFile(Path base, String name) throws IOException { + if (name == null || name.isEmpty()) throw new IllegalArgumentException("path required"); + Path relative = Path.of(name); + if (relative.isAbsolute()) throw new IllegalArgumentException("relative path required"); + Path root = base.toRealPath(); + Path target = root.resolve(relative).toRealPath(); + if (!target.startsWith(root) || !Files.isRegularFile(target)) { + throw new IllegalArgumentException("outside allowed directory"); + } + return target; + } +} +``` + +`startsWith` here is a **Path** method, not string-prefix comparison. `toRealPath` requires existence and resolves symlinks. A mutable tree still permits TOCTOU between checking and opening: use platform-supported directory-relative safe opening. This snippet is not for writing or archive extraction. Authorization and read limits remain separate requirements. + +**Check:** Allowed file, similarly named sibling directory, absolute path, outward link, missing file and another user's file. + +
+ +**Reference:** [primary source](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/nio/file/Path.html). + + + +## JAVA-ZIP-SLIP. ZipEntry becomes an output path + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'ZipInputStream|ZipFile|getName\(|resolve\(' . +~~~ + +Trace every entry through target selection to writing, including directory names and link metadata. + +**Vulnerable example:** + +An archive name is joined to a directory without containment or checking the actual filesystem tree. + +**Fix:** Validate all paths/types, avoid untrusted links, limit expanded size/entries and publish only after success. + +**Verification:** Ordinary archive, absolute/traversal entries, volume overflow and cleanup after rejection. + +**Reference:** [primary source](https://cheatsheetseries.owasp.org/cheatsheets/File_Upload_Cheat_Sheet.html). + + + +## JAVA-SPRING-BIND. Spring binds request data into a domain entity + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e '@ModelAttribute|@RequestBody|DataBinder|setAllowedFields|BeanUtils' . +~~~ + +Compare public setters, nested properties and ownership fields with incoming data. + +**Vulnerable example:** + +The binder writes owner/admin/status into an entity before authorization. + +**Fix:** A dedicated request DTO with allowed fields, copied explicitly after authorization; restrict nested paths. + +**Verification:** Administrative fields and nested updates cannot change; legitimate partial updates work. + + + +## JAVA-SECURITY-MATCHER. Matcher ordering and method security + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'SecurityFilterChain|requestMatchers|permitAll|PreAuthorize|EnableMethodSecurity' . +~~~ + +Check the first matching rule, all HTTP methods, dispatch types and whether method security is actually enabled. + +**Vulnerable example:** + +A broad permitAll precedes a private rule, or the method annotation is inactive. + +**Fix:** Explicit route policy with default denial for private areas and resource checks in the service layer; preserve intended public endpoints. + +**Verification:** Anonymous, ordinary and administrator users get their expected routes/methods; error/forward dispatch does not bypass authorization. + + + +## JAVA-THREADLOCAL. ThreadLocal leaks the previous request's user + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'ThreadLocal|SecurityContext|Executor|CompletableFuture|remove\(' . +~~~ + +Review set/remove inside finally and context propagation into thread pools. + +**Vulnerable example:** + +A thread is reused after an exception with the previous principal still attached. + +**Fix:** Use the framework's security-context lifecycle or explicit cleanup; give async tasks minimal immutable context. + +**Verification:** Sequential different users on the same worker and an exception between context setup and cleanup. + + + +## JAVA-REGEX-DOS. A regular expression blocks a worker + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'Pattern.compile|Matcher|matches\(|replaceAll' . +~~~ + +Review nested quantifiers and long near-matches; request timeout does not necessarily interrupt the matcher. + +**Vulnerable example:** + +Backtracking on client input occupies a worker beyond the HTTP timeout. + +**Fix:** Simplify the pattern or use a deterministic parser, limit input length and, where compatible, use a bounded-complexity engine. + +**Verification:** Long failing matches finish within budget; normal formats and Unicode remain compatible. + + + +## JAVA-JNDI. Dynamic JNDI lookup name + +**Search:** scanner rule JAVA-JNDI. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain JAVA-JNDI` for details. Regex: InitialContext.doLookup or ctx/context/initialContext.lookup with a non-string argument. Inspect arbitrary receiver names and indirect calls manually. + +Additional manual search for forms outside automatic coverage: + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'InitialContext|JndiTemplate|lookup\(|NamingManager' . +~~~ + +Trace the name/provider URL and local object factories; disabling remote codebases does not remove other effects. + +**Vulnerable example:** + +The client selects the resource/service for a lookup using application privileges. + +**Fix:** Use a closed map of trusted local names and restrict providers; JDK updates do not replace input validation. + +**Verification:** Valid resources resolve; unknown/external names cannot initiate lookups or change backend. + +**Scanner example before:** + +~~~java +Object value = context.lookup(requestName); +~~~ + +**Fix template:** + +~~~java +Object value = context.lookup("java:comp/env/jdbc/Notes"); +~~~ + +Primary documentation: [reference 1](https://docs.oracle.com/en/java/javase/21/docs/api/java.naming/javax/naming/InitialContext.html). + + + +## JAVA-ERROR-LEAK. Stack traces and SQL in API errors + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'printStackTrace|getMessage\(|ResponseEntity|ExceptionHandler' . +~~~ + +Compare private logs with client response bodies for authorization, SQL and parser failures. + +**Vulnerable example:** + +An exception exposes SQL, paths, connection strings or secret arguments to the client. + +**Fix:** Return a standard encoded error with correlation ID; redact sensitive values before logging. + +**Verification:** Diagnostics remain private; error responses contain no private data. + + + +## JAVA-HOSTNAME-VERIFY. Hostname verifier accepts every peer + +**Search:** scanner rule JAVA-HOSTNAME-VERIFY. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain JAVA-HOSTNAME-VERIFY` for details. Regex: NoopHostnameVerifier/ALLOW_ALL_HOSTNAME_VERIFIER and setHostnameVerifier with a simple true-lambda. Review complex callbacks and TrustManager separately. + +**Vulnerable example:** Certificate-chain validation without hostname validation does not authenticate the intended server. + +~~~java +builder.setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE); +~~~ + +**Fix:** Restore the default verifier and trusted store instead of always-true callbacks. + +~~~java +builder.setSSLHostnameVerifier(new DefaultHostnameVerifier()); +~~~ + +**Verification:** Trusted CA certificates for another host fail; the intended endpoint works. + +Primary documentation: [reference 1](https://hc.apache.org/httpcomponents-client-5.5.x/current/httpclient5/apidocs/org/apache/hc/client5/http/ssl/NoopHostnameVerifier.html). + + + +## JAVA-SPRING-CSRF. Spring Security CSRF disabled + +**Search:** scanner rule JAVA-SPRING-CSRF. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain JAVA-SPRING-CSRF` for details. Regex: csrf().disable(), csrf(x -> x.disable()) and csrf(AbstractHttpConfigurer::disable). Review individual security chains and matchers. + +**Vulnerable example:** Global disable can remove CSRF protection from cookie-authenticated operations. + +~~~java +http.csrf(csrf -> csrf.disable()); +~~~ + +**Fix:** Keep protection for browser routes; restrict exemptions to an explicit bearer/webhook contract with no cookie fallback. + +~~~java +http.csrf(Customizer.withDefaults()); +~~~ + +**Verification:** Valid CSRF requests work; cookie POST without a token fails; approved API scenarios work. + +Primary documentation: [reference 1](https://docs.spring.io/spring-security/reference/servlet/exploits/csrf.html). + + + +## JAVA-LDAP-FILTER. JNDI search filter assembled by concatenation + +**Search:** scanner rule JAVA-LDAP-FILTER. Use `--explain JAVA-LDAP-FILTER` for the exact detector contract. Regex with lexical exclusions: ctx/context/dirContext.search with a simple first argument and directly concatenated string filter. Does not resolve receiver types, prebuilt filters, wrappers or earlier escaping. + +**Vulnerable example:** + +~~~java +ctx.search(base, "(uid=" + name + ")", controls); +~~~ + +**Fix:** Use JNDI filter arguments with a fixed filter, and retain explicit search scope and authorization. + +~~~java +ctx.search(base, "(uid={0})", new Object[] { name }, controls); +~~~ + +**Verification:** Filter metacharacters remain values; unauthorized entries stay inaccessible and valid searches work. + +[Primary reference 1](https://docs.oracle.com/javase/jndi/tutorial/ldap/search/search.html) diff --git a/docs/vulnerabilities/javascript-RU.md b/docs/vulnerabilities/javascript-RU.md new file mode 100644 index 0000000..a357583 --- /dev/null +++ b/docs/vulnerabilities/javascript-RU.md @@ -0,0 +1,1023 @@ + + +# JavaScript / TypeScript: поиск и исправление + +[English](javascript.md) | Русский + +[Вся база](README-RU.md) · [Сканер](../offline-scanner-RU.md) · [Проверка патча](../patch-validation-RU.md) + +28 разделов. Формат: **Поиск → Уязвимый вариант → Исправление → Проверка**. +Команды `rg` выполняются в корне локальной копии сервиса и только читают файлы. Субъект/владелец определяется по проверенной сессии, а не данным запроса. Примеры нужно адаптировать к реальным API и контракту. + +Автоматические находки — ограниченные синтаксические сигналы для проверки. AST-анализ не разрешает типы и не отслеживает данные между функциями; regex не заменяет парсер языка. Комментарии, строки и одноимённые пользовательские API могут давать совпадения. Проверьте фактическое исполнение, входные данные, авторизацию и границы доверия. + + + +## Содержание + +- [JS-SHELL — Shell API Node.js](#js-shell) +- [JS-EVAL — Динамический JavaScript](#js-eval) +- [JS-SQL — Динамический SQL Node.js](#js-sql) +- [JS-NOSQL — Тело запроса как фильтр MongoDB](#js-nosql) +- [JS-MASS-ASSIGN — Массовое присваивание](#js-mass-assign) +- [JS-PROTOTYPE — Глубокое слияние недоверенного объекта](#js-prototype) +- [JS-TLS — TLS отключён в Node.js](#js-tls) +- [JS-HTML — HTML sink](#js-html) +- [JS-TRUST-PROXY — Полное доверие proxy-заголовкам](#js-trust-proxy) +- [JS-CURL-ARGV — curl из Node.js: проверить опции и URL](#js-curl-argv) +- [JS-SESSION-STATE — Изменение чувствительного состояния сессии](#js-session-state) +- [JS-VM — node:vm используется как security sandbox](#js-vm) +- [JS-REGEX-DYNAMIC — Regex создаётся из клиентского текста](#js-regex-dynamic) +- [JS-TYPE-ASSERTION — TypeScript as не валидирует JSON](#js-type-assertion) +- [JS-AWAIT-AUTH — Забытый await у проверки прав](#js-await-auth) +- [JS-WEBSOCKET — WebSocket: права только на handshake](#js-websocket) +- [JS-GRAPHQL — GraphQL: resolver и batching обходят общий guard](#js-graphql) +- [JS-SESSION-FIXATION — Сессия не меняется после входа](#js-session-fixation) +- [JS-SSRF — fetch/axios: redirect и повторное DNS-разрешение](#js-ssrf) +- [JS-BUFFER-EXPOSURE — Неинициализированная память в Buffer](#js-buffer-exposure) +- [JS-JWT-DECODE — JWT декодируется без проверки подписи](#js-jwt-decode) +- [JS-JWT-OPTIONS — Ослабленные параметры JWT](#js-jwt-options) +- [JS-HTTP-PARSER — Ослабленный HTTP parser Node.js](#js-http-parser) +- [JS-STATIC-DOTFILES — Статика разрешает скрытые файлы](#js-static-dotfiles) +- [JS-QUERY-SHAPE — Параметр меняет тип между middleware](#js-query-shape) +- [JS-MIDDLEWARE-TRUST — Обработчик доверяет выполнению middleware](#js-middleware-trust) +- [JS-REDIRECT-INPUT — Поле запроса напрямую передаётся в Express-подобный redirect](#js-redirect-input) + +- [JS-LOG-CREDENTIALS — Credentials напрямую передаются в console](#js-log-credentials) + + + + + +## JS-SHELL. Shell API Node.js + +**Поиск:** скрипт, правило JS-SHELL. Запуск: python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain JS-SHELL. Regex: exec/execSync без receiver, распространённые child_process/cp receiver, shell:true или непустая строка shell, буквальный shell у spawn/execFile. Дополнительно статические ESM/CommonJS imports child_process с aliases и строковым bracket-access. Произвольный object.exec не считается процессом. Imports — подсказка без scope/type/data-flow анализа: комментарии, shadowing и reassignment могут дать ложный сигнал; wrappers и dynamic import требуют ручного просмотра. + +**Уязвимый вариант:** + +~~~javascript +child_process.exec(command); +~~~ + +**Исправление:** execFile/spawn с shell:false, фиксированным executable, проверенными argv и ограничением времени исполнения. + +~~~javascript +child_process.execFile('/usr/bin/file', ['--', filename], {timeout: 3000}, callback); +~~~ + +**Проверка:** Спецсимволы остаются данными; опасные опции отклоняются; штатные команды работают. + +
+Развёрнутый пример и ограничения + +```javascript +// Vulnerable: a shell interprets the command string. +exec("printf '%s' '" + req.body.text + "' | sha256sum", callback); +``` + +**Патч для хеша содержимого:** + + +```javascript +const { createHash } = require("node:crypto"); + +function digestText(text) { + if (typeof text !== "string") throw new TypeError("string required"); + return createHash("sha256").update(text, "utf8").digest("hex"); +} +``` + +Для ESM использовать `import { createHash } from "node:crypto"`. +Сохранить кодировку и внешний формат результата. Если внешняя программа +действительно нужна, фиксировать executable и аргументы отдельно; даже +`execFile` не запрещает вредную опцию самой программы автоматически. + +**Проверить:** известный digest, пустая строка, Unicode, кавычки и переводы строк; +нет дочернего процесса. SHA-256 сам по себе не подходит для хранения паролей. + +
+ + + + + +## JS-EVAL. Динамический JavaScript + +**Поиск:** скрипт, правило JS-EVAL. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain JS-EVAL. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API. + +**Уязвимый вариант:** + +~~~javascript +const value = eval(input); +~~~ + +**Исправление:** JSON.parse + схема для данных; ограниченный парсер для выражений. + +~~~javascript +const value = JSON.parse(input); // validate schema +~~~ + +**Проверка:** Выражения не исполняются; размер/структура ограничены. + + + + + +## JS-SQL. Динамический SQL Node.js + +**Поиск:** правило сканера JS-SQL. Подробности: `--explain JS-SQL`. Старый regex с исключением комментариев/строк: строковая сборка query/execute или text/sql objects (receiver без определения типа). Ограниченный анализ токенов также распознаёт прямое свойство req/request.body/query/params как SQL у pg Pool/Client или mysql/mysql2 createPool/createConnection через default/namespace import. Именованные импорты, полученные соединения, SQL-переменные, tagged templates, wrappers и потоки между файлами требуют ручной проверки. + +**Уязвимый вариант:** + +~~~javascript +db.query("SELECT id FROM notes WHERE name=" + name); +~~~ + +**Исправление:** Параметризовать значения синтаксисом драйвера; identifiers по allowlist. + +~~~javascript +db.query("SELECT id FROM notes WHERE name=?", [name]); +~~~ + +**Проверка:** Кавычки — данные; owner_id сохраняется. + +
+Развёрнутый пример и ограничения + +```javascript +// Vulnerable: client input controls the query and ownership is unchecked. +const result = await pool.query(`SELECT body FROM notes WHERE id = '${req.params.id}'`); +``` + +**Патч для node-postgres (`pg`) и приватных заметок:** + + +```javascript +async function readPrivateNote(pool, currentUserId, noteId) { + if (currentUserId == null) throw new Error("authentication required"); + const result = await pool.query( + "SELECT body FROM notes WHERE id = $1 AND owner_id = $2", + [noteId, currentUserId] + ); + if (result.rows.length === 0) return null; + return result.rows[0].body; +} +``` + +`null` здесь означает отсутствие доступного объекта; маршрут преобразует его +в принятый API ответ. Имена колонок/направление сортировки выбирать из фиксированной +карты, не принимать как текст запроса. Маркеры `$1` относятся к PostgreSQL, +не ко всем JS-драйверам. + +**Проверить:** своё читается, чужое не возвращается; апостроф в строковом поле +остаётся данными; ошибочный тип не превращается в запрос другого смысла; +отказ не содержит тела чужой заметки. + +
+ + + + + +## JS-NOSQL. Тело запроса как фильтр MongoDB + +**Поиск:** скрипт, правило JS-NOSQL. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain JS-NOSQL. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API. + +**Уязвимый вариант:** + +~~~javascript +collection.findOne(req.body); +~~~ + +**Исправление:** Собрать фиксированный фильтр из проверенных скаляров и server-side owner_id. + +~~~javascript +if (typeof req.body.name !== 'string') throw new Error('invalid'); +collection.findOne({name: req.body.name, ownerId: currentUser.id}); +~~~ + +**Проверка:** Объект/массив вместо строки отвергается; клиент не выбирает владельца. + +
+Развёрнутый пример и ограничения + +```javascript +// Vulnerable: title may be an operator object rather than a string. +const note = await notes.findOne({ ownerId: currentUserId, title: req.body.title }); +``` + +**Патч:** проверить тип и собрать фильтр самостоятельно. Пример для документа, +где `ownerId` уже имеет ожидаемый тип идентификатора из доверенного контекста. + + +```javascript +function privateTitleFilter(currentUserId, body) { + if (currentUserId == null) throw new Error("authentication required"); + if (body === null || typeof body !== "object" || Array.isArray(body)) { + throw new TypeError("object required"); + } + if (!Object.prototype.hasOwnProperty.call(body, "title") || typeof body.title !== "string") { + throw new TypeError("title must be a string"); + } + return { ownerId: currentUserId, title: body.title }; +} +// In the handler: await notes.findOne(privateTitleFilter(currentUserId, req.body)); +``` + +Не исправлять через `String(req.body.title)`: объект станет бессмысленной +строкой и изменит контракт. Не переносить остальной `req.body` в фильтр и +не смешивать с ним серверное условие владельца. + +**Проверить:** строка, Unicode, разрешённый пустой заголовок; объект, массив, +`null` вместо title отвергаются **до обращения к БД**; присланный `ownerId` +не меняет фильтр. + +
+ + + + + +## JS-MASS-ASSIGN. Массовое присваивание + +**Поиск:** скрипт, правило JS-MASS-ASSIGN. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain JS-MASS-ASSIGN. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API. + +**Уязвимый вариант:** + +~~~javascript +Object.assign(user, req.body); +~~~ + +**Исправление:** Явно перечислить разрешённые поля; роль и владелец задаются сервером. + +~~~javascript +user.displayName = validateName(req.body.displayName); +~~~ + +**Проверка:** Лишние и вложенные поля role/owner не меняют привилегии: они отклоняются или игнорируются; разрешённые поля редактируются. + +
+Развёрнутый пример и ограничения + +```javascript +// Vulnerable: clients can write ownerId/role and other administrative fields. +Object.assign(note, req.body); +``` + +**Патч для редактирования заголовка и текста:** + + +```javascript +function editableNoteFields(body) { + if (body === null || typeof body !== "object" || Array.isArray(body)) { + throw new TypeError("object required"); + } + const result = {}; + for (const key of Object.keys(body)) { + if (key !== "title" && key !== "body") throw new TypeError("unknown field"); + if (typeof body[key] !== "string") throw new TypeError("string required"); + result[key] = body[key]; + } + return result; +} +// After authorization: update only editableNoteFields(req.body). +``` + +Список разрешённых полей не заменяет авторизацию записи. Не «очищать» объект +удалением одного ключа с последующим глубоким merge: вложенные пути остаются. +Клиентский JSON с `__proto__` не должен попадать в произвольный merge. + +**Проверить:** частичное обновление title, допустимый пустой body; `ownerId`, +`role`, неизвестное поле и вложенный объект отвергаются; исходный объект не мутирует. + +
+ + + + + +## JS-PROTOTYPE. Глубокое слияние недоверенного объекта + +**Поиск:** скрипт, правило JS-PROTOTYPE. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain JS-PROTOTYPE. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API. + +**Уязвимый вариант:** + +~~~javascript +merge(settings, req.body); +~~~ + +**Исправление:** Проверить библиотеку/версию; собирать объект из allowlist. Если merge необходим, учитывать опасные ключи на любой глубине. + +~~~javascript +settings.theme = validateTheme(req.body.theme); +~~~ + +**Проверка:** Вложенные ключи не меняют прототип/служебные поля. + + + + + +## JS-TLS. TLS отключён в Node.js + +**Поиск:** скрипт, правило JS-TLS. Запуск: python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain JS-TLS. Regex: rejectUnauthorized:false/присваивание только в JavaScript/config; NODE_TLS_REJECT_UNAUTHORIZED с точным литералом 0 или парными кавычками вокруг 0. Отдельные шаблоны языков: shell KEY=0 до whitespace/;&|/конца; Docker — первый ключ ENV KEY=0 до whitespace/конца или ENV KEY 0 с целым значением, включая парные кавычки. 0.1/0-disabled/0 с пробелом внутри кавычек не сигналят; #//suffix — часть shell/Docker значения, ; также часть Docker ENV. Комментарии/строки могут совпадать; Docker RUN/последующие ENV ключи, конкатенация, shell expansions, продолжения строк, custom Agent и действующее окружение/переопределения требуют ручного анализа. + +**Уязвимый вариант:** + +~~~javascript +const options = {rejectUnauthorized: false}; +~~~ + +**Исправление:** Вернуть проверку сертификата, при необходимости задать доверенный CA. + +~~~javascript +const options = {rejectUnauthorized: true}; +~~~ + +**Проверка:** Корректный сертификат работает; неверный CA, чужое имя сервера и истёкший срок дают отказ. + +Тот же риск задаётся вне JavaScript через окружение процесса: + +~~~dockerfile +ENV NODE_TLS_REJECT_UNAUTHORIZED=0 +~~~ + +~~~bash +NODE_TLS_REJECT_UNAUTHORIZED=0 node server.js +~~~ + +Node.js отключает штатную проверку, когда значение переменной равно строке +`'0'`. Значения `'0.1'`, `'0-disabled'` и `'0 '` не равны этому флагу; +не использовать их как исправление — устранить настройку или явно восстановить +проверку. Сравнение `process.env.NODE_TLS_REJECT_UNAUTHORIZED === '0'` +само по себе ничего не отключает. +[Node.js: переменная окружения](https://nodejs.org/api/cli.html#node_tls_reject_unauthorizedvalue), +[точное сравнение в Node.js 22.14.0](https://github.com/nodejs/node/blob/v22.14.0/lib/internal/options.js). + +Для внутреннего CA сохранить нужное доверие через настройку CA приложения +или поддерживаемую Node.js конфигурацию. Например, при заранее установленном +PEM-файле в образе: + +~~~dockerfile +ENV NODE_TLS_REJECT_UNAUTHORIZED=1 +ENV NODE_EXTRA_CA_CERTS=/etc/service-ca.pem +~~~ + +Проверить путь, доступность и нужный состав CA; CA задаёт доверие, а не заменяет +проверку имени. Настройка `ca` у отдельного TLS-клиента и пользовательский Agent +требуют отдельного просмотра. Проверить штатный внутренний сервер и отказ +для чужого CA/имени/просроченного сертификата на фактической версии Node.js. + +У Docker поддержаны формы `ENV KEY=value` и устаревшая `ENV KEY value`. +У второй формы весь остаток — значение: `ENV NODE_TLS_REJECT_UNAUTHORIZED 0 extra` +не означает точное `'0'`. ENV образа может быть переопределён при запуске. +[Dockerfile ENV](https://docs.docker.com/reference/dockerfile/#env). + +В Dockerfile сканер проверяет только первый ключ инструкции `ENV`; +`RUN NODE_TLS_REJECT_UNAUTHORIZED=0 node server.js` и значение после другого +первого ключа `ENV` искать вручную. У shell и Dockerfile разные границы токена: +`0#suffix` и `0//suffix` входят в значение, а `0;` отделяет команду в shell, +но является значением в `ENV KEY=0;`. Кавычки вокруг точного `0` поддержаны +и в устаревшей форме `ENV KEY "0"`. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'NODE_TLS_REJECT_UNAUTHORIZED|NODE_EXTRA_CA_CERTS|rejectUnauthorized|https[.]Agent|tls[.]connect|env_file|environment:' . +~~~ + +Связать Dockerfile/build stage, Compose/манифест, startup shell и код с +окружением именно работающего процесса; проверить поздние присваивания и +параметры конкретного запроса. Regex не вычисляет подстановки, порядок запуска +и эффективное окружение, не является полным парсером shell/Dockerfile/JS. +Комментарии и строки-примеры могут давать сигнал; это требует просмотра контекста. + + + + + +## JS-HTML. HTML sink + +**Поиск:** скрипт, правило JS-HTML. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain JS-HTML. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API. + +**Уязвимый вариант:** + +~~~javascript +element.innerHTML = message; +~~~ + +**Исправление:** Для текста textContent; для необходимой разметки проверенный sanitizer с явной политикой. + +~~~javascript +element.textContent = message; +~~~ + +**Проверка:** Текст отображается; события/скрипты не исполняются. + + + + + +## JS-TRUST-PROXY. Полное доверие proxy-заголовкам + +**Поиск:** правило сканера JS-TRUST-PROXY. Подробности: `--explain JS-TRUST-PROXY`. Regex исключает комментарии/строки: .set('trust proxy', true). Тип receiver не определяется; true бывает допустим за proxy, который перезаписывает forwarded headers. Топология и число proxy-hops не проверяются; исследуйте прямые входы и фактический ближайший peer. + +**Уязвимый вариант:** + +~~~javascript +app.set('trust proxy', true); +~~~ + +**Исправление:** Проверить реальную цепочку proxy и доверять конкретным непосредственным узлам; не использовать клиентский X-Forwarded-* как auth. Сеть организаторов не менять. + +~~~javascript +app.set('trust proxy', isKnownProxy); // implement topology-specific peer validation +~~~ + +**Проверка:** Прямой запрос с поддельным заголовком не получает доверенную роль/IP/scheme; штатный reverse proxy работает. + + + + + +## JS-CURL-ARGV. curl из Node.js: проверить опции и URL + +**Поиск:** скрипт, правило JS-CURL-ARGV. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain JS-CURL-ARGV. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API. + +**Уязвимый вариант:** + +~~~javascript +spawn('/usr/bin/curl', [url, '-o', filename]); +~~~ + +**Исправление:** Отдельные argv не мешают option injection. Предпочесть HTTP-библиотеку с политикой URL/redirect и лимитами; если curl нужен, жёсткие опции/протоколы, -- перед проверенным URL, серверный output. + +~~~javascript +downloadValidatedHttpResource(url, destination); // bounded HTTP client, checked redirects/DNS and server-chosen output +~~~ + +**Проверка:** URL с ведущим дефисом, другие схемы, redirects и чужой output не принимаются; штатная загрузка работает. + +**Вариант A/D:** Отдельные argv не защищают от опций самой программы. **ECSC / duogesto, автор.** curl интерпретировал клиентское значение как опцию. +**Патч:** ограниченный HTTP-клиент либо фиксированные опции, --, допустимые +схемы/redirect и серверный output. **Тест:** ведущий дефис, иной протокол, +чужой путь и штатный URL. **Поиск:** JS-CURL-ARGV; shell:false недостаточно. + +[исходник/разбор 1](https://github.com/ECSC2024/ECSC2024-CTF-AD/blob/2a92e17384ad228072a84fb076a35066fe2ffeff/sources/duogesto/README.md); [исходник/разбор 2](https://github.com/ECSC2024/ECSC2024-CTF-AD/blob/2a92e17384ad228072a84fb076a35066fe2ffeff/sources/duogesto/backend/app.mjs). + + + + + +## JS-SESSION-STATE. Изменение чувствительного состояния сессии + +**Поиск:** скрипт, правило JS-SESSION-STATE. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain JS-SESSION-STATE. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API. + +**Уязвимый вариант:** + +~~~javascript +const user = req.body; +req.session.user = user; +~~~ + +**Исправление:** Формировать session DTO из сохранённого проверенного объекта; author/question/commitment связать одной серверной записью. Не хранить клиентские поля привилегий. + +~~~javascript +req.session.user = {id: savedUser.id, friends: savedUser.friends}; // server-validated fields only +~~~ + +**Проверка:** Лишние friends/role во входе и другой порядок endpoint не меняют права; корректное присваивание тоже даёт сигнал. + +**Вариант A/D:** Несвязанные endpoint перезаписывают контекст операции. **ECSC / duogesto, автор.** Автор текущего задания менялся другим запросом, +а завершение использовало старый ответ с новым автором. +**Патч:** хранить challenge ID, автора и состояние вместе; проверять связь +при завершении. **Тест:** перестановки запросов и несколько вкладок. +**Поиск:** JS-SESSION-STATE, семантика вручную. + +[исходник/разбор 1](https://github.com/ECSC2024/ECSC2024-CTF-AD/blob/2a92e17384ad228072a84fb076a35066fe2ffeff/sources/duogesto/README.md); [исходник/разбор 2](https://github.com/ECSC2024/ECSC2024-CTF-AD/blob/2a92e17384ad228072a84fb076a35066fe2ffeff/sources/duogesto/backend/app.mjs). + +**Вариант A/D:** В БД безопасный объект, в сессии — исходный request body. **ECSC / duogesto, автор.** Инициализация session сохраняла клиентские friends. +**Патч:** явный session DTO из проверенного сохранённого пользователя; +не копировать пароль/лишние поля. +**Тест:** регистрация с role/friends не даёт привилегий, обычный login работает. +**Поиск:** JS-SESSION-STATE; отсутствие taint-анализа учитывать. + +[исходник/разбор 1](https://github.com/ECSC2024/ECSC2024-CTF-AD/blob/2a92e17384ad228072a84fb076a35066fe2ffeff/sources/duogesto/README.md); [исходник/разбор 2](https://github.com/ECSC2024/ECSC2024-CTF-AD/blob/2a92e17384ad228072a84fb076a35066fe2ffeff/sources/duogesto/backend/app.mjs). + + + + + +## JS-VM. node:vm используется как security sandbox + +**Поиск:** скрипт, правило JS-VM. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain JS-VM. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API. + +**Уязвимый вариант:** + +~~~javascript +vm.runInNewContext(userCode, context); +~~~ + +**Исправление:** node:vm не граница безопасности для чужого кода. Если нужен калькулятор — ограниченная грамматика; выполнение программ требует отдельно спроектированной изоляции. + +~~~javascript +evaluateAllowedExpression(parsedInput); // implement a restricted grammar +~~~ + +**Проверка:** Недопустимые конструкции отвергаются, штатные выражения работают; лимиты времени и памяти проверены. + +**Основание:** [первичный материал](https://nodejs.org/api/vm.html). + + + + + +## JS-REGEX-DYNAMIC. Regex создаётся из клиентского текста + +**Поиск:** скрипт, правило JS-REGEX-DYNAMIC. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain JS-REGEX-DYNAMIC. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API. + +**Уязвимый вариант:** + +~~~javascript +const re = new RegExp(input); +~~~ + +**Исправление:** Для поиска подстроки includes; если regex — функция сервиса, ограниченный движок/сложность и размер. Простое timeout Promise не прерывает синхронный regex. + +~~~javascript +const found = text.includes(input); +~~~ + +**Проверка:** Длинный почти совпадающий ввод не блокирует event loop; Unicode/регистрозависимость сохранены. + +**Основание:** [первичный материал](https://nodejs.org/en/learn/asynchronous-work/dont-block-the-event-loop). + + + + + +## JS-TYPE-ASSERTION. TypeScript as не валидирует JSON + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'as [A-Z]|JSON.parse|req.body|parseInt|Number\(' . +~~~ + +Найти переход unknown → тип; проверить реальную runtime-схему перед доступом к полям. + +**Уязвимый вариант:** + +req.body as User скрывает отсутствие проверки; parseInt принимает числовой префикс. + +**Исправление:** Schema validator или явные проверки типов/диапазона/полей; strict full-string numeric parsing, серверные ID отдельно. + +**Проверка:** Массив/null/объект вместо строки, хвост числа, NaN/Infinity и unsafe integer отклоняются. + + + + + +## JS-AWAIT-AUTH. Забытый await у проверки прав + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'authorize|isAllowed|verifyToken|Promise|async' . +~~~ + +Для каждого if с auth-helper сверить возвращаемый тип; Promise truthy вне зависимости от результата. + +**Уязвимый вариант:** + +if (isAllowed(user, note)) при async isAllowed пропускает запрос до решения. + +**Исправление:** await перед проверкой, явный отказ при исключении; не продолжать response после rejected Promise. + +**Проверка:** Асинхронные true/false/error и задержка: закрытый объект не читается до завершения проверки. + + + + + +## JS-WEBSOCKET. WebSocket: права только на handshake + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'WebSocket|upgrade|on\(.message|subscribe|room|channel' . +~~~ + +Сопоставить handshake, каждое message/action, room join и broadcast; проверить Origin отдельно от cookie. + +**Уязвимый вариант:** + +После входа клиент выбирает чужой room или сохраняет доступ после смены прав. + +**Исправление:** Проверять субъект и ресурс каждой операции/подписки, срок сессии и допустимый Origin браузера; лимиты сообщений. + +**Проверка:** Два пользователя, отзыв роли, reconnect, чужой room и обычный broadcast. + +**Основание:** [первичный материал](https://cheatsheetseries.owasp.org/cheatsheets/WebSocket_Security_Cheat_Sheet.html). + + + + + +## JS-GRAPHQL. GraphQL: resolver и batching обходят общий guard + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'resolver|resolve|GraphQL|DataLoader|context|mutation' . +~~~ + +Проверить nested resolver, node(id), loaders и mutations; scope кеша DataLoader к запросу/пользователю. + +**Уязвимый вариант:** + +Корневой query защищён, вложенный resolver читает объект по ID без owner; общий loader отдаёт чужой результат. + +**Исправление:** Resource auth в resolver/service, request-scoped loader, лимит глубины/стоимости/пакета по контракту. + +**Проверка:** Чужой node, вложенный путь, aliases/batch и обычная пагинация. + +**Основание:** [первичный материал](https://cheatsheetseries.owasp.org/cheatsheets/GraphQL_Cheat_Sheet.html). + + + + + +## JS-SESSION-FIXATION. Сессия не меняется после входа + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'session|regenerate|login|logout|sessionID' . +~~~ + +Сравнить идентификатор до/после login и связь прежнего ID с новым principal. + +**Уязвимый вариант:** + +Предварительно известная анонимная сессия после входа становится авторизованной. + +**Исправление:** Штатная регенерация session ID на переходе привилегий с переносом только разрешённых данных; logout инвалидирует серверное состояние. + +**Проверка:** Старый ID не авторизует, корзина/допустимое состояние сохраняется, concurrent login не теряет сессию. + + + + + +## JS-SSRF. fetch/axios: redirect и повторное DNS-разрешение + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'fetch\(|axios|undici|http.request|https.request' . +~~~ + +Проследить URL до фактического соединения и каждый redirect; JS-CURL-ARGV покрывает только curl-вызов. + +**Уязвимый вариант:** + +Проверен исходный hostname, но соединение или redirect выбирает иной адрес/схему. + +**Исправление:** Серверная карта назначений или policy нормализованного URL, разрешённых IP/портов и фактического соединения; лимиты ответа/времени. + +**Проверка:** Mock DNS/redirect, разрешённый внутренний адрес по контракту, timeout и oversized body. + +**Основание:** [первичный материал](https://cheatsheetseries.owasp.org/cheatsheets/Server_Side_Request_Forgery_Prevention_Cheat_Sheet.html). + + + + + +## JS-BUFFER-EXPOSURE. Неинициализированная память в Buffer + +**Поиск:** скрипт, правило JS-BUFFER-EXPOSURE. Запуск: python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain JS-BUFFER-EXPOSURE. Regex: Buffer.allocUnsafe и allocUnsafeSlow. Полная инициализация до выдачи снимает риск вручную; старый new Buffer и ошибочные длины искать отдельно. + +Дополнительный ручной поиск для непокрытых форм: + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'allocUnsafe|allocUnsafeSlow|write\(|subarray|res.end|socket.write' . +~~~ + +Сравнить allocated capacity, реально записанные байты и длину отправки. + +**Уязвимый вариант:** + +Buffer.allocUnsafe(n) отправляется целиком после частичного заполнения. + +**Исправление:** Buffer.alloc либо заполнение каждого байта; отправлять только записанную длину, обрабатывать short read. + +**Проверка:** Короткое чтение, EOF и ошибки не раскрывают байты незаписанного хвоста; штатные бинарные ответы, NUL и максимальная длина сохранены. + +**Основание:** [первичный материал](https://nodejs.org/api/buffer.html). + +**Сигнал сканера — пример до:** + +~~~javascript +const out = Buffer.allocUnsafe(size); +const n = await readInto(out); +res.end(out); +~~~ + +**Шаблон исправления:** + +~~~javascript +const out = Buffer.alloc(size); +const n = await readInto(out); +res.end(out.subarray(0, n)); +~~~ + +Первичная документация: [документация 1](https://nodejs.org/api/buffer.html#what-makes-bufferallocunsafe-and-bufferallocunsafeslow-unsafe). + + + + + +## JS-JWT-DECODE. JWT декодируется без проверки подписи + +**Поиск:** скрипт, правило JS-JWT-DECODE. Запуск: python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain JS-JWT-DECODE. Regex: привычные jwt.decode/decodeJwt/jwtDecode; дополнительно статические ESM/CommonJS aliases jsonwebtoken.decode и jose.decodeJwt. Нет анализа scope/reassignment, re-export, dynamic import или использования claims; декодирование для диагностики может быть допустимо. + +**Уязвимый вариант:** decode/decodeJwt только извлекает данные; использовать их как подтверждённую личность нельзя. + +~~~javascript +const user = jwt.decode(token); +loadNotes(user.sub); +~~~ + +**Исправление:** Проверять подпись и claims до выдачи данных. В async варианте дождаться проверки и обрабатывать ошибку до продолжения. + +~~~javascript +const claims = jwt.verify(token, key, { algorithms: ['RS256'], issuer: 'auth', audience: 'notes' }); +loadNotes(claims.sub); +~~~ + +**Проверка:** Изменённый payload, неверная подпись, чужой issuer/audience не дают доступа; штатный токен работает. + +Первичная документация: [документация 1](https://github.com/auth0/node-jsonwebtoken#jwtdecodetoken--options). + + + + + +## JS-JWT-OPTIONS. Ослабленные параметры JWT + +**Поиск:** скрипт, правило JS-JWT-OPTIONS. Запуск: python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain JS-JWT-OPTIONS. Regex: ignoreExpiration/ignoreNotBefore/allowInvalidAsymmetricKeyTypes=true; options может находиться отдельно от verify, поэтому контекст проверять вручную. + +**Уязвимый вариант:** Игнорирование времени или разрешение несовместимого ключа ослабляет проверку токена. + +~~~javascript +jwt.verify(token, key, { ignoreExpiration: true, ignoreNotBefore: true }); +~~~ + +**Исправление:** Убрать обходы проверки, закрепить алгоритм/тип ключа и контракт claims. Отсутствие exp при необходимости отклонять отдельно. + +~~~javascript +jwt.verify(token, key, { algorithms: ['RS256'], issuer: 'auth', audience: 'notes' }); +~~~ + +**Проверка:** Просроченный и ещё не действующий токен отклонены; неверные alg и key type не проходят. + +Первичная документация: [документация 1](https://github.com/auth0/node-jsonwebtoken#jwtverifytoken-secretorpublickey-options-callback). + + + + + +## JS-HTTP-PARSER. Ослабленный HTTP parser Node.js + +**Поиск:** скрипт, правило JS-HTTP-PARSER. Запуск: python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain JS-HTTP-PARSER. Regex: insecureHTTPParser:true или --insecure-http-parser. Сам по себе сигнал не подтверждает request smuggling. + +**Уязвимый вариант:** Разные правила разбора proxy/backend создают неоднозначные границы запроса. + +~~~javascript +http.createServer({ insecureHTTPParser: true }, handler); +~~~ + +**Исправление:** Использовать строгий parser на всех hop; согласовать нормализацию и framing. Проверить также NODE_OPTIONS и CLI. + +~~~javascript +http.createServer({ insecureHTTPParser: false }, handler); +~~~ + +**Проверка:** Противоречивые длины/заголовки отклоняются на первом hop; штатные keep-alive запросы не смешиваются. + +Первичная документация: [документация 1](https://nodejs.org/api/http.html#httpcreateserveroptions-requestlistener). + + + + + +## JS-STATIC-DOTFILES. Статика разрешает скрытые файлы + +**Поиск:** скрипт, правило JS-STATIC-DOTFILES. Запуск: python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain JS-STATIC-DOTFILES. Regex: dotfiles:allow. Не проверяет фактический root, middleware order, backup-файлы без точки и символические ссылки. + +**Уязвимый вариант:** Статический root со скрытыми файлами может раскрыть конфиги, историю и ключи. + +~~~javascript +app.use(express.static(root, { dotfiles: 'allow' })); +~~~ + +**Исправление:** Выделить публичный каталог, запретить dotfiles; служебные .well-known маршруты разрешать точечно без секретов. + +~~~javascript +app.use(express.static(publicDir, { dotfiles: 'deny' })); +~~~ + +**Проверка:** Публичные ассеты доступны; dotfile, резервная копия и файл за пределами root недоступны. + +Первичная документация: [документация 1](https://expressjs.com/en/4x/api.html#express.static). + + + + + +## JS-QUERY-SHAPE. Параметр меняет тип между middleware + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'req\.(query|body|params)|URLSearchParams|querystring|qs\.|Object\.assign|\.\.\.' . +~~~ + +Проверить повторные query keys, scalar/array/object, настройку query parser и порядок merge params/query/body. Сравнить поле, которое проверяли, с полем, которое реально передали в DB/auth. + +**Уязвимый вариант:** Валидатор проверяет одну строку, следующий слой берёт последнее значение/объект или body перезаписывает уже проверенный owner из params. + +**Исправление:** Один раз разобрать запрос в DTO с точными типами; отвергать дубликаты/неожиданные структуры по контракту. Не смешивать клиентские поля с установленным сервером principal. + +**Проверка:** Дубликаты, bracket notation, вложенный объект и конфликт body/query не меняют owner/фильтр; обычный запрос сохраняет прежний результат. + +Основание: [первичная документация/материал](https://expressjs.com/en/4x/api.html#req.query). Описание и рецепт адаптации составлены для этой базы. + + + + + +## JS-MIDDLEWARE-TRUST. Обработчик доверяет выполнению middleware + +**Поиск:** вручную; отдельного правила сканера нет. Этот ID обозначает раздел +каталога. Сканер не устанавливает версию Next.js, топологию маршрутизации или +наличие проверки доступа на каждом пути исполнения. + +~~~bash +rg -n --hidden -g '!node_modules/**' -g '!.git/**' -g 'middleware.*' -g 'proxy.*' -g 'next.config.*' -g '*.conf' -e 'matcher|NextResponse\.(next|rewrite|redirect)|x-middleware-subrequest|proxy_pass|proxy_set_header|standalone' . +rg -n --hidden -g '!node_modules/**' -g '!.git/**' -e 'next/server|export.*(GET|POST|PUT|PATCH|DELETE)|use server|verifySession|authorize|"next"|next@' . +~~~ + +По первому поиску составить цепочку внешний вход → proxy/adapter → Next.js → +matcher/rewrite → обработчик. По второму проследить реальную проверку сессии +и прав до чтения/изменения данных; открыть helper и lock-файл, не ограничиваться +именем функции или диапазоном package.json. Проверить также прямой доступ к +backend в обход proxy. Middleware только для локали/публичной страницы и +обработчик с собственной проверкой доступа — похожие безопасные случаи. + +**Уязвимый вариант:** В CVE-2025-29927 внешний `x-middleware-subrequest` +попадал в механизм предотвращения рекурсии Next.js и позволял пропустить +middleware. Если обработчик полагался только на него, проверка доступа +пропускалась. Postmortem подтверждает влияние на self-hosted `next start` +и `output: 'standalone'`; static export не выполняет middleware. Vercel и +рассмотренные авторами adapters Netlify/Cloudflare Workers не были затронуты +из-за другой маршрутизации. Это границы конкретного инцидента, не гарантия +безопасности любой конфигурации этих платформ. +[Разбор разработчиков](https://vercel.com/blog/postmortem-on-next-js-middleware-bypass). + +Минимальная опасная связка; `verifySession` и функции данных — helpers проекта: + +~~~javascript +// middleware.js +import { NextResponse } from 'next/server'; +import { verifySession } from './lib/auth.js'; +export async function middleware(req) { + if (!(await verifySession(req))) { + return NextResponse.redirect(new URL('/login', req.url)); + } + return NextResponse.next(); +} +export const config = { matcher: ['/api/notes/:path*'] }; +~~~ + +~~~javascript +// app/api/notes/route.js +import { listNotes } from '../../../lib/data.js'; +export async function GET(req) { + return Response.json(await listNotes()); +} +~~~ + +Исторические диапазоны advisory: `>=11.1.4 <12.3.5`, +`>=13.0.0 <13.5.9`, `>=14.0.0 <14.2.25`, `>=15.0.0 <15.2.3`. +Релизы 12.3.5, 13.5.9, 14.2.25, 15.2.3 исправляют именно этот CVE; +отдельного исправленного релиза 11.x advisory не указывает. +[GHSA-f82v-jwr5-mffw](https://github.com/vercel/next.js/security/advisories/GHSA-f82v-jwr5-mffw). + +**Исправление:** Перейти на поддерживаемую ветку с актуальными исправлениями +безопасности. Исторический минимальный релиз выше не является рекомендацией +для установки сегодня: последующее исправление утечки внутреннего заголовка +потребовало новых релизов. +[GHSA-223j-4rm8-mrmf](https://github.com/vercel/next.js/security/advisories/GHSA-223j-4rm8-mrmf), +[advisories проекта](https://github.com/vercel/next.js/security/advisories). +Upstream-патч проверяет происхождение внутреннего заголовка; regression test +сохраняет ожидаемый redirect при внешнем заголовке. +[Исправление 52a078d и тест](https://github.com/vercel/next.js/commit/52a078da3884efe6501613c7834a3d02a91676d2). + +Проверять сессию и разрешение операции в обработчике/слое доступа к данным, +включая Server Actions; middleware может сохранить ранний redirect для UX. +`verifySession` ниже должен валидировать сессию, а `listNotesForUser` — +ограничивать выборку проверенным субъектом, не значением из запроса. +[Next.js: авторизация и DAL](https://nextjs.org/docs/app/guides/authentication). + +~~~javascript +// app/api/notes/route.js +import { verifySession } from '../../../lib/auth.js'; +import { listNotesForUser } from '../../../lib/data.js'; +export async function GET(req) { + const session = await verifySession(req); + if (!session) return new Response(null, { status: 401 }); + return Response.json(await listNotesForUser(session.userId)); +} +~~~ + +Единая политика owner/tenant и альтернативные endpoints описаны в +[CFG-OBJECT-POLICY](configuration-RU.md#cfg-object-policy). + +Временная мера на **внешней** границе nginx — удалить присланный клиентом +заголовок перед передачей Next.js. Добавить в каждый применимый proxy location, +сохраняя прочие необходимые заголовки и параметры: + +~~~nginx +proxy_set_header x-middleware-subrequest ""; +~~~ + +Пустое значение исключает заголовок из upstream-запроса. Директивы +`proxy_set_header` наследуются только при отсутствии таких директив на текущем +уровне: проверить все locations и отдельные ingress, ограничить backend +доверенными входами. Это не готовая полная конфигурация proxy. +[nginx: proxy_set_header](https://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_set_header). +Не удалять внутренний заголовок без разбора на каждом межсервисном переходе: +штатный fetch из middleware использует его для предотвращения рекурсии. + +**Проверка:** В разрешённом тестовом окружении повторить проверки с внешним +заголовком и без него. Матрица должна включать: + +| Путь | Проверяемый результат | +|---|---| +| Страница, API чтения и записи, rewrite и альтернативный URL | Аноним не получает защищённые данные; разрешённая операция владельца работает; чужие данные недоступны. | +| Server Action и прямой вызов обработчика | Проверка прав выполняется независимо от страницы и middleware. | +| Каждый внешний ingress и прямой backend | Внешний внутренний заголовок не отключает защиту; backend недоступен через неразрешённый вход. | +| Внутренний fetch из middleware | Сохраняются штатные ответы/redirect; нет рекурсивного цикла. | + +Сверить cookies, сессию, response contract и нагрузку после переноса проверок: +дополнительный доступ к хранилищу и несовместимый auth helper могут нарушить +штатные операции. Здесь проверены исходники и инертные примеры для офлайн-сканера; +Next.js runtime и HTTP-проверки приложения не запускались. Нулевой отчёт сканера +не подтверждает устранение этой ручной проблемы. + + + + + +## JS-REDIRECT-INPUT. Поле запроса напрямую передаётся в Express-подобный redirect + +**Поиск:** правило сканера JS-REDIRECT-INPUT. Точный контракт детектора: `--explain JS-REDIRECT-INPUT`. Regex с лексическими исключениями комментариев и строк: res/response.redirect с прямым свойством req/request.query/body/params, возможно после литерального кода статуса. Тип получателя и поток данных не анализируются; вычисляемые ключи, aliases и предшествующая валидация требуют проверки. + +**Уязвимый вариант:** + +~~~javascript +res.redirect(req.query.next); +~~~ + +**Исправление:** Определяйте redirect по серверной таблице маршрутов или явной политике нормализованных URL. + +~~~javascript +res.redirect('/account'); +~~~ + +**Проверка:** Внешние адреса и адреса вида //host отклоняются; согласованная навигация работает. + +[Первичный источник 1](https://expressjs.com/en/4x/api.html#res.redirect) + + + + +## JS-LOG-CREDENTIALS. Credentials напрямую передаются в console + +**Поиск:** правило сканера JS-LOG-CREDENTIALS. Подробности: `--explain JS-LOG-CREDENTIALS`. Ограниченные JS-токены: console log/info/warn/error/debug/trace с прямыми чувствительными именами/свойствами, inline object/array или конкатенацией. Наблюдаемые shadows/reassignments console подавляют подсказки во всём файле. Templates, helper calls, другие loggers, динамические ключи и потоки между файлами проверяются вручную; отсутствие сигнала не доказывает очистку. + +**Уязвимый вариант:** + +~~~javascript +console.warn(req.headers.authorization); +~~~ + +**Исправление:** Логируйте категории событий и согласованные идентификаторы, а не credentials. Проверьте ошибки входа и исключения; helper очистки нужно реализовать и протестировать отдельно. + +~~~javascript +console.warn('authentication failed'); +~~~ + +**Проверка:** Синтетические canary credentials не появляются в stdout, логах, evidence и трансляции экрана; полезные категории ошибок остаются. + +[Первичный источник](https://nodejs.org/api/console.html) diff --git a/docs/vulnerabilities/javascript.md b/docs/vulnerabilities/javascript.md new file mode 100644 index 0000000..044b723 --- /dev/null +++ b/docs/vulnerabilities/javascript.md @@ -0,0 +1,869 @@ +# JavaScript / TypeScript: find, fix and verify + +English | [Русский](javascript-RU.md) + +[Catalog](README.md) · [Scanner](../offline-scanner.md) · [Patch verification](../patch-validation.md) + +28 sections. Each follows **Search → Vulnerable example → Fix → Verification**. +Run `rg` from a local service checkout; searches only read files. Derive the actor/owner from a verified session, not request data. Adapt examples to the actual API and contract. + +## Contents + +- [JS-SHELL — Shell API Node.js](#js-shell) +- [JS-EVAL — Dynamic JavaScript execution](#js-eval) +- [JS-SQL — Dynamic Node.js SQL](#js-sql) +- [JS-NOSQL — Request body used as a MongoDB filter](#js-nosql) +- [JS-MASS-ASSIGN — Mass assignment](#js-mass-assign) +- [JS-PROTOTYPE — Deep merge of an untrusted object](#js-prototype) +- [JS-TLS — Node.js TLS verification disabled](#js-tls) +- [JS-HTML — HTML sink](#js-html) +- [JS-TRUST-PROXY — Unrestricted trust in proxy headers](#js-trust-proxy) +- [JS-CURL-ARGV — Node.js curl: review URL and options](#js-curl-argv) +- [JS-SESSION-STATE — Sensitive session state assignment](#js-session-state) +- [JS-VM — node:vm used as a security sandbox](#js-vm) +- [JS-REGEX-DYNAMIC — Regex built from client text](#js-regex-dynamic) +- [JS-TYPE-ASSERTION — TypeScript as does not validate JSON](#js-type-assertion) +- [JS-AWAIT-AUTH — Missing await on authorization checks](#js-await-auth) +- [JS-WEBSOCKET — Authorization only at the WebSocket handshake](#js-websocket) +- [JS-GRAPHQL — Resolvers and batching bypass a common guard](#js-graphql) +- [JS-SESSION-FIXATION — Session ID does not change at login](#js-session-fixation) +- [JS-SSRF — fetch/axios redirects and repeated DNS resolution](#js-ssrf) +- [JS-BUFFER-EXPOSURE — Uninitialized Buffer exposure](#js-buffer-exposure) +- [JS-JWT-DECODE — JWT decoded without signature verification](#js-jwt-decode) +- [JS-JWT-OPTIONS — Weakened JWT options](#js-jwt-options) +- [JS-HTTP-PARSER — Lenient Node.js HTTP parser](#js-http-parser) +- [JS-STATIC-DOTFILES — Static server allows dotfiles](#js-static-dotfiles) +- [JS-QUERY-SHAPE — Parameters change type between middleware](#js-query-shape) +- [JS-MIDDLEWARE-TRUST — Handlers assume middleware has run](#js-middleware-trust) +- [JS-REDIRECT-INPUT — Request field passed directly to an Express-style redirect](#js-redirect-input) +- [JS-LOG-CREDENTIALS — Credential-like value passed directly to console](#js-log-credentials) + + + +## JS-SHELL. Shell API Node.js + +**Search:** scanner rule JS-SHELL. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain JS-SHELL` for details. Regex: bare exec/execSync, common child_process/cp receivers, shell:true/nonempty shell string and literal shell in spawn/execFile. Static ESM/CommonJS child_process imports support aliases and string bracket access; arbitrary object.exec is not a process call. Import hints are not scope/type/data-flow analysis: comments, shadowing and reassignment may match; review wrappers/dynamic imports. + +**Vulnerable example:** + +~~~javascript +child_process.exec(command); +~~~ + +**Fix:** Use a fixed executable and separate argv with validated options and bounded execution. + +~~~javascript +child_process.execFile('/usr/bin/file', ['--', filename], {timeout: 3000}, callback); +~~~ + +**Verification:** Metacharacters stay data; dangerous options fail; normal commands work. + +
+Expanded example and limitations + +```javascript +// Vulnerable: a shell interprets the command string. +exec("printf '%s' '" + req.body.text + "' | sha256sum", callback); +``` + +**Patch for a content hash:** + + + +```javascript +const { createHash } = require("node:crypto"); + +function digestText(text) { + if (typeof text !== "string") throw new TypeError("string required"); + return createHash("sha256").update(text, "utf8").digest("hex"); +} +``` + +For ESM use `import { createHash } from "node:crypto"`. Preserve encoding and the external result format. If an external program is genuinely needed, fix the executable and pass arguments separately; execFile does not automatically prevent dangerous program options. + +**Check:** Known digest, empty string, Unicode, quotes/newlines and no child process. SHA-256 alone is unsuitable for password storage. + +
+ + + +## JS-EVAL. Dynamic JavaScript execution + +**Search:** scanner rule JS-EVAL. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain JS-EVAL` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries. + +**Vulnerable example:** + +~~~javascript +const value = eval(input); +~~~ + +**Fix:** Parse schema-validated data or a restricted DSL instead of evaluating JavaScript. + +~~~javascript +const value = JSON.parse(input); // validate schema +~~~ + +**Verification:** Code-like input stays data; valid input works within limits. + + + +## JS-SQL. Dynamic Node.js SQL + +**Search:** scanner rule JS-SQL. Use `--explain JS-SQL` for the exact detector contract. Legacy regex with comment/string exclusions: query/execute string construction or text/sql objects (receiver untyped). Bounded tokens also detect direct req/request.body/query/params property as SQL to a default/namespace imported pg Pool/Client or mysql/mysql2 createPool/createConnection binding. Named imports, acquired connections, SQL variables, tagged templates, wrappers and cross-file flows remain manual. + +**Vulnerable example:** + +~~~javascript +db.query("SELECT id FROM notes WHERE name=" + name); +~~~ + +**Fix:** Use driver-supported bind parameters and allowlist identifiers. + +~~~javascript +db.query("SELECT id FROM notes WHERE name=?", [name]); +~~~ + +**Verification:** Quotes do not alter query structure; ownership restrictions remain. + +
+Expanded example and limitations + +```javascript +// Vulnerable: client input controls the query and ownership is unchecked. +const result = await pool.query(`SELECT body FROM notes WHERE id = '${req.params.id}'`); +``` + +**node-postgres (pg) patch for private notes:** + + + +```javascript +async function readPrivateNote(pool, currentUserId, noteId) { + if (currentUserId == null) throw new Error("authentication required"); + const result = await pool.query( + "SELECT body FROM notes WHERE id = $1 AND owner_id = $2", + [noteId, currentUserId] + ); + if (result.rows.length === 0) return null; + return result.rows[0].body; +} +``` + +`null` means no accessible object; the route maps it to the API's normal response. Select column names/sorting direction from a fixed map, not request text. $1 placeholders are PostgreSQL-specific, not universal across JavaScript drivers. + +**Check:** Owners can read, foreign records are absent, apostrophes remain data, wrong types do not change query meaning, and denied responses contain no foreign note body. + +
+ + + +## JS-NOSQL. Request body used as a MongoDB filter + +**Search:** scanner rule JS-NOSQL. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain JS-NOSQL` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries. + +**Vulnerable example:** + +~~~javascript +collection.findOne(req.body); +~~~ + +**Fix:** Validate field types and build a server-owned filter with ownership constraints. + +~~~javascript +if (typeof req.body.name !== 'string') throw new Error('invalid'); +collection.findOne({name: req.body.name, ownerId: currentUser.id}); +~~~ + +**Verification:** Operator objects and unknown fields cannot widen the query; normal lookups work. + +
+Expanded example and limitations + +```javascript +// Vulnerable: title may be an operator object rather than a string. +const note = await notes.findOne({ ownerId: currentUserId, title: req.body.title }); +``` + +**Patch:** Validate types and build the filter yourself. The example assumes ownerId already has the expected identifier type from trusted context. + + + +```javascript +function privateTitleFilter(currentUserId, body) { + if (currentUserId == null) throw new Error("authentication required"); + if (body === null || typeof body !== "object" || Array.isArray(body)) { + throw new TypeError("object required"); + } + if (!Object.prototype.hasOwnProperty.call(body, "title") || typeof body.title !== "string") { + throw new TypeError("title must be a string"); + } + return { ownerId: currentUserId, title: body.title }; +} +// In the handler: await notes.findOne(privateTitleFilter(currentUserId, req.body)); +``` + +Do not fix this with String(req.body.title): objects become meaningless strings and the contract changes. Never spread the rest of req.body into the filter or mix it with server-side ownership predicates. + +**Check:** Strings, Unicode and permitted empty titles work; objects, arrays and null titles fail **before database access**. A supplied ownerId never changes the filter. + +
+ + + +## JS-MASS-ASSIGN. Mass assignment + +**Search:** scanner rule JS-MASS-ASSIGN. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain JS-MASS-ASSIGN` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries. + +**Vulnerable example:** + +~~~javascript +Object.assign(user, req.body); +~~~ + +**Fix:** Allowlist editable fields; derive owner, role and privileges on the server. + +~~~javascript +user.displayName = validateName(req.body.displayName); +~~~ + +**Verification:** Additional/nested privilege fields fail or are ignored; normal edits work. + +
+Expanded example and limitations + +```javascript +// Vulnerable: clients can write ownerId/role and other administrative fields. +Object.assign(note, req.body); +``` + +**Patch for editing title and body:** + + + +```javascript +function editableNoteFields(body) { + if (body === null || typeof body !== "object" || Array.isArray(body)) { + throw new TypeError("object required"); + } + const result = {}; + for (const key of Object.keys(body)) { + if (key !== "title" && key !== "body") throw new TypeError("unknown field"); + if (typeof body[key] !== "string") throw new TypeError("string required"); + result[key] = body[key]; + } + return result; +} +// After authorization: update only editableNoteFields(req.body). +``` + +A field allowlist does not authorize the record. Do not remove one key then deep-merge the rest: nested paths remain dangerous. Client JSON containing __proto__ must not enter arbitrary merging. + +**Check:** Partial title updates and permitted empty bodies work; ownerId, role, unknown fields and nested objects fail; the original object is not mutated. + +
+ + + +## JS-PROTOTYPE. Deep merge of an untrusted object + +**Search:** scanner rule JS-PROTOTYPE. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain JS-PROTOTYPE` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries. + +**Vulnerable example:** + +~~~javascript +merge(settings, req.body); +~~~ + +**Fix:** Copy only schema-approved fields and reject prototype-related keys at every level. + +~~~javascript +settings.theme = validateTheme(req.body.theme); +~~~ + +**Verification:** Nested prototype keys cannot affect unrelated objects; supported settings apply. + + + +## JS-TLS. Node.js TLS verification disabled + +**Search:** scanner rule JS-TLS. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain JS-TLS` for details. Regex: rejectUnauthorized:false/assignment only in JavaScript/config; NODE_TLS_REJECT_UNAUTHORIZED with exact 0 or paired quotes. Shell KEY=0 ends at whitespace, shell separators or end. Docker covers first ENV KEY=0 or whole-value ENV KEY 0, including paired quotes. 0.1, 0-disabled and quoted whitespace do not match; # or // suffix belongs to the shell/Docker value and semicolon belongs to Docker ENV. Comments/strings may match. Review Docker RUN/later ENV keys, concatenation, expansions, continuations, custom Agent and effective overrides. + +**Vulnerable example:** + +~~~javascript +const options = {rejectUnauthorized: false}; +~~~ + +**Fix:** Enable peer/hostname checks and configure the trusted CA instead of disabling validation globally. + +~~~javascript +const options = {rejectUnauthorized: true}; +~~~ + +**Verification:** Valid certificates work; wrong CA/hostname and expiry fail. + +The same risk can be configured outside JavaScript through process environment: + +~~~dockerfile +ENV NODE_TLS_REJECT_UNAUTHORIZED=0 +~~~ + +~~~bash +NODE_TLS_REJECT_UNAUTHORIZED=0 node server.js +~~~ + +Node.js disables normal validation only when the variable is exactly the string '0'. '0.1', '0-disabled' and '0 ' are not that flag; do not use these as fixes—remove the setting or explicitly restore validation. Merely comparing process.env.NODE_TLS_REJECT_UNAUTHORIZED === '0' disables nothing. [Node.js environment variable](https://nodejs.org/api/cli.html#node_tls_reject_unauthorizedvalue), [exact comparison in Node.js 22.14.0](https://github.com/nodejs/node/blob/v22.14.0/lib/internal/options.js). + +For an internal CA retain the required trust through application CA settings or supported Node.js configuration. For example, with a preinstalled PEM file in the image: + +~~~dockerfile +ENV NODE_TLS_REJECT_UNAUTHORIZED=1 +ENV NODE_EXTRA_CA_CERTS=/etc/service-ca.pem +~~~ + +Check the file's path, availability and CA contents. CA trust does not replace hostname validation. Per-client ca settings and custom Agents need separate review. Test the actual Node.js version against the normal internal server and reject wrong CAs, wrong names and expired certificates. + +Docker supports ENV KEY=value and legacy ENV KEY value. In the latter, the entire remainder is the value: ENV NODE_TLS_REJECT_UNAUTHORIZED 0 extra is not exactly '0'. Runtime configuration can override image ENV. [Dockerfile ENV](https://docs.docker.com/reference/dockerfile/#env). + +In Dockerfiles the scanner checks only the first ENV key. Manually search RUN NODE_TLS_REJECT_UNAUTHORIZED=0 node server.js and settings after another first key. Shell/Dockerfile token boundaries differ: 0#suffix and 0//suffix belong to the value; 0; separates shell commands but remains the value in ENV KEY=0;. Quotes around exact 0 are supported, including legacy ENV KEY "0". + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'NODE_TLS_REJECT_UNAUTHORIZED|NODE_EXTRA_CA_CERTS|rejectUnauthorized|https[.]Agent|tls[.]connect|env_file|environment:' . +~~~ + +Connect Dockerfiles/build stages, Compose/manifests, startup shell and code to the environment of the actual running process. Review later assignments and per-request parameters. Regex does not evaluate substitutions, startup order or effective environment and is not a complete shell/Dockerfile/JavaScript parser. Comments/examples can signal and need context review. + + + +## JS-HTML. HTML sink + +**Search:** scanner rule JS-HTML. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain JS-HTML` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries. + +**Vulnerable example:** + +~~~javascript +element.innerHTML = message; +~~~ + +**Fix:** Use textContent for text or a reviewed context-appropriate sanitizer for supported rich HTML. + +~~~javascript +element.textContent = message; +~~~ + +**Verification:** User markup cannot execute; intended presentation remains usable. + + + +## JS-TRUST-PROXY. Unrestricted trust in proxy headers + +**Search:** scanner rule JS-TRUST-PROXY. Use `--explain JS-TRUST-PROXY` for the exact detector contract. Regex with comment/string exclusions: .set('trust proxy', true). Receiver untyped; true may be valid behind proxies that overwrite forwarded headers. No effective topology or proxy-hop verification; inspect all direct entrypoints and the immediate peer. + +**Vulnerable example:** + +~~~javascript +app.set('trust proxy', true); +~~~ + +**Fix:** Trust actual immediate proxies, not client X-Forwarded-* as authentication; do not change organizer networking. + +~~~javascript +app.set('trust proxy', isKnownProxy); // implement topology-specific peer validation +~~~ + +**Verification:** Spoofed direct headers grant no trusted identity/IP/scheme; proxy works. + + + +## JS-CURL-ARGV. Node.js curl: review URL and options + +**Search:** scanner rule JS-CURL-ARGV. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain JS-CURL-ARGV` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries. + +**Vulnerable example:** + +~~~javascript +spawn('/usr/bin/curl', [url, '-o', filename]); +~~~ + +**Fix:** Separate argv does not prevent option injection. Prefer bounded HTTP APIs; otherwise fix curl options/protocols, use -- before validated URL and choose server-side output. + +~~~javascript +downloadValidatedHttpResource(url, destination); // bounded HTTP client, checked redirects/DNS and server-chosen output +~~~ + +**Verification:** Leading-dash URLs, forbidden schemes/redirects and output paths fail; normal downloads work. + +**A/D variant:** Separate argv do not protect against program options. **ECSC / duogesto, author write-up.** curl interpreted client text as an option. **Patch:** A constrained HTTP client or fixed options, --, permitted schemes/redirects and server-selected output. **Test:** Leading dashes, other protocols, foreign paths and normal URLs. **Search:** JS-CURL-ARGV; shell:false is insufficient. + +[source/write-up 1](https://github.com/ECSC2024/ECSC2024-CTF-AD/blob/2a92e17384ad228072a84fb076a35066fe2ffeff/sources/duogesto/README.md); [source/write-up 2](https://github.com/ECSC2024/ECSC2024-CTF-AD/blob/2a92e17384ad228072a84fb076a35066fe2ffeff/sources/duogesto/backend/app.mjs). + + + +## JS-SESSION-STATE. Sensitive session state assignment + +**Search:** scanner rule JS-SESSION-STATE. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain JS-SESSION-STATE` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries. + +**Vulnerable example:** + +~~~javascript +const user = req.body; +req.session.user = user; +~~~ + +**Fix:** Build session DTOs from persisted validated records; bind related state server-side and reject client privilege fields. + +~~~javascript +req.session.user = {id: savedUser.id, friends: savedUser.friends}; // server-validated fields only +~~~ + +**Verification:** Extra role/friends fields or endpoint reordering cannot change access; correct assignments may still match. + +**A/D variant:** Unrelated endpoints overwrite operation context. **ECSC / duogesto, author write-up.** Another request changed the current task's author; completion combined an old answer with the new author. **Patch:** Store challenge ID, author and state together and verify their binding at completion. **Test:** Reordered requests and multiple tabs. **Search:** JS-SESSION-STATE; review semantics manually. + +[source/write-up 1](https://github.com/ECSC2024/ECSC2024-CTF-AD/blob/2a92e17384ad228072a84fb076a35066fe2ffeff/sources/duogesto/README.md); [source/write-up 2](https://github.com/ECSC2024/ECSC2024-CTF-AD/blob/2a92e17384ad228072a84fb076a35066fe2ffeff/sources/duogesto/backend/app.mjs). + +**A/D variant:** Safe database object, original request body in the session. **ECSC / duogesto, author write-up.** Session initialization retained client-supplied friends. **Patch:** Explicit session DTO from the verified persisted user; do not copy passwords or extra fields. **Test:** Registration with role/friends grants no privileges; ordinary login works. **Search:** JS-SESSION-STATE; account for the lack of taint analysis. + +[source/write-up 1](https://github.com/ECSC2024/ECSC2024-CTF-AD/blob/2a92e17384ad228072a84fb076a35066fe2ffeff/sources/duogesto/README.md); [source/write-up 2](https://github.com/ECSC2024/ECSC2024-CTF-AD/blob/2a92e17384ad228072a84fb076a35066fe2ffeff/sources/duogesto/backend/app.mjs). + + + +## JS-VM. node:vm used as a security sandbox + +**Search:** scanner rule JS-VM. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain JS-VM` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries. + +**Vulnerable example:** + +~~~javascript +vm.runInNewContext(userCode, context); +~~~ + +**Fix:** node:vm is not a security boundary for untrusted code. Use a restricted grammar or a separately designed execution isolation system. + +~~~javascript +evaluateAllowedExpression(parsedInput); // implement a restricted grammar +~~~ + +**Verification:** Disallowed syntax fails; supported expressions work under time/memory limits. + +**Reference:** [primary source](https://nodejs.org/api/vm.html). + + + +## JS-REGEX-DYNAMIC. Regex built from client text + +**Search:** scanner rule JS-REGEX-DYNAMIC. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain JS-REGEX-DYNAMIC` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries. + +**Vulnerable example:** + +~~~javascript +const re = new RegExp(input); +~~~ + +**Fix:** Use includes for literal search; bound regex grammar/complexity and input when regex is a feature. A Promise timeout cannot interrupt synchronous regex execution. + +~~~javascript +const found = text.includes(input); +~~~ + +**Verification:** Long near-matches cannot block the event loop; Unicode/case semantics remain compatible. + +**Reference:** [primary source](https://nodejs.org/en/learn/asynchronous-work/dont-block-the-event-loop). + + + +## JS-TYPE-ASSERTION. TypeScript as does not validate JSON + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'as [A-Z]|JSON.parse|req.body|parseInt|Number\(' . +~~~ + +Find unknown-to-type transitions; verify a real runtime schema before field access. + +**Vulnerable example:** + +`req.body as User` hides missing validation; parseInt accepts a numeric prefix. + +**Fix:** A schema validator or explicit type/range/field checks, strict whole-string number parsing and separate server-derived IDs. + +**Verification:** Arrays/null/objects replacing strings, numeric suffixes, NaN/Infinity and unsafe integers fail. + + + +## JS-AWAIT-AUTH. Missing await on authorization checks + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'authorize|isAllowed|verifyToken|Promise|async' . +~~~ + +Check the return type of every authorization helper used in an if; Promise objects are truthy regardless of eventual result. + +**Vulnerable example:** + +`if (isAllowed(user, note))` with async isAllowed permits execution before the decision. + +**Fix:** Await the check and explicitly deny exceptions; do not continue response handling after rejected Promises. + +**Verification:** Async true/false/error and delay cases; private data is never read before verification completes. + + + +## JS-WEBSOCKET. Authorization only at the WebSocket handshake + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'WebSocket|upgrade|on\(.message|subscribe|room|channel' . +~~~ + +Compare handshake, every message/action, room joins and broadcasts; validate Origin separately from cookies. + +**Vulnerable example:** + +After login the client selects a foreign room or retains access after its privileges change. + +**Fix:** Authenticate/authorize every operation and subscription, enforce session lifetime and permitted browser Origins, and bound messages. + +**Verification:** Two users, role revocation, reconnect, foreign rooms and legitimate broadcast. + +**Reference:** [primary source](https://cheatsheetseries.owasp.org/cheatsheets/WebSocket_Security_Cheat_Sheet.html). + + + +## JS-GRAPHQL. Resolvers and batching bypass a common guard + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'resolver|resolve|GraphQL|DataLoader|context|mutation' . +~~~ + +Inspect nested resolvers, node(id), loaders and mutations; DataLoader caches must be request/user-scoped. + +**Vulnerable example:** + +The root query is protected, but a nested resolver loads by ID without owner checks, or a shared loader returns another user's cached result. + +**Fix:** Resource authorization in resolvers/services, request-scoped loaders and contractual depth/cost/batch limits. + +**Verification:** Foreign nodes, nested paths, aliases/batching and normal pagination. + +**Reference:** [primary source](https://cheatsheetseries.owasp.org/cheatsheets/GraphQL_Cheat_Sheet.html). + + + +## JS-SESSION-FIXATION. Session ID does not change at login + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'session|regenerate|login|logout|sessionID' . +~~~ + +Compare identifiers before/after login and the old ID's association with the new principal. + +**Vulnerable example:** + +A previously known anonymous session becomes authenticated. + +**Fix:** Supported session-ID regeneration at privilege transitions, transferring only allowed state; logout invalidates server state. + +**Verification:** Old IDs cannot authorize, shopping cart/permitted state survives and concurrent login does not lose sessions. + + + +## JS-SSRF. fetch/axios redirects and repeated DNS resolution + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'fetch\(|axios|undici|http.request|https.request' . +~~~ + +Trace URLs to actual connections and every redirect; JS-CURL-ARGV covers only curl calls. + +**Vulnerable example:** + +The initial hostname is checked but connection/redirect behavior selects another address or scheme. + +**Fix:** Server-defined destinations or policy covering normalized URLs, allowed IPs/ports and actual connections; bound response size/time. + +**Verification:** Mock DNS/redirects, contractually allowed internal addresses, timeouts and oversized bodies. + +**Reference:** [primary source](https://cheatsheetseries.owasp.org/cheatsheets/Server_Side_Request_Forgery_Prevention_Cheat_Sheet.html). + + + +## JS-BUFFER-EXPOSURE. Uninitialized Buffer exposure + +**Search:** scanner rule JS-BUFFER-EXPOSURE. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain JS-BUFFER-EXPOSURE` for details. Regex: Buffer.allocUnsafe/allocUnsafeSlow. Full initialization before disclosure may remove risk on review; inspect legacy new Buffer and incorrect lengths separately. + +Additional manual search for forms outside automatic coverage: + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'allocUnsafe|allocUnsafeSlow|write\(|subarray|res.end|socket.write' . +~~~ + +Compare allocation capacity, bytes actually initialized and transmitted length. + +**Vulnerable example:** + +`Buffer.allocUnsafe(n)` is transmitted whole after only partial initialization. + +**Fix:** Initialize memory, emit only the written range and validate size/read results. + +**Verification:** Short read, EOF and errors disclose no tail bytes; valid binary responses work. + +**Reference:** [primary source](https://nodejs.org/api/buffer.html). + +**Scanner example before:** + +~~~javascript +const out = Buffer.allocUnsafe(size); +const n = await readInto(out); +res.end(out); +~~~ + +**Fix template:** + +~~~javascript +const out = Buffer.alloc(size); +const n = await readInto(out); +res.end(out.subarray(0, n)); +~~~ + +Primary documentation: [reference 1](https://nodejs.org/api/buffer.html#what-makes-bufferallocunsafe-and-bufferallocunsafeslow-unsafe). + + + +## JS-JWT-DECODE. JWT decoded without signature verification + +**Search:** scanner rule JS-JWT-DECODE. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain JS-JWT-DECODE` for details. Regex: common jwt.decode/decodeJwt/jwtDecode and static ESM/CommonJS aliases for jsonwebtoken.decode/jose.decodeJwt. No scope/reassignment, re-export, dynamic import or claims-use analysis. Diagnostic decoding may be legitimate. + +**Vulnerable example:** decode/decodeJwt extracts data without verification; it cannot establish an authenticated identity. + +~~~javascript +const user = jwt.decode(token); +loadNotes(user.sub); +~~~ + +**Fix:** Verify signature and claims before access; await asynchronous verification and reject errors before proceeding. + +~~~javascript +const claims = jwt.verify(token, key, { algorithms: ['RS256'], issuer: 'auth', audience: 'notes' }); +loadNotes(claims.sub); +~~~ + +**Verification:** Modified payload, invalid signature and wrong issuer/audience grant no access. + +Primary documentation: [reference 1](https://github.com/auth0/node-jsonwebtoken#jwtdecodetoken--options). + + + +## JS-JWT-OPTIONS. Weakened JWT options + +**Search:** scanner rule JS-JWT-OPTIONS. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain JS-JWT-OPTIONS` for details. Regex: ignoreExpiration/ignoreNotBefore/allowInvalidAsymmetricKeyTypes=true. Options may be separate from verify; inspect actual use. + +**Vulnerable example:** Ignoring time constraints or accepting incompatible keys weakens token verification. + +~~~javascript +jwt.verify(token, key, { ignoreExpiration: true, ignoreNotBefore: true }); +~~~ + +**Fix:** Remove verification bypasses and fix algorithm/key/claims policy; require exp separately where needed. + +~~~javascript +jwt.verify(token, key, { algorithms: ['RS256'], issuer: 'auth', audience: 'notes' }); +~~~ + +**Verification:** Expired/premature tokens and wrong algorithms/key types fail. + +Primary documentation: [reference 1](https://github.com/auth0/node-jsonwebtoken#jwtverifytoken-secretorpublickey-options-callback). + + + +## JS-HTTP-PARSER. Lenient Node.js HTTP parser + +**Search:** scanner rule JS-HTTP-PARSER. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain JS-HTTP-PARSER` for details. Regex: insecureHTTPParser:true or --insecure-http-parser. This alone does not prove request smuggling. + +**Vulnerable example:** Different proxy/backend parsing rules create ambiguous request boundaries. + +~~~javascript +http.createServer({ insecureHTTPParser: true }, handler); +~~~ + +**Fix:** Use strict parsers on every hop and align framing/normalization; check NODE_OPTIONS and CLI flags. + +~~~javascript +http.createServer({ insecureHTTPParser: false }, handler); +~~~ + +**Verification:** Conflicting framing fails at the first hop; valid keep-alive requests stay separate. + +Primary documentation: [reference 1](https://nodejs.org/api/http.html#httpcreateserveroptions-requestlistener). + + + +## JS-STATIC-DOTFILES. Static server allows dotfiles + +**Search:** scanner rule JS-STATIC-DOTFILES. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain JS-STATIC-DOTFILES` for details. Regex: dotfiles:allow. Does not check actual root, middleware order, non-dot backups or symlinks. + +**Vulnerable example:** A static root allowing dotfiles can expose configuration, history and keys. + +~~~javascript +app.use(express.static(root, { dotfiles: 'allow' })); +~~~ + +**Fix:** Use a dedicated public root and deny dotfiles; allow required .well-known resources narrowly without secrets. + +~~~javascript +app.use(express.static(publicDir, { dotfiles: 'deny' })); +~~~ + +**Verification:** Assets work; dotfiles, backups and files outside the root are unavailable. + +Primary documentation: [reference 1](https://expressjs.com/en/4x/api.html#express.static). + + + +## JS-QUERY-SHAPE. Parameters change type between middleware + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'req\.(query|body|params)|URLSearchParams|querystring|qs\.|Object\.assign|\.\.\.' . +~~~ + +Review repeated query keys, scalar/array/object forms, parser settings and params/query/body merge order. Compare the checked field with the value actually passed to database/authentication code. + +**Vulnerable example:** A validator checks one string, the next layer selects the last value/object, or body overwrites an already verified params owner. + +**Fix:** Parse once into a precisely typed DTO; reject duplicates/unexpected structures according to contract. Never merge client fields into server-established principal context. + +**Verification:** Duplicates, bracket notation, nested objects and body/query conflicts cannot change owner/filter; ordinary requests retain their results. + +Reference: [primary documentation](https://expressjs.com/en/4x/api.html#req.query). The explanation and adaptation recipe were written for this catalog. + + + +## JS-MIDDLEWARE-TRUST. Handlers assume middleware has run + +**Search:** manual review; no separate scanner rule. This ID identifies a catalog section. The scanner does not establish Next.js version, routing topology or authorization on every execution path. + +~~~bash +rg -n --hidden -g '!node_modules/**' -g '!.git/**' -g 'middleware.*' -g 'proxy.*' -g 'next.config.*' -g '*.conf' -e 'matcher|NextResponse\.(next|rewrite|redirect)|x-middleware-subrequest|proxy_pass|proxy_set_header|standalone' . +rg -n --hidden -g '!node_modules/**' -g '!.git/**' -e 'next/server|export.*(GET|POST|PUT|PATCH|DELETE)|use server|verifySession|authorize|"next"|next@' . +~~~ + +Use the first search to map external entry → proxy/adapter → Next.js → matcher/rewrite → handler. Use the second to trace actual session/permission validation before reads/writes; inspect helper implementations and lockfiles, not only function names or package.json ranges. Test direct backend access bypassing the proxy. Locale/public-page middleware and handlers with independent authorization are similar-looking safe cases. + +**Vulnerable example:** In CVE-2025-29927, an external x-middleware-subrequest reached Next.js recursion prevention and bypassed middleware. Handlers relying exclusively on middleware lost authorization. The postmortem confirms self-hosted next start and output: 'standalone' were affected; static export does not execute middleware. Vercel and the examined Netlify/Cloudflare Workers adapters were unaffected because of different routing. These are boundaries of that incident, not a guarantee for every platform configuration. [Developer postmortem](https://vercel.com/blog/postmortem-on-next-js-middleware-bypass). + +Minimal vulnerable arrangement; verifySession and data functions are project helpers: + +~~~javascript +// middleware.js +import { NextResponse } from 'next/server'; +import { verifySession } from './lib/auth.js'; +export async function middleware(req) { + if (!(await verifySession(req))) { + return NextResponse.redirect(new URL('/login', req.url)); + } + return NextResponse.next(); +} +export const config = { matcher: ['/api/notes/:path*'] }; +~~~ + +~~~javascript +// app/api/notes/route.js +import { listNotes } from '../../../lib/data.js'; +export async function GET(req) { + return Response.json(await listNotes()); +} +~~~ + +Historical advisory ranges: >=11.1.4 <12.3.5, >=13.0.0 <13.5.9, >=14.0.0 <14.2.25, >=15.0.0 <15.2.3. Versions 12.3.5, 13.5.9, 14.2.25 and 15.2.3 fix this specific CVE; the advisory lists no fixed 11.x release. [GHSA-f82v-jwr5-mffw](https://github.com/vercel/next.js/security/advisories/GHSA-f82v-jwr5-mffw). + +**Fix:** Use a supported branch with current security updates. The historical minimum versions above are not present-day installation recommendations: a subsequent internal-header leakage fix required newer releases. [GHSA-223j-4rm8-mrmf](https://github.com/vercel/next.js/security/advisories/GHSA-223j-4rm8-mrmf), [project advisories](https://github.com/vercel/next.js/security/advisories). The upstream patch validates the internal header's origin; its regression test preserves the expected redirect when the header arrives externally. [Fix 52a078d and test](https://github.com/vercel/next.js/commit/52a078da3884efe6501613c7834a3d02a91676d2). + +Validate sessions and operation permissions in handlers/data access, including Server Actions; middleware may retain early redirects for user experience. verifySession below must verify the session, while listNotesForUser must scope queries to that verified actor, not a request value. [Next.js authorization and DAL](https://nextjs.org/docs/app/guides/authentication). + +~~~javascript +// app/api/notes/route.js +import { verifySession } from '../../../lib/auth.js'; +import { listNotesForUser } from '../../../lib/data.js'; +export async function GET(req) { + const session = await verifySession(req); + if (!session) return new Response(null, { status: 401 }); + return Response.json(await listNotesForUser(session.userId)); +} +~~~ + +Unified owner/tenant policy and alternative endpoints are covered by [CFG-OBJECT-POLICY](configuration.md#cfg-object-policy). + +A temporary mitigation at the **external** nginx boundary removes client-supplied headers before forwarding to Next.js. Add it to each relevant proxy location while preserving other required headers/settings: + +~~~nginx +proxy_set_header x-middleware-subrequest ""; +~~~ + +An empty value omits the header from upstream requests. proxy_set_header directives inherit only when none are defined at the current level: inspect every location and ingress and restrict the backend to trusted entrypoints. This is not a complete proxy configuration. [nginx proxy_set_header](https://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_set_header). Do not indiscriminately remove internal headers on every inter-service hop: legitimate middleware fetch uses them to prevent recursion. + +**Verification:** In an authorized environment, repeat tests with and without the externally supplied header. Include: + +| Path | Expected result | +|---|---| +| Page, read/write API, rewrite and alternative URL | Anonymous callers receive no private data; owner operations work; foreign data remains inaccessible. | +| Server Action and direct handler call | Authorization runs independently of the page and middleware. | +| Every external ingress and direct backend | Externally supplied internal headers never disable protection; unauthorized backend entry is unavailable. | +| Internal middleware fetch | Expected responses/redirects work without recursive loops. | + +Recheck cookies, sessions, response contracts and load after moving authorization: extra storage access and incompatible helpers can break normal operations. This catalog review checked sources and inert scanner examples; it did not execute Next.js or application HTTP tests. A clean scanner report does not prove this manual issue fixed. + + + +## JS-REDIRECT-INPUT. Request field passed directly to an Express-style redirect + +**Search:** scanner rule JS-REDIRECT-INPUT. Use `--explain JS-REDIRECT-INPUT` for the exact detector contract. Regex with lexical comment/string exclusions: res/response.redirect with direct req/request.query/body/params property, optionally following a literal status code. Not receiver typing or data-flow analysis; computed keys, aliases and upstream validation need review. + +**Vulnerable example:** + +~~~javascript +res.redirect(req.query.next); +~~~ + +**Fix:** Resolve redirects using a server-owned route table or an explicit normalized URL policy. + +~~~javascript +res.redirect('/account'); +~~~ + +**Verification:** External and scheme-relative destinations fail; approved navigation still works. + +[Primary reference 1](https://expressjs.com/en/4x/api.html#res.redirect) + + + +## JS-LOG-CREDENTIALS. Credential-like value passed directly to console + +**Search:** scanner rule JS-LOG-CREDENTIALS. Use `--explain JS-LOG-CREDENTIALS` for details. Bounded JS tokens: console log/info/warn/error/debug/trace with direct sensitive names/properties, inline object/array values or concatenation. Observed console shadows/reassignments suppress hints file-wide. Templates, helper calls, custom loggers, dynamic keys and cross-file flows remain manual; absence of a signal does not verify redaction. + +**Vulnerable example:** + +~~~javascript +console.warn(req.headers.authorization); +~~~ + +**Fix:** Log stable event categories and approved identifiers, not credential values. Inspect failed-login and exception paths; implement and test any redaction helper independently. + +~~~javascript +console.warn('authentication failed'); +~~~ + +**Verification:** Synthetic canary credentials never appear in stdout, logs, exported evidence or screen broadcasts; failure categories remain useful. + +[Primary reference](https://nodejs.org/api/console.html) diff --git a/docs/vulnerabilities/php-RU.md b/docs/vulnerabilities/php-RU.md new file mode 100644 index 0000000..b5ada63 --- /dev/null +++ b/docs/vulnerabilities/php-RU.md @@ -0,0 +1,790 @@ + + +# PHP: поиск и исправление + +[English](php.md) | Русский + +[Вся база](README-RU.md) · [Сканер](../offline-scanner-RU.md) · [Проверка патча](../patch-validation-RU.md) + +23 разделов. Формат: **Поиск → Уязвимый вариант → Исправление → Проверка**. +Команды `rg` выполняются в корне локальной копии сервиса и только читают файлы. Субъект/владелец определяется по проверенной сессии, а не данным запроса. Примеры нужно адаптировать к реальным API и контракту. + +Автоматические находки — ограниченные синтаксические сигналы для проверки. AST-анализ не разрешает типы и не отслеживает данные между функциями; regex не заменяет парсер языка. Комментарии, строки и одноимённые пользовательские API могут давать совпадения. Проверьте фактическое исполнение, входные данные, авторизацию и границы доверия. + + + +## Содержание + +- [PHP-SQL — Динамический SQL PHP](#php-sql) +- [PHP-OBJECT — unserialize внешних данных](#php-object) +- [PHP-SHELL — Исполнение текста PHP/команды](#php-shell) +- [PHP-INCLUDE — Клиентский путь include](#php-include) +- [PHP-PREFIX-MAC — Хеш конкатенации вместо MAC](#php-prefix-mac) +- [PHP-PARSE-STR — Нормализация ключей parse_str](#php-parse-str) +- [PHP-LOOSE-COMPARE — Нестрогое сравнение токена или подписи](#php-loose-compare) +- [PHP-UPLOAD — Перенос загруженного файла](#php-upload) +- [PHP-DISPLAY-ERRORS — PHP показывает ошибки клиенту](#php-display-errors) +- [PHP-XSS — HTML/атрибут/JS получают сырой текст](#php-xss) +- [PHP-SESSION — PHP session: fixation, strict mode, старое состояние](#php-session) +- [PHP-WRAPPERS — Файловый API принимает URL/wrapper](#php-wrappers) +- [PHP-EXTRACT — extract и variable variables подменяют контекст](#php-extract) +- [PHP-SERIALIZE-MAGIC — Magic methods и доверие данным из БД](#php-serialize-magic) +- [PHP-CSRF — Cookie авторизует изменяющий запрос без CSRF](#php-csrf) +- [PHP-REGEX-ERROR — Ошибка preg_match трактуется как разрешение](#php-regex-error) +- [PHP-XML-FLAGS — XML разрешает подстановку сущностей и DTD](#php-xml-flags) +- [PHP-TEMPLATE — Шаблон создаётся из динамического текста](#php-template) +- [PHP-CURL-TLS — cURL не проверяет сертификат или имя](#php-curl-tls) +- [PHP-URL-INCLUDE — Разрешён include удалённого ресурса](#php-url-include) +- [PHP-SESSION-CONFIG — Ослабленные настройки PHP-сессии](#php-session-config) +- [PHP-MASS-ASSIGN — Ключи массива выбирают колонки и права](#php-mass-assign) +- [PHP-LDAP-FILTER — LDAP-фильтр склеивается с PHP-переменной](#php-ldap-filter) + + + + + +## PHP-SQL. Динамический SQL PHP + +**Поиск:** скрипт, правило PHP-SQL. Запуск: python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain PHP-SQL. Regex: query/exec/prepare со сборкой строки, double-quoted интерполяция, mysqli_query/pg_query с обычным аргументом соединения. Escaping, другие формы интерполяции и SQL из переменной полноценно не разбираются. + +**Уязвимый вариант:** + +~~~php +$db->query("SELECT id FROM notes WHERE name=" . $name); +~~~ + +**Исправление:** Prepared statements и связанные значения в API выбранного драйвера, например PDO prepare/execute; идентификаторы — из разрешённого набора, значения не подставлять вручную. + +~~~php +$stmt = $db->prepare("SELECT id FROM notes WHERE name = ?"); +$stmt->execute([$name]); +~~~ + +**Проверка:** Кавычки остаются данными; ограничения владельца сохраняются. + +
+Развёрнутый пример и ограничения + +```php +// Vulnerable: client input is interpolated into SQL. +$row = $pdo->query("SELECT body FROM notes WHERE id = '" . $_GET['id'] . "'")->fetch(); +``` + +**Патч PDO для приватной заметки:** + +```php +function readPrivateNote(PDO $pdo, ?int $userId, int $noteId): ?string { + if ($userId === null) { + throw new RuntimeException('authentication required'); + } + $stmt = $pdo->prepare('SELECT body FROM notes WHERE id = :id AND owner_id = :owner'); + $stmt->bindValue(':id', $noteId, PDO::PARAM_INT); + $stmt->bindValue(':owner', $userId, PDO::PARAM_INT); + $stmt->execute(); + $row = $stmt->fetch(PDO::FETCH_ASSOC); + return $row === false ? null : $row['body']; +} +``` + +До функции валидировать числовой ID: `(int) $_GET['id']` молча преобразует часть +некорректных строк. Настроить обработку ошибок PDO; не возвращать клиенту текст +SQL-исключения. Маркеры предназначены для значений, не имён таблиц/столбцов. +Для поддерживающего драйвера можно использовать native prepares; не менять +режим всего приложения вслепую, поскольку поведение драйверов различается. + +**Проверить:** своё/чужое/нет сессии; отсутствующая запись; неверный ID; поиск +другого строкового поля с апострофом не ломается. Сохранить общий доступ, если он есть. + +
+ + + + + +## PHP-OBJECT. unserialize внешних данных + +**Поиск:** скрипт, правило PHP-OBJECT. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain PHP-OBJECT. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API. + +**Уязвимый вариант:** + +~~~php +$value = unserialize($data); +~~~ + +**Исправление:** JSON со схемой; совместимость старого формата отдельно. allowed_classes=false не заменяет схему. + +~~~php +$value = json_decode($data, true, 32, JSON_THROW_ON_ERROR); // validate schema +~~~ + +**Проверка:** Объекты PHP не создаются; старые данные учтены. + +
+Развёрнутый пример и ограничения + +```php +// Vulnerable with untrusted input: object restoration has side effects. +$profile = unserialize($_COOKIE['profile']); +``` + +**Патч для простого профиля при совместимом JSON-контракте:** + +```php +function decodeProfile(string $raw): array { + $value = json_decode($raw, false, 32, JSON_THROW_ON_ERROR); + if (!($value instanceof stdClass)) { + throw new InvalidArgumentException('object required'); + } + $fields = get_object_vars($value); + if (array_keys($fields) !== ['display_name'] || !is_string($fields['display_name'])) { + throw new InvalidArgumentException('unexpected profile fields'); + } + return ['display_name' => $fields['display_name']]; +} +``` + +Глубина 32 — пример ограничения, не требование игры; размер тела ограничивать +до парсинга по контракту. `role` и владелец задаются сервером. PHP прямо +предостерегает от `unserialize` недоверенных данных даже с `allowed_classes`: +один этот флаг не считать полным исправлением. + +**Проверить:** корректный профиль, неизвестное поле, массив вместо объекта, +неверный тип и ошибка JSON. Переход формата требует совместимости старых клиентов +и данных; не оставлять fallback на `unserialize` для строки клиента. + +
+ + + + + +## PHP-SHELL. Исполнение текста PHP/команды + +**Поиск:** скрипт, правило PHP-SHELL. Запуск: python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain PHP-SHELL. Regex: eval/shell_exec/system/passthru/popen/exec и строковый/переменный proc_open. Literal argv-массив proc_open в первом аргументе, также с command: в PHP 8+, не помечается, кроме явного shell; массив поддержан PHP 7.4+. Исполняемый файл и опасные опции проверить вручную. Переставленные named arguments, backticks, variable functions, wrappers и действующая версия PHP требуют ручного анализа; одноимённые пользовательские функции и комментарии могут совпадать. + +**Уязвимый вариант:** + +~~~php +shell_exec($command); +~~~ + +**Исправление:** Библиотечная операция вместо shell; иначе фиксированные argv через API без оболочки. + +~~~php +$size = filesize($checkedPath); +~~~ + +**Проверка:** Штатная функция сохранена; текст не исполняется. + +`proc_open` принимает argv-массив начиная с PHP 7.4; именованный `command:` — +с PHP 8.0. Массив передаётся процессу без неявной оболочки. Для действительно +нужной утилиты можно сохранить вызов без shell, например на PHP 8+: + +~~~php +$process = proc_open( + command: ['/usr/bin/file', '--', $checkedName], + descriptor_spec: $descriptors, + pipes: $pipes +); +~~~ + +Здесь путь к executable фиксирован, а `$checkedName` должен пройти проверку +доступа и допустимого пути. `--` подходит только утилите, поддерживающей такой +разделитель. `command: array('/usr/bin/file', '--', $checkedName)` также не +получает PHP-SHELL. Исключение ограничено первым аргументом с литеральной +формой массива; перестановка именованных аргументов и массив из переменной +остаются сигналами для просмотра. +[proc_open: массив и ограничения Windows](https://github.com/php/doc-en/blob/master/reference/exec/functions/proc-open.xml#L68), +[PHP 8: именованные аргументы](https://www.php.net/manual/en/migration80.new-features.php#migration80.new-features.core.named-arguments), +[сигнатура proc_open в PHP 8.0](https://github.com/php/php-src/blob/php-8.0.0/ext/standard/basic_functions.stub.php#L1156). + +Явный запуск shell сохраняет риск и сигнал даже при массиве: + +~~~php +$process = proc_open(command: ['sh', '-c', $command], descriptor_spec: $descriptors, pipes: $pipes); +~~~ + +Не превращать pipeline в argv простым разделением строки: перенести нужные +операции в библиотеку либо явно связать процессы. Проверить executable, +опции, `PATH`, рабочий каталог и окружение. На Windows экранирование массива +рассчитано на совместимый с VC runtime разбор командной строки; произвольный +parser программы может иметь другой контракт. Закрывать pipes и процесс, +проверять ошибки, лимиты времени/вывода и прежний формат результата. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'proc_open|proc_close|proc_terminate|shell_exec|descriptor_spec|bypass_shell' . +~~~ + +После совпадения проследить реальный argv и источник каждого аргумента. +В разрешённом тестовом окружении проверить пробелы, кавычки, имя с ведущим +дефисом, штатный файл и ошибку процесса. Отсутствие PHP-SHELL не доказывает +безопасность аргументов. Здесь проверены исходники и поведение сканера; +PHP runtime и найденные команды не запускались. + + + + + +## PHP-INCLUDE. Клиентский путь include + +**Поиск:** скрипт, правило PHP-INCLUDE. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain PHP-INCLUDE. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API. + +**Уязвимый вариант:** + +~~~php +include $_GET['page']; +~~~ + +**Исправление:** Фиксированная таблица разрешённых модулей; пользовательский текст хранить как данные. + +~~~php +$pages = ['home' => __DIR__ . '/pages/home.php']; +if (!isset($pages[$page])) { throw new Exception('bad page'); } +include $pages[$page]; +~~~ + +**Проверка:** Неизвестные имена/пути отвергаются; штатные страницы работают. + +
+Развёрнутый пример и ограничения + +```php +// Vulnerable: the client controls the executable PHP file path. +include $_GET['page']; +``` + +**Патч, если контракт — выбор одной из известных страниц:** + +```php +$pages = [ + 'help' => __DIR__ . '/pages/help.php', + 'profile' => __DIR__ . '/pages/profile.php', +]; +$page = $_GET['page'] ?? 'help'; +if (!is_string($page) || !array_key_exists($page, $pages)) { + http_response_code(404); + exit; +} +require $pages[$page]; +``` + +Пути заданы сервером. Требования авторизации `profile` остаются обязательными +до выдачи приватных данных. `basename()` не ограничивает пользователя нужным +набором страниц и не решает права. Если функция обещает загрузку пользовательского +файла, `include` вообще не должен использоваться для его отображения. + +**Проверить:** обе штатные страницы, неизвестное имя, массив вместо page; +закрытая страница не открывается анониму; меняется только допустимый выбор страницы. + +
+ + + + + +## PHP-PREFIX-MAC. Хеш конкатенации вместо MAC + +**Поиск:** скрипт, правило PHP-PREFIX-MAC. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain PHP-PREFIX-MAC. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API. + +**Уязвимый вариант:** + +~~~php +$tag = sha1($key . $payload); +~~~ + +**Исправление:** HMAC с секретом вместо sha1(secret || data). Проверять тег через hash_equals; версионировать формат и спланировать переход старых токенов. + +~~~php +$tag = hash_hmac('sha256', $payload, $key); +~~~ + +**Проверка:** Изменение/добавление данных не проходит; подпись охватывает назначение и все auth-поля. + +**Вариант A/D:** Secret-prefix hash ошибочно назван HMAC. **ECSC / Diese, автор + код.** Подпись построена как SHA1 от secret || data. +**Патч:** настоящий HMAC и версия токена; безопасный переход старых подписей. +**Тест:** изменение/добавление полей не принимается. +**Поиск:** PHP-PREFIX-MAC; имя функции hmac само по себе ничего не гарантирует. + +[исходник/разбор 1](https://github.com/ECSC2024/ECSC2024-CTF-AD/blob/2a92e17384ad228072a84fb076a35066fe2ffeff/sources/Diese/README.md); [исходник/разбор 2](https://github.com/ECSC2024/ECSC2024-CTF-AD/blob/2a92e17384ad228072a84fb076a35066fe2ffeff/sources/Diese/webapp/src/classes/Utils.class.php); [исходник/разбор 3](https://github.com/ECSC2024/ECSC2024-CTF-AD/blob/2a92e17384ad228072a84fb076a35066fe2ffeff/sources/Diese/hsm/src/msg.c). + + + + + +## PHP-PARSE-STR. Нормализация ключей parse_str + +**Поиск:** скрипт, правило PHP-PARSE-STR. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain PHP-PARSE-STR. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API. + +**Уязвимый вариант:** + +~~~php +parse_str($token_data, $params); +~~~ + +**Исправление:** Явная схема и allowlist полей до подписи и после разбора; учесть преобразование точек/пробелов в underscore, массивы и дубли ключей. + +~~~php +$params = parse_and_validate_canonical_share_dto($token_data); // one schema, duplicate policy, server-owned fields +~~~ + +**Проверка:** Разные написания поля не меняют owner/doc_id; signer и verifier разбирают одинаково. + +**Вариант A/D:** Нормализация ключей параметров после подписи. **ECSC / Diese, автор + код.** parse_str превращает некоторые разные имена +в одинаковые, меняя смысл полей. +**Патч:** allowlist и одна каноническая DTO-схема у signer/verifier; запрет +неоднозначных дублей. **Тест:** точки, пробелы, underscore и массивы. +**Поиск:** PHP-PARSE-STR; сам вызов не обязательно уязвим. + +[исходник/разбор 1](https://github.com/ECSC2024/ECSC2024-CTF-AD/blob/2a92e17384ad228072a84fb076a35066fe2ffeff/sources/Diese/README.md); [исходник/разбор 2](https://github.com/ECSC2024/ECSC2024-CTF-AD/blob/2a92e17384ad228072a84fb076a35066fe2ffeff/sources/Diese/webapp/src/classes/Utils.class.php); [исходник/разбор 3](https://github.com/ECSC2024/ECSC2024-CTF-AD/blob/2a92e17384ad228072a84fb076a35066fe2ffeff/sources/Diese/hsm/src/msg.c). + + + + + +## PHP-LOOSE-COMPARE. Нестрогое сравнение токена или подписи + +**Поиск:** скрипт, правило PHP-LOOSE-COMPARE. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain PHP-LOOSE-COMPARE. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API. + +**Уязвимый вариант:** + +~~~php +$ok = $token == $provided; +~~~ + +**Исправление:** Проверить тип; для тега hash_equals, для обычного значения ===, для пароля password_verify. Семантика числовых строк зависит от версии и операндов. + +~~~php +$ok = is_string($provided) && hash_equals($token, $provided); +~~~ + +**Проверка:** Число/массив/числовая строка не превращаются в авторизацию; правильное значение принимается. + +**Основание:** [первичный материал](https://www.php.net/manual/en/language.operators.comparison.php). + + + + + +## PHP-UPLOAD. Перенос загруженного файла + +**Поиск:** скрипт, правило PHP-UPLOAD. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain PHP-UPLOAD. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API. + +**Уязвимый вариант:** + +~~~php +move_uploaded_file($tmp, $webroot . $name); +~~~ + +**Исправление:** Проверять upload error/размер/тип, серверное имя и отсутствие перезаписи, хранить вне исполняемого webroot; выдавать после auth. + +~~~php +move_uploaded_file($validatedTmp, $serverChosenPrivatePath); +~~~ + +**Проверка:** Обычный upload/download, коллизия имени, чужой owner, неверный тип и полный диск. Вызов остаётся сигналом. + +**Основание:** [первичный материал](https://www.php.net/manual/en/features.file-upload.php). + + + + + +## PHP-DISPLAY-ERRORS. PHP показывает ошибки клиенту + +**Поиск:** скрипт, правило PHP-DISPLAY-ERRORS. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain PHP-DISPLAY-ERRORS. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API. + +**Уязвимый вариант:** + +~~~php +display_errors = On +~~~ + +**Исправление:** Отключить клиентский вывод, включить локальный журнал без секретов; проверить эффективный php.ini/FPM pool и runtime ini_set. + +~~~php +display_errors = Off +~~~ + +**Проверка:** Parse/DB/type error дают штатный ответ, диагностика сохраняется. + +**Основание:** [первичный материал](https://www.php.net/manual/en/errorfunc.configuration.php). + + + + + +## PHP-XSS. HTML/атрибут/JS получают сырой текст + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'echo|print|htmlspecialchars|json_encode| +Развёрнутый пример и ограничения + +```php +// Vulnerable with untrusted title: the browser interprets it as markup. +echo '

' . $title . '

'; +``` + +**Патч для текстового содержимого HTML:** + +```php +echo '

' . htmlspecialchars($title, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8') . '

'; +``` + +`$title` перед этим проверен как строка. Сохранить исходный текст в БД и кодировать +при выводе. Иначе повторное редактирование может накопить двойное экранирование. +Этот пример не является кодированием JavaScript, CSS или проверкой URL; для этих +контекстов другой механизм. Разрешённый по контракту HTML требует очистки +допустимого подмножества, а не превращения всей разметки в текст. + +**Проверить:** `<`, `>`, `&`, кавычки и Unicode показываются текстом; старая запись +и цикл «сохранить → открыть → изменить» сохраняют исходное содержание. + + + + + + + +## PHP-SESSION. PHP session: fixation, strict mode, старое состояние + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'session_start|session_regenerate_id|session.use_strict_mode|session_id' . +~~~ + +Проследить принятие внешнего ID, регенерацию при login и запись роли в session. + +**Уязвимый вариант:** + +Внешний неизвестный ID принимается, после входа остаётся тем же. + +**Исправление:** session.use_strict_mode, штатная регенерация с учётом concurrent requests, серверная роль; согласованные Secure/HttpOnly/SameSite. + +**Проверка:** Прежний ID не авторизует, обычные параллельные запросы не теряют состояние. + +**Основание:** [первичный материал](https://www.php.net/manual/en/session.security.ini.php). + + + + + +## PHP-WRAPPERS. Файловый API принимает URL/wrapper + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'file_get_contents|fopen|copy\(|file_exists|is_file|phar|stream_context' . +~~~ + +Проверить, что API принимает путь или stream URL; сопоставить версию PHP и нужные wrappers. + +**Уязвимый вариант:** + +Пользователь выбирает схему/локальный путь вместо разрешённого объекта; open_basedir не является полным sandbox. + +**Исправление:** Серверный путь из авторизованного ID; для HTTP отдельный клиент с URL policy; запрет клиентского выбора wrapper. + +**Проверка:** Штатный файл читается, внешний URL/чужой файл/нестандартная схема не достигают операции. + + + + + +## PHP-EXTRACT. extract и variable variables подменяют контекст + +**Поиск:** скрипт, правило PHP-EXTRACT. Запуск: python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain PHP-EXTRACT. Regex: любой extract(...); доверенные шаблонные контексты требуют ручной классификации. + +Дополнительный ручной поиск для непокрытых форм: + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'extract\(|parse_str|\$\$|GLOBALS|register_globals' . +~~~ + +Сравнить импортируемые ключи с именами auth/config переменных; двухаргументный parse_str имеет иной риск, чем старое поведение. + +**Уязвимый вариант:** + +extract($_REQUEST) перезаписывает локальные переменные либо $$key выбирает чувствительное имя. + +**Исправление:** Явно читать разрешённые поля в отдельный DTO; не импортировать клиентские ключи в symbol table. EXTR_SKIP уменьшает перезаписи, но не заменяет проверку схемы, типов и новых имён. + +**Проверка:** role, authorized, путь и конфигурация не меняются при лишних ключах. + +**Основание:** [первичный материал](https://www.php.net/manual/en/function.extract.php). + + +**Сигнал сканера — пример до:** + +~~~php +extract($_POST); +if ($is_admin) { show_private_data(); } +~~~ + +**Шаблон исправления:** + +~~~php +$display_name = validate_display_name($_POST['display_name'] ?? ''); +~~~ + +Первичная документация: [документация 1](https://www.php.net/manual/en/function.extract.php). + + + + + +## PHP-SERIALIZE-MAGIC. Magic methods и доверие данным из БД + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e '__wakeup|__unserialize|__destruct|__toString|unserialize' . +~~~ + +От места PHP-OBJECT пройти reachable classes и побочные эффекты; БД не становится доверенной после клиентской записи. + +**Уязвимый вариант:** + +Десериализованный объект вызывает файловую/сетевую операцию до проверки результата. + +**Исправление:** DTO без выбора класса и побочных эффектов; совместимая миграция отдельно, не fallback на небезопасный parser. + +**Проверка:** Неизвестный тип не вызывает эффектов; старый допустимый формат читается по плану. + + + + + +## PHP-CSRF. Cookie авторизует изменяющий запрос без CSRF + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'csrf|POST|PUT|DELETE|REQUEST_METHOD|SameSite' . +~~~ + +Проверить формы и JSON endpoint с cookie auth, исключения middleware и Origin/Referer policy. + +**Уязвимый вариант:** + +Браузер автоматически прикладывает cookie к изменению состояния из чужого контекста. + +**Исправление:** Штатный CSRF token и проверка origin по архитектуре; SameSite дополняет, не заменяет серверную проверку. Bearer API имеет другой контекст. + +**Проверка:** Неверный/отсутствующий token отклоняется; нормальная форма и предусмотренные API-клиенты работают. + + + + + +## PHP-REGEX-ERROR. Ошибка preg_match трактуется как разрешение + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'preg_match|preg_last_error|preg_replace' . +~~~ + +Различить false, 0 и 1; найти отрицание результата и лимиты regex. + +**Уязвимый вариант:** + +Ошибка движка при длинном вводе попадает в ветвь «запрещённое не найдено». + +**Исправление:** Проверять результат === 1/0/false по смыслу, fail closed при ошибке; ограничить длину и сложность. + +**Проверка:** Match/no-match/ошибка движка дают разные ожидаемые ответы, штатный Unicode поддержан. + +**Основание:** [первичный материал](https://www.php.net/manual/en/function.preg-match.php). + + + + + +## PHP-XML-FLAGS. XML разрешает подстановку сущностей и DTD + +**Поиск:** скрипт, правило PHP-XML-FLAGS. Запуск: python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain PHP-XML-FLAGS. Regex: LIBXML_NOENT/DTDLOAD/DTDATTR/DTDVALID и substituteEntities/resolveExternals=true. Числовые маски из ini/БД не распознаются: вручную сопоставить каждый бит с константами runtime. + +**Уязвимый вариант:** NOENT означает подстановку сущностей, а NONET сам по себе не запрещает доступ к локальному файлу. + +~~~php +$doc->loadXML($xml, LIBXML_NOENT | LIBXML_DTDLOAD | LIBXML_NONET); +~~~ + +**Исправление:** Убрать подстановку/загрузку внешних DTD, установить лимиты и проверить версию libxml. На поддерживаемом runtime добавить LIBXML_NO_XXE; не полагаться на один NONET. + +~~~php +$doc->resolveExternals = false; +$doc->substituteEntities = false; +$doc->loadXML($boundedXml, LIBXML_NONET); +~~~ + +**Проверка:** Обычный XML разбирается; внешний DTD/сущность не читает файл и не делает сетевой запрос, объём/вложенность ограничены. + +Первичная документация: [документация 1](https://www.php.net/manual/en/libxml.constants.php), [документация 2](https://github.com/enowars/enowars7-service-oldschool#vulnerabilities). + + + + + +## PHP-TEMPLATE. Шаблон создаётся из динамического текста + +**Поиск:** скрипт, правило PHP-TEMPLATE. Запуск: python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain PHP-TEMPLATE. Regex: createTemplate($...) и Smarty display/fetch с eval: или string:. Переменные loaders, custom filters и шаблоны из БД просматривать вручную. + +**Уязвимый вариант:** Если пользовательские данные становятся исходником шаблона, возможности template engine становятся доступными пользователю. + +~~~php +$template = $twig->createTemplate($profileText); +echo $template->render($vars); +~~~ + +**Исправление:** Разделить доверенный шаблон и параметры; если продукт допускает шаблоны, отдельно ограничить sandbox, loader, доступные функции и ресурсы. + +~~~php +echo $twig->render('profile.html.twig', ['about' => $profileText]); +~~~ + +**Проверка:** Текст шаблонных выражений в профиле отображается как данные; приватные шаблоны/файлы недоступны. + +Первичная документация: [документация 1](https://twig.symfony.com/doc/3.x/api.html#loading-templates-from-a-string). + + + + + +## PHP-CURL-TLS. cURL не проверяет сертификат или имя + +**Поиск:** скрипт, правило PHP-CURL-TLS. Запуск: python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain PHP-CURL-TLS. Regex: CURLOPT_SSL_VERIFYPEER=false/0 и CURLOPT_SSL_VERIFYHOST=false/0/1, аргумент или setopt_array. Значения из переменных не вычисляются. + +**Уязвимый вариант:** Отключение проверки сервера позволяет подменить результат исходящего HTTPS-запроса. + +~~~php +curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); +curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); +~~~ + +**Исправление:** Проверять peer и hostname, настроить доверенный CA. На VERIFYHOST использовать 2, не исторически неоднозначное 1. + +~~~php +curl_setopt_array($ch, [CURLOPT_SSL_VERIFYPEER => true, CURLOPT_SSL_VERIFYHOST => 2, CURLOPT_CAINFO => $trustedCA]); +~~~ + +**Проверка:** Верный CA/hostname работает, чужой hostname/CA и истёкший сертификат дают ошибку без fallback. + +Первичная документация: [документация 1](https://www.php.net/manual/en/function.curl-setopt.php). + + + + + +## PHP-URL-INCLUDE. Разрешён include удалённого ресурса + +**Поиск:** скрипт, правило PHP-URL-INCLUDE. Запуск: python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain PHP-URL-INCLUDE. Regex: allow_url_include=On/1/true в ini/config или присваивании. Runtime overrides и фактический include path проверять отдельно. + +**Уязвимый вариант:** URL include расширяет последствия управления путём PHP include/require. + +~~~config +allow_url_include = On +~~~ + +**Исправление:** Отключить allow_url_include в действующей конфигурации SAPI; пути подключений выбирать из закрытой серверной таблицы. + +~~~config +allow_url_include = Off +~~~ + +**Проверка:** Приложение загружает штатные модули; пользовательский URL не становится исполняемым кодом. + +Первичная документация: [документация 1](https://www.php.net/manual/en/filesystem.configuration.php#ini.allow-url-include). + + + + + +## PHP-SESSION-CONFIG. Ослабленные настройки PHP-сессии + +**Поиск:** скрипт, правило PHP-SESSION-CONFIG. Запуск: python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain PHP-SESSION-CONFIG. Regex: явные опасные значения use_strict_mode/use_only_cookies/use_trans_sid. Пропущенные настройки и ini_set с аргументами остаются ручными. + +**Уязвимый вариант:** Принятие навязанного session id и перенос id в URL создают фиксацию/утечку сессии. + +~~~config +session.use_strict_mode = 0 +session.use_only_cookies = 0 +session.use_trans_sid = 1 +~~~ + +**Исправление:** Включить strict mode и cookie-only transport, отключить URL rewriting; при auth сменить id, проверить custom session handler и флаги cookie. + +~~~config +session.use_strict_mode = 1 +session.use_only_cookies = 1 +session.use_trans_sid = 0 +~~~ + +**Проверка:** Навязанный неизвестный id не принимается, после login id меняется; URL/логи не содержат id, штатная сессия сохраняется. + +Первичная документация: [документация 1](https://www.php.net/manual/en/session.configuration.php). + + + + + +## PHP-MASS-ASSIGN. Ключи массива выбирают колонки и права + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e '\$_(POST|GET|REQUEST)|array_keys|array_merge|profileData|UPDATE|SET|fill\(|update\(' . +~~~ + +Проследить не только значения, но и ключи массива от запроса до UPDATE/ORM и назначения owner/admin/association. Проверить вложенные поля и числовые индексы. + +**Уязвимый вариант:** Параметризованы значения SQL, но имена колонок берутся из пользовательского массива; поле роли или связи с чужим объектом массово обновляется. + +**Исправление:** Явно сопоставить разрешённые входные поля фиксированным колонкам и типам. Права, owner и связи проверять отдельно; placeholders не экранируют SQL identifiers. + +**Проверка:** Неизвестная колонка, служебное поле и чужая связь отклонены без изменения состояния; разрешённые поля сохраняются. + +Основание: [OWASP Mass Assignment](https://cheatsheetseries.owasp.org/cheatsheets/Mass_Assignment_Cheat_Sheet.html). Описание и рецепт адаптации составлены для этой базы. + +**Вариант A/D:** в Oldschool массовое обновление позволяло менять служебную связь; имена колонок также попадали в SQL без ограничения. [Авторское описание](https://github.com/enowars/enowars7-service-oldschool#vulnerabilities). + + + + + +## PHP-LDAP-FILTER. LDAP-фильтр склеивается с PHP-переменной + +**Поиск:** правило сканера PHP-LDAP-FILTER. Точный контракт детектора: `--explain PHP-LDAP-FILTER`. Regex с лексическими исключениями: ldap_search/list/read с простыми первыми двумя аргументами и строкой, напрямую объединённой с переменной в третьем аргументе. Переменная может уже быть экранирована; заранее собранные фильтры и интерполяция требуют ручной проверки. + +**Уязвимый вариант:** + +~~~php +ldap_search($conn, $base, '(uid=' . $name . ')'); +~~~ + +**Исправление:** Экранируйте значения для контекста LDAP-фильтра, а не DN; имена атрибутов и область поиска должны быть доверенными. + +~~~php +$filter = '(uid=' . ldap_escape($name, '', LDAP_ESCAPE_FILTER) . ')'; +ldap_search($conn, $base, $filter); +~~~ + +**Проверка:** Метасимволы LDAP в значении не расширяют результат; разрешённые поисковые запросы работают. + +[Первичный источник 1](https://www.php.net/manual/en/function.ldap-escape.php) diff --git a/docs/vulnerabilities/php.md b/docs/vulnerabilities/php.md new file mode 100644 index 0000000..2f82aac --- /dev/null +++ b/docs/vulnerabilities/php.md @@ -0,0 +1,692 @@ +# PHP: find, fix and verify + +English | [Русский](php-RU.md) + +[Catalog](README.md) · [Scanner](../offline-scanner.md) · [Patch verification](../patch-validation.md) + +23 sections. Each follows **Search → Vulnerable example → Fix → Verification**. +Run `rg` from a local service checkout; searches only read files. Derive the actor/owner from a verified session, not request data. Adapt examples to the actual API and contract. + +## Contents + +- [PHP-SQL — Dynamic PHP SQL](#php-sql) +- [PHP-OBJECT — Untrusted PHP unserialize](#php-object) +- [PHP-SHELL — PHP code or shell execution](#php-shell) +- [PHP-INCLUDE — Client-selected include path](#php-include) +- [PHP-PREFIX-MAC — Hash concatenation instead of MAC](#php-prefix-mac) +- [PHP-PARSE-STR — parse_str key normalization](#php-parse-str) +- [PHP-LOOSE-COMPARE — Loose comparison of token or signature](#php-loose-compare) +- [PHP-UPLOAD — Moving an uploaded file](#php-upload) +- [PHP-DISPLAY-ERRORS — PHP displays errors to clients](#php-display-errors) +- [PHP-XSS — Raw data reaches HTML, attributes or JavaScript](#php-xss) +- [PHP-SESSION — Session fixation, strict mode and stale state](#php-session) +- [PHP-WRAPPERS — Filesystem APIs accept URLs or wrappers](#php-wrappers) +- [PHP-EXTRACT — extract overwrites local variables](#php-extract) +- [PHP-SERIALIZE-MAGIC — Magic methods and trust in stored data](#php-serialize-magic) +- [PHP-CSRF — Cookies authorize mutations without CSRF protection](#php-csrf) +- [PHP-REGEX-ERROR — preg_match errors become permission](#php-regex-error) +- [PHP-XML-FLAGS — XML entity substitution or DTD enabled](#php-xml-flags) +- [PHP-TEMPLATE — Template built from dynamic text](#php-template) +- [PHP-CURL-TLS — cURL certificate or hostname checks disabled](#php-curl-tls) +- [PHP-URL-INCLUDE — Remote resource inclusion enabled](#php-url-include) +- [PHP-SESSION-CONFIG — Weakened PHP session configuration](#php-session-config) +- [PHP-MASS-ASSIGN — Array keys choose columns and privileges](#php-mass-assign) +- [PHP-LDAP-FILTER — LDAP filter concatenates a PHP variable](#php-ldap-filter) + + + +## PHP-SQL. Dynamic PHP SQL + +**Search:** scanner rule PHP-SQL. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain PHP-SQL` for details. Regex: query/exec/prepare with concatenation, double-quoted interpolation and mysqli_query/pg_query with an ordinary connection argument. Escaping, other interpolation and SQL variables are not fully parsed. + +**Vulnerable example:** + +~~~php +$db->query("SELECT id FROM notes WHERE name=" . $name); +~~~ + +**Fix:** Use driver-supported prepared statements and bound values; allowlist identifiers. + +~~~php +$stmt = $db->prepare("SELECT id FROM notes WHERE name = ?"); +$stmt->execute([$name]); +~~~ + +**Verification:** Quotes stay data and ownership conditions remain. + +
+Expanded example and limitations + +```php +// Vulnerable: client input is interpolated into SQL. +$row = $pdo->query("SELECT body FROM notes WHERE id = '" . $_GET['id'] . "'")->fetch(); +``` + +**PDO patch for a private note:** + +```php +function readPrivateNote(PDO $pdo, ?int $userId, int $noteId): ?string { + if ($userId === null) { + throw new RuntimeException('authentication required'); + } + $stmt = $pdo->prepare('SELECT body FROM notes WHERE id = :id AND owner_id = :owner'); + $stmt->bindValue(':id', $noteId, PDO::PARAM_INT); + $stmt->bindValue(':owner', $userId, PDO::PARAM_INT); + $stmt->execute(); + $row = $stmt->fetch(PDO::FETCH_ASSOC); + return $row === false ? null : $row['body']; +} +``` + +Validate the numeric ID first: `(int) $_GET['id']` silently converts some invalid strings. Configure PDO error handling and do not return SQL exceptions to clients. Placeholders represent values, not table/column names. Native prepares may be appropriate for supported drivers, but do not change application-wide settings blindly; driver behavior differs. + +**Check:** Owner, other user, no session, missing record, invalid ID and another searchable text field containing an apostrophe. Preserve intended sharing. + +
+ + + +## PHP-OBJECT. Untrusted PHP unserialize + +**Search:** scanner rule PHP-OBJECT. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain PHP-OBJECT` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries. + +**Vulnerable example:** + +~~~php +$value = unserialize($data); +~~~ + +**Fix:** Prefer schema-validated JSON; migrate trusted legacy records separately. allowed_classes alone is not a complete input policy. + +~~~php +$value = json_decode($data, true, 32, JSON_THROW_ON_ERROR); // validate schema +~~~ + +**Verification:** Unexpected object types fail without construction; valid records stay readable. + +
+Expanded example and limitations + +```php +// Vulnerable with untrusted input: object restoration has side effects. +$profile = unserialize($_COOKIE['profile']); +``` + +**Patch for a simple profile when the protocol supports JSON:** + +```php +function decodeProfile(string $raw): array { + $value = json_decode($raw, false, 32, JSON_THROW_ON_ERROR); + if (!($value instanceof stdClass)) { + throw new InvalidArgumentException('object required'); + } + $fields = get_object_vars($value); + if (array_keys($fields) !== ['display_name'] || !is_string($fields['display_name'])) { + throw new InvalidArgumentException('unexpected profile fields'); + } + return ['display_name' => $fields['display_name']]; +} +``` + +Depth 32 is an example bound, not a competition requirement; bound body size before parsing according to contract. Role and owner come from the server. PHP warns against untrusted unserialize even with allowed_classes: that flag alone is not a complete fix. + +**Check:** Valid profile, unknown field, array instead of object, wrong type and malformed JSON. Format migration must support old clients/data; never retain unserialize fallback for client strings. + +
+ + + +## PHP-SHELL. PHP code or shell execution + +**Search:** scanner rule PHP-SHELL. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain PHP-SHELL` for details. Regex: eval/shell_exec/system/passthru/popen/exec and string/variable proc_open. Literal argv arrays in proc_open's first argument (including PHP 8 command:) are excluded unless explicitly launching shell; arrays require PHP 7.4+. Review executable/options, reordered named arguments, backticks, variable functions, wrappers and runtime version. Custom same-named functions/comments may match. + +**Vulnerable example:** + +~~~php +shell_exec($command); +~~~ + +**Fix:** Prefer a library operation; otherwise use a fixed executable and validated argv without a shell. + +~~~php +$size = filesize($checkedPath); +~~~ + +**Verification:** Metacharacters and dangerous options cannot change the operation. + +proc_open accepts argv arrays from PHP 7.4; the named command argument requires PHP 8.0. Arrays pass arguments without an implicit shell. A genuinely required utility can run without shell, for example on PHP 8+: + +~~~php +$process = proc_open( + command: ['/usr/bin/file', '--', $checkedName], + descriptor_spec: $descriptors, + pipes: $pipes +); +~~~ + +The executable is fixed; $checkedName still needs authorization and path checks. `--` is valid only for utilities supporting that separator. `command: array('/usr/bin/file', '--', $checkedName)` also avoids PHP-SHELL. The exclusion covers only a literal-array first argument; reordered named arguments and variable arrays remain review signals. [proc_open arrays and Windows limitations](https://github.com/php/doc-en/blob/master/reference/exec/functions/proc-open.xml#L68), [PHP 8 named arguments](https://www.php.net/manual/en/migration80.new-features.php#migration80.new-features.core.named-arguments), [PHP 8.0 proc_open signature](https://github.com/php/php-src/blob/php-8.0.0/ext/standard/basic_functions.stub.php#L1156). + +Explicit shell execution remains risky and still signals even with an array: + +~~~php +$process = proc_open(command: ['sh', '-c', $command], descriptor_spec: $descriptors, pipes: $pipes); +~~~ + +Do not convert a pipeline to argv by simply splitting text: move operations to a library or connect processes explicitly. Review executable, options, PATH, cwd and environment. On Windows array escaping assumes VC-runtime-compatible command-line parsing; other parsers may differ. Close pipes/processes and check errors, runtime/output limits and the old result format. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'proc_open|proc_close|proc_terminate|shell_exec|descriptor_spec|bypass_shell' . +~~~ + +After a match trace actual argv and every argument's origin. In an authorized test environment check spaces, quotes, leading dashes, normal files and process failure. Absence of PHP-SHELL does not prove argument safety. This catalog review checked source and scanner behavior; it did not run PHP or the discovered commands. + + + +## PHP-INCLUDE. Client-selected include path + +**Search:** scanner rule PHP-INCLUDE. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain PHP-INCLUDE` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries. + +**Vulnerable example:** + +~~~php +include $_GET['page']; +~~~ + +**Fix:** Select server-owned include paths from a closed allowlist, never client paths/URLs. + +~~~php +$pages = ['home' => __DIR__ . '/pages/home.php']; +if (!isset($pages[$page])) { throw new Exception('bad page'); } +include $pages[$page]; +~~~ + +**Verification:** Only approved pages load; traversal and remote schemes fail. + +
+Expanded example and limitations + +```php +// Vulnerable: the client controls the executable PHP file path. +include $_GET['page']; +``` + +**Patch when the contract selects one of several known pages:** + +```php +$pages = [ + 'help' => __DIR__ . '/pages/help.php', + 'profile' => __DIR__ . '/pages/profile.php', +]; +$page = $_GET['page'] ?? 'help'; +if (!is_string($page) || !array_key_exists($page, $pages)) { + http_response_code(404); + exit; +} +require $pages[$page]; +``` + +The server defines paths. The profile page still requires authorization before private data is returned. basename() neither restricts selection to the intended pages nor checks access. If the feature displays user-uploaded files, include must not implement that display. + +**Check:** Both normal pages, unknown names and an array in place of page; anonymous callers cannot open private pages; only permitted selection changes. + +
+ + + +## PHP-PREFIX-MAC. Hash concatenation instead of MAC + +**Search:** scanner rule PHP-PREFIX-MAC. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain PHP-PREFIX-MAC` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries. + +**Vulnerable example:** + +~~~php +$tag = sha1($key . $payload); +~~~ + +**Fix:** Use HMAC rather than a hash of secret concatenated with data, compare with hash_equals and migrate/version old formats. + +~~~php +$tag = hash_hmac('sha256', $payload, $key); +~~~ + +**Verification:** Changed/appended data fails; tags bind purpose and all authentication fields. + +**A/D variant:** Secret-prefix hash mislabeled HMAC. **ECSC / Diese, author and source.** Signatures used SHA1(secret || data). **Patch:** Real HMAC, token versioning and safe migration of existing signatures. **Test:** Changed/added fields fail validation. **Search:** PHP-PREFIX-MAC; a function named hmac guarantees nothing. + +[source/write-up 1](https://github.com/ECSC2024/ECSC2024-CTF-AD/blob/2a92e17384ad228072a84fb076a35066fe2ffeff/sources/Diese/README.md); [source/write-up 2](https://github.com/ECSC2024/ECSC2024-CTF-AD/blob/2a92e17384ad228072a84fb076a35066fe2ffeff/sources/Diese/webapp/src/classes/Utils.class.php); [source/write-up 3](https://github.com/ECSC2024/ECSC2024-CTF-AD/blob/2a92e17384ad228072a84fb076a35066fe2ffeff/sources/Diese/hsm/src/msg.c). + + + +## PHP-PARSE-STR. parse_str key normalization + +**Search:** scanner rule PHP-PARSE-STR. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain PHP-PARSE-STR` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries. + +**Vulnerable example:** + +~~~php +parse_str($token_data, $params); +~~~ + +**Fix:** Use identical schemas before signing/after parsing; account for dots/spaces becoming underscores, arrays and duplicate keys. + +~~~php +$params = parse_and_validate_canonical_share_dto($token_data); // one schema, duplicate policy, server-owned fields +~~~ + +**Verification:** Alternate spellings cannot change owner/document; signer and verifier agree. + +**A/D variant:** Parameter-key normalization after signing. **ECSC / Diese, author and source.** parse_str merges certain distinct names and changes field meaning. **Patch:** An allowlist and one canonical signer/verifier DTO schema; reject ambiguous duplicates. **Test:** Dots, spaces, underscores and arrays. **Search:** PHP-PARSE-STR; the call itself need not be vulnerable. + +[source/write-up 1](https://github.com/ECSC2024/ECSC2024-CTF-AD/blob/2a92e17384ad228072a84fb076a35066fe2ffeff/sources/Diese/README.md); [source/write-up 2](https://github.com/ECSC2024/ECSC2024-CTF-AD/blob/2a92e17384ad228072a84fb076a35066fe2ffeff/sources/Diese/webapp/src/classes/Utils.class.php); [source/write-up 3](https://github.com/ECSC2024/ECSC2024-CTF-AD/blob/2a92e17384ad228072a84fb076a35066fe2ffeff/sources/Diese/hsm/src/msg.c). + + + +## PHP-LOOSE-COMPARE. Loose comparison of token or signature + +**Search:** scanner rule PHP-LOOSE-COMPARE. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain PHP-LOOSE-COMPARE` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries. + +**Vulnerable example:** + +~~~php +$ok = $token == $provided; +~~~ + +**Fix:** Validate types; use hash_equals for tags, === for ordinary values and password_verify for passwords. Numeric-string semantics depend on version/operands. + +~~~php +$ok = is_string($provided) && hash_equals($token, $provided); +~~~ + +**Verification:** Numbers, arrays and numeric strings cannot grant access; valid values work. + +**Reference:** [primary source](https://www.php.net/manual/en/language.operators.comparison.php). + + + +## PHP-UPLOAD. Moving an uploaded file + +**Search:** scanner rule PHP-UPLOAD. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain PHP-UPLOAD` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries. + +**Vulnerable example:** + +~~~php +move_uploaded_file($tmp, $webroot . $name); +~~~ + +**Fix:** Check upload error/size/type; use non-overwriting server-generated names outside executable web roots and authorize downloads. + +~~~php +move_uploaded_file($validatedTmp, $serverChosenPrivatePath); +~~~ + +**Verification:** Test upload/download, collisions, wrong owner/type and full disk. The call remains a review signal. + +**Reference:** [primary source](https://www.php.net/manual/en/features.file-upload.php). + + + +## PHP-DISPLAY-ERRORS. PHP displays errors to clients + +**Search:** scanner rule PHP-DISPLAY-ERRORS. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain PHP-DISPLAY-ERRORS` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries. + +**Vulnerable example:** + +~~~php +display_errors = On +~~~ + +**Fix:** Disable client error output and retain redacted local logs; check effective php.ini/FPM and runtime ini_set. + +~~~php +display_errors = Off +~~~ + +**Verification:** Parse/database/type errors yield expected public responses while private diagnostics remain. + +**Reference:** [primary source](https://www.php.net/manual/en/errorfunc.configuration.php). + + + +## PHP-XSS. Raw data reaches HTML, attributes or JavaScript + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'echo|print|htmlspecialchars|json_encode| +Expanded example and limitations + +```php +// Vulnerable with untrusted title: the browser interprets it as markup. +echo '

' . $title . '

'; +``` + +**Patch for HTML text content:** + +```php +echo '

' . htmlspecialchars($title, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8') . '

'; +``` + +Validate $title as a string first. Store original text and encode on output to avoid cumulative double escaping during edits. This is not JavaScript/CSS encoding or URL validation; those contexts need different mechanisms. Intentionally supported HTML requires sanitizing the permitted subset rather than turning all markup into text. + +**Check:** <, >, &, quotes and Unicode render as text; existing records and save/open/edit cycles preserve original content. + + + + + +## PHP-SESSION. Session fixation, strict mode and stale state + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'session_start|session_regenerate_id|session.use_strict_mode|session_id' . +~~~ + +Trace externally supplied session IDs, login-time regeneration and role storage. + +**Vulnerable example:** + +An unknown external ID is accepted and remains unchanged after login. + +**Fix:** session.use_strict_mode, supported regeneration with concurrent requests considered, server-derived roles and consistent Secure/HttpOnly/SameSite settings. + +**Verification:** The old ID cannot authorize; normal parallel requests retain state. + +**Reference:** [primary source](https://www.php.net/manual/en/session.security.ini.php). + + + +## PHP-WRAPPERS. Filesystem APIs accept URLs or wrappers + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'file_get_contents|fopen|copy\(|file_exists|is_file|phar|stream_context' . +~~~ + +Determine whether each API accepts a path or stream URL; check installed PHP version and required wrappers. + +**Vulnerable example:** + +Users select a scheme/local path instead of an allowed object; open_basedir is not a complete sandbox. + +**Fix:** Server-side paths derived from authorized IDs; a separate policy-constrained HTTP client for URLs; no client-selected wrapper. + +**Verification:** Valid files load; external URLs, foreign files and unsupported schemes never reach the operation. + + + +## PHP-EXTRACT. extract overwrites local variables + +**Search:** scanner rule PHP-EXTRACT. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain PHP-EXTRACT` for details. Regex: any extract(...); trusted template contexts need manual classification. + +Additional manual search for forms outside automatic coverage: + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'extract\(|parse_str|\$\$|GLOBALS|register_globals' . +~~~ + +Compare imported keys with authorization/config variable names; two-argument parse_str has a different risk from its historical behavior. + +**Vulnerable example:** + +`extract($_REQUEST)` overwrites locals, or `$$key` selects a sensitive variable. + +**Fix:** Read explicit allowed fields. EXTR_SKIP reduces overwrites but does not replace schema/type and new-name controls. + +**Verification:** Input is_admin/owner/config cannot alter access; approved values retain types. + +**Reference:** [primary source](https://www.php.net/manual/en/function.extract.php). + +**Scanner example before:** + +~~~php +extract($_POST); +if ($is_admin) { show_private_data(); } +~~~ + +**Fix template:** + +~~~php +$display_name = validate_display_name($_POST['display_name'] ?? ''); +~~~ + +Primary documentation: [reference 1](https://www.php.net/manual/en/function.extract.php). + + + +## PHP-SERIALIZE-MAGIC. Magic methods and trust in stored data + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e '__wakeup|__unserialize|__destruct|__toString|unserialize' . +~~~ + +Trace PHP-OBJECT sinks to reachable classes and side effects; a database is not trusted merely because client input was stored there. + +**Vulnerable example:** + +A deserialized object performs file/network operations before its result is checked. + +**Fix:** DTOs without type selection or side effects; separate compatible migration, not fallback to an unsafe parser. + +**Verification:** Unknown types have no effects; legitimate legacy formats follow the migration plan. + + + +## PHP-CSRF. Cookies authorize mutations without CSRF protection + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'csrf|POST|PUT|DELETE|REQUEST_METHOD|SameSite' . +~~~ + +Review forms and cookie-authenticated JSON endpoints, middleware exceptions and Origin/Referer policies. + +**Vulnerable example:** + +The browser automatically attaches a cookie to state-changing requests from another context. + +**Fix:** Framework CSRF tokens and architecture-appropriate origin checks. SameSite supplements, not replaces, server-side checks. Bearer APIs have a different threat context. + +**Verification:** Wrong/missing tokens fail; normal forms and supported API clients work. + + + +## PHP-REGEX-ERROR. preg_match errors become permission + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'preg_match|preg_last_error|preg_replace' . +~~~ + +Distinguish false, 0 and 1; find negated results and regex limits. + +**Vulnerable example:** + +An engine error on long input enters the 'prohibited content not found' branch. + +**Fix:** Compare results strictly against 1/0/false according to meaning; fail closed on errors and bound length/complexity. + +**Verification:** Match, no-match and engine errors produce distinct expected responses; normal Unicode remains supported. + +**Reference:** [primary source](https://www.php.net/manual/en/function.preg-match.php). + + + +## PHP-XML-FLAGS. XML entity substitution or DTD enabled + +**Search:** scanner rule PHP-XML-FLAGS. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain PHP-XML-FLAGS` for details. Regex: LIBXML_NOENT/DTDLOAD/DTDATTR/DTDVALID and substituteEntities/resolveExternals=true. Numeric ini/database masks are not decoded; inspect bits against runtime constants. + +**Vulnerable example:** NOENT substitutes entities; NONET alone does not prevent local-file access. + +~~~php +$doc->loadXML($xml, LIBXML_NOENT | LIBXML_DTDLOAD | LIBXML_NONET); +~~~ + +**Fix:** Disable entity substitution/external DTD loading, bound input and check libxml version. Use LIBXML_NO_XXE where supported; NONET alone is insufficient. + +~~~php +$doc->resolveExternals = false; +$doc->substituteEntities = false; +$doc->loadXML($boundedXml, LIBXML_NONET); +~~~ + +**Verification:** Ordinary XML works; entities/DTD read no files or network and nesting/size are limited. + +Primary documentation: [reference 1](https://www.php.net/manual/en/libxml.constants.php), [reference 2](https://github.com/enowars/enowars7-service-oldschool#vulnerabilities). + + + +## PHP-TEMPLATE. Template built from dynamic text + +**Search:** scanner rule PHP-TEMPLATE. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain PHP-TEMPLATE` for details. Regex: createTemplate($...) and Smarty display/fetch with eval: or string:. Inspect variable loaders, custom filters and database templates. + +**Vulnerable example:** When user data becomes template source, users gain the template engine's capabilities. + +~~~php +$template = $twig->createTemplate($profileText); +echo $template->render($vars); +~~~ + +**Fix:** Separate trusted template source from values; user templates need explicit sandbox/loader/function/resource policy. + +~~~php +echo $twig->render('profile.html.twig', ['about' => $profileText]); +~~~ + +**Verification:** Profile template expressions remain data; private templates/files are unavailable. + +Primary documentation: [reference 1](https://twig.symfony.com/doc/3.x/api.html#loading-templates-from-a-string). + + + +## PHP-CURL-TLS. cURL certificate or hostname checks disabled + +**Search:** scanner rule PHP-CURL-TLS. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain PHP-CURL-TLS` for details. Regex: CURLOPT_SSL_VERIFYPEER=false/0 and CURLOPT_SSL_VERIFYHOST=false/0/1 in arguments/setopt_array. Variable values are not evaluated. + +**Vulnerable example:** Disabling server validation permits substitution of outbound HTTPS results. + +~~~php +curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); +curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); +~~~ + +**Fix:** Verify peer and hostname with the trusted CA; use VERIFYHOST=2, not historical ambiguous 1. + +~~~php +curl_setopt_array($ch, [CURLOPT_SSL_VERIFYPEER => true, CURLOPT_SSL_VERIFYHOST => 2, CURLOPT_CAINFO => $trustedCA]); +~~~ + +**Verification:** Correct CA/host works; wrong CA/host and expiry fail without fallback. + +Primary documentation: [reference 1](https://www.php.net/manual/en/function.curl-setopt.php). + + + +## PHP-URL-INCLUDE. Remote resource inclusion enabled + +**Search:** scanner rule PHP-URL-INCLUDE. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain PHP-URL-INCLUDE` for details. Regex: allow_url_include=On/1/true in ini/config/assignment. Review runtime overrides and effective include paths separately. + +**Vulnerable example:** URL include increases the consequences of controlling an include/require path. + +~~~config +allow_url_include = On +~~~ + +**Fix:** Disable allow_url_include in the effective SAPI config; select include paths from a closed server-side map. + +~~~config +allow_url_include = Off +~~~ + +**Verification:** Normal modules load; client URLs cannot become executable code. + +Primary documentation: [reference 1](https://www.php.net/manual/en/filesystem.configuration.php#ini.allow-url-include). + + + +## PHP-SESSION-CONFIG. Weakened PHP session configuration + +**Search:** scanner rule PHP-SESSION-CONFIG. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain PHP-SESSION-CONFIG` for details. Regex: explicit unsafe use_strict_mode/use_only_cookies/use_trans_sid values. Missing settings and ini_set argument forms need manual review. + +**Vulnerable example:** Attacker-selected session IDs and IDs in URLs enable fixation or leakage. + +~~~config +session.use_strict_mode = 0 +session.use_only_cookies = 0 +session.use_trans_sid = 1 +~~~ + +**Fix:** Enable strict mode and cookie-only transport, disable URL rewriting and regenerate IDs at login; review custom handlers/cookies. + +~~~config +session.use_strict_mode = 1 +session.use_only_cookies = 1 +session.use_trans_sid = 0 +~~~ + +**Verification:** Unknown fixed IDs fail, login changes the ID, URLs/logs contain no IDs and sessions work. + +Primary documentation: [reference 1](https://www.php.net/manual/en/session.configuration.php). + + + +## PHP-MASS-ASSIGN. Array keys choose columns and privileges + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e '\$_(POST|GET|REQUEST)|array_keys|array_merge|profileData|UPDATE|SET|fill\(|update\(' . +~~~ + +Trace keys as well as values from requests into UPDATE/ORM and owner/admin/association assignment. Review nested fields and numeric indices. + +**Vulnerable example:** SQL values are parameterized but column names come from request keys; role fields or relationships to foreign objects are updated wholesale. + +**Fix:** Explicitly map allowed input fields to fixed columns and types. Check privileges, owners and relationships separately; placeholders do not escape SQL identifiers. + +**Verification:** Unknown columns, administrative fields and foreign relationships fail without mutation; allowed fields persist. + +Reference: [OWASP Mass Assignment](https://cheatsheetseries.owasp.org/cheatsheets/Mass_Assignment_Cheat_Sheet.html). The explanation and adaptation recipe were written for this catalog. + +**A/D variant:** Oldschool's mass update could change an administrative relationship; column names also entered SQL without restriction. [Author description](https://github.com/enowars/enowars7-service-oldschool#vulnerabilities). + + + +## PHP-LDAP-FILTER. LDAP filter concatenates a PHP variable + +**Search:** scanner rule PHP-LDAP-FILTER. Use `--explain PHP-LDAP-FILTER` for the exact detector contract. Regex with lexical exclusions: ldap_search/list/read with simple first two arguments and a string concatenated directly with a variable as the third argument. Variables may already be escaped; prebuilt filters and interpolation need manual review. + +**Vulnerable example:** + +~~~php +ldap_search($conn, $base, '(uid=' . $name . ')'); +~~~ + +**Fix:** Escape values for LDAP filter context, not DN context; keep attribute names and search scope trusted. + +~~~php +$filter = '(uid=' . ldap_escape($name, '', LDAP_ESCAPE_FILTER) . ')'; +ldap_search($conn, $base, $filter); +~~~ + +**Verification:** LDAP metacharacters in a value do not widen results; authorized lookups work. + +[Primary reference 1](https://www.php.net/manual/en/function.ldap-escape.php) diff --git a/docs/vulnerabilities/python-RU.md b/docs/vulnerabilities/python-RU.md new file mode 100644 index 0000000..c4f8544 --- /dev/null +++ b/docs/vulnerabilities/python-RU.md @@ -0,0 +1,1682 @@ + + +# Python: поиск и исправление + +[English](python.md) | Русский + +[Вся база](README-RU.md) · [Сканер](../offline-scanner-RU.md) · [Проверка патча](../patch-validation-RU.md) + +40 разделов. Формат: **Поиск → Уязвимый вариант → Исправление → Проверка**. +Команды `rg` выполняются в корне локальной копии сервиса и только читают файлы. Субъект/владелец определяется по проверенной сессии, а не данным запроса. Примеры нужно адаптировать к реальным API и контракту. + +Автоматические находки — ограниченные синтаксические сигналы для проверки. AST-анализ не разрешает типы и не отслеживает данные между функциями; regex не заменяет парсер языка. Комментарии, строки и одноимённые пользовательские API могут давать совпадения. Проверьте фактическое исполнение, входные данные, авторизацию и границы доверия. + + + +## Содержание + +- [PY-EVAL — Выполнение текста как Python](#py-eval) +- [PY-SHELL — Shell в Python](#py-shell) +- [PY-DESERIALIZE — Десериализация объектов Python](#py-deserialize) +- [PY-YAML — YAML с потенциально опасным Loader](#py-yaml) +- [PY-SQL — SQL собирается строковым выражением](#py-sql) +- [PY-ORM-BOOL — Python and/or в ORM](#py-orm-bool) +- [PY-TEMPLATE — Динамический исходник шаблона](#py-template) +- [PY-TLS — TLS verify=False](#py-tls) +- [PY-DEBUG — Веб-отладчик Python](#py-debug) +- [PY-JWT — Подпись JWT отключена](#py-jwt) +- [PY-ARCHIVE — Распаковка требует проверки путей](#py-archive) +- [PY-TEMP — Неатомарное имя временного файла](#py-temp) +- [PY-XML — XML с разрешёнными сущностями](#py-xml) +- [PY-WEAK-HASH — MD5/SHA1: проверить назначение](#py-weak-hash) +- [PY-RNG — Обычный PRNG в возможном секрете](#py-rng) +- [PY-FILE — Динамический путь выдачи файла](#py-file) +- [PY-URL — Динамический исходящий URL](#py-url) +- [PY-CRC — CRC/Adler как возможная защита целостности](#py-crc) +- [PY-XPATH — Строковая сборка XPath](#py-xpath) +- [PY-UUID-BYTES — Граница UUID bytes/bytes_le](#py-uuid-bytes) +- [PY-ASSERT-AUTH — Проверка доступа через assert](#py-assert-auth) +- [PY-DJANGO-HOSTS — Любой host разрешён через ALLOWED_HOSTS Django](#py-django-hosts) +- [PY-HTML-SAFE — Явное отключение HTML-экранирования](#py-html-safe) +- [PY-MASS-ASSIGN — Поля запроса становятся атрибутами модели](#py-mass-assign) +- [PY-DECORATOR-AUTH — Маршрут зарегистрирован до auth-декоратора](#py-decorator-auth) +- [PY-ASYNC-CONTEXT — Глобальный current_user между async-запросами](#py-async-context) +- [PY-REDIRECT — Открытый redirect и доверие next](#py-redirect) +- [PY-PASSWORD-HASH — Быстрый digest вместо хранения пароля](#py-password-hash) +- [PY-ZIP-LIMITS — Архив: traversal, symlink и распаковочный объём](#py-zip-limits) +- [PY-JSON-DUPLICATES — Разные парсеры выбирают разные повторные ключи](#py-json-duplicates) +- [PY-CACHE-KEY — Коллизии ключей кэша авторизации](#py-cache-key) +- [PY-JWT-DEPENDENCY — Уязвимая зависимость проверки JWT](#py-jwt-dependency) +- [PY-CHALLENGE-STATE — Challenge раскрывается до фиксации commitment](#py-challenge-state) +- [PY-SSL-CONTEXT — Отключённая проверка TLS-контекста](#py-ssl-context) +- [PY-CSRF-EXEMPT — Исключение Django view из CSRF](#py-csrf-exempt) +- [PY-JWT-ALGORITHMS — Алгоритм JWT берётся из выражения](#py-jwt-algorithms) +- [PY-JWT-CLAIMS — Проверки срока и адресата JWT отключены](#py-jwt-claims) +- [PY-REGEX-DYNAMIC — Динамический шаблон регулярного выражения](#py-regex-dynamic) +- [PY-AUTH-DECORATOR — Маршрут Flask регистрируется до защиты login_required](#py-auth-decorator) +- [PY-LOG-CREDENTIALS — Значение, похожее на credential, напрямую передаётся в logging](#py-log-credentials) + + + + + +## PY-EVAL. Выполнение текста как Python + +**Поиск:** скрипт, правило PY-EVAL. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain PY-EVAL. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API. + +**Уязвимый вариант:** + +~~~python +eval(payload) +~~~ + +**Исправление:** Для данных — JSON + схема; для DSL — ограниченный парсер. Не переносить код в другой eval. + +~~~python +import json +value = json.loads(payload) +if not isinstance(value, dict): + raise ValueError('object required') +~~~ + +**Проверка:** Допустимый документ читается; выражения Python не исполняются; есть лимит размера. + + + + + +## PY-SHELL. Shell в Python + +**Поиск:** скрипт, правило PY-SHELL. Запуск: python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain PY-SHELL. AST: shell=True через явный аргумент или inline **dict, shell helpers, буквальный argv shell у subprocess и asyncio.create_subprocess_exec. Значения argv из переменных, wrappers и сложное ветвление не вычисляются. + +**Уязвимый вариант:** + +~~~python +import subprocess +subprocess.run(command, shell=True) +~~~ + +**Исправление:** Фиксированный executable и список argv без shell; аргументы ограничить контрактом утилиты. + +~~~python +import subprocess +subprocess.run(['/usr/bin/file', '--', filename], shell=False, check=True, timeout=3) +~~~ + +**Проверка:** Спецсимволы остаются частью аргумента; опасные опции не проходят; штатная операция работает. + +
+Развёрнутый пример и ограничения + +**Узнать:** пользовательский текст склеивается в команду с `shell=True`. + +```python +# Vulnerable: data becomes part of an interpreter command. +digest = subprocess.check_output("printf '%s' '" + text + "' | sha256sum", shell=True) +``` + +**Патч для SHA-256 содержимого:** + + +```python +import hashlib + +def digest_text(text): + if not isinstance(text, str): + raise ValueError("text must be a string") + return hashlib.sha256(text.encode("utf-8")).hexdigest() +``` + +Сохранить ожидаемую кодировку и формат ответа. Оболочка `sha256sum` печатает +дополнительные поля/перевод строки; API мог их обрабатывать отдельно. Если +команда нужна для другой функции, см. [ограничения аргументов](README-RU.md). + +**Проверить:** известный digest, пустой текст, кавычки, перевод строки, Unicode; +отсутствие запуска внешней программы. Для хеширования паролей этот рецепт не подходит. + +
+ + + + + +## PY-DESERIALIZE. Десериализация объектов Python + +**Поиск:** скрипт, правило PY-DESERIALIZE. Запуск: python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain PY-DESERIALIZE. AST: pickle/dill/shelve, jsonpickle.decode/loads, joblib.load, pandas.read_pickle, Unpickler(...).load и простое локальное присваивание Unpickler. numpy.load и numpy.lib.format.read_array — только известный allow_pickle=True (именованный либо третий/второй позиционный аргумент соответственно). Учтены import aliases, простые scalar присваивания и inline **dict; defaults старых версий, mutable dict, wrappers и доверенность данных проверять вручную. + +**Уязвимый вариант:** + +~~~python +import pickle +value = pickle.loads(data) +~~~ + +**Исправление:** Для обмена обычными данными использовать JSON со схемой; +для числовых массивов NumPy сохранить `.npy`/`.npz` с `allow_pickle=False` +и проверкой dtype/формы/лимитов, как показано ниже. JSON не является универсальной +заменой этих форматов. Старые доверенные записи мигрировать отдельно; +не загружать клиентский pickle для конвертации. + +~~~python +import json +value = json.loads(data) # validate schema +~~~ + +**Проверка:** Ранее созданные данные читаются; неизвестные поля/типы и объектные массивы отклоняются; проверяются dtype, форма и объём данных. + +
+Развёрнутый пример и ограничения + +**Узнать:** pickle приходит из cookie, тела запроса, загрузки или строки в БД, +которую ранее мог записать клиент. Base64 не делает содержимое доверенным. + +```python +# Vulnerable with untrusted raw input: loading can execute code. +profile = pickle.loads(raw) +``` + +**Патч для простого обмена профилем**, если протокол уже допускает JSON +или согласован его совместимый переход: + + +```python +import json + +def decode_profile(raw): + value = json.loads(raw) + if not isinstance(value, dict) or set(value) != {"display_name"}: + raise ValueError("unexpected profile fields") + if not isinstance(value["display_name"], str): + raise ValueError("display_name must be a string") + return {"display_name": value["display_name"]} +``` + +HTTP-слой ограничивает размер тела до чтения; JSON-схема не ограничивает стоимость +парсинга автоматически. Роль и владелец определяются на сервере. Не оставлять +fallback в `pickle.loads` при ошибке JSON. Не переводить старые записи +небезопасным парсером, пока не доказано доверие к их происхождению. + +**Проверить:** корректное имя, Unicode и допустимое пустое значение; массив, +число и неизвестное служебное поле отклоняются; старые данные/клиенты совместимы. +Если checker требует прежний формат, замена парсера без плана миграции не готова к выкладке. + +
+ + +Объектный JSON тоже требует проверки: jsonpickle.decode не равен обычному json.loads. [jsonpickle](https://jsonpickle.readthedocs.io/en/latest/), [joblib.load](https://joblib.readthedocs.io/en/stable/generated/joblib.load.html) и [pandas.read_pickle](https://pandas.pydata.org/docs/reference/api/pandas.read_pickle.html) предупреждают о недоверенном входе. Установить происхождение сериализованного объекта до загрузки. + +**NumPy и объектные массивы.** `numpy.load` с `allow_pickle=True` разрешает +объектную десериализацию из файла. У `numpy.load` это третий позиционный аргумент, +у `numpy.lib.format.read_array` — второй. Установить, может ли клиент заменить +файл или запись в хранилище: расширение `.npy`/`.npz` доверие не доказывает. +[numpy.load](https://numpy.org/doc/stable/reference/generated/numpy.load.html), +[read_array](https://numpy.org/doc/stable/reference/generated/numpy.lib.format.read_array.html). + +~~~python +import numpy as np +values = np.load(upload_path, allow_pickle=True) +~~~ + +Для контракта числового `.npy` предложенный патч сохраняет формат массива: + +~~~python +import numpy as np +values = np.load(upload_path, allow_pickle=False) +if not isinstance(values, np.ndarray) or values.dtype.kind not in "iuf": + raise ValueError("numeric array required") +~~~ + +Проверить допустимые dtype, размерность и количество элементов по контракту. +Ограничить размер входа до загрузки; проверки уже созданного массива не заменяют +лимиты памяти. `allow_pickle=False` отклоняет прежние object arrays: сначала +спланировать миграцию доверенных данных, не включать небезопасный fallback. +Для `.npz` сохранять предусмотренный API контейнера и закрывать `NpzFile`; +пример выше предназначен только для одиночного числового `.npy`. + +Ручной поиск параметров и версии без импорта анализируемого проекта: + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'numpy|allow_pickle|read_array|requirements|poetry.lock|uv.lock' . +~~~ + +После совпадения связать импорт с вызовом, проверить lock-файл/метаданные +развёрнутого окружения и фактический источник файла. Сканер не определяет +версию, доверенность файла и значения словарей-переменных. Отсутствующий +`allow_pickle` не получает сигнал: значение по умолчанию проверить для версии. +Проверка патча: числовые массивы прежних dtype/формы читаются, object array +отвергается без выполнения его содержимого, oversized вход ограничен; старые +данные сохраняются по плану миграции. + + + + + +## PY-YAML. YAML с потенциально опасным Loader + +**Поиск:** скрипт, правило PY-YAML. Запуск: python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain PY-YAML. AST: yaml.load/load_all/unsafe_load/unsafe_load_all; SafeLoader/CSafeLoader/BaseLoader/CBaseLoader исключаются, включая import aliases, позиционный Loader и inline **dict. BaseLoader/CBaseLoader возвращают scalars строками; defaults конкретной версии, wrappers и лимиты ресурсов проверить вручную. + +**Уязвимый вариант:** + +~~~python +import yaml +value = yaml.load(data, Loader=yaml.Loader) +~~~ + +**Исправление:** safe_load, затем проверить типы/поля и ограничить размер/сложность документа. + +~~~python +import yaml +value = yaml.safe_load(data) # validate schema +~~~ + +**Проверка:** Обычный YAML работает; теги объектов и неожиданные структуры отвергаются. + +`yaml.BaseLoader` и `yaml.CBaseLoader` не создают произвольные Python-объекты +и не получают этот сигнал. Они превращают скаляры в строки: например, `false` +не становится `False`, а непустая строка в условии истинна. Такой loader допустим, +если приложение явно проверяет и преобразует строки согласно схеме; +заменять им `SafeLoader` во всём сервисе без проверки типов нельзя. +`SafeLoader`/`CSafeLoader` сохраняют стандартные YAML-типы, но не заменяют схему +и лимиты размера/вложенности. Включение собственных constructors проверить +отдельно. [PyYAML: loaders и типы](https://pyyaml.org/wiki/PyYAMLDocumentation). + +~~~python +import yaml +raw_settings = yaml.load(data, Loader=yaml.BaseLoader) +# Strings are expected; validate structure and convert fields separately. +~~~ + +Для wrappers, переопределений loader и версий: + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'yaml[.]|Loader|add_constructor|PyYAML|requirements|poetry.lock|uv.lock' . +~~~ + +Сопоставить вызов с импортом, выбранным loader и зарегистрированными +constructors; версию проверить по lock-файлу и метаданным развёртывания, +не импортируя сервис. Дополнительно проверить числа, булевы значения, даты, +пустые scalars и прежние документы на фактическом runtime. Если контракт уже +использует `BaseLoader`, отсутствие PY-YAML означает только отсутствие +известной опасной объектной загрузки, а не доказанную безопасность парсинга. + + + + + +## PY-SQL. SQL собирается строковым выражением + +**Поиск:** правило сканера PY-SQL. Подробности: `--explain PY-SQL`. AST: строковая сборка в SQL-вызовах и keywords, включая простые присваивания. Импортированные psycopg/psycopg2.sql SQL(не-литерал) и format/join с неизвестными или сырыми частями дают сигнал. Литеральный SQL с известными Identifier/Literal/Placeholder подавляет только этот сигнал, но не проверку прав на таблицу. Изменяемые объекты, wrappers, межфункциональные потоки и версии драйверов требуют ручного анализа. + +**Уязвимый вариант:** + +~~~python +db.execute("SELECT id FROM notes WHERE name=%s" % name) +~~~ + +**Исправление:** Параметры драйвера вместо подстановки; identifiers выбирать из фиксированного набора. Placeholder зависит от драйвера. + +~~~python +db.execute("SELECT id FROM notes WHERE name=?", (name,)) # sqlite3 +~~~ + +**Проверка:** Кавычки остаются данными; ограничения владельца и обычные запросы работают корректно. + +Фиксированный SQL не становится инъекцией от разделения на строковые литералы: + +~~~python +db.execute("SELECT " + "1") +db.execute(f"SELECT 1") +~~~ + +Такие формы не получают PY-SQL. Исключение ограничено литералами, их сложением +и f-строкой без подстановок; общего вычисления константных выражений нет. +Например, `.format()` остаётся синтаксическим сигналом и требует просмотра. +Исчезновение сигнала не проверяет право на объект, смысл фиксированного запроса +или настройки драйвера. Для пользовательских значений сохранить bind-параметры, +а не заменять один вид интерполяции другим. +[sqlite3: параметры запроса](https://docs.python.org/3/library/sqlite3.html#how-to-use-placeholders-to-bind-values-in-sql-queries). + +
+Развёрнутый пример и ограничения + +**Узнать:** `execute(f"...")`, `%`, `.format()` или конкатенация внутри SQL; +объект выбирается без проверки владельца. + +```python +# Vulnerable: client_id controls SQL; ownership is not constrained. +row = db.execute(f"SELECT body FROM notes WHERE id = '{client_id}'").fetchone() +``` + +**Минимальный патч для приватных заметок в sqlite3:** + + +```python +def read_private_note(db, user_id, note_id): + if user_id is None: + raise PermissionError("authentication required") + row = db.execute( + "SELECT body FROM notes WHERE id = ? AND owner_id = ?", + (note_id, user_id), + ).fetchone() + if row is None: + raise LookupError("not found") + return row[0] +``` + +Маркер `?` относится к sqlite3. В psycopg использовать `%s` **в SQL** и отдельный +кортеж значений; не применять Python-оператор `%` к запросу. Имена столбцов +не становятся безопасными от передачи как параметров значений. + +**Проверить:** владелец читает старую запись; другой пользователь и аноним — нет; +строковый ID с кавычкой обрабатывается как значение; список/экспорт соблюдают +тот же контроль. Если ID строго числовой, валидировать его по контракту. + +
+ +**Вариант A/D:** SQL blacklist не учитывает взаимодействие параметров. **ECSC / fonograph, автор.** Фильтр символов не предотвращал изменение +границ соседних строковых аргументов. +**Патч:** параметры драйвера вместо ручной сборки и blacklist. +**Тест:** кавычки/backslash в каждом параметре и их комбинации, обычный текст. +**Поиск:** PY-SQL; «есть sanitize» не снимает сигнал. + +[исходник/разбор 1](https://github.com/ECSC2024/ECSC2024-CTF-AD/blob/2a92e17384ad228072a84fb076a35066fe2ffeff/sources/fonograph/README.md); [исходник/разбор 2](https://github.com/ECSC2024/ECSC2024-CTF-AD/blob/2a92e17384ad228072a84fb076a35066fe2ffeff/sources/fonograph/backend/db.py); [исходник/разбор 3](https://github.com/ECSC2024/ECSC2024-CTF-AD/blob/2a92e17384ad228072a84fb076a35066fe2ffeff/sources/fonograph/backend/handlers.py). + + + + + +## PY-ORM-BOOL. Python and/or в ORM + +**Поиск:** скрипт, правило PY-ORM-BOOL. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain PY-ORM-BOOL. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API. + +**Уязвимый вариант:** + +~~~python +User.find(User.name == name and User.password == password) +~~~ + +**Исправление:** Композиция конкретной ORM: Beanie find(cond1, cond2), SQLAlchemy and_(...). Python and/or может отбросить условие. + +~~~python +User.find(User.name == name, User.password == password) # Beanie +~~~ + +**Проверка:** Оба предиката присутствуют в фактическом запросе; неверный пароль и доступ к чужому объекту отклоняются. Из четырёх пар верного/неверного имени и пароля только одна авторизуется. + +**Вариант A/D:** Python and вместо композиции Beanie. **Основание:** explorers CTF Cup, анализ кода и закреплённой зависимости +Beanie 1.23.6. Полная авторизация с MongoDB здесь не воспроизводилась. +Сканер на исходнике обнаружил PY-ORM-BOOL. + +~~~python +# before +User.find(User.username == name and User.password == password) +# after: Beanie accepts multiple criteria +User.find(User.username == name, User.password == password) +~~~ + +**Тест:** четыре комбинации верного/неверного имени и пароля, разные пользователи, +пустые значения; проверить фактически сформированный фильтр. Для другой ORM +использовать её API, а не копировать синтаксис. + +[исходник/разбор 1](https://github.com/C4T-BuT-S4D/ctfcup-2023-ad/blob/53d6b9b7369448ac6c5d7d8e9458f66b25271e8a/services/explorers/src/app/api.py); [исходник/разбор 2](https://github.com/C4T-BuT-S4D/ctfcup-2023-ad/blob/53d6b9b7369448ac6c5d7d8e9458f66b25271e8a/services/explorers/src/requirements.txt). + + + + + +## PY-TEMPLATE. Динамический исходник шаблона + +**Поиск:** скрипт, правило PY-TEMPLATE. Запуск: python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain PY-TEMPLATE. AST: render_template_string/from_string по имени метода, первый позиционный аргумент либо source=, включая import aliases и inline **dict. Нелитеральный исходник даёт review; кастомные одноимённые методы могут совпадать. Переменные dict, wrappers, тип окружения, доверие к исходнику и autoescape проверять вручную. + +**Уязвимый вариант:** + +~~~python +from flask import render_template_string +render_template_string(source=user_text) +~~~ + +**Исправление:** Фиксированный шаблон + параметры; проверить autoescape и контекст HTML/JS. + +~~~python +from flask import render_template_string +render_template_string(source='

{{ message }}

', message=user_text) +~~~ + +**Проверка:** Синтаксис шаблона показывается текстом; штатная верстка сохранена. + +`source=` у Flask `render_template_string` и Jinja `Environment.from_string` +задаёт именно исходник. Autoescape экранирует вывод, но не запрещает вычисление +выражений из недоверенного исходника. Параметр `message` в фиксированном шаблоне +остаётся данными. Проверить aliases импортов, wrappers и перенесённые в конфиг +шаблоны: сканер не устанавливает происхождение строки. +[Flask: render_template_string](https://flask.palletsprojects.com/en/stable/api/#flask.render_template_string), +[Jinja: from_string](https://jinja.palletsprojects.com/en/stable/api/#jinja2.Environment.from_string). + +
+Развёрнутый пример и ограничения + +**Узнать:** `render_template_string` или `Environment.from_string` получает +строку из запроса, в том числе после конкатенации с HTML. + +```python +# Vulnerable: the user controls template source. +return render_template_string(request.form["message"]) +``` + +**Патч Flask:** + +```python +from flask import render_template, request + +message = request.form["message"] +return render_template("message.html", message=message) +``` + +`templates/message.html` — фиксированный файл проекта: + +```html +

{{ message }}

+``` + +Не добавлять `|safe`. Flask по умолчанию включает autoescape для HTML-шаблонов; +проверить, что приложение его не отключило. Экранирование HTML и запрет компиляции +пользовательского шаблона — две разные границы. + +**Проверить:** строка `{{ 2 + 3 }}` выводится буквально, а не как результат +выражения; кавычки и HTML отображаются как текст; обычное сообщение сохранено. +Если функция сервиса именно редактор шаблонов, эта замена меняет контракт: +нужен отдельный дизайн допустимого языка, а не этот быстрый патч. + +
+ + + + + +## PY-TLS. TLS verify=False + +**Поиск:** скрипт, правило PY-TLS. Запуск: python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain PY-TLS. AST: verify=False, простая локальная скалярная переменная или inline **dict; учитывается порядок перезаписи ключей. Известны requests Session/session и httpx Client/AsyncClient, включая подходящие with/async with; requests Session.send и httpx.stream также распознаются. Общий поиск методов get/post/put/patch/delete/request остаётся эвристикой без доказанного типа. Переменные dict, свойства клиента, runtime config и wrappers не вычисляются. + +**Уязвимый вариант:** + +~~~python +import requests +requests.get(url, verify=False) +~~~ + +**Исправление:** Вернуть проверку TLS; при необходимости задать доверенный CA bundle. + +~~~python +import requests +requests.get(url, verify=True, timeout=3) +~~~ + +**Проверка:** Доверенный CA и правильное имя сервера принимаются; неверный, просроченный сертификат или сертификат другого host отклоняется без обходного режима. + +У `requests.Session.send` параметр `verify` действует на отправку подготовленного +запроса, в том числе внутри `with requests.session() as session`. +При использовании собственного CA сохранить нужную цепочку доверия; +не отключать проверку ради исправления ошибки сертификата. +Для prepared requests отдельно проверить способ объединения настроек окружения. +[Requests: подготовленные запросы и TLS](https://requests.readthedocs.io/en/latest/user/advanced/). + +~~~python +import requests +with requests.session() as session: + with session.send(prepared_request, verify=False, timeout=3) as response: + response.raise_for_status() +~~~ + +В таком вызове вернуть `verify=True` либо передать путь к принятому CA bundle. +Сканер проверяет явно переданный флаг, но не восстанавливает URL внутри +`prepared_request`, настройки адаптера и политику доверия всего приложения. + +У `httpx.Client`/`AsyncClient` проверка задаётся в конструкторе. `verify` +у клиентского `stream` не является допустимым параметром; модульный +`httpx.stream` принимает его. Пример сохранения потокового чтения с проверкой TLS: + +~~~python +import httpx +with httpx.Client(verify=True, timeout=3) as client: + with client.stream('GET', approved_url) as response: + response.raise_for_status() + # Read inside the context, bounded by the service contract. +~~~ + +Для своего CA использовать поддерживаемый текущим HTTPX `ssl.SSLContext`. +Контекстный блок закрывает ответ; сам TLS не проверяет допустимость адресата, +поэтому динамический `approved_url` сохраняет PY-URL до ручного просмотра. +[HTTPX: Client и stream](https://www.python-httpx.org/api/). + + + + + +## PY-DEBUG. Веб-отладчик Python + +**Поиск:** правило сканера PY-DEBUG. Подробности: `--explain PY-DEBUG`. AST: явные debug/use_debugger=True в run/run_simple (старый поиск по имени). Для известного импортированного Flask: DEBUG=True через config[index]/update/from_mapping и app.debug=True. Поддерживаются inline dict и aliases; пользовательские фабрики, runtime overrides, файлы конфигурации и ветвления требуют ручной проверки. + +**Уязвимый вариант:** + +~~~python +app.run(debug=True) +~~~ + +**Исправление:** Отключить debug/use_debugger в игровом процессе; сохранить приватную диагностику с удалением секретов из вывода. + +~~~python +app.run(debug=False) +~~~ + +**Проверка:** Ошибки без консоли и stack trace; все штатные маршруты доступны. + + + + + +## PY-JWT. Подпись JWT отключена + +**Поиск:** скрипт, правило PY-JWT. Запуск: python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain PY-JWT. AST: options.verify_signature=False, включая inline **kwargs/options и порядок перезаписи dict. Только jose.jwt.decode и jwt.decode_complete также связывают options с четвёртым позиционным аргументом; generic jwt.decode позиционно неоднозначен между версиями. Legacy verify=False сохраняется для generic jwt.decode, но не для двух известных современных API. *args, mutable dict, wrappers и настройки экземпляра вручную; явно дублированные positional/keyword algorithms/options не трактуются как исполнимый JWT-вызов. + +**Уязвимый вариант:** + +~~~python +import jwt +claims = jwt.decode(token, options={'verify_signature': False}) +~~~ + +**Исправление:** Проверять подпись, фиксированный алгоритм, назначение токена +и обязательные claims; существующий ключ — из защищённого конфига. Пример ниже +для PyJWT 2.x; у python-jose другой формат обязательных claims, см. +[PY-JWT-CLAIMS](#py-jwt-claims). + +~~~python +import jwt +claims = jwt.decode(token, key, algorithms=['HS256'], audience='service', options={'require': ['exp', 'sub', 'aud']}) +~~~ + +**Проверка:** Неверная подпись, срок и назначение отвергаются; совместимость старых сессий проверена. + +У известных `jose.jwt.decode` и `jwt.decode_complete` inline options могут быть +четвёртым позиционным аргументом: + +~~~python +from jose import jwt +claims = jwt.decode(token, key, ['HS256'], {'verify_signature': False}) +~~~ + +У обычного `jwt.decode` позиционный контракт неоднозначен без версии: +в PyJWT 1.7.1 третий аргумент — `verify`, четвёртый — `algorithms`, пятый — +`options`; в 2.10.1 algorithms/options занимают третью/четвёртую позиции. +Сканер не определяет установленный пакет или версию и не интерпретирует эти +позиции для общего `jwt.decode`. +[PyJWT 1.7.1](https://github.com/jpadilla/pyjwt/blob/1.7.1/jwt/api_jwt.py), +[PyJWT 2.10.1](https://github.com/jpadilla/pyjwt/blob/2.10.1/jwt/api_jwt.py). + +`verify=False` не отключает проверку в PyJWT 2.x `decode_complete`; +в python-jose 3.5.0 у `decode` такого аргумента нет, вызов завершается TypeError. +Эти две формы не получают PY-JWT только за legacy-аргумент. У общего +`jwt.decode(..., verify=False)` сигнал остаётся версионной эвристикой для старого +API. Реальное `options={'verify_signature': False}` продолжает обнаруживаться. +[python-jose 3.5.0: decode](https://github.com/mpdavis/python-jose/blob/3.5.0/jose/jwt.py). + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'decode_complete|jwt[.]decode|from jose|from jwt|import jwt|PyJWT|python-jose|verify_signature|options=|requirements|poetry.lock|uv.lock' . +~~~ + +После совпадения установить импорт, реальную версию по lock-файлу/метаданным, +позиции аргументов, параметры экземпляра и место использования результата. +Непроверенное чтение claims для диагностики не должно становиться авторизацией. +`decode_complete` возвращает структуру с `payload`, а не только claims: +при правке сохранить контракт возврата. Ошибка парсинга или TypeError не должна +включать fallback, принимающий токен без проверки. + +Семантика JWT в этих трёх разделах сверена по исходникам зафиксированных +версий; библиотеки JWT в этой проверке не запускались. Номера версий обозначают +проверенный API, а не рекомендацию устанавливать старую версию: для сервиса +сверить поддерживаемую версию, её исправления безопасности и контракт вызова. + + + + + +## PY-ARCHIVE. Распаковка требует проверки путей + +**Поиск:** скрипт, правило PY-ARCHIVE. Запуск: python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain PY-ARCHIVE. AST: любой extractall остаётся эвристикой (включая ZIP); extract — только у известных tarfile.open/TarFile/TarFile.open через import aliases, конструктор, простое присваивание или with/as. shutil.unpack_archive — только с известным format tar/gztar/bztar/xztar/zstdtar, включая третий позиционный аргумент. filter='data' или tarfile.data_filter (также import alias/inline **dict) снимает сигнал, но не доказывает безопасность. Неизвестный/custom filter требует review; формат по расширению, extraction_filter, версия, квоты, wrappers и сложный поток управления проверяются вручную. + +Сигнал при пропущенном `filter` требует просмотра версии и +`TarFile.extraction_filter`: начиная с Python 3.14 штатный default — `data`, +раньше он был эквивалентен `fully_trusted`. Переопределение на экземпляре, +классе или в подклассе меняет поведение. Даже безопасный default не подавляет +эвристику сканера. [tarfile: фильтры](https://docs.python.org/3/library/tarfile.html#extraction-filters). + +**Уязвимый вариант:** недоверенный tar извлекается без ограничения путей, +типов членов и UNIX-метаданных. + +~~~python +import tarfile +with tarfile.open(upload_path) as archive: + archive.extract(member, destination, filter='fully_trusted') +~~~ + +**Исправление:** Для архива данных на исправленном runtime явно применить +`data` или `tarfile.data_filter`. Это предложение для распаковки в новый +закрытый от чужой записи каталог; лимиты диска, памяти, CPU и числа файлов +настраиваются отдельно. Без поддержки фильтра нужен совместимый обновлённый +runtime: небезопасный fallback не является исправлением. + +~~~python +import tarfile +with tarfile.open(upload_path) as archive: + archive.extract(member, new_destination, filter=tarfile.data_filter) +~~~ + +Для `shutil` правило рассматривает только явно выбранный встроенный tar-формат: + +~~~python +import shutil +shutil.unpack_archive(upload_path, new_destination, format='gztar', filter='data') +~~~ + +`format='zip'` не получает этот сигнал; ZIP не принимает параметр `filter`. +Не переносить на ZIP приведённый патч. Формат из расширения, пользовательские +распаковщики и замена регистрации даже встроенного формата требуют просмотра +реальной функции. [shutil.unpack_archive](https://docs.python.org/3/library/shutil.html#shutil.unpack_archive). + +`data_filter` ограничивает выход за каталог и опасные типы/метаданные, но может +разрешать внутренние ссылки. Он не даёт изоляцию от гонки с другим процессом, +меняющим каталог, и не ограничивает распаковочный объём. Операции с архивами, +которым нужны владельцы, права UNIX или специальные файлы, требуют отдельной +политики совместимости. После ошибки возможен частичный результат: его нельзя +объявлять завершённой загрузкой или публиковать; новый каталог упрощает очистку. +[PEP 706: назначение и ограничения](https://peps.python.org/pep-0706/). + +Поддержка API ещё не означает наличие всех исправлений. Релизы от 1 октября +2026 — 3.10.22, 3.11.17, 3.12.15, 3.13.16 и 3.14.8 — включают исправления обходов +tar-фильтров; для дистрибутива проверить эквивалентные backports. +[Объявление Python](https://blog.python.org/2026/10/python-31022-31117/). + +**Проверка:** На фактическом исправленном runtime проверить обычные файлы, +требуемые внутренние ссылки и метаданные; выход за корень, внешние ссылки, +специальные файлы, повторы имён и превышение квот — по принятой политике. +После отказа сервис не использует неполный результат. Проверить отдельно +Linux/macOS и используемую файловую систему, если на них развёрнут сервис. +Исчезновение PY-ARCHIVE не заменяет эти проверки. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'tarfile|extractall|[.]extract[(]|unpack_archive|register_unpack_format|extraction_filter|data_filter|errorlevel|FROM python|requires-python' . +~~~ + +После совпадения установить импорт/тип архива, источник входа, формат, +переопределённый фильтр, обработку ошибок и доступ к каталогу назначения. +Версию и backports сверить по образу/метаданным развёртывания без импорта +целевого проекта. Общий поиск `extractall` также отмечает ZIP и неизвестные +объекты: это повод проверить конкретный API, а не доказанный tar traversal. + + + + + +## PY-TEMP. Неатомарное имя временного файла + +**Поиск:** скрипт, правило PY-TEMP. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain PY-TEMP. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API. + +**Уязвимый вариант:** + +~~~python +import tempfile +name = tempfile.mktemp() +~~~ + +**Исправление:** TemporaryFile/NamedTemporaryFile/mkstemp: работать с уже открытым файлом. + +~~~python +import tempfile +with tempfile.TemporaryFile() as output: + output.write(data) +~~~ + +**Проверка:** Параллельные запросы получают разные временные файлы, не делят данные и не могут перезаписать существующий файл или ссылку. + + + + + +## PY-XML. XML с разрешёнными сущностями + +**Поиск:** скрипт, правило PY-XML. Запуск: python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain PY-XML. AST: XMLParser по имени метода; lxml.etree.XMLPullParser/ETCompatXMLParser/iterparse — по разрешённому имени импорта, включая aliases. Сигнал только при известном resolve_entities=True, в том числе scalar переменная или inline **dict. Defaults, версия lxml, DTD, тип входа и wrappers проверяются вручную; сканер не определяет применимость CVE. + +**Уязвимый вариант:** + +~~~python +from lxml import etree +parser = etree.ETCompatXMLParser(resolve_entities=True) +~~~ + +**Исправление:** Если внешние сущности и DTD не нужны контракту, отключить +их загрузку и разрешение явно. `no_network=True` само по себе не запрещает +обращение к локальным файлам через сущности. + +~~~python +from lxml import etree +parser = etree.ETCompatXMLParser(resolve_entities=False, load_dtd=False, no_network=True) +~~~ + +Те же параметры проверить у `XMLPullParser` и `iterparse`. Когда штатному +формату нужны внутренние сущности, для поддерживающей это версии рассмотреть +`resolve_entities='internal'` и проверить лимиты. `False` может изменить дерево +и текст документа; выбор режима должен сохранять нужные операции сервиса. + +**Проверка:** Обычный XML и используемые внутренние сущности обрабатываются +по контракту; внешняя сущность с локальным URI и сетевым URI не раскрывает данные +и не вызывает обращения наружу. Проверить custom resolvers, последующую +обработку дерева и лимиты объёма/вложенности: создание парсера само по себе +не доказывает, что именно его передают всем точкам разбора. + +Для вызовов без явной настройки и версионных defaults требуется ручная проверка: + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'lxml|XMLParser|XMLPullParser|ETCompatXMLParser|iterparse|resolve_entities|requirements|poetry.lock|uv.lock' . +~~~ + +Сопоставить импорт, API и версию из lock-файла/метаданных развёртывания, затем +проследить путь недоверенного XML. В lxml до 6.1 `iterparse` и +`ETCompatXMLParser` по умолчанию разрешали внешние сущности и могли читать +локальные файлы; исправление 6.1.0 изменило default на `'internal'`. +Обновление не исправляет явное `resolve_entities=True`. Сканер ищет явную +опасную настройку и не устанавливает наличие CVE по версии. +[Advisory GHSA-vfmq-68hx-4jfw / CVE-2026-41066](https://github.com/lxml/lxml/security/advisories/GHSA-vfmq-68hx-4jfw). + + + + + +## PY-WEAK-HASH. MD5/SHA1: проверить назначение + +**Поиск:** скрипт, правило PY-WEAK-HASH. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain PY-WEAK-HASH. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API. + +**Уязвимый вариант:** + +~~~python +import hashlib +digest = hashlib.md5(password) +~~~ + +**Исправление:** Пароли — password KDF, целостность с секретом — HMAC. Обычный checksum не обязательно требует изменения. Параметры KDF подобрать под нагрузку. + +~~~python +import hashlib +digest = hashlib.scrypt(password, salt=salt, n=16384, r=8, p=1) +~~~ + +**Проверка:** Есть версия формата/миграция старых паролей; стоимость не нарушает SLA. + + + + + +## PY-RNG. Обычный PRNG в возможном секрете + +**Поиск:** скрипт, правило PY-RNG. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain PY-RNG. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API. + +**Уязвимый вариант:** + +~~~python +import random +token = str(random.getrandbits(128)) +~~~ + +**Исправление:** Для токенов и секретов использовать secrets или поддержанный криптографический генератор с достаточной энтропией; обрабатывать ошибки генератора. Публичную случайность отделить от секретов. Симуляция на random может быть корректной. + +~~~python +import secrets +token = secrets.token_urlsafe(32) +~~~ + +**Проверка:** Нет предсказуемого резервного генератора; формат токена и сессии остаются совместимыми. + + + + + +## PY-FILE. Динамический путь выдачи файла + +**Поиск:** скрипт, правило PY-FILE. Запуск: python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain PY-FILE. AST: send_file по имени метода, первый позиционный аргумент либо path_or_file=, включая import aliases и inline **dict. Нелитеральный путь даёт review и после безопасного поиска owned record; кастомный одноимённый метод может совпадать. Авторизацию, файловый корень, ссылки, wrappers и переменные dict проверить вручную. + +**Уязвимый вариант:** + +~~~python +from flask import send_file +result = send_file(path_or_file=user_path) +~~~ + +**Исправление:** Серверный путь по ID после проверки владельца; для имени — разрешённый корень и политика ссылок. Сигнал может остаться после исправления. + +~~~python +from flask import send_file +record = load_owned_file(file_id, current_user.id) +result = send_file(path_or_file=record.storage_path) +~~~ + +**Проверка:** Чужой ID, выход из каталога и внешние symlinks отклоняются; собственные старые файлы доступны. + +`path_or_file=` соответствует современному Flask API. `load_owned_file` в примере +обозначает обязательную реализованную проверку владельца и получение серверного +пути; одного переименования переменной недостаточно. Этот исправленный вызов +сохраняет PY-FILE, поскольку сканер не проверяет авторизацию, ссылки и гонку +подмены файла. Также проверить, что динамический аргумент не является уже +открытым доверенным файловым объектом: API допускает и такую штатную форму. +[Flask: send_file](https://flask.palletsprojects.com/en/stable/api/#flask.send_file). + + + + + +## PY-URL. Динамический исходящий URL + +**Поиск:** скрипт, правило PY-URL. Запуск: python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain PY-URL. AST: requests/httpx и urlopen; известные Session/session, requests.sessions.Session/session, Client/AsyncClient через import aliases, локальное присваивание или непосредственный конструктор. with/as поддержан для requests Session и httpx Client, async with/as — для httpx AsyncClient; факты присваиваний инвалидируются после области. request(method,url), httpx.stream и Client/AsyncClient.stream(method,url) используют второй аргумент либо url=. Литерал URL не сигналит; wrappers, возвращённые клиенты, mutable config и сложные связи вручную. Проверки URL/DNS/redirect не анализируются. + +**Уязвимый вариант:** + +~~~python +import requests +response = requests.get(user_url) +~~~ + +**Исправление:** Фиксированный разрешённый endpoint либо явная политика назначения, схемы и порта; проверка разрешённых DNS-адресов и каждого redirect; timeout и лимит ответа. + +~~~python +import requests +response = requests.get('https://api.example.invalid/status', timeout=3, allow_redirects=False) +~~~ + +**Проверка:** Требуемые источники работают; запрещённые схемы/внутренние адреса/редиректы отвергаются приложением. + +Переход к context API и потоковому чтению не меняет источник URL: + +~~~python +import httpx +async def fetch(user_url): + async with httpx.AsyncClient(timeout=3, follow_redirects=False) as client: + async with client.stream('GET', user_url) as response: + response.raise_for_status() + # Bound response reads; the URL has not been authorized yet. +~~~ + +Исправление выбирается по контракту: фиксированный серверный endpoint, как +выше, или проверенный динамический адрес с политикой схемы, host, порта, +пути и redirect. Динамический URL из allowlist всё равно получает PY-URL: +сканер не доказывает качество этой проверки. Литерал URL не получает сигнал, +но его наличие не доказывает безопасность DNS, proxy или последующих redirect. + +Потоковый ответ нужно закрывать и при превышении лимита, отмене операции и +ошибке чтения. `async with client.stream(...)` закрывает его при выходе; +в ручном streaming API нужен гарантированный `aclose()`. Для долгоживущего +сервиса сохранить жизненный цикл и переиспользование клиента, а не создавать +новый пул в каждой итерации. [HTTPX: async streaming](https://www.python-httpx.org/async/). + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'requests|httpx|urlopen|base_url|proxies|proxy=|trust_env|allow_redirects|follow_redirects|HTTP_PROXY|HTTPS_PROXY|NO_PROXY' . +~~~ + +После совпадения проследить вход до полного URL, соединить client/base_url, +proxy и настройки окружения. Проверить фактическое разрешение адреса и каждый +переход, доступ к внутренним адресам, перенос credentials между адресатами, +таймауты и лимит ответа. `timeout` отдельной операции не всегда ограничивает +всю цепочку. Объекты Request/PreparedRequest, возвращённые фабрикой клиенты, +переопределённые transports и межфункциональные связи требуют ручного анализа. +Эту проверку выполнять в разрешённом тестовом окружении; сканер сеть не использует. + +**Вариант A/D:** Проверили hostname, но приняли клиентский URL целиком. **FAUST / quickr-maps, код.** Строка server вставляется в URL, проверяется +лишь hostname, затем URL передаётся requests. Возможные изменения path/query +остаются отдельной границей проверки. + +**Патч:** клиент выбирает символическое имя из таблицы серверов; весь URL, +маршрут и owner строит сервер. **Тест:** разделители URL не меняют маршрут, +порт или субъект. **Поиск:** PY-URL, включая исправленное обнаружение url=. +Полная цепочка обхода здесь не воспроизводилась. + +[исходник/разбор 1](https://github.com/fausecteam/faustctf-2024-quickr-maps/blob/fe77e8f1926117b788108f7614271f3133a1f607/location_portal/src/main.py); [исходник/разбор 2](https://github.com/fausecteam/faustctf-2024-quickr-maps/blob/fe77e8f1926117b788108f7614271f3133a1f607/private_loc/main.go). + + + + + +## PY-CRC. CRC/Adler как возможная защита целостности + +**Поиск:** скрипт, правило PY-CRC. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain PY-CRC. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API. + +**Уязвимый вариант:** + +~~~python +import zlib +tag = zlib.crc32(payload) +~~~ + +**Исправление:** Для аутентичности HMAC/подпись; для ID — уникальный серверный ключ и ownership. Обычный checksum может оставаться CRC. + +~~~python +import hmac +tag = hmac.digest(key, payload, 'sha256') +~~~ + +**Проверка:** Изменённое сообщение без ключа не принимается; договорённость о формате и старые данные сохранены. + + + + + +## PY-XPATH. Строковая сборка XPath + +**Поиск:** скрипт, правило PY-XPATH. Запуск: python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain PY-XPATH. AST: xpath/XPath по имени метода и строковое выражение в первом аргументе, включая простое присваивание. Строковые литералы, их Add-конкатенация и f-строки без FormattedValue не сигналят; %, format и f-строки с подстановкой остаются review. Произвольные выражения не вычисляются; wrappers, переменные XPath и доверенность данных проверяются вручную. + +**Уязвимый вариант:** + +~~~python +node.xpath("//user[name='%s']" % username) +~~~ + +**Исправление:** Связать значение переменной XPath в поддержанном API; не собирать синтаксис кавычками. Само выражение должно быть фиксированным. + +~~~python +node.xpath("//user[name=$name]", name=username) +~~~ + +**Проверка:** Кавычки/скобки — данные, область поиска и ownership не расширяются. + +Фиксированное выражение, разделённое на литералы, не получает PY-XPATH: + +~~~python +node.xpath("//" + "user") +node.xpath(f"//user") +~~~ + +Исключены только распознанные строки без подставляемых значений, их сложение +и f-строки без подстановок. Сканер не выполняет XPath и не вычисляет произвольные +Python-выражения. Переменные XPath связывают данные; названия осей, узлов и сам +текст выражения должны задаваться серверной политикой. Указать правильный API +для конкретной библиотеки: пример с `name=` относится к lxml. +[lxml: параметры XPath](https://lxml.de/xpathxslt.html#the-xpath-method). + + + + + +## PY-UUID-BYTES. Граница UUID bytes/bytes_le + +**Поиск:** скрипт, правило PY-UUID-BYTES. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain PY-UUID-BYTES. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API. + +**Уязвимый вариант:** + +~~~python +import uuid +value = uuid.UUID(bytes_le=wire_bytes) +~~~ + +**Исправление:** Согласовать wire-формат между всеми языками/кэшем/БД; canonical text либо документированный порядок 16 байт. Наличие bytes_le само по себе нормально. + +~~~python +import uuid +value = uuid.UUID(wire_text) # canonical text contract +~~~ + +**Проверка:** Одинаковые known vectors дают один UUID в обеих средах; round-trip и старые ссылки сохранены. + +**Вариант A/D:** UUID меняет смысл между C# и Python. **RuCTF / hyperborea-legends, автор.** Разный порядок байтов UUID в кэше +и основном пути менял объект, к которому относились права. + +**Патч:** один документированный wire-формат и преобразование на границе; +предпочтительно canonical text, если совместим с протоколом. +**Тест:** несимметричные known vectors, round-trip между языками и старые записи. +**Поиск:** PY-UUID-BYTES, CS-GUID-BYTES — только места для проверки. + +[исходник/разбор 1](https://github.com/HackerDom/ructf-2023/blob/0cc333e44f2ba6908ff6c5d613146e3b00173315/writeups/hyperborea-legends/README.md). + + + + + +## PY-ASSERT-AUTH. Проверка доступа через assert + +**Поиск:** скрипт, правило PY-ASSERT-AUTH. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain PY-ASSERT-AUTH. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API. + +**Уязвимый вариант:** + +~~~python +assert note.owner_id == current_user.id +~~~ + +**Исправление:** Явная ветвь отказа, работающая при -O; не заменять обычные тестовые assert без причины. + +~~~python +if note.owner_id != current_user.id: + raise PermissionError('access denied') +~~~ + +**Проверка:** Чужой объект отклоняется и при обычном, и при оптимизированном запуске; своё действие работает. + + + + + +## PY-DJANGO-HOSTS. Любой host разрешён через ALLOWED_HOSTS Django + +**Поиск:** скрипт, правило PY-DJANGO-HOSTS. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain PY-DJANGO-HOSTS. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API. + +**Уязвимый вариант:** + +~~~python +ALLOWED_HOSTS = ["*"] +~~~ + +**Исправление:** Явные фактические имена/IP из контракта, включая checker. get_host вместо сырого Host; доверенные proxy-заголовки отдельно. + +~~~python +ALLOWED_HOSTS = ["service.internal"] +~~~ + +**Проверка:** Неизвестный Host отвергается; штатный host/checker работает. + +**Основание:** [первичный материал](https://docs.djangoproject.com/en/5.2/ref/settings/#allowed-hosts). + + + + + +## PY-HTML-SAFE. Явное отключение HTML-экранирования + +**Поиск:** скрипт, правило PY-HTML-SAFE. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain PY-HTML-SAFE. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API. + +**Уязвимый вариант:** + +~~~python +html = mark_safe(message) +~~~ + +**Исправление:** Передавать данные в autoescaped шаблон; для разрешённого HTML sanitizer по контракту. HTML escaping не защищает JS/URL-контекст. + +~~~python +html = message +~~~ + +**Проверка:** Кавычки и теги остаются текстом; штатное форматирование не потеряно. + +**Основание:** [первичный материал](https://docs.djangoproject.com/en/5.2/topics/security/). + + + + + +## PY-MASS-ASSIGN. Поля запроса становятся атрибутами модели + +**Поиск:** скрипт, правило PY-MASS-ASSIGN. Запуск: python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain PY-MASS-ASSIGN. AST: setattr с нелитеральным именем атрибута. **kwargs, setattr-wrapper, ORM update и конструкторы автоматически не покрыты; оставить ручной поиск ниже. + +Дополнительный ручной поиск для непокрытых форм: + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'setattr|__dict__|model_validate|update\(|request.json' . +~~~ + +Проследить список полей до ORM; найти owner/role/tenant и вложенные DTO. + +**Уязвимый вариант:** + +setattr(model, key, value) в цикле по клиентскому JSON применяет служебные поля. + +**Исправление:** Явный DTO разрешённых полей; запрет лишних полей по контракту, проверка типов во время выполнения, owner из сессии. + +**Проверка:** Частичный update работает; owner, role, вложенный объект и null не меняют права. + + +**Сигнал сканера — пример до:** + +~~~python +for field, value in payload.items(): + setattr(account, field, value) +~~~ + +**Шаблон исправления:** + +~~~python +account.display_name = validate_display_name(payload['display_name']) +~~~ + + + + + +## PY-DECORATOR-AUTH. Маршрут зарегистрирован до auth-декоратора + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e '@.*route|@.*get|@.*post|login_required|permission_required' . +~~~ + +Развернуть порядок применения декораторов и посмотреть функцию, реально сохранённую в router. + +**Уязвимый вариант:** + +Auth оборачивает локальное имя, но router уже хранит необёрнутую функцию. + +**Исправление:** Поставить auth внутрь route-регистрации либо использовать штатную dependency/policy фреймворка; проверить каждый HTTP-метод. + +**Проверка:** Запрос без сессии через реальный router отклоняется; прямой unit-вызов сам по себе недостаточен. + + + + + +## PY-ASYNC-CONTEXT. Глобальный current_user между async-запросами + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'global|current_user|ContextVar|threading.local|asyncio' . +~~~ + +Найти записи principal и await между записью и использованием; проверить reset ContextVar в finally. + +**Уязвимый вариант:** + +Общая переменная или thread-local обслуживает несколько coroutine одного потока. + +**Исправление:** Request-scoped объект/ContextVar с восстановлением токена; заданиям передавать явный проверенный контекст. + +**Проверка:** Два запроса с barrier и разные пользователи; исключение не оставляет чужой контекст. + + + + + +## PY-REDIRECT. Открытый redirect и доверие next + +**Поиск:** скрипт, правило PY-REDIRECT. Запуск: python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain PY-REDIRECT. AST: flask.redirect/werkzeug.utils.redirect с первым позиционным аргументом либо location=; django.shortcuts.redirect — с первым аргументом либо to=. Поддержаны import aliases и inline **dict; литерал или известное простое scalar значение не сигналит. Анализ доверия, wrappers, runtime kwargs, разрешения маршрутов и reverse-proxy redirects вручную. + +Дополнительный ручной поиск для непокрытых форм: + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'redirect\(|next|return_url|urljoin' . +~~~ + +Проследить построение Location: относительный путь не должен превращаться в network-path URL или иной origin. + +**Уязвимый вариант:** + +redirect(request.args["next"]) выбирает внешний адрес; проверка startswith("/") недостаточна. + +**Исправление:** Разрешённые внутренние маршруты/серверная карта, либо полноценный разбор origin и нормализация один раз. + +**Проверка:** Штатный переход работает; абсолютный URL, двойной slash, backslash и кодированные разделители отклоняются. + + +**Сигнал сканера — пример до:** + +~~~python +from flask import redirect +return_url = request.args['next'] +response = redirect(return_url) +~~~ + +**Шаблон исправления:** + +~~~python +from flask import redirect +response = redirect('/profile') +~~~ + +Первичная документация: [документация 1](https://docs.djangoproject.com/en/5.2/ref/utils/#django.utils.http.url_has_allowed_host_and_scheme). + +Именованные аргументы не меняют границу доверия: + +~~~python +from flask import redirect +response = redirect(location=request.args['next']) +~~~ + +~~~python +from django.shortcuts import redirect +response = redirect(to=request.GET['next']) +~~~ + +У Flask/Werkzeug это `location=`, у Django — `to=`. Django также принимает имя +view и объект с `get_absolute_url()`: проверить смысл цели и итоговый Location, +а не считать каждую динамическую цель внешним URL. При фиксированном маршруте +можно использовать `redirect(location='/profile')` во Flask или +`redirect(to='profile')` в Django, если такой именованный маршрут определён. +Сохранить требуемые параметры и поведение метода/status; навязанная замена +всех переходов одним маршрутом меняет контракт сервиса. +[Flask: redirect](https://flask.palletsprojects.com/en/stable/api/#flask.redirect), +[Django 5.2: redirect](https://docs.djangoproject.com/en/5.2/topics/http/shortcuts/#redirect). + +Динамическая цель после полноценной проверки остаётся сигналом. Сканер +не воспроизводит URLconf, `get_absolute_url`, нормализацию браузера или +effective Host/proxy; эти связи проверяются вручную на штатных переходах. + + + + + +## PY-PASSWORD-HASH. Быстрый digest вместо хранения пароля + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'password|hashlib|sha256|md5|pbkdf2' . +~~~ + +Найти регистрацию и login; сравнить salt, work factor, формат хранимой записи и ветвь миграции. + +**Уязвимый вариант:** + +sha256(password) без адаптивной стоимости позволяет быстро проверять догадки по утёкшей БД. + +**Исправление:** Поддержанный password hasher фреймворка/Argon2id или подходящий KDF; соль и параметры в записи, обновление после успешного входа. + +**Проверка:** Старый пользователь входит и мигрирует; неверный пароль не перезаписывает hash, длинный ввод ограничен. + + + + + +## PY-ZIP-LIMITS. Архив: traversal, symlink и распаковочный объём + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'zipfile|tarfile|extractall|extract\(' . +~~~ + +Помимо PY-ARCHIVE проверить список entries, фактический объём и filesystem boundary; фильтр путей не ограничивает объём. + +**Уязвимый вариант:** + +Архив пишет вне root либо исчерпывает диск при допустимом размере сжатого файла. + +**Исправление:** Отдельный каталог, проверка каждого пути/типа/ссылки, лимиты числа entries и реально распакованных байтов; атомарная публикация результата. + +**Проверка:** Обычный архив, абсолютный путь, ссылка наружу, множество entries, ошибка посередине и уборка временных данных. + +**Основание:** [первичный материал](https://cheatsheetseries.owasp.org/cheatsheets/File_Upload_Cheat_Sheet.html). + + + + + +## PY-JSON-DUPLICATES. Разные парсеры выбирают разные повторные ключи + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'json.loads|object_pairs_hook|orjson|signature|canonical' . +~~~ + +Сравнить парсер подписи, API и downstream: first/last duplicate, числа и нормализация ключей. + +**Уязвимый вариант:** + +Подпись проверяет одну интерпретацию owner, операция использует другую. + +**Исправление:** Единый канонический DTO до подписи и после чтения; явная политика дублей/чисел, reject неоднозначных документов. + +**Проверка:** Повторный owner, разный порядок, Unicode и большие числа дают одинаковый смысл или явный отказ. + + + + + +## PY-CACHE-KEY. Коллизии ключей кэша авторизации + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'cache|memoize|lru_cache' . +~~~ + +Сравнить полный ключ для двух пользователей и двух аргументов с одинаковым префиксом; найти усечение и инвалидацию. + +**Уязвимый вариант:** + +**Основание:** hermicache, авторский разбор RuCTF. Общий кэш строил строковый +ключ из функции и аргументов с усечением до 90 символов. + +**Искать:** конкатенация без однозначных границ, prefix/slice ключа, отсутствие +user/tenant/версии прав, совместное хранение публичных результатов и auth. + +**Исправление:** сериализовать полный типизированный кортеж, включить нужный контекст. +Успех проверки пароля не кэшировать общим ключом. Сохранить необходимый для SLA +вычислительный кэш. Пример принципа: + +~~~python +# before: cache[(function + str(arguments))[:90]] +# after: no truncation, no ambiguous concatenation +key = json.dumps([function, tenant_id, user_id, arguments], + separators=(",", ":"), ensure_ascii=False) +~~~ + +**Проверка:** две разные пары аргументов с одинаковым префиксом; разные пользователи; +смена прав/пароля; штатные повторные вычисления. + +**Вариант A/D:** Основание и версия: [исходник/разбор 1](https://github.com/HackerDom/ructf-finals-2023/blob/a7442769909e08c39716cb18d3d1c3a99324bbf8/writeups/hermicache/README.md). + +**Основание:** [первичный материал](https://github.com/HackerDom/ructf-finals-2023/blob/a7442769909e08c39716cb18d3d1c3a99324bbf8/writeups/hermicache/README.md). + + + + + +## PY-JWT-DEPENDENCY. Уязвимая зависимость проверки JWT + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'python-jwt|PyJWT|jwt|requirements|lock' . +~~~ + +Сопоставить distribution, lock, vendored-копию и реально загружаемую версию; python-jwt и PyJWT различаются. + +**Уязвимый вариант:** + +**Основание:** deutsches-flugzeug, авторский обзор saarCTF; advisory python-jwt +CVE-2022-39227. Ошибка находилась в зависимости, даже если вызов выглядел штатно. +**Искать:** точное имя distribution, lock/version, реально импортируемый модуль +и vendored-копии, несовпадение lock с образом. + +**Исправление:** исправленная совместимая версия с заранее подготовленными локальными +пакетами/образом; один lockfile не меняет уже запущенный контейнер. + +**Проверка:** подпись, все claims, срок, неверный ключ, обычная сессия и подтверждённый +регрессионный случай. Порог исправления именно этого CVE — 3.3.4 у python-jwt; +это не PyJWT и не рекомендация закрепить старую версию навсегда. + +**Вариант A/D:** Основание и версия: [исходник/разбор 1](https://github.com/saarsec/saarctf-2024/blob/3a06d18974ca177c6dd251a11bdf9b4b334f382a/deutsches-flugzeug/overview.md). + +**Основание:** [первичный материал](https://github.com/saarsec/saarctf-2024/blob/3a06d18974ca177c6dd251a11bdf9b4b334f382a/deutsches-flugzeug/overview.md). + + + + + +## PY-CHALLENGE-STATE. Challenge раскрывается до фиксации commitment + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'chall|comm|resp|init_get|finish_get' . +~~~ + +Построить init/finish state machine; повторный init не должен менять commitment при уже известном challenge. + +**Уязвимый вариант:** + +**ECSC / fonograph, автор.** Шаги протокола использовали неправильно обновляемый +challenge. + +**Исправление:** свежий challenge после commitment, привязка к сессии/объекту, +атомарное однократное потребление. + +**Проверка:** повторный init, перестановка +и повтор finish, параллельные сессии, штатный обмен. + +**Вариант A/D:** Основание и версия: [исходник/разбор 1](https://github.com/ECSC2024/ECSC2024-CTF-AD/blob/2a92e17384ad228072a84fb076a35066fe2ffeff/sources/fonograph/README.md); [исходник/разбор 2](https://github.com/ECSC2024/ECSC2024-CTF-AD/blob/2a92e17384ad228072a84fb076a35066fe2ffeff/sources/fonograph/backend/db.py); [исходник/разбор 3](https://github.com/ECSC2024/ECSC2024-CTF-AD/blob/2a92e17384ad228072a84fb076a35066fe2ffeff/sources/fonograph/backend/handlers.py). + +**Основание:** [первичный материал](https://github.com/ECSC2024/ECSC2024-CTF-AD/blob/2a92e17384ad228072a84fb076a35066fe2ffeff/sources/fonograph/README.md). + + + + + +## PY-SSL-CONTEXT. Отключённая проверка TLS-контекста + +**Поиск:** скрипт, правило PY-SSL-CONTEXT. Запуск: python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain PY-SSL-CONTEXT. AST: ssl._create_unverified_context(), присваивания verify_mode=ssl.CERT_NONE и check_hostname=False; aliases импортов поддержаны. Тип объекта присваивания не устанавливается. + +**Уязвимый вариант:** В клиентском TLS-контексте `CERT_NONE`, отключённая +проверка hostname или непроверяющий контекст могут позволить принять чужой сервер. + +~~~python +import ssl +context = ssl._create_unverified_context() +~~~ + +**Исправление:** Для клиента создать проверяющий контекст; для внутреннего CA +передать доверенный CA и проверять ожидаемое имя сервера. + +~~~python +import ssl +context = ssl.create_default_context(cafile=trusted_ca_file) +~~~ + +**Проверка:** Доверенный сервер доступен; сертификат чужого имени, просроченный и неизвестного CA отвергаются. + +У сервера без mTLS `CERT_NONE` означает, что сертификат клиента не запрашивается: +это штатная конфигурация, если контракт не требует клиентских сертификатов. +`check_hostname` также относится к проверке удалённого сервера клиентом. +Сканер роль и фактический тип объекта не различает, поэтому такой сигнал требует +просмотра; не включать обязательный mTLS только ради его устранения. +[Python ssl.CERT_NONE](https://docs.python.org/3/library/ssl.html#ssl.CERT_NONE). + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'PROTOCOL_TLS_CLIENT|PROTOCOL_TLS_SERVER|create_default_context|CERT_NONE|check_hostname|server_side|server_hostname' . +~~~ + +После совпадения связать создание контекста с местом его использования, +проверить роль `server_side`, назначение `create_default_context` и требование +сертификата клиента. При исправлении серверной конфигурации проверить прежних +клиентов и согласованный механизм аутентификации. + + + + + +## PY-CSRF-EXEMPT. Исключение Django view из CSRF + +**Поиск:** скрипт, правило PY-CSRF-EXEMPT. Запуск: python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain PY-CSRF-EXEMPT. AST: декоратор или вызов django.views.decorators.csrf.csrf_exempt, включая import alias. Наличие исключения ещё не доказывает дефект bearer-only endpoint. + +**Уязвимый вариант:** Cookie-аутентифицированная операция изменения состояния без CSRF-проверки принимает чужой браузерный запрос. + +~~~python +from django.views.decorators.csrf import csrf_exempt +@csrf_exempt +def update(request): + return change_profile(request) +~~~ + +**Исправление:** Для cookie flow вернуть CSRF middleware/decorator и токен в клиенте. Для webhook или bearer API отдельно проверить подпись/auth и отсутствие cookie fallback. + +~~~python +from django.views.decorators.csrf import csrf_protect +@csrf_protect +def update(request): + return change_profile(request) +~~~ + +**Проверка:** Штатный запрос с токеном проходит; POST без/с чужим CSRF-токеном отклонён; разрешённый webhook продолжает работать. + +Первичная документация: [документация 1](https://docs.djangoproject.com/en/5.2/ref/csrf/). + + + + + +## PY-JWT-ALGORITHMS. Алгоритм JWT берётся из выражения + +**Поиск:** скрипт, правило PY-JWT-ALGORITHMS. Запуск: python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain PY-JWT-ALGORITHMS. AST: algorithms вне inline списка/кортежа строк; у точного jose.jwt.decode строковый литерал или известный scalar string также не сигналит. Только jose.jwt.decode и jwt.decode_complete используют третий позиционный аргумент; generic jwt.decode — лишь keyword. Явный None даёт review; отсутствие аргумента, *args, mutable config, версия и происхождение allowlist проверяются вручную. Явные positional/keyword дубликаты algorithms/options не анализируются как исполнимый JWT-вызов. + +**Уязвимый вариант:** Недоверенный alg не должен выбирать допустимый криптографический алгоритм проверки. + +~~~python +import jwt +claims = jwt.decode(token, key, algorithms=[header['alg']]) +~~~ + +**Исправление:** Связать разрешённый алгоритм с доверенной конфигурацией ключа; не смешивать HMAC и RSA для одного материала ключа. + +~~~python +import jwt +claims = jwt.decode(token, key, algorithms=['RS256'], audience='notes', issuer='auth') +~~~ + +**Проверка:** Правильный токен принимается, другой alg/key type и подпись отвергаются; проверить issuer/audience/срок. + +Первичная документация: [документация 1](https://pyjwt.readthedocs.io/en/stable/api.html). + +В известном python-jose 3.5.0 фиксированная строка `algorithms='HS256'` +допустима и не получает сигнал; список `['HS256']` тоже подходит. Это не +разрешение выбирать алгоритм из заголовка токена. Явный `algorithms=None` +остаётся поводом для просмотра: его смысл зависит от библиотеки и типа ключа, +а отсутствие аргумента сканер не считает проверкой допустимого списка. +[python-jose 3.5.0](https://github.com/mpdavis/python-jose/blob/3.5.0/jose/jwt.py), +[PyJWT 2.10.1: algorithms и PyJWK](https://pyjwt.readthedocs.io/en/2.10.1/api.html). + +Доверенная переменная со списком алгоритмов может сохранить PY-JWT-ALGORITHMS; +проследить её до конфигурации ключа. Для позиционных вызовов сначала сверить +импорт и версию по методике [PY-JWT](#py-jwt). Отсутствие сигнала не проверяет +криптографическую пригодность ключа, его происхождение и разделение назначений. + + + + + +## PY-JWT-CLAIMS. Проверки срока и адресата JWT отключены + +**Поиск:** скрипт, правило PY-JWT-CLAIMS. Запуск: python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain PY-JWT-CLAIMS. AST: inline options с verify_exp/verify_nbf/verify_aud/verify_iss=False, включая scalar bool и inline dict spreads. Только jose.jwt.decode и jwt.decode_complete учитывают четвёртый позиционный options. Только у jose.jwt.decode require_X=True снимает сигнал для соответствующего verify_X=False; другие claims и подпись не подавляются. Внешние dict, *args, явные дубликаты аргументов, настройки экземпляра, версии и обязательность claims проверить вручную. + +**Уязвимый вариант:** Верная подпись не делает просроченный токен или токен другого приложения допустимым. + +~~~python +import jwt +claims = jwt.decode(token, key, algorithms=['HS256'], options={'verify_exp': False}) +~~~ + +**Исправление:** Проверять срок, issuer, audience и обязательные claims согласно +контракту. В PyJWT 2.x `require` — список присутствующих полей; он не включает +обратно отключённый `verify_exp`/`verify_aud`/другую проверку значения. +Пример для PyJWT 2.x с обычными включёнными проверками: + +~~~python +import jwt +claims = jwt.decode(token, key, algorithms=['HS256'], audience='notes', issuer='auth', options={'require': ['exp', 'sub', 'iss', 'aud']}) +~~~ + +**Проверка:** Истёкший, преждевременный, без обязательных полей и для другого приложения токены отклоняются; штатные сессии работают с выбранной библиотекой и форматом возвращаемого результата. + +Первичная документация: [PyJWT 2.10.1: require и verify](https://pyjwt.readthedocs.io/en/2.10.1/api.html). + +У python-jose 3.5.0 применяются отдельные `require_*`: + +~~~python +from jose import jwt +claims = jwt.decode( + token, key, algorithms=['HS256'], audience='notes', issuer='auth', + options={'require_exp': True, 'require_sub': True, + 'require_aud': True, 'require_iss': True}, +) +~~~ + +В этой библиотеке `require_exp=True` требует поле и восстанавливает +соответствующий `verify_exp`. Поэтому известное сочетание +`verify_exp=False, require_exp=True` не получает PY-JWT-CLAIMS; требование +другого поля не подавляет отключённую проверку. Эта семантика не переносится +на PyJWT `require=[...]`. `require_signature` не восстанавливает проверку +подписи: она происходит раньше проверки claims. +[python-jose 3.5.0: проверка claims](https://github.com/mpdavis/python-jose/blob/3.5.0/jose/jwt.py). + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'verify_exp|verify_nbf|verify_aud|verify_iss|require_|require["\x27]|PyJWT[(]|options|decode_complete' . +~~~ + +Просмотреть настройки экземпляра, сборку options, overrides и версию API; +словари-переменные и обязательность отсутствующих claims автоматикой не +доказываются. Сверить `iss`/`aud` с принимающим сервисом, затем проверить старые +легитимные токены и новые отрицательные случаи. Добавление обязательного поля +может нарушить старые сессии: согласовать выдачу/миграцию до ужесточения приёма. + + + + + +## PY-REGEX-DYNAMIC. Динамический шаблон регулярного выражения + +**Поиск:** скрипт, правило PY-REGEX-DYNAMIC. Запуск: python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain PY-REGEX-DYNAMIC. AST: re.compile/match/search/fullmatch/findall/finditer/split/sub/subn с нелитеральным первым аргументом. Не измеряет сложность regex; безопасный re.escape остаётся сигналом. + +**Уязвимый вариант:** Пользовательский regex меняет семантику поиска и может вызвать чрезмерный backtracking. + +~~~python +import re +found = re.search(request_pattern, text) +~~~ + +**Исправление:** Для буквального поиска использовать escape или строковую операцию; для regex-функции ограничить грамматику, длины и бюджет исполнения подходящим движком. + +~~~python +import re +found = re.search(re.escape(search_text), bounded_text) +~~~ + +**Проверка:** Метасимволы в буквальном запросе трактуются буквально; длинный почти совпавший текст не блокирует обработчик. + +Сигнал может остаться после правильного патча: правило не доказывает соблюдение указанного инварианта. + +Первичная документация: [документация 1](https://docs.python.org/3/library/re.html#re.escape). + + + + + +## PY-AUTH-DECORATOR. Маршрут Flask регистрируется до защиты login_required + +**Поиск:** правило сканера PY-AUTH-DECORATOR. Подробности: `--explain PY-AUTH-DECORATOR`. AST: импортированный flask_login.login_required выше route/get/post/put/patch/delete у известного Flask/Blueprint. Учитываются aliases и последовательные переприсваивания. Пользовательские декораторы, фабрики, динамические маршруты и другие способы регистрации требуют ручной проверки. Проверяйте зарегистрированный HTTP endpoint, а не только прямой вызов функции. + +**Уязвимый вариант:** + +~~~python +from flask import Flask +from flask_login import login_required +app = Flask(__name__) +@login_required +@app.route('/private') +def private(): + return 'private' +~~~ + +**Исправление:** Поместите известный декоратор маршрута Flask снаружи login_required; проверяйте авторизацию через зарегистрированный endpoint, а не только прямым вызовом функции. + +~~~python +from flask import Flask +from flask_login import login_required +app = Flask(__name__) +@app.route('/private') +@login_required +def private(): + return 'private' +~~~ + +**Проверка:** Анонимный запрос через реальный маршрут должен отклоняться; аутентифицированные запросы и поведение checker должны сохраниться. + +[Первичный источник 1](https://flask.palletsprojects.com/en/stable/patterns/viewdecorators/) + + + + + +## PY-LOG-CREDENTIALS. Значение, похожее на credential, напрямую передаётся в logging + +**Поиск:** правило сканера PY-LOG-CREDENTIALS. Подробности: `--explain PY-LOG-CREDENTIALS`. AST: известные logging/getLogger или Flask app.logger с прямыми чувствительными именами, атрибутами, индексами, значениями dict/list или простым форматированием. Имена: password/passwd/secret/token/access_token/refresh_token/api_key/authorization. Helper calls, logging kwargs, wrappers и другие имена не отслеживаются; отсутствие сигнала на redact() не подтверждает очистку. + +**Уязвимый вариант:** + +~~~python +import logging +logging.warning('authentication failed: %s', password) +~~~ + +**Исправление:** Записывайте стабильные категории событий и согласованные идентификаторы; не записывайте значения credentials и заголовки Authorization. Проверяйте неудачный вход и обработку исключений. + +~~~python +import logging +logging.warning('authentication failed') +~~~ + +**Проверка:** Тестовые canary-credentials не должны появляться в stdout, логах, evidence или трансляции; полезная диагностика ошибок должна сохраниться. + +[Первичный источник 1](https://docs.python.org/3/library/logging.html) diff --git a/docs/vulnerabilities/python.md b/docs/vulnerabilities/python.md new file mode 100644 index 0000000..d74db53 --- /dev/null +++ b/docs/vulnerabilities/python.md @@ -0,0 +1,1353 @@ +# Python: find, fix and verify + +English | [Русский](python-RU.md) + +[Catalog](README.md) · [Scanner](../offline-scanner.md) · [Patch verification](../patch-validation.md) + +40 sections. Each follows **Search → Vulnerable example → Fix → Verification**. +Run `rg` from a local service checkout; searches only read files. Derive the actor/owner from a verified session, not request data. Adapt examples to the actual API and contract. + +## Contents + +- [PY-EVAL — Executing text as Python](#py-eval) +- [PY-SHELL — Python shell execution](#py-shell) +- [PY-DESERIALIZE — Python object deserialization](#py-deserialize) +- [PY-YAML — YAML with a potentially unsafe loader](#py-yaml) +- [PY-SQL — SQL assembled from string expressions](#py-sql) +- [PY-ORM-BOOL — Python and/or used in an ORM expression](#py-orm-bool) +- [PY-TEMPLATE — Dynamic template source](#py-template) +- [PY-TLS — TLS verify=False](#py-tls) +- [PY-DEBUG — Python web debugger enabled](#py-debug) +- [PY-JWT — JWT signature verification disabled](#py-jwt) +- [PY-ARCHIVE — Archive extraction requires path review](#py-archive) +- [PY-TEMP — Non-atomic temporary filename](#py-temp) +- [PY-XML — XML entity resolution enabled](#py-xml) +- [PY-WEAK-HASH — MD5/SHA1: review the purpose](#py-weak-hash) +- [PY-RNG — Non-cryptographic randomness near a possible secret](#py-rng) +- [PY-FILE — Dynamic file-serving path](#py-file) +- [PY-URL — Dynamic outbound URL](#py-url) +- [PY-CRC — CRC/Adler near an integrity boundary](#py-crc) +- [PY-XPATH — XPath assembled from strings](#py-xpath) +- [PY-UUID-BYTES — UUID bytes/bytes_le protocol boundary](#py-uuid-bytes) +- [PY-ASSERT-AUTH — Access control using assert](#py-assert-auth) +- [PY-DJANGO-HOSTS — Django wildcard ALLOWED_HOSTS](#py-django-hosts) +- [PY-HTML-SAFE — HTML escaping explicitly bypassed](#py-html-safe) +- [PY-MASS-ASSIGN — Request fields become model attributes](#py-mass-assign) +- [PY-DECORATOR-AUTH — A route is registered before the authorization wrapper](#py-decorator-auth) +- [PY-ASYNC-CONTEXT — Global current_user leaks across async requests](#py-async-context) +- [PY-REDIRECT — Dynamic redirect destination](#py-redirect) +- [PY-PASSWORD-HASH — Fast digests used for password storage](#py-password-hash) +- [PY-ZIP-LIMITS — Archive traversal, symlinks and expanded volume](#py-zip-limits) +- [PY-JSON-DUPLICATES — Parsers disagree on repeated keys](#py-json-duplicates) +- [PY-CACHE-KEY — Authorization-cache key collisions](#py-cache-key) +- [PY-JWT-DEPENDENCY — Vulnerable JWT-verification dependencies](#py-jwt-dependency) +- [PY-CHALLENGE-STATE — Challenge disclosure before commitment](#py-challenge-state) +- [PY-SSL-CONTEXT — TLS context verification disabled](#py-ssl-context) +- [PY-CSRF-EXEMPT — Django view excluded from CSRF](#py-csrf-exempt) +- [PY-JWT-ALGORITHMS — JWT algorithms taken from an expression](#py-jwt-algorithms) +- [PY-JWT-CLAIMS — JWT expiry or recipient checks disabled](#py-jwt-claims) +- [PY-REGEX-DYNAMIC — Dynamic regular-expression pattern](#py-regex-dynamic) +- [PY-AUTH-DECORATOR — Flask route registers before login protection](#py-auth-decorator) +- [PY-LOG-CREDENTIALS — Credential-like value passed directly to logging](#py-log-credentials) + + + +## PY-EVAL. Executing text as Python + +**Search:** scanner rule PY-EVAL. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain PY-EVAL` for details. Bounded syntactic AST analysis, not type resolution or interprocedural taint analysis. Review actual API, inputs and authorization. + +**Vulnerable example:** + +~~~python +eval(payload) +~~~ + +**Fix:** Use JSON plus a schema for data, or a limited parser for a DSL; do not move code into another eval. + +~~~python +import json +value = json.loads(payload) +if not isinstance(value, dict): + raise ValueError('object required') +~~~ + +**Verification:** Valid documents parse, Python expressions are not executed, and input size is bounded. + + + +## PY-SHELL. Python shell execution + +**Search:** scanner rule PY-SHELL. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain PY-SHELL` for details. AST: explicit shell=True or inline **dict, shell helpers and literal shell argv in subprocess/asyncio.create_subprocess_exec. Variable argv, wrappers and complex branching are not evaluated. + +**Vulnerable example:** + +~~~python +import subprocess +subprocess.run(command, shell=True) +~~~ + +**Fix:** Use a fixed executable and separate argv without a shell; allowlist arguments according to the utility contract. + +~~~python +import subprocess +subprocess.run(['/usr/bin/file', '--', filename], shell=False, check=True, timeout=3) +~~~ + +**Verification:** Metacharacters remain data, dangerous options fail, and normal operations work. + +
+Expanded example and limitations + +**Recognize:** User text is concatenated into a command using shell=True. + +```python +# Vulnerable: data becomes part of an interpreter command. +digest = subprocess.check_output("printf '%s' '" + text + "' | sha256sum", shell=True) +``` + +**Patch for a content SHA-256 digest:** + + + +```python +import hashlib + +def digest_text(text): + if not isinstance(text, str): + raise ValueError("text must be a string") + return hashlib.sha256(text.encode("utf-8")).hexdigest() +``` + +Preserve expected encoding and response format. The sha256sum shell utility prints extra fields/newlines that the API may process separately. If a command serves another purpose, see [argument boundaries](README.md). + +**Check:** Known digest, empty text, quotes, newlines, Unicode and no external execution. This recipe is not suitable for password hashing. + +
+ + + +## PY-DESERIALIZE. Python object deserialization + +**Search:** scanner rule PY-DESERIALIZE. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain PY-DESERIALIZE` for details. AST: pickle/dill/shelve, jsonpickle.decode/loads, joblib.load, pandas.read_pickle and direct or simply assigned Unpickler(...).load. numpy.load and numpy.lib.format.read_array require known allow_pickle=True (keyword or third/second positional argument respectively). Import aliases, simple scalar assignments and inline **dict are supported; old defaults, mutable dictionaries, wrappers and data trust need review. + +**Vulnerable example:** + +~~~python +import pickle +value = pickle.loads(data) +~~~ + +**Fix:** For pickle-like formats, use schema-validated JSON where compatible and migrate trusted legacy records separately. For NumPy retain numeric .npy/.npz with allow_pickle=False, dtype/shape and size checks; migrate object arrays separately. Never load an untrusted pickle to convert it. + +~~~python +import json +value = json.loads(data) # validate schema +~~~ + +**Verification:** Valid records remain readable; unknown fields/types and object arrays fail; dtype, shape and volume are checked. + +
+Expanded example and limitations + +**Recognize:** Pickle arrives from cookies, request bodies, uploads or database rows previously writable by clients. Base64 does not establish trust. + +```python +# Vulnerable with untrusted raw input: loading can execute code. +profile = pickle.loads(raw) +``` + +**Patch for simple profile exchange**, if the protocol already permits JSON or a compatible migration is agreed: + + + +```python +import json + +def decode_profile(raw): + value = json.loads(raw) + if not isinstance(value, dict) or set(value) != {"display_name"}: + raise ValueError("unexpected profile fields") + if not isinstance(value["display_name"], str): + raise ValueError("display_name must be a string") + return {"display_name": value["display_name"]} +``` + +The HTTP layer must bound body size before reading; a JSON schema does not automatically bound parsing cost. Role and owner are server-derived. Never fall back to pickle.loads after JSON errors or migrate old records with an unsafe parser before establishing their trusted origin. + +**Check:** Valid names, Unicode and permitted empty values work; arrays, numbers and unknown administrative fields fail; old clients/data remain compatible. If the checker requires the old format, parser replacement without a migration plan is not deployable. + +
+ +Object-oriented JSON also needs scrutiny: jsonpickle.decode is not ordinary json.loads. [jsonpickle](https://jsonpickle.readthedocs.io/en/latest/), [joblib.load](https://joblib.readthedocs.io/en/stable/generated/joblib.load.html) and [pandas.read_pickle](https://pandas.pydata.org/docs/reference/api/pandas.read_pickle.html) warn about untrusted input. Establish serialized-object provenance before loading. + +**NumPy object arrays.** numpy.load with allow_pickle=True permits object deserialization from files. It is numpy.load's third positional argument and numpy.lib.format.read_array's second. Determine whether clients can replace the file/storage record; .npy/.npz extensions prove nothing. [numpy.load](https://numpy.org/doc/stable/reference/generated/numpy.load.html), [read_array](https://numpy.org/doc/stable/reference/generated/numpy.lib.format.read_array.html). + +~~~python +import numpy as np +values = np.load(upload_path, allow_pickle=True) +~~~ + +For a numeric .npy contract, the proposed patch preserves array format: + +~~~python +import numpy as np +values = np.load(upload_path, allow_pickle=False) +if not isinstance(values, np.ndarray) or values.dtype.kind not in "iuf": + raise ValueError("numeric array required") +~~~ + +Validate permitted dtypes, dimensions and element counts. Bound input before loading; checks after array allocation do not replace memory limits. allow_pickle=False rejects legacy object arrays: migrate trusted data first, with no unsafe fallback. For .npz preserve the container API and close NpzFile; the example above is only for one numeric .npy array. + +Search parameters/versions manually without importing the target project: + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'numpy|allow_pickle|read_array|requirements|poetry.lock|uv.lock' . +~~~ + +Connect imports to calls and inspect lockfiles/deployed metadata plus actual file origins. The scanner cannot establish package version, file trust or values in variable dictionaries. Omitted allow_pickle does not signal: check that version's default. Verify old numeric dtypes/shapes still load, object arrays fail without executing content, oversized input is bounded and old data follows the migration plan. + + + +## PY-YAML. YAML with a potentially unsafe loader + +**Search:** scanner rule PY-YAML. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain PY-YAML` for details. AST: yaml.load/load_all/unsafe_load/unsafe_load_all, excluding SafeLoader/CSafeLoader/BaseLoader/CBaseLoader, with import aliases, positional Loader and inline **dict. BaseLoader/CBaseLoader return scalars as strings. Review version defaults, wrappers and resource limits. + +**Vulnerable example:** + +~~~python +import yaml +value = yaml.load(data, Loader=yaml.Loader) +~~~ + +**Fix:** Use safe_load, validate fields/types, and bound document size and complexity. + +~~~python +import yaml +value = yaml.safe_load(data) # validate schema +~~~ + +**Verification:** Ordinary YAML works; object tags and unexpected structures fail. + +yaml.BaseLoader/CBaseLoader do not instantiate arbitrary Python objects and do not trigger this rule. They turn scalars into strings: false is not False, and a nonempty string is truthy. They are appropriate only with explicit schema-based string conversion; never replace SafeLoader globally without type tests. SafeLoader/CSafeLoader preserve standard YAML types but do not replace schemas or size/depth bounds. Review custom constructors separately. [PyYAML loaders/types](https://pyyaml.org/wiki/PyYAMLDocumentation). + +~~~python +import yaml +raw_settings = yaml.load(data, Loader=yaml.BaseLoader) +# Strings are expected; validate structure and convert fields separately. +~~~ + +For wrappers, loader overrides and versions: + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'yaml[.]|Loader|add_constructor|PyYAML|requirements|poetry.lock|uv.lock' . +~~~ + +Match calls to imports, selected loaders and registered constructors. Read versions from lockfiles/deployment metadata without importing the service. Test numbers, booleans, dates, empty scalars and legacy documents on the actual runtime. With a BaseLoader contract, no PY-YAML signal means only no recognized dangerous object loading, not proven parser safety. + + + +## PY-SQL. SQL assembled from string expressions + +**Search:** scanner rule PY-SQL. Use `--explain PY-SQL` for the exact detector contract. AST: string construction at SQL sinks and keywords, including simple assignments. Imported psycopg/psycopg2.sql SQL(nonliteral) or format/join with unknown/raw pieces signal. Literal SQL plus known Identifier/Literal/Placeholder compositions suppress this signal only, not identifier authorization. Mutable composition, wrappers, cross-function flows and driver versions remain manual. + +**Vulnerable example:** + +~~~python +db.execute("SELECT id FROM notes WHERE name=%s" % name) +~~~ + +**Fix:** Bind values using the actual driver's parameter API; select identifiers from a server-side allowlist. + +~~~python +db.execute("SELECT id FROM notes WHERE name=?", (name,)) # sqlite3 +~~~ + +**Verification:** Quotes remain data; ownership restrictions and normal queries remain correct. + +Splitting fixed SQL across string literals does not introduce injection: + +~~~python +db.execute("SELECT " + "1") +db.execute(f"SELECT 1") +~~~ + +These forms do not trigger PY-SQL. The exception covers literals, their concatenation and f-strings without substitutions, not general constant evaluation. .format() still signals and needs review. No signal proves neither ownership nor fixed-query meaning nor driver settings. Keep bind parameters for user values instead of switching interpolation styles. [sqlite3 query parameters](https://docs.python.org/3/library/sqlite3.html#how-to-use-placeholders-to-bind-values-in-sql-queries). + +
+Expanded example and limitations + +**Recognize:** execute with f-strings, %, .format() or concatenated SQL; object selection lacks ownership checks. + +```python +# Vulnerable: client_id controls SQL; ownership is not constrained. +row = db.execute(f"SELECT body FROM notes WHERE id = '{client_id}'").fetchone() +``` + +**Minimal sqlite3 patch for private notes:** + + + +```python +def read_private_note(db, user_id, note_id): + if user_id is None: + raise PermissionError("authentication required") + row = db.execute( + "SELECT body FROM notes WHERE id = ? AND owner_id = ?", + (note_id, user_id), + ).fetchone() + if row is None: + raise LookupError("not found") + return row[0] +``` + +`?` is sqlite3 syntax. With psycopg use %s **inside SQL** plus a separate value tuple, never Python's % interpolation operator. Column names do not become safe by passing them as value parameters. + +**Check:** Owners read old records; other users/anonymous callers cannot. Quoted string IDs remain values; list/export paths enforce the same policy. Validate numeric IDs where required by contract. + +
+ +**A/D variant:** SQL blacklists overlook interactions between parameters. **ECSC / fonograph, author write-up.** Character filtering did not preserve boundaries between neighboring string arguments. **Patch:** Driver parameters instead of manual assembly/blacklists. **Test:** Quotes/backslashes in each parameter and combinations, plus normal text. **Search:** PY-SQL; a sanitize function's presence does not clear the finding. + +[source/write-up 1](https://github.com/ECSC2024/ECSC2024-CTF-AD/blob/2a92e17384ad228072a84fb076a35066fe2ffeff/sources/fonograph/README.md); [source/write-up 2](https://github.com/ECSC2024/ECSC2024-CTF-AD/blob/2a92e17384ad228072a84fb076a35066fe2ffeff/sources/fonograph/backend/db.py); [source/write-up 3](https://github.com/ECSC2024/ECSC2024-CTF-AD/blob/2a92e17384ad228072a84fb076a35066fe2ffeff/sources/fonograph/backend/handlers.py). + + + +## PY-ORM-BOOL. Python and/or used in an ORM expression + +**Search:** scanner rule PY-ORM-BOOL. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain PY-ORM-BOOL` for details. Bounded syntactic AST analysis, not type resolution or interprocedural taint analysis. Review actual API, inputs and authorization. + +**Vulnerable example:** + +~~~python +User.find(User.name == name and User.password == password) +~~~ + +**Fix:** Use the ORM's documented expression composition, not Python short-circuit operators; retain all ownership/authentication predicates. + +~~~python +User.find(User.name == name, User.password == password) # Beanie +~~~ + +**Verification:** Both predicates appear in the actual query; wrong passwords and other users' objects fail. + +**A/D variant:** Python and instead of Beanie predicate composition. **Reference:** explorers, CTF Cup source and pinned Beanie 1.23.6. Full MongoDB authorization was not reproduced here. The scanner found PY-ORM-BOOL in the source. + +~~~python +# before +User.find(User.username == name and User.password == password) +# after: Beanie accepts multiple criteria +User.find(User.username == name, User.password == password) +~~~ + +**Test:** All four valid/invalid username/password combinations, different users and empty values; inspect the actual generated filter. Use the installed ORM's API rather than copying unrelated syntax. + +[source/write-up 1](https://github.com/C4T-BuT-S4D/ctfcup-2023-ad/blob/53d6b9b7369448ac6c5d7d8e9458f66b25271e8a/services/explorers/src/app/api.py); [source/write-up 2](https://github.com/C4T-BuT-S4D/ctfcup-2023-ad/blob/53d6b9b7369448ac6c5d7d8e9458f66b25271e8a/services/explorers/src/requirements.txt). + + + +## PY-TEMPLATE. Dynamic template source + +**Search:** scanner rule PY-TEMPLATE. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain PY-TEMPLATE` for details. AST: render_template_string/from_string by method name, first argument or source=, import aliases and inline **dict. Nonliteral source requires review; custom same-named methods may match. Review dictionary variables, wrappers, environment type, trust and autoescape. + +**Vulnerable example:** + +~~~python +from flask import render_template_string +render_template_string(source=user_text) +~~~ + +**Fix:** Keep template source trusted and pass untrusted values as parameters; review autoescape and loader boundaries. + +~~~python +from flask import render_template_string +render_template_string(source='

{{ message }}

', message=user_text) +~~~ + +**Verification:** Template syntax in a user field stays data; expected formatting is preserved. + +source= in Flask render_template_string and Jinja Environment.from_string denotes template source. Autoescape escapes output but does not prevent expressions in untrusted source from executing. A message parameter in a fixed template remains data. Review import aliases, wrappers and configuration-loaded templates; the scanner does not establish string provenance. [Flask render_template_string](https://flask.palletsprojects.com/en/stable/api/#flask.render_template_string), [Jinja from_string](https://jinja.palletsprojects.com/en/stable/api/#jinja2.Environment.from_string). + +
+Expanded example and limitations + +**Recognize:** render_template_string or Environment.from_string receives request text, including text concatenated with HTML. + +```python +# Vulnerable: the user controls template source. +return render_template_string(request.form["message"]) +``` + +**Flask patch:** + +```python +from flask import render_template, request + +message = request.form["message"] +return render_template("message.html", message=message) +``` + +`templates/message.html` is a fixed project file: + +```html +

{{ message }}

+``` + +Do not add |safe. Flask enables autoescape for HTML templates by default; verify the app has not disabled it. HTML escaping and preventing user-template compilation are separate boundaries. + +**Check:** {{ 2 + 3 }} appears literally, not as an evaluated result; quotes/HTML render as text; normal messages work. If the service is intentionally a template editor, this substitution changes its contract: design an allowed language instead of applying this shortcut. + +
+ + + +## PY-TLS. TLS verify=False + +**Search:** scanner rule PY-TLS. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain PY-TLS` for details. AST: verify=False, simple local scalar or inline **dict, respecting overwrite order. Known requests Session/session and httpx Client/AsyncClient with matching with/async with, Session.send and httpx.stream are supported. Generic get/post/put/patch/delete/request remains an untyped heuristic. Dictionary variables, client properties, runtime config and wrappers are not evaluated. + +**Vulnerable example:** + +~~~python +import requests +requests.get(url, verify=False) +~~~ + +**Fix:** Enable certificate/hostname checks and configure the trusted CA instead of bypassing verification. + +~~~python +import requests +requests.get(url, verify=True, timeout=3) +~~~ + +**Verification:** Correct CA/hostname works; invalid, expired or wrong-host certificates fail without fallback. + +requests.Session.send applies verify to prepared-request transmission, including inside with requests.session(). Preserve the required CA trust chain; do not disable verification to fix certificate errors. For prepared requests also inspect how environment settings are merged. [Requests prepared requests/TLS](https://requests.readthedocs.io/en/latest/user/advanced/). + +~~~python +import requests +with requests.session() as session: + with session.send(prepared_request, verify=False, timeout=3) as response: + response.raise_for_status() +~~~ + +Restore verify=True or supply the approved CA bundle path. The scanner examines explicit flags; it does not reconstruct prepared_request URLs, adapter settings or application-wide trust policy. + +httpx.Client/AsyncClient configure validation at construction. Client.stream does not accept verify; module-level httpx.stream does. To preserve streaming with TLS validation: + +~~~python +import httpx +with httpx.Client(verify=True, timeout=3) as client: + with client.stream('GET', approved_url) as response: + response.raise_for_status() + # Read inside the context, bounded by the service contract. +~~~ + +For a private CA use an ssl.SSLContext supported by the installed HTTPX version. The context manager closes responses. TLS does not authorize destinations, so dynamic approved_url still triggers PY-URL pending review. [HTTPX Client/stream](https://www.python-httpx.org/api/). + + + +## PY-DEBUG. Python web debugger enabled + +**Search:** scanner rule PY-DEBUG. Use `--explain PY-DEBUG` for the exact detector contract. AST: explicit debug/use_debugger=True at run/run_simple (legacy name heuristic). Known imported Flask instances: DEBUG=True via config subscript/update/from_mapping or app.debug=True. Inline dictionaries and aliases supported; custom factories, runtime overrides, configuration files and branches remain manual. + +**Vulnerable example:** + +~~~python +app.run(debug=True) +~~~ + +**Fix:** Disable the debugger in the competition runtime and retain private, redacted diagnostics. + +~~~python +app.run(debug=False) +~~~ + +**Verification:** Errors expose no interactive console or stack trace; health checks work. + + + +## PY-JWT. JWT signature verification disabled + +**Search:** scanner rule PY-JWT. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain PY-JWT` for details. AST: options.verify_signature=False with inline **kwargs/options and overwrite order. Only jose.jwt.decode and jwt.decode_complete bind fourth positional options; generic jwt.decode is version-ambiguous. Legacy verify=False remains only for generic jwt.decode. Review *args, mutable dictionaries, wrappers and instance settings; explicit positional/keyword duplicates are not treated as executable JWT calls. + +**Vulnerable example:** + +~~~python +import jwt +claims = jwt.decode(token, options={'verify_signature': False}) +~~~ + +**Fix:** Verify signatures with a trusted key and fixed algorithm policy; validate required claims and values using the installed library version. + +~~~python +import jwt +claims = jwt.decode(token, key, algorithms=['HS256'], audience='service', options={'require': ['exp', 'sub', 'aud']}) +~~~ + +**Verification:** Modified, unsigned, expired and wrong-audience tokens fail; valid sessions work. + +For recognized jose.jwt.decode and jwt.decode_complete, inline options may be the fourth positional argument: + +~~~python +from jose import jwt +claims = jwt.decode(token, key, ['HS256'], {'verify_signature': False}) +~~~ + +The generic jwt.decode positional contract is version-dependent: PyJWT 1.7.1 uses third verify, fourth algorithms and fifth options; 2.10.1 uses third algorithms and fourth options. The scanner does not identify the installed distribution/version and does not interpret these generic jwt.decode positions. [PyJWT 1.7.1](https://github.com/jpadilla/pyjwt/blob/1.7.1/jwt/api_jwt.py), [PyJWT 2.10.1](https://github.com/jpadilla/pyjwt/blob/2.10.1/jwt/api_jwt.py). + +verify=False does not disable validation in PyJWT 2.x decode_complete. python-jose 3.5.0 decode does not accept that argument and raises TypeError. These forms do not trigger solely for the legacy argument. Generic jwt.decode(..., verify=False) remains a legacy-version heuristic. Actual options={'verify_signature': False} remains detected. [python-jose 3.5.0 decode](https://github.com/mpdavis/python-jose/blob/3.5.0/jose/jwt.py). + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'decode_complete|jwt[.]decode|from jose|from jwt|import jwt|PyJWT|python-jose|verify_signature|options=|requirements|poetry.lock|uv.lock' . +~~~ + +Identify imports, deployed/locked versions, argument positions, instance settings and result consumers. Unverified diagnostic claims must not become authorization. decode_complete returns a structure containing payload, not just claims; preserve this return contract. Parse errors or TypeError must not enable an unverified fallback. + +JWT semantics in these sections were reviewed against pinned source versions; JWT libraries were not executed for that review. Versions identify reviewed APIs, not recommendations to install obsolete releases. Check the service's supported version, security updates and call contract. + + + +## PY-ARCHIVE. Archive extraction requires path review + +**Search:** scanner rule PY-ARCHIVE. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain PY-ARCHIVE` for details. AST: any extractall is a heuristic including ZIP; extract requires known tarfile.open/TarFile/TarFile.open through aliases, constructors, simple assignment or with/as. shutil.unpack_archive requires known tar/gztar/bztar/xztar/zstdtar format, including third argument. filter='data' or tarfile.data_filter (aliases/inline **dict included) suppresses this signal, not all risks. Review custom filters, extension-inferred format, extraction_filter, versions, quotas, wrappers and complex control flow. + +A missing filter requires reviewing Python version and TarFile.extraction_filter: Python 3.14 defaults to data; earlier behavior was equivalent to fully_trusted. Instance/class/subclass overrides change this. Even a safe default does not suppress the scanner heuristic. [tarfile filters](https://docs.python.org/3/library/tarfile.html#extraction-filters). + +**Vulnerable example:** Untrusted tar extraction without path, member-type or UNIX-metadata restrictions. + +~~~python +import tarfile +with tarfile.open(upload_path) as archive: + archive.extract(member, destination, filter='fully_trusted') +~~~ + +**Fix:** Validate paths, links, member types and quotas; use tarfile's data filter where supported. A filter is not a resource limit or a complete ZIP policy. + +~~~python +import tarfile +with tarfile.open(upload_path) as archive: + archive.extract(member, new_destination, filter=tarfile.data_filter) +~~~ + +For shutil the rule considers only explicitly selected built-in tar formats: + +~~~python +import shutil +shutil.unpack_archive(upload_path, new_destination, format='gztar', filter='data') +~~~ + +format='zip' does not trigger this tar signal; ZIP accepts no filter argument. Do not apply the shown tar patch to ZIP. Extension-based detection, custom unpackers and replacement registrations need review of the actual implementation. [shutil.unpack_archive](https://docs.python.org/3/library/shutil.html#shutil.unpack_archive). + +data_filter restricts escapes and dangerous types/metadata but may allow internal links. It neither isolates races with another process mutating the directory nor bounds expanded volume. Archives requiring owners, UNIX permissions or special files need a separate compatibility policy. Errors can leave partial output: never publish it as complete; a new directory simplifies cleanup. [PEP 706 scope/limitations](https://peps.python.org/pep-0706/). + +API support alone does not imply all security fixes. The October 1, 2026 releases—3.10.22, 3.11.17, 3.12.15, 3.13.16 and 3.14.8—include tar-filter bypass fixes; verify equivalent distribution backports. [Python announcement](https://blog.python.org/2026/10/python-31022-31117/). + +**Verification:** Traversal, links, device entries and oversized archives fail; ordinary archives remain inside the root. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'tarfile|extractall|[.]extract[(]|unpack_archive|register_unpack_format|extraction_filter|data_filter|errorlevel|FROM python|requires-python' . +~~~ + +Identify import/archive type, input source, format, effective filter, error handling and destination-directory access. Check versions/backports from image/deployment metadata without importing the target. Generic extractall matches also include ZIP/unknown objects: review the actual API rather than asserting tar traversal. + + + +## PY-TEMP. Non-atomic temporary filename + +**Search:** scanner rule PY-TEMP. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain PY-TEMP` for details. Bounded syntactic AST analysis, not type resolution or interprocedural taint analysis. Review actual API, inputs and authorization. + +**Vulnerable example:** + +~~~python +import tempfile +name = tempfile.mktemp() +~~~ + +**Fix:** Create a private temporary file atomically and retain its handle; never reopen an untrusted name. + +~~~python +import tempfile +with tempfile.TemporaryFile() as output: + output.write(data) +~~~ + +**Verification:** Concurrent requests obtain separate files and cannot overwrite existing files or links. + + + +## PY-XML. XML entity resolution enabled + +**Search:** scanner rule PY-XML. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain PY-XML` for details. AST: XMLParser by method name; lxml.etree.XMLPullParser/ETCompatXMLParser/iterparse by resolved import name/alias. Requires known resolve_entities=True, including scalar variables or inline **dict. Review defaults, lxml version, DTD, input type and wrappers. This does not determine CVE applicability. + +**Vulnerable example:** + +~~~python +from lxml import etree +parser = etree.ETCompatXMLParser(resolve_entities=True) +~~~ + +**Fix:** Disable entity/DTD loading and network access; bound document complexity for the actual parser. + +~~~python +from lxml import etree +parser = etree.ETCompatXMLParser(resolve_entities=False, load_dtd=False, no_network=True) +~~~ + +Review the same settings in XMLPullParser and iterparse. If internal entities are required, consider resolve_entities='internal' on a supporting version and test limits. False may change tree/text semantics; preserve the required service behavior. + +**Verification:** Ordinary XML parses; external resources are not read and oversized input fails. + +Calls without explicit settings and version-specific defaults need manual review: + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'lxml|XMLParser|XMLPullParser|ETCompatXMLParser|iterparse|resolve_entities|requirements|poetry.lock|uv.lock' . +~~~ + +Match import, API and locked/deployed version, then trace untrusted XML. Before lxml 6.1, iterparse and ETCompatXMLParser defaulted to external-entity resolution and could read local files; 6.1.0 changed the default to 'internal'. Updating does not fix explicit resolve_entities=True. The scanner finds explicit unsafe settings, not version-based CVEs. [GHSA-vfmq-68hx-4jfw / CVE-2026-41066](https://github.com/lxml/lxml/security/advisories/GHSA-vfmq-68hx-4jfw). + + + +## PY-WEAK-HASH. MD5/SHA1: review the purpose + +**Search:** scanner rule PY-WEAK-HASH. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain PY-WEAK-HASH` for details. Bounded syntactic AST analysis, not type resolution or interprocedural taint analysis. Review actual API, inputs and authorization. + +**Vulnerable example:** + +~~~python +import hashlib +digest = hashlib.md5(password) +~~~ + +**Fix:** Use a supported password KDF for passwords and HMAC/signatures for authenticity; ordinary checksums need a separate decision. + +~~~python +import hashlib +digest = hashlib.scrypt(password, salt=salt, n=16384, r=8, p=1) +~~~ + +**Verification:** Authentication checks work and legacy data has a migration path. + + + +## PY-RNG. Non-cryptographic randomness near a possible secret + +**Search:** scanner rule PY-RNG. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain PY-RNG` for details. Bounded syntactic AST analysis, not type resolution or interprocedural taint analysis. Review actual API, inputs and authorization. + +**Vulnerable example:** + +~~~python +import random +token = str(random.getrandbits(128)) +~~~ + +**Fix:** Use secrets or a supported CSPRNG with sufficient entropy for tokens; handle generator errors. + +~~~python +import secrets +token = secrets.token_urlsafe(32) +~~~ + +**Verification:** No predictable fallback is used; token format and sessions stay compatible. + + + +## PY-FILE. Dynamic file-serving path + +**Search:** scanner rule PY-FILE. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain PY-FILE` for details. AST: send_file by method name, first argument or path_or_file= with aliases/inline **dict. Nonliteral paths still signal after safe owned-record lookup; custom same-named methods may match. Review authorization, root, links, wrappers and dictionary variables. + +**Vulnerable example:** + +~~~python +from flask import send_file +result = send_file(path_or_file=user_path) +~~~ + +**Fix:** Resolve a server-owned record after authorization and enforce the storage root; review symlinks and races. + +~~~python +from flask import send_file +record = load_owned_file(file_id, current_user.id) +result = send_file(path_or_file=record.storage_path) +~~~ + +**Verification:** Other owners' files, traversal and external symlinks fail; authorized downloads work. + +path_or_file= is modern Flask API syntax. load_owned_file represents an actually implemented owner check and server-side path lookup, not a cosmetic rename. The corrected call still triggers PY-FILE because the scanner does not verify authorization, links or replacement races. A dynamic argument might also be an already opened trusted file object, which the API legitimately supports. [Flask send_file](https://flask.palletsprojects.com/en/stable/api/#flask.send_file). + + + +## PY-URL. Dynamic outbound URL + +**Search:** scanner rule PY-URL. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain PY-URL` for details. AST: requests/httpx/urlopen and known Session/session, requests.sessions.Session/session, Client/AsyncClient via aliases, local assignment or immediate constructor. with/as supports requests Session/httpx Client and async with/as supports AsyncClient; facts are invalidated after the region. request(method,url), httpx.stream and Client/AsyncClient.stream use second argument or url=. Literal URLs do not signal. No URL/DNS/redirect validation analysis; review wrappers, returned clients, mutable config and complex relationships. + +**Vulnerable example:** + +~~~python +import requests +response = requests.get(user_url) +~~~ + +**Fix:** Apply explicit destination/scheme/port policy, validate resolved addresses and every redirect, and bound time/response size. + +~~~python +import requests +response = requests.get('https://api.example.invalid/status', timeout=3, allow_redirects=False) +~~~ + +**Verification:** Approved endpoints work; forbidden destinations and redirects cannot cross the trust boundary. + +Switching to context managers and streaming does not change URL provenance: + +~~~python +import httpx +async def fetch(user_url): + async with httpx.AsyncClient(timeout=3, follow_redirects=False) as client: + async with client.stream('GET', user_url) as response: + response.raise_for_status() + # Bound response reads; the URL has not been authorized yet. +~~~ + +Choose a contract-compatible fix: a fixed server endpoint, or a validated dynamic address with scheme/host/port/path/redirect policy. Allowlisted dynamic URLs still trigger PY-URL: the scanner cannot prove validation quality. Literal URLs do not signal, but do not prove DNS, proxy or later redirects safe. + +Close streaming responses after size overflow, cancellation and read failures. async with client.stream closes on exit; manual streaming requires guaranteed aclose(). Preserve client lifetime/pool reuse instead of creating a pool each iteration. [HTTPX async streaming](https://www.python-httpx.org/async/). + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'requests|httpx|urlopen|base_url|proxies|proxy=|trust_env|allow_redirects|follow_redirects|HTTP_PROXY|HTTPS_PROXY|NO_PROXY' . +~~~ + +Trace input to the complete URL and combine client/base_url, proxy and environment settings. Review actual resolution, every redirect, internal-address access, cross-destination credential forwarding, timeouts and body limits. A per-operation timeout may not bound the whole chain. Request/PreparedRequest objects, factory clients, custom transports and interprocedural flows require manual review in an authorized test environment; the scanner itself makes no network requests. + +**A/D variant:** Checking hostname while accepting the whole client URL. **FAUST / quickr-maps, source.** A server string was interpolated into a URL, only hostname was checked, then requests consumed it. Path/query changes remain a separate boundary. + +**Patch:** Clients select symbolic names from a server map; the server builds the entire URL, route and owner. **Test:** URL delimiters cannot change route, port or principal. **Search:** PY-URL, including url= keyword coverage. The complete bypass chain was not reproduced here. + +[source/write-up 1](https://github.com/fausecteam/faustctf-2024-quickr-maps/blob/fe77e8f1926117b788108f7614271f3133a1f607/location_portal/src/main.py); [source/write-up 2](https://github.com/fausecteam/faustctf-2024-quickr-maps/blob/fe77e8f1926117b788108f7614271f3133a1f607/private_loc/main.go). + + + +## PY-CRC. CRC/Adler near an integrity boundary + +**Search:** scanner rule PY-CRC. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain PY-CRC` for details. Bounded syntactic AST analysis, not type resolution or interprocedural taint analysis. Review actual API, inputs and authorization. + +**Vulnerable example:** + +~~~python +import zlib +tag = zlib.crc32(payload) +~~~ + +**Fix:** Use HMAC/signatures for authenticity or unique IDs plus authorization; ordinary checksums may remain CRC. + +~~~python +import hmac +tag = hmac.digest(key, payload, 'sha256') +~~~ + +**Verification:** Modified messages without the key fail; formats/records stay compatible. + + + +## PY-XPATH. XPath assembled from strings + +**Search:** scanner rule PY-XPATH. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain PY-XPATH` for details. AST: xpath/XPath by method name and string construction in first argument or simple assignment. String literals, Add-concatenated literals and f-strings without FormattedValue do not signal; %, format and interpolated f-strings require review. No arbitrary evaluation; inspect wrappers, XPath variables and trust. + +**Vulnerable example:** + +~~~python +node.xpath("//user[name='%s']" % username) +~~~ + +**Fix:** Bind variables with the actual API and keep XPath fixed; do not quote data into syntax. + +~~~python +node.xpath("//user[name=$name]", name=username) +~~~ + +**Verification:** Quotes/brackets stay data; search scope/ownership does not expand. + +A fixed XPath split across literals does not trigger PY-XPATH: + +~~~python +node.xpath("//" + "user") +node.xpath(f"//user") +~~~ + +Only recognized strings without substituted values, concatenated literals and interpolation-free f-strings are excluded. The scanner neither executes XPath nor evaluates arbitrary Python expressions. XPath variables bind data; axes, node names and expression text require server-side policy. Select the actual library's API: name= in this example is lxml-specific. [lxml XPath parameters](https://lxml.de/xpathxslt.html#the-xpath-method). + + + +## PY-UUID-BYTES. UUID bytes/bytes_le protocol boundary + +**Search:** scanner rule PY-UUID-BYTES. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain PY-UUID-BYTES` for details. Bounded syntactic AST analysis, not type resolution or interprocedural taint analysis. Review actual API, inputs and authorization. + +**Vulnerable example:** + +~~~python +import uuid +value = uuid.UUID(bytes_le=wire_bytes) +~~~ + +**Fix:** Agree on canonical text or documented byte order across languages/cache/DB; bytes_le is not inherently unsafe. + +~~~python +import uuid +value = uuid.UUID(wire_text) # canonical text contract +~~~ + +**Verification:** Asymmetric vectors and round trips agree; old references remain valid. + +**A/D variant:** UUID meaning changes between C# and Python. **RuCTF / hyperborea-legends, author write-up.** Different UUID byte order in cache and primary paths changed the object to which authorization applied. + +**Patch:** One documented wire format with boundary conversion; canonical text is preferable if protocol-compatible. **Test:** Asymmetric known vectors, cross-language round-trips and old records. **Search:** PY-UUID-BYTES and CS-GUID-BYTES identify review locations only. + +[source/write-up 1](https://github.com/HackerDom/ructf-2023/blob/0cc333e44f2ba6908ff6c5d613146e3b00173315/writeups/hyperborea-legends/README.md). + + + +## PY-ASSERT-AUTH. Access control using assert + +**Search:** scanner rule PY-ASSERT-AUTH. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain PY-ASSERT-AUTH` for details. Bounded syntactic AST analysis, not type resolution or interprocedural taint analysis. Review actual API, inputs and authorization. + +**Vulnerable example:** + +~~~python +assert note.owner_id == current_user.id +~~~ + +**Fix:** Use explicit denial active under -O; do not blanket-replace ordinary test assertions. + +~~~python +if note.owner_id != current_user.id: + raise PermissionError('access denied') +~~~ + +**Verification:** Unauthorized objects fail in normal/optimized mode; authorized actions work. + + + +## PY-DJANGO-HOSTS. Django wildcard ALLOWED_HOSTS + +**Search:** scanner rule PY-DJANGO-HOSTS. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain PY-DJANGO-HOSTS` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries. + +**Vulnerable example:** + +~~~python +ALLOWED_HOSTS = ["*"] +~~~ + +**Fix:** Allowlist actual hostnames/IPs including the checker; use get_host instead of raw Host and review trusted proxy headers separately. + +~~~python +ALLOWED_HOSTS = ["service.internal"] +~~~ + +**Verification:** Unknown Host fails; normal host/checker works. + +**Reference:** [primary source](https://docs.djangoproject.com/en/5.2/ref/settings/#allowed-hosts). + + + +## PY-HTML-SAFE. HTML escaping explicitly bypassed + +**Search:** scanner rule PY-HTML-SAFE. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain PY-HTML-SAFE` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries. + +**Vulnerable example:** + +~~~python +html = mark_safe(message) +~~~ + +**Fix:** Use autoescaped templates; sanitize permitted rich HTML. HTML escaping does not secure JS or URL contexts. + +~~~python +html = message +~~~ + +**Verification:** Tags/quotes stay data without breaking supported formatting. + +**Reference:** [primary source](https://docs.djangoproject.com/en/5.2/topics/security/). + + + +## PY-MASS-ASSIGN. Request fields become model attributes + +**Search:** scanner rule PY-MASS-ASSIGN. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain PY-MASS-ASSIGN` for details. AST: setattr with nonliteral attribute name. **kwargs, wrappers, ORM update and constructors are not automatically covered. + +Additional manual search for forms outside automatic coverage: + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'setattr|__dict__|model_validate|update\(|request.json' . +~~~ + +Trace field lists into the ORM; locate owner/role/tenant and nested DTOs. + +**Vulnerable example:** + +`setattr(model, key, value)` over client JSON applies administrative fields. + +**Fix:** Explicitly allowlist editable attributes; derive owner/role and nested privileges server-side. + +**Verification:** Unknown/admin fields do not alter state; permitted edits remain functional. + +**Scanner example before:** + +~~~python +for field, value in payload.items(): + setattr(account, field, value) +~~~ + +**Fix template:** + +~~~python +account.display_name = validate_display_name(payload['display_name']) +~~~ + + + +## PY-DECORATOR-AUTH. A route is registered before the authorization wrapper + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e '@.*route|@.*get|@.*post|login_required|permission_required' . +~~~ + +Expand decorator application order and inspect the function actually saved in the router. + +**Vulnerable example:** + +Authorization wraps the local name, but the router already retains the unwrapped function. + +**Fix:** Put authorization inside route registration or use the framework's supported dependency/policy mechanism; check every HTTP method. + +**Verification:** Sessionless requests through the actual router fail; direct unit calls alone are insufficient. + + + +## PY-ASYNC-CONTEXT. Global current_user leaks across async requests + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'global|current_user|ContextVar|threading.local|asyncio' . +~~~ + +Find principal assignments and awaits between assignment/use; ensure ContextVar tokens reset in finally. + +**Vulnerable example:** + +A global variable or thread-local serves multiple coroutines sharing a thread. + +**Fix:** Request-scoped objects/ContextVar with token restoration; pass explicit verified context into jobs. + +**Verification:** Barrier-interleaved requests from different users; exceptions leave no foreign context. + + + +## PY-REDIRECT. Dynamic redirect destination + +**Search:** scanner rule PY-REDIRECT. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain PY-REDIRECT` for details. AST: flask.redirect/werkzeug.utils.redirect first argument or location=; django.shortcuts.redirect first argument or to=. Import aliases/inline **dict supported; literals or known simple scalar values do not signal. Review trust, wrappers, runtime kwargs, route resolution and reverse-proxy redirects. + +Additional manual search for forms outside automatic coverage: + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'redirect\(|next|return_url|urljoin' . +~~~ + +Trace Location construction: relative paths must not become network-path URLs or another origin. + +**Vulnerable example:** + +`redirect(request.args['next'])` selects an external destination; startswith('/') is insufficient. + +**Fix:** Resolve destinations from an allowlist or verify approved scheme/host/path after normalization; do not trust user-controlled return URLs. + +**Verification:** External, scheme-relative and malformed destinations fail; supported navigation works. + +**Scanner example before:** + +~~~python +from flask import redirect +return_url = request.args['next'] +response = redirect(return_url) +~~~ + +**Fix template:** + +~~~python +from flask import redirect +response = redirect('/profile') +~~~ + +Primary documentation: [reference 1](https://docs.djangoproject.com/en/5.2/ref/utils/#django.utils.http.url_has_allowed_host_and_scheme). + +Named arguments do not change the trust boundary: + +~~~python +from flask import redirect +response = redirect(location=request.args['next']) +~~~ + +~~~python +from django.shortcuts import redirect +response = redirect(to=request.GET['next']) +~~~ + +Flask/Werkzeug uses location=; Django uses to=. Django also accepts view names and objects with get_absolute_url(): inspect destination meaning and the final Location rather than treating every dynamic value as an external URL. A fixed route may use redirect(location='/profile') or Django redirect(to='profile') if that named route exists. Preserve parameters, methods and status behavior; forcing all navigation onto one route changes the service contract. [Flask redirect](https://flask.palletsprojects.com/en/stable/api/#flask.redirect), [Django 5.2 redirect](https://docs.djangoproject.com/en/5.2/topics/http/shortcuts/#redirect). + +Fully validated dynamic destinations still signal. The scanner does not reproduce URLconf, get_absolute_url, browser normalization or effective Host/proxy behavior; verify those relationships through normal navigation. + + + +## PY-PASSWORD-HASH. Fast digests used for password storage + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'password|hashlib|sha256|md5|pbkdf2' . +~~~ + +Inspect registration/login, salt, work factor, stored-record format and migration branches. + +**Vulnerable example:** + +sha256(password) without adaptive cost permits rapid guessing against a leaked database. + +**Fix:** A supported framework password hasher, Argon2id or suitable KDF; retain salt/parameters in records and upgrade after successful login. + +**Verification:** Existing users log in and migrate; wrong passwords never overwrite hashes; long input is bounded. + + + +## PY-ZIP-LIMITS. Archive traversal, symlinks and expanded volume + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'zipfile|tarfile|extractall|extract\(' . +~~~ + +Beyond PY-ARCHIVE, inspect entries, actual expanded volume and filesystem boundaries; path filters do not bound size. + +**Vulnerable example:** + +An archive writes outside the root or fills storage despite a small compressed input. + +**Fix:** Separate destination, validation of every path/type/link, entry-count and actual expanded-byte limits, then atomic publication. + +**Verification:** Normal archive, absolute paths, outward links, many entries, mid-run failure and temporary-data cleanup. + +**Reference:** [primary source](https://cheatsheetseries.owasp.org/cheatsheets/File_Upload_Cheat_Sheet.html). + + + +## PY-JSON-DUPLICATES. Parsers disagree on repeated keys + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'json.loads|object_pairs_hook|orjson|signature|canonical' . +~~~ + +Compare signer, API and downstream parsing: first/last duplicate, numeric handling and key normalization. + +**Vulnerable example:** + +Signature verification sees one owner interpretation while the operation uses another. + +**Fix:** One canonical DTO before signing and after reading; explicit duplicate/numeric policy and rejection of ambiguous documents. + +**Verification:** Repeated owners, key ordering, Unicode and large numbers produce identical meaning or explicit rejection. + + + +## PY-CACHE-KEY. Authorization-cache key collisions + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'cache|memoize|lru_cache' . +~~~ + +Compare complete keys across users and argument pairs sharing a prefix; find truncation and invalidation. + +**Vulnerable example:** + +**Reference:** hermicache, RuCTF author write-up. A shared cache built string keys from functions/arguments and truncated them to 90 characters. + +**Search:** Ambiguous concatenation, prefix/slice keys, missing user/tenant/permission version and shared caching of public results and authentication. + +**Fix:** Serialize complete typed tuples with required context. Never cache password-verification success under a shared key. Preserve computational caching needed for SLA. Example principle: + +~~~python +# before: cache[(function + str(arguments))[:90]] +# after: no truncation, no ambiguous concatenation +key = json.dumps([function, tenant_id, user_id, arguments], + separators=(",", ":"), ensure_ascii=False) +~~~ + +**Verification:** Distinct argument pairs sharing a prefix, different users, role/password changes and legitimate repeat computation. + +**A/D variant:** Source and version: [source/write-up 1](https://github.com/HackerDom/ructf-finals-2023/blob/a7442769909e08c39716cb18d3d1c3a99324bbf8/writeups/hermicache/README.md). + +**Reference:** [primary source](https://github.com/HackerDom/ructf-finals-2023/blob/a7442769909e08c39716cb18d3d1c3a99324bbf8/writeups/hermicache/README.md). + + + +## PY-JWT-DEPENDENCY. Vulnerable JWT-verification dependencies + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'python-jwt|PyJWT|jwt|requirements|lock' . +~~~ + +Compare distribution name, lock, vendored copies and actual loaded version; python-jwt and PyJWT differ. + +**Vulnerable example:** + +**Reference:** deutsches-flugzeug, saarCTF author overview; python-jwt advisory CVE-2022-39227. The dependency was vulnerable even when calls looked normal. **Search:** Exact distribution name, lock/version, imported module, vendored copies and image/lock mismatch. + +**Fix:** A fixed compatible version with locally prepared packages/image; editing a lockfile does not replace an already running container. + +**Verification:** Signature, all claims, lifetime, wrong key, normal sessions and the confirmed regression case. The fix threshold for this particular CVE was python-jwt 3.3.4, not PyJWT; it is not a recommendation to pin that old release indefinitely. + +**A/D variant:** Source and version: [source/write-up 1](https://github.com/saarsec/saarctf-2024/blob/3a06d18974ca177c6dd251a11bdf9b4b334f382a/deutsches-flugzeug/overview.md). + +**Reference:** [primary source](https://github.com/saarsec/saarctf-2024/blob/3a06d18974ca177c6dd251a11bdf9b4b334f382a/deutsches-flugzeug/overview.md). + + + +## PY-CHALLENGE-STATE. Challenge disclosure before commitment + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'chall|comm|resp|init_get|finish_get' . +~~~ + +Map init/finish state transitions; repeated init must not change commitments after the challenge is known. + +**Vulnerable example:** + +**ECSC / fonograph, author write-up.** Protocol steps reused incorrectly updated challenge state. + +**Fix:** Fresh challenges after commitment, bound to session/object, with atomic one-time consumption. + +**Verification:** Repeated init, reordered/replayed finish, parallel sessions and normal exchanges. + +**A/D variant:** Source and version: [source/write-up 1](https://github.com/ECSC2024/ECSC2024-CTF-AD/blob/2a92e17384ad228072a84fb076a35066fe2ffeff/sources/fonograph/README.md); [source/write-up 2](https://github.com/ECSC2024/ECSC2024-CTF-AD/blob/2a92e17384ad228072a84fb076a35066fe2ffeff/sources/fonograph/backend/db.py); [source/write-up 3](https://github.com/ECSC2024/ECSC2024-CTF-AD/blob/2a92e17384ad228072a84fb076a35066fe2ffeff/sources/fonograph/backend/handlers.py). + +**Reference:** [primary source](https://github.com/ECSC2024/ECSC2024-CTF-AD/blob/2a92e17384ad228072a84fb076a35066fe2ffeff/sources/fonograph/README.md). + + + +## PY-SSL-CONTEXT. TLS context verification disabled + +**Search:** scanner rule PY-SSL-CONTEXT. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain PY-SSL-CONTEXT` for details. AST: ssl._create_unverified_context(), verify_mode=ssl.CERT_NONE and check_hostname=False assignments with import aliases. Assignment receiver type is not established. + +**Vulnerable example:** CERT_NONE, disabled hostname validation or an unverified client TLS context can accept an unintended server. + +~~~python +import ssl +context = ssl._create_unverified_context() +~~~ + +**Fix:** Enable certificate/hostname verification and configure the correct CA rather than an unverified context. + +~~~python +import ssl +context = ssl.create_default_context(cafile=trusted_ca_file) +~~~ + +**Verification:** Correct peers work; wrong CA/hostname and expiry fail. + +For a server without mTLS, CERT_NONE means no client certificate is requested; this is normal unless the contract requires them. check_hostname concerns a client authenticating a server. The scanner cannot distinguish role/effective object type; do not require mTLS merely to silence a finding. [Python ssl.CERT_NONE](https://docs.python.org/3/library/ssl.html#ssl.CERT_NONE). + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'PROTOCOL_TLS_CLIENT|PROTOCOL_TLS_SERVER|create_default_context|CERT_NONE|check_hostname|server_side|server_hostname' . +~~~ + +Connect context construction to use; review server_side, create_default_context purpose and client-certificate requirements. When changing server configuration test existing clients and the agreed authentication mechanism. + + + +## PY-CSRF-EXEMPT. Django view excluded from CSRF + +**Search:** scanner rule PY-CSRF-EXEMPT. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain PY-CSRF-EXEMPT` for details. AST: django.views.decorators.csrf.csrf_exempt decorator/call with import alias. An exemption alone is not proof of a flaw on a bearer-only endpoint. + +**Vulnerable example:** A cookie-authenticated mutation without CSRF validation accepts cross-context browser requests. + +~~~python +from django.views.decorators.csrf import csrf_exempt +@csrf_exempt +def update(request): + return change_profile(request) +~~~ + +**Fix:** Retain CSRF on cookie-authenticated browser routes; narrow exemptions to independently authenticated stateless endpoints. + +~~~python +from django.views.decorators.csrf import csrf_protect +@csrf_protect +def update(request): + return change_profile(request) +~~~ + +**Verification:** Browser mutations need the correct token; authorized API/webhook requests still work. + +Primary documentation: [reference 1](https://docs.djangoproject.com/en/5.2/ref/csrf/). + + + +## PY-JWT-ALGORITHMS. JWT algorithms taken from an expression + +**Search:** scanner rule PY-JWT-ALGORITHMS. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain PY-JWT-ALGORITHMS` for details. AST: algorithms outside an inline list/tuple of strings; exact jose.jwt.decode also permits known literal/scalar strings. Only jose.jwt.decode and jwt.decode_complete use third positional algorithms; generic jwt.decode uses keyword only. Explicit None signals; missing arguments, *args, mutable config, version and allowlist origin need review. Explicit duplicate algorithms/options arguments are not analyzed as executable calls. + +**Vulnerable example:** Untrusted alg values must not choose the permitted signature-verification algorithm. + +~~~python +import jwt +claims = jwt.decode(token, key, algorithms=[header['alg']]) +~~~ + +**Fix:** Bind allowed algorithms to trusted key configuration; never mix HMAC/RSA for the same key material. + +~~~python +import jwt +claims = jwt.decode(token, key, algorithms=['RS256'], audience='notes', issuer='auth') +~~~ + +**Verification:** Wrong algorithm/key type/signature fails; issuer, audience and expiry are checked. + +Primary documentation: [reference 1](https://pyjwt.readthedocs.io/en/stable/api.html). + +In known python-jose 3.5.0, a fixed algorithms='HS256' string is valid and does not signal; ['HS256'] also works. This does not permit deriving algorithms from token headers. Explicit algorithms=None still requires review: meaning depends on library/key type. Omission does not prove an allowlist. [python-jose 3.5.0](https://github.com/mpdavis/python-jose/blob/3.5.0/jose/jwt.py), [PyJWT 2.10.1 algorithms/PyJWK](https://pyjwt.readthedocs.io/en/2.10.1/api.html). + +A trusted algorithm-list variable may retain PY-JWT-ALGORITHMS; trace it to key configuration. For positional calls first verify imports/versions as in [PY-JWT](#py-jwt). No signal proves neither key strength, provenance nor purpose separation. + + + +## PY-JWT-CLAIMS. JWT expiry or recipient checks disabled + +**Search:** scanner rule PY-JWT-CLAIMS. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain PY-JWT-CLAIMS` for details. AST: inline options with verify_exp/verify_nbf/verify_aud/verify_iss=False, scalar booleans and inline spreads. Only jose.jwt.decode/jwt.decode_complete consider fourth positional options. Only jose.jwt.decode require_X=True suppresses corresponding verify_X=False, not other claims/signature. Review external dictionaries, *args, duplicates, instance config, versions and required presence. + +**Vulnerable example:** A valid signature does not make expired or other-application tokens acceptable. + +~~~python +import jwt +claims = jwt.decode(token, key, algorithms=['HS256'], options={'verify_exp': False}) +~~~ + +**Fix:** Validate expiry, issuer, audience and required presence separately. The after example uses PyJWT 2.x options.require; python-jose uses require_*. Check decode_complete's result shape. + +~~~python +import jwt +claims = jwt.decode(token, key, algorithms=['HS256'], audience='notes', issuer='auth', options={'require': ['exp', 'sub', 'iss', 'aud']}) +~~~ + +**Verification:** Expired, premature, missing-claim and other-application tokens fail; sessions work with the selected library/result shape. + +Primary documentation: [PyJWT 2.10.1 require/verify](https://pyjwt.readthedocs.io/en/2.10.1/api.html). + +python-jose 3.5.0 uses separate require_* options: + +~~~python +from jose import jwt +claims = jwt.decode( + token, key, algorithms=['HS256'], audience='notes', issuer='auth', + options={'require_exp': True, 'require_sub': True, + 'require_aud': True, 'require_iss': True}, +) +~~~ + +In this library require_exp=True requires the claim and restores corresponding verify_exp. Thus known verify_exp=False, require_exp=True does not trigger PY-JWT-CLAIMS; requiring another field does not suppress disabled verification. This differs from PyJWT require=[...]. require_signature does not restore signature verification, which happens before claim validation. [python-jose 3.5.0 claims](https://github.com/mpdavis/python-jose/blob/3.5.0/jose/jwt.py). + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'verify_exp|verify_nbf|verify_aud|verify_iss|require_|require["\x27]|PyJWT[(]|options|decode_complete' . +~~~ + +Review instance settings, options construction, overrides and API versions. Variable dictionaries and missing-claim requirements are not proven automatically. Match iss/aud to the receiver, then test old legitimate tokens and new negative cases. Requiring a new field can break sessions: coordinate issuance/migration before tightening acceptance. + + + +## PY-REGEX-DYNAMIC. Dynamic regular-expression pattern + +**Search:** scanner rule PY-REGEX-DYNAMIC. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain PY-REGEX-DYNAMIC` for details. AST: re.compile/match/search/fullmatch/findall/finditer/split/sub/subn with nonliteral first argument. Does not measure regex complexity; safe re.escape still signals. + +**Vulnerable example:** User-provided regex changes search semantics and may cause excessive backtracking. + +~~~python +import re +found = re.search(request_pattern, text) +~~~ + +**Fix:** For literal search use escaping/string operations; a regex feature needs constrained grammar, lengths and execution budget. + +~~~python +import re +found = re.search(re.escape(search_text), bounded_text) +~~~ + +**Verification:** Metacharacters stay literal where intended; long near-matches cannot block the handler. + +A correct patch may retain this signal: the detector does not prove the stated invariant. + +Primary documentation: [reference 1](https://docs.python.org/3/library/re.html#re.escape). + + + +## PY-AUTH-DECORATOR. Flask route registers before login protection + +**Search:** scanner rule PY-AUTH-DECORATOR. Use `--explain PY-AUTH-DECORATOR` for the exact detector contract. AST: imported flask_login.login_required above route/get/post/put/patch/delete on a known Flask/Blueprint constructor. Aliases and straight-line rebinding respected. Custom decorators, factories, dynamic routes and other registration methods remain manual. + +**Vulnerable example:** + +~~~python +from flask import Flask +from flask_login import login_required +app = Flask(__name__) +@login_required +@app.route('/private') +def private(): + return 'private' +~~~ + +**Fix:** Put the known Flask route decorator outside login_required; verify authorization using the registered endpoint, not only direct function calls. + +~~~python +from flask import Flask +from flask_login import login_required +app = Flask(__name__) +@app.route('/private') +@login_required +def private(): + return 'private' +~~~ + +**Verification:** Anonymous requests must fail through the real route; authenticated requests and checker behavior must still work. + +[Primary reference 1](https://flask.palletsprojects.com/en/stable/patterns/viewdecorators/) + + + +## PY-LOG-CREDENTIALS. Credential-like value passed directly to logging + +**Search:** scanner rule PY-LOG-CREDENTIALS. Use `--explain PY-LOG-CREDENTIALS` for the exact detector contract. AST: known logging module/getLogger or Flask app.logger methods with direct sensitive names/attributes/subscripts, dict/list values or simple format expressions. Names: password/passwd/secret/token/access_token/refresh_token/api_key/authorization. Helper calls, logging kwargs, wrappers and other names are not traced; no helper-call signal does not verify redaction. + +**Vulnerable example:** + +~~~python +import logging +logging.warning('authentication failed: %s', password) +~~~ + +**Fix:** Log stable event categories and approved identifiers, never credential values or Authorization headers; test failed login and exception paths. + +~~~python +import logging +logging.warning('authentication failed') +~~~ + +**Verification:** Canary credentials must not appear in stdout, logs, evidence or broadcasts; useful failure diagnostics remain available. + +[Primary reference 1](https://docs.python.org/3/library/logging.html) diff --git a/docs/vulnerabilities/ruby-RU.md b/docs/vulnerabilities/ruby-RU.md new file mode 100644 index 0000000..a600a33 --- /dev/null +++ b/docs/vulnerabilities/ruby-RU.md @@ -0,0 +1,474 @@ + + +# Ruby / Rails: поиск и исправление + +[English](ruby.md) | Русский + +[Вся база](README-RU.md) · [Сканер](../offline-scanner-RU.md) · [Проверка патча](../patch-validation-RU.md) + +18 разделов. Формат: **Поиск → Уязвимый вариант → Исправление → Проверка**. +Команды `rg` выполняются в корне локальной копии сервиса и только читают файлы. Субъект/владелец определяется по проверенной сессии, а не данным запроса. Примеры нужно адаптировать к реальным API и контракту. + +Автоматические находки — ограниченные синтаксические сигналы для проверки. AST-анализ не разрешает типы и не отслеживает данные между функциями; regex не заменяет парсер языка. Комментарии, строки и одноимённые пользовательские API могут давать совпадения. Проверьте фактическое исполнение, входные данные, авторизацию и границы доверия. + + + +## Содержание + +- [RUBY-OBJECT — Ruby Marshal/небезопасный YAML](#ruby-object) +- [RUBY-SHELL — Shell-строка Ruby](#ruby-shell) +- [RUBY-EVAL — Ruby eval/ERB из данных](#ruby-eval) +- [RUBY-PERMIT-ALL — Rails разрешает все параметры](#ruby-permit-all) +- [RUBY-CONSTANTIZE — Строка выбирает Ruby-класс](#ruby-constantize) +- [RUBY-HTML-SAFE — Ruby html_safe/raw](#ruby-html-safe) +- [RUBY-SQL — Интерполяция в SQL Ruby](#ruby-sql) +- [RUBY-IDOR — ActiveRecord find без области владельца](#ruby-idor) +- [RUBY-PATH — send_file и File.join на имени клиента](#ruby-path) +- [RUBY-REDIRECT — redirect_to принимает внешний return_to](#ruby-redirect) +- [RUBY-CSRF — Пропущенная forgery protection](#ruby-csrf) +- [RUBY-REGEX-ANCHOR — ^ и $ проверяют строку внутри многострочного поля](#ruby-regex-anchor) +- [RUBY-YAML-VERSION — YAML.load зависит от версии Psych](#ruby-yaml-version) +- [RUBY-DESERIALIZE-COOKIE — Подписанная cookie не обязательно секретна](#ruby-deserialize-cookie) +- [RUBY-SSRF — Net::HTTP/open-uri на вводе клиента](#ruby-ssrf) +- [RUBY-CALLBACKS — Callbacks выполняют эффект до проверки прав](#ruby-callbacks) +- [RUBY-TLS — Ruby HTTPS без проверки peer](#ruby-tls) +- [RUBY-REDIRECT-INPUT — Rails redirect напрямую принимает параметры запроса](#ruby-redirect-input) + + + + + +## RUBY-OBJECT. Ruby Marshal/небезопасный YAML + +**Поиск:** скрипт, правило RUBY-OBJECT. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain RUBY-OBJECT. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API. + +**Уязвимый вариант:** + +~~~ruby +record = Marshal.load(payload) +~~~ + +**Исправление:** Внешний формат — JSON или ограниченный YAML.safe_load с явной политикой классов/aliases и схемой; legacy мигрировать отдельно. + +~~~ruby +record = JSON.parse(payload) # validate DTO schema and size +~~~ + +**Проверка:** Произвольные объекты не создаются; старые законные данные сохранены. + + + + + +## RUBY-SHELL. Shell-строка Ruby + +**Поиск:** скрипт, правило RUBY-SHELL. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain RUBY-SHELL. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API. + +**Уязвимый вариант:** + +~~~ruby +system(command) +~~~ + +**Исправление:** Фиксированный executable + отдельные argv; запрет выбора опасных опций. Backticks и %x тоже вызывают shell. + +~~~ruby +system("/usr/bin/file", "--", filename) +~~~ + +**Проверка:** Спецсимволы не становятся командами; штатные файлы обрабатываются. + + + + + +## RUBY-EVAL. Ruby eval/ERB из данных + +**Поиск:** скрипт, правило RUBY-EVAL. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain RUBY-EVAL. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API. + +**Уязвимый вариант:** + +~~~ruby +result = eval(input) +~~~ + +**Исправление:** Данные не исполнять; фиксированный ERB-шаблон + переменные или ограниченный парсер. + +~~~ruby +result = JSON.parse(input) # validate expected schema +~~~ + +**Проверка:** Синтаксис Ruby не исполняется; штатный формат читается. + + + + + +## RUBY-PERMIT-ALL. Rails разрешает все параметры + +**Поиск:** скрипт, правило RUBY-PERMIT-ALL. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain RUBY-PERMIT-ALL. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API. + +**Уязвимый вариант:** + +~~~ruby +attrs = params.permit! +~~~ + +**Исправление:** Явный набор редактируемых полей, owner/role из сервера; nested params ограничить отдельно. + +~~~ruby +attrs = params.require(:note).permit(:title, :body) +~~~ + +**Проверка:** Owner/role/вложенные неизвестные поля не применяются; допустимое частичное изменение работает. + +**Основание:** [первичный материал](https://guides.rubyonrails.org/action_controller_overview.html#strong-parameters). + + + + + +## RUBY-CONSTANTIZE. Строка выбирает Ruby-класс + +**Поиск:** скрипт, правило RUBY-CONSTANTIZE. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain RUBY-CONSTANTIZE. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API. + +**Уязвимый вариант:** + +~~~ruby +klass = params[:type].constantize +~~~ + +**Исправление:** Фиксированная карта типов с безопасным DTO. safe_constantize меняет обработку ошибки поиска, не ограничивает выбор класса. + +~~~ruby +klass = {"text" => TextNote}.fetch(validated_type) +~~~ + +**Проверка:** Неизвестный тип не создаёт объектов; законные типы совместимы. + +**Основание:** [первичный материал](https://api.rubyonrails.org/classes/ActiveSupport/Inflector.html). + + + + + +## RUBY-HTML-SAFE. Ruby html_safe/raw + +**Поиск:** скрипт, правило RUBY-HTML-SAFE. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain RUBY-HTML-SAFE. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API. + +**Уязвимый вариант:** + +~~~ruby +value = params[:text].html_safe +~~~ + +**Исправление:** Autoescape по контексту; для предусмотренного HTML sanitizer. Не путать обработку HTML с исходником ERB. + +~~~ruby +value = params[:text] # render with automatic escaping +~~~ + +**Проверка:** Теги и кавычки — текст, разрешённое форматирование сохранилось. + +**Основание:** [первичный материал](https://guides.rubyonrails.org/security.html). + + + + + +## RUBY-SQL. Интерполяция в SQL Ruby + +**Поиск:** скрипт, правило RUBY-SQL. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain RUBY-SQL. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API. + +**Уязвимый вариант:** + +~~~ruby +Note.where("title = '#{title}'") +~~~ + +**Исправление:** Параметры/hash conditions; сортировка и имена полей из фиксированной карты. Сырой SQL внутри параметра не исправляется сам. + +~~~ruby +Note.where(title: title, owner_id: current_user.id) +~~~ + +**Проверка:** Кавычки — данные; чужой owner не читается. + +**Основание:** [первичный материал](https://guides.rubyonrails.org/active_record_querying.html). + + + + + +## RUBY-IDOR. ActiveRecord find без области владельца + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e '\.find\(|find_by|params\[:id\]|current_user' . +~~~ + +Сверить read/update/destroy/export и association scope; strong params не выполняют авторизацию объекта. + +**Уязвимый вариант:** + +Note.find(params[:id]) получает запись любого пользователя. + +**Исправление:** Поиск через current_user.notes либо явная policy/shared-access область; owner не из params. + +**Проверка:** Своё/чужое/аноним, экспорт/удаление и предусмотренное sharing. + +**Основание:** [первичный материал](https://cheatsheetseries.owasp.org/cheatsheets/Authorization_Cheat_Sheet.html). + + + + + +## RUBY-PATH. send_file и File.join на имени клиента + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'send_file|File.join|File.read|Pathname|realpath' . +~~~ + +Проследить filename до открытия; join не проверяет containment, realpath не убирает TOCTOU. + +**Уязвимый вариант:** + +send_file(params[:path]) выбирает произвольный ресурс. + +**Исправление:** Серверный storage ID после policy check, контролируемый root и links, лимит/Content-Disposition. + +**Проверка:** Чужой ID, абсолютный путь, ссылка наружу и штатная загрузка. + + + + + +## RUBY-REDIRECT. redirect_to принимает внешний return_to + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'redirect_to|return_to|allow_other_host|url_from' . +~~~ + +Сверить версию Rails и настройки open-redirect protection; raw return_to не превращать в доверенный URL. + +**Уязвимый вариант:** + +Внешнее назначение разрешено параметром/allow_other_host. + +**Исправление:** Серверная карта путей либо штатный безопасный механизм версии Rails с проверкой host. + +**Проверка:** Внутренний переход работает, внешний origin и неоднозначный путь отклоняются. + +**Основание:** [первичный материал](https://guides.rubyonrails.org/security.html). + + + + + +## RUBY-CSRF. Пропущенная forgery protection + +**Поиск:** скрипт, правило RUBY-CSRF. Запуск: python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain RUBY-CSRF. Regex: skip_forgery_protection, skip_before_action/filter :verify_authenticity_token и allow_forgery_protection=false. only/except анализировать вручную. + +Дополнительный ручной поиск для непокрытых форм: + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'skip_forgery_protection|skip_before_action|protect_from_forgery|csrf' . +~~~ + +Проверить исключения controller и применение cookie auth на JSON endpoint. + +**Уязвимый вариант:** + +Cookie-сессия сохраняется, а CSRF middleware отключено ради удобства API. + +**Исправление:** Восстановить проверку для cookie-auth; token API отделить явно, не отключать весь controller. + +**Проверка:** Правильный token принимается, чужой origin/пустой token отклоняются; API-клиент совместим. + +**Основание:** [первичный материал](https://guides.rubyonrails.org/security.html). + + +**Сигнал сканера — пример до:** + +~~~ruby +skip_forgery_protection +skip_before_action :verify_authenticity_token +~~~ + +**Шаблон исправления:** + +~~~ruby +protect_from_forgery with: :exception +~~~ + +Первичная документация: [документация 1](https://api.rubyonrails.org/classes/ActionController/RequestForgeryProtection/ClassMethods.html). + + + + + +## RUBY-REGEX-ANCHOR. ^ и $ проверяют строку внутри многострочного поля + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'validates|format:|Regexp|match\?|\^|\$' . +~~~ + +Сравнить начало/конец строки и всего поля; проверить переводы строк и timeout regexp. + +**Уязвимый вариант:** + +Валидатор имени использует ^...$ и принимает подходящую строку внутри большего значения. + +**Исправление:** Для целого значения \A и \z, проверка типа/длины; при разрешённых multiline выбрать соответствующий контракт. + +**Проверка:** Переводы строк в начале/конце/середине и штатный Unicode. + +**Основание:** [первичный материал](https://guides.rubyonrails.org/security.html). + + + + + +## RUBY-YAML-VERSION. YAML.load зависит от версии Psych + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'YAML.load|Psych.load|safe_load|unsafe_load|Gemfile.lock' . +~~~ + +Сверить фактическую Psych/Ruby версию и allowed classes/aliases; RUBY-OBJECT намеренно не считает каждый load unsafe. + +**Уязвимый вариант:** + +Ожидают safe semantics нового Psych, запускают старую версию с созданием произвольных объектов. + +**Исправление:** Явный safe_load с минимальным набором типов и схемой; фиксировать совместимые зависимости локально. + +**Проверка:** Произвольный класс/alias и старый допустимый документ; на фактическом runtime. + +**Основание:** [первичный материал](https://docs.ruby-lang.org/en/3.3/Psych.html). + + + + + +## RUBY-DESERIALIZE-COOKIE. Подписанная cookie не обязательно секретна + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'cookies.signed|cookies.encrypted|session\[|secret_key_base' . +~~~ + +Посмотреть, что хранится в cookie; отличить целостность от шифрования и ключ подписи от доступа к объекту. + +**Уязвимый вариант:** + +В signed cookie кладут приватный текст, полагая что подпись его скрывает. + +**Исправление:** Для конфиденциальности encrypted cookie либо серверный session store; минимальные данные и срок, безопасная ротация ключей. + +**Проверка:** Обычная сессия читается, клиент не видит приватное содержимое, изменённая cookie отвергается. + + + + + +## RUBY-SSRF. Net::HTTP/open-uri на вводе клиента + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'Net::HTTP|URI.open|open-uri|Faraday|HTTParty' . +~~~ + +Найти URL parser, redirects и DNS в реальном adapter. + +**Уязвимый вариант:** + +URL/redirect ведёт к внутреннему ресурсу с доверием к приложению. + +**Исправление:** Фиксированное назначение либо единая политика всех переходов/соединения и лимиты; URI.parse не авторизация. + +**Проверка:** Mock redirect/DNS, запрещённая схема, timeout и штатный upstream. + +**Основание:** [первичный материал](https://cheatsheetseries.owasp.org/cheatsheets/Server_Side_Request_Forgery_Prevention_Cheat_Sheet.html). + + + + + +## RUBY-CALLBACKS. Callbacks выполняют эффект до проверки прав + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'before_save|after_save|after_commit|after_find|validate|authorize' . +~~~ + +Сопоставить policy check, instantiation, callbacks и transaction boundary. + +**Уязвимый вариант:** + +Модель пишет файл/отправляет задачу в callback до auth либо до commit. + +**Исправление:** Авторизация до изменения; внешние эффекты после подтверждённого commit, идемпотентность и компенсация по контракту. + +**Проверка:** Rollback/отказ не оставляет эффектов, повторная задача не дублирует результат. + + + + + +## RUBY-TLS. Ruby HTTPS без проверки peer + +**Поиск:** скрипт, правило RUBY-TLS. Запуск: python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain RUBY-TLS. Regex: VERIFY_NONE. Не определяет, применён ли объект к реальному соединению. + +**Уязвимый вариант:** VERIFY_NONE делает TLS-соединение непроверенным. + +~~~ruby +http.verify_mode = OpenSSL::SSL::VERIFY_NONE +~~~ + +**Исправление:** Вернуть проверку peer/hostname и доверенный CA; проверить настройки используемого HTTP-клиента. + +~~~ruby +http.verify_mode = OpenSSL::SSL::VERIFY_PEER +http.ca_file = trusted_ca_file +~~~ + +**Проверка:** Штатный сервер доступен, неверный сертификат не даёт полезного ответа. + +Первичная документация: [документация 1](https://docs.ruby-lang.org/en/master/OpenSSL/SSL/SSLContext.html). + + + + + +## RUBY-REDIRECT-INPUT. Rails redirect напрямую принимает параметры запроса + +**Поиск:** правило сканера RUBY-REDIRECT-INPUT. Точный контракт детектора: `--explain RUBY-REDIRECT-INPUT`. Regex с лексическими исключениями: redirect_to с params[...] или request.params[...], с необязательной открывающей скобкой. Defaults фреймворка могут уже запрещать внешние hosts; aliases, вспомогательные функции и allow_other_host требуют проверки. + +**Уязвимый вариант:** + +~~~ruby +redirect_to params[:next] +~~~ + +**Исправление:** Используйте маршруты, выбранные сервером, или явную политику redirect; сохраняйте проверки host в Rails и учитывайте установленную версию фреймворка. + +~~~ruby +redirect_to account_path +~~~ + +**Проверка:** Чужие адреса и адреса вида //host отклоняются; обычная навигация работает. + +[Первичный источник 1](https://api.rubyonrails.org/classes/ActionController/Redirecting.html) diff --git a/docs/vulnerabilities/ruby.md b/docs/vulnerabilities/ruby.md new file mode 100644 index 0000000..e476475 --- /dev/null +++ b/docs/vulnerabilities/ruby.md @@ -0,0 +1,431 @@ +# Ruby / Rails: find, fix and verify + +English | [Русский](ruby-RU.md) + +[Catalog](README.md) · [Scanner](../offline-scanner.md) · [Patch verification](../patch-validation.md) + +18 sections. Each follows **Search → Vulnerable example → Fix → Verification**. +Run `rg` from a local service checkout; searches only read files. Derive the actor/owner from a verified session, not request data. Adapt examples to the actual API and contract. + +## Contents + +- [RUBY-OBJECT — Ruby Marshal or unsafe YAML](#ruby-object) +- [RUBY-SHELL — Ruby shell string](#ruby-shell) +- [RUBY-EVAL — Ruby eval/ERB from data](#ruby-eval) +- [RUBY-PERMIT-ALL — Rails permits all parameters](#ruby-permit-all) +- [RUBY-CONSTANTIZE — String selects a Ruby class](#ruby-constantize) +- [RUBY-HTML-SAFE — Ruby html_safe/raw](#ruby-html-safe) +- [RUBY-SQL — Ruby SQL interpolation](#ruby-sql) +- [RUBY-IDOR — ActiveRecord lookup outside the owner's scope](#ruby-idor) +- [RUBY-PATH — Client filenames reach send_file and File.join](#ruby-path) +- [RUBY-REDIRECT — redirect_to accepts an external return_to](#ruby-redirect) +- [RUBY-CSRF — Rails controller disables CSRF](#ruby-csrf) +- [RUBY-REGEX-ANCHOR — ^ and $ match a line inside a multiline value](#ruby-regex-anchor) +- [RUBY-YAML-VERSION — YAML.load behavior depends on Psych version](#ruby-yaml-version) +- [RUBY-DESERIALIZE-COOKIE — Signed cookies are not necessarily confidential](#ruby-deserialize-cookie) +- [RUBY-SSRF — Client input reaches Net::HTTP or open-uri](#ruby-ssrf) +- [RUBY-CALLBACKS — Callbacks cause effects before authorization](#ruby-callbacks) +- [RUBY-TLS — Ruby HTTPS peer verification disabled](#ruby-tls) +- [RUBY-REDIRECT-INPUT — Rails redirect takes request params directly](#ruby-redirect-input) + + + +## RUBY-OBJECT. Ruby Marshal or unsafe YAML + +**Search:** scanner rule RUBY-OBJECT. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain RUBY-OBJECT` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries. + +**Vulnerable example:** + +~~~ruby +record = Marshal.load(payload) +~~~ + +**Fix:** Use JSON or bounded YAML.safe_load with class/alias policy and schema; migrate trusted legacy data separately. + +~~~ruby +record = JSON.parse(payload) # validate DTO schema and size +~~~ + +**Verification:** Arbitrary objects are not built; old valid data works. + + + +## RUBY-SHELL. Ruby shell string + +**Search:** scanner rule RUBY-SHELL. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain RUBY-SHELL` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries. + +**Vulnerable example:** + +~~~ruby +system(command) +~~~ + +**Fix:** Use fixed executable plus separate validated argv; backticks and %x also invoke shell. + +~~~ruby +system("/usr/bin/file", "--", filename) +~~~ + +**Verification:** Metacharacters cannot become commands; normal files work. + + + +## RUBY-EVAL. Ruby eval/ERB from data + +**Search:** scanner rule RUBY-EVAL. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain RUBY-EVAL` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries. + +**Vulnerable example:** + +~~~ruby +result = eval(input) +~~~ + +**Fix:** Use trusted templates plus values or a restricted parser instead of executing data. + +~~~ruby +result = JSON.parse(input) # validate expected schema +~~~ + +**Verification:** Ruby syntax stays data; normal input parses. + + + +## RUBY-PERMIT-ALL. Rails permits all parameters + +**Search:** scanner rule RUBY-PERMIT-ALL. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain RUBY-PERMIT-ALL` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries. + +**Vulnerable example:** + +~~~ruby +attrs = params.permit! +~~~ + +**Fix:** Allowlist editable fields; choose owner/role server-side and constrain nested params separately. + +~~~ruby +attrs = params.require(:note).permit(:title, :body) +~~~ + +**Verification:** Owner/role/unknown nested fields do not apply; valid partial edits work. + +**Reference:** [primary source](https://guides.rubyonrails.org/action_controller_overview.html#strong-parameters). + + + +## RUBY-CONSTANTIZE. String selects a Ruby class + +**Search:** scanner rule RUBY-CONSTANTIZE. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain RUBY-CONSTANTIZE` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries. + +**Vulnerable example:** + +~~~ruby +klass = params[:type].constantize +~~~ + +**Fix:** Use a fixed map of allowed DTO types; safe_constantize only changes lookup errors, not the allowed classes. + +~~~ruby +klass = {"text" => TextNote}.fetch(validated_type) +~~~ + +**Verification:** Unknown types cannot create objects; valid types remain compatible. + +**Reference:** [primary source](https://api.rubyonrails.org/classes/ActiveSupport/Inflector.html). + + + +## RUBY-HTML-SAFE. Ruby html_safe/raw + +**Search:** scanner rule RUBY-HTML-SAFE. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain RUBY-HTML-SAFE` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries. + +**Vulnerable example:** + +~~~ruby +value = params[:text].html_safe +~~~ + +**Fix:** Use context-appropriate autoescape or a sanitizer for permitted HTML; HTML data is not ERB source. + +~~~ruby +value = params[:text] # render with automatic escaping +~~~ + +**Verification:** Tags/quotes remain text and approved formatting works. + +**Reference:** [primary source](https://guides.rubyonrails.org/security.html). + + + +## RUBY-SQL. Ruby SQL interpolation + +**Search:** scanner rule RUBY-SQL. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain RUBY-SQL` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries. + +**Vulnerable example:** + +~~~ruby +Note.where("title = '#{title}'") +~~~ + +**Fix:** Bind values with the ORM/driver API; select identifiers from a server allowlist. + +~~~ruby +Note.where(title: title, owner_id: current_user.id) +~~~ + +**Verification:** Quotes remain values and tenant/owner conditions hold. + +**Reference:** [primary source](https://guides.rubyonrails.org/active_record_querying.html). + + + +## RUBY-IDOR. ActiveRecord lookup outside the owner's scope + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e '\.find\(|find_by|params\[:id\]|current_user' . +~~~ + +Review read/update/destroy/export and association scopes; strong parameters do not authorize an object. + +**Vulnerable example:** + +`Note.find(params[:id])` can retrieve any user's record. + +**Fix:** Query through `current_user.notes` or an explicit policy/shared-access scope; never take the owner from request parameters. + +**Verification:** Owner, other user, anonymous caller, export/deletion and intended sharing. + +**Reference:** [primary source](https://cheatsheetseries.owasp.org/cheatsheets/Authorization_Cheat_Sheet.html). + + + +## RUBY-PATH. Client filenames reach send_file and File.join + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'send_file|File.join|File.read|Pathname|realpath' . +~~~ + +Trace the filename to the open operation; join does not enforce containment, and realpath alone does not prevent TOCTOU. + +**Vulnerable example:** + +`send_file(params[:path])` selects an arbitrary resource. + +**Fix:** Resolve a server-side storage ID after policy checks; control the root and symlinks, bound the response and set Content-Disposition. + +**Verification:** Another owner's ID, absolute path, outward symlink and legitimate download. + + + +## RUBY-REDIRECT. redirect_to accepts an external return_to + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'redirect_to|return_to|allow_other_host|url_from' . +~~~ + +Check the installed Rails version and open-redirect protection settings; a raw return_to value is not a trusted URL. + +**Vulnerable example:** + +A parameter or `allow_other_host` permits an external destination. + +**Fix:** Use a server-side route map or the installed Rails version's safe redirect mechanism with host validation. + +**Verification:** Internal navigation works; external origins and ambiguous paths fail. + +**Reference:** [primary source](https://guides.rubyonrails.org/security.html). + + + +## RUBY-CSRF. Rails controller disables CSRF + +**Search:** scanner rule RUBY-CSRF. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain RUBY-CSRF` for details. Regex: skip_forgery_protection, skip_before_action/filter :verify_authenticity_token and allow_forgery_protection=false. Review only/except conditions. + +Additional manual search for forms outside automatic coverage: + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'skip_forgery_protection|skip_before_action|protect_from_forgery|csrf' . +~~~ + +Review controller exceptions and cookie authentication on JSON endpoints. + +**Vulnerable example:** + +The cookie session remains active while CSRF middleware is disabled for API convenience. + +**Fix:** Restore browser CSRF; narrow exceptions to an independently authenticated stateless API/webhook. + +**Verification:** Valid POST works; missing/wrong authenticity token fails; authorized webhooks work. + +**Reference:** [primary source](https://guides.rubyonrails.org/security.html). + +**Scanner example before:** + +~~~ruby +skip_forgery_protection +skip_before_action :verify_authenticity_token +~~~ + +**Fix template:** + +~~~ruby +protect_from_forgery with: :exception +~~~ + +Primary documentation: [reference 1](https://api.rubyonrails.org/classes/ActionController/RequestForgeryProtection/ClassMethods.html). + + + +## RUBY-REGEX-ANCHOR. ^ and $ match a line inside a multiline value + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'validates|format:|Regexp|match\?|\^|\$' . +~~~ + +Distinguish line boundaries from whole-field boundaries; test newlines and regexp timeouts. + +**Vulnerable example:** + +A name validator uses ^...$ and accepts one matching line inside a larger value. + +**Fix:** Use `\A` and `\z` for the whole value, plus type/length checks; explicitly define the contract if multiline input is allowed. + +**Verification:** Newlines at the beginning, end and middle, plus ordinary Unicode. + +**Reference:** [primary source](https://guides.rubyonrails.org/security.html). + + + +## RUBY-YAML-VERSION. YAML.load behavior depends on Psych version + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'YAML.load|Psych.load|safe_load|unsafe_load|Gemfile.lock' . +~~~ + +Check the actual Psych/Ruby version and permitted classes/aliases; RUBY-OBJECT deliberately does not classify every load as unsafe. + +**Vulnerable example:** + +The application assumes new Psych's safe semantics but runs an older object-instantiating version. + +**Fix:** Explicit safe_load with minimal permitted types and a schema; pin compatible dependencies locally. + +**Verification:** Arbitrary classes/aliases and legitimate legacy documents on the actual runtime. + +**Reference:** [primary source](https://docs.ruby-lang.org/en/3.3/Psych.html). + + + +## RUBY-DESERIALIZE-COOKIE. Signed cookies are not necessarily confidential + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'cookies.signed|cookies.encrypted|session\[|secret_key_base' . +~~~ + +Inspect cookie contents; distinguish integrity from encryption, and possession of a signing key from authorization to an object. + +**Vulnerable example:** + +Private text is placed in a signed cookie under the mistaken assumption that the signature hides it. + +**Fix:** Use encrypted cookies or server-side session storage for confidentiality; minimize data and lifetime and plan safe key rotation. + +**Verification:** Normal sessions remain readable, clients cannot see private contents, and tampering is rejected. + + + +## RUBY-SSRF. Client input reaches Net::HTTP or open-uri + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'Net::HTTP|URI.open|open-uri|Faraday|HTTParty' . +~~~ + +Find URL parsing, redirects and DNS resolution in the actual adapter. + +**Vulnerable example:** + +A URL or redirect reaches an internal resource using the application's trust. + +**Fix:** Use a fixed destination or a unified policy for every redirect and connection, with limits; URI.parse is not authorization. + +**Verification:** Mock redirects/DNS, prohibited schemes, timeouts and the legitimate upstream. + +**Reference:** [primary source](https://cheatsheetseries.owasp.org/cheatsheets/Server_Side_Request_Forgery_Prevention_Cheat_Sheet.html). + + + +## RUBY-CALLBACKS. Callbacks cause effects before authorization + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'before_save|after_save|after_commit|after_find|validate|authorize' . +~~~ + +Compare the ordering of policy checks, instantiation, callbacks and transaction boundaries. + +**Vulnerable example:** + +A model writes a file or queues a task in a callback before authorization or commit. + +**Fix:** Authorize before mutation; perform external effects after confirmed commit with contractual idempotency and compensation. + +**Verification:** Rollback/denial leaves no effects; repeated tasks do not duplicate results. + + + +## RUBY-TLS. Ruby HTTPS peer verification disabled + +**Search:** scanner rule RUBY-TLS. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain RUBY-TLS` for details. Regex: VERIFY_NONE. Does not establish whether the object is used for a real connection. + +**Vulnerable example:** VERIFY_NONE leaves the TLS connection unverified. + +~~~ruby +http.verify_mode = OpenSSL::SSL::VERIFY_NONE +~~~ + +**Fix:** Restore peer/hostname checks and the trusted CA; verify actual HTTP client settings. + +~~~ruby +http.verify_mode = OpenSSL::SSL::VERIFY_PEER +http.ca_file = trusted_ca_file +~~~ + +**Verification:** Correct server works; invalid certificates cannot yield useful responses. + +Primary documentation: [reference 1](https://docs.ruby-lang.org/en/master/OpenSSL/SSL/SSLContext.html). + + + +## RUBY-REDIRECT-INPUT. Rails redirect takes request params directly + +**Search:** scanner rule RUBY-REDIRECT-INPUT. Use `--explain RUBY-REDIRECT-INPUT` for the exact detector contract. Regex with lexical exclusions: redirect_to with params[...] or request.params[...], with optional opening parenthesis. Framework defaults may already reject external hosts; aliases, helpers and allow_other_host configuration need review. + +**Vulnerable example:** + +~~~ruby +redirect_to params[:next] +~~~ + +**Fix:** Use server-selected routes or an explicit redirect policy; preserve Rails' host checks and review the installed framework version. + +~~~ruby +redirect_to account_path +~~~ + +**Verification:** Foreign and scheme-relative destinations fail; legitimate navigation works. + +[Primary reference 1](https://api.rubyonrails.org/classes/ActionController/Redirecting.html) diff --git a/docs/vulnerabilities/rust-RU.md b/docs/vulnerabilities/rust-RU.md new file mode 100644 index 0000000..a30a1d7 --- /dev/null +++ b/docs/vulnerabilities/rust-RU.md @@ -0,0 +1,512 @@ + + +# Rust: поиск и исправление + +[English](rust.md) | Русский + +[Вся база](README-RU.md) · [Сканер](../offline-scanner-RU.md) · [Проверка патча](../patch-validation-RU.md) + +18 разделов. Формат: **Поиск → Уязвимый вариант → Исправление → Проверка**. +Команды `rg` выполняются в корне локальной копии сервиса и только читают файлы. Субъект/владелец определяется по проверенной сессии, а не данным запроса. Примеры нужно адаптировать к реальным API и контракту. + +Автоматические находки — ограниченные синтаксические сигналы для проверки. AST-анализ не разрешает типы и не отслеживает данные между функциями; regex не заменяет парсер языка. Комментарии, строки и одноимённые пользовательские API могут давать совпадения. Проверьте фактическое исполнение, входные данные, авторизацию и границы доверия. + + + +## Содержание + +- [RUST-UNSAFE-CONVERSION — Непроверенные преобразования и сырые указатели Rust](#rust-unsafe-conversion) +- [RUST-SQL-FORMAT — SQL Rust через format!](#rust-sql-format) +- [RUST-STATIC-MUT — Общее изменяемое состояние Rust](#rust-static-mut) +- [RUST-AUTHORIZATION — Типизированный ID не проверяет owner](#rust-authorization) +- [RUST-SERDE-FIELDS — serde entity принимает служебные поля](#rust-serde-fields) +- [RUST-PANIC-INPUT — unwrap и byte slicing на входе](#rust-panic-input) +- [RUST-COMMAND — Command запускает интерпретатор/опасные опции](#rust-command) +- [RUST-LOCK-AWAIT — Блокировка удерживается через await](#rust-lock-await) +- [RUST-UNBOUNDED-READ — Потенциально неограниченное чтение потока Rust](#rust-unbounded-read) +- [RUST-FFI-OWNERSHIP — FFI удерживает pointer после drop](#rust-ffi-ownership) +- [RUST-SSRF — reqwest redirects и политики URL](#rust-ssrf) +- [RUST-NUMERIC-CAST — as обрезает значение размера](#rust-numeric-cast) +- [RUST-DISTRIBUTED-CAS — Логическая гонка в распределённом состоянии](#rust-distributed-cas) +- [RUST-FFI-LENGTH — В C передаётся объявленная длина вместо длины Rust-буфера](#rust-ffi-length) +- [RUST-PATH-PREFIX — Валидация префикса имени и файловый fallback](#rust-path-prefix) +- [RUST-FFI-ABI — Несовпадение возвращаемого типа C и Rust extern](#rust-ffi-abi) +- [RUST-TLS — Rust HTTP принимает недействительный сертификат](#rust-tls) +- [RUST-JWT-VALIDATION — Rust JWT: отключены обязательные проверки](#rust-jwt-validation) + + + + + +## RUST-UNSAFE-CONVERSION. Непроверенные преобразования и сырые указатели Rust + +**Поиск:** скрипт, правило RUST-UNSAFE-CONVERSION. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain RUST-UNSAFE-CONVERSION. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API. + +**Уязвимый вариант:** + +~~~rust +let text = unsafe { std::str::from_utf8_unchecked(data) }; +~~~ + +**Исправление:** Использовать checked API; для необходимого unsafe доказать длину, выравнивание, lifetime, инициализацию и уникальность ссылок. Не убирать unsafe без понимания инвариантов. + +~~~rust +let text = std::str::from_utf8(data)?; +~~~ + +**Проверка:** Неверный UTF-8/длина/индекс, EOF; по возможности Miri/sanitizers в подготовленной среде. + + + + + +## RUST-SQL-FORMAT. SQL Rust через format! + +**Поиск:** скрипт, правило RUST-SQL-FORMAT. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain RUST-SQL-FORMAT. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API. + +**Уязвимый вариант:** + +~~~rust +sqlx::query(&format!("SELECT * FROM notes WHERE name={}", name)); +~~~ + +**Исправление:** Параметры поддержанного драйвера/ORM, identifiers из allowlist; тип SQL placeholder зависит от БД. + +~~~rust +sqlx::query("SELECT * FROM notes WHERE name=$1").bind(name); +~~~ + +**Проверка:** Кавычки — данные; условие владельца сохраняется. + + + + + +## RUST-STATIC-MUT. Общее изменяемое состояние Rust + +**Поиск:** скрипт, правило RUST-STATIC-MUT. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain RUST-STATIC-MUT. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API. + +**Уязвимый вариант:** + +~~~rust +static mut CURRENT_USER: u64 = 0; +~~~ + +**Исправление:** Mutex/atomic для настоящего shared state; principal обычно должен быть per-request, один Mutex не исправит смешение пользователей. + +~~~rust +static CURRENT_USER: std::sync::Mutex = std::sync::Mutex::new(0); +~~~ + +**Проверка:** Конкурентные запросы не делят principal; нет data race и неправильного lock scope. + +**Основание:** [первичный материал](https://doc.rust-lang.org/reference/items/static-items.html). + + + + + +## RUST-AUTHORIZATION. Типизированный ID не проверяет owner + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'Path<|State<|Extension<|find_by_id|owner|tenant' . +~~~ + +От extractor пройти до SELECT/UPDATE и проверки сессии; compile-time тип не связывает ID с пользователем. + +**Уязвимый вариант:** + +Десериализованный NoteId используется для загрузки чужой записи. + +**Исправление:** Запрос по ID и серверному owner/policy; проверка tenant у вложенных объектов и задач. + +**Проверка:** Своё/чужое/аноним, разные tenant и список/экспорт. + +**Основание:** [первичный материал](https://cheatsheetseries.owasp.org/cheatsheets/Authorization_Cheat_Sheet.html). + + + + + +## RUST-SERDE-FIELDS. serde entity принимает служебные поля + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'Deserialize|flatten|default|deny_unknown_fields|serde' . +~~~ + +Сверить DTO/entity, default role и flatten; deny_unknown_fields имеет ограничения совместимости с flatten. + +**Уязвимый вариант:** + +Клиент присылает owner/admin, default создаёт привилегию при отсутствующем поле. + +**Исправление:** Отдельный DTO с разрешёнными полями, явная валидация и серверные auth-поля; не полагаться на тип bool как проверку полномочий. + +**Проверка:** Лишнее/отсутствующее поле, null, вложенный объект и обычный payload. + + + + + +## RUST-PANIC-INPUT. unwrap и byte slicing на входе + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'unwrap\(|expect\(|\[[0-9]+\.\.|parse::<|from_utf8' . +~~~ + +Сверить Result/Option и UTF-8 границы; определить, падает task, worker или процесс при panic. + +**Уязвимый вариант:** + +parse().unwrap() либо &name[..32] паникует на неправильном/коротком/многобайтовом вводе. + +**Исправление:** Вернуть контролируемую ошибку, checked get/range и ограничение размера; не скрывать все ошибки пустым default. + +**Проверка:** Некорректный UTF-8/число, короткая строка, многобайтовая граница и штатный запрос. + + + + + +## RUST-COMMAND. Command запускает интерпретатор/опасные опции + +**Поиск:** скрипт, правило RUST-COMMAND. Запуск: python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain RUST-COMMAND. Regex: Command::new с буквальным sh/bash/dash/zsh/cmd/powershell/pwsh. Команда может быть доверенной; arg -c, переменные executable и .args проверять вручную. + +Дополнительный ручной поиск для непокрытых форм: + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'Command::new|\.arg\(|\.args\(|sh|cmd.exe' . +~~~ + +Сверить executable, каждый argv, окружение/cwd; отдельные аргументы не выключают опции программы. + +**Уязвимый вариант:** + +Command::new("sh").arg("-c").arg(input) запускает shell с клиентским текстом. + +**Исправление:** Библиотечный API или фиксированный executable/argv и политика опций/путей, bounded output/time. + +**Проверка:** Кавычки/ведущий дефис остаются данными либо отклоняются; штатная операция совместима. + + +**Сигнал сканера — пример до:** + +~~~rust +Command::new("sh").arg("-c").arg(command).output()?; +~~~ + +**Шаблон исправления:** + +~~~rust +Command::new("/usr/bin/file").arg("--").arg(validated_name).output()?; +~~~ + +Первичная документация: [документация 1](https://doc.rust-lang.org/std/process/struct.Command.html). + + + + + +## RUST-LOCK-AWAIT. Блокировка удерживается через await + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'lock\(|\.await|Mutex|RwLock|DashMap' . +~~~ + +Проверить область guard, повторный вход и порядок нескольких locks. + +**Уязвимый вариант:** + +Запрос держит lock во время I/O, второй путь ждёт ресурс и создаёт deadlock/истощение. + +**Исправление:** Минимальная критическая секция, снимок/версия и повторная атомарная проверка; не отпускать lock между auth и mutation без защиты. + +**Проверка:** Два запроса с barrier, cancellation и медленный upstream не блокируют всё приложение. + + + + + +## RUST-UNBOUNDED-READ. Потенциально неограниченное чтение потока Rust + +**Поиск:** правило сканера RUST-UNBOUNDED-READ. Точный контракт детектора: `--explain RUST-UNBOUNDED-READ`. Regex с лексическими исключениями: stream/socket/request/reader.read_to_end/read_to_string. Имена получателя — подсказки, а не типы; уже ограниченный поток может дать совпадение, другие имена и wrappers могут быть пропущены. + +Дополнительный ручной поиск форм, которые не покрывает автоматическое правило: + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'read_to_end|read_to_string|read_line|collect\(|to_bytes' . +~~~ + +Проследите ограничения фактически прочитанных байтов и затраченного времени, в том числе для chunked-потоков. + +**Уязвимый вариант:** + +Управляемый клиентом поток накапливается в памяти до EOF. + +**Исправление:** Ограничьте чтение, обнаруживайте limit+1 и задайте подходящий timeout; Read::take сам по себе молча останавливается на лимите. + +**Проверка:** Проверьте EOF, limit-1, limit, limit+1 и медленный бесконечный источник; допустимые документы максимального размера должны обрабатываться. + + +**Пример для сканера до исправления:** + +~~~rust +stream.read_to_end(&mut payload)?; +~~~ + +**Шаблон исправления:** + +~~~rust +let mut bounded = stream.take(MAX_BYTES + 1); +bounded.read_to_end(&mut payload)?; +if payload.len() as u64 > MAX_BYTES { return Err(too_large()); } +~~~ + + + + + +## RUST-FFI-OWNERSHIP. FFI удерживает pointer после drop + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'CString|into_raw|from_raw|as_ptr|extern|free' . +~~~ + +Сравнить lifetime, allocator и контракт удержания pointer обеими сторонами. + +**Уязвимый вариант:** + +C сохраняет as_ptr временного Rust-объекта; C free освобождает allocation другого allocator. + +**Исправление:** Явная передача владения и парная функция освобождения; keep-alive до callback, FFI-safe типы и обработка panic boundary. + +**Проверка:** Отложенный callback, повторное освобождение, ошибка C и штатный teardown. + +**Основание:** [первичный материал](https://doc.rust-lang.org/nomicon/ffi.html). + + + + + +## RUST-SSRF. reqwest redirects и политики URL + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'reqwest|Client::builder|redirect|Url::parse|resolve' . +~~~ + +Сверить URL, redirect policy и transport DNS; тип Url означает только успешный разбор. + +**Уязвимый вариант:** + +Разрешённый первый URL перенаправляет к другому trust zone. + +**Исправление:** Серверная карта или policy назначения на каждом переходе и реальном соединении; лимиты. + +**Проверка:** Mock DNS/redirect/timeout, обычный upstream и запрет недопустимых схем. + +**Основание:** [первичный материал](https://cheatsheetseries.owasp.org/cheatsheets/Server_Side_Request_Forgery_Prevention_Cheat_Sheet.html). + + + + + +## RUST-NUMERIC-CAST. as обрезает значение размера + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e ' as u8| as u16| as u32| as usize|wrapping_|unchecked_' . +~~~ + +Сверить исходный диапазон и целевой тип до allocation/index/DB ID. + +**Уязвимый вариант:** + +Широкое число обрезается через as, разные ID/размеры становятся одним. + +**Исправление:** TryFrom/checked arithmetic и ограничения протокола; отрицательные значения отвергать до unsigned. + +**Проверка:** Максимум, максимум+1, отрицательное и штатное значение, release/debug поведение. + + + + + +## RUST-DISTRIBUTED-CAS. Логическая гонка в распределённом состоянии + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'etcd|txn|compare|round|version' . +~~~ + +Сравнить revision при чтении и записи между workers; process-local Mutex не защищает удалённую транзакцию. + +**Уязвимый вариант:** + +**RuCTF / rustest, автор.** Несколько запросов проходили проверку одной версии +раунда и независимо записывали результат. + +**Исправление:** транзакция хранилища/CAS по версии и атомарное потребление одноразового +состояния. Mutex одного процесса недостаточен при нескольких workers. + +**Проверка:** параллельные ответы дают ровно один переход; retries не начисляют +результат дважды. + +**Вариант A/D:** Основание и версия: [исходник/разбор 1](https://github.com/HackerDom/ructf-2023/blob/0cc333e44f2ba6908ff6c5d613146e3b00173315/writeups/rustest/README.md). + +**Основание:** [первичный материал](https://github.com/HackerDom/ructf-2023/blob/0cc333e44f2ba6908ff6c5d613146e3b00173315/writeups/rustest/README.md). + + + + + +## RUST-FFI-LENGTH. В C передаётся объявленная длина вместо длины Rust-буфера + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'extern|as_ptr|as_mut_ptr|size_t|memcpy' . +~~~ + +Сопоставить pointer и length на Rust/C сторонах: длина выделенного среза, не объявленная клиентом. + +**Уязвимый вариант:** + +**DEF CON / bisbee, код.** FFI store_data получает decoded_data.as_ptr() +и независимо выбранный block_size; C копирует size байт. + +**Исправление:** проверить заявленный размер против реального среза и лимита, +передавать длину проверенного буфера. + +**Проверка:** размер меньше/равен/больше, +ошибка декодирования, пустой ввод. + +**Вариант A/D:** Основание и версия: [исходник/разбор 1](https://github.com/Nautilus-Institute/finals-2024/blob/f17456fed4ff40e6f4f1237ed4b82c242e52ec67/bisbee/src/service/src/main.rs); [исходник/разбор 2](https://github.com/Nautilus-Institute/finals-2024/blob/f17456fed4ff40e6f4f1237ed4b82c242e52ec67/bisbee/src/db/kv.c); [исходник/разбор 3](https://github.com/Nautilus-Institute/finals-2024/blob/f17456fed4ff40e6f4f1237ed4b82c242e52ec67/bisbee/src/db/kv.h); [исходник/разбор 4](https://github.com/Nautilus-Institute/finals-2024/blob/f17456fed4ff40e6f4f1237ed4b82c242e52ec67/bisbee/src/db/kv_hashmap.c); [исходник/разбор 5](https://github.com/Nautilus-Institute/finals-2024/blob/f17456fed4ff40e6f4f1237ed4b82c242e52ec67/bisbee/src/db/kv_hashmap.h); [исходник/разбор 6](https://github.com/Nautilus-Institute/finals-2024/blob/f17456fed4ff40e6f4f1237ed4b82c242e52ec67/bisbee/src/db/kv_list.c). + +**Основание:** [первичный материал](https://github.com/Nautilus-Institute/finals-2024/blob/f17456fed4ff40e6f4f1237ed4b82c242e52ec67/bisbee/src/service/src/main.rs). + + +**Вариант A/D:** в FlagDrive (ENOWARS10) ёмкость контейнера считали по всей структуре вместе со служебным флагом, а данные предназначались только для массива токена. Считать длину/ёмкость самого подмассива, отказаться от неверного reinterpretation и отдельно сохранять owner-проверку. Тест: максимальная длина токена и максимум+1 не меняют соседний признак полномочий. [Авторский разбор](https://github.com/enowars/enowars10-service-flagdrive/blob/d1575098fe2c516460136bb5fba11d9a1c4af3f7/documentation/FLAGSTORE_1.md). Это ошибка границ и преобразования памяти в конкретном сервисе, не утверждение о дефекте компилятора. + + + + + +## RUST-PATH-PREFIX. Валидация префикса имени и файловый fallback + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'username|canonicalize|create_dir|fs::read|fs::write' . +~~~ + +Сравнить проверенный префикс и целый путь; проверить UTF-8 boundary и альтернативный filesystem fallback. + +**Уязвимый вариант:** + +**DEF CON / bisbee, код.** Проверяется часть username, целое имя используется +в пути; при промахе внутренней БД происходит чтение файла. + +**Исправление:** проверять полное имя и границы UTF-8, серверный storage path, +одинаковая auth-политика основного и fallback пути. + +**Проверка:** короткое/длинное/многобайтовое имя, разделители в хвосте, промах БД. + +**Вариант A/D:** Основание и версия: [исходник/разбор 1](https://github.com/Nautilus-Institute/finals-2024/blob/f17456fed4ff40e6f4f1237ed4b82c242e52ec67/bisbee/src/service/src/main.rs); [исходник/разбор 2](https://github.com/Nautilus-Institute/finals-2024/blob/f17456fed4ff40e6f4f1237ed4b82c242e52ec67/bisbee/src/db/kv.c); [исходник/разбор 3](https://github.com/Nautilus-Institute/finals-2024/blob/f17456fed4ff40e6f4f1237ed4b82c242e52ec67/bisbee/src/db/kv.h); [исходник/разбор 4](https://github.com/Nautilus-Institute/finals-2024/blob/f17456fed4ff40e6f4f1237ed4b82c242e52ec67/bisbee/src/db/kv_hashmap.c); [исходник/разбор 5](https://github.com/Nautilus-Institute/finals-2024/blob/f17456fed4ff40e6f4f1237ed4b82c242e52ec67/bisbee/src/db/kv_hashmap.h); [исходник/разбор 6](https://github.com/Nautilus-Institute/finals-2024/blob/f17456fed4ff40e6f4f1237ed4b82c242e52ec67/bisbee/src/db/kv_list.c). + +**Основание:** [первичный материал](https://github.com/Nautilus-Institute/finals-2024/blob/f17456fed4ff40e6f4f1237ed4b82c242e52ec67/bisbee/src/service/src/main.rs). + + + + + +## RUST-FFI-ABI. Несовпадение возвращаемого типа C и Rust extern + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'extern|store_data|c_void|size_t' . +~~~ + +Сравнить C header/реализацию и Rust declaration: return type, signedness, layout и calling convention. + +**Уязвимый вариант:** + +**DEF CON / bisbee, код + header.** C store_data возвращает void, +Rust объявляет i8 и использует полученный результат для выбора fallback. + +**Исправление:** общий ABI-контракт/генерация bindings; статус только через действительно +возвращаемое значение одинакового типа, обработка ошибок без неинициализированного +результата. + +**Проверка:** build с предупреждениями, размеры/знаковость/тип результата, +штатные ошибки хранения. + +**Вариант A/D:** Основание и версия: [исходник/разбор 1](https://github.com/Nautilus-Institute/finals-2024/blob/f17456fed4ff40e6f4f1237ed4b82c242e52ec67/bisbee/src/service/src/main.rs); [исходник/разбор 2](https://github.com/Nautilus-Institute/finals-2024/blob/f17456fed4ff40e6f4f1237ed4b82c242e52ec67/bisbee/src/db/kv.c); [исходник/разбор 3](https://github.com/Nautilus-Institute/finals-2024/blob/f17456fed4ff40e6f4f1237ed4b82c242e52ec67/bisbee/src/db/kv.h); [исходник/разбор 4](https://github.com/Nautilus-Institute/finals-2024/blob/f17456fed4ff40e6f4f1237ed4b82c242e52ec67/bisbee/src/db/kv_hashmap.c); [исходник/разбор 5](https://github.com/Nautilus-Institute/finals-2024/blob/f17456fed4ff40e6f4f1237ed4b82c242e52ec67/bisbee/src/db/kv_hashmap.h); [исходник/разбор 6](https://github.com/Nautilus-Institute/finals-2024/blob/f17456fed4ff40e6f4f1237ed4b82c242e52ec67/bisbee/src/db/kv_list.c). + +**Основание:** [первичный материал](https://github.com/Nautilus-Institute/finals-2024/blob/f17456fed4ff40e6f4f1237ed4b82c242e52ec67/bisbee/src/service/src/main.rs). + + + + + +## RUST-TLS. Rust HTTP принимает недействительный сертификат + +**Поиск:** скрипт, правило RUST-TLS. Запуск: python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain RUST-TLS. Regex: danger_accept_invalid_certs/hostnames(true), включая reqwest/native-tls-подобные builders. Значения из переменных и custom verifier вручную. + +**Уязвимый вариант:** Опасные builder flags отключают проверку сертификата/имени. + +~~~rust +let client = reqwest::Client::builder().danger_accept_invalid_certs(true).build()?; +~~~ + +**Исправление:** Использовать стандартную проверку; для внутреннего CA добавить доверенный root, не отключая проверки. + +~~~rust +let client = reqwest::Client::builder().add_root_certificate(trusted_ca).build()?; +~~~ + +**Проверка:** Свой CA/hostname работает; чужой сертификат/hostname отвергнут. + +Первичная документация: [документация 1](https://docs.rs/reqwest/latest/reqwest/struct.ClientBuilder.html). + + + + + +## RUST-JWT-VALIDATION. Rust JWT: отключены обязательные проверки + +**Поиск:** скрипт, правило RUST-JWT-VALIDATION. Запуск: python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain RUST-JWT-VALIDATION. Regex: insecure_disable_signature_validation, validate_exp/validate_aud=false и старые dangerous_*decode. API зависит от версии jsonwebtoken. + +**Уязвимый вариант:** Отключённая подпись или expiry делает разобранные claims недостаточным основанием для доступа. + +~~~rust +validation.insecure_disable_signature_validation(); +validation.validate_exp = false; +~~~ + +**Исправление:** Использовать проверяющий decode с доверенным ключом и контрактом Validation; проверить результат до доступа. + +~~~rust +let mut validation = Validation::new(Algorithm::RS256); +validation.set_audience(&["notes"]); +validation.set_issuer(&["auth"]); +validation.set_required_spec_claims(&["exp", "sub", "iss", "aud"]); +~~~ + +**Проверка:** Неверная подпись, истечение и отсутствие обязательного поля отклоняются. + +Первичная документация: [документация 1](https://docs.rs/jsonwebtoken/latest/jsonwebtoken/struct.Validation.html). diff --git a/docs/vulnerabilities/rust.md b/docs/vulnerabilities/rust.md new file mode 100644 index 0000000..e24ca6b --- /dev/null +++ b/docs/vulnerabilities/rust.md @@ -0,0 +1,457 @@ +# Rust: find, fix and verify + +English | [Русский](rust-RU.md) + +[Catalog](README.md) · [Scanner](../offline-scanner.md) · [Patch verification](../patch-validation.md) + +18 sections. Each follows **Search → Vulnerable example → Fix → Verification**. +Run `rg` from a local service checkout; searches only read files. Derive the actor/owner from a verified session, not request data. Adapt examples to the actual API and contract. + +## Contents + +- [RUST-UNSAFE-CONVERSION — Rust unchecked/raw conversion](#rust-unsafe-conversion) +- [RUST-SQL-FORMAT — Rust SQL using format!](#rust-sql-format) +- [RUST-STATIC-MUT — Shared mutable Rust state](#rust-static-mut) +- [RUST-AUTHORIZATION — A typed ID does not authorize its owner](#rust-authorization) +- [RUST-SERDE-FIELDS — serde entities accept administrative fields](#rust-serde-fields) +- [RUST-PANIC-INPUT — unwrap and byte slicing on request input](#rust-panic-input) +- [RUST-COMMAND — Shell launched from Rust](#rust-command) +- [RUST-LOCK-AWAIT — Holding locks across await](#rust-lock-await) +- [RUST-UNBOUNDED-READ — Potentially unbounded Rust stream read](#rust-unbounded-read) +- [RUST-FFI-OWNERSHIP — FFI retains a pointer after drop](#rust-ffi-ownership) +- [RUST-SSRF — reqwest redirects and URL policies](#rust-ssrf) +- [RUST-NUMERIC-CAST — as truncates a size value](#rust-numeric-cast) +- [RUST-DISTRIBUTED-CAS — Logical races in distributed state](#rust-distributed-cas) +- [RUST-FFI-LENGTH — Passing declared length instead of Rust buffer length to C](#rust-ffi-length) +- [RUST-PATH-PREFIX — Prefix validation and filesystem fallback](#rust-path-prefix) +- [RUST-FFI-ABI — C and Rust extern return types disagree](#rust-ffi-abi) +- [RUST-TLS — Rust HTTP accepts invalid certificates](#rust-tls) +- [RUST-JWT-VALIDATION — Rust JWT checks disabled](#rust-jwt-validation) + + + +## RUST-UNSAFE-CONVERSION. Rust unchecked/raw conversion + +**Search:** scanner rule RUST-UNSAFE-CONVERSION. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain RUST-UNSAFE-CONVERSION` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries. + +**Vulnerable example:** + +~~~rust +let text = unsafe { std::str::from_utf8_unchecked(data) }; +~~~ + +**Fix:** Prefer checked APIs; necessary unsafe needs length, alignment, lifetime, initialization and aliasing proofs. Do not remove it blindly. + +~~~rust +let text = std::str::from_utf8(data)?; +~~~ + +**Verification:** Test invalid UTF-8/length/index and EOF; use Miri/sanitizers where prepared. + + + +## RUST-SQL-FORMAT. Rust SQL using format! + +**Search:** scanner rule RUST-SQL-FORMAT. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain RUST-SQL-FORMAT` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries. + +**Vulnerable example:** + +~~~rust +sqlx::query(&format!("SELECT * FROM notes WHERE name={}", name)); +~~~ + +**Fix:** Use driver binding and allowlisted identifiers; placeholder syntax is database-specific. + +~~~rust +sqlx::query("SELECT * FROM notes WHERE name=$1").bind(name); +~~~ + +**Verification:** Quotes remain data and ownership predicates work. + + + +## RUST-STATIC-MUT. Shared mutable Rust state + +**Search:** scanner rule RUST-STATIC-MUT. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain RUST-STATIC-MUT` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries. + +**Vulnerable example:** + +~~~rust +static mut CURRENT_USER: u64 = 0; +~~~ + +**Fix:** Use ownership or synchronized primitives with clear invariants; review all unsafe accesses and cross-request state. + +~~~rust +static CURRENT_USER: std::sync::Mutex = std::sync::Mutex::new(0); +~~~ + +**Verification:** Concurrent requests do not race or leak another user's data; ordinary operations work. + +**Reference:** [primary source](https://doc.rust-lang.org/reference/items/static-items.html). + + + +## RUST-AUTHORIZATION. A typed ID does not authorize its owner + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'Path<|State<|Extension<|find_by_id|owner|tenant' . +~~~ + +Trace extractors to SELECT/UPDATE and session verification; a compile-time type does not bind the ID to the caller. + +**Vulnerable example:** + +A deserialized NoteId loads another user's record. + +**Fix:** Query by ID plus server-derived owner/policy; check tenant boundaries for nested resources and jobs. + +**Verification:** Owner, other user, anonymous caller, cross-tenant access, lists and exports. + +**Reference:** [primary source](https://cheatsheetseries.owasp.org/cheatsheets/Authorization_Cheat_Sheet.html). + + + +## RUST-SERDE-FIELDS. serde entities accept administrative fields + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'Deserialize|flatten|default|deny_unknown_fields|serde' . +~~~ + +Compare request DTOs/entities, role defaults and flatten; deny_unknown_fields has compatibility limitations with flatten. + +**Vulnerable example:** + +The client supplies owner/admin, or a missing field's default grants privileges. + +**Fix:** A separate allowlisted DTO, explicit validation and server-derived authorization fields; a bool type is not a permission check. + +**Verification:** Extra/missing fields, nulls, nested objects and normal payloads. + + + +## RUST-PANIC-INPUT. unwrap and byte slicing on request input + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'unwrap\(|expect\(|\[[0-9]+\.\.|parse::<|from_utf8' . +~~~ + +Review Result/Option handling and UTF-8 boundaries; determine whether panic terminates a task, worker or process. + +**Vulnerable example:** + +`parse().unwrap()` or `&name[..32]` panics on malformed, short or multibyte input. + +**Fix:** Controlled errors, checked get/ranges and size bounds; do not conceal every failure with an empty default. + +**Verification:** Invalid UTF-8/numbers, short strings, multibyte boundaries and normal requests. + + + +## RUST-COMMAND. Shell launched from Rust + +**Search:** scanner rule RUST-COMMAND. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain RUST-COMMAND` for details. Regex: Command::new with literal sh/bash/dash/zsh/cmd/powershell/pwsh. A command may be trusted; review -c, variable executables and .args. + +Additional manual search for forms outside automatic coverage: + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'Command::new|\.arg\(|\.args\(|sh|cmd.exe' . +~~~ + +Review the executable, every argument, environment and cwd; separate argv do not disable a program's dangerous options. + +**Vulnerable example:** + +`Command::new("sh").arg("-c").arg(input)` gives a shell client-controlled text. + +**Fix:** Use a fixed executable, separate arguments, allowlisted options and bounded time/output. + +**Verification:** Metacharacters stay data; dangerous options cannot change behavior. + +**Scanner example before:** + +~~~rust +Command::new("sh").arg("-c").arg(command).output()?; +~~~ + +**Fix template:** + +~~~rust +Command::new("/usr/bin/file").arg("--").arg(validated_name).output()?; +~~~ + +Primary documentation: [reference 1](https://doc.rust-lang.org/std/process/struct.Command.html). + + + +## RUST-LOCK-AWAIT. Holding locks across await + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'lock\(|\.await|Mutex|RwLock|DashMap' . +~~~ + +Review guard scope, reentrancy and the ordering of multiple locks. + +**Vulnerable example:** + +A request holds a lock during I/O while another path waits on a dependent resource, causing deadlock or exhaustion. + +**Fix:** Minimize critical sections; use snapshots/versions with a repeated atomic check. Do not release a lock between authorization and mutation without equivalent protection. + +**Verification:** Barrier-controlled concurrent requests, cancellation and slow upstreams do not block the whole application. + + + +## RUST-UNBOUNDED-READ. Potentially unbounded Rust stream read + +**Search:** scanner rule RUST-UNBOUNDED-READ. Regex with lexical exclusions: stream/socket/request/reader.read_to_end/read_to_string. Receiver names are hints, not types; an already bounded receiver may match and other names/wrappers may be missed. + +Additional manual search for forms outside automatic coverage: + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'read_to_end|read_to_string|read_line|collect\(|to_bytes' . +~~~ + +Trace bounds on bytes actually read and time spent, including chunked streams. + +**Vulnerable example:** + +A client-controlled stream accumulates in memory until EOF. + +**Fix:** Bound reads, detect limit+1 and enforce an appropriate timeout; Read::take alone silently stops at its limit. + +**Verification:** Test EOF, limit-1, limit, limit+1 and a slow never-ending source; valid maximum documents work. + + +**Scanner example before:** + +~~~rust +stream.read_to_end(&mut payload)?; +~~~ + +**Fix template:** + +~~~rust +let mut bounded = stream.take(MAX_BYTES + 1); +bounded.read_to_end(&mut payload)?; +if payload.len() as u64 > MAX_BYTES { return Err(too_large()); } +~~~ + + + + +## RUST-FFI-OWNERSHIP. FFI retains a pointer after drop + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'CString|into_raw|from_raw|as_ptr|extern|free' . +~~~ + +Compare lifetimes, allocators and both sides' pointer-retention contracts. + +**Vulnerable example:** + +C retains as_ptr from a temporary Rust object, or C free releases memory belonging to another allocator. + +**Fix:** Explicit ownership transfer with a matching deallocator; keep owners alive through callbacks, use FFI-safe types and handle panic boundaries. + +**Verification:** Delayed callbacks, duplicate frees, C-side errors and normal teardown. + +**Reference:** [primary source](https://doc.rust-lang.org/nomicon/ffi.html). + + + +## RUST-SSRF. reqwest redirects and URL policies + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'reqwest|Client::builder|redirect|Url::parse|resolve' . +~~~ + +Review URL parsing, redirect policy and transport DNS; a Url value proves parsing, not permission. + +**Vulnerable example:** + +An initially permitted URL redirects into a different trust zone. + +**Fix:** A server-side destination map or destination policy on every redirect and actual connection, with limits. + +**Verification:** Mock DNS/redirects/timeouts, normal upstream access and prohibited schemes. + +**Reference:** [primary source](https://cheatsheetseries.owasp.org/cheatsheets/Server_Side_Request_Forgery_Prevention_Cheat_Sheet.html). + + + +## RUST-NUMERIC-CAST. as truncates a size value + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e ' as u8| as u16| as u32| as usize|wrapping_|unchecked_' . +~~~ + +Check source range and destination type before allocation, indexing or database lookup. + +**Vulnerable example:** + +A wide integer is truncated by as, making distinct IDs/sizes identical. + +**Fix:** TryFrom, checked arithmetic and protocol bounds; reject negative values before unsigned conversion. + +**Verification:** Maximum, maximum+1, negative and normal values under release/debug behavior. + + + +## RUST-DISTRIBUTED-CAS. Logical races in distributed state + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'etcd|txn|compare|round|version' . +~~~ + +Compare read/write revisions across workers; a process-local Mutex does not protect a remote transaction. + +**Vulnerable example:** + +**RuCTF / rustest, author write-up.** Multiple requests checked the same round version and independently recorded a result. + +**Fix:** Storage transactions/CAS on the version and atomic consumption of one-use state. A single process's Mutex is insufficient across workers. + +**Verification:** Parallel answers produce exactly one state transition; retries never score twice. + +**A/D variant:** Source and version: [source/write-up 1](https://github.com/HackerDom/ructf-2023/blob/0cc333e44f2ba6908ff6c5d613146e3b00173315/writeups/rustest/README.md). + +**Reference:** [primary source](https://github.com/HackerDom/ructf-2023/blob/0cc333e44f2ba6908ff6c5d613146e3b00173315/writeups/rustest/README.md). + + + +## RUST-FFI-LENGTH. Passing declared length instead of Rust buffer length to C + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'extern|as_ptr|as_mut_ptr|size_t|memcpy' . +~~~ + +Compare pointer/length pairs on both sides: the actual allocated slice length, not the client's claim. + +**Vulnerable example:** + +**DEF CON / bisbee, source.** FFI store_data receives decoded_data.as_ptr() and an independently selected block_size; C copies size bytes. + +**Fix:** Check declared size against the actual slice and limit; pass the validated buffer's length. + +**Verification:** Smaller, equal and larger sizes, decoding failures and empty input. + +**A/D variant:** Source and version: [source/write-up 1](https://github.com/Nautilus-Institute/finals-2024/blob/f17456fed4ff40e6f4f1237ed4b82c242e52ec67/bisbee/src/service/src/main.rs); [source/write-up 2](https://github.com/Nautilus-Institute/finals-2024/blob/f17456fed4ff40e6f4f1237ed4b82c242e52ec67/bisbee/src/db/kv.c); [source/write-up 3](https://github.com/Nautilus-Institute/finals-2024/blob/f17456fed4ff40e6f4f1237ed4b82c242e52ec67/bisbee/src/db/kv.h); [source/write-up 4](https://github.com/Nautilus-Institute/finals-2024/blob/f17456fed4ff40e6f4f1237ed4b82c242e52ec67/bisbee/src/db/kv_hashmap.c); [source/write-up 5](https://github.com/Nautilus-Institute/finals-2024/blob/f17456fed4ff40e6f4f1237ed4b82c242e52ec67/bisbee/src/db/kv_hashmap.h); [source/write-up 6](https://github.com/Nautilus-Institute/finals-2024/blob/f17456fed4ff40e6f4f1237ed4b82c242e52ec67/bisbee/src/db/kv_list.c). + +**Reference:** [primary source](https://github.com/Nautilus-Institute/finals-2024/blob/f17456fed4ff40e6f4f1237ed4b82c242e52ec67/bisbee/src/service/src/main.rs). + +**A/D variant:** In FlagDrive (ENOWARS10), capacity was calculated over a whole structure including an administrative flag, although data belonged only in the token array. Use the subarray's actual length/capacity, remove invalid reinterpretation and retain separate ownership checks. Test maximum token length and maximum+1 without changing adjacent authorization state. [Author write-up](https://github.com/enowars/enowars10-service-flagdrive/blob/d1575098fe2c516460136bb5fba11d9a1c4af3f7/documentation/FLAGSTORE_1.md). This is a service-specific memory-boundary/conversion defect, not a claim of a compiler defect. + + + +## RUST-PATH-PREFIX. Prefix validation and filesystem fallback + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'username|canonicalize|create_dir|fs::read|fs::write' . +~~~ + +Compare the validated prefix with the entire path; check UTF-8 boundaries and alternative filesystem fallbacks. + +**Vulnerable example:** + +**DEF CON / bisbee, source.** Only part of username is checked, while the full name forms a path; an internal database miss falls back to file reading. + +**Fix:** Validate the complete name and UTF-8 boundaries, select storage paths server-side, and apply identical authorization to primary and fallback paths. + +**Verification:** Short/long/multibyte names, separators in the suffix and database misses. + +**A/D variant:** Source and version: [source/write-up 1](https://github.com/Nautilus-Institute/finals-2024/blob/f17456fed4ff40e6f4f1237ed4b82c242e52ec67/bisbee/src/service/src/main.rs); [source/write-up 2](https://github.com/Nautilus-Institute/finals-2024/blob/f17456fed4ff40e6f4f1237ed4b82c242e52ec67/bisbee/src/db/kv.c); [source/write-up 3](https://github.com/Nautilus-Institute/finals-2024/blob/f17456fed4ff40e6f4f1237ed4b82c242e52ec67/bisbee/src/db/kv.h); [source/write-up 4](https://github.com/Nautilus-Institute/finals-2024/blob/f17456fed4ff40e6f4f1237ed4b82c242e52ec67/bisbee/src/db/kv_hashmap.c); [source/write-up 5](https://github.com/Nautilus-Institute/finals-2024/blob/f17456fed4ff40e6f4f1237ed4b82c242e52ec67/bisbee/src/db/kv_hashmap.h); [source/write-up 6](https://github.com/Nautilus-Institute/finals-2024/blob/f17456fed4ff40e6f4f1237ed4b82c242e52ec67/bisbee/src/db/kv_list.c). + +**Reference:** [primary source](https://github.com/Nautilus-Institute/finals-2024/blob/f17456fed4ff40e6f4f1237ed4b82c242e52ec67/bisbee/src/service/src/main.rs). + + + +## RUST-FFI-ABI. C and Rust extern return types disagree + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'extern|store_data|c_void|size_t' . +~~~ + +Compare C headers/implementation with Rust declarations: return type, signedness, layout and calling convention. + +**Vulnerable example:** + +**DEF CON / bisbee, source and header.** C store_data returns void; Rust declares i8 and uses that result to select a fallback. + +**Fix:** A shared ABI contract/generated bindings; consume status only through a real, identically typed return value. Never base error handling on an uninitialized result. + +**Verification:** Builds with warnings, size/signedness/return-type agreement and ordinary storage failures. + +**A/D variant:** Source and version: [source/write-up 1](https://github.com/Nautilus-Institute/finals-2024/blob/f17456fed4ff40e6f4f1237ed4b82c242e52ec67/bisbee/src/service/src/main.rs); [source/write-up 2](https://github.com/Nautilus-Institute/finals-2024/blob/f17456fed4ff40e6f4f1237ed4b82c242e52ec67/bisbee/src/db/kv.c); [source/write-up 3](https://github.com/Nautilus-Institute/finals-2024/blob/f17456fed4ff40e6f4f1237ed4b82c242e52ec67/bisbee/src/db/kv.h); [source/write-up 4](https://github.com/Nautilus-Institute/finals-2024/blob/f17456fed4ff40e6f4f1237ed4b82c242e52ec67/bisbee/src/db/kv_hashmap.c); [source/write-up 5](https://github.com/Nautilus-Institute/finals-2024/blob/f17456fed4ff40e6f4f1237ed4b82c242e52ec67/bisbee/src/db/kv_hashmap.h); [source/write-up 6](https://github.com/Nautilus-Institute/finals-2024/blob/f17456fed4ff40e6f4f1237ed4b82c242e52ec67/bisbee/src/db/kv_list.c). + +**Reference:** [primary source](https://github.com/Nautilus-Institute/finals-2024/blob/f17456fed4ff40e6f4f1237ed4b82c242e52ec67/bisbee/src/service/src/main.rs). + + + +## RUST-TLS. Rust HTTP accepts invalid certificates + +**Search:** scanner rule RUST-TLS. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain RUST-TLS` for details. Regex: danger_accept_invalid_certs/hostnames(true), including reqwest/native-tls-like builders. Review variable values and custom verifiers. + +**Vulnerable example:** Dangerous builder flags disable certificate/hostname validation. + +~~~rust +let client = reqwest::Client::builder().danger_accept_invalid_certs(true).build()?; +~~~ + +**Fix:** Use default validation and add the internal root CA instead of bypassing checks. + +~~~rust +let client = reqwest::Client::builder().add_root_certificate(trusted_ca).build()?; +~~~ + +**Verification:** Correct CA/host works; invalid certificates/hostnames fail. + +Primary documentation: [reference 1](https://docs.rs/reqwest/latest/reqwest/struct.ClientBuilder.html). + + + +## RUST-JWT-VALIDATION. Rust JWT checks disabled + +**Search:** scanner rule RUST-JWT-VALIDATION. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain RUST-JWT-VALIDATION` for details. Regex: insecure_disable_signature_validation, validate_exp/validate_aud=false and legacy dangerous_*decode. API depends on jsonwebtoken version. + +**Vulnerable example:** Without signature or expiry validation, decoded claims are insufficient grounds for granting access. + +~~~rust +validation.insecure_disable_signature_validation(); +validation.validate_exp = false; +~~~ + +**Fix:** Use verifying decode with a trusted key and Validation contract; check its result before access. + +~~~rust +let mut validation = Validation::new(Algorithm::RS256); +validation.set_audience(&["notes"]); +validation.set_issuer(&["auth"]); +validation.set_required_spec_claims(&["exp", "sub", "iss", "aud"]); +~~~ + +**Verification:** Invalid signatures, expiry and missing required fields fail. + +Primary documentation: [reference 1](https://docs.rs/jsonwebtoken/latest/jsonwebtoken/struct.Validation.html). diff --git a/docs/vulnerabilities/sql-RU.md b/docs/vulnerabilities/sql-RU.md new file mode 100644 index 0000000..9a96353 --- /dev/null +++ b/docs/vulnerabilities/sql-RU.md @@ -0,0 +1,513 @@ + + +# SQL / базы данных: поиск и исправление + +[English](sql.md) | Русский + +[Вся база](README-RU.md) · [Сканер](../offline-scanner-RU.md) · [Проверка патча](../patch-validation-RU.md) + +18 разделов. Формат: **Поиск → Уязвимый вариант → Исправление → Проверка**. +Команды `rg` выполняются в корне локальной копии сервиса и только читают файлы. Субъект/владелец определяется по проверенной сессии, а не данным запроса. Примеры нужно адаптировать к реальным API и контракту. + +Автоматические находки — ограниченные синтаксические сигналы для проверки. AST-анализ не разрешает типы и не отслеживает данные между функциями; regex не заменяет парсер языка. Комментарии, строки и одноимённые пользовательские API могут давать совпадения. Проверьте фактическое исполнение, входные данные, авторизацию и границы доверия. + + + +## Содержание + +- [SQL-UPSERT — Upsert/replace требует проверки владельца](#sql-upsert) +- [SQL-DEFINER — SECURITY DEFINER и доверие search_path](#sql-definer) +- [SQL-BYPASSRLS — Роль приложения обходит RLS](#sql-bypassrls) +- [SQL-PUBLIC-GRANT — Широкая выдача прав PUBLIC](#sql-public-grant) +- [SQL-RLS-POLICY — RLS: USING, WITH CHECK и объединение политик](#sql-rls-policy) +- [SQL-IDENTIFIERS — Параметры не подставляют имена таблиц и ORDER BY](#sql-identifiers) +- [SQL-COLLATION — Разная канонизация в auth и unique constraint](#sql-collation) +- [SQL-TRANSACTION — Проверка и изменение вне одной атомарной операции](#sql-transaction) +- [SQL-POOL-CONTEXT — Пул соединений сохраняет tenant/search_path](#sql-pool-context) +- [SQL-SQLITE-FK — SQLite foreign_keys явно отключён](#sql-sqlite-fk) +- [SQL-MYSQL-PRIVILEGES — MySQL FILE и административные права app](#sql-mysql-privileges) +- [SQL-SECOND-ORDER — Сохранённое значение снова становится SQL](#sql-second-order) +- [SQL-NESTED-DSL — Несколько уровней языка запроса](#sql-nested-dsl) +- [SQL-RLS-DISABLE — PostgreSQL RLS отключают для таблицы](#sql-rls-disable) +- [SQL-TOKEN-PREFIX — Секретный токен проверяется по префиксу или диапазону](#sql-token-prefix) +- [SQL-NULL-AUTH — NULL меняет смысл проверки доступа](#sql-null-auth) +- [SQL-RLS-ALLOW-ALL — Безусловное выражение в политике RLS](#sql-rls-allow-all) + +- [SQL-SERVER-ROLE — Выданы роли PostgreSQL для файлов и программ сервера](#sql-server-role) + + + + + +## SQL-UPSERT. Upsert/replace требует проверки владельца + +**Поиск:** скрипт, правило SQL-UPSERT. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain SQL-UPSERT. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API. + +**Уязвимый вариант:** + +~~~sql +INSERT INTO notes(id, owner, body) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE body=VALUES(body); +~~~ + +**Исправление:** Разделить создание и обновление; нормализация/колляция до проверки, ownership в атомарном UPDATE. Проверить число изменённых строк, уникальность и транзакцию. + +~~~sql +UPDATE notes SET body=? WHERE id=? AND owner=?; +~~~ + +**Проверка:** Конфликт после case-fold/Unicode/триггера не обновляет чужую запись; штатное создание/редактирование сохранены. + +**Вариант A/D:** Нормализация ключа после проверки + upsert. **RuCTF / rusi-trainer, автор.** Поиск прав использовал исходное имя, а триггер +БД нормализовал ключ перед вставкой; конфликт превращал её в обновление. + +**Патч:** единая канонизация и колляция, разделить insert/update, ownership +в самой мутации. Замена СУБД не универсальное исправление. +**Тест:** Unicode/case-варианты, конфликт уникальности, параллельная вставка. +**Поиск:** SQL-UPSERT; триггер и сопоставление ключей вручную. + +[исходник/разбор 1](https://github.com/HackerDom/ructf-2023/blob/0cc333e44f2ba6908ff6c5d613146e3b00173315/writeups/rusi-trainer/README.md). + + + + + +## SQL-DEFINER. SECURITY DEFINER и доверие search_path + +**Поиск:** скрипт, правило SQL-DEFINER. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain SQL-DEFINER. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API. + +**Уязвимый вариант:** + +~~~sql +CREATE FUNCTION f() RETURNS int LANGUAGE sql SECURITY DEFINER AS $$ SELECT value FROM settings $$; +~~~ + +**Исправление:** Если повышенные права не нужны — INVOKER. Иначе минимальный владелец, безопасный фиксированный search_path с pg_temp в конце, schema-qualified объекты и ограниченный EXECUTE. + +~~~sql +CREATE FUNCTION f() RETURNS int LANGUAGE sql SECURITY INVOKER AS $$ SELECT value FROM app.settings $$; +~~~ + +**Проверка:** Пользователь не может подменить объект временной/доступной схемой; обычный вызов сохраняет права. + +**Основание:** [первичный материал](https://www.postgresql.org/docs/current/sql-createfunction.html). + + + + + +## SQL-BYPASSRLS. Роль приложения обходит RLS + +**Поиск:** правило сканера SQL-BYPASSRLS. Подробности: `--explain SQL-BYPASSRLS`. Ограниченный SQL-поиск: CREATE/ALTER ROLE или USER с явным SUPERUSER/BYPASSRLS. Комментарии и строки исключены; keywords без кавычек, до 300 символов. Поздние overrides, владелец таблиц, наследуемые роли и фактическая runtime-политика требуют ручной проверки. + +**Уязвимый вариант:** + +~~~sql +ALTER ROLE app BYPASSRLS; +~~~ + +**Исправление:** Отдельная роль приложения без повышенных атрибутов; владельца таблицы проверять отдельно. FORCE RLS не ограничивает superuser/BYPASSRLS. + +~~~sql +ALTER ROLE app NOBYPASSRLS NOSUPERUSER; +~~~ + +**Проверка:** SELECT/INSERT/UPDATE от реальной роли двух tenant; миграционная роль отдельно. + +**Основание:** [первичный материал](https://www.postgresql.org/docs/current/ddl-rowsecurity.html). + + + + + +## SQL-PUBLIC-GRANT. Широкая выдача прав PUBLIC + +**Поиск:** правило сканера SQL-PUBLIC-GRANT. Подробности: `--explain SQL-PUBLIC-GRANT`. Ограниченный SQL-поиск: GRANT ALL или списки SELECT/INSERT/UPDATE/DELETE/TRUNCATE/REFERENCES/TRIGGER/CREATE/USAGE/EXECUTE/CONNECT/TEMPORARY/TEMP ON object TO PUBLIC. Комментарии/строки исключены; совпадение не пересекает statements. Quoted identifiers, defaults, сложные grants, реальные права и намеренно общие объекты проверяются вручную. + +**Уязвимый вариант:** + +~~~sql +GRANT ALL ON notes TO PUBLIC; +~~~ + +**Исправление:** Выдать конкретной роли необходимые действия; проверить старые и default privileges, sequences и функции. Не отзывать права чужой инфраструктуры. + +~~~sql +GRANT SELECT, INSERT, UPDATE ON notes TO app; +~~~ + +**Проверка:** Нет доступа соседней роли; app создаёт ID/читает старые данные. + +**Основание:** [первичный материал](https://www.postgresql.org/docs/current/sql-grant.html). + + + + + +## SQL-RLS-POLICY. RLS: USING, WITH CHECK и объединение политик + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'CREATE POLICY|ROW LEVEL SECURITY|USING|WITH CHECK' . +~~~ + +Сверить роль приложения, SELECT/UPDATE/INSERT, owner bypass и OR между permissive policies. + +**Уязвимый вариант:** + +Новая широкая policy делает прежнее ограничение бесполезным либо изменение tenant не контролируется. + +**Исправление:** Политика чтения и нового состояния по контракту, тестировать effective role; ограничения RLS не заменяют object-level app policy. + +**Проверка:** Чужая строка скрыта и tenant нельзя изменить; migrations/checker работают. + +**Основание:** [первичный материал](https://www.postgresql.org/docs/current/ddl-rowsecurity.html). + + + + + +## SQL-IDENTIFIERS. Параметры не подставляют имена таблиц и ORDER BY + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'ORDER BY|table_name|column_name|quote_ident|identifier' . +~~~ + +Найти все динамические identifiers и направление сортировки, отдельно от значений. + +**Уязвимый вариант:** + +Конкатенация order/column из запроса меняет синтаксис; placeholder для имени не работает как ожидается. + +**Исправление:** Фиксированная карта допустимых identifiers/направлений, quoting API драйвера при необходимости; значения параметризовать. + +**Проверка:** Разрешённая сортировка сохраняется, неизвестное поле/направление отвергаются. + + + + + +## SQL-COLLATION. Разная канонизация в auth и unique constraint + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'COLLATE|LOWER\(|UPPER\(|UNIQUE|TRIGGER|citext' . +~~~ + +Сопоставить сравнение приложения, collation БД, trigger и уникальный индекс. + +**Уязвимый вариант:** + +Два имени различаются при проверке прав, но считаются одним при записи. + +**Исправление:** Единая канонизация до проверки/записи и стабильный owner ID; миграция конфликтов, не просто смена всей БД. + +**Проверка:** Case/Unicode/trailing spaces по реальной БД, старые ссылки и уникальность. + + + + + +## SQL-TRANSACTION. Проверка и изменение вне одной атомарной операции + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'SELECT|UPDATE|DELETE|BEGIN|FOR UPDATE|version' . +~~~ + +Сверить isolation level и where условия записи, число изменённых строк. + +**Уязвимый вариант:** + +Два запроса проходят SELECT-проверку и оба тратят ресурс/меняют чужое после смены owner. + +**Исправление:** Условный UPDATE/DELETE с owner/version/остатком, транзакция и bounded retry; выбрать нужный уровень изоляции. + +**Проверка:** Детерминированная гонка, conflict/rollback и штатная конкурентность. + + + + + +## SQL-POOL-CONTEXT. Пул соединений сохраняет tenant/search_path + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'SET ROLE|SET search_path|set_config|tenant|pool|RESET' . +~~~ + +Сравнить session-level SET и transaction-local SET; проверить возврат соединения после ошибки. + +**Уязвимый вариант:** + +Следующий запрос получает прежнюю роль/schema/tenant. + +**Исправление:** SET LOCAL в корректной транзакции либо надёжный reset; owner не из client-controlled session variable. + +**Проверка:** Два tenant на одном соединении, rollback/exception и обычный повторный запрос. + +**Основание:** [первичный материал](https://www.postgresql.org/docs/current/ddl-schemas.html). + + + + + +## SQL-SQLITE-FK. SQLite foreign_keys явно отключён + +**Поиск:** скрипт, правило SQL-SQLITE-FK. Запуск: python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain SQL-SQLITE-FK. Regex: PRAGMA foreign_keys=OFF/0/false или foreign_keys(OFF/0/false). Отсутствие ON, pool hooks и compile options требуют ручной проверки. + +Дополнительный ручной поиск для непокрытых форм: + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'PRAGMA foreign_keys|sqlite3.connect|Data Source|FOREIGN KEY' . +~~~ + +Проверить фактический PRAGMA после открытия каждого connection и до начала транзакции. + +**Уязвимый вариант:** + +DDL содержит FK, приложение считает ownership связи гарантированными, enforcement отключён. + +**Исправление:** Включить foreign_keys для каждого соединения вне транзакции, проверить результат и существующие нарушения; отдельно мигрировать некорректные записи и обработать constraint errors. + +**Проверка:** Каждое соединение сообщает foreign_keys=1; foreign_key_check не возвращает нарушений; недопустимый владелец отклоняется, каскады и старые данные совместимы. + +**Основание:** [первичный материал](https://www.sqlite.org/pragma.html#pragma_foreign_keys). + + +**Сигнал сканера — пример до:** + +~~~sql +PRAGMA foreign_keys = OFF; +~~~ + +**Шаблон исправления:** + +~~~sql +PRAGMA foreign_keys = ON; +~~~ + +Первичная документация: [документация 1](https://www.sqlite.org/foreignkeys.html). + + + + + +## SQL-MYSQL-PRIVILEGES. MySQL FILE и административные права app + +**Поиск:** скрипт, правило SQL-MYSQL-PRIVILEGES. Запуск: python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain SQL-MYSQL-PRIVILEGES. Regex: GRANT с FILE/SUPER или ALL [PRIVILEGES] ON *.*. Другие опасные dynamic privileges, роли и уже выданные права вручную. + +Дополнительный ручной поиск для непокрытых форм: + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'GRANT|FILE|SUPER|ALL PRIVILEGES|secure_file_priv|local_infile' . +~~~ + +Прочитать SHOW GRANTS своей app-роли; проверить FILE, чтение/запись и настройки LOCAL INFILE обеих сторон. + +**Уязвимый вариант:** + +Обычное приложение имеет права файлового/административного доступа, которые усиливают ошибку запроса. + +**Исправление:** Разделить runtime-аккаунт и аккаунт миграций; убрать ненужные глобальные привилегии и GRANT OPTION; ограничить hosts аккаунтов реальной топологией. Согласовать secure_file_priv и отключение ненужного LOCAL INFILE. + +**Проверка:** SHOW GRANTS содержит только необходимые права; CRUD, миграции и checker работают, операция вне полномочий отвергается; аккаунты организаторов не менять. + +**Основание:** [первичный материал](https://dev.mysql.com/doc/refman/8.4/en/privileges-provided.html). + + +**Сигнал сканера — пример до:** + +~~~sql +GRANT FILE, SUPER ON *.* TO 'app'@'%'; +~~~ + +**Шаблон исправления:** + +~~~sql +GRANT SELECT, INSERT, UPDATE, DELETE ON appdb.* TO 'app'@'localhost'; +~~~ + +Первичная документация: [документация 1](https://dev.mysql.com/doc/refman/8.4/en/privileges-provided.html). + + + + + +## SQL-SECOND-ORDER. Сохранённое значение снова становится SQL + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'execute|query|EXECUTE|format\(|quote|SELECT' . +~~~ + +Проследить значение из БД до второго запроса/export/job; хранение не делает данные доверенными. + +**Уязвимый вариант:** + +При insert значение параметризовано, позже строка из записи вставляется в динамический SQL. + +**Исправление:** Параметризация на каждом sink, включая stored procedures и jobs; отдельная карта identifiers. + +**Проверка:** Сохранённое значение с разделителем остаётся данными при последующей операции. + + + + + +## SQL-NESTED-DSL. Несколько уровней языка запроса + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'LIKE|database|tenant|parse|execute' . +~~~ + +Разделить внешний DSL, внутренний SQL и выбор базы; проверить интерпретацию разделителей на обоих уровнях. + +**Уязвимый вариант:** + +**Основание:** museumorphosis, авторский разбор RuCTF: собственный SQL DSL и +плохая граница между запросом и выбором базы. +**Искать:** SQL внутри строк другого языка, regex вместо полноценного парсера, +пользовательский текст в LIKE, имя базы/tenant. + +**Исправление:** параметры для значений на каждом уровне; выбор базы из проверенного +серверного tenant; однозначный парсер DSL. Экранирование внутреннего SQL +не доказывает безопасность внешнего языка. + +**Проверка:** разделители обоих языков, обычные wildcard согласно контракту, +попытка сменить базу, доступ только к своему tenant. + +**Вариант A/D:** Основание и версия: [исходник/разбор 1](https://github.com/HackerDom/ructf-finals-2023/blob/a7442769909e08c39716cb18d3d1c3a99324bbf8/writeups/museumorphosis/README.md). + +**Основание:** [первичный материал](https://github.com/HackerDom/ructf-finals-2023/blob/a7442769909e08c39716cb18d3d1c3a99324bbf8/writeups/museumorphosis/README.md). + + + + + +## SQL-RLS-DISABLE. PostgreSQL RLS отключают для таблицы + +**Поиск:** скрипт, правило SQL-RLS-DISABLE. Запуск: python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain SQL-RLS-DISABLE. Regex: ALTER TABLE ... DISABLE ROW LEVEL SECURITY. Отсутствие ENABLE, широкие политики и роль соединения не выводятся из текста. + +**Уязвимый вариант:** Отключение RLS снимает серверную границу строк, если доступ полагается на политики. + +~~~sql +ALTER TABLE notes DISABLE ROW LEVEL SECURITY; +~~~ + +**Исправление:** Установить нужные policies и включить RLS; runtime не должен быть superuser/BYPASSRLS. FORCE влияет на владельца, но не устраняет эти bypass-привилегии. + +~~~sql +ALTER TABLE notes ENABLE ROW LEVEL SECURITY; +ALTER TABLE notes FORCE ROW LEVEL SECURITY; +-- Install reviewed owner/tenant policies before serving traffic. +~~~ + +**Проверка:** Проверить SELECT/INSERT/UPDATE/DELETE двумя runtime субъектами и чужим tenant; migration user отдельно. + +Первичная документация: [документация 1](https://www.postgresql.org/docs/current/ddl-rowsecurity.html). + + + + + +## SQL-TOKEN-PREFIX. Секретный токен проверяется по префиксу или диапазону + +**Поиск:** скрипт, правило SQL-TOKEN-PREFIX. Запуск: python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain SQL-TOKEN-PREFIX. Regex: nonce/token/reset_token/api_key перед LIKE, >= или <= в SQL-тексте. Числовые счётчики и поиск служебных журналов могут быть допустимы; переименованные поля, substr, startsWith и сравнение части в приложении искать вручную. + +**Уязвимый вариант:** Если nonce/token является bearer-секретом, частичное совпадение резко уменьшает пространство проверки. + +~~~sql +SELECT content FROM exports WHERE username = $1 AND nonce >= $2 AND nonce < $3; +~~~ + +**Исправление:** Требовать полный канонический токен допустимой длины, точное совпадение и связь с пользователем/действием/сроком; не заменять проверку rate limit. + +~~~sql +SELECT content FROM exports WHERE username = $1 AND nonce = $2; +-- Before querying: require the full canonical token, correct length/type and purpose. +~~~ + +**Проверка:** Пустой, короткий, префиксный, лишний суффикс и токен другого пользователя отвергнуты; полный действующий токен работает. + +Первичная документация: [документация 1](https://github.com/enowars/enowars10-service-flagdrive/blob/d1575098fe2c516460136bb5fba11d9a1c4af3f7/documentation/FLAGSTORE_0.md). + + +**Вариант A/D:** авторы FlagDrive (ENOWARS10) описали выбор экспорта по короткому префиксу nonce. Исправление требует полной длины и точного равенства; правило отмечает SQL-диапазон, а смысл bearer-секрета проверяется вручную. + + + + + +## SQL-NULL-AUTH. NULL меняет смысл проверки доступа + +**Поиск:** вручную; отдельного правила сканера нет. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'NOT IN|!=|<>|IS NULL|IS NOT NULL|COALESCE|LEFT JOIN|owner|tenant' . +~~~ + +Составить таблицу TRUE/FALSE/UNKNOWN для auth-условия и результата LEFT JOIN. Проследить, как приложение превращает nullable bool в разрешение/отказ, есть ли NULL в NOT IN subquery. + +**Уязвимый вариант:** Условие отказа owner <> actor даёт UNKNOWN при NULL, и приложение проваливается в разрешённую ветку; отсутствующая ACL трактуется как default allow. + +**Исправление:** Разрешать доступ только при явно истинной положительной проверке. Где NULL недопустим — NOT NULL и целостная связь; где допустим — задать его точный смысл, не подменять владельца общим значением через COALESCE. + +**Проверка:** NULL owner, отсутствующая ACL, пустой join и NULL внутри подзапроса не дают доступа; обычные own/shared сценарии сохраняются. + +Основание: [первичная документация/материал](https://www.postgresql.org/docs/current/functions-comparison.html). Описание и рецепт адаптации составлены для этой базы. + + + + + +## SQL-RLS-ALLOW-ALL. Безусловное выражение в политике RLS + +**Поиск:** правило сканера SQL-RLS-ALLOW-ALL. Точный контракт детектора: `--explain SQL-RLS-ALLOW-ALL`. Regex с лексическими исключениями: USING(true) или WITH CHECK(true). Может быть намеренным; правило не связывает выражения с CREATE POLICY, ролями и командами. Фактические политики и авторизация приложения требуют проверки. + +**Уязвимый вариант:** + +~~~sql +CREATE POLICY open_notes ON notes USING (true); +~~~ + +**Исправление:** Определите выражения USING и WITH CHECK с учётом ролей и арендаторов для реальной модели идентификации; проверьте сочетания разрешающих политик и роли, обходящие RLS. + +~~~sql +CREATE POLICY owned_notes ON notes USING (owner_id = current_user); +~~~ + +**Проверка:** Два пользователя времени исполнения не могут читать или менять строки друг друга; INSERT и UPDATE проверяют нужного владельца, а допустимые операции работают. + +[Первичный источник 1](https://www.postgresql.org/docs/current/sql-createpolicy.html) + + + + +## SQL-SERVER-ROLE. Выданы роли PostgreSQL для файлов и программ сервера + +**Поиск:** правило сканера SQL-SERVER-ROLE. Подробности: `--explain SQL-SERVER-ROLE`. Ограниченный SQL-поиск: GRANT списка ролей без кавычек, содержащего pg_read_server_files, pg_write_server_files или pg_execute_server_program перед TO. Комментарии/строки исключены; REVOKE и отдельный pg_monitor не дают сигнал. Quoted roles, наследование, поздние отзывы прав, версии и эффективные права проверяются вручную. + +**Уязвимый вариант:** + +~~~sql +GRANT pg_read_server_files TO app; +~~~ + +**Исправление:** Разделите роли приложения и администратора. Выдавайте необходимые права на объекты, а не файлы/программы сервера; проверяйте членство. Отзывайте только согласованные права своего сервиса с процедурой rollback. + +~~~sql +GRANT SELECT ON notes TO app; +~~~ + +**Проверка:** Фактическая runtime-роль не читает/пишет файлы сервера и не запускает программы; обычные запросы, миграции и восстановление работают. + +[Первичный источник](https://www.postgresql.org/docs/14/predefined-roles.html) diff --git a/docs/vulnerabilities/sql.md b/docs/vulnerabilities/sql.md new file mode 100644 index 0000000..a9090fc --- /dev/null +++ b/docs/vulnerabilities/sql.md @@ -0,0 +1,461 @@ +# SQL / databases: find, fix and verify + +English | [Русский](sql-RU.md) + +[Catalog](README.md) · [Scanner](../offline-scanner.md) · [Patch verification](../patch-validation.md) + +18 sections. Each follows **Search → Vulnerable example → Fix → Verification**. +Run `rg` from a local service checkout; searches only read files. Derive the actor/owner from a verified session, not request data. Adapt examples to the actual API and contract. + +## Contents + +- [SQL-UPSERT — Upsert/replace requires ownership review](#sql-upsert) +- [SQL-DEFINER — SECURITY DEFINER and search_path trust](#sql-definer) +- [SQL-BYPASSRLS — Application role bypasses RLS](#sql-bypassrls) +- [SQL-PUBLIC-GRANT — Broad privileges granted to PUBLIC](#sql-public-grant) +- [SQL-RLS-POLICY — RLS USING, WITH CHECK and policy composition](#sql-rls-policy) +- [SQL-IDENTIFIERS — Parameters do not substitute table names or ORDER BY](#sql-identifiers) +- [SQL-COLLATION — Authorization and uniqueness use different canonicalization](#sql-collation) +- [SQL-TRANSACTION — Check and mutation are not one atomic operation](#sql-transaction) +- [SQL-POOL-CONTEXT — Connection pools retain tenant or search_path](#sql-pool-context) +- [SQL-SQLITE-FK — SQLite foreign_keys explicitly disabled](#sql-sqlite-fk) +- [SQL-MYSQL-PRIVILEGES — MySQL runtime user has admin privileges](#sql-mysql-privileges) +- [SQL-SECOND-ORDER — Stored data becomes SQL again](#sql-second-order) +- [SQL-NESTED-DSL — Multiple query-language layers](#sql-nested-dsl) +- [SQL-RLS-DISABLE — PostgreSQL table RLS disabled](#sql-rls-disable) +- [SQL-TOKEN-PREFIX — Secret token checked by prefix or range](#sql-token-prefix) +- [SQL-NULL-AUTH — NULL changes authorization logic](#sql-null-auth) +- [SQL-RLS-ALLOW-ALL — RLS policy has an unconditional expression](#sql-rls-allow-all) +- [SQL-SERVER-ROLE — PostgreSQL server file/program role granted](#sql-server-role) + + + +## SQL-UPSERT. Upsert/replace requires ownership review + +**Search:** scanner rule SQL-UPSERT. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain SQL-UPSERT` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries. + +**Vulnerable example:** + +~~~sql +INSERT INTO notes(id, owner, body) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE body=VALUES(body); +~~~ + +**Fix:** Separate create/update, normalize before authorization, enforce ownership in atomic UPDATE and check rows, uniqueness and transactions. + +~~~sql +UPDATE notes SET body=? WHERE id=? AND owner=?; +~~~ + +**Verification:** Case/Unicode/trigger conflicts cannot update another owner; normal edits work. + +**A/D variant:** Key normalization after authorization plus upsert. **RuCTF / rusi-trainer, author write-up.** Authorization used the original name, but a database trigger normalized the key before insertion; a conflict converted the insert into an update. + +**Patch:** Apply consistent canonicalization/collation, separate insert from update, and enforce ownership in the mutation itself. Switching database engines is not a universal fix. +**Test:** Unicode/case variants, uniqueness conflicts and concurrent inserts. +**Search:** SQL-UPSERT; review triggers and key comparison manually. + +[Source/write-up 1](https://github.com/HackerDom/ructf-2023/blob/0cc333e44f2ba6908ff6c5d613146e3b00173315/writeups/rusi-trainer/README.md). + + + +## SQL-DEFINER. SECURITY DEFINER and search_path trust + +**Search:** scanner rule SQL-DEFINER. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain SQL-DEFINER` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries. + +**Vulnerable example:** + +~~~sql +CREATE FUNCTION f() RETURNS int LANGUAGE sql SECURITY DEFINER AS $$ SELECT value FROM settings $$; +~~~ + +**Fix:** Prefer INVOKER unless elevated rights are needed; otherwise use a minimal owner, fixed safe search_path with pg_temp last, qualified names and restricted EXECUTE. + +~~~sql +CREATE FUNCTION f() RETURNS int LANGUAGE sql SECURITY INVOKER AS $$ SELECT value FROM app.settings $$; +~~~ + +**Verification:** Callers cannot replace objects using temporary/writable schemas; valid calls work. + +**Reference:** [primary source](https://www.postgresql.org/docs/current/sql-createfunction.html). + + + +## SQL-BYPASSRLS. Application role bypasses RLS + +**Search:** scanner rule SQL-BYPASSRLS. Use `--explain SQL-BYPASSRLS` for the exact detector contract. Bounded SQL: CREATE/ALTER ROLE or USER with explicit SUPERUSER/BYPASSRLS, comments and quoted strings excluded, unquoted keywords and statements up to 300 characters. Later overrides, ownership, inherited roles and effective runtime policy remain manual. + +**Vulnerable example:** + +~~~sql +ALTER ROLE app BYPASSRLS; +~~~ + +**Fix:** Use a runtime role without elevated attributes and review table ownership separately; FORCE RLS does not constrain superuser/BYPASSRLS. + +~~~sql +ALTER ROLE app NOBYPASSRLS NOSUPERUSER; +~~~ + +**Verification:** Actual runtime roles for two tenants cannot cross boundaries; migration role is separate. + +**Reference:** [primary source](https://www.postgresql.org/docs/current/ddl-rowsecurity.html). + + + +## SQL-PUBLIC-GRANT. Broad privileges granted to PUBLIC + +**Search:** scanner rule SQL-PUBLIC-GRANT. Use `--explain SQL-PUBLIC-GRANT` for the exact detector contract. Bounded SQL: GRANT ALL or SELECT/INSERT/UPDATE/DELETE/TRUNCATE/REFERENCES/TRIGGER/CREATE/USAGE/EXECUTE/CONNECT/TEMPORARY/TEMP privilege lists ON an object TO PUBLIC. Comments/strings excluded; no cross-statement matching. Quoted identifiers, defaults, complex grants, effective rights and intentional public objects remain manual. + +**Vulnerable example:** + +~~~sql +GRANT ALL ON notes TO PUBLIC; +~~~ + +**Fix:** Grant only required actions to specific roles; review existing/default privileges, sequences and functions. Never revoke unrelated infrastructure rights. + +~~~sql +GRANT SELECT, INSERT, UPDATE ON notes TO app; +~~~ + +**Verification:** Neighbor roles cannot read data; app ID generation and old records work. + +**Reference:** [primary source](https://www.postgresql.org/docs/current/sql-grant.html). + + + +## SQL-RLS-POLICY. RLS USING, WITH CHECK and policy composition + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'CREATE POLICY|ROW LEVEL SECURITY|USING|WITH CHECK' . +~~~ + +Review the application role, SELECT/UPDATE/INSERT, owner bypass and OR composition between permissive policies. + +**Vulnerable example:** + +A new broad policy makes an earlier restriction ineffective, or a tenant-changing update is unchecked. + +**Fix:** Define policies for reads and resulting row state according to the contract; test the effective role. RLS does not replace application object-level authorization. + +**Verification:** Other tenants' rows stay hidden, tenant changes are denied, and migrations/checkers still work. + +**Reference:** [primary source](https://www.postgresql.org/docs/current/ddl-rowsecurity.html). + + + +## SQL-IDENTIFIERS. Parameters do not substitute table names or ORDER BY + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'ORDER BY|table_name|column_name|quote_ident|identifier' . +~~~ + +Find dynamic identifiers and sorting directions separately from data values. + +**Vulnerable example:** + +Concatenated request order/column values change syntax; an identifier placeholder does not behave as expected. + +**Fix:** Map allowed identifiers/directions explicitly, using the driver's quoting API where required; parameterize values. + +**Verification:** Permitted sorting remains available; unknown fields/directions are rejected. + + + +## SQL-COLLATION. Authorization and uniqueness use different canonicalization + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'COLLATE|LOWER\(|UPPER\(|UNIQUE|TRIGGER|citext' . +~~~ + +Compare application equality, database collation, triggers and the unique index. + +**Vulnerable example:** + +Two names differ during authorization but identify the same row during a write. + +**Fix:** Canonicalize consistently before both checks and writes; use stable owner IDs and migrate conflicts rather than merely switching databases. + +**Verification:** Case, Unicode and trailing spaces on the actual database, including old references and uniqueness. + + + +## SQL-TRANSACTION. Check and mutation are not one atomic operation + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'SELECT|UPDATE|DELETE|BEGIN|FOR UPDATE|version' . +~~~ + +Review isolation level, write predicates and affected-row counts. + +**Vulnerable example:** + +Two requests pass a SELECT check and both spend the resource or modify an object after ownership changes. + +**Fix:** Conditional UPDATE/DELETE with owner/version/balance predicates, transactions and bounded retries; choose the necessary isolation level. + +**Verification:** Deterministic races, conflicts/rollback and legitimate concurrency. + + + +## SQL-POOL-CONTEXT. Connection pools retain tenant or search_path + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'SET ROLE|SET search_path|set_config|tenant|pool|RESET' . +~~~ + +Distinguish session SET from transaction-local SET; inspect connection return after exceptions. + +**Vulnerable example:** + +The next request inherits the previous role, schema or tenant. + +**Fix:** SET LOCAL inside the correct transaction or reliable reset; do not derive ownership from client-controlled session variables. + +**Verification:** Two tenants sharing a connection, rollback/exceptions and ordinary subsequent requests. + +**Reference:** [primary source](https://www.postgresql.org/docs/current/ddl-schemas.html). + + + +## SQL-SQLITE-FK. SQLite foreign_keys explicitly disabled + +**Search:** scanner rule SQL-SQLITE-FK. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain SQL-SQLITE-FK` for details. Regex: PRAGMA foreign_keys=OFF/0/false or foreign_keys(OFF/0/false). Review missing ON, pool hooks and compile options. + +Additional manual search for forms outside automatic coverage: + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'PRAGMA foreign_keys|sqlite3.connect|Data Source|FOREIGN KEY' . +~~~ + +Check the effective PRAGMA after every connection opens and before a transaction begins. + +**Vulnerable example:** + +The DDL declares foreign keys and the app trusts ownership relationships, but enforcement is disabled. + +**Fix:** Enable FK on every connection outside transactions, verify the result and existing violations, and migrate invalid records separately. + +**Verification:** Every connection reports foreign_keys=1; foreign_key_check is empty and invalid owners fail. + +**Reference:** [primary source](https://www.sqlite.org/pragma.html#pragma_foreign_keys). + +**Scanner example before:** + +~~~sql +PRAGMA foreign_keys = OFF; +~~~ + +**Fix template:** + +~~~sql +PRAGMA foreign_keys = ON; +~~~ + +Primary documentation: [reference 1](https://www.sqlite.org/foreignkeys.html). + + + +## SQL-MYSQL-PRIVILEGES. MySQL runtime user has admin privileges + +**Search:** scanner rule SQL-MYSQL-PRIVILEGES. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain SQL-MYSQL-PRIVILEGES` for details. Regex: GRANT with FILE/SUPER or ALL [PRIVILEGES] ON *.*. Review other dangerous dynamic privileges, roles and existing grants. + +Additional manual search for forms outside automatic coverage: + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'GRANT|FILE|SUPER|ALL PRIVILEGES|secure_file_priv|local_infile' . +~~~ + +Read SHOW GRANTS for the application's own role; review FILE, file read/write and both sides of LOCAL INFILE configuration. + +**Vulnerable example:** + +An ordinary application has filesystem or administrative privileges that amplify a query bug. + +**Fix:** Separate runtime/migration accounts; remove unnecessary global grants and GRANT OPTION; match account hosts to topology. + +**Verification:** SHOW GRANTS contains only required actions; migrations/checker still work. + +**Reference:** [primary source](https://dev.mysql.com/doc/refman/8.4/en/privileges-provided.html). + +**Scanner example before:** + +~~~sql +GRANT FILE, SUPER ON *.* TO 'app'@'%'; +~~~ + +**Fix template:** + +~~~sql +GRANT SELECT, INSERT, UPDATE, DELETE ON appdb.* TO 'app'@'localhost'; +~~~ + +Primary documentation: [reference 1](https://dev.mysql.com/doc/refman/8.4/en/privileges-provided.html). + + + +## SQL-SECOND-ORDER. Stored data becomes SQL again + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'execute|query|EXECUTE|format\(|quote|SELECT' . +~~~ + +Trace stored values into subsequent queries, exports and jobs; persistence does not make data trusted. + +**Vulnerable example:** + +The insert parameterizes a value, but a later operation concatenates it into SQL. + +**Fix:** Parameterize every sink, including stored procedures and jobs; use a separate identifier allowlist. + +**Verification:** A stored delimiter remains data in every subsequent operation. + + + +## SQL-NESTED-DSL. Multiple query-language layers + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'LIKE|database|tenant|parse|execute' . +~~~ + +Separate the outer DSL, inner SQL and database selection; inspect how both layers interpret delimiters. + +**Vulnerable example:** + +**Reference:** The museumorphosis author write-up from RuCTF describes a custom SQL DSL with an unsafe boundary between query text and database selection. +**Search:** SQL inside another language's strings, regex instead of a real parser, user-controlled LIKE text and database/tenant names. + +**Fix:** Parameterize values at each layer; derive database selection from a verified server-side tenant and use an unambiguous DSL parser. Escaping inner SQL does not prove the outer language safe. + +**Verification:** Delimiters of both languages, contractual wildcards, attempted database changes and access restricted to the correct tenant. + +**A/D variant:** Source and version: [source/write-up 1](https://github.com/HackerDom/ructf-finals-2023/blob/a7442769909e08c39716cb18d3d1c3a99324bbf8/writeups/museumorphosis/README.md). + +**Reference:** [primary source](https://github.com/HackerDom/ructf-finals-2023/blob/a7442769909e08c39716cb18d3d1c3a99324bbf8/writeups/museumorphosis/README.md). + + + +## SQL-RLS-DISABLE. PostgreSQL table RLS disabled + +**Search:** scanner rule SQL-RLS-DISABLE. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain SQL-RLS-DISABLE` for details. Regex: ALTER TABLE ... DISABLE ROW LEVEL SECURITY. Does not infer missing ENABLE, broad policies or connection role. + +**Vulnerable example:** Disabling RLS removes the server-side row boundary when access depends on its policies. + +~~~sql +ALTER TABLE notes DISABLE ROW LEVEL SECURITY; +~~~ + +**Fix:** Install intended policies and enable RLS; runtime must not be superuser/BYPASSRLS. FORCE constrains table owners, not these bypass roles. + +~~~sql +ALTER TABLE notes ENABLE ROW LEVEL SECURITY; +ALTER TABLE notes FORCE ROW LEVEL SECURITY; +-- Install reviewed owner/tenant policies before serving traffic. +~~~ + +**Verification:** Test SELECT/INSERT/UPDATE/DELETE with two runtime identities/tenants and separate migration role. + +Primary documentation: [reference 1](https://www.postgresql.org/docs/current/ddl-rowsecurity.html). + + + +## SQL-TOKEN-PREFIX. Secret token checked by prefix or range + +**Search:** scanner rule SQL-TOKEN-PREFIX. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain SQL-TOKEN-PREFIX` for details. Regex: nonce/token/reset_token/api_key before LIKE, >= or <= in SQL text. Counters/log searches may be legitimate; inspect renamed fields, substr, startsWith and application-side partial comparisons. + +**Vulnerable example:** If a nonce/token is a bearer secret, partial matching drastically reduces the effective search space. + +~~~sql +SELECT content FROM exports WHERE username = $1 AND nonce >= $2 AND nonce < $3; +~~~ + +**Fix:** Require the complete canonical token with valid length/type, exact equality and binding to user/purpose/expiry; rate limiting is separate. + +~~~sql +SELECT content FROM exports WHERE username = $1 AND nonce = $2; +-- Before querying: require the full canonical token, correct length/type and purpose. +~~~ + +**Verification:** Empty, short, prefix, extra-suffix and foreign-user tokens fail; complete valid tokens work. + +Primary documentation: [reference 1](https://github.com/enowars/enowars10-service-flagdrive/blob/d1575098fe2c516460136bb5fba11d9a1c4af3f7/documentation/FLAGSTORE_0.md). + +**A/D variant:** FlagDrive's ENOWARS10 authors describe selecting exports by a short nonce prefix. Require full length and exact equality; the rule flags SQL range comparisons, while the bearer-secret meaning requires manual review. + + + +## SQL-NULL-AUTH. NULL changes authorization logic + +**Search:** manual review; no separate scanner rule. + +~~~bash +rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'NOT IN|!=|<>|IS NULL|IS NOT NULL|COALESCE|LEFT JOIN|owner|tenant' . +~~~ + +Construct a TRUE/FALSE/UNKNOWN table for authorization conditions and LEFT JOIN results. Trace nullable booleans into allow/deny decisions and check for NULL inside NOT IN subqueries. + +**Vulnerable example:** A denial condition `owner <> actor` becomes UNKNOWN for NULL and execution falls through to allow; missing ACL entries become default allow. + +**Fix:** Permit access only for an explicitly true positive check. Use NOT NULL and referential integrity where NULL is invalid; otherwise define its exact meaning. Do not merge owners into a shared COALESCE default. + +**Verification:** NULL owners, missing ACLs, empty joins and NULL subquery values never grant access; ordinary own/shared cases remain valid. + +Reference: [primary documentation](https://www.postgresql.org/docs/current/functions-comparison.html). The explanation and adaptation recipe were written for this catalog. + + + +## SQL-RLS-ALLOW-ALL. RLS policy has an unconditional expression + +**Search:** scanner rule SQL-RLS-ALLOW-ALL. Use `--explain SQL-RLS-ALLOW-ALL` for the exact detector contract. Regex with lexical exclusions: USING(true) or WITH CHECK(true). May be intentional and does not associate expressions with CREATE POLICY, roles or commands; effective policies and application authorization require review. + +**Vulnerable example:** + +~~~sql +CREATE POLICY open_notes ON notes USING (true); +~~~ + +**Fix:** Define role/tenant-aware USING and WITH CHECK expressions for the actual identity model; review permissive-policy combinations and bypass roles. + +~~~sql +CREATE POLICY owned_notes ON notes USING (owner_id = current_user); +~~~ + +**Verification:** Two runtime identities cannot read/change each other's rows; inserts and updates enforce the intended owner and valid operations work. + +[Primary reference 1](https://www.postgresql.org/docs/current/sql-createpolicy.html) + + + +## SQL-SERVER-ROLE. PostgreSQL server file/program role granted + +**Search:** scanner rule SQL-SERVER-ROLE. Use `--explain SQL-SERVER-ROLE` for details. Bounded SQL: unquoted GRANT role lists containing pg_read_server_files, pg_write_server_files or pg_execute_server_program before TO. Comments/strings excluded; REVOKE and pg_monitor alone do not signal. Quoted roles, inheritance, later revocations, versions and effective permissions remain manual. + +**Vulnerable example:** + +~~~sql +GRANT pg_read_server_files TO app; +~~~ + +**Fix:** Separate application and administrator roles. Grant only required object privileges, not server file/program access; review memberships and revoke only approved service-owned grants with rollback. + +~~~sql +GRANT SELECT ON notes TO app; +~~~ + +**Verification:** The actual runtime role cannot read/write server files or execute server programs; ordinary queries, migrations and recovery still work. + +[Primary reference](https://www.postgresql.org/docs/14/predefined-roles.html) diff --git a/durka.py b/durka.py new file mode 100644 index 0000000..d695951 --- /dev/null +++ b/durka.py @@ -0,0 +1,655 @@ +#!/usr/bin/env python3 +"""DurkaHelper operator commands: configure, prepare, start, scan and import traffic.""" +from __future__ import annotations + +import argparse +import hashlib +import importlib.util +import json +import os +from pathlib import Path +import platform +import re +import secrets +import struct +import subprocess +import sys +import tempfile +from types import SimpleNamespace +from urllib.parse import urlsplit + +ROOT = Path(__file__).resolve().parent +DEFAULT_CONFIG = ROOT / "local/durka.json" +SCHEMA = "durkahelper.operator.v1" +CONFIG_FILES = ("config/farm.py", "config/neo-server.yml", "config/packmate.properties", "profile.json", "compose.json", "model.json", "policy.json", + "runtime-compose.json", "runtime-model.json", "runtime-policy.json", "build-receipt.json", "deployment.json") +CONFIG_JOURNAL = ".durka-configuration.json" + + +def module(name, path): + spec = importlib.util.spec_from_file_location(name, ROOT / path) + value = importlib.util.module_from_spec(spec) + spec.loader.exec_module(value) + return value + + +# Operator commands must not leave import-cache writes in an offline checkout; +# this also keeps the doctor path read-only without requiring a special flag. +sys.dont_write_bytecode = True +kit = module("durka_deployment", "deployment/toolkit.py") +Error = kit.Error + + +def target_platform(): + architecture = {"aarch64": "arm64", "x86_64": "amd64", "AMD64": "amd64"}.get(platform.machine(), platform.machine()) + if sys.platform == "darwin" and architecture == "arm64": + return {"os": "darwin", "architecture": "arm64", "runtime": "docker-desktop"} + if sys.platform.startswith("linux") and architecture in {"amd64", "arm64"}: + return {"os": "linux", "architecture": architecture, "runtime": "docker-engine"} + # Windows can configure an Apple Silicon deployment and run the scanner. + return {"os": "darwin", "architecture": "arm64", "runtime": "docker-desktop"} + + +def private_directory(path): + path = kit.shared.no_links(path) + path.mkdir(mode=0o700, parents=True, exist_ok=True) + if not path.is_dir() or (os.name != "nt" and path.stat().st_mode & 0o077): + raise Error("operator directories must be private (chmod 700); use a new private directory") + return path + + +def config_path(value): + return kit.shared.no_links(Path(value).absolute()) + + +def init(path): + path = config_path(path) + if path.exists(): + raise Error("configuration already exists; edit it instead of running init again") + private_directory(path.parent) + value = kit.load(ROOT / "config/durka.example.json") + value["profile"]["platform"] = target_platform() + value["profile"]["allow_amd64_emulation"] = value["profile"]["platform"]["architecture"] == "arm64" + value["credentials"] = {name: secrets.token_hex(20) for name in + ("farm_password", "database_password", "neo_key", "packmate_password")} + value["credentials"]["packmate_user"] = "operator" + kit.shared.write(path, kit.shared.canonical(value)) + print("Created " + str(path)) + print("Edit the LAN address, team map and competition settings before setup. Passwords are stored in this private file.") + if os.name == "nt": + print("Run deployment commands on the Mac or Linux host; source scanning also works on Windows.") + elif value["profile"]["platform"]["architecture"] == "arm64": + print("Packmate uses its pinned amd64 image through Docker emulation on ARM64.") + return 0 + + +def load_config(path): + path = config_path(path) + try: + value = kit.load(path) + except FileNotFoundError as error: + raise Error("configuration is missing; run python3 durka.py init first") from error + if (not isinstance(value, dict) or set(value) != {"schema", "profile", "credentials", "paths"} + or value["schema"] != SCHEMA or not isinstance(value["paths"], dict) + or set(value["paths"]) != {"sources", "workspace"}): + raise Error("invalid operator configuration; use config/durka.example.json as the reference") + kit.validate_profile(value["profile"]) + kit.validate_credentials(value["credentials"]) + paths = {} + for name, text in value["paths"].items(): + if not isinstance(text, str) or not text.strip(): + raise Error("sources and workspace paths must be nonempty") + candidate = Path(text) + paths[name] = kit.shared.no_links(candidate if candidate.is_absolute() else ROOT / candidate) + if paths[name] == ROOT or paths[name] in ROOT.parents: + raise Error("deployment paths must use dedicated directories") + if (paths["sources"] == paths["workspace"] or paths["sources"] in paths["workspace"].parents + or paths["workspace"] in paths["sources"].parents): + raise Error("source and deployment directories must be separate") + return value, paths + + +def args_for(action, workspace, **values): + defaults = dict(action=action, workspace=str(workspace), apply=True, + approval_id="operator-" + secrets.token_hex(8), runtime=False, + connected_preparation=False, protocol_reviewed=False, queue_reviewed=False, + profile=None, credentials=None, s4dfarm_source=None, neo_source=None) + defaults.update(values) + return SimpleNamespace(**defaults) + + +def require_host(profile): + if os.name == "nt": + raise Error("deployment commands require macOS or Linux; use scan on Windows") + if profile["platform"] != target_platform(): + raise Error("configured platform differs from this host; correct profile.platform before setup") + + +def source_checkout(root, component, source): + """Fetch only a locked repository/commit; resume only our private source cache.""" + expected = {"schema": "durkahelper.operator-sources.v1", "sources": source} + if root.exists(): + private_directory(root) + if not (root / ".durka-sources.json").is_file() or kit.load(root / ".durka-sources.json") != expected: + raise Error("source directory is not this operator cache; choose a new sources path") + else: + private_directory(root) + kit.shared.write(root / ".durka-sources.json", kit.shared.canonical(expected)) + path = kit.shared.no_links(root / component) + item = source[component] + environment = {k: v for k, v in os.environ.items() if not k.upper().startswith("GIT_")} + environment.update(GIT_CONFIG_GLOBAL=os.devnull, GIT_CONFIG_NOSYSTEM="1", GIT_TERMINAL_PROMPT="0", + GIT_NO_REPLACE_OBJECTS="1", GIT_ATTR_NOSYSTEM="1", GIT_OPTIONAL_LOCKS="0") + + def git(*argv, capture=False): + return kit.shared.checked(["git", "-c", "core.hooksPath=" + os.devnull, + "-c", "core.fsmonitor=false", "-C", str(path), *argv], + capture=capture, timeout=600, environment=environment) + + if not path.exists(): + path.mkdir(mode=0o700) + git("init", "--template=") + git("remote", "add", "origin", item["repository"]) + if not (path / ".git").is_dir() or (path / ".git").is_symlink(): + raise Error("source checkout is incomplete or linked; use a new sources path") + if git("remote", "get-url", "origin", capture=True).decode().strip() != item["repository"]: + raise Error("source checkout origin differs from the locked upstream") + try: + head = git("rev-parse", "--verify", "HEAD", capture=True).decode().strip() + except Error: + head = None + if head is not None: + if head != item["commit"] or git("status", "--porcelain", "--untracked-files=all", capture=True): + raise Error("source checkout changed; use a new sources path rather than overwriting it") + else: + git("fetch", "--depth", "1", "origin", item["commit"]) + git("checkout", "--detach", item["commit"]) + if git("rev-parse", "HEAD", capture=True).decode().strip() != item["commit"]: + raise Error("source checkout did not resolve to the locked version") + return path + + +def check_config(root, value): + if not root.exists(): + raise Error("deployment is missing; run python3 durka.py setup first") + root, state, spec, profile = kit.workspace(root) + if profile != value["profile"] or spec != kit.compose_spec(profile, value["credentials"], state["project"], + kit.shared.image_map(ROOT / "config/integration-images.lock.json")): + raise Error("configuration changed after setup; run durka.py down, then durka.py configure to apply event settings") + if not credentials_match(root, state, spec, profile, value["credentials"]): + raise Error("configuration changed after setup; keep the old workspace for its data and set paths.workspace to a new directory") + return root, state, spec, profile + + +def credentials_match(root, state, spec, profile, credentials): + return (spec == kit.compose_spec(profile, credentials, state["project"], + kit.shared.image_map(ROOT / "config/integration-images.lock.json")) + and kit.read(root / "config/packmate.properties").decode("ascii") == kit.properties(profile, credentials) + and ('grpc_auth_key: "' + credentials["neo_key"] + '"\n') in + kit.read(root / "config/neo-server.yml").decode("ascii")) + + +def checksum(data): + return hashlib.sha256(data).hexdigest() + + +def replace_file(path, data, expected): + """Replace one known private file atomically; never blindly overwrite a changed file.""" + if checksum(kit.read(path)) != expected: + raise Error("configuration changed concurrently; retained backup must be inspected") + metadata = path.lstat() + temporary = path.with_name(".durka-write-" + secrets.token_hex(8)) + try: + kit.shared.write(temporary, data) + temporary.chmod(metadata.st_mode & 0o777) + if checksum(kit.read(path)) != expected: + raise Error("configuration changed concurrently; retained backup must be inspected") + os.replace(temporary, path) + if kit.read(path) != data: + raise Error("configuration changed during publication; retained backup must be inspected") + finally: + if temporary.exists(): + temporary.unlink() + + +def bind_paths(root, paths): + expected = {"schema": "durkahelper.operator-paths.v1", "paths": {name: str(path) for name, path in paths.items()}} + path = root / "operator-paths.json" + if path.exists(): + if kit.load(path) != expected: + raise Error("operator paths changed; retain the existing deployment and restore its original paths") + return + root, state, _, _ = kit.workspace(root) + before = kit.read(root / "deployment.json") + kit.shared.write(path, kit.shared.canonical(expected)) + state["files"]["operator-paths.json"] = checksum(kit.read(path)) + replace_file(root / "deployment.json", kit.shared.canonical(state), checksum(before)) + + +def stopped(state): + kit.owned_resources(state) + identities = kit.shared.checked(["docker", "ps", "--all", "--quiet", "--filter", + "label=com.docker.compose.project=" + state["project"]], capture=True).decode().split() + if len(identities) > 64 or any(not re.fullmatch(r"[a-f0-9]{12,64}", item) for item in identities): + raise Error("unexpected deployment resource inventory") + for identity in identities: + state_text = kit.shared.checked(["docker", "container", "inspect", "--format", + "{{.State.Running}};{{.State.Restarting}}", identity], capture=True).decode().strip() + if state_text != "false;false": + raise Error("stop the entire deployment with durka.py down before configure") + + +def pending(root): + path = root / CONFIG_JOURNAL + if path.exists() and kit.load(path).get("phase") == "pending": + raise Error("configuration update was interrupted; run durka.py configure --rollback") + + +def configuration_rollback(root): + """Recover only the bounded files of the latest recorded configuration change.""" + journal = kit.load(root / CONFIG_JOURNAL) + if (set(journal) != {"schema", "phase", "backup", "files"} or journal["schema"] != "durkahelper.operator-configuration.v1" + or journal["phase"] not in {"pending", "committed", "rolled-back"} + or not isinstance(journal["backup"], str) + or not re.fullmatch(r"configuration-backups/[a-f0-9]{16}", journal["backup"]) + or not isinstance(journal["files"], dict) or set(journal["files"]) != set(CONFIG_FILES)): + raise Error("invalid configuration recovery record") + backup = kit.shared.no_links(root / journal["backup"]) + originals = {} + for name, hashes in journal["files"].items(): + if (not isinstance(hashes, dict) or set(hashes) != {"before", "after"} + or any(not isinstance(value, str) or not re.fullmatch(r"[a-f0-9]{64}", value) for value in hashes.values())): + raise Error("invalid configuration recovery checks") + originals[name] = kit.read(backup / name) + if checksum(originals[name]) != hashes["before"] or checksum(kit.read(root / name)) not in set(hashes.values()): + raise Error("configuration recovery files changed; retained backup must be inspected") + state = json.loads(originals["deployment.json"]) + if (state.get("schema") != kit.SCHEMA or state.get("source_pins") != kit.shared.PINS + or not re.fullmatch(r"dh-deploy-[a-f0-9]{12}", state.get("project", "")) + or not isinstance(state.get("files"), dict) or not 1 <= len(state["files"]) <= 20000): + raise Error("configuration recovery ownership record is invalid") + for name, digest in state["files"].items(): + if (not isinstance(name, str) or Path(name).is_absolute() or "\\" in name or ":" in name + or any(part in {"..", "."} for part in name.split("/"))): + raise Error("unsafe recovery member") + candidate = kit.shared.no_links(root / name) + data = originals[name] if name in originals else kit.read(candidate, kit.shared.MAX_SOURCE) + if checksum(data) != digest: + raise Error("original deployment changed outside configuration; refusing recovery") + stopped(state) + for name in CONFIG_FILES: + current = checksum(kit.read(root / name)) + if current != journal["files"][name]["before"]: + replace_file(root / name, originals[name], current) + root, state, spec, _ = kit.workspace(root) + kit.check_build_receipt(root, spec) + before = kit.read(root / CONFIG_JOURNAL) + journal["phase"] = "rolled-back" + replace_file(root / CONFIG_JOURNAL, kit.shared.canonical(journal), checksum(before)) + return backup / "operator.json" + + +def configure(value, paths, rollback=False): + require_host(value["profile"]) + root = paths["workspace"] + if rollback: + previous = configuration_rollback(root) + print("Previous deployment configuration restored; data retained.") + print("Copy " + str(previous) + " over the private operator config before up.") + return 0 + pending(root) + root, state, old_spec, old_profile = kit.workspace(root) + expected_paths = {"schema": "durkahelper.operator-paths.v1", "paths": {name: str(path) for name, path in paths.items()}} + if kit.load(root / "operator-paths.json") != expected_paths: + raise Error("configure cannot change operator paths; restore the original paths") + new_profile = value["profile"] + if (any(old_profile[name] != new_profile[name] for name in ("schema", "platform", "allow_amd64_emulation")) + or any(old_profile["packmate"][name] != new_profile["packmate"][name] for name in ("mode", "pcap_file", "interface")) + or new_profile["packmate"]["mode"] != "FILE"): + raise Error("configure changes event settings only; platform, runtime and capture layout require a new deployment") + if not credentials_match(root, state, old_spec, old_profile, value["credentials"]): + raise Error("configure cannot rotate credentials; restore their original values") + old_runtime = kit.check_build_receipt(root, old_spec) + receipt = kit.load(root / "build-receipt.json") + stopped(state) + kit.check_build_receipt(root, old_spec, kit.image_preflight(old_runtime, old_profile)) + spec = kit.compose_spec(new_profile, value["credentials"], state["project"], + kit.shared.image_map(ROOT / "config/integration-images.lock.json")) + runtime = kit.runtime_spec(spec, receipt["images"]) + deployment_model = kit.model(spec, new_profile) + runtime_model = kit.model(runtime, new_profile) + farm = new_profile["farm"] + farm_config = dict(DEBUG=False, TEAMS=farm["teams"], FLAG_FORMAT=farm["flag_format"], SYSTEM_PROTOCOL=farm["protocol"], + SUBMIT_FLAG_LIMIT=farm["submit_limit"], SUBMIT_PERIOD=farm["submit_period"], FLAG_LIFETIME=farm["flag_lifetime"], + SERVER_PASSWORD=value["credentials"]["farm_password"], TIMEZONE="UTC", **farm["protocol_settings"]) + candidate = {"config/farm.py": ("CONFIG = " + repr(farm_config) + "\n").encode("utf-8"), + "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: "' + value["credentials"]["neo_key"] + '"\nfarm:\n url: "' + kit.neo_farm_url(new_profile) + '"\n password: "' + value["credentials"]["farm_password"] + '"\n').encode("ascii"), + "config/packmate.properties": kit.properties(new_profile, value["credentials"]).encode("ascii"), + "profile.json": kit.shared.canonical(new_profile), "compose.json": kit.shared.canonical(spec), + "model.json": kit.shared.canonical(deployment_model), "policy.json": kit.shared.canonical(kit.policy(new_profile, deployment_model)), + "runtime-compose.json": kit.shared.canonical(runtime), "runtime-model.json": kit.shared.canonical(runtime_model), + "runtime-policy.json": kit.shared.canonical(kit.policy(new_profile, runtime_model)), + "build-receipt.json": kit.shared.canonical({"schema": "durkahelper.deployment-build.v2", "images": receipt["images"], + "compose_sha256": checksum(kit.shared.canonical(spec)), "runtime_sha256": checksum(kit.shared.canonical(runtime))})} + originals = {name: kit.read(root / name) for name in CONFIG_FILES} + for name, payload in candidate.items(): + if name in state["files"]: + state["files"][name] = checksum(payload) + candidate["deployment.json"] = kit.shared.canonical(state) + backup = root / "configuration-backups" / secrets.token_hex(8) + private_directory(backup) + for name, data in originals.items(): + kit.shared.write(backup / name, data) + old_operator = dict(value, profile=old_profile) + kit.shared.write(backup / "operator.json", kit.shared.canonical(old_operator)) + journal = {"schema": "durkahelper.operator-configuration.v1", "phase": "pending", "backup": backup.relative_to(root).as_posix(), + "files": {name: {"before": checksum(originals[name]), "after": checksum(candidate[name])} for name in CONFIG_FILES}} + journal_path = root / CONFIG_JOURNAL + if journal_path.exists(): + replace_file(journal_path, kit.shared.canonical(journal), checksum(kit.read(journal_path))) + else: + kit.shared.write(journal_path, kit.shared.canonical(journal)) + try: + for name in CONFIG_FILES: + stopped(state) + replace_file(root / name, candidate[name], checksum(originals[name])) + kit.workspace(root) + kit.check_build_receipt(root, spec) + before = kit.read(journal_path) + journal["phase"] = "committed" + replace_file(journal_path, kit.shared.canonical(journal), checksum(before)) + except (Exception, KeyboardInterrupt): + configuration_rollback(root) + raise + print("Event settings updated. Data and cached images retained; no downloads or rebuild required.") + print("Previous configuration: " + str(backup / "operator.json")) + print("Run python3 durka.py up, then worker and submit when needed.") + return 0 + + +def empty_capture(root, profile): + path = root / "pcaps" / profile["packmate"]["pcap_file"] + if path.is_symlink(): + raise Error("capture path cannot be a link") + if not path.exists(): + kit.shared.write(path, struct.pack(" + +Это developer fixtures, **не инструкция развёртывания**. Для рабочего командного стека используйте [durka.py и инструкцию администратора](../deployment/README-RU.md). + + +## Изоляция и prerequisites + +Opt-in Docker-тесты запускаются только в отдельном приватном workspace с синтетическими credentials/data. Нужны разрешённый Linux Docker Engine, кешированные закреплённые образы, уникальные project names и свободные ресурсы. Recovery и fault-injection требуют snapshot хоста. Чужие workloads не исследуются. + + +## Подготовка и запуск + +Прочитайте help fixture, просмотрите preview, затем примените осознанно. В профилях нет shell-команд. Запускайте из корня репозитория. Результаты остаются в выбранном приватном workspace, а не в Git. + +```bash +python3 integration/stack_smoke.py --help +python3 integration/packmate_smoke.py --help +``` + + +## Откат и ошибки + +Используйте shutdown самого fixture; не глобальный prune или удаление общих volumes. При сбое локальные результаты/данные сохраняются для диагностики. Проверьте точечную очистку перед повтором в новом workspace. + + +## Границы проверки + +Синтетический тест не сертифицирует Docker Desktop, захват на соревновании или доступ реальных участников. CI logs и приватные outputs заменяют закоммиченные исторические отчёты. См. [возможности и ограничения](../docs/CAPABILITY_INVENTORY-RU.md). + + +## Fixture Packmate FILE + +`packmate_smoke.py` проверяет импорт закрытого синтетического PCAP, authentication и известные потоки. Непрерывный захват он не подтверждает. + + +## Нативное восстановление PostgreSQL + +`recovery_smoke.py` проверяет native dump/restore в изолированные базы. Не подменяйте его синтетические inputs игровыми volumes. + + +## Опубликованный Neo client + +`neo_release_smoke.py` проверяет закреплённый опубликованный client с закреплённым server; latest автоматически не выбирается. + + +## Безвредный цикл Neo + +`neo_lifecycle_smoke.py` проверяет безвредную задачу, результат, reconnect и disable. Workers исполняют доверенный код; не передавайте произвольные задачи. + + +## Нативное восстановление Redis + +`component_recovery_smoke.py` проверяет persistence/recovery в изолированном fixture. Для настоящих очередей отправки отдельно решают, можно ли replay. + + +## Canary логирования Packmate + +`packmate_logger_smoke.py` проверяет подавление failed-auth logger через конфигурацию: одноразовый canary и positive control. Все возможные пути логирования этим не сертифицируются. + + +## Восстановление синтетического стека + +`stack_recovery_smoke.py` восстанавливает синтетические Farm, Neo и Packmate в новые projects с отключённой автоматической отправкой. Это не разрешение перезаписывать существующий deployment. + + +## Синтетический LIVE + +`packmate_live_smoke.py` наблюдает только свою синтетическую Linux network/namespace. Проверяет TCP/UDP, timeout и restart, но не видимость настоящего Vulnbox или длительную нагрузку. + + +## Изолированная офлайн-репетиция + +`offline_runtime_smoke.py` делает cold start Linux-стека из подготовленных образов и проверяет network denial плюс сохранение синтетических данных. Полный toolchain на пустой ноутбук он не устанавливает. Для обычной подготовки см. [офлайн-работу](../docs/offline-bundles-RU.md). + +Аргументы каждого fixture доступны через `--help`; низкоуровневые защитные флаги нужны разработчикам, а не как формы для обычного оператора. + + +## Перенос синтетического 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. + + +## Приёмка 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. diff --git a/integration/README.md b/integration/README.md new file mode 100644 index 0000000..6ef26ac --- /dev/null +++ b/integration/README.md @@ -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. diff --git a/integration/component_recovery_smoke.py b/integration/component_recovery_smoke.py new file mode 100644 index 0000000..5564ca1 --- /dev/null +++ b/integration/component_recovery_smoke.py @@ -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()) diff --git a/integration/neo_lifecycle_smoke.py b/integration/neo_lifecycle_smoke.py new file mode 100644 index 0000000..9a7c52c --- /dev/null +++ b/integration/neo_lifecycle_smoke.py @@ -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()) diff --git a/integration/neo_release_smoke.py b/integration/neo_release_smoke.py new file mode 100644 index 0000000..ffd2d4b --- /dev/null +++ b/integration/neo_release_smoke.py @@ -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()) diff --git a/integration/offline_runtime_smoke.py b/integration/offline_runtime_smoke.py new file mode 100644 index 0000000..bedaa99 --- /dev/null +++ b/integration/offline_runtime_smoke.py @@ -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()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()) diff --git a/integration/packmate_host_smoke.py b/integration/packmate_host_smoke.py new file mode 100644 index 0000000..f5d832d --- /dev/null +++ b/integration/packmate_host_smoke.py @@ -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()) diff --git a/integration/packmate_live_smoke.py b/integration/packmate_live_smoke.py new file mode 100644 index 0000000..58cdb08 --- /dev/null +++ b/integration/packmate_live_smoke.py @@ -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()) diff --git a/integration/packmate_logger_smoke.py b/integration/packmate_logger_smoke.py new file mode 100644 index 0000000..6d7ac21 --- /dev/null +++ b/integration/packmate_logger_smoke.py @@ -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()) diff --git a/integration/packmate_smoke.py b/integration/packmate_smoke.py new file mode 100644 index 0000000..dfcbd43 --- /dev/null +++ b/integration/packmate_smoke.py @@ -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" 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()) diff --git a/integration/recovery_smoke.py b/integration/recovery_smoke.py new file mode 100644 index 0000000..0572b98 --- /dev/null +++ b/integration/recovery_smoke.py @@ -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()) diff --git a/integration/stack_recovery_smoke.py b/integration/stack_recovery_smoke.py new file mode 100644 index 0000000..97fdef2 --- /dev/null +++ b/integration/stack_recovery_smoke.py @@ -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()) diff --git a/integration/stack_smoke.py b/integration/stack_smoke.py new file mode 100644 index 0000000..249b0a9 --- /dev/null +++ b/integration/stack_smoke.py @@ -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"> 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(" 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() diff --git a/integration/vulnbox_handoff.py b/integration/vulnbox_handoff.py new file mode 100644 index 0000000..41f86cb --- /dev/null +++ b/integration/vulnbox_handoff.py @@ -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()) diff --git a/lab/README-RU.md b/lab/README-RU.md new file mode 100644 index 0000000..74d12c4 --- /dev/null +++ b/lab/README-RU.md @@ -0,0 +1,39 @@ + +# Синтетическая локальная лаборатория защиты + +[English](README.md) | Русский + +Этот сервис использует только стандартную библиотеку, намеренно мал и доступен только через loopback. Он не подключается к инфраструктуре соревнования. Запускайте из корня репозитория с Python 3.10+. + +Свидетельство: `REVIEWED`; эффект `SERVICE-CHANGE` (один локальный процесс). Ожидается: loopback listener без внешнего bind. Секреты: используйте только предоставленные синтетические fixtures. Rollback: Ctrl-C останавливает процесс. + +```bash +python3 lab/health_service.py +``` + +Порт по умолчанию: 8080. Используйте --port 8081 для другого явно выбранного порта или --port 0 для временного порта, фактический URL которого будет напечатан. Соответственно обновите профиль probe. fixtures/service.json демонстрирует резервное копирование конфигурации; сервер его не загружает. + +| Запрос | Ответ | +|---|---| +| GET /health or /health?check=1 | 200 и {"status": "ok"} | +| GET /version | 200 и {"version": "demo"} | +| HEAD /health | Заголовки GET без тела | +| GET /missing | 404 | +| POST /health | 405; Allow: GET, HEAD | + +Сервис пишет в stderr JSONL-записи level/status без URL или содержимого запросов. + +В другом терминале: свидетельство `REVIEWED`, эффект `READ-ONLY`, тот же рабочий каталог; ожидается код выхода probe 0 и сводка лога с двумя HTTP-ошибками в предоставленном fixture из четырёх записей: + +```bash +python3 scripts/http_probe.py config/services.example.json +python3 scripts/log_summary.py lab/fixtures/events.jsonl +``` + +Unit tests создают и останавливают собственные временные loopback-серверы; отдельно запущенная лаборатория не нужна. Эффект: временный `WORKSPACE-WRITE`; ожидается успешное прохождение набора. + +```bash +python3 -m unittest discover -s tests -p 'test_defense*.py' -v +``` + +DEMO_ONLY_DO_NOT_COPY в fixtures/service.json — безвредное тестовое значение, а не действующий пароль. Внешние контейнерные тесты — отдельный запускаемый по выбору [integration fixture](../integration/README-RU.md). diff --git a/lab/README.md b/lab/README.md new file mode 100644 index 0000000..12d94a5 --- /dev/null +++ b/lab/README.md @@ -0,0 +1,38 @@ +# Synthetic local defense lab + +English | [Русский](README-RU.md) + +This stdlib-only service is intentionally small and loopback-only. It does not connect to competition infrastructure. Run from the repository root with Python 3.10+. + +Evidence: `REVIEWED`; effect `SERVICE-CHANGE` (one local process). Expected: a loopback listener, no external binding. Secrets: use only provided synthetic fixtures. Rollback: Ctrl-C stops the process. + +```bash +python3 lab/health_service.py +``` + +Default port: 8080. Use --port 8081 for another explicit port, or --port 0 for an ephemeral port whose actual URL is printed. Update your probe profile accordingly. fixtures/service.json demonstrates configuration backup; the server does not load it. + +| Request | Response | +|---|---| +| GET /health or /health?check=1 | 200 and {"status": "ok"} | +| GET /version | 200 and {"version": "demo"} | +| HEAD /health | GET headers without body | +| GET /missing | 404 | +| POST /health | 405; Allow: GET, HEAD | + +The service writes JSONL level/status records to stderr without URLs or request contents. + +In another terminal, evidence `REVIEWED`, effect `READ-ONLY`, same cwd; expected probe exit 0 and a log summary with two HTTP errors in the provided four-record fixture: + +```bash +python3 scripts/http_probe.py config/services.example.json +python3 scripts/log_summary.py lab/fixtures/events.jsonl +``` + +Unit tests create/stop their own temporary loopback servers; no separately running lab is needed. Effect: temporary `WORKSPACE-WRITE`; expected suite pass. + +```bash +python3 -m unittest discover -s tests -p 'test_defense*.py' -v +``` + +DEMO_ONLY_DO_NOT_COPY in fixtures/service.json is an inert test value, not a working password. External container tests are a separate opt-in [integration fixture](../integration/README.md). diff --git a/lab/fixtures/defense_ops/event.redacted.json b/lab/fixtures/defense_ops/event.redacted.json new file mode 100644 index 0000000..9542b51 --- /dev/null +++ b/lab/fixtures/defense_ops/event.redacted.json @@ -0,0 +1,15 @@ +{ + "schema": "durkahelper.event.v1", + "id": "event-synthetic-redacted-0001", + "timestamp": "2026-01-01T00:01:00Z", + "source": "synthetic-triage", + "kind": "suspicious_activity", + "severity": "medium", + "summary": "Synthetic triage event exported with sensitive details removed.", + "attributes": { + "detail": "[REDACTED]", + "record_count": 2, + "redacted": true, + "source_address": "127.0.0.1" + } +} diff --git a/lab/fixtures/defense_ops/event.valid.json b/lab/fixtures/defense_ops/event.valid.json new file mode 100644 index 0000000..817c15a --- /dev/null +++ b/lab/fixtures/defense_ops/event.valid.json @@ -0,0 +1,14 @@ +{ + "schema": "durkahelper.event.v1", + "id": "event-synthetic-health-0001", + "timestamp": "2026-01-01T00:00:00Z", + "source": "synthetic-health", + "kind": "service_health", + "severity": "info", + "summary": "Synthetic loopback health check passed.", + "attributes": { + "endpoint": "http://127.0.0.1:8080/health", + "healthy": true, + "status_code": 200 + } +} diff --git a/lab/fixtures/defense_ops/validation-record.redacted.json b/lab/fixtures/defense_ops/validation-record.redacted.json new file mode 100644 index 0000000..98b9591 --- /dev/null +++ b/lab/fixtures/defense_ops/validation-record.redacted.json @@ -0,0 +1,16 @@ +{ + "schema": "durkahelper.validation-record.v1", + "id": "validation-redacted-0001", + "timestamp": "2026-01-01T00:03:00Z", + "check": "evidence_export", + "status": "partial", + "summary": "Synthetic validation retained only redacted evidence.", + "evidence": [ + "lab/fixtures/defense_ops/event.redacted.json" + ], + "attributes": { + "inspected_events": 1, + "redacted": true, + "retained_detail": "[REDACTED]" + } +} diff --git a/lab/fixtures/defense_ops/validation-record.valid.json b/lab/fixtures/defense_ops/validation-record.valid.json new file mode 100644 index 0000000..a8d7f43 --- /dev/null +++ b/lab/fixtures/defense_ops/validation-record.valid.json @@ -0,0 +1,15 @@ +{ + "schema": "durkahelper.validation-record.v1", + "id": "validation-baseline-0001", + "timestamp": "2026-01-01T00:02:00Z", + "check": "baseline_compare", + "status": "pass", + "summary": "Synthetic baseline matched the current snapshot.", + "evidence": [ + "lab/fixtures/defense_ops/event.valid.json" + ], + "attributes": { + "comparable": true, + "drift_count": 0 + } +} diff --git a/lab/fixtures/events.jsonl b/lab/fixtures/events.jsonl new file mode 100644 index 0000000..c0088df --- /dev/null +++ b/lab/fixtures/events.jsonl @@ -0,0 +1,4 @@ +{"level":"INFO","status":200,"message":"health check"} +{"level":"INFO","status":200,"message":"version check"} +{"level":"WARNING","status":404,"message":"unknown route"} +{"level":"ERROR","status":503,"message":"synthetic unavailable response"} diff --git a/lab/fixtures/service.json b/lab/fixtures/service.json new file mode 100644 index 0000000..f6ae782 --- /dev/null +++ b/lab/fixtures/service.json @@ -0,0 +1,7 @@ +{ + "service": {"name": "local-demo"}, + "http": {"port": 8080}, + "logging": {"level": "INFO"}, + "credentials": {"password": "DEMO_ONLY_DO_NOT_COPY"}, + "unselected": "THIS_FIELD_IS_NOT_INCLUDED" +} diff --git a/lab/health_service.py b/lab/health_service.py new file mode 100644 index 0000000..9f08dbd --- /dev/null +++ b/lab/health_service.py @@ -0,0 +1,68 @@ +#!/usr/bin/env python3 +"""Small health-check demo bound only to IPv4 loopback.""" +import argparse +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +import json +import sys +from urllib.parse import urlsplit + + +class Handler(BaseHTTPRequestHandler): + def log_message(self, *args): + pass + + def respond(self, head=False, unsupported=False): + try: + path = urlsplit(self.path).path + except ValueError: + path = "" + if unsupported: + status, body = 405, {"error": "method not allowed"} + elif path == "/health": + status, body = 200, {"status": "ok"} + elif path == "/version": + status, body = 200, {"version": "demo"} + else: + status, body = 404, {"error": "not found"} + payload = json.dumps(body).encode("utf-8") + self.send_response(status) + self.send_header("Content-Type", "application/json; charset=utf-8") + self.send_header("Content-Length", str(len(payload))) + if status == 405: + self.send_header("Allow", "GET, HEAD") + self.end_headers() + if not head: + self.wfile.write(payload) + print(json.dumps({"level": "INFO", "status": status}), file=sys.stderr, flush=True) + + def do_GET(self): + self.respond() + + def do_HEAD(self): + self.respond(head=True) + + def do_POST(self): + self.respond(unsupported=True) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--port", type=int, default=8080) + args = parser.parse_args() + if not 0 <= args.port <= 65535: + parser.error("port must be 0..65535 (0 chooses an available port)") + try: + with ThreadingHTTPServer(("127.0.0.1", args.port), Handler) as server: + print(f"http://127.0.0.1:{server.server_port}", flush=True) + try: + server.serve_forever() + except KeyboardInterrupt: + pass + except OSError as exc: + print(f"local demo: {type(exc).__name__}", file=sys.stderr) + return 2 + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/rules/defense.json b/rules/defense.json new file mode 100644 index 0000000..2635e1c --- /dev/null +++ b/rules/defense.json @@ -0,0 +1,4096 @@ +{ + "schema_version": 1, + "ruleset": "2026-10-09.2", + "rules": [ + { + "id": "PY-EVAL", + "languages": [ + "python" + ], + "title": "Executing text as Python", + "before": "eval(payload)", + "after": "import json\nvalue = json.loads(payload)\nif not isinstance(value, dict):\n raise ValueError('object required')", + "fix": "Use JSON plus a schema for data, or a limited parser for a DSL; do not move code into another eval.", + "check": "Valid documents parse, Python expressions are not executed, and input size is bounded.", + "engine": "python-ast", + "doc": "docs/vulnerabilities/python.md#py-eval", + "reason": "Review signal: Executing text as Python. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "limitations": "Bounded syntactic AST analysis, not type resolution or interprocedural taint analysis. Review actual API, inputs and authorization.", + "family": "injection", + "cwe": [ + "CWE-94" + ], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "PY-SHELL", + "languages": [ + "python" + ], + "title": "Python shell execution", + "before": "import subprocess\nsubprocess.run(command, shell=True)", + "after": "import subprocess\nsubprocess.run(['/usr/bin/file', '--', filename], shell=False, check=True, timeout=3)", + "fix": "Use a fixed executable and separate argv without a shell; allowlist arguments according to the utility contract.", + "check": "Metacharacters remain data, dangerous options fail, and normal operations work.", + "engine": "python-ast", + "doc": "docs/vulnerabilities/python.md#py-shell", + "reason": "Review signal: Python shell execution. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "detection": "AST: explicit shell=True or inline **dict, shell helpers and literal shell argv in subprocess/asyncio.create_subprocess_exec. Variable argv, wrappers and complex branching are not evaluated.", + "limitations": "AST: explicit shell=True or inline **dict, shell helpers and literal shell argv in subprocess/asyncio.create_subprocess_exec. Variable argv, wrappers and complex branching are not evaluated.", + "family": "injection", + "cwe": [ + "CWE-78" + ], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "PY-DESERIALIZE", + "languages": [ + "python" + ], + "title": "Python object deserialization", + "before": "import pickle\nvalue = pickle.loads(data)", + "after": "import json\nvalue = json.loads(data) # validate schema", + "fix": "For pickle-like formats, use schema-validated JSON where compatible and migrate trusted legacy records separately. For NumPy retain numeric .npy/.npz with allow_pickle=False, dtype/shape and size checks; migrate object arrays separately. Never load an untrusted pickle to convert it.", + "check": "Valid records remain readable; unknown fields/types and object arrays fail; dtype, shape and volume are checked.", + "engine": "python-ast", + "doc": "docs/vulnerabilities/python.md#py-deserialize", + "reason": "Review signal: Python object deserialization. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "detection": "AST: pickle/dill/shelve, jsonpickle.decode/loads, joblib.load, pandas.read_pickle and direct or simply assigned Unpickler(...).load. numpy.load and numpy.lib.format.read_array require known allow_pickle=True (keyword or third/second positional argument respectively). Import aliases, simple scalar assignments and inline **dict are supported; old defaults, mutable dictionaries, wrappers and data trust need review.", + "references": [ + "https://jsonpickle.readthedocs.io/en/latest/", + "https://joblib.readthedocs.io/en/stable/generated/joblib.load.html", + "https://pandas.pydata.org/docs/reference/api/pandas.read_pickle.html", + "https://numpy.org/doc/stable/reference/generated/numpy.load.html", + "https://numpy.org/doc/stable/reference/generated/numpy.lib.format.read_array.html" + ], + "limitations": "AST: pickle/dill/shelve, jsonpickle.decode/loads, joblib.load, pandas.read_pickle and direct or simply assigned Unpickler(...).load. numpy.load and numpy.lib.format.read_array require known allow_pickle=True (keyword or third/second positional argument respectively). Import aliases, simple scalar assignments and inline **dict are supported; old defaults, mutable dictionaries, wrappers and data trust need review.", + "family": "injection", + "cwe": [ + "CWE-502" + ], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "PY-YAML", + "languages": [ + "python" + ], + "title": "YAML with a potentially unsafe loader", + "before": "import yaml\nvalue = yaml.load(data, Loader=yaml.Loader)", + "after": "import yaml\nvalue = yaml.safe_load(data) # validate schema", + "fix": "Use safe_load, validate fields/types, and bound document size and complexity.", + "check": "Ordinary YAML works; object tags and unexpected structures fail.", + "engine": "python-ast", + "doc": "docs/vulnerabilities/python.md#py-yaml", + "reason": "Review signal: YAML with a potentially unsafe loader. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "detection": "AST: yaml.load/load_all/unsafe_load/unsafe_load_all, excluding SafeLoader/CSafeLoader/BaseLoader/CBaseLoader, with import aliases, positional Loader and inline **dict. BaseLoader/CBaseLoader return scalars as strings. Review version defaults, wrappers and resource limits.", + "references": [ + "https://pyyaml.org/wiki/PyYAMLDocumentation" + ], + "limitations": "AST: yaml.load/load_all/unsafe_load/unsafe_load_all, excluding SafeLoader/CSafeLoader/BaseLoader/CBaseLoader, with import aliases, positional Loader and inline **dict. BaseLoader/CBaseLoader return scalars as strings. Review version defaults, wrappers and resource limits.", + "family": "injection", + "cwe": [ + "CWE-502" + ], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "PY-SQL", + "languages": [ + "python" + ], + "title": "SQL assembled from string expressions", + "before": "db.execute(\"SELECT id FROM notes WHERE name=%s\" % name)", + "after": "db.execute(\"SELECT id FROM notes WHERE name=?\", (name,)) # sqlite3", + "fix": "Bind values using the actual driver's parameter API; select identifiers from a server-side allowlist.", + "check": "Quotes remain data; ownership restrictions and normal queries remain correct.", + "engine": "python-ast", + "doc": "docs/vulnerabilities/python.md#py-sql", + "reason": "Review signal: SQL assembled from string expressions. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "detection": "AST: string construction at SQL sinks and keywords, including simple assignments. Imported psycopg/psycopg2.sql SQL(nonliteral) or format/join with unknown/raw pieces signal. Literal SQL plus known Identifier/Literal/Placeholder compositions suppress this signal only, not identifier authorization. Mutable composition, wrappers, cross-function flows and driver versions remain manual.", + "limitations": "AST: string construction at SQL sinks and keywords, including simple assignments. Imported psycopg/psycopg2.sql SQL(nonliteral) or format/join with unknown/raw pieces signal. Literal SQL plus known Identifier/Literal/Placeholder compositions suppress this signal only, not identifier authorization. Mutable composition, wrappers, cross-function flows and driver versions remain manual.", + "family": "injection", + "cwe": [ + "CWE-89" + ], + "review_priority": "normal", + "signal_kind": "syntactic-review", + "coverage_required": [ + "python" + ], + "references": [ + "https://www.psycopg.org/psycopg3/docs/api/sql.html", + "https://www.psycopg.org/docs/sql.html" + ] + }, + { + "id": "PY-ORM-BOOL", + "languages": [ + "python" + ], + "title": "Python and/or used in an ORM expression", + "before": "User.find(User.name == name and User.password == password)", + "after": "User.find(User.name == name, User.password == password) # Beanie", + "fix": "Use the ORM's documented expression composition, not Python short-circuit operators; retain all ownership/authentication predicates.", + "check": "Both predicates appear in the actual query; wrong passwords and other users' objects fail.", + "engine": "python-ast", + "doc": "docs/vulnerabilities/python.md#py-orm-bool", + "reason": "Review signal: Python and/or used in an ORM expression. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "limitations": "Bounded syntactic AST analysis, not type resolution or interprocedural taint analysis. Review actual API, inputs and authorization.", + "family": "authentication", + "cwe": [], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "PY-TEMPLATE", + "languages": [ + "python" + ], + "title": "Dynamic template source", + "before": "render_template_string(user_text)", + "after": "render_template('message.html', message=user_text)", + "fix": "Keep template source trusted and pass untrusted values as parameters; review autoescape and loader boundaries.", + "check": "Template syntax in a user field stays data; expected formatting is preserved.", + "engine": "python-ast", + "doc": "docs/vulnerabilities/python.md#py-template", + "reason": "Review signal: Dynamic template source. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "detection": "AST: render_template_string/from_string by method name, first argument or source=, import aliases and inline **dict. Nonliteral source requires review; custom same-named methods may match. Review dictionary variables, wrappers, environment type, trust and autoescape.", + "references": [ + "https://flask.palletsprojects.com/en/stable/api/#flask.render_template_string", + "https://jinja.palletsprojects.com/en/stable/api/#jinja2.Environment.from_string" + ], + "limitations": "AST: render_template_string/from_string by method name, first argument or source=, import aliases and inline **dict. Nonliteral source requires review; custom same-named methods may match. Review dictionary variables, wrappers, environment type, trust and autoescape.", + "family": "injection", + "cwe": [], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "PY-TLS", + "languages": [ + "python" + ], + "title": "Python TLS verification disabled", + "before": "import requests\nrequests.get(url, verify=False)", + "after": "import requests\nrequests.get(url, verify=True, timeout=3)", + "fix": "Enable certificate/hostname checks and configure the trusted CA instead of bypassing verification.", + "check": "Correct CA/hostname works; invalid, expired or wrong-host certificates fail without fallback.", + "engine": "python-ast", + "doc": "docs/vulnerabilities/python.md#py-tls", + "reason": "Review signal: Python TLS verification disabled. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "detection": "AST: verify=False, simple local scalar or inline **dict, respecting overwrite order. Known requests Session/session and httpx Client/AsyncClient with matching with/async with, Session.send and httpx.stream are supported. Generic get/post/put/patch/delete/request remains an untyped heuristic. Dictionary variables, client properties, runtime config and wrappers are not evaluated.", + "references": [ + "https://requests.readthedocs.io/en/latest/user/advanced/", + "https://www.python-httpx.org/api/" + ], + "limitations": "AST: verify=False, simple local scalar or inline **dict, respecting overwrite order. Known requests Session/session and httpx Client/AsyncClient with matching with/async with, Session.send and httpx.stream are supported. Generic get/post/put/patch/delete/request remains an untyped heuristic. Dictionary variables, client properties, runtime config and wrappers are not evaluated.", + "family": "network-exposure", + "cwe": [], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "PY-DEBUG", + "languages": [ + "python" + ], + "title": "Python web debugger enabled", + "before": "app.run(debug=True)", + "after": "app.run(debug=False)", + "fix": "Disable the debugger in the competition runtime and retain private, redacted diagnostics.", + "check": "Errors expose no interactive console or stack trace; health checks work.", + "engine": "python-ast", + "doc": "docs/vulnerabilities/python.md#py-debug", + "reason": "Review signal: Python web debugger enabled. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "limitations": "AST: explicit debug/use_debugger=True at run/run_simple (legacy name heuristic). Known imported Flask instances: DEBUG=True via config subscript/update/from_mapping or app.debug=True. Inline dictionaries and aliases supported; custom factories, runtime overrides, configuration files and branches remain manual.", + "family": "information-disclosure", + "cwe": [], + "review_priority": "normal", + "signal_kind": "syntactic-review", + "detection": "AST: explicit debug/use_debugger=True at run/run_simple (legacy name heuristic). Known imported Flask instances: DEBUG=True via config subscript/update/from_mapping or app.debug=True. Inline dictionaries and aliases supported; custom factories, runtime overrides, configuration files and branches remain manual.", + "coverage_required": [ + "python" + ], + "references": [ + "https://flask.palletsprojects.com/en/stable/config/" + ] + }, + { + "id": "PY-JWT", + "languages": [ + "python" + ], + "title": "JWT signature verification disabled", + "before": "import jwt\nclaims = jwt.decode(token, options={'verify_signature': False})", + "after": "import jwt\nclaims = jwt.decode(token, key, algorithms=['HS256'], audience='service', options={'require': ['exp', 'sub', 'aud']})", + "fix": "Verify signatures with a trusted key and fixed algorithm policy; validate required claims and values using the installed library version.", + "check": "Modified, unsigned, expired and wrong-audience tokens fail; valid sessions work.", + "engine": "python-ast", + "doc": "docs/vulnerabilities/python.md#py-jwt", + "reason": "Review signal: JWT signature verification disabled. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "detection": "AST: options.verify_signature=False with inline **kwargs/options and overwrite order. Only jose.jwt.decode and jwt.decode_complete bind fourth positional options; generic jwt.decode is version-ambiguous. Legacy verify=False remains only for generic jwt.decode. Review *args, mutable dictionaries, wrappers and instance settings; explicit positional/keyword duplicates are not treated as executable JWT calls.", + "references": [ + "https://github.com/mpdavis/python-jose/blob/3.5.0/jose/jwt.py", + "https://github.com/jpadilla/pyjwt/blob/2.10.1/jwt/api_jwt.py", + "https://github.com/jpadilla/pyjwt/blob/1.7.1/jwt/api_jwt.py" + ], + "limitations": "AST: options.verify_signature=False with inline **kwargs/options and overwrite order. Only jose.jwt.decode and jwt.decode_complete bind fourth positional options; generic jwt.decode is version-ambiguous. Legacy verify=False remains only for generic jwt.decode. Review *args, mutable dictionaries, wrappers and instance settings; explicit positional/keyword duplicates are not treated as executable JWT calls.", + "family": "authentication", + "cwe": [], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "PY-ARCHIVE", + "languages": [ + "python" + ], + "title": "Archive extraction requires path review", + "before": "archive.extractall(destination)", + "after": "archive.extractall(destination, filter='data') # tarfile; check runtime support", + "fix": "Validate paths, links, member types and quotas; use tarfile's data filter where supported. A filter is not a resource limit or a complete ZIP policy.", + "check": "Traversal, links, device entries and oversized archives fail; ordinary archives remain inside the root.", + "engine": "python-ast", + "doc": "docs/vulnerabilities/python.md#py-archive", + "reason": "Review signal: Archive extraction requires path review. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "detection": "AST: any extractall is a heuristic including ZIP; extract requires known tarfile.open/TarFile/TarFile.open through aliases, constructors, simple assignment or with/as. shutil.unpack_archive requires known tar/gztar/bztar/xztar/zstdtar format, including third argument. filter='data' or tarfile.data_filter (aliases/inline **dict included) suppresses this signal, not all risks. Review custom filters, extension-inferred format, extraction_filter, versions, quotas, wrappers and complex control flow.", + "references": [ + "https://docs.python.org/3/library/tarfile.html#extraction-filters", + "https://docs.python.org/3/library/shutil.html#shutil.unpack_archive", + "https://peps.python.org/pep-0706/" + ], + "limitations": "AST: any extractall is a heuristic including ZIP; extract requires known tarfile.open/TarFile/TarFile.open through aliases, constructors, simple assignment or with/as. shutil.unpack_archive requires known tar/gztar/bztar/xztar/zstdtar format, including third argument. filter='data' or tarfile.data_filter (aliases/inline **dict included) suppresses this signal, not all risks. Review custom filters, extension-inferred format, extraction_filter, versions, quotas, wrappers and complex control flow.", + "family": "file-access", + "cwe": [ + "CWE-22" + ], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "PY-TEMP", + "languages": [ + "python" + ], + "title": "Non-atomic temporary filename", + "before": "import tempfile\nname = tempfile.mktemp()", + "after": "import tempfile\nwith tempfile.TemporaryFile() as output:\n output.write(data)", + "fix": "Create a private temporary file atomically and retain its handle; never reopen an untrusted name.", + "check": "Concurrent requests obtain separate files and cannot overwrite existing files or links.", + "engine": "python-ast", + "doc": "docs/vulnerabilities/python.md#py-temp", + "reason": "Review signal: Non-atomic temporary filename. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "limitations": "Bounded syntactic AST analysis, not type resolution or interprocedural taint analysis. Review actual API, inputs and authorization.", + "family": "file-access", + "cwe": [], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "PY-XML", + "languages": [ + "python" + ], + "title": "XML entity resolution enabled", + "before": "parser = etree.XMLParser(resolve_entities=True)", + "after": "parser = etree.XMLParser(resolve_entities=False, load_dtd=False, no_network=True)", + "fix": "Disable entity/DTD loading and network access; bound document complexity for the actual parser.", + "check": "Ordinary XML parses; external resources are not read and oversized input fails.", + "engine": "python-ast", + "doc": "docs/vulnerabilities/python.md#py-xml", + "reason": "Review signal: XML entity resolution enabled. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "detection": "AST: XMLParser by method name; lxml.etree.XMLPullParser/ETCompatXMLParser/iterparse by resolved import name/alias. Requires known resolve_entities=True, including scalar variables or inline **dict. Review defaults, lxml version, DTD, input type and wrappers. This does not determine CVE applicability.", + "references": [ + "https://github.com/lxml/lxml/security/advisories/GHSA-vfmq-68hx-4jfw" + ], + "limitations": "AST: XMLParser by method name; lxml.etree.XMLPullParser/ETCompatXMLParser/iterparse by resolved import name/alias. Requires known resolve_entities=True, including scalar variables or inline **dict. Review defaults, lxml version, DTD, input type and wrappers. This does not determine CVE applicability.", + "family": "injection", + "cwe": [ + "CWE-611" + ], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "PY-WEAK-HASH", + "languages": [ + "python" + ], + "title": "MD5/SHA1: review the purpose", + "before": "import hashlib\ndigest = hashlib.md5(password)", + "after": "import hashlib\ndigest = hashlib.scrypt(password, salt=salt, n=16384, r=8, p=1)", + "fix": "Use a supported password KDF for passwords and HMAC/signatures for authenticity; ordinary checksums need a separate decision.", + "check": "Authentication checks work and legacy data has a migration path.", + "engine": "python-ast", + "doc": "docs/vulnerabilities/python.md#py-weak-hash", + "reason": "Review signal: MD5/SHA1: review the purpose. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "limitations": "Bounded syntactic AST analysis, not type resolution or interprocedural taint analysis. Review actual API, inputs and authorization.", + "family": "secret-handling", + "cwe": [], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "PY-RNG", + "languages": [ + "python" + ], + "title": "Non-cryptographic randomness near a possible secret", + "before": "import random\ntoken = str(random.getrandbits(128))", + "after": "import secrets\ntoken = secrets.token_urlsafe(32)", + "fix": "Use secrets or a supported CSPRNG with sufficient entropy for tokens; handle generator errors.", + "check": "No predictable fallback is used; token format and sessions stay compatible.", + "engine": "python-ast", + "doc": "docs/vulnerabilities/python.md#py-rng", + "reason": "Review signal: Non-cryptographic randomness near a possible secret. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "limitations": "Bounded syntactic AST analysis, not type resolution or interprocedural taint analysis. Review actual API, inputs and authorization.", + "family": "secret-handling", + "cwe": [], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "PY-FILE", + "languages": [ + "python" + ], + "title": "Dynamic file-serving path", + "before": "result = send_file(user_path)", + "after": "record = load_owned_file(file_id, current_user.id)\nresult = send_file(record.storage_path)", + "fix": "Resolve a server-owned record after authorization and enforce the storage root; review symlinks and races.", + "check": "Other owners' files, traversal and external symlinks fail; authorized downloads work.", + "engine": "python-ast", + "doc": "docs/vulnerabilities/python.md#py-file", + "reason": "Review signal: Dynamic file-serving path. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "review_after": true, + "detection": "AST: send_file by method name, first argument or path_or_file= with aliases/inline **dict. Nonliteral paths still signal after safe owned-record lookup; custom same-named methods may match. Review authorization, root, links, wrappers and dictionary variables.", + "references": [ + "https://flask.palletsprojects.com/en/stable/api/#flask.send_file" + ], + "limitations": "AST: send_file by method name, first argument or path_or_file= with aliases/inline **dict. Nonliteral paths still signal after safe owned-record lookup; custom same-named methods may match. Review authorization, root, links, wrappers and dictionary variables.", + "family": "file-access", + "cwe": [ + "CWE-22" + ], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "PY-URL", + "languages": [ + "python" + ], + "title": "Dynamic outbound URL", + "before": "import requests\nresponse = requests.get(user_url)", + "after": "import requests\nresponse = requests.get('https://api.example.invalid/status', timeout=3, allow_redirects=False)", + "fix": "Apply explicit destination/scheme/port policy, validate resolved addresses and every redirect, and bound time/response size.", + "check": "Approved endpoints work; forbidden destinations and redirects cannot cross the trust boundary.", + "engine": "python-ast", + "doc": "docs/vulnerabilities/python.md#py-url", + "reason": "Review signal: Dynamic outbound URL. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "detection": "AST: requests/httpx/urlopen and known Session/session, requests.sessions.Session/session, Client/AsyncClient via aliases, local assignment or immediate constructor. with/as supports requests Session/httpx Client and async with/as supports AsyncClient; facts are invalidated after the region. request(method,url), httpx.stream and Client/AsyncClient.stream use second argument or url=. Literal URLs do not signal. No URL/DNS/redirect validation analysis; review wrappers, returned clients, mutable config and complex relationships.", + "references": [ + "https://requests.readthedocs.io/en/latest/user/advanced/", + "https://www.python-httpx.org/async/", + "https://www.python-httpx.org/api/" + ], + "limitations": "AST: requests/httpx/urlopen and known Session/session, requests.sessions.Session/session, Client/AsyncClient via aliases, local assignment or immediate constructor. with/as supports requests Session/httpx Client and async with/as supports AsyncClient; facts are invalidated after the region. request(method,url), httpx.stream and Client/AsyncClient.stream use second argument or url=. Literal URLs do not signal. No URL/DNS/redirect validation analysis; review wrappers, returned clients, mutable config and complex relationships.", + "family": "network-exposure", + "cwe": [], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "JS-SHELL", + "languages": [ + "javascript" + ], + "title": "Node.js shell API", + "before": "child_process.exec(command);", + "after": "child_process.execFile('/usr/bin/file', ['--', filename], {timeout: 3000}, callback);", + "fix": "Use a fixed executable and separate argv with validated options and bounded execution.", + "check": "Metacharacters stay data; dangerous options fail; normal commands work.", + "engine": "regex", + "doc": "docs/vulnerabilities/javascript.md#js-shell", + "reason": "Review signal: Node.js shell API. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "pattern": "(?query(\"SELECT id FROM notes WHERE name=\" . $name);", + "after": "$stmt = $db->prepare(\"SELECT id FROM notes WHERE name = ?\");\n$stmt->execute([$name]);", + "fix": "Use driver-supported prepared statements and bound values; allowlist identifiers.", + "check": "Quotes stay data and ownership conditions remain.", + "engine": "regex", + "doc": "docs/vulnerabilities/php.md#php-sql", + "reason": "Review signal: Dynamic PHP SQL. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "pattern": "(?:->\\s*(?:query|exec|prepare)\\s*\\(\\s*(?:(?:\"(?:\\\\.|[^\"\\\\\\r\\n]){0,500}\"|'(?:\\\\.|[^'\\\\\\r\\n]){0,500}')\\s*\\.|\"(?:\\\\.|[^\"\\\\\\r\\n]){0,500}\\$[A-Za-z_{])|\\b(?:mysqli_query|pg_query)\\s*\\(\\s*(?:[^,\\n]{1,120},\\s*)?(?:(?:\"(?:\\\\.|[^\"\\\\\\r\\n]){0,500}\"|'(?:\\\\.|[^'\\\\\\r\\n]){0,500}')\\s*\\.|\"(?:\\\\.|[^\"\\\\\\r\\n]){0,500}\\$[A-Za-z_{]))", + "detection": "Regex: query/exec/prepare with concatenation, double-quoted interpolation and mysqli_query/pg_query with an ordinary connection argument. Escaping, other interpolation and SQL variables are not fully parsed.", + "limitations": "Regex: query/exec/prepare with concatenation, double-quoted interpolation and mysqli_query/pg_query with an ordinary connection argument. Escaping, other interpolation and SQL variables are not fully parsed.", + "family": "injection", + "cwe": [ + "CWE-89" + ], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "PHP-OBJECT", + "languages": [ + "php" + ], + "title": "Untrusted PHP unserialize", + "before": "$value = unserialize($data);", + "after": "$value = json_decode($data, true, 32, JSON_THROW_ON_ERROR); // validate schema", + "fix": "Prefer schema-validated JSON; migrate trusted legacy records separately. allowed_classes alone is not a complete input policy.", + "check": "Unexpected object types fail without construction; valid records stay readable.", + "engine": "regex", + "doc": "docs/vulnerabilities/php.md#php-object", + "reason": "Review signal: Untrusted PHP unserialize. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "pattern": "\\bunserialize\\s*\\(", + "limitations": "Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.", + "family": "injection", + "cwe": [ + "CWE-502" + ], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "PHP-SHELL", + "languages": [ + "php" + ], + "title": "PHP code or shell execution", + "before": "shell_exec($command);", + "after": "$size = filesize($checkedPath);", + "fix": "Prefer a library operation; otherwise use a fixed executable and validated argv without a shell.", + "check": "Metacharacters and dangerous options cannot change the operation.", + "engine": "regex", + "doc": "docs/vulnerabilities/php.md#php-shell", + "reason": "Review signal: PHP code or shell execution. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "pattern": "(?])(?:eval|shell_exec|system|passthru|popen)\\s*\\(|(?])exec\\s*\\(|\\bproc_open\\s*\\((?!\\s*(?:command\\s*:\\s*)?(?:\\[|array\\s*\\())|\\bproc_open\\s*\\(\\s*(?:command\\s*:\\s*)?(?:\\[|array\\s*\\()\\s*[\"\\'](?:[^\"\\'\\n]*/)?(?:sh|bash|dash|zsh|cmd(?:\\.exe)?|powershell(?:\\.exe)?|pwsh)[\"\\']", + "detection": "Regex: eval/shell_exec/system/passthru/popen/exec and string/variable proc_open. Literal argv arrays in proc_open's first argument (including PHP 8 command:) are excluded unless explicitly launching shell; arrays require PHP 7.4+. Review executable/options, reordered named arguments, backticks, variable functions, wrappers and runtime version. Custom same-named functions/comments may match.", + "references": [ + "https://www.php.net/manual/en/function.proc-open.php", + "https://github.com/php/php-src/blob/php-8.0.0/ext/standard/basic_functions.stub.php#L1156", + "https://github.com/php/doc-en/blob/master/reference/exec/functions/proc-open.xml#L68" + ], + "limitations": "Regex: eval/shell_exec/system/passthru/popen/exec and string/variable proc_open. Literal argv arrays in proc_open's first argument (including PHP 8 command:) are excluded unless explicitly launching shell; arrays require PHP 7.4+. Review executable/options, reordered named arguments, backticks, variable functions, wrappers and runtime version. Custom same-named functions/comments may match.", + "family": "injection", + "cwe": [ + "CWE-78" + ], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "PHP-INCLUDE", + "languages": [ + "php" + ], + "title": "Client-selected include path", + "before": "include $_GET['page'];", + "after": "$pages = ['home' => __DIR__ . '/pages/home.php'];\nif (!isset($pages[$page])) { throw new Exception('bad page'); }\ninclude $pages[$page];", + "fix": "Select server-owned include paths from a closed allowlist, never client paths/URLs.", + "check": "Only approved pages load; traversal and remote schemes fail.", + "engine": "regex", + "doc": "docs/vulnerabilities/php.md#php-include", + "reason": "Review signal: Client-selected include path. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "pattern": "\\b(?:include|require)(?:_once)?\\s*\\(?\\s*\\$_(?:GET|POST|REQUEST|COOKIE)\\b", + "limitations": "Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.", + "family": "file-access", + "cwe": [ + "CWE-22" + ], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "GO-SQL", + "languages": [ + "go" + ], + "title": "Dynamic Go SQL", + "before": "db.Query(\"SELECT id FROM notes WHERE name=\" + name)", + "after": "db.Query(\"SELECT id FROM notes WHERE name=$1\", name)", + "fix": "Bind values using actual driver placeholders; allowlist identifiers.", + "check": "Quotes remain values; legitimate queries and ownership checks work.", + "engine": "regex", + "doc": "docs/vulnerabilities/go.md#go-sql", + "reason": "Review signal: Dynamic Go SQL. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "pattern": "\\.(?:(?:Query|QueryRow|Exec|Prepare)\\s*\\(\\s*|(?:Query|QueryRow|Exec|Prepare)Context\\s*\\(\\s*[^,\\n]{1,160},\\s*)(?:fmt\\.Sprintf\\s*\\(|\"(?:\\\\.|[^\"\\\\\\r\\n]){0,500}\"\\s*\\+)", + "detection": "Regex: Query/QueryRow/Exec/Prepare and Context forms with concatenation or fmt.Sprintf. Simple context expressions are supported; review complex syntax, fmt aliases and preassembled SQL.", + "limitations": "Regex: Query/QueryRow/Exec/Prepare and Context forms with concatenation or fmt.Sprintf. Simple context expressions are supported; review complex syntax, fmt aliases and preassembled SQL.", + "family": "injection", + "cwe": [ + "CWE-89" + ], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "GO-HASH-SUM", + "languages": [ + "go" + ], + "title": "Non-empty argument to hash.Sum", + "before": "digest := h.Sum(record.Hash[:])", + "after": "h.Write(record.Hash[:])\ndigest := h.Sum(nil)", + "fix": "Use Write to hash bytes and Sum(nil) for the digest; Sum appends a digest instead of hashing its argument.", + "check": "Known vectors match; legacy digest formats are migrated deliberately.", + "engine": "regex", + "doc": "docs/vulnerabilities/go.md#go-hash-sum", + "reason": "Review signal: Non-empty argument to hash.Sum. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "pattern": "\\.Sum\\s*\\(\\s*(?!nil\\s*\\))[^)\\s][^)]{0,250}\\)", + "limitations": "Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.", + "family": "manual-review", + "cwe": [], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "GO-HTML", + "languages": [ + "go" + ], + "title": "Go autoescape bypass", + "before": "value := template.HTML(input)", + "after": "value := input // string passed to html/template", + "fix": "Pass strings to html/template; use trusted HTML only after a reviewed sanitizer if needed.", + "check": "User tags/quotes render as text; intended formatting works.", + "engine": "regex", + "doc": "docs/vulnerabilities/go.md#go-html", + "reason": "Review signal: Go autoescape bypass. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "pattern": "\\btemplate\\.(?:HTML|JS|URL|CSS|HTMLAttr)\\s*\\(", + "limitations": "Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.", + "family": "injection", + "cwe": [ + "CWE-79" + ], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "GO-TLS", + "languages": [ + "go" + ], + "title": "Go InsecureSkipVerify", + "before": "cfg := tls.Config{InsecureSkipVerify: true}", + "after": "cfg := tls.Config{InsecureSkipVerify: false}", + "fix": "Use normal certificate/hostname verification and the required CA; review custom verification callbacks.", + "check": "Correct peers work and invalid certificates fail.", + "engine": "regex", + "doc": "docs/vulnerabilities/go.md#go-tls", + "reason": "Review signal: Go InsecureSkipVerify. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "pattern": "\\bInsecureSkipVerify\\s*:\\s*true\\b|\\.\\s*InsecureSkipVerify\\s*=(?!=)\\s*true\\b", + "detection": "Regex: InsecureSkipVerify:true and .InsecureSkipVerify=true assignments including newlines; ==, != and false do not match. VerifyConnection does not suppress review: inspect object type, reachability, callback and effective config. Comments/strings may match.", + "references": [ + "https://pkg.go.dev/crypto/tls#Config" + ], + "limitations": "Regex: InsecureSkipVerify:true and .InsecureSkipVerify=true assignments including newlines; ==, != and false do not match. VerifyConnection does not suppress review: inspect object type, reachability, callback and effective config. Comments/strings may match.", + "family": "network-exposure", + "cwe": [], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "JAVA-OBJECT", + "languages": [ + "java" + ], + "title": "Java ObjectInputStream", + "before": "ObjectInputStream in = new ObjectInputStream(stream);", + "after": "Message value = parseValidatedMessage(stream);", + "fix": "Prefer constrained DTO parsing over native object deserialization; migrate trusted legacy data separately.", + "check": "Unknown types cannot be constructed; ordinary messages stay compatible.", + "engine": "regex", + "doc": "docs/vulnerabilities/java.md#java-object", + "reason": "Review signal: Java ObjectInputStream. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "pattern": "\\bObjectInputStream\\b|\\.readObject\\s*\\(", + "limitations": "Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.", + "family": "injection", + "cwe": [ + "CWE-502" + ], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "JAVA-RNG", + "languages": [ + "java" + ], + "title": "java.util.Random near a possible secret", + "before": "Random rng = new Random();", + "after": "SecureRandom rng = new SecureRandom();", + "fix": "Use SecureRandom and sufficient token length for secrets.", + "check": "No predictable seed or fallback exists; valid tokens work.", + "engine": "regex", + "doc": "docs/vulnerabilities/java.md#java-rng", + "reason": "Review signal: java.util.Random near a possible secret. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "pattern": "\\bnew\\s+(?:java\\.util\\.)?Random\\s*\\(|\\bMath\\.random\\s*\\(", + "limitations": "Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.", + "family": "secret-handling", + "cwe": [], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "JAVA-SQL", + "languages": [ + "java" + ], + "title": "Dynamic JDBC SQL", + "before": "statement.executeQuery(\"SELECT id FROM notes WHERE name=\" + name);", + "after": "PreparedStatement q = connection.prepareStatement(\"SELECT id FROM notes WHERE name=?\");\nq.setString(1, name);\nq.executeQuery();", + "fix": "Bind values with PreparedStatement, not already-concatenated SQL; allowlist identifiers.", + "check": "Quotes stay data and ownership remains enforced.", + "engine": "regex", + "doc": "docs/vulnerabilities/java.md#java-sql", + "reason": "Review signal: Dynamic JDBC SQL. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "pattern": "\\.(?:executeQuery|executeUpdate|execute|prepareStatement|prepareCall)\\s*\\(\\s*(?:\"(?:\\\\.|[^\"\\\\\\r\\n]){0,500}\"\\s*\\+|String\\s*\\.\\s*format\\s*\\()", + "detection": "Regex: executeQuery/executeUpdate/execute/prepareStatement/prepareCall with concatenation or String.format. PreparedStatement does not secure already-built SQL; inspect SQL variables and formatter wrappers.", + "limitations": "Regex: executeQuery/executeUpdate/execute/prepareStatement/prepareCall with concatenation or String.format. PreparedStatement does not secure already-built SQL; inspect SQL variables and formatter wrappers.", + "family": "injection", + "cwe": [ + "CWE-89" + ], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "JAVA-PROCESS", + "languages": [ + "java" + ], + "title": "Java process execution", + "before": "Runtime.getRuntime().exec(command);", + "after": "runValidatedConversion(inputPath); // fixed executable and validated argv inside", + "fix": "Use a library operation or fixed executable with validated argv and bounded time/output.", + "check": "Arguments cannot choose another operation; output stays compatible.", + "engine": "regex", + "doc": "docs/vulnerabilities/java.md#java-process", + "reason": "Review signal: Java process execution. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "pattern": "\\bRuntime\\.getRuntime\\s*\\(\\s*\\)\\.exec\\s*\\(|\\bnew\\s+ProcessBuilder\\s*\\(", + "limitations": "Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.", + "family": "injection", + "cwe": [ + "CWE-78" + ], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "CS-DESERIALIZE", + "languages": [ + "csharp" + ], + "title": "Type-controlled .NET deserialization", + "before": "var formatter = new BinaryFormatter();", + "after": "var value = JsonSerializer.Deserialize(json); // validate fields", + "fix": "Use explicit DTOs and a supported serializer with schema/size checks; remove unrestricted type activation and migrate legacy data.", + "check": "Unknown types fail before side effects; valid records parse.", + "engine": "regex", + "doc": "docs/vulnerabilities/csharp.md#cs-deserialize", + "reason": "Review signal: Type-controlled .NET deserialization. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "pattern": "\\b(?:BinaryFormatter|NetDataContractSerializer)\\b|\\bTypeNameHandling\\s*=\\s*TypeNameHandling\\.(?:All|Auto|Objects|Arrays)", + "limitations": "Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.", + "family": "injection", + "cwe": [ + "CWE-502" + ], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "CS-ENUM", + "languages": [ + "csharp" + ], + "title": "Enum.TryParse requires an allowed-value check", + "before": "bool ok = Enum.TryParse(input, out FilterKind kind);", + "after": "if (!TryParseAllowedFilter(input, out FilterKind kind)) return BadRequest(); // helper validates named allowlist", + "fix": "Validate allowed named values; parsing success alone does not prove enum membership.", + "check": "Unnamed numeric values and unsupported flags fail; supported filters work.", + "engine": "regex", + "doc": "docs/vulnerabilities/csharp.md#cs-enum", + "reason": "Review signal: Enum.TryParse requires an allowed-value check. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "pattern": "\\bEnum\\.TryParse(?:<[^>]{1,100}>)?\\s*\\(", + "limitations": "Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.", + "family": "manual-review", + "cwe": [], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "CS-SQL", + "languages": [ + "csharp" + ], + "title": "Dynamic .NET SQL", + "before": "context.Notes.FromSqlRaw(\"SELECT * FROM notes WHERE name=\" + name);", + "after": "context.Notes.FromSqlRaw(\"SELECT * FROM notes WHERE name={0}\", name);", + "fix": "Use provider-supported parameters and allowlisted identifiers.", + "check": "Quotes cannot change SQL structure; tenant restrictions remain.", + "engine": "regex", + "doc": "docs/vulnerabilities/csharp.md#cs-sql", + "reason": "Review signal: Dynamic .NET SQL. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "pattern": "\\b(?:FromSqlRaw|ExecuteSqlRaw)\\s*\\(\\s*(?:\\$\\\"|\\\"[^\\n]{0,500}\\\"\\s*\\+)", + "limitations": "Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.", + "family": "injection", + "cwe": [ + "CWE-89" + ], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "C-BOUNDS", + "languages": [ + "native" + ], + "title": "Unbounded C/C++ copy", + "before": "strcpy(destination, source);", + "after": "size_t n = strlen(source);\nif (n >= capacity) return ERROR;\nmemcpy(destination, source, n + 1);", + "fix": "Check length/capacity before copying and check snprintf's result; mechanical strncpy replacement is insufficient.", + "check": "Test empty, boundary and oversized input; use ASan/UBSan where available.", + "engine": "regex", + "doc": "docs/vulnerabilities/c-cpp.md#c-bounds", + "reason": "Review signal: Unbounded C/C++ copy. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "pattern": "\\b(?:strcpy|strcat|sprintf|gets)\\s*\\(", + "limitations": "Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.", + "family": "memory-safety", + "cwe": [], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "C-FORMAT", + "languages": [ + "native" + ], + "title": "Variable used as a format string", + "before": "printf(message);", + "after": "printf(\"%s\", message);", + "fix": "Use a fixed format and checked arguments; pass explicit lengths for binary data.", + "check": "Percent characters print without interpreting directives.", + "engine": "regex", + "doc": "docs/vulnerabilities/c-cpp.md#c-format", + "reason": "Review signal: Variable used as a format string. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "pattern": "\\bprintf\\s*\\(\\s*[A-Za-z_]\\w*\\s*[,)]|\\bfprintf\\s*\\(\\s*[^,]{1,100},\\s*[A-Za-z_]\\w*\\s*[,)]", + "limitations": "Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.", + "family": "memory-safety", + "cwe": [], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "C-SHELL", + "languages": [ + "native" + ], + "title": "C/C++ shell execution", + "before": "system(command);", + "after": "run_fixed_tool(validated_filename); // fixed executable + argv inside", + "fix": "Use execve/posix_spawn with fixed program and validated argv; handle errors.", + "check": "Metacharacters are not interpreted by a shell.", + "engine": "regex", + "doc": "docs/vulnerabilities/c-cpp.md#c-shell", + "reason": "Review signal: C/C++ shell execution. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "pattern": "\\b(?:system|popen)\\s*\\(", + "limitations": "Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.", + "family": "injection", + "cwe": [ + "CWE-78" + ], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "CFG-SECRET", + "languages": [ + "python", + "javascript", + "php", + "go", + "java", + "csharp", + "config", + "ruby", + "rust" + ], + "title": "Literal secret or default key", + "before": "JWT_SECRET = \"development\"", + "after": "JWT_SECRET = load_existing_secret()", + "fix": "Check active fallbacks; read secrets from private configuration. Rotate with migration/rollback for sessions and data.", + "check": "No shared fallback remains; legitimate sessions/data stay recoverable.", + "engine": "regex", + "doc": "docs/vulnerabilities/configuration.md#cfg-secret", + "reason": "Review signal: Literal secret or default key. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "pattern": "\\b(?:jwt[_-]?(?:secret|key)|secret[_-]?key|session[_-]?secret|admin[_-]?password)\\b[\\\"']?\\s*(?::\\s*(?:str|string))?\\s*[:=]\\s*[\\\"'][^\\\"'\\r\\n]{1,200}[\\\"']", + "limitations": "Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.", + "family": "secret-handling", + "cwe": [], + "review_priority": "normal", + "signal_kind": "configuration-review" + }, + { + "id": "CFG-DEBUG", + "languages": [ + "config" + ], + "title": "Debug enabled in configuration", + "before": "DEBUG=true", + "after": "DEBUG=false", + "fix": "Disable runtime debug and keep private diagnostics without secrets.", + "check": "Errors expose neither console nor stack trace.", + "engine": "regex", + "doc": "docs/vulnerabilities/configuration.md#cfg-debug", + "reason": "Review signal: Debug enabled in configuration. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "pattern": "\\b(?:DEBUG|FLASK_DEBUG|APP_DEBUG)\\s*[:=]\\s*[\\\"']?(?:true|1)\\b", + "limitations": "Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.", + "family": "information-disclosure", + "cwe": [], + "review_priority": "normal", + "signal_kind": "configuration-review" + }, + { + "id": "CFG-CORS", + "languages": [ + "config", + "javascript", + "python", + "go", + "java", + "csharp" + ], + "title": "Broad CORS policy", + "before": "Access-Control-Allow-Origin: *", + "after": "Access-Control-Allow-Origin: https://ui.example.invalid", + "fix": "Allowlist actual origins and use Vary: Origin where needed; authentication and CSRF remain separate. A wildcard alone is not an auth bypass.", + "check": "Authorized browsers work; unrelated origins cannot read private responses.", + "engine": "regex", + "doc": "docs/vulnerabilities/configuration.md#cfg-cors", + "reason": "Review signal: Broad CORS policy. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "pattern": "(?:Access-Control-Allow-Origin|allow_origins|allowedOrigins|cors_origin)\\s*[\\\"']?\\s*[:=]\\s*\\[?\\s*[\\\"']?\\*", + "limitations": "Legacy wildcard header/config heuristic (untyped). JS bounded tokens also detect default imported/required cors with inline origin:true and credentials:true, literal quoted keys and last-write-wins fields. Observed shadows/reassignments suppress the new hint. Computed keys, variables, wrappers, actual response policy and other languages remain manual.", + "family": "network-exposure", + "cwe": [], + "review_priority": "normal", + "signal_kind": "configuration-review", + "detection": "Legacy wildcard header/config heuristic (untyped). JS bounded tokens also detect default imported/required cors with inline origin:true and credentials:true, literal quoted keys and last-write-wins fields. Observed shadows/reassignments suppress the new hint. Computed keys, variables, wrappers, actual response policy and other languages remain manual.", + "coverage_required": [ + "javascript" + ] + }, + { + "id": "CFG-DOCKER-PRIV", + "languages": [ + "config" + ], + "title": "Privileged container", + "before": "privileged: true", + "after": "privileged: false", + "fix": "Identify minimum capabilities and change only authorized owned services, not organizer infrastructure.", + "check": "Service/checker works without unnecessary privileges.", + "engine": "regex", + "doc": "docs/vulnerabilities/configuration.md#cfg-docker-priv", + "reason": "Review signal: Privileged container. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "pattern": "\\bprivileged[\"\\']?\\s*:\\s*true\\b|\\bcap_add[\"\\']?\\s*:\\s*\\[[^\\]]{0,300}\\b(?:SYS_ADMIN|ALL)\\b", + "detection": "Regex: privileged:true and cap_add with SYS_ADMIN/ALL, including quoted JSON keys. CFG-CAPABILITIES covers block capabilities; inspect effective Docker/Kubernetes config.", + "limitations": "Regex: privileged:true and cap_add with SYS_ADMIN/ALL, including quoted JSON keys. CFG-CAPABILITIES covers block capabilities; inspect effective Docker/Kubernetes config.", + "family": "container-isolation", + "cwe": [], + "review_priority": "normal", + "signal_kind": "configuration-review" + }, + { + "id": "CFG-DOCKER-SOCKET", + "languages": [ + "config", + "docker", + "shell" + ], + "title": "Docker socket exposed to a service", + "before": "- /var/run/docker.sock:/var/run/docker.sock", + "after": "- app-data:/srv/data", + "fix": "Remove unnecessary mounts after checking dependencies/rules; never alter unrelated containers automatically.", + "check": "Required service and approved management operations work.", + "engine": "regex", + "doc": "docs/vulnerabilities/configuration.md#cfg-docker-socket", + "reason": "Review signal: Docker socket exposed to a service. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "pattern": "/(?:var/)?run/docker\\.sock", + "limitations": "Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.", + "family": "container-isolation", + "cwe": [], + "review_priority": "normal", + "signal_kind": "configuration-review" + }, + { + "id": "CFG-DOCKER-ROOT", + "languages": [ + "docker" + ], + "title": "Explicit Docker USER root", + "before": "USER root", + "after": "USER app", + "fix": "Prepare an unprivileged user and directory permissions; missing USER is not detected by this rule.", + "check": "Volumes, ports, writes and restart work.", + "engine": "regex", + "doc": "docs/vulnerabilities/configuration.md#cfg-docker-root", + "reason": "Review signal: Explicit Docker USER root. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "pattern": "^\\s*USER\\s+(?:root|0)(?:\\s|:|$)", + "limitations": "Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.", + "family": "container-isolation", + "cwe": [], + "review_priority": "normal", + "signal_kind": "configuration-review" + }, + { + "id": "CFG-WORLD-WRITE", + "languages": [ + "docker", + "shell" + ], + "title": "Broad write permissions", + "before": "chmod -R 777 /srv/app", + "after": "chmod 750 /srv/app", + "fix": "Set intended owner/group and minimum modes; do not recursively replace permissions blindly.", + "check": "Service can write data; others cannot change code.", + "engine": "regex", + "doc": "docs/vulnerabilities/configuration.md#cfg-world-write", + "reason": "Review signal: Broad write permissions. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "pattern": "\\bchmod\\s+(?:-[A-Za-z]+\\s+)*(?:0?777|0?666|a\\+w)\\b", + "limitations": "Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.", + "family": "manual-review", + "cwe": [], + "review_priority": "normal", + "signal_kind": "configuration-review" + }, + { + "id": "CFG-NGINX-LIST", + "languages": [ + "config" + ], + "title": "nginx directory listing", + "before": "autoindex on;", + "after": "autoindex off;", + "fix": "Disable listing unless it is required functionality.", + "check": "Downloads work; private directory contents are not enumerated.", + "engine": "regex", + "doc": "docs/vulnerabilities/configuration.md#cfg-nginx-list", + "reason": "Review signal: nginx directory listing. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "pattern": "\\bautoindex\\s+on\\s*;", + "limitations": "Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.", + "family": "file-access", + "cwe": [], + "review_priority": "normal", + "signal_kind": "configuration-review" + }, + { + "id": "CFG-NGINX-ALIAS", + "languages": [ + "config" + ], + "title": "Review nginx alias boundaries", + "before": "location /files { alias /srv/files/; }", + "after": "location /files/ { root /srv; } # verify mapping and auth", + "fix": "Align location /files/ with alias /srv/files/; review normalization/auth. Correct aliases also trigger review.", + "check": "Boundary URLs stay inside the root; old public URLs work.", + "engine": "regex", + "doc": "docs/vulnerabilities/configuration.md#cfg-nginx-alias", + "reason": "Review signal: Review nginx alias boundaries. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "pattern": "\\balias\\s+[^;]{1,500};", + "limitations": "Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.", + "family": "file-access", + "cwe": [ + "CWE-22" + ], + "review_priority": "normal", + "signal_kind": "configuration-review" + }, + { + "id": "CFG-POSTGRES-TRUST", + "languages": [ + "config" + ], + "title": "PostgreSQL trust authentication", + "before": "POSTGRES_HOST_AUTH_METHOD: trust", + "after": "POSTGRES_HOST_AUTH_METHOD: scram-sha-256", + "fix": "Use supported auth and coordinated application credentials; do not change organizer accounts/network.", + "check": "Application connects; unknown credentials fail.", + "engine": "regex", + "doc": "docs/vulnerabilities/configuration.md#cfg-postgres-trust", + "reason": "Review signal: PostgreSQL trust authentication. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "pattern": "\\bPOSTGRES_HOST_AUTH_METHOD[\"\\']?\\s*[:=]\\s*[\"\\']?trust\\b|^[ \\t]*local[ \\t]+\\S+[ \\t]+\\S+[ \\t]+trust\\b|^[ \\t]*host(?:ssl|nossl|gssenc|nogssenc)?[ \\t]+\\S+[ \\t]+\\S+[ \\t]+\\S+[ \\t]+(?:\\S+[ \\t]+)?trust\\b", + "detection": "Regex: POSTGRES_HOST_AUTH_METHOD=trust including JSON; pg_hba local/host/hostssl/hostnossl/hostgssenc/hostnogssenc with trust and CIDR or separate IPv4 netmask. Inspect HBA order and actual matching entries.", + "limitations": "Regex: POSTGRES_HOST_AUTH_METHOD=trust including JSON; pg_hba local/host/hostssl/hostnossl/hostgssenc/hostnogssenc with trust and CIDR or separate IPv4 netmask. Inspect HBA order and actual matching entries.", + "family": "authentication", + "cwe": [], + "review_priority": "normal", + "signal_kind": "configuration-review" + }, + { + "id": "CFG-REDIS-PROTECTION", + "languages": [ + "config" + ], + "title": "Redis protected-mode disabled", + "before": "protected-mode no", + "after": "protected-mode yes", + "fix": "Review ACL, credentials, bind and clients against game rules without blocking required traffic.", + "check": "Application connects with minimum required permissions.", + "engine": "regex", + "doc": "docs/vulnerabilities/configuration.md#cfg-redis-protection", + "reason": "Review signal: Redis protected-mode disabled. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "pattern": "\\bprotected-mode\\s+no\\b", + "limitations": "Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.", + "family": "network-exposure", + "cwe": [], + "review_priority": "normal", + "signal_kind": "configuration-review" + }, + { + "id": "TPL-RAW", + "languages": [ + "template" + ], + "title": "Unescaped template output", + "before": "{{ message | safe }}", + "after": "{{ message }}", + "fix": "Use normal escaped text output or a context-tested sanitizer for permitted HTML.", + "check": "User markup stays text and layout remains intact.", + "engine": "regex", + "doc": "docs/vulnerabilities/configuration.md#tpl-raw", + "reason": "Review signal: Unescaped template output. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "pattern": "\\|\\s*(?:safe|raw)\\b|\\{\\{\\{[\\s\\S]{0,300}?\\}\\}\\}|<%-", + "limitations": "Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.", + "family": "injection", + "cwe": [ + "CWE-79" + ], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "SRC-MIXED-IDENTIFIER", + "languages": [ + "python", + "javascript", + "php", + "go", + "java", + "csharp", + "native", + "ruby", + "rust", + "shell" + ], + "title": "Mixed Latin/Cyrillic/Greek identifier", + "before": "uuіd = input_value", + "after": "validated_uuid = parse_uuid(input_value)", + "fix": "Inspect code points/references and use distinguishable names and the validated value; never blindly rename text.", + "check": "Validation and consumption use the same value; invalid input fails. Strings/comments may be harmless.", + "doc": "docs/vulnerabilities/configuration.md#src-mixed-identifier", + "engine": "regex", + "reason": "Review signal: Mixed Latin/Cyrillic/Greek identifier. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "pattern": "\\b(?=\\w{0,127}[A-Za-z])(?=\\w{0,127}[\\u0370-\\u03ff\\u0400-\\u052f])\\w{1,128}\\b", + "limitations": "Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.", + "family": "manual-review", + "cwe": [], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "SRC-BIDI-CONTROL", + "languages": [ + "python", + "javascript", + "php", + "go", + "java", + "csharp", + "native", + "ruby", + "rust", + "shell", + "config", + "template", + "sql" + ], + "title": "Bidirectional text control in source", + "before": "# direction ‮ marker", + "after": "# explicit plain-text comment", + "fix": "Inspect actual Unicode/token order and remove unnecessary controls; review legitimate localization separately.", + "check": "Rendered and actual flow agree; copying does not restore controls.", + "doc": "docs/vulnerabilities/configuration.md#src-bidi-control", + "engine": "regex", + "reason": "Review signal: Bidirectional text control in source. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "pattern": "[\\u202a-\\u202e\\u2066-\\u2069]", + "limitations": "Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.", + "family": "manual-review", + "cwe": [], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "GO-SHELL", + "languages": [ + "go" + ], + "title": "Go exec.Command launches a shell", + "before": "cmd := exec.Command(\"sh\", \"-c\", command)", + "after": "cmd := exec.Command(\"/usr/bin/file\", \"--\", filename)", + "fix": "Use fixed executable plus argv. Pass stdin records without a shell and validate their separators.", + "check": "Metacharacters stay data; dangerous options/separators fail; supported arguments work.", + "doc": "docs/vulnerabilities/go.md#go-shell", + "engine": "regex", + "reason": "Review signal: Go exec.Command launches a shell. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "pattern": "\\b[A-Za-z_]\\w*\\s*\\.\\s*(?:Command\\s*\\(\\s*|CommandContext\\s*\\(\\s*[^,\\n]{1,160},\\s*)\"(?:/(?:usr/)?bin/)?(?:sh|bash|zsh|dash|ksh)\"\\s*,\\s*\"-(?:c|lc|ec)\"", + "detection": "Regex: any receiver.Command/CommandContext with literal shell and -c/-lc/-ec. Simple context expressions including r.Context() work; nested commas may hide a call. Inspect receiver type and command trust.", + "limitations": "Regex: any receiver.Command/CommandContext with literal shell and -c/-lc/-ec. Simple context expressions including r.Context() work; nested commas may hide a call. Inspect receiver type and command trust.", + "family": "injection", + "cwe": [ + "CWE-78" + ], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "GO-CRC", + "languages": [ + "go" + ], + "title": "CRC near an identifier or trust boundary", + "before": "resource := service.CRC.Calculate(username)", + "after": "resource := sha256.Sum256([]byte(username))", + "fix": "CRC is not an ownership boundary. Use unique server-owned IDs plus authorization or HMAC for authenticity.", + "check": "Collisions cannot change ownership; old IDs have a migration path.", + "doc": "docs/vulnerabilities/go.md#go-crc", + "engine": "regex", + "reason": "Review signal: CRC near an identifier or trust boundary. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "pattern": "\\b(?:crc32|crc64)\\.(?:Checksum|ChecksumIEEE|New|NewIEEE)\\s*\\(|\\bCRC(?:\\d+)?\\.(?:Calculate|Checksum)\\s*\\(", + "limitations": "Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.", + "family": "secret-handling", + "cwe": [], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "GO-MATH-RAND", + "languages": [ + "go" + ], + "title": "math/rand near a possible secret", + "before": "import \"math/rand\"\nrand.Seed(time.Now().UnixMilli())", + "after": "import \"crypto/rand\"\n_, err := rand.Read(token)\nif err != nil { return err }", + "fix": "Use crypto/rand and handle errors; alphabet shuffling/hidden seeds do not create a CSPRNG.", + "check": "Entropy/length suffice and failure never creates a predictable fallback.", + "doc": "docs/vulnerabilities/go.md#go-math-rand", + "engine": "regex", + "reason": "Review signal: math/rand near a possible secret. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "pattern": "\\\"math/rand(?:/v2)?\\\"", + "limitations": "Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.", + "family": "secret-handling", + "cwe": [], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "PY-CRC", + "languages": [ + "python" + ], + "title": "CRC/Adler near an integrity boundary", + "before": "import zlib\ntag = zlib.crc32(payload)", + "after": "import hmac\ntag = hmac.digest(key, payload, 'sha256')", + "fix": "Use HMAC/signatures for authenticity or unique IDs plus authorization; ordinary checksums may remain CRC.", + "check": "Modified messages without the key fail; formats/records stay compatible.", + "doc": "docs/vulnerabilities/python.md#py-crc", + "engine": "python-ast", + "reason": "Review signal: CRC/Adler near an integrity boundary. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "limitations": "Bounded syntactic AST analysis, not type resolution or interprocedural taint analysis. Review actual API, inputs and authorization.", + "family": "secret-handling", + "cwe": [], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "C-PRNG", + "languages": [ + "native" + ], + "title": "Ordinary PRNG/LCG near a possible secret", + "before": "srand((unsigned)time(NULL));\ntoken = rand();", + "after": "if (!fill_from_os_csprng(token, sizeof token)) return ERROR; // implement using supported OS/library API", + "fix": "Use system CSPRNG/supported crypto and check results; ordinary non-security randomness may use a PRNG.", + "check": "No predictable seed/fallback exists; token format stays compatible.", + "doc": "docs/vulnerabilities/c-cpp.md#c-prng", + "engine": "regex", + "reason": "Review signal: Ordinary PRNG/LCG near a possible secret. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "pattern": "\\b(?:srand|rand|random|srandom|lcgrand|slcgrand)\\s*\\(", + "limitations": "Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.", + "family": "secret-handling", + "cwe": [], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "C-SNPRINTF-FORMAT", + "languages": [ + "native" + ], + "title": "Variable format in bounded printf", + "before": "snprintf(out, capacity, message);", + "after": "snprintf(out, capacity, \"%s\", message);", + "fix": "Use a fixed format; buffer limits do not secure untrusted format strings. Trace wrappers/macros.", + "check": "Percent characters stay text, truncation is handled; legitimate wrappers may still match.", + "doc": "docs/vulnerabilities/c-cpp.md#c-snprintf-format", + "engine": "regex", + "reason": "Review signal: Variable format in bounded printf. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "pattern": "\\b(?:snprintf|vsnprintf|safe_snprintf)\\s*\\(\\s*[^,;\\n]{1,180},\\s*(?:sizeof\\s*\\([^)]{1,100}\\)|[^,;\\n]{1,180})\\s*,\\s*[A-Za-z_]\\w*(?:\\[[^\\]]{1,100}\\])?\\s*[,)]", + "limitations": "Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.", + "family": "memory-safety", + "cwe": [], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "C-RECV-TERMINATOR", + "languages": [ + "native" + ], + "title": "recv/read result used as an index", + "before": "n = recv(fd, buffer, sizeof buffer, 0);\nbuffer[n] = '\\0';", + "after": "ssize_t n = recv(fd, buffer, sizeof buffer - 1, 0);\nif (n <= 0) return ERROR;\nbuffer[n] = '\\0';", + "fix": "Reserve NUL space, handle negative/EOF results before indexing, and handle short reads. Correct code may still match.", + "check": "Test errors, EOF, full buffer, short reads and normal messages.", + "doc": "docs/vulnerabilities/c-cpp.md#c-recv-terminator", + "engine": "regex", + "reason": "Review signal: recv/read result used as an index. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "pattern": "\\b(?P[A-Za-z_]\\w*)\\s*=\\s*(?:recv|read)\\s*\\([^;]{1,300}\\);[\\s\\S]{0,400}?\\b[A-Za-z_]\\w*\\s*\\[\\s*(?P=read_count)\\s*\\]\\s*=", + "review_after": true, + "limitations": "Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.", + "family": "memory-safety", + "cwe": [], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "PY-XPATH", + "languages": [ + "python" + ], + "title": "XPath assembled from strings", + "before": "node.xpath(\"//user[name='%s']\" % username)", + "after": "node.xpath(\"//user[name=$name]\", name=username)", + "fix": "Bind variables with the actual API and keep XPath fixed; do not quote data into syntax.", + "check": "Quotes/brackets stay data; search scope/ownership does not expand.", + "doc": "docs/vulnerabilities/python.md#py-xpath", + "engine": "python-ast", + "reason": "Review signal: XPath assembled from strings. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "detection": "AST: xpath/XPath by method name and string construction in first argument or simple assignment. String literals, Add-concatenated literals and f-strings without FormattedValue do not signal; %, format and interpolated f-strings require review. No arbitrary evaluation; inspect wrappers, XPath variables and trust.", + "limitations": "AST: xpath/XPath by method name and string construction in first argument or simple assignment. String literals, Add-concatenated literals and f-strings without FormattedValue do not signal; %, format and interpolated f-strings require review. No arbitrary evaluation; inspect wrappers, XPath variables and trust.", + "family": "injection", + "cwe": [], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "PY-UUID-BYTES", + "languages": [ + "python" + ], + "title": "UUID bytes/bytes_le protocol boundary", + "before": "import uuid\nvalue = uuid.UUID(bytes_le=wire_bytes)", + "after": "import uuid\nvalue = uuid.UUID(wire_text) # canonical text contract", + "fix": "Agree on canonical text or documented byte order across languages/cache/DB; bytes_le is not inherently unsafe.", + "check": "Asymmetric vectors and round trips agree; old references remain valid.", + "doc": "docs/vulnerabilities/python.md#py-uuid-bytes", + "engine": "python-ast", + "reason": "Review signal: UUID bytes/bytes_le protocol boundary. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "limitations": "Bounded syntactic AST analysis, not type resolution or interprocedural taint analysis. Review actual API, inputs and authorization.", + "family": "manual-review", + "cwe": [], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "CS-GUID-BYTES", + "languages": [ + "csharp" + ], + "title": "Byte-order Guid protocol boundary", + "before": "var value = new Guid(wireBytes);", + "after": "var value = Guid.ParseExact(wireText, \"D\");", + "fix": "Agree on byte order with peers; use canonical text or explicit conversion, not arbitrary reversal.", + "check": "Asymmetric UUID vectors agree across C#/Python, database and cache.", + "doc": "docs/vulnerabilities/csharp.md#cs-guid-bytes", + "engine": "regex", + "reason": "Review signal: Byte-order Guid protocol boundary. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "pattern": "\\bnew\\s+Guid\\s*\\(\\s*[A-Za-z_]\\w*(?:\\.[A-Za-z_]\\w*)*\\s*\\)", + "limitations": "Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.", + "family": "manual-review", + "cwe": [], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "SQL-UPSERT", + "languages": [ + "sql", + "python", + "javascript", + "php", + "go", + "java", + "csharp", + "ruby", + "rust" + ], + "title": "Upsert/replace requires ownership review", + "before": "INSERT INTO notes(id, owner, body) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE body=VALUES(body);", + "after": "UPDATE notes SET body=? WHERE id=? AND owner=?;", + "fix": "Separate create/update, normalize before authorization, enforce ownership in atomic UPDATE and check rows, uniqueness and transactions.", + "check": "Case/Unicode/trigger conflicts cannot update another owner; normal edits work.", + "doc": "docs/vulnerabilities/sql.md#sql-upsert", + "engine": "regex", + "reason": "Review signal: Upsert/replace requires ownership review. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "pattern": "\\bON\\s+DUPLICATE\\s+KEY\\s+UPDATE\\b|\\bON\\s+CONFLICT[\\s\\S]{0,200}?\\bDO\\s+UPDATE\\b|\\bINSERT\\s+OR\\s+REPLACE\\s+INTO\\b|\\bREPLACE\\s+INTO\\b", + "limitations": "Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.", + "family": "authentication", + "cwe": [], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "GO-READALL-BODY", + "languages": [ + "go" + ], + "title": "ReadAll on a request body", + "before": "body, err := io.ReadAll(r.Body)", + "after": "r.Body = http.MaxBytesReader(w, r.Body, 1<<20)\nbody, err := io.ReadAll(r.Body)\nif err != nil { return } // map to an appropriate client error", + "fix": "Limit the body before reading and handle excess size; the rule does not track earlier MaxBytesReader calls.", + "check": "Test limit-1/limit/limit+1 and streams without Content-Length.", + "doc": "docs/vulnerabilities/go.md#go-readall-body", + "engine": "regex", + "reason": "Review signal: ReadAll on a request body. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "pattern": "\\b(?:io|ioutil)\\.ReadAll\\s*\\(\\s*[A-Za-z_]\\w*\\.Body\\s*\\)", + "review_after": true, + "limitations": "Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.", + "family": "resource-limits", + "cwe": [], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "JS-TRUST-PROXY", + "languages": [ + "javascript" + ], + "title": "Unrestricted trust in proxy headers", + "before": "app.set('trust proxy', true);", + "after": "app.set('trust proxy', isKnownProxy); // implement topology-specific peer validation", + "fix": "Trust actual immediate proxies, not client X-Forwarded-* as authentication; do not change organizer networking.", + "check": "Spoofed direct headers grant no trusted identity/IP/scheme; proxy works.", + "doc": "docs/vulnerabilities/javascript.md#js-trust-proxy", + "engine": "regex", + "reason": "Review signal: Unrestricted trust in proxy headers. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "pattern": "\\.set\\s*\\(\\s*[\\\"']trust proxy[\\\"']\\s*,\\s*true\\s*\\)", + "limitations": "Regex with comment/string exclusions: .set('trust proxy', true). Receiver untyped; true may be valid behind proxies that overwrite forwarded headers. No effective topology or proxy-hop verification; inspect all direct entrypoints and the immediate peer.", + "family": "network-exposure", + "cwe": [], + "review_priority": "normal", + "signal_kind": "syntactic-review", + "detection": "Regex with comment/string exclusions: .set('trust proxy', true). Receiver untyped; true may be valid behind proxies that overwrite forwarded headers. No effective topology or proxy-hop verification; inspect all direct entrypoints and the immediate peer.", + "coverage_required": [ + "javascript" + ], + "code_only": true + }, + { + "id": "PY-ASSERT-AUTH", + "languages": [ + "python" + ], + "title": "Access control using assert", + "before": "assert note.owner_id == current_user.id", + "after": "if note.owner_id != current_user.id:\n raise PermissionError('access denied')", + "fix": "Use explicit denial active under -O; do not blanket-replace ordinary test assertions.", + "check": "Unauthorized objects fail in normal/optimized mode; authorized actions work.", + "doc": "docs/vulnerabilities/python.md#py-assert-auth", + "engine": "python-ast", + "reason": "Review signal: Access control using assert. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "limitations": "Bounded syntactic AST analysis, not type resolution or interprocedural taint analysis. Review actual API, inputs and authorization.", + "family": "authentication", + "cwe": [], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "RUBY-OBJECT", + "languages": [ + "ruby" + ], + "title": "Ruby Marshal or unsafe YAML", + "before": "record = Marshal.load(payload)", + "after": "record = JSON.parse(payload) # validate DTO schema and size", + "fix": "Use JSON or bounded YAML.safe_load with class/alias policy and schema; migrate trusted legacy data separately.", + "check": "Arbitrary objects are not built; old valid data works.", + "doc": "docs/vulnerabilities/ruby.md#ruby-object", + "engine": "regex", + "reason": "Review signal: Ruby Marshal or unsafe YAML. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "pattern": "\\bMarshal\\.(?:load|restore)\\s*(?:\\(|\\s)|\\b(?:YAML|Psych)\\.unsafe_load\\s*(?:\\(|\\s)", + "limitations": "Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.", + "family": "injection", + "cwe": [ + "CWE-502" + ], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "RUBY-SHELL", + "languages": [ + "ruby" + ], + "title": "Ruby shell string", + "before": "system(command)", + "after": "system(\"/usr/bin/file\", \"--\", filename)", + "fix": "Use fixed executable plus separate validated argv; backticks and %x also invoke shell.", + "check": "Metacharacters cannot become commands; normal files work.", + "doc": "docs/vulnerabilities/ruby.md#ruby-shell", + "engine": "regex", + "reason": "Review signal: Ruby shell string. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "pattern": "\\b(?:system|exec)\\s*\\(\\s*[A-Za-z_]\\w*\\s*\\)|\\b(?:system|exec)\\s*\\(\\s*\\\"[^\\\"\\n]{0,500}#\\{|%x[\\[({]|\\x60[^\\x60\\n]{1,500}\\x60", + "limitations": "Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.", + "family": "injection", + "cwe": [ + "CWE-78" + ], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "RUBY-EVAL", + "languages": [ + "ruby" + ], + "title": "Ruby eval/ERB from data", + "before": "result = eval(input)", + "after": "result = JSON.parse(input) # validate expected schema", + "fix": "Use trusted templates plus values or a restricted parser instead of executing data.", + "check": "Ruby syntax stays data; normal input parses.", + "doc": "docs/vulnerabilities/ruby.md#ruby-eval", + "engine": "regex", + "reason": "Review signal: Ruby eval/ERB from data. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "pattern": "\\b(?:eval|instance_eval|class_eval|module_eval)\\s*\\(|\\bERB\\.new\\s*\\(", + "limitations": "Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.", + "family": "injection", + "cwe": [ + "CWE-94" + ], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "RUST-UNSAFE-CONVERSION", + "languages": [ + "rust" + ], + "title": "Rust unchecked/raw conversion", + "before": "let text = unsafe { std::str::from_utf8_unchecked(data) };", + "after": "let text = std::str::from_utf8(data)?;", + "fix": "Prefer checked APIs; necessary unsafe needs length, alignment, lifetime, initialization and aliasing proofs. Do not remove it blindly.", + "check": "Test invalid UTF-8/length/index and EOF; use Miri/sanitizers where prepared.", + "doc": "docs/vulnerabilities/rust.md#rust-unsafe-conversion", + "engine": "regex", + "reason": "Review signal: Rust unchecked/raw conversion. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "pattern": "\\b(?:from_utf8_unchecked|from_raw_parts(?:_mut)?|get_unchecked(?:_mut)?|transmute|set_len)\\s*(?:::\\s*<[^>]{1,150}>)?\\s*\\(", + "limitations": "Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.", + "family": "memory-safety", + "cwe": [], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "RUST-SQL-FORMAT", + "languages": [ + "rust" + ], + "title": "Rust SQL using format!", + "before": "sqlx::query(&format!(\"SELECT * FROM notes WHERE name={}\", name));", + "after": "sqlx::query(\"SELECT * FROM notes WHERE name=$1\").bind(name);", + "fix": "Use driver binding and allowlisted identifiers; placeholder syntax is database-specific.", + "check": "Quotes remain data and ownership predicates work.", + "doc": "docs/vulnerabilities/rust.md#rust-sql-format", + "engine": "regex", + "reason": "Review signal: Rust SQL using format!. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "pattern": "\\b(?:query|query_as|sql_query)\\s*\\(\\s*&?\\s*format!\\s*\\(", + "limitations": "Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.", + "family": "injection", + "cwe": [ + "CWE-89" + ], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "PHP-PREFIX-MAC", + "languages": [ + "php" + ], + "title": "Hash concatenation instead of MAC", + "before": "$tag = sha1($key . $payload);", + "after": "$tag = hash_hmac('sha256', $payload, $key);", + "fix": "Use HMAC rather than a hash of secret concatenated with data, compare with hash_equals and migrate/version old formats.", + "check": "Changed/appended data fails; tags bind purpose and all authentication fields.", + "doc": "docs/vulnerabilities/php.md#php-prefix-mac", + "engine": "regex", + "reason": "Review signal: Hash concatenation instead of MAC. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "pattern": "\\b(?:sha1|md5)\\s*\\(\\s*\\$[A-Za-z_]\\w*\\s*\\.", + "limitations": "Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.", + "family": "secret-handling", + "cwe": [], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "PHP-PARSE-STR", + "languages": [ + "php" + ], + "title": "parse_str key normalization", + "before": "parse_str($token_data, $params);", + "after": "$params = parse_and_validate_canonical_share_dto($token_data); // one schema, duplicate policy, server-owned fields", + "fix": "Use identical schemas before signing/after parsing; account for dots/spaces becoming underscores, arrays and duplicate keys.", + "check": "Alternate spellings cannot change owner/document; signer and verifier agree.", + "doc": "docs/vulnerabilities/php.md#php-parse-str", + "engine": "regex", + "reason": "Review signal: parse_str key normalization. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "pattern": "\\bparse_str\\s*\\(", + "limitations": "Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.", + "family": "manual-review", + "cwe": [], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "JS-CURL-ARGV", + "languages": [ + "javascript" + ], + "title": "Node.js curl: review URL and options", + "before": "spawn('/usr/bin/curl', [url, '-o', filename]);", + "after": "downloadValidatedHttpResource(url, destination); // bounded HTTP client, checked redirects/DNS and server-chosen output", + "fix": "Separate argv does not prevent option injection. Prefer bounded HTTP APIs; otherwise fix curl options/protocols, use -- before validated URL and choose server-side output.", + "check": "Leading-dash URLs, forbidden schemes/redirects and output paths fail; normal downloads work.", + "doc": "docs/vulnerabilities/javascript.md#js-curl-argv", + "engine": "regex", + "reason": "Review signal: Node.js curl: review URL and options. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "pattern": "\\b(?:spawn|execFile|execFileSync)\\s*\\(\\s*[\\\"'](?:/(?:usr/)?bin/)?curl[\\\"']", + "limitations": "Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.", + "family": "injection", + "cwe": [ + "CWE-78" + ], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "JS-SESSION-STATE", + "languages": [ + "javascript" + ], + "title": "Sensitive session state assignment", + "before": "const user = req.body;\nreq.session.user = user;", + "after": "req.session.user = {id: savedUser.id, friends: savedUser.friends}; // server-validated fields only", + "fix": "Build session DTOs from persisted validated records; bind related state server-side and reject client privilege fields.", + "check": "Extra role/friends fields or endpoint reordering cannot change access; correct assignments may still match.", + "doc": "docs/vulnerabilities/javascript.md#js-session-state", + "engine": "regex", + "reason": "Review signal: Sensitive session state assignment. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "pattern": "\\b(?:req|request)\\.session\\.(?:user|author|owner|role|friends)\\s*=", + "review_after": true, + "limitations": "Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.", + "family": "authentication", + "cwe": [], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "CFG-REDIS-ACL", + "languages": [ + "config" + ], + "title": "Redis ACL user without a password", + "engine": "regex", + "pattern": "^[ \\t]*(?-i:user) [^ \\t\\r\\n]+(?: |$)", + "reason": "Review signal: Redis ACL user without a password. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "before": "user default on nopass ~* &* +@all", + "after": "user default off", + "fix": "First provision credentials and minimum commands/keys/channels for an app user; migrate clients and test AUTH/reconnect. Only then remove nopass or disable default. An empty > value is not a secure password.", + "check": "New app-user connections work before disabling default; new anonymous connections then fail. Check existing connections, namespaces, Pub/Sub and transactions.", + "doc": "docs/vulnerabilities/configuration.md#cfg-redis-acl", + "detection": "Regex selects user lines, then a bounded parser reads the physical line up to 8192 characters: lowercase user, one ASCII space before a nonempty username and ordinary modifier spaces. on/off/reset and nopass/resetpass/>password/#64lowerhex are processed in order; both final flags must be explicitly true. Names, passwords and key/channel patterns are not flags. Quotes, escapes, internal tabs, selectors and unknown operations need review; long lines are partial. This is not effective ACL analysis: inspect includes/runtime, grant validity, password strength and existing connections.", + "references": [ + "https://redis.io/docs/latest/operate/oss_and_stack/management/security/acl/", + "https://github.com/redis/redis/blob/7.2.7/src/acl.c", + "https://github.com/redis/redis/blob/7.2.7/src/config.c", + "https://github.com/redis/redis/blob/7.2.7/tests/unit/acl.tcl" + ], + "limitations": "Regex selects user lines, then a bounded parser reads the physical line up to 8192 characters: lowercase user, one ASCII space before a nonempty username and ordinary modifier spaces. on/off/reset and nopass/resetpass/>password/#64lowerhex are processed in order; both final flags must be explicitly true. Names, passwords and key/channel patterns are not flags. Quotes, escapes, internal tabs, selectors and unknown operations need review; long lines are partial. This is not effective ACL analysis: inspect includes/runtime, grant validity, password strength and existing connections.", + "family": "authentication", + "cwe": [], + "review_priority": "normal", + "signal_kind": "configuration-review" + }, + { + "id": "CFG-MONGO-NOAUTH", + "languages": [ + "config" + ], + "title": "MongoDB authorization disabled", + "engine": "regex", + "pattern": "\\bauthorization\\s*:\\s*disabled\\b", + "reason": "Review signal: MongoDB authorization disabled. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "before": "security:\n authorization: disabled", + "after": "security:\n authorization: enabled", + "fix": "Prepare application credentials and least-privilege roles before enabling auth on an owned service.", + "check": "Restart/reconnect and CRUD work; anonymous access fails. Do not alter organizer accounts.", + "doc": "docs/vulnerabilities/configuration.md#cfg-mongo-noauth", + "limitations": "Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.", + "family": "authentication", + "cwe": [], + "review_priority": "normal", + "signal_kind": "configuration-review" + }, + { + "id": "CFG-CAPABILITIES", + "languages": [ + "config" + ], + "title": "Broad container capabilities", + "engine": "regex", + "pattern": "\\b(?:cap_add[\"\\']?\\s*:\\s*|capabilities[\"\\']?\\s*:[\\s\\S]{0,160}?\\badd[\"\\']?\\s*:\\s*)(?:\\[[^\\]]{0,300}\\b(?:SYS_ADMIN|ALL)\\b|(?:[ \\t]*\\n[ \\t]*-[^\\n]{0,100}){0,6}[ \\t]*\\n[ \\t]*-[ \\t]*[\"\\']?(?:SYS_ADMIN|ALL)\\b)", + "reason": "Review signal: Broad container capabilities. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "before": "cap_add: [SYS_ADMIN]", + "after": "cap_drop: [ALL]", + "fix": "Remove unnecessary capabilities only on owned services; retain proven requirements and verify user/port/volume permissions.", + "check": "Startup/checker and required syscalls work; do not apply this to organizer launchers.", + "doc": "docs/vulnerabilities/configuration.md#cfg-capabilities", + "detection": "Regex: cap_add or capabilities.add with SYS_ADMIN/ALL in flow/block lists. capabilities.drop:[ALL] alone is not a grant. Bounded text windows are not YAML parsing; review nesting, merges/anchors and actual securityContext.", + "limitations": "Regex: cap_add or capabilities.add with SYS_ADMIN/ALL in flow/block lists. capabilities.drop:[ALL] alone is not a grant. Bounded text windows are not YAML parsing; review nesting, merges/anchors and actual securityContext.", + "family": "container-isolation", + "cwe": [], + "review_priority": "normal", + "signal_kind": "configuration-review" + }, + { + "id": "CFG-BUILD-SECRET", + "languages": [ + "docker" + ], + "title": "Secret in Dockerfile ARG/ENV", + "engine": "regex", + "pattern": "^\\s*(?:ARG|ENV)\\s+\\w*(?:TOKEN|PASSWORD|SECRET|PRIVATE_KEY)\\w*(?:\\s|=)", + "reason": "Review signal: Secret in Dockerfile ARG/ENV. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "before": "ARG API_TOKEN=example", + "after": "RUN --mount=type=secret,id=api_token build-with-secret", + "fix": "Use build secret mounts instead of ARG/ENV/layers. Rotate published secrets deliberately; later deletion does not erase an earlier layer.", + "check": "Build history/logs disclose no secret; runtime secrets are separate. The sample build command is a placeholder.", + "doc": "docs/vulnerabilities/configuration.md#cfg-build-secret", + "limitations": "Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.", + "family": "secret-handling", + "cwe": [], + "review_priority": "normal", + "signal_kind": "configuration-review" + }, + { + "id": "SQL-DEFINER", + "languages": [ + "sql" + ], + "title": "SECURITY DEFINER and search_path trust", + "engine": "regex", + "pattern": "\\bSECURITY\\s+DEFINER\\b", + "reason": "Review signal: SECURITY DEFINER and search_path trust. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "before": "CREATE FUNCTION f() RETURNS int LANGUAGE sql SECURITY DEFINER AS $$ SELECT value FROM settings $$;", + "after": "CREATE FUNCTION f() RETURNS int LANGUAGE sql SECURITY INVOKER AS $$ SELECT value FROM app.settings $$;", + "fix": "Prefer INVOKER unless elevated rights are needed; otherwise use a minimal owner, fixed safe search_path with pg_temp last, qualified names and restricted EXECUTE.", + "check": "Callers cannot replace objects using temporary/writable schemas; valid calls work.", + "doc": "docs/vulnerabilities/sql.md#sql-definer", + "limitations": "Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.", + "family": "manual-review", + "cwe": [], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "SQL-BYPASSRLS", + "languages": [ + "sql" + ], + "title": "Application role bypasses RLS", + "engine": "regex", + "pattern": "\\b(?:CREATE|ALTER)\\s+(?:ROLE|USER)\\b[^;]{0,300}\\b(?:BYPASSRLS|SUPERUSER)\\b", + "reason": "Review signal: Application role bypasses RLS. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "before": "ALTER ROLE app BYPASSRLS;", + "after": "ALTER ROLE app NOBYPASSRLS NOSUPERUSER;", + "fix": "Use a runtime role without elevated attributes and review table ownership separately; FORCE RLS does not constrain superuser/BYPASSRLS.", + "check": "Actual runtime roles for two tenants cannot cross boundaries; migration role is separate.", + "doc": "docs/vulnerabilities/sql.md#sql-bypassrls", + "limitations": "Bounded SQL: CREATE/ALTER ROLE or USER with explicit SUPERUSER/BYPASSRLS, comments and quoted strings excluded, unquoted keywords and statements up to 300 characters. Later overrides, ownership, inherited roles and effective runtime policy remain manual.", + "family": "authentication", + "cwe": [], + "review_priority": "normal", + "signal_kind": "syntactic-review", + "detection": "Bounded SQL: CREATE/ALTER ROLE or USER with explicit SUPERUSER/BYPASSRLS, comments and quoted strings excluded, unquoted keywords and statements up to 300 characters. Later overrides, ownership, inherited roles and effective runtime policy remain manual.", + "coverage_required": [ + "sql" + ], + "code_only": true + }, + { + "id": "SQL-PUBLIC-GRANT", + "languages": [ + "sql" + ], + "title": "Broad privileges granted to PUBLIC", + "engine": "regex", + "pattern": "\\bGRANT\\s+(?:ALL(?:\\s+PRIVILEGES)?|(?:SELECT|INSERT|UPDATE|DELETE|TRUNCATE|REFERENCES|TRIGGER|CREATE|USAGE|EXECUTE|CONNECT|TEMPORARY|TEMP)(?:\\s*,\\s*(?:SELECT|INSERT|UPDATE|DELETE|TRUNCATE|REFERENCES|TRIGGER|CREATE|USAGE|EXECUTE|CONNECT|TEMPORARY|TEMP)){0,20})\\s+ON\\b[^;]{0,250}?\\bTO\\s+PUBLIC\\b", + "reason": "Review signal: Broad privileges granted to PUBLIC. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "before": "GRANT ALL ON notes TO PUBLIC;", + "after": "GRANT SELECT, INSERT, UPDATE ON notes TO app;", + "fix": "Grant only required actions to specific roles; review existing/default privileges, sequences and functions. Never revoke unrelated infrastructure rights.", + "check": "Neighbor roles cannot read data; app ID generation and old records work.", + "doc": "docs/vulnerabilities/sql.md#sql-public-grant", + "limitations": "Bounded SQL: GRANT ALL or SELECT/INSERT/UPDATE/DELETE/TRUNCATE/REFERENCES/TRIGGER/CREATE/USAGE/EXECUTE/CONNECT/TEMPORARY/TEMP privilege lists ON an object TO PUBLIC. Comments/strings excluded; no cross-statement matching. Quoted identifiers, defaults, complex grants, effective rights and intentional public objects remain manual.", + "family": "authentication", + "cwe": [], + "review_priority": "normal", + "signal_kind": "syntactic-review", + "detection": "Bounded SQL: GRANT ALL or SELECT/INSERT/UPDATE/DELETE/TRUNCATE/REFERENCES/TRIGGER/CREATE/USAGE/EXECUTE/CONNECT/TEMPORARY/TEMP privilege lists ON an object TO PUBLIC. Comments/strings excluded; no cross-statement matching. Quoted identifiers, defaults, complex grants, effective rights and intentional public objects remain manual.", + "coverage_required": [ + "sql" + ], + "code_only": true + }, + { + "id": "PY-DJANGO-HOSTS", + "languages": [ + "python" + ], + "title": "Django wildcard ALLOWED_HOSTS", + "engine": "regex", + "pattern": "\\bALLOWED_HOSTS\\s*=\\s*\\[\\s*[\"']\\*[\"']", + "reason": "Review signal: Django wildcard ALLOWED_HOSTS. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "before": "ALLOWED_HOSTS = [\"*\"]", + "after": "ALLOWED_HOSTS = [\"service.internal\"]", + "fix": "Allowlist actual hostnames/IPs including the checker; use get_host instead of raw Host and review trusted proxy headers separately.", + "check": "Unknown Host fails; normal host/checker works.", + "doc": "docs/vulnerabilities/python.md#py-django-hosts", + "limitations": "Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.", + "family": "network-exposure", + "cwe": [], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "PY-HTML-SAFE", + "languages": [ + "python" + ], + "title": "HTML escaping explicitly bypassed", + "engine": "regex", + "pattern": "\\b(?:mark_safe|Markup)\\s*\\(", + "reason": "Review signal: HTML escaping explicitly bypassed. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "before": "html = mark_safe(message)", + "after": "html = message", + "fix": "Use autoescaped templates; sanitize permitted rich HTML. HTML escaping does not secure JS or URL contexts.", + "check": "Tags/quotes stay data without breaking supported formatting.", + "doc": "docs/vulnerabilities/python.md#py-html-safe", + "limitations": "Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.", + "family": "injection", + "cwe": [ + "CWE-79" + ], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "JS-VM", + "languages": [ + "javascript" + ], + "title": "node:vm used as a security sandbox", + "engine": "regex", + "pattern": "\\b(?:runInNewContext|runInContext|runInThisContext)\\s*\\(", + "reason": "Review signal: node:vm used as a security sandbox. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "before": "vm.runInNewContext(userCode, context);", + "after": "evaluateAllowedExpression(parsedInput); // implement a restricted grammar", + "fix": "node:vm is not a security boundary for untrusted code. Use a restricted grammar or a separately designed execution isolation system.", + "check": "Disallowed syntax fails; supported expressions work under time/memory limits.", + "doc": "docs/vulnerabilities/javascript.md#js-vm", + "limitations": "Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.", + "family": "injection", + "cwe": [ + "CWE-94" + ], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "JS-REGEX-DYNAMIC", + "languages": [ + "javascript" + ], + "title": "Regex built from client text", + "engine": "regex", + "pattern": "\\bnew\\s+RegExp\\s*\\(\\s*[A-Za-z_]\\w*(?:\\.\\w+)*\\s*[,)]", + "reason": "Review signal: Regex built from client text. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "before": "const re = new RegExp(input);", + "after": "const found = text.includes(input);", + "fix": "Use includes for literal search; bound regex grammar/complexity and input when regex is a feature. A Promise timeout cannot interrupt synchronous regex execution.", + "check": "Long near-matches cannot block the event loop; Unicode/case semantics remain compatible.", + "doc": "docs/vulnerabilities/javascript.md#js-regex-dynamic", + "limitations": "Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.", + "family": "resource-limits", + "cwe": [], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "PHP-LOOSE-COMPARE", + "languages": [ + "php" + ], + "title": "Loose comparison of token or signature", + "engine": "regex", + "pattern": "\\$(?:token|signature|hash|password|digest)\\b\\s*(?:==|!=)(?!=)", + "reason": "Review signal: Loose comparison of token or signature. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "before": "$ok = $token == $provided;", + "after": "$ok = is_string($provided) && hash_equals($token, $provided);", + "fix": "Validate types; use hash_equals for tags, === for ordinary values and password_verify for passwords. Numeric-string semantics depend on version/operands.", + "check": "Numbers, arrays and numeric strings cannot grant access; valid values work.", + "doc": "docs/vulnerabilities/php.md#php-loose-compare", + "limitations": "Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.", + "family": "authentication", + "cwe": [], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "PHP-UPLOAD", + "languages": [ + "php" + ], + "title": "Moving an uploaded file", + "engine": "regex", + "pattern": "\\bmove_uploaded_file\\s*\\(", + "reason": "Review signal: Moving an uploaded file. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "before": "move_uploaded_file($tmp, $webroot . $name);", + "after": "move_uploaded_file($validatedTmp, $serverChosenPrivatePath);", + "fix": "Check upload error/size/type; use non-overwriting server-generated names outside executable web roots and authorize downloads.", + "check": "Test upload/download, collisions, wrong owner/type and full disk. The call remains a review signal.", + "doc": "docs/vulnerabilities/php.md#php-upload", + "review_after": true, + "limitations": "Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.", + "family": "file-access", + "cwe": [ + "CWE-434" + ], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "PHP-DISPLAY-ERRORS", + "languages": [ + "php", + "config" + ], + "title": "PHP displays errors to clients", + "engine": "regex", + "pattern": "\\bdisplay_errors\\s*(?:=|,)\\s*[\"']?(?:On|1|true)\\b", + "reason": "Review signal: PHP displays errors to clients. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "before": "display_errors = On", + "after": "display_errors = Off", + "fix": "Disable client error output and retain redacted local logs; check effective php.ini/FPM and runtime ini_set.", + "check": "Parse/database/type errors yield expected public responses while private diagnostics remain.", + "doc": "docs/vulnerabilities/php.md#php-display-errors", + "limitations": "Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.", + "family": "information-disclosure", + "cwe": [], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "GO-PPROF", + "languages": [ + "go" + ], + "title": "pprof registered on an HTTP mux", + "engine": "regex", + "pattern": "[\"]net/http/pprof[\"]", + "reason": "Review signal: pprof registered on an HTTP mux. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "before": "import _ \"net/http/pprof\"", + "after": "// use a separate authenticated diagnostics mux when diagnostics is required", + "fix": "Do not expose DefaultServeMux debug handlers as the business API; separate muxes and authorize diagnostic endpoints.", + "check": "Normal API works; anonymous clients cannot obtain profiles/heap. Import alone does not prove exposure.", + "doc": "docs/vulnerabilities/go.md#go-pprof", + "limitations": "Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.", + "family": "network-exposure", + "cwe": [], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "GO-FILESERVER", + "languages": [ + "go" + ], + "title": "FileServer publishes a file tree", + "engine": "regex", + "pattern": "\\bhttp\\.(?:FileServer|FileServerFS)\\s*\\(", + "reason": "Review signal: FileServer publishes a file tree. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "before": "http.Handle(\"/\", http.FileServer(http.Dir(\".\")))", + "after": "http.Handle(\"/assets/\", http.StripPrefix(\"/assets/\", http.FileServer(http.Dir(\"./public\"))))", + "fix": "Use a dedicated public root without secrets/databases; authorize private files separately and review symlinks/listing.", + "check": "Assets work; .env, source, foreign files and outward symlinks are unavailable.", + "doc": "docs/vulnerabilities/go.md#go-fileserver", + "review_after": true, + "limitations": "Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.", + "family": "file-access", + "cwe": [ + "CWE-22" + ], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "JAVA-JACKSON-TYPES", + "languages": [ + "java" + ], + "title": "Jackson default typing", + "engine": "regex", + "pattern": "\\.(?:enableDefaultTyping|activateDefaultTyping)\\s*\\(", + "reason": "Review signal: Jackson default typing. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "before": "mapper.enableDefaultTyping();", + "after": "// deserialize into a fixed DTO without client-selected implementation types", + "fix": "Prefer explicit DTOs; required polymorphism needs a narrow type set/validator for the installed version, not a package-wide allowlist.", + "check": "Unknown types fail before side effects; valid documents remain readable.", + "doc": "docs/vulnerabilities/java.md#java-jackson-types", + "limitations": "Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.", + "family": "injection", + "cwe": [ + "CWE-502" + ], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "JAVA-XML", + "languages": [ + "java" + ], + "title": "XML parser needs an external-resource policy", + "engine": "regex", + "pattern": "\\b(?:DocumentBuilderFactory|SAXParserFactory|XMLInputFactory|TransformerFactory)\\.newInstance\\s*\\(", + "reason": "Review signal: XML parser needs an external-resource policy. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "before": "var f = DocumentBuilderFactory.newInstance();", + "after": "var f = DocumentBuilderFactory.newInstance();\nf.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, \"\");\nf.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, \"\");\n// also configure DTD/entity policy and parser-specific limits", + "fix": "Restrict DTD/entities/schema/XSLT on the actual factory and set limits; never silently ignore unsupported security options.", + "check": "Parser reads no external files/URLs; ordinary XML and size limits work.", + "doc": "docs/vulnerabilities/java.md#java-xml", + "review_after": true, + "limitations": "Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.", + "family": "injection", + "cwe": [ + "CWE-611" + ], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "JAVA-EXPRESSION", + "languages": [ + "java" + ], + "title": "Client text parsed as SpEL", + "engine": "regex", + "pattern": "\\.parseExpression\\s*\\(", + "reason": "Review signal: Client text parsed as SpEL. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "before": "parser.parseExpression(input).getValue(context);", + "after": "lookupAllowedOperation(operationId, validatedArguments);", + "fix": "Use fixed operations/arguments or a restricted DSL and evaluation context; never expose arbitrary reflection.", + "check": "Disallowed operations cannot reach runtime; approved calculations work.", + "doc": "docs/vulnerabilities/java.md#java-expression", + "limitations": "Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.", + "family": "injection", + "cwe": [ + "CWE-94" + ], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "CS-PROCESS", + "languages": [ + "csharp" + ], + "title": ".NET process creation", + "engine": "regex", + "pattern": "\\b(?:new\\s+ProcessStartInfo|Process\\.Start)\\s*\\(", + "reason": "Review signal: .NET process creation. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "before": "Process.Start(\"sh\", \"-c \" + command);", + "after": "var digest = SHA256.HashData(Encoding.UTF8.GetBytes(text));", + "fix": "Prefer a library operation or fixed executable plus ArgumentList. UseShellExecute=false does not neutralize explicit sh/cmd or option injection.", + "check": "Quotes stay data and expected output format is preserved.", + "doc": "docs/vulnerabilities/csharp.md#cs-process", + "limitations": "Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.", + "family": "injection", + "cwe": [ + "CWE-78" + ], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "CS-IGNORE-FILTERS", + "languages": [ + "csharp" + ], + "title": "Global query filters disabled", + "engine": "regex", + "pattern": "\\.IgnoreQueryFilters\\s*\\(", + "reason": "Review signal: Global query filters disabled. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "before": "var rows = db.Notes.IgnoreQueryFilters().ToList();", + "after": "var rows = db.Notes.Where(n => n.OwnerId == userId).ToList();", + "fix": "Do not disable tenant/auth filters merely for soft-delete; admin bypass requires explicit authorization and query restrictions.", + "check": "Test two tenants, deleted records and exports against the actual provider SQL.", + "doc": "docs/vulnerabilities/csharp.md#cs-ignore-filters", + "limitations": "Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.", + "family": "authentication", + "cwe": [], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "CS-ALLOWANON", + "languages": [ + "csharp" + ], + "title": "AllowAnonymous route", + "engine": "regex", + "pattern": "\\[\\s*AllowAnonymous(?:Attribute)?\\s*\\]", + "reason": "Review signal: AllowAnonymous route. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "before": "[AllowAnonymous]\npublic IActionResult PrivateNote() => View();", + "after": "[Authorize]\npublic IActionResult PrivateNote() => View();", + "fix": "Review effective endpoint metadata/ownership; AllowAnonymous may override Authorize. Login/health may be intentionally public.", + "check": "Public login works; private endpoints and nested operations require authorization.", + "doc": "docs/vulnerabilities/csharp.md#cs-allowanon", + "limitations": "Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.", + "family": "authentication", + "cwe": [], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "RUBY-PERMIT-ALL", + "languages": [ + "ruby" + ], + "title": "Rails permits all parameters", + "engine": "regex", + "pattern": "\\.permit!|\\bpermit_all_parameters\\s*=\\s*true\\b", + "reason": "Review signal: Rails permits all parameters. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "before": "attrs = params.permit!", + "after": "attrs = params.require(:note).permit(:title, :body)", + "fix": "Allowlist editable fields; choose owner/role server-side and constrain nested params separately.", + "check": "Owner/role/unknown nested fields do not apply; valid partial edits work.", + "doc": "docs/vulnerabilities/ruby.md#ruby-permit-all", + "limitations": "Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.", + "family": "authentication", + "cwe": [], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "RUBY-CONSTANTIZE", + "languages": [ + "ruby" + ], + "title": "String selects a Ruby class", + "engine": "regex", + "pattern": "\\.(?:safe_constantize|constantize)\\b", + "reason": "Review signal: String selects a Ruby class. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "before": "klass = params[:type].constantize", + "after": "klass = {\"text\" => TextNote}.fetch(validated_type)", + "fix": "Use a fixed map of allowed DTO types; safe_constantize only changes lookup errors, not the allowed classes.", + "check": "Unknown types cannot create objects; valid types remain compatible.", + "doc": "docs/vulnerabilities/ruby.md#ruby-constantize", + "limitations": "Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.", + "family": "manual-review", + "cwe": [], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "RUBY-HTML-SAFE", + "languages": [ + "ruby" + ], + "title": "Ruby html_safe/raw", + "engine": "regex", + "pattern": "\\.html_safe\\b|\\braw\\s*\\(", + "reason": "Review signal: Ruby html_safe/raw. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "before": "value = params[:text].html_safe", + "after": "value = params[:text] # render with automatic escaping", + "fix": "Use context-appropriate autoescape or a sanitizer for permitted HTML; HTML data is not ERB source.", + "check": "Tags/quotes remain text and approved formatting works.", + "doc": "docs/vulnerabilities/ruby.md#ruby-html-safe", + "limitations": "Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.", + "family": "injection", + "cwe": [ + "CWE-79" + ], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "RUBY-SQL", + "languages": [ + "ruby" + ], + "title": "Ruby SQL interpolation", + "engine": "regex", + "pattern": "\\.(?:where|find_by_sql|order)\\s*\\(\\s*\"[^\"\\n]{0,400}#\\{", + "reason": "Review signal: Ruby SQL interpolation. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "before": "Note.where(\"title = '#{title}'\")", + "after": "Note.where(title: title, owner_id: current_user.id)", + "fix": "Bind values with the ORM/driver API; select identifiers from a server allowlist.", + "check": "Quotes remain values and tenant/owner conditions hold.", + "doc": "docs/vulnerabilities/ruby.md#ruby-sql", + "limitations": "Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.", + "family": "injection", + "cwe": [ + "CWE-89" + ], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "RUST-STATIC-MUT", + "languages": [ + "rust" + ], + "title": "Shared mutable Rust state", + "engine": "regex", + "pattern": "\\bstatic\\s+mut\\b", + "reason": "Review signal: Shared mutable Rust state. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "before": "static mut CURRENT_USER: u64 = 0;", + "after": "static CURRENT_USER: std::sync::Mutex = std::sync::Mutex::new(0);", + "fix": "Use ownership or synchronized primitives with clear invariants; review all unsafe accesses and cross-request state.", + "check": "Concurrent requests do not race or leak another user's data; ordinary operations work.", + "doc": "docs/vulnerabilities/rust.md#rust-static-mut", + "limitations": "Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.", + "family": "memory-safety", + "cwe": [], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "C-ATOI", + "languages": [ + "native" + ], + "title": "atoi without checked conversion", + "engine": "regex", + "pattern": "\\b(?:atoi|atol|atoll)\\s*\\(", + "reason": "Review signal: atoi without checked conversion. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "before": "int size = atoi(input);", + "after": "// use strtol/strtoull with errno, end pointer, sign and application bounds checks", + "fix": "Use checked conversion with end-pointer, range and errno validation; define the accepted numeric grammar.", + "check": "Empty, trailing junk, signs and overflow fail; permitted boundary values work.", + "doc": "docs/vulnerabilities/c-cpp.md#c-atoi", + "limitations": "Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.", + "family": "memory-safety", + "cwe": [], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "C-REALLOC", + "languages": [ + "native" + ], + "title": "Overwriting the only pointer with realloc", + "engine": "regex", + "pattern": "\\b([A-Za-z_]\\w*)\\s*=\\s*realloc\\s*\\(\\s*\\1\\s*,", + "reason": "Review signal: Overwriting the only pointer with realloc. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "before": "buffer = realloc(buffer, size);", + "after": "void *next = realloc(buffer, size);\nif (next == NULL) { /* preserve buffer; handle error */ }\nelse { buffer = next; }", + "fix": "Keep the original pointer until allocation succeeds; handle zero size and overflow according to the intended contract.", + "check": "Allocation failure leaks no original allocation and does not cause invalid access.", + "doc": "docs/vulnerabilities/c-cpp.md#c-realloc", + "limitations": "Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.", + "family": "memory-safety", + "cwe": [], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "CFG-NGINX-AUTH-OFF", + "languages": [ + "config" + ], + "title": "Nested nginx location disables auth_request", + "engine": "regex", + "pattern": "\\bauth_request\\s+off\\s*;", + "reason": "Review signal: Nested nginx location disables auth_request. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "before": "location /export/ { auth_request off; }", + "after": "location /export/ { auth_request /verify; }", + "fix": "Review location selection/inheritance and remove unintended auth bypass while preserving intended public endpoints.", + "check": "Protected resources require authentication through every matching location; health/login works.", + "doc": "docs/vulnerabilities/configuration.md#cfg-nginx-auth-off", + "limitations": "Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.", + "family": "authentication", + "cwe": [], + "review_priority": "normal", + "signal_kind": "configuration-review" + }, + { + "id": "PY-SSL-CONTEXT", + "title": "TLS context verification disabled", + "languages": [ + "python" + ], + "engine": "python-ast", + "before": "import ssl\ncontext = ssl._create_unverified_context()", + "after": "import ssl\ncontext = ssl.create_default_context(cafile=trusted_ca_file)", + "reason": "Review signal: TLS context verification disabled. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "fix": "Enable certificate/hostname verification and configure the correct CA rather than an unverified context.", + "check": "Correct peers work; wrong CA/hostname and expiry fail.", + "doc": "docs/vulnerabilities/python.md#py-ssl-context", + "detection": "AST: ssl._create_unverified_context(), verify_mode=ssl.CERT_NONE and check_hostname=False assignments with import aliases. Assignment receiver type is not established.", + "references": [ + "https://docs.python.org/3/library/ssl.html#security-considerations" + ], + "limitations": "AST: ssl._create_unverified_context(), verify_mode=ssl.CERT_NONE and check_hostname=False assignments with import aliases. Assignment receiver type is not established.", + "family": "network-exposure", + "cwe": [], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "PY-CSRF-EXEMPT", + "title": "Django view excluded from CSRF", + "languages": [ + "python" + ], + "engine": "python-ast", + "before": "from django.views.decorators.csrf import csrf_exempt\n@csrf_exempt\ndef update(request):\n return change_profile(request)", + "after": "from django.views.decorators.csrf import csrf_protect\n@csrf_protect\ndef update(request):\n return change_profile(request)", + "reason": "Review signal: Django view excluded from CSRF. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "fix": "Retain CSRF on cookie-authenticated browser routes; narrow exemptions to independently authenticated stateless endpoints.", + "check": "Browser mutations need the correct token; authorized API/webhook requests still work.", + "doc": "docs/vulnerabilities/python.md#py-csrf-exempt", + "detection": "AST: django.views.decorators.csrf.csrf_exempt decorator/call with import alias. An exemption alone is not proof of a flaw on a bearer-only endpoint.", + "references": [ + "https://docs.djangoproject.com/en/5.2/ref/csrf/" + ], + "limitations": "AST: django.views.decorators.csrf.csrf_exempt decorator/call with import alias. An exemption alone is not proof of a flaw on a bearer-only endpoint.", + "family": "authentication", + "cwe": [], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "PY-MASS-ASSIGN", + "title": "Request fields become model attributes", + "languages": [ + "python" + ], + "engine": "python-ast", + "before": "for field, value in payload.items():\n setattr(account, field, value)", + "after": "account.display_name = validate_display_name(payload['display_name'])", + "reason": "Review signal: Request fields become model attributes. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "fix": "Explicitly allowlist editable attributes; derive owner/role and nested privileges server-side.", + "check": "Unknown/admin fields do not alter state; permitted edits remain functional.", + "doc": "docs/vulnerabilities/python.md#py-mass-assign", + "detection": "AST: setattr with nonliteral attribute name. **kwargs, wrappers, ORM update and constructors are not automatically covered.", + "limitations": "AST: setattr with nonliteral attribute name. **kwargs, wrappers, ORM update and constructors are not automatically covered.", + "family": "authentication", + "cwe": [], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "PY-REDIRECT", + "title": "Dynamic redirect destination", + "languages": [ + "python" + ], + "engine": "python-ast", + "before": "from flask import redirect\nreturn_url = request.args['next']\nresponse = redirect(return_url)", + "after": "from flask import redirect\nresponse = redirect('/profile')", + "reason": "Review signal: Dynamic redirect destination. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "fix": "Resolve destinations from an allowlist or verify approved scheme/host/path after normalization; do not trust user-controlled return URLs.", + "check": "External, scheme-relative and malformed destinations fail; supported navigation works.", + "doc": "docs/vulnerabilities/python.md#py-redirect", + "detection": "AST: flask.redirect/werkzeug.utils.redirect first argument or location=; django.shortcuts.redirect first argument or to=. Import aliases/inline **dict supported; literals or known simple scalar values do not signal. Review trust, wrappers, runtime kwargs, route resolution and reverse-proxy redirects.", + "references": [ + "https://flask.palletsprojects.com/en/stable/api/#flask.redirect", + "https://werkzeug.palletsprojects.com/en/stable/utils/#werkzeug.utils.redirect", + "https://docs.djangoproject.com/en/stable/topics/http/shortcuts/#redirect" + ], + "limitations": "AST: flask.redirect/werkzeug.utils.redirect first argument or location=; django.shortcuts.redirect first argument or to=. Import aliases/inline **dict supported; literals or known simple scalar values do not signal. Review trust, wrappers, runtime kwargs, route resolution and reverse-proxy redirects.", + "family": "network-exposure", + "cwe": [], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "PY-JWT-ALGORITHMS", + "title": "JWT algorithms taken from an expression", + "languages": [ + "python" + ], + "engine": "python-ast", + "before": "import jwt\nclaims = jwt.decode(token, key, algorithms=[header['alg']])", + "after": "import jwt\nclaims = jwt.decode(token, key, algorithms=['RS256'], audience='notes', issuer='auth')", + "reason": "Review signal: JWT algorithms taken from an expression. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "fix": "Bind allowed algorithms to trusted key configuration; never mix HMAC/RSA for the same key material.", + "check": "Wrong algorithm/key type/signature fails; issuer, audience and expiry are checked.", + "doc": "docs/vulnerabilities/python.md#py-jwt-algorithms", + "detection": "AST: algorithms outside an inline list/tuple of strings; exact jose.jwt.decode also permits known literal/scalar strings. Only jose.jwt.decode and jwt.decode_complete use third positional algorithms; generic jwt.decode uses keyword only. Explicit None signals; missing arguments, *args, mutable config, version and allowlist origin need review. Explicit duplicate algorithms/options arguments are not analyzed as executable calls.", + "references": [ + "https://github.com/mpdavis/python-jose/blob/3.5.0/jose/jwt.py", + "https://github.com/jpadilla/pyjwt/blob/2.10.1/jwt/api_jwt.py", + "https://github.com/jpadilla/pyjwt/blob/1.7.1/jwt/api_jwt.py" + ], + "limitations": "AST: algorithms outside an inline list/tuple of strings; exact jose.jwt.decode also permits known literal/scalar strings. Only jose.jwt.decode and jwt.decode_complete use third positional algorithms; generic jwt.decode uses keyword only. Explicit None signals; missing arguments, *args, mutable config, version and allowlist origin need review. Explicit duplicate algorithms/options arguments are not analyzed as executable calls.", + "family": "authentication", + "cwe": [], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "PY-JWT-CLAIMS", + "title": "JWT expiry or recipient checks disabled", + "languages": [ + "python" + ], + "engine": "python-ast", + "before": "import jwt\nclaims = jwt.decode(token, key, algorithms=['HS256'], options={'verify_exp': False})", + "after": "import jwt\nclaims = jwt.decode(token, key, algorithms=['HS256'], audience='notes', issuer='auth', options={'require': ['exp', 'sub', 'iss', 'aud']})", + "reason": "Review signal: JWT expiry or recipient checks disabled. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "fix": "Validate expiry, issuer, audience and required presence separately. The after example uses PyJWT 2.x options.require; python-jose uses require_*. Check decode_complete's result shape.", + "check": "Expired, premature, missing-claim and other-application tokens fail; sessions work with the selected library/result shape.", + "doc": "docs/vulnerabilities/python.md#py-jwt-claims", + "detection": "AST: inline options with verify_exp/verify_nbf/verify_aud/verify_iss=False, scalar booleans and inline spreads. Only jose.jwt.decode/jwt.decode_complete consider fourth positional options. Only jose.jwt.decode require_X=True suppresses corresponding verify_X=False, not other claims/signature. Review external dictionaries, *args, duplicates, instance config, versions and required presence.", + "references": [ + "https://github.com/mpdavis/python-jose/blob/3.5.0/jose/jwt.py", + "https://github.com/jpadilla/pyjwt/blob/2.10.1/jwt/api_jwt.py", + "https://github.com/jpadilla/pyjwt/blob/1.7.1/jwt/api_jwt.py" + ], + "limitations": "AST: inline options with verify_exp/verify_nbf/verify_aud/verify_iss=False, scalar booleans and inline spreads. Only jose.jwt.decode/jwt.decode_complete consider fourth positional options. Only jose.jwt.decode require_X=True suppresses corresponding verify_X=False, not other claims/signature. Review external dictionaries, *args, duplicates, instance config, versions and required presence.", + "family": "authentication", + "cwe": [], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "PY-REGEX-DYNAMIC", + "title": "Dynamic regular-expression pattern", + "languages": [ + "python" + ], + "engine": "python-ast", + "before": "import re\nfound = re.search(request_pattern, text)", + "after": "import re\nfound = re.search(re.escape(search_text), bounded_text)", + "reason": "Review signal: Dynamic regular-expression pattern. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "fix": "For literal search use escaping/string operations; a regex feature needs constrained grammar, lengths and execution budget.", + "check": "Metacharacters stay literal where intended; long near-matches cannot block the handler.", + "doc": "docs/vulnerabilities/python.md#py-regex-dynamic", + "detection": "AST: re.compile/match/search/fullmatch/findall/finditer/split/sub/subn with nonliteral first argument. Does not measure regex complexity; safe re.escape still signals.", + "review_after": true, + "references": [ + "https://docs.python.org/3/library/re.html#re.escape" + ], + "limitations": "AST: re.compile/match/search/fullmatch/findall/finditer/split/sub/subn with nonliteral first argument. Does not measure regex complexity; safe re.escape still signals.", + "family": "resource-limits", + "cwe": [], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "JS-BUFFER-EXPOSURE", + "title": "Uninitialized Buffer exposure", + "languages": [ + "javascript" + ], + "engine": "regex", + "before": "const out = Buffer.allocUnsafe(size);\nconst n = await readInto(out);\nres.end(out);", + "after": "const out = Buffer.alloc(size);\nconst n = await readInto(out);\nres.end(out.subarray(0, n));", + "reason": "Review signal: Uninitialized Buffer exposure. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "fix": "Initialize memory, emit only the written range and validate size/read results.", + "check": "Short read, EOF and errors disclose no tail bytes; valid binary responses work.", + "doc": "docs/vulnerabilities/javascript.md#js-buffer-exposure", + "detection": "Regex: Buffer.allocUnsafe/allocUnsafeSlow. Full initialization before disclosure may remove risk on review; inspect legacy new Buffer and incorrect lengths separately.", + "pattern": "\\bBuffer\\s*\\.\\s*allocUnsafe(?:Slow)?\\s*\\(", + "references": [ + "https://nodejs.org/api/buffer.html#what-makes-bufferallocunsafe-and-bufferallocunsafeslow-unsafe" + ], + "limitations": "Regex: Buffer.allocUnsafe/allocUnsafeSlow. Full initialization before disclosure may remove risk on review; inspect legacy new Buffer and incorrect lengths separately.", + "family": "information-disclosure", + "cwe": [], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "JS-JWT-DECODE", + "title": "JWT decoded without signature verification", + "languages": [ + "javascript" + ], + "engine": "regex", + "before": "const user = jwt.decode(token);\nloadNotes(user.sub);", + "after": "const claims = jwt.verify(token, key, { algorithms: ['RS256'], issuer: 'auth', audience: 'notes' });\nloadNotes(claims.sub);", + "reason": "Review signal: JWT decoded without signature verification. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "fix": "Verify signature and claims before access; await asynchronous verification and reject errors before proceeding.", + "check": "Modified payload, invalid signature and wrong issuer/audience grant no access.", + "doc": "docs/vulnerabilities/javascript.md#js-jwt-decode", + "detection": "Regex: common jwt.decode/decodeJwt/jwtDecode and static ESM/CommonJS aliases for jsonwebtoken.decode/jose.decodeJwt. No scope/reassignment, re-export, dynamic import or claims-use analysis. Diagnostic decoding may be legitimate.", + "pattern": "\\b(?:(?:jwt|jsonwebtoken)\\s*\\.\\s*decode|jwtDecode|decodeJwt)\\s*\\(", + "references": [ + "https://github.com/auth0/node-jsonwebtoken#jwtdecodetoken--options" + ], + "limitations": "Regex: common jwt.decode/decodeJwt/jwtDecode and static ESM/CommonJS aliases for jsonwebtoken.decode/jose.decodeJwt. No scope/reassignment, re-export, dynamic import or claims-use analysis. Diagnostic decoding may be legitimate.", + "family": "authentication", + "cwe": [], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "JS-JWT-OPTIONS", + "title": "Weakened JWT options", + "languages": [ + "javascript" + ], + "engine": "regex", + "before": "jwt.verify(token, key, { ignoreExpiration: true, ignoreNotBefore: true });", + "after": "jwt.verify(token, key, { algorithms: ['RS256'], issuer: 'auth', audience: 'notes' });", + "reason": "Review signal: Weakened JWT options. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "fix": "Remove verification bypasses and fix algorithm/key/claims policy; require exp separately where needed.", + "check": "Expired/premature tokens and wrong algorithms/key types fail.", + "doc": "docs/vulnerabilities/javascript.md#js-jwt-options", + "detection": "Regex: ignoreExpiration/ignoreNotBefore/allowInvalidAsymmetricKeyTypes=true. Options may be separate from verify; inspect actual use.", + "pattern": "\\b(?:ignoreExpiration|ignoreNotBefore|allowInvalidAsymmetricKeyTypes)[\"\\']?\\s*:\\s*true\\b", + "references": [ + "https://github.com/auth0/node-jsonwebtoken#jwtverifytoken-secretorpublickey-options-callback" + ], + "limitations": "Regex: ignoreExpiration/ignoreNotBefore/allowInvalidAsymmetricKeyTypes=true. Options may be separate from verify; inspect actual use.", + "family": "authentication", + "cwe": [], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "JS-HTTP-PARSER", + "title": "Lenient Node.js HTTP parser", + "languages": [ + "javascript", + "config" + ], + "engine": "regex", + "before": "http.createServer({ insecureHTTPParser: true }, handler);", + "after": "http.createServer({ insecureHTTPParser: false }, handler);", + "reason": "Review signal: Lenient Node.js HTTP parser. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "fix": "Use strict parsers on every hop and align framing/normalization; check NODE_OPTIONS and CLI flags.", + "check": "Conflicting framing fails at the first hop; valid keep-alive requests stay separate.", + "doc": "docs/vulnerabilities/javascript.md#js-http-parser", + "detection": "Regex: insecureHTTPParser:true or --insecure-http-parser. This alone does not prove request smuggling.", + "pattern": "\\binsecureHTTPParser[\"\\']?\\s*:\\s*true\\b|--insecure-http-parser\\b", + "references": [ + "https://nodejs.org/api/http.html#httpcreateserveroptions-requestlistener" + ], + "limitations": "Regex: insecureHTTPParser:true or --insecure-http-parser. This alone does not prove request smuggling.", + "family": "network-exposure", + "cwe": [], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "JS-STATIC-DOTFILES", + "title": "Static server allows dotfiles", + "languages": [ + "javascript" + ], + "engine": "regex", + "before": "app.use(express.static(root, { dotfiles: 'allow' }));", + "after": "app.use(express.static(publicDir, { dotfiles: 'deny' }));", + "reason": "Review signal: Static server allows dotfiles. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "fix": "Use a dedicated public root and deny dotfiles; allow required .well-known resources narrowly without secrets.", + "check": "Assets work; dotfiles, backups and files outside the root are unavailable.", + "doc": "docs/vulnerabilities/javascript.md#js-static-dotfiles", + "detection": "Regex: dotfiles:allow. Does not check actual root, middleware order, non-dot backups or symlinks.", + "pattern": "\\bdotfiles[\"\\']?\\s*:\\s*[\"\\']allow[\"\\']", + "references": [ + "https://expressjs.com/en/4x/api.html#express.static" + ], + "limitations": "Regex: dotfiles:allow. Does not check actual root, middleware order, non-dot backups or symlinks.", + "family": "file-access", + "cwe": [], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "PHP-EXTRACT", + "title": "extract overwrites local variables", + "languages": [ + "php" + ], + "engine": "regex", + "before": "extract($_POST);\nif ($is_admin) { show_private_data(); }", + "after": "$display_name = validate_display_name($_POST['display_name'] ?? '');", + "reason": "Review signal: extract overwrites local variables. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "fix": "Read explicit allowed fields. EXTR_SKIP reduces overwrites but does not replace schema/type and new-name controls.", + "check": "Input is_admin/owner/config cannot alter access; approved values retain types.", + "doc": "docs/vulnerabilities/php.md#php-extract", + "detection": "Regex: any extract(...); trusted template contexts need manual classification.", + "pattern": "\\bextract\\s*\\(", + "references": [ + "https://www.php.net/manual/en/function.extract.php" + ], + "limitations": "Regex: any extract(...); trusted template contexts need manual classification.", + "family": "manual-review", + "cwe": [], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "PHP-XML-FLAGS", + "title": "XML entity substitution or DTD enabled", + "languages": [ + "php", + "config" + ], + "engine": "regex", + "before": "$doc->loadXML($xml, LIBXML_NOENT | LIBXML_DTDLOAD | LIBXML_NONET);", + "after": "$doc->resolveExternals = false;\n$doc->substituteEntities = false;\n$doc->loadXML($boundedXml, LIBXML_NONET);", + "reason": "Review signal: XML entity substitution or DTD enabled. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "fix": "Disable entity substitution/external DTD loading, bound input and check libxml version. Use LIBXML_NO_XXE where supported; NONET alone is insufficient.", + "check": "Ordinary XML works; entities/DTD read no files or network and nesting/size are limited.", + "doc": "docs/vulnerabilities/php.md#php-xml-flags", + "detection": "Regex: LIBXML_NOENT/DTDLOAD/DTDATTR/DTDVALID and substituteEntities/resolveExternals=true. Numeric ini/database masks are not decoded; inspect bits against runtime constants.", + "pattern": "\\bLIBXML_(?:NOENT|DTDLOAD|DTDATTR|DTDVALID)\\b|\\b(?:substituteEntities|resolveExternals)\\s*=\\s*true\\b", + "references": [ + "https://www.php.net/manual/en/libxml.constants.php", + "https://github.com/enowars/enowars7-service-oldschool#vulnerabilities" + ], + "limitations": "Regex: LIBXML_NOENT/DTDLOAD/DTDATTR/DTDVALID and substituteEntities/resolveExternals=true. Numeric ini/database masks are not decoded; inspect bits against runtime constants.", + "family": "injection", + "cwe": [ + "CWE-611" + ], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "PHP-TEMPLATE", + "title": "Template built from dynamic text", + "languages": [ + "php" + ], + "engine": "regex", + "before": "$template = $twig->createTemplate($profileText);\necho $template->render($vars);", + "after": "echo $twig->render('profile.html.twig', ['about' => $profileText]);", + "reason": "Review signal: Template built from dynamic text. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "fix": "Separate trusted template source from values; user templates need explicit sandbox/loader/function/resource policy.", + "check": "Profile template expressions remain data; private templates/files are unavailable.", + "doc": "docs/vulnerabilities/php.md#php-template", + "detection": "Regex: createTemplate($...) and Smarty display/fetch with eval: or string:. Inspect variable loaders, custom filters and database templates.", + "pattern": "\\bcreateTemplate\\s*\\(\\s*\\$|->\\s*(?:fetch|display)\\s*\\(\\s*[\"\\'](?:eval|string):", + "references": [ + "https://twig.symfony.com/doc/3.x/api.html#loading-templates-from-a-string" + ], + "limitations": "Regex: createTemplate($...) and Smarty display/fetch with eval: or string:. Inspect variable loaders, custom filters and database templates.", + "family": "injection", + "cwe": [], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "PHP-CURL-TLS", + "title": "cURL certificate or hostname checks disabled", + "languages": [ + "php" + ], + "engine": "regex", + "before": "curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);\ncurl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);", + "after": "curl_setopt_array($ch, [CURLOPT_SSL_VERIFYPEER => true, CURLOPT_SSL_VERIFYHOST => 2, CURLOPT_CAINFO => $trustedCA]);", + "reason": "Review signal: cURL certificate or hostname checks disabled. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "fix": "Verify peer and hostname with the trusted CA; use VERIFYHOST=2, not historical ambiguous 1.", + "check": "Correct CA/host works; wrong CA/host and expiry fail without fallback.", + "doc": "docs/vulnerabilities/php.md#php-curl-tls", + "detection": "Regex: CURLOPT_SSL_VERIFYPEER=false/0 and CURLOPT_SSL_VERIFYHOST=false/0/1 in arguments/setopt_array. Variable values are not evaluated.", + "pattern": "\\b(?:CURLOPT_SSL_VERIFYPEER\\s*(?:,|=>)\\s*(?:false|0)\\b|CURLOPT_SSL_VERIFYHOST\\s*(?:,|=>)\\s*(?:false|[01])\\b)", + "references": [ + "https://www.php.net/manual/en/function.curl-setopt.php" + ], + "limitations": "Regex: CURLOPT_SSL_VERIFYPEER=false/0 and CURLOPT_SSL_VERIFYHOST=false/0/1 in arguments/setopt_array. Variable values are not evaluated.", + "family": "network-exposure", + "cwe": [], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "PHP-URL-INCLUDE", + "title": "Remote resource inclusion enabled", + "languages": [ + "config", + "php" + ], + "engine": "regex", + "before": "allow_url_include = On", + "after": "allow_url_include = Off", + "reason": "Review signal: Remote resource inclusion enabled. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "fix": "Disable allow_url_include in the effective SAPI config; select include paths from a closed server-side map.", + "check": "Normal modules load; client URLs cannot become executable code.", + "doc": "docs/vulnerabilities/php.md#php-url-include", + "detection": "Regex: allow_url_include=On/1/true in ini/config/assignment. Review runtime overrides and effective include paths separately.", + "pattern": "\\ballow_url_include[\"\\']?\\s*[:=]\\s*[\"\\']?(?:on|true|1)\\b", + "references": [ + "https://www.php.net/manual/en/filesystem.configuration.php#ini.allow-url-include" + ], + "limitations": "Regex: allow_url_include=On/1/true in ini/config/assignment. Review runtime overrides and effective include paths separately.", + "family": "network-exposure", + "cwe": [], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "PHP-SESSION-CONFIG", + "title": "Weakened PHP session configuration", + "languages": [ + "config", + "php" + ], + "engine": "regex", + "before": "session.use_strict_mode = 0\nsession.use_only_cookies = 0\nsession.use_trans_sid = 1", + "after": "session.use_strict_mode = 1\nsession.use_only_cookies = 1\nsession.use_trans_sid = 0", + "reason": "Review signal: Weakened PHP session configuration. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "fix": "Enable strict mode and cookie-only transport, disable URL rewriting and regenerate IDs at login; review custom handlers/cookies.", + "check": "Unknown fixed IDs fail, login changes the ID, URLs/logs contain no IDs and sessions work.", + "doc": "docs/vulnerabilities/php.md#php-session-config", + "detection": "Regex: explicit unsafe use_strict_mode/use_only_cookies/use_trans_sid values. Missing settings and ini_set argument forms need manual review.", + "pattern": "\\bsession\\.(?:(?:use_strict_mode|use_only_cookies)[\"\\']?\\s*[:=]\\s*[\"\\']?(?:0|off|false)\\b|use_trans_sid[\"\\']?\\s*[:=]\\s*[\"\\']?(?:1|on|true)\\b)", + "references": [ + "https://www.php.net/manual/en/session.configuration.php" + ], + "limitations": "Regex: explicit unsafe use_strict_mode/use_only_cookies/use_trans_sid values. Missing settings and ini_set argument forms need manual review.", + "family": "authentication", + "cwe": [], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "GO-TLS-MIN", + "title": "Obsolete minimum TLS version", + "languages": [ + "go" + ], + "engine": "regex", + "before": "cfg := &tls.Config{MinVersion: tls.VersionTLS10}", + "after": "cfg := &tls.Config{MinVersion: tls.VersionTLS12}", + "reason": "Review signal: Obsolete minimum TLS version. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "fix": "Choose TLS 1.2/1.3 minimum compatible with checker/peers while retaining certificate checks.", + "check": "Normal peers connect; versions below the chosen minimum fail.", + "doc": "docs/vulnerabilities/go.md#go-tls-min", + "detection": "Regex: MinVersion:tls.VersionSSL30/TLS10/TLS11 and assignments, including newlines; ==, !=, TLS12/TLS13 and 0 do not signal. SSL30 is obsolete and unsupported by modern Go. Review object/effective config/version; numbers, aliases, variables and external listener settings are not evaluated.", + "pattern": "(?:\\bMinVersion\\s*:|\\.\\s*MinVersion\\s*=(?!=))\\s*(?:tls\\.)?Version(?:SSL30|TLS10|TLS11)\\b", + "references": [ + "https://pkg.go.dev/crypto/tls#Config", + "https://github.com/golang/go/blob/go1.24.0/src/crypto/tls/common.go#L756" + ], + "limitations": "Regex: MinVersion:tls.VersionSSL30/TLS10/TLS11 and assignments, including newlines; ==, !=, TLS12/TLS13 and 0 do not signal. SSL30 is obsolete and unsupported by modern Go. Review object/effective config/version; numbers, aliases, variables and external listener settings are not evaluated.", + "family": "network-exposure", + "cwe": [], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "GO-JWT-UNVERIFIED", + "title": "JWT without signature or claims verification", + "languages": [ + "go" + ], + "engine": "regex", + "before": "token, _, err := parser.ParseUnverified(raw, &claims)", + "after": "token, err := jwt.ParseWithClaims(raw, &claims, trustedKeyFunc, jwt.WithValidMethods([]string{\"RS256\"}), jwt.WithIssuer(\"auth\"), jwt.WithAudience(\"notes\"), jwt.WithExpirationRequired())\nif err != nil || !token.Valid { return ErrUnauthorized }", + "reason": "Review signal: JWT without signature or claims verification. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "fix": "Use a validating API with trusted keyfunc, algorithms and claims; check err before using token/claims.", + "check": "Signature/expiry/audience checks work, error nil tokens do not panic and valid tokens pass.", + "doc": "docs/vulnerabilities/go.md#go-jwt-unverified", + "detection": "Regex: ParseUnverified and WithoutClaimsValidation; does not prove authentication uses the result. The example targets golang-jwt/jwt/v5.", + "pattern": "\\b(?:ParseUnverified|WithoutClaimsValidation)\\s*\\(", + "references": [ + "https://pkg.go.dev/github.com/golang-jwt/jwt/v5" + ], + "limitations": "Regex: ParseUnverified and WithoutClaimsValidation; does not prove authentication uses the result. The example targets golang-jwt/jwt/v5.", + "family": "authentication", + "cwe": [], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "JAVA-JNDI", + "title": "Dynamic JNDI lookup name", + "languages": [ + "java" + ], + "engine": "regex", + "before": "Object value = context.lookup(requestName);", + "after": "Object value = context.lookup(\"java:comp/env/jdbc/Notes\");", + "reason": "Review signal: Dynamic JNDI lookup name. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "fix": "Use a closed map of trusted local names and restrict providers; JDK updates do not replace input validation.", + "check": "Valid resources resolve; unknown/external names cannot initiate lookups or change backend.", + "doc": "docs/vulnerabilities/java.md#java-jndi", + "detection": "Regex: InitialContext.doLookup or ctx/context/initialContext.lookup with a non-string argument. Inspect arbitrary receiver names and indirect calls manually.", + "pattern": "\\b(?:InitialContext\\s*\\.\\s*doLookup|(?:ctx|context|initialContext)\\s*\\.\\s*lookup)\\s*\\(\\s*(?![\"\\'\\s])[\\w$]", + "references": [ + "https://docs.oracle.com/en/java/javase/21/docs/api/java.naming/javax/naming/InitialContext.html" + ], + "limitations": "Regex: InitialContext.doLookup or ctx/context/initialContext.lookup with a non-string argument. Inspect arbitrary receiver names and indirect calls manually.", + "family": "manual-review", + "cwe": [], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "JAVA-HOSTNAME-VERIFY", + "title": "Hostname verifier accepts every peer", + "languages": [ + "java" + ], + "engine": "regex", + "before": "builder.setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE);", + "after": "builder.setSSLHostnameVerifier(new DefaultHostnameVerifier());", + "reason": "Review signal: Hostname verifier accepts every peer. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "fix": "Restore the default verifier and trusted store instead of always-true callbacks.", + "check": "Trusted CA certificates for another host fail; the intended endpoint works.", + "doc": "docs/vulnerabilities/java.md#java-hostname-verify", + "detection": "Regex: NoopHostnameVerifier/ALLOW_ALL_HOSTNAME_VERIFIER and setHostnameVerifier with a simple true-lambda. Review complex callbacks and TrustManager separately.", + "pattern": "\\b(?:NoopHostnameVerifier|ALLOW_ALL_HOSTNAME_VERIFIER)\\b|\\bset(?:Default)?HostnameVerifier\\s*\\(\\s*\\([^)]{0,120}\\)\\s*->\\s*true\\b", + "references": [ + "https://hc.apache.org/httpcomponents-client-5.5.x/current/httpclient5/apidocs/org/apache/hc/client5/http/ssl/NoopHostnameVerifier.html" + ], + "limitations": "Regex: NoopHostnameVerifier/ALLOW_ALL_HOSTNAME_VERIFIER and setHostnameVerifier with a simple true-lambda. Review complex callbacks and TrustManager separately.", + "family": "network-exposure", + "cwe": [], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "JAVA-SPRING-CSRF", + "title": "Spring Security CSRF disabled", + "languages": [ + "java" + ], + "engine": "regex", + "before": "http.csrf(csrf -> csrf.disable());", + "after": "http.csrf(Customizer.withDefaults());", + "reason": "Review signal: Spring Security CSRF disabled. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "fix": "Keep protection for browser routes; restrict exemptions to an explicit bearer/webhook contract with no cookie fallback.", + "check": "Valid CSRF requests work; cookie POST without a token fails; approved API scenarios work.", + "doc": "docs/vulnerabilities/java.md#java-spring-csrf", + "detection": "Regex: csrf().disable(), csrf(x -> x.disable()) and csrf(AbstractHttpConfigurer::disable). Review individual security chains and matchers.", + "pattern": "\\bcsrf\\s*\\(\\s*\\)\\s*\\.\\s*disable\\s*\\(|\\bcsrf\\s*\\(\\s*[\\w]+\\s*->\\s*[\\w]+\\s*\\.\\s*disable\\s*\\(|\\bcsrf\\s*\\(\\s*AbstractHttpConfigurer\\s*::\\s*disable", + "references": [ + "https://docs.spring.io/spring-security/reference/servlet/exploits/csrf.html" + ], + "limitations": "Regex: csrf().disable(), csrf(x -> x.disable()) and csrf(AbstractHttpConfigurer::disable). Review individual security chains and matchers.", + "family": "authentication", + "cwe": [], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "CS-HTML-RAW", + "title": "HTML output without escaping", + "languages": [ + "csharp", + "template" + ], + "engine": "regex", + "before": "@Html.Raw(Model.About)", + "after": "@Model.About", + "reason": "Review signal: HTML output without escaping. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "fix": "Use regular Razor output or an allowlisted HTML sanitizer for supported rich text; consider URL/JS context.", + "check": "Untrusted tags, attributes and URLs cannot execute script; permitted text renders.", + "doc": "docs/vulnerabilities/csharp.md#cs-html-raw", + "detection": "Regex: Html.Raw and new HtmlString. Sanitization is not inferred from a call; trusted static markup may be legitimate.", + "pattern": "\\bHtml\\s*\\.\\s*Raw\\s*\\(|\\bnew\\s+HtmlString\\s*\\(", + "references": [ + "https://learn.microsoft.com/en-us/aspnet/core/security/cross-site-scripting" + ], + "limitations": "Regex: Html.Raw and new HtmlString. Sanitization is not inferred from a call; trusted static markup may be legitimate.", + "family": "injection", + "cwe": [ + "CWE-79" + ], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "CS-XML", + "title": "XML parser permits DTD or external resolver", + "languages": [ + "csharp" + ], + "engine": "regex", + "before": "var settings = new XmlReaderSettings { DtdProcessing = DtdProcessing.Parse, XmlResolver = new XmlUrlResolver() };", + "after": "var settings = new XmlReaderSettings { DtdProcessing = DtdProcessing.Prohibit, XmlResolver = null, MaxCharactersInDocument = 1048576 };", + "reason": "Review signal: XML parser permits DTD or external resolver. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "fix": "Prohibit DTD, remove external resolver and bound input; pass these settings to the actual XmlReader.", + "check": "Ordinary XML works; external resources/DTD fail and size is bounded.", + "doc": "docs/vulnerabilities/csharp.md#cs-xml", + "detection": "Regex: DtdProcessing.Parse, XmlResolver=new XmlUrlResolver and ProhibitDtd=false. Defaults depend on framework/API; absence of a match is not proof of safety.", + "pattern": "\\bDtdProcessing\\s*=\\s*(?:[\\w.]*\\.)?DtdProcessing\\.Parse\\b|\\bXmlResolver\\s*=\\s*new\\s+(?:[\\w.]*\\.)?XmlUrlResolver\\s*\\(|\\bProhibitDtd\\s*=\\s*false\\b", + "references": [ + "https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca3075" + ], + "limitations": "Regex: DtdProcessing.Parse, XmlResolver=new XmlUrlResolver and ProhibitDtd=false. Defaults depend on framework/API; absence of a match is not proof of safety.", + "family": "injection", + "cwe": [ + "CWE-611" + ], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "CS-JWT-VALIDATION", + "title": "Weakened .NET token validation", + "languages": [ + "csharp", + "config" + ], + "engine": "regex", + "before": "new TokenValidationParameters { ValidateLifetime = false, ValidateAudience = false, RequireSignedTokens = false };", + "after": "new TokenValidationParameters { ValidateLifetime = true, ValidateAudience = true, ValidAudience = \"notes\", ValidateIssuer = true, ValidIssuer = \"auth\", RequireSignedTokens = true, RequireExpirationTime = true, IssuerSigningKey = trustedKey };", + "reason": "Review signal: Weakened .NET token validation. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "fix": "Validate signature, key, time, issuer and audience; custom validators must retain these invariants.", + "check": "Unsigned, expired and foreign tokens fail; valid tokens pass.", + "doc": "docs/vulnerabilities/csharp.md#cs-jwt-validation", + "detection": "Regex: explicit false for ValidateLifetime/Issuer/Audience and RequireSignedTokens/ExpirationTime. ValidateIssuerSigningKey=false alone is not treated as missing signature verification.", + "pattern": "\\b(?:ValidateLifetime|ValidateIssuer|ValidateAudience|RequireSignedTokens|RequireExpirationTime)[\"\\']?\\s*[:=]\\s*false\\b", + "references": [ + "https://learn.microsoft.com/en-us/dotnet/api/microsoft.identitymodel.tokens.tokenvalidationparameters" + ], + "limitations": "Regex: explicit false for ValidateLifetime/Issuer/Audience and RequireSignedTokens/ExpirationTime. ValidateIssuerSigningKey=false alone is not treated as missing signature verification.", + "family": "authentication", + "cwe": [], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "CS-TLS-VALIDATION", + "title": "HTTPS validation callback always accepts", + "languages": [ + "csharp" + ], + "engine": "regex", + "before": "handler.ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator;", + "after": "var handler = new HttpClientHandler();\nvar client = new HttpClient(handler);", + "reason": "Review signal: HTTPS validation callback always accepts. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "fix": "Use default certificate checks and trusted CA; custom trust must not unconditionally accept.", + "check": "Valid certificates work; wrong host/CA and expiry fail.", + "doc": "docs/vulnerabilities/csharp.md#cs-tls-validation", + "detection": "Regex: DangerousAcceptAnyServerCertificateValidator and simple true-lambdas for certificate callbacks. Arbitrary methods and block-bodied lambdas need manual review.", + "pattern": "\\bDangerousAcceptAnyServerCertificateValidator\\b|\\b(?:ServerCertificateCustomValidationCallback|ServerCertificateValidationCallback)\\s*\\+?=\\s*\\([^)]{0,180}\\)\\s*=>\\s*true\\b", + "references": [ + "https://learn.microsoft.com/en-us/dotnet/api/system.net.http.httpclienthandler.dangerousacceptanyservercertificatevalidator" + ], + "limitations": "Regex: DangerousAcceptAnyServerCertificateValidator and simple true-lambdas for certificate callbacks. Arbitrary methods and block-bodied lambdas need manual review.", + "family": "network-exposure", + "cwe": [], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "RUBY-CSRF", + "title": "Rails controller disables CSRF", + "languages": [ + "ruby" + ], + "engine": "regex", + "before": "skip_forgery_protection\nskip_before_action :verify_authenticity_token", + "after": "protect_from_forgery with: :exception", + "reason": "Review signal: Rails controller disables CSRF. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "fix": "Restore browser CSRF; narrow exceptions to an independently authenticated stateless API/webhook.", + "check": "Valid POST works; missing/wrong authenticity token fails; authorized webhooks work.", + "doc": "docs/vulnerabilities/ruby.md#ruby-csrf", + "detection": "Regex: skip_forgery_protection, skip_before_action/filter :verify_authenticity_token and allow_forgery_protection=false. Review only/except conditions.", + "pattern": "\\bskip_forgery_protection\\b|\\bskip_before_(?:action|filter)\\s*\\(?\\s*:verify_authenticity_token\\b|\\ballow_forgery_protection\\s*=\\s*false\\b", + "references": [ + "https://api.rubyonrails.org/classes/ActionController/RequestForgeryProtection/ClassMethods.html" + ], + "limitations": "Regex: skip_forgery_protection, skip_before_action/filter :verify_authenticity_token and allow_forgery_protection=false. Review only/except conditions.", + "family": "authentication", + "cwe": [], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "RUBY-TLS", + "title": "Ruby HTTPS peer verification disabled", + "languages": [ + "ruby" + ], + "engine": "regex", + "before": "http.verify_mode = OpenSSL::SSL::VERIFY_NONE", + "after": "http.verify_mode = OpenSSL::SSL::VERIFY_PEER\nhttp.ca_file = trusted_ca_file", + "reason": "Review signal: Ruby HTTPS peer verification disabled. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "fix": "Restore peer/hostname checks and the trusted CA; verify actual HTTP client settings.", + "check": "Correct server works; invalid certificates cannot yield useful responses.", + "doc": "docs/vulnerabilities/ruby.md#ruby-tls", + "detection": "Regex: VERIFY_NONE. Does not establish whether the object is used for a real connection.", + "pattern": "\\b(?:OpenSSL::SSL::)?VERIFY_NONE\\b", + "references": [ + "https://docs.ruby-lang.org/en/master/OpenSSL/SSL/SSLContext.html" + ], + "limitations": "Regex: VERIFY_NONE. Does not establish whether the object is used for a real connection.", + "family": "network-exposure", + "cwe": [], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "RUST-COMMAND", + "title": "Shell launched from Rust", + "languages": [ + "rust" + ], + "engine": "regex", + "before": "Command::new(\"sh\").arg(\"-c\").arg(command).output()?;", + "after": "Command::new(\"/usr/bin/file\").arg(\"--\").arg(validated_name).output()?;", + "reason": "Review signal: Shell launched from Rust. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "fix": "Use a fixed executable, separate arguments, allowlisted options and bounded time/output.", + "check": "Metacharacters stay data; dangerous options cannot change behavior.", + "doc": "docs/vulnerabilities/rust.md#rust-command", + "detection": "Regex: Command::new with literal sh/bash/dash/zsh/cmd/powershell/pwsh. A command may be trusted; review -c, variable executables and .args.", + "pattern": "\\bCommand\\s*::\\s*new\\s*\\(\\s*\"(?:[^\"\\n]*/)?(?:sh|bash|dash|zsh|cmd(?:\\.exe)?|powershell(?:\\.exe)?|pwsh)\"", + "references": [ + "https://doc.rust-lang.org/std/process/struct.Command.html" + ], + "limitations": "Regex: Command::new with literal sh/bash/dash/zsh/cmd/powershell/pwsh. A command may be trusted; review -c, variable executables and .args.", + "family": "injection", + "cwe": [ + "CWE-78" + ], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "RUST-TLS", + "title": "Rust HTTP accepts invalid certificates", + "languages": [ + "rust" + ], + "engine": "regex", + "before": "let client = reqwest::Client::builder().danger_accept_invalid_certs(true).build()?;", + "after": "let client = reqwest::Client::builder().add_root_certificate(trusted_ca).build()?;", + "reason": "Review signal: Rust HTTP accepts invalid certificates. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "fix": "Use default validation and add the internal root CA instead of bypassing checks.", + "check": "Correct CA/host works; invalid certificates/hostnames fail.", + "doc": "docs/vulnerabilities/rust.md#rust-tls", + "detection": "Regex: danger_accept_invalid_certs/hostnames(true), including reqwest/native-tls-like builders. Review variable values and custom verifiers.", + "pattern": "\\bdanger_accept_invalid_(?:certs|hostnames)\\s*\\(\\s*true\\s*\\)", + "references": [ + "https://docs.rs/reqwest/latest/reqwest/struct.ClientBuilder.html" + ], + "limitations": "Regex: danger_accept_invalid_certs/hostnames(true), including reqwest/native-tls-like builders. Review variable values and custom verifiers.", + "family": "network-exposure", + "cwe": [], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "RUST-JWT-VALIDATION", + "title": "Rust JWT checks disabled", + "languages": [ + "rust" + ], + "engine": "regex", + "before": "validation.insecure_disable_signature_validation();\nvalidation.validate_exp = false;", + "after": "let mut validation = Validation::new(Algorithm::RS256);\nvalidation.set_audience(&[\"notes\"]);\nvalidation.set_issuer(&[\"auth\"]);\nvalidation.set_required_spec_claims(&[\"exp\", \"sub\", \"iss\", \"aud\"]);", + "reason": "Review signal: Rust JWT checks disabled. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "fix": "Use verifying decode with a trusted key and Validation contract; check its result before access.", + "check": "Invalid signatures, expiry and missing required fields fail.", + "doc": "docs/vulnerabilities/rust.md#rust-jwt-validation", + "detection": "Regex: insecure_disable_signature_validation, validate_exp/validate_aud=false and legacy dangerous_*decode. API depends on jsonwebtoken version.", + "pattern": "\\binsecure_disable_signature_validation\\s*\\(|\\bvalidate_(?:exp|aud)\\s*=\\s*false\\b|\\bdangerous_(?:insecure_)?decode(?:_with_validation)?\\s*\\(", + "references": [ + "https://docs.rs/jsonwebtoken/latest/jsonwebtoken/struct.Validation.html" + ], + "limitations": "Regex: insecure_disable_signature_validation, validate_exp/validate_aud=false and legacy dangerous_*decode. API depends on jsonwebtoken version.", + "family": "authentication", + "cwe": [], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "C-TEMPFILE-RACE", + "title": "Temporary filename without atomic creation", + "languages": [ + "native" + ], + "engine": "regex", + "before": "char name[L_tmpnam];\ntmpnam(name);\nFILE *f = fopen(name, \"w\");", + "after": "char name[] = \"/tmp/app-XXXXXX\";\nint fd = mkstemp(name);\nif (fd < 0) return ERROR;\nunlink(name);\n/* use fd; close(fd) on every exit */", + "reason": "Review signal: Temporary filename without atomic creation. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "fix": "Create a private file atomically, retain its fd, check errors/modes and close/remove it on all paths.", + "check": "Concurrent operations get separate fds; existing files/symlinks are not overwritten.", + "doc": "docs/vulnerabilities/c-cpp.md#c-tempfile-race", + "detection": "Regex: tmpnam/tempnam/mktemp. Custom filename schemes, reopening after mkstemp and directory TOCTOU need manual review.", + "pattern": "\\b(?:tmpnam|tempnam|mktemp)\\s*\\(", + "references": [ + "https://pubs.opengroup.org/onlinepubs/9799919799/functions/mkstemp.html" + ], + "limitations": "Regex: tmpnam/tempnam/mktemp. Custom filename schemes, reopening after mkstemp and directory TOCTOU need manual review.", + "family": "file-access", + "cwe": [], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "C-STRNCPY", + "title": "strncpy may omit NUL termination", + "languages": [ + "native" + ], + "engine": "regex", + "before": "strncpy(out, input, sizeof out);\nputs(out);", + "after": "size_t n = bounded_input_length;\nif (n >= sizeof out) return ERROR;\nmemcpy(out, input, n);\nout[n] = '\\0';", + "reason": "Review signal: strncpy may omit NUL termination. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "fix": "Choose reject-too-long or explicit bounded truncation with NUL space; use explicit lengths for binary data.", + "check": "Test empty/capacity-1/capacity/capacity+1; truncation cannot change identity.", + "doc": "docs/vulnerabilities/c-cpp.md#c-strncpy", + "detection": "Regex: strncpy. Review later NUL termination and actual capacity; memcpy without length checks is not a fix.", + "pattern": "\\bstrncpy\\s*\\(", + "references": [ + "https://pubs.opengroup.org/onlinepubs/9799919799/functions/strncpy.html" + ], + "limitations": "Regex: strncpy. Review later NUL termination and actual capacity; memcpy without length checks is not a fix.", + "family": "memory-safety", + "cwe": [], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "SQL-SQLITE-FK", + "title": "SQLite foreign_keys explicitly disabled", + "languages": [ + "sql", + "python", + "javascript", + "go", + "php", + "java", + "csharp", + "ruby", + "rust" + ], + "engine": "regex", + "before": "PRAGMA foreign_keys = OFF;", + "after": "PRAGMA foreign_keys = ON;", + "reason": "Review signal: SQLite foreign_keys explicitly disabled. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "fix": "Enable FK on every connection outside transactions, verify the result and existing violations, and migrate invalid records separately.", + "check": "Every connection reports foreign_keys=1; foreign_key_check is empty and invalid owners fail.", + "doc": "docs/vulnerabilities/sql.md#sql-sqlite-fk", + "detection": "Regex: PRAGMA foreign_keys=OFF/0/false or foreign_keys(OFF/0/false). Review missing ON, pool hooks and compile options.", + "pattern": "\\bPRAGMA\\s+foreign_keys\\s*(?:=|\\()\\s*(?:OFF|0|false)\\b", + "references": [ + "https://www.sqlite.org/foreignkeys.html" + ], + "limitations": "Regex: PRAGMA foreign_keys=OFF/0/false or foreign_keys(OFF/0/false). Review missing ON, pool hooks and compile options.", + "family": "manual-review", + "cwe": [], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "SQL-MYSQL-PRIVILEGES", + "title": "MySQL runtime user has admin privileges", + "languages": [ + "sql" + ], + "engine": "regex", + "before": "GRANT FILE, SUPER ON *.* TO 'app'@'%';", + "after": "GRANT SELECT, INSERT, UPDATE, DELETE ON appdb.* TO 'app'@'localhost';", + "reason": "Review signal: MySQL runtime user has admin privileges. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "fix": "Separate runtime/migration accounts; remove unnecessary global grants and GRANT OPTION; match account hosts to topology.", + "check": "SHOW GRANTS contains only required actions; migrations/checker still work.", + "doc": "docs/vulnerabilities/sql.md#sql-mysql-privileges", + "detection": "Regex: GRANT with FILE/SUPER or ALL [PRIVILEGES] ON *.*. Review other dangerous dynamic privileges, roles and existing grants.", + "pattern": "\\bGRANT\\s+(?:(?:[A-Z_]+\\s*,\\s*)*(?:FILE|SUPER)\\b|ALL(?:\\s+PRIVILEGES)?\\s+ON\\s+\\*\\s*\\.\\s*\\*)", + "references": [ + "https://dev.mysql.com/doc/refman/8.4/en/privileges-provided.html" + ], + "limitations": "Regex: GRANT with FILE/SUPER or ALL [PRIVILEGES] ON *.*. Review other dangerous dynamic privileges, roles and existing grants.", + "family": "authentication", + "cwe": [], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "SQL-RLS-DISABLE", + "title": "PostgreSQL table RLS disabled", + "languages": [ + "sql" + ], + "engine": "regex", + "before": "ALTER TABLE notes DISABLE ROW LEVEL SECURITY;", + "after": "ALTER TABLE notes ENABLE ROW LEVEL SECURITY;\nALTER TABLE notes FORCE ROW LEVEL SECURITY;\n-- Install reviewed owner/tenant policies before serving traffic.", + "reason": "Review signal: PostgreSQL table RLS disabled. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "fix": "Install intended policies and enable RLS; runtime must not be superuser/BYPASSRLS. FORCE constrains table owners, not these bypass roles.", + "check": "Test SELECT/INSERT/UPDATE/DELETE with two runtime identities/tenants and separate migration role.", + "doc": "docs/vulnerabilities/sql.md#sql-rls-disable", + "detection": "Regex: ALTER TABLE ... DISABLE ROW LEVEL SECURITY. Does not infer missing ENABLE, broad policies or connection role.", + "pattern": "\\bALTER\\s+TABLE\\s+[^;\\n]{1,180}\\s+DISABLE\\s+ROW\\s+LEVEL\\s+SECURITY\\b", + "references": [ + "https://www.postgresql.org/docs/current/ddl-rowsecurity.html" + ], + "limitations": "Regex: ALTER TABLE ... DISABLE ROW LEVEL SECURITY. Does not infer missing ENABLE, broad policies or connection role.", + "family": "authentication", + "cwe": [], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "CFG-K8S-HOST", + "title": "Container shares host namespaces", + "languages": [ + "config" + ], + "engine": "regex", + "before": "hostPID: true\nhostIPC: true\nhostNetwork: true", + "after": "hostPID: false\nhostIPC: false\nhostNetwork: false", + "reason": "Review signal: Container shares host namespaces. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "fix": "Disable unnecessary host namespaces; implement required connectivity within approved competition topology and verify probes/ports.", + "check": "Service/checker works without host process/IPC visibility or unintended sockets.", + "doc": "docs/vulnerabilities/configuration.md#cfg-k8s-host", + "detection": "Regex: hostPID/hostIPC/hostNetwork:true and Compose pid/ipc/network_mode:host. No admission-policy or running-pod analysis.", + "pattern": "\\b(?:hostPID|hostIPC|hostNetwork)[\"\\']?\\s*:\\s*true\\b|\\b(?:pid|ipc|network_mode)[\"\\']?\\s*:\\s*[\"\\']?host\\b", + "references": [ + "https://kubernetes.io/docs/concepts/security/pod-security-standards/" + ], + "limitations": "Regex: hostPID/hostIPC/hostNetwork:true and Compose pid/ipc/network_mode:host. No admission-policy or running-pod analysis.", + "family": "container-isolation", + "cwe": [], + "review_priority": "normal", + "signal_kind": "configuration-review" + }, + { + "id": "CFG-UNCONFINED", + "title": "seccomp/AppArmor profile disabled", + "languages": [ + "config", + "docker", + "shell" + ], + "engine": "regex", + "before": "security_opt:\n - seccomp:unconfined\n - apparmor:unconfined", + "after": "security_opt:\n - no-new-privileges:true\n# Keep the runtime default seccomp/AppArmor profiles.", + "reason": "Review signal: seccomp/AppArmor profile disabled. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "fix": "Restore the default or minimum compatible profile with narrow exceptions.", + "check": "Normal operations/checker work and the effective container applies the profile.", + "doc": "docs/vulnerabilities/configuration.md#cfg-unconfined", + "detection": "Regex: seccomp/apparmor=unconfined or :unconfined and Kubernetes type:Unconfined. Unrelated YAML type keys may match.", + "pattern": "\\b(?:seccomp|apparmor)\\s*[:=]\\s*[\"\\']?unconfined\\b|\\btype[\"\\']?\\s*:\\s*[\"\\']?Unconfined\\b", + "references": [ + "https://docs.docker.com/engine/security/seccomp/" + ], + "limitations": "Regex: seccomp/apparmor=unconfined or :unconfined and Kubernetes type:Unconfined. Unrelated YAML type keys may match.", + "family": "container-isolation", + "cwe": [], + "review_priority": "normal", + "signal_kind": "configuration-review" + }, + { + "id": "CFG-PRIV-ESCALATION", + "title": "Process privilege escalation allowed", + "languages": [ + "config" + ], + "engine": "regex", + "before": "allowPrivilegeEscalation: true", + "after": "allowPrivilegeEscalation: false", + "reason": "Review signal: Process privilege escalation allowed. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "fix": "Disable allowPrivilegeEscalation and remove privileged/CAP_SYS_ADMIN and unnecessary capabilities.", + "check": "Required operations work and effective securityContext matches the manifest.", + "doc": "docs/vulnerabilities/configuration.md#cfg-priv-escalation", + "detection": "Regex: explicit allowPrivilegeEscalation:true. Review missing fields, defaults and interactions with privileged/CAP_SYS_ADMIN.", + "pattern": "\\ballowPrivilegeEscalation[\"\\']?\\s*:\\s*true\\b", + "references": [ + "https://kubernetes.io/docs/tasks/configure-pod-container/security-context/" + ], + "limitations": "Regex: explicit allowPrivilegeEscalation:true. Review missing fields, defaults and interactions with privileged/CAP_SYS_ADMIN.", + "family": "container-isolation", + "cwe": [], + "review_priority": "normal", + "signal_kind": "configuration-review" + }, + { + "id": "CFG-K8S-RBAC", + "title": "Workload bound to cluster-admin", + "languages": [ + "config" + ], + "engine": "regex", + "before": "roleRef:\n apiGroup: rbac.authorization.k8s.io\n kind: ClusterRole\n name: cluster-admin", + "after": "roleRef:\n apiGroup: rbac.authorization.k8s.io\n kind: Role\n name: notes-read-config", + "reason": "Review signal: Workload bound to cluster-admin. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "fix": "Use a least-privilege Role and namespaced RoleBinding; review subjects, verbs, resources, names and impersonate/bind/escalate.", + "check": "Runtime identity can perform only required operations, not read foreign Secrets or grant rights.", + "doc": "docs/vulnerabilities/configuration.md#cfg-k8s-rbac", + "detection": "Regex: name:cluster-admin. Does not connect roleRef to subjects or find equivalent wildcard roles; inspect remaining RBAC manually.", + "pattern": "\\bname[\"\\']?\\s*:\\s*[\"\\']?cluster-admin(?:[\\\"\\']|\\s|$)", + "references": [ + "https://kubernetes.io/docs/reference/access-authn-authz/rbac/" + ], + "limitations": "Regex: name:cluster-admin. Does not connect roleRef to subjects or find equivalent wildcard roles; inspect remaining RBAC manually.", + "family": "container-isolation", + "cwe": [], + "review_priority": "normal", + "signal_kind": "configuration-review" + }, + { + "id": "CFG-ACTUATOR", + "title": "Spring Actuator exposes every endpoint", + "languages": [ + "config" + ], + "engine": "regex", + "before": "management.endpoints.web.exposure.include=*", + "after": "management.endpoints.web.exposure.include=health", + "reason": "Review signal: Spring Actuator exposes every endpoint. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "fix": "Expose only necessary endpoints and restrict management access; inspect health details/custom SecurityFilterChain separately.", + "check": "Health/checker works; env, heapdump, loggers, shutdown and unnecessary endpoints require approved admin access.", + "doc": "docs/vulnerabilities/configuration.md#cfg-actuator", + "detection": "Regex: flat property or MANAGEMENT_ENDPOINTS_WEB_EXPOSURE_INCLUDE with *. Inspect nested YAML and active profiles using endpoints/exposure/include.", + "pattern": "\\b(?:management\\.endpoints\\.web\\.exposure\\.include|MANAGEMENT_ENDPOINTS_WEB_EXPOSURE_INCLUDE)[\"\\']?\\s*[:=]\\s*[\"\\']?\\*", + "references": [ + "https://docs.spring.io/spring-boot/reference/actuator/endpoints.html" + ], + "limitations": "Regex: flat property or MANAGEMENT_ENDPOINTS_WEB_EXPOSURE_INCLUDE with *. Inspect nested YAML and active profiles using endpoints/exposure/include.", + "family": "network-exposure", + "cwe": [], + "review_priority": "normal", + "signal_kind": "configuration-review" + }, + { + "id": "CFG-H2-CONSOLE", + "title": "H2 web console enabled", + "languages": [ + "config" + ], + "engine": "regex", + "before": "spring.h2.console.enabled=true", + "after": "spring.h2.console.enabled=false", + "reason": "Review signal: H2 web console enabled. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "fix": "Disable in the runtime profile or provide protected local admin access; never remove application-wide auth/CSRF for it.", + "check": "Database operations work; console is not exposed to the game network.", + "doc": "docs/vulnerabilities/configuration.md#cfg-h2-console", + "detection": "Regex: spring.h2.console.enabled/SPRING_H2_CONSOLE_ENABLED=true. Inspect nested YAML, aliases and active profiles.", + "pattern": "\\b(?:spring\\.h2\\.console\\.enabled|SPRING_H2_CONSOLE_ENABLED)[\"\\']?\\s*[:=]\\s*[\"\\']?true\\b", + "references": [ + "https://docs.spring.io/spring-boot/reference/data/sql.html#data.sql.h2-web-console" + ], + "limitations": "Regex: spring.h2.console.enabled/SPRING_H2_CONSOLE_ENABLED=true. Inspect nested YAML, aliases and active profiles.", + "family": "network-exposure", + "cwe": [], + "review_priority": "normal", + "signal_kind": "configuration-review" + }, + { + "id": "CFG-TLS-UPSTREAM", + "title": "Proxy does not verify upstream TLS", + "languages": [ + "config" + ], + "engine": "regex", + "before": "proxy_ssl_verify off;", + "after": "proxy_ssl_verify on;\nproxy_ssl_trusted_certificate /etc/nginx/trusted-ca.pem;\nproxy_ssl_server_name on;\nproxy_ssl_name notes.internal;", + "reason": "Review signal: Proxy does not verify upstream TLS. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "fix": "Enable verification, trusted CA and correct name/SNI; validate chain/intermediate depth for the actual upstream.", + "check": "Correct backend works; wrong certificate/host fails without HTTP fallback.", + "doc": "docs/vulnerabilities/configuration.md#cfg-tls-upstream", + "detection": "Regex: proxy_ssl_verify/grpc_ssl_verify off. Missing directives, inheritance and effective values require complete nginx config review.", + "pattern": "\\b(?:proxy_ssl_verify|grpc_ssl_verify)\\s+off\\s*;", + "references": [ + "https://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_ssl_verify" + ], + "limitations": "Regex: proxy_ssl_verify/grpc_ssl_verify off. Missing directives, inheritance and effective values require complete nginx config review.", + "family": "network-exposure", + "cwe": [], + "review_priority": "normal", + "signal_kind": "configuration-review" + }, + { + "id": "CFG-SSH-EMPTY-PASSWORD", + "title": "SSHD permits empty passwords", + "languages": [ + "config" + ], + "engine": "regex", + "before": "PermitEmptyPasswords yes", + "after": "PermitEmptyPasswords no", + "reason": "Review signal: SSHD permits empty passwords. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "fix": "Disallow empty passwords; review Match/PAM/accounts while retaining a working administration channel before applying changes.", + "check": "Approved login works; empty passwords fail in every applicable Match context.", + "doc": "docs/vulnerabilities/configuration.md#cfg-ssh-empty-password", + "detection": "Regex: PermitEmptyPasswords yes. Recognizes sshd_config; include files with arbitrary names require explicit review.", + "pattern": "^\\s*PermitEmptyPasswords\\s+yes\\b", + "references": [ + "https://man.openbsd.org/sshd_config#PermitEmptyPasswords" + ], + "limitations": "Regex: PermitEmptyPasswords yes. Recognizes sshd_config; include files with arbitrary names require explicit review.", + "family": "authentication", + "cwe": [], + "review_priority": "normal", + "signal_kind": "configuration-review" + }, + { + "id": "CFG-SUDO-ALL", + "title": "Unrestricted passwordless sudo", + "languages": [ + "config" + ], + "engine": "regex", + "before": "app ALL=(ALL:ALL) NOPASSWD: ALL", + "after": "# Runtime user has no sudo grant.\n# Provision required resources before service startup.", + "reason": "Review signal: Unrestricted passwordless sudo. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "fix": "Remove runtime sudo; move rare privileged operations into a minimal helper without arbitrary argv, shell or writable dependencies.", + "check": "Service works without sudo; effective rights contain neither ALL nor shell-escaping commands.", + "doc": "docs/vulnerabilities/configuration.md#cfg-sudo-all", + "detection": "Regex: NOPASSWD:ALL. Review aliases, includes, wildcard argv and dangerous allowed binaries; recognizes sudoers.", + "pattern": "\\bNOPASSWD\\s*:\\s*ALL\\b", + "references": [ + "https://www.sudo.ws/docs/man/sudoers.man/" + ], + "limitations": "Regex: NOPASSWD:ALL. Review aliases, includes, wildcard argv and dangerous allowed binaries; recognizes sudoers.", + "family": "authentication", + "cwe": [], + "review_priority": "normal", + "signal_kind": "configuration-review" + }, + { + "id": "SQL-TOKEN-PREFIX", + "title": "Secret token checked by prefix or range", + "languages": [ + "sql", + "python", + "javascript", + "php", + "go", + "java", + "csharp", + "ruby", + "rust" + ], + "engine": "regex", + "before": "SELECT content FROM exports WHERE username = $1 AND nonce >= $2 AND nonce < $3;", + "after": "SELECT content FROM exports WHERE username = $1 AND nonce = $2;\n-- Before querying: require the full canonical token, correct length/type and purpose.", + "reason": "Review signal: Secret token checked by prefix or range. Trace data origin, validation and actual use; a match does not prove a vulnerability.", + "fix": "Require the complete canonical token with valid length/type, exact equality and binding to user/purpose/expiry; rate limiting is separate.", + "check": "Empty, short, prefix, extra-suffix and foreign-user tokens fail; complete valid tokens work.", + "doc": "docs/vulnerabilities/sql.md#sql-token-prefix", + "detection": "Regex: nonce/token/reset_token/api_key before LIKE, >= or <= in SQL text. Counters/log searches may be legitimate; inspect renamed fields, substr, startsWith and application-side partial comparisons.", + "pattern": "\\b(?:nonce|token|reset_token|api_key)\\s*(?:LIKE\\b|>=|<=)", + "references": [ + "https://github.com/enowars/enowars10-service-flagdrive/blob/d1575098fe2c516460136bb5fba11d9a1c4af3f7/documentation/FLAGSTORE_0.md" + ], + "limitations": "Regex: nonce/token/reset_token/api_key before LIKE, >= or <= in SQL text. Counters/log searches may be legitimate; inspect renamed fields, substr, startsWith and application-side partial comparisons.", + "family": "authentication", + "cwe": [], + "review_priority": "normal", + "signal_kind": "syntactic-review" + }, + { + "id": "PY-AUTH-DECORATOR", + "languages": [ + "python" + ], + "title": "Flask route registers before login protection", + "engine": "python-ast", + "before": "from flask import Flask\nfrom flask_login import login_required\napp = Flask(__name__)\n@login_required\n@app.route('/private')\ndef private():\n return 'private'", + "after": "from flask import Flask\nfrom flask_login import login_required\napp = Flask(__name__)\n@app.route('/private')\n@login_required\ndef private():\n return 'private'", + "fix": "Put the known Flask route decorator outside login_required; verify authorization using the registered endpoint, not only direct function calls.", + "check": "Anonymous requests must fail through the real route; authenticated requests and checker behavior must still work.", + "doc": "docs/vulnerabilities/python.md#py-auth-decorator", + "reason": "Review signal: Flask route registers before login protection. A match is not proof of exploitability; validate the actual service contract.", + "detection": "AST: imported flask_login.login_required above route/get/post/put/patch/delete on a known Flask/Blueprint constructor. Aliases and straight-line rebinding respected. Custom decorators, factories, dynamic routes and other registration methods remain manual.", + "limitations": "AST: imported flask_login.login_required above route/get/post/put/patch/delete on a known Flask/Blueprint constructor. Aliases and straight-line rebinding respected. Custom decorators, factories, dynamic routes and other registration methods remain manual.", + "family": "authentication", + "cwe": [ + "CWE-862" + ], + "review_priority": "normal", + "signal_kind": "syntactic-review", + "references": [ + "https://flask.palletsprojects.com/en/stable/patterns/viewdecorators/" + ], + "introduced": "1.7.0", + "coverage_required": [ + "python" + ] + }, + { + "id": "PY-LOG-CREDENTIALS", + "languages": [ + "python" + ], + "title": "Credential-like value passed directly to logging", + "engine": "python-ast", + "before": "import logging\nlogging.warning('authentication failed: %s', password)", + "after": "import logging\nlogging.warning('authentication failed')", + "fix": "Log stable event categories and approved identifiers, never credential values or Authorization headers; test failed login and exception paths.", + "check": "Canary credentials must not appear in stdout, logs, evidence or broadcasts; useful failure diagnostics remain available.", + "doc": "docs/vulnerabilities/python.md#py-log-credentials", + "reason": "Review signal: Credential-like value passed directly to logging. A match is not proof of exploitability; validate the actual service contract.", + "detection": "AST: known logging module/getLogger or Flask app.logger methods with direct sensitive names/attributes/subscripts, dict/list values or simple format expressions. Names: password/passwd/secret/token/access_token/refresh_token/api_key/authorization. Helper calls, logging kwargs, wrappers and other names are not traced; no helper-call signal does not verify redaction.", + "limitations": "AST: known logging module/getLogger or Flask app.logger methods with direct sensitive names/attributes/subscripts, dict/list values or simple format expressions. Names: password/passwd/secret/token/access_token/refresh_token/api_key/authorization. Helper calls, logging kwargs, wrappers and other names are not traced; no helper-call signal does not verify redaction.", + "family": "secret-handling", + "cwe": [ + "CWE-532" + ], + "review_priority": "normal", + "signal_kind": "syntactic-review", + "references": [ + "https://docs.python.org/3/library/logging.html", + "https://flask.palletsprojects.com/en/stable/logging/" + ], + "introduced": "1.7.0", + "coverage_required": [ + "python" + ] + }, + { + "id": "JS-REDIRECT-INPUT", + "languages": [ + "javascript" + ], + "title": "Request field passed directly to an Express-style redirect", + "engine": "regex", + "before": "res.redirect(req.query.next);", + "after": "res.redirect('/account');", + "fix": "Resolve redirects using a server-owned route table or an explicit normalized URL policy.", + "check": "External and scheme-relative destinations fail; approved navigation still works.", + "doc": "docs/vulnerabilities/javascript.md#js-redirect-input", + "reason": "Review signal: Request field passed directly to an Express-style redirect. A match is not proof of exploitability; validate the actual service contract.", + "detection": "Regex with lexical comment/string exclusions: res/response.redirect with direct req/request.query/body/params property, optionally following a literal status code. Not receiver typing or data-flow analysis; computed keys, aliases and upstream validation need review.", + "limitations": "Regex with lexical comment/string exclusions: res/response.redirect with direct req/request.query/body/params property, optionally following a literal status code. Not receiver typing or data-flow analysis; computed keys, aliases and upstream validation need review.", + "family": "network-exposure", + "cwe": [ + "CWE-601" + ], + "review_priority": "normal", + "signal_kind": "syntactic-review", + "references": [ + "https://expressjs.com/en/4x/api.html#res.redirect" + ], + "introduced": "1.7.0", + "pattern": "\\b(?:res|response)\\s*\\.\\s*redirect\\s*\\(\\s*(?:[12345][0-9]{2}\\s*,\\s*)?(?:req|request)\\s*\\.\\s*(?:query|body|params)\\s*\\.\\s*[A-Za-z_]\\w*", + "code_only": true + }, + { + "id": "PHP-LDAP-FILTER", + "languages": [ + "php" + ], + "title": "LDAP filter concatenates a PHP variable", + "engine": "regex", + "before": "ldap_search($conn, $base, '(uid=' . $name . ')');", + "after": "$filter = '(uid=' . ldap_escape($name, '', LDAP_ESCAPE_FILTER) . ')';\nldap_search($conn, $base, $filter);", + "fix": "Escape values for LDAP filter context, not DN context; keep attribute names and search scope trusted.", + "check": "LDAP metacharacters in a value do not widen results; authorized lookups work.", + "doc": "docs/vulnerabilities/php.md#php-ldap-filter", + "reason": "Review signal: LDAP filter concatenates a PHP variable. A match is not proof of exploitability; validate the actual service contract.", + "detection": "Regex with lexical exclusions: ldap_search/list/read with simple first two arguments and a string concatenated directly with a variable as the third argument. Variables may already be escaped; prebuilt filters and interpolation need manual review.", + "limitations": "Regex with lexical exclusions: ldap_search/list/read with simple first two arguments and a string concatenated directly with a variable as the third argument. Variables may already be escaped; prebuilt filters and interpolation need manual review.", + "family": "injection", + "cwe": [ + "CWE-90" + ], + "review_priority": "normal", + "signal_kind": "syntactic-review", + "references": [ + "https://www.php.net/manual/en/function.ldap-escape.php" + ], + "introduced": "1.7.0", + "pattern": "\\bldap_(?:search|list|read)\\s*\\(\\s*[^,;\\n]{1,100},\\s*[^,;\\n]{1,100},\\s*['\"][^'\"\\n]{0,160}['\"]\\s*\\.\\s*\\$[A-Za-z_]\\w*", + "code_only": true + }, + { + "id": "GO-UPLOAD-PATH", + "languages": [ + "go" + ], + "title": "Multipart filename used directly in a joined path", + "engine": "regex", + "before": "path := filepath.Join(root, header.Filename)", + "after": "path := filepath.Join(root, serverGeneratedID)", + "fix": "Choose a non-overwriting server-side storage name outside executable/public roots; authorize downloads and enforce upload size/type.", + "check": "Alternate separators, traversal, collisions and other-owner requests cannot change the chosen storage path; ordinary uploads work.", + "doc": "docs/vulnerabilities/go.md#go-upload-path", + "reason": "Review signal: Multipart filename used directly in a joined path. A match is not proof of exploitability; validate the actual service contract.", + "detection": "Regex with lexical exclusions: filepath.Join with a simple first argument and a direct header/fileHeader/file.Filename second argument. The MIME parser may normalize filenames; the rule does not prove traversal, imported types or missing earlier validation.", + "limitations": "Regex with lexical exclusions: filepath.Join with a simple first argument and a direct header/fileHeader/file.Filename second argument. The MIME parser may normalize filenames; the rule does not prove traversal, imported types or missing earlier validation.", + "family": "file-access", + "cwe": [ + "CWE-22" + ], + "review_priority": "normal", + "signal_kind": "syntactic-review", + "references": [ + "https://pkg.go.dev/mime/multipart#FileHeader" + ], + "introduced": "1.7.0", + "pattern": "\\bfilepath\\s*\\.\\s*Join\\s*\\(\\s*[^,;\\n]{1,100},\\s*(?:header|fileHeader|file)\\s*\\.\\s*Filename\\s*\\)", + "code_only": true + }, + { + "id": "JAVA-LDAP-FILTER", + "languages": [ + "java" + ], + "title": "JNDI search filter assembled by concatenation", + "engine": "regex", + "before": "ctx.search(base, \"(uid=\" + name + \")\", controls);", + "after": "ctx.search(base, \"(uid={0})\", new Object[] { name }, controls);", + "fix": "Use JNDI filter arguments with a fixed filter, and retain explicit search scope and authorization.", + "check": "Filter metacharacters remain values; unauthorized entries stay inaccessible and valid searches work.", + "doc": "docs/vulnerabilities/java.md#java-ldap-filter", + "reason": "Review signal: JNDI search filter assembled by concatenation. A match is not proof of exploitability; validate the actual service contract.", + "detection": "Regex with lexical exclusions: ctx/context/dirContext.search with a simple first argument and directly concatenated string filter. Does not resolve receiver types, prebuilt filters, wrappers or earlier escaping.", + "limitations": "Regex with lexical exclusions: ctx/context/dirContext.search with a simple first argument and directly concatenated string filter. Does not resolve receiver types, prebuilt filters, wrappers or earlier escaping.", + "family": "injection", + "cwe": [ + "CWE-90" + ], + "review_priority": "normal", + "signal_kind": "syntactic-review", + "references": [ + "https://docs.oracle.com/javase/jndi/tutorial/ldap/search/search.html" + ], + "introduced": "1.7.0", + "pattern": "\\b(?:ctx|context|dirContext)\\s*\\.\\s*search\\s*\\(\\s*[^,;\\n]{1,100},\\s*\"[^\"\\n]{0,160}\"\\s*\\+\\s*[A-Za-z_]\\w*", + "code_only": true + }, + { + "id": "CS-LDAP-FILTER", + "languages": [ + "csharp" + ], + "title": "DirectorySearcher filter concatenates a value", + "engine": "regex", + "before": "var query = new DirectorySearcher(\"(uid=\" + name + \")\");", + "after": "var query = new DirectorySearcher(BuildReviewedLdapFilter(name)); // helper implements filter-context escaping", + "fix": "Use a reviewed LDAP filter builder with filter-context escaping and fixed attribute/scope policy; the helper is application-specific.", + "check": "Metacharacters cannot add conditions or broaden results; supported lookups remain compatible.", + "doc": "docs/vulnerabilities/csharp.md#cs-ldap-filter", + "reason": "Review signal: DirectorySearcher filter concatenates a value. A match is not proof of exploitability; validate the actual service contract.", + "detection": "Regex with lexical exclusions: new DirectorySearcher with a first string literal concatenated with an identifier. Does not inspect Filter assignments, interpolated strings, helper implementations or arbitrary type aliases.", + "limitations": "Regex with lexical exclusions: new DirectorySearcher with a first string literal concatenated with an identifier. Does not inspect Filter assignments, interpolated strings, helper implementations or arbitrary type aliases.", + "family": "injection", + "cwe": [ + "CWE-90" + ], + "review_priority": "normal", + "signal_kind": "syntactic-review", + "references": [ + "https://learn.microsoft.com/en-us/dotnet/api/system.directoryservices.directorysearcher.filter" + ], + "introduced": "1.7.0", + "pattern": "\\bnew\\s+(?:System\\.DirectoryServices\\.)?DirectorySearcher\\s*\\(\\s*\"[^\"\\n]{0,160}\"\\s*\\+\\s*[A-Za-z_]\\w*", + "code_only": true + }, + { + "id": "RUBY-REDIRECT-INPUT", + "languages": [ + "ruby" + ], + "title": "Rails redirect takes request params directly", + "engine": "regex", + "before": "redirect_to params[:next]", + "after": "redirect_to account_path", + "fix": "Use server-selected routes or an explicit redirect policy; preserve Rails' host checks and review the installed framework version.", + "check": "Foreign and scheme-relative destinations fail; legitimate navigation works.", + "doc": "docs/vulnerabilities/ruby.md#ruby-redirect-input", + "reason": "Review signal: Rails redirect takes request params directly. A match is not proof of exploitability; validate the actual service contract.", + "detection": "Regex with lexical exclusions: redirect_to with params[...] or request.params[...], with optional opening parenthesis. Framework defaults may already reject external hosts; aliases, helpers and allow_other_host configuration need review.", + "limitations": "Regex with lexical exclusions: redirect_to with params[...] or request.params[...], with optional opening parenthesis. Framework defaults may already reject external hosts; aliases, helpers and allow_other_host configuration need review.", + "family": "network-exposure", + "cwe": [ + "CWE-601" + ], + "review_priority": "normal", + "signal_kind": "syntactic-review", + "references": [ + "https://api.rubyonrails.org/classes/ActionController/Redirecting.html" + ], + "introduced": "1.7.0", + "pattern": "\\bredirect_to\\s*(?:\\(\\s*)?(?:request\\s*\\.\\s*)?params\\s*\\[", + "code_only": true + }, + { + "id": "RUST-UNBOUNDED-READ", + "languages": [ + "rust" + ], + "title": "Potentially unbounded Rust stream read", + "engine": "regex", + "before": "stream.read_to_end(&mut payload)?;", + "after": "let mut bounded = stream.take(MAX_BYTES + 1);\nbounded.read_to_end(&mut payload)?;\nif payload.len() as u64 > MAX_BYTES { return Err(too_large()); }", + "fix": "Bound reads, detect limit+1 and enforce an appropriate timeout; Read::take alone silently stops at its limit.", + "check": "Test EOF, limit-1, limit, limit+1 and a slow never-ending source; valid maximum documents work.", + "doc": "docs/vulnerabilities/rust.md#rust-unbounded-read", + "reason": "Review signal: Potentially unbounded Rust stream read. A match is not proof of exploitability; validate the actual service contract.", + "detection": "Regex with lexical exclusions: stream/socket/request/reader.read_to_end/read_to_string. Receiver names are hints, not types; an already bounded receiver may match and other names/wrappers may be missed.", + "limitations": "Regex with lexical exclusions: stream/socket/request/reader.read_to_end/read_to_string. Receiver names are hints, not types; an already bounded receiver may match and other names/wrappers may be missed.", + "family": "resource-limits", + "cwe": [ + "CWE-400" + ], + "review_priority": "normal", + "signal_kind": "syntactic-review", + "references": [ + "https://doc.rust-lang.org/std/io/trait.Read.html#method.take" + ], + "introduced": "1.7.0", + "pattern": "\\b(?:stream|socket|request|reader)\\s*\\.\\s*read_to_(?:end|string)\\s*\\(", + "code_only": true + }, + { + "id": "C-COPY-LENGTH", + "languages": [ + "native" + ], + "title": "Copy length comes directly from source strlen", + "engine": "regex", + "before": "memcpy(dest, input, strlen(input) + 1);", + "after": "size_t n = validated_length;\nif (n >= capacity) return ERROR;\nmemcpy(dest, input, n + 1);", + "fix": "Validate readable source length and destination capacity before copying, including terminator and arithmetic overflow.", + "check": "Test empty input, capacity boundaries, missing terminator and overflow using sanitizers where available.", + "doc": "docs/vulnerabilities/c-cpp.md#c-copy-length", + "reason": "Review signal: Copy length comes directly from source strlen. A match is not proof of exploitability; validate the actual service contract.", + "detection": "Regex with lexical exclusions: memcpy/memmove with simple first two arguments and strlen/strnlen directly as length. Does not prove missing preceding checks or actual buffer sizes; custom same-named APIs and macros require review.", + "limitations": "Regex with lexical exclusions: memcpy/memmove with simple first two arguments and strlen/strnlen directly as length. Does not prove missing preceding checks or actual buffer sizes; custom same-named APIs and macros require review.", + "family": "memory-safety", + "cwe": [ + "CWE-787" + ], + "review_priority": "normal", + "signal_kind": "syntactic-review", + "references": [ + "https://pubs.opengroup.org/onlinepubs/9799919799/functions/memcpy.html" + ], + "introduced": "1.7.0", + "pattern": "\\b(?:memcpy|memmove)\\s*\\(\\s*[^,;\\n]{1,100},\\s*[^,;\\n]{1,100},\\s*(?:strlen|strnlen)\\s*\\(", + "code_only": true + }, + { + "id": "CFG-COOKIE-FLAGS", + "languages": [ + "config", + "python", + "javascript" + ], + "title": "Explicitly weakened session cookie flags", + "engine": "regex", + "before": "SESSION_COOKIE_HTTPONLY = False", + "after": "SESSION_COOKIE_HTTPONLY = True", + "fix": "Keep session cookies HttpOnly and use Secure where the approved service transport supports HTTPS; changing Secure on an HTTP-only checker requires a coordinated transport decision.", + "check": "Scripts cannot read session cookies; sessions work over the intended transport and secure cookies are not sent over plaintext.", + "doc": "docs/vulnerabilities/configuration.md#cfg-cookie-flags", + "reason": "Review signal: explicitly weakened session cookie flags. Check the real framework and transport contract before patching.", + "detection": "Regex with lexical exclusions: bare Django SESSION_COOKIE_HTTPONLY/SESSION_COOKIE_SECURE/CSRF_COOKIE_SECURE=false/0. Python AST: known Flask config subscript/update/from_mapping with disabled session HttpOnly/Secure. JS bounded tokens: default imported express-session with inline cookie.httpOnly:false. Dynamic configs/defaults remain manual. JS secure:false alone is not a new signal; HTTPS/checker compatibility must be reviewed.", + "limitations": "Regex with lexical exclusions: bare Django SESSION_COOKIE_HTTPONLY/SESSION_COOKIE_SECURE/CSRF_COOKIE_SECURE=false/0. Python AST: known Flask config subscript/update/from_mapping with disabled session HttpOnly/Secure. JS bounded tokens: default imported express-session with inline cookie.httpOnly:false. Dynamic configs/defaults remain manual. JS secure:false alone is not a new signal; HTTPS/checker compatibility must be reviewed.", + "family": "authentication", + "cwe": [ + "CWE-614", + "CWE-1004" + ], + "review_priority": "normal", + "signal_kind": "configuration-review", + "references": [ + "https://docs.djangoproject.com/en/5.2/ref/settings/#session-cookie-httponly", + "https://flask.palletsprojects.com/en/stable/config/", + "https://expressjs.com/en/resources/middleware/session/" + ], + "introduced": "1.7.0", + "pattern": "\\b(?:SESSION_COOKIE_HTTPONLY|SESSION_COOKIE_SECURE|CSRF_COOKIE_SECURE)\\s*[:=]\\s*(?:false|0)\\b", + "code_only": true, + "coverage_required": [ + "python", + "javascript" + ] + }, + { + "id": "CFG-DOCKER-TCP", + "languages": [ + "shell", + "docker" + ], + "title": "Docker daemon listens on every TCP interface", + "engine": "regex", + "before": "dockerd -H tcp://0.0.0.0:2375", + "after": "dockerd -H unix:///var/run/docker.sock", + "fix": "Prefer local Docker access. Required remote management needs authenticated encrypted transport and a deliberately restricted management interface; never publish it as a team UI.", + "check": "Unapproved LAN clients cannot control Docker; approved administration remains possible without exposing credentials.", + "doc": "docs/vulnerabilities/configuration.md#cfg-docker-tcp", + "reason": "Review signal: Docker daemon listens on every TCP interface. A match is not proof of exploitability; validate the actual service contract.", + "detection": "Regex with lexical exclusions: dockerd followed on the same line by -H/--host tcp://0.0.0.0 or [::]. Does not evaluate TLS flags, JSON daemon configuration, named interfaces or shell expansions; a TLS-protected listener still requires review.", + "limitations": "Regex with lexical exclusions: dockerd followed on the same line by -H/--host tcp://0.0.0.0 or [::]. Does not evaluate TLS flags, JSON daemon configuration, named interfaces or shell expansions; a TLS-protected listener still requires review.", + "family": "container-isolation", + "cwe": [], + "review_priority": "normal", + "signal_kind": "configuration-review", + "references": [ + "https://docs.docker.com/reference/cli/dockerd/#daemon-socket-option" + ], + "introduced": "1.7.0", + "pattern": "\\bdockerd\\b[^\\n;]{0,200}?(?:-H[ =]*|--host[ =]+)tcp://(?:0\\.0\\.0\\.0|\\[::\\]):[0-9]{1,5}\\b", + "code_only": true + }, + { + "id": "CFG-FLOATING-IMAGE", + "languages": [ + "docker", + "config" + ], + "title": "Explicit latest image tag", + "engine": "regex", + "before": "FROM example.invalid/app:latest", + "after": "FROM example.invalid/app@sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "fix": "Record the approved source version and architecture-specific image digest; populate the offline image inventory and verify imported images.", + "check": "Repeated offline starts use the approved bytes and architecture; no implicit pull or latest fallback occurs.", + "doc": "docs/vulnerabilities/configuration.md#cfg-floating-image", + "reason": "Review signal: Explicit latest image tag. A match is not proof of exploitability; validate the actual service contract.", + "detection": "Regex with lexical exclusions: Docker FROM or a bare YAML image key using an unquoted image:latest with no digest. Quoted YAML, untagged images, other mutable tags, ARG expansion and resolved architecture need deployment-model audit.", + "limitations": "Regex with lexical exclusions: Docker FROM or a bare YAML image key using an unquoted image:latest with no digest. Quoted YAML, untagged images, other mutable tags, ARG expansion and resolved architecture need deployment-model audit.", + "family": "container-isolation", + "cwe": [], + "review_priority": "normal", + "signal_kind": "configuration-review", + "references": [ + "https://docs.docker.com/reference/dockerfile/#from" + ], + "introduced": "1.7.0", + "pattern": "^[ \\t]*(?:FROM[ \\t]+(?:--platform=\\S+[ \\t]+)?|image[ \\t]*:[ \\t]*)[A-Za-z0-9][A-Za-z0-9./_:-]{0,200}:latest(?=\\s|$)", + "language_patterns": { + "docker": "^[ \\t]*FROM[ \\t]+(?:--platform=\\S+[ \\t]+)?[A-Za-z0-9][A-Za-z0-9./_:-]{0,200}:latest(?=\\s|$)", + "config": "^[ \\t]*image[ \\t]*:[ \\t]*[A-Za-z0-9][A-Za-z0-9./_:-]{0,200}:latest(?=\\s|$)" + }, + "code_only": true + }, + { + "id": "SQL-RLS-ALLOW-ALL", + "languages": [ + "sql" + ], + "title": "RLS policy has an unconditional expression", + "engine": "regex", + "before": "CREATE POLICY open_notes ON notes USING (true);", + "after": "CREATE POLICY owned_notes ON notes USING (owner_id = current_user);", + "fix": "Define role/tenant-aware USING and WITH CHECK expressions for the actual identity model; review permissive-policy combinations and bypass roles.", + "check": "Two runtime identities cannot read/change each other's rows; inserts and updates enforce the intended owner and valid operations work.", + "doc": "docs/vulnerabilities/sql.md#sql-rls-allow-all", + "reason": "Review signal: RLS policy has an unconditional expression. A match is not proof of exploitability; validate the actual service contract.", + "detection": "Regex with lexical exclusions: USING(true) or WITH CHECK(true). May be intentional and does not associate expressions with CREATE POLICY, roles or commands; effective policies and application authorization require review.", + "limitations": "Regex with lexical exclusions: USING(true) or WITH CHECK(true). May be intentional and does not associate expressions with CREATE POLICY, roles or commands; effective policies and application authorization require review.", + "family": "authentication", + "cwe": [ + "CWE-863" + ], + "review_priority": "normal", + "signal_kind": "syntactic-review", + "references": [ + "https://www.postgresql.org/docs/current/sql-createpolicy.html" + ], + "introduced": "1.7.0", + "pattern": "\\b(?:USING|WITH\\s+CHECK)\\s*\\(\\s*true\\s*\\)", + "code_only": true + }, + { + "id": "TPL-AUTOESCAPE-OFF", + "languages": [ + "template" + ], + "title": "Template block disables autoescaping", + "engine": "regex", + "before": "{% autoescape false %}{{ message }}{% endautoescape %}", + "after": "{{ message }}", + "fix": "Retain autoescaping for untrusted text; sanitize supported HTML explicitly and review the output context.", + "check": "User tags/attributes remain data and allowed formatting still works.", + "doc": "docs/vulnerabilities/configuration.md#tpl-autoescape-off", + "reason": "Review signal: Template block disables autoescaping. A match is not proof of exploitability; validate the actual service contract.", + "detection": "Regex excluding HTML/Jinja comments: Jinja/Twig autoescape false and Django autoescape off blocks. Does not evaluate template engine defaults, enclosing blocks or whether values are trusted.", + "limitations": "Regex excluding HTML/Jinja comments: Jinja/Twig autoescape false and Django autoescape off blocks. Does not evaluate template engine defaults, enclosing blocks or whether values are trusted.", + "family": "injection", + "cwe": [ + "CWE-79" + ], + "review_priority": "normal", + "signal_kind": "syntactic-review", + "references": [ + "https://jinja.palletsprojects.com/en/stable/templates/#autoescape-overrides" + ], + "introduced": "1.7.0", + "pattern": "\\{%\\s*autoescape\\s+(?:false|off)\\s*%\\}", + "code_only": true + }, + { + "id": "JS-LOG-CREDENTIALS", + "languages": [ + "javascript" + ], + "title": "Credential-like value passed directly to console", + "engine": "javascript-tokens", + "before": "console.warn(req.headers.authorization);", + "after": "console.warn('authentication failed');", + "fix": "Log stable event categories and approved identifiers, not credential values. Inspect failed-login and exception paths; implement and test any redaction helper independently.", + "check": "Synthetic canary credentials never appear in stdout, logs, exported evidence or screen broadcasts; failure categories remain useful.", + "doc": "docs/vulnerabilities/javascript.md#js-log-credentials", + "reason": "Review signal: a credential-like value is logged directly. This does not prove that the value is a real secret.", + "detection": "Bounded JS tokens: console log/info/warn/error/debug/trace with direct sensitive names/properties, inline object/array values or concatenation. Observed console shadows/reassignments suppress hints file-wide. Templates, helper calls, custom loggers, dynamic keys and cross-file flows remain manual; absence of a signal does not verify redaction.", + "family": "secret-handling", + "cwe": [ + "CWE-532" + ], + "review_priority": "normal", + "signal_kind": "syntactic-review", + "references": [ + "https://nodejs.org/api/console.html" + ], + "introduced": "1.8.0", + "limitations": "Bounded JS tokens: console log/info/warn/error/debug/trace with direct sensitive names/properties, inline object/array values or concatenation. Observed console shadows/reassignments suppress hints file-wide. Templates, helper calls, custom loggers, dynamic keys and cross-file flows remain manual; absence of a signal does not verify redaction." + }, + { + "id": "SQL-SERVER-ROLE", + "languages": [ + "sql" + ], + "title": "PostgreSQL server file/program role granted", + "engine": "regex", + "before": "GRANT pg_read_server_files TO app;", + "after": "GRANT SELECT ON notes TO app;", + "fix": "Separate application and administrator roles. Grant only required object privileges, not server file/program access; review memberships and revoke only approved service-owned grants with rollback.", + "check": "The actual runtime role cannot read/write server files or execute server programs; ordinary queries, migrations and recovery still work.", + "doc": "docs/vulnerabilities/sql.md#sql-server-role", + "reason": "Review signal: an elevated PostgreSQL server role is granted. Review the recipient and its actual runtime privileges.", + "detection": "Bounded SQL: unquoted GRANT role lists containing pg_read_server_files, pg_write_server_files or pg_execute_server_program before TO. Comments/strings excluded; REVOKE and pg_monitor alone do not signal. Quoted roles, inheritance, later revocations, versions and effective permissions remain manual.", + "family": "authentication", + "cwe": [ + "CWE-250" + ], + "review_priority": "high", + "signal_kind": "configuration-review", + "references": [ + "https://www.postgresql.org/docs/14/predefined-roles.html" + ], + "introduced": "1.8.0", + "pattern": "\\bGRANT\\s+(?:[a-z_][\\w$]*\\s*,\\s*){0,20}(?:pg_read_server_files|pg_write_server_files|pg_execute_server_program)\\b(?:\\s*,\\s*[a-z_][\\w$]*){0,20}\\s+TO\\s+", + "code_only": true, + "limitations": "Bounded SQL: unquoted GRANT role lists containing pg_read_server_files, pg_write_server_files or pg_execute_server_program before TO. Comments/strings excluded; REVOKE and pg_monitor alone do not signal. Quoted roles, inheritance, later revocations, versions and effective permissions remain manual." + } + ] +} diff --git a/schemas/approved-drift.v1.schema.json b/schemas/approved-drift.v1.schema.json new file mode 100644 index 0000000..7f7adbc --- /dev/null +++ b/schemas/approved-drift.v1.schema.json @@ -0,0 +1,63 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "urn:durkahelper:schema:approved-drift:v1", + "title": "DurkaHelper reviewed approved drift v1", + "type": "object", + "additionalProperties": false, + "required": [ + "schema", + "id", + "reviewed_at", + "baseline_sha256", + "current_sha256", + "drift" + ], + "properties": { + "schema": {"const": "durkahelper.approved-drift.v1"}, + "id": { + "type": "string", + "minLength": 8, + "maxLength": 128, + "pattern": "^[A-Za-z0-9][A-Za-z0-9._:-]*$" + }, + "reviewed_at": {"type": "string", "format": "date-time"}, + "baseline_sha256": {"type": "string", "pattern": "^[0-9a-f]{64}$"}, + "current_sha256": {"type": "string", "pattern": "^[0-9a-f]{64}$"}, + "drift": { + "type": "object", + "additionalProperties": false, + "required": [ + "adapters_changed", + "files_added", + "files_content_changed", + "files_metadata_changed", + "files_removed" + ], + "properties": { + "adapters_changed": { + "type": "array", + "uniqueItems": true, + "items": {"enum": ["platform", "processes", "listeners", "services", "compose"]} + }, + "files_added": {"$ref": "#/$defs/paths"}, + "files_content_changed": {"$ref": "#/$defs/paths"}, + "files_metadata_changed": {"$ref": "#/$defs/paths"}, + "files_removed": {"$ref": "#/$defs/paths"} + } + } + }, + "$defs": { + "paths": { + "type": "array", + "maxItems": 100000, + "uniqueItems": true, + "$comment": "Runtime additionally requires sorted, NFC, portable relative POSIX paths.", + "items": { + "type": "string", + "minLength": 1, + "maxLength": 1024, + "pattern": "^(?!/)(?!.*(?:^|/)\\.\\.(?:/|$))(?!.*\\\\)(?!.*:)[^/]+(?:/[^/]+)*$" + } + } + } +} diff --git a/schemas/backup-manifest.v1.schema.json b/schemas/backup-manifest.v1.schema.json new file mode 100644 index 0000000..3dca39b --- /dev/null +++ b/schemas/backup-manifest.v1.schema.json @@ -0,0 +1,61 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "urn:durkahelper:schema:backup-manifest:v1", + "title": "DurkaHelper backup manifest v1", + "type": "object", + "additionalProperties": false, + "required": ["schema", "tool", "created_at", "profile", "root", "entries", "summary", "bundle_sha256"], + "properties": { + "schema": {"const": "durkahelper.backup-manifest.v1"}, + "tool": {"$ref": "#/$defs/tool"}, + "created_at": {"type": "string", "format": "date-time"}, + "profile": {"$ref": "#/$defs/profileRef"}, + "root": {"type": "string", "pattern": "^sha256:[0-9a-f]{64}$"}, + "entries": { + "type": "array", "minItems": 1, "maxItems": 100000, + "items": { + "type": "object", "additionalProperties": false, + "required": ["source", "stored", "kind", "size", "sha256", "mode", "mtime_ns"], + "properties": { + "source": {"$ref": "#/$defs/portablePathOrDot"}, + "stored": {"type": "string", "pattern": "^files/[0-9]{6}\\.bin$"}, + "kind": {"enum": ["file", "tree", "native_dump"]}, + "size": {"type": "integer", "minimum": 0, "maximum": 4294967296}, + "sha256": {"type": "string", "pattern": "^[0-9a-f]{64}$"}, + "mode": {"type": "integer", "minimum": 0, "maximum": 4095}, + "mtime_ns": {"type": "integer", "minimum": 0, "maximum": 253402300799999999999} + } + } + }, + "summary": { + "type": "object", "additionalProperties": false, + "required": ["files", "total_bytes"], + "properties": { + "files": {"type": "integer", "minimum": 1, "maximum": 100000}, + "total_bytes": {"type": "integer", "minimum": 0, "maximum": 107374182400} + } + }, + "bundle_sha256": {"type": "string", "pattern": "^[0-9a-f]{64}$"} + }, + "$defs": { + "tool": { + "type": "object", "additionalProperties": false, "required": ["name", "version"], + "properties": { + "name": {"const": "DurkaHelper defense_ops"}, + "version": {"type": "string", "pattern": "^[0-9]+\\.[0-9]+\\.[0-9]+(?:[-+][0-9A-Za-z.-]+)?$"} + } + }, + "profileRef": { + "type": "object", "additionalProperties": false, "required": ["name", "sha256"], + "properties": { + "name": {"type": "string", "minLength": 1, "maxLength": 120}, + "sha256": {"type": "string", "pattern": "^[0-9a-f]{64}$"} + } + }, + "portablePathOrDot": { + "$comment": "The runtime additionally enforces NFC, case-fold uniqueness, reserved-device names, and deterministic ordering.", + "type": "string", "minLength": 1, "maxLength": 1024, + "pattern": "^(?:\\.|(?!/)(?!.*(?:^|/)\\.\\.(?:/|$))(?!.*(?:^|/)(?:[Cc][Oo][Nn]|[Pp][Rr][Nn]|[Aa][Uu][Xx]|[Nn][Uu][Ll]|[Cc][Oo][Mm][1-9]|[Ll][Pp][Tt][1-9])(?:[ .]*\\.[^/]*)?(?:/|$))(?!.*\\\\)(?!.*:)(?!.*[<>\"|?*])(?!.+(?:[. ])(?:/|$))[^/]+(?:/[^/]+)*)$" + } + } +} diff --git a/schemas/comparison.v1.schema.json b/schemas/comparison.v1.schema.json new file mode 100644 index 0000000..4539a43 --- /dev/null +++ b/schemas/comparison.v1.schema.json @@ -0,0 +1,81 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "urn:durkahelper:schema:comparison:v1", + "title": "DurkaHelper snapshot comparison v1", + "type": "object", + "additionalProperties": false, + "required": ["schema", "tool", "compared_at", "baseline", "current", "profile", "scope", "comparable", "partial", "reasons", "drift", "summary", "exit_code"], + "properties": { + "schema": {"const": "durkahelper.comparison.v1"}, + "tool": {"$ref": "#/$defs/tool"}, + "compared_at": {"type": "string", "format": "date-time"}, + "baseline": {"$ref": "#/$defs/input"}, + "current": {"$ref": "#/$defs/input"}, + "profile": {"$ref": "#/$defs/profileRef"}, + "scope": { + "type": "object", "additionalProperties": false, + "required": ["baseline_sha256", "current_sha256"], + "properties": { + "baseline_sha256": {"type": "string", "pattern": "^[0-9a-f]{64}$"}, + "current_sha256": {"type": "string", "pattern": "^[0-9a-f]{64}$"} + } + }, + "comparable": {"type": "boolean"}, + "partial": {"type": "boolean"}, + "reasons": {"type": "array", "maxItems": 16, "uniqueItems": true, "items": {"type": "string", "minLength": 1, "maxLength": 120}}, + "drift": { + "type": "object", "additionalProperties": false, + "required": ["adapters_changed", "files_added", "files_content_changed", "files_metadata_changed", "files_removed"], + "properties": { + "adapters_changed": {"type": "array", "uniqueItems": true, "items": {"enum": ["platform", "processes", "listeners", "services"]}}, + "files_added": {"$ref": "#/$defs/paths"}, + "files_content_changed": {"$ref": "#/$defs/paths"}, + "files_metadata_changed": {"$ref": "#/$defs/paths"}, + "files_removed": {"$ref": "#/$defs/paths"} + } + }, + "summary": { + "type": "object", "additionalProperties": false, + "required": ["adapter_changes", "drift_count", "files_added", "files_content_changed", "files_metadata_changed", "files_removed"], + "properties": { + "adapter_changes": {"type": "integer", "minimum": 0}, + "drift_count": {"type": "integer", "minimum": 0}, + "files_added": {"type": "integer", "minimum": 0}, + "files_content_changed": {"type": "integer", "minimum": 0}, + "files_metadata_changed": {"type": "integer", "minimum": 0}, + "files_removed": {"type": "integer", "minimum": 0} + } + }, + "exit_code": {"enum": [0, 1, 2]} + }, + "$defs": { + "tool": { + "type": "object", "additionalProperties": false, "required": ["name", "version"], + "properties": { + "name": {"const": "DurkaHelper defense_ops"}, + "version": {"type": "string", "pattern": "^[0-9]+\\.[0-9]+\\.[0-9]+(?:[-+][0-9A-Za-z.-]+)?$"} + } + }, + "profileRef": { + "type": "object", "additionalProperties": false, "required": ["name", "sha256"], + "properties": { + "name": {"type": "string", "minLength": 1, "maxLength": 120}, + "sha256": {"type": "string", "pattern": "^[0-9a-f]{64}$"} + } + }, + "input": { + "type": "object", "additionalProperties": false, "required": ["created_at", "sha256"], + "properties": { + "created_at": {"type": "string", "format": "date-time"}, + "sha256": {"type": "string", "pattern": "^[0-9a-f]{64}$"} + } + }, + "paths": { + "type": "array", "maxItems": 100000, "uniqueItems": true, + "items": { + "type": "string", "minLength": 1, "maxLength": 1024, + "pattern": "^(?!/)(?!.*(?:^|/)\\.\\.(?:/|$))(?!.*(?:^|/)(?:[Cc][Oo][Nn]|[Pp][Rr][Nn]|[Aa][Uu][Xx]|[Nn][Uu][Ll]|[Cc][Oo][Mm][1-9]|[Ll][Pp][Tt][1-9])(?:[ .]*\\.[^/]*)?(?:/|$))(?!.*\\\\)(?!.*:)(?!.*[<>\"|?*])(?!.+(?:[. ])(?:/|$))[^/]+(?:/[^/]+)*$" + } + } + } +} diff --git a/schemas/deployment-audit.v1.schema.json b/schemas/deployment-audit.v1.schema.json new file mode 100644 index 0000000..b20451f --- /dev/null +++ b/schemas/deployment-audit.v1.schema.json @@ -0,0 +1,126 @@ +{ + "type": "object", + "additionalProperties": false, + "required": [ + "schema", + "checked_at", + "scope", + "model_sha256", + "policy_sha256", + "source_sha256", + "services", + "findings", + "issues", + "status", + "exit_code" + ], + "properties": { + "schema": { + "const": "durkahelper.deployment-audit.v1" + }, + "checked_at": { + "type": "string", + "format": "date-time" + }, + "scope": { + "const": "declared-model-only" + }, + "model_sha256": { + "type": "string", + "pattern": "^[0-9a-f]{64}$" + }, + "policy_sha256": { + "type": "string", + "pattern": "^[0-9a-f]{64}$" + }, + "source_sha256": { + "type": "string", + "pattern": "^[0-9a-f]{64}$" + }, + "services": { + "type": "integer", + "minimum": 1, + "maximum": 64 + }, + "findings": { + "type": "array", + "items": { + "type": "object", + "additionalProperties": false, + "required": [ + "service_sha256", + "check", + "kind" + ], + "properties": { + "service_sha256": { + "type": "string", + "pattern": "^[0-9a-f]{64}$" + }, + "check": { + "type": "string", + "maxLength": 80 + }, + "kind": { + "enum": [ + "deployment", + "security", + "availability", + "coverage" + ] + } + } + }, + "maxItems": 4096 + }, + "issues": { + "type": "array", + "items": { + "type": "object", + "additionalProperties": false, + "required": [ + "service_sha256", + "check", + "kind" + ], + "properties": { + "service_sha256": { + "type": "string", + "pattern": "^[0-9a-f]{64}$" + }, + "check": { + "type": "string", + "maxLength": 80 + }, + "kind": { + "enum": [ + "deployment", + "security", + "availability", + "coverage" + ] + } + } + }, + "maxItems": 4096 + }, + "status": { + "enum": [ + "pass", + "fail", + "partial" + ] + }, + "exit_code": { + "enum": [ + 0, + 1, + 2 + ] + } + }, + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "urn:durkahelper:schema:deployment-audit:v1", + "title": "Sanitized model-only audit", + "$comment": "Runtime enforces allowed check IDs and consistency between issues/findings/status/exit_code. Model/policy are recomputed when used by patch-check." +} diff --git a/schemas/deployment-model.v1.schema.json b/schemas/deployment-model.v1.schema.json new file mode 100644 index 0000000..ba44216 --- /dev/null +++ b/schemas/deployment-model.v1.schema.json @@ -0,0 +1,244 @@ +{ + "type": "object", + "additionalProperties": false, + "required": [ + "schema", + "source_sha256", + "platform", + "services" + ], + "properties": { + "schema": { + "const": "durkahelper.deployment-model.v1" + }, + "source_sha256": { + "type": "string", + "pattern": "^[0-9a-f]{64}$" + }, + "platform": { + "type": "object", + "additionalProperties": false, + "required": [ + "os", + "architecture", + "runtime" + ], + "properties": { + "os": { + "enum": [ + "linux", + "darwin" + ] + }, + "architecture": { + "enum": [ + "amd64", + "arm64" + ] + }, + "runtime": { + "enum": [ + "docker-engine", + "docker-desktop" + ] + } + } + }, + "services": { + "type": "array", + "items": { + "type": "object", + "additionalProperties": false, + "required": [ + "id", + "role", + "image", + "architectures", + "mode", + "ports", + "mounts", + "privileged", + "network_mode", + "capabilities", + "nonroot", + "healthcheck", + "memory_limit_mb", + "cpu_limit", + "restart" + ], + "properties": { + "id": { + "type": "string", + "pattern": "^[a-z0-9][a-z0-9_.-]{0,63}$" + }, + "role": { + "enum": [ + "ui", + "api", + "backend", + "worker", + "capture" + ] + }, + "image": { + "type": "string", + "maxLength": 256, + "pattern": "^[a-z0-9][a-z0-9._/:@-]*$" + }, + "architectures": { + "type": "array", + "items": { + "enum": [ + "amd64", + "arm64" + ] + }, + "maxItems": 2, + "uniqueItems": true + }, + "mode": { + "enum": [ + "none", + "file", + "live" + ] + }, + "ports": { + "type": "array", + "items": { + "type": "object", + "additionalProperties": false, + "required": [ + "host_port", + "container_port", + "protocol", + "host_ip" + ], + "properties": { + "host_port": { + "type": "integer", + "minimum": 1, + "maximum": 65535 + }, + "container_port": { + "type": "integer", + "minimum": 1, + "maximum": 65535 + }, + "protocol": { + "enum": [ + "tcp", + "udp" + ] + }, + "host_ip": { + "type": "string", + "maxLength": 45 + } + } + }, + "maxItems": 128 + }, + "mounts": { + "type": "array", + "items": { + "type": "object", + "additionalProperties": false, + "required": [ + "kind", + "target", + "source_scope", + "read_only" + ], + "properties": { + "kind": { + "enum": [ + "bind", + "volume", + "tmpfs" + ] + }, + "target": { + "type": "string", + "maxLength": 1024, + "pattern": "^/" + }, + "source_scope": { + "enum": [ + "approved-data", + "approved-config", + "outside", + "socket", + "host-root", + "unknown" + ] + }, + "read_only": { + "type": "boolean" + } + } + }, + "maxItems": 64 + }, + "privileged": { + "type": "boolean" + }, + "network_mode": { + "enum": [ + "bridge", + "host", + "none" + ] + }, + "capabilities": { + "type": "array", + "items": { + "type": "string", + "pattern": "^(CAP_)?[A-Z][A-Z0-9_]{0,63}$" + }, + "maxItems": 64 + }, + "nonroot": { + "type": [ + "boolean", + "null" + ] + }, + "healthcheck": { + "type": "boolean" + }, + "memory_limit_mb": { + "type": [ + "integer", + "null" + ], + "minimum": 1, + "maximum": 1048576 + }, + "cpu_limit": { + "type": [ + "number", + "null" + ], + "exclusiveMinimum": 0, + "maximum": 1024 + }, + "restart": { + "enum": [ + "no", + "always", + "on-failure", + "unless-stopped" + ] + } + } + }, + "maxItems": 64, + "minItems": 1 + } + }, + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "urn:durkahelper:schema:deployment-model:v1", + "title": "Declared deployment metadata; never runtime proof", + "$comment": "Runtime additionally requires canonical literal IPs, unique service ids, safe mount paths, and no secret or command fields." +} diff --git a/schemas/deployment-policy.v1.schema.json b/schemas/deployment-policy.v1.schema.json new file mode 100644 index 0000000..a99138d --- /dev/null +++ b/schemas/deployment-policy.v1.schema.json @@ -0,0 +1,104 @@ +{ + "type": "object", + "additionalProperties": false, + "required": [ + "schema", + "team_lan", + "approved_bind_addresses", + "approved_publications", + "approved_images", + "require_healthcheck", + "require_resource_limits", + "require_nonroot", + "require_restart", + "allow_amd64_emulation", + "approved_live_capture" + ], + "properties": { + "schema": { + "const": "durkahelper.deployment-policy.v1" + }, + "team_lan": { + "type": "boolean" + }, + "approved_bind_addresses": { + "type": "array", + "items": { + "type": "string", + "maxLength": 45 + }, + "maxItems": 128 + }, + "approved_publications": { + "type": "array", + "items": { + "type": "object", + "additionalProperties": false, + "required": [ + "host_port", + "container_port", + "protocol", + "service" + ], + "properties": { + "host_port": { + "type": "integer", + "minimum": 1, + "maximum": 65535 + }, + "container_port": { + "type": "integer", + "minimum": 1, + "maximum": 65535 + }, + "protocol": { + "enum": [ + "tcp", + "udp" + ] + }, + "service": { + "type": "string", + "pattern": "^[a-z0-9][a-z0-9_.-]{0,63}$" + } + } + }, + "maxItems": 128 + }, + "approved_images": { + "type": "array", + "items": { + "type": "string", + "maxLength": 256, + "pattern": "(?:@|^)sha256:[0-9a-f]{64}$" + }, + "maxItems": 128 + }, + "require_healthcheck": { + "type": "boolean" + }, + "require_resource_limits": { + "type": "boolean" + }, + "require_nonroot": { + "type": "boolean" + }, + "require_restart": { + "type": "boolean" + }, + "allow_amd64_emulation": { + "type": "boolean" + }, + "approved_live_capture": { + "type": "array", + "items": { + "type": "string", + "pattern": "^[a-z0-9][a-z0-9_.-]{0,63}$" + }, + "maxItems": 128 + } + }, + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "urn:durkahelper:schema:deployment-policy:v1", + "title": "Explicit deployment audit policy" +} diff --git a/schemas/event.v1.schema.json b/schemas/event.v1.schema.json new file mode 100644 index 0000000..6039a65 --- /dev/null +++ b/schemas/event.v1.schema.json @@ -0,0 +1,37 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "urn:durkahelper:schema:event:v1", + "title": "DurkaHelper normalized defense event v1", + "type": "object", + "additionalProperties": false, + "required": ["schema", "timestamp", "source", "kind", "severity", "summary"], + "properties": { + "schema": {"const": "durkahelper.event.v1"}, + "id": {"type": "string", "minLength": 1, "maxLength": 128, "pattern": "^[A-Za-z0-9][A-Za-z0-9._:-]*$"}, + "timestamp": {"type": "string", "format": "date-time"}, + "source": {"type": "string", "minLength": 1, "maxLength": 120}, + "kind": {"type": "string", "pattern": "^[a-z0-9][a-z0-9_.-]{0,63}$"}, + "severity": {"enum": ["info", "low", "medium", "high", "critical"]}, + "summary": {"type": "string", "minLength": 1, "maxLength": 512}, + "attributes": {"$ref": "#/$defs/attributes"} + }, + "$defs": { + "attributes": { + "type": "object", + "maxProperties": 64, + "propertyNames": { + "minLength": 1, + "maxLength": 64, + "not": {"pattern": "(?:[Pp][Aa][Ss][Ss][Ww][Oo][Rr][Dd]|[Pp][Aa][Ss][Ss][Ww][Dd]|[Pp][Ww][Dd]|[Ss][Ee][Cc][Rr][Ee][Tt]|[Tt][Oo][Kk][Ee][Nn]|[Cc][Rr][Ee][Dd][Ee][Nn][Tt][Ii][Aa][Ll]|[Aa][Uu][Tt][Hh][Oo][Rr][Ii][Zz][Aa][Tt][Ii][Oo][Nn]|[Cc][Oo][Oo][Kk][Ii][Ee]|[Pp][Rr][Ii][Vv][Aa][Tt][Ee].?[Kk][Ee][Yy]|[Aa][Pp][Ii].?[Kk][Ee][Yy]|[Aa][Cc][Cc][Ee][Ss][Ss].?[Kk][Ee][Yy]|[Ss][Ee][Ss][Ss][Ii][Oo][Nn]|[Dd][Ss][Nn]|[Cc][Oo][Nn][Nn][Ee][Cc][Tt][Ii][Oo][Nn].?[Ss][Tt][Rr][Ii][Nn][Gg]|[Cc][Oo][Mm][Mm][Aa][Nn][Dd]|[Ee][Xx][Ee][Cc]|[Aa][Rr][Gg][Vv]|[Ss][Hh][Ee][Ll][Ll])"} + }, + "additionalProperties": { + "anyOf": [ + {"type": "string", "maxLength": 4096}, + {"type": "number"}, + {"type": "boolean"}, + {"type": "null"} + ] + } + } + } +} diff --git a/schemas/image-export.v1.schema.json b/schemas/image-export.v1.schema.json new file mode 100644 index 0000000..7fdd08b --- /dev/null +++ b/schemas/image-export.v1.schema.json @@ -0,0 +1,31 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "durkahelper.image-export.v1", + "title": "Private image export profile (not redistribution authorization)", + "type": "object", + "additionalProperties": false, + "required": ["schema", "release_commit", "images", "max_archive_bytes", "max_total_bytes", "timeout_seconds"], + "properties": { + "schema": {"const": "durkahelper.image-export.v1"}, + "release_commit": {"type": "string", "pattern": "^[0-9a-f]{40}$"}, + "max_archive_bytes": {"type": "integer", "minimum": 1, "maximum": 34359738368}, + "max_total_bytes": {"type": "integer", "minimum": 1, "maximum": 103079215104}, + "timeout_seconds": {"type": "integer", "minimum": 1, "maximum": 1800}, + "images": { + "type": "array", "minItems": 1, "maxItems": 64, + "items": { + "type": "object", "additionalProperties": false, + "required": ["id", "component", "architecture", "image_id", "license", "redistribution", "reviewed_for_secrets"], + "properties": { + "id": {"type": "string", "pattern": "^[a-z0-9][a-z0-9_.-]{0,63}$"}, + "component": {"type": "string", "pattern": "^[a-z0-9][a-z0-9_.-]{0,63}$"}, + "architecture": {"enum": ["linux/amd64", "linux/arm64"]}, + "image_id": {"type": "string", "pattern": "^sha256:[0-9a-f]{64}$"}, + "license": {"type": "string", "pattern": "^[A-Za-z0-9][A-Za-z0-9.+() -]{0,127}$"}, + "redistribution": {"const": "local-only"}, + "reviewed_for_secrets": {"const": true} + } + } + } + } +} diff --git a/schemas/profile.v1.schema.json b/schemas/profile.v1.schema.json new file mode 100644 index 0000000..f38cb66 --- /dev/null +++ b/schemas/profile.v1.schema.json @@ -0,0 +1,128 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "urn:durkahelper:schema:profile:v1", + "title": "DurkaHelper declarative defense profile v1", + "type": "object", + "additionalProperties": false, + "required": ["schema", "name"], + "properties": { + "schema": {"const": "durkahelper.profile.v1"}, + "name": {"type": "string", "minLength": 1, "maxLength": 120}, + "snapshot": { + "type": "object", + "additionalProperties": false, + "properties": { + "adapters": { + "type": "array", + "maxItems": 5, + "uniqueItems": true, + "items": {"enum": ["platform", "processes", "listeners", "services", "compose"]} + }, + "include": {"$ref": "#/$defs/globs"}, + "exclude": {"$ref": "#/$defs/globs"}, + "max_files": {"type": "integer", "minimum": 1, "maximum": 100000}, + "max_file_bytes": {"type": "integer", "minimum": 1, "maximum": 1073741824}, + "max_total_bytes": {"type": "integer", "minimum": 1, "maximum": 21474836480} + } + }, + "compose": { + "type": "object", + "additionalProperties": false, + "required": ["project", "files", "services"], + "properties": { + "project": {"type": "string", "pattern": "^[a-z0-9][a-z0-9_-]{0,62}$"}, + "files": { + "type": "array", "minItems": 1, "maxItems": 8, "uniqueItems": true, + "items": {"$ref": "#/$defs/composePath"} + }, + "services": { + "type": "array", "minItems": 1, "maxItems": 128, "uniqueItems": true, + "items": {"type": "string", "pattern": "^[a-z0-9][a-z0-9_.-]{0,63}$"} + } + } + }, + "health": { + "type": "array", + "minItems": 1, + "maxItems": 128, + "items": { + "type": "object", + "additionalProperties": false, + "required": ["name", "url"], + "properties": { + "name": {"type": "string", "minLength": 1, "maxLength": 120}, + "url": {"type": "string", "minLength": 1, "maxLength": 4096, "pattern": "^https?://"}, + "status": {"type": "integer", "minimum": 100, "maximum": 599}, + "contains": {"type": "string", "maxLength": 4096}, + "timeout": {"type": "number", "exclusiveMinimum": 0, "maximum": 60} + } + } + }, + "backup": { + "type": "object", + "additionalProperties": false, + "required": ["entries"], + "properties": { + "entries": { + "type": "array", + "minItems": 1, + "maxItems": 256, + "items": { + "type": "object", + "additionalProperties": false, + "required": ["path", "kind"], + "properties": { + "path": {"$ref": "#/$defs/relativePathOrDot"}, + "kind": {"enum": ["file", "tree", "native_dump"]} + } + } + }, + "exclude": {"$ref": "#/$defs/globs"}, + "max_files": {"type": "integer", "minimum": 1, "maximum": 100000}, + "max_file_bytes": {"type": "integer", "minimum": 1, "maximum": 4294967296}, + "max_total_bytes": {"type": "integer", "minimum": 1, "maximum": 107374182400} + } + }, + "evidence": { + "type": "object", + "additionalProperties": false, + "properties": { + "allow_extensions": { + "type": "array", + "minItems": 1, + "maxItems": 2, + "uniqueItems": true, + "items": {"enum": [".json", ".jsonl"]} + }, + "max_files": {"type": "integer", "minimum": 1, "maximum": 1024}, + "max_file_bytes": {"type": "integer", "minimum": 1, "maximum": 67108864}, + "max_total_bytes": {"type": "integer", "minimum": 1, "maximum": 1073741824} + } + } + }, + "$defs": { + "composePath": { + "type": "string", + "minLength": 5, + "maxLength": 1024, + "pattern": "^(?!/)(?!.*(?:^|/)\\.\\.(?:/|$))(?!.*\\\\)(?!.*:)(?!.*[<>\"|?*])(?!.+(?:[. ])(?:/|$))[^/]+(?:/[^/]+)*\\.ya?ml$" + }, + "relativePathOrDot": { + "$comment": "The runtime additionally enforces NFC, case-fold uniqueness, and Windows reserved-device names for backup/restore portability.", + "type": "string", + "minLength": 1, + "maxLength": 1024, + "pattern": "^(?:\\.|(?!/)(?!.*(?:^|/)\\.\\.(?:/|$))(?!.*(?:^|/)(?:[Cc][Oo][Nn]|[Pp][Rr][Nn]|[Aa][Uu][Xx]|[Nn][Uu][Ll]|[Cc][Oo][Mm][1-9]|[Ll][Pp][Tt][1-9])(?:[ .]*\\.[^/]*)?(?:/|$))(?!.*\\\\)(?!.*:)(?!.*[<>\"|?*])(?!.+(?:[. ])(?:/|$))[^/]+(?:/[^/]+)*)$" + }, + "globs": { + "type": "array", + "maxItems": 128, + "items": { + "type": "string", + "minLength": 1, + "maxLength": 512, + "pattern": "^(?!/)(?!.*(?:^|/)\\.\\.(?:/|$))(?!.*\\\\)(?!.*:).+$" + } + } + } +} diff --git a/schemas/scanner-context.v1.schema.json b/schemas/scanner-context.v1.schema.json new file mode 100644 index 0000000..1c87925 --- /dev/null +++ b/schemas/scanner-context.v1.schema.json @@ -0,0 +1,17 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "urn:durkahelper:schema:scanner-context:v1", + "title": "Non-secret scanner infrastructure context v1", + "$comment": "Context only changes review priority and static explanations. It never disables rules, grants permission, starts processes or makes network requests. The runtime normalizes infrastructure enum ordering before hashing.", + "type": "object", + "additionalProperties": false, + "required": ["schema", "infrastructure", "role"], + "properties": { + "schema": {"const": "durkahelper.scanner-context.v1"}, + "infrastructure": { + "type": "array", "maxItems": 7, "uniqueItems": true, + "items": {"enum": ["docker-desktop", "compose", "vulnbox", "team-lan", "s4dfarm", "neo", "packmate"]} + }, + "role": {"enum": ["defender", "administrator", "both"]} + } +} diff --git a/schemas/scanner-scope.v2.schema.json b/schemas/scanner-scope.v2.schema.json new file mode 100644 index 0000000..7e5fd3b --- /dev/null +++ b/schemas/scanner-scope.v2.schema.json @@ -0,0 +1,27 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "urn:durkahelper:schema:scanner-scope:v2", + "title": "Scanner comparability scope v2", + "$comment": "SHA256 covers canonical ASCII JSON with sorted keys and compact separators, excluding the sha256 field. Root is an opaque identity, not a path. Context digest covers normalized context including the empty default. A v1/v2 or context/semantics mismatch is incomparable, not a clean result. Exclusions must also be sorted/unique and all digests are verified by runtime.", + "type": "object", "additionalProperties": false, + "required": ["schema", "root", "rules_sha256", "exclude", "limits", "path_semantics", "semantic_revision", "context_sha256", "sha256"], + "properties": { + "schema": {"const": "durkahelper.scanner-scope.v2"}, + "root": {"type": "string", "pattern": "^sha256:[0-9a-f]{64}$"}, + "rules_sha256": {"type": "string", "pattern": "^[0-9a-f]{64}$"}, + "context_sha256": {"type": "string", "pattern": "^[0-9a-f]{64}$"}, + "sha256": {"type": "string", "pattern": "^[0-9a-f]{64}$"}, + "path_semantics": {"const": "root-relative-posix.v1"}, + "semantic_revision": {"enum": ["bounded-source-signals.v2", "bounded-source-signals.v3"]}, + "exclude": {"type": "array", "maxItems": 10000, "uniqueItems": true, "items": {"type": "string", "maxLength": 4096, "pattern": "^[^\u0000]*$"}}, + "limits": { + "type": "object", "additionalProperties": false, + "required": ["max_bytes", "max_files", "max_findings"], + "properties": { + "max_bytes": {"type": "integer", "minimum": 1, "maximum": 9223372036854775807}, + "max_files": {"type": "integer", "minimum": 1, "maximum": 9223372036854775807}, + "max_findings": {"type": "integer", "minimum": 1, "maximum": 9223372036854775807} + } + } + } +} diff --git a/schemas/snapshot.v1.schema.json b/schemas/snapshot.v1.schema.json new file mode 100644 index 0000000..192a104 --- /dev/null +++ b/schemas/snapshot.v1.schema.json @@ -0,0 +1,224 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "urn:durkahelper:schema:snapshot:v1", + "title": "DurkaHelper defense snapshot v1", + "type": "object", + "additionalProperties": false, + "required": ["schema", "tool", "created_at", "profile", "root", "scope", "partial", "issues", "limits", "files", "adapters", "skipped", "summary"], + "properties": { + "schema": {"const": "durkahelper.snapshot.v1"}, + "tool": {"$ref": "#/$defs/tool"}, + "created_at": {"type": "string", "format": "date-time"}, + "profile": {"$ref": "#/$defs/profileRef"}, + "root": {"type": "string", "pattern": "^sha256:[0-9a-f]{64}$"}, + "scope": {"$ref": "#/$defs/scope"}, + "partial": {"type": "boolean"}, + "issues": { + "type": "array", "maxItems": 100000, + "items": { + "type": "object", "additionalProperties": false, + "required": ["component", "path", "reason"], + "properties": { + "component": {"type": "string", "minLength": 1, "maxLength": 120}, + "path": {"type": ["string", "null"], "maxLength": 4096}, + "reason": {"type": "string", "minLength": 1, "maxLength": 120} + } + } + }, + "limits": {"$ref": "#/$defs/limits"}, + "files": {"type": "array", "maxItems": 100000, "items": {"$ref": "#/$defs/file"}}, + "adapters": { + "type": "object", "additionalProperties": false, + "properties": { + "platform": {"oneOf": [{"$ref": "#/$defs/platform"}, {"type": "null"}]}, + "processes": {"oneOf": [{"$ref": "#/$defs/processes"}, {"type": "null"}]}, + "listeners": {"oneOf": [{"$ref": "#/$defs/listeners"}, {"type": "null"}]}, + "services": {"oneOf": [{"$ref": "#/$defs/services"}, {"type": "null"}]}, + "compose": {"oneOf": [{"$ref": "#/$defs/compose"}, {"type": "null"}]} + } + }, + "skipped": { + "type": "object", "maxProperties": 128, + "propertyNames": {"minLength": 1, "maxLength": 120}, + "additionalProperties": {"type": "integer", "minimum": 0} + }, + "summary": { + "type": "object", "additionalProperties": false, + "required": ["files", "total_bytes"], + "properties": { + "files": {"type": "integer", "minimum": 0, "maximum": 100000}, + "total_bytes": {"type": "integer", "minimum": 0, "maximum": 21474836480} + } + } + }, + "$defs": { + "tool": { + "type": "object", "additionalProperties": false, "required": ["name", "version"], + "properties": { + "name": {"const": "DurkaHelper defense_ops"}, + "version": {"type": "string", "pattern": "^[0-9]+\\.[0-9]+\\.[0-9]+(?:[-+][0-9A-Za-z.-]+)?$"} + } + }, + "profileRef": { + "type": "object", "additionalProperties": false, "required": ["name", "sha256"], + "properties": { + "name": {"type": "string", "minLength": 1, "maxLength": 120}, + "sha256": {"type": "string", "pattern": "^[0-9a-f]{64}$"} + } + }, + "limits": { + "type": "object", "additionalProperties": false, + "required": ["max_files", "max_file_bytes", "max_total_bytes"], + "properties": { + "max_files": {"type": "integer", "minimum": 1, "maximum": 100000}, + "max_file_bytes": {"type": "integer", "minimum": 1, "maximum": 1073741824}, + "max_total_bytes": {"type": "integer", "minimum": 1, "maximum": 21474836480} + } + }, + "portablePath": { + "$comment": "The runtime additionally enforces NFC, case-fold uniqueness, and reserved-device names.", + "type": "string", "minLength": 1, "maxLength": 1024, + "pattern": "^(?!/)(?!.*(?:^|/)\\.\\.(?:/|$))(?!.*(?:^|/)(?:[Cc][Oo][Nn]|[Pp][Rr][Nn]|[Aa][Uu][Xx]|[Nn][Uu][Ll]|[Cc][Oo][Mm][1-9]|[Ll][Pp][Tt][1-9])(?:[ .]*\\.[^/]*)?(?:/|$))(?!.*\\\\)(?!.*:)(?!.*[<>\"|?*])(?!.+(?:[. ])(?:/|$))[^/]+(?:/[^/]+)*$" + }, + "file": { + "type": "object", "additionalProperties": false, + "required": ["path", "size", "mtime_ns", "mode", "sha256"], + "properties": { + "path": {"$ref": "#/$defs/portablePath"}, + "size": {"type": "integer", "minimum": 0, "maximum": 1073741824}, + "mtime_ns": {"type": "integer", "minimum": 0, "maximum": 253402300799999999999}, + "mode": {"type": "integer", "minimum": 0, "maximum": 4095}, + "sha256": {"type": "string", "pattern": "^[0-9a-f]{64}$"} + } + }, + "scope": { + "type": "object", "additionalProperties": false, + "required": ["schema", "tool_compatibility", "adapter_semantics", "adapter_config", "files", "sha256"], + "properties": { + "schema": {"const": "durkahelper.snapshot-scope.v1"}, + "tool_compatibility": {"const": "durkahelper-defense-ops-major-2"}, + "adapter_semantics": { + "type": "object", "additionalProperties": false, + "properties": { + "platform": {"const": "platform-system-machine-release-python-v1"}, + "processes": {"const": "process-name-uid-count-v1"}, + "listeners": {"const": "listener-endpoint-no-pid-v1"}, + "services": {"const": "service-state-no-pid-v1"}, + "compose": {"const": "compose-explicit-project-config-hash-service-state-v1"} + } + }, + "adapter_config": { + "type": "object", "additionalProperties": false, + "properties": { + "compose": { + "type": "object", "additionalProperties": false, + "required": ["config_files", "project_sha256", "services"], + "properties": { + "config_files": {"type": "array", "minItems": 1, "maxItems": 8, "uniqueItems": true, "items": {"$ref": "#/$defs/portablePath"}}, + "project_sha256": {"type": "string", "pattern": "^sha256:[0-9a-f]{64}$"}, + "services": {"type": "array", "minItems": 1, "maxItems": 128, "uniqueItems": true, "items": {"type": "string", "pattern": "^[a-z0-9][a-z0-9_.-]{0,63}$"}} + } + } + } + }, + "files": { + "type": "object", "additionalProperties": false, + "required": ["content_semantics", "exclude", "include", "max_file_bytes", "max_files", "max_total_bytes", "path_semantics"], + "properties": { + "content_semantics": {"const": "sha256-size-mode-mtime-v1"}, + "exclude": {"$ref": "#/$defs/globs"}, + "include": {"$ref": "#/$defs/globs"}, + "max_file_bytes": {"type": "integer", "minimum": 1, "maximum": 1073741824}, + "max_files": {"type": "integer", "minimum": 1, "maximum": 100000}, + "max_total_bytes": {"type": "integer", "minimum": 1, "maximum": 21474836480}, + "path_semantics": {"const": "portable-nfc-casefold-v1"} + } + }, + "sha256": {"type": "string", "pattern": "^[0-9a-f]{64}$"} + } + }, + "globs": { + "type": "array", "maxItems": 128, "uniqueItems": true, + "items": {"type": "string", "minLength": 1, "maxLength": 512} + }, + "platform": { + "type": "object", "additionalProperties": false, "required": ["machine", "system"], + "properties": { + "machine": {"type": "string", "maxLength": 512}, + "python": {"type": "string", "maxLength": 512}, + "release": {"type": "string", "maxLength": 512}, + "system": {"type": "string", "maxLength": 512} + } + }, + "processes": { + "type": "array", "maxItems": 100000, + "items": { + "type": "object", "additionalProperties": false, "required": ["name", "pid", "ppid", "uid"], + "properties": { + "name": {"type": "string", "maxLength": 1024}, + "pid": {"type": ["integer", "null"]}, "ppid": {"type": ["integer", "null"]}, + "uid": {"type": ["integer", "null"]} + } + } + }, + "listeners": { + "type": "array", "maxItems": 100000, + "items": { + "type": "object", "additionalProperties": false, + "required": ["address", "port", "protocol", "state"], + "properties": { + "address": {"type": "string", "minLength": 1, "maxLength": 256}, + "name": {"type": ["string", "null"], "maxLength": 1024}, + "pid": {"type": ["integer", "null"]}, + "port": {"type": "integer", "minimum": 0, "maximum": 65535}, + "protocol": {"type": "string", "minLength": 1, "maxLength": 32}, + "state": {"type": "string", "minLength": 1, "maxLength": 64} + } + } + }, + "services": { + "type": "array", "maxItems": 100000, + "items": { + "type": "object", "additionalProperties": false, "required": ["name"], + "properties": { + "active": {"type": "string", "maxLength": 256}, "load": {"type": "string", "maxLength": 256}, + "name": {"type": "string", "minLength": 1, "maxLength": 1024}, + "pid": {"type": ["integer", "null"]}, "state": {"type": "string", "maxLength": 256}, + "status": {"type": "string", "maxLength": 256}, "sub": {"type": "string", "maxLength": 256} + } + } + }, + "compose": { + "type": "object", "additionalProperties": false, + "required": ["config_files", "project_sha256", "services"], + "properties": { + "project_sha256": {"type": "string", "pattern": "^sha256:[0-9a-f]{64}$"}, + "config_files": { + "type": "array", "minItems": 1, "maxItems": 8, + "items": { + "type": "object", "additionalProperties": false, + "required": ["path", "sha256", "size"], + "properties": { + "path": {"$ref": "#/$defs/portablePath"}, + "sha256": {"type": "string", "pattern": "^[0-9a-f]{64}$"}, + "size": {"type": "integer", "minimum": 0, "maximum": 16777216} + } + } + }, + "services": { + "type": "array", "maxItems": 100000, + "items": { + "type": "object", "additionalProperties": false, + "required": ["count", "health", "service", "state"], + "properties": { + "count": {"type": "integer", "minimum": 0, "maximum": 100000}, + "health": {"enum": ["healthy", "unhealthy", "starting", "none"]}, + "service": {"type": "string", "pattern": "^[a-z0-9][a-z0-9_.-]{0,63}$"}, + "state": {"type": "string", "minLength": 1, "maxLength": 64} + } + } + } + } + } + } +} diff --git a/schemas/toolchain-inventory.v1.schema.json b/schemas/toolchain-inventory.v1.schema.json new file mode 100644 index 0000000..4e97b09 --- /dev/null +++ b/schemas/toolchain-inventory.v1.schema.json @@ -0,0 +1,63 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "urn:durkahelper:toolchain-inventory:v1", + "title": "Operator-reviewed private cache recipe; not a runtime acceptance record", + "type": "object", + "additionalProperties": false, + "required": ["schema", "release_commit", "target", "receipt", "image_export", "artifacts"], + "properties": { + "schema": {"const": "durkahelper.toolchain-inventory.v1"}, + "release_commit": {"type": "string", "pattern": "^[0-9a-f]{40}$"}, + "target": { + "type": "object", + "additionalProperties": false, + "required": ["id", "platform"], + "properties": { + "id": {"$ref": "#/$defs/id"}, + "platform": {"enum": ["darwin/arm64", "linux/amd64", "linux/arm64", "windows/amd64"]} + } + }, + "receipt": {"$ref": "#/$defs/reference"}, + "image_export": {"$ref": "#/$defs/reference"}, + "artifacts": {"type": "array", "maxItems": 128, "items": {"$ref": "#/$defs/artifact"}} + }, + "$defs": { + "id": {"type": "string", "pattern": "^[a-z0-9][a-z0-9_.-]{0,63}$"}, + "sha256": {"type": "string", "pattern": "^[0-9a-f]{64}$"}, + "path": { + "type": "string", + "minLength": 1, + "maxLength": 4096, + "description": "Portable relative POSIX path. Runtime validation additionally rejects traversal, links, private-data paths and collisions." + }, + "reference": { + "type": "object", + "additionalProperties": false, + "required": ["path", "sha256"], + "properties": {"path": {"$ref": "#/$defs/path"}, "sha256": {"$ref": "#/$defs/sha256"}} + }, + "artifact": { + "type": "object", + "additionalProperties": false, + "required": ["id", "path", "kind", "component", "architecture", "version", "sha256", "size", "license", "redistribution", "source_pins"], + "properties": { + "id": {"$ref": "#/$defs/id"}, + "path": {"$ref": "#/$defs/path"}, + "kind": {"enum": ["core", "source", "client", "license", "installer", "runtime"]}, + "component": {"enum": ["durkahelper", "postgres", "redis", "s4dfarm", "neo", "packmate", "container-runtime", "python", "ripgrep"]}, + "architecture": {"enum": ["all", "darwin/arm64", "linux/amd64", "linux/arm64", "windows/amd64"]}, + "version": {"type": "string", "pattern": "^[A-Za-z0-9][A-Za-z0-9._+:/@-]{0,127}$", "description": "Exact pin; floating names are rejected by runtime validation."}, + "sha256": {"$ref": "#/$defs/sha256"}, + "size": {"type": "integer", "minimum": 1, "maximum": 34359738368}, + "license": {"type": "string", "pattern": "^[A-Za-z0-9][A-Za-z0-9.+() -]{0,127}$"}, + "redistribution": {"const": "local-only"}, + "source_pins": { + "type": "object", + "maxProperties": 32, + "additionalProperties": {"type": "string", "pattern": "^[0-9a-f]{40}$"}, + "description": "For source archives only: dot is the root commit; every pinned submodule path must be present. Empty for other artifact kinds. Declarations do not independently authenticate archive provenance." + } + } + } + } +} diff --git a/schemas/toolchain-manifest.v1.schema.json b/schemas/toolchain-manifest.v1.schema.json new file mode 100644 index 0000000..0a818c5 --- /dev/null +++ b/schemas/toolchain-manifest.v1.schema.json @@ -0,0 +1,132 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "urn:durkahelper:toolchain-manifest:v1", + "title": "Operator-local external toolchain inventory", + "type": "object", + "additionalProperties": false, + "required": [ + "schema", + "release_commit", + "required_ids", + "artifacts" + ], + "properties": { + "schema": { + "const": "durkahelper.toolchain-manifest.v1" + }, + "release_commit": { + "type": "string", + "pattern": "^[0-9a-f]{40}$" + }, + "required_ids": { + "type": "array", + "minItems": 1, + "maxItems": 256, + "uniqueItems": true, + "items": { + "type": "string", + "pattern": "^[a-z0-9][a-z0-9_.-]{0,63}$" + } + }, + "artifacts": { + "type": "array", + "minItems": 1, + "maxItems": 256, + "items": { + "type": "object", + "additionalProperties": false, + "allOf": [ + { + "if": { + "properties": { + "kind": {"const": "image"} + }, + "required": ["kind"] + }, + "then": { + "properties": { + "architecture": { + "enum": ["linux/amd64", "linux/arm64"] + } + } + } + } + ], + "required": [ + "id", + "path", + "kind", + "component", + "architecture", + "sha256", + "size", + "license", + "redistribution", + "image_ids" + ], + "properties": { + "id": { + "type": "string", + "pattern": "^[a-z0-9][a-z0-9_.-]{0,63}$" + }, + "path": { + "type": "string", + "minLength": 1, + "maxLength": 1024 + }, + "kind": { + "enum": [ + "core", + "image", + "source", + "client", + "license" + ] + }, + "component": { + "type": "string", + "pattern": "^[a-z0-9][a-z0-9_.-]{0,63}$" + }, + "architecture": { + "enum": [ + "all", + "linux/amd64", + "linux/arm64", + "darwin/arm64", + "windows/amd64" + ] + }, + "sha256": { + "type": "string", + "pattern": "^[0-9a-f]{64}$" + }, + "size": { + "type": "integer", + "minimum": 1, + "maximum": 34359738368 + }, + "license": { + "type": "string", + "pattern": "^[A-Za-z0-9][A-Za-z0-9.+() -]{0,127}$" + }, + "redistribution": { + "enum": [ + "local-only", + "reviewed" + ] + }, + "image_ids": { + "type": "array", + "maxItems": 64, + "uniqueItems": true, + "items": { + "type": "string", + "pattern": "^sha256:[0-9a-f]{64}$" + } + } + } + } + } + }, + "$comment": "CLI additionally enforces relative portable/private-path rules, exact inventory identities, byte budget, checksum matching and tag-free Docker-save structure. No redistribution or offline-runtime attestation is implied." +} diff --git a/schemas/toolchain-manifest.v2.schema.json b/schemas/toolchain-manifest.v2.schema.json new file mode 100644 index 0000000..34d6a88 --- /dev/null +++ b/schemas/toolchain-manifest.v2.schema.json @@ -0,0 +1,260 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "urn:durkahelper:toolchain-manifest:v2", + "title": "DurkaHelper complete target or partial image-export inventory", + "type": "object", + "additionalProperties": false, + "required": [ + "schema", + "release_commit", + "scope", + "targets", + "required_ids", + "artifacts" + ], + "properties": { + "schema": {"const": "durkahelper.toolchain-manifest.v2"}, + "release_commit": {"type": "string", "pattern": "^[0-9a-f]{40}$"}, + "scope": {"enum": ["complete-target", "image-export"]}, + "targets": { + "type": "array", + "maxItems": 16, + "items": {"$ref": "#/$defs/target"} + }, + "required_ids": { + "type": "array", + "minItems": 1, + "maxItems": 256, + "uniqueItems": true, + "items": {"$ref": "#/$defs/id"} + }, + "artifacts": { + "type": "array", + "minItems": 1, + "maxItems": 256, + "items": {"$ref": "#/$defs/artifact"} + } + }, + "$defs": { + "id": { + "type": "string", + "pattern": "^[a-z0-9][a-z0-9_.-]{0,63}$" + }, + "imageId": { + "type": "string", + "pattern": "^sha256:[0-9a-f]{64}$" + }, + "containerPlatform": { + "enum": ["linux/amd64", "linux/arm64"] + }, + "role": { + "type": "object", + "additionalProperties": false, + "required": ["id", "component", "platform", "image_id"], + "properties": { + "id": { + "enum": [ + "postgres", + "redis", + "neo-redis", + "farm", + "celery", + "front", + "neo-server", + "neo-worker", + "packmate-db", + "packmate" + ] + }, + "component": {"enum": ["s4dfarm", "neo", "packmate"]}, + "platform": {"$ref": "#/$defs/containerPlatform"}, + "image_id": {"$ref": "#/$defs/imageId"} + } + }, + "target": { + "type": "object", + "additionalProperties": false, + "required": [ + "id", + "platform", + "container_platforms", + "deployment_contract_sha256", + "runtime_roles", + "artifact_ids" + ], + "properties": { + "id": {"$ref": "#/$defs/id"}, + "platform": { + "enum": ["linux/amd64", "linux/arm64", "darwin/arm64", "windows/amd64"] + }, + "container_platforms": { + "type": "array", + "minItems": 1, + "maxItems": 2, + "uniqueItems": true, + "items": {"$ref": "#/$defs/containerPlatform"} + }, + "deployment_contract_sha256": { + "const": "a2327cb0dd091d387d33b283337c048778b6b7aa9bef5a344d19aa48c0d9322b" + }, + "runtime_roles": { + "type": "array", + "minItems": 10, + "maxItems": 10, + "uniqueItems": true, + "items": {"$ref": "#/$defs/role"}, + "allOf": [ + {"contains": {"properties": {"id": {"const": "postgres"}, "component": {"const": "s4dfarm"}}, "required": ["id", "component"]}, "minContains": 1, "maxContains": 1}, + {"contains": {"properties": {"id": {"const": "redis"}, "component": {"const": "s4dfarm"}}, "required": ["id", "component"]}, "minContains": 1, "maxContains": 1}, + {"contains": {"properties": {"id": {"const": "neo-redis"}, "component": {"const": "neo"}}, "required": ["id", "component"]}, "minContains": 1, "maxContains": 1}, + {"contains": {"properties": {"id": {"const": "farm"}, "component": {"const": "s4dfarm"}}, "required": ["id", "component"]}, "minContains": 1, "maxContains": 1}, + {"contains": {"properties": {"id": {"const": "celery"}, "component": {"const": "s4dfarm"}}, "required": ["id", "component"]}, "minContains": 1, "maxContains": 1}, + {"contains": {"properties": {"id": {"const": "front"}, "component": {"const": "s4dfarm"}}, "required": ["id", "component"]}, "minContains": 1, "maxContains": 1}, + {"contains": {"properties": {"id": {"const": "neo-server"}, "component": {"const": "neo"}}, "required": ["id", "component"]}, "minContains": 1, "maxContains": 1}, + {"contains": {"properties": {"id": {"const": "neo-worker"}, "component": {"const": "neo"}}, "required": ["id", "component"]}, "minContains": 1, "maxContains": 1}, + {"contains": {"properties": {"id": {"const": "packmate-db"}, "component": {"const": "packmate"}}, "required": ["id", "component"]}, "minContains": 1, "maxContains": 1}, + {"contains": {"properties": {"id": {"const": "packmate"}, "component": {"const": "packmate"}, "platform": {"const": "linux/amd64"}}, "required": ["id", "component", "platform"]}, "minContains": 1, "maxContains": 1} + ] + }, + "artifact_ids": { + "type": "array", + "minItems": 1, + "maxItems": 256, + "uniqueItems": true, + "items": {"$ref": "#/$defs/id"} + } + } + }, + "artifact": { + "type": "object", + "additionalProperties": false, + "required": [ + "id", + "path", + "kind", + "component", + "architecture", + "version", + "compatible_with", + "runtime_roles", + "sha256", + "size", + "license", + "redistribution", + "image_ids" + ], + "properties": { + "id": {"$ref": "#/$defs/id"}, + "path": {"type": "string", "minLength": 1, "maxLength": 1024}, + "kind": { + "enum": ["core", "image", "source", "client", "license", "installer", "runtime"] + }, + "component": {"$ref": "#/$defs/id"}, + "architecture": { + "enum": ["all", "linux/amd64", "linux/arm64", "darwin/arm64", "windows/amd64"] + }, + "version": { + "type": "string", + "pattern": "^[A-Za-z0-9][A-Za-z0-9._+:/@-]{0,127}$" + }, + "compatible_with": { + "type": "array", + "maxItems": 64, + "uniqueItems": true, + "items": {"$ref": "#/$defs/id"} + }, + "runtime_roles": { + "type": "array", + "maxItems": 10, + "uniqueItems": true, + "items": { + "enum": [ + "postgres", + "redis", + "neo-redis", + "farm", + "celery", + "front", + "neo-server", + "neo-worker", + "packmate-db", + "packmate" + ] + } + }, + "sha256": {"type": "string", "pattern": "^[0-9a-f]{64}$"}, + "size": {"type": "integer", "minimum": 1, "maximum": 34359738368}, + "license": { + "type": "string", + "pattern": "^[A-Za-z0-9][A-Za-z0-9.+() -]{0,127}$" + }, + "redistribution": {"enum": ["local-only", "reviewed"]}, + "image_ids": { + "type": "array", + "maxItems": 64, + "uniqueItems": true, + "items": {"$ref": "#/$defs/imageId"} + } + }, + "allOf": [ + { + "if": {"properties": {"kind": {"const": "image"}}, "required": ["kind"]}, + "then": { + "properties": { + "architecture": {"$ref": "#/$defs/containerPlatform"}, + "image_ids": {"minItems": 1}, + "runtime_roles": {"minItems": 0} + } + }, + "else": { + "properties": { + "image_ids": {"maxItems": 0}, + "runtime_roles": {"maxItems": 0} + } + } + }, + { + "if": {"properties": {"kind": {"const": "client"}}, "required": ["kind"]}, + "then": {"properties": {"compatible_with": {"minItems": 2, "maxItems": 2}}}, + "else": { + "if": {"properties": {"kind": {"const": "image"}}, "required": ["kind"]}, + "else": {"properties": {"compatible_with": {"maxItems": 0}}} + } + }, + { + "if": {"properties": {"kind": {"const": "source"}}, "required": ["kind"]}, + "then": {"properties": {"version": {"pattern": "^[0-9a-f]{40}$"}}} + } + ] + } + }, + "allOf": [ + { + "if": {"properties": {"scope": {"const": "complete-target"}}, "required": ["scope"]}, + "then": {"properties": {"targets": {"minItems": 1}}} + }, + { + "if": {"properties": {"scope": {"const": "image-export"}}, "required": ["scope"]}, + "then": { + "properties": { + "targets": {"maxItems": 0}, + "artifacts": { + "items": { + "allOf": [ + {"$ref": "#/$defs/artifact"}, + { + "properties": { + "kind": {"const": "image"}, + "compatible_with": {"maxItems": 0}, + "runtime_roles": {"maxItems": 0} + } + } + ] + } + } + } + } + } + ], + "$comment": "The parser additionally enforces portable/private paths, exact inventory identity, byte budgets, fixed component/kind coverage, global and per-target compatibility/provenance edges, release/source pins, image-role identity coverage, target-derived role platforms, shared Redis image identity, and the fixed maintained-deployment contract. complete-target verification requires a trusted detached manifest SHA-256. image-export remains partial." +} diff --git a/schemas/validation-record.v1.schema.json b/schemas/validation-record.v1.schema.json new file mode 100644 index 0000000..547f335 --- /dev/null +++ b/schemas/validation-record.v1.schema.json @@ -0,0 +1,47 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "urn:durkahelper:schema:validation-record:v1", + "title": "DurkaHelper validation record v1", + "type": "object", + "additionalProperties": false, + "required": ["schema", "id", "timestamp", "check", "status", "summary"], + "properties": { + "schema": {"const": "durkahelper.validation-record.v1"}, + "id": {"type": "string", "minLength": 1, "maxLength": 128, "pattern": "^[A-Za-z0-9][A-Za-z0-9._:-]*$"}, + "timestamp": {"type": "string", "format": "date-time"}, + "check": {"type": "string", "minLength": 1, "maxLength": 120}, + "status": {"enum": ["pass", "fail", "partial", "blocked", "not_run", "skipped_not_applicable"]}, + "summary": {"type": "string", "minLength": 1, "maxLength": 512}, + "evidence": { + "$comment": "NFC normalization is additionally enforced by the runtime.", + "type": "array", + "maxItems": 128, + "items": { + "type": "string", + "minLength": 1, + "maxLength": 1024, + "pattern": "^(?!/)(?!.*(?:^|/)\\.\\.(?:/|$))(?!.*\\\\)(?!.*:)[^/]+(?:/[^/]+)*$" + } + }, + "attributes": {"$ref": "#/$defs/attributes"} + }, + "$defs": { + "attributes": { + "type": "object", + "maxProperties": 64, + "propertyNames": { + "minLength": 1, + "maxLength": 64, + "not": {"pattern": "(?:[Pp][Aa][Ss][Ss][Ww][Oo][Rr][Dd]|[Pp][Aa][Ss][Ss][Ww][Dd]|[Pp][Ww][Dd]|[Ss][Ee][Cc][Rr][Ee][Tt]|[Tt][Oo][Kk][Ee][Nn]|[Cc][Rr][Ee][Dd][Ee][Nn][Tt][Ii][Aa][Ll]|[Aa][Uu][Tt][Hh][Oo][Rr][Ii][Zz][Aa][Tt][Ii][Oo][Nn]|[Cc][Oo][Oo][Kk][Ii][Ee]|[Pp][Rr][Ii][Vv][Aa][Tt][Ee].?[Kk][Ee][Yy]|[Aa][Pp][Ii].?[Kk][Ee][Yy]|[Aa][Cc][Cc][Ee][Ss][Ss].?[Kk][Ee][Yy]|[Ss][Ee][Ss][Ss][Ii][Oo][Nn]|[Dd][Ss][Nn]|[Cc][Oo][Nn][Nn][Ee][Cc][Tt][Ii][Oo][Nn].?[Ss][Tt][Rr][Ii][Nn][Gg]|[Cc][Oo][Mm][Mm][Aa][Nn][Dd]|[Ee][Xx][Ee][Cc]|[Aa][Rr][Gg][Vv]|[Ss][Hh][Ee][Ll][Ll])"} + }, + "additionalProperties": { + "anyOf": [ + {"type": "string", "maxLength": 4096}, + {"type": "number"}, + {"type": "boolean"}, + {"type": "null"} + ] + } + } + } +} diff --git a/scripts/backup_config.py b/scripts/backup_config.py new file mode 100644 index 0000000..4c82ca4 --- /dev/null +++ b/scripts/backup_config.py @@ -0,0 +1,151 @@ +#!/usr/bin/env python3 +"""Back up explicitly approved scalar JSON settings, never whole config files.""" +import argparse +import hashlib +import json +from pathlib import Path, PurePosixPath +import re +import shutil +import stat +import sys +import tempfile + +MAX_FILE = 1024 * 1024 +SENSITIVE = re.compile(r"password|passwd|pwd|secret|token|credential|auth|cookie|" + r"privatekey|apikey|accesskey|session|dsn|url|uri|connectionstring") + + +def sensitive_key(key): + return bool(SENSITIVE.search(re.sub(r"[^a-z0-9]", "", key.lower()))) + + +def unique_object(pairs): + obj = {} + for key, value in pairs: + if key in obj: + raise ValueError("duplicate JSON key") + obj[key] = value + return obj + + +def reject_constant(value): + raise ValueError("non-finite JSON number") + + +def read_json(path): + if not stat.S_ISREG(path.lstat().st_mode): + raise ValueError("expected regular JSON file") + with path.open("rb") as stream: + data = stream.read(MAX_FILE + 1) + if len(data) > MAX_FILE: + raise ValueError("JSON file exceeds 1 MiB") + return json.loads(data, object_pairs_hook=unique_object, parse_constant=reject_constant) + + +def source_path(root, relative): + if not isinstance(relative, str) or "\\" in relative or ":" in relative: + raise ValueError("expected relative POSIX path") + parts = relative.split("/") + if any(part in {"", ".", ".."} for part in parts): + raise ValueError("empty or traversal path component") + rel = PurePosixPath(relative) + if rel.suffix != ".json" or len(parts) > 16: + raise ValueError("only relative JSON paths are supported") + current = root + for part in parts: + current = current / part + if current.is_symlink(): + raise ValueError("source symlinks are not supported") + return current + + +def project_settings(source, allowed): + if not isinstance(allowed, list) or not 1 <= len(allowed) <= 256: + raise ValueError("allow must contain 1..256 key paths") + output, seen = {}, set() + for keys in allowed: + if (not isinstance(keys, list) or not 1 <= len(keys) <= 16 + or any(not isinstance(k, str) or not k or len(k) > 128 for k in keys)): + raise ValueError("each key path must be a nonempty list of strings") + if any(sensitive_key(k) for k in keys): + raise ValueError("sensitive field name is not allowed") + key_tuple = tuple(keys) + if key_tuple in seen: + raise ValueError("duplicate key path") + seen.add(key_tuple) + value = source + for key in keys: + if not isinstance(value, dict) or key not in value: + raise ValueError("selected field is missing") + value = value[key] + if isinstance(value, (dict, list)): + raise ValueError("select scalar leaves, not entire objects or lists") + # Never implicitly retain an unselected sibling or nested value. + target = output + for key in keys[:-1]: + target = target.setdefault(key, {}) + target[keys[-1]] = value + return output + + +def backup(root, manifest, output): + root = root.resolve(strict=True) + if not root.is_dir(): + raise ValueError("root must be a directory") + if not isinstance(manifest, dict) or set(manifest) != {"files"}: + raise ValueError("manifest needs only the files field") + files = manifest["files"] + if not isinstance(files, list) or not 1 <= len(files) <= 64: + raise ValueError("files must contain 1..64 entries") + prepared, seen = [], set() + for entry in files: + if not isinstance(entry, dict) or set(entry) != {"path", "allow"}: + raise ValueError("file entry needs path and allow") + source = source_path(root, entry["path"]) + if entry["path"] in seen: + raise ValueError("duplicate source path") + seen.add(entry["path"]) + selected = project_settings(read_json(source), entry["allow"]) + payload = (json.dumps(selected, ensure_ascii=True, indent=2, allow_nan=False) + "\n").encode() + prepared.append((entry["path"], payload)) + + # Validate and sanitize every source before creating any backup files. + output.mkdir(parents=True, exist_ok=True, mode=0o700) + session = Path(tempfile.mkdtemp(prefix="config-", dir=output)) + try: + session.chmod(0o700) + index = {"format": 1, "kind": "selected-settings", "files": []} + for number, (source, payload) in enumerate(prepared, 1): + name = f"settings-{number:03d}.json" + dest = session / name + with dest.open("xb") as stream: + stream.write(payload) + dest.chmod(0o600) + index["files"].append({"source": source, "backup": name, + "sha256": hashlib.sha256(payload).hexdigest()}) + index_path = session / "manifest.json" + index_path.write_text(json.dumps(index, ensure_ascii=True, indent=2) + "\n", encoding="utf-8") + index_path.chmod(0o600) + except BaseException: + shutil.rmtree(session) + raise + return session + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("manifest", type=Path) + parser.add_argument("--root", required=True, type=Path, help="directory containing source configs") + parser.add_argument("--output", type=Path, default=Path("artifacts/config-backups")) + args = parser.parse_args() + try: + session = backup(args.root, read_json(args.manifest), args.output) + print(session) + return 0 + except (OSError, ValueError, TypeError, RecursionError) as exc: + print(f"config backup: {type(exc).__name__}; no source values printed", file=sys.stderr) + return 2 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/build_offline_bundle.py b/scripts/build_offline_bundle.py new file mode 100644 index 0000000..029a3de --- /dev/null +++ b/scripts/build_offline_bundle.py @@ -0,0 +1,1135 @@ +#!/usr/bin/env python3 +"""Build or verify a deterministic, offline DurkaHelper source bundle.""" +from __future__ import annotations + +import argparse +import gzip +import hashlib +import json +import os +from pathlib import Path +import re +import shutil +import stat +import subprocess +import sys +import tarfile +import tempfile +import unicodedata +import zlib + + +SCHEMA = "durkahelper.offline-bundle.v1" +MANIFEST_NAME = "MANIFEST.json" +MAX_GIT_LIST_BYTES = 64 * 1024 * 1024 +MAX_ARCHIVE_BYTES = 1024 * 1024 * 1024 +MAX_MEMBER_BYTES = 512 * 1024 * 1024 +MAX_TOTAL_BYTES = 4 * 1024 * 1024 * 1024 +MAX_MANIFEST_BYTES = 16 * 1024 * 1024 +MAX_MEMBERS = 20_000 +MAX_PAX_BYTES = 32 * 1024 +MAX_RAW_TAR_HEADERS = MAX_MEMBERS * 2 + 2 +CHUNK = 1024 * 1024 + +FORBIDDEN_COMPONENTS = { + ".cache", ".git", ".mypy_cache", ".pytest_cache", ".ruff_cache", ".ssh", + "__pycache__", ".codex-remote-attachments", "artifacts", "cache", "local", "logs", "secrets", "upstream", +} +FORBIDDEN_SUFFIXES = { + ".accdb", ".cap", ".db", ".db3", ".jks", ".kdb", ".kdbx", ".key", + ".keystore", ".log", ".mdb", ".p12", ".p7b", ".p8", ".pcap", + ".pcapng", ".pem", ".pfx", ".pkcs8", ".ppk", ".secret", ".secrets", + ".sqlite", ".sqlite3", ".wal", +} +WINDOWS_RESERVED = { + "aux", "clock$", "con", "nul", "prn", + *(f"com{number}" for number in range(1, 10)), + *(f"lpt{number}" for number in range(1, 10)), +} +PRIVATE_KEY_HEADER = re.compile(br"-----BEGIN [A-Z0-9 ]{0,64}PRIVATE KEY-----") +HEX_DIGEST = re.compile(r"[0-9a-f]{64}\Z") +COMMIT_ID = re.compile(r"(?:[0-9a-f]{40}|[0-9a-f]{64})\Z") +ROOT_NAME = re.compile(r"DurkaHelper-([0-9a-f]{12})\Z") +LOWER_HEX = frozenset("0123456789abcdef") + + +class BundleError(Exception): + """Expected failure whose message is safe to show to an operator.""" + + +def _canonical_json(value) -> bytes: + return (json.dumps(value, ensure_ascii=True, sort_keys=True, + separators=(",", ":"), allow_nan=False) + "\n").encode("utf-8") + + +def _unique_object(pairs): + result = {} + for key, value in pairs: + if key in result: + raise BundleError("manifest contains a duplicate JSON key") + result[key] = value + return result + + +def _reject_constant(_value): + raise BundleError("manifest contains a non-finite number") + + +def _identity(metadata): + return ( + metadata.st_dev, + metadata.st_ino, + metadata.st_mode, + metadata.st_size, + metadata.st_mtime_ns, + getattr(metadata, "st_ctime_ns", 0), + ) + + +def _is_lower_hex(value: str, length: int) -> bool: + """Validate a fixed-size Git identifier without compiling a dynamic regex.""" + return len(value) == length and all(character in LOWER_HEX for character in value) + + +def _has_control(value: str) -> bool: + return any(ord(character) < 32 or ord(character) == 127 for character in value) + + +def _validate_relative_path(value: str, *, repository_path=True) -> str: + if (not isinstance(value, str) or not value or len(value) > 4096 or + value.startswith("/") or "\\" in value or ":" in value or + _has_control(value) or unicodedata.normalize("NFC", value) != value): + raise BundleError("bundle contains an unsafe path") + parts = value.split("/") + if any(part in {"", ".", ".."} for part in parts): + raise BundleError("bundle contains an unsafe path") + for part in parts: + if (part.endswith((" ", ".")) or len(part.encode("utf-8")) > 255 or + part.split(".", 1)[0].casefold() in WINDOWS_RESERVED): + raise BundleError("bundle contains a non-portable path") + if not repository_path: + return value + + folded_parts = [part.casefold() for part in parts] + if any(part in FORBIDDEN_COMPONENTS for part in folded_parts): + raise BundleError("tracked forbidden path") + name = parts[-1].casefold() + if name == ".env" or (name.startswith(".env.") and name != ".env.example"): + raise BundleError("tracked environment file") + if (any(name.endswith(suffix) for suffix in FORBIDDEN_SUFFIXES) or + any(marker in name for marker in (".db-", ".sqlite-", ".sqlite3-"))): + raise BundleError("tracked sensitive or runtime-data file") + if name in {"id_dsa", "id_ecdsa", "id_ed25519", "id_rsa"}: + raise BundleError("tracked private-key file") + if value.casefold() == MANIFEST_NAME.casefold(): + raise BundleError("tracked path collides with bundle manifest") + return value + + +def _canonical_parent_with_leaf(path: Path) -> Path: + """Resolve legitimate ancestor links while preserving the final entry.""" + absolute = Path(os.path.abspath(path)) + try: + parent = absolute.parent.resolve(strict=True) + except PermissionError as exc: + # Managed Windows sandboxes can deny realpath queries even when normal + # file access succeeds. Leaf no-follow checks still apply below. + if os.name != "nt": + raise BundleError("path parent is unavailable") from exc + parent = absolute.parent + except (OSError, RuntimeError) as exc: + raise BundleError("path parent is unavailable") from exc + if not parent.is_dir(): + raise BundleError("path parent is unavailable") + return parent / absolute.name + + +def _reject_symlink_leaf(path: Path): + try: + metadata = path.lstat() + except FileNotFoundError: + return + except OSError as exc: + raise BundleError("path metadata is unavailable") from exc + if stat.S_ISLNK(metadata.st_mode): + raise BundleError("path leaf is a symbolic link") + + +def _worktree_identity(root: Path, relative: str): + current = root + parts = relative.split("/") + for index, part in enumerate(parts): + current = current / part + try: + metadata = current.lstat() + except OSError as exc: + raise BundleError("tracked worktree path is unavailable") from exc + if stat.S_ISLNK(metadata.st_mode): + raise BundleError("tracked path contains a symbolic link") + if index + 1 == len(parts): + if not stat.S_ISREG(metadata.st_mode): + raise BundleError("tracked path is not a regular file") + return _identity(metadata) + if not stat.S_ISDIR(metadata.st_mode): + raise BundleError("tracked path has a non-directory parent") + raise BundleError("invalid tracked path") + + +def _git_environment(): + environment = os.environ.copy() + for name in tuple(environment): + if name.upper().startswith("GIT_"): + environment.pop(name, None) + environment["GIT_ATTR_NOSYSTEM"] = "1" + environment["GIT_CONFIG_GLOBAL"] = os.devnull + environment["GIT_CONFIG_NOSYSTEM"] = "1" + environment["GIT_LITERAL_PATHSPECS"] = "1" + environment["GIT_NO_LAZY_FETCH"] = "1" + environment["GIT_NO_REPLACE_OBJECTS"] = "1" + environment["GIT_OPTIONAL_LOCKS"] = "0" + environment["GIT_PAGER"] = "cat" + environment["GIT_TERMINAL_PROMPT"] = "0" + return environment + + +def _git_command(git: str, arguments): + return [git, "-c", "core.fsmonitor=false", "-c", "core.untrackedCache=false", *arguments] + + +def _run_git(git: str, root: Path, arguments, *, limit=MAX_GIT_LIST_BYTES) -> bytes: + try: + completed = subprocess.run( + _git_command(git, arguments), + cwd=root, + env=_git_environment(), + stdin=subprocess.DEVNULL, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + shell=False, + timeout=30, + ) + except (OSError, subprocess.SubprocessError) as exc: + raise BundleError("local Git inspection failed") from exc + if completed.returncode != 0: + raise BundleError("local Git inspection failed") + if len(completed.stdout) > limit: + raise BundleError("local Git metadata exceeds limit") + return completed.stdout + + +def _repository(git: str): + current = Path.cwd() + inside = _run_git(git, current, ["rev-parse", "--is-inside-work-tree"], limit=64) + if inside.strip() != b"true": + raise BundleError("current directory is not a Git worktree") + raw_root = _run_git(git, current, ["rev-parse", "--show-toplevel"], limit=16 * 1024) + try: + root_text = os.fsdecode(raw_root.rstrip(b"\r\n")) + except UnicodeError as exc: + raise BundleError("Git worktree path is not decodable") from exc + if not root_text or _has_control(root_text): + raise BundleError("Git worktree path is unsafe") + absolute_root = Path(os.path.abspath(root_text)) + try: + root = absolute_root.resolve(strict=True) + except PermissionError as exc: + if os.name != "nt": + raise BundleError("Git worktree root is unavailable") from exc + root = absolute_root + except (OSError, RuntimeError) as exc: + raise BundleError("Git worktree root is unavailable") from exc + if not root.is_dir(): + raise BundleError("Git worktree root is unavailable") + expected_script = root / "scripts" / "build_offline_bundle.py" + try: + if not os.path.samefile(Path(__file__), expected_script): + raise BundleError("builder must run from its repository") + except OSError as exc: + raise BundleError("builder must run from its repository") from exc + return root + + +def _assert_clean(git: str, root: Path): + index = _run_git(git, root, ["ls-files", "-v", "-z"]) + if index and not index.endswith(b"\0"): + raise BundleError("Git index listing is invalid") + for record in index.split(b"\0"): + if record and (len(record) < 3 or record[:2] != b"H "): + raise BundleError("Git index contains special tracked-file flags") + status = _run_git( + git, + root, + ["status", "--porcelain=v1", "-z", "--untracked-files=no", + "--ignore-submodules=none"], + ) + if status: + raise BundleError("tracked files or index differ from HEAD") + + +def _parse_tree(raw: bytes, object_format: str): + if raw and not raw.endswith(b"\0"): + raise BundleError("invalid Git tree listing") + digest_length = hashlib.new(object_format).digest_size * 2 + entries = [] + paths = set() + folded_paths = set() + total = 0 + for record in raw.split(b"\0"): + if not record: + continue + try: + metadata, raw_path = record.split(b"\t", 1) + mode, object_type, object_id, raw_size = metadata.split() + path = raw_path.decode("utf-8", "strict") + except (UnicodeError, ValueError) as exc: + raise BundleError("invalid Git tree entry") from exc + if object_type != b"blob" or mode not in {b"100644", b"100755"}: + raise BundleError("tracked symlink, submodule, or special entry") + try: + size = int(raw_size) + except ValueError as exc: + raise BundleError("invalid Git blob size") from exc + if size < 0 or size > MAX_MEMBER_BYTES: + raise BundleError("tracked file exceeds bundle limit") + try: + object_text = object_id.decode("ascii") + except UnicodeError as exc: + raise BundleError("invalid Git object identifier") from exc + if not _is_lower_hex(object_text, digest_length): + raise BundleError("invalid Git object identifier") + path = _validate_relative_path(path) + folded = path.casefold() + if path in paths or folded in folded_paths: + raise BundleError("duplicate or case-colliding tracked path") + paths.add(path) + folded_paths.add(folded) + total += size + if len(entries) >= MAX_MEMBERS - 2 or total > MAX_TOTAL_BYTES: + raise BundleError("tracked tree exceeds bundle limits") + entries.append({ + "git_mode": mode.decode("ascii"), + "mode": 0o755 if mode == b"100755" else 0o644, + "object": object_text, + "path": path, + "size": size, + }) + if not entries: + raise BundleError("Git HEAD contains no regular files") + entries.sort(key=lambda item: item["path"]) + return entries + + +def _git_snapshot(git: str, root: Path): + _assert_clean(git, root) + try: + object_format = _run_git( + git, root, ["rev-parse", "--show-object-format"], limit=32 + ).strip().decode("ascii") + except UnicodeError as exc: + raise BundleError("invalid Git object format") from exc + if object_format not in {"sha1", "sha256"}: + raise BundleError("unsupported Git object format") + try: + commit = _run_git( + git, root, ["rev-parse", "--verify", "HEAD^{commit}"], limit=128 + ).strip().decode("ascii") + commit_time_text = _run_git( + git, root, ["show", "-s", "--format=%ct", commit], limit=64 + ).strip().decode("ascii") + commit_time = int(commit_time_text) + except (UnicodeError, ValueError) as exc: + raise BundleError("invalid Git commit metadata") from exc + expected_length = hashlib.new(object_format).digest_size * 2 + if (not _is_lower_hex(commit, expected_length) or + not 0 <= commit_time <= 0xFFFFFFFF): + raise BundleError("invalid Git commit metadata") + tree_raw = _run_git( + git, root, ["ls-tree", "-r", "-z", "-l", "--full-tree", commit] + ) + entries = _parse_tree(tree_raw, object_format) + if "scripts/build_offline_bundle.py" not in {item["path"] for item in entries}: + raise BundleError("builder is not tracked in HEAD") + worktree = {item["path"]: _worktree_identity(root, item["path"]) for item in entries} + return { + "commit": commit, + "commit_time": commit_time, + "entries": entries, + "object_format": object_format, + "tree_raw": tree_raw, + "worktree": worktree, + } + + +def _assert_snapshot_unchanged(git: str, root: Path, snapshot): + _assert_clean(git, root) + current_commit = _run_git( + git, root, ["rev-parse", "--verify", "HEAD^{commit}"], limit=128 + ).strip() + if current_commit != snapshot["commit"].encode("ascii"): + raise BundleError("Git HEAD changed during bundle creation") + current_tree = _run_git( + git, root, + ["ls-tree", "-r", "-z", "-l", "--full-tree", snapshot["commit"]], + ) + if current_tree != snapshot["tree_raw"]: + raise BundleError("Git tree changed during bundle creation") + for path, before in snapshot["worktree"].items(): + if _worktree_identity(root, path) != before: + raise BundleError("tracked worktree changed during bundle creation") + + +class _BlobReader: + def __init__(self, stream, size: int, object_format: str): + self.stream = stream + self.remaining = size + self.sha256 = hashlib.sha256() + self.object_hash = hashlib.new(object_format) + self.object_hash.update(f"blob {size}\0".encode("ascii")) + self.private_key = False + self.tail = b"" + + def read(self, size=-1): + if self.remaining == 0: + return b"" + if size is None or size < 0 or size > self.remaining: + size = self.remaining + data = self.stream.read(size) + if not data: + raise BundleError("Git object read was incomplete") + self.remaining -= len(data) + self.sha256.update(data) + self.object_hash.update(data) + inspected = self.tail + data + if PRIVATE_KEY_HEADER.search(inspected): + self.private_key = True + self.tail = inspected[-128:] + return data + + +def _tar_info(name: str, *, size: int, mode: int, mtime: int, entry_type): + info = tarfile.TarInfo(name) + info.type = entry_type + info.size = size + info.mode = mode + info.mtime = mtime + info.uid = 0 + info.gid = 0 + info.uname = "" + info.gname = "" + info.linkname = "" + info.devmajor = 0 + info.devminor = 0 + info.pax_headers = {} + return info + + +def _add_git_blob(archive, git: str, root: Path, root_name: str, entry, object_format: str, + commit_time: int): + command = _git_command(git, ["cat-file", "blob", entry["object"]]) + try: + process = subprocess.Popen( + command, + cwd=root, + env=_git_environment(), + stdin=subprocess.DEVNULL, + stdout=subprocess.PIPE, + stderr=subprocess.DEVNULL, + shell=False, + ) + except OSError as exc: + raise BundleError("could not read a local Git object") from exc + if process.stdout is None: + process.kill() + raise BundleError("could not read a local Git object") + reader = _BlobReader(process.stdout, entry["size"], object_format) + info = _tar_info( + f"{root_name}/{entry['path']}", + size=entry["size"], + mode=entry["mode"], + mtime=commit_time, + entry_type=tarfile.REGTYPE, + ) + try: + archive.addfile(info, reader) + try: + return_code = process.wait(timeout=30) + except subprocess.TimeoutExpired as exc: + process.kill() + process.wait() + raise BundleError("local Git object read timed out") from exc + extra = process.stdout.read(1) + except BaseException: + if process.poll() is None: + process.kill() + process.wait() + raise + finally: + process.stdout.close() + if return_code != 0 or reader.remaining != 0 or extra: + raise BundleError("local Git object read was unstable") + if reader.object_hash.hexdigest() != entry["object"]: + raise BundleError("local Git object hash mismatch") + if reader.private_key: + raise BundleError("tracked file contains private-key material") + return { + "git_mode": entry["git_mode"], + "mode": entry["mode"], + "path": entry["path"], + "sha256": reader.sha256.hexdigest(), + "size": entry["size"], + } + + +def _prepare_output(value: Path): + if not str(value).endswith(".tar.gz"): + raise BundleError("output must end with .tar.gz") + output = _canonical_parent_with_leaf(value) + if _has_control(output.name): + raise BundleError("output filename is unsafe") + parent = output.parent + sidecar = Path(str(output) + ".sha256") + _reject_symlink_leaf(output) + _reject_symlink_leaf(sidecar) + if os.path.lexists(output) or os.path.lexists(sidecar): + raise BundleError("output or checksum sidecar already exists") + return output, sidecar + + +def _hash_regular_file(path: Path, limit: int): + flags = os.O_RDONLY | getattr(os, "O_BINARY", 0) | getattr(os, "O_NOFOLLOW", 0) + try: + descriptor = os.open(path, flags) + except OSError as exc: + raise BundleError("regular file is unavailable") from exc + try: + before = os.fstat(descriptor) + if not stat.S_ISREG(before.st_mode) or before.st_size > limit: + raise BundleError("regular file exceeds limit") + digest = hashlib.sha256() + consumed = 0 + with os.fdopen(descriptor, "rb", closefd=False) as stream: + while True: + block = stream.read(CHUNK) + if not block: + break + consumed += len(block) + if consumed > limit: + raise BundleError("regular file exceeds limit") + digest.update(block) + after = os.fstat(descriptor) + if _identity(before) != _identity(after) or consumed != before.st_size: + raise BundleError("regular file changed while reading") + return digest.hexdigest(), _identity(before) + finally: + os.close(descriptor) + + +def _write_sidecar(path: Path, archive_name: str, archive_sha256: str): + descriptor, temporary_name = tempfile.mkstemp(prefix=".durkahelper-sidecar-", dir=path.parent) + temporary = Path(temporary_name) + try: + payload = f"{archive_sha256} {archive_name}\n".encode("utf-8") + with os.fdopen(descriptor, "wb") as stream: + stream.write(payload) + stream.flush() + os.fsync(stream.fileno()) + try: + temporary.chmod(0o600) + except OSError: + pass + return temporary + except BaseException: + try: + os.close(descriptor) + except OSError: + pass + try: + temporary.unlink() + except OSError: + pass + raise + + +def _unlink_if_same(path: Path, temporary: Path): + try: + if os.path.samefile(path, temporary): + path.unlink() + except OSError: + pass + + +def _publish_pair(archive_temporary: Path, output: Path, sidecar_temporary: Path, + sidecar: Path): + linked_sidecar = False + linked_archive = False + try: + if os.path.lexists(output) or os.path.lexists(sidecar): + raise BundleError("output or checksum sidecar already exists") + os.link(sidecar_temporary, sidecar) + linked_sidecar = True + os.link(archive_temporary, output) + linked_archive = True + try: + directory_descriptor = os.open(output.parent, os.O_RDONLY) + except OSError: + directory_descriptor = None + if directory_descriptor is not None: + try: + os.fsync(directory_descriptor) + except OSError: + pass + finally: + os.close(directory_descriptor) + except (OSError, BundleError) as exc: + if linked_archive: + _unlink_if_same(output, archive_temporary) + if linked_sidecar: + _unlink_if_same(sidecar, sidecar_temporary) + if isinstance(exc, BundleError): + raise + raise BundleError("filesystem cannot atomically publish bundle") from exc + + +def build_bundle(output_value: Path): + output, sidecar = _prepare_output(output_value) + git = shutil.which("git") + if git is None: + raise BundleError("Git is required") + root = _repository(git) + snapshot = _git_snapshot(git, root) + root_name = "DurkaHelper-" + snapshot["commit"][:12] + + descriptor, temporary_name = tempfile.mkstemp(prefix=".durkahelper-bundle-", + suffix=".tmp", dir=output.parent) + temporary = Path(temporary_name) + sidecar_temporary = None + manifest_entries = [] + try: + try: + os.chmod(temporary, 0o600) + except OSError: + pass + with os.fdopen(descriptor, "wb") as raw_stream: + with gzip.GzipFile(filename="", mode="wb", compresslevel=9, + fileobj=raw_stream, mtime=snapshot["commit_time"]) as compressed: + with tarfile.open(fileobj=compressed, mode="w|", + format=tarfile.PAX_FORMAT, encoding="utf-8", + errors="strict") as archive: + archive.addfile(_tar_info( + root_name, + size=0, + mode=0o755, + mtime=snapshot["commit_time"], + entry_type=tarfile.DIRTYPE, + )) + for entry in snapshot["entries"]: + manifest_entries.append(_add_git_blob( + archive, git, root, root_name, entry, + snapshot["object_format"], snapshot["commit_time"] + )) + total_bytes = sum(item["size"] for item in manifest_entries) + manifest = { + "commit": snapshot["commit"], + "commit_time": snapshot["commit_time"], + "files": manifest_entries, + "root": root_name, + "schema": SCHEMA, + "summary": { + "files": len(manifest_entries), + "total_bytes": total_bytes, + }, + } + manifest_payload = _canonical_json(manifest) + if len(manifest_payload) > MAX_MANIFEST_BYTES: + raise BundleError("bundle manifest exceeds limit") + archive.addfile( + _tar_info( + f"{root_name}/{MANIFEST_NAME}", + size=len(manifest_payload), + mode=0o644, + mtime=snapshot["commit_time"], + entry_type=tarfile.REGTYPE, + ), + fileobj=_BytesReader(manifest_payload), + ) + raw_stream.flush() + os.fsync(raw_stream.fileno()) + + _assert_snapshot_unchanged(git, root, snapshot) + archive_sha256, _archive_identity = _hash_regular_file(temporary, MAX_ARCHIVE_BYTES) + sidecar_temporary = _write_sidecar( + sidecar, output.name, archive_sha256 + ) + _publish_pair(temporary, output, sidecar_temporary, sidecar) + return { + "archive_sha256": archive_sha256, + "files": len(manifest_entries), + "root": root_name, + "status": "created", + } + finally: + for path in (temporary, sidecar_temporary): + if path is not None: + try: + path.unlink() + except FileNotFoundError: + pass + except OSError: + pass + + +class _BytesReader: + def __init__(self, data: bytes): + self.data = data + self.offset = 0 + + def read(self, size=-1): + if size is None or size < 0: + size = len(self.data) - self.offset + end = min(self.offset + size, len(self.data)) + result = self.data[self.offset:end] + self.offset = end + return result + + +def _strict_gzip_chunks(raw_stream): + """Yield one gzip member and reject concatenated or trailing raw data.""" + decompressor = zlib.decompressobj(16 + zlib.MAX_WBITS) + while True: + compressed = raw_stream.read(CHUNK) + if not compressed: + break + pending = compressed + while pending: + try: + payload = decompressor.decompress(pending, CHUNK) + except zlib.error as exc: + raise BundleError("archive gzip stream is invalid") from exc + pending = decompressor.unconsumed_tail + if decompressor.eof: + if decompressor.unused_data or pending or raw_stream.read(1): + raise BundleError("archive has concatenated or trailing gzip data") + try: + flushed = decompressor.flush() + except zlib.error as exc: + raise BundleError("archive gzip stream is invalid") from exc + if payload: + yield payload + if flushed: + yield flushed + return + if payload: + yield payload + if not pending: + break + raise BundleError("archive gzip stream is truncated") + + +class _ChunkStream: + """Small bounded buffer over a byte-chunk iterator.""" + def __init__(self, chunks): + self.chunks = iter(chunks) + self.buffer = bytearray() + self.finished = False + + def read(self, size: int) -> bytes: + if size < 0: + raise BundleError("invalid archive stream read") + while len(self.buffer) < size and not self.finished: + try: + block = next(self.chunks) + except StopIteration: + self.finished = True + break + if block: + self.buffer.extend(block) + take = min(size, len(self.buffer)) + result = bytes(self.buffer[:take]) + del self.buffer[:take] + return result + + +def _read_exact(stream: _ChunkStream, size: int, message: str) -> bytes: + value = stream.read(size) + if len(value) != size: + raise BundleError(message) + return value + + +def _consume_stream(stream: _ChunkStream, size: int, *, require_zero=False): + remaining = size + while remaining: + block = _read_exact( + stream, min(CHUNK, remaining), "archive tar stream is truncated" + ) + if require_zero and block.strip(b"\0"): + raise BundleError("archive tar padding is not canonical") + remaining -= len(block) + + +def _tar_octal(field: bytes, label: str) -> int: + value = field.rstrip(b"\0 ") + if not value or any(character < ord("0") or character > ord("7") for character in value): + raise BundleError("archive tar " + label + " is invalid") + try: + return int(value, 8) + except ValueError as exc: + raise BundleError("archive tar " + label + " is invalid") from exc + + +def _validate_tar_header(block: bytes): + recorded = _tar_octal(block[148:156], "checksum") + calculated = sum(block[:148]) + (ord(" ") * 8) + sum(block[156:]) + if recorded != calculated: + raise BundleError("archive tar header checksum is invalid") + return _tar_octal(block[124:136], "size"), block[156:157] + + +def _validate_strict_gzip_tar(raw_stream): + """Validate the raw wrapper and canonical tar framing without extracting.""" + stream = _ChunkStream(_strict_gzip_chunks(raw_stream)) + zero_block = b"\0" * tarfile.BLOCKSIZE + raw_headers = 0 + regular_bytes = 0 + pax_bytes = 0 + pending_pax = False + offset = 0 + + while True: + header = _read_exact(stream, tarfile.BLOCKSIZE, "archive tar end marker is missing") + offset += tarfile.BLOCKSIZE + if header == zero_block: + second = _read_exact( + stream, tarfile.BLOCKSIZE, "archive tar end marker is incomplete" + ) + offset += tarfile.BLOCKSIZE + if second != zero_block or pending_pax: + raise BundleError("archive tar end marker is invalid") + canonical_size = ( + (offset + tarfile.RECORDSIZE - 1) // tarfile.RECORDSIZE + ) * tarfile.RECORDSIZE + _consume_stream(stream, canonical_size - offset, require_zero=True) + if stream.read(1): + raise BundleError("archive has data after the canonical tar end") + return + + raw_headers += 1 + if raw_headers > MAX_RAW_TAR_HEADERS: + raise BundleError("archive raw tar header limit exceeded") + size, entry_type = _validate_tar_header(header) + if entry_type == tarfile.XHDTYPE: + if pending_pax or size > MAX_PAX_BYTES: + raise BundleError("archive PAX header is invalid or too large") + pending_pax = True + pax_bytes += size + if pax_bytes > MAX_MEMBERS * MAX_PAX_BYTES: + raise BundleError("archive PAX data exceeds limit") + elif entry_type in {tarfile.REGTYPE, tarfile.AREGTYPE}: + pending_pax = False + if size > MAX_MEMBER_BYTES: + raise BundleError("archive member exceeds byte limit") + regular_bytes += size + if regular_bytes > MAX_TOTAL_BYTES + MAX_MANIFEST_BYTES: + raise BundleError("archive regular data exceeds byte limit") + elif entry_type == tarfile.DIRTYPE: + pending_pax = False + if size != 0: + raise BundleError("archive directory has data") + else: + raise BundleError("archive contains an unsupported raw tar entry") + + _consume_stream(stream, size) + padding = (-size) % tarfile.BLOCKSIZE + _consume_stream(stream, padding, require_zero=True) + offset += size + padding + + +def _read_sidecar(path: Path, archive_name: str): + path = _canonical_parent_with_leaf(path) + if not os.path.lexists(path): + return None + _reject_symlink_leaf(path) + flags = os.O_RDONLY | getattr(os, "O_BINARY", 0) | getattr(os, "O_NOFOLLOW", 0) + try: + descriptor = os.open(path, flags) + except OSError as exc: + raise BundleError("checksum sidecar is unreadable") from exc + try: + before = os.fstat(descriptor) + if not stat.S_ISREG(before.st_mode) or before.st_size > 4096: + raise BundleError("checksum sidecar is invalid") + with os.fdopen(descriptor, "rb", closefd=False) as stream: + raw = stream.read(4097) + after = os.fstat(descriptor) + if (_identity(before) != _identity(after) or len(raw) != before.st_size or + len(raw) > 4096): + raise BundleError("checksum sidecar changed while reading") + finally: + os.close(descriptor) + try: + value = raw.decode("utf-8", "strict") + except UnicodeError as exc: + raise BundleError("checksum sidecar is invalid") from exc + match = re.fullmatch(r"([0-9a-f]{64}) ([^\r\n]+)\n?", value) + if match is None or match.group(2) != archive_name: + raise BundleError("checksum sidecar is invalid") + return match.group(1) + + +def _scan_member(stream, size: int, *, retain=False): + digest = hashlib.sha256() + remaining = size + content = bytearray() if retain else None + tail = b"" + private_key = False + while remaining: + block = stream.read(min(CHUNK, remaining)) + if not block: + raise BundleError("archive member is truncated") + remaining -= len(block) + digest.update(block) + inspected = tail + block + if PRIVATE_KEY_HEADER.search(inspected): + private_key = True + tail = inspected[-128:] + if content is not None: + content.extend(block) + if stream.read(1): + raise BundleError("archive member exceeds declared size") + if private_key: + raise BundleError("archive contains private-key material") + return digest.hexdigest(), bytes(content) if content is not None else None + + +def _validate_member_metadata(member): + if (member.uid != 0 or member.gid != 0 or member.uname not in {"", None} or + member.gname not in {"", None} or member.linkname or + member.devmajor != 0 or member.devminor != 0): + raise BundleError("archive member metadata is not deterministic") + if member.pax_headers: + if set(member.pax_headers) != {"path"} or member.pax_headers["path"] != member.name: + raise BundleError("archive contains unexpected extended metadata") + + +def _parse_manifest(raw: bytes, root_name: str): + try: + value = json.loads( + raw.decode("utf-8", "strict"), + object_pairs_hook=_unique_object, + parse_constant=_reject_constant, + ) + except (UnicodeError, json.JSONDecodeError, RecursionError) as exc: + raise BundleError("bundle manifest is invalid") from exc + required = {"schema", "commit", "commit_time", "root", "files", "summary"} + if not isinstance(value, dict) or set(value) != required or value.get("schema") != SCHEMA: + raise BundleError("bundle manifest schema is invalid") + if (not isinstance(value["commit"], str) or not COMMIT_ID.fullmatch(value["commit"]) or + type(value["commit_time"]) is not int or + not 0 <= value["commit_time"] <= 0xFFFFFFFF or + value["root"] != root_name): + raise BundleError("bundle manifest commit metadata is invalid") + root_match = ROOT_NAME.fullmatch(root_name) + if root_match is None or root_match.group(1) != value["commit"][:12]: + raise BundleError("bundle root does not match manifest commit") + if not isinstance(value["files"], list) or not 1 <= len(value["files"]) <= MAX_MEMBERS - 2: + raise BundleError("bundle manifest file list is invalid") + expected = {} + folded_paths = set() + total = 0 + previous = None + for item in value["files"]: + keys = {"git_mode", "mode", "path", "sha256", "size"} + if not isinstance(item, dict) or set(item) != keys: + raise BundleError("bundle manifest file entry is invalid") + path = _validate_relative_path(item.get("path")) + folded = path.casefold() + if path in expected or folded in folded_paths or (previous is not None and path <= previous): + raise BundleError("bundle manifest paths are not unique and sorted") + folded_paths.add(folded) + previous = path + mode = item.get("mode") + git_mode = item.get("git_mode") + expected_git_mode = "100755" if mode == 0o755 else "100644" if mode == 0o644 else None + if (git_mode != expected_git_mode or type(item.get("size")) is not int or + not 0 <= item["size"] <= MAX_MEMBER_BYTES or + not isinstance(item.get("sha256"), str) or + not HEX_DIGEST.fullmatch(item["sha256"])): + raise BundleError("bundle manifest file metadata is invalid") + total += item["size"] + if total > MAX_TOTAL_BYTES: + raise BundleError("bundle manifest exceeds byte limit") + expected[path] = item + summary = value["summary"] + if (not isinstance(summary, dict) or set(summary) != {"files", "total_bytes"} or + summary["files"] != len(expected) or summary["total_bytes"] != total): + raise BundleError("bundle manifest summary is invalid") + return value, expected + + +def verify_bundle(archive_value: Path): + if not str(archive_value).endswith(".tar.gz"): + raise BundleError("archive must end with .tar.gz") + archive_path = _canonical_parent_with_leaf(archive_value) + _reject_symlink_leaf(archive_path) + if not archive_path.is_file(): + raise BundleError("archive is unavailable") + sidecar_path = Path(str(archive_path) + ".sha256") + sidecar_digest = _read_sidecar(sidecar_path, archive_path.name) + + flags = os.O_RDONLY | getattr(os, "O_BINARY", 0) | getattr(os, "O_NOFOLLOW", 0) + try: + descriptor = os.open(archive_path, flags) + except OSError as exc: + raise BundleError("archive is unavailable") from exc + try: + before = os.fstat(descriptor) + if (not stat.S_ISREG(before.st_mode) or before.st_size <= 0 or + before.st_size > MAX_ARCHIVE_BYTES): + raise BundleError("archive size is invalid") + with os.fdopen(descriptor, "rb", closefd=False) as stream: + digest = hashlib.sha256() + while True: + block = stream.read(CHUNK) + if not block: + break + digest.update(block) + archive_sha256 = digest.hexdigest() + if sidecar_digest is not None and sidecar_digest != archive_sha256: + raise BundleError("archive checksum does not match sidecar") + stream.seek(0) + gzip_header = stream.read(10) + if (len(gzip_header) != 10 or gzip_header[:3] != b"\x1f\x8b\x08" or + gzip_header[3] != 0 or gzip_header[8:] != b"\x02\xff"): + raise BundleError("archive gzip header is invalid") + gzip_mtime = int.from_bytes(gzip_header[4:8], "little") + stream.seek(0) + _validate_strict_gzip_tar(stream) + stream.seek(0) + + root_name = None + root_metadata = None + manifest_raw = None + manifest_metadata = None + actual = {} + member_names = [] + exact_names = set() + folded_names = set() + total = 0 + try: + with tarfile.open(fileobj=stream, mode="r:gz", encoding="utf-8", + errors="strict") as archive: + if archive.pax_headers: + raise BundleError("archive contains global extended metadata") + for member in archive: + if len(member_names) >= MAX_MEMBERS: + raise BundleError("archive member limit exceeded") + name = _validate_relative_path(member.name, repository_path=False) + folded = name.casefold() + if name in exact_names or folded in folded_names: + raise BundleError("archive contains duplicate member names") + exact_names.add(name) + folded_names.add(folded) + member_names.append(name) + _validate_member_metadata(member) + + if root_name is None: + if member.type != tarfile.DIRTYPE or ROOT_NAME.fullmatch(name) is None: + raise BundleError("archive does not start with one safe root") + if member.size != 0 or member.mode != 0o755: + raise BundleError("archive root metadata is invalid") + root_name = name + root_metadata = member + continue + prefix = root_name + "/" + if not name.startswith(prefix): + raise BundleError("archive member escapes bundle root") + relative = name[len(prefix):] + if member.type != tarfile.REGTYPE or member.sparse is not None: + raise BundleError("archive contains a link or special member") + if member.size < 0 or member.size > MAX_MEMBER_BYTES: + raise BundleError("archive member exceeds byte limit") + source = archive.extractfile(member) + if source is None: + raise BundleError("archive member is unreadable") + if relative == MANIFEST_NAME: + if manifest_raw is not None or member.size > MAX_MANIFEST_BYTES: + raise BundleError("archive manifest is missing or duplicated") + _manifest_hash, manifest_raw = _scan_member( + source, member.size, retain=True + ) + manifest_metadata = member + continue + relative = _validate_relative_path(relative) + if member.mode not in {0o644, 0o755}: + raise BundleError("archive file mode is invalid") + total += member.size + if total > MAX_TOTAL_BYTES: + raise BundleError("archive exceeds uncompressed byte limit") + sha256, _unused = _scan_member(source, member.size) + actual[relative] = { + "mode": member.mode, + "mtime": member.mtime, + "sha256": sha256, + "size": member.size, + } + except (tarfile.TarError, EOFError, UnicodeError) as exc: + raise BundleError("archive structure is invalid") from exc + + after = os.fstat(descriptor) + if _identity(before) != _identity(after): + raise BundleError("archive changed while verifying") + finally: + os.close(descriptor) + + if root_name is None or root_metadata is None or manifest_raw is None or manifest_metadata is None: + raise BundleError("archive root or manifest is missing") + manifest, expected = _parse_manifest(manifest_raw, root_name) + commit_time = manifest["commit_time"] + if gzip_mtime != commit_time: + raise BundleError("gzip timestamp does not match commit") + for metadata in (root_metadata, manifest_metadata): + if metadata.mtime != commit_time: + raise BundleError("archive member timestamp does not match commit") + if manifest_metadata.mode != 0o644: + raise BundleError("archive manifest mode is invalid") + if set(actual) != set(expected): + raise BundleError("archive members do not match manifest") + for path, wanted in expected.items(): + found = actual[path] + if (found["mode"] != wanted["mode"] or found["size"] != wanted["size"] or + found["sha256"] != wanted["sha256"] or found["mtime"] != commit_time): + raise BundleError("archive member does not match manifest") + expected_order = [root_name] + expected_order.extend(f"{root_name}/{path}" for path in expected) + expected_order.append(f"{root_name}/{MANIFEST_NAME}") + if member_names != expected_order: + raise BundleError("archive member order is not deterministic") + return { + "archive_sha256": archive_sha256, + "files": len(expected), + "root": root_name, + "sidecar": sidecar_digest is not None, + "status": "verified", + } + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + group = parser.add_mutually_exclusive_group(required=True) + group.add_argument("--output", type=Path, metavar="ARCHIVE.tar.gz") + group.add_argument("--verify", type=Path, metavar="ARCHIVE") + args = parser.parse_args(argv) + try: + result = build_bundle(args.output) if args.output is not None else verify_bundle(args.verify) + print(json.dumps(result, ensure_ascii=True, sort_keys=True)) + return 0 + except BundleError as exc: + print(f"offline bundle: {exc}", file=sys.stderr) + return 2 + except Exception as exc: + print(f"offline bundle: operation failed ({type(exc).__name__})", file=sys.stderr) + return 2 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/common.py b/scripts/common.py new file mode 100644 index 0000000..1c60e3f --- /dev/null +++ b/scripts/common.py @@ -0,0 +1,47 @@ +"""Small shared helpers; Python 3.10+, standard library only.""" +import argparse +import math +import re +from urllib.parse import urlsplit +from urllib.request import HTTPRedirectHandler, ProxyHandler, build_opener + + +class NoRedirect(HTTPRedirectHandler): + def redirect_request(self, req, fp, code, msg, headers, newurl): + return None + + +def opener(): + # Direct connections and no redirects: do not forward farm credentials. + return build_opener(ProxyHandler({}), NoRedirect()) + + +def http_url(value): + p = urlsplit(value) + if p.scheme not in {"http", "https"} or not p.hostname: + raise ValueError("expected an absolute http(s) URL") + if p.username is not None or p.password is not None or p.fragment: + raise ValueError("userinfo and fragments are not allowed in URLs") + _ = p.port # Validate malformed/out-of-range ports. + return value + + +def positive_float(value): + n = float(value) + if not math.isfinite(n) or n <= 0: + raise argparse.ArgumentTypeError("must be finite and greater than zero") + return n + + +def flag_pattern(value): + pattern = re.compile(value) + if pattern.search("") is not None: + raise ValueError("flag regex must not match the empty string") + return pattern + + +def limited_read(response, limit=1024 * 1024): + data = response.read(limit + 1) + if len(data) > limit: + raise ValueError(f"response exceeds {limit} bytes") + return data diff --git a/scripts/defense_diff.py b/scripts/defense_diff.py new file mode 100644 index 0000000..71e0ab4 --- /dev/null +++ b/scripts/defense_diff.py @@ -0,0 +1,295 @@ +#!/usr/bin/env python3 +"""Compare two saved defense_scan JSON reports offline; never open source paths.""" + +import argparse +from datetime import datetime +import hashlib +import json +import os +from pathlib import Path +import re +import stat +import sys + + +MAX_REPORT_BYTES = 32 * 1024 * 1024 +MAX_FINDINGS = 100000 +SCOPE_SCHEMA = "durkahelper.scanner-scope.v2" +LEGACY_SCOPE_SCHEMA = "durkahelper.scanner-scope.v1" +PATH_SEMANTICS = "root-relative-posix.v1" +NOTE = ("Matches exact path, line and rule ID without comparing source code. Moving lines creates a " + "new/not-observed pair. A disappearing signal does not prove a fix. " + "A clean comparison requires identical verified scopes.") + + +def file_identity(metadata): + return (metadata.st_dev, metadata.st_ino, metadata.st_mode, metadata.st_size, + metadata.st_mtime_ns, getattr(metadata, "st_ctime_ns", 0)) + + +def unique_object(pairs): + result = {} + for key, value in pairs: + if key in result: + raise ValueError("duplicate JSON key") + result[key] = value + return result + + +def _canonical_json(value): + return json.dumps(value, ensure_ascii=True, sort_keys=True, + separators=(",", ":")).encode("utf-8") + + +def _timestamp(value): + if not isinstance(value, str) or len(value) > 64 or not value.endswith("Z"): + raise ValueError("invalid timestamp") + try: + parsed = datetime.fromisoformat(value[:-1] + "+00:00") + except ValueError as exc: + raise ValueError("invalid timestamp") from exc + if parsed.utcoffset() is None or parsed.utcoffset().total_seconds() != 0: + raise ValueError("invalid timestamp") + return value + + +def _positive_integer(value): + if type(value) is not int or not 1 <= value <= 2**63 - 1: + raise ValueError("invalid scope integer") + return value + + +def validate_scope(scope): + expected = {"schema", "root", "rules_sha256", "exclude", "limits", + "path_semantics", "sha256"} + if not isinstance(scope, dict): + raise ValueError("invalid scope") + if scope.get("schema") == SCOPE_SCHEMA: + expected |= {"semantic_revision", "context_sha256"} + if set(scope) != expected: + raise ValueError("invalid scope") + if (not isinstance(scope["schema"], str) + or scope["schema"] not in {SCOPE_SCHEMA, LEGACY_SCOPE_SCHEMA} + or scope["path_semantics"] != PATH_SEMANTICS): + raise ValueError("unsupported scope") + if not isinstance(scope["root"], str) or not re.fullmatch(r"sha256:[0-9a-f]{64}", scope["root"]): + raise ValueError("invalid root identity") + if not isinstance(scope["rules_sha256"], str) or not re.fullmatch(r"[0-9a-f]{64}", scope["rules_sha256"]): + raise ValueError("invalid rules scope") + exclude = scope["exclude"] + if (not isinstance(exclude, list) or len(exclude) > 10000 + or any(not isinstance(item, str) or len(item) > 4096 or "\x00" in item + for item in exclude) + or exclude != sorted(set(exclude))): + raise ValueError("invalid exclusions scope") + limits = scope["limits"] + if not isinstance(limits, dict) or set(limits) != {"max_bytes", "max_files", "max_findings"}: + raise ValueError("invalid limits scope") + for field in ("max_bytes", "max_files", "max_findings"): + _positive_integer(limits[field]) + if not isinstance(scope["sha256"], str) or not re.fullmatch(r"[0-9a-f]{64}", scope["sha256"]): + raise ValueError("invalid scope digest") + sanitized = { + "schema": scope["schema"], + "root": scope["root"], + "rules_sha256": scope["rules_sha256"], + "exclude": list(exclude), + "limits": {field: limits[field] for field in + ("max_bytes", "max_files", "max_findings")}, + "path_semantics": PATH_SEMANTICS, + } + if scope["schema"] == SCOPE_SCHEMA: + if (scope["semantic_revision"] not in {"bounded-source-signals.v2", "bounded-source-signals.v3"} + or not isinstance(scope["context_sha256"], str) + or not re.fullmatch(r"[0-9a-f]{64}", scope["context_sha256"])): + raise ValueError("invalid scanner semantics or context digest") + sanitized.update(semantic_revision=scope["semantic_revision"], context_sha256=scope["context_sha256"]) + expected_digest = hashlib.sha256(_canonical_json(sanitized)).hexdigest() + if scope["sha256"] != expected_digest: + raise ValueError("scope digest mismatch") + sanitized["sha256"] = expected_digest + return sanitized + + +def load_report(filename, max_bytes=MAX_REPORT_BYTES): + requested = Path(os.path.abspath(filename)) + requested_metadata = requested.lstat() + if stat.S_ISLNK(requested_metadata.st_mode): + raise ValueError("symlink report") + # Resolve ordinary symlinked ancestors (notably macOS /tmp -> /private/tmp) + # before the no-follow leaf open. This prevents an ancestor swap from + # redirecting the descriptor while preserving the leaf-symlink boundary. + # Path.resolve() may require extra handle permissions on Windows. The + # macOS/Linux branch canonicalizes ancestors; Windows retains the absolute + # path after the explicit leaf-symlink check. + path = requested if os.name == "nt" else requested.parent.resolve(strict=True) / requested.name + canonical_metadata = path.lstat() + if stat.S_ISLNK(canonical_metadata.st_mode): + raise ValueError("symlink report") + if ((requested_metadata.st_dev, requested_metadata.st_ino, + stat.S_IFMT(requested_metadata.st_mode)) != + (canonical_metadata.st_dev, canonical_metadata.st_ino, + stat.S_IFMT(canonical_metadata.st_mode))): + raise ValueError("report changed before reading") + flags = (os.O_RDONLY | getattr(os, "O_BINARY", 0) | + getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0)) + fd = os.open(path, flags) + try: + metadata = os.fstat(fd) + if not stat.S_ISREG(metadata.st_mode) or metadata.st_size > max_bytes: + raise ValueError("report is not a bounded regular file") + if ((canonical_metadata.st_dev, canonical_metadata.st_ino, + stat.S_IFMT(canonical_metadata.st_mode)) != + (metadata.st_dev, metadata.st_ino, stat.S_IFMT(metadata.st_mode))): + raise ValueError("report changed before reading") + with os.fdopen(fd, "rb", closefd=False) as stream: + raw = stream.read(max_bytes + 1) + after = os.fstat(fd) + if len(raw) > max_bytes: + raise ValueError("report too large") + if file_identity(metadata) != file_identity(after) or len(raw) != metadata.st_size: + raise ValueError("report changed while reading") + finally: + os.close(fd) + data = json.loads(raw.decode("utf-8-sig"), object_pairs_hook=unique_object) + return validate_report(data) + + +def validate_report(data): + if not isinstance(data, dict) or data.get("tool") != "DurkaHelper defense_scan": + raise ValueError("not a scanner report") + if data.get("offline") is not True or type(data.get("partial")) is not bool: + raise ValueError("invalid report status") + version = data.get("version") + if not isinstance(version, str) or not re.fullmatch(r"[0-9][0-9A-Za-z.+-]{0,63}", version): + raise ValueError("invalid version") + if type(data.get("exit_code")) is not int or data["exit_code"] not in (0, 1, 2): + raise ValueError("invalid exit code") + scope = data.get("scope") + created_at = data.get("created_at") + if scope is None: + if created_at is not None: + _timestamp(created_at) + else: + if created_at is None: + raise ValueError("scoped report has no timestamp") + _timestamp(created_at) + scope = validate_scope(scope) + issues = data.get("issues") + findings = data.get("findings") + if not isinstance(issues, list) or not isinstance(findings, list) or len(findings) > MAX_FINDINGS: + raise ValueError("invalid collections") + indexed = {} + for finding in findings: + if not isinstance(finding, dict): + raise ValueError("invalid finding") + path, line, rule = (finding.get(field) for field in ("path", "line", "rule")) + if not isinstance(path, str) or not 1 <= len(path) <= 4096 or "\x00" in path: + raise ValueError("invalid path") + if type(line) is not int or not 1 <= line <= 2**63 - 1: + raise ValueError("invalid line") + if not isinstance(rule, str) or not re.fullmatch(r"[A-Z][A-Z0-9]*(?:-[A-Z0-9]+)+", rule) or len(rule) > 100: + raise ValueError("invalid rule ID") + key = (path, line, rule) + if key in indexed: + raise ValueError("duplicate finding") + # Do not copy source text, patches, arbitrary descriptions or issue payloads. + indexed[key] = {"path": path, "line": line, "rule": rule} + return {"version": version, "created_at": created_at, "scope": scope, + "scope_sha256": scope["sha256"] if scope is not None else None, + "partial": data["partial"] or bool(issues) or data["exit_code"] == 2, + "issue_count": len(issues), "findings": indexed} + + +def compare_reports(before, after): + old, new = before["findings"], after["findings"] + warnings = [] + if before["partial"]: + warnings.append("before_partial") + if after["partial"]: + warnings.append("after_partial") + if before["version"] != after["version"]: + warnings.append("scanner_version_changed") + if before["scope"] is None or after["scope"] is None: + warnings.append("scope_unverified") + elif before["scope"] != after["scope"]: + warnings.append("scope_changed") + scope_verified = before["scope"] is not None and before["scope"] == after["scope"] + added = [new[key] for key in sorted(new.keys() - old.keys())] + existing = [new[key] for key in sorted(new.keys() & old.keys())] + absent = [old[key] for key in sorted(old.keys() - new.keys())] + return {"tool": "DurkaHelper defense_diff", "offline": True, + "matching": ["path", "line", "rule"], "scope_verified": scope_verified, + "before": {"version": before["version"], "partial": before["partial"], + "issue_count": before["issue_count"], + "scope_sha256": before["scope_sha256"]}, + "after": {"version": after["version"], "partial": after["partial"], + "issue_count": after["issue_count"], + "scope_sha256": after["scope_sha256"]}, + "new": added, "existing": existing, "not_observed": absent, + "counts": {"new": len(added), "existing": len(existing), "not_observed": len(absent)}, + "warnings": warnings, "partial": bool(warnings), "note": NOTE, + "exit_code": 2 if warnings else 1 if added else 0} + + +def printable(value): + return str(value) if str(value).isprintable() else json.dumps(str(value), ensure_ascii=True) + + +def positive(value): + number = int(value) + if number <= 0: + raise argparse.ArgumentTypeError("expected a positive integer") + return number + + +def configure_text_output(): + """Keep CLI diagnostics printable on legacy Windows code pages.""" + for stream in (sys.stdout, sys.stderr): + reconfigure = getattr(stream, "reconfigure", None) + if reconfigure is not None: + try: + reconfigure(errors="backslashreplace") + except (AttributeError, OSError, ValueError): + pass + + +def main(argv=None): + configure_text_output() + parser = argparse.ArgumentParser(description="Compare two defense_scan JSON reports without reading source files.") + parser.add_argument("before", help="previous JSON report") + parser.add_argument("after", help="current JSON report") + parser.add_argument("--json", action="store_true", help="structured JSON result") + parser.add_argument("--show-existing", action="store_true", help="also show unchanged signals in text output") + parser.add_argument("--max-bytes", type=positive, default=MAX_REPORT_BYTES, help="size limit for each report; default 32 MiB") + args = parser.parse_args(argv) + try: + report = compare_reports(load_report(args.before, args.max_bytes), load_report(args.after, args.max_bytes)) + except (OSError, ValueError, OverflowError, RecursionError, MemoryError) as exc: + # Exception messages can contain report contents, paths or secret fields. + error = {"error": "invalid_or_unreadable_report", "type": type(exc).__name__, "exit_code": 2} + print(json.dumps(error) if args.json else "ERROR: invalid or unreadable report (" + type(exc).__name__ + ").") + return 2 + if args.json: + print(json.dumps(report, ensure_ascii=True, indent=2)) + else: + for field, label in (("new", "NEW"), ("not_observed", "NOT OBSERVED"), ("existing", "EXISTING")): + if field == "existing" and not args.show_existing: + continue + for finding in report[field]: + print(f"{label}: {printable(finding['path'])}:{finding['line']} [{finding['rule']}]") + counts = report["counts"] + print(f"New: {counts['new']}; existing: {counts['existing']}; not observed: {counts['not_observed']}.") + if report["warnings"]: + descriptions = {"before_partial": "previous scan is partial", + "after_partial": "current scan is partial", + "scanner_version_changed": "scanner versions differ", + "scope_unverified": "scope is missing or unverified", + "scope_changed": "report scopes differ"} + print("Incomplete comparison: " + ", ".join(descriptions[item] for item in report["warnings"])) + print(NOTE) + return report["exit_code"] + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/defense_ops.py b/scripts/defense_ops.py new file mode 100644 index 0000000..6bf91f9 --- /dev/null +++ b/scripts/defense_ops.py @@ -0,0 +1,4469 @@ +#!/usr/bin/env python3 +"""Bounded, read-only-by-default defense operations for DurkaHelper. + +The profile format is declarative: it cannot name commands or executable +arguments. Platform inventory adapters and every subprocess argument are +hardcoded in this file. Mutating operations only create new local artifacts +and never overwrite an existing path. +""" +from __future__ import annotations + +import argparse +from collections import Counter +import csv +import datetime as dt +import fnmatch +import hashlib +import ipaddress +import json +import math +import os +from pathlib import Path, PurePosixPath +import platform +import re +import secrets +import shutil +import stat +import subprocess +import sys +import tempfile +import time +import unicodedata +from urllib.error import HTTPError +from urllib.parse import urlsplit +from urllib.request import HTTPRedirectHandler, ProxyHandler, Request, build_opener + + +VERSION = "2.2.0" +TOOL = "DurkaHelper defense_ops" + +PROFILE_SCHEMA = "durkahelper.profile.v1" +SNAPSHOT_SCHEMA = "durkahelper.snapshot.v1" +COMPARISON_SCHEMA = "durkahelper.comparison.v1" +BACKUP_SCHEMA = "durkahelper.backup-manifest.v1" +EVENT_SCHEMA = "durkahelper.event.v1" +VALIDATION_SCHEMA = "durkahelper.validation-record.v1" +APPROVED_DRIFT_SCHEMA = "durkahelper.approved-drift.v1" +SNAPSHOT_SCOPE_SCHEMA = "durkahelper.snapshot-scope.v1" +SNAPSHOT_TOOL_COMPATIBILITY = "durkahelper-defense-ops-major-2" +SCANNER_SCOPE_SCHEMA = "durkahelper.scanner-scope.v1" +SCANNER_SCOPE_V2 = "durkahelper.scanner-scope.v2" +SCANNER_PATH_SEMANTICS = "root-relative-posix.v1" +DEPLOYMENT_MODEL_SCHEMA = "durkahelper.deployment-model.v1" +DEPLOYMENT_POLICY_SCHEMA = "durkahelper.deployment-policy.v1" +DEPLOYMENT_AUDIT_SCHEMA = "durkahelper.deployment-audit.v1" + +ADAPTER_SEMANTICS = { + "platform": "platform-system-machine-release-python-v1", + "processes": "process-name-uid-count-v1", + "listeners": "listener-endpoint-no-pid-v1", + "services": "service-state-no-pid-v1", + "compose": "compose-explicit-project-config-hash-service-state-v1", +} + +MAX_JSON_BYTES = 64 * 1024 * 1024 +MAX_PROFILE_BYTES = 1024 * 1024 +MAX_EVENTS = 100_000 +MAX_EVENT_LINE = 1024 * 1024 +MAX_HTTP_BODY = 1024 * 1024 +MAX_ADAPTER_OUTPUT = 8 * 1024 * 1024 +MAX_COMPOSE_FILE_BYTES = 16 * 1024 * 1024 +CHUNK = 1024 * 1024 +MAX_IMPORTED_FILE_BYTES = 4 * 1024 ** 3 +MAX_IMPORTED_TOTAL_BYTES = 100 * 1024 ** 3 +MAX_MTIME_NS = 253402300799999999999 +DIRECTORY_STAGING_SUPPORTED = os.name == "posix" +ATOMIC_DIRFD_SUPPORTED = all(function in os.supports_dir_fd for function in + (os.open, os.stat, os.link, os.unlink)) +DIRECTORY_DIRFD_SUPPORTED = all(function in os.supports_dir_fd for function in + (os.open, os.mkdir, os.stat, os.unlink, os.rmdir)) + +DEFAULT_ADAPTERS = ("platform", "processes", "listeners", "services") +ADAPTERS = DEFAULT_ADAPTERS + ("compose",) +COMMAND_KEYS = { + "arg", "args", "argv", "cmd", "command", "commands", "exec", + "executable", "hook", "program", "script", "shell", "subprocess", +} +SECRET_KEY = re.compile( + r"password|passwd|pwd|secret|token|credential|authorization|cookie|" + r"privatekey|apikey|accesskey|session|dsn|connectionstring", re.I) +SECRET_NAME = re.compile( + r"(^|[._-])(secret|secrets|credential|credentials|token|tokens|password|" + r"passwd|private[._-]?key)([._-]|$)", re.I) +SECRET_VALUE_PATTERNS = ( + re.compile(r"-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----"), + re.compile(r"\bAKIA[0-9A-Z]{16}\b"), + re.compile(r"\b(?:Bearer|Basic)\s+[A-Za-z0-9._~+/=-]{8,}", re.I), + re.compile(r"\b(?:password|passwd|secret|token|api[_-]?key)\s*[:=]\s*\S+", re.I), +) +LIVE_DATABASE_SUFFIXES = (".db", ".sqlite", ".sqlite3", ".mdb", ".accdb", ".rdb", ".aof") +NATIVE_DUMP_SUFFIXES = ( + ".sql", ".dump", ".backup", ".bak", ".tar", ".gz", ".zst", + ".xz", ".bz2", ".rdb", +) +SAFE_EVIDENCE_EXTENSIONS = (".json", ".jsonl") +SNAPSHOT_SKIP_DIRS = { + ".git", ".hg", ".svn", ".venv", "venv", "node_modules", "vendor", + "__pycache__", ".cache", "artifacts", "dist", "build", "target", "obj", "bin", + ".ssh", ".aws", ".gnupg", ".kube", +} +APPROVAL_ID = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]{7,127}\Z") +IDENTIFIER = re.compile(r"[a-z0-9][a-z0-9_.-]{0,63}\Z") +RFC3339 = re.compile( + r"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,6})?(?:Z|[+-]\d{2}:\d{2})\Z") +OPAQUE_ID = re.compile(r"sha256:[0-9a-f]{64}\Z") +WINDOWS_RESERVED_NAMES = { + "CON", "PRN", "AUX", "NUL", + *(f"COM{number}" for number in range(1, 10)), + *(f"LPT{number}" for number in range(1, 10)), +} + + +class DefenseError(Exception): + """Expected, sanitized validation or safety failure.""" + + +class PartialError(DefenseError): + """A requested read-only observation could not be completed.""" + + +def _unique_object(pairs): + result = {} + for key, value in pairs: + if key in result: + raise DefenseError("duplicate JSON key") + result[key] = value + return result + + +def _reject_constant(_value): + raise DefenseError("non-finite JSON number") + + +def _canonical(value) -> bytes: + return (json.dumps(value, ensure_ascii=True, sort_keys=True, + separators=(",", ":"), allow_nan=False) + "\n").encode("utf-8") + + +def _bounded_canonical(value, limit=MAX_JSON_BYTES, field="JSON artifact") -> bytes: + payload = _canonical(value) + if len(payload) > limit: + raise PartialError(field + " exceeds byte limit") + return payload + + +def _sha256_bytes(data: bytes) -> str: + return hashlib.sha256(data).hexdigest() + + +def _now() -> str: + return dt.datetime.now(dt.timezone.utc).isoformat(timespec="seconds").replace("+00:00", "Z") + + +def _tool_record(): + return {"name": TOOL, "version": VERSION} + + +def _is_regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def _canonical_parent_with_leaf(path: Path) -> Path: + """Resolve existing ancestor links while leaving the final name untouched.""" + absolute = Path(os.path.abspath(path)) + try: + parent = absolute.parent.resolve(strict=True) + except PermissionError as exc: + # Some managed Windows sandboxes deny realpath queries even when the + # directory itself is readable. Absolute NT paths still preserve the + # leaf no-follow/no-overwrite checks used below. + if os.name != "nt": + raise DefenseError("path parent is unavailable") from exc + parent = absolute.parent + except (OSError, RuntimeError) as exc: + raise DefenseError("path parent is unavailable") from exc + if not parent.is_dir(): + raise DefenseError("path parent must be a directory") + return parent / absolute.name + + +def _canonical_input_leaf(path: Path) -> Path: + """Canonicalize ancestors but reject an input whose final entry is a link.""" + absolute = Path(os.path.abspath(path)) + try: + if absolute.is_symlink(): + raise DefenseError("input leaf cannot be a symlink") + except OSError as exc: + raise DefenseError("path metadata unavailable") from exc + canonical = _canonical_parent_with_leaf(absolute) + try: + if canonical.is_symlink(): + raise DefenseError("input leaf cannot be a symlink") + except OSError as exc: + raise DefenseError("path metadata unavailable") from exc + return canonical + + +def _canonical_root_directory(path: Path) -> Path: + """Resolve ancestor aliases while rejecting a symlink supplied as the root.""" + absolute = Path(os.path.abspath(path)) + try: + metadata = absolute.lstat() + except (OSError, RuntimeError) as exc: + raise DefenseError("root path is unavailable") from exc + if stat.S_ISLNK(metadata.st_mode): + raise DefenseError("root leaf cannot be a symlink") + try: + canonical = absolute if os.name == "nt" else absolute.parent.resolve(strict=True) / absolute.name + except PermissionError as exc: + if os.name != "nt": + raise DefenseError("root path is unavailable") from exc + canonical = absolute + except (OSError, RuntimeError) as exc: + raise DefenseError("root path is unavailable") from exc + try: + canonical_metadata = canonical.lstat() + except OSError as exc: + raise DefenseError("root path is unavailable") from exc + if stat.S_ISLNK(canonical_metadata.st_mode): + raise DefenseError("root leaf cannot be a symlink") + if ((metadata.st_dev, metadata.st_ino, stat.S_IFMT(metadata.st_mode)) != + (canonical_metadata.st_dev, canonical_metadata.st_ino, + stat.S_IFMT(canonical_metadata.st_mode))): + raise DefenseError("root changed during canonicalization") + if not canonical.is_dir(): + raise DefenseError("root must be a directory") + return canonical + + +def _read_regular_bytes(path, limit=MAX_JSON_BYTES) -> bytes: + path = _canonical_input_leaf(Path(path)) + flags = (os.O_RDONLY | getattr(os, "O_BINARY", 0) | + getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0)) + try: + fd = os.open(path, flags) + except OSError as exc: + raise DefenseError("unreadable input") from exc + try: + before = os.fstat(fd) + if not stat.S_ISREG(before.st_mode) or before.st_size > limit: + raise DefenseError("input is not a bounded regular file") + with os.fdopen(fd, "rb", closefd=False) as stream: + data = stream.read(limit + 1) + after = os.fstat(fd) + if len(data) > limit: + raise DefenseError("input exceeds byte limit") + if _stat_identity(before) != _stat_identity(after): + raise DefenseError("input changed while reading") + return data + finally: + os.close(fd) + + +def _read_json(path, limit=MAX_JSON_BYTES): + raw = _read_regular_bytes(path, limit) + try: + return json.loads(raw.decode("utf-8-sig"), object_pairs_hook=_unique_object, + parse_constant=_reject_constant), raw + except (UnicodeError, json.JSONDecodeError, RecursionError) as exc: + raise DefenseError("invalid JSON input") from exc + + +def _stat_identity(value): + return (value.st_dev, value.st_ino, value.st_mode, value.st_size, + value.st_mtime_ns, getattr(value, "st_ctime_ns", 0)) + + +def _safe_string(value, field, minimum=1, maximum=4096): + if not isinstance(value, str) or not minimum <= len(value) <= maximum or "\x00" in value: + raise DefenseError("invalid " + field) + return value + + +def _positive_int(value, field, maximum): + if type(value) is not int or not 1 <= value <= maximum: + raise DefenseError("invalid " + field) + return value + + +def _positive_float_value(value, field="timeout", maximum=60.0): + if type(value) not in (int, float): + raise DefenseError("invalid " + field) + number = float(value) + if not math.isfinite(number) or not 0 < number <= maximum: + raise DefenseError("invalid " + field) + return number + + +def _strict_keys(value, allowed, required=(), field="object"): + if not isinstance(value, dict) or set(value) - set(allowed) or not set(required) <= set(value): + raise DefenseError("invalid " + field + " fields") + + +def _normalized_key(value): + return re.sub(r"[^a-z0-9]", "", str(value).lower()) + + +def _reject_declarative_hazards(value): + if isinstance(value, dict): + for key, child in value.items(): + if _normalized_key(key) in COMMAND_KEYS or SECRET_KEY.search(_normalized_key(key)): + raise DefenseError("profile contains a forbidden field") + _reject_declarative_hazards(child) + elif isinstance(value, list): + for child in value: + _reject_declarative_hazards(child) + + +def _relative_posix(value, field="path", *, allow_dot=False) -> str: + _safe_string(value, field, 1, 1024) + if unicodedata.normalize("NFC", value) != value: + raise DefenseError("non-NFC relative " + field) + if "\\" in value or ":" in value or value.startswith("/"): + raise DefenseError("invalid relative " + field) + parts = value.split("/") + if (any(part in {"", ".."} for part in parts) or + any(part == "." for part in parts) and not (allow_dot and value == ".")): + raise DefenseError("invalid relative " + field) + if value == "." and not allow_dot: + raise DefenseError("invalid relative " + field) + return PurePosixPath(value).as_posix() + + +def _portable_relative_posix(value, field="path", *, allow_dot=False) -> str: + normalized = _relative_posix(value, field, allow_dot=allow_dot) + if normalized == ".": + return normalized + for component in normalized.split("/"): + if (component.endswith((".", " ")) or + any(ord(character) < 32 or character in '<>"|?*' for character in component)): + raise DefenseError("nonportable relative " + field) + stem = component.split(".", 1)[0].rstrip(" .").upper() + if stem in WINDOWS_RESERVED_NAMES: + raise DefenseError("reserved relative " + field) + return normalized + + +def _portable_path_key(value): + return unicodedata.normalize("NFC", value).casefold() + + +def _opaque_text_identifier(value) -> str: + return "sha256:" + _sha256_bytes(value.encode("utf-8", errors="surrogatepass")) + + +def _opaque_root_identifier(root: Path) -> str: + normalized = unicodedata.normalize("NFC", os.path.normcase(str(root))) + return _opaque_text_identifier("durkahelper-root-v1\x00" + normalized) + + +def _relative_glob(value, field="glob") -> str: + _safe_string(value, field, 1, 512) + if unicodedata.normalize("NFC", value) != value: + raise DefenseError("non-NFC relative " + field) + if "\\" in value or ":" in value or value.startswith("/") or "\x00" in value: + raise DefenseError("invalid relative " + field) + if any(part in {"", ".", ".."} for part in value.split("/")): + raise DefenseError("invalid relative " + field) + return value + + +def _safe_output_target(path: Path): + target = _canonical_parent_with_leaf(Path(path)) + try: + parent_metadata = target.parent.lstat() + except OSError as exc: + raise DefenseError("output parent is unavailable") from exc + if not stat.S_ISDIR(parent_metadata.st_mode) or stat.S_ISLNK(parent_metadata.st_mode): + raise DefenseError("output parent must be a real directory") + if target.exists() or target.is_symlink(): + raise DefenseError("output already exists") + parent_identity = (parent_metadata.st_dev, parent_metadata.st_ino, + stat.S_IFMT(parent_metadata.st_mode)) + return target, parent_identity + + +def _safe_output_parent(path: Path): + return _safe_output_target(path)[0] + + +def _atomic_write_new(path, data: bytes, mode=0o600): + target, expected_parent_identity = _safe_output_target(Path(path)) + if os.name != "nt": + if (not ATOMIC_DIRFD_SUPPORTED or not hasattr(os, "O_DIRECTORY") or + not hasattr(os, "O_NOFOLLOW")): + raise DefenseError("filesystem lacks safe atomic publication support") + parent_fd = os.open(target.parent, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW) + temporary_name = None + try: + if _root_anchor_identity(os.fstat(parent_fd)) != expected_parent_identity: + raise DefenseError("output parent changed during validation") + try: + os.stat(target.name, dir_fd=parent_fd, follow_symlinks=False) + except FileNotFoundError: + pass + else: + raise DefenseError("output already exists") + for _attempt in range(16): + candidate = ".defense-" + secrets.token_hex(16) + try: + fd = os.open(candidate, os.O_WRONLY | os.O_CREAT | os.O_EXCL | + getattr(os, "O_BINARY", 0), mode, dir_fd=parent_fd) + except FileExistsError: + continue + temporary_name = candidate + break + else: + raise DefenseError("could not reserve temporary output") + try: + _write_all(fd, data) + os.fsync(fd) + try: + os.fchmod(fd, mode) + except OSError: + pass + finally: + os.close(fd) + try: + os.link(temporary_name, target.name, src_dir_fd=parent_fd, + dst_dir_fd=parent_fd, follow_symlinks=False) + except FileExistsError as exc: + raise DefenseError("output already exists") from exc + os.unlink(temporary_name, dir_fd=parent_fd) + temporary_name = None + os.fsync(parent_fd) + return target + finally: + if temporary_name is not None: + try: + os.unlink(temporary_name, dir_fd=parent_fd) + except OSError: + pass + os.close(parent_fd) + + if _root_anchor_identity(target.parent.lstat()) != expected_parent_identity: + raise DefenseError("output parent changed during validation") + fd, temporary_name = tempfile.mkstemp(prefix=".defense-", dir=target.parent) + temporary = Path(temporary_name) + try: + with os.fdopen(fd, "wb") as stream: + stream.write(data) + stream.flush() + os.fsync(stream.fileno()) + try: + temporary.chmod(mode) + except OSError: + pass + try: + if os.name == "nt": + # Windows rename is an atomic no-replace operation for a new + # destination. Hard links may be denied in managed sandboxes. + os.rename(temporary, target) + temporary = None + else: + # link(2) is atomic and fails when the destination already + # exists, unlike POSIX rename(2), which would replace it. + os.link(temporary, target, follow_symlinks=False) + except (OSError, NotImplementedError) as exc: + if target.exists() or target.is_symlink(): + raise DefenseError("output already exists") from exc + if os.name == "nt" and isinstance(exc, PermissionError): + # Some managed Windows sandboxes prohibit rename/link inside + # their virtual Temp directory. CREATE_NEW still preserves + # the critical no-overwrite property; delete on any short + # write so a partial result is never retained. + direct_fd = None + created = False + created_identity = None + try: + direct_fd = os.open(target, os.O_WRONLY | os.O_CREAT | os.O_EXCL | + getattr(os, "O_BINARY", 0), mode) + created = True + metadata = os.fstat(direct_fd) + created_identity = (metadata.st_dev, metadata.st_ino) + with os.fdopen(direct_fd, "wb") as direct: + direct_fd = None + direct.write(data) + direct.flush() + os.fsync(direct.fileno()) + try: + target.chmod(mode) + except OSError: + pass + return target + except OSError as direct_exc: + if direct_fd is not None: + os.close(direct_fd) + if created: + try: + current = target.lstat() + if (current.st_dev, current.st_ino) == created_identity: + target.unlink() + except OSError: + pass + raise DefenseError("filesystem cannot create output safely") from direct_exc + raise DefenseError("filesystem cannot atomically create output") from exc + finally: + if temporary is not None: + try: + temporary.unlink() + except FileNotFoundError: + pass + return target + + +def _publication_items(temporary: Path): + items = sorted(temporary.iterdir(), key=lambda item: item.name) + count = 0 + for item in items: + try: + metadata = item.lstat() + except OSError as exc: + raise DefenseError("temporary publication is unreadable") from exc + if stat.S_ISLNK(metadata.st_mode): + raise DefenseError("temporary publication contains a symlink") + if stat.S_ISDIR(metadata.st_mode): + for root, directories, files in os.walk(item, followlinks=False): + count += len(directories) + len(files) + if count > 100_000: + raise PartialError("temporary publication entry limit reached") + for name in directories + files: + candidate = Path(root) / name + candidate_metadata = candidate.lstat() + if (stat.S_ISLNK(candidate_metadata.st_mode) or + not (stat.S_ISREG(candidate_metadata.st_mode) or + stat.S_ISDIR(candidate_metadata.st_mode))): + raise DefenseError("temporary publication contains a special entry") + elif not stat.S_ISREG(metadata.st_mode): + raise DefenseError("temporary publication contains a special entry") + manifests = [item for item in items if item.name == "manifest.json"] + ordinary = [item for item in items if item.name != "manifest.json"] + return ordinary + manifests + + +def _write_all(fd, data): + view = memoryview(data) + while view: + written = os.write(fd, view) + if written <= 0: + raise OSError("short write") + view = view[written:] + + +class _StagingDirectory: + """Private output tree anchored to the directory descriptors that created it.""" + + def __init__(self, target, path, parent_identity, identity, *, parent_fd=None, + directory_fd=None): + self.target = target + self.path = path + self.name = path.name + self.parent_identity = parent_identity + self.identity = identity + self.parent_fd = parent_fd + self.directory_fd = directory_fd + self.ledger = {} + self.consumed = False + self.closed = False + + @classmethod + def create(cls, target: Path, prefix: str): + target, parent_identity = _safe_output_target(Path(target)) + if not DIRECTORY_STAGING_SUPPORTED: + raise PartialError("secure directory staging is unavailable on Windows") + if (not DIRECTORY_DIRFD_SUPPORTED or not hasattr(os, "O_DIRECTORY") or + not hasattr(os, "O_NOFOLLOW")): + raise DefenseError("filesystem lacks safe staging support") + parent_metadata = target.parent.lstat() + if (parent_metadata.st_uid != os.geteuid() or + stat.S_IMODE(parent_metadata.st_mode) & 0o022): + raise PartialError("staging parent is not owner-controlled") + parent_fd = os.open(target.parent, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW) + directory_fd = None + name = None + created_identity = None + try: + if _root_anchor_identity(os.fstat(parent_fd)) != parent_identity: + raise DefenseError("output parent changed during validation") + try: + os.stat(target.name, dir_fd=parent_fd, follow_symlinks=False) + except FileNotFoundError: + pass + else: + raise DefenseError("output already exists") + for _attempt in range(16): + candidate = prefix + secrets.token_hex(16) + try: + os.mkdir(candidate, 0o700, dir_fd=parent_fd) + except FileExistsError: + continue + name = candidate + created = os.stat(name, dir_fd=parent_fd, follow_symlinks=False) + if not stat.S_ISDIR(created.st_mode) or stat.S_ISLNK(created.st_mode): + raise DefenseError("staging creation did not produce a directory") + created_identity = _root_anchor_identity(created) + break + else: + raise DefenseError("could not reserve staging directory") + directory_fd = os.open(name, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, + dir_fd=parent_fd) + identity = _root_anchor_identity(os.fstat(directory_fd)) + current = os.stat(name, dir_fd=parent_fd, follow_symlinks=False) + if identity != created_identity or _root_anchor_identity(current) != identity: + raise DefenseError("staging directory changed during creation") + return cls(target, target.parent / name, parent_identity, identity, + parent_fd=parent_fd, directory_fd=directory_fd) + except BaseException: + if directory_fd is not None: + os.close(directory_fd) + if name is not None and created_identity is not None: + try: + current = os.stat(name, dir_fd=parent_fd, follow_symlinks=False) + if _root_anchor_identity(current) == created_identity: + os.rmdir(name, dir_fd=parent_fd) + except OSError: + pass + os.close(parent_fd) + raise + + def _assert_open(self): + if self.closed: + raise DefenseError("staging directory is closed") + + def _assert_named_identity(self): + self._assert_open() + if self.parent_fd is not None: + self._assert_parent_path_identity() + if _root_anchor_identity(os.fstat(self.parent_fd)) != self.parent_identity: + raise DefenseError("staging parent changed") + current = os.stat(self.name, dir_fd=self.parent_fd, follow_symlinks=False) + if _root_anchor_identity(current) != self.identity: + raise DefenseError("staging directory changed") + if _root_anchor_identity(os.fstat(self.directory_fd)) != self.identity: + raise DefenseError("staging descriptor changed") + return + if (_root_anchor_identity(self.path.parent.lstat()) != self.parent_identity or + _root_anchor_identity(self.path.lstat()) != self.identity): + raise DefenseError("staging directory changed") + + def _assert_parent_path_identity(self): + self._assert_open() + try: + current = self.target.parent.lstat() + except OSError as exc: + raise DefenseError("staging parent path is unavailable") from exc + if _root_anchor_identity(current) != self.parent_identity: + raise DefenseError("staging parent path changed") + + def _relative_parts(self, relative): + normalized = _portable_relative_posix(str(relative), "staging path") + if normalized == ".": + raise DefenseError("staging path must name an entry") + return normalized, normalized.split("/") + + def _open_parent_fd(self, parts, create): + current_fd = os.dup(self.directory_fd) + traversed = [] + try: + for part in parts: + traversed.append(part) + relative = "/".join(traversed) + created = False + if create: + try: + os.mkdir(part, 0o700, dir_fd=current_fd) + created = True + except FileExistsError: + pass + before = os.stat(part, dir_fd=current_fd, follow_symlinks=False) + if not stat.S_ISDIR(before.st_mode) or stat.S_ISLNK(before.st_mode): + raise DefenseError("staging parent entry is not a directory") + next_fd = os.open(part, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, + dir_fd=current_fd) + identity = _root_anchor_identity(os.fstat(next_fd)) + after = os.stat(part, dir_fd=current_fd, follow_symlinks=False) + if (_root_anchor_identity(before) != identity or + _root_anchor_identity(after) != identity): + os.close(next_fd) + raise DefenseError("staging directory changed during traversal") + record = self.ledger.get(relative) + if created: + if record is not None: + os.close(next_fd) + raise DefenseError("duplicate staging directory") + self.ledger[relative] = ("directory", identity, identity, True) + elif (record is None or record[0] != "directory" or + record[1] != identity): + os.close(next_fd) + raise DefenseError("untracked staging directory") + os.close(current_fd) + current_fd = next_fd + return current_fd + except BaseException: + os.close(current_fd) + raise + + def mkdir(self, relative): + _normalized, parts = self._relative_parts(relative) + if self.directory_fd is not None: + self._assert_named_identity() + descriptor = self._open_parent_fd(parts, True) + os.close(descriptor) + return + self._assert_named_identity() + destination = self.path.joinpath(*parts) + destination.mkdir(parents=True, exist_ok=True, mode=0o700) + self._assert_named_identity() + + def open_new_file(self, relative, mode=0o600): + normalized, parts = self._relative_parts(relative) + self._assert_named_identity() + flags = (os.O_WRONLY | os.O_CREAT | os.O_EXCL | + getattr(os, "O_BINARY", 0) | getattr(os, "O_NOFOLLOW", 0)) + if self.directory_fd is not None: + parent_fd = self._open_parent_fd(parts[:-1], True) + try: + descriptor = os.open(parts[-1], flags, mode, dir_fd=parent_fd) + metadata = os.fstat(descriptor) + named = os.stat(parts[-1], dir_fd=parent_fd, follow_symlinks=False) + identity = _stat_identity(metadata) + anchor = _root_anchor_identity(metadata) + if (not stat.S_ISREG(metadata.st_mode) or + _stat_identity(named) != identity or normalized in self.ledger): + os.close(descriptor) + raise DefenseError("staging file changed during creation") + self.ledger[normalized] = ("file", anchor, identity, False) + return descriptor + finally: + os.close(parent_fd) + destination = self.path.joinpath(*parts) + destination.parent.mkdir(parents=True, exist_ok=True, mode=0o700) + self._assert_named_identity() + return os.open(destination, flags, mode) + + def write_new_bytes(self, relative, payload: bytes, mode=0o600): + normalized, _parts = self._relative_parts(relative) + descriptor = self.open_new_file(relative, mode) + try: + _write_all(descriptor, payload) + os.fsync(descriptor) + if hasattr(os, "fchmod"): + try: + os.fchmod(descriptor, mode) + except OSError: + pass + self._finalize_file_record(normalized, descriptor) + finally: + os.close(descriptor) + + def _finalize_file_record(self, normalized, descriptor): + record = self.ledger.get(normalized) + if record is None or record[0] != "file": + raise DefenseError("untracked staging file") + metadata = os.fstat(descriptor) + if (not stat.S_ISREG(metadata.st_mode) or + _root_anchor_identity(metadata) != record[1]): + raise DefenseError("staging file identity changed") + parts = normalized.split("/") + parent_fd = self._open_parent_fd(parts[:-1], False) + try: + named = os.stat(parts[-1], dir_fd=parent_fd, follow_symlinks=False) + finally: + os.close(parent_fd) + identity = _stat_identity(metadata) + if _stat_identity(named) != identity: + raise DefenseError("staging file changed during finalization") + self.ledger[normalized] = ("file", record[1], identity, True) + + def set_file_metadata(self, relative, mode, mtime_ns=None): + normalized, parts = self._relative_parts(relative) + self._assert_named_identity() + flags = os.O_RDONLY | getattr(os, "O_BINARY", 0) | getattr(os, "O_NOFOLLOW", 0) + if self.directory_fd is not None: + parent_fd = self._open_parent_fd(parts[:-1], False) + try: + descriptor = os.open(parts[-1], flags, dir_fd=parent_fd) + finally: + os.close(parent_fd) + else: + descriptor = os.open(self.path.joinpath(*parts), flags) + try: + metadata = os.fstat(descriptor) + record = self.ledger.get(normalized) + if (not stat.S_ISREG(metadata.st_mode) or record is None or + record[0] != "file" or + _root_anchor_identity(metadata) != record[1] or + (record[3] and _stat_identity(metadata) != record[2])): + raise DefenseError("staging entry is not regular") + if self.directory_fd is None: + destination = self.path.joinpath(*parts) + destination.chmod(mode & 0o755) + else: + os.fchmod(descriptor, mode & 0o755) + if mtime_ns is not None and self.directory_fd is not None: + os.utime(descriptor, ns=(mtime_ns, mtime_ns)) + elif mtime_ns is not None: + try: + os.utime(destination, ns=(mtime_ns, mtime_ns), follow_symlinks=False) + except NotImplementedError: + os.utime(destination, ns=(mtime_ns, mtime_ns)) + self._finalize_file_record(normalized, descriptor) + finally: + os.close(descriptor) + + def _ledger_plan(self, *, manifest_last=False): + children = {} + for relative, record in self.ledger.items(): + if record[0] == "file" and not record[3]: + raise DefenseError("staging file was not finalized") + parent, _separator, name = relative.rpartition("/") + children.setdefault(parent, []).append((name, relative, record)) + + def build(parent): + entries = sorted(children.get(parent, []), key=lambda value: value[0]) + if not parent and manifest_last: + entries.sort(key=lambda value: (value[0] == "manifest.json", value[0])) + result = [] + for name, relative, record in entries: + kind, _anchor, identity, _finalized = record + descendants = build(relative) if kind == "directory" else [] + result.append((name, kind, identity, descendants)) + return result + + plan = build("") + represented = set() + + def collect(entries, parent=""): + for name, kind, _identity, descendants in entries: + relative = name if not parent else parent + "/" + name + represented.add(relative) + if kind == "directory": + collect(descendants, relative) + + collect(plan) + if represented != set(self.ledger): + raise DefenseError("staging ledger hierarchy is invalid") + return plan + + def publication_plan(self, *, manifest_last=False): + self._assert_named_identity() + plan = self._ledger_plan(manifest_last=manifest_last) + _validate_tree_fd(self.directory_fd, plan) + self._assert_named_identity() + return plan + + def close(self): + if self.closed: + return + self.closed = True + if self.directory_fd is not None: + os.close(self.directory_fd) + self.directory_fd = None + if self.parent_fd is not None: + os.close(self.parent_fd) + self.parent_fd = None + + def cleanup(self): + if self.closed: + return + try: + if not self.consumed: + if self.directory_fd is not None: + try: + plan = self.publication_plan() + _remove_tree_contents_fd(self.directory_fd, plan) + except (OSError, DefenseError): + pass + try: + current = os.stat(self.name, dir_fd=self.parent_fd, + follow_symlinks=False) + if _root_anchor_identity(current) == self.identity: + os.rmdir(self.name, dir_fd=self.parent_fd) + except OSError: + pass + else: + try: + if _root_anchor_identity(self.path.lstat()) == self.identity: + shutil.rmtree(self.path) + except OSError: + pass + finally: + self.close() + + +def _publication_plan_fd(directory_fd: int, state, *, manifest_last=False): + try: + names = sorted(os.listdir(directory_fd)) + except OSError as exc: + raise DefenseError("temporary publication is unreadable") from exc + if manifest_last and "manifest.json" in names: + names.remove("manifest.json") + names.append("manifest.json") + plan = [] + for name in names: + state[0] += 1 + if state[0] > 100_000: + raise PartialError("temporary publication entry limit reached") + metadata = os.stat(name, dir_fd=directory_fd, follow_symlinks=False) + if stat.S_ISREG(metadata.st_mode): + state[1] += metadata.st_size + if state[1] > MAX_IMPORTED_TOTAL_BYTES: + raise PartialError("temporary publication byte limit reached") + plan.append((name, "file", _stat_identity(metadata), None)) + elif stat.S_ISDIR(metadata.st_mode): + named_identity = _root_anchor_identity(metadata) + child_fd = os.open(name, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, + dir_fd=directory_fd) + try: + identity = _root_anchor_identity(os.fstat(child_fd)) + if identity != named_identity: + raise DefenseError("temporary publication directory changed") + children = _publication_plan_fd(child_fd, state) + current = os.stat(name, dir_fd=directory_fd, follow_symlinks=False) + if _root_anchor_identity(current) != identity: + raise DefenseError("temporary publication directory changed") + finally: + os.close(child_fd) + plan.append((name, "directory", identity, children)) + else: + raise DefenseError("temporary publication contains a special entry") + return plan + + +def _copy_regular_to_dirfd(source_directory_fd: int, name: str, destination_fd: int, + expected_identity): + source_flags = (os.O_RDONLY | getattr(os, "O_BINARY", 0) | + getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0)) + source_fd = os.open(name, source_flags, dir_fd=source_directory_fd) + target_fd = None + try: + before = os.fstat(source_fd) + if not stat.S_ISREG(before.st_mode) or _stat_identity(before) != expected_identity: + raise DefenseError("temporary publication contains a special entry") + target_fd = os.open(name, os.O_WRONLY | os.O_CREAT | os.O_EXCL | + getattr(os, "O_BINARY", 0), 0o600, + dir_fd=destination_fd) + while True: + block = os.read(source_fd, CHUNK) + if not block: + break + _write_all(target_fd, block) + # Publication is a descriptor-anchored copy on POSIX, not a rename. + # Preserve the already-sanitized staging metadata so restore-stage does + # not silently collapse every restored file to mode 0600 or lose the + # recorded timestamp. Staging producers create only regular files and + # have already stripped unsafe mode bits. + os.fchmod(target_fd, stat.S_IMODE(before.st_mode) & 0o755) + os.utime(target_fd, ns=(before.st_mtime_ns, before.st_mtime_ns)) + os.fsync(target_fd) + after = os.fstat(source_fd) + if _stat_identity(before) != _stat_identity(after): + raise PartialError("temporary publication changed during copy") + published = os.fstat(target_fd) + named = os.stat(name, dir_fd=destination_fd, follow_symlinks=False) + published_identity = _stat_identity(published) + if (not stat.S_ISREG(named.st_mode) or + _stat_identity(named) != published_identity): + raise DefenseError("publication file changed during copy") + return (name, "file", published_identity, []) + finally: + if target_fd is not None: + os.close(target_fd) + os.close(source_fd) + + +def _copy_tree_to_dirfd(source_parent_fd: int, name: str, destination_fd: int, + expected_identity, children): + source_fd = os.open(name, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, + dir_fd=source_parent_fd) + child_fd = None + try: + if _root_anchor_identity(os.fstat(source_fd)) != expected_identity: + raise DefenseError("temporary publication directory changed") + os.mkdir(name, 0o700, dir_fd=destination_fd) + created = os.stat(name, dir_fd=destination_fd, follow_symlinks=False) + if not stat.S_ISDIR(created.st_mode) or stat.S_ISLNK(created.st_mode): + raise DefenseError("publication directory creation was replaced") + created_identity = _root_anchor_identity(created) + child_fd = os.open(name, os.O_RDONLY | os.O_DIRECTORY | + getattr(os, "O_NOFOLLOW", 0), dir_fd=destination_fd) + if _root_anchor_identity(os.fstat(child_fd)) != created_identity: + raise DefenseError("publication directory changed during creation") + current = os.stat(name, dir_fd=destination_fd, follow_symlinks=False) + if _root_anchor_identity(current) != created_identity: + raise DefenseError("publication directory changed during creation") + published_children = [] + for child_name, kind, identity, descendants in children: + if kind == "directory": + published_children.append( + _copy_tree_to_dirfd(source_fd, child_name, child_fd, identity, descendants) + ) + else: + published_children.append( + _copy_regular_to_dirfd(source_fd, child_name, child_fd, identity) + ) + os.fsync(child_fd) + current = os.stat(name, dir_fd=destination_fd, follow_symlinks=False) + if _root_anchor_identity(current) != created_identity: + raise DefenseError("publication directory changed during copy") + return (name, "directory", created_identity, published_children) + finally: + if child_fd is not None: + os.close(child_fd) + os.close(source_fd) + + +def _validate_tree_fd(directory_fd: int, plan): + """Validate exact recursive membership and identities without changing the tree.""" + expected_names = [entry[0] for entry in plan] + if sorted(os.listdir(directory_fd)) != sorted(expected_names): + raise DefenseError("publication tree membership changed") + for name, kind, identity, children in plan: + current = os.stat(name, dir_fd=directory_fd, follow_symlinks=False) + if kind == "directory": + if (not stat.S_ISDIR(current.st_mode) or + _root_anchor_identity(current) != identity): + raise DefenseError("publication directory identity changed") + child_fd = os.open(name, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, + dir_fd=directory_fd) + try: + if _root_anchor_identity(os.fstat(child_fd)) != identity: + raise DefenseError("publication directory identity changed") + _validate_tree_fd(child_fd, children) + finally: + os.close(child_fd) + current = os.stat(name, dir_fd=directory_fd, follow_symlinks=False) + if _root_anchor_identity(current) != identity: + raise DefenseError("publication directory identity changed") + else: + if not stat.S_ISREG(current.st_mode) or _stat_identity(current) != identity: + raise DefenseError("publication file identity changed") + flags = (os.O_RDONLY | getattr(os, "O_BINARY", 0) | + getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0)) + descriptor = os.open(name, flags, dir_fd=directory_fd) + try: + if _stat_identity(os.fstat(descriptor)) != identity: + raise DefenseError("publication file identity changed") + finally: + os.close(descriptor) + current = os.stat(name, dir_fd=directory_fd, follow_symlinks=False) + if _stat_identity(current) != identity: + raise DefenseError("publication file identity changed") + + +def _remove_tree_contents_fd(directory_fd: int, plan=None): + """Remove only an identity-checked tree; abort on injection or replacement.""" + if plan is None: + plan = _publication_plan_fd(directory_fd, [0, 0]) + _validate_tree_fd(directory_fd, plan) + for name, kind, identity, children in reversed(plan): + current = os.stat(name, dir_fd=directory_fd, follow_symlinks=False) + if kind == "directory": + if (not stat.S_ISDIR(current.st_mode) or + _root_anchor_identity(current) != identity): + raise DefenseError("cleanup directory identity changed") + child_fd = os.open(name, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, + dir_fd=directory_fd) + try: + if _root_anchor_identity(os.fstat(child_fd)) != identity: + raise DefenseError("cleanup directory identity changed") + _remove_tree_contents_fd(child_fd, children) + finally: + os.close(child_fd) + current = os.stat(name, dir_fd=directory_fd, follow_symlinks=False) + if _root_anchor_identity(current) != identity: + raise DefenseError("cleanup directory identity changed") + os.rmdir(name, dir_fd=directory_fd) + else: + if not stat.S_ISREG(current.st_mode) or _stat_identity(current) != identity: + raise DefenseError("cleanup file identity changed") + flags = (os.O_RDONLY | getattr(os, "O_BINARY", 0) | + getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0)) + descriptor = os.open(name, flags, dir_fd=directory_fd) + try: + if _stat_identity(os.fstat(descriptor)) != identity: + raise DefenseError("cleanup file identity changed") + finally: + os.close(descriptor) + current = os.stat(name, dir_fd=directory_fd, follow_symlinks=False) + if _stat_identity(current) != identity: + raise DefenseError("cleanup file identity changed") + os.unlink(name, dir_fd=directory_fd) + if os.listdir(directory_fd): + raise DefenseError("cleanup tree membership changed") + + +def _ensure_incomplete_marker(directory_fd: int): + """Best-effort persistent failure marker for an owned publication target.""" + try: + current = os.stat(".INCOMPLETE", dir_fd=directory_fd, follow_symlinks=False) + except FileNotFoundError: + marker_fd = os.open(".INCOMPLETE", os.O_WRONLY | os.O_CREAT | os.O_EXCL, + 0o600, dir_fd=directory_fd) + try: + os.fsync(marker_fd) + identity = _stat_identity(os.fstat(marker_fd)) + named = os.stat(".INCOMPLETE", dir_fd=directory_fd, + follow_symlinks=False) + if _stat_identity(named) != identity: + raise DefenseError("publication marker changed during recovery") + finally: + os.close(marker_fd) + try: + os.fsync(directory_fd) + except OSError: + pass + return + if not stat.S_ISREG(current.st_mode): + raise DefenseError("publication failure marker is not regular") + + +def _publish_staging_directory(staging: _StagingDirectory, target: Path): + staging._assert_open() + target = _canonical_parent_with_leaf(Path(target)) + if target != staging.target: + raise DefenseError("publication target changed") + if target.exists() or target.is_symlink(): + raise DefenseError("output already exists") + staging._assert_named_identity() + + if staging.directory_fd is None: + _publication_items(staging.path) + if (_root_anchor_identity(target.parent.lstat()) != staging.parent_identity or + _root_anchor_identity(staging.path.lstat()) != staging.identity): + raise DefenseError("staging directory changed during validation") + try: + os.rename(staging.path, target) + except OSError as exc: + raise DefenseError("could not safely publish directory") from exc + staging.consumed = True + return target + + parent_fd = staging.parent_fd + source_fd = staging.directory_fd + target_fd = None + created = False + created_identity = None + cleanup_plan = [] + committed_after_exception = False + ready_to_commit = False + try: + if _root_anchor_identity(target.parent.lstat()) != staging.parent_identity: + raise DefenseError("output parent changed during validation") + try: + os.stat(target.name, dir_fd=parent_fd, follow_symlinks=False) + except FileNotFoundError: + pass + else: + raise DefenseError("output already exists") + plan = staging.publication_plan(manifest_last=True) + staging._assert_named_identity() + os.mkdir(target.name, 0o700, dir_fd=parent_fd) + created = True + created_metadata = os.stat(target.name, dir_fd=parent_fd, follow_symlinks=False) + if (not stat.S_ISDIR(created_metadata.st_mode) or + stat.S_ISLNK(created_metadata.st_mode)): + raise DefenseError("publication target creation was replaced") + created_identity = _root_anchor_identity(created_metadata) + target_fd = os.open(target.name, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, + dir_fd=parent_fd) + if _root_anchor_identity(os.fstat(target_fd)) != created_identity: + raise DefenseError("publication target changed during creation") + current = os.stat(target.name, dir_fd=parent_fd, follow_symlinks=False) + if _root_anchor_identity(current) != created_identity: + raise DefenseError("publication target changed during creation") + marker_fd = os.open(".INCOMPLETE", os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600, + dir_fd=target_fd) + try: + os.fsync(marker_fd) + marker_identity = _stat_identity(os.fstat(marker_fd)) + marker_named = os.stat(".INCOMPLETE", dir_fd=target_fd, + follow_symlinks=False) + if _stat_identity(marker_named) != marker_identity: + raise DefenseError("publication marker changed during creation") + cleanup_plan.append((".INCOMPLETE", "file", marker_identity, [])) + finally: + os.close(marker_fd) + for name, kind, identity, children in plan: + if kind == "directory": + cleanup_plan.append( + _copy_tree_to_dirfd(source_fd, name, target_fd, identity, children) + ) + else: + cleanup_plan.append( + _copy_regular_to_dirfd(source_fd, name, target_fd, identity) + ) + if staging.publication_plan(manifest_last=True) != plan: + raise PartialError("temporary publication membership changed during copy") + staging._assert_named_identity() + current = os.stat(target.name, dir_fd=parent_fd, follow_symlinks=False) + if _root_anchor_identity(current) != created_identity: + raise DefenseError("publication target changed during copy") + _validate_tree_fd(target_fd, cleanup_plan) + os.fsync(target_fd) + os.fsync(parent_fd) + current = os.stat(target.name, dir_fd=parent_fd, follow_symlinks=False) + if _root_anchor_identity(current) != created_identity: + raise DefenseError("publication target changed during finalization") + _remove_tree_contents_fd(source_fd, plan) + staging._assert_named_identity() + os.rmdir(staging.name, dir_fd=parent_fd) + staging._assert_parent_path_identity() + current = os.stat(target.name, dir_fd=parent_fd, follow_symlinks=False) + if (_root_anchor_identity(current) != created_identity or + _root_anchor_identity(os.fstat(target_fd)) != created_identity): + raise DefenseError("publication target changed before commit") + _validate_tree_fd(target_fd, cleanup_plan) + staging._assert_parent_path_identity() + current = os.stat(target.name, dir_fd=parent_fd, follow_symlinks=False) + if (_root_anchor_identity(current) != created_identity or + _root_anchor_identity(os.fstat(target_fd)) != created_identity): + raise DefenseError("publication target changed at commit") + try: + os.stat(staging.name, dir_fd=parent_fd, follow_symlinks=False) + except FileNotFoundError: + pass + else: + raise DefenseError("staging directory still exists at commit") + ready_to_commit = True + os.unlink(".INCOMPLETE", dir_fd=target_fd) + try: + os.stat(".INCOMPLETE", dir_fd=target_fd, follow_symlinks=False) + except FileNotFoundError: + pass + else: + raise DefenseError("publication marker still exists after commit") + cleanup_plan = [entry for entry in cleanup_plan if entry[0] != ".INCOMPLETE"] + staging.consumed = True + # Marker removal is the commit point. Once it succeeds, do not turn a + # completed publication into a failed, markerless result. Durability + # fsync is best-effort because rollback is no longer possible after the + # producer staging tree has been consumed. + try: + os.fsync(target_fd) + os.fsync(parent_fd) + except OSError: + pass + except BaseException as exc: + target_is_owned = False + if target_fd is not None and created_identity is not None: + try: + named = os.stat(target.name, dir_fd=parent_fd, follow_symlinks=False) + target_is_owned = ( + _root_anchor_identity(os.fstat(target_fd)) == created_identity and + _root_anchor_identity(named) == created_identity + ) + except (OSError, DefenseError): + pass + if target_is_owned: + try: + staging._assert_parent_path_identity() + try: + os.stat(staging.name, dir_fd=parent_fd, follow_symlinks=False) + except FileNotFoundError: + source_absent = True + else: + source_absent = False + try: + os.stat(".INCOMPLETE", dir_fd=target_fd, follow_symlinks=False) + except FileNotFoundError: + marker_absent = True + else: + marker_absent = False + completed_plan = [entry for entry in cleanup_plan + if entry[0] != ".INCOMPLETE"] + if ready_to_commit and source_absent and marker_absent: + _validate_tree_fd(target_fd, completed_plan) + current = os.stat(target.name, dir_fd=parent_fd, + follow_symlinks=False) + committed_after_exception = ( + _root_anchor_identity(current) == created_identity and + _root_anchor_identity(os.fstat(target_fd)) == created_identity + ) + except (OSError, DefenseError): + pass + if committed_after_exception: + staging.consumed = True + elif target_fd is not None and created_identity is not None: + try: + if _root_anchor_identity(os.fstat(target_fd)) == created_identity: + _ensure_incomplete_marker(target_fd) + except BaseException: + pass + if committed_after_exception: + pass + elif isinstance(exc, DefenseError): + raise + else: + raise DefenseError("could not safely publish directory") from exc + finally: + if target_fd is not None: + os.close(target_fd) + return target + + +def _publish_directory(temporary: Path, target: Path): + if isinstance(temporary, _StagingDirectory): + return _publish_staging_directory(temporary, target) + if not DIRECTORY_STAGING_SUPPORTED: + raise PartialError("secure directory publication is unavailable on Windows") + target, expected_parent_identity = _safe_output_target(target) + temporary = _canonical_input_leaf(temporary) + if temporary.parent != target.parent: + raise DefenseError("temporary publication must share the output parent") + if os.name == "nt": + _publication_items(temporary) + if _root_anchor_identity(target.parent.lstat()) != expected_parent_identity: + raise DefenseError("output parent changed during validation") + # Windows rename is an atomic no-replace operation for directories. + try: + os.rename(temporary, target) + except OSError as exc: + raise DefenseError("could not safely publish directory") from exc + return target + + if (not DIRECTORY_DIRFD_SUPPORTED or not hasattr(os, "O_DIRECTORY") or + not hasattr(os, "O_NOFOLLOW")): + raise DefenseError("filesystem lacks safe directory publication support") + + parent_fd = None + source_fd = None + target_fd = None + created = False + created_identity = None + cleanup_plan = [] + committed_after_exception = False + ready_to_commit = False + try: + parent_fd = os.open(target.parent, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW) + if _root_anchor_identity(os.fstat(parent_fd)) != expected_parent_identity: + raise DefenseError("output parent changed during validation") + source_metadata = os.stat(temporary.name, dir_fd=parent_fd, follow_symlinks=False) + if not stat.S_ISDIR(source_metadata.st_mode): + raise DefenseError("temporary publication must be a directory") + source_identity = _root_anchor_identity(source_metadata) + source_fd = os.open(temporary.name, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, + dir_fd=parent_fd) + if _root_anchor_identity(os.fstat(source_fd)) != source_identity: + raise DefenseError("temporary publication changed during validation") + plan = _publication_plan_fd(source_fd, [0, 0], manifest_last=True) + os.mkdir(target.name, 0o700, dir_fd=parent_fd) + created = True + created_metadata = os.stat(target.name, dir_fd=parent_fd, follow_symlinks=False) + if (not stat.S_ISDIR(created_metadata.st_mode) or + stat.S_ISLNK(created_metadata.st_mode)): + raise DefenseError("publication target creation was replaced") + created_identity = _root_anchor_identity(created_metadata) + target_fd = os.open(target.name, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, + dir_fd=parent_fd) + if _root_anchor_identity(os.fstat(target_fd)) != created_identity: + raise DefenseError("publication target changed during creation") + current = os.stat(target.name, dir_fd=parent_fd, follow_symlinks=False) + if _root_anchor_identity(current) != created_identity: + raise DefenseError("publication target changed during creation") + marker_fd = os.open(".INCOMPLETE", os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600, + dir_fd=target_fd) + try: + os.fsync(marker_fd) + marker_identity = _stat_identity(os.fstat(marker_fd)) + marker_named = os.stat(".INCOMPLETE", dir_fd=target_fd, + follow_symlinks=False) + if _stat_identity(marker_named) != marker_identity: + raise DefenseError("publication marker changed during creation") + cleanup_plan.append((".INCOMPLETE", "file", marker_identity, [])) + finally: + os.close(marker_fd) + for name, kind, identity, children in plan: + if kind == "directory": + cleanup_plan.append( + _copy_tree_to_dirfd(source_fd, name, target_fd, identity, children) + ) + else: + cleanup_plan.append( + _copy_regular_to_dirfd(source_fd, name, target_fd, identity) + ) + if _publication_plan_fd(source_fd, [0, 0], manifest_last=True) != plan: + raise PartialError("temporary publication membership changed during copy") + current = os.stat(target.name, dir_fd=parent_fd, follow_symlinks=False) + if _root_anchor_identity(current) != created_identity: + raise DefenseError("publication target changed during copy") + _validate_tree_fd(target_fd, cleanup_plan) + os.fsync(target_fd) + os.fsync(parent_fd) + current = os.stat(target.name, dir_fd=parent_fd, follow_symlinks=False) + if _root_anchor_identity(current) != created_identity: + raise DefenseError("publication target changed during finalization") + _remove_tree_contents_fd(source_fd, plan) + os.rmdir(temporary.name, dir_fd=parent_fd) + current = os.stat(target.name, dir_fd=parent_fd, follow_symlinks=False) + if (_root_anchor_identity(current) != created_identity or + _root_anchor_identity(os.fstat(target_fd)) != created_identity): + raise DefenseError("publication target changed before commit") + _validate_tree_fd(target_fd, cleanup_plan) + if _root_anchor_identity(target.parent.lstat()) != expected_parent_identity: + raise DefenseError("output parent changed at commit") + current = os.stat(target.name, dir_fd=parent_fd, follow_symlinks=False) + if (_root_anchor_identity(current) != created_identity or + _root_anchor_identity(os.fstat(target_fd)) != created_identity): + raise DefenseError("publication target changed at commit") + try: + os.stat(temporary.name, dir_fd=parent_fd, follow_symlinks=False) + except FileNotFoundError: + pass + else: + raise DefenseError("temporary publication still exists at commit") + ready_to_commit = True + os.unlink(".INCOMPLETE", dir_fd=target_fd) + try: + os.stat(".INCOMPLETE", dir_fd=target_fd, follow_symlinks=False) + except FileNotFoundError: + pass + else: + raise DefenseError("publication marker still exists after commit") + cleanup_plan = [entry for entry in cleanup_plan if entry[0] != ".INCOMPLETE"] + try: + os.fsync(target_fd) + os.fsync(parent_fd) + except OSError: + pass + except BaseException as exc: + target_is_owned = False + if target_fd is not None and created_identity is not None: + try: + named = os.stat(target.name, dir_fd=parent_fd, follow_symlinks=False) + target_is_owned = ( + _root_anchor_identity(os.fstat(target_fd)) == created_identity and + _root_anchor_identity(named) == created_identity + ) + except (OSError, DefenseError): + pass + if target_is_owned: + try: + if _root_anchor_identity(target.parent.lstat()) != expected_parent_identity: + raise DefenseError("output parent changed") + try: + os.stat(temporary.name, dir_fd=parent_fd, follow_symlinks=False) + except FileNotFoundError: + source_absent = True + else: + source_absent = False + try: + os.stat(".INCOMPLETE", dir_fd=target_fd, follow_symlinks=False) + except FileNotFoundError: + marker_absent = True + else: + marker_absent = False + completed_plan = [entry for entry in cleanup_plan + if entry[0] != ".INCOMPLETE"] + if ready_to_commit and source_absent and marker_absent: + _validate_tree_fd(target_fd, completed_plan) + committed_after_exception = True + except (OSError, DefenseError): + pass + if not committed_after_exception and target_fd is not None and created_identity is not None: + try: + if _root_anchor_identity(os.fstat(target_fd)) == created_identity: + _ensure_incomplete_marker(target_fd) + except BaseException: + pass + if committed_after_exception: + pass + elif isinstance(exc, DefenseError): + raise + else: + raise DefenseError("could not safely publish directory") from exc + finally: + if target_fd is not None: + os.close(target_fd) + if source_fd is not None: + os.close(source_fd) + if parent_fd is not None: + os.close(parent_fd) + return target + + +def _profile_hash(profile) -> str: + return _sha256_bytes(_canonical(profile)) + + +def _snapshot_scope(settings, requested, compose=None): + adapter_config = {} + if "compose" in requested and compose is not None: + adapter_config["compose"] = { + "config_files": list(compose["files"]), + "project_sha256": _opaque_text_identifier(compose["project"]), + "services": list(compose["services"]), + } + payload = { + "adapter_config": adapter_config, + "adapter_semantics": {name: ADAPTER_SEMANTICS[name] for name in sorted(requested)}, + "files": { + "content_semantics": "sha256-size-mode-mtime-v1", + "exclude": sorted(set(settings.get("exclude", []))), + "include": sorted(set(settings.get("include", ["*"]))), + "max_file_bytes": settings.get("max_file_bytes", 64 * 1024 * 1024), + "max_files": settings.get("max_files", 20_000), + "max_total_bytes": settings.get("max_total_bytes", 4 * 1024 * 1024 * 1024), + "path_semantics": "portable-nfc-casefold-v1", + }, + "schema": SNAPSHOT_SCOPE_SCHEMA, + "tool_compatibility": SNAPSHOT_TOOL_COMPATIBILITY, + } + return {**payload, "sha256": _sha256_bytes(_canonical(payload))} + + +def _validate_tool_record(value, field="tool"): + _strict_keys(value, {"name", "version"}, {"name", "version"}, field) + if value["name"] != TOOL or not isinstance(value["version"], str) or not re.fullmatch( + r"[0-9]+\.[0-9]+\.[0-9]+(?:[-+][0-9A-Za-z.-]+)?", value["version"]): + raise DefenseError("invalid " + field) + return value + + +def _tool_major(value): + _validate_tool_record(value) + return int(value["version"].split(".", 1)[0]) + + +def _validate_profile_reference(value, field="profile"): + _strict_keys(value, {"name", "sha256"}, {"name", "sha256"}, field) + _safe_string(value["name"], field + " name", 1, 120) + if not isinstance(value["sha256"], str) or not re.fullmatch(r"[0-9a-f]{64}", value["sha256"]): + raise DefenseError("invalid " + field + " hash") + return value + + +def _validate_snapshot_scope(value): + _strict_keys(value, {"schema", "tool_compatibility", "adapter_semantics", "adapter_config", + "files", "sha256"}, + {"schema", "tool_compatibility", "adapter_semantics", "adapter_config", + "files", "sha256"}, + "snapshot scope") + if (value["schema"] != SNAPSHOT_SCOPE_SCHEMA or + value["tool_compatibility"] != SNAPSHOT_TOOL_COMPATIBILITY): + raise DefenseError("invalid snapshot scope schema") + semantics = value["adapter_semantics"] + if not isinstance(semantics, dict) or set(semantics) - set(ADAPTERS): + raise DefenseError("invalid adapter semantics") + for name, semantic in semantics.items(): + if semantic != ADAPTER_SEMANTICS[name]: + raise DefenseError("invalid adapter semantics") + adapter_config = value["adapter_config"] + if not isinstance(adapter_config, dict) or set(adapter_config) - {"compose"}: + raise DefenseError("invalid adapter configuration scope") + if ("compose" in semantics) != ("compose" in adapter_config): + raise DefenseError("compose adapter scope is incomplete") + if "compose" in adapter_config: + compose = adapter_config["compose"] + _strict_keys(compose, {"config_files", "project_sha256", "services"}, + {"config_files", "project_sha256", "services"}, "compose scope") + if not isinstance(compose["project_sha256"], str) or not OPAQUE_ID.fullmatch( + compose["project_sha256"]): + raise DefenseError("invalid compose project scope") + for field in ("config_files", "services"): + values = compose[field] + if (not isinstance(values, list) or not values or values != sorted(set(values)) or + len(values) > 128): + raise DefenseError("invalid compose scope " + field) + for path in compose["config_files"]: + _portable_relative_posix(path, "compose config path") + for service in compose["services"]: + if not IDENTIFIER.fullmatch(service if isinstance(service, str) else ""): + raise DefenseError("invalid compose service scope") + files = value["files"] + _strict_keys(files, {"content_semantics", "exclude", "include", "max_file_bytes", + "max_files", "max_total_bytes", "path_semantics"}, + {"content_semantics", "exclude", "include", "max_file_bytes", "max_files", + "max_total_bytes", "path_semantics"}, "snapshot file scope") + if (files["content_semantics"] != "sha256-size-mode-mtime-v1" or + files["path_semantics"] != "portable-nfc-casefold-v1"): + raise DefenseError("unsupported snapshot file semantics") + for field in ("include", "exclude"): + patterns = files[field] + if (not isinstance(patterns, list) or len(patterns) > 128 or + any(not isinstance(pattern, str) for pattern in patterns) or + patterns != sorted(set(patterns))): + raise DefenseError("invalid snapshot scope patterns") + for pattern in patterns: + _relative_glob(pattern, field) + _positive_int(files["max_files"], "max_files", 100_000) + _positive_int(files["max_file_bytes"], "max_file_bytes", 1024 ** 3) + _positive_int(files["max_total_bytes"], "max_total_bytes", 20 * 1024 ** 3) + payload = {key: value[key] for key in ("adapter_config", "adapter_semantics", "files", "schema", + "tool_compatibility")} + if (not isinstance(value["sha256"], str) or + value["sha256"] != _sha256_bytes(_canonical(payload))): + raise DefenseError("snapshot scope hash mismatch") + return value + + +def _validate_url(value): + _safe_string(value, "health URL", 1, 4096) + try: + parsed = urlsplit(value) + port = parsed.port + except ValueError as exc: + raise DefenseError("invalid health URL") from exc + if (parsed.scheme not in {"http", "https"} or not parsed.hostname or + parsed.username is not None or parsed.password is not None or parsed.fragment): + raise DefenseError("invalid health URL") + _ = port + return value + + +def _validate_profile(data): + _strict_keys(data, {"schema", "name", "snapshot", "compose", "health", "backup", "evidence"}, + {"schema", "name"}, "profile") + if data["schema"] != PROFILE_SCHEMA: + raise DefenseError("unsupported profile schema") + _safe_string(data["name"], "profile name", 1, 120) + _reject_declarative_hazards(data) + + if "snapshot" in data: + item = data["snapshot"] + _strict_keys(item, {"adapters", "include", "exclude", "max_files", + "max_file_bytes", "max_total_bytes"}, field="snapshot profile") + if "adapters" in item: + adapters = item["adapters"] + if (not isinstance(adapters, list) or len(adapters) > len(ADAPTERS) or + any(not isinstance(adapter, str) for adapter in adapters) or + len(set(adapters)) != len(adapters) or + any(adapter not in ADAPTERS for adapter in adapters)): + raise DefenseError("invalid snapshot adapters") + for field in ("include", "exclude"): + if field in item: + values = item[field] + if not isinstance(values, list) or len(values) > 128: + raise DefenseError("invalid snapshot " + field) + item[field] = [_relative_glob(value, field) for value in values] + if "max_files" in item: + _positive_int(item["max_files"], "max_files", 100_000) + if "max_file_bytes" in item: + _positive_int(item["max_file_bytes"], "max_file_bytes", 1024 ** 3) + if "max_total_bytes" in item: + _positive_int(item["max_total_bytes"], "max_total_bytes", 20 * 1024 ** 3) + + if "compose" in data: + compose = data["compose"] + _strict_keys(compose, {"project", "files", "services"}, + {"project", "files", "services"}, "compose profile") + project = compose["project"] + if (not isinstance(project, str) or + not re.fullmatch(r"[a-z0-9][a-z0-9_-]{0,62}", project)): + raise DefenseError("invalid compose project") + files = compose["files"] + if (not isinstance(files, list) or not 1 <= len(files) <= 8 or + files != sorted(set(files))): + raise DefenseError("invalid compose files") + compose["files"] = [_portable_relative_posix(path, "compose config path") + for path in files] + if any(not path.lower().endswith((".yml", ".yaml")) for path in compose["files"]): + raise DefenseError("compose configs must be YAML files") + services = compose["services"] + if (not isinstance(services, list) or not 1 <= len(services) <= 128 or + services != sorted(set(services)) or + any(not IDENTIFIER.fullmatch(service if isinstance(service, str) else "") + for service in services)): + raise DefenseError("invalid compose services") + snapshot_adapters = data.get("snapshot", {}).get("adapters", list(DEFAULT_ADAPTERS)) + if ("compose" in snapshot_adapters) != ("compose" in data): + raise DefenseError("compose profile and adapter must be configured together") + + if "health" in data: + checks = data["health"] + if not isinstance(checks, list) or not 1 <= len(checks) <= 128: + raise DefenseError("health must contain 1..128 checks") + names = set() + for check in checks: + _strict_keys(check, {"name", "url", "status", "contains", "timeout"}, + {"name", "url"}, "health check") + name = _safe_string(check["name"], "health name", 1, 120) + if name in names: + raise DefenseError("duplicate health name") + names.add(name) + _validate_url(check["url"]) + if "status" in check and (type(check["status"]) is not int or + not 100 <= check["status"] <= 599): + raise DefenseError("invalid health status") + if "contains" in check: + _safe_string(check["contains"], "health contains", 0, 4096) + if "timeout" in check: + _positive_float_value(check["timeout"]) + + if "backup" in data: + backup = data["backup"] + _strict_keys(backup, {"entries", "exclude", "max_files", "max_file_bytes", + "max_total_bytes"}, {"entries"}, "backup profile") + entries = backup["entries"] + if not isinstance(entries, list) or not 1 <= len(entries) <= 256: + raise DefenseError("backup entries must contain 1..256 items") + seen = set() + portable_seen = set() + normalized = [] + for entry in entries: + _strict_keys(entry, {"path", "kind"}, {"path", "kind"}, "backup entry") + path = _portable_relative_posix(entry["path"], "backup path", allow_dot=True) + if (not isinstance(entry["kind"], str) or + entry["kind"] not in {"file", "tree", "native_dump"}): + raise DefenseError("invalid backup kind") + portable_key = _portable_path_key(path) + if path in seen or portable_key in portable_seen: + raise DefenseError("duplicate backup path") + seen.add(path) + portable_seen.add(portable_key) + normalized.append((path, entry["kind"])) + for path, kind in normalized: + for other, _other_kind in normalized: + if path != other and kind == "tree" and (path == "." or other.startswith(path + "/")): + raise DefenseError("overlapping backup entries") + if "exclude" in backup: + if not isinstance(backup["exclude"], list) or len(backup["exclude"]) > 128: + raise DefenseError("invalid backup exclude") + backup["exclude"] = [_relative_glob(value, "backup exclude") for value in backup["exclude"]] + if "max_files" in backup: + _positive_int(backup["max_files"], "max_files", 100_000) + if "max_file_bytes" in backup: + _positive_int(backup["max_file_bytes"], "max_file_bytes", 4 * 1024 ** 3) + if "max_total_bytes" in backup: + _positive_int(backup["max_total_bytes"], "max_total_bytes", 100 * 1024 ** 3) + + if "evidence" in data: + evidence = data["evidence"] + _strict_keys(evidence, {"allow_extensions", "max_files", "max_file_bytes", + "max_total_bytes"}, field="evidence profile") + if "allow_extensions" in evidence: + extensions = evidence["allow_extensions"] + if (not isinstance(extensions, list) or not 1 <= len(extensions) <= 2 or + any(not isinstance(value, str) for value in extensions) or + len(set(extensions)) != len(extensions) or + any(value not in SAFE_EVIDENCE_EXTENSIONS for value in extensions)): + raise DefenseError("invalid evidence extensions") + if "max_files" in evidence: + _positive_int(evidence["max_files"], "max_files", 1024) + if "max_file_bytes" in evidence: + _positive_int(evidence["max_file_bytes"], "max_file_bytes", 64 * 1024 ** 2) + if "max_total_bytes" in evidence: + _positive_int(evidence["max_total_bytes"], "max_total_bytes", 1024 ** 3) + return data + + +def load_profile(path): + data, _raw = _read_json(path, MAX_PROFILE_BYTES) + return _validate_profile(data) + + +def _matches(path, patterns): + return any(fnmatch.fnmatchcase(path, pattern) for pattern in patterns) + + +def _secret_filename(name): + lowered = name.lower() + return (lowered == ".env" or lowered.startswith(".env.") or + lowered.endswith((".pem", ".key", ".p12", ".pfx", ".kdbx")) or + bool(SECRET_NAME.search(lowered))) + + +def _bounded_walk(root: Path, include, exclude, max_files, skip_dirs=(), + skip_secret_dirs=False, require_portable=False): + stack = [root] + skipped_directory_names = {name.casefold() for name in skip_dirs} + seen = 0 + while stack: + directory = stack.pop() + try: + with os.scandir(directory) as stream: + remaining = max_files * 10 - seen + if remaining <= 0: + yield "limit", root, "entry_limit_reached" + return + entries = [] + for entry in stream: + entries.append(entry) + if len(entries) > remaining: + yield "limit", root, "entry_limit_reached" + return + entries.sort(key=lambda value: value.name) + except (OSError, PermissionError) as exc: + yield "issue", directory, "directory_unreadable" + continue + directories = [] + for entry in entries: + seen += 1 + if seen > max_files * 10: + yield "limit", root, "entry_limit_reached" + return + path = Path(entry.path) + try: + rel = path.relative_to(root).as_posix() + except ValueError: + yield "issue", path, "path_outside_root" + continue + if _matches(rel, exclude): + yield "skip", path, "excluded" + elif entry.is_symlink(): + yield "skip", path, "symlink" + elif entry.is_dir(follow_symlinks=False): + if (entry.name.casefold() in skipped_directory_names or + skip_secret_dirs and _secret_filename(entry.name)): + yield "skip", path, "excluded_directory" + elif require_portable: + try: + _portable_relative_posix(rel, "discovered path") + except DefenseError: + yield "nonportable", path, _opaque_text_identifier(rel) + else: + directories.append(path) + else: + directories.append(path) + elif entry.is_file(follow_symlinks=False): + if _matches(rel, include): + if require_portable: + try: + rel = _portable_relative_posix(rel, "discovered path") + except DefenseError: + yield "nonportable", path, _opaque_text_identifier(rel) + continue + yield "file", path, rel + else: + yield "skip", path, "not_included" + else: + yield "skip", path, "special" + stack.extend(reversed(directories)) + + +def _hash_regular(path: Path, max_bytes: int): + flags = (os.O_RDONLY | getattr(os, "O_BINARY", 0) | + getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0)) + fd = os.open(path, flags) + try: + before = os.fstat(fd) + if not stat.S_ISREG(before.st_mode): + raise PartialError("not_regular") + if before.st_size > max_bytes: + raise PartialError("file_too_large") + digest = hashlib.sha256() + consumed = 0 + with os.fdopen(fd, "rb", closefd=False) as stream: + while True: + block = stream.read(CHUNK) + if not block: + break + consumed += len(block) + if consumed > max_bytes: + raise PartialError("file_too_large") + digest.update(block) + after = os.fstat(fd) + if _stat_identity(before) != _stat_identity(after): + raise PartialError("file_changed_during_read") + return before, digest.hexdigest() + finally: + os.close(fd) + + +def _known_executable(candidates): + for candidate in candidates: + path = Path(candidate) + if path.is_file() and not path.is_symlink(): + return str(path) + return None + + +def _platform_command(adapter): + system = platform.system() + if system == "Darwin": + commands = { + "processes": (["/bin/ps", "-axo", "pid=,ppid=,uid=,comm="], "/bin/ps"), + "listeners": (["/usr/sbin/lsof", "-nP", "-iTCP", "-sTCP:LISTEN", "-F", "pcPn"], + "/usr/sbin/lsof"), + "services": (["/bin/launchctl", "list"], "/bin/launchctl"), + } + return commands.get(adapter) + if system == "Windows": + base = r"C:\Windows" + commands = { + "processes": ([str(Path(base) / "System32" / "tasklist.exe"), "/fo", "csv", "/nh"], + str(Path(base) / "System32" / "tasklist.exe")), + "services": ([str(Path(base) / "System32" / "sc.exe"), "query", "state=", "all"], + str(Path(base) / "System32" / "sc.exe")), + } + return commands.get(adapter) + if system == "Linux" and adapter == "services": + executable = _known_executable(("/usr/bin/systemctl", "/bin/systemctl")) + if executable: + return ([executable, "list-units", "--type=service", "--all", "--no-legend", + "--no-pager", "--plain"], executable) + return None + + +def _platform_subprocess_environment(): + # Do not let user-controlled loader, locale, or proxy variables influence + # the small allowlist of trusted read-only platform tools. + if os.name == "nt": + system_root = r"C:\Windows" + return { + "PATH": system_root + r"\System32;" + system_root, + "PATHEXT": ".COM;.EXE;.BAT;.CMD", + "SystemRoot": system_root, + "WINDIR": system_root, + } + return {"LANG": "C", "LC_ALL": "C", "PATH": "/usr/bin:/bin:/usr/sbin:/sbin"} + + +def _run_platform_command(argv, executable, timeout=15): + if not argv or argv[0] != executable or not _is_regular(Path(executable)): + raise PartialError("adapter_tool_missing") + try: + # Spool hardcoded adapter output to private temporary files so a large + # process/service table cannot cause an unbounded in-memory capture. + with tempfile.TemporaryFile() as stdout, tempfile.TemporaryFile() as stderr: + completed = subprocess.run(argv, stdin=subprocess.DEVNULL, stdout=stdout, + stderr=stderr, timeout=timeout, check=False, + shell=False, env=_platform_subprocess_environment()) + stdout_size = stdout.tell() + stderr_size = stderr.tell() + if stdout_size > MAX_ADAPTER_OUTPUT or stderr_size > MAX_ADAPTER_OUTPUT: + raise PartialError("adapter_output_limit") + stdout.seek(0) + stderr.seek(0) + stdout_bytes = stdout.read(MAX_ADAPTER_OUTPUT + 1) + stderr_bytes = stderr.read(MAX_ADAPTER_OUTPUT + 1) + except (OSError, subprocess.SubprocessError) as exc: + raise PartialError("adapter_execution_failed") from exc + if completed.returncode != 0: + raise PartialError("adapter_permission_or_runtime_failure") + if stderr_bytes.strip(): + raise PartialError("adapter_reported_warning") + try: + return stdout_bytes.decode("utf-8", errors="strict") + except UnicodeError as exc: + raise PartialError("adapter_output_encoding") from exc + + +def _adapter_platform(): + return { + "machine": platform.machine(), + "python": platform.python_version(), + "release": platform.release(), + "system": platform.system(), + } + + +def _linux_processes(): + root = Path("/proc") + if not root.is_dir(): + raise PartialError("proc_unavailable") + records = [] + partial = False + try: + pids = sorted((entry for entry in root.iterdir() if entry.name.isdigit()), + key=lambda value: int(value.name)) + except OSError as exc: + raise PartialError("proc_unreadable") from exc + if len(pids) > 100_000: + partial = True + for path in pids[:100_000]: + try: + data = (path / "status").read_text(encoding="utf-8", errors="strict") + fields = {} + for line in data.splitlines(): + key, separator, value = line.partition(":") + if separator and key in {"Name", "PPid", "Uid"}: + fields[key] = value.strip() + records.append({ + "name": fields.get("Name", "?"), + "pid": int(path.name), + "ppid": int(fields.get("PPid", "0").split()[0]), + "uid": int(fields.get("Uid", "-1").split()[0]), + }) + except FileNotFoundError: + # A process exiting during enumeration is normal and does not make + # the remaining observation misleading. + continue + except (OSError, UnicodeError, ValueError, IndexError): + # Processes may exit while /proc is being read. Keep the snapshot + # useful but make the adapter explicitly partial. + partial = True + return records, partial + + +def _processes_adapter(): + system = platform.system() + if system == "Linux": + return _linux_processes() + command = _platform_command("processes") + if not command: + raise PartialError("adapter_unsupported") + output = _run_platform_command(*command) + records = [] + if system == "Darwin": + for line in output.splitlines(): + parts = line.strip().split(None, 3) + if len(parts) != 4: + continue + try: + pid, ppid, uid = map(int, parts[:3]) + except ValueError: + continue + records.append({"pid": pid, "ppid": ppid, "uid": uid, "name": parts[3]}) + elif system == "Windows": + for row in csv.reader(output.splitlines()): + if len(row) < 2: + continue + try: + pid = int(row[1]) + except ValueError: + continue + records.append({"pid": pid, "ppid": None, "uid": None, "name": row[0]}) + return sorted(records, key=lambda value: (value["pid"], value["name"])), False + + +def _decode_proc_address(value, ipv6=False): + address, port = value.split(":", 1) + packed = bytes.fromhex(address) + if ipv6: + # Linux /proc exposes IPv6 as four native-endian 32-bit words. + packed = b"".join(packed[index:index + 4][::-1] for index in range(0, 16, 4)) + else: + packed = packed[::-1] + return str(ipaddress.ip_address(packed)), int(port, 16) + + +def _linux_listeners(): + records = [] + partial = False + for filename, protocol, ipv6 in ( + ("/proc/net/tcp", "tcp", False), ("/proc/net/tcp6", "tcp6", True), + ("/proc/net/udp", "udp", False), ("/proc/net/udp6", "udp6", True)): + path = Path(filename) + try: + stream = path.open("r", encoding="ascii", errors="strict") + except (OSError, UnicodeError): + partial = True + continue + with stream: + consumed = 0 + for line_number, line in enumerate(stream): + consumed += len(line.encode("ascii")) + if consumed > MAX_ADAPTER_OUTPUT or line_number > 100_000: + partial = True + break + if line_number == 0: + continue + parts = line.split() + if len(parts) < 10: + partial = True + continue + state = parts[3] + if protocol.startswith("tcp") and state != "0A": + continue + try: + address, port = _decode_proc_address(parts[1], ipv6) + except (ValueError, IndexError): + partial = True + continue + records.append({"address": address, "port": port, "protocol": protocol, + "state": "listen" if protocol.startswith("tcp") else "bound"}) + records.sort(key=lambda value: (value["protocol"], value["address"], value["port"])) + return records, partial + + +def _darwin_listeners(): + command = _platform_command("listeners") + if not command: + raise PartialError("adapter_tool_missing") + output = _run_platform_command(*command) + records = [] + current_pid = None + current_name = None + for line in output.splitlines(): + if not line: + continue + tag, value = line[0], line[1:] + if tag == "p" and value.isdigit(): + current_pid = int(value) + elif tag == "c": + current_name = value + elif tag == "n": + match = re.search(r"(?:\[([^]]+)\]|([^:]+)):(\d+)(?:\s|$)", value) + if match: + records.append({"address": match.group(1) or match.group(2), + "name": current_name, "pid": current_pid, + "port": int(match.group(3)), "protocol": "tcp", + "state": "listen"}) + records.sort(key=lambda value: (value["port"], value.get("pid") or -1, + value.get("name") or "")) + return records, False + + +def _listeners_adapter(): + if platform.system() == "Linux": + return _linux_listeners() + if platform.system() == "Darwin": + return _darwin_listeners() + raise PartialError("adapter_unsupported") + + +def _services_adapter(): + command = _platform_command("services") + if not command: + raise PartialError("adapter_tool_missing") + output = _run_platform_command(*command) + system = platform.system() + records = [] + if system == "Linux": + for line in output.splitlines(): + fields = line.split(None, 4) + if len(fields) >= 4: + records.append({"name": fields[0], "load": fields[1], + "active": fields[2], "sub": fields[3]}) + elif system == "Darwin": + for line in output.splitlines()[1:]: + fields = line.split(None, 2) + if len(fields) == 3: + try: + pid = None if fields[0] == "-" else int(fields[0]) + except ValueError: + continue + records.append({"name": fields[2], "pid": pid, "status": fields[1]}) + elif system == "Windows": + name = state_value = None + for line in output.splitlines(): + stripped = line.strip() + if stripped.startswith("SERVICE_NAME:"): + if name is not None: + records.append({"name": name, "state": state_value or "unknown"}) + name = stripped.partition(":")[2].strip() + state_value = None + elif stripped.startswith("STATE"): + fields = stripped.split() + state_value = fields[3].lower() if len(fields) >= 4 else "unknown" + if name is not None: + records.append({"name": name, "state": state_value or "unknown"}) + return sorted(records, key=lambda value: value["name"]), False + + +def _docker_executable(): + system = platform.system() + if system == "Darwin": + return _known_executable(( + "/Applications/Docker.app/Contents/Resources/bin/docker", + "/opt/homebrew/bin/docker", "/usr/local/bin/docker", "/usr/bin/docker", + )) + if system == "Linux": + return _known_executable(("/usr/bin/docker", "/usr/local/bin/docker", "/bin/docker")) + if system == "Windows": + return _known_executable(( + r"C:\Program Files\Docker\Docker\resources\bin\docker.exe", + r"C:\ProgramData\DockerDesktop\version-bin\docker.exe", + )) + return None + + +def _compose_adapter(root: Path, compose): + executable = _docker_executable() + if not executable: + raise PartialError("adapter_tool_missing") + root_identity = _root_anchor_identity(root.lstat()) + config_files = [] + for relative in compose["files"]: + metadata, digest = _hash_anchored_regular( + root, relative, root_identity, MAX_COMPOSE_FILE_BYTES + ) + config_files.append({"path": relative, "sha256": digest, "size": metadata.st_size}) + + project = compose["project"] + template = '{{.Label "com.docker.compose.service"}}\t{{.State}}\t{{.Status}}' + argv = [executable, "ps", "--all", "--filter", + "label=com.docker.compose.project=" + project, "--format", template] + output = _run_platform_command(argv, executable) + groups = Counter() + partial = False + for line in output.splitlines(): + fields = line.split("\t", 2) + if len(fields) != 3: + partial = True + continue + service, state, status_text = (field.strip() for field in fields) + if not IDENTIFIER.fullmatch(service) or not state or len(state) > 64: + partial = True + continue + health_match = re.search(r"\((healthy|unhealthy|starting)\)", status_text) + health = health_match.group(1) if health_match else "none" + groups[(service, state, health)] += 1 + observed_services = {key[0] for key in groups} + for service in compose["services"]: + if service not in observed_services: + groups[(service, "missing", "none")] = 0 + services = [ + {"count": count, "health": health, "service": service, "state": state} + for (service, state, health), count in sorted(groups.items()) + ] + return { + "config_files": config_files, + "project_sha256": _opaque_text_identifier(project), + "services": services, + }, partial + + +def _adapter_preflight(name, profile_data=None): + if name == "platform": + return True, None + system = platform.system() + if name == "processes" and system == "Linux": + return Path("/proc").is_dir(), None if Path("/proc").is_dir() else "proc_unavailable" + if name == "listeners" and system == "Linux": + ok = Path("/proc/net").is_dir() + return ok, None if ok else "proc_net_unavailable" + if name == "listeners" and system not in {"Darwin", "Linux"}: + return False, "adapter_unsupported" + if name == "compose": + if not profile_data or "compose" not in profile_data: + return False, "compose_profile_missing" + executable = _docker_executable() + return (bool(executable), None if executable else "adapter_tool_missing") + command = _platform_command(name) + if not command or not _is_regular(Path(command[1])): + return False, "adapter_tool_missing" + return True, None + + +def command_preflight(args): + profile_data = load_profile(args.profile) + snapshot_profile = profile_data.get("snapshot", {}) + requested = snapshot_profile.get("adapters", list(DEFAULT_ADAPTERS)) + checks = [{"name": "python", "ok": sys.version_info >= (3, 10), + "reason": None if sys.version_info >= (3, 10) else "python_too_old"}] + for adapter in requested: + ok, reason = _adapter_preflight(adapter, profile_data) + checks.append({"name": "adapter:" + adapter, "ok": ok, "reason": reason}) + if "health" in profile_data: + checks.append({"name": "health-profile", "ok": True, "reason": None}) + if "backup" in profile_data: + checks.append({"name": "backup-profile", "ok": True, "reason": None}) + if "backup" in profile_data or "evidence" in profile_data: + checks.append({ + "name": "directory-staging", + "ok": DIRECTORY_STAGING_SUPPORTED, + "reason": None if DIRECTORY_STAGING_SUPPORTED else "platform_unsupported", + }) + partial = not all(check["ok"] for check in checks) + result = {"command": "preflight", "exit_code": 2 if partial else 0, + "partial": partial, "platform": _adapter_platform(), + "profile": {"name": profile_data["name"], "sha256": _profile_hash(profile_data)}, + "checks": checks, "tool": _tool_record()} + print(_canonical(result).decode("utf-8"), end="") + return result["exit_code"] + + +def _snapshot_files(root, settings): + include = settings.get("include", ["*"]) + exclude = settings.get("exclude", []) + max_files = settings.get("max_files", 20_000) + max_file_bytes = settings.get("max_file_bytes", 64 * 1024 * 1024) + max_total_bytes = settings.get("max_total_bytes", 4 * 1024 * 1024 * 1024) + files = [] + issues = [] + skipped = Counter() + portable_paths = set() + total = 0 + for kind, path, detail in _bounded_walk(root, include, exclude, max_files, + SNAPSHOT_SKIP_DIRS, skip_secret_dirs=True, + require_portable=True): + if kind == "skip": + skipped[detail] += 1 + if detail == "symlink" or (detail == "special" and _matches( + path.relative_to(root).as_posix(), include)): + try: + raw_rel = path.relative_to(root).as_posix() + except ValueError: + raw_rel = "." + try: + issue_path = _portable_relative_posix(raw_rel, "snapshot issue path", + allow_dot=True) + except DefenseError: + issue_path = _opaque_text_identifier(raw_rel) + issues.append({"component": "files", "path": issue_path, + "reason": "included_" + detail}) + continue + if kind == "nonportable": + skipped["nonportable_path"] += 1 + issues.append({"component": "files", "path": detail, + "reason": "nonportable_path"}) + continue + if kind in {"issue", "limit"}: + rel = "." + try: + rel = path.relative_to(root).as_posix() + except ValueError: + pass + issues.append({"component": "files", "path": rel, "reason": detail}) + if kind == "limit": + break + continue + rel = detail + portable_key = _portable_path_key(rel) + if portable_key in portable_paths: + skipped["casefold_collision"] += 1 + issues.append({"component": "files", "path": _opaque_text_identifier(rel), + "reason": "casefold_collision"}) + continue + portable_paths.add(portable_key) + if _secret_filename(path.name): + skipped["secret_filename"] += 1 + continue + if len(files) >= max_files: + issues.append({"component": "files", "path": rel, "reason": "file_limit_reached"}) + break + try: + metadata, digest = _hash_regular(path, max_file_bytes) + except (OSError, PartialError): + issues.append({"component": "files", "path": rel, "reason": "unreadable_or_unstable"}) + continue + if total + metadata.st_size > max_total_bytes: + issues.append({"component": "files", "path": rel, "reason": "total_byte_limit_reached"}) + break + total += metadata.st_size + files.append({"mode": stat.S_IMODE(metadata.st_mode), "mtime_ns": metadata.st_mtime_ns, + "path": rel, "sha256": digest, "size": metadata.st_size}) + return files, issues, dict(sorted(skipped.items())), total + + +def command_snapshot(args): + profile_data = load_profile(args.profile) + root = _canonical_root_directory(Path(args.root)) + if root.name.casefold() in {name.casefold() for name in SNAPSHOT_SKIP_DIRS} or _secret_filename(root.name): + raise DefenseError("snapshot root is a secret or excluded directory") + settings = profile_data.get("snapshot", {}) + files, issues, skipped, total = _snapshot_files(root, settings) + requested = settings.get("adapters", list(DEFAULT_ADAPTERS)) + adapter_data = {} + for name in requested: + try: + if name == "platform": + data, partial = _adapter_platform(), False + elif name == "processes": + data, partial = _processes_adapter() + elif name == "listeners": + data, partial = _listeners_adapter() + elif name == "services": + data, partial = _services_adapter() + elif name == "compose": + data, partial = _compose_adapter(root, profile_data["compose"]) + else: # Profile validation should make this unreachable. + raise PartialError("adapter_not_allowed") + adapter_data[name] = data + if partial: + issues.append({"component": "adapter:" + name, "path": None, + "reason": "observation_partial"}) + except PartialError as exc: + adapter_data[name] = None + issues.append({"component": "adapter:" + name, "path": None, + "reason": str(exc)}) + partial = bool(issues) + result = { + "adapters": adapter_data, + "created_at": _now(), + "files": files, + "issues": sorted(issues, key=lambda value: (value["component"], value.get("path") or "", + value["reason"])), + "limits": {"max_file_bytes": settings.get("max_file_bytes", 64 * 1024 * 1024), + "max_files": settings.get("max_files", 20_000), + "max_total_bytes": settings.get("max_total_bytes", 4 * 1024 * 1024 * 1024)}, + "partial": partial, + "profile": {"name": profile_data["name"], "sha256": _profile_hash(profile_data)}, + "root": _opaque_root_identifier(root), + "schema": SNAPSHOT_SCHEMA, + "scope": _snapshot_scope(settings, requested, profile_data.get("compose")), + "skipped": skipped, + "summary": {"files": len(files), "total_bytes": total}, + "tool": _tool_record(), + } + _validate_snapshot(result) + output_path = _atomic_write_new( + args.output, _bounded_canonical(result, MAX_JSON_BYTES, "snapshot") + ) + print(json.dumps({"output": str(output_path), "partial": partial, + "files": len(files), "exit_code": 2 if partial else 0}, sort_keys=True)) + return 2 if partial else 0 + + +def _validate_adapter_value(name, value): + if value is None: + return + if name == "platform": + _strict_keys(value, {"machine", "python", "release", "system"}, + {"machine", "system"}, "platform adapter") + for field, item in value.items(): + _safe_string(item, "platform " + field, 0, 512) + return + if name == "compose": + _strict_keys(value, {"config_files", "project_sha256", "services"}, + {"config_files", "project_sha256", "services"}, "compose adapter") + if not isinstance(value["project_sha256"], str) or not OPAQUE_ID.fullmatch( + value["project_sha256"]): + raise DefenseError("invalid compose project identifier") + configs = value["config_files"] + if not isinstance(configs, list) or not 1 <= len(configs) <= 8: + raise DefenseError("invalid compose config records") + config_paths = [] + for record in configs: + _strict_keys(record, {"path", "sha256", "size"}, {"path", "sha256", "size"}, + "compose config record") + path = _portable_relative_posix(record["path"], "compose config path") + if (type(record["size"]) is not int or + not 0 <= record["size"] <= MAX_COMPOSE_FILE_BYTES or + not isinstance(record["sha256"], str) or + not re.fullmatch(r"[0-9a-f]{64}", record["sha256"])): + raise DefenseError("invalid compose config metadata") + config_paths.append(path) + if config_paths != sorted(set(config_paths)): + raise DefenseError("compose configs are not deterministically ordered") + services = value["services"] + if not isinstance(services, list) or len(services) > 100_000: + raise DefenseError("invalid compose service records") + ordering = [] + for record in services: + _strict_keys(record, {"count", "health", "service", "state"}, + {"count", "health", "service", "state"}, + "compose service record") + if (not IDENTIFIER.fullmatch(record["service"] if isinstance( + record["service"], str) else "") or + not isinstance(record["state"], str) or + not 1 <= len(record["state"]) <= 64 or + record["health"] not in {"healthy", "unhealthy", "starting", "none"} or + type(record["count"]) is not int or not 0 <= record["count"] <= 100_000): + raise DefenseError("invalid compose service state") + ordering.append((record["service"], record["state"], record["health"])) + if ordering != sorted(set(ordering)): + raise DefenseError("compose services are not deterministically ordered") + return + if not isinstance(value, list) or len(value) > 100_000: + raise DefenseError("invalid adapter records") + for record in value: + if name == "processes": + _strict_keys(record, {"name", "pid", "ppid", "uid"}, + {"name", "pid", "ppid", "uid"}, "process adapter record") + _safe_string(record["name"], "process name", 0, 1024) + for field in ("pid", "ppid", "uid"): + if record[field] is not None and type(record[field]) is not int: + raise DefenseError("invalid process adapter identifier") + elif name == "listeners": + _strict_keys(record, {"address", "name", "pid", "port", "protocol", "state"}, + {"address", "port", "protocol", "state"}, "listener adapter record") + _safe_string(record["address"], "listener address", 1, 256) + _safe_string(record["protocol"], "listener protocol", 1, 32) + _safe_string(record["state"], "listener state", 1, 64) + if type(record["port"]) is not int or not 0 <= record["port"] <= 65535: + raise DefenseError("invalid listener port") + if "pid" in record and record["pid"] is not None and type(record["pid"]) is not int: + raise DefenseError("invalid listener pid") + if "name" in record and record["name"] is not None: + _safe_string(record["name"], "listener name", 0, 1024) + elif name == "services": + _strict_keys(record, {"active", "load", "name", "pid", "state", "status", "sub"}, + {"name"}, "service adapter record") + _safe_string(record["name"], "service name", 1, 1024) + if "pid" in record and record["pid"] is not None and type(record["pid"]) is not int: + raise DefenseError("invalid service pid") + for field in set(record) - {"name", "pid"}: + _safe_string(record[field], "service " + field, 0, 256) + else: + raise DefenseError("unsupported adapter") + + +def _validate_snapshot(data): + allowed = {"schema", "tool", "created_at", "profile", "root", "partial", "issues", + "limits", "files", "adapters", "scope", "skipped", "summary"} + _strict_keys(data, allowed, allowed, "snapshot") + if data["schema"] != SNAPSHOT_SCHEMA or type(data["partial"]) is not bool: + raise DefenseError("invalid snapshot schema") + _validate_tool_record(data["tool"], "snapshot tool") + _parse_timestamp(data["created_at"]) + _validate_profile_reference(data["profile"], "snapshot profile") + scope = _validate_snapshot_scope(data["scope"]) + _safe_string(data["root"], "snapshot root identifier", 1, 4096) + if not OPAQUE_ID.fullmatch(data["root"]): + raise DefenseError("snapshot root must be opaque") + + limits = data["limits"] + _strict_keys(limits, {"max_file_bytes", "max_files", "max_total_bytes"}, + {"max_file_bytes", "max_files", "max_total_bytes"}, "snapshot limits") + _positive_int(limits["max_files"], "max_files", 100_000) + _positive_int(limits["max_file_bytes"], "max_file_bytes", 1024 ** 3) + _positive_int(limits["max_total_bytes"], "max_total_bytes", 20 * 1024 ** 3) + if any(limits[key] != scope["files"][key] for key in limits): + raise DefenseError("snapshot limits do not match scope") + + if not isinstance(data["files"], list) or len(data["files"]) > limits["max_files"]: + raise DefenseError("invalid snapshot files") + indexed = {} + portable_keys = set() + for item in data["files"]: + _strict_keys(item, {"path", "size", "mtime_ns", "mode", "sha256"}, + {"path", "size", "mtime_ns", "mode", "sha256"}, "snapshot file") + path = _portable_relative_posix(item["path"], "snapshot path") + portable_key = _portable_path_key(path) + if path in indexed or portable_key in portable_keys: + raise DefenseError("duplicate snapshot file") + if (type(item["size"]) is not int or not 0 <= item["size"] <= limits["max_file_bytes"] or + type(item["mtime_ns"]) is not int or not 0 <= item["mtime_ns"] <= MAX_MTIME_NS or + type(item["mode"]) is not int or not 0 <= item["mode"] <= 0o7777 or + not isinstance(item["sha256"], str) or + not re.fullmatch(r"[0-9a-f]{64}", item["sha256"])): + raise DefenseError("invalid snapshot file metadata") + indexed[path] = item + portable_keys.add(portable_key) + + issues = data["issues"] + if not isinstance(issues, list) or len(issues) > 100_000: + raise DefenseError("invalid snapshot issues") + for issue in issues: + _strict_keys(issue, {"component", "path", "reason"}, + {"component", "path", "reason"}, "snapshot issue") + _safe_string(issue["component"], "snapshot issue component", 1, 120) + _safe_string(issue["reason"], "snapshot issue reason", 1, 120) + if issue["path"] is not None: + _safe_string(issue["path"], "snapshot issue path", 1, 4096) + if data["partial"] != bool(issues): + raise DefenseError("snapshot partial status is inconsistent") + + if not isinstance(data["adapters"], dict) or set(data["adapters"]) - set(ADAPTERS): + raise DefenseError("invalid snapshot adapters") + if set(data["adapters"]) != set(scope["adapter_semantics"]): + raise DefenseError("snapshot adapters do not match scope") + for name, value in data["adapters"].items(): + _validate_adapter_value(name, value) + if value is None and not any(issue["component"] == "adapter:" + name for issue in issues): + raise DefenseError("missing adapter has no partial issue") + + if not isinstance(data["skipped"], dict) or len(data["skipped"]) > 128: + raise DefenseError("invalid snapshot skipped summary") + for key, value in data["skipped"].items(): + _safe_string(key, "snapshot skipped key", 1, 120) + if type(value) is not int or value < 0: + raise DefenseError("invalid snapshot skipped count") + summary = data["summary"] + _strict_keys(summary, {"files", "total_bytes"}, {"files", "total_bytes"}, + "snapshot summary") + if (type(summary["files"]) is not int or type(summary["total_bytes"]) is not int or + summary["files"] != len(data["files"]) or + summary["total_bytes"] != sum(item["size"] for item in data["files"]) or + summary["total_bytes"] > limits["max_total_bytes"]): + raise DefenseError("snapshot summary is inconsistent") + return data, indexed + + +def _semantic_adapter(name, value): + if value is None or name == "platform": + return value + if name == "processes": + counts = Counter((record["name"], record["uid"]) for record in value) + return [{"count": count, "name": key[0], "uid": key[1]} + for key, count in sorted(counts.items(), key=lambda item: (item[0][0], + item[0][1] is None, + item[0][1] or -1))] + if name == "listeners": + records = {(record["address"], record["port"], record["protocol"], record["state"]) + for record in value} + return [{"address": address, "port": port, "protocol": protocol, "state": state} + for address, port, protocol, state in sorted(records)] + if name == "compose": + return value + records = [] + for record in value: + records.append({key: record[key] for key in sorted(record) if key != "pid"}) + return sorted(records, key=_canonical) + + +def _snapshot_comparison(before_data, after_data, before_sha, after_sha): + before, old = _validate_snapshot(before_data) + after, new = _validate_snapshot(after_data) + reasons = [] + if before["partial"]: + reasons.append("baseline_partial") + if after["partial"]: + reasons.append("current_partial") + before_scope = before["scope"] + after_scope = after["scope"] + if before_scope["tool_compatibility"] != after_scope["tool_compatibility"]: + reasons.append("tool_semantics_changed") + if before_scope["adapter_semantics"] != after_scope["adapter_semantics"]: + reasons.append("adapter_semantics_changed") + if before_scope["sha256"] != after_scope["sha256"]: + reasons.append("snapshot_scope_changed") + if before["profile"] != after["profile"]: + reasons.append("profile_changed") + current_major = int(VERSION.split(".", 1)[0]) + if (_tool_major(before["tool"]) != _tool_major(after["tool"]) or + _tool_major(before["tool"]) != current_major or + _tool_major(after["tool"]) != current_major): + reasons.append("tool_incompatible") + if before["root"] != after["root"]: + reasons.append("root_changed") + if set(before["adapters"]) != set(after["adapters"]): + reasons.append("adapter_scope_changed") + added = sorted(new.keys() - old.keys()) + removed = sorted(old.keys() - new.keys()) + content_changed = [] + metadata_changed = [] + for path in sorted(old.keys() & new.keys()): + if old[path]["sha256"] != new[path]["sha256"] or old[path]["size"] != new[path]["size"]: + content_changed.append(path) + elif (old[path]["mode"], old[path]["mtime_ns"]) != (new[path]["mode"], new[path]["mtime_ns"]): + metadata_changed.append(path) + changed_adapters = sorted( + name for name in set(before["adapters"]) & set(after["adapters"]) + if _semantic_adapter(name, before["adapters"][name]) != + _semantic_adapter(name, after["adapters"][name])) + comparable = not reasons + drift_count = len(added) + len(removed) + len(content_changed) + len(metadata_changed) + len(changed_adapters) + exit_code = 2 if not comparable else 1 if drift_count else 0 + return { + "baseline": {"created_at": before["created_at"], "sha256": before_sha}, + "comparable": comparable, + "compared_at": _now(), + "current": {"created_at": after["created_at"], "sha256": after_sha}, + "drift": {"adapters_changed": changed_adapters, "files_added": added, + "files_content_changed": content_changed, + "files_metadata_changed": metadata_changed, "files_removed": removed}, + "exit_code": exit_code, + "partial": not comparable, + "profile": before["profile"], + "reasons": reasons, + "schema": COMPARISON_SCHEMA, + "scope": {"baseline_sha256": before_scope["sha256"], + "current_sha256": after_scope["sha256"]}, + "summary": {"adapter_changes": len(changed_adapters), "drift_count": drift_count, + "files_added": len(added), "files_content_changed": len(content_changed), + "files_metadata_changed": len(metadata_changed), "files_removed": len(removed)}, + "tool": _tool_record(), + } + + +def command_compare(args): + baseline, baseline_raw = _read_json(args.baseline) + current, current_raw = _read_json(args.current) + result = _snapshot_comparison(baseline, current, _sha256_bytes(baseline_raw), + _sha256_bytes(current_raw)) + print(_canonical(result).decode("utf-8"), end="") + return result["exit_code"] + + +class _NoRedirect(HTTPRedirectHandler): + def redirect_request(self, req, fp, code, msg, headers, newurl): + return None + + +def _http_opener(): + return build_opener(ProxyHandler({}), _NoRedirect()) + + +def _health_probe(check): + started = time.monotonic() + result = {"name": check["name"], "ok": False, "status": None} + try: + request = Request(check["url"], headers={"User-Agent": f"DurkaHelper-defense-ops/{VERSION}"}) + try: + response = _http_opener().open(request, timeout=float(check.get("timeout", 3.0))) + except HTTPError as exc: + response = exc + with response: + result["status"] = response.code + body = response.read(MAX_HTTP_BODY + 1) + if len(body) > MAX_HTTP_BODY: + raise ValueError("response limit") + text = body.decode("utf-8", errors="replace") + result["ok"] = (result["status"] == check.get("status", 200) and + check.get("contains", "") in text) + except (OSError, ValueError) as exc: + result["error"] = type(exc).__name__ + result["ms"] = round((time.monotonic() - started) * 1000) + return result + + +def command_health(args): + profile_data = load_profile(args.profile) + checks = profile_data.get("health") + if not checks: + raise DefenseError("profile has no health checks") + # Profile validation happens in full before the first connection. + results = [_health_probe(check) for check in checks] + failed = sum(not result["ok"] for result in results) + output = {"checked_at": _now(), "command": "health", "exit_code": 1 if failed else 0, + "profile": {"name": profile_data["name"], "sha256": _profile_hash(profile_data)}, + "results": results, "summary": {"failed": failed, "total": len(results)}, + "tool": _tool_record()} + print(_canonical(output).decode("utf-8"), end="") + return output["exit_code"] + + +def _resolve_profile_path(root: Path, relative: str): + parts = [] if relative == "." else relative.split("/") + current = root + for part in parts: + current = current / part + try: + if current.is_symlink(): + raise DefenseError("backup source contains a symlink") + except OSError as exc: + raise DefenseError("backup source metadata unavailable") from exc + try: + current.relative_to(root) + except ValueError as exc: + raise DefenseError("backup source leaves root") from exc + return current + + +def _live_database_name(path: str): + lowered = path.lower() + return (lowered.endswith(LIVE_DATABASE_SUFFIXES) or ".sqlite-" in lowered or + lowered.endswith((".db-wal", ".db-shm", ".db-journal"))) + + +def _backup_sources(root: Path, backup): + excluded = backup.get("exclude", []) + max_files = backup.get("max_files", 20_000) + sources = [] + seen = set() + portable_seen = set() + for entry in backup["entries"]: + rel = PurePosixPath(entry["path"]).as_posix() + source = _resolve_profile_path(root, rel) + kind = entry["kind"] + if not source.exists(): + raise DefenseError("backup source is missing") + if kind in {"file", "native_dump"}: + if not _is_regular(source): + raise DefenseError("backup source is not a regular file") + if kind != "native_dump" and _live_database_name(rel): + raise DefenseError("live database files cannot be copied") + if kind == "native_dump" and not rel.lower().endswith(NATIVE_DUMP_SUFFIXES): + raise DefenseError("native dump has an unrecognized dump suffix") + if rel not in seen and not _matches(rel, excluded): + portable_key = _portable_path_key(rel) + if portable_key in portable_seen: + raise DefenseError("case-fold-colliding backup source") + seen.add(rel) + portable_seen.add(portable_key) + sources.append((rel, source, kind)) + else: + if not source.is_dir(): + raise DefenseError("backup tree source is not a directory") + prefix = "" if rel == "." else rel + "/" + for found_kind, path, detail in _bounded_walk(source, ["*"], [], max_files, + require_portable=True): + if found_kind in {"issue", "limit"}: + raise PartialError("backup tree is unreadable or exceeds limits") + if found_kind == "nonportable": + raise DefenseError("backup tree contains a nonportable path") + if found_kind == "skip": + if detail in {"symlink", "special"}: + raise DefenseError("backup tree contains a symlink or special file") + continue + child = prefix + detail + if _matches(child, excluded): + continue + if _live_database_name(child): + raise DefenseError("backup tree contains a live database file") + if child in seen: + raise DefenseError("duplicate backup source") + portable_key = _portable_path_key(child) + if portable_key in portable_seen: + raise DefenseError("case-fold-colliding backup source") + seen.add(child) + portable_seen.add(portable_key) + sources.append((child, path, "tree")) + if len(sources) > max_files: + raise PartialError("backup file limit reached") + return sorted(sources, key=lambda value: value[0]) + + +def _root_anchor_identity(metadata): + return (metadata.st_dev, metadata.st_ino, stat.S_IFMT(metadata.st_mode)) + + +def _open_anchored_regular(root: Path, relative: str, expected_root_identity): + relative = _portable_relative_posix(relative, "backup source") + flags = (os.O_RDONLY | getattr(os, "O_BINARY", 0) | + getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0)) + if (os.name == "posix" and hasattr(os, "O_DIRECTORY") and hasattr(os, "O_NOFOLLOW") and + os.open in os.supports_dir_fd): + root_fd = os.open(root, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW) + current_fd = root_fd + try: + if _root_anchor_identity(os.fstat(root_fd)) != expected_root_identity: + raise PartialError("backup root changed during read") + parts = relative.split("/") + for part in parts[:-1]: + next_fd = os.open(part, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, + dir_fd=current_fd) + if current_fd != root_fd: + os.close(current_fd) + current_fd = next_fd + fd = os.open(parts[-1], flags, dir_fd=current_fd) + metadata = os.fstat(fd) + if not stat.S_ISREG(metadata.st_mode): + os.close(fd) + raise DefenseError("backup source is not regular") + return fd + except OSError as exc: + raise PartialError("backup source identity unavailable") from exc + finally: + if current_fd != root_fd: + os.close(current_fd) + os.close(root_fd) + + # Windows has no Python dirfd traversal. Preserve no-follow leaf checks + # and verify every current ancestor before opening; the POSIX competition + # paths above use the stronger descriptor-anchored implementation. + source = root.joinpath(*relative.split("/")) + current = root + try: + if _root_anchor_identity(root.lstat()) != expected_root_identity: + raise PartialError("backup root changed during read") + for part in relative.split("/")[:-1]: + current = current / part + metadata = current.lstat() + if not stat.S_ISDIR(metadata.st_mode) or stat.S_ISLNK(metadata.st_mode): + raise PartialError("backup source parent changed during read") + return os.open(source, flags) + except OSError as exc: + raise PartialError("backup source identity unavailable") from exc + + +def _hash_anchored_regular(root: Path, relative: str, expected_root_identity, + max_bytes: int): + fd = _open_anchored_regular(root, relative, expected_root_identity) + try: + before = os.fstat(fd) + if before.st_size > max_bytes: + raise PartialError("compose_config_too_large") + digest = hashlib.sha256() + consumed = 0 + while True: + block = os.read(fd, CHUNK) + if not block: + break + consumed += len(block) + if consumed > max_bytes: + raise PartialError("compose_config_too_large") + digest.update(block) + after = os.fstat(fd) + if _stat_identity(before) != _stat_identity(after): + raise PartialError("compose_config_changed_during_read") + return before, digest.hexdigest() + finally: + os.close(fd) + + +def _copy_stable(root: Path, relative: str, destination: Path, max_bytes: int, + total_state, expected_root_identity): + fd = _open_anchored_regular(root, relative, expected_root_identity) + staging_destination = (isinstance(destination, tuple) and len(destination) == 2 and + isinstance(destination[0], _StagingDirectory)) + if staging_destination: + staging, staging_relative = destination + destination_path = None + else: + destination_path = Path(destination) + try: + before = os.fstat(fd) + if not stat.S_ISREG(before.st_mode): + raise DefenseError("backup source is not regular") + if before.st_size > max_bytes: + raise PartialError("backup file byte limit reached") + if total_state[0] + before.st_size > total_state[1]: + raise PartialError("backup total byte limit reached") + if staging_destination: + target_fd = staging.open_new_file(staging_relative, 0o600) + else: + destination_path.parent.mkdir(parents=True, exist_ok=True, mode=0o700) + target_fd = os.open(destination_path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | + getattr(os, "O_BINARY", 0), 0o600) + digest = hashlib.sha256() + consumed = 0 + with os.fdopen(fd, "rb", closefd=False) as source_stream, os.fdopen(target_fd, "wb") as target: + while True: + block = source_stream.read(CHUNK) + if not block: + break + consumed += len(block) + if consumed > max_bytes: + raise PartialError("backup file byte limit reached") + digest.update(block) + target.write(block) + target.flush() + os.fsync(target.fileno()) + after = os.fstat(fd) + if _stat_identity(before) != _stat_identity(after): + if not staging_destination: + try: + destination_path.unlink() + except OSError: + pass + raise PartialError("backup source changed while reading") + if staging_destination: + staging.set_file_metadata(staging_relative, 0o600) + else: + try: + destination_path.chmod(0o600) + except OSError: + pass + total_state[0] += consumed + return before, digest.hexdigest() + finally: + os.close(fd) + + +def _regular_path_identity(root: Path, relative: str, expected_root_identity): + fd = _open_anchored_regular(root, relative, expected_root_identity) + try: + metadata = os.fstat(fd) + if not stat.S_ISREG(metadata.st_mode): + raise DefenseError("backup source is not regular") + return _stat_identity(metadata) + finally: + os.close(fd) + + +def _manifest_bundle_hash(entries): + return _sha256_bytes(_canonical(entries)) + + +def command_backup_create(args): + profile_data = load_profile(args.profile) + backup = profile_data.get("backup") + if not backup: + raise DefenseError("profile has no backup entries") + root = _canonical_root_directory(Path(args.root)) + root_identity = _root_anchor_identity(root.lstat()) + target = _safe_output_parent(Path(args.output)) + sources = _backup_sources(root, backup) + if not sources: + raise DefenseError("backup selection is empty") + max_file_bytes = backup.get("max_file_bytes", 1024 * 1024 * 1024) + total_state = [0, backup.get("max_total_bytes", 20 * 1024 * 1024 * 1024)] + identities = {relative: _regular_path_identity(root, relative, root_identity) + for relative, source, _kind in sources} + staging = _StagingDirectory.create(target, ".defense-backup-") + try: + staging.mkdir("files") + manifest_entries = [] + for number, (relative, source, kind) in enumerate(sources, 1): + stored = f"files/{number:06d}.bin" + metadata, digest = _copy_stable(root, relative, (staging, stored), max_file_bytes, + total_state, root_identity) + if _stat_identity(metadata) != identities[relative]: + raise PartialError("backup source changed before copy") + manifest_entries.append({ + "kind": kind, + "mode": stat.S_IMODE(metadata.st_mode), + "mtime_ns": metadata.st_mtime_ns, + "sha256": digest, + "size": metadata.st_size, + "source": relative, + "stored": stored, + }) + rechecked_sources = _backup_sources(root, backup) + if ([(relative, kind) for relative, _source, kind in rechecked_sources] != + [(relative, kind) for relative, _source, kind in sources]): + raise PartialError("backup source membership changed during copy") + for relative, source, _kind in sources: + if _regular_path_identity(root, relative, root_identity) != identities[relative]: + raise PartialError("backup source set changed during copy") + manifest = { + "bundle_sha256": _manifest_bundle_hash(manifest_entries), + "created_at": _now(), + "entries": manifest_entries, + "profile": {"name": profile_data["name"], "sha256": _profile_hash(profile_data)}, + "root": _opaque_root_identifier(root), + "schema": BACKUP_SCHEMA, + "summary": {"files": len(manifest_entries), "total_bytes": total_state[0]}, + "tool": _tool_record(), + } + _validate_backup_manifest(manifest) + manifest_payload = _bounded_canonical(manifest, MAX_JSON_BYTES, "backup manifest") + staging.write_new_bytes("manifest.json", manifest_payload) + _publish_directory(staging, target) + finally: + staging.cleanup() + output = {"backup": str(target), "bundle_sha256": manifest["bundle_sha256"], + "exit_code": 0, "files": len(manifest_entries), "total_bytes": total_state[0]} + print(_canonical(output).decode("utf-8"), end="") + return 0 + + +def _validate_backup_manifest(data): + _strict_keys(data, {"schema", "tool", "created_at", "profile", "root", "entries", + "summary", "bundle_sha256"}, + {"schema", "tool", "created_at", "profile", "root", "entries", + "summary", "bundle_sha256"}, "backup manifest") + if (data["schema"] != BACKUP_SCHEMA or not isinstance(data["bundle_sha256"], str) or + not re.fullmatch(r"[0-9a-f]{64}", data["bundle_sha256"])): + raise DefenseError("invalid backup manifest schema") + _validate_tool_record(data["tool"], "backup tool") + _parse_timestamp(data["created_at"]) + _validate_profile_reference(data["profile"], "backup profile") + if not isinstance(data["root"], str) or not OPAQUE_ID.fullmatch(data["root"]): + raise DefenseError("backup root must be opaque") + if not isinstance(data["entries"], list) or not 1 <= len(data["entries"]) <= 100_000: + raise DefenseError("invalid backup entries") + sources = set() + portable_sources = set() + stored_paths = set() + total_bytes = 0 + ordered_sources = [] + for number, entry in enumerate(data["entries"], 1): + _strict_keys(entry, {"source", "stored", "kind", "size", "sha256", "mode", "mtime_ns"}, + {"source", "stored", "kind", "size", "sha256", "mode", "mtime_ns"}, + "backup manifest entry") + source = _portable_relative_posix(entry["source"], "backup source", allow_dot=True) + stored = _relative_posix(entry["stored"], "backup stored path") + portable_key = _portable_path_key(source) + if (stored != f"files/{number:06d}.bin" or source in sources or + portable_key in portable_sources or stored in stored_paths): + raise DefenseError("duplicate or invalid backup entry") + if (not isinstance(entry["kind"], str) or + entry["kind"] not in {"file", "tree", "native_dump"}): + raise DefenseError("invalid backup entry kind") + if (type(entry["size"]) is not int or not 0 <= entry["size"] <= MAX_IMPORTED_FILE_BYTES or + type(entry["mode"]) is not int or not 0 <= entry["mode"] <= 0o7777 or + type(entry["mtime_ns"]) is not int or not 0 <= entry["mtime_ns"] <= MAX_MTIME_NS or + not isinstance(entry["sha256"], str) or + not re.fullmatch(r"[0-9a-f]{64}", entry["sha256"])): + raise DefenseError("invalid backup entry metadata") + sources.add(source) + portable_sources.add(portable_key) + stored_paths.add(stored) + ordered_sources.append(source) + total_bytes += entry["size"] + if total_bytes > MAX_IMPORTED_TOTAL_BYTES: + raise DefenseError("backup manifest total exceeds limit") + if ordered_sources != sorted(ordered_sources): + raise DefenseError("backup entries are not deterministically ordered") + for index, source in enumerate(ordered_sources): + if source == "." or any(other.startswith(source + "/") + for other in ordered_sources[index + 1:]): + raise DefenseError("backup source paths overlap") + summary = data["summary"] + _strict_keys(summary, {"files", "total_bytes"}, {"files", "total_bytes"}, + "backup summary") + if (type(summary["files"]) is not int or type(summary["total_bytes"]) is not int or + summary["files"] != len(data["entries"]) or summary["total_bytes"] != total_bytes): + raise DefenseError("backup summary is inconsistent") + if data["bundle_sha256"] != _manifest_bundle_hash(data["entries"]): + raise DefenseError("backup manifest bundle hash mismatch") + return data + + +def _load_backup(backup_path): + backup = _canonical_input_leaf(Path(backup_path)) + if not backup.is_dir(): + raise DefenseError("backup must be a directory") + manifest, raw = _read_json(backup / "manifest.json") + return backup, _validate_backup_manifest(manifest), raw + + +def _verify_backup(backup, manifest): + expected = {entry["stored"] for entry in manifest["entries"]} + expected_directories = {"files"} + for stored in expected: + parent = PurePosixPath(stored).parent + while parent.as_posix() not in {".", ""}: + expected_directories.add(parent.as_posix()) + parent = parent.parent + actual = set() + actual_directories = {"files"} + files_root = backup / "files" + if not files_root.is_dir() or files_root.is_symlink(): + raise DefenseError("backup files directory is invalid") + try: + top_level = sorted(item.name for item in backup.iterdir()) + except OSError as exc: + raise DefenseError("backup directory is unreadable") from exc + if top_level != ["files", "manifest.json"]: + raise DefenseError("backup contains unexpected top-level entries") + for root, directories, files in os.walk(files_root, followlinks=False): + directories.sort() + files.sort() + for name in list(directories): + path = Path(root) / name + if path.is_symlink(): + raise DefenseError("backup contains a symlink") + actual_directories.add(path.relative_to(backup).as_posix()) + for name in files: + path = Path(root) / name + if path.is_symlink() or not _is_regular(path): + raise DefenseError("backup contains a non-regular file") + actual.add(path.relative_to(backup).as_posix()) + problems = [] + for entry in manifest["entries"]: + path = backup / PurePosixPath(entry["stored"]) + try: + metadata, digest = _hash_regular(path, max(entry["size"], 1)) + except (OSError, PartialError): + problems.append({"path": entry["stored"], "reason": "missing_or_unreadable"}) + continue + if metadata.st_size != entry["size"] or digest != entry["sha256"]: + problems.append({"path": entry["stored"], "reason": "checksum_mismatch"}) + for extra in sorted(actual - expected): + problems.append({"path": extra, "reason": "unexpected_file"}) + for missing in sorted(expected - actual): + if not any(item["path"] == missing for item in problems): + problems.append({"path": missing, "reason": "missing_file"}) + for extra in sorted(actual_directories - expected_directories): + problems.append({"path": extra, "reason": "unexpected_directory"}) + return sorted(problems, key=lambda value: (value["path"], value["reason"])) + + +def command_backup_verify(args): + backup, manifest, _raw = _load_backup(args.backup) + problems = _verify_backup(backup, manifest) + output = {"backup": str(backup), "checked_at": _now(), "exit_code": 1 if problems else 0, + "problems": problems, "summary": {"files": len(manifest["entries"]), + "problems": len(problems)}, + "tool": _tool_record()} + print(_canonical(output).decode("utf-8"), end="") + return output["exit_code"] + + +def _validate_approval_id(value): + if (not isinstance(value, str) or not APPROVAL_ID.fullmatch(value) or + value.lower() in {"approved", "approval", "yes", "true", "apply", "restore"}): + raise DefenseError("a specific safe approval id is required") + return value + + +def _safe_restore_mode(value): + if type(value) is not int or not 0 <= value <= 0o7777: + raise DefenseError("invalid restore mode") + return value & 0o755 + + +def command_restore_stage(args): + backup, manifest, _raw = _load_backup(args.backup) + problems = _verify_backup(backup, manifest) + if problems: + output = {"command": "restore-stage", "exit_code": 1, "problems": problems, + "status": "backup_verification_failed", "tool": _tool_record()} + print(_canonical(output).decode("utf-8"), end="") + return 1 + target = _safe_output_parent(Path(args.target)) + try: + target.relative_to(backup) + except ValueError: + pass + else: + raise DefenseError("restore staging target cannot be inside the backup") + if not args.apply: + output = {"apply_required": True, "backup": str(backup), "command": "restore-stage", + "exit_code": 0, "files": len(manifest["entries"]), "status": "safe_to_stage", + "target": str(target), "tool": _tool_record()} + print(_canonical(output).decode("utf-8"), end="") + return 0 + approval_id = _validate_approval_id(args.approval_id) + backup_root_identity = _root_anchor_identity(backup.lstat()) + staging = _StagingDirectory.create(target, ".defense-restore-") + try: + for entry in manifest["entries"]: + state = [0, max(entry["size"], 1)] + metadata, digest = _copy_stable( + backup, entry["stored"], (staging, entry["source"]), + max(entry["size"], 1), state, + backup_root_identity + ) + if metadata.st_size != entry["size"] or digest != entry["sha256"]: + raise DefenseError("backup changed during restore") + # Never restore set-id/sticky bits or group/world write access. + # Preserve only the original owner rwx and shared read/execute bits. + safe_mode = _safe_restore_mode(entry["mode"]) + try: + staging.set_file_metadata(entry["source"], safe_mode, entry["mtime_ns"]) + except OSError as exc: + raise PartialError("could not restore required file metadata") from exc + _publish_directory(staging, target) + finally: + staging.cleanup() + output = {"approval_id": approval_id, "backup": str(backup), "command": "restore-stage", + "exit_code": 0, "files": len(manifest["entries"]), "status": "staged", + "target": str(target), "tool": _tool_record()} + print(_canonical(output).decode("utf-8"), end="") + return 0 + + +def _parse_timestamp(value): + _safe_string(value, "timestamp", 20, 40) + if not RFC3339.fullmatch(value): + raise DefenseError("timestamp must be RFC3339 with timezone") + try: + parsed = dt.datetime.fromisoformat(value.replace("Z", "+00:00")) + except ValueError as exc: + raise DefenseError("invalid event timestamp") from exc + if parsed.tzinfo is None: + raise DefenseError("event timestamp needs a timezone") + return parsed.astimezone(dt.timezone.utc) + + +def _secret_string(value): + return any(pattern.search(value) for pattern in SECRET_VALUE_PATTERNS) + + +def _validate_safe_attributes(value, field="attributes"): + if not isinstance(value, dict) or len(value) > 64: + raise DefenseError("invalid " + field) + result = {} + for key, item in value.items(): + _safe_string(key, field + " key", 1, 64) + if SECRET_KEY.search(_normalized_key(key)) or _normalized_key(key) in COMMAND_KEYS: + raise DefenseError(field + " contains a forbidden key") + if item is not None and type(item) not in (str, int, float, bool): + raise DefenseError(field + " values must be scalar") + if type(item) is float and not math.isfinite(item): + raise DefenseError(field + " contains a non-finite number") + if isinstance(item, str): + _safe_string(item, field + " value", 0, 4096) + if _secret_string(item): + raise DefenseError(field + " contains secret-looking text") + result[key] = item + return result + + +def _validate_event(value): + _strict_keys(value, {"schema", "id", "timestamp", "source", "kind", "severity", + "summary", "attributes"}, + {"schema", "timestamp", "source", "kind", "severity", "summary"}, "event") + if value["schema"] != EVENT_SCHEMA: + raise DefenseError("unsupported event schema") + _parse_timestamp(value["timestamp"]) + _safe_string(value["source"], "event source", 1, 120) + if _secret_string(value["source"]): + raise DefenseError("event source contains secret-looking text") + if not IDENTIFIER.fullmatch(value["kind"] if isinstance(value["kind"], str) else ""): + raise DefenseError("invalid event kind") + if (not isinstance(value["severity"], str) or + value["severity"] not in {"info", "low", "medium", "high", "critical"}): + raise DefenseError("invalid event severity") + _safe_string(value["summary"], "event summary", 1, 512) + if _secret_string(value["summary"]): + raise DefenseError("event summary contains secret-looking text") + if "id" in value: + if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._:-]{0,127}", + value["id"] if isinstance(value["id"], str) else ""): + raise DefenseError("invalid event id") + if "attributes" in value: + _validate_safe_attributes(value["attributes"]) + return value + + +def _validate_validation_record(value): + _strict_keys(value, {"schema", "id", "timestamp", "check", "status", "summary", + "evidence", "attributes"}, + {"schema", "id", "timestamp", "check", "status", "summary"}, + "validation record") + if value["schema"] != VALIDATION_SCHEMA: + raise DefenseError("unsupported validation record schema") + if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._:-]{0,127}", + value["id"] if isinstance(value["id"], str) else ""): + raise DefenseError("invalid validation id") + _parse_timestamp(value["timestamp"]) + _safe_string(value["check"], "validation check", 1, 120) + if (not isinstance(value["status"], str) or + value["status"] not in {"pass", "fail", "partial", "blocked", "not_run", + "skipped_not_applicable"}): + raise DefenseError("invalid validation status") + _safe_string(value["summary"], "validation summary", 1, 512) + if _secret_string(value["summary"]): + raise DefenseError("validation summary contains secret-looking text") + if "evidence" in value: + evidence = value["evidence"] + if not isinstance(evidence, list) or len(evidence) > 128: + raise DefenseError("invalid validation evidence") + for reference in evidence: + _relative_posix(reference, "evidence reference") + if "attributes" in value: + _validate_safe_attributes(value["attributes"]) + return value + + +def _parse_events_bytes(raw, suffix): + events = [] + if suffix == ".jsonl": + for line_number, line in enumerate(raw.splitlines(), 1): + if not line.strip(): + continue + if len(line) > MAX_EVENT_LINE: + raise DefenseError("event line exceeds limit") + try: + event = json.loads(line.decode("utf-8"), object_pairs_hook=_unique_object, + parse_constant=_reject_constant) + except (UnicodeError, json.JSONDecodeError, RecursionError) as exc: + raise DefenseError("invalid JSONL event") from exc + events.append(_validate_event(event)) + if len(events) > MAX_EVENTS: + raise DefenseError("event count exceeds limit") + elif suffix == ".json": + try: + value = json.loads(raw.decode("utf-8-sig"), object_pairs_hook=_unique_object, + parse_constant=_reject_constant) + except (UnicodeError, json.JSONDecodeError, RecursionError) as exc: + raise DefenseError("invalid JSON event") from exc + values = value if isinstance(value, list) else [value] + if len(values) > MAX_EVENTS: + raise DefenseError("event count exceeds limit") + events.extend(_validate_event(item) for item in values) + else: + raise DefenseError("events must be .json or .jsonl") + return events + + +def _read_events(path): + raw = _read_regular_bytes(path, MAX_JSON_BYTES) + return _parse_events_bytes(raw, Path(path).suffix.lower()) + + +def command_timeline(args): + events = [] + total_bytes = 0 + for path in args.events: + try: + size = Path(path).lstat().st_size + except OSError as exc: + raise DefenseError("event input unavailable") from exc + total_bytes += size + if total_bytes > MAX_JSON_BYTES: + raise DefenseError("combined events exceed byte limit") + events.extend(_read_events(path)) + if len(events) > MAX_EVENTS: + raise DefenseError("event count exceeds limit") + if not events: + raise DefenseError("timeline has no events") + identifiers = set() + for event in events: + if "id" in event: + if event["id"] in identifiers: + raise DefenseError("duplicate event id") + identifiers.add(event["id"]) + events.sort(key=lambda value: (_parse_timestamp(value["timestamp"]), value["source"], + value["kind"], value.get("id", ""), value["summary"], + _canonical(value))) + payload = b"".join(_canonical(event) for event in events) + output_path = _atomic_write_new(args.output, payload) + findings = sum(event["severity"] in {"high", "critical"} for event in events) + print(json.dumps({"events": len(events), "exit_code": 1 if findings else 0, + "high_or_critical": findings, + "output": str(output_path)}, sort_keys=True)) + return 1 if findings else 0 + + +def _validate_comparison(value): + fields = {"schema", "tool", "compared_at", "baseline", "current", "profile", "scope", + "comparable", "partial", "reasons", "drift", "summary", "exit_code"} + _strict_keys(value, fields, fields, + "comparison") + if value["schema"] != COMPARISON_SCHEMA or type(value["comparable"]) is not bool or type(value["partial"]) is not bool: + raise DefenseError("invalid comparison schema") + if type(value["exit_code"]) is not int or value["exit_code"] not in {0, 1, 2}: + raise DefenseError("invalid comparison exit code") + _validate_tool_record(value["tool"], "comparison tool") + _parse_timestamp(value["compared_at"]) + _validate_profile_reference(value["profile"], "comparison profile") + for name in ("baseline", "current"): + item = value[name] + _strict_keys(item, {"created_at", "sha256"}, {"created_at", "sha256"}, + name + " comparison input") + _parse_timestamp(item["created_at"]) + if not isinstance(item["sha256"], str) or not re.fullmatch(r"[0-9a-f]{64}", item["sha256"]): + raise DefenseError("invalid comparison input hash") + scope = value["scope"] + _strict_keys(scope, {"baseline_sha256", "current_sha256"}, + {"baseline_sha256", "current_sha256"}, "comparison scope") + if any(not isinstance(scope[key], str) or not re.fullmatch(r"[0-9a-f]{64}", scope[key]) + for key in scope): + raise DefenseError("invalid comparison scope hash") + if (not isinstance(value["drift"], dict) or not isinstance(value["reasons"], list) or + len(value["reasons"]) > 16 or + any(not isinstance(reason, str) for reason in value["reasons"]) or + len(set(value["reasons"])) != len(value["reasons"])): + raise DefenseError("invalid comparison content") + allowed_drift = {"adapters_changed", "files_added", "files_content_changed", + "files_metadata_changed", "files_removed"} + if set(value["drift"]) != allowed_drift: + raise DefenseError("invalid comparison drift") + for name, items in value["drift"].items(): + if (not isinstance(items, list) or len(items) > 100_000 or + any(not isinstance(item, str) for item in items) or + items != sorted(set(items))): + raise DefenseError("invalid comparison drift entries") + if name == "adapters_changed": + if any(item not in ADAPTERS for item in items): + raise DefenseError("invalid comparison adapter drift") + else: + for item in items: + _portable_relative_posix(item, "comparison path") + summary = value["summary"] + summary_fields = {"adapter_changes", "drift_count", "files_added", + "files_content_changed", "files_metadata_changed", "files_removed"} + _strict_keys(summary, summary_fields, summary_fields, "comparison summary") + expected = { + "adapter_changes": len(value["drift"]["adapters_changed"]), + "files_added": len(value["drift"]["files_added"]), + "files_content_changed": len(value["drift"]["files_content_changed"]), + "files_metadata_changed": len(value["drift"]["files_metadata_changed"]), + "files_removed": len(value["drift"]["files_removed"]), + } + expected["drift_count"] = sum(expected.values()) + if any(type(summary[key]) is not int or summary[key] != expected[key] for key in summary_fields): + raise DefenseError("comparison summary is inconsistent") + if value["comparable"] == value["partial"] or value["comparable"] != (not value["reasons"]): + raise DefenseError("comparison compatibility status is inconsistent") + expected_exit = 2 if value["partial"] else 1 if summary["drift_count"] else 0 + if value["exit_code"] != expected_exit: + raise DefenseError("comparison exit code is inconsistent") + return value + + +def _validate_approved_drift(value, comparison, baseline_sha256, current_sha256): + fields = {"schema", "id", "reviewed_at", "baseline_sha256", "current_sha256", "drift"} + _strict_keys(value, fields, fields, "approved drift") + if value["schema"] != APPROVED_DRIFT_SCHEMA: + raise DefenseError("unsupported approved drift schema") + if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._:-]{7,127}", + value["id"] if isinstance(value["id"], str) else ""): + raise DefenseError("invalid approved drift id") + reviewed_at = _parse_timestamp(value["reviewed_at"]) + if reviewed_at < _parse_timestamp(comparison["current"]["created_at"]): + raise DefenseError("approved drift predates current snapshot") + if (value["baseline_sha256"] != baseline_sha256 or + value["current_sha256"] != current_sha256): + raise DefenseError("approved drift is bound to different snapshots") + drift = value["drift"] + if not isinstance(drift, dict) or set(drift) != set(comparison["drift"]): + raise DefenseError("invalid approved drift entries") + normalized = {} + for name, entries in drift.items(): + if (not isinstance(entries, list) or len(entries) > 100_000 or + entries != sorted(set(entries))): + raise DefenseError("invalid approved drift entries") + if name == "adapters_changed": + if any(entry not in ADAPTERS for entry in entries): + raise DefenseError("invalid approved adapter drift") + else: + for entry in entries: + _portable_relative_posix(entry, "approved drift path") + normalized[name] = entries + if normalized != comparison["drift"]: + raise DefenseError("approved drift does not exactly match observed drift") + return value + + +def _reject_evidence_secrets(value): + if isinstance(value, dict): + for key, child in value.items(): + if SECRET_KEY.search(_normalized_key(key)) or _normalized_key(key) in COMMAND_KEYS: + raise DefenseError("evidence contains a forbidden key") + _reject_evidence_secrets(child) + elif isinstance(value, list): + for child in value: + _reject_evidence_secrets(child) + elif isinstance(value, str): + if _secret_string(value) or _secret_filename(Path(value).name): + raise DefenseError("evidence contains secret-looking text") + + +def _validate_scanner_scope(value): + fields = {"schema", "root", "rules_sha256", "exclude", "limits", + "path_semantics", "sha256"} + if isinstance(value, dict) and value.get("schema") == SCANNER_SCOPE_V2: + fields |= {"semantic_revision", "context_sha256"} + _strict_keys(value, fields, fields, "scanner scope") + if (value["schema"] not in {SCANNER_SCOPE_SCHEMA, SCANNER_SCOPE_V2} or + value["path_semantics"] != SCANNER_PATH_SEMANTICS or + not isinstance(value["root"], str) or not OPAQUE_ID.fullmatch(value["root"]) or + not isinstance(value["rules_sha256"], str) or + not re.fullmatch(r"[0-9a-f]{64}", value["rules_sha256"])): + raise DefenseError("invalid scanner scope") + exclude = value["exclude"] + if (not isinstance(exclude, list) or len(exclude) > 10_000 or + exclude != sorted(set(exclude)) or + any(not isinstance(item, str) or not 1 <= len(item) <= 4096 or "\x00" in item + for item in exclude)): + raise DefenseError("invalid scanner scope exclusions") + limits = value["limits"] + _strict_keys(limits, {"max_bytes", "max_files", "max_findings"}, + {"max_bytes", "max_files", "max_findings"}, "scanner scope limits") + for name in ("max_bytes", "max_files", "max_findings"): + _positive_int(limits[name], "scanner " + name, 2 ** 63 - 1) + body = {name: value[name] for name in + ("schema", "root", "rules_sha256", "exclude", "limits", "path_semantics")} + if value["schema"] == SCANNER_SCOPE_V2: + if (value["semantic_revision"] not in {"bounded-source-signals.v2", "bounded-source-signals.v3"} or + not isinstance(value["context_sha256"], str) or + not re.fullmatch(r"[0-9a-f]{64}", value["context_sha256"])): + raise DefenseError("invalid scanner context semantics") + body.update({name: value[name] for name in ("semantic_revision", "context_sha256")}) + expected = _sha256_bytes(json.dumps(body, ensure_ascii=True, sort_keys=True, + separators=(",", ":"), allow_nan=False).encode("utf-8")) + if value["sha256"] != expected: + raise DefenseError("invalid scanner scope digest") + return {**body, "sha256": expected} + + +def _sanitize_scanner_report(value): + if (not isinstance(value, dict) or value.get("tool") != "DurkaHelper defense_scan" or + value.get("offline") is not True or type(value.get("partial")) is not bool or + type(value.get("exit_code")) is not int or value.get("exit_code") not in {0, 1, 2}): + raise DefenseError("invalid scanner report") + version = value.get("version") + if not isinstance(version, str) or not re.fullmatch(r"[0-9][0-9A-Za-z.+-]{0,63}", version): + raise DefenseError("invalid scanner version") + findings = value.get("findings") + issues = value.get("issues") + if (not isinstance(findings, list) or not isinstance(issues, list) or + len(findings) > 100_000 or len(issues) > 100_000): + raise DefenseError("invalid scanner report") + expected_exit_code = 2 if issues else 1 if findings else 0 + if (value["partial"] != bool(issues) or + value["exit_code"] != expected_exit_code): + raise DefenseError("inconsistent scanner report status") + created_at = value.get("created_at") + scope = value.get("scope") + if (created_at is None) != (scope is None): + raise DefenseError("incomplete scanner scope metadata") + if created_at is not None: + _parse_timestamp(created_at) + scope = _validate_scanner_scope(scope) + safe_findings = [] + for item in findings: + if not isinstance(item, dict): + raise DefenseError("invalid scanner finding") + path, line, rule = item.get("path"), item.get("line"), item.get("rule") + _relative_posix(path, "scanner finding path") + if (type(line) is not int or line < 1 or not isinstance(rule, str) or len(rule) > 100 or + not re.fullmatch(r"[A-Z][A-Z0-9]*(?:-[A-Z0-9]+)+", rule)): + raise DefenseError("invalid scanner finding") + safe_findings.append({"line": line, "path": path, "rule": rule}) + safe_issues = [] + for item in issues: + if not isinstance(item, dict) or not isinstance(item.get("path"), str) or not isinstance(item.get("reason"), str): + raise DefenseError("invalid scanner issue") + _relative_posix(item["path"], "scanner issue path", allow_dot=True) + _safe_string(item["reason"], "scanner issue reason", 1, 120) + safe_issues.append({"path": item["path"], "reason": item["reason"]}) + return {"exit_code": value["exit_code"], "findings": sorted(safe_findings, + key=lambda item: (item["path"], item["line"], item["rule"])), + "issues": sorted(safe_issues, key=lambda item: (item["path"], item["reason"])), + "offline": True, "partial": value["partial"], "tool": value["tool"], + "version": version, "created_at": created_at, "scope": scope} + + +def _hashed_record_groups(records): + counts = Counter(_sha256_bytes(_canonical(record)) for record in records) + return [{"count": count, "record_sha256": digest} + for digest, count in sorted(counts.items())] + + +def _safe_adapter_evidence(name, value): + if value is None: + return {"available": False, "records": 0} + if name == "platform": + return {"available": True, **{key: value[key] for key in + ("machine", "python", "release", "system") if key in value}} + if name == "compose": + return { + "available": True, + "config_files": [ + {"content_sha256": item["sha256"], + "path_sha256": _opaque_text_identifier(item["path"]), + "size": item["size"]} + for item in value["config_files"] + ], + "project_sha256": value["project_sha256"], + "service_groups": _hashed_record_groups(value["services"]), + "services": len(value["services"]), + } + semantic = _semantic_adapter(name, value) + return {"available": True, "groups": _hashed_record_groups(semantic), + "records": len(value)} + + +def _safe_snapshot_evidence(value): + snapshot, _indexed = _validate_snapshot(value) + issue_counts = Counter((item["component"], item["reason"]) for item in snapshot["issues"]) + return { + "adapters": {name: _safe_adapter_evidence(name, snapshot["adapters"][name]) + for name in sorted(snapshot["adapters"])}, + "created_at": snapshot["created_at"], + "files": [{"content_sha256": item["sha256"], + "path_sha256": _opaque_text_identifier(item["path"]), + "size": item["size"]} for item in snapshot["files"]], + "issues": [{"component": component, "count": count, "reason": reason} + for (component, reason), count in sorted(issue_counts.items())], + "partial": snapshot["partial"], + "profile_sha256": snapshot["profile"]["sha256"], + "root": snapshot["root"], + "schema": "durkahelper.snapshot-evidence.safe.v1", + "scope_sha256": snapshot["scope"]["sha256"], + "summary": dict(snapshot["summary"]), + "tool": dict(snapshot["tool"]), + } + + +def _safe_comparison_evidence(value): + comparison = _validate_comparison(value) + drift = {"adapters_changed": list(comparison["drift"]["adapters_changed"])} + for name in ("files_added", "files_content_changed", "files_metadata_changed", "files_removed"): + drift[name] = [_opaque_text_identifier(path) for path in comparison["drift"][name]] + return { + "baseline": dict(comparison["baseline"]), + "comparable": comparison["comparable"], + "compared_at": comparison["compared_at"], + "current": dict(comparison["current"]), + "drift": drift, + "exit_code": comparison["exit_code"], + "partial": comparison["partial"], + "profile_sha256": comparison["profile"]["sha256"], + "reasons": list(comparison["reasons"]), + "schema": "durkahelper.comparison-evidence.safe.v1", + "scope": dict(comparison["scope"]), + "summary": dict(comparison["summary"]), + "tool": dict(comparison["tool"]), + } + + +def _safe_backup_evidence(value): + manifest = _validate_backup_manifest(value) + return { + "bundle_sha256": manifest["bundle_sha256"], + "created_at": manifest["created_at"], + "entries": [{"content_sha256": entry["sha256"], "kind": entry["kind"], + "safe_mode": _safe_restore_mode(entry["mode"]), "size": entry["size"], + "source_sha256": _opaque_text_identifier(entry["source"])} + for entry in manifest["entries"]], + "profile_sha256": manifest["profile"]["sha256"], + "root": manifest["root"], + "schema": "durkahelper.backup-evidence.safe.v1", + "summary": dict(manifest["summary"]), + "tool": dict(manifest["tool"]), + } + + +def _sanitize_operation_result(value): + command = value.get("command") if isinstance(value, dict) else None + if command == "health": + allowed = {"checked_at", "command", "exit_code", "profile", "results", "summary", "tool"} + if (set(value) != allowed or type(value.get("exit_code")) is not int or + value["exit_code"] not in {0, 1} or not isinstance(value.get("results"), list)): + raise DefenseError("invalid health result") + _parse_timestamp(value["checked_at"]) + _validate_tool_record(value["tool"], "health result tool") + _validate_profile_reference(value["profile"], "health result profile") + results = [] + for item in value["results"]: + if not isinstance(item, dict) or set(item) - {"name", "ok", "status", "ms", "error"}: + raise DefenseError("invalid health result") + if (not isinstance(item.get("name"), str) or type(item.get("ok")) is not bool or + item.get("status") is not None and type(item.get("status")) is not int or + type(item.get("ms")) is not int): + raise DefenseError("invalid health result") + if item.get("status") is not None and not 100 <= item["status"] <= 599: + raise DefenseError("invalid health status result") + if item["ms"] < 0 or item["ms"] > 3_600_000: + raise DefenseError("invalid health duration") + error = item.get("error") + if error is not None: + _safe_string(error, "health error", 1, 120) + results.append({"error": error, "ms": item["ms"], + "name_sha256": _opaque_text_identifier(item["name"]), + "ok": item["ok"], "status": item.get("status")}) + summary = value["summary"] + _strict_keys(summary, {"failed", "total"}, {"failed", "total"}, "health summary") + if (type(summary["failed"]) is not int or type(summary["total"]) is not int or + summary["total"] != len(results) or + summary["failed"] != sum(not item["ok"] for item in results)): + raise DefenseError("inconsistent health summary") + if value["exit_code"] != (1 if summary["failed"] else 0): + raise DefenseError("inconsistent health exit code") + return {"checked_at": value["checked_at"], "operation": command, + "exit_code": value["exit_code"], "profile_sha256": value["profile"]["sha256"], + "results": results, "schema": "durkahelper.operation-result.safe.v1", + "summary": dict(summary), "tool": dict(value["tool"])} + if command == "preflight": + allowed = {"checks", "command", "exit_code", "partial", "platform", "profile", "tool"} + if (set(value) != allowed or not isinstance(value.get("checks"), list) or + type(value.get("partial")) is not bool or + type(value.get("exit_code")) is not int or value["exit_code"] not in {0, 2}): + raise DefenseError("invalid preflight result") + _validate_tool_record(value["tool"], "preflight result tool") + _validate_profile_reference(value["profile"], "preflight result profile") + _validate_adapter_value("platform", value["platform"]) + checks = [] + for item in value["checks"]: + if (not isinstance(item, dict) or set(item) != {"name", "ok", "reason"} or + not isinstance(item["name"], str) or type(item["ok"]) is not bool or + item["reason"] is not None and not isinstance(item["reason"], str)): + raise DefenseError("invalid preflight result") + if item["reason"] is not None: + _safe_string(item["reason"], "preflight reason", 1, 120) + checks.append({"name_sha256": _opaque_text_identifier(item["name"]), + "ok": item["ok"], "reason": item["reason"]}) + if value["partial"] != any(not item["ok"] for item in checks): + raise DefenseError("inconsistent preflight result") + if value["exit_code"] != (2 if value["partial"] else 0): + raise DefenseError("inconsistent preflight exit code") + return {"checks": checks, "operation": command, "exit_code": value["exit_code"], + "partial": value["partial"], "platform": dict(value["platform"]), + "profile_sha256": value["profile"]["sha256"], + "schema": "durkahelper.operation-result.safe.v1", "tool": dict(value["tool"])} + if command == "restore-stage": + allowed = {"approval_id", "apply_required", "backup", "command", "exit_code", "files", + "problems", "status", "target", "tool"} + if (set(value) - allowed or not {"command", "exit_code", "status", "tool"} <= set(value) or + type(value["exit_code"]) is not int or value["exit_code"] not in {0, 1} or + not isinstance(value["status"], str) or + value["status"] not in {"backup_verification_failed", "safe_to_stage", "staged"}): + raise DefenseError("invalid restore-stage result") + _validate_tool_record(value["tool"], "restore result tool") + files = value.get("files", 0) + if type(files) is not int or not 0 <= files <= 100_000: + raise DefenseError("invalid restore result file count") + problems = value.get("problems", []) + if not isinstance(problems, list) or len(problems) > 100_000: + raise DefenseError("invalid restore problems") + reasons = Counter() + for item in problems: + if not isinstance(item, dict) or not isinstance(item.get("reason"), str): + raise DefenseError("invalid restore problem") + _safe_string(item["reason"], "restore problem reason", 1, 120) + reasons[item["reason"]] += 1 + expected_exit = 1 if value["status"] == "backup_verification_failed" else 0 + if value["exit_code"] != expected_exit: + raise DefenseError("inconsistent restore result") + return {"exit_code": value["exit_code"], "files": files, "operation": command, + "problem_summary": [{"count": count, "reason": reason} + for reason, count in sorted(reasons.items())], + "schema": "durkahelper.operation-result.safe.v1", "status": value["status"], + "tool": dict(value["tool"])} + raise DefenseError("unrecognized operation result") + + +def _normalize_evidence_file(path, max_bytes): + path = Path(path) + lowered_name = path.name.lower() + if (path.suffix.lower() not in SAFE_EVIDENCE_EXTENSIONS or + any(marker in lowered_name for marker in (".pcap", ".pcapng", ".log", "neo-info", + "neo_info", "compose-config", "compose_config"))): + raise DefenseError("raw traffic, logs, Neo info, and Compose expansion are not evidence inputs") + raw = _read_regular_bytes(path, max_bytes) + if path.suffix.lower() == ".jsonl": + events = _parse_events_bytes(raw, ".jsonl") + normalized = b"".join(_canonical(event) for event in events) + return normalized, EVENT_SCHEMA, len(events) + try: + value = json.loads(raw.decode("utf-8-sig"), object_pairs_hook=_unique_object, + parse_constant=_reject_constant) + except (UnicodeError, json.JSONDecodeError, RecursionError) as exc: + raise DefenseError("invalid structured evidence") from exc + if not isinstance(value, dict): + raise DefenseError("evidence JSON must be an object") + schema = value.get("schema") + if schema == SNAPSHOT_SCHEMA: + normalized_value = _safe_snapshot_evidence(value) + elif schema == COMPARISON_SCHEMA: + normalized_value = _safe_comparison_evidence(value) + elif schema == BACKUP_SCHEMA: + if (path.parent / ".INCOMPLETE").exists(): + raise DefenseError("backup publication is incomplete") + normalized_value = _safe_backup_evidence(value) + elif schema == EVENT_SCHEMA: + normalized_value = _validate_event(value) + elif schema == VALIDATION_SCHEMA: + normalized_value = _validate_validation_record(value) + elif schema == DEPLOYMENT_AUDIT_SCHEMA: + normalized_value = _validate_deployment_audit_report(value) + elif value.get("tool") == "DurkaHelper defense_scan": + normalized_value = _sanitize_scanner_report(value) + schema = "durkahelper.scanner-report.safe.v1" + elif (isinstance(value.get("command"), str) and + value.get("command") in {"health", "preflight", "restore-stage"}): + normalized_value = _sanitize_operation_result(value) + schema = "durkahelper.operation-result.safe.v1" + else: + raise DefenseError("unrecognized evidence schema") + _reject_evidence_secrets(normalized_value) + return _canonical(normalized_value), schema, 1 + + +def command_evidence(args): + profile_data = load_profile(args.profile) + settings = profile_data.get("evidence", {}) + allowed = settings.get("allow_extensions", list(SAFE_EVIDENCE_EXTENSIONS)) + max_files = settings.get("max_files", 128) + max_file_bytes = settings.get("max_file_bytes", 16 * 1024 * 1024) + max_total_bytes = settings.get("max_total_bytes", 256 * 1024 * 1024) + if not 1 <= len(args.input) <= max_files: + raise DefenseError("invalid evidence input count") + target = _safe_output_parent(Path(args.output)) + normalized = [] + total = 0 + for path_text in args.input: + path = Path(path_text) + if path.suffix.lower() not in allowed: + raise DefenseError("evidence extension is not allowed by the profile") + payload, schema, records = _normalize_evidence_file(path, max_file_bytes) + total += len(payload) + if total > max_total_bytes: + raise DefenseError("evidence total byte limit reached") + normalized.append((payload, schema, records, path.suffix.lower())) + normalized.sort(key=lambda item: (item[1], item[3], _sha256_bytes(item[0]), item[0])) + staging = _StagingDirectory.create(target, ".defense-evidence-") + try: + manifest_entries = [] + for number, (payload, schema, records, suffix) in enumerate(normalized, 1): + name = f"artifact-{number:03d}{suffix}" + staging.write_new_bytes(name, payload) + manifest_entries.append({"artifact": name, "records": records, "schema": schema, + "sha256": _sha256_bytes(payload), "size": len(payload)}) + manifest = {"created_at": _now(), "format": 1, "kind": "sanitized-evidence-bundle", + "artifacts": manifest_entries, + "profile": {"name_sha256": _opaque_text_identifier(profile_data["name"]), + "sha256": _profile_hash(profile_data)}, + "tool": _tool_record()} + manifest_payload = _bounded_canonical(manifest, MAX_JSON_BYTES, "evidence manifest") + staging.write_new_bytes("manifest.json", manifest_payload) + _publish_directory(staging, target) + finally: + staging.cleanup() + print(json.dumps({"artifacts": len(normalized), "evidence": str(target), "exit_code": 0, + "total_bytes": total}, sort_keys=True)) + return 0 + + +def _deployment_list(value, field, maximum=128): + if not isinstance(value, list) or len(value) > maximum: + raise DefenseError("invalid deployment " + field) + return value + + +def _deployment_enum(value, choices, field): + if not isinstance(value, str) or value not in choices: + raise DefenseError("invalid deployment " + field) + + +def _deployment_id(value): + if not isinstance(value, str) or not IDENTIFIER.fullmatch(value): + raise DefenseError("invalid deployment identifier") + + +def _deployment_ip(value): + if not isinstance(value, str) or "%" in value: + raise DefenseError("deployment bindings require literal IP addresses") + try: + parsed = ipaddress.ip_address(value) + except ValueError as exc: + raise DefenseError("deployment bindings require literal IP addresses") from exc + spellings = {str(parsed)} + if parsed.version == 6 and parsed.ipv4_mapped is not None: + # Python 3.14 changed IPv4-mapped IPv6 rendering to dotted decimal. + # Accept both stable compressed spellings, not arbitrary textual aliases. + mapped = int(parsed.ipv4_mapped) + spellings.update({"::ffff:" + str(parsed.ipv4_mapped), + "::ffff:" + format(mapped >> 16, "x") + ":" + format(mapped & 65535, "x")}) + if value not in spellings or parsed.is_multicast: + raise DefenseError("invalid deployment bind address") + return parsed + + +def _deployment_port(value, *, publication=False): + fields = {"host_port", "container_port", "protocol", "service" if publication else "host_ip"} + _strict_keys(value, fields, fields, "deployment publication") + for field in ("host_port", "container_port"): + _positive_int(value[field], "deployment port", 65535) + _deployment_enum(value["protocol"], {"tcp", "udp"}, "protocol") + if publication: + _deployment_id(value["service"]) + else: + _deployment_ip(value["host_ip"]) + + +def _deployment_image(value): + # References, not URLs or command lines. Never echo an untrusted value. + if (not isinstance(value, str) or len(value) > 256 or "://" in value or + not re.fullmatch(r"[a-z0-9][a-z0-9._/:@-]*", value)): + raise DefenseError("invalid deployment image reference") + + +def _validate_deployment_inputs(model, policy): + model_fields = {"schema", "source_sha256", "platform", "services"} + _strict_keys(model, model_fields, model_fields, "deployment model") + if (model["schema"] != DEPLOYMENT_MODEL_SCHEMA or + not isinstance(model["source_sha256"], str) or + not re.fullmatch(r"[0-9a-f]{64}", model["source_sha256"])): + raise DefenseError("invalid deployment model schema or provenance") + _strict_keys(model["platform"], {"os", "architecture", "runtime"}, + {"os", "architecture", "runtime"}, "deployment platform") + _deployment_enum(model["platform"]["os"], {"linux", "darwin"}, "OS") + _deployment_enum(model["platform"]["architecture"], {"amd64", "arm64"}, "architecture") + _deployment_enum(model["platform"]["runtime"], {"docker-engine", "docker-desktop"}, "runtime") + services = _deployment_list(model["services"], "services", 64) + if not services: + raise DefenseError("deployment model must describe services") + service_fields = {"id", "role", "image", "architectures", "mode", "ports", "mounts", + "privileged", "network_mode", "capabilities", "nonroot", "healthcheck", + "memory_limit_mb", "cpu_limit", "restart"} + identifiers = set() + for service in services: + _strict_keys(service, service_fields, service_fields, "deployment service") + _deployment_id(service["id"]) + if service["id"] in identifiers: + raise DefenseError("duplicate deployment service") + identifiers.add(service["id"]) + _deployment_enum(service["role"], {"ui", "api", "backend", "worker", "capture"}, "role") + _deployment_image(service["image"]) + arches = _deployment_list(service["architectures"], "architectures", 2) + for architecture in arches: + _deployment_enum(architecture, {"amd64", "arm64"}, "image architecture") + if len(set(arches)) != len(arches): + raise DefenseError("duplicate deployment architecture") + _deployment_enum(service["mode"], {"none", "file", "live"}, "mode") + _deployment_enum(service["network_mode"], {"bridge", "host", "none"}, "network mode") + _deployment_enum(service["restart"], {"no", "always", "on-failure", "unless-stopped"}, "restart") + for field in ("privileged", "healthcheck"): + if type(service[field]) is not bool: + raise DefenseError("invalid deployment boolean") + if service["nonroot"] is not None and type(service["nonroot"]) is not bool: + raise DefenseError("invalid deployment nonroot evidence") + if service["memory_limit_mb"] is not None: + _positive_int(service["memory_limit_mb"], "deployment memory", 1048576) + cpu = service["cpu_limit"] + if cpu is not None and (type(cpu) not in {int, float} or not math.isfinite(cpu) or not 0 < cpu <= 1024): + raise DefenseError("invalid deployment CPU limit") + for port in _deployment_list(service["ports"], "ports"): + _deployment_port(port) + capabilities = _deployment_list(service["capabilities"], "capabilities", 64) + for capability in capabilities: + if not isinstance(capability, str) or not re.fullmatch(r"(?:CAP_)?[A-Z][A-Z0-9_]{0,63}", capability): + raise DefenseError("invalid deployment capability") + for mount in _deployment_list(service["mounts"], "mounts", 64): + fields = {"kind", "target", "source_scope", "read_only"} + _strict_keys(mount, fields, fields, "deployment mount") + _deployment_enum(mount["kind"], {"bind", "volume", "tmpfs"}, "mount kind") + _deployment_enum(mount["source_scope"], {"approved-data", "approved-config", "outside", "socket", "host-root", "unknown"}, "mount scope") + target = mount["target"] + if (not isinstance(target, str) or not target.startswith("/") or len(target) > 1024 or + "\\" in target or any(ord(c) < 32 for c in target) or + str(PurePosixPath(target)) != target or ".." in PurePosixPath(target).parts): + raise DefenseError("invalid deployment mount target") + if type(mount["read_only"]) is not bool: + raise DefenseError("invalid deployment mount access") + policy_fields = {"schema", "team_lan", "approved_bind_addresses", "approved_publications", + "approved_images", "require_healthcheck", "require_resource_limits", + "require_nonroot", "require_restart", "allow_amd64_emulation", "approved_live_capture"} + _strict_keys(policy, policy_fields, policy_fields, "deployment policy") + if policy["schema"] != DEPLOYMENT_POLICY_SCHEMA: + raise DefenseError("invalid deployment policy schema") + for field in ("team_lan", "require_healthcheck", "require_resource_limits", "require_nonroot", + "require_restart", "allow_amd64_emulation"): + if type(policy[field]) is not bool: + raise DefenseError("invalid deployment policy boolean") + for address in _deployment_list(policy["approved_bind_addresses"], "approved addresses"): + _deployment_ip(address) + for port in _deployment_list(policy["approved_publications"], "approved publications"): + _deployment_port(port, publication=True) + if port["service"] not in identifiers: + raise DefenseError("policy refers to an unknown service") + for reference in _deployment_list(policy["approved_images"], "approved images"): + _deployment_image(reference) + if not re.search(r"(?:@|^)sha256:[0-9a-f]{64}$", reference): + raise DefenseError("approved images must use immutable digests") + for identifier in _deployment_list(policy["approved_live_capture"], "approved capture"): + _deployment_id(identifier) + if identifier not in identifiers: + raise DefenseError("capture approval refers to an unknown service") + return model, policy + + +def deployment_audit(model, policy, *, checked_at=None): + """Audit declared metadata only. This does not inspect a running daemon.""" + _validate_deployment_inputs(model, policy) + findings, issues = [], [] + arch = model["platform"]["architecture"] + approved_ports = {(p["service"], p["host_port"], p["container_port"], p["protocol"]) + for p in policy["approved_publications"]} + observed_ports = set() + bind_groups = {} + + def add(destination, identifier, check, kind="deployment"): + destination.append({"service_sha256": _sha256_bytes(identifier.encode("utf-8")), + "check": check, "kind": kind}) + + for service in model["services"]: + sid = service["id"] + emit = lambda check, kind="deployment": add(findings, sid, check, kind) + unknown = lambda check: add(issues, sid, check, "coverage") + if not re.search(r"(?:@|^)sha256:[0-9a-f]{64}$", service["image"]): + emit("image_unpinned") + elif service["image"] not in policy["approved_images"]: + emit("image_lock_mismatch") + if not service["architectures"]: + unknown("image_architecture_unknown") + elif arch not in service["architectures"]: + if not (arch == "arm64" and "amd64" in service["architectures"] and policy["allow_amd64_emulation"]): + emit("image_architecture_incompatible") + else: + # Permission to emulate is not evidence that it works. + unknown("emulation_runtime_unverified") + for port in service["ports"]: + key = (sid, port["host_port"], port["container_port"], port["protocol"]) + observed_ports.add(key) + if service["role"] in {"backend", "worker"}: + emit("internal_service_published", "security") + if key not in approved_ports: + emit("publication_unapproved", "security") + address = _deployment_ip(port["host_ip"]) + # Normalize IPv4-mapped IPv6 aliases for conservative collision + # detection. Only declarations are checked; no local socket probe. + address = getattr(address, "ipv4_mapped", None) or address + bindings = bind_groups.setdefault((port["host_port"], port["protocol"]), {}) + bindings.setdefault(address, set()).add((sid, port["container_port"])) + if port["host_ip"] not in policy["approved_bind_addresses"] or address.is_unspecified: + emit("bind_unapproved_or_wildcard", "security") + if policy["team_lan"] and address.is_loopback: + emit("team_ui_loopback_only", "availability") + if service["ports"] and service["network_mode"] in {"none", "host"}: + # Host mode ignores/rejects port mapping; none has no container + # network endpoint to forward to. Neither fulfills this model. + emit("publication_network_mode_incompatible", "availability") + if service["privileged"]: + emit("privileged_container", "security") + live_allowed = (service["mode"] == "live" and sid in policy["approved_live_capture"] and + model["platform"]["os"] == "linux" and model["platform"]["runtime"] == "docker-engine") + if service["mode"] == "live" and not live_allowed: + emit("live_capture_not_approved", "security") + if live_allowed: + unknown("live_capture_visibility_requires_runtime_test") + if service["network_mode"] == "host": + if live_allowed: + unknown("host_namespace_requires_runtime_boundary_test") + else: + emit("host_network_unapproved", "security") + for capability in service["capabilities"]: + normalized = capability.removeprefix("CAP_") + if not (live_allowed and normalized == "NET_RAW"): + emit("capability_not_minimal", "security") + for mount in service["mounts"]: + scope = mount["source_scope"] + if scope in {"socket", "host-root"} or mount["target"] in {"/", "/var/run/docker.sock", "/run/docker.sock"}: + emit("sensitive_host_mount", "security") + elif scope == "unknown": + unknown("mount_scope_unknown") + elif scope == "outside" or (scope == "approved-config" and not mount["read_only"]): + emit("mount_outside_policy", "security") + if policy["require_nonroot"] and service["nonroot"] is not True: + if service["nonroot"] is None: + unknown("service_user_unknown") + else: + emit("service_runs_as_root", "security") + if policy["require_healthcheck"] and not service["healthcheck"]: + emit("healthcheck_missing", "availability") + if policy["require_resource_limits"] and (service["memory_limit_mb"] is None or service["cpu_limit"] is None): + emit("resource_limits_missing", "availability") + if policy["require_restart"] and service["restart"] == "no": + emit("restart_policy_missing", "availability") + for addresses in bind_groups.values(): + if any(address.is_unspecified for address in addresses): + # Wildcard listeners may overlap either IP family on dual-stack + # systems. Fail closed instead of assuming IPV6_V6ONLY behavior. + owners = {owner for bindings in addresses.values() for owner in bindings} + overlapping = sum(len(bindings) for bindings in addresses.values()) > 1 + collisions = {sid for sid, _target in owners} if overlapping else set() + else: + collisions = {sid for bindings in addresses.values() if len(bindings) > 1 + for sid, _target in bindings} + for sid in collisions: + add(findings, sid, "publication_bind_conflict", "availability") + for sid, _host, _container, _protocol in approved_ports - observed_ports: + add(findings, sid, "required_publication_missing", "availability") + unique = lambda rows: [dict(zip(("service_sha256", "check", "kind"), row)) + for row in sorted({(r["service_sha256"], r["check"], r["kind"]) for r in rows})] + checked_at = checked_at or _now() + _parse_timestamp(checked_at) + findings, issues = unique(findings), unique(issues) + return {"schema": DEPLOYMENT_AUDIT_SCHEMA, "checked_at": checked_at, + "scope": "declared-model-only", "model_sha256": _sha256_bytes(_canonical(model)), + "policy_sha256": _sha256_bytes(_canonical(policy)), "source_sha256": model["source_sha256"], + "services": len(model["services"]), "findings": findings, "issues": issues, + "status": "partial" if issues else "fail" if findings else "pass", + "exit_code": 2 if issues else 1 if findings else 0} + + +def command_audit_deployment(args): + model, _ = _read_json(args.model, MAX_PROFILE_BYTES) + policy, _ = _read_json(args.policy, MAX_PROFILE_BYTES) + result = deployment_audit(model, policy) + print(_canonical(result).decode("utf-8"), end="") + return result["exit_code"] + + +def _validate_deployment_audit_report(value): + fields = {"schema", "checked_at", "scope", "model_sha256", "policy_sha256", "source_sha256", + "services", "findings", "issues", "status", "exit_code"} + _strict_keys(value, fields, fields, "deployment audit") + if value["schema"] != DEPLOYMENT_AUDIT_SCHEMA or value["scope"] != "declared-model-only": + raise DefenseError("invalid deployment audit scope") + _parse_timestamp(value["checked_at"]) + for field in ("model_sha256", "policy_sha256", "source_sha256"): + if not isinstance(value[field], str) or not re.fullmatch(r"[0-9a-f]{64}", value[field]): + raise DefenseError("invalid deployment audit digest") + _positive_int(value["services"], "deployment service count", 64) + checks = {"image_unpinned", "image_lock_mismatch", "image_architecture_unknown", + "image_architecture_incompatible", "emulation_runtime_unverified", "internal_service_published", + "publication_unapproved", "bind_unapproved_or_wildcard", "team_ui_loopback_only", + "privileged_container", "live_capture_not_approved", "live_capture_visibility_requires_runtime_test", + "host_namespace_requires_runtime_boundary_test", "host_network_unapproved", "capability_not_minimal", + "sensitive_host_mount", "mount_scope_unknown", "mount_outside_policy", "service_user_unknown", + "service_runs_as_root", "healthcheck_missing", "resource_limits_missing", "restart_policy_missing", + "required_publication_missing", "publication_bind_conflict", "publication_network_mode_incompatible"} + for field in ("findings", "issues"): + for row in _deployment_list(value[field], "audit entries", 4096): + _strict_keys(row, {"service_sha256", "check", "kind"}, {"service_sha256", "check", "kind"}, "audit entry") + if not isinstance(row["service_sha256"], str) or not re.fullmatch(r"[0-9a-f]{64}", row["service_sha256"]): + raise DefenseError("invalid audit service digest") + _deployment_enum(row["check"], checks, "audit check") + _deployment_enum(row["kind"], {"coverage"} if field == "issues" else {"deployment", "security", "availability"}, "audit kind") + expected = ("partial", 2) if value["issues"] else ("fail", 1) if value["findings"] else ("pass", 0) + if type(value["exit_code"]) is not int or (value["status"], value["exit_code"]) != expected: + raise DefenseError("inconsistent deployment audit status") + return value + + +def _scanner_index(path): + data, raw = _read_json(path) + safe = _sanitize_scanner_report(data) + indexed = {(item["path"], item["line"], item["rule"]) for item in safe["findings"]} + return safe, indexed, _sha256_bytes(raw) + + +def command_patch_check(args): + before, before_raw = _read_json(args.before) + after, after_raw = _read_json(args.after) + before_sha256 = _sha256_bytes(before_raw) + after_sha256 = _sha256_bytes(after_raw) + comparison = _snapshot_comparison(before, after, before_sha256, after_sha256) + before_created = _parse_timestamp(comparison["baseline"]["created_at"]) + after_created = _parse_timestamp(comparison["current"]["created_at"]) + partial_reasons = list(comparison["reasons"]) + fail_reasons = [] + scanner_new = 0 + before_scanner_sha256 = None + after_scanner_sha256 = None + after_scanner_created = None + if bool(args.before_scanner) != bool(args.after_scanner): + raise DefenseError("both scanner reports are required together") + if not args.before_scanner: + partial_reasons.append("scanner_evidence_missing") + else: + old_report, old, before_scanner_sha256 = _scanner_index(args.before_scanner) + new_report, new, after_scanner_sha256 = _scanner_index(args.after_scanner) + if old_report["partial"] or old_report["exit_code"] == 2: + partial_reasons.append("before_scanner_partial") + if new_report["partial"] or new_report["exit_code"] == 2: + partial_reasons.append("after_scanner_partial") + if old_report.get("version") != new_report.get("version"): + partial_reasons.append("scanner_version_changed") + if old_report.get("scope") is None or new_report.get("scope") is None: + partial_reasons.append("scanner_scope_unverified") + elif old_report.get("scope") != new_report.get("scope"): + partial_reasons.append("scanner_scope_changed") + elif (old_report["scope"]["root"] != before["root"] or + new_report["scope"]["root"] != after["root"]): + partial_reasons.append("scanner_root_unbound") + if old_report.get("created_at") is None or new_report.get("created_at") is None: + partial_reasons.append("scanner_time_unverified") + else: + old_scanner_created = _parse_timestamp(old_report["created_at"]) + after_scanner_created = _parse_timestamp(new_report["created_at"]) + if old_scanner_created < before_created or old_scanner_created > after_created: + partial_reasons.append("before_scanner_time_unbound") + if after_scanner_created < after_created: + partial_reasons.append("after_scanner_time_unbound") + scanner_new = len(new - old) + if scanner_new: + fail_reasons.append("new_scanner_findings") + health_failures = 0 + health_sha256 = None + health_checked = None + if not args.health_result: + partial_reasons.append("health_evidence_missing") + else: + health_data, health_raw = _read_json(args.health_result, MAX_PROFILE_BYTES) + health_sha256 = _sha256_bytes(health_raw) + health = _sanitize_operation_result(health_data) + if health.get("operation") != "health": + raise DefenseError("patch health evidence must be a health result") + health_checked = _parse_timestamp(health["checked_at"]) + if health["profile_sha256"] != after["profile"]["sha256"]: + partial_reasons.append("health_profile_unbound") + if health_checked < after_created: + partial_reasons.append("health_time_unbound") + health_failures = health["summary"]["failed"] + if health_failures: + fail_reasons.append("health_failure") + validation_failures = 0 + validation_partial = 0 + validation_passes = 0 + validation_not_run = 0 + validation_skipped = 0 + validation_run_ids = set() + validation_hashes = [] + deployment_bindings = {} + audit_checked = None + deployment_paths = [getattr(args, name, None) for name in + ("deployment_audit", "deployment_model", "deployment_policy")] + if any(deployment_paths): + if not all(deployment_paths): + raise DefenseError("deployment audit requires its model and policy") + audit, audit_raw = _read_json(deployment_paths[0], MAX_PROFILE_BYTES) + model, _ = _read_json(deployment_paths[1], MAX_PROFILE_BYTES) + policy, _ = _read_json(deployment_paths[2], MAX_PROFILE_BYTES) + _validate_deployment_audit_report(audit) + expected = deployment_audit(model, policy, checked_at=audit["checked_at"]) + if audit != expected: + raise DefenseError("deployment audit does not match its model and policy") + deployment_bindings = {"deployment_audit_sha256": _sha256_bytes(audit_raw), + "deployment_model_sha256": audit["model_sha256"], + "deployment_policy_sha256": audit["policy_sha256"]} + audit_checked = _parse_timestamp(audit["checked_at"]) + if audit_checked < after_created: + partial_reasons.append("deployment_audit_time_unbound") + observed_config_hashes = {item["sha256"] for item in after["files"]} + compose = after["adapters"].get("compose") + if isinstance(compose, dict): + observed_config_hashes.update(item["sha256"] for item in compose.get("config_files", [])) + if audit["source_sha256"] not in observed_config_hashes: + partial_reasons.append("deployment_source_unbound") + if audit["issues"]: + partial_reasons.append("deployment_audit_incomplete") + if audit["findings"]: + fail_reasons.append("deployment_policy_failure") + elif getattr(args, "require_deployment_audit", False): + partial_reasons.append("deployment_audit_missing") + for path in args.validation_record or []: + record, validation_raw = _read_json(path, MAX_PROFILE_BYTES) + validation_hashes.append(_sha256_bytes(validation_raw)) + _validate_validation_record(record) + attributes = record.get("attributes", {}) + required_bindings = { + "before_snapshot_sha256": before_sha256, + "after_snapshot_sha256": after_sha256, + "health_sha256": health_sha256, + "before_scanner_sha256": before_scanner_sha256, + "after_scanner_sha256": after_scanner_sha256, + **deployment_bindings, + } + if (any(expected is None or attributes.get(name) != expected + for name, expected in required_bindings.items()) or + not isinstance(attributes.get("run_id"), str) or + not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._:-]{7,127}", attributes["run_id"])): + partial_reasons.append("validation_evidence_unbound") + else: + validation_run_ids.add(attributes["run_id"]) + record_time = _parse_timestamp(record["timestamp"]) + latest_dependency = max(timestamp for timestamp in + (after_created, health_checked, after_scanner_created, audit_checked) + if timestamp is not None) + if record_time < latest_dependency: + partial_reasons.append("validation_time_unbound") + if record["status"] == "fail": + validation_failures += 1 + elif record["status"] in {"partial", "blocked"}: + validation_partial += 1 + elif record["status"] == "not_run": + validation_not_run += 1 + elif record["status"] == "skipped_not_applicable": + validation_skipped += 1 + else: + validation_passes += 1 + if not args.validation_record: + partial_reasons.append("validation_evidence_missing") + elif not validation_passes and not validation_failures and not validation_partial: + partial_reasons.append("validation_evidence_not_executed") + if len(validation_run_ids) > 1: + partial_reasons.append("validation_run_mismatch") + if validation_failures: + fail_reasons.append("validation_failure") + if validation_partial or validation_not_run: + partial_reasons.append("validation_incomplete") + approved_drift = False + approved_drift_id = None + approved_drift_sha256 = None + if args.approved_drift: + approval, approval_raw = _read_json(args.approved_drift, MAX_JSON_BYTES) + _validate_approved_drift(approval, comparison, before_sha256, after_sha256) + approved_drift = True + approved_drift_id = approval["id"] + approved_drift_sha256 = _sha256_bytes(approval_raw) + if comparison["summary"]["drift_count"] and not approved_drift: + fail_reasons.append("snapshot_drift") + if partial_reasons: + status, exit_code = "partial", 2 + elif fail_reasons: + status, exit_code = "fail", 1 + else: + status, exit_code = "pass", 0 + validation_evidence_sha256 = _sha256_bytes(_canonical(sorted(validation_hashes))) + run_id = next(iter(validation_run_ids)) if len(validation_run_ids) == 1 else None + provenance = { + "after_scanner_sha256": after_scanner_sha256, + "after_snapshot_sha256": after_sha256, + "approved_drift_sha256": approved_drift_sha256, + "before_scanner_sha256": before_scanner_sha256, + "before_snapshot_sha256": before_sha256, + "health_sha256": health_sha256, + "run_id": run_id, + "validation_evidence_sha256": validation_evidence_sha256, + **deployment_bindings, + } + identity = _sha256_bytes(_canonical(provenance))[:16] + record = { + "attributes": { + "scanner_new_findings": scanner_new, + "snapshot_drift_count": comparison["summary"]["drift_count"], + "snapshot_drift_approved": approved_drift, + "before_snapshot_sha256": before_sha256, + "after_snapshot_sha256": after_sha256, + "before_scanner_sha256": before_scanner_sha256, + "after_scanner_sha256": after_scanner_sha256, + "health_sha256": health_sha256, + "validation_evidence_sha256": validation_evidence_sha256, + "run_id": run_id, + "approved_drift_id": approved_drift_id, + "approved_drift_sha256": approved_drift_sha256, + "health_failures": health_failures, + "validation_failures": validation_failures, + "validation_not_run": validation_not_run, + "validation_partial": validation_partial, + "validation_passes": validation_passes, + "validation_skipped_not_applicable": validation_skipped, + **deployment_bindings, + }, + "check": "patch-check", + "id": "patch-check-" + identity, + "schema": VALIDATION_SCHEMA, + "status": status, + "summary": ("Patch validation is incomplete: " + ", ".join(sorted(set(partial_reasons))) + if partial_reasons else + "Patch validation found regressions: " + ", ".join(sorted(set(fail_reasons))) + if fail_reasons else + "Snapshot, health, scanner, and executed validation evidence passed."), + "timestamp": _now(), + } + _validate_validation_record(record) + print(_canonical(record).decode("utf-8"), end="") + return exit_code + + +def build_parser(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--version", action="version", version=VERSION) + commands = parser.add_subparsers(dest="command", required=True) + + preflight = commands.add_parser("preflight", help="validate a declarative profile and adapter availability") + preflight.add_argument("--profile", required=True) + preflight.set_defaults(handler=command_preflight) + + snapshot = commands.add_parser("snapshot", help="create a read-only system and file snapshot") + snapshot.add_argument("--profile", required=True) + snapshot.add_argument("--root", required=True) + snapshot.add_argument("--output", required=True) + snapshot.set_defaults(handler=command_snapshot) + + compare = commands.add_parser("compare", help="compare two compatible snapshot documents") + compare.add_argument("baseline", metavar="BASELINE") + compare.add_argument("current", metavar="CURRENT") + compare.set_defaults(handler=command_compare) + + health = commands.add_parser("health", help="run explicit safe HTTP health checks") + health.add_argument("--profile", required=True) + health.set_defaults(handler=command_health) + + backup = commands.add_parser("backup", help="create or verify a bounded backup") + backup_commands = backup.add_subparsers(dest="backup_command", required=True) + backup_create = backup_commands.add_parser("create") + backup_create.add_argument("--profile", required=True) + backup_create.add_argument("--root", required=True) + backup_create.add_argument("--output", required=True) + backup_create.set_defaults(handler=command_backup_create) + backup_verify = backup_commands.add_parser("verify") + backup_verify.add_argument("backup", metavar="BACKUP") + backup_verify.set_defaults(handler=command_backup_verify) + + restore = commands.add_parser("restore-stage", help="verify and optionally extract into a new staging path") + restore.add_argument("backup", metavar="BACKUP") + restore.add_argument("--target", required=True) + restore.add_argument("--apply", action="store_true") + restore.add_argument("--approval-id") + restore.set_defaults(handler=command_restore_stage) + + patch_check = commands.add_parser("patch-check", help="compare before/after evidence and validation records") + patch_check.add_argument("--before", required=True) + patch_check.add_argument("--after", required=True) + patch_check.add_argument("--before-scanner", "--scanner-before", dest="before_scanner") + patch_check.add_argument("--after-scanner", "--scanner-after", dest="after_scanner") + patch_check.add_argument("--health-result", required=False) + patch_check.add_argument("--validation-record", action="append", default=[]) + patch_check.add_argument("--approved-drift") + patch_check.add_argument("--deployment-audit") + patch_check.add_argument("--deployment-model") + patch_check.add_argument("--deployment-policy") + patch_check.add_argument("--require-deployment-audit", action="store_true") + patch_check.set_defaults(handler=command_patch_check) + + audit = commands.add_parser("audit-deployment", help="audit declared metadata, not a running daemon") + audit.add_argument("--model", required=True) + audit.add_argument("--policy", required=True) + audit.set_defaults(handler=command_audit_deployment) + + timeline = commands.add_parser("timeline", help="normalize and sort event.v1 files") + timeline.add_argument("--events", nargs="+", required=True) + timeline.add_argument("--output", required=True) + timeline.set_defaults(handler=command_timeline) + + evidence = commands.add_parser("evidence", help="build a sanitized structured evidence directory") + evidence.add_argument("--profile", required=True) + evidence.add_argument("--output", required=True) + evidence.add_argument("--input", nargs="+", required=True) + evidence.set_defaults(handler=command_evidence) + return parser + + +def main(argv=None): + parser = build_parser() + args = parser.parse_args(argv) + try: + return args.handler(args) + except DefenseError as exc: + error = {"error": "blocked_or_invalid", "reason": str(exc), "exit_code": 2, + "tool": _tool_record()} + print(_canonical(error).decode("utf-8"), end="", file=sys.stderr) + return 2 + except (OSError, UnicodeError, json.JSONDecodeError, RecursionError, MemoryError) as exc: + error = {"error": "operation_failed", "reason": type(exc).__name__, "exit_code": 2, + "tool": _tool_record()} + print(_canonical(error).decode("utf-8"), end="", file=sys.stderr) + return 2 + except KeyboardInterrupt: + error = {"error": "interrupted", "exit_code": 2, "tool": _tool_record()} + print(_canonical(error).decode("utf-8"), end="", file=sys.stderr) + return 2 + except Exception as exc: + error = {"error": "unexpected_failure", "reason": type(exc).__name__, "exit_code": 2, + "tool": _tool_record()} + print(_canonical(error).decode("utf-8"), end="", file=sys.stderr) + return 2 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/defense_scan.py b/scripts/defense_scan.py new file mode 100644 index 0000000..07300b8 --- /dev/null +++ b/scripts/defense_scan.py @@ -0,0 +1,1547 @@ +#!/usr/bin/env python3 +"""Offline, read-only source triage. Python 3.10+, standard library only. + +Never imports or executes scanned code. Rules are loaded only from the toolkit's +own rules directory, never discovered inside the target. No network/update API. +""" +from __future__ import annotations + +import argparse +import ast +from bisect import bisect_right +from collections import Counter +from datetime import datetime, timezone +import fnmatch +import hashlib +import json +import os +from pathlib import Path +import re +import stat +import sys +import tokenize +import io +import unicodedata + +VERSION = "1.8.0" +SCOPE_SCHEMA = "durkahelper.scanner-scope.v2" +CONTEXT_SCHEMA = "durkahelper.scanner-context.v1" +SEMANTIC_REVISION = "bounded-source-signals.v3" +INFRASTRUCTURE = {"docker-desktop", "compose", "vulnbox", "team-lan", "s4dfarm", "neo", "packmate"} +PATH_SEMANTICS = "root-relative-posix.v1" +RULE_PATH = Path(__file__).resolve().parents[1] / "rules" / "defense.json" +SKIP_DIRS = {".git", ".hg", ".svn", ".venv", "venv", "node_modules", "vendor", + "__pycache__", ".cache", ".ssh", ".aws", "artifacts", "dist", "build", "target", "obj", "bin"} +EXTENSIONS = { + ".py": "python", ".js": "javascript", ".jsx": "javascript", ".ts": "javascript", + ".tsx": "javascript", ".mjs": "javascript", ".cjs": "javascript", + ".php": "php", ".go": "go", ".java": "java", ".cs": "csharp", + ".c": "native", ".h": "native", ".cpp": "native", ".hpp": "native", ".cc": "native", + ".yaml": "config", ".yml": "config", ".toml": "config", ".json": "config", + ".conf": "config", ".ini": "config", ".properties": "config", ".xml": "config", + ".sh": "shell", ".bash": "shell", ".ejs": "template", ".html": "template", + ".hbs": "template", ".j2": "template", ".twig": "template", ".erb": "template", + ".rb": "ruby", ".rake": "ruby", ".rs": "rust", ".sql": "sql", + ".acl": "config", ".cnf": "config", ".config": "config", + ".cshtml": "csharp", ".razor": "csharp", + ".service": "config", ".socket": "config", +} + + +def load_rules(): + data = json.loads(RULE_PATH.read_text(encoding="utf-8")) + if data["schema_version"] != 1: + raise ValueError("unsupported rules schema") + rules = data["rules"] + if len({r["id"] for r in rules}) != len(rules): + raise ValueError("duplicate rule IDs") + for rule in rules: + for field in ("id", "title", "engine", "languages", "reason", "fix", "before", "after", "check", "doc", "family", "limitations"): + if not rule.get(field): + raise ValueError("incomplete rule: " + rule.get("id", "?")) + if (rule.get("review_priority") not in {"normal", "high"} + or rule.get("signal_kind") not in {"syntactic-review", "configuration-review"} + or not isinstance(rule.get("cwe"), list) + or any(not isinstance(item, str) or not re.fullmatch(r"CWE-[1-9][0-9]*", item) for item in rule["cwe"]) + or type(rule.get("code_only", False)) is not bool): + raise ValueError("invalid rule metadata") + if rule["engine"] == "regex": + rule["compiled"] = re.compile(rule["pattern"], re.MULTILINE | re.IGNORECASE) + rule["compiled_languages"] = {} + variants = rule.get("language_patterns", {}) + if not isinstance(variants, dict): + raise ValueError("language patterns must be a mapping") + for lang, pattern in variants.items(): + if lang not in rule["languages"] or not isinstance(pattern, str): + raise ValueError("invalid language pattern") + rule["compiled_languages"][lang] = re.compile(pattern, re.MULTILINE | re.IGNORECASE) + elif rule["engine"] not in {"python-ast", "javascript-tokens"}: + raise ValueError("unknown engine") + return rules + + +def _canonical_json(value): + return json.dumps(value, ensure_ascii=True, sort_keys=True, + separators=(",", ":")).encode("utf-8") + + +def validate_context(value=None): + """Allow only non-secret context enums; context never filters detectors.""" + if value is None: + value = {"schema": CONTEXT_SCHEMA, "infrastructure": [], "role": "both"} + if not isinstance(value, dict) or set(value) != {"schema", "infrastructure", "role"}: + raise ValueError("invalid scanner context") + items = value["infrastructure"] + if (value["schema"] != CONTEXT_SCHEMA or value["role"] not in ("defender", "administrator", "both") + or not isinstance(items, list) or len(items) > len(INFRASTRUCTURE) + or any(not isinstance(item, str) or item not in INFRASTRUCTURE for item in items) + or len(items) != len(set(items))): + raise ValueError("invalid scanner context") + return {"schema": CONTEXT_SCHEMA, "infrastructure": sorted(items), "role": value["role"]} + + +def _unique_json_object(pairs): + result = {} + for key, value in pairs: + if key in result: + raise ValueError("duplicate JSON key") + result[key] = value + return result + + +def load_context(filename): + return validate_context(json.loads(read_regular(canonical_scan_root(filename), 16384), + object_pairs_hook=_unique_json_object)) + + +def review_metadata(rule, context): + """Return authored explanations only, never strings taken from the target.""" + notes = [] + active = set(context["infrastructure"]) + family = rule["family"] + if active & {"compose", "docker-desktop"} and family == "container-isolation": + notes.append("Review this setting in the resolved deployment model; source text is not runtime evidence.") + if active & {"team-lan", "s4dfarm", "neo", "packmate"} and family in {"authentication", "secret-handling", "network-exposure"}: + notes.append("Check access from a separate authorized LAN client and keep credentials out of logs and broadcasts.") + if "vulnbox" in active and family in {"injection", "file-access", "authentication"}: + notes.append("Verify the service contract and checker behavior before applying a patch to a Vulnbox service.") + return {"family": family, "cwe": list(rule["cwe"]), + "review_priority": "high" if notes else rule["review_priority"], + "signal_kind": rule["signal_kind"], "limitations": rule["limitations"], + "context_notes": notes} + + +def rules_fingerprint(rules): + """Hash only authored rule data, never runtime regex objects.""" + portable = [] + for rule in sorted(rules, key=lambda item: item["id"]): + portable.append({key: value for key, value in rule.items() + if key not in {"compiled", "compiled_languages"}}) + return hashlib.sha256(_canonical_json(portable)).hexdigest() + + +def scan_scope(root, rules, exclude, max_bytes, max_files, max_findings, context=None): + """Return a deterministic, non-secret description of scan comparability.""" + normalized_root = unicodedata.normalize("NFC", os.path.normcase(str(root))) + root_digest = hashlib.sha256( + ("durkahelper-root-v1\0" + normalized_root).encode( + "utf-8", errors="surrogatepass" + ) + ).hexdigest() + body = { + "schema": SCOPE_SCHEMA, + "root": "sha256:" + root_digest, + "rules_sha256": rules_fingerprint(rules), + "exclude": sorted(set(exclude)), + "limits": { + "max_bytes": max_bytes, + "max_files": max_files, + "max_findings": max_findings, + }, + "path_semantics": PATH_SEMANTICS, + "semantic_revision": SEMANTIC_REVISION, + "context_sha256": hashlib.sha256(_canonical_json(validate_context(context))).hexdigest(), + } + body["sha256"] = hashlib.sha256(_canonical_json(body)).hexdigest() + return body + + +def language(path): + name = path.name.lower() + if name.startswith("dockerfile"): + return "docker" + if name == ".env.example" or name in {"nginx.conf", "redis.conf", "my.cnf", ".htaccess", "sshd_config", "sudoers"}: + return "config" + if name in {"gemfile", "rakefile"}: + return "ruby" + return EXTENSIONS.get(path.suffix.lower()) + + +class PythonSignals(ast.NodeVisitor): + """Syntactic signals only. No claim of type resolution or data-flow analysis.""" + + def __init__(self): + self.aliases = {} + # Only immutable scalar/string-expression facts from straight-line code. + # No mutable dict/list propagation, execution or interprocedural analysis. + self.values = {} + self.hits = set() + self.issues = set() + self.replaced_api_members = set() + + def resolved(self, node): + return self.values.get(node.id, node) if isinstance(node, ast.Name) else node + + @staticmethod + def literal_dict(node): + """Known keys of an inline dict, respecting last-write-wins unpacking. + + Unknown spreads/keys invalidate earlier facts; no dict variable is + evaluated or treated as an immutable copy of a mutable object. + """ + result = {} + if not isinstance(node, ast.Dict): + return result + for key, value in PythonSignals.dict_entries(node): + if key is None: + result.clear() + else: + result[key] = value + return result + + @staticmethod + def dict_entries(node): + for key, value in zip(node.keys, node.values): + if key is None and isinstance(value, ast.Dict): + yield from PythonSignals.dict_entries(value) + elif isinstance(key, ast.Constant) and isinstance(key.value, str): + yield key.value, value + else: + yield None, None + + INSTANCE_FACTORIES = {"requests.Session": "requests.Session", + "requests.sessions.Session": "requests.Session", + "requests.session": "requests.Session", + "requests.sessions.session": "requests.Session", + "httpx.Client": "httpx.Client", "httpx.AsyncClient": "httpx.AsyncClient", + "pickle.Unpickler": "pickle.Unpickler", "_pickle.Unpickler": "_pickle.Unpickler", + "flask.Flask": "flask.Flask", "flask.Blueprint": "flask.Blueprint", + "logging.getLogger": "logging.Logger"} + TAR_FACTORIES = {"tarfile.open": "tarfile.TarFile", "tarfile.TarFile": "tarfile.TarFile", + "tarfile.TarFile.open": "tarfile.TarFile"} + + def constructed_type(self, node): + if not isinstance(node, ast.Call): + return "" + factory = self.name(node.func) + if factory in {"flask.Flask", "flask.Blueprint", "logging.getLogger"} and not self.known_binding(node.func): + return "" + return self.TAR_FACTORIES.get(factory, self.INSTANCE_FACTORIES.get(factory, "")) + + def known_binding(self, node): + """Whether the new narrow detectors have an explicit local name fact.""" + if isinstance(node, ast.Name): + return node.id in self.aliases and self.aliases[node.id] != "" + if isinstance(node, ast.Attribute): + return self.name(node) not in self.replaced_api_members and self.known_binding(node.value) + if isinstance(node, ast.Call): + return self.known_binding(node.func) + return False + + def forget(self, target): + for item in ast.walk(target): + if isinstance(item, ast.Attribute) and isinstance(item.ctx, (ast.Store, ast.Del)): + self.replaced_api_members.add(self.name(item)) + if isinstance(item, ast.Name) and isinstance(item.ctx, (ast.Store, ast.Del)): + self.values.pop(item.id, None) + self.aliases[item.id] = "" + + def visit_Assign(self, node): + self.visit(node.value) + value = self.resolved(node.value) + factory = self.constructed_type(node.value) + for target in node.targets: + self.visit(target) + self.forget(target) + if isinstance(target, ast.Name) and (isinstance(value, ast.Constant) + or self.dynamic_string(value) + or self.psycopg_sql(value) != "unknown"): + self.values[target.id] = value + elif isinstance(target, ast.Name) and factory: + self.aliases[target.id] = factory + for target in node.targets: + if isinstance(target, ast.Attribute): + self.replaced_api_members.add(self.name(target)) + if (isinstance(target, ast.Subscript) and self.flask_config(target.value) + and isinstance(target.slice, ast.Constant)): + self.config_signal(target.slice.value, node.value, node) + if isinstance(target, ast.Attribute): + if (target.attr == "debug" and self.name(target.value) == "flask.Flask" + and self.known_binding(target.value) and self.constant(node.value, True)): + self.hit("PY-DEBUG", node) + if target.attr == "verify_mode" and self.name(node.value) == "ssl.CERT_NONE": + self.hit("PY-SSL-CONTEXT", node) + if target.attr == "check_hostname" and self.constant(node.value, False): + self.hit("PY-SSL-CONTEXT", node) + + def visit_AnnAssign(self, node): + if node.value is not None: + # Reuse assignment handling, retaining the original line number. + assignment = ast.Assign(targets=[node.target], value=node.value) + ast.copy_location(assignment, node) + self.visit_Assign(assignment) + else: + self.forget(node.target) + + def visit_AugAssign(self, node): + self.generic_visit(node) + self.forget(node.target) + + def visit_NamedExpr(self, node): + self.visit(node.value) + self.forget(node.target) + + def visit_Delete(self, node): + for target in node.targets: + self.forget(target) + + def visit_branch(self, node): + # Do not carry scalar facts across branches, loops, exception handlers, + # comprehensions or context managers. Scan each statement list locally. + self.values = {} + saved = self.aliases.copy() + for _, value in ast.iter_fields(node): + if isinstance(value, list): + self.values = {} + self.aliases = saved.copy() + for child in value: + if isinstance(child, ast.AST): + self.visit(child) + elif isinstance(value, ast.AST): + self.visit(value) + self.invalidate_region_aliases(node, saved) + self.values = {} + + def invalidate_region_aliases(self, node, saved): + # Any store/import in a conditional region makes that alias uncertain. + self.aliases = saved + for child in ast.walk(node): + if isinstance(child, ast.Name) and isinstance(child.ctx, (ast.Store, ast.Del)): + self.aliases[child.id] = "" + elif isinstance(child, (ast.Import, ast.ImportFrom)): + for alias in child.names: + self.aliases[alias.asname or alias.name.split(".")[0]] = "" + + def visit_context(self, node, *, asynchronous): + # Retain only known constructor types with the matching context API. + # Scalar facts never cross a context manager; __enter__/__exit__ may + # affect application state and are never executed by this scanner. + allowed = {"httpx.AsyncClient"} if asynchronous else {"tarfile.TarFile", "requests.Session", "httpx.Client"} + saved = self.aliases.copy() + self.values = {} + for item in node.items: + self.visit(item.context_expr) + context_type = self.name(item.context_expr) + if item.optional_vars is not None: + self.forget(item.optional_vars) + if isinstance(item.optional_vars, ast.Name) and context_type in allowed: + self.aliases[item.optional_vars.id] = context_type + for statement in node.body: + self.visit(statement) + self.invalidate_region_aliases(node, saved) + self.values = {} + + def visit_With(self, node): + self.visit_context(node, asynchronous=False) + + def visit_AsyncWith(self, node): + self.visit_context(node, asynchronous=True) + + visit_If = visit_branch + visit_For = visit_branch + visit_AsyncFor = visit_branch + visit_While = visit_branch + visit_Try = visit_branch + visit_TryStar = visit_branch + visit_Match = visit_branch + visit_IfExp = visit_branch + visit_ListComp = visit_branch + visit_SetComp = visit_branch + visit_DictComp = visit_branch + visit_GeneratorExp = visit_branch + + def name(self, node): + if isinstance(node, ast.Name): + return self.aliases.get(node.id, node.id) + if isinstance(node, ast.Attribute): + return self.name(node.value) + "." + node.attr + if isinstance(node, ast.Call): + return self.constructed_type(node) + return "" + + def visit_Import(self, node): + for alias in node.names: + self.values.pop(alias.asname or alias.name.split(".")[0], None) + self.aliases[alias.asname or alias.name.split(".")[0]] = alias.name if alias.asname else alias.name.split(".")[0] + + def visit_ImportFrom(self, node): + if node.module: + for alias in node.names: + if alias.name != "*": + self.values.pop(alias.asname or alias.name, None) + self.aliases[alias.asname or alias.name] = node.module + "." + alias.name + + def visit_FunctionDef(self, node): + saved, saved_values = self.aliases.copy(), self.values.copy() + auth_seen = False + for decorator in node.decorator_list: + # Decorators are listed outermost first. Flask's registration + # decorator must wrap the authentication decorator, not vice versa. + if self.name(decorator) == "flask_login.login_required" and self.known_binding(decorator): + auth_seen = True + if (auth_seen and isinstance(decorator, ast.Call) + and self.name(decorator.func) in { + "flask.Flask.route", "flask.Blueprint.route", + *{"flask." + kind + "." + method for kind in ("Flask", "Blueprint") + for method in ("get", "post", "put", "patch", "delete")}}): + self.hit("PY-AUTH-DECORATOR", decorator) + if self.name(decorator) == "django.views.decorators.csrf.csrf_exempt": + self.hit("PY-CSRF-EXEMPT", decorator) + self.visit(decorator) + for default in [*node.args.defaults, *node.args.kw_defaults]: + if default is not None: + self.visit(default) + self.values = {} + # Parameters shadow imports. Function-local scalar facts do not escape. + arguments = node.args.posonlyargs + node.args.args + node.args.kwonlyargs + arguments += [arg for arg in (node.args.vararg, node.args.kwarg) if arg] + for arg in arguments: + self.aliases[arg.arg] = "" + for statement in node.body: + self.visit(statement) + self.aliases = saved + self.aliases[node.name] = "" + self.values = saved_values + self.values.pop(node.name, None) + + visit_AsyncFunctionDef = visit_FunctionDef + + def visit_ClassDef(self, node): + saved, saved_values = self.aliases.copy(), self.values.copy() + self.values = {} + self.generic_visit(node) + self.aliases = saved + self.aliases[node.name] = "" + self.values = saved_values + self.values.pop(node.name, None) + + def visit_Lambda(self, node): + saved, saved_values = self.aliases.copy(), self.values.copy() + for default in [*node.args.defaults, *node.args.kw_defaults]: + if default is not None: + self.visit(default) + for arg in [*node.args.posonlyargs, *node.args.args, *node.args.kwonlyargs, + *[a for a in (node.args.vararg, node.args.kwarg) if a]]: + self.aliases[arg.arg] = "" + self.values = {} + self.visit(node.body) + self.aliases, self.values = saved, saved_values + + def constant(self, node, value): + node = self.resolved(node) + return isinstance(node, ast.Constant) and node.value == value + + @staticmethod + def literal_string(node): + # Recognize syntax only: no evaluation, formatting, arbitrary constant + # folding or recursive expansion of names (which may be self-referential). + if isinstance(node, ast.Constant): + return isinstance(node.value, str) + if isinstance(node, ast.JoinedStr): + return all(isinstance(part, ast.Constant) and isinstance(part.value, str) for part in node.values) + return (isinstance(node, ast.BinOp) and isinstance(node.op, ast.Add) + and PythonSignals.literal_string(node.left) and PythonSignals.literal_string(node.right)) + + def dynamic_string(self, node): + node = self.resolved(node) + if self.literal_string(node): + return False + return (isinstance(node, ast.JoinedStr) + or isinstance(node, ast.BinOp) and isinstance(node.op, (ast.Add, ast.Mod)) + or isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute) and node.func.attr == "format") + + def flask_config(self, node): + return (isinstance(node, ast.Attribute) and node.attr == "config" + and self.name(node.value) == "flask.Flask" and self.known_binding(node)) + + def config_signal(self, key, value, node): + if key == "DEBUG" and self.constant(value, True): + self.hit("PY-DEBUG", node) + if key in {"SESSION_COOKIE_HTTPONLY", "SESSION_COOKIE_SECURE"} and self.constant(value, False): + self.hit("CFG-COOKIE-FLAGS", node) + + def psycopg_sql(self, node, depth=0, active=None): + """Return safe/unsafe/unknown for a narrow, imported composable tree. + + SQL() never escapes its argument. Only literal SQL snippets and known + quoting constructors are suppressed; unknown pieces remain reviewable. + This says nothing about authorization to select an identifier. + """ + node = self.resolved(node) + active = set() if active is None else active + if id(node) in active: + return "unknown" # A scalar/name cycle is not deep composition. + if depth > 32: + self.issues.add("python_composition_limit") + return "unknown" + active = active | {id(node)} + if isinstance(node, ast.BinOp) and isinstance(node.op, ast.Add): + states = [self.psycopg_sql(part, depth + 1, active) for part in (node.left, node.right)] + return "unsafe" if "unsafe" in states else "safe" if states == ["safe", "safe"] else "unknown" + if not isinstance(node, ast.Call): + return "unknown" + name = self.name(node.func) + prefixes = ("psycopg.sql.", "psycopg2.sql.") + if name.startswith(prefixes) and self.known_binding(node.func): + kind = name.rsplit(".", 1)[-1] + if kind == "SQL": + return "safe" if len(node.args) == 1 and not node.keywords and self.literal_string(self.resolved(node.args[0])) else "unsafe" + if kind in {"Identifier", "Literal", "Placeholder"}: + return "safe" + if isinstance(node.func, ast.Attribute) and node.func.attr in {"format", "join", "as_string"}: + base = self.psycopg_sql(node.func.value, depth + 1, active) + if base == "unknown": + return "unknown" + if node.func.attr == "as_string": + return base + if node.func.attr == "join": + parts = node.args[0].elts if len(node.args) == 1 and isinstance(node.args[0], (ast.List, ast.Tuple)) else [None] + else: + parts = [*node.args, *[kw.value if kw.arg else None for kw in node.keywords]] + states = [base, *[self.psycopg_sql(part, depth + 1, active) for part in parts]] + return "safe" if all(state == "safe" for state in states) else "unsafe" + return "unknown" + + def hit(self, rule, node): + self.hits.add((rule, node.lineno)) + + def visit_Assert(self, node): + # Runtime security checks must survive python -O; ordinary test asserts + # are deliberately omitted by this name-based heuristic. + sensitive = re.compile(r"(?:auth|permission|owner|admin|token|session|password|allowed)", re.I) + if any(isinstance(item, ast.Name) and sensitive.search(item.id) + or isinstance(item, ast.Attribute) and sensitive.search(item.attr) + for item in ast.walk(node.test)): + self.hit("PY-ASSERT-AUTH", node) + self.generic_visit(node) + + def visit_Call(self, node): + name = self.name(node.func) + tail = name.rsplit(".", 1)[-1] + kwargs = {} + for kw in node.keywords: + if kw.arg: + kwargs[kw.arg] = kw.value + else: + kwargs.update(self.literal_dict(kw.value)) + first = node.args[0] if node.args else None + if (isinstance(node.func, ast.Attribute) and node.func.attr in {"update", "from_mapping"} + and self.flask_config(node.func.value)): + config = {} + if len(node.args) <= 1: + if node.args: + config.update(self.literal_dict(node.args[0])) + for kw in node.keywords: + if kw.arg: + config[kw.arg] = kw.value + elif isinstance(kw.value, ast.Dict): + for key, value in self.dict_entries(kw.value): + if key is None: + config.clear() + else: + config[key] = value + else: + config.clear() + for key, value in config.items(): + self.config_signal(key, value, node) + if (self.known_binding(node.func) and name.rsplit(".", 1)[0] in {"logging", "logging.Logger", "flask.Flask.logger"} + and tail in {"debug", "info", "warning", "warn", "error", "exception", "critical", "log"}): + sensitive = {"password", "passwd", "secret", "token", "access_token", "refresh_token", "api_key", "authorization"} + # Only direct values/format expressions, not arguments to a + # potential redaction/hash helper. No source text is exported. + def exposes(value): + if isinstance(value, ast.Name): + return value.id.lower() in sensitive + if isinstance(value, ast.Attribute): + return value.attr.lower() in sensitive + if isinstance(value, ast.Subscript): + return isinstance(value.slice, ast.Constant) and isinstance(value.slice.value, str) and value.slice.value.lower() in sensitive + if isinstance(value, ast.JoinedStr): + return any(exposes(item.value) for item in value.values if isinstance(item, ast.FormattedValue)) + if isinstance(value, (ast.Tuple, ast.List)): + return any(exposes(item) for item in value.elts) + if isinstance(value, ast.Dict): + return any(exposes(item) for item in value.values) + if isinstance(value, ast.BinOp): + return exposes(value.left) or exposes(value.right) + return False + if any(exposes(value) for value in node.args): + self.hit("PY-LOG-CREDENTIALS", node) + if name in {"eval", "exec", "builtins.eval", "builtins.exec"}: + self.hit("PY-EVAL", node) + subprocess_call = name in {"subprocess.run", "subprocess.call", "subprocess.check_call", + "subprocess.check_output", "subprocess.Popen"} + process_args = first if first is not None else kwargs.get("args") + if name == "asyncio.create_subprocess_exec": + process_args = ast.Tuple(elts=node.args, ctx=ast.Load()) + shell_argv = (isinstance(process_args, (ast.List, ast.Tuple)) and len(process_args.elts) > 1 + and isinstance(process_args.elts[0], ast.Constant) + and isinstance(process_args.elts[0].value, str) + and process_args.elts[0].value.replace("\\", "/").rsplit("/", 1)[-1].lower() + in {"sh", "bash", "dash", "zsh", "ksh", "cmd", "cmd.exe", "powershell", "powershell.exe", "pwsh"} + and any(isinstance(arg, ast.Constant) and isinstance(arg.value, str) + and arg.value.lower() in {"-c", "-lc", "-ec", "/c", "-command", "-encodedcommand"} + for arg in process_args.elts[1:])) + if (name in {"os.system", "os.popen", "subprocess.getoutput", "subprocess.getstatusoutput", + "asyncio.create_subprocess_shell"} + or subprocess_call and (self.constant(kwargs.get("shell"), True) or shell_argv) + or name == "asyncio.create_subprocess_exec" and shell_argv): + self.hit("PY-SHELL", node) + if name in {"pickle.load", "pickle.loads", "_pickle.load", "_pickle.loads", "dill.load", "dill.loads", "shelve.open", + "pickle.Unpickler.load", "_pickle.Unpickler.load", "jsonpickle.decode", "jsonpickle.loads", + "joblib.load", "pandas.read_pickle"}: + self.hit("PY-DESERIALIZE", node) + if name in {"numpy.load", "numpy.lib.format.read_array"}: + # These APIs default to rejecting pickle; signal only an explicit + # opt-in. Starred argv prevent a reliable positional index. + position = 2 if name == "numpy.load" else 1 + allow_pickle = kwargs.get("allow_pickle") + if (allow_pickle is None and len(node.args) > position + and not any(isinstance(arg, ast.Starred) for arg in node.args[:position + 1])): + allow_pickle = node.args[position] + if self.constant(allow_pickle, True): + self.hit("PY-DESERIALIZE", node) + if name in {"yaml.load", "yaml.load_all", "yaml.unsafe_load", "yaml.unsafe_load_all"}: + loader = kwargs.get("Loader", node.args[1] if len(node.args) > 1 else None) + if self.name(loader) not in {"yaml.SafeLoader", "yaml.CSafeLoader", "yaml.BaseLoader", "yaml.CBaseLoader"}: + self.hit("PY-YAML", node) + sql_arg = first + if sql_arg is None: + sql_arg = next((kwargs[k] for k in ("query", "sql", "operation", "statement", "sql_script", "raw_query", "text") if k in kwargs), None) + if tail in {"execute", "executemany", "executescript", "raw", "text"}: + composition = self.psycopg_sql(sql_arg) + if composition == "unsafe" or composition != "safe" and self.dynamic_string(sql_arg): + self.hit("PY-SQL", node) + if tail in {"find", "find_one", "filter", "where"} and any(isinstance(arg, ast.BoolOp) for arg in node.args): + self.hit("PY-ORM-BOOL", node) + template_arg = first if first is not None else kwargs.get("source") + if tail in {"render_template_string", "from_string"} and template_arg is not None and not isinstance(template_arg, ast.Constant): + self.hit("PY-TEMPLATE", node) + if self.constant(kwargs.get("verify"), False) and (name.startswith(("requests.", "httpx.")) or tail in {"get", "post", "put", "patch", "delete", "request"}): + self.hit("PY-TLS", node) + if name == "ssl._create_unverified_context": + self.hit("PY-SSL-CONTEXT", node) + if name == "django.views.decorators.csrf.csrf_exempt": + self.hit("PY-CSRF-EXEMPT", node) + if name in {"setattr", "builtins.setattr"} and len(node.args) > 1 and not isinstance(self.resolved(node.args[1]), ast.Constant): + self.hit("PY-MASS-ASSIGN", node) + redirect_keyword = "to" if name == "django.shortcuts.redirect" else "location" + redirect_arg = first if first is not None else kwargs.get(redirect_keyword) + if name in {"flask.redirect", "django.shortcuts.redirect", "werkzeug.utils.redirect"} and redirect_arg is not None and not isinstance(self.resolved(redirect_arg), ast.Constant): + self.hit("PY-REDIRECT", node) + if name in {"re.compile", "re.match", "re.fullmatch", "re.search", "re.findall", "re.finditer", "re.split", "re.sub", "re.subn"} and first is not None and not isinstance(self.resolved(first), ast.Constant): + self.hit("PY-REGEX-DYNAMIC", node) + if tail in {"run", "run_simple"} and self.constant(kwargs.get("debug", kwargs.get("use_debugger")), True): + self.hit("PY-DEBUG", node) + if name in {"jwt.decode", "jwt.decode_complete"} or name.endswith((".jwt.decode", ".jwt.decode_complete")): + jose = name == "jose.jwt.decode" + known_modern = jose or name == "jwt.decode_complete" + jwt_args = kwargs.copy() + valid_binding = True + if known_modern: + # Generic jwt.decode is version-dependent: PyJWT 1.x placed + # verify third. Only these exact APIs have this known layout. + for argument, position in (("algorithms", 2), ("options", 3)): + if (len(node.args) > position + and not any(isinstance(arg, ast.Starred) for arg in node.args[:position + 1])): + if argument in jwt_args: + valid_binding = False # Runtime TypeError, not a disabled verifier. + else: + jwt_args[argument] = node.args[position] + if valid_binding: + options = self.literal_dict(jwt_args.get("options")) + disabled = not known_modern and self.constant(jwt_args.get("verify"), False) + disabled |= self.constant(options.get("verify_signature"), False) + if any(self.constant(options.get("verify_" + claim), False) + and not (jose and self.constant(options.get("require_" + claim), True)) + for claim in ("exp", "nbf", "aud", "iss")): + self.hit("PY-JWT-CLAIMS", node) + if disabled: + self.hit("PY-JWT", node) + algorithms = jwt_args.get("algorithms") + algorithm_value = self.resolved(algorithms) + fixed_algorithms = (isinstance(algorithms, (ast.List, ast.Tuple)) + and all(isinstance(a, ast.Constant) and isinstance(a.value, str) for a in algorithms.elts)) + fixed_algorithms |= (jose and isinstance(algorithm_value, ast.Constant) + and isinstance(algorithm_value.value, str)) + if algorithms is not None and not fixed_algorithms: + self.hit("PY-JWT-ALGORITHMS", node) + archive_filter = kwargs.get("filter") + data_filter = (self.constant(archive_filter, "data") + or self.name(archive_filter) == "tarfile.data_filter") + tar_extract = name == "tarfile.TarFile.extract" + unpack_tar = False + if name == "shutil.unpack_archive": + archive_format = kwargs.get("format") + if (archive_format is None and len(node.args) > 2 + and not any(isinstance(arg, ast.Starred) for arg in node.args[:3])): + archive_format = node.args[2] + unpack_tar = any(self.constant(archive_format, fmt) + for fmt in ("tar", "gztar", "bztar", "xztar", "zstdtar")) + if (tail == "extractall" or tar_extract or unpack_tar) and not data_filter: + self.hit("PY-ARCHIVE", node) + if name in {"tempfile.mktemp"}: + self.hit("PY-TEMP", node) + if (tail == "XMLParser" or name in {"lxml.etree.XMLPullParser", "lxml.etree.ETCompatXMLParser", + "lxml.etree.iterparse"}) and self.constant(kwargs.get("resolve_entities"), True): + self.hit("PY-XML", node) + if name in {"hashlib.md5", "hashlib.sha1"}: + self.hit("PY-WEAK-HASH", node) + if name.startswith("random.") and tail in {"random", "randint", "randrange", "getrandbits", "choice", "choices"}: + self.hit("PY-RNG", node) + file_arg = first if first is not None else kwargs.get("path_or_file") + if tail == "send_file" and file_arg is not None and not isinstance(file_arg, ast.Constant): + self.hit("PY-FILE", node) + url_arg = first if first is not None else kwargs.get("url") + http_owner = name.rsplit(".", 1)[0] + http_call = (http_owner in {"requests", "httpx", "requests.Session", "requests.sessions.Session", "httpx.Client", "httpx.AsyncClient"} + and tail in {"get", "post", "put", "patch", "delete", "head", "options", "request"}) + http_call |= http_owner in {"httpx", "httpx.Client", "httpx.AsyncClient"} and tail == "stream" + if http_call and tail in {"request", "stream"}: + url_arg = (node.args[1] if len(node.args) > 1 + and not any(isinstance(arg, ast.Starred) for arg in node.args[:2]) else kwargs.get("url")) + if (http_call or name == "urllib.request.urlopen") and url_arg is not None and not isinstance(self.resolved(url_arg), ast.Constant): + self.hit("PY-URL", node) + if name in {"zlib.crc32", "zlib.adler32", "binascii.crc32", "binascii.crc_hqx"}: + self.hit("PY-CRC", node) + if tail in {"xpath", "XPath"} and self.dynamic_string(first): + self.hit("PY-XPATH", node) + if name == "uuid.UUID" and ({"bytes", "bytes_le"} & kwargs.keys()): + self.hit("PY-UUID-BYTES", node) + self.generic_visit(node) + + +def javascript_alias_patterns(source): + """Bounded import-name hints, not a JavaScript parser or scope analysis. + + Source is never evaluated. Only exact known module/member pairs contribute + patterns, and every target-controlled identifier is escaped first. + """ + ident = r"[A-Za-z_$][\w$]{0,127}" + module = r"['\"]((?:node:)?child_process|jsonwebtoken|jose)['\"]" + bindings = [] + + def bind(mod, local, member, end): + mod = mod.removeprefix("node:") + if not re.fullmatch(ident, local): + return + members = {"child_process": ("exec", "execSync", "spawn", "spawnSync", "execFile", "execFileSync"), + "jsonwebtoken": ("decode",), "jose": ("decodeJwt",)}[mod] + for name in members if member is None else (member,): + if name not in members: + continue + if len(bindings) >= 128: + raise ValueError("javascript_alias_limit") + rid = "JS-SHELL" if mod == "child_process" else "JS-JWT-DECODE" + receiver = re.escape(local) + if member is None: + access = r"\s*(?:\?\.\s*|\.\s*)" + re.escape(name) + access += r"|\s*(?:\?\.\s*)?\[\s*['\"]" + re.escape(name) + r"['\"]\s*\]" + receiver += "(?:" + access + ")" + suffix = r"\s*(?:\?\.)?\s*\(" + if mod == "child_process" and name not in {"exec", "execSync"}: + suffix += r"\s*['\"](?:[^'\"\n]*/)?(?:sh|bash|dash|zsh|cmd(?:\.exe)?|powershell(?:\.exe)?|pwsh)['\"]" + bindings.append((rid, re.compile(r"(?|\.\.\.|\?\.|===|==|!=|\+=|-=|\+\+|--|[^\s]") + i = 0 + while i < len(source): + if source[i].isspace(): + i += 1 + continue + if source.startswith("//", i): + end = source.find("\n", i + 2) + i = len(source) if end < 0 else end + continue + if source.startswith("/*", i): + end = source.find("*/", i + 2) + if end < 0: + issues.append("lexical_unterminated") + i = len(source) if end < 0 else end + 2 + continue + start = i + if (source[i] == "/" + and (not tokens or tokens[-1][0] in {"=", "(", "[", ":", ",", "return", "=>", "!", "?", ";"})): + # Common regex-literal positions only; division and ambiguous + # statement contexts are not resolved as by a full JS grammar. + end, character_class = i + 1, False + while end < len(source) and source[end] not in "\r\n": + if source[end] == "\\": + end += 2 + continue + if source[end] == "[": + character_class = True + elif source[end] == "]": + character_class = False + elif source[end] == "/" and not character_class: + break + end += 1 + if end < len(source) and source[end] == "/": + i = end + 1 + tokens.append(("", start)) + continue + if source[i] in "\"'`": + quote, closed = source[i], False + i += 1 + while i < len(source): + if source[i] == "\\": + i = min(len(source), i + 2) + elif source[i] == quote: + i += 1 + closed = True + break + else: + i += 1 + if not closed: + issues.append("lexical_unterminated") + tokens.append(("