init
This commit is contained in:
commit
303438d206
217 files changed
+66681
No files matched your search
@@ -0,0 +1,3 @@
|
||||
* text=auto
|
||||
*.sh text eol=lf
|
||||
*.py text eol=lf
|
||||
@@ -0,0 +1,38 @@
|
||||
---
|
||||
name: Сообщение об ошибке (RU)
|
||||
about: Сообщить о воспроизводимой проблеме toolkit без приватных данных
|
||||
title: "[Bug] "
|
||||
labels: ""
|
||||
assignees: ""
|
||||
---
|
||||
|
||||
<a id="safety-check"></a>
|
||||
## Проверка безопасности
|
||||
|
||||
[English](bug_report.md) | Русский
|
||||
|
||||
Не публикуйте credentials, приватные адреса, профили оператора, настоящие flags, traffic, raw logs или конфиденциальные исходники. При проблеме безопасности прочитайте [SECURITY.md](../../SECURITY-RU.md) до отправки публичного сообщения.
|
||||
|
||||
<a id="expected-and-actual-behavior"></a>
|
||||
## Ожидаемое и фактическое поведение
|
||||
|
||||
Опишите задуманный результат команды и то, что произошло вместо него. Статическая находка — сигнал для review, а не доказательство эксплуатируемости сервиса.
|
||||
|
||||
<a id="reproduction"></a>
|
||||
## Воспроизведение
|
||||
|
||||
Приведите минимальный синтетический пример, точную очищенную команду, exit code и ограниченный очищенный текст ошибки. Укажите, был ли это preview или явно применённое действие. Не запускайте destructive tests только ради воспроизведения issue.
|
||||
|
||||
<a id="environment"></a>
|
||||
## Окружение
|
||||
|
||||
- Commit/version DurkaHelper:
|
||||
- OS и архитектура:
|
||||
- Версии Python и ripgrep:
|
||||
- Только для deployment: версии Docker/Compose и архитектура image:
|
||||
- Последний известный рабочий commit, если известен:
|
||||
|
||||
<a id="scope-and-recovery"></a>
|
||||
## Область и восстановление
|
||||
|
||||
Что было затронуто? Сработал ли документированный ограниченный rollback? Укажите, относится ли проблема к native core, synthetic fixture или сопровождаемому deployment.
|
||||
@@ -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.
|
||||
@@ -0,0 +1,32 @@
|
||||
---
|
||||
name: Ложное срабатывание или пропуск сканера (RU)
|
||||
about: Улучшить детектор с помощью небольшого синтетического примера
|
||||
title: "[Scanner] RULE-ID: "
|
||||
labels: ""
|
||||
assignees: ""
|
||||
---
|
||||
|
||||
<a id="rule-and-environment"></a>
|
||||
## Правило и окружение
|
||||
|
||||
[English](false_positive.md) | Русский
|
||||
|
||||
- Rule ID и commit/version сканера:
|
||||
- Версия language/runtime:
|
||||
- Detection engine, если известен:
|
||||
- Context schema и относящаяся к проблеме настройка приоритета без секретов, если есть:
|
||||
|
||||
<a id="minimal-synthetic-example"></a>
|
||||
## Минимальный синтетический пример
|
||||
|
||||
Приведите код, который можно публиковать. Удалите реальные credentials, identifiers, приватные адреса и чужие исходники. Не прикладывайте полный scan report или настоящий репозиторий, если достаточно небольшого примера.
|
||||
|
||||
<a id="expected-result-and-reasoning"></a>
|
||||
## Ожидаемый результат и обоснование
|
||||
|
||||
Объясните, должно ли правило срабатывать на примере и почему. Добавьте противоположный безопасный или небезопасный пример и соответствующее документированное ограничение детектора. Для проблем aliasing или shadowing включите окружающие binding statements.
|
||||
|
||||
<a id="reproduction-and-proposed-coverage"></a>
|
||||
## Воспроизведение и предлагаемое покрытие
|
||||
|
||||
Укажите очищенную команду и наблюдаемые rule IDs/exit code. Предложите независимые positive и negative tests; не ограничивайтесь изменением regex. Проблемы безопасности в самом toolkit описываются согласно [SECURITY.md](../../SECURITY-RU.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).
|
||||
@@ -0,0 +1,29 @@
|
||||
---
|
||||
name: Запрос нового правила обнаружения (RU)
|
||||
about: Предложить ограниченный сигнал для review с независимыми тестами
|
||||
title: "[Rule request] "
|
||||
labels: ""
|
||||
assignees: ""
|
||||
---
|
||||
|
||||
<a id="family-languages-and-existing-coverage"></a>
|
||||
## Семейство, языки и существующее покрытие
|
||||
|
||||
[English](rule_request.md) | Русский
|
||||
|
||||
Укажите семейство безопасности, затронутые формы языка/API и подходящий CWE, если применимо. С какими существующими правилами есть пересечение? Предпочитайте расширение поддерживаемого детектора дублированию сигнала или увеличению рекламного счётчика правил.
|
||||
|
||||
<a id="detectable-shape-and-limits"></a>
|
||||
## Обнаруживаемая форма и ограничения
|
||||
|
||||
Опишите точный локальный синтаксис, который можно обнаружить без исполнения кода, сетевого доступа или новых core dependencies. Отделяйте deployment risks от подтверждённых уязвимостей. Перечислите случаи, требующие ручного, межпроцедурного review или проверки бизнес-логики.
|
||||
|
||||
<a id="independent-examples"></a>
|
||||
## Независимые примеры
|
||||
|
||||
Для каждой заявленной формы приведите как минимум два независимо написанных положительных и два безопасных/context-negative синтетических примера. Где применимо, включите comments, strings, одноимённые пользовательские функции, alias rebinding и более безопасные альтернативы.
|
||||
|
||||
<a id="remediation-and-sources"></a>
|
||||
## Исправление и источники
|
||||
|
||||
Объясните безопасное исправление с сохранением поведения service/checker и способ его проверки. Дайте ссылки на авторитетную документацию языка/API. Не отправляйте приватный игровой код, flags, secrets, logs или traffic. См. [участие в разработке](../../CONTRIBUTING-RU.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).
|
||||
@@ -0,0 +1,28 @@
|
||||
<a id="outcome-and-scope"></a>
|
||||
## Результат и область изменений
|
||||
|
||||
[English](PULL_REQUEST_TEMPLATE.md) | Русский
|
||||
|
||||
Опишите видимый пользователю результат, сохранённую совместимость и явные ограничения. Ссылайтесь на issues, не копируя приватные данные оператора.
|
||||
|
||||
<a id="verification"></a>
|
||||
## Проверки
|
||||
|
||||
- [ ] Запущены targeted tests и полный локальный suite; указаны точные результаты/skips.
|
||||
- [ ] Сохранены поведение CLI `0/1/2`, read-only defaults и сопоставимость scope.
|
||||
- [ ] У новых и изменённых правил есть независимые positive/negative cases и честно описанные ограничения.
|
||||
- [ ] Проходят проверки счётчиков каталога, стабильных anchors, локальных ссылок, английского текста и парных русских переводов; команды и примеры остаются идентичными.
|
||||
- [ ] Не добавлены исполнение цели, скрытый сетевой доступ или раскрытие секретов.
|
||||
- [ ] Изменения требуют разрешения, проверяют ownership и имеют ограниченный rollback.
|
||||
- [ ] Offline packaging и publication checks охватывают изменённые материалы.
|
||||
- [ ] Закреплённые версии сторонних исходников и образов, происхождение и лицензии остаются явными.
|
||||
|
||||
<a id="platform-and-evidence-boundaries"></a>
|
||||
## Платформы и границы свидетельств
|
||||
|
||||
Перечислите точные commits, platforms и выполненные tests. Невыполненные сценарии Mac, Docker Desktop, физических клиентов, непрерывного захвата и offline start отметьте NOT_RUN или BLOCKED. Не переносите на них выводы из синтетических Linux-проверок.
|
||||
|
||||
<a id="release-and-safety"></a>
|
||||
## Релиз и безопасность
|
||||
|
||||
Опишите требования migration/rollback, нерешённые условия релиза и действия оператора. Подтвердите отсутствие приватных endpoints, credentials, raw logs или PCAP в diff, предназначенной для публикации истории, screenshots, artifacts и обсуждении. Сообщение об уязвимости следует [SECURITY.md](../SECURITY-RU.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.
|
||||
@@ -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"
|
||||
+18
@@ -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
|
||||
@@ -0,0 +1,25 @@
|
||||
# История изменений
|
||||
|
||||
[English](CHANGELOG.md) | Русский
|
||||
|
||||
<a id="changelog"></a>
|
||||
<a id="unreleased"></a>
|
||||
## В разработке
|
||||
|
||||
- Последовательные 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 раздела по исправлению уязвимостей.
|
||||
|
||||
<a id="release-policy"></a>
|
||||
## Политика релизов
|
||||
|
||||
См. [версионирование](docs/development-RU.md#versioning). Core CI проверяет нативные инструменты, а не Docker Desktop, конкретный ноутбук или сеть соревнования.
|
||||
@@ -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.
|
||||
@@ -0,0 +1,29 @@
|
||||
<a id="contributing"></a>
|
||||
# Участие в разработке
|
||||
|
||||
[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.
|
||||
|
||||
<a id="rules-and-examples"></a>
|
||||
## Правила и примеры
|
||||
|
||||
Для каждого нового или существенно изменённого правила нужны как минимум два независимо написанных положительных и два безопасных/context-negative примера. Покройте все заявленные языковые формы, комментарии и строковые примеры, aliases/shadowing и безопасные альтернативы. Строки «до/после», скопированные только из метаданных правила, не являются независимым свидетельством.
|
||||
|
||||
Сохраняйте существующие rule IDs и явные anchors каталога. Изменённая семантика должна входить в scope отчёта, чтобы несовместимые сканирования нельзя было сравнить с ложным результатом «чисто». Описывайте, какие выводы правило сделать не может.
|
||||
|
||||
<a id="review-and-releases"></a>
|
||||
## Review и релизы
|
||||
|
||||
Записывайте точные закреплённые версии исходников и образов, а также платформы, на которых выполнялись проверки. Не приравнивайте CI к приёмке на целевом компьютере, Docker Desktop, физических клиентах, захвату трафика или офлайн-стеку. Для чувствительных сообщений следуйте [политике безопасности](SECURITY-RU.md) и сохраняйте указание авторства upstream.
|
||||
@@ -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.
|
||||
@@ -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.
|
||||
+100
@@ -0,0 +1,100 @@
|
||||
<a id="durkahelper"></a>
|
||||
# DurkaHelper
|
||||
|
||||
[English](README.md) | Русский
|
||||
|
||||
Офлайн-инструменты Defense для Attack/Defense CTF: разбор исходников, исследование трафика, проверка патчей и запуск общих командных инструментов из одного репозитория.
|
||||
|
||||
<a id="what-does-what"></a>
|
||||
## Что за что отвечает
|
||||
|
||||
| Инструмент | Для чего нужен |
|
||||
|---|---|
|
||||
| **Сканер DurkaHelper** | Найти подозрительный код/конфигурацию в **локальной копии исходников** и открыть инструкцию исправления. Удалённые хосты не сканирует, патчи не применяет. |
|
||||
| **Packmate** | Смотреть запросы/ответы и искать по трафику. На Docker Desktop — закрытые PCAP; LIVE — на разрешённом Linux-узле, который видит нужный трафик. |
|
||||
| **S4DFarm** | Собирать флаги, показывать их статус и отправлять в систему соревнования. |
|
||||
| **Neo** | Распределять командные скрипты между исполнителями и целями; передавать найденные флаги в S4DFarm. |
|
||||
|
||||
Защищаемые сервисы остаются на Vulnbox. Проверенные патчи применяйте там обычным способом развёртывания сервиса. Ферма обслуживает флаги, а не распространение патчей.
|
||||
|
||||
<a id="quick-start"></a>
|
||||
## Быстрый старт
|
||||
|
||||
Для разбора исходников достаточно 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: прогоните стек на своём ноутбуке.
|
||||
|
||||
<a id="during-the-game"></a>
|
||||
## Во время игры
|
||||
|
||||
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).
|
||||
|
||||
<a id="find-fix-and-verify"></a>
|
||||
## Найти, исправить и проверить
|
||||
|
||||
**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 |
|
||||
|
||||
<a id="development"></a>
|
||||
## Разработка
|
||||
|
||||
Тесты и 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).
|
||||
@@ -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).
|
||||
@@ -0,0 +1,24 @@
|
||||
<a id="security-policy"></a>
|
||||
# Политика безопасности
|
||||
|
||||
[English](SECURITY.md) | Русский
|
||||
|
||||
Используйте DurkaHelper только для разрешённого защитного review и инфраструктуры соревнований. Считайте деревья исходников, конфигурацию и отчёты недоверенными и чувствительными входными данными. Ядро не исполняет сканируемые исходники, не применяет патчи автоматически и не запускает эксплуатацию уязвимостей.
|
||||
|
||||
<a id="reporting-a-security-issue"></a>
|
||||
## Как сообщить о проблеме безопасности
|
||||
|
||||
**Не публикуйте** учётные данные, приватные адреса, реальные захваты трафика или неочищенный эксплойт против настоящего сервиса в публичном issue.
|
||||
|
||||
Проверенный приватный канал сообщений — **условие публикации**. Прежде чем открыть репозиторий, сопровождающий должен включить и проверить GitHub private vulnerability reporting либо описать здесь другой согласованный приватный канал. Этот репозиторий не утверждает, что приватные сообщения уже включены, и не указывает непроверенный email.
|
||||
|
||||
Если на странице Security в GitHub есть **Report a vulnerability**, перед отправкой убедитесь, что кнопка открывает приватную форму. Иначе запросите приватный контакт через публичный issue без содержательных подробностей; не включайте чувствительные данные до подтверждения канала.
|
||||
|
||||
Укажите затронутый commit, платформу, минимальное синтетическое воспроизведение, ожидаемое и наблюдаемое поведение, а также последствия. Удалите секреты из имён файлов, вывода и вложений.
|
||||
|
||||
<a id="supported-security-boundary"></a>
|
||||
## Поддерживаемая граница безопасности
|
||||
|
||||
Поддерживается только текущая сопровождаемая ревизия; перенос исправлений на старые закреплённые версии toolchain не обещается. У внешних интеграций сохраняются собственные upstream-политики и лицензии. Закрепление версии повышает воспроизводимость, но не обеспечивает постоянное устранение уязвимостей.
|
||||
|
||||
Особенно важно сообщать об исполнении исходников, раскрытии секретов, path traversal, обходе защиты от symlink/race, небезопасном восстановлении или перезаписи, обходе сравнения scope, непреднамеренном создании Docker-ресурсов и false negatives проверки публикации. Чистый статический scan или поиск секретов не доказывает безопасность.
|
||||
+21
@@ -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.
|
||||
@@ -0,0 +1,18 @@
|
||||
<a id="third-party-notices"></a>
|
||||
# Уведомления о сторонних компонентах
|
||||
|
||||
[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 внешние кеши и экспорты образов остаются приватными артефактами оператора. При обезличивании операторских данных не удаляйте указание авторства.
|
||||
@@ -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.
|
||||
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"files": [
|
||||
{
|
||||
"path": "service.json",
|
||||
"allow": [
|
||||
["service", "name"],
|
||||
["http", "port"],
|
||||
["logging", "level"]
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -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"
|
||||
}
|
||||
}
|
||||
@@ -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"
|
||||
}
|
||||
@@ -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."
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"schema": "durkahelper.scanner-context.v1",
|
||||
"infrastructure": ["docker-desktop", "compose", "vulnbox", "team-lan", "s4dfarm", "neo", "packmate"],
|
||||
"role": "both"
|
||||
}
|
||||
@@ -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"}
|
||||
]
|
||||
@@ -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"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
<a id="deployment-kit"></a>
|
||||
# Deployment kit
|
||||
|
||||
[English](README.md) | Русский
|
||||
|
||||
Для обычной работы используйте `durka.py`. Он связывает поддерживаемый deployment S4DFarm/Neo/Packmate, генерирует приватные пароли и автоматически обрабатывает внутренние ID/checksum образов.
|
||||
|
||||
<a id="configure-and-start"></a>
|
||||
## Настроить и запустить
|
||||
|
||||
```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`; это не выбор протокола для неизвестного соревнования.
|
||||
|
||||
<a id="change-event-settings"></a>
|
||||
## Изменить настройки площадки
|
||||
|
||||
Если изменились LAN-адреса, команды, отправка или IP сервиса Packmate, остановите стек, отредактируйте конфиг, примените настройки и снова запустите:
|
||||
|
||||
```bash
|
||||
python3 durka.py down
|
||||
python3 durka.py configure
|
||||
python3 durka.py up
|
||||
```
|
||||
|
||||
Редактируйте `local/durka.json` между первой и второй командой. Данные сохраняются, используются кешированные образы; скачивания/пересборки нет. Замена платформы или учётных данных требует отдельной подготовки.
|
||||
|
||||
<a id="traffic-and-shutdown"></a>
|
||||
## Трафик и остановка
|
||||
|
||||
```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.
|
||||
|
||||
<a id="advanced-tools"></a>
|
||||
## Расширенные инструменты
|
||||
|
||||
Они остаются для специальных операций, автоматизации и диагностики; это не дополнительные шаги знакомства с тулсетом:
|
||||
|
||||
| Скрипт | Назначение |
|
||||
|---|---|
|
||||
| `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 хоста не выполняется.
|
||||
|
||||
<a id="native-backup-and-quarantine-restore"></a>
|
||||
<a id="backup-and-recovery"></a>
|
||||
## 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 сохраняйте отдельно.
|
||||
|
||||
<a id="application-recovery-and-explicit-activation"></a>
|
||||
<a id="application-recovery"></a>
|
||||
## Восстановление приложений
|
||||
|
||||
```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.
|
||||
|
||||
<a id="approved-linux-container-namespace-live"></a>
|
||||
<a id="linux-container-namespace-live"></a>
|
||||
## 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)
|
||||
@@ -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.
|
||||
|
||||
<a id="native-backup-and-quarantine-restore"></a>
|
||||
## 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.
|
||||
|
||||
<a id="application-recovery-and-explicit-activation"></a>
|
||||
## 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.
|
||||
|
||||
<a id="approved-linux-container-namespace-live"></a>
|
||||
## 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)
|
||||
@@ -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"
|
||||
}
|
||||
@@ -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] == 0x0100000C and struct.unpack_from('<I', raw, 12)[0] == 2
|
||||
# Universal executables are accepted only with a bounded ARM64 slice.
|
||||
if raw[:4] in (b'\xca\xfe\xba\xbe', b'\xca\xfe\xba\xbf'):
|
||||
count = 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('<I', header, 4)[0] == cpu
|
||||
and struct.unpack_from('<I', header, 12)[0] == 2)
|
||||
return False
|
||||
finally:
|
||||
os.close(descriptor)
|
||||
|
||||
|
||||
def inspect(operator, config, neo_client=None):
|
||||
kit = operator.kit
|
||||
rows = []
|
||||
|
||||
def add(name, status, detail, next_step=''):
|
||||
rows.append(dict(check=name, status=status, detail=detail, guidance=next_step))
|
||||
|
||||
mac = platform.system() == 'Darwin'
|
||||
machine = platform.machine()
|
||||
version = platform.mac_ver()[0] if mac else ''
|
||||
add('macOS ARM64', 'READY' if mac and machine == 'arm64' and version else 'BLOCKED',
|
||||
('macOS ' + version + ' / ' + machine) if mac else 'This is not macOS; no Mac compatibility is inferred.',
|
||||
'Run on the approved Mac with native ARM64 Python (not a Rosetta shell).')
|
||||
add('Python', 'READY' if sys.version_info >= (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']
|
||||
@@ -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())
|
||||
@@ -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())
|
||||
@@ -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())
|
||||
@@ -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())
|
||||
@@ -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}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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("<IHHIIII", 0xa1b2c3d4, 2, 4, 0, 0, 65535, 1)
|
||||
CHECKS = {"postgres", "packmate-db", "candidate_redis_empty", "runtime_ownership",
|
||||
"farm_authenticated", "neo_authenticated", "packmate_authenticated",
|
||||
"packmate_capture_stopped", "restart_reconnect", "source_stopped", "stage_stopped"}
|
||||
LIMITS = ["new candidate Redis state intentionally reset; original RDBs retained in backup",
|
||||
"real traffic, team LAN, physical Mac and large-data RPO/RTO not validated",
|
||||
"no worker, submission or capture automatically enabled",
|
||||
"Neo authentication and native state restored; task execution requires a separate synthetic drill"]
|
||||
|
||||
|
||||
def selected(runtime, names=ACTIVE):
|
||||
result = copy.deepcopy(runtime)
|
||||
result["services"] = {name: result["services"][name] for name in names}
|
||||
return result
|
||||
|
||||
|
||||
def inputs(args, target):
|
||||
data = rec._promotion_inputs(args, target)
|
||||
backup, manifest, original, spec, runtime, profile, stage = data
|
||||
source, state, source_runtime, source_profile, _ = rec.source_workspace(args.workspace)
|
||||
if (state != original or source_runtime != runtime or source_profile != profile or
|
||||
state["project"] != manifest["source_project"]):
|
||||
raise Error("selected source does not match the verified backup")
|
||||
rec._separate_promotion_target(target, source)
|
||||
return data, (source, state["project"], runtime, args.daemon_id, kit.LABEL)
|
||||
|
||||
|
||||
def require_gates(args):
|
||||
rec.require_promotion_apply(args)
|
||||
if not args.discard_candidate_redis_state:
|
||||
raise Error("requires --discard-candidate-redis-state: new Redis queues, caches and sessions are reset; backup retained")
|
||||
|
||||
|
||||
def stopped(context, *, strict=False):
|
||||
current = rec.owned(*context, exclusive=False, strict_networks=strict)
|
||||
if any(value["running"] for value in current.values()):
|
||||
raise Error("source or verified recovery stage is running; stop it separately before recovery")
|
||||
return current
|
||||
|
||||
|
||||
def command(root, state):
|
||||
return kit.command(root, state, runtime=True)
|
||||
|
||||
|
||||
def prepare_files(args, target, data):
|
||||
backup, manifest, original, spec, runtime, profile, stage = data
|
||||
project = "dh-deploy-" + secrets.token_hex(6)
|
||||
projected = rec.reproject_spec(spec, project)
|
||||
images = kit.image_preflight(runtime, profile)
|
||||
kit.check_build_receipt(backup / "private", spec, images)
|
||||
projected_runtime = kit.runtime_spec(projected, images)
|
||||
context = (target, project, selected(projected_runtime), args.daemon_id, kit.LABEL)
|
||||
if rec.owned(*context, exclusive=False, require_no_networks=True):
|
||||
raise Error("new candidate project already has Docker resources")
|
||||
# The pinned Neo server image currently runs as root. Reject a changed
|
||||
# runtime identity rather than broadly chmod/chown restored bbolt files.
|
||||
user = json.loads(rec.run(["docker", "image", "inspect", "--format", "{{json .Config.User}}",
|
||||
images["neo-server"]]))
|
||||
if user not in ("", "0", "0:0", "root", "root:root"):
|
||||
raise Error("unsupported Neo runtime UID/GID; no ownership mutation attempted")
|
||||
staging = ops._StagingDirectory.create(target, ".application-recovery-")
|
||||
try:
|
||||
anchor, total = ops._root_anchor_identity(backup.stat()), [0, rec.MAX_TOTAL]
|
||||
for name, expected in sorted(manifest["files"].items()):
|
||||
if not name.startswith(("private/config/", "private/sources/")):
|
||||
continue
|
||||
destination = name[len("private/"):]
|
||||
meta, digest = ops._copy_stable(backup, name, (staging, destination), rec.MAX_FILE, total, anchor)
|
||||
if expected != {"bytes": meta.st_size, "sha256": digest}:
|
||||
raise Error("immutable recovery source changed")
|
||||
staging.set_file_metadata(destination, 0o644 if destination in {
|
||||
"config/neo-client.yml", "config/packmate.properties"} else 0o600)
|
||||
for name in (*rec.BACKENDS, "neo"):
|
||||
staging.mkdir("data/" + name)
|
||||
staging.mkdir("pcaps")
|
||||
# This is a closed empty file, never an automatic capture/import.
|
||||
staging.write_new_bytes("pcaps/" + profile["packmate"]["pcap_file"], EMPTY_PCAP, mode=0o644)
|
||||
relative = "cold/neo.tar"
|
||||
if rec.cold_members(backup / relative, staging=staging, directory="neo", source_root=backup,
|
||||
expected=manifest["files"][relative]) != manifest["cold"]["neo"]:
|
||||
raise Error("Neo cold state changed while restoring")
|
||||
generated = {"compose.json": projected, "runtime-compose.json": projected_runtime, "profile.json": profile}
|
||||
model = kit.model(projected, profile)
|
||||
generated.update({"model.json": model, "policy.json": kit.policy(profile, model),
|
||||
"build-receipt.json": {"schema": "durkahelper.deployment-build.v2", "images": images,
|
||||
"compose_sha256": rec.sha(kit.shared.canonical(projected)),
|
||||
"runtime_sha256": rec.sha(kit.shared.canonical(projected_runtime))}})
|
||||
for name, value in generated.items():
|
||||
staging.write_new_bytes(name, kit.shared.canonical(value))
|
||||
files = {name: value["sha256"] for name, value in rec.inventory(staging).items()
|
||||
if not name.startswith(("data/", "pcaps/"))}
|
||||
pending = {"schema": kit.SCHEMA, "project": project, "source_pins": kit.shared.PINS,
|
||||
"approval_id": args.approval_id, "files": files}
|
||||
staging.write_new_bytes("deployment.pending.json", ops._canonical(pending))
|
||||
state = {"schema": SCHEMA, "project": project, "source_project": original["project"],
|
||||
"stage_project": stage[1]["project"], "daemon_id": args.daemon_id,
|
||||
"backup_sha256": rec.sha(ops._canonical(manifest)),
|
||||
"stage_verification_sha256": stage[3]["verification_sha256"],
|
||||
"pending_sha256": rec.sha(ops._canonical(pending)),
|
||||
"owner": {"uid": args.target_uid, "gid": args.target_gid},
|
||||
"redis_policy": "DISCARD_CANDIDATE_ALL_STATE_BACKUP_RETAINED",
|
||||
"neo_runtime_owner": "0:0", "pcap_policy": "EMPTY_CLOSED_FILE_NO_AUTO_IMPORT"}
|
||||
staging.write_new_bytes("application-recovery.json", ops._canonical(state))
|
||||
# Validate once more before publishing a private, non-toolkit-runnable
|
||||
# candidate. No database service has been started at this point.
|
||||
if rec.verify_backup(backup)[1] != manifest:
|
||||
raise Error("backup changed during application recovery preparation")
|
||||
ops._publish_directory(staging, target)
|
||||
finally:
|
||||
staging.cleanup()
|
||||
# Only this exact newly published public-to-container directory needs
|
||||
# traversal by UID 65534. Its parent stays operator-only 0700.
|
||||
folder = ops._canonical_root_directory(target / "pcaps")
|
||||
fd = os.open(folder, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
|
||||
try:
|
||||
os.fchmod(fd, 0o755)
|
||||
finally:
|
||||
os.close(fd)
|
||||
return workspace(target)
|
||||
|
||||
|
||||
def workspace(path):
|
||||
root = rec.private_root(path)
|
||||
state = kit.load(root / "application-recovery.json")
|
||||
fields = {"schema", "project", "source_project", "stage_project", "daemon_id", "backup_sha256",
|
||||
"stage_verification_sha256", "pending_sha256", "owner", "redis_policy", "neo_runtime_owner", "pcap_policy"}
|
||||
ops._strict_keys(state, fields, fields, "application recovery")
|
||||
if (state["schema"] != SCHEMA or not re.fullmatch(r"dh-deploy-[a-f0-9]{12}", state["project"]) or
|
||||
not re.fullmatch(r"dh-deploy-[a-f0-9]{12}", state["source_project"]) or
|
||||
state["project"] == state["source_project"] or
|
||||
not re.fullmatch(r"dh-recovery-[a-f0-9]{12}", state["stage_project"]) or
|
||||
not re.fullmatch(r"[A-Za-z0-9:_.-]{8,128}", state["daemon_id"]) or
|
||||
any(not re.fullmatch(r"[a-f0-9]{64}", state[name]) for name in
|
||||
("backup_sha256", "stage_verification_sha256", "pending_sha256")) or
|
||||
state["owner"] != {"uid": root.stat().st_uid, "gid": root.stat().st_gid} or
|
||||
state["redis_policy"] != "DISCARD_CANDIDATE_ALL_STATE_BACKUP_RETAINED" or
|
||||
state["neo_runtime_owner"] != "0:0" or state["pcap_policy"] != "EMPTY_CLOSED_FILE_NO_AUTO_IMPORT"):
|
||||
raise Error("application recovery identity or ownership contract changed")
|
||||
pending = kit.load(root / "deployment.pending.json")
|
||||
ops._strict_keys(pending, {"schema", "project", "source_pins", "approval_id", "files"},
|
||||
{"schema", "project", "source_pins", "approval_id", "files"}, "pending deployment")
|
||||
if (rec.sha(ops._canonical(pending)) != state["pending_sha256"] or pending["schema"] != kit.SCHEMA or
|
||||
pending["project"] != state["project"] or pending["source_pins"] != kit.shared.PINS or
|
||||
not isinstance(pending["files"], dict) or not 1 <= len(pending["files"]) <= rec.MAX_FILES):
|
||||
raise Error("application recovery pending manifest changed")
|
||||
anchor = ops._root_anchor_identity(root.stat())
|
||||
for name, digest in pending["files"].items():
|
||||
ops._portable_relative_posix(name, "pending recovery member")
|
||||
if name.startswith(("data/", "pcaps/")) or not re.fullmatch(r"[a-f0-9]{64}", digest):
|
||||
raise Error("invalid recovery immutable member")
|
||||
metadata, observed = ops._hash_anchored_regular(root, name, anchor, rec.MAX_FILE)
|
||||
if observed != digest or metadata.st_uid != state["owner"]["uid"]:
|
||||
raise Error("application recovery immutable input changed")
|
||||
for folder in ("data", *["data/" + name for name in (*rec.BACKENDS, "neo")], "pcaps"):
|
||||
if ops._canonical_root_directory(root / folder) != root / folder:
|
||||
raise Error("linked recovery data directory")
|
||||
runtime = rec.maintained_runtime(root, pending, kit.load(root / "compose.json"), kit.validate_profile(kit.load(root / "profile.json")))
|
||||
return root, state, pending, runtime, kit.load(root / "profile.json")
|
||||
|
||||
|
||||
def ready(identity, database):
|
||||
deadline = time.monotonic() + 60
|
||||
while True:
|
||||
try:
|
||||
if database:
|
||||
rec.run(["docker", "exec", identity, "pg_isready", "-h", "127.0.0.1", "-U", database, "-d", database], timeout=5)
|
||||
elif rec.run(["docker", "exec", identity, "redis-cli", "--raw", "PING"], timeout=5).strip() != b"PONG":
|
||||
raise Error("candidate Redis not ready")
|
||||
return
|
||||
except Error:
|
||||
if time.monotonic() >= 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())
|
||||
@@ -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())
|
||||
@@ -0,0 +1,170 @@
|
||||
<a id="administrator-workflows"></a>
|
||||
# Рабочие процессы администратора
|
||||
|
||||
[English](ADMIN_WORKFLOWS.md) | Русский
|
||||
|
||||
Практический маршрут для одного администратора и доверенной команды. Карточки и ручное переписывание hashes не требуются. Сохраните этот checkout, русские инструкции и приватные зависимости для офлайн-работы. [Короткая памятка для печати](TEAM_LAN_ADMIN_CHEATSHEET-RU.md).
|
||||
|
||||
<a id="roles-and-command-conventions"></a>
|
||||
## Роли и правила выполнения команд
|
||||
|
||||
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`.
|
||||
|
||||
<a id="workflow-01--deploy-and-prepare-offline"></a>
|
||||
## 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).
|
||||
|
||||
<a id="workflow-02--scan-patch-and-verify"></a>
|
||||
## 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) относится к стеку тулсета, а не любому защищаемому сервису.
|
||||
|
||||
<a id="workflow-03--prepare-scripts-and-neo-execution"></a>
|
||||
## 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.
|
||||
|
||||
<a id="workflow-04--farm-and-jury-submission"></a>
|
||||
## 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` отправка включается явно снова. Перед включением проверьте восстановленные очереди: нельзя слепо переотправлять просроченные данные.
|
||||
|
||||
<a id="workflow-05--packmate-live-or-file"></a>
|
||||
## 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 нужно проверить отдельно, прежде чем полагаться на него.
|
||||
|
||||
<a id="final-operator-checks"></a>
|
||||
## Финальные проверки оператора
|
||||
|
||||
Войдите с каждого участвующего устройства; выполните полезное действие UI и переподключение. Проверьте фактическую среду каждого скрипта, приём Farm → жюри, разрешённый LIVE либо closed FILE, офлайн-перезапуск под обычной нагрузкой. Маршруты события, capture permission и настройки организаторов проверяются на конкретном соревновании. Linux tests и hosted macOS CI не доказывают совместимость Docker Desktop, командной LAN или локальных правил. Невыполненные проверки — **NOT TESTED**, не готовность.
|
||||
@@ -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.
|
||||
@@ -0,0 +1,28 @@
|
||||
# Возможности и ограничения
|
||||
|
||||
[English](CAPABILITY_INVENTORY.md) | Русский
|
||||
|
||||
<a id="capabilities-and-limits"></a>
|
||||
|
||||
Для установки используйте [основную инструкцию](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 нужно установить и кешировать заранее; одной копии репозитория мало |
|
||||
|
||||
<a id="support"></a>
|
||||
## Поддержка
|
||||
|
||||
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 не доказывает безопасность сервиса. Успех в лаборатории не доказывает, что сеть соревнования разрешает захват или что все участники имеют доступ к инструментам.
|
||||
@@ -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.
|
||||
@@ -0,0 +1,107 @@
|
||||
<a id="first-mac-run"></a>
|
||||
# Первый запуск на Mac
|
||||
|
||||
[English](MACOS_FIRST_RUN.md) | Русский
|
||||
|
||||
Это короткий маршрут оператора, а не заявление о готовности ноутбука. Все шаги с runtime Mac ниже имеют статус **PENDING: требуется проверка на реальном Mac**. Выполняйте их только после согласования Docker Desktop, локальных сервисов, Ethernet. Подробная установка, поля конфигурации и backup описаны в [полном руководстве](MACOS_FULL_DEPLOYMENT_AND_TESTING-RU.md).
|
||||
|
||||
<a id="1-read-only-preflight"></a>
|
||||
## 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 ГиБ, затем измерьте нагрузку.
|
||||
|
||||
<a id="2-first-setup-while-online"></a>
|
||||
## 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.
|
||||
|
||||
<a id="3-start-and-check-the-tools"></a>
|
||||
## 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 на трансляцию.
|
||||
|
||||
<a id="4-synthetic-end-to-end-checks"></a>
|
||||
## 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 отправки.
|
||||
|
||||
<a id="5-offline-restart-and-workload-rehearsal"></a>
|
||||
## 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 и совместимость с локальными правилами.
|
||||
|
||||
<a id="6-failures-and-safe-shutdown"></a>
|
||||
## 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.
|
||||
|
||||
<a id="remaining-manual-gates"></a>
|
||||
## Оставшиеся ручные 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 восстановленных очередей остаётся выключен до проверки.
|
||||
@@ -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.
|
||||
@@ -0,0 +1,167 @@
|
||||
<a id="set-up-and-run-the-team-tools-on-macos"></a>
|
||||
# Установка и работа командных инструментов на 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.
|
||||
|
||||
<a id="1-know-the-layout"></a>
|
||||
## 1. Как устроено
|
||||
|
||||
DurkaHelper запускается нативно в Python. Docker Desktop поднимает S4DFarm, координатор/worker Neo и Packmate FILE. Защищаемые сервисы остаются на Vulnbox в Ethernet-сети. Ноутбук обслуживает инструменты, а не развёртывание защищаемых сервисов.
|
||||
|
||||
Ферма = флаги и отправка. Neo = распределение/исполнение скриптов. Packmate = анализ трафика. Сканер = разбор локальных исходников. [Схема связей](team-setup-RU.md).
|
||||
|
||||
<a id="2-install-prerequisites"></a>
|
||||
## 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.
|
||||
|
||||
|
||||
<a id="3-clone-and-configure"></a>
|
||||
## 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 — отдельная подготовка.
|
||||
|
||||
<a id="4-prepare-while-internet-is-available"></a>
|
||||
## 4. Подготовить при доступном Интернете
|
||||
|
||||
```bash
|
||||
python3 durka.py setup
|
||||
```
|
||||
|
||||
Команда получает закреплённые версии исходников/образов, готовит приватный workspace и собирает ферму/Neo. Это может занять несколько минут. Проверки версий и образов выполняются автоматически; переписывать checksum руками не нужно.
|
||||
|
||||
Выполняйте подготовку на машине, с которой будете работать. Linux amd64-кеш не содержит нативные зависимости Mac и не подтверждает скорость Apple Silicon. До отключения сохраните Docker Desktop, Python, репозиторий, образы, клиент Neo и нужные скрипты/зависимости.
|
||||
|
||||
<a id="5-start-and-check-access"></a>
|
||||
## 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.
|
||||
|
||||
<a id="6-traffic-and-scripts"></a>
|
||||
## 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 с реальными зависимостями скриптов. Им нужны маршруты до координатора, фермы и разрешённых сервисов-целей.
|
||||
|
||||
<a id="7-enable-submission-and-defend"></a>
|
||||
## 7. Включить отправку и защищать
|
||||
|
||||
После проверки реального адаптера, endpoint, формата флага и списка команд:
|
||||
|
||||
```bash
|
||||
python3 durka.py submit
|
||||
```
|
||||
|
||||
Смотрите accepted/rejected/expired в ферме. Доступный UI ещё не означает принятие флагов соревнованием.
|
||||
|
||||
Для каждого сервиса скопируйте исходники с Vulnbox в приватный рабочий каталог и запустите скан:
|
||||
|
||||
```bash
|
||||
python3 durka.py scan /path/to/service --patches
|
||||
```
|
||||
|
||||
Прочитайте связанную инструкцию, сохраните оригинал, примените небольшой патч на Vulnbox и проверьте доступность/checker. Повторите скан исходников. Сканер читает файлы; по SSH в цели не заходит, код не запускает и фиксы не развёртывает.
|
||||
|
||||
<a id="8-rehearse-offline-and-with-load"></a>
|
||||
## 8. Прогнать офлайн и под нагрузкой
|
||||
|
||||
Дома используйте Mac и отдельный ПК в проводной LAN: войдите в ферму/Packmate, подключите Neo, импортируйте известный трафик, выполните безвредный скрипт и переподключитесь после перезапуска своего приложения. Затем отключите Интернет, сохранив LAN, и повторите запуск/работу.
|
||||
|
||||
Проверьте инструменты под обычной нагрузкой не менее 60 минут. Следите за памятью/CPU Docker, ростом PCAP/БД и свободным диском. На событии повторите проверку доступа каждого устройства и выберите подготовленный разрешённый источник трафика.
|
||||
|
||||
<a id="9-backup-stop-and-recover"></a>
|
||||
## 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`.
|
||||
|
||||
<a id="10-common-problems"></a>
|
||||
## 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 и общих образов — отдельная задача администрирования машины.
|
||||
@@ -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.
|
||||
@@ -0,0 +1,36 @@
|
||||
<a id="documentation"></a>
|
||||
# Документация
|
||||
|
||||
[English](README.md) | Русский
|
||||
|
||||
Начните со своей роли. У английских страниц есть русский перевод рядом; обе версии доступны офлайн.
|
||||
|
||||
<a id="main-routes"></a>
|
||||
## Основные маршруты
|
||||
|
||||
| Ваша задача | Что читать |
|
||||
|---|---|
|
||||
| Поднять общие инструменты | [Последовательные 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) |
|
||||
|
||||
<a id="how-the-stack-fits-together"></a>
|
||||
## Как связан стек
|
||||
|
||||
[Схема команды](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 в этом маршруте нет.
|
||||
|
||||
<a id="references"></a>
|
||||
## Справочники
|
||||
|
||||
| Тема | Страницы |
|
||||
|---|---|
|
||||
| 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. Открывайте эти справочники по необходимости; это не дополнительные шаги для каждого участника.
|
||||
@@ -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.
|
||||
@@ -0,0 +1,97 @@
|
||||
<a id="administrator-cheat-sheet"></a>
|
||||
# Шпаргалка администратора
|
||||
|
||||
[English](TEAM_LAN_ADMIN_CHEATSHEET.md) | Русский
|
||||
|
||||
Вы поднимаете общую ферму, координатор Neo и Packmate. После настройки для обычной работы нужны эти команды, а не форма валидации. Распечатайте страницу и сохраните [workflow 01–05](ADMIN_WORKFLOWS-RU.md) офлайн.
|
||||
|
||||
<a id="start"></a>
|
||||
## Запуск
|
||||
|
||||
Запустите 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.
|
||||
|
||||
<a id="share-access"></a>
|
||||
## Выдать доступ
|
||||
|
||||
| Что передать участникам | Откуда взять |
|
||||
|---|---|
|
||||
| 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).
|
||||
|
||||
<a id="enable-work"></a>
|
||||
## Включить работу
|
||||
|
||||
Когда скрипты/зависимости готовы:
|
||||
|
||||
```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 не означает приём жюри. Патчи применяются штатным механизмом сервиса.
|
||||
|
||||
<a id="traffic"></a>
|
||||
## Трафик
|
||||
|
||||
Для закрытого 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.
|
||||
|
||||
<a id="check-the-team"></a>
|
||||
## Проверить команду
|
||||
|
||||
Дома используйте Mac и отдельный ПК. На соревновании повторите с каждым рабочим устройством:
|
||||
|
||||
- Войти в ферму и Packmate по LAN-адресам.
|
||||
- Найти один и тот же известный запрос/ответ в Packmate.
|
||||
- Подключить клиент Neo, выполнить согласованный безвредный скрипт и увидеть результат.
|
||||
- Переподключиться после обрыва клиента или перезапуска своего приложения.
|
||||
- Держать обычную нагрузку; следить за памятью и диском.
|
||||
|
||||
Заполнять форму не требуется. Исправьте ошибки до использования этого устройства/маршрута.
|
||||
|
||||
<a id="if-something-breaks"></a>
|
||||
## Если что-то сломалось
|
||||
|
||||
| Симптом | Что проверить |
|
||||
|---|---|
|
||||
| Все 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.
|
||||
|
||||
<a id="finish"></a>
|
||||
## Завершение
|
||||
|
||||
Остановите новые скрипты/захват, сохраните backups, затем:
|
||||
|
||||
```bash
|
||||
python3 durka.py --config "$DURKA_CONFIG" down
|
||||
```
|
||||
|
||||
Данные и образы сохраняются. Не используйте общий prune и `down -v`. [Полная установка](MACOS_FULL_DEPLOYMENT_AND_TESTING-RU.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).
|
||||
@@ -0,0 +1,33 @@
|
||||
<a id="review-an-owned-service"></a>
|
||||
# Review своего сервиса
|
||||
|
||||
[English](code-review.md) | Русский
|
||||
|
||||
Работайте с локальной копией исходников, которую вам разрешено проверять. Используйте [сканер](offline-scanner-RU.md) и [каталог](vulnerabilities/README-RU.md), чтобы найти конкретные места для review.
|
||||
|
||||
<a id="identify-startup-and-dependencies"></a>
|
||||
## Определите запуск и зависимости
|
||||
|
||||
Свидетельство: `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.
|
||||
|
||||
<a id="trace-a-request"></a>
|
||||
## Проследите запрос
|
||||
|
||||
1. Источник ввода: body, URL, cookie, header, сохранённая запись, задача или файл.
|
||||
2. Проверенный субъект и разрешение на конкретный объект.
|
||||
3. Разбор, нормализация, сериализация, шаблоны и преобразования типов.
|
||||
4. Чувствительная операция и её фактические аргументы.
|
||||
5. Исключения, callbacks, awaits и альтернативные пути к той же операции.
|
||||
|
||||
Ручные рецепты rg показывают, с чего начать; отсутствие совпадений не подтверждает безопасность. Сопоставьте обычный собственный запрос с разрешёнными логами/PCAP, затем воспроизведите один инвариант на изолированной копии. У запрещённой операции не должно быть запрещённого побочного эффекта.
|
||||
|
||||
После минимального совместимого патча повторите регрессионный тест, обычный пользовательский сценарий и чтение старых записей. Следуйте [процедуре deployment и rollback](patch-validation-RU.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).
|
||||
@@ -0,0 +1,23 @@
|
||||
<a id="competition-scope-and-rules"></a>
|
||||
# Область и правила соревнования
|
||||
|
||||
[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 и инфраструктурных инструментов явно указаны другие эффекты.
|
||||
@@ -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.
|
||||
@@ -0,0 +1,44 @@
|
||||
<a id="defense-operator-workflow"></a>
|
||||
# Рабочий процесс оператора защиты
|
||||
|
||||
[English](defense.md) | Русский
|
||||
|
||||
[Шпаргалка](defense-cheatsheet-RU.md) · [Каталог](vulnerabilities/README-RU.md) · [Проверка патчей](patch-validation-RU.md)
|
||||
|
||||
<a id="before-the-first-change"></a>
|
||||
## До первого изменения
|
||||
|
||||
Подтвердите разрешённую область и [контракт соревнования](competition-rules-RU.md). Назначьте одного ответственного за deployment каждого сервиса. Запишите фактическую ревизию кода/образа, механизм запуска, источники конфигурации, нужные порты, расположение данных и способ rollback.
|
||||
|
||||
Выполните обычную пользовательскую операцию и сохраните синтетические или разрешённые старые записи для регрессионных проверок. Исправный health endpoint не доказывает работу входа, авторизации, сохранения данных или совместимость с checker.
|
||||
|
||||
Создайте ограниченный [baseline](local-tools-RU.md#defense-operations), scan исходников и согласованный health profile. Сохраняйте read-only копии исходников; никогда не используйте общий inventory процессов/контейнеров для раскрытия посторонних workloads.
|
||||
|
||||
<a id="repeated-loop"></a>
|
||||
## Повторяющийся цикл
|
||||
|
||||
1. Следите за статусом checker, явно заданными health checks и поведением приложения.
|
||||
2. Сравнивайте snapshots для выявления изменений файлов, конфигурации, процессов и listeners.
|
||||
3. Локально изучайте минимальный нужный интервал логов и трафика.
|
||||
4. Проследите подозрительную операцию до инварианта в исходниках.
|
||||
5. Добавьте падающий регрессионный тест и внесите минимальный совместимый патч.
|
||||
6. Повторите проверки владельца/другого пользователя/анонимного пользователя, старых данных и доступности.
|
||||
7. Разверните через отрепетированный процесс; наблюдайте и откатите код/образ при регрессии.
|
||||
|
||||
Не меняйте попутно ключи, схемы, runtime и не удаляйте функциональность. Старые данные, созданные в последующих раундах, должны пережить rollback кода.
|
||||
|
||||
<a id="triage-and-evidence"></a>
|
||||
## Разбор подозрений и свидетельства
|
||||
|
||||
Находка сканера или подозрительно выглядящий запрос — гипотеза, а не доказательство компрометации. Сравните с нормальным трафиком, 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. Диагностические терминалы и интерфейсы с секретами остаются приватными.
|
||||
|
||||
<a id="recovery"></a>
|
||||
## Восстановление
|
||||
|
||||
Проверьте резервную копию, прежде чем на неё полагаться. Восстановите в новую изолированную staging-среду и проверьте данные и функциональность до любого согласованного production-действия. Используйте нативные dumps БД или контролируемые консистентные cold copies; копия живого файла БД не является надёжным backup.
|
||||
|
||||
Начальные цели репетиции: RPO пять минут и RTO десять минут, измеряемые для каждого компонента. Синтетические прогоны длительностью меньше секунды не доказывают достижение этих целей на реальном объёме данных. Submission и workers остаются остановленными до review восстановленных и просроченных очередей.
|
||||
|
||||
При неполных свидетельствах указывайте partial/blocked вместо «безопасно». Для эксплуатационных сбоев используйте [runbook игрового дня](game-day-RU.md), для доступа к общим инструментам — [шпаргалку администратора](TEAM_LAN_ADMIN_CHEATSHEET-RU.md).
|
||||
@@ -0,0 +1,21 @@
|
||||
<a id="defender-quick-sheet"></a>
|
||||
# Краткая шпаргалка защитника
|
||||
|
||||
[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.
|
||||
@@ -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.
|
||||
@@ -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.
|
||||
@@ -0,0 +1,64 @@
|
||||
<a id="development-contracts-and-rule-coverage"></a>
|
||||
# Разработка, контракты и покрытие правил
|
||||
|
||||
[English](development.md) | Русский
|
||||
|
||||
[Руководство для участников](../CONTRIBUTING-RU.md) · [Релизный чеклист](release-checklist-RU.md)
|
||||
|
||||
<a id="architecture"></a>
|
||||
## Архитектура
|
||||
|
||||
Ядро остаётся на стандартной библиотеке 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.
|
||||
|
||||
<a id="add-or-change-a-rule"></a>
|
||||
## Добавление или изменение правила
|
||||
|
||||
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 и вывод без секретов входят в обязательную регрессию.
|
||||
|
||||
<a id="versioning"></a>
|
||||
## Версионирование
|
||||
|
||||
Версии 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.
|
||||
|
||||
<a id="evidence-and-ci"></a>
|
||||
## Свидетельства и CI
|
||||
|
||||
Записывайте commit/tree, platform/interpreter, версии инструментов, команды, scope, результаты и ограничения. Проверяйте точно распакованный bundle, а не только checkout. Исторические свидетельства — неизменяемый контекст, а не сертификация следующего commit.
|
||||
|
||||
Ручной macOS ARM64 workflow — один ограниченный job на standard runner с минимальными permissions и закреплёнными action SHAs. Он проверяет архитектуру, тесты ядра, CLI и упаковку; он не обращается к приватным тестовым хостам и не валидирует Docker Desktop или физических LAN-клиентов. Используйте только включённую квоту и перед dispatch проверяйте, что платные расходы отключены.
|
||||
@@ -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.
|
||||
@@ -0,0 +1,59 @@
|
||||
<a id="game-day-runbook"></a>
|
||||
# Runbook игрового дня
|
||||
|
||||
[English](game-day.md) | Русский
|
||||
|
||||
Это краткое руководство по работе после успешной [репетиции развёртывания](MACOS_FULL_DEPLOYMENT_AND_TESTING-RU.md). Соблюдайте область разрешений организаторов и назначайте одного ответственного за deployment каждого сервиса.
|
||||
|
||||
<a id="receive-a-service"></a>
|
||||
## Получение сервиса
|
||||
|
||||
Найдите настоящие пути его исходников, запуска, конфигурации и данных, а также неизменяемую ревизию. Держите проекты игровых сервисов отдельно от проектов командных 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 исходников.
|
||||
|
||||
<a id="availability-failure"></a>
|
||||
## Сбой доступности
|
||||
|
||||
Сохраните время сбоя и последнее изменение. Изучайте только состояние затронутого проекта, здоровье зависимостей и ограниченные приватные логи; логи могут содержать секреты и должны оставаться вне публичного экспорта evidence. На общих системах избегайте общих списков всех контейнеров и процессов хоста.
|
||||
|
||||
| Симптом | Следующая проверка |
|
||||
|---|---|
|
||||
| Компонент остановлен или перезапускается | Причина выхода, параметры запуска, готовность зависимостей |
|
||||
| UI работает, но действия не проходят | База данных, persistence, точный API и аутентификация |
|
||||
| На хосте работает, teammate не подключается | Ethernet-адрес, опубликованный порт, политика хоста, путь клиента |
|
||||
| Сбой начался после патча | Точный diff и отрепетированный rollback кода/образа |
|
||||
| Health проходит, checker падает | Настоящая семантика checker, обычный сценарий и старые данные |
|
||||
| Очередь не движется | Согласованный протокол, лимиты, ответ receiver и состояние submission |
|
||||
| Neo не подключается | Правильная версия клиента, адрес/key coordinator и доступность farm |
|
||||
| Packmate не показывает streams | Видимость источника, режим, регистрация сервиса и временное окно |
|
||||
|
||||
Перезапуск не восстанавливает потерянные данные. Не используйте down -v, не удаляйте volumes и не меняйте сеть на основании подозрения. Перед перезапуском разберитесь с сохранением данных.
|
||||
|
||||
<a id="suspicious-traffic"></a>
|
||||
## Подозрительный трафик
|
||||
|
||||
Используйте согласованную точку наблюдения и короткий временной интервал. Сравните request/response, method/path, типы параметров, size/status и события приложения с нормальным поведением. Сохраняйте только необходимые приватные свидетельства.
|
||||
|
||||
Общая LAN не означает видимость пакетов. UI Packmate без известного request/response не подтверждает рабочий захват. Импорт FILE — запасной вариант, а не доказательство непрерывного LIVE-анализа.
|
||||
|
||||
<a id="patch-loop"></a>
|
||||
## Цикл патча
|
||||
|
||||
[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).
|
||||
@@ -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).
|
||||
@@ -0,0 +1,95 @@
|
||||
<a id="local-tools-and-cli-reference"></a>
|
||||
# Локальные инструменты и справочник 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).
|
||||
|
||||
<a id="defense-operations"></a>
|
||||
## Защитные операции
|
||||
|
||||
`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
|
||||
```
|
||||
|
||||
<a id="backup-and-staging-restore"></a>
|
||||
## 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-путь изменения данных.
|
||||
|
||||
<a id="deployment-audit"></a>
|
||||
## Аудит 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 и эмуляции.
|
||||
|
||||
<a id="patch-evidence-timelines-and-export"></a>
|
||||
## Свидетельства патча, 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
|
||||
```
|
||||
|
||||
<a id="small-standalone-utilities"></a>
|
||||
## Небольшие самостоятельные утилиты
|
||||
|
||||
| Утилита | Назначение / ограничения |
|
||||
|---|---|
|
||||
| [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 и значения.
|
||||
@@ -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.
|
||||
+169
@@ -0,0 +1,169 @@
|
||||
<a id="neo-distribute-and-run-team-scripts"></a>
|
||||
# Neo: распределить и выполнить командные скрипты
|
||||
|
||||
[English](neo.md) | Русский
|
||||
|
||||
Neo хранит командные скрипты на координаторе и распределяет исполнение между подключёнными workers и командами из списка фермы. Workers передают подходящие флаги в S4DFarm. Это полезно, когда одному ноутбуку не нужно запускать каждый скрипт против каждой цели. Защитные патчи Neo не развёртывает.
|
||||
|
||||
<a id="administrator"></a>
|
||||
## Администратор
|
||||
|
||||
`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 адрес недоступен.
|
||||
|
||||
<a id="install-a-client"></a>
|
||||
## Установить клиент
|
||||
|
||||
Используйте [релиз 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: "<ADMIN_ETHERNET_IPV4>:5005"
|
||||
grpc_auth_key: "<PRIVATE_NEO_KEY_FROM_ADMIN>"
|
||||
exploit_dir: "exploits"
|
||||
```
|
||||
|
||||
Замените placeholders; конфиг приватный. Если macOS запросит разрешение, используйте обычную процедуру допуска приложений. Не показывайте ключ в скриншотах и аргументах shell.
|
||||
|
||||
```bash
|
||||
./neo --verbose=false --config client_config.yml --help
|
||||
```
|
||||
|
||||
<a id="first-harmless-task"></a>
|
||||
## Первое безвредное задание
|
||||
|
||||
Создайте в редакторе `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-сообщение; периодическое исполнение остаётся выключенным.
|
||||
|
||||
<a id="real-scripts-and-recurring-execution"></a>
|
||||
## Настоящие скрипты и периодическое исполнение
|
||||
|
||||
Скрипт получает IP цели первым аргументом. Нужны доступный interpreter/shebang и flush stdout; флаги нужного формата идут в ферму. Сначала локальный тест. Не загружайте недоверенные скрипты в workers.
|
||||
|
||||
Зарегистрируйте скрипт с явными ID, interval и timeout той же disabled-first командой `add`. После успешного разрешённого single-прогона включите или выключите этот ID:
|
||||
|
||||
```bash
|
||||
./neo --verbose=false --config client_config.yml enable <TASK_ID>
|
||||
./neo --verbose=false --config client_config.yml disable <TASK_ID>
|
||||
```
|
||||
|
||||
При добавлении существующего 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 нужно прогнать на самой машине.
|
||||
|
||||
<a id="team-workflow-clients-coordinator-and-workers"></a>
|
||||
## Командный 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 фермы. Успех подтверждается ответом жюрейки; напечатанного значения или записи в очереди недостаточно.
|
||||
|
||||
<a id="one-shot-and-scheduled-harmless-example"></a>
|
||||
### Безвредный пример: один раз и по расписанию
|
||||
|
||||
Используйте `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: один сервер исполнителем не является.
|
||||
|
||||
<a id="troubleshooting"></a>
|
||||
## Диагностика
|
||||
|
||||
| Симптом | Что проверить |
|
||||
|---|---|
|
||||
| Не проходит вход | Точный 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)
|
||||
+161
@@ -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: "<ADMIN_ETHERNET_IPV4>:5005"
|
||||
grpc_auth_key: "<PRIVATE_NEO_KEY_FROM_ADMIN>"
|
||||
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 <TASK_ID>
|
||||
./neo --verbose=false --config client_config.yml disable <TASK_ID>
|
||||
```
|
||||
|
||||
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)
|
||||
@@ -0,0 +1,66 @@
|
||||
# Офлайн-работа
|
||||
|
||||
[English](offline-bundles.md) | Русский
|
||||
|
||||
<a id="offline-operation"></a>
|
||||
<a id="prepare-the-machine-once"></a>
|
||||
## Подготовьте машину заранее
|
||||
|
||||
Сканеру нужен Python 3.10+; полному стеку — ещё Docker и кешированные образы. Установите их при наличии Интернета. Пройдите [установку на Mac](MACOS_FULL_DEPLOYMENT_AND_TESTING-RU.md), завершите `durka.py setup`, поднимите стек и проверьте его до выезда.
|
||||
|
||||
Сохраните репозиторий, приватный каталог `local/` и Docker data. Перед офлайн-запуском не удаляйте образы, не сбрасывайте Docker Desktop и не запускайте cleanup/prune. Setup может скачивать и собирать; обычный запуск использует подготовленные образы и не должен незаметно делать pull.
|
||||
|
||||
<a id="rehearse-without-internet"></a>
|
||||
## Репетиция без Интернета
|
||||
|
||||
<a id="prepare-clean-event-state-after-a-rehearsal"></a>
|
||||
### Чистое окружение соревнования после репетиции
|
||||
|
||||
Не удаляйте подготовленный 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.
|
||||
|
||||
<a id="optional-core-archive"></a>
|
||||
## Необязательный архив 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 в нём тоже нет. Проверка автоматическая; для обычной работы переписывать хеш не нужно.
|
||||
|
||||
<a id="moving-an-external-cache"></a>
|
||||
## Перенос внешнего кеша
|
||||
|
||||
Для другой машины есть расширенные утилиты 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.
|
||||
@@ -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.
|
||||
@@ -0,0 +1,121 @@
|
||||
<a id="offline-source-scanner"></a>
|
||||
# Офлайн-сканер исходников
|
||||
|
||||
[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-анализа.
|
||||
|
||||
<a id="safe-first-scan"></a>
|
||||
## Первый безопасный 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, а не правила из сканируемого каталога. Не устанавливайте зависимости и не импортируйте цель только ради её изучения.
|
||||
|
||||
<a id="reading-a-finding"></a>
|
||||
## Как читать находку
|
||||
|
||||
Каждая находка содержит путь относительно 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 и проверяйте поведение.
|
||||
|
||||
<a id="infrastructure-context"></a>
|
||||
## Контекст инфраструктуры
|
||||
|
||||
Необязательный [пример 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 отчёта.
|
||||
|
||||
<a id="inputs-and-limits"></a>
|
||||
## Входы и ограничения
|
||||
|
||||
Поддерживаемые семейства исходников и конфигурации: 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.
|
||||
|
||||
<a id="json-scope-and-comparison"></a>
|
||||
## 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; также отсутствие поддерживаемых входов |
|
||||
|
||||
<a id="coverage-and-next-steps"></a>
|
||||
## Покрытие и следующие шаги
|
||||
|
||||
Свидетельство: `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.
|
||||
|
||||
<a id="framework-and-database-boundaries"></a>
|
||||
|
||||
## Границы 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 вручную заполнять не нужно.
|
||||
@@ -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.
|
||||
@@ -0,0 +1,74 @@
|
||||
<a id="packmate-inspect-traffic"></a>
|
||||
# Packmate: разбор трафика
|
||||
|
||||
[English](packmate.md) | Русский
|
||||
|
||||
Packmate показывает запросы/ответы и ищет по содержимому потоков. Он помогает защитнику распознать атаку и проверить изменение нужного поведения после патча. DurkaHelper даёт конфигурацию и launch/import; upstream-исходники не меняются.
|
||||
|
||||
<a id="ui-services-and-patterns"></a>
|
||||
## Где настроить сервисы и поиск в 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).
|
||||
|
||||
<a id="file-on-the-laptop"></a>
|
||||
## 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.
|
||||
|
||||
<a id="live-on-linux"></a>
|
||||
## 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 не видит весь трафик автоматически.
|
||||
|
||||
<a id="resources-and-troubleshooting"></a>
|
||||
## Ресурсы и диагностика
|
||||
|
||||
Текущий образ 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)
|
||||
@@ -0,0 +1,194 @@
|
||||
<a id="packmate-live-deploy-from-the-laptop-over-ssh"></a>
|
||||
# Packmate LIVE: запуск с ноутбука по SSH
|
||||
|
||||
[English](packmate-remote.md) | Русский
|
||||
|
||||
Все команды ниже выполняются **на ноутбуке из корня DurkaHelper**. На Vulnbox
|
||||
Python не нужен: программа переносит готовые конфиги и запускает Docker Compose.
|
||||
Это не заменяет [FILE import](traffic-capture-RU.md#file-on-the-laptop) на Mac.
|
||||
|
||||
<a id="requirements"></a>
|
||||
## Что требуется
|
||||
|
||||
- На ноутбуке: 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.
|
||||
|
||||
<a id="1-read-only-doctor-before-configuration"></a>
|
||||
## 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 означает проблему доступа, платформы,
|
||||
ресурсов или портов; чужие процессы/контейнеры не останавливайте.
|
||||
|
||||
<a id="2-prepare-offline-images-before-the-event"></a>
|
||||
## 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.
|
||||
|
||||
<a id="3-create-one-private-configuration"></a>
|
||||
## 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`.
|
||||
|
||||
<a id="where-the-deployment-configuration-lives"></a>
|
||||
## Где находится 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 не переносится.
|
||||
|
||||
<a id="4-check-and-start"></a>
|
||||
## 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 не перезаписывается.
|
||||
|
||||
<a id="5-login-and-inspect-a-transaction"></a>
|
||||
## 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**, проверьте направление, время,
|
||||
повторный запрос и доступность приложения. Статус контейнера этого не заменяет.
|
||||
|
||||
<a id="6-stop-and-start-again"></a>
|
||||
## 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 не присваивается автоматически.
|
||||
|
||||
<a id="troubleshooting"></a>
|
||||
## Если не получилось
|
||||
|
||||
- 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)
|
||||
@@ -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)
|
||||
@@ -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)
|
||||
@@ -0,0 +1,47 @@
|
||||
<a id="participant-guide"></a>
|
||||
# Инструкция участника
|
||||
|
||||
[English](participant-guide.md) | Русский
|
||||
|
||||
Ферму устанавливать и конфиг админа заполнять не нужно. Получите у админа LAN URL/логины фермы и Packmate; авторам скриптов также нужны адрес/ключ координатора Neo.
|
||||
|
||||
<a id="defend-a-service"></a>
|
||||
## Защитить сервис
|
||||
|
||||
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 — некорректный/неполный вход, который нужно проверить. Чистый отчёт не заменяет доступность и ручную проверку авторизации/бизнес-логики.
|
||||
|
||||
<a id="inspect-traffic"></a>
|
||||
## Разобрать трафик
|
||||
|
||||
Откройте LAN URL Packmate и войдите. Выберите свой сервис, ищите подозрительное значение/путь и изучайте запрос вместе с ответом. Для FILE попросите админа зарегистрировать сервис/шаблон до начала обработки.
|
||||
|
||||
Если трафика нет, проверьте timestamps потоков, IP стороны сервиса и порт/шаблон и то, импортировал ли админ закрытый файл или выбрал разрешённый LIVE-источник. Не предполагается наличие фильтра времени в UI. Один Ethernet на Mac не захватывает всю LAN автоматически. [Работа с трафиком](traffic-capture-RU.md).
|
||||
|
||||
<a id="write-and-distribute-scripts"></a>
|
||||
## Написать и распределить скрипты
|
||||
|
||||
Neo — исполнитель/распределитель скриптов. Ферма собирает полученные флаги. Начните с локального теста на разрешённой цели и явно определите зависимости.
|
||||
|
||||
Скрипт получает IP цели первым аргументом; флаги печатает в stdout без буферизации. Диагностику отделяйте от флагов. Shebang должен указывать интерпретатор, доступный у каждого worker. Встроенный light-worker содержит shell, а не Python/Sage и произвольные пакеты.
|
||||
|
||||
[Настройка Neo и первое задание](neo-RU.md) описывает совместимый клиент. Сначала зарегистрируйте доверенный скрипт выключенным, затем запросите единичный прогон до периодического исполнения. `single` Neo запускает один раз на **всех настроенных командах**, поэтому сверьте scope/список с админом.
|
||||
|
||||
Следите за исполнением и флагами/статусом в ферме. Ферма/Neo не являются автоматическим установщиком защитных патчей.
|
||||
|
||||
<a id="if-access-fails"></a>
|
||||
## Если нет доступа
|
||||
|
||||
Используйте LAN-адрес админа, а не `localhost`. Если ошибка только у вас — URL/порт, credentials и версия Neo. Если у всех — админ проверяет `python3 durka.py status` и LAN bind.
|
||||
|
||||
Не показывайте приватные исходники, credentials, флаги и трафик в общей трансляции. [Шпаргалка защитника](defense-cheatsheet-RU.md) · [Связи инструментов](team-setup-RU.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).
|
||||
@@ -0,0 +1,89 @@
|
||||
<a id="patch-verification-deployment-and-rollback"></a>
|
||||
# Проверка патчей, deployment и rollback
|
||||
|
||||
[English](patch-validation.md) | Русский
|
||||
|
||||
[Шпаргалка защитника](defense-cheatsheet-RU.md) · [Каталог](vulnerabilities/README-RU.md)
|
||||
|
||||
За deployment каждого сервиса отвечает один человек. Все начальные проверки выполняются на изолированной локальной копии разрешённого сервиса. Адаптируйте production-команды только после подтверждения его фактического контракта запуска и данных. Обычный ручной маршрут: сохранить оригиналы, применить небольшой патч, прогнать regression/normal-user/checker проверки и повторить скан. Карточки и ручное переписывание hashes не нужны; раздел 4 — необязательная расширенная проверка evidence, не условие ручного исправления.
|
||||
|
||||
<a id="1-preserve-the-before-state"></a>
|
||||
## 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 или проверенной процедуры копирования в остановленном состоянии.
|
||||
|
||||
<a id="2-required-behavioral-matrix"></a>
|
||||
## 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.
|
||||
|
||||
<a id="3-match-the-deployment-mechanism"></a>
|
||||
## 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.
|
||||
|
||||
<a id="4-bound-evidence-to-this-patch"></a>
|
||||
## 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-разрешение не поддерживается.
|
||||
|
||||
<a id="5-apply-observe-revert-if-necessary"></a>
|
||||
## 5. Примените, наблюдайте, при необходимости откатите
|
||||
|
||||
После явного разрешения используйте только отрепетированный путь deployment собственного сервиса. Сразу повторите health, фактические операции пользователей/checker и чтение старых данных, затем наблюдайте полный релевантный интервал раунда. При сбое сохраните очищенную incident timeline.
|
||||
|
||||
Сначала откатите code/image по записанному плану. Восстановление данных — отдельное решение с серьёзными последствиями: старый dump может стереть данные нового раунда. Не меняйте попутно ключи, schemas или runtime.
|
||||
@@ -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.
|
||||
@@ -0,0 +1,61 @@
|
||||
<a id="release-and-publication-checklist"></a>
|
||||
# Чеклист релиза и публикации
|
||||
|
||||
[English](release-checklist.md) | Русский
|
||||
|
||||
Чеклист сопровождающего, а не форма оператора. Для развёртывания используйте [инструкцию Mac](MACOS_FULL_DEPLOYMENT_AND_TESTING-RU.md). Готовность к публикации и к соревнованию учитываются отдельно.
|
||||
|
||||
<a id="source-and-tests"></a>
|
||||
## Исходники и тесты
|
||||
|
||||
- [ ] Одобренный 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.
|
||||
|
||||
<a id="publication-safety"></a>
|
||||
## Безопасность публикации
|
||||
|
||||
Запускайте из корня репозитория. Эти 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, переписывание истории или публикация сторонних артефактов — отдельные осознанные действия. Не автоматизируйте их как косметическую уборку.
|
||||
|
||||
<a id="release-candidate-and-public-access"></a>
|
||||
## Релиз-кандидат и публичный доступ
|
||||
|
||||
`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) — рабочий маршрут; локальные результаты проверок остаются приватными.
|
||||
|
||||
<a id="competition-gate"></a>
|
||||
## Условия готовности к соревнованию
|
||||
|
||||
- [ ] Проверены архитектура реального целевого 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.
|
||||
@@ -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.
|
||||
@@ -0,0 +1,36 @@
|
||||
<a id="s4dfarm-flags-and-submission"></a>
|
||||
# S4DFarm: флаги и отправка
|
||||
|
||||
[English](s4dfarm.md) | Русский
|
||||
|
||||
S4DFarm собирает флаги команды, ставит их в очередь отправки и показывает accepted/rejected/expired. Neo автоматически передаёт найденные флаги. **Патчи сервисов ферма не распространяет.**
|
||||
|
||||
<a id="start-through-durkahelper"></a>
|
||||
## Запуск через DurkaHelper
|
||||
|
||||
```bash
|
||||
python3 durka.py up
|
||||
python3 durka.py status
|
||||
```
|
||||
|
||||
Откройте URL фермы; пароль — `credentials.farm_password` в приватном `local/durka.json`. Передайте участникам LAN URL/пароль, а не конфигурацию PostgreSQL/Redis.
|
||||
|
||||
<a id="configure-the-competition"></a>
|
||||
## Настроить соревнование
|
||||
|
||||
В `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.
|
||||
|
||||
<a id="change-configuration-or-recover"></a>
|
||||
## Изменить конфиг или восстановить
|
||||
|
||||
Настройки площадки: остановить, отредактировать приватный конфиг, выполнить `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)
|
||||
@@ -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)
|
||||
@@ -0,0 +1,39 @@
|
||||
<a id="how-the-teams-tools-connect"></a>
|
||||
# Как связаны командные инструменты
|
||||
|
||||
[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
|
||||
```
|
||||
|
||||
<a id="who-owns-what"></a>
|
||||
## Кто за что отвечает
|
||||
|
||||
Админ отвечает за общий конфиг, запуск, учётные данные, отправку и backups. Защитники — за review, патчи и regression-тесты сервиса. Авторы — за свои скрипты/зависимости и результаты в ферме. Workers Neo выполняют доверенный командный код.
|
||||
|
||||
Ферма отправляет **флаги**, Neo распределяет **скрипты**. Патчи сервисов они автоматически не развёртывают. Используйте обычный доступ/деплой Vulnbox вашей команды.
|
||||
|
||||
Автор загружает скрипт в общий координатор Neo; подготовленный worker исполняет его и передаёт подходящие результаты stdout прямо в ферму. Несколько авторов могут пользоваться одним worker: каждому запускать свой не обязательно. См. [workflow клиентов/workers и примеры разового запуска и расписания](neo-RU.md#team-workflow-clients-coordinator-and-workers). Отправка из фермы включается отдельно; попадание в очередь ещё не подтверждает приём жюрейкой.
|
||||
|
||||
<a id="addresses"></a>
|
||||
## Адреса
|
||||
|
||||
Используйте Ethernet IPv4 админа и порты из `python3 durka.py status`. По умолчанию: ферма 8080, Neo 5005, Packmate 65000. Участникам не нужны `localhost`, Docker DNS и `host.docker.internal`.
|
||||
|
||||
Database, Redis и Docker остаются приватными. Клиентам/workers Neo нужен доступ к координатору и ферме; workers также нужны разрешённые маршруты до целей. Используйте только разрешённые площадкой порты и доступ.
|
||||
|
||||
<a id="first-check"></a>
|
||||
## Первая проверка
|
||||
|
||||
Дома проверьте машину админа и отдельный ПК. На площадке каждый участник должен войти, выполнить полезное действие и переподключиться. 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)
|
||||
@@ -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)
|
||||
@@ -0,0 +1,129 @@
|
||||
<a id="traffic-live-or-pcap-import"></a>
|
||||
# Трафик: LIVE или импорт PCAP
|
||||
|
||||
[English](traffic-capture.md) | Русский
|
||||
|
||||
Подготовьте оба пути до соревнования. На месте выберите разрешённый организаторами; обычный FILE import не требует изменения кода.
|
||||
|
||||
<a id="choose-a-route"></a>
|
||||
## Выбрать вариант
|
||||
|
||||
| Что доступно | Использовать |
|
||||
|---|---|
|
||||
| Разрешено запустить 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.
|
||||
|
||||
<a id="file-on-the-laptop"></a>
|
||||
## 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, учётные данные и флаги.
|
||||
|
||||
<a id="capture-a-closed-file-on-linux"></a>
|
||||
## Получить закрытый файл на Linux
|
||||
|
||||
Лучше использовать файлы организаторов. Если capture разрешён и `tcpdump`/`timeout` уже установлены, запускайте в приватном каталоге источника. Замените все placeholders разрешённым интерфейсом/сервисом/портами и **новым** именем файла:
|
||||
|
||||
```bash
|
||||
umask 077
|
||||
timeout --signal=INT 60 tcpdump -i <APPROVED_INTERFACE> -p -nn -s 65535 \
|
||||
-c 1000 -w <NEW_PRIVATE_PREFIX>.pcap \
|
||||
'host <SERVICE_IPV4> and (tcp port <TCP_PORT> or udp port <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 <SSH_PORT> \
|
||||
<USER>@<SOURCE_HOST>:<EXACT_CLOSED_FILE> ./incoming-01.pcap
|
||||
python3 durka.py traffic import ./incoming-01.pcap
|
||||
```
|
||||
|
||||
Эти две команды запускаются на ноутбуке из корня репозитория. Сохраните source до успешного импорта/использования. Файл, в который ещё идёт запись, не передавайте.
|
||||
|
||||
<a id="host-interface-live"></a>
|
||||
## 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 '<INTERFACE>:<IFINDEX>:<MAC>' \
|
||||
--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`.
|
||||
|
||||
<a id="check-before-relying-on-traffic"></a>
|
||||
## Проверить до использования
|
||||
|
||||
Найдите известную транзакцию, а не только работающий UI. Проверьте оба направления, время, характерные TCP/UDP, рост диска и restart. Остановите capture при неверном scope, утечке секретов или приближении к пределу диска.
|
||||
|
||||
FILE — отложенный анализ. Если необходим непрерывный анализ, одних закрытых файлов недостаточно. Прогоните оба разрешённых пути и подготовьте capture-зависимости/образы до выезда.
|
||||
|
||||
[Packmate](packmate-RU.md) · [Шпаргалка админа](TEAM_LAN_ADMIN_CHEATSHEET-RU.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 <APPROVED_INTERFACE> -p -nn -s 65535 \
|
||||
-c 1000 -w <NEW_PRIVATE_PREFIX>.pcap \
|
||||
'host <SERVICE_IPV4> and (tcp port <TCP_PORT> or udp port <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 <SSH_PORT> \
|
||||
<USER>@<SOURCE_HOST>:<EXACT_CLOSED_FILE> ./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 '<INTERFACE>:<IFINDEX>:<MAC>' \
|
||||
--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)
|
||||
@@ -0,0 +1,50 @@
|
||||
<a id="vulnerability-and-remediation-catalog"></a>
|
||||
|
||||
# Каталог уязвимостей и исправлений
|
||||
|
||||
[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 |
|
||||
|
||||
<a id="find-and-fix"></a>
|
||||
|
||||
## Найти и исправить
|
||||
|
||||
1. Запустите [офлайн-сканер](../offline-scanner-RU.md) на локальной копии сервиса, которую вам разрешено проверять.
|
||||
2. Откройте ссылку на конкретный раздел для каждой находки.
|
||||
3. Просмотрите разделы языка и конфигурации, предназначенные только для ручной проверки; их команды rg находят код для анализа, а не подтверждённые уязвимости.
|
||||
4. Внесите совместимое исправление и проверьте поведение для владельца и другого пользователя, старые данные и checker соревнования. Используйте [проверку патча](../patch-validation-RU.md).
|
||||
|
||||
Каждый раздел построен по схеме **Поиск → Уязвимый вариант → Исправление → Проверка**.
|
||||
Покрытие: **174 автоматических сигнала и 120 разделов только для ручной проверки**.
|
||||
Две темы, ранее проверявшиеся только вручную, теперь имеют намеренно узкие автоматические сигналы; ручной поиск остаётся необходимым для остальных форм.
|
||||
|
||||
Пустой отчёт не доказывает безопасность. Пользовательские wrappers, сгенерированный код, defaults конкретных версий и бизнес-логика требуют ручного анализа. Сканер не импортирует и не исполняет код цели и не обращается к сетевой базе уязвимостей.
|
||||
|
||||
<a id="example-boundaries"></a>
|
||||
|
||||
## Границы применимости примеров
|
||||
|
||||
Функции вроде validateOwnedResource и evaluateAllowedExpression обозначают логику, которую нужно реализовать самостоятельно; это не готовые зависимости. Шаблоны патчей никогда не применяются автоматически. Сохраняйте штатное поведение, границы авторизации, старые данные и совместимость с checker.
|
||||
|
||||
Отделяйте данные от кода и аргументов. Массив argv без shell всё ещё допускает опасные опции вызываемой программы; проверяйте собственный контракт утилиты. Парсер или проверка типа не заменяет авторизацию. Корректное исправление может сохранить синтаксический сигнал сканера.
|
||||
|
||||
Исторические A/D-примеры сохраняют зафиксированные версии источников и авторство. Проверка семантики исходников не доказывает, что каждый пример запускался на всех поддерживаемых runtime. Каталог не предлагает устанавливать устаревшие версии, упомянутые для объяснения исторического поведения.
|
||||
|
||||
См. [покрытие и разработку правил](../development-RU.md): независимые положительные и отрицательные fixtures и заявленные ограничения детекторов.
|
||||
@@ -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.
|
||||
@@ -0,0 +1,946 @@
|
||||
<a id="c--c-find-fix-and-verify"></a>
|
||||
|
||||
# C / C++: поиск и исправление
|
||||
|
||||
[English](c-cpp.md) | Русский
|
||||
|
||||
[Вся база](README-RU.md) · [Сканер](../offline-scanner-RU.md) · [Проверка патча](../patch-validation-RU.md)
|
||||
|
||||
28 разделов. Формат: **Поиск → Уязвимый вариант → Исправление → Проверка**.
|
||||
Команды `rg` выполняются в корне локальной копии сервиса и только читают файлы. Субъект/владелец определяется по проверенной сессии, а не данным запроса. Примеры нужно адаптировать к реальным API и контракту.
|
||||
|
||||
Автоматические находки — ограниченные синтаксические сигналы для проверки. AST-анализ не разрешает типы и не отслеживает данные между функциями; regex не заменяет парсер языка. Комментарии, строки и одноимённые пользовательские API могут давать совпадения. Проверьте фактическое исполнение, входные данные, авторизацию и границы доверия.
|
||||
|
||||
<a id="contents"></a>
|
||||
|
||||
## Содержание
|
||||
|
||||
- [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)
|
||||
|
||||
<a id="c-bounds"></a>
|
||||
|
||||
<a id="c-bounds-unbounded-cc-copy"></a>
|
||||
|
||||
## 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 если доступны.
|
||||
|
||||
<details>
|
||||
<summary>Развёрнутый пример и ограничения</summary>
|
||||
|
||||
```c
|
||||
/* Vulnerable: capacity and available source length are unchecked. */
|
||||
char dst[64];
|
||||
memcpy(dst, src, client_len);
|
||||
dst[client_len] = '\0';
|
||||
```
|
||||
|
||||
**Патч для поля протокола, которое является C-строкой без встроенного NUL:**
|
||||
|
||||
<!-- example: c-copy-text -->
|
||||
```c
|
||||
#include <stdbool.h>
|
||||
#include <stddef.h>
|
||||
#include <string.h>
|
||||
|
||||
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.
|
||||
|
||||
</details>
|
||||
|
||||
<a id="c-format"></a>
|
||||
|
||||
<a id="c-format-variable-used-as-a-format-string"></a>
|
||||
|
||||
## 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);
|
||||
~~~
|
||||
|
||||
**Проверка:** Символы процента печатаются текстом.
|
||||
|
||||
<details>
|
||||
<summary>Развёрнутый пример и ограничения</summary>
|
||||
|
||||
```c
|
||||
/* Vulnerable: message controls the format and argument interpretation. */
|
||||
printf(message);
|
||||
```
|
||||
|
||||
**Патч, если message — корректная NUL-терминированная строка:**
|
||||
|
||||
<!-- example: c-write-message -->
|
||||
```c
|
||||
#include <stdbool.h>
|
||||
#include <stdio.h>
|
||||
|
||||
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 выводится буквально; пустая строка
|
||||
допустима; текст не получает лишний перевод строки, если это важно протоколу.
|
||||
|
||||
</details>
|
||||
|
||||
<a id="c-shell"></a>
|
||||
|
||||
<a id="c-shell-cc-shell-execution"></a>
|
||||
|
||||
## 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.
|
||||
|
||||
<a id="c-prng"></a>
|
||||
|
||||
<a id="c-prng-ordinary-prnglcg-near-a-possible-secret"></a>
|
||||
|
||||
## 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).
|
||||
|
||||
<a id="c-snprintf-format"></a>
|
||||
|
||||
<a id="c-snprintf-format-variable-format-in-bounded-printf"></a>
|
||||
|
||||
## 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).
|
||||
|
||||
<a id="c-recv-terminator"></a>
|
||||
|
||||
<a id="c-recv-terminator-recvread-result-used-as-an-index"></a>
|
||||
|
||||
## 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, полный буфер, короткое чтение и обычное сообщение.
|
||||
|
||||
<a id="c-atoi"></a>
|
||||
|
||||
<a id="c-atoi-atoi-without-checked-conversion"></a>
|
||||
|
||||
## 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/).
|
||||
|
||||
<a id="c-realloc"></a>
|
||||
|
||||
<a id="c-realloc-overwriting-the-only-pointer-with-realloc"></a>
|
||||
|
||||
## 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/).
|
||||
|
||||
<a id="c-size-overflow"></a>
|
||||
|
||||
<a id="c-size-overflow-size-arithmetic-overflow"></a>
|
||||
|
||||
## 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.
|
||||
|
||||
**Проверка:** Ноль, граница, переполнение произведения/суммы, отрицательный вход и прежний буфер.
|
||||
|
||||
<details>
|
||||
<summary>Развёрнутый пример и ограничения</summary>
|
||||
|
||||
```c
|
||||
/* Vulnerable: count * sizeof(Item) can overflow. */
|
||||
Item *items = malloc(count * sizeof(*items));
|
||||
```
|
||||
|
||||
**Патч проверки арифметики и согласованного лимита:**
|
||||
|
||||
<!-- example: c-array-bytes -->
|
||||
```c
|
||||
#include <stdbool.h>
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
|
||||
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-буфер.
|
||||
|
||||
</details>
|
||||
|
||||
<a id="cpp-lifetime"></a>
|
||||
|
||||
<a id="cpp-lifetime-a-pointer-or-view-outlives-its-owner"></a>
|
||||
|
||||
## 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 дожидается окончания.
|
||||
|
||||
<details>
|
||||
<summary>Развёрнутый пример и ограничения</summary>
|
||||
|
||||
```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();
|
||||
}
|
||||
```
|
||||
|
||||
**Патч: вернуть владеющий объект, а не указатель в уничтоженное хранилище:**
|
||||
|
||||
<!-- example: cpp-label -->
|
||||
```cpp
|
||||
#include <string>
|
||||
|
||||
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; асинхронный путь
|
||||
удерживает данные до завершения операции.
|
||||
|
||||
</details>
|
||||
|
||||
<a id="c-partial-io"></a>
|
||||
|
||||
<a id="c-partial-io-tcp-does-not-preserve-message-boundaries"></a>
|
||||
|
||||
## 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 посредине и обычное сообщение.
|
||||
|
||||
<a id="c-signed-length"></a>
|
||||
|
||||
<a id="c-signed-length-signed-lengths-become-huge-size_t-values"></a>
|
||||
|
||||
## 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.
|
||||
|
||||
<a id="c-double-free"></a>
|
||||
|
||||
<a id="c-double-free-multiple-owners-free-the-same-object"></a>
|
||||
|
||||
## 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, нормальный жизненный цикл.
|
||||
|
||||
<a id="c-uninitialized"></a>
|
||||
|
||||
<a id="c-uninitialized-exposing-padding-or-uninitialized-tails"></a>
|
||||
|
||||
## 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, короткий ввод, отсутствие незаполненных байтов в ответе.
|
||||
|
||||
<a id="c-tempfile-race"></a>
|
||||
|
||||
<a id="c-tempfile-race-temporary-filename-without-atomic-creation"></a>
|
||||
|
||||
## 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).
|
||||
|
||||
<a id="c-jit-return"></a>
|
||||
|
||||
<a id="c-jit-return-not-every-jit-function-path-terminates"></a>
|
||||
|
||||
## 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).
|
||||
|
||||
<a id="c-header-secret"></a>
|
||||
|
||||
<a id="c-header-secret-a-special-header-branch-changes-a-secret"></a>
|
||||
|
||||
## 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).
|
||||
|
||||
<a id="c-object-toctou"></a>
|
||||
|
||||
<a id="c-object-toctou-re-reading-mutable-references-after-authorization"></a>
|
||||
|
||||
## 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).
|
||||
|
||||
<a id="c-exec-failure"></a>
|
||||
|
||||
<a id="c-exec-failure-failed-exec-leaves-a-child-on-the-server-path"></a>
|
||||
|
||||
## 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).
|
||||
|
||||
<a id="cpp-cached-lifetime"></a>
|
||||
|
||||
<a id="cpp-cached-lifetime-cached-pointers-survive-object-destruction"></a>
|
||||
|
||||
## 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).
|
||||
|
||||
<a id="c-block-tail"></a>
|
||||
|
||||
<a id="c-block-tail-four-byte-block-processing-corrupts-the-tail"></a>
|
||||
|
||||
## 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).
|
||||
|
||||
<a id="c-alloc-failure"></a>
|
||||
|
||||
<a id="c-alloc-failure-allocation-failure-becomes-a-null-write"></a>
|
||||
|
||||
## 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).
|
||||
|
||||
<a id="c-fd-nul"></a>
|
||||
|
||||
<a id="c-fd-nul-descriptor-leaks-amplify-a-read_line-off-by-one"></a>
|
||||
|
||||
## 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).
|
||||
|
||||
<a id="c-reentrancy-auth"></a>
|
||||
|
||||
<a id="c-reentrancy-auth-a-callback-runs-between-authorization-and-signing"></a>
|
||||
|
||||
## 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).
|
||||
|
||||
<a id="c-builtin-types"></a>
|
||||
|
||||
<a id="c-builtin-types-one-builtin-overload-omits-argument-type-checks"></a>
|
||||
|
||||
## 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).
|
||||
|
||||
<a id="c-hash-index"></a>
|
||||
|
||||
<a id="c-hash-index-hash-table-indices-exceed-the-upper-boundary"></a>
|
||||
|
||||
## 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).
|
||||
|
||||
<a id="c-strncpy"></a>
|
||||
|
||||
<a id="c-strncpy-strncpy-may-omit-nul-termination"></a>
|
||||
|
||||
## 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).
|
||||
|
||||
<a id="c-copy-length"></a>
|
||||
|
||||
<a id="c-copy-length-copy-length-comes-directly-from-source-strlen"></a>
|
||||
|
||||
## 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)
|
||||
@@ -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)
|
||||
|
||||
<a id="c-bounds"></a>
|
||||
|
||||
## 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.
|
||||
|
||||
<details>
|
||||
<summary>Expanded example and limitations</summary>
|
||||
|
||||
```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:**
|
||||
|
||||
<!-- example: c-copy-text -->
|
||||
|
||||
```c
|
||||
#include <stdbool.h>
|
||||
#include <stddef.h>
|
||||
#include <string.h>
|
||||
|
||||
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.
|
||||
|
||||
</details>
|
||||
|
||||
<a id="c-format"></a>
|
||||
|
||||
## 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.
|
||||
|
||||
<details>
|
||||
<summary>Expanded example and limitations</summary>
|
||||
|
||||
```c
|
||||
/* Vulnerable: message controls the format and argument interpretation. */
|
||||
printf(message);
|
||||
```
|
||||
|
||||
**Patch when message is a valid NUL-terminated string:**
|
||||
|
||||
<!-- example: c-write-message -->
|
||||
|
||||
```c
|
||||
#include <stdbool.h>
|
||||
#include <stdio.h>
|
||||
|
||||
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.
|
||||
|
||||
</details>
|
||||
|
||||
<a id="c-shell"></a>
|
||||
|
||||
## 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.
|
||||
|
||||
<a id="c-prng"></a>
|
||||
|
||||
## 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).
|
||||
|
||||
<a id="c-snprintf-format"></a>
|
||||
|
||||
## 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).
|
||||
|
||||
<a id="c-recv-terminator"></a>
|
||||
|
||||
## 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.
|
||||
|
||||
<a id="c-atoi"></a>
|
||||
|
||||
## 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/).
|
||||
|
||||
<a id="c-realloc"></a>
|
||||
|
||||
## 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/).
|
||||
|
||||
<a id="c-size-overflow"></a>
|
||||
|
||||
## 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.
|
||||
|
||||
<details>
|
||||
<summary>Expanded example and limitations</summary>
|
||||
|
||||
```c
|
||||
/* Vulnerable: count * sizeof(Item) can overflow. */
|
||||
Item *items = malloc(count * sizeof(*items));
|
||||
```
|
||||
|
||||
**Patch for arithmetic and the agreed size limit:**
|
||||
|
||||
<!-- example: c-array-bytes -->
|
||||
|
||||
```c
|
||||
#include <stdbool.h>
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
|
||||
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.
|
||||
|
||||
</details>
|
||||
|
||||
<a id="cpp-lifetime"></a>
|
||||
|
||||
## 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.
|
||||
|
||||
<details>
|
||||
<summary>Expanded example and limitations</summary>
|
||||
|
||||
```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:**
|
||||
|
||||
<!-- example: cpp-label -->
|
||||
|
||||
```cpp
|
||||
#include <string>
|
||||
|
||||
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.
|
||||
|
||||
</details>
|
||||
|
||||
<a id="c-partial-io"></a>
|
||||
|
||||
## 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.
|
||||
|
||||
<a id="c-signed-length"></a>
|
||||
|
||||
## 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.
|
||||
|
||||
<a id="c-double-free"></a>
|
||||
|
||||
## 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.
|
||||
|
||||
<a id="c-uninitialized"></a>
|
||||
|
||||
## 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.
|
||||
|
||||
<a id="c-tempfile-race"></a>
|
||||
|
||||
## 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).
|
||||
|
||||
<a id="c-jit-return"></a>
|
||||
|
||||
## 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).
|
||||
|
||||
<a id="c-header-secret"></a>
|
||||
|
||||
## 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).
|
||||
|
||||
<a id="c-object-toctou"></a>
|
||||
|
||||
## 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).
|
||||
|
||||
<a id="c-exec-failure"></a>
|
||||
|
||||
## 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).
|
||||
|
||||
<a id="cpp-cached-lifetime"></a>
|
||||
|
||||
## 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).
|
||||
|
||||
<a id="c-block-tail"></a>
|
||||
|
||||
## 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).
|
||||
|
||||
<a id="c-alloc-failure"></a>
|
||||
|
||||
## 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).
|
||||
|
||||
<a id="c-fd-nul"></a>
|
||||
|
||||
## 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).
|
||||
|
||||
<a id="c-reentrancy-auth"></a>
|
||||
|
||||
## 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).
|
||||
|
||||
<a id="c-builtin-types"></a>
|
||||
|
||||
## 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).
|
||||
|
||||
<a id="c-hash-index"></a>
|
||||
|
||||
## 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).
|
||||
|
||||
<a id="c-strncpy"></a>
|
||||
|
||||
## 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).
|
||||
|
||||
<a id="c-copy-length"></a>
|
||||
|
||||
## 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)
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,688 @@
|
||||
<a id="c--net-find-fix-and-verify"></a>
|
||||
|
||||
# C# / .NET: поиск и исправление
|
||||
|
||||
[English](csharp.md) | Русский
|
||||
|
||||
[Вся база](README-RU.md) · [Сканер](../offline-scanner-RU.md) · [Проверка патча](../patch-validation-RU.md)
|
||||
|
||||
20 разделов. Формат: **Поиск → Уязвимый вариант → Исправление → Проверка**.
|
||||
Команды `rg` выполняются в корне локальной копии сервиса и только читают файлы. Субъект/владелец определяется по проверенной сессии, а не данным запроса. Примеры нужно адаптировать к реальным API и контракту.
|
||||
|
||||
Автоматические находки — ограниченные синтаксические сигналы для проверки. AST-анализ не разрешает типы и не отслеживает данные между функциями; regex не заменяет парсер языка. Комментарии, строки и одноимённые пользовательские API могут давать совпадения. Проверьте фактическое исполнение, входные данные, авторизацию и границы доверия.
|
||||
|
||||
<a id="contents"></a>
|
||||
|
||||
## Содержание
|
||||
|
||||
- [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)
|
||||
|
||||
<a id="cs-deserialize"></a>
|
||||
|
||||
<a id="cs-deserialize-type-controlled-net-deserialization"></a>
|
||||
|
||||
## 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<MessageDto>(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).
|
||||
|
||||
<a id="cs-enum"></a>
|
||||
|
||||
<a id="cs-enum-enumtryparse-requires-an-allowed-value-check"></a>
|
||||
|
||||
## 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<FilterKind>(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).
|
||||
|
||||
<a id="cs-sql"></a>
|
||||
|
||||
<a id="cs-sql-dynamic-net-sql"></a>
|
||||
|
||||
## 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 сохраняется.
|
||||
|
||||
<details>
|
||||
<summary>Развёрнутый пример и ограничения</summary>
|
||||
|
||||
```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.
|
||||
|
||||
</details>
|
||||
|
||||
<a id="cs-guid-bytes"></a>
|
||||
|
||||
<a id="cs-guid-bytes-byte-order-guid-protocol-boundary"></a>
|
||||
|
||||
## 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.
|
||||
|
||||
<a id="cs-process"></a>
|
||||
|
||||
<a id="cs-process-net-process-creation"></a>
|
||||
|
||||
## 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));
|
||||
~~~
|
||||
|
||||
**Проверка:** Кавычки — данные, штатный формат результата совпадает.
|
||||
|
||||
<details>
|
||||
<summary>Развёрнутый пример и ограничения</summary>
|
||||
|
||||
```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, кавычки и переводы строк;
|
||||
нет дочернего процесса и утечки его окружения при ошибке.
|
||||
|
||||
</details>
|
||||
|
||||
**Основание:** [первичный материал](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.processstartinfo.argumentlist).
|
||||
|
||||
<a id="cs-ignore-filters"></a>
|
||||
|
||||
<a id="cs-ignore-filters-global-query-filters-disabled"></a>
|
||||
|
||||
## 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).
|
||||
|
||||
<a id="cs-allowanon"></a>
|
||||
|
||||
<a id="cs-allowanon-allowanonymous-route"></a>
|
||||
|
||||
## 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).
|
||||
|
||||
<a id="cs-mass-assign"></a>
|
||||
|
||||
<a id="cs-mass-assign-client-entities-update-the-database-wholesale"></a>
|
||||
|
||||
## 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/отсутствующее поле различаются по контракту.
|
||||
|
||||
<details>
|
||||
<summary>Развёрнутый пример и ограничения</summary>
|
||||
|
||||
```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-поля могут игнорироваться сериализатором —
|
||||
не обещать их автоматический отказ без отдельной настройки.
|
||||
|
||||
</details>
|
||||
|
||||
**Основание:** [первичный материал](https://learn.microsoft.com/en-us/aspnet/core/mvc/models/model-binding).
|
||||
|
||||
<a id="cs-xml"></a>
|
||||
|
||||
<a id="cs-xml-xml-parser-permits-dtd-or-external-resolver"></a>
|
||||
|
||||
## 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).
|
||||
|
||||
<a id="cs-html-raw"></a>
|
||||
|
||||
<a id="cs-html-raw-html-output-without-escaping"></a>
|
||||
|
||||
## 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).
|
||||
|
||||
<a id="cs-path"></a>
|
||||
|
||||
<a id="cs-path-pathcombine-and-getfullpath-do-not-check-ownership"></a>
|
||||
|
||||
## 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 варианты, общий префикс, ссылка наружу, собственный/чужой файл.
|
||||
|
||||
<a id="cs-archive"></a>
|
||||
|
||||
<a id="cs-archive-ziparchive-entries-escape-the-directory"></a>
|
||||
|
||||
## 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).
|
||||
|
||||
<a id="cs-claims"></a>
|
||||
|
||||
<a id="cs-claims-incomplete-jwt-or-claims-validation"></a>
|
||||
|
||||
## 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/срок/назначение и валидная сессия со старыми данными.
|
||||
|
||||
<a id="cs-async-void"></a>
|
||||
|
||||
<a id="cs-async-void-async-void-hides-authorization-errors"></a>
|
||||
|
||||
## 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 проверки не возвращают защищённые данные; корректный путь завершается.
|
||||
|
||||
<a id="cs-regex-timeout"></a>
|
||||
|
||||
<a id="cs-regex-timeout-untrusted-regex-input-without-a-budget"></a>
|
||||
|
||||
## 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-конструкции работают.
|
||||
|
||||
<a id="cs-auth-filter-reduce"></a>
|
||||
|
||||
<a id="cs-auth-filter-reduce-simplification-removes-a-mandatory-authorization-condition"></a>
|
||||
|
||||
## 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).
|
||||
|
||||
<a id="cs-colliding-principal"></a>
|
||||
|
||||
<a id="cs-colliding-principal-a-normalized-character-sum-replaces-a-unique-user-id"></a>
|
||||
|
||||
## 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).
|
||||
|
||||
<a id="cs-jwt-validation"></a>
|
||||
|
||||
<a id="cs-jwt-validation-weakened-net-token-validation"></a>
|
||||
|
||||
## 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).
|
||||
|
||||
<a id="cs-tls-validation"></a>
|
||||
|
||||
<a id="cs-tls-validation-https-validation-callback-always-accepts"></a>
|
||||
|
||||
## 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).
|
||||
|
||||
<a id="cs-ldap-filter"></a>
|
||||
|
||||
<a id="cs-ldap-filter-directorysearcher-filter-concatenates-a-value"></a>
|
||||
|
||||
## 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)
|
||||
@@ -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)
|
||||
|
||||
<a id="cs-deserialize"></a>
|
||||
|
||||
## 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<MessageDto>(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).
|
||||
|
||||
<a id="cs-enum"></a>
|
||||
|
||||
## 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<FilterKind>(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).
|
||||
|
||||
<a id="cs-sql"></a>
|
||||
|
||||
## 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.
|
||||
|
||||
<details>
|
||||
<summary>Expanded example and limitations</summary>
|
||||
|
||||
```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.
|
||||
|
||||
</details>
|
||||
|
||||
<a id="cs-guid-bytes"></a>
|
||||
|
||||
## 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.
|
||||
|
||||
<a id="cs-process"></a>
|
||||
|
||||
## 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.
|
||||
|
||||
<details>
|
||||
<summary>Expanded example and limitations</summary>
|
||||
|
||||
```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.
|
||||
|
||||
</details>
|
||||
|
||||
**Reference:** [primary source](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.processstartinfo.argumentlist).
|
||||
|
||||
<a id="cs-ignore-filters"></a>
|
||||
|
||||
## 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).
|
||||
|
||||
<a id="cs-allowanon"></a>
|
||||
|
||||
## 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).
|
||||
|
||||
<a id="cs-mass-assign"></a>
|
||||
|
||||
## 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.
|
||||
|
||||
<details>
|
||||
<summary>Expanded example and limitations</summary>
|
||||
|
||||
```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.
|
||||
|
||||
</details>
|
||||
|
||||
**Reference:** [primary source](https://learn.microsoft.com/en-us/aspnet/core/mvc/models/model-binding).
|
||||
|
||||
<a id="cs-xml"></a>
|
||||
|
||||
## 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).
|
||||
|
||||
<a id="cs-html-raw"></a>
|
||||
|
||||
## 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).
|
||||
|
||||
<a id="cs-path"></a>
|
||||
|
||||
## 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.
|
||||
|
||||
<a id="cs-archive"></a>
|
||||
|
||||
## 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).
|
||||
|
||||
<a id="cs-claims"></a>
|
||||
|
||||
## 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.
|
||||
|
||||
<a id="cs-async-void"></a>
|
||||
|
||||
## 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.
|
||||
|
||||
<a id="cs-regex-timeout"></a>
|
||||
|
||||
## 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.
|
||||
|
||||
<a id="cs-auth-filter-reduce"></a>
|
||||
|
||||
## 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).
|
||||
|
||||
<a id="cs-colliding-principal"></a>
|
||||
|
||||
## 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).
|
||||
|
||||
<a id="cs-jwt-validation"></a>
|
||||
|
||||
## 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).
|
||||
|
||||
<a id="cs-tls-validation"></a>
|
||||
|
||||
## 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).
|
||||
|
||||
<a id="cs-ldap-filter"></a>
|
||||
|
||||
## 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)
|
||||
@@ -0,0 +1,682 @@
|
||||
<a id="go-find-fix-and-verify"></a>
|
||||
|
||||
# Go: поиск и исправление
|
||||
|
||||
[English](go.md) | Русский
|
||||
|
||||
[Вся база](README-RU.md) · [Сканер](../offline-scanner-RU.md) · [Проверка патча](../patch-validation-RU.md)
|
||||
|
||||
19 разделов. Формат: **Поиск → Уязвимый вариант → Исправление → Проверка**.
|
||||
Команды `rg` выполняются в корне локальной копии сервиса и только читают файлы. Субъект/владелец определяется по проверенной сессии, а не данным запроса. Примеры нужно адаптировать к реальным API и контракту.
|
||||
|
||||
Автоматические находки — ограниченные синтаксические сигналы для проверки. AST-анализ не разрешает типы и не отслеживает данные между функциями; regex не заменяет парсер языка. Комментарии, строки и одноимённые пользовательские API могут давать совпадения. Проверьте фактическое исполнение, входные данные, авторизацию и границы доверия.
|
||||
|
||||
<a id="contents"></a>
|
||||
|
||||
## Содержание
|
||||
|
||||
- [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)
|
||||
|
||||
<a id="go-sql"></a>
|
||||
|
||||
<a id="go-sql-dynamic-go-sql"></a>
|
||||
|
||||
## 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)
|
||||
~~~
|
||||
|
||||
**Проверка:** Кавычки — данные; права сохранены.
|
||||
|
||||
<details>
|
||||
<summary>Развёрнутый пример и ограничения</summary>
|
||||
|
||||
```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()` после обхода.
|
||||
|
||||
</details>
|
||||
|
||||
<a id="go-hash-sum"></a>
|
||||
|
||||
<a id="go-hash-sum-non-empty-argument-to-hashsum"></a>
|
||||
|
||||
## 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).
|
||||
|
||||
<a id="go-html"></a>
|
||||
|
||||
<a id="go-html-go-autoescape-bypass"></a>
|
||||
|
||||
## 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
|
||||
~~~
|
||||
|
||||
**Проверка:** Теги и кавычки пользователя отображаются текстом; предусмотренное форматирование работает.
|
||||
|
||||
<details>
|
||||
<summary>Развёрнутый пример и ограничения</summary>
|
||||
|
||||
```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("<p>{{.}}</p>")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return page.Execute(w, message)
|
||||
}
|
||||
```
|
||||
|
||||
Шаблон фиксирован; данные — обычная строка. Использовать `html/template`, а не
|
||||
`text/template`, для HTML. Не заменять ошибку типом `template.JS`/`template.URL`:
|
||||
эти типы тоже выражают доверие к данным. В реальном приложении фиксированный
|
||||
шаблон можно разобрать один раз при старте. Если возможна ошибка рендеринга,
|
||||
учесть частично записанный HTTP-ответ: при необходимости сначала рендерить в буфер.
|
||||
|
||||
**Проверить:** разметка и кавычки отображаются текстом, Unicode сохранён;
|
||||
сервис не стал компилировать сам message; допустимое форматирование по контракту работает.
|
||||
|
||||
</details>
|
||||
|
||||
<a id="go-tls"></a>
|
||||
|
||||
<a id="go-tls-insecureskipverify"></a>
|
||||
|
||||
## 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 может
|
||||
совпасть с комментарием или текстовым примером; это не подтверждение выполнения.
|
||||
|
||||
<a id="go-shell"></a>
|
||||
|
||||
<a id="go-shell-go-execcommand-launches-a-shell"></a>
|
||||
|
||||
## 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)
|
||||
~~~
|
||||
|
||||
**Проверка:** Спецсимволы остаются данными, опасные опции/разделители отвергаются; штатные допустимые аргументы работают.
|
||||
|
||||
<details>
|
||||
<summary>Развёрнутый пример и ограничения</summary>
|
||||
|
||||
```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
|
||||
и аргументы отдельно, ограничивать время через контекст; аргументы всё ещё может
|
||||
интерпретировать сама программа.
|
||||
|
||||
</details>
|
||||
|
||||
**Вариант 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).
|
||||
|
||||
<a id="go-crc"></a>
|
||||
|
||||
<a id="go-crc-crc-near-an-identifier-or-trust-boundary"></a>
|
||||
|
||||
## 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).
|
||||
|
||||
<a id="go-math-rand"></a>
|
||||
|
||||
<a id="go-math-rand-mathrand-near-a-possible-secret"></a>
|
||||
|
||||
## 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).
|
||||
|
||||
<a id="go-readall-body"></a>
|
||||
|
||||
<a id="go-readall-body-readall-on-a-request-body"></a>
|
||||
|
||||
## 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; штатный максимальный документ работает.
|
||||
|
||||
<a id="go-pprof"></a>
|
||||
|
||||
<a id="go-pprof-pprof-registered-on-an-http-mux"></a>
|
||||
|
||||
## 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).
|
||||
|
||||
<a id="go-fileserver"></a>
|
||||
|
||||
<a id="go-fileserver-fileserver-publishes-a-file-tree"></a>
|
||||
|
||||
## 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).
|
||||
|
||||
<a id="go-auth-return"></a>
|
||||
|
||||
<a id="go-auth-return-execution-continues-after-httperror"></a>
|
||||
|
||||
## 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; свой запрос работает.
|
||||
|
||||
<a id="go-json-fields"></a>
|
||||
|
||||
<a id="go-json-fields-json-entities-and-ambiguous-keys"></a>
|
||||
|
||||
## 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.
|
||||
|
||||
<a id="go-race"></a>
|
||||
|
||||
<a id="go-race-shared-mapslice-state-and-check-then-use"></a>
|
||||
|
||||
## 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-отчёта не доказывает отсутствие логической гонки.
|
||||
|
||||
<a id="go-error-default"></a>
|
||||
|
||||
<a id="go-error-default-ignored-errors-produce-a-zero-principal"></a>
|
||||
|
||||
## 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/таймаут БД не авторизуют и не возвращают чужое; допустимый ноль по контракту обработан явно.
|
||||
|
||||
<a id="go-ssrf"></a>
|
||||
|
||||
<a id="go-ssrf-http-clients-and-redirects"></a>
|
||||
|
||||
## 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).
|
||||
|
||||
<a id="go-zip-path"></a>
|
||||
|
||||
<a id="go-zip-path-filepathjoin-does-not-enforce-containment"></a>
|
||||
|
||||
## 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).
|
||||
|
||||
<a id="go-tls-min"></a>
|
||||
|
||||
<a id="go-tls-min-obsolete-minimum-tls-version"></a>
|
||||
|
||||
## 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-соединения в этой проверке не запускались.
|
||||
|
||||
<a id="go-jwt-unverified"></a>
|
||||
|
||||
<a id="go-jwt-unverified-jwt-without-signature-or-claims-verification"></a>
|
||||
|
||||
## 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).
|
||||
|
||||
<a id="go-upload-path"></a>
|
||||
|
||||
<a id="go-upload-path-multipart-filename-used-directly-in-a-joined-path"></a>
|
||||
|
||||
## 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)
|
||||
@@ -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)
|
||||
|
||||
<a id="go-sql"></a>
|
||||
|
||||
## 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.
|
||||
|
||||
<details>
|
||||
<summary>Expanded example and limitations</summary>
|
||||
|
||||
```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().
|
||||
|
||||
</details>
|
||||
|
||||
<a id="go-hash-sum"></a>
|
||||
|
||||
## 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).
|
||||
|
||||
<a id="go-html"></a>
|
||||
|
||||
## 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.
|
||||
|
||||
<details>
|
||||
<summary>Expanded example and limitations</summary>
|
||||
|
||||
```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("<p>{{.}}</p>")
|
||||
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.
|
||||
|
||||
</details>
|
||||
|
||||
<a id="go-tls"></a>
|
||||
|
||||
## 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.
|
||||
|
||||
<a id="go-shell"></a>
|
||||
|
||||
## 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.
|
||||
|
||||
<details>
|
||||
<summary>Expanded example and limitations</summary>
|
||||
|
||||
```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.
|
||||
|
||||
</details>
|
||||
|
||||
**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).
|
||||
|
||||
<a id="go-crc"></a>
|
||||
|
||||
## 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).
|
||||
|
||||
<a id="go-math-rand"></a>
|
||||
|
||||
## 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).
|
||||
|
||||
<a id="go-readall-body"></a>
|
||||
|
||||
## 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.
|
||||
|
||||
<a id="go-pprof"></a>
|
||||
|
||||
## 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).
|
||||
|
||||
<a id="go-fileserver"></a>
|
||||
|
||||
## 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).
|
||||
|
||||
<a id="go-auth-return"></a>
|
||||
|
||||
## 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.
|
||||
|
||||
<a id="go-json-fields"></a>
|
||||
|
||||
## 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.
|
||||
|
||||
<a id="go-race"></a>
|
||||
|
||||
## 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.
|
||||
|
||||
<a id="go-error-default"></a>
|
||||
|
||||
## 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.
|
||||
|
||||
<a id="go-ssrf"></a>
|
||||
|
||||
## 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).
|
||||
|
||||
<a id="go-zip-path"></a>
|
||||
|
||||
## 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).
|
||||
|
||||
<a id="go-tls-min"></a>
|
||||
|
||||
## 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.
|
||||
|
||||
<a id="go-jwt-unverified"></a>
|
||||
|
||||
## 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).
|
||||
|
||||
<a id="go-upload-path"></a>
|
||||
|
||||
## 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)
|
||||
Loaded 100 of 217 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user