feat: build wahrwelt A/D toolkit
This commit is contained in:
1 parent
303438d206
commit
653924d8c6
564 files changed
+36310
-49998
No files matched your search
@@ -0,0 +1,37 @@
|
||||
# Доступ к интерфейсам. Для команды укажите LAN-адрес хоста.
|
||||
BIND_ADDRESS=127.0.0.1
|
||||
FARM_PORT=8080
|
||||
NEO_PORT=5005
|
||||
PACKMATE_PORT=65000
|
||||
PACKMATE_USERNAME=packmate
|
||||
|
||||
# ./control init создает .env со случайными паролями и ключами.
|
||||
FARM_PASSWORD=
|
||||
FARM_DB_PASSWORD=
|
||||
NEO_KEY=
|
||||
NEO_WORKER_KEY=
|
||||
PACKMATE_PASSWORD=
|
||||
PACKMATE_DB_PASSWORD=
|
||||
|
||||
# Параметры соревнования задаются вручную.
|
||||
FARM_TEAMS='{"Example":"192.0.2.1"}'
|
||||
FARM_FLAG_FORMAT='[A-Z0-9]{31}='
|
||||
FARM_FLAG_LIFETIME=300
|
||||
FARM_SYSTEM_PROTOCOL=
|
||||
FARM_SYSTEM_HOST=
|
||||
FARM_SYSTEM_PORT=31337
|
||||
FARM_SYSTEM_URL=
|
||||
FARM_SYSTEM_TOKEN=
|
||||
FARM_SYSTEM_VALIDATOR=
|
||||
FARM_SYSTEM_SERVER_KEY=
|
||||
|
||||
# Параллелизм исполнителя Neo.
|
||||
NEO_WORKER_JOBS=2
|
||||
NEO_WORKER_ENDLESS_JOBS=0
|
||||
|
||||
# Разбор закрытого файла. LIVE настраивается отдельным Compose-файлом Packmate.
|
||||
PACKMATE_LOCAL_IP=192.0.2.1
|
||||
PACKMATE_PCAP_FILE=/pcaps/capture.pcap
|
||||
PACKMATE_MEMORY_LIMIT=2g
|
||||
PACKMATE_INTERFACE_NAME=
|
||||
PACKMATE_DB_PORT=65432
|
||||
@@ -1,38 +0,0 @@
|
||||
---
|
||||
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.
|
||||
@@ -1,39 +0,0 @@
|
||||
---
|
||||
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.
|
||||
@@ -1,32 +0,0 @@
|
||||
---
|
||||
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).
|
||||
@@ -1,34 +0,0 @@
|
||||
---
|
||||
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).
|
||||
@@ -1,29 +0,0 @@
|
||||
---
|
||||
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).
|
||||
@@ -1,34 +0,0 @@
|
||||
---
|
||||
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).
|
||||
@@ -1,28 +0,0 @@
|
||||
<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), а не публичной демонстрации эксплойта.
|
||||
@@ -1,32 +0,0 @@
|
||||
|
||||
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.
|
||||
@@ -1,208 +0,0 @@
|
||||
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"
|
||||
+19
-3
@@ -3,13 +3,29 @@
|
||||
!.env.example
|
||||
.ssh/
|
||||
.venv/
|
||||
node_modules/
|
||||
dist/
|
||||
.gradle/
|
||||
build/
|
||||
.pytest_cache/
|
||||
.ruff_cache/
|
||||
.mypy_cache/
|
||||
.idea/
|
||||
.vscode/
|
||||
coverage/
|
||||
out/
|
||||
components/neo/data/
|
||||
components/neo/volumes/
|
||||
components/neo/neo_client
|
||||
components/neo/neo_server
|
||||
components/neo/client
|
||||
components/neo/server
|
||||
components/neo/exploits/
|
||||
*.tsbuildinfo
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
artifacts/
|
||||
.codex-remote-attachments/
|
||||
docs/validation/
|
||||
local/
|
||||
upstream/
|
||||
*.pcap
|
||||
*.pcapng
|
||||
*.db
|
||||
|
||||
@@ -1,25 +0,0 @@
|
||||
# История изменений
|
||||
|
||||
[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, конкретный ноутбук или сеть соревнования.
|
||||
@@ -1,22 +0,0 @@
|
||||
# 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.
|
||||
@@ -1,29 +0,0 @@
|
||||
<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.
|
||||
@@ -1,26 +0,0 @@
|
||||
# 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.
|
||||
@@ -2,6 +2,16 @@ MIT License
|
||||
|
||||
Copyright (c) 2026 DurkaHelper contributors
|
||||
|
||||
S4DFarm:
|
||||
Original work Copyright (c) 2017, 2018 Alexander Borzunov ("Destructive Voice" team)
|
||||
Modified work Copyright (c) 2021 Roman Nikitin ("C4T BuT S4D" team)
|
||||
|
||||
Neo:
|
||||
Copyright (c) 2021 Roman Nikitin
|
||||
|
||||
Packmate:
|
||||
Copyright (c) 2020 Packmate
|
||||
|
||||
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
|
||||
|
||||
-100
@@ -1,100 +0,0 @@
|
||||
<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).
|
||||
@@ -1,94 +1,116 @@
|
||||
# DurkaHelper
|
||||
# wahrwelt A/D
|
||||
|
||||
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.
|
||||
Инструменты команды для A/D. Основной стенд: Linux x86_64 и Docker Compose.
|
||||
|
||||
## What does what
|
||||
При сборке используются обновляемые теги образов и актуальные совместимые
|
||||
библиотеки. Для Python достаточно коротких `requirements.txt` с `>=`.
|
||||
Java-образ остается на линии 27, чтобы собирать Packmate.
|
||||
Farm и Neo используют плавающий образ `python:alpine`; в проверенной сборке
|
||||
от 2026-10-14 он содержал Python 3.15.0. Локальный сканер запускается системным
|
||||
Python и не требует внешних библиотек.
|
||||
|
||||
| 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. |
|
||||
| Инструмент | Назначение |
|
||||
| ---------- | ------------------------------------------------------------------ |
|
||||
| Сканер | Проверка локальных исходников и рецепты исправлений. |
|
||||
| S4DFarm | Прием, учет и отправка флагов. |
|
||||
| Neo | Распределение заданий между исполнителями и передача флагов ферме. |
|
||||
| Packmate | Просмотр потоков, поиск по трафику и шаблоны подсветки. |
|
||||
|
||||
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
|
||||
./control init
|
||||
# Настройте .env: адрес команды, сервисы и параметры соревнования.
|
||||
./control farm # Только Farm с базой данных и интерфейсом.
|
||||
./control neo # Только Neo с Redis и исполнителем.
|
||||
./control pack # Только Packmate с базой данных.
|
||||
# Или ./control all-up для всего стенда.
|
||||
```
|
||||
|
||||
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.
|
||||
`init` создает приватный `.env` и рабочие каталоги, контейнеры не запускает.
|
||||
Повторный `init` сохраняет существующие пароли.
|
||||
По умолчанию веб-интерфейсы доступны только на этом компьютере: Farm на порту
|
||||
8080, Packmate на 65000. Neo управляется через CLI и слушает gRPC на порту 5005.
|
||||
Для доступа команды задайте
|
||||
`BIND_ADDRESS` равным LAN-адресу хоста.
|
||||
|
||||
To host the shared tools, start Docker Desktop on macOS or Docker Engine with Compose on Linux:
|
||||
Остановка сохраняет данные. Отправка в систему соревнования включается отдельно:
|
||||
|
||||
```bash
|
||||
python3 durka.py init
|
||||
./control pack down
|
||||
./control farm restart
|
||||
./control neo logs
|
||||
./control status
|
||||
./control farm submit-up # Включить отправку после настройки .env.
|
||||
./control farm submit-down
|
||||
./control all-down
|
||||
```
|
||||
|
||||
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.
|
||||
У каждого компонента есть `up`, `down`, `restart`, `logs` и `status`.
|
||||
`./control --help` показывает справку. Равнозначный запуск: `python3 control.py`.
|
||||
|
||||
Use an actual Ethernet IPv4 for teammate access and native Neo workers. Loopback is suitable for a laptop-only demo with the bundled worker.
|
||||
## От скрипта до борды
|
||||
|
||||
Настройте в `.env` адреса команд `FARM_TEAMS`, формат флага `FARM_FLAG_FORMAT`
|
||||
и параметры системы приема `FARM_SYSTEM_*`. Затем запустите Farm и Neo:
|
||||
|
||||
```bash
|
||||
python3 durka.py setup
|
||||
python3 durka.py up
|
||||
python3 durka.py status
|
||||
./control farm
|
||||
./control neo
|
||||
```
|
||||
|
||||
`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:
|
||||
Полученный скрипт сначала проверьте на разрешенном адресе. `test` покажет вывод,
|
||||
код завершения и найденные флаги без их отправки. Для автоматической работы
|
||||
загрузите скрипт, включите его и просмотрите журнал:
|
||||
|
||||
```bash
|
||||
python3 durka.py worker
|
||||
python3 durka.py submit
|
||||
./control neo test ./sploit_example.py 192.0.2.10 --timeout 10s
|
||||
./control neo add ./sploit_example.py --id example --disabled
|
||||
./control neo enable example
|
||||
./control neo tail example
|
||||
```
|
||||
|
||||
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.
|
||||
Повторный `neo add` с тем же `--id` загружает новую версию скрипта.
|
||||
Neo запускает задание по адресам из Farm и передает найденные флаги в Farm.
|
||||
Готовый флаг можно положить в Farm напрямую:
|
||||
|
||||
## During the game
|
||||
```bash
|
||||
./control farm flag 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA='
|
||||
```
|
||||
|
||||
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`.
|
||||
То же действие есть в веб-интерфейсе Farm. Флаги появятся в очереди и таблице.
|
||||
После настройки протокола, адреса и токена системы соревнования включите отправку:
|
||||
|
||||
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).
|
||||
```bash
|
||||
./control farm submit-up
|
||||
```
|
||||
|
||||
## Find, fix and verify
|
||||
Статусы ответов системы видны в Farm. Если скрипту нужны соседние файлы,
|
||||
укажите `--dir` в `neo test` и `neo add`.
|
||||
В корне лежит [sploit_example.py](sploit_example.py): он получает адрес цели первым аргументом,
|
||||
делает HTTP-запрос и печатает уникальные совпадения формата
|
||||
`FARM_FLAG_FORMAT`. Настройте порт, путь и регулярное выражение в начале файла,
|
||||
затем добавьте логику своего задания в `run_exploit`. Neo передает
|
||||
напечатанные флаги в Farm; отправка на борду включается отдельно командой
|
||||
`./control farm submit-up`. Подробности: [Neo](components/neo/README.md),
|
||||
[Farm](components/farm/README.md), [Packmate и LIVE](components/packmate/README.md).
|
||||
|
||||
**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 |
|
||||
```bash
|
||||
./control scan /путь/к/проекту --patches
|
||||
./control scan-external /путь/к/проекту
|
||||
```
|
||||
|
||||
## Development
|
||||
Встроенный сканер запускается системным Python без установки библиотек. Он не запускает проверяемый код. Подробности: [справка по сканерам](docs/scanners.md), [каталог правил](docs/vulnerabilities/README.md).
|
||||
|
||||
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).
|
||||
Происхождение исходников и уведомления MIT собраны в [LICENSE](LICENSE).
|
||||
@@ -1,24 +0,0 @@
|
||||
<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
@@ -1,21 +0,0 @@
|
||||
# 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.
|
||||
@@ -1,18 +0,0 @@
|
||||
<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 внешние кеши и экспорты образов остаются приватными артефактами оператора. При обезличивании операторских данных не удаляйте указание авторства.
|
||||
@@ -1,17 +0,0 @@
|
||||
# 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,21 @@
|
||||
# wahrwelt / Farm
|
||||
|
||||
Веб-панель принимает флаги через API, хранит очередь в PostgreSQL и показывает статусы.
|
||||
Интерфейс собран на Vue 3 и Quasar 2; API работает на Python 3.15 и Flask.
|
||||
|
||||
Компонент основан на [S4DFarm](https://github.com/C4T-BuT-S4D/S4DFarm), коммит
|
||||
`3b8b057c95e0467c6afb3a47648e8b6befd1a815`. Исходная лицензия сохранена в [общем LICENSE](../../LICENSE).
|
||||
Удалены клиент запуска командных скриптов, HTTP-прокси и старые интеграции; отправку флагов
|
||||
в систему проверки выполняет только отдельный процесс `farm-submit`.
|
||||
|
||||
Корневой Compose публикует интерфейс на `${BIND_ADDRESS:-127.0.0.1}:${FARM_PORT:-8080}`. Внутренний адрес API для Neo:
|
||||
`http://farm:5000`. Оба маршрута, `/api/get_config` и `/api/post_flags`, принимают пароль в
|
||||
заголовках `Authorization` и `X-Token`.
|
||||
|
||||
Для запуска только фермы выполните из корня `./control farm`.
|
||||
Настройки соревнования задаются в корневом `.env`. Отправка включается командой
|
||||
`./control farm submit-up` после настройки адреса и протокола.
|
||||
Остановка отправки: `./control farm submit-down`; всей фермы: `./control farm down`.
|
||||
Готовый флаг можно поставить в очередь без Neo: `./control farm flag 'ФЛАГ'`.
|
||||
Для обычной ручной отправки используется метка `Manual`; указать конкретную
|
||||
команду и скрипт можно через `--team` и `--script`.
|
||||
@@ -0,0 +1,149 @@
|
||||
services:
|
||||
farm-db:
|
||||
build:
|
||||
context: ../../containers
|
||||
dockerfile: postgres.Dockerfile
|
||||
environment:
|
||||
POSTGRES_DB: farm
|
||||
POSTGRES_USER: farm
|
||||
POSTGRES_PASSWORD: ${FARM_DB_PASSWORD:?Задайте FARM_DB_PASSWORD}
|
||||
volumes:
|
||||
- farm-db:/var/lib/postgresql
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U farm -d farm"]
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
retries: 12
|
||||
start_period: 10s
|
||||
mem_limit: 512m
|
||||
restart: unless-stopped
|
||||
networks:
|
||||
- farm-data
|
||||
|
||||
farm:
|
||||
build:
|
||||
context: ./server
|
||||
additional_contexts:
|
||||
project: ../..
|
||||
dockerfile: docker/server/Dockerfile
|
||||
environment:
|
||||
FARM_PASSWORD: ${FARM_PASSWORD:?Задайте FARM_PASSWORD}
|
||||
FARM_TEAMS: ${FARM_TEAMS:-}
|
||||
FARM_FLAG_FORMAT: ${FARM_FLAG_FORMAT:-}
|
||||
FARM_SYSTEM_PROTOCOL: ${FARM_SYSTEM_PROTOCOL:-}
|
||||
FARM_SYSTEM_HOST: ${FARM_SYSTEM_HOST:-}
|
||||
FARM_SYSTEM_PORT: ${FARM_SYSTEM_PORT:-31337}
|
||||
FARM_SYSTEM_URL: ${FARM_SYSTEM_URL:-}
|
||||
FARM_SYSTEM_TOKEN: ${FARM_SYSTEM_TOKEN:-}
|
||||
FARM_SYSTEM_VALIDATOR: ${FARM_SYSTEM_VALIDATOR:-}
|
||||
FARM_SYSTEM_SERVER_KEY: ${FARM_SYSTEM_SERVER_KEY:-}
|
||||
FARM_SUBMIT_FLAG_LIMIT: ${FARM_SUBMIT_FLAG_LIMIT:-100}
|
||||
FARM_SUBMIT_PERIOD: ${FARM_SUBMIT_PERIOD:-2}
|
||||
FARM_FLAG_LIFETIME: ${FARM_FLAG_LIFETIME:-300}
|
||||
FARM_INFO_FLAG_LIMIT: ${FARM_INFO_FLAG_LIMIT:-10}
|
||||
FARM_TIMEZONE: ${FARM_TIMEZONE:-Europe/Moscow}
|
||||
POSTGRES_DSN: postgresql://farm:${FARM_DB_PASSWORD:?Задайте FARM_DB_PASSWORD}@farm-db:5432/farm
|
||||
expose:
|
||||
- "5000"
|
||||
depends_on:
|
||||
farm-db:
|
||||
condition: service_healthy
|
||||
networks:
|
||||
- default
|
||||
- farm-data
|
||||
healthcheck:
|
||||
test: ["CMD", "python", "-c", "from urllib.request import urlopen; urlopen('http://127.0.0.1:5000/healthz', timeout=2)"]
|
||||
interval: 10s
|
||||
timeout: 3s
|
||||
retries: 6
|
||||
start_period: 10s
|
||||
mem_limit: 384m
|
||||
pids_limit: 128
|
||||
read_only: true
|
||||
cap_drop:
|
||||
- ALL
|
||||
security_opt:
|
||||
- no-new-privileges:true
|
||||
tmpfs:
|
||||
- /tmp:rw,noexec,nosuid,nodev,size=32m,mode=1777
|
||||
restart: unless-stopped
|
||||
|
||||
farm-front:
|
||||
build:
|
||||
context: ./server
|
||||
additional_contexts:
|
||||
project: ../..
|
||||
dockerfile: docker/front/Dockerfile
|
||||
ports:
|
||||
- "${BIND_ADDRESS:-127.0.0.1}:${FARM_PORT:-8080}:8080"
|
||||
depends_on:
|
||||
farm:
|
||||
condition: service_healthy
|
||||
networks:
|
||||
- default
|
||||
healthcheck:
|
||||
test: ["CMD", "wget", "-q", "-O", "/dev/null", "http://127.0.0.1:8080/healthz"]
|
||||
interval: 10s
|
||||
timeout: 3s
|
||||
retries: 6
|
||||
start_period: 5s
|
||||
mem_limit: 128m
|
||||
pids_limit: 64
|
||||
read_only: true
|
||||
cap_drop:
|
||||
- ALL
|
||||
security_opt:
|
||||
- no-new-privileges:true
|
||||
tmpfs:
|
||||
- /tmp:rw,noexec,nosuid,nodev,size=32m,mode=1777
|
||||
restart: unless-stopped
|
||||
|
||||
farm-submit:
|
||||
build:
|
||||
context: ./server
|
||||
additional_contexts:
|
||||
project: ../..
|
||||
dockerfile: docker/server/Dockerfile
|
||||
profiles: [submission]
|
||||
command: ["python", "sender.py"]
|
||||
environment:
|
||||
FARM_PASSWORD: ${FARM_PASSWORD:?Задайте FARM_PASSWORD}
|
||||
FARM_TEAMS: ${FARM_TEAMS:-}
|
||||
FARM_FLAG_FORMAT: ${FARM_FLAG_FORMAT:-}
|
||||
FARM_SYSTEM_PROTOCOL: ${FARM_SYSTEM_PROTOCOL:-}
|
||||
FARM_SYSTEM_HOST: ${FARM_SYSTEM_HOST:-}
|
||||
FARM_SYSTEM_PORT: ${FARM_SYSTEM_PORT:-31337}
|
||||
FARM_SYSTEM_URL: ${FARM_SYSTEM_URL:-}
|
||||
FARM_SYSTEM_TOKEN: ${FARM_SYSTEM_TOKEN:-}
|
||||
FARM_SYSTEM_VALIDATOR: ${FARM_SYSTEM_VALIDATOR:-}
|
||||
FARM_SYSTEM_SERVER_KEY: ${FARM_SYSTEM_SERVER_KEY:-}
|
||||
FARM_SUBMIT_FLAG_LIMIT: ${FARM_SUBMIT_FLAG_LIMIT:-100}
|
||||
FARM_SUBMIT_PERIOD: ${FARM_SUBMIT_PERIOD:-2}
|
||||
FARM_FLAG_LIFETIME: ${FARM_FLAG_LIFETIME:-300}
|
||||
FARM_INFO_FLAG_LIMIT: ${FARM_INFO_FLAG_LIMIT:-10}
|
||||
FARM_TIMEZONE: ${FARM_TIMEZONE:-Europe/Moscow}
|
||||
POSTGRES_DSN: postgresql://farm:${FARM_DB_PASSWORD:?Задайте FARM_DB_PASSWORD}@farm-db:5432/farm
|
||||
depends_on:
|
||||
farm-db:
|
||||
condition: service_healthy
|
||||
restart: on-failure:3
|
||||
stop_grace_period: 10m
|
||||
mem_limit: 256m
|
||||
pids_limit: 64
|
||||
read_only: true
|
||||
cap_drop:
|
||||
- ALL
|
||||
security_opt:
|
||||
- no-new-privileges:true
|
||||
tmpfs:
|
||||
- /tmp:rw,noexec,nosuid,nodev,size=32m,mode=1777
|
||||
networks:
|
||||
- default
|
||||
- farm-data
|
||||
|
||||
volumes:
|
||||
farm-db:
|
||||
|
||||
networks:
|
||||
farm-data:
|
||||
internal: true
|
||||
@@ -0,0 +1,8 @@
|
||||
**/__pycache__/
|
||||
**/*.py[cod]
|
||||
**/.pytest_cache/
|
||||
**/.venv/
|
||||
front/node_modules/
|
||||
front/dist/
|
||||
.git/
|
||||
*.log
|
||||
@@ -0,0 +1,3 @@
|
||||
from app_flask import app
|
||||
|
||||
__all__ = ('app',)
|
||||
@@ -0,0 +1,263 @@
|
||||
import re
|
||||
import time
|
||||
from collections import defaultdict
|
||||
from datetime import datetime
|
||||
|
||||
from flask import Blueprint, jsonify, request
|
||||
from prometheus_client import Counter, Gauge
|
||||
|
||||
import auth
|
||||
from config import CONFIG
|
||||
from database import db_cursor
|
||||
from models import FlagStatus
|
||||
from validators.volgactf import validate_flags as validate_volgactf_flags
|
||||
|
||||
api = Blueprint('api', __name__, url_prefix='/api')
|
||||
|
||||
FLAGS_RECEIVED = Counter(
|
||||
'flags_received',
|
||||
'Число полученных флагов',
|
||||
['sploit', 'team'],
|
||||
)
|
||||
TOTAL_TEAMS = Gauge('total_teams', 'Число команд')
|
||||
TOTAL_TEAMS.set_function(lambda: len(CONFIG['TEAMS']))
|
||||
|
||||
PUBLIC_CONFIG_KEYS = (
|
||||
'FLAG_FORMAT',
|
||||
'TEAMS',
|
||||
)
|
||||
MAX_FLAGS_PER_REQUEST = 1000
|
||||
MAX_FILTER_LENGTH = 256
|
||||
|
||||
|
||||
def _bad_request(message):
|
||||
return jsonify({'error': message}), 400
|
||||
|
||||
|
||||
def _query_conditions(filters):
|
||||
conditions = []
|
||||
for column in ('sploit', 'status', 'team'):
|
||||
value = filters.get(column, '').strip()
|
||||
if value:
|
||||
if len(value) > MAX_FILTER_LENGTH:
|
||||
raise ValueError('Значение фильтра слишком длинное')
|
||||
conditions.append((f'{column} = %s', value))
|
||||
|
||||
for column in ('flag', 'checksystem_response'):
|
||||
value = filters.get(column, '').strip()
|
||||
if value:
|
||||
if len(value) > MAX_FILTER_LENGTH:
|
||||
raise ValueError('Значение фильтра слишком длинное')
|
||||
conditions.append((f'POSITION(%s in LOWER({column})) > 0', value.lower()))
|
||||
|
||||
for column in ('since', 'until'):
|
||||
value = filters.get(column, '').strip()
|
||||
if value:
|
||||
try:
|
||||
timestamp = round(datetime.strptime(value, '%Y-%m-%d %H:%M').timestamp())
|
||||
except ValueError as exc:
|
||||
raise ValueError('Дата должна иметь формат ГГГГ-ММ-ДД ЧЧ:ММ') from exc
|
||||
sign = '>=' if column == 'since' else '<='
|
||||
conditions.append((f'time {sign} %s', timestamp))
|
||||
|
||||
return conditions
|
||||
|
||||
|
||||
def _parse_positive_int(value, name, default, maximum):
|
||||
try:
|
||||
result = int(value or default)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValueError(f'Параметр {name} должен быть целым числом') from exc
|
||||
if not 1 <= result <= maximum:
|
||||
raise ValueError(f'Параметр {name} вне допустимого диапазона')
|
||||
return result
|
||||
|
||||
|
||||
def _validated_flags(payload):
|
||||
if not isinstance(payload, list) or len(payload) > MAX_FLAGS_PER_REQUEST:
|
||||
raise ValueError(f'Ожидается список не более чем из {MAX_FLAGS_PER_REQUEST} флагов')
|
||||
|
||||
pattern = re.compile(CONFIG['FLAG_FORMAT'])
|
||||
validated = []
|
||||
team_names = set(CONFIG['TEAMS'])
|
||||
for item in payload:
|
||||
if not isinstance(item, dict) or set(item) != {'flag', 'sploit', 'team'}:
|
||||
raise ValueError('Каждый элемент должен содержать только flag, sploit и team')
|
||||
flag, sploit, team = item['flag'], item['sploit'], item['team']
|
||||
if not all(isinstance(value, str) for value in (flag, sploit, team)):
|
||||
raise ValueError('Поля flag, sploit и team должны быть строками')
|
||||
if (not flag or len(flag) > 4096 or not pattern.fullmatch(flag)
|
||||
or any(ord(char) < 32 for char in flag)):
|
||||
raise ValueError('Флаг не соответствует FARM_FLAG_FORMAT')
|
||||
if (not sploit.strip() or len(sploit) > 128
|
||||
or any(ord(char) < 32 for char in sploit)):
|
||||
raise ValueError('Некорректное имя sploit')
|
||||
if team == '*' and sploit == 'Manual':
|
||||
pass
|
||||
elif team not in team_names:
|
||||
raise ValueError('Команда отсутствует в FARM_TEAMS')
|
||||
validated.append({'flag': flag, 'sploit': sploit, 'team': team})
|
||||
return validated
|
||||
|
||||
|
||||
@api.route('/get_config')
|
||||
@auth.auth_required
|
||||
def get_config():
|
||||
return jsonify({key: CONFIG[key] for key in PUBLIC_CONFIG_KEYS})
|
||||
|
||||
|
||||
@api.route('/post_flags', methods=['POST'])
|
||||
@auth.auth_required
|
||||
def post_flags():
|
||||
payload = request.get_json(silent=True)
|
||||
if payload is None:
|
||||
return _bad_request('Ожидается JSON-массив флагов')
|
||||
try:
|
||||
flags = _validated_flags(payload)
|
||||
except ValueError as exc:
|
||||
return _bad_request(str(exc))
|
||||
|
||||
if CONFIG['SYSTEM_VALIDATOR']:
|
||||
try:
|
||||
flags = list(validate_volgactf_flags(flags, CONFIG))
|
||||
except Exception:
|
||||
return jsonify({'error': 'Не удалось проверить полученные флаги'}), 400
|
||||
|
||||
cur_time = round(time.time())
|
||||
rows = [
|
||||
{
|
||||
'flag': flag['flag'],
|
||||
'sploit': flag['sploit'],
|
||||
'team': flag['team'],
|
||||
'time': cur_time,
|
||||
'status': FlagStatus.QUEUED.name,
|
||||
}
|
||||
for flag in flags
|
||||
]
|
||||
|
||||
if rows:
|
||||
with db_cursor() as (conn, curs):
|
||||
curs.executemany(
|
||||
"""
|
||||
INSERT INTO flags (flag, sploit, team, time, status)
|
||||
VALUES (%(flag)s, %(sploit)s, %(team)s, %(time)s, %(status)s)
|
||||
ON CONFLICT DO NOTHING
|
||||
""",
|
||||
rows,
|
||||
)
|
||||
conn.commit()
|
||||
|
||||
for flag in flags:
|
||||
FLAGS_RECEIVED.labels(sploit=flag['sploit'], team=flag['team']).inc()
|
||||
|
||||
return '', 200
|
||||
|
||||
|
||||
@api.route('/filter_flags', methods=['GET'])
|
||||
@auth.auth_required
|
||||
def get_filtered_flags():
|
||||
try:
|
||||
conditions = _query_conditions(request.args)
|
||||
page = _parse_positive_int(request.args.get('page'), 'page', 1, 100000)
|
||||
page_size = _parse_positive_int(request.args.get('page_size'), 'page_size', 30, 100)
|
||||
except ValueError as exc:
|
||||
return _bad_request(str(exc))
|
||||
|
||||
if conditions:
|
||||
chunks, values = list(zip(*conditions))
|
||||
conditions_sql = 'WHERE ' + ' AND '.join(chunks)
|
||||
conditions_args = list(values)
|
||||
else:
|
||||
conditions_sql = ''
|
||||
conditions_args = []
|
||||
|
||||
sql = 'SELECT * FROM flags ' + conditions_sql + ' ORDER BY time DESC LIMIT %s OFFSET %s'
|
||||
args = conditions_args + [page_size, page_size * (page - 1)]
|
||||
count_sql = 'SELECT COUNT(*) as cnt FROM flags ' + conditions_sql
|
||||
|
||||
with db_cursor() as (_, curs):
|
||||
curs.execute(sql, args)
|
||||
flags = curs.fetchall()
|
||||
curs.execute(count_sql, conditions_args)
|
||||
total_count = curs.fetchone()['cnt']
|
||||
|
||||
return jsonify({
|
||||
'flags': list(map(dict, flags)),
|
||||
'page_size': page_size,
|
||||
'page': page,
|
||||
'total': total_count,
|
||||
})
|
||||
|
||||
|
||||
@api.route('/filter_config', methods=['GET'])
|
||||
@auth.auth_required
|
||||
def get_filter_config():
|
||||
distinct_values = {}
|
||||
with db_cursor() as (_, curs):
|
||||
for column in ('sploit', 'status', 'team'):
|
||||
curs.execute(f'SELECT DISTINCT {column} FROM flags ORDER BY {column}')
|
||||
distinct_values[column] = [item[column] for item in curs.fetchall()]
|
||||
|
||||
server_tz_name = time.strftime('%Z')
|
||||
if server_tz_name.startswith('+'):
|
||||
server_tz_name = 'UTC' + server_tz_name
|
||||
|
||||
return jsonify({
|
||||
'filters': distinct_values,
|
||||
'flag_format': CONFIG['FLAG_FORMAT'],
|
||||
'server_tz': server_tz_name,
|
||||
})
|
||||
|
||||
|
||||
@api.route('/summary', methods=['GET'])
|
||||
@auth.auth_required
|
||||
def summary():
|
||||
try:
|
||||
conditions = _query_conditions(request.args)
|
||||
last = request.args.get('last', '').strip()
|
||||
if last:
|
||||
seconds = _parse_positive_int(last, 'last', 0, 31_536_000)
|
||||
conditions.append(('time >= %s', round(time.time() - seconds)))
|
||||
except ValueError as exc:
|
||||
return _bad_request(str(exc))
|
||||
|
||||
if conditions:
|
||||
chunks, values = list(zip(*conditions))
|
||||
conditions_sql = 'WHERE ' + ' AND '.join(chunks)
|
||||
conditions_args = list(values)
|
||||
else:
|
||||
conditions_sql = ''
|
||||
conditions_args = []
|
||||
|
||||
with db_cursor() as (_, curs):
|
||||
curs.execute('SELECT * FROM flags ' + conditions_sql, conditions_args)
|
||||
flags = curs.fetchall()
|
||||
|
||||
result = defaultdict(lambda: defaultdict(lambda: defaultdict(int)))
|
||||
include_response = request.args.get('response', '')
|
||||
for item in flags:
|
||||
response = item.get('checksystem_response') or ''
|
||||
key = response[:64] if include_response else item['status']
|
||||
result[item['sploit']][item['team']][key] += 1
|
||||
|
||||
sploits = []
|
||||
for sploit, teams in result.items():
|
||||
rows = []
|
||||
for team in CONFIG['TEAMS']:
|
||||
if team not in teams:
|
||||
rows.append({'team': team, 'team_status': 'нет данных'})
|
||||
for team, statuses in teams.items():
|
||||
output = ''.join(f'{key}: {value}\n' for key, value in statuses.items())
|
||||
rows.append({'team': team, 'team_status': output})
|
||||
sploits.append({'sploit_name': sploit, 'teams': rows})
|
||||
|
||||
return jsonify(sploits)
|
||||
|
||||
|
||||
@api.route('/teams', methods=['GET'])
|
||||
@auth.auth_required
|
||||
def get_teams():
|
||||
return jsonify([
|
||||
{'name': name, 'address': address}
|
||||
for name, address in CONFIG['TEAMS'].items()
|
||||
])
|
||||
@@ -0,0 +1,9 @@
|
||||
from factory import create_app
|
||||
from log import setup_logging
|
||||
|
||||
setup_logging('INFO')
|
||||
|
||||
app = create_app()
|
||||
|
||||
if __name__ == '__main__':
|
||||
app.run(debug=False, port=5000, host='127.0.0.1')
|
||||
@@ -0,0 +1,24 @@
|
||||
import hmac
|
||||
from functools import wraps
|
||||
|
||||
from flask import request, abort
|
||||
|
||||
from config import CONFIG
|
||||
|
||||
|
||||
def auth_required(f):
|
||||
@wraps(f)
|
||||
def decorated(*args, **kwargs):
|
||||
config = CONFIG
|
||||
auth = request.headers.get('Authorization') or request.headers.get('X-Token') or ''
|
||||
try:
|
||||
supplied = auth.encode('ascii')
|
||||
except UnicodeEncodeError:
|
||||
abort(403)
|
||||
expected = config['SERVER_PASSWORD'].encode('ascii')
|
||||
if not hmac.compare_digest(supplied, expected):
|
||||
abort(403)
|
||||
|
||||
return f(*args, **kwargs)
|
||||
|
||||
return decorated
|
||||
@@ -0,0 +1,110 @@
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
import re
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
|
||||
SUPPORTED_PROTOCOLS = frozenset({
|
||||
'ctfcup_tcp',
|
||||
'faust',
|
||||
'ructf_http',
|
||||
'ructf_tcp',
|
||||
'volgactf',
|
||||
})
|
||||
|
||||
|
||||
def load_config(environ=None):
|
||||
environ = os.environ if environ is None else environ
|
||||
password = environ.get('FARM_PASSWORD', '')
|
||||
if not password.isascii() or len(password) < 32:
|
||||
raise RuntimeError('FARM_PASSWORD должен содержать не менее 32 ASCII-символов')
|
||||
|
||||
try:
|
||||
teams = json.loads(environ.get('FARM_TEAMS') or '{"Example":"192.0.2.1"}')
|
||||
except json.JSONDecodeError as exc:
|
||||
raise RuntimeError('FARM_TEAMS должен быть корректным JSON-объектом') from exc
|
||||
if not isinstance(teams, dict) or not 1 <= len(teams) <= 256:
|
||||
raise RuntimeError('FARM_TEAMS должен содержать от 1 до 256 команд')
|
||||
for name, address in teams.items():
|
||||
if (not isinstance(name, str) or not name.strip() or len(name) > 100
|
||||
or not isinstance(address, str) or not address.strip() or len(address) > 253
|
||||
or any(ord(char) < 32 or ord(char) == 127 for char in name + address)):
|
||||
raise RuntimeError('FARM_TEAMS содержит некорректное имя или адрес')
|
||||
|
||||
flag_format = environ.get('FARM_FLAG_FORMAT') or r'[A-Z0-9]{31}='
|
||||
if len(flag_format) > 256:
|
||||
raise RuntimeError('FARM_FLAG_FORMAT слишком длинный')
|
||||
try:
|
||||
re.compile(flag_format)
|
||||
except re.error as exc:
|
||||
raise RuntimeError('FARM_FLAG_FORMAT содержит некорректное регулярное выражение') from exc
|
||||
|
||||
protocol = environ.get('FARM_SYSTEM_PROTOCOL', '').strip() or None
|
||||
if protocol and protocol not in SUPPORTED_PROTOCOLS:
|
||||
raise RuntimeError('FARM_SYSTEM_PROTOCOL не поддерживается')
|
||||
|
||||
try:
|
||||
port = int(environ.get('FARM_SYSTEM_PORT', '31337'))
|
||||
submit_limit = int(environ.get('FARM_SUBMIT_FLAG_LIMIT', '100'))
|
||||
submit_period = float(environ.get('FARM_SUBMIT_PERIOD', '2'))
|
||||
flag_lifetime = int(environ.get('FARM_FLAG_LIFETIME', '300'))
|
||||
info_limit = int(environ.get('FARM_INFO_FLAG_LIMIT', '10'))
|
||||
except ValueError as exc:
|
||||
raise RuntimeError('Параметры отправки флагов должны быть числами') from exc
|
||||
if not 1 <= port <= 65535 or not 1 <= submit_limit <= 10000:
|
||||
raise RuntimeError('Порт или лимит отправки флагов вне допустимого диапазона')
|
||||
if (not math.isfinite(submit_period) or not 0.1 <= submit_period <= 3600
|
||||
or not 1 <= flag_lifetime <= 86400 or not 1 <= info_limit <= 10000):
|
||||
raise RuntimeError('Параметр отправки флагов вне допустимого диапазона')
|
||||
|
||||
validator = environ.get('FARM_SYSTEM_VALIDATOR', '').strip() or None
|
||||
if validator not in (None, 'volgactf'):
|
||||
raise RuntimeError('FARM_SYSTEM_VALIDATOR не поддерживается')
|
||||
server_key = environ.get('FARM_SYSTEM_SERVER_KEY', '').strip() or None
|
||||
if validator and not server_key:
|
||||
raise RuntimeError('Для FARM_SYSTEM_VALIDATOR=volgactf задайте FARM_SYSTEM_SERVER_KEY')
|
||||
|
||||
return {
|
||||
'DEBUG': False,
|
||||
'TEAMS': teams,
|
||||
'FLAG_FORMAT': flag_format,
|
||||
'SYSTEM_PROTOCOL': protocol,
|
||||
'SYSTEM_URL': environ.get('FARM_SYSTEM_URL', '').strip() or None,
|
||||
'SYSTEM_TOKEN': environ.get('FARM_SYSTEM_TOKEN', '').strip() or None,
|
||||
'SYSTEM_HOST': environ.get('FARM_SYSTEM_HOST', '').strip() or None,
|
||||
'SYSTEM_PORT': port,
|
||||
'SYSTEM_VALIDATOR': validator,
|
||||
'SYSTEM_SERVER_KEY': server_key,
|
||||
'SUBMIT_FLAG_LIMIT': submit_limit,
|
||||
'SUBMIT_PERIOD': submit_period,
|
||||
'FLAG_LIFETIME': flag_lifetime,
|
||||
'INFO_FLAG_LIMIT': info_limit,
|
||||
'SERVER_PASSWORD': password,
|
||||
'TIMEZONE': environ.get('FARM_TIMEZONE', 'Europe/Moscow'),
|
||||
}
|
||||
|
||||
|
||||
def validate_submission_config(config):
|
||||
protocol = config.get('SYSTEM_PROTOCOL')
|
||||
if not protocol:
|
||||
raise RuntimeError('Отправка отключена: задайте FARM_SYSTEM_PROTOCOL')
|
||||
if protocol == 'ructf_http':
|
||||
url = config.get('SYSTEM_URL')
|
||||
token = config.get('SYSTEM_TOKEN')
|
||||
parsed = urlsplit(url or '')
|
||||
try:
|
||||
parsed.port
|
||||
except ValueError:
|
||||
raise RuntimeError('Для ructf_http задайте корректный FARM_SYSTEM_URL')
|
||||
if (parsed.scheme not in {'http', 'https'} or not parsed.hostname
|
||||
or parsed.username is not None or parsed.password is not None or parsed.fragment):
|
||||
raise RuntimeError('Для ructf_http задайте корректный FARM_SYSTEM_URL')
|
||||
if not token:
|
||||
raise RuntimeError('Для ructf_http задайте FARM_SYSTEM_TOKEN')
|
||||
return
|
||||
if not config.get('SYSTEM_HOST'):
|
||||
raise RuntimeError(f'Для {protocol} задайте FARM_SYSTEM_HOST')
|
||||
|
||||
|
||||
CONFIG = load_config()
|
||||
@@ -0,0 +1,11 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
BASE_DIR = Path(__file__).resolve().parent
|
||||
RESOURCES_DIR = BASE_DIR / 'resources'
|
||||
|
||||
SCHEMA_PATH = RESOURCES_DIR / 'schema.sql'
|
||||
|
||||
POSTGRES_DSN = os.getenv('POSTGRES_DSN', '').strip()
|
||||
if not POSTGRES_DSN:
|
||||
raise RuntimeError('Не задан POSTGRES_DSN')
|
||||
@@ -0,0 +1,91 @@
|
||||
"""Пул соединений PostgreSQL и блокировка отправителя."""
|
||||
|
||||
import logging
|
||||
import threading
|
||||
from contextlib import contextmanager
|
||||
|
||||
from psycopg.rows import dict_row
|
||||
from psycopg_pool import ConnectionPool
|
||||
|
||||
from constants import SCHEMA_PATH, POSTGRES_DSN
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class DBPool:
|
||||
_lock = threading.RLock()
|
||||
_value = None
|
||||
|
||||
@staticmethod
|
||||
def create():
|
||||
p = ConnectionPool(
|
||||
conninfo=POSTGRES_DSN,
|
||||
min_size=1,
|
||||
max_size=10,
|
||||
open=False,
|
||||
)
|
||||
logger.info('Инициализация схемы базы данных')
|
||||
try:
|
||||
p.open(wait=True, timeout=10)
|
||||
with p.connection() as conn:
|
||||
with conn.cursor() as curs:
|
||||
curs.execute('SELECT pg_advisory_xact_lock(1128774993, 1)')
|
||||
for statement in SCHEMA_PATH.read_text().split(';'):
|
||||
if statement.strip():
|
||||
curs.execute(statement)
|
||||
except Exception:
|
||||
p.close()
|
||||
raise
|
||||
return p
|
||||
|
||||
@classmethod
|
||||
def get(cls):
|
||||
with cls._lock:
|
||||
if cls._value is None:
|
||||
cls._value = cls.create()
|
||||
return cls._value
|
||||
|
||||
|
||||
@contextmanager
|
||||
def db_cursor(dict_cursor: bool = True):
|
||||
db_pool = DBPool.get()
|
||||
conn = db_pool.getconn(timeout=10)
|
||||
|
||||
if dict_cursor:
|
||||
curs = conn.cursor(row_factory=dict_row)
|
||||
else:
|
||||
curs = conn.cursor()
|
||||
try:
|
||||
yield conn, curs
|
||||
finally:
|
||||
try:
|
||||
curs.close()
|
||||
finally:
|
||||
try:
|
||||
conn.rollback()
|
||||
finally:
|
||||
db_pool.putconn(conn)
|
||||
|
||||
|
||||
@contextmanager
|
||||
def advisory_lock(lock_id: int):
|
||||
db_pool = DBPool.get()
|
||||
conn = db_pool.getconn()
|
||||
curs = conn.cursor()
|
||||
acquired = False
|
||||
try:
|
||||
curs.execute('SELECT pg_try_advisory_lock(%s)', (lock_id,))
|
||||
acquired = bool(curs.fetchone()[0])
|
||||
yield acquired
|
||||
finally:
|
||||
try:
|
||||
if acquired:
|
||||
curs.execute('SELECT pg_advisory_unlock(%s)', (lock_id,))
|
||||
finally:
|
||||
try:
|
||||
curs.close()
|
||||
finally:
|
||||
try:
|
||||
conn.rollback()
|
||||
finally:
|
||||
db_pool.putconn(conn)
|
||||
@@ -0,0 +1,55 @@
|
||||
import logging
|
||||
import time
|
||||
|
||||
from flask import Flask, Response, g, request
|
||||
from prometheus_client import CONTENT_TYPE_LATEST, Counter, Histogram, generate_latest
|
||||
|
||||
from api import api
|
||||
from config import CONFIG
|
||||
|
||||
HTTP_REQUESTS = Counter(
|
||||
'http_requests_total',
|
||||
'Количество обработанных HTTP-запросов',
|
||||
['method', 'endpoint', 'status'],
|
||||
)
|
||||
HTTP_REQUEST_DURATION = Histogram(
|
||||
'http_request_duration_seconds',
|
||||
'Время обработки HTTP-запросов в секундах',
|
||||
['method', 'endpoint'],
|
||||
)
|
||||
|
||||
|
||||
def create_app():
|
||||
app = Flask('s4d_farm')
|
||||
app.config.update(CONFIG)
|
||||
app.config['MAX_CONTENT_LENGTH'] = 1024 * 1024
|
||||
app.logger.setLevel(logging.INFO)
|
||||
for handler in app.logger.handlers:
|
||||
handler.setLevel(logging.INFO)
|
||||
|
||||
app.register_blueprint(api)
|
||||
|
||||
|
||||
@app.before_request
|
||||
def start_request_timer():
|
||||
g.request_started_at = time.perf_counter()
|
||||
|
||||
@app.after_request
|
||||
def record_request(response):
|
||||
if request.endpoint != 'metrics':
|
||||
endpoint = request.endpoint or 'unknown'
|
||||
HTTP_REQUESTS.labels(request.method, endpoint, str(response.status_code)).inc()
|
||||
HTTP_REQUEST_DURATION.labels(request.method, endpoint).observe(
|
||||
time.perf_counter() - g.request_started_at
|
||||
)
|
||||
return response
|
||||
|
||||
@app.route('/metrics')
|
||||
def metrics():
|
||||
return Response(generate_latest(), mimetype=CONTENT_TYPE_LATEST)
|
||||
|
||||
@app.route('/healthz')
|
||||
def healthz():
|
||||
return {'status': 'ok'}
|
||||
|
||||
return app
|
||||
@@ -0,0 +1,41 @@
|
||||
import logging.config
|
||||
from typing import Any
|
||||
|
||||
|
||||
def get_logging_config(level: str = 'DEBUG') -> dict[str, Any]:
|
||||
return {
|
||||
'version': 1,
|
||||
|
||||
'formatters': {
|
||||
'brief': {
|
||||
'format': '%(message)s',
|
||||
},
|
||||
'default': {
|
||||
'format': f'[%(asctime)s.%(msecs)03d] [%(levelname)s] [%(name)s] %(message)s',
|
||||
'datefmt': '%Y-%m-%d %H:%M:%S',
|
||||
},
|
||||
},
|
||||
|
||||
'handlers': {
|
||||
'console': {
|
||||
'class': 'logging.StreamHandler',
|
||||
'level': level,
|
||||
'formatter': 'default',
|
||||
'stream': 'ext://sys.stdout',
|
||||
},
|
||||
},
|
||||
|
||||
'root': {
|
||||
'handlers': ['console'],
|
||||
'level': level,
|
||||
},
|
||||
|
||||
'disable_existing_loggers': False,
|
||||
|
||||
}
|
||||
|
||||
|
||||
def setup_logging(level: str = 'DEBUG') -> dict[str, Any]:
|
||||
cfg = get_logging_config(level=level)
|
||||
logging.config.dictConfig(cfg)
|
||||
return cfg
|
||||
@@ -0,0 +1,26 @@
|
||||
from enum import Enum
|
||||
from dataclasses import dataclass
|
||||
|
||||
|
||||
class FlagStatus(Enum):
|
||||
QUEUED = 0
|
||||
SKIPPED = 1
|
||||
ACCEPTED = 2
|
||||
REJECTED = 3
|
||||
|
||||
|
||||
@dataclass
|
||||
class Flag:
|
||||
flag: str
|
||||
sploit: str
|
||||
team: str
|
||||
time: int
|
||||
status: FlagStatus
|
||||
checksystem_response: str
|
||||
|
||||
|
||||
@dataclass
|
||||
class SubmitResult:
|
||||
flag: str
|
||||
status: FlagStatus
|
||||
checksystem_response: str
|
||||
Whitespace-only changes.
@@ -0,0 +1,85 @@
|
||||
import socket
|
||||
import logging
|
||||
|
||||
from models import FlagStatus, SubmitResult
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
RESPONSES = {
|
||||
FlagStatus.QUEUED: ['timeout', 'game not started', 'try again later', 'game over', 'is not up',
|
||||
'no such flag'],
|
||||
FlagStatus.ACCEPTED: ['accepted', 'congrat'],
|
||||
FlagStatus.REJECTED: (
|
||||
[
|
||||
'bad',
|
||||
'wrong',
|
||||
'expired',
|
||||
'unknown',
|
||||
'your own',
|
||||
'too old',
|
||||
'not in database',
|
||||
'already submitted',
|
||||
'invalid flag',
|
||||
] + [
|
||||
'self',
|
||||
'invalid',
|
||||
'already_submitted',
|
||||
'team_not_found',
|
||||
'too_old',
|
||||
]
|
||||
),
|
||||
}
|
||||
|
||||
READ_TIMEOUT = 5
|
||||
APPEND_TIMEOUT = 0.05
|
||||
BUFSIZE = 4096
|
||||
|
||||
|
||||
def recvall(sock):
|
||||
sock.settimeout(READ_TIMEOUT)
|
||||
chunks = [sock.recv(BUFSIZE)]
|
||||
|
||||
sock.settimeout(APPEND_TIMEOUT)
|
||||
while True:
|
||||
try:
|
||||
chunk = sock.recv(BUFSIZE)
|
||||
if not chunk:
|
||||
break
|
||||
|
||||
chunks.append(chunk)
|
||||
except socket.timeout:
|
||||
break
|
||||
|
||||
sock.settimeout(READ_TIMEOUT)
|
||||
return b''.join(chunks)
|
||||
|
||||
|
||||
def submit_flags(flags, config):
|
||||
sock = socket.create_connection((config['SYSTEM_HOST'], config['SYSTEM_PORT']),
|
||||
READ_TIMEOUT)
|
||||
greeting = recvall(sock)
|
||||
if b'Please enter flags' not in greeting:
|
||||
raise RuntimeError('Чекер не отправил приветствие: {}'.format(greeting))
|
||||
|
||||
unknown_responses = set()
|
||||
for item in flags:
|
||||
sock.sendall(item.flag.encode() + b'\n')
|
||||
response = recvall(sock).decode().strip()
|
||||
if response:
|
||||
response = response.splitlines()[0]
|
||||
response = response.replace('[{}] '.format(item.flag), '')
|
||||
|
||||
response_lower = response.lower()
|
||||
for status, substrings in RESPONSES.items():
|
||||
if any(s in response_lower for s in substrings):
|
||||
found_status = status
|
||||
break
|
||||
else:
|
||||
found_status = FlagStatus.QUEUED
|
||||
if response not in unknown_responses:
|
||||
unknown_responses.add(response)
|
||||
logger.warning('Неизвестный ответ чекера (флаг будет отправлен повторно): %s', response)
|
||||
|
||||
yield SubmitResult(item.flag, found_status, response)
|
||||
|
||||
sock.close()
|
||||
@@ -0,0 +1,86 @@
|
||||
import socket
|
||||
import logging
|
||||
import time
|
||||
|
||||
from models import FlagStatus, SubmitResult
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
RESPONSES = {
|
||||
FlagStatus.QUEUED: [
|
||||
'ERR',
|
||||
'INV',
|
||||
],
|
||||
FlagStatus.ACCEPTED: [
|
||||
'OK',
|
||||
],
|
||||
FlagStatus.REJECTED: [
|
||||
'DUP',
|
||||
'OWN',
|
||||
'OLD',
|
||||
],
|
||||
}
|
||||
|
||||
READ_TIMEOUT = 5
|
||||
APPEND_TIMEOUT = 0.05
|
||||
BUFSIZE = 4096
|
||||
|
||||
|
||||
def recvall(sock):
|
||||
sock.settimeout(READ_TIMEOUT)
|
||||
chunks = [sock.recv(BUFSIZE)]
|
||||
|
||||
sock.settimeout(APPEND_TIMEOUT)
|
||||
while True:
|
||||
try:
|
||||
chunk = sock.recv(BUFSIZE)
|
||||
if not chunk:
|
||||
break
|
||||
|
||||
chunks.append(chunk)
|
||||
except socket.timeout:
|
||||
break
|
||||
|
||||
sock.settimeout(READ_TIMEOUT)
|
||||
return b''.join(chunks)
|
||||
|
||||
|
||||
def submit_flags(flags, config):
|
||||
sock = socket.create_connection((config['SYSTEM_HOST'], config['SYSTEM_PORT']),
|
||||
READ_TIMEOUT)
|
||||
greeting = recvall(sock)
|
||||
if b'One flag per line please' not in greeting:
|
||||
raise RuntimeError('Чекер не отправил приветствие: {}'.format(greeting))
|
||||
|
||||
unknown_responses = set()
|
||||
sock.sendall(b'\n'.join(item.flag.encode() for item in flags) + b'\n')
|
||||
|
||||
while len(flags) > 0:
|
||||
response = recvall(sock).decode().strip()
|
||||
if not response:
|
||||
break
|
||||
|
||||
response = response.splitlines()
|
||||
for line in response:
|
||||
flag = flags[0]
|
||||
line = line.replace(f'{flag.flag} ', '')
|
||||
|
||||
for status, substrings in RESPONSES.items():
|
||||
if any(s in line for s in substrings):
|
||||
found_status = status
|
||||
break
|
||||
else:
|
||||
found_status = FlagStatus.QUEUED
|
||||
if line not in unknown_responses:
|
||||
unknown_responses.add(line)
|
||||
logger.warning('Неизвестный ответ чекера (флаг будет отправлен повторно): %s', line)
|
||||
|
||||
if found_status == FlagStatus.QUEUED and time.time() - flag.time > 10:
|
||||
found_status = FlagStatus.REJECTED
|
||||
line = f'was response {line}, but inv flag too old'
|
||||
|
||||
yield SubmitResult(flag.flag, found_status, line)
|
||||
|
||||
flags = flags[1:]
|
||||
|
||||
sock.close()
|
||||
@@ -0,0 +1,47 @@
|
||||
import requests
|
||||
import logging
|
||||
|
||||
from models import FlagStatus, SubmitResult
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
RESPONSES = {
|
||||
FlagStatus.QUEUED: ['timeout', 'game not started', 'try again later', 'game over', 'is not up',
|
||||
'no such flag'],
|
||||
FlagStatus.ACCEPTED: ['accepted', 'congrat'],
|
||||
FlagStatus.REJECTED: ['bad', 'wrong', 'expired', 'unknown', 'your own',
|
||||
'too old', 'not in database', 'already submitted', 'invalid flag'],
|
||||
}
|
||||
# Чекер RuCTF добавляет подпись ко всем правильным флагам. Он возвращает
|
||||
# "invalid flag", если подпись неверна, и "no such flag", если подпись верна,
|
||||
# но флаг пока отсутствует в базе чекера.
|
||||
#
|
||||
# Так бывает, когда сервис публикует флаг раньше, чем чекер сохраняет его у себя.
|
||||
# В этом случае флаг нужно отправить повторно позже.
|
||||
|
||||
|
||||
TIMEOUT = 5
|
||||
|
||||
|
||||
def submit_flags(flags, config):
|
||||
r = requests.put(config['SYSTEM_URL'],
|
||||
headers={'X-Team-Token': config['SYSTEM_TOKEN']},
|
||||
json=[item.flag for item in flags], timeout=TIMEOUT)
|
||||
|
||||
unknown_responses = set()
|
||||
for item in r.json():
|
||||
response = item['msg'].strip()
|
||||
response = response.replace('[{}] '.format(item['flag']), '')
|
||||
|
||||
response_lower = response.lower()
|
||||
for status, substrings in RESPONSES.items():
|
||||
if any(s in response_lower for s in substrings):
|
||||
found_status = status
|
||||
break
|
||||
else:
|
||||
found_status = FlagStatus.QUEUED
|
||||
if response not in unknown_responses:
|
||||
unknown_responses.add(response)
|
||||
logger.warning('Неизвестный ответ чекера (флаг будет отправлен повторно): %s', response)
|
||||
|
||||
yield SubmitResult(item['flag'], found_status, response)
|
||||
@@ -0,0 +1,75 @@
|
||||
import socket
|
||||
import logging
|
||||
|
||||
from models import FlagStatus, SubmitResult
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
RESPONSES = {
|
||||
FlagStatus.QUEUED: ['timeout', 'game not started', 'try again later', 'game over', 'is not up',
|
||||
'no such flag'],
|
||||
FlagStatus.ACCEPTED: ['accepted', 'congrat'],
|
||||
FlagStatus.REJECTED: ['bad', 'wrong', 'expired', 'unknown', 'your own',
|
||||
'too old', 'not in database', 'already submitted', 'invalid flag'],
|
||||
}
|
||||
# Чекер RuCTF добавляет подпись ко всем правильным флагам. Он возвращает
|
||||
# "invalid flag", если подпись неверна, и "no such flag", если подпись верна,
|
||||
# но флаг пока отсутствует в базе чекера.
|
||||
#
|
||||
# Так бывает, когда сервис публикует флаг раньше, чем чекер сохраняет его у себя.
|
||||
# В этом случае флаг нужно отправить повторно позже.
|
||||
|
||||
READ_TIMEOUT = 5
|
||||
APPEND_TIMEOUT = 0.05
|
||||
BUFSIZE = 4096
|
||||
|
||||
|
||||
def recvall(sock):
|
||||
sock.settimeout(READ_TIMEOUT)
|
||||
chunks = [sock.recv(BUFSIZE)]
|
||||
|
||||
sock.settimeout(APPEND_TIMEOUT)
|
||||
while True:
|
||||
try:
|
||||
chunk = sock.recv(BUFSIZE)
|
||||
if not chunk:
|
||||
break
|
||||
|
||||
chunks.append(chunk)
|
||||
except socket.timeout:
|
||||
break
|
||||
|
||||
sock.settimeout(READ_TIMEOUT)
|
||||
return b''.join(chunks)
|
||||
|
||||
|
||||
def submit_flags(flags, config):
|
||||
sock = socket.create_connection((config['SYSTEM_HOST'], config['SYSTEM_PORT']),
|
||||
READ_TIMEOUT)
|
||||
|
||||
greeting = recvall(sock)
|
||||
if b'Enter your flags' not in greeting:
|
||||
raise RuntimeError('Чекер не отправил приветствие: {}'.format(greeting))
|
||||
|
||||
unknown_responses = set()
|
||||
for item in flags:
|
||||
sock.sendall(item.flag.encode() + b'\n')
|
||||
response = recvall(sock).decode().strip()
|
||||
if response:
|
||||
response = response.splitlines()[0]
|
||||
response = response.replace('[{}] '.format(item.flag), '')
|
||||
|
||||
response_lower = response.lower()
|
||||
for status, substrings in RESPONSES.items():
|
||||
if any(s in response_lower for s in substrings):
|
||||
found_status = status
|
||||
break
|
||||
else:
|
||||
found_status = FlagStatus.QUEUED
|
||||
if response not in unknown_responses:
|
||||
unknown_responses.add(response)
|
||||
logger.warning('Неизвестный ответ чекера (флаг будет отправлен повторно): %s', response)
|
||||
|
||||
yield SubmitResult(item.flag, found_status, response)
|
||||
|
||||
sock.close()
|
||||
@@ -0,0 +1,154 @@
|
||||
import datetime
|
||||
from enum import Enum
|
||||
from itertools import chain
|
||||
from urllib.parse import quote
|
||||
|
||||
import dateutil.parser
|
||||
import pytz
|
||||
import requests
|
||||
import logging
|
||||
|
||||
from models import FlagStatus, SubmitResult
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class ChecksystemResult(Enum):
|
||||
SUCCESS = 0 # submitted flag has been accepted
|
||||
ERROR_UNKNOWN = 1 # generic error
|
||||
ERROR_ACCESS_DENIED = 2 # the attacker does not appear to be a team
|
||||
ERROR_COMPETITION_NOT_STARTED = 3 # contest has not been started yet
|
||||
ERROR_COMPETITION_PAUSED = 4 # contest has been paused
|
||||
ERROR_COMPETITION_FINISHED = 5 # contest has been completed
|
||||
ERROR_FLAG_INVALID = 6 # submitted data has invalid format
|
||||
ERROR_RATELIMIT = 7 # attack attempts limit exceeded
|
||||
ERROR_FLAG_EXPIRED = 8 # submitted flag has expired
|
||||
ERROR_FLAG_YOUR_OWN = 9 # submitted flag belongs to the attacking team
|
||||
ERROR_FLAG_SUBMITTED = 10 # submitted flag has been accepted already
|
||||
ERROR_FLAG_NOT_FOUND = 11 # submitted flag hs not been found
|
||||
ERROR_SERVICE_STATE_INVALID = 12 # the attacking team service is not up
|
||||
|
||||
|
||||
class GetInfoResult(Enum):
|
||||
SUCCESS = 0 # submitted flag has been accepted
|
||||
ERROR_UNKNOWN = 1 # generic error
|
||||
ERROR_ACCESS_DENIED = 2 # getinfo calls are allowed from a team's subnet
|
||||
ERROR_NOT_FOUND = 3 # flag is invalid
|
||||
ERROR_RATELIMIT = 4 # rate limit exceeded
|
||||
|
||||
|
||||
RESPONSES = {
|
||||
FlagStatus.ACCEPTED: {
|
||||
ChecksystemResult.SUCCESS: 'success'
|
||||
},
|
||||
FlagStatus.QUEUED: {
|
||||
ChecksystemResult.ERROR_UNKNOWN: 'unknown error',
|
||||
ChecksystemResult.ERROR_ACCESS_DENIED: 'access denied',
|
||||
ChecksystemResult.ERROR_COMPETITION_NOT_STARTED: 'competition has not started',
|
||||
ChecksystemResult.ERROR_COMPETITION_PAUSED: 'competition is paused',
|
||||
ChecksystemResult.ERROR_COMPETITION_FINISHED: 'competition has finished',
|
||||
ChecksystemResult.ERROR_RATELIMIT: 'ratelimit exceeded',
|
||||
ChecksystemResult.ERROR_SERVICE_STATE_INVALID: 'attacking team service down',
|
||||
},
|
||||
FlagStatus.REJECTED: {
|
||||
ChecksystemResult.ERROR_FLAG_INVALID: 'invalid flag',
|
||||
ChecksystemResult.ERROR_FLAG_EXPIRED: 'expired',
|
||||
ChecksystemResult.ERROR_FLAG_YOUR_OWN: 'you own flag',
|
||||
ChecksystemResult.ERROR_FLAG_SUBMITTED: 'already submitted',
|
||||
ChecksystemResult.ERROR_FLAG_NOT_FOUND: 'not found',
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
class API:
|
||||
def __init__(self, host: str, timezone: str, version='v1'):
|
||||
self.api_base = f'https://{host}/api/flag/{version}'
|
||||
self.timezone = pytz.timezone(timezone)
|
||||
|
||||
def flag_is_fresh(self, info, until_seconds=2):
|
||||
expiry = dateutil.parser.parse(info['exp'])
|
||||
until = datetime.datetime.now() + datetime.timedelta(seconds=until_seconds)
|
||||
until = self.timezone.localize(until)
|
||||
return expiry >= until
|
||||
|
||||
def parse_flag_info_response(self, flag: str, response: requests.Response):
|
||||
if response.status_code == 200:
|
||||
info = response.json()
|
||||
if self.flag_is_fresh(info):
|
||||
return True, None
|
||||
return False, SubmitResult(flag, FlagStatus.REJECTED, 'expired')
|
||||
|
||||
try:
|
||||
respcode = GetInfoResult[response.text]
|
||||
except: # noqa
|
||||
respcode = GetInfoResult.ERROR_UNKNOWN
|
||||
|
||||
if respcode == GetInfoResult.ERROR_RATELIMIT:
|
||||
return False, SubmitResult(flag, FlagStatus.QUEUED, 'ограничение частоты запросов сведений о флагах')
|
||||
|
||||
return False, SubmitResult(flag, FlagStatus.QUEUED, f'ошибка ответа getinfo для флага: {respcode}')
|
||||
|
||||
def info_flags(self, *flags: str):
|
||||
responses = list(map(
|
||||
lambda flag: requests.get(f'{self.api_base}/info/{quote(flag, safe="")}', timeout=5),
|
||||
flags,
|
||||
))
|
||||
return dict(zip(flags, map(self.parse_flag_info_response, flags, responses)))
|
||||
|
||||
@staticmethod
|
||||
def parse_flag_submit_response(flag: str, response: requests.Response):
|
||||
try:
|
||||
result_code = ChecksystemResult[response.text]
|
||||
except: # noqa
|
||||
result_code = ChecksystemResult.ERROR_UNKNOWN
|
||||
|
||||
for status, possible_codes in RESPONSES.items():
|
||||
if result_code in possible_codes:
|
||||
return SubmitResult(flag, status, RESPONSES[status][result_code])
|
||||
|
||||
return SubmitResult(flag, FlagStatus.QUEUED, f'неизвестный код чекера: {result_code}')
|
||||
|
||||
def submit_flags(self, *flags: str):
|
||||
h = {'Content-Type': 'text/plain'}
|
||||
responses = [
|
||||
requests.post(f'{self.api_base}/submit', data=flag, headers=h, timeout=5)
|
||||
for flag in flags
|
||||
]
|
||||
return map(self.parse_flag_submit_response, flags, responses)
|
||||
|
||||
|
||||
def submit_flags(flags, config):
|
||||
flags = list(map(lambda flag: flag.flag, flags))
|
||||
|
||||
api = API(host=config['SYSTEM_HOST'], timezone=config['TIMEZONE'])
|
||||
info_rate = config['INFO_FLAG_LIMIT']
|
||||
submit_rate = config['SUBMIT_FLAG_LIMIT']
|
||||
|
||||
# Запрашиваем сведения о максимально возможном числе флагов.
|
||||
flags_info = api.info_flags(*flags[:info_rate])
|
||||
flags_processed = info_rate
|
||||
|
||||
# Отбираем флаги, которые можно отправить.
|
||||
to_submit = list(filter(lambda flag: flags_info[flag][0], flags_info))
|
||||
# Остальные флаги уже истекли или недействительны.
|
||||
other_flags = map(
|
||||
lambda flag: flags_info[flag][1],
|
||||
filter(lambda flag: not flags_info[flag][0], flags_info)
|
||||
)
|
||||
# Если допустимых флагов мало, добавляем следующие из очереди.
|
||||
if len(to_submit) < submit_rate:
|
||||
flags_processed += submit_rate - len(to_submit)
|
||||
to_submit += flags[info_rate:flags_processed]
|
||||
|
||||
queued = map(
|
||||
lambda f: SubmitResult(f, FlagStatus.QUEUED, 'ограничение частоты отправки флагов'),
|
||||
to_submit[submit_rate:] + flags[flags_processed:]
|
||||
)
|
||||
|
||||
results = chain(
|
||||
api.submit_flags(*to_submit[:submit_rate]),
|
||||
other_flags,
|
||||
queued,
|
||||
)
|
||||
for res in results:
|
||||
yield res
|
||||
@@ -0,0 +1,13 @@
|
||||
CREATE TABLE IF NOT EXISTS flags (
|
||||
flag TEXT PRIMARY KEY,
|
||||
sploit TEXT,
|
||||
team TEXT,
|
||||
time INTEGER,
|
||||
status TEXT,
|
||||
checksystem_response TEXT
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_flags_sploit ON flags(sploit);
|
||||
CREATE INDEX IF NOT EXISTS idx_flags_team ON flags(team);
|
||||
CREATE INDEX IF NOT EXISTS idx_flags_status_time ON flags(status, time);
|
||||
CREATE INDEX IF NOT EXISTS idx_flags_time ON flags(time);
|
||||
@@ -0,0 +1,41 @@
|
||||
import logging
|
||||
import signal
|
||||
import time
|
||||
from threading import Event
|
||||
|
||||
from config import CONFIG, validate_submission_config
|
||||
from log import setup_logging
|
||||
from tasks import submit_flags_task
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def run(stop_event=None):
|
||||
validate_submission_config(CONFIG)
|
||||
stop_event = stop_event or Event()
|
||||
period = CONFIG['SUBMIT_PERIOD']
|
||||
|
||||
logger.info('Запуск отправителя флагов с интервалом %.2f с', period)
|
||||
while not stop_event.is_set():
|
||||
started = time.monotonic()
|
||||
try:
|
||||
submit_flags_task()
|
||||
except Exception:
|
||||
logger.exception('Ошибка обработки очереди флагов')
|
||||
stop_event.wait(max(0, period - (time.monotonic() - started)))
|
||||
|
||||
|
||||
def main():
|
||||
setup_logging('INFO')
|
||||
stop_event = Event()
|
||||
|
||||
def request_stop(_signum, _frame):
|
||||
stop_event.set()
|
||||
|
||||
signal.signal(signal.SIGTERM, request_stop)
|
||||
signal.signal(signal.SIGINT, request_stop)
|
||||
run(stop_event)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,106 @@
|
||||
import logging
|
||||
import time
|
||||
from collections import defaultdict
|
||||
|
||||
from prometheus_client import Counter, Gauge
|
||||
|
||||
from config import CONFIG
|
||||
from database import advisory_lock, db_cursor
|
||||
from models import Flag, FlagStatus
|
||||
from utils import get_fair_share, submit_flags
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
FLAGS_QUEUED = Gauge(
|
||||
'flags_queued',
|
||||
'Число флагов в очереди',
|
||||
['sploit', 'team'],
|
||||
)
|
||||
|
||||
FLAGS_SUBMITTED = Counter(
|
||||
'flags_submitted',
|
||||
'Число отправленных флагов',
|
||||
['sploit', 'team', 'status'],
|
||||
)
|
||||
|
||||
FLAGS_TIMED_OUT = Counter(
|
||||
'flags_timed_out',
|
||||
'Число флагов с истекшим сроком',
|
||||
)
|
||||
|
||||
|
||||
def submit_flags_task():
|
||||
with advisory_lock(1128774994) as acquired:
|
||||
if not acquired:
|
||||
logger.info('Пропуск отправки: предыдущая задача еще выполняется')
|
||||
return
|
||||
_submit_queued_flags()
|
||||
|
||||
|
||||
def _submit_queued_flags():
|
||||
logger.info('Обработка очереди флагов')
|
||||
config = CONFIG
|
||||
now = time.time()
|
||||
skip_time = round(now - config['FLAG_LIFETIME'])
|
||||
|
||||
with db_cursor(True) as (conn, curs):
|
||||
curs.execute(
|
||||
"""
|
||||
UPDATE flags SET status = %s WHERE status = %s AND time < %s
|
||||
""",
|
||||
(FlagStatus.SKIPPED.name, FlagStatus.QUEUED.name, skip_time),
|
||||
)
|
||||
skipped_flags = curs.rowcount
|
||||
conn.commit()
|
||||
curs.execute(
|
||||
"""
|
||||
SELECT * FROM flags WHERE status = %s
|
||||
""",
|
||||
(FlagStatus.QUEUED.name,),
|
||||
)
|
||||
queued_flags = [Flag(**item) for item in curs.fetchall()]
|
||||
|
||||
logger.info('В очереди: %s, просрочено: %s', len(queued_flags), skipped_flags)
|
||||
FLAGS_TIMED_OUT.inc(skipped_flags)
|
||||
|
||||
queued_by_labels: dict[(str, str), int] = defaultdict(int)
|
||||
for item in queued_flags:
|
||||
queued_by_labels[item.sploit, item.team] += 1
|
||||
for key, value in queued_by_labels.items():
|
||||
FLAGS_QUEUED.labels(sploit=key[0], team=key[1]).set(value)
|
||||
|
||||
if queued_flags:
|
||||
grouped_flags: dict[(str, str), list[Flag]] = defaultdict(list)
|
||||
for item in queued_flags:
|
||||
grouped_flags[item.sploit, item.team].append(item)
|
||||
flags = get_fair_share(list(grouped_flags.values()), config['SUBMIT_FLAG_LIMIT'])
|
||||
|
||||
flag_by_text = {item.flag: item for item in queued_flags}
|
||||
|
||||
logger.info('Отправка флагов: %s из %s', len(flags), len(queued_flags))
|
||||
|
||||
results = submit_flags(flags, config)
|
||||
|
||||
rows = []
|
||||
for submit_result in results:
|
||||
rows.append((
|
||||
submit_result.status.name,
|
||||
submit_result.checksystem_response,
|
||||
submit_result.flag,
|
||||
))
|
||||
|
||||
flag = flag_by_text[submit_result.flag]
|
||||
FLAGS_SUBMITTED.labels(
|
||||
sploit=flag.sploit,
|
||||
team=flag.team,
|
||||
status=submit_result.status.name,
|
||||
).inc()
|
||||
|
||||
with db_cursor(True) as (conn, curs):
|
||||
curs.executemany(
|
||||
"""
|
||||
UPDATE flags SET status = %s, checksystem_response = %s WHERE flag = %s
|
||||
""",
|
||||
rows,
|
||||
)
|
||||
conn.commit()
|
||||
@@ -0,0 +1,55 @@
|
||||
import importlib
|
||||
import logging
|
||||
import random
|
||||
import traceback
|
||||
from typing import List, TypeVar
|
||||
|
||||
from models import Flag, FlagStatus, SubmitResult
|
||||
|
||||
T = TypeVar('T')
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def get_fair_share(groups: List[List[T]], limit: int) -> List[T]:
|
||||
if not groups:
|
||||
return []
|
||||
|
||||
groups = sorted(groups, key=len)
|
||||
places_left = limit
|
||||
group_count = len(groups)
|
||||
fair_share = places_left // group_count
|
||||
|
||||
result = []
|
||||
residuals = []
|
||||
for group in groups:
|
||||
if len(group) <= fair_share:
|
||||
result += group
|
||||
|
||||
places_left -= len(group)
|
||||
group_count -= 1
|
||||
if group_count > 0:
|
||||
fair_share = places_left // group_count
|
||||
# Равная доля может вырасти, если в обработанной группе было мало
|
||||
# элементов. Сортировка гарантирует обработку меньших групп сначала.
|
||||
else:
|
||||
selected = random.sample(group, fair_share + 1)
|
||||
result += selected[:-1]
|
||||
residuals.append(selected[-1])
|
||||
result += random.sample(residuals, min(limit - len(result), len(residuals)))
|
||||
|
||||
random.shuffle(result)
|
||||
return result
|
||||
|
||||
|
||||
def submit_flags(flags: List[Flag], config) -> List[SubmitResult]:
|
||||
module_path = 'protocols.' + config['SYSTEM_PROTOCOL']
|
||||
logger.debug('Загрузка протокола %s', module_path)
|
||||
module = importlib.import_module(module_path)
|
||||
|
||||
try:
|
||||
return list(module.submit_flags(flags, config))
|
||||
except Exception as e:
|
||||
message = '{}: {}'.format(type(e).__name__, str(e))
|
||||
logger.error('Ошибка протокола отправки: %s\n%s', message, traceback.format_exc())
|
||||
return [SubmitResult(item.flag, FlagStatus.QUEUED, message) for item in flags]
|
||||
@@ -0,0 +1,43 @@
|
||||
import copy
|
||||
|
||||
import jwt
|
||||
import requests
|
||||
|
||||
API_PREFIX = 'api/capsule/v1'
|
||||
PUBLIC_KEY_ENDPOINT = 'public_key'
|
||||
|
||||
|
||||
def get_public_key(host):
|
||||
r = requests.get(f"{host}/{API_PREFIX}/{PUBLIC_KEY_ENDPOINT}", timeout=5)
|
||||
|
||||
if r is not None and r.status_code == requests.codes.ok:
|
||||
return r.text
|
||||
|
||||
raise ConnectionError("Не удалось получить открытый ключ для проверки флагов: %s" % host)
|
||||
|
||||
|
||||
def decode(key, capsule):
|
||||
payload = jwt.decode(
|
||||
capsule,
|
||||
algorithms=['ES256', 'RS256'],
|
||||
key=key
|
||||
)
|
||||
return payload
|
||||
|
||||
|
||||
def validate_flags(flags, config):
|
||||
key = config.get('SYSTEM_SERVER_KEY')
|
||||
if not key:
|
||||
key = get_public_key(config['SYSTEM_HOST'])
|
||||
|
||||
for item in flags:
|
||||
item = copy.deepcopy(item)
|
||||
flag = item['flag']
|
||||
if flag.startswith('VolgaCTF{'):
|
||||
flag = flag[len('VolgaCTF{'): -len('}')]
|
||||
|
||||
try:
|
||||
item['flag'] = decode(key, flag)['flag']
|
||||
yield item
|
||||
except: # noqa
|
||||
continue
|
||||
@@ -0,0 +1,26 @@
|
||||
FROM node:slim AS build
|
||||
|
||||
ENV PNPM_HOME=/pnpm \
|
||||
PATH=/pnpm:$PATH \
|
||||
NODE_OPTIONS=--max-old-space-size=1536
|
||||
|
||||
WORKDIR /app
|
||||
RUN npm install --global npm pnpm
|
||||
|
||||
COPY front/package.json front/pnpm-workspace.yaml ./
|
||||
RUN --mount=type=cache,id=wahrwelt-farm-pnpm,target=/pnpm/store pnpm install --no-frozen-lockfile --lockfile=false
|
||||
|
||||
COPY front/ ./
|
||||
RUN pnpm build
|
||||
|
||||
FROM nginxinc/nginx-unprivileged:alpine
|
||||
|
||||
USER root
|
||||
RUN apk upgrade --no-cache
|
||||
USER 101
|
||||
|
||||
COPY docker/front/app.conf /etc/nginx/conf.d/default.conf
|
||||
COPY --from=build /app/dist /usr/share/nginx/html
|
||||
|
||||
EXPOSE 8080
|
||||
COPY --from=project /LICENSE /usr/share/licenses/wahrwelt/LICENSE
|
||||
@@ -0,0 +1,34 @@
|
||||
server {
|
||||
listen 8080;
|
||||
server_name _;
|
||||
server_tokens off;
|
||||
root /usr/share/nginx/html;
|
||||
index index.html;
|
||||
client_max_body_size 1m;
|
||||
|
||||
add_header X-Content-Type-Options nosniff always;
|
||||
add_header X-Frame-Options DENY always;
|
||||
add_header Referrer-Policy no-referrer always;
|
||||
add_header Permissions-Policy "camera=(), geolocation=(), microphone=()" always;
|
||||
|
||||
location = /healthz {
|
||||
access_log off;
|
||||
add_header Content-Type text/plain;
|
||||
return 200 "ok\n";
|
||||
}
|
||||
|
||||
location /api/ {
|
||||
proxy_pass http://farm:5000;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_connect_timeout 5s;
|
||||
proxy_read_timeout 30s;
|
||||
}
|
||||
|
||||
location / {
|
||||
try_files $uri $uri/ /index.html;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
FROM python:alpine
|
||||
|
||||
ENV PYTHONDONTWRITEBYTECODE=1 \
|
||||
PYTHONUNBUFFERED=1 \
|
||||
PYTHONPATH=/app \
|
||||
PIP_DISABLE_PIP_VERSION_CHECK=1
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY requirements.txt ./requirements.txt
|
||||
RUN apk upgrade --no-cache \
|
||||
&& python -m pip install --no-cache-dir -r requirements.txt \
|
||||
&& python -m pip cache purge \
|
||||
&& python -m pip uninstall -y setuptools pip
|
||||
|
||||
COPY app/ ./
|
||||
RUN addgroup -S farm && adduser -S -D -H -G farm farm \
|
||||
&& chown -R farm:farm /app
|
||||
|
||||
COPY --from=project /LICENSE /usr/share/licenses/wahrwelt/LICENSE
|
||||
|
||||
USER farm
|
||||
EXPOSE 5000
|
||||
CMD ["gunicorn", "--bind=0.0.0.0:5000", "--workers=2", "--worker-class=gthread", "--threads=4", "--timeout=30", "--access-logfile=-", "--error-logfile=-", "app_flask:app"]
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"$schema": "https://json.schemastore.org/prettierrc",
|
||||
"semi": false,
|
||||
"tabWidth": 2,
|
||||
"singleQuote": true,
|
||||
"printWidth": 100,
|
||||
"trailingComma": "none"
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
const eslint = require('@eslint/js')
|
||||
const eslintConfigPrettier = require('eslint-config-prettier/flat')
|
||||
const globals = require('globals')
|
||||
const vue = require('eslint-plugin-vue')
|
||||
|
||||
module.exports = [
|
||||
{
|
||||
ignores: ['dist/**', 'node_modules/**']
|
||||
},
|
||||
{
|
||||
files: ['**/*.{js,mjs,cjs,vue}'],
|
||||
languageOptions: {
|
||||
ecmaVersion: 'latest',
|
||||
sourceType: 'module',
|
||||
globals: globals.browser
|
||||
},
|
||||
rules: eslint.configs.recommended.rules
|
||||
},
|
||||
{
|
||||
files: ['**/*.cjs'],
|
||||
languageOptions: {
|
||||
sourceType: 'commonjs',
|
||||
globals: globals.node
|
||||
}
|
||||
},
|
||||
...vue.configs['flat/essential'],
|
||||
eslintConfigPrettier
|
||||
]
|
||||
@@ -0,0 +1,18 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<link rel="icon" href="/logo.jpg" type="image/jpeg">
|
||||
<link rel="apple-touch-icon" href="/logo.jpg">
|
||||
<link rel="manifest" href="/manifest.webmanifest">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<meta name="theme-color" content="#333333">
|
||||
<meta name="application-name" content="wahrwelt / Farm">
|
||||
<meta name="description" content="Панель сбора флагов wahrwelt / Farm">
|
||||
<title>wahrwelt / Farm</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
<script type="module" src="/src/main.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,36 @@
|
||||
{
|
||||
"name": "wahrwelt-farm-ui",
|
||||
"version": "1.0.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"engines": {
|
||||
"node": ">=26"
|
||||
},
|
||||
"scripts": {
|
||||
"dev": "vite --host 127.0.0.1",
|
||||
"build": "vite build",
|
||||
"preview": "vite preview --host 127.0.0.1",
|
||||
"lint": "eslint .",
|
||||
"format": "prettier --write src/",
|
||||
"format:check": "prettier --check src/"
|
||||
},
|
||||
"dependencies": {
|
||||
"@quasar/extras": ">=2.1.0",
|
||||
"axios": ">=1.20.0",
|
||||
"quasar": ">=2.35.1",
|
||||
"vue": ">=3.5.44",
|
||||
"vue-router": ">=4.6.4",
|
||||
"vuex": ">=4.1.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": ">=10.0.1",
|
||||
"@vitejs/plugin-vue": ">=6.0.10",
|
||||
"eslint": ">=10.12.0",
|
||||
"eslint-config-prettier": ">=10.1.8",
|
||||
"eslint-plugin-vue": ">=10.11.1",
|
||||
"globals": ">=17.13.0",
|
||||
"prettier": ">=3.9.10",
|
||||
"sass": ">=1.105.1",
|
||||
"vite": ">=8.3.4"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
# Скрипт сборки watcher не запускается: он нужен только для режима наблюдения Sass.
|
||||
allowBuilds:
|
||||
'@parcel/watcher': false
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 23 KiB |
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"name": "wahrwelt / Farm",
|
||||
"short_name": "wahrwelt",
|
||||
"start_url": "/",
|
||||
"scope": "/",
|
||||
"display": "standalone",
|
||||
"background_color": "#ffffff",
|
||||
"theme_color": "#333333",
|
||||
"icons": [
|
||||
{
|
||||
"src": "/logo.jpg",
|
||||
"type": "image/jpeg",
|
||||
"sizes": "739x415"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
<template>
|
||||
<component :is="layout">
|
||||
<router-view />
|
||||
</component>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
export default {
|
||||
computed: {
|
||||
layout() {
|
||||
return this.$route.meta.layout || "base-layout";
|
||||
},
|
||||
},
|
||||
};
|
||||
</script>
|
||||
|
||||
<style lang="scss">
|
||||
html,
|
||||
body,
|
||||
#app {
|
||||
height: 100%;
|
||||
margin: 0;
|
||||
background-color: white;
|
||||
}
|
||||
|
||||
body {
|
||||
font-family: "Source Code Pro", monospace !important;
|
||||
}
|
||||
|
||||
.text-wahrwelt {
|
||||
color: white !important;
|
||||
}
|
||||
|
||||
.bg-wahrwelt {
|
||||
background: #333333 !important;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,186 @@
|
||||
<template>
|
||||
<q-card class="q-pa-md">
|
||||
<q-card-section>
|
||||
<div class="text-h6">Фильтр флагов</div>
|
||||
</q-card-section>
|
||||
<q-card-section>
|
||||
<q-form @submit.prevent="onSubmit">
|
||||
<div class="row">
|
||||
<div class="col col-4 q-px-sm">
|
||||
<q-select
|
||||
outlined
|
||||
v-model="sploit"
|
||||
:options="sploitOptions"
|
||||
label="Скрипт"
|
||||
><template v-if="sploit" v-slot:append>
|
||||
<q-icon
|
||||
name="cancel"
|
||||
@click.stop="sploit = null"
|
||||
class="cursor-pointer"
|
||||
/> </template
|
||||
></q-select>
|
||||
</div>
|
||||
<div class="col col-4 q-px-sm">
|
||||
<q-select
|
||||
outlined
|
||||
v-model="team"
|
||||
:options="teamOptions"
|
||||
label="Команда"
|
||||
><template v-if="team" v-slot:append>
|
||||
<q-icon
|
||||
name="cancel"
|
||||
@click.stop="team = null"
|
||||
class="cursor-pointer"
|
||||
/> </template
|
||||
></q-select>
|
||||
</div>
|
||||
<div class="col col-4 q-px-sm">
|
||||
<q-input
|
||||
outlined
|
||||
v-model="flag"
|
||||
label="Флаг"
|
||||
hint="Фрагмент без учета регистра"
|
||||
><template v-if="flag" v-slot:append>
|
||||
<q-icon
|
||||
name="cancel"
|
||||
@click.stop="flag = null"
|
||||
class="cursor-pointer"
|
||||
/> </template
|
||||
></q-input>
|
||||
</div>
|
||||
</div>
|
||||
<div class="row q-pt-md">
|
||||
<div class="col col-3 q-px-sm">
|
||||
<q-input
|
||||
outlined
|
||||
v-model="since"
|
||||
label="С"
|
||||
:hint="serverTZ"
|
||||
placeholder="гггг-мм-дд чч:мм"
|
||||
><template v-if="since" v-slot:append>
|
||||
<q-icon
|
||||
name="cancel"
|
||||
@click.stop="since = null"
|
||||
class="cursor-pointer"
|
||||
/> </template
|
||||
></q-input>
|
||||
</div>
|
||||
<div class="col col-3 q-px-sm">
|
||||
<q-input
|
||||
outlined
|
||||
v-model="until"
|
||||
label="По"
|
||||
:hint="serverTZ"
|
||||
placeholder="гггг-мм-дд чч:мм"
|
||||
><template v-if="until" v-slot:append>
|
||||
<q-icon
|
||||
name="cancel"
|
||||
@click.stop="until = null"
|
||||
class="cursor-pointer"
|
||||
/> </template
|
||||
></q-input>
|
||||
</div>
|
||||
<div class="col col-2 q-px-sm">
|
||||
<q-select
|
||||
outlined
|
||||
v-model="status"
|
||||
:options="statusOptions"
|
||||
option-label="label"
|
||||
option-value="value"
|
||||
emit-value
|
||||
map-options
|
||||
label="Статус"
|
||||
><template v-if="status" v-slot:append>
|
||||
<q-icon
|
||||
name="cancel"
|
||||
@click.stop="status = null"
|
||||
class="cursor-pointer"
|
||||
/> </template
|
||||
></q-select>
|
||||
</div>
|
||||
<div class="col col-4 q-px-sm">
|
||||
<q-input
|
||||
outlined
|
||||
v-model="checksystemResponse"
|
||||
label="Ответ чекера"
|
||||
hint="Фрагмент без учета регистра"
|
||||
><template v-if="checksystemResponse" v-slot:append>
|
||||
<q-icon
|
||||
name="cancel"
|
||||
@click.stop="checksystemResponse = null"
|
||||
class="cursor-pointer"
|
||||
/> </template
|
||||
></q-input>
|
||||
</div>
|
||||
</div>
|
||||
<div class="q-pt-md">
|
||||
<q-btn label="Применить" type="submit" color="wahrwelt" />
|
||||
</div>
|
||||
</q-form>
|
||||
</q-card-section>
|
||||
</q-card>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
import { mapState, mapActions, mapMutations } from "vuex";
|
||||
|
||||
const statusLabels = {
|
||||
QUEUED: "В очереди",
|
||||
SKIPPED: "Пропущен",
|
||||
ACCEPTED: "Принят",
|
||||
REJECTED: "Отклонен",
|
||||
};
|
||||
|
||||
export default {
|
||||
data: function () {
|
||||
return {
|
||||
sploit: null,
|
||||
|
||||
team: null,
|
||||
|
||||
flag: null,
|
||||
since: null,
|
||||
until: null,
|
||||
|
||||
status: null,
|
||||
|
||||
checksystemResponse: null,
|
||||
};
|
||||
},
|
||||
methods: {
|
||||
onSubmit: async function () {
|
||||
const filters = {
|
||||
sploit: this.sploit,
|
||||
team: this.team,
|
||||
flag: this.flag,
|
||||
since: this.since,
|
||||
until: this.until,
|
||||
status: this.status,
|
||||
checksystem_response: this.checksystemResponse,
|
||||
};
|
||||
|
||||
this.setFlagFilters(filters);
|
||||
this.setSelectedPage(1);
|
||||
await this.fetchFlags();
|
||||
},
|
||||
...mapActions(["fetchFlags"]),
|
||||
...mapMutations(["setSelectedPage", "setFlagFilters"]),
|
||||
},
|
||||
computed: {
|
||||
...mapState({
|
||||
sploitOptions: "sploitFilterOptions",
|
||||
teamOptions: "teamFilterOptions",
|
||||
statusFilterOptions: "statusFilterOptions",
|
||||
serverTZ: "serverTZ",
|
||||
}),
|
||||
statusOptions() {
|
||||
return this.statusFilterOptions.map((value) => ({
|
||||
label: statusLabels[value] || value,
|
||||
value,
|
||||
}));
|
||||
},
|
||||
},
|
||||
};
|
||||
</script>
|
||||
|
||||
<style></style>
|
||||
@@ -0,0 +1,61 @@
|
||||
<template>
|
||||
<q-card class="q-pa-md">
|
||||
<q-card-section>
|
||||
<div class="text-h6">Ручная отправка</div>
|
||||
</q-card-section>
|
||||
<q-card-section>
|
||||
<q-form @submit.prevent="onSubmit">
|
||||
<q-input
|
||||
outlined
|
||||
v-model="text"
|
||||
label="Текст с флагами"
|
||||
type="textarea"
|
||||
:hint="'Формат флага: ' + flagFormat"
|
||||
><template v-if="text" v-slot:append>
|
||||
<q-icon
|
||||
name="cancel"
|
||||
@click.stop="text = null"
|
||||
class="cursor-pointer"
|
||||
/> </template
|
||||
></q-input>
|
||||
<div class="q-pt-md">
|
||||
<q-btn label="Отправить" type="submit" color="wahrwelt" />
|
||||
</div>
|
||||
</q-form>
|
||||
</q-card-section>
|
||||
</q-card>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
import { mapState, mapActions, mapMutations } from "vuex";
|
||||
import APIService from "@/services/api";
|
||||
|
||||
export default {
|
||||
data: function () {
|
||||
return {
|
||||
text: "",
|
||||
};
|
||||
},
|
||||
methods: {
|
||||
onSubmit: async function () {
|
||||
const matches = [...this.text.matchAll(new RegExp(this.flagFormat, "g"))];
|
||||
const flags = matches.map((flag) => {
|
||||
return { flag: flag[0], team: "*", sploit: "Manual" };
|
||||
});
|
||||
try {
|
||||
await APIService.post("/post_flags", flags);
|
||||
const newFilters = { sploit: "Manual" };
|
||||
this.setFlagFilters(newFilters);
|
||||
await this.updatePage(1);
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
},
|
||||
...mapActions(["updatePage"]),
|
||||
...mapMutations(["setFlagFilters"]),
|
||||
},
|
||||
computed: mapState(["flagFormat"]),
|
||||
};
|
||||
</script>
|
||||
|
||||
<style></style>
|
||||
@@ -0,0 +1,155 @@
|
||||
<template>
|
||||
<q-table
|
||||
:rows="flags"
|
||||
:columns="columns"
|
||||
:rows-per-page-options="[flagsPerPage]"
|
||||
v-model:pagination="pagination"
|
||||
@request="onRequest"
|
||||
row-key="flag"
|
||||
no-data-label="Флагов пока нет"
|
||||
table-header-class="bg-wahrwelt text-wahrwelt"
|
||||
dense
|
||||
>
|
||||
<template v-slot:top="scope">
|
||||
<div class="text-h6">Всего флагов: {{ scope.pagination.rowsNumber }}</div>
|
||||
<q-space />
|
||||
<pagination-custom
|
||||
:pagesNumber="scope.pagesNumber"
|
||||
:isFirstPage="scope.isFirstPage"
|
||||
:isLastPage="scope.isLastPage"
|
||||
:page="scope.pagination.page"
|
||||
:pageSize="scope.pagination.rowsPerPage"
|
||||
:total="scope.pagination.rowsNumber"
|
||||
@firstPage="scope.firstPage"
|
||||
@prevPage="scope.prevPage"
|
||||
@nextPage="scope.nextPage"
|
||||
@lastPage="scope.lastPage"
|
||||
/>
|
||||
<q-btn
|
||||
flat
|
||||
round
|
||||
dense
|
||||
:icon="scope.inFullscreen ? 'fullscreen_exit' : 'fullscreen'"
|
||||
@click="scope.toggleFullscreen"
|
||||
class="q-ml-md"
|
||||
/>
|
||||
</template>
|
||||
<template v-slot:no-data="{ message }">
|
||||
<div class="full-width row flex-center text-accent q-gutter-sm">
|
||||
<q-icon size="2em" name="sentiment_dissatisfied" />
|
||||
<span>{{ message }}</span>
|
||||
</div>
|
||||
</template>
|
||||
<template v-slot:header-cell="props">
|
||||
<q-th :props="props" :style="{ textAlign: 'center' }">
|
||||
{{ props.col.label }}
|
||||
</q-th>
|
||||
</template>
|
||||
<template v-slot:body-cell="props">
|
||||
<q-td :props="props">
|
||||
<div>
|
||||
{{ props.value }}
|
||||
<q-btn
|
||||
size="sm"
|
||||
flat
|
||||
round
|
||||
icon="content_copy"
|
||||
v-if="copyableColumns.includes(props.col.name)"
|
||||
@click="copyToClipboard(props.value)"
|
||||
/>
|
||||
</div>
|
||||
</q-td>
|
||||
</template>
|
||||
<template v-slot:pagination="scope">
|
||||
<pagination-custom
|
||||
:pagesNumber="scope.pagesNumber"
|
||||
:isFirstPage="scope.isFirstPage"
|
||||
:isLastPage="scope.isLastPage"
|
||||
:page="scope.pagination.page"
|
||||
:pageSize="scope.pagination.rowsPerPage"
|
||||
:total="scope.pagination.rowsNumber"
|
||||
@firstPage="scope.firstPage"
|
||||
@prevPage="scope.prevPage"
|
||||
@nextPage="scope.nextPage"
|
||||
@lastPage="scope.lastPage" /></template
|
||||
></q-table>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
import { mapState, mapActions } from "vuex";
|
||||
import { copyToClipboard } from "quasar";
|
||||
import { flagsPerPage } from "@/config";
|
||||
import PaginationCustom from "@/components/PaginationCustom.vue";
|
||||
|
||||
const statusLabels = {
|
||||
QUEUED: "В очереди",
|
||||
SKIPPED: "Пропущен",
|
||||
ACCEPTED: "Принят",
|
||||
REJECTED: "Отклонен",
|
||||
};
|
||||
|
||||
export default {
|
||||
components: { PaginationCustom },
|
||||
data: function () {
|
||||
return {
|
||||
columns: [
|
||||
{ name: "sploit", label: "Скрипт", field: "sploit", align: "center" },
|
||||
{ name: "team", label: "Команда", field: "team", align: "center" },
|
||||
{ name: "flag", label: "Флаг", field: "flag", align: "center" },
|
||||
{
|
||||
name: "time",
|
||||
label: "Время",
|
||||
field: "time",
|
||||
align: "center",
|
||||
format: (val) => new Intl.DateTimeFormat("ru-RU", {
|
||||
dateStyle: "long",
|
||||
timeStyle: "medium",
|
||||
}).format(new Date(val * 1000)),
|
||||
},
|
||||
{
|
||||
name: "status",
|
||||
label: "Статус",
|
||||
field: "status",
|
||||
align: "center",
|
||||
format: (value) => statusLabels[value] || value,
|
||||
},
|
||||
{
|
||||
name: "checksystemResponse",
|
||||
label: "Ответ чекера",
|
||||
field: "checksystemResponse",
|
||||
align: "left",
|
||||
},
|
||||
],
|
||||
copyableColumns: ["sploit", "flag", "checksystemResponse"],
|
||||
flagsPerPage,
|
||||
};
|
||||
},
|
||||
computed: {
|
||||
pagination: {
|
||||
get: function () {
|
||||
return {
|
||||
page: this.selectedPage,
|
||||
rowsPerPage: flagsPerPage,
|
||||
rowsNumber: this.totalFlags,
|
||||
};
|
||||
},
|
||||
set: function (newPagination) {
|
||||
if (newPagination.page) {
|
||||
this.updatePage(newPagination.page);
|
||||
}
|
||||
},
|
||||
},
|
||||
...mapState(["flags", "totalFlags", "selectedPage"]),
|
||||
},
|
||||
methods: {
|
||||
onRequest: async function (props) {
|
||||
this.pagination = props.pagination;
|
||||
},
|
||||
copyToClipboard,
|
||||
|
||||
...mapActions(["updatePage"]),
|
||||
},
|
||||
};
|
||||
</script>
|
||||
|
||||
<style></style>
|
||||
@@ -0,0 +1,47 @@
|
||||
<template>
|
||||
<q-card class="q-pa-md">
|
||||
<q-card-section>
|
||||
<div class="text-h6">Введите пароль сервера</div>
|
||||
</q-card-section>
|
||||
<q-card-section>
|
||||
<q-form @submit.prevent="onSubmit">
|
||||
<div class="row">
|
||||
<div class="col col-12">
|
||||
<q-input
|
||||
outlined
|
||||
v-model="password"
|
||||
type="password"
|
||||
label="Пароль"
|
||||
autocomplete="current-password"
|
||||
required
|
||||
></q-input>
|
||||
</div>
|
||||
</div>
|
||||
<div class="q-pt-md">
|
||||
<q-btn label="Войти" type="submit" color="wahrwelt" />
|
||||
</div>
|
||||
</q-form>
|
||||
</q-card-section>
|
||||
</q-card>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
import { mapMutations } from "vuex";
|
||||
|
||||
export default {
|
||||
data: function () {
|
||||
return {
|
||||
password: null,
|
||||
};
|
||||
},
|
||||
methods: {
|
||||
onSubmit: async function () {
|
||||
this.setServerPassword(this.password);
|
||||
await this.$router.push({ name: "flags" });
|
||||
},
|
||||
...mapMutations(["setServerPassword"]),
|
||||
},
|
||||
};
|
||||
</script>
|
||||
|
||||
<style></style>
|
||||
@@ -0,0 +1,83 @@
|
||||
<template>
|
||||
<div class="pagination">
|
||||
<span class="message">
|
||||
{{ paginationMessage }}
|
||||
</span>
|
||||
<q-btn
|
||||
v-if="pagesNumber > 2"
|
||||
icon="first_page"
|
||||
color="grey-8"
|
||||
round
|
||||
dense
|
||||
flat
|
||||
:disable="isFirstPage"
|
||||
@click="$emit('firstPage')"
|
||||
/>
|
||||
|
||||
<q-btn
|
||||
icon="chevron_left"
|
||||
color="grey-8"
|
||||
round
|
||||
dense
|
||||
flat
|
||||
:disable="isFirstPage"
|
||||
@click="$emit('prevPage')"
|
||||
/>
|
||||
|
||||
<q-btn
|
||||
icon="chevron_right"
|
||||
color="grey-8"
|
||||
round
|
||||
dense
|
||||
flat
|
||||
:disable="isLastPage"
|
||||
@click="$emit('nextPage')"
|
||||
/>
|
||||
<q-btn
|
||||
v-if="pagesNumber > 2"
|
||||
icon="last_page"
|
||||
color="grey-8"
|
||||
round
|
||||
dense
|
||||
flat
|
||||
:disable="isLastPage"
|
||||
@click="$emit('lastPage')"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
export default {
|
||||
name: "PaginationCustom",
|
||||
props: {
|
||||
pagesNumber: Number,
|
||||
isFirstPage: Boolean,
|
||||
isLastPage: Boolean,
|
||||
|
||||
page: Number,
|
||||
pageSize: Number,
|
||||
total: Number,
|
||||
},
|
||||
computed: {
|
||||
paginationMessage: function () {
|
||||
if (!this.total) {
|
||||
return "0 из 0";
|
||||
}
|
||||
const firstRow = this.pageSize * (this.page - 1) + 1;
|
||||
const lastRow = Math.min(this.pageSize * this.page, this.total);
|
||||
return `${firstRow}-${lastRow} из ${this.total}`;
|
||||
},
|
||||
},
|
||||
emits: ["firstPage", "prevPage", "nextPage", "lastPage"],
|
||||
};
|
||||
</script>
|
||||
|
||||
<style lang="scss" scoped>
|
||||
.pagination {
|
||||
font-size: 0.9em;
|
||||
|
||||
> .message {
|
||||
margin-right: 1em;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,64 @@
|
||||
<template>
|
||||
<q-table
|
||||
virtual-scroll
|
||||
dense
|
||||
:rows="teams"
|
||||
:columns="columns"
|
||||
:rows-per-page-options="[0]"
|
||||
style="height: 80vh"
|
||||
row-key="name"
|
||||
no-data-label="Список команд пуст"
|
||||
table-header-class="bg-wahrwelt text-wahrwelt"
|
||||
>
|
||||
<template v-slot:no-data="{ message }">
|
||||
<div class="full-width row flex-center text-accent q-gutter-sm">
|
||||
<q-icon size="2em" name="sentiment_dissatisfied" />
|
||||
<span>{{ message }}</span>
|
||||
</div>
|
||||
</template>
|
||||
<template v-slot:header-cell="props">
|
||||
<q-th :props="props" :style="{ textAlign: 'center' }">
|
||||
{{ props.col.label }}
|
||||
</q-th>
|
||||
</template>
|
||||
<template v-slot:body-cell-address="props">
|
||||
<q-td :props="props">
|
||||
<div>
|
||||
{{ props.value }}
|
||||
<q-btn
|
||||
size="sm"
|
||||
flat
|
||||
round
|
||||
icon="content_copy"
|
||||
@click="copyToClipboard(props.value)"
|
||||
/>
|
||||
</div>
|
||||
</q-td>
|
||||
</template>
|
||||
</q-table>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
import { mapState } from "vuex";
|
||||
import { copyToClipboard } from "quasar";
|
||||
|
||||
export default {
|
||||
data: function () {
|
||||
return {
|
||||
columns: [
|
||||
{ name: "name", label: "Название", field: "name", align: "center" },
|
||||
{
|
||||
name: "address",
|
||||
label: "Адрес",
|
||||
field: "address",
|
||||
align: "center",
|
||||
},
|
||||
],
|
||||
};
|
||||
},
|
||||
computed: mapState(["teams"]),
|
||||
methods: { copyToClipboard },
|
||||
};
|
||||
</script>
|
||||
|
||||
<style></style>
|
||||
@@ -0,0 +1,6 @@
|
||||
const serverUrl = window.location.origin;
|
||||
const apiUrl = `${serverUrl}/api`;
|
||||
|
||||
const flagsPerPage = 30;
|
||||
|
||||
export { apiUrl, flagsPerPage, serverUrl };
|
||||
@@ -0,0 +1,41 @@
|
||||
<template>
|
||||
<q-layout view="hHh lpR fFf">
|
||||
<q-header elevated class="bg-wahrwelt text-wahrwelt">
|
||||
<q-toolbar class="bg-wahrwelt text-wahrwelt">
|
||||
<q-img class="brand-logo" src="/logo.jpg" alt="Логотип wahrwelt" ratio="1.78" />
|
||||
<q-toolbar-title> wahrwelt / Farm </q-toolbar-title>
|
||||
<q-tabs class="bg-wahrwelt text-wahrwelt" shrink>
|
||||
<q-route-tab :to="{ name: 'flags' }" label="Флаги" />
|
||||
<q-route-tab :to="{ name: 'teams' }" label="Команды" />
|
||||
</q-tabs>
|
||||
<q-space />
|
||||
<q-btn flat label="Выйти" @click="logout" />
|
||||
</q-toolbar>
|
||||
</q-header>
|
||||
|
||||
<q-page-container>
|
||||
<slot />
|
||||
</q-page-container>
|
||||
</q-layout>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
import { mapMutations } from "vuex";
|
||||
|
||||
export default {
|
||||
name: "BaseLayout",
|
||||
methods: {
|
||||
...mapMutations(["setServerPassword"]),
|
||||
logout() {
|
||||
this.setServerPassword(null);
|
||||
this.$router.push({ name: "login" });
|
||||
},
|
||||
},
|
||||
};
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.brand-logo {
|
||||
width: 80px;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,18 @@
|
||||
import App from "@/App.vue";
|
||||
import BaseLayout from "@/layouts/BaseLayout.vue";
|
||||
import quasarUserOptions from "@/quasar-user-options";
|
||||
import router from "@/router";
|
||||
import store from "@/store";
|
||||
import { Quasar } from "quasar";
|
||||
import "quasar/dist/quasar.sass";
|
||||
import { createApp } from "vue";
|
||||
|
||||
const app = createApp(App);
|
||||
|
||||
app.use(Quasar, quasarUserOptions);
|
||||
app.use(store);
|
||||
app.use(router);
|
||||
|
||||
app.component("base-layout", BaseLayout);
|
||||
|
||||
app.mount("#app");
|
||||
@@ -0,0 +1,19 @@
|
||||
class Flag {
|
||||
constructor({
|
||||
sploit,
|
||||
flag,
|
||||
team,
|
||||
status,
|
||||
checksystem_response: checksystemResponse,
|
||||
time,
|
||||
}) {
|
||||
this.sploit = sploit;
|
||||
this.flag = flag;
|
||||
this.team = team;
|
||||
this.status = status;
|
||||
this.checksystemResponse = checksystemResponse;
|
||||
this.time = time;
|
||||
}
|
||||
}
|
||||
|
||||
export default Flag;
|
||||
@@ -0,0 +1,8 @@
|
||||
class Team {
|
||||
constructor({ name, address }) {
|
||||
this.name = name;
|
||||
this.address = address;
|
||||
}
|
||||
}
|
||||
|
||||
export default Team;
|
||||
@@ -0,0 +1,54 @@
|
||||
import "./styles/quasar.scss";
|
||||
import "@quasar/extras/material-icons/material-icons.css";
|
||||
import "@quasar/extras/fontawesome-v7/fontawesome-v7.css";
|
||||
import {
|
||||
Notify,
|
||||
QBtn,
|
||||
QCard,
|
||||
QCardSection,
|
||||
QForm,
|
||||
QHeader,
|
||||
QIcon,
|
||||
QInput,
|
||||
QImg,
|
||||
QLayout,
|
||||
QPage,
|
||||
QPageContainer,
|
||||
QRouteTab,
|
||||
QSelect,
|
||||
QSpace,
|
||||
QTable,
|
||||
QTabs,
|
||||
QTd,
|
||||
QTh,
|
||||
QToolbar,
|
||||
QToolbarTitle,
|
||||
} from "quasar";
|
||||
|
||||
// Передается в app.use(Quasar, ...).
|
||||
export default {
|
||||
config: {},
|
||||
components: {
|
||||
QBtn,
|
||||
QCard,
|
||||
QCardSection,
|
||||
QForm,
|
||||
QHeader,
|
||||
QIcon,
|
||||
QInput,
|
||||
QImg,
|
||||
QLayout,
|
||||
QPage,
|
||||
QPageContainer,
|
||||
QRouteTab,
|
||||
QSelect,
|
||||
QSpace,
|
||||
QTable,
|
||||
QTabs,
|
||||
QTd,
|
||||
QTh,
|
||||
QToolbar,
|
||||
QToolbarTitle,
|
||||
},
|
||||
plugins: { Notify },
|
||||
};
|
||||
@@ -0,0 +1,34 @@
|
||||
import { createRouter, createWebHistory } from "vue-router";
|
||||
import store from "@/store";
|
||||
|
||||
const routes = [
|
||||
{
|
||||
path: "/",
|
||||
name: "flags",
|
||||
component: () => import("@/views/Flags.vue"),
|
||||
},
|
||||
{
|
||||
path: "/teams",
|
||||
name: "teams",
|
||||
component: () => import("@/views/Teams.vue"),
|
||||
},
|
||||
{
|
||||
path: "/login",
|
||||
name: "login",
|
||||
component: () => import("@/views/Login.vue"),
|
||||
},
|
||||
];
|
||||
|
||||
const router = createRouter({
|
||||
history: createWebHistory(import.meta.env.BASE_URL),
|
||||
routes,
|
||||
});
|
||||
|
||||
router.beforeEach((to) => {
|
||||
if (to.name !== "login" && !store.state.serverPassword) {
|
||||
return { name: "login" };
|
||||
}
|
||||
return true;
|
||||
});
|
||||
|
||||
export default router;
|
||||
@@ -0,0 +1,16 @@
|
||||
import axios from "axios";
|
||||
import { apiUrl } from "@/config";
|
||||
import {
|
||||
errorHandlerInterceptor,
|
||||
passwordCheckInterceptor,
|
||||
} from "@/services/interceptors";
|
||||
|
||||
const APIService = axios.create({ baseURL: apiUrl });
|
||||
|
||||
APIService.interceptors.request.use(passwordCheckInterceptor);
|
||||
APIService.interceptors.response.use(
|
||||
errorHandlerInterceptor.onFulfilled,
|
||||
errorHandlerInterceptor.onRejected
|
||||
);
|
||||
|
||||
export default APIService;
|
||||
@@ -0,0 +1,38 @@
|
||||
import store from "@/store";
|
||||
import router from "@/router";
|
||||
import { Notify } from "quasar";
|
||||
|
||||
const passwordCheckInterceptor = function (config) {
|
||||
const password = store.state.serverPassword ?? "";
|
||||
config.headers.Authorization = password;
|
||||
config.headers["X-Token"] = password;
|
||||
return config;
|
||||
};
|
||||
|
||||
const errorHandlerInterceptor = {
|
||||
onFulfilled: (response) => response,
|
||||
onRejected: (error) => {
|
||||
const status = error.response?.status;
|
||||
|
||||
if (status === 403) {
|
||||
if (error.config?.headers?.["X-Token"] !== store.state.serverPassword) {
|
||||
return Promise.reject(error);
|
||||
}
|
||||
store.commit("setServerPassword", null);
|
||||
Notify.create({
|
||||
type: "negative",
|
||||
message: "Неверный пароль или срок сессии истек",
|
||||
});
|
||||
router.push({ name: "login" });
|
||||
} else {
|
||||
Notify.create({
|
||||
type: "negative",
|
||||
message: status ? `Ошибка API: ${status}` : "Сервер недоступен",
|
||||
});
|
||||
}
|
||||
|
||||
return Promise.reject(error);
|
||||
},
|
||||
};
|
||||
|
||||
export { passwordCheckInterceptor, errorHandlerInterceptor };
|
||||
@@ -0,0 +1,127 @@
|
||||
import { flagsPerPage } from "@/config";
|
||||
import Flag from "@/models/flag.js";
|
||||
import Team from "@/models/team.js";
|
||||
import APIService from "@/services/api";
|
||||
import { createStore } from "vuex";
|
||||
|
||||
function readPassword() {
|
||||
try {
|
||||
return window.sessionStorage.getItem("farmPassword");
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export default createStore({
|
||||
state: {
|
||||
totalFlags: 0,
|
||||
selectedPage: 1,
|
||||
|
||||
flags: [],
|
||||
flagFilters: null,
|
||||
serverTZ: null,
|
||||
|
||||
sploitFilterOptions: [],
|
||||
teamFilterOptions: [],
|
||||
statusFilterOptions: [],
|
||||
|
||||
flagFormat: null,
|
||||
|
||||
teams: [],
|
||||
|
||||
serverPassword: readPassword(),
|
||||
},
|
||||
mutations: {
|
||||
setTotalFlags(state, totalFlags) {
|
||||
state.totalFlags = totalFlags;
|
||||
},
|
||||
setFlags(state, flags) {
|
||||
state.flags = flags;
|
||||
},
|
||||
setFlagFilters(state, flagFilters) {
|
||||
state.flagFilters = flagFilters;
|
||||
},
|
||||
setSelectedPage(state, page) {
|
||||
state.selectedPage = page;
|
||||
},
|
||||
setServerTZ(state, tz) {
|
||||
state.serverTZ = tz;
|
||||
},
|
||||
|
||||
setFilterOptions(state, filterOptions) {
|
||||
state.sploitFilterOptions = filterOptions.sploit ?? [];
|
||||
state.teamFilterOptions = filterOptions.team ?? [];
|
||||
state.statusFilterOptions = filterOptions.status ?? [];
|
||||
},
|
||||
setFlagFormat(state, flagFormat) {
|
||||
state.flagFormat = flagFormat;
|
||||
},
|
||||
|
||||
setTeams(state, teams) {
|
||||
state.teams = teams;
|
||||
},
|
||||
|
||||
setServerPassword(state, password) {
|
||||
state.serverPassword = password;
|
||||
try {
|
||||
if (password) {
|
||||
window.sessionStorage.setItem("farmPassword", password);
|
||||
} else {
|
||||
window.sessionStorage.removeItem("farmPassword");
|
||||
}
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
},
|
||||
},
|
||||
actions: {
|
||||
fetchFlags: async function (context) {
|
||||
const filters = context.state.flagFilters;
|
||||
let params = {
|
||||
page: context.state.selectedPage,
|
||||
page_size: flagsPerPage,
|
||||
};
|
||||
if (filters) {
|
||||
params = { ...params, ...filters };
|
||||
}
|
||||
try {
|
||||
const { data } = await APIService.get("/filter_flags", { params });
|
||||
|
||||
const flags = data.flags.map((flag) => new Flag(flag));
|
||||
context.commit("setFlags", flags);
|
||||
context.commit("setTotalFlags", data.total);
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
|
||||
await context.dispatch("fetchFilterOptions");
|
||||
},
|
||||
|
||||
updatePage: async function (context, page) {
|
||||
context.commit("setSelectedPage", page);
|
||||
await context.dispatch("fetchFlags");
|
||||
},
|
||||
|
||||
fetchFilterOptions: async function (context) {
|
||||
try {
|
||||
const { data } = await APIService.get("/filter_config");
|
||||
context.commit("setFilterOptions", data.filters);
|
||||
context.commit("setFlagFormat", data.flag_format);
|
||||
context.commit("setServerTZ", data.server_tz);
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
},
|
||||
|
||||
fetchTeams: async function (context) {
|
||||
try {
|
||||
const { data } = await APIService.get("/teams");
|
||||
const teams = data.map((team) => new Team(team));
|
||||
context.commit("setTeams", teams);
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
},
|
||||
},
|
||||
modules: {},
|
||||
});
|
||||
@@ -0,0 +1 @@
|
||||
@use "./quasar.variables.scss" as *;
|
||||
@@ -0,0 +1,12 @@
|
||||
// Цвета Quasar можно настроить в соответствии с оформлением интерфейса.
|
||||
|
||||
$primary: #027BE3;
|
||||
$secondary: #26A69A;
|
||||
$accent: #9C27B0;
|
||||
|
||||
$dark: #1D1D1D;
|
||||
|
||||
$positive: #21BA45;
|
||||
$negative: #C10015;
|
||||
$info: #31CCEC;
|
||||
$warning: #F2C037;
|
||||
@@ -0,0 +1,30 @@
|
||||
<template>
|
||||
<q-page class="q-pa-md"
|
||||
><div class="row justify-between q-col-gutter-md">
|
||||
<div class="col col-12 col-md-8"><flags-form /></div>
|
||||
<div class="col col-12 col-md-4"><flags-submit /></div>
|
||||
</div>
|
||||
<div class="row q-pt-md justify-center">
|
||||
<div class="col">
|
||||
<flags-table />
|
||||
</div>
|
||||
</div>
|
||||
</q-page>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
import FlagsForm from "@/components/FlagsForm.vue";
|
||||
import FlagsSubmit from "@/components/FlagsSubmit.vue";
|
||||
import FlagsTable from "@/components/FlagsTable.vue";
|
||||
import { mapActions } from "vuex";
|
||||
import { flagsPerPage } from "@/config";
|
||||
export default {
|
||||
components: { FlagsForm, FlagsSubmit, FlagsTable },
|
||||
methods: mapActions(["fetchFlags"]),
|
||||
created: async function () {
|
||||
await this.fetchFlags({ page: 1, pageSize: flagsPerPage });
|
||||
},
|
||||
};
|
||||
</script>
|
||||
|
||||
<style></style>
|
||||
@@ -0,0 +1,16 @@
|
||||
<template>
|
||||
<q-page class="q-pa-md"
|
||||
><div class="row justify-center">
|
||||
<div class="col col-12 col-md-6"><login-form /></div>
|
||||
</div>
|
||||
</q-page>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
import LoginForm from "@/components/LoginForm.vue";
|
||||
export default {
|
||||
components: { LoginForm },
|
||||
};
|
||||
</script>
|
||||
|
||||
<style></style>
|
||||
@@ -0,0 +1,21 @@
|
||||
<template>
|
||||
<q-page class="q-pa-md"
|
||||
><div class="row justify-between q-col-gutter-md">
|
||||
<div class="col col-12"><teams-table /></div>
|
||||
</div>
|
||||
</q-page>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
import TeamsTable from "@/components/TeamsTable.vue";
|
||||
import { mapActions } from "vuex";
|
||||
export default {
|
||||
components: { TeamsTable },
|
||||
created: async function () {
|
||||
await this.fetchTeams();
|
||||
},
|
||||
methods: mapActions(["fetchTeams"]),
|
||||
};
|
||||
</script>
|
||||
|
||||
<style></style>
|
||||
@@ -0,0 +1,25 @@
|
||||
import { fileURLToPath, URL } from 'node:url'
|
||||
|
||||
import vue from '@vitejs/plugin-vue'
|
||||
import { defineConfig, loadEnv } from 'vite'
|
||||
|
||||
export default defineConfig(({ mode }) => {
|
||||
const env = loadEnv(mode, '.', 'VITE_')
|
||||
|
||||
return {
|
||||
plugins: [vue()],
|
||||
resolve: {
|
||||
alias: {
|
||||
'@': fileURLToPath(new URL('./src', import.meta.url))
|
||||
}
|
||||
},
|
||||
server: {
|
||||
proxy: {
|
||||
'/api': {
|
||||
target: env.VITE_API_TARGET || 'http://127.0.0.1:5000',
|
||||
changeOrigin: false
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,8 @@
|
||||
Flask>=3.1.3
|
||||
gunicorn>=26.2.0
|
||||
prometheus-client>=0.26.0
|
||||
PyJWT[crypto]>=2.15.1
|
||||
psycopg[binary,pool]>=3.3.6
|
||||
python-dateutil>=2.9.0.post0
|
||||
pytz>=2026.5
|
||||
requests>=2.34.2
|
||||
@@ -0,0 +1,210 @@
|
||||
import os
|
||||
import sys
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from unittest import mock
|
||||
|
||||
APP_DIR = Path(__file__).resolve().parents[1] / 'app'
|
||||
sys.path.insert(0, str(APP_DIR))
|
||||
|
||||
os.environ.setdefault('FARM_PASSWORD', 'f' * 48)
|
||||
os.environ.setdefault('FARM_TEAMS', '{"Example":"192.0.2.1"}')
|
||||
os.environ.setdefault('FARM_FLAG_FORMAT', r'[A-Z0-9]{31}=')
|
||||
os.environ.setdefault('POSTGRES_DSN', 'postgresql://farm:test@127.0.0.1/farm')
|
||||
|
||||
import config
|
||||
import database
|
||||
import sender
|
||||
from factory import create_app
|
||||
|
||||
PASSWORD = os.environ['FARM_PASSWORD']
|
||||
FLAG = 'A' * 31 + '='
|
||||
|
||||
|
||||
class FakeCursor:
|
||||
def __init__(self):
|
||||
self.closed = False
|
||||
self.executed = []
|
||||
|
||||
def execute(self, *args):
|
||||
self.executed.append(args)
|
||||
|
||||
def executemany(self, *args):
|
||||
self.executed.append(args)
|
||||
|
||||
def fetchone(self):
|
||||
return (True,)
|
||||
|
||||
def close(self):
|
||||
self.closed = True
|
||||
|
||||
|
||||
class FakeConnection:
|
||||
def __init__(self):
|
||||
self.cursors = []
|
||||
self.rollbacks = 0
|
||||
|
||||
def cursor(self, **_kwargs):
|
||||
cursor = FakeCursor()
|
||||
self.cursors.append(cursor)
|
||||
return cursor
|
||||
|
||||
def rollback(self):
|
||||
self.rollbacks += 1
|
||||
|
||||
|
||||
class FakePool:
|
||||
def __init__(self, connection):
|
||||
self.connection = connection
|
||||
self.returned = []
|
||||
|
||||
def getconn(self, **_kwargs):
|
||||
return self.connection
|
||||
|
||||
def putconn(self, connection):
|
||||
self.returned.append(connection)
|
||||
|
||||
|
||||
class ConfigTests(unittest.TestCase):
|
||||
def test_config_requires_a_long_password_and_disables_debug(self):
|
||||
with self.assertRaisesRegex(RuntimeError, 'FARM_PASSWORD'):
|
||||
config.load_config({'FARM_PASSWORD': 'short'})
|
||||
|
||||
loaded = config.load_config({'FARM_PASSWORD': 'x' * 48})
|
||||
self.assertFalse(loaded['DEBUG'])
|
||||
self.assertEqual(loaded['TEAMS'], {'Example': '192.0.2.1'})
|
||||
|
||||
def test_submission_requires_an_explicit_protocol(self):
|
||||
loaded = config.load_config({'FARM_PASSWORD': 'x' * 48})
|
||||
with self.assertRaisesRegex(RuntimeError, 'FARM_SYSTEM_PROTOCOL'):
|
||||
config.validate_submission_config(loaded)
|
||||
|
||||
def test_period_must_be_finite_and_bounded(self):
|
||||
for period in ('nan', 'inf', '3601'):
|
||||
with self.subTest(period=period):
|
||||
with self.assertRaisesRegex(RuntimeError, 'Параметр отправки'):
|
||||
config.load_config({
|
||||
'FARM_PASSWORD': 'x' * 48,
|
||||
'FARM_SUBMIT_PERIOD': period,
|
||||
})
|
||||
|
||||
def test_sender_validates_before_running_and_respects_stop(self):
|
||||
loaded = config.load_config({'FARM_PASSWORD': 'x' * 48})
|
||||
loaded.update(SYSTEM_PROTOCOL='ructf_tcp', SYSTEM_HOST='example.invalid')
|
||||
stop_event = mock.Mock()
|
||||
stop_event.is_set.return_value = True
|
||||
with mock.patch.object(sender, 'CONFIG', loaded):
|
||||
sender.run(stop_event)
|
||||
stop_event.wait.assert_not_called()
|
||||
|
||||
|
||||
class ApiTests(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.client = create_app().test_client()
|
||||
|
||||
def headers(self, name='Authorization'):
|
||||
return {name: PASSWORD}
|
||||
|
||||
def test_public_config_is_compatible_and_contains_no_secrets(self):
|
||||
response = self.client.get('/api/get_config', headers=self.headers())
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertEqual(set(response.json), {'FLAG_FORMAT', 'TEAMS'})
|
||||
self.assertNotIn(PASSWORD, response.get_data(as_text=True))
|
||||
|
||||
def test_each_neo_auth_header_is_accepted(self):
|
||||
for name in ('Authorization', 'X-Token'):
|
||||
with self.subTest(header=name):
|
||||
response = self.client.get('/api/get_config', headers=self.headers(name))
|
||||
self.assertEqual(response.status_code, 200)
|
||||
|
||||
def test_debug_does_not_bypass_authentication(self):
|
||||
app = create_app()
|
||||
app.config['DEBUG'] = True
|
||||
response = app.test_client().get('/api/get_config')
|
||||
self.assertEqual(response.status_code, 403)
|
||||
|
||||
def test_valid_synthetic_flag_is_queued(self):
|
||||
connection = mock.Mock()
|
||||
cursor = mock.Mock()
|
||||
cursor.rowcount = 1
|
||||
context = mock.MagicMock()
|
||||
context.__enter__.return_value = (connection, cursor)
|
||||
|
||||
with mock.patch('api.db_cursor', return_value=context):
|
||||
response = self.client.post(
|
||||
'/api/post_flags',
|
||||
headers=self.headers('X-Token'),
|
||||
json=[{'flag': FLAG, 'sploit': 'synthetic-test', 'team': 'Example'}],
|
||||
)
|
||||
|
||||
self.assertEqual(response.status_code, 200)
|
||||
cursor.executemany.assert_called_once()
|
||||
connection.commit.assert_called_once()
|
||||
|
||||
def test_invalid_payloads_are_rejected_before_database_access(self):
|
||||
invalid_payloads = (
|
||||
None,
|
||||
[{'flag': FLAG, 'sploit': 'synthetic-test', 'team': 'Unknown'}],
|
||||
[{'flag': 'bad', 'sploit': 'synthetic-test', 'team': 'Example'}],
|
||||
[{'flag': FLAG, 'sploit': 'synthetic-test', 'team': 'Example', 'extra': 'x'}],
|
||||
)
|
||||
with mock.patch('api.db_cursor') as db_cursor:
|
||||
for payload in invalid_payloads:
|
||||
with self.subTest(payload=payload):
|
||||
response = self.client.post(
|
||||
'/api/post_flags', headers=self.headers(), json=payload
|
||||
)
|
||||
self.assertEqual(response.status_code, 400)
|
||||
db_cursor.assert_not_called()
|
||||
|
||||
def test_bad_credentials_are_rejected(self):
|
||||
for password in ('wrong', 'é'):
|
||||
with self.subTest(password=password):
|
||||
response = self.client.get(
|
||||
'/api/get_config', headers={'Authorization': password}
|
||||
)
|
||||
self.assertEqual(response.status_code, 403)
|
||||
|
||||
|
||||
class DatabasePoolTests(unittest.TestCase):
|
||||
def test_cursor_is_rolled_back_and_returned_after_success(self):
|
||||
connection = FakeConnection()
|
||||
pool = FakePool(connection)
|
||||
|
||||
with mock.patch.object(database.DBPool, 'get', return_value=pool):
|
||||
with database.db_cursor():
|
||||
pass
|
||||
|
||||
self.assertEqual(connection.rollbacks, 1)
|
||||
self.assertTrue(connection.cursors[0].closed)
|
||||
self.assertEqual(pool.returned, [connection])
|
||||
|
||||
def test_cursor_is_rolled_back_and_returned_after_exception(self):
|
||||
connection = FakeConnection()
|
||||
pool = FakePool(connection)
|
||||
|
||||
with mock.patch.object(database.DBPool, 'get', return_value=pool):
|
||||
with self.assertRaisesRegex(ValueError, 'synthetic failure'):
|
||||
with database.db_cursor():
|
||||
raise ValueError('synthetic failure')
|
||||
|
||||
self.assertEqual(connection.rollbacks, 1)
|
||||
self.assertTrue(connection.cursors[0].closed)
|
||||
self.assertEqual(pool.returned, [connection])
|
||||
|
||||
def test_advisory_lock_is_released_on_exit(self):
|
||||
connection = FakeConnection()
|
||||
pool = FakePool(connection)
|
||||
|
||||
with mock.patch.object(database.DBPool, 'get', return_value=pool):
|
||||
with database.advisory_lock(42) as acquired:
|
||||
self.assertTrue(acquired)
|
||||
|
||||
self.assertEqual(len(connection.cursors[0].executed), 2)
|
||||
self.assertEqual(connection.rollbacks, 1)
|
||||
self.assertEqual(pool.returned, [connection])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,10 @@
|
||||
.git
|
||||
.env
|
||||
.env.*
|
||||
data
|
||||
dist
|
||||
volumes
|
||||
*.db
|
||||
**/__pycache__
|
||||
**/*.py[cod]
|
||||
**/tests
|
||||
@@ -0,0 +1,29 @@
|
||||
FROM golang:alpine AS build
|
||||
|
||||
ENV CGO_ENABLED=0 GOTOOLCHAIN=local GOMAXPROCS=2
|
||||
WORKDIR /src
|
||||
COPY go.mod go.sum ./
|
||||
RUN go mod download
|
||||
COPY cmd/server ./cmd/server
|
||||
COPY internal ./internal
|
||||
COPY proto/go ./proto/go
|
||||
COPY pkg ./pkg
|
||||
RUN go build -p=2 -trimpath -buildvcs=false -ldflags="-s -w" -o /out/neo-server ./cmd/server
|
||||
|
||||
FROM alpine:latest
|
||||
|
||||
RUN apk upgrade --no-cache \
|
||||
&& apk add --no-cache ca-certificates \
|
||||
&& addgroup -S -g 10001 neo \
|
||||
&& adduser -S -D -H -u 10001 -G neo neo \
|
||||
&& install -d -o 10001 -g 10001 -m 0700 /data
|
||||
COPY --from=build --chown=10001:10001 /out/neo-server /usr/local/bin/neo-server
|
||||
COPY configs/server/config.yml /etc/neo/server_config.yml
|
||||
|
||||
COPY --from=project /LICENSE /usr/share/licenses/wahrwelt/LICENSE
|
||||
|
||||
USER 10001:10001
|
||||
WORKDIR /data
|
||||
EXPOSE 5005
|
||||
ENTRYPOINT ["/usr/local/bin/neo-server"]
|
||||
CMD ["--config", "/etc/neo/server_config.yml"]
|
||||
@@ -0,0 +1,66 @@
|
||||
# Neo
|
||||
|
||||
Neo получает от Farm конфигурацию, адреса команд и настройки флагов, а затем отправляет Farm найденные флаги. Эксплойты добавляет и настраивает администратор через CLI Neo.
|
||||
|
||||
В корне проекта выполните `./control init` и настройте команды и формат флага в `.env`.
|
||||
Скрипт можно проверить до запуска серверов:
|
||||
|
||||
```sh
|
||||
./control neo test ./sploit_example.py 192.0.2.10 --timeout 10s
|
||||
```
|
||||
|
||||
Проба выполняется в отдельном временном контейнере. Она показывает stdout, stderr,
|
||||
код завершения и найденные флаги, не регистрирует задание и не отправляет флаги.
|
||||
Формат флага берется из `FARM_FLAG_FORMAT`. При превышении времени код выхода равен 124.
|
||||
|
||||
Для работы по расписанию запустите Farm и Neo:
|
||||
|
||||
```sh
|
||||
./control farm
|
||||
./control neo
|
||||
./control neo add ./sploit_example.py --id example --disabled
|
||||
./control neo enable example
|
||||
./control neo info
|
||||
./control neo tail example --count 20
|
||||
./control neo update example --interval 10s --timeout 5s
|
||||
./control neo disable example
|
||||
```
|
||||
|
||||
`add` без `--disabled` сразу включает задание. `update` меняет параметры запуска;
|
||||
для загрузки новой версии файла повторите `add` с тем же `--id`.
|
||||
`./control neo single example` запускает загруженное задание один раз по всем
|
||||
настроенным командам и передает найденные флаги Farm.
|
||||
|
||||
Пути к файлам считаются от текущего каталога. Если скрипту нужны соседние файлы,
|
||||
добавьте `--dir` к `add` или `test`: control скопирует каталог скрипта целиком.
|
||||
Символические ссылки и специальные файлы не принимаются. Исходные файлы не меняются.
|
||||
|
||||
Корневой [sploit_example.py](../../sploit_example.py) уже принимает адрес цели, делает HTTP-запрос,
|
||||
извлекает совпадения формата `FARM_FLAG_FORMAT` и печатает каждый флаг отдельной
|
||||
строкой. Настройте в начале файла порт, путь и выражение, затем допишите запрос
|
||||
или проверку сервиса в `run_exploit`:
|
||||
|
||||
```sh
|
||||
./control neo test ./sploit_example.py 192.0.2.10 --timeout 10s
|
||||
./control neo add ./sploit_example.py --id example --disabled
|
||||
./control neo enable example
|
||||
```
|
||||
|
||||
Neo получает только строки из stdout и передает совпавшие флаги в Farm. Диагностику
|
||||
пишите в stderr. Формат в `FLAG_PATTERN` должен соответствовать `FARM_FLAG_FORMAT`
|
||||
из `.env`.
|
||||
|
||||
Для соединения с Farm используется адрес `http://farm:5000`, маршруты `/api/get_config` и `/api/post_flags`, заголовки `Authorization` и `X-Token`.
|
||||
|
||||
`./control neo` запускает сервер, Redis и worker, который выполняет включенные задания.
|
||||
Farm запускается отдельно. `./control neo down` останавливает только Neo с его Redis
|
||||
и worker, сохраняя задания. Статус и журнал: `./control neo status` и `./control neo logs`.
|
||||
Отправка из Farm в систему соревнования включается через `./control farm submit-up`.
|
||||
|
||||
`NEO_KEY` и `NEO_WORKER_KEY` должны быть разными ключами длиной не менее 32 байт. Обычный worker не получает админский ключ. Его ключ разрешает только RPC для опроса, загрузки заданий и файлов, потоков команд и отправки журналов. Сеть Redis закрыта для worker. Рассылка команд выключена.
|
||||
|
||||
Worker работает без root, привилегий и Docker socket. Задания получают отдельное окружение без ключей управления Neo; клиент также закрывает чтение своей памяти через `/proc` для процессов того же UID. При остановке завершается группа процессов задания. Все процессы заданий все еще работают под UID worker внутри одного контейнера, поэтому это не изоляция заданий. По протоколу worker получает от Neo настройки Farm, включая пароль для прямой отправки флагов. Не запускайте worker для непроверенных команд без отдельной изоляции.
|
||||
|
||||
Образы используют обновляемые теги Go, Python, Alpine и Redis. Базовый worker
|
||||
устанавливает `requests` из короткого `client_env/requirements.txt` с нижней
|
||||
границей версии. Если скриптам нужны дополнительные библиотеки, добавьте их туда.
|
||||
@@ -0,0 +1,43 @@
|
||||
FROM golang:alpine AS build
|
||||
|
||||
ENV CGO_ENABLED=0 GOTOOLCHAIN=local GOMAXPROCS=2
|
||||
WORKDIR /src
|
||||
COPY go.mod go.sum ./
|
||||
RUN go mod download
|
||||
COPY cmd/client ./cmd/client
|
||||
COPY internal ./internal
|
||||
COPY proto/go ./proto/go
|
||||
COPY pkg ./pkg
|
||||
RUN go build -p=2 -trimpath -buildvcs=false -ldflags="-s -w" -o /out/neo ./cmd/client
|
||||
|
||||
FROM python:alpine
|
||||
|
||||
ENV PIP_DISABLE_PIP_VERSION_CHECK=1 \
|
||||
PYTHONDONTWRITEBYTECODE=1 \
|
||||
PYTHONUNBUFFERED=1 \
|
||||
HOME=/work
|
||||
|
||||
RUN apk --no-cache upgrade \
|
||||
&& apk --no-cache add bash \
|
||||
&& addgroup -S -g 10001 neo \
|
||||
&& adduser -S -D -H -u 10001 -G neo -h /work -s /sbin/nologin neo \
|
||||
&& install -d -o 10001 -g 10001 -m 0700 /work /work/exploits
|
||||
|
||||
COPY client_env/requirements.txt /tmp/requirements.txt
|
||||
RUN python -m pip install --no-cache-dir --upgrade -r /tmp/requirements.txt \
|
||||
&& python -m pip check \
|
||||
&& python -m pip uninstall --yes pip setuptools \
|
||||
&& rm -f /usr/local/bin/pip /usr/local/bin/pip3 /usr/local/bin/pip3.* \
|
||||
&& rm -rf /usr/local/lib/python*/ensurepip /usr/local/lib/python*/__pycache__/ensurepip* \
|
||||
&& rm /tmp/requirements.txt
|
||||
|
||||
COPY --from=build /out/neo /usr/local/bin/neo
|
||||
COPY --chmod=0555 client_env/entrypoint.sh /entrypoint.sh
|
||||
COPY configs/client/config.yml /etc/neo/client_config.yml
|
||||
|
||||
COPY --from=project /LICENSE /usr/share/licenses/wahrwelt/LICENSE
|
||||
|
||||
USER 10001:10001
|
||||
WORKDIR /work
|
||||
ENTRYPOINT ["/entrypoint.sh"]
|
||||
CMD ["/usr/local/bin/neo", "--config", "/etc/neo/client_config.yml", "run", "--jobs", "2", "--endless-jobs", "0"]
|
||||
@@ -0,0 +1,9 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
if [ -z "${NEO_CLIENT_ID:-}" ]; then
|
||||
NEO_CLIENT_ID="$(hostname)"
|
||||
export NEO_CLIENT_ID
|
||||
fi
|
||||
|
||||
exec "$@"
|
||||
@@ -0,0 +1 @@
|
||||
requests>=2.34.2
|
||||
@@ -0,0 +1,203 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/sirupsen/logrus"
|
||||
"github.com/spf13/cobra"
|
||||
"google.golang.org/protobuf/types/known/durationpb"
|
||||
|
||||
"github.com/c4t-but-s4d/neo/v2/internal/client"
|
||||
"github.com/c4t-but-s4d/neo/v2/pkg/archive"
|
||||
epb "github.com/c4t-but-s4d/neo/v2/proto/go/exploits"
|
||||
)
|
||||
|
||||
type addCLI struct {
|
||||
*baseCLI
|
||||
path string
|
||||
isArchive bool
|
||||
exploitID string
|
||||
runEvery time.Duration
|
||||
timeout time.Duration
|
||||
endless bool
|
||||
disabled bool
|
||||
yes bool
|
||||
}
|
||||
|
||||
func NewAdd(cmd *cobra.Command, args []string, cfg *client.Config) NeoCLI {
|
||||
c := &addCLI{
|
||||
baseCLI: &baseCLI{cfg: cfg},
|
||||
path: args[0],
|
||||
}
|
||||
|
||||
var err error
|
||||
if c.exploitID, err = cmd.Flags().GetString("id"); err != nil {
|
||||
logrus.Fatalf("Не удалось прочитать идентификатор эксплойта: %v", err)
|
||||
}
|
||||
if c.isArchive, err = cmd.Flags().GetBool("dir"); err != nil {
|
||||
logrus.Fatalf("Не удалось прочитать параметр каталога: %v", err)
|
||||
}
|
||||
if c.runEvery, err = cmd.Flags().GetDuration("interval"); err != nil {
|
||||
logrus.Fatalf("Не удалось прочитать интервал запуска: %v", err)
|
||||
}
|
||||
if c.timeout, err = cmd.Flags().GetDuration("timeout"); err != nil {
|
||||
logrus.Fatalf("Не удалось прочитать тайм-аут запуска: %v", err)
|
||||
}
|
||||
if c.endless, err = cmd.Flags().GetBool("endless"); err != nil {
|
||||
logrus.Fatalf("Не удалось прочитать параметр бесконечного режима: %v", err)
|
||||
}
|
||||
if c.disabled, err = cmd.Flags().GetBool("disabled"); err != nil {
|
||||
logrus.Fatalf("Не удалось прочитать параметр отключения: %v", err)
|
||||
}
|
||||
if c.yes, err = cmd.Flags().GetBool("yes"); err != nil {
|
||||
logrus.Fatalf("Не удалось прочитать параметр --yes: %v", err)
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
func (ac *addCLI) Run(ctx context.Context) error {
|
||||
_, err := os.Stat(ac.path)
|
||||
if err != nil {
|
||||
return fmt.Errorf("не удалось проверить файл %s: %w", ac.path, err)
|
||||
}
|
||||
// Заменить путь на абсолютный.
|
||||
if ac.path, err = filepath.Abs(ac.path); err != nil {
|
||||
return fmt.Errorf("не удалось получить абсолютный путь: %w", err)
|
||||
}
|
||||
|
||||
if errs := ac.validateEntry(ac.path); len(errs) > 0 {
|
||||
for _, v := range errs {
|
||||
logrus.Errorf("%v", v)
|
||||
}
|
||||
return errors.New("эксплойт некорректен")
|
||||
}
|
||||
|
||||
dir, file := path.Split(ac.path)
|
||||
if ac.exploitID == "" {
|
||||
ac.exploitID = file
|
||||
}
|
||||
logrus.Infof("Добавление эксплойта с id = %s", ac.exploitID)
|
||||
|
||||
c, err := ac.client()
|
||||
if err != nil {
|
||||
return fmt.Errorf("не удалось создать клиент: %w", err)
|
||||
}
|
||||
state, err := c.GetServerState(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("не удалось получить конфигурацию сервера: %w", err)
|
||||
}
|
||||
|
||||
if getExploitFromState(state, ac.exploitID) != nil {
|
||||
confirmed, err := confirmNewVersion(os.Stdin, os.Stdout, ac.yes)
|
||||
if err != nil {
|
||||
return fmt.Errorf("не удалось прочитать ответ: %w", err)
|
||||
}
|
||||
if !confirmed {
|
||||
logrus.Fatal("Операция отменена")
|
||||
}
|
||||
}
|
||||
|
||||
var f *os.File
|
||||
if ac.isArchive {
|
||||
f, err = os.CreateTemp("", "ARCHIVE")
|
||||
if err != nil {
|
||||
return fmt.Errorf("не удалось создать временный файл: %w", err)
|
||||
}
|
||||
|
||||
defer func() {
|
||||
_ = os.Remove(f.Name())
|
||||
}()
|
||||
if err := archive.Tar(dir, f); err != nil {
|
||||
return fmt.Errorf("не удалось создать архив tar.gz: %w", err)
|
||||
}
|
||||
|
||||
// Переместить указатель в начало файла перед чтением.
|
||||
if _, err := f.Seek(0, io.SeekStart); err != nil {
|
||||
return fmt.Errorf("не удалось переместить указатель в архиве: %w", err)
|
||||
}
|
||||
} else {
|
||||
f, err = os.Open(ac.path)
|
||||
if err != nil {
|
||||
return fmt.Errorf("не удалось открыть файл эксплойта: %w", err)
|
||||
}
|
||||
}
|
||||
defer func() {
|
||||
_ = f.Close()
|
||||
}()
|
||||
|
||||
fileInfo, err := c.UploadFile(ctx, f)
|
||||
if err != nil {
|
||||
return fmt.Errorf("не удалось загрузить файл эксплойта: %w", err)
|
||||
}
|
||||
|
||||
exState := &epb.ExploitState{
|
||||
ExploitId: ac.exploitID,
|
||||
File: fileInfo,
|
||||
Config: &epb.ExploitConfiguration{
|
||||
Entrypoint: file,
|
||||
IsArchive: ac.isArchive,
|
||||
RunEvery: durationpb.New(ac.runEvery),
|
||||
Timeout: durationpb.New(ac.timeout),
|
||||
Endless: ac.endless,
|
||||
Disabled: ac.disabled,
|
||||
},
|
||||
}
|
||||
newState, err := c.UpdateExploit(ctx, exState)
|
||||
if err != nil {
|
||||
return fmt.Errorf("не удалось обновить эксплойт: %w", err)
|
||||
}
|
||||
logrus.Infof("Эксплойт %s обновлен до версии %d", newState.GetExploitId(), newState.GetVersion())
|
||||
return nil
|
||||
}
|
||||
|
||||
func confirmNewVersion(input io.Reader, output io.Writer, assumeYes bool) (bool, error) {
|
||||
if assumeYes {
|
||||
return true, nil
|
||||
}
|
||||
if _, err := fmt.Fprintln(output, "Эксплойт с таким id уже есть. Добавить новую версию? да/нет"); err != nil {
|
||||
return false, fmt.Errorf("не удалось показать запрос подтверждения: %w", err)
|
||||
}
|
||||
var response string
|
||||
if _, err := fmt.Fscanln(input, &response); err != nil {
|
||||
return false, err
|
||||
}
|
||||
answer := strings.ToLower(strings.TrimSpace(response))
|
||||
return answer == "y" || answer == "yes" || answer == "д" || answer == "да", nil
|
||||
}
|
||||
|
||||
func (ac *addCLI) validateEntry(f string) (errors []string) {
|
||||
data, err := os.ReadFile(f)
|
||||
if err != nil {
|
||||
errors = append(errors, err.Error())
|
||||
return
|
||||
}
|
||||
if !isBinary(data) {
|
||||
if !bytes.HasPrefix(data, []byte("#!")) {
|
||||
desc := fmt.Sprintf(
|
||||
"Добавьте в первую строку скрипта shebang, например %s",
|
||||
"#!/usr/bin/env python3",
|
||||
)
|
||||
errors = append(errors, desc)
|
||||
}
|
||||
|
||||
// Для Python задана переменная PYTHONUNBUFFERED=1, поэтому принудительный сброс не нужен.
|
||||
if !bytes.Contains(data, []byte("#!/usr/bin/env python")) {
|
||||
re := regexp.MustCompile(`(?m)flush[(=]`)
|
||||
if !re.Match(data) {
|
||||
desc := "Сбрасывайте вывод явно, например print(..., flush=True) в Python"
|
||||
errors = append(errors, desc)
|
||||
}
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/c4t-but-s4d/neo/v2/internal/client"
|
||||
)
|
||||
|
||||
func TestValidateEntryHandlesShortFiles(t *testing.T) {
|
||||
for _, content := range []string{"", "#", "#!"} {
|
||||
t.Run(content, func(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "short-script")
|
||||
require.NoError(t, os.WriteFile(path, []byte(content), 0600))
|
||||
require.NotPanics(t, func() {
|
||||
require.NotEmpty(t, (&addCLI{}).validateEntry(path))
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfirmNewVersionWithYesDoesNotPromptOrReadInput(t *testing.T) {
|
||||
var output bytes.Buffer
|
||||
confirmed, err := confirmNewVersion(strings.NewReader(""), &output, true)
|
||||
require.NoError(t, err)
|
||||
require.True(t, confirmed)
|
||||
require.Empty(t, output.String())
|
||||
}
|
||||
|
||||
func TestConfirmNewVersionKeepsInteractivePrompt(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
input string
|
||||
confirmed bool
|
||||
}{
|
||||
{name: "английское да", input: "y\n", confirmed: true},
|
||||
{name: "английское yes", input: "YES\n", confirmed: true},
|
||||
{name: "русская буква", input: "д\n", confirmed: true},
|
||||
{name: "русское да", input: "Да\n", confirmed: true},
|
||||
{name: "отказ", input: "нет\n", confirmed: false},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
var output bytes.Buffer
|
||||
confirmed, err := confirmNewVersion(strings.NewReader(test.input), &output, false)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, test.confirmed, confirmed)
|
||||
require.Contains(t, output.String(), "Добавить новую версию? да/нет")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfirmNewVersionReturnsEOFWithoutAssumingYes(t *testing.T) {
|
||||
var output bytes.Buffer
|
||||
confirmed, err := confirmNewVersion(strings.NewReader(""), &output, false)
|
||||
require.ErrorIs(t, err, io.EOF)
|
||||
require.False(t, confirmed)
|
||||
require.Contains(t, output.String(), "Добавить новую версию? да/нет")
|
||||
}
|
||||
|
||||
func TestNewAddReadsYesFlag(t *testing.T) {
|
||||
command := &cobra.Command{}
|
||||
command.Flags().String("id", "", "")
|
||||
command.Flags().Bool("dir", false, "")
|
||||
command.Flags().Duration("interval", 0, "")
|
||||
command.Flags().Duration("timeout", 0, "")
|
||||
command.Flags().Bool("endless", false, "")
|
||||
command.Flags().Bool("disabled", false, "")
|
||||
command.Flags().Bool("yes", true, "")
|
||||
|
||||
result := NewAdd(command, []string{"job.py"}, &client.Config{})
|
||||
add, ok := result.(*addCLI)
|
||||
require.True(t, ok)
|
||||
require.True(t, add.yes)
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/sirupsen/logrus"
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/c4t-but-s4d/neo/v2/internal/client"
|
||||
)
|
||||
|
||||
type broadcastCLI struct {
|
||||
*baseCLI
|
||||
cmd string
|
||||
}
|
||||
|
||||
func NewBroadcast(cmd *cobra.Command, _ []string, cfg *client.Config) NeoCLI {
|
||||
command, err := cmd.Flags().GetString("command")
|
||||
if err != nil {
|
||||
logrus.Fatalf("Не удалось прочитать команду: %v", err)
|
||||
}
|
||||
return &broadcastCLI{
|
||||
baseCLI: &baseCLI{cfg: cfg},
|
||||
cmd: command,
|
||||
}
|
||||
}
|
||||
|
||||
func (bc *broadcastCLI) Run(ctx context.Context) error {
|
||||
logrus.Info("Отправка команды всем подключенным клиентам")
|
||||
c, err := bc.client()
|
||||
if err != nil {
|
||||
return fmt.Errorf("не удалось создать клиент: %w", err)
|
||||
}
|
||||
if err := c.BroadcastCommand(ctx, bc.cmd); err != nil {
|
||||
return fmt.Errorf("не удалось отправить широковещательную команду: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/denisbrodbeck/machineid"
|
||||
"github.com/sirupsen/logrus"
|
||||
"github.com/spf13/viper"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/credentials"
|
||||
"google.golang.org/grpc/credentials/insecure"
|
||||
"google.golang.org/grpc/encoding/gzip"
|
||||
|
||||
"github.com/c4t-but-s4d/neo/v2/internal/client"
|
||||
"github.com/c4t-but-s4d/neo/v2/pkg/grpcauth"
|
||||
)
|
||||
|
||||
type NeoCLI interface {
|
||||
Run(ctx context.Context) error
|
||||
}
|
||||
|
||||
type baseCLI struct {
|
||||
cfg *client.Config
|
||||
|
||||
clientID string
|
||||
}
|
||||
|
||||
func (cmd *baseCLI) client() (*client.Client, error) {
|
||||
if err := grpcauth.ValidateKey(cmd.cfg.GrpcAuthKey); err != nil {
|
||||
return nil, fmt.Errorf("неверный ключ gRPC: %w", err)
|
||||
}
|
||||
opts := []grpc.DialOption{
|
||||
grpc.WithDefaultCallOptions(
|
||||
grpc.UseCompressor(gzip.Name),
|
||||
),
|
||||
}
|
||||
interceptor := grpcauth.NewClientInterceptor(cmd.cfg.GrpcAuthKey)
|
||||
opts = append(
|
||||
opts,
|
||||
grpc.WithUnaryInterceptor(interceptor.Unary()),
|
||||
grpc.WithStreamInterceptor(interceptor.Stream()),
|
||||
)
|
||||
if !cmd.cfg.UseTLS {
|
||||
opts = append(
|
||||
opts,
|
||||
grpc.WithTransportCredentials(insecure.NewCredentials()),
|
||||
)
|
||||
} else {
|
||||
opts = append(opts, grpc.WithTransportCredentials(credentials.NewTLS(&tls.Config{})))
|
||||
}
|
||||
conn, err := grpc.Dial(cmd.cfg.Host, opts...)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("не удалось подключиться к gRPC-серверу: %w", err)
|
||||
}
|
||||
return client.New(conn, cmd.ClientID()), nil
|
||||
}
|
||||
|
||||
func (cmd *baseCLI) ClientID() string {
|
||||
if cmd.clientID != "" {
|
||||
return cmd.clientID
|
||||
}
|
||||
|
||||
cmd.clientID = viper.GetString("client_id")
|
||||
if cmd.clientID == "" {
|
||||
var err error
|
||||
if cmd.clientID, err = machineid.ID(); err != nil {
|
||||
logrus.Fatalf("Не удалось получить уникальный идентификатор клиента: %v", err)
|
||||
}
|
||||
}
|
||||
logrus.Infof("Идентификатор клиента: %s", cmd.clientID)
|
||||
return cmd.clientID
|
||||
}
|
||||
|
||||
func (cmd *baseCLI) Run(_ context.Context) error {
|
||||
return errors.New("команда не реализована")
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"path"
|
||||
"sync"
|
||||
|
||||
"github.com/sirupsen/logrus"
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/c4t-but-s4d/neo/v2/internal/client"
|
||||
"github.com/c4t-but-s4d/neo/v2/internal/config"
|
||||
"github.com/c4t-but-s4d/neo/v2/internal/exploit"
|
||||
"github.com/c4t-but-s4d/neo/v2/internal/queue"
|
||||
"github.com/c4t-but-s4d/neo/v2/pkg/joblogger"
|
||||
)
|
||||
|
||||
type dryRunCLI struct {
|
||||
*baseCLI
|
||||
jobs int
|
||||
exploitID string
|
||||
teamID string
|
||||
teamIP string
|
||||
}
|
||||
|
||||
func NewDryRun(cmd *cobra.Command, args []string, cfg *client.Config) NeoCLI {
|
||||
cfg.ExploitDir = path.Join(cfg.ExploitDir, "dry")
|
||||
if err := os.MkdirAll(cfg.ExploitDir, os.ModePerm); err != nil {
|
||||
logrus.Fatalf("Не удалось создать каталог для локального запуска %v: %v", cfg.ExploitDir, err)
|
||||
}
|
||||
|
||||
cli := &dryRunCLI{
|
||||
baseCLI: &baseCLI{cfg: cfg},
|
||||
exploitID: args[0],
|
||||
jobs: parseJobsFlag(cmd, "jobs"),
|
||||
}
|
||||
cli.teamID, _ = cmd.Flags().GetString("team_id")
|
||||
cli.teamIP, _ = cmd.Flags().GetString("team_ip")
|
||||
return cli
|
||||
}
|
||||
|
||||
func (rc *dryRunCLI) Run(ctx context.Context) error {
|
||||
c, err := rc.client()
|
||||
if err != nil {
|
||||
return fmt.Errorf("не удалось создать клиент: %w", err)
|
||||
}
|
||||
state, err := c.GetServerState(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("не удалось получить конфигурацию сервера: %w", err)
|
||||
}
|
||||
cfg, err := config.FromProto(state.Config)
|
||||
if err != nil {
|
||||
return fmt.Errorf("не удалось разобрать конфигурацию: %w", err)
|
||||
}
|
||||
|
||||
if getExploitFromState(state, rc.exploitID) == nil {
|
||||
return fmt.Errorf("эксплойт %s не найден, сначала добавьте его", rc.exploitID)
|
||||
}
|
||||
|
||||
storage := exploit.NewStorage(exploit.NewCache(), rc.baseCLI.cfg.ExploitDir, c)
|
||||
storage.UpdateExploits(ctx, state.Exploits)
|
||||
ex, ok := storage.Exploit(rc.exploitID)
|
||||
if !ok {
|
||||
return fmt.Errorf("эксплойт %s не найден в хранилище", rc.exploitID)
|
||||
}
|
||||
|
||||
allTeams := make(map[string]string)
|
||||
for _, tbuck := range state.ClientTeamMap {
|
||||
for k, v := range tbuck.Teams {
|
||||
allTeams[k] = v
|
||||
}
|
||||
}
|
||||
|
||||
sender := joblogger.NewDummySender()
|
||||
|
||||
var tasks []*queue.Job
|
||||
if rc.teamIP == "" && rc.teamID == "" {
|
||||
tasks = exploit.CreateExploitJobs(ex, allTeams, cfg.Environ, sender)
|
||||
} else {
|
||||
oneTeamMap := make(map[string]string)
|
||||
for k, v := range allTeams {
|
||||
if k == rc.teamID || v == rc.teamIP {
|
||||
oneTeamMap[k] = v
|
||||
}
|
||||
}
|
||||
tasks = exploit.CreateExploitJobs(ex, oneTeamMap, cfg.Environ, sender)
|
||||
}
|
||||
|
||||
var q queue.Queue
|
||||
if ex.Endless {
|
||||
q = queue.NewEndlessQueue(rc.jobs)
|
||||
} else {
|
||||
q = queue.NewSimpleQueue(rc.jobs)
|
||||
}
|
||||
|
||||
runCtx, runCancel := context.WithCancel(ctx)
|
||||
defer runCancel()
|
||||
|
||||
wg := sync.WaitGroup{}
|
||||
defer wg.Wait()
|
||||
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
q.Start(runCtx)
|
||||
logrus.Info("Очередь завершена")
|
||||
}()
|
||||
|
||||
for _, t := range tasks {
|
||||
if err := q.Add(t); err != nil {
|
||||
logrus.Errorf("Не удалось добавить эксплойт %s для цели %s в очередь: %v", t.Exploit.ID, t.Target.IP, err)
|
||||
}
|
||||
}
|
||||
|
||||
tasksDone := 0
|
||||
loop:
|
||||
for {
|
||||
select {
|
||||
case res, ok := <-q.Results():
|
||||
if !ok || tasksDone+1 == len(tasks) && !ex.Endless {
|
||||
logrus.Info("Запуски завершены, ожидание остановки очереди")
|
||||
break loop
|
||||
}
|
||||
tasksDone++
|
||||
logrus.Infof("Цель = %v, вывод = %v", res.Target, string(res.Out))
|
||||
case <-ctx.Done():
|
||||
logrus.Info("Получен сигнал остановки")
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/c4t-but-s4d/neo/v2/internal/client"
|
||||
"github.com/c4t-but-s4d/neo/v2/internal/config"
|
||||
epb "github.com/c4t-but-s4d/neo/v2/proto/go/exploits"
|
||||
)
|
||||
|
||||
type infoCLI struct {
|
||||
*baseCLI
|
||||
}
|
||||
|
||||
func NewInfo(_ *cobra.Command, _ []string, cfg *client.Config) NeoCLI {
|
||||
return &infoCLI{&baseCLI{cfg: cfg}}
|
||||
}
|
||||
|
||||
func (ic *infoCLI) Run(ctx context.Context) error {
|
||||
c, err := ic.client()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
state, err := c.GetServerState(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("не удалось запросить конфигурацию сервера: %w", err)
|
||||
}
|
||||
cfg, err := config.FromProto(state.Config)
|
||||
if err != nil {
|
||||
return fmt.Errorf("не удалось разобрать конфигурацию: %w", err)
|
||||
}
|
||||
fmt.Print(formatServerInfo(cfg, state))
|
||||
return nil
|
||||
}
|
||||
|
||||
func formatServerInfo(cfg *config.ExploitsConfig, state *epb.ServerState) string {
|
||||
var out strings.Builder
|
||||
fmt.Fprintf(&out, "Farm: %s\n", cfg.FarmURL)
|
||||
fmt.Fprintf(&out, "Интервал опроса: %s\n", cfg.PingEvery)
|
||||
fmt.Fprintf(&out, "Интервал отправки флагов: %s\n", cfg.SubmitEvery)
|
||||
fmt.Fprintf(&out, "Правило флага: %s\n", cfg.FlagRegexp)
|
||||
fmt.Fprintf(&out, "Переменных окружения: %d\n", len(cfg.Environ))
|
||||
|
||||
fmt.Fprintln(&out, "Адреса команд:")
|
||||
bucketIDs := make([]string, 0, len(state.ClientTeamMap))
|
||||
for id := range state.ClientTeamMap {
|
||||
bucketIDs = append(bucketIDs, id)
|
||||
}
|
||||
sort.Strings(bucketIDs)
|
||||
for _, bucketID := range bucketIDs {
|
||||
bucket := state.ClientTeamMap[bucketID]
|
||||
teamIDs := make([]string, 0, len(bucket.GetTeams()))
|
||||
for id := range bucket.GetTeams() {
|
||||
teamIDs = append(teamIDs, id)
|
||||
}
|
||||
sort.Strings(teamIDs)
|
||||
for _, teamID := range teamIDs {
|
||||
fmt.Fprintf(&out, " %s: %s\n", teamID, bucket.GetTeams()[teamID])
|
||||
}
|
||||
}
|
||||
|
||||
fmt.Fprintln(&out, "Эксплойты:")
|
||||
for _, exploit := range state.Exploits {
|
||||
if exploit == nil {
|
||||
continue
|
||||
}
|
||||
cfg := exploit.GetConfig()
|
||||
fmt.Fprintf(&out, " %s, версия %d", exploit.GetExploitId(), exploit.GetVersion())
|
||||
if cfg != nil {
|
||||
fmt.Fprintf(&out, ", интервал %s, тайм-аут %s, бесконечный режим %t, отключен %t, точка входа %s",
|
||||
cfg.GetRunEvery().AsDuration(), cfg.GetTimeout().AsDuration(), cfg.GetEndless(), cfg.GetDisabled(), cfg.GetEntrypoint())
|
||||
}
|
||||
fmt.Fprintln(&out)
|
||||
}
|
||||
return out.String()
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/c4t-but-s4d/neo/v2/internal/config"
|
||||
epb "github.com/c4t-but-s4d/neo/v2/proto/go/exploits"
|
||||
"github.com/stretchr/testify/require"
|
||||
"google.golang.org/protobuf/types/known/durationpb"
|
||||
)
|
||||
|
||||
func TestFormatServerInfoOmitsSecrets(t *testing.T) {
|
||||
const secret = "farm-password-must-not-appear"
|
||||
cfg := &config.ExploitsConfig{
|
||||
FarmURL: "http://farm:5000",
|
||||
FarmPassword: secret,
|
||||
FlagRegexp: regexp.MustCompile(`FLAG\\{.*\\}`),
|
||||
PingEvery: time.Second * 5,
|
||||
SubmitEvery: time.Second * 2,
|
||||
Environ: []string{"TOKEN=environment-secret"},
|
||||
}
|
||||
state := &epb.ServerState{
|
||||
Config: &epb.Config{
|
||||
FarmPassword: secret,
|
||||
Environ: []string{"TOKEN=environment-secret"},
|
||||
},
|
||||
ClientTeamMap: map[string]*epb.TeamBucket{
|
||||
"worker": {Teams: map[string]string{"team-1": "127.0.0.1"}},
|
||||
},
|
||||
Exploits: []*epb.ExploitState{{
|
||||
ExploitId: "check",
|
||||
Version: 1,
|
||||
Config: &epb.ExploitConfiguration{
|
||||
Entrypoint: "check.py",
|
||||
RunEvery: durationpb.New(time.Second * 30),
|
||||
Timeout: durationpb.New(time.Second * 10),
|
||||
},
|
||||
}},
|
||||
}
|
||||
|
||||
output := formatServerInfo(cfg, state)
|
||||
require.NotContains(t, output, secret)
|
||||
require.NotContains(t, output, "environment-secret")
|
||||
require.Contains(t, output, "http://farm:5000")
|
||||
require.Contains(t, output, "team-1: 127.0.0.1")
|
||||
require.Contains(t, output, "check, версия 1")
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
|
||||
"github.com/sirupsen/logrus"
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/c4t-but-s4d/neo/v2/internal/client"
|
||||
"github.com/c4t-but-s4d/neo/v2/internal/exploit"
|
||||
"github.com/c4t-but-s4d/neo/v2/pkg/joblogger"
|
||||
)
|
||||
|
||||
const JobsPerCPU = 5
|
||||
|
||||
type runCLI struct {
|
||||
*baseCLI
|
||||
run *exploit.Runner
|
||||
sender *joblogger.RemoteSender
|
||||
}
|
||||
|
||||
func parseJobsFlag(cmd *cobra.Command, name string) int {
|
||||
jobs, err := cmd.Flags().GetInt(name)
|
||||
if err != nil {
|
||||
logrus.Fatalf("Не удалось прочитать число заданий: %v", err)
|
||||
}
|
||||
if jobs < 0 {
|
||||
logrus.Fatal("run: число заданий не может быть отрицательным")
|
||||
}
|
||||
return jobs
|
||||
}
|
||||
|
||||
func NewRun(cmd *cobra.Command, _ []string, cfg *client.Config) NeoCLI {
|
||||
cli := &runCLI{
|
||||
baseCLI: &baseCLI{cfg: cfg},
|
||||
}
|
||||
neocli, err := cli.client()
|
||||
if err != nil {
|
||||
logrus.Fatalf("run: не удалось создать клиент: %v", err)
|
||||
}
|
||||
|
||||
jobs := parseJobsFlag(cmd, "jobs")
|
||||
endlessJobs := parseJobsFlag(cmd, "endless-jobs")
|
||||
timeoutScaleTarget, err := cmd.Flags().GetFloat64("timeout-autoscale-target")
|
||||
if err != nil {
|
||||
logrus.Fatalf("Не удалось прочитать параметр timeout-autoscale-target: %v", err)
|
||||
}
|
||||
if timeoutScaleTarget < 0 {
|
||||
logrus.Fatalf("timeout-autoscale-target не может быть отрицательным")
|
||||
}
|
||||
|
||||
neocli.Weight = jobs
|
||||
cli.sender = joblogger.NewRemoteSender(neocli)
|
||||
cli.run = exploit.NewRunner(
|
||||
cli.ClientID(),
|
||||
jobs,
|
||||
endlessJobs,
|
||||
timeoutScaleTarget,
|
||||
cfg,
|
||||
neocli,
|
||||
cli.sender,
|
||||
)
|
||||
|
||||
return cli
|
||||
}
|
||||
|
||||
func (rc *runCLI) Run(ctx context.Context) error {
|
||||
wg := sync.WaitGroup{}
|
||||
defer wg.Wait()
|
||||
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
rc.sender.Start(ctx)
|
||||
logrus.Info("Отправка журналов завершена")
|
||||
}()
|
||||
|
||||
return rc.run.Run(ctx) // nolint:wrapcheck
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/c4t-but-s4d/neo/v2/internal/client"
|
||||
)
|
||||
|
||||
type setDisabledCli struct {
|
||||
*baseCLI
|
||||
exploitID string
|
||||
disabled bool
|
||||
}
|
||||
|
||||
func NewSetDisabled(_ *cobra.Command, args []string, cfg *client.Config, disabled bool) NeoCLI {
|
||||
return &setDisabledCli{
|
||||
baseCLI: &baseCLI{cfg: cfg},
|
||||
exploitID: args[0],
|
||||
disabled: disabled,
|
||||
}
|
||||
}
|
||||
|
||||
func (sc *setDisabledCli) Run(ctx context.Context) error {
|
||||
c, err := sc.client()
|
||||
if err != nil {
|
||||
return fmt.Errorf("не удалось создать клиент: %w", err)
|
||||
}
|
||||
state, err := c.GetServerState(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("не удалось получить конфигурацию сервера: %w", err)
|
||||
}
|
||||
|
||||
if spl := getExploitFromState(state, sc.exploitID); spl == nil {
|
||||
return fmt.Errorf("эксплойт %s не найден", sc.exploitID)
|
||||
} else if err := c.SetExploitDisabled(ctx, spl.ExploitId, sc.disabled); err != nil {
|
||||
return fmt.Errorf("не удалось изменить состояние эксплойта: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/sirupsen/logrus"
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/c4t-but-s4d/neo/v2/internal/client"
|
||||
)
|
||||
|
||||
type singleRunCLI struct {
|
||||
*baseCLI
|
||||
exploitID string
|
||||
}
|
||||
|
||||
func NewSingleRun(_ *cobra.Command, args []string, cfg *client.Config) NeoCLI {
|
||||
return &singleRunCLI{
|
||||
baseCLI: &baseCLI{cfg: cfg},
|
||||
exploitID: args[0],
|
||||
}
|
||||
}
|
||||
|
||||
func (sc *singleRunCLI) Run(ctx context.Context) error {
|
||||
c, err := sc.client()
|
||||
if err != nil {
|
||||
return fmt.Errorf("не удалось создать клиент: %w", err)
|
||||
}
|
||||
state, err := c.GetServerState(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("не удалось получить конфигурацию сервера: %w", err)
|
||||
}
|
||||
|
||||
if getExploitFromState(state, sc.exploitID) == nil {
|
||||
logrus.Fatalf("Эксплойт %s не найден. Сначала добавьте его.", sc.exploitID)
|
||||
}
|
||||
if err := c.SingleRun(ctx, sc.exploitID); err != nil {
|
||||
return fmt.Errorf("не удалось выполнить разовый запуск: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/sirupsen/logrus"
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/c4t-but-s4d/neo/v2/internal/client"
|
||||
logspb "github.com/c4t-but-s4d/neo/v2/proto/go/logs"
|
||||
)
|
||||
|
||||
type tailCLI struct {
|
||||
*baseCLI
|
||||
exploitID string
|
||||
version int64
|
||||
count int
|
||||
}
|
||||
|
||||
func NewTail(cmd *cobra.Command, args []string, cfg *client.Config) NeoCLI {
|
||||
c := &tailCLI{
|
||||
baseCLI: &baseCLI{cfg: cfg},
|
||||
exploitID: args[0],
|
||||
}
|
||||
|
||||
var err error
|
||||
if c.version, err = cmd.Flags().GetInt64("version"); err != nil {
|
||||
logrus.Fatalf("Не удалось прочитать версию эксплойта: %v", err)
|
||||
}
|
||||
if c.count, err = cmd.Flags().GetInt("count"); err != nil {
|
||||
logrus.Fatalf("Не удалось прочитать число строк: %v", err)
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
func (tc *tailCLI) Run(ctx context.Context) error {
|
||||
c, err := tc.client()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
state, err := c.GetServerState(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("не удалось запросить конфигурацию сервера: %w", err)
|
||||
}
|
||||
found := false
|
||||
for _, ex := range state.Exploits {
|
||||
if ex.ExploitId == tc.exploitID {
|
||||
found = true
|
||||
if tc.version == 0 {
|
||||
tc.version = ex.Version
|
||||
}
|
||||
if ex.Version > tc.version {
|
||||
return fmt.Errorf("запрошена более новая версия, текущая версия: %v", ex.Version)
|
||||
}
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
return fmt.Errorf("эксплойт %v версии %v не найден", tc.exploitID, tc.version)
|
||||
}
|
||||
|
||||
stream, err := c.SearchLogLines(ctx, tc.exploitID, tc.version)
|
||||
if err != nil {
|
||||
return fmt.Errorf("не удалось запросить строки журнала: %w", err)
|
||||
}
|
||||
var lines []*logspb.LogLine
|
||||
for batch := range stream {
|
||||
lines = append(lines, batch...)
|
||||
}
|
||||
logrus.Debugf("Получено строк журнала: %d", len(lines))
|
||||
if tc.count != -1 && len(lines) > tc.count {
|
||||
lines = lines[len(lines)-tc.count:]
|
||||
}
|
||||
|
||||
logrus.SetLevel(logrus.DebugLevel)
|
||||
for _, line := range lines {
|
||||
logger := logrus.WithFields(logrus.Fields{
|
||||
"exploit": line.Exploit,
|
||||
"version": line.Version,
|
||||
"team": line.Team,
|
||||
})
|
||||
switch line.Level {
|
||||
case "debug":
|
||||
logger.Debug(line.Message)
|
||||
case "info":
|
||||
logger.Info(line.Message)
|
||||
case "warning":
|
||||
logger.Warning(line.Message)
|
||||
case "error":
|
||||
logger.Error(line.Message)
|
||||
default:
|
||||
logger.Warningf("Неизвестный уровень журнала: %v", line.Level)
|
||||
logger.Warning(line.Message)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,393 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/c4t-but-s4d/neo/v2/internal/models"
|
||||
"github.com/c4t-but-s4d/neo/v2/internal/queue"
|
||||
)
|
||||
|
||||
const (
|
||||
testOutputLimit = 1 << 20
|
||||
testFileLimit = int64(512 << 20)
|
||||
testEntryLimit = 10_000
|
||||
testTimeoutCode = 124
|
||||
testCancelCode = 130
|
||||
testDirPrefix = ".neo-test-"
|
||||
)
|
||||
|
||||
// TestResult содержит ограниченный вывод локального запуска и найденные совпадения.
|
||||
type TestResult struct {
|
||||
Stdout []byte
|
||||
Stderr []byte
|
||||
StdoutTruncated bool
|
||||
StderrTruncated bool
|
||||
ExitCode int
|
||||
TimedOut bool
|
||||
Flags []string
|
||||
}
|
||||
|
||||
type limitedBuffer struct {
|
||||
buf bytes.Buffer
|
||||
limit int
|
||||
truncated bool
|
||||
}
|
||||
|
||||
func (b *limitedBuffer) Write(p []byte) (int, error) {
|
||||
remaining := b.limit - b.buf.Len()
|
||||
if remaining > len(p) {
|
||||
remaining = len(p)
|
||||
}
|
||||
if remaining > 0 {
|
||||
if _, err := b.buf.Write(p[:remaining]); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
}
|
||||
if remaining < len(p) {
|
||||
b.truncated = true
|
||||
}
|
||||
return len(p), nil
|
||||
}
|
||||
|
||||
func (b *limitedBuffer) Bytes() []byte {
|
||||
return b.buf.Bytes()
|
||||
}
|
||||
|
||||
type copyLimits struct {
|
||||
entries int
|
||||
bytes int64
|
||||
}
|
||||
|
||||
func (limits *copyLimits) add(size int64) error {
|
||||
limits.entries++
|
||||
if limits.entries > testEntryLimit {
|
||||
return fmt.Errorf("в каталоге больше %d файлов и папок", testEntryLimit)
|
||||
}
|
||||
if size < 0 || size > testFileLimit-limits.bytes {
|
||||
return fmt.Errorf("данные превышают %d байт", testFileLimit)
|
||||
}
|
||||
limits.bytes += size
|
||||
return nil
|
||||
}
|
||||
|
||||
// RunTest запускает локальную копию файла с адресом цели как единственным аргументом.
|
||||
func RunTest(ctx context.Context, file, host string, timeout time.Duration, flagPattern string, includeDir bool) (TestResult, error) {
|
||||
workDir, err := os.Getwd()
|
||||
if err != nil {
|
||||
return TestResult{}, fmt.Errorf("не удалось получить рабочий каталог: %w", err)
|
||||
}
|
||||
return runTestAt(ctx, workDir, file, host, timeout, flagPattern, includeDir)
|
||||
}
|
||||
|
||||
func runTestAt(ctx context.Context, workDir, file, host string, timeout time.Duration, flagPattern string, includeDir bool) (result TestResult, returnErr error) {
|
||||
if host == "" {
|
||||
return result, errors.New("адрес цели не может быть пустым")
|
||||
}
|
||||
if timeout <= 0 {
|
||||
return result, errors.New("тайм-аут должен быть больше нуля")
|
||||
}
|
||||
if flagPattern == "" {
|
||||
return result, errors.New("параметр --flag-regexp обязателен")
|
||||
}
|
||||
flagRegexp, err := regexp.Compile(flagPattern)
|
||||
if err != nil {
|
||||
return result, fmt.Errorf("неверное выражение --flag-regexp: %w", err)
|
||||
}
|
||||
|
||||
absoluteFile, err := filepath.Abs(file)
|
||||
if err != nil {
|
||||
return result, fmt.Errorf("не удалось получить путь к файлу: %w", err)
|
||||
}
|
||||
info, err := os.Lstat(absoluteFile)
|
||||
if err != nil {
|
||||
return result, fmt.Errorf("не удалось проверить файл %s: %w", absoluteFile, err)
|
||||
}
|
||||
if !info.Mode().IsRegular() {
|
||||
return result, errors.New("файл задания должен быть обычным файлом, не ссылкой или каталогом")
|
||||
}
|
||||
resolvedFile, err := filepath.EvalSymlinks(absoluteFile)
|
||||
if err != nil || resolvedFile != absoluteFile {
|
||||
return result, errors.New("путь к файлу задания не должен проходить через символическую ссылку")
|
||||
}
|
||||
|
||||
absoluteWorkDir, err := filepath.Abs(workDir)
|
||||
if err != nil {
|
||||
return result, fmt.Errorf("не удалось определить рабочий каталог: %w", err)
|
||||
}
|
||||
workingCopy, err := os.MkdirTemp(absoluteWorkDir, testDirPrefix)
|
||||
if err != nil {
|
||||
return result, fmt.Errorf("не удалось создать рабочую копию в %s: %w", absoluteWorkDir, err)
|
||||
}
|
||||
defer func() {
|
||||
if err := os.RemoveAll(workingCopy); err != nil {
|
||||
returnErr = errors.Join(returnErr, fmt.Errorf("не удалось удалить временную копию: %w", err))
|
||||
}
|
||||
}()
|
||||
|
||||
entrypoint, err := copyTestInput(absoluteFile, workingCopy, includeDir)
|
||||
if err != nil {
|
||||
return result, fmt.Errorf("не удалось подготовить копию задания: %w", err)
|
||||
}
|
||||
|
||||
stdout := &limitedBuffer{limit: testOutputLimit}
|
||||
stderr := &limitedBuffer{limit: testOutputLimit}
|
||||
job := queue.NewJob(
|
||||
models.NewExploit("local-test", 1, models.ExploitTypeRecurrent),
|
||||
models.NewTarget("local-test", host),
|
||||
entrypoint,
|
||||
workingCopy,
|
||||
nil,
|
||||
timeout,
|
||||
nil,
|
||||
)
|
||||
runCtx, cancel := context.WithTimeout(ctx, timeout)
|
||||
defer cancel()
|
||||
cmd := job.Command(runCtx)
|
||||
cmd.Stdout = stdout
|
||||
cmd.Stderr = stderr
|
||||
|
||||
runErr := cmd.Run()
|
||||
result.Stdout = stdout.Bytes()
|
||||
result.Stderr = stderr.Bytes()
|
||||
result.StdoutTruncated = stdout.truncated
|
||||
result.StderrTruncated = stderr.truncated
|
||||
switch {
|
||||
case runErr == nil:
|
||||
result.ExitCode = 0
|
||||
case errors.Is(runCtx.Err(), context.DeadlineExceeded):
|
||||
result.ExitCode = testTimeoutCode
|
||||
result.TimedOut = true
|
||||
case errors.Is(runCtx.Err(), context.Canceled):
|
||||
result.ExitCode = testCancelCode
|
||||
default:
|
||||
var exitErr *exec.ExitError
|
||||
if !errors.As(runErr, &exitErr) {
|
||||
return result, fmt.Errorf("не удалось запустить задание: %w", runErr)
|
||||
}
|
||||
result.ExitCode = exitErr.ExitCode()
|
||||
if result.ExitCode < 0 {
|
||||
if status, ok := exitErr.Sys().(syscall.WaitStatus); ok && status.Signaled() {
|
||||
result.ExitCode = 128 + int(status.Signal())
|
||||
} else {
|
||||
result.ExitCode = 1
|
||||
}
|
||||
}
|
||||
}
|
||||
result.Flags = findFlags(flagRegexp, result.Stdout, result.Stderr)
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func copyTestInput(sourceFile, destination string, includeDir bool) (string, error) {
|
||||
sourceDir := filepath.Dir(sourceFile)
|
||||
entrypoint, err := filepath.Rel(sourceDir, sourceFile)
|
||||
if err != nil || !filepath.IsLocal(entrypoint) {
|
||||
return "", errors.New("небезопасный путь к точке входа")
|
||||
}
|
||||
limits := ©Limits{}
|
||||
if !includeDir {
|
||||
destinationFile := filepath.Join(destination, entrypoint)
|
||||
if err := copyRegularFile(sourceFile, destinationFile, true, limits); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return destinationFile, nil
|
||||
}
|
||||
|
||||
rootInfo, err := os.Lstat(sourceDir)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("не удалось проверить каталог задания: %w", err)
|
||||
}
|
||||
if !rootInfo.IsDir() {
|
||||
return "", errors.New("родительская папка задания не является обычным каталогом")
|
||||
}
|
||||
resolvedRoot, err := filepath.EvalSymlinks(sourceDir)
|
||||
if err != nil || resolvedRoot != sourceDir {
|
||||
return "", errors.New("путь к папке задания не должен проходить через символическую ссылку")
|
||||
}
|
||||
|
||||
destinationAbs, err := filepath.Abs(destination)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("не удалось определить путь рабочей копии: %w", err)
|
||||
}
|
||||
foundEntrypoint := false
|
||||
err = filepath.WalkDir(sourceDir, func(path string, entry os.DirEntry, walkErr error) error {
|
||||
if walkErr != nil {
|
||||
return walkErr
|
||||
}
|
||||
if filepath.Clean(path) == filepath.Clean(destinationAbs) {
|
||||
return filepath.SkipDir
|
||||
}
|
||||
if filepath.Clean(path) == filepath.Clean(sourceDir) {
|
||||
return nil
|
||||
}
|
||||
|
||||
info, err := os.Lstat(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if info.Mode()&os.ModeSymlink != 0 {
|
||||
return fmt.Errorf("символическая ссылка запрещена: %s", entry.Name())
|
||||
}
|
||||
relative, err := filepath.Rel(sourceDir, path)
|
||||
if err != nil || !filepath.IsLocal(relative) {
|
||||
return fmt.Errorf("небезопасный путь в папке задания: %s", entry.Name())
|
||||
}
|
||||
target := filepath.Join(destinationAbs, relative)
|
||||
if info.IsDir() {
|
||||
if err := limits.add(0); err != nil {
|
||||
return err
|
||||
}
|
||||
return os.Mkdir(target, 0700)
|
||||
}
|
||||
if !info.Mode().IsRegular() {
|
||||
return fmt.Errorf("специальный файл запрещен: %s", entry.Name())
|
||||
}
|
||||
if err := copyRegularFile(path, target, filepath.Clean(path) == filepath.Clean(sourceFile), limits); err != nil {
|
||||
return err
|
||||
}
|
||||
if filepath.Clean(path) == filepath.Clean(sourceFile) {
|
||||
foundEntrypoint = true
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("обход каталога задания: %w", err)
|
||||
}
|
||||
if !foundEntrypoint {
|
||||
return "", errors.New("точка входа не найдена в родительской папке")
|
||||
}
|
||||
return filepath.Join(destinationAbs, entrypoint), nil
|
||||
}
|
||||
|
||||
func copyRegularFile(source, destination string, entrypoint bool, limits *copyLimits) error {
|
||||
info, err := os.Lstat(source)
|
||||
if err != nil {
|
||||
return fmt.Errorf("не удалось проверить файл %s: %w", filepath.Base(source), err)
|
||||
}
|
||||
if !info.Mode().IsRegular() {
|
||||
return fmt.Errorf("обнаружен не обычный файл: %s", filepath.Base(source))
|
||||
}
|
||||
if err := limits.add(info.Size()); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Dir(destination), 0700); err != nil {
|
||||
return fmt.Errorf("не удалось создать папку рабочей копии: %w", err)
|
||||
}
|
||||
|
||||
src, err := os.Open(source)
|
||||
if err != nil {
|
||||
return fmt.Errorf("не удалось открыть файл %s: %w", filepath.Base(source), err)
|
||||
}
|
||||
srcInfo, err := src.Stat()
|
||||
if err != nil || !os.SameFile(info, srcInfo) || !srcInfo.Mode().IsRegular() {
|
||||
_ = src.Close()
|
||||
return fmt.Errorf("файл изменился при копировании: %s", filepath.Base(source))
|
||||
}
|
||||
dst, err := os.OpenFile(destination, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0600)
|
||||
if err != nil {
|
||||
_ = src.Close()
|
||||
return fmt.Errorf("не удалось создать файл рабочей копии: %w", err)
|
||||
}
|
||||
_, copyErr := io.CopyN(dst, src, info.Size())
|
||||
if copyErr == nil {
|
||||
var extra [1]byte
|
||||
if n, readErr := src.Read(extra[:]); n != 0 || !errors.Is(readErr, io.EOF) {
|
||||
if readErr != nil && !errors.Is(readErr, io.EOF) {
|
||||
copyErr = readErr
|
||||
} else {
|
||||
copyErr = errors.New("размер файла изменился при копировании")
|
||||
}
|
||||
}
|
||||
}
|
||||
closeSourceErr := src.Close()
|
||||
closeDestinationErr := dst.Close()
|
||||
if copyErr != nil || closeSourceErr != nil || closeDestinationErr != nil {
|
||||
_ = os.Remove(destination)
|
||||
return errors.Join(copyErr, closeSourceErr, closeDestinationErr)
|
||||
}
|
||||
mode := os.FileMode(0600)
|
||||
if entrypoint || info.Mode().Perm()&0100 != 0 {
|
||||
mode |= 0100
|
||||
}
|
||||
if err := os.Chmod(destination, mode); err != nil {
|
||||
_ = os.Remove(destination)
|
||||
return fmt.Errorf("не удалось подготовить права файла: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func findFlags(flagRegexp *regexp.Regexp, streams ...[]byte) []string {
|
||||
seen := make(map[string]struct{})
|
||||
var flags []string
|
||||
for _, stream := range streams {
|
||||
for _, match := range flagRegexp.FindAll(stream, -1) {
|
||||
flag := string(match)
|
||||
if flag == "" {
|
||||
continue
|
||||
}
|
||||
if _, exists := seen[flag]; exists {
|
||||
continue
|
||||
}
|
||||
seen[flag] = struct{}{}
|
||||
flags = append(flags, flag)
|
||||
}
|
||||
}
|
||||
return flags
|
||||
}
|
||||
|
||||
// WriteTo показывает оба потока отдельно, код завершения и уникальные совпадения.
|
||||
func (result TestResult) WriteTo(stdout, stderr io.Writer) error {
|
||||
if _, err := fmt.Fprintln(stdout, "stdout:"); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := writeOutput(stdout, result.Stdout, result.StdoutTruncated, "stdout"); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := fmt.Fprintln(stderr, "stderr:"); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := writeOutput(stderr, result.Stderr, result.StderrTruncated, "stderr"); err != nil {
|
||||
return err
|
||||
}
|
||||
if result.TimedOut {
|
||||
if _, err := fmt.Fprintln(stdout, "тайм-аут: истекло время ожидания"); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if _, err := fmt.Fprintf(stdout, "код выхода: %d\nфлаги:\n", result.ExitCode); err != nil {
|
||||
return err
|
||||
}
|
||||
for _, flag := range result.Flags {
|
||||
if _, err := fmt.Fprintf(stdout, " %s\n", flag); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func writeOutput(dst io.Writer, output []byte, truncated bool, stream string) error {
|
||||
if len(output) > 0 {
|
||||
if _, err := dst.Write(output); err != nil {
|
||||
return err
|
||||
}
|
||||
if output[len(output)-1] != '\n' {
|
||||
if _, err := fmt.Fprintln(dst); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
if truncated {
|
||||
_, err := fmt.Fprintf(dst, "[вывод %s обрезан после 1 МиБ]\n", stream)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,212 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"syscall"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestRunTestCapturesStreamsExitCodeFlagsAndFiltersSecrets(t *testing.T) {
|
||||
secrets := []string{"NEO_GRPC_AUTH_KEY", "NEO_WORKER_KEY", "NEO_KEY", "GRPC_AUTH_KEY", "FARM_PASSWORD", "NEO_FARM_PASSWORD"}
|
||||
for _, name := range secrets {
|
||||
t.Setenv(name, "test-secret-"+name)
|
||||
}
|
||||
work := t.TempDir()
|
||||
file := writeTestProgram(t, "#!/bin/sh\nprintf 'stdout: ABC123=\\n'\nprintf 'stderr: ABC123= DEF456=\\n' >&2\n"+
|
||||
"printf 'credentials=%s|%s|%s|%s|%s|%s\\n' \"${NEO_GRPC_AUTH_KEY-unset}\" \"${NEO_WORKER_KEY-unset}\" \"${NEO_KEY-unset}\" \"${GRPC_AUTH_KEY-unset}\" \"${FARM_PASSWORD-unset}\" \"${NEO_FARM_PASSWORD-unset}\" >&2\nexit 7\n")
|
||||
|
||||
result, err := runTestAt(context.Background(), work, file, "192.0.2.10", time.Second, `[A-Z0-9]{6}=`, false)
|
||||
if err != nil {
|
||||
t.Fatalf("ошибка локального запуска: %v", err)
|
||||
}
|
||||
if result.ExitCode != 7 {
|
||||
t.Fatalf("код выхода = %d, ожидался 7", result.ExitCode)
|
||||
}
|
||||
if got := string(result.Stdout); got != "stdout: ABC123=\n" {
|
||||
t.Fatalf("stdout = %q", got)
|
||||
}
|
||||
if got := string(result.Stderr); !strings.Contains(got, "stderr: ABC123= DEF456=") || !strings.Contains(got, "credentials=unset|unset|unset|unset|unset|unset") {
|
||||
t.Fatalf("stderr = %q", got)
|
||||
}
|
||||
for _, name := range secrets {
|
||||
if strings.Contains(string(result.Stderr), "test-secret-"+name) {
|
||||
t.Fatalf("секрет %s попал в окружение запускаемого задания", name)
|
||||
}
|
||||
}
|
||||
if got, want := strings.Join(result.Flags, ","), "ABC123=,DEF456="; got != want {
|
||||
t.Fatalf("флаги = %q, ожидались %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunTestCopiesSiblingFilesForWritesAndCleansUp(t *testing.T) {
|
||||
stage := t.TempDir()
|
||||
work := t.TempDir()
|
||||
file := filepath.Join(stage, "job.sh")
|
||||
if err := os.WriteFile(file, []byte("#!/bin/sh\nset -eu\ncat resource.txt\nprintf 'host=%s\\n' \"$1\"\nprintf 'created\\n' > result.txt\nprintf 'FLAG123=\\n'\n"), 0444); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
resource := filepath.Join(stage, "resource.txt")
|
||||
if err := os.WriteFile(resource, []byte("sibling resource\n"), 0444); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
result, err := runTestAt(context.Background(), work, file, "target.example", time.Second, `FLAG[0-9]+=`, true)
|
||||
if err != nil {
|
||||
t.Fatalf("ошибка запуска копии папки: %v", err)
|
||||
}
|
||||
if result.ExitCode != 0 {
|
||||
t.Fatalf("код выхода = %d, ожидался 0; stderr = %q", result.ExitCode, result.Stderr)
|
||||
}
|
||||
if got, want := string(result.Stdout), "sibling resource\nhost=target.example\nFLAG123=\n"; got != want {
|
||||
t.Fatalf("stdout = %q, ожидалось %q", got, want)
|
||||
}
|
||||
if got, want := strings.Join(result.Flags, ","), "FLAG123="; got != want {
|
||||
t.Fatalf("найденные флаги = %q, ожидался %q", got, want)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(stage, "result.txt")); !os.IsNotExist(err) {
|
||||
t.Fatalf("исходная папка изменена: stat result.txt = %v", err)
|
||||
}
|
||||
entries, err := os.ReadDir(work)
|
||||
if err != nil {
|
||||
t.Fatalf("не удалось проверить очистку рабочей папки: %v", err)
|
||||
}
|
||||
if len(entries) != 0 {
|
||||
t.Fatalf("временная копия осталась после запуска: %v", entries)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunTestTimeoutUses124(t *testing.T) {
|
||||
work := t.TempDir()
|
||||
file := writeTestProgram(t, "#!/bin/sh\nsleep 5 &\nwait\n")
|
||||
|
||||
started := time.Now()
|
||||
result, err := runTestAt(context.Background(), work, file, "target", 50*time.Millisecond, `FLAG[0-9]+=`, false)
|
||||
if err != nil {
|
||||
t.Fatalf("ошибка локального запуска: %v", err)
|
||||
}
|
||||
if result.ExitCode != testTimeoutCode || !result.TimedOut {
|
||||
t.Fatalf("результат {код:%d тайм-аут:%t}, ожидался тайм-аут 124", result.ExitCode, result.TimedOut)
|
||||
}
|
||||
if time.Since(started) > 2*time.Second {
|
||||
t.Fatal("дочерний процесс не остановился после тайм-аута")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunTestCapsEachOutputStream(t *testing.T) {
|
||||
work := t.TempDir()
|
||||
file := writeTestProgram(t, fmt.Sprintf("#!/bin/sh\nhead -c %d /dev/zero | tr '\\000' x\nhead -c %d /dev/zero | tr '\\000' y >&2\n", testOutputLimit+1, testOutputLimit+1))
|
||||
|
||||
result, err := runTestAt(context.Background(), work, file, "target", 5*time.Second, `FLAG[0-9]+=`, false)
|
||||
if err != nil {
|
||||
t.Fatalf("ошибка локального запуска: %v", err)
|
||||
}
|
||||
if len(result.Stdout) != testOutputLimit || len(result.Stderr) != testOutputLimit {
|
||||
t.Fatalf("длины вывода = (%d, %d), обрезан = (%t, %t), ожидалось по %d байт", len(result.Stdout), len(result.Stderr), result.StdoutTruncated, result.StderrTruncated, testOutputLimit)
|
||||
}
|
||||
if !result.StdoutTruncated || !result.StderrTruncated {
|
||||
t.Fatal("оба потока должны иметь отметку об обрезке")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunTestRejectsInvalidInputs(t *testing.T) {
|
||||
work := t.TempDir()
|
||||
file := writeTestProgram(t, "#!/bin/sh\nexit 0\n")
|
||||
tests := []struct {
|
||||
name string
|
||||
file string
|
||||
host string
|
||||
timeout time.Duration
|
||||
pattern string
|
||||
}{
|
||||
{name: "пустой адрес", file: file, timeout: time.Second, pattern: `FLAG[0-9]+=`},
|
||||
{name: "неположительный тайм-аут", file: file, host: "target", pattern: `FLAG[0-9]+=`},
|
||||
{name: "нет выражения флага", file: file, host: "target", timeout: time.Second},
|
||||
{name: "неверное выражение", file: file, host: "target", timeout: time.Second, pattern: "["},
|
||||
{name: "нет файла", file: filepath.Join(t.TempDir(), "missing"), host: "target", timeout: time.Second, pattern: `FLAG[0-9]+=`},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
if _, err := runTestAt(context.Background(), work, test.file, test.host, test.timeout, test.pattern, false); err == nil {
|
||||
t.Fatal("ошибка проверки входных данных отсутствует")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunTestRejectsSymlinksAndSpecialFiles(t *testing.T) {
|
||||
for _, kind := range []string{"символическая ссылка", "FIFO"} {
|
||||
t.Run(kind, func(t *testing.T) {
|
||||
stage := t.TempDir()
|
||||
work := t.TempDir()
|
||||
file := filepath.Join(stage, "job.sh")
|
||||
if err := os.WriteFile(file, []byte("#!/bin/sh\nexit 0\n"), 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
switch kind {
|
||||
case "символическая ссылка":
|
||||
if err := os.Symlink("job.sh", filepath.Join(stage, "linked.sh")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
case "FIFO":
|
||||
if err := syscall.Mkfifo(filepath.Join(stage, "pipe"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if _, err := runTestAt(context.Background(), work, file, "target", time.Second, `FLAG[0-9]+=`, true); err == nil {
|
||||
t.Fatal("опасный файл должен отклоняться")
|
||||
}
|
||||
entries, err := os.ReadDir(work)
|
||||
if err != nil {
|
||||
t.Fatalf("не удалось проверить очистку: %v", err)
|
||||
}
|
||||
if len(entries) != 0 {
|
||||
t.Fatalf("временная копия осталась после ошибки: %v", entries)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCopyLimitsBoundTotalBytesAndEntries(t *testing.T) {
|
||||
var limits copyLimits
|
||||
if err := limits.add(testFileLimit); err != nil {
|
||||
t.Fatalf("допустимый предел байтов отклонен: %v", err)
|
||||
}
|
||||
if err := limits.add(1); err == nil {
|
||||
t.Fatal("превышение предела байтов не обнаружено")
|
||||
}
|
||||
|
||||
limits = copyLimits{}
|
||||
for i := 0; i < testEntryLimit; i++ {
|
||||
if err := limits.add(0); err != nil {
|
||||
t.Fatalf("допустимое число записей отклонено: %v", err)
|
||||
}
|
||||
}
|
||||
if err := limits.add(0); err == nil {
|
||||
t.Fatal("превышение предела записей не обнаружено")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLimitedBufferKeepsDrainingAfterLimit(t *testing.T) {
|
||||
buffer := &limitedBuffer{limit: testOutputLimit}
|
||||
data := make([]byte, testOutputLimit+1)
|
||||
if n, err := buffer.Write(data); err != nil || n != len(data) {
|
||||
t.Fatalf("Write() = (%d, %v), ожидалось (%d, nil)", n, err, len(data))
|
||||
}
|
||||
if buffer.buf.Len() != testOutputLimit || !buffer.truncated {
|
||||
t.Fatalf("длина буфера = %d, обрезан = %t", buffer.buf.Len(), buffer.truncated)
|
||||
}
|
||||
}
|
||||
|
||||
func writeTestProgram(t *testing.T, content string) string {
|
||||
t.Helper()
|
||||
file := filepath.Join(t.TempDir(), "job.sh")
|
||||
if err := os.WriteFile(file, []byte(content), 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return file
|
||||
}
|
||||
Loaded 100 of 564 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user