diff --git a/.env.example b/.env.example
new file mode 100644
index 0000000..231f95a
--- /dev/null
+++ b/.env.example
@@ -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
diff --git a/.github/ISSUE_TEMPLATE/bug_report-RU.md b/.github/ISSUE_TEMPLATE/bug_report-RU.md
deleted file mode 100644
index 964d6cf..0000000
--- a/.github/ISSUE_TEMPLATE/bug_report-RU.md
+++ /dev/null
@@ -1,38 +0,0 @@
----
-name: Сообщение об ошибке (RU)
-about: Сообщить о воспроизводимой проблеме toolkit без приватных данных
-title: "[Bug] "
-labels: ""
-assignees: ""
----
-
-
-## Проверка безопасности
-
-[English](bug_report.md) | Русский
-
-Не публикуйте credentials, приватные адреса, профили оператора, настоящие flags, traffic, raw logs или конфиденциальные исходники. При проблеме безопасности прочитайте [SECURITY.md](../../SECURITY-RU.md) до отправки публичного сообщения.
-
-
-## Ожидаемое и фактическое поведение
-
-Опишите задуманный результат команды и то, что произошло вместо него. Статическая находка — сигнал для review, а не доказательство эксплуатируемости сервиса.
-
-
-## Воспроизведение
-
-Приведите минимальный синтетический пример, точную очищенную команду, exit code и ограниченный очищенный текст ошибки. Укажите, был ли это preview или явно применённое действие. Не запускайте destructive tests только ради воспроизведения issue.
-
-
-## Окружение
-
-- Commit/version DurkaHelper:
-- OS и архитектура:
-- Версии Python и ripgrep:
-- Только для deployment: версии Docker/Compose и архитектура image:
-- Последний известный рабочий commit, если известен:
-
-
-## Область и восстановление
-
-Что было затронуто? Сработал ли документированный ограниченный rollback? Укажите, относится ли проблема к native core, synthetic fixture или сопровождаемому deployment.
diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md
deleted file mode 100644
index 4c36dac..0000000
--- a/.github/ISSUE_TEMPLATE/bug_report.md
+++ /dev/null
@@ -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.
diff --git a/.github/ISSUE_TEMPLATE/false_positive-RU.md b/.github/ISSUE_TEMPLATE/false_positive-RU.md
deleted file mode 100644
index 681b87c..0000000
--- a/.github/ISSUE_TEMPLATE/false_positive-RU.md
+++ /dev/null
@@ -1,32 +0,0 @@
----
-name: Ложное срабатывание или пропуск сканера (RU)
-about: Улучшить детектор с помощью небольшого синтетического примера
-title: "[Scanner] RULE-ID: "
-labels: ""
-assignees: ""
----
-
-
-## Правило и окружение
-
-[English](false_positive.md) | Русский
-
-- Rule ID и commit/version сканера:
-- Версия language/runtime:
-- Detection engine, если известен:
-- Context schema и относящаяся к проблеме настройка приоритета без секретов, если есть:
-
-
-## Минимальный синтетический пример
-
-Приведите код, который можно публиковать. Удалите реальные credentials, identifiers, приватные адреса и чужие исходники. Не прикладывайте полный scan report или настоящий репозиторий, если достаточно небольшого примера.
-
-
-## Ожидаемый результат и обоснование
-
-Объясните, должно ли правило срабатывать на примере и почему. Добавьте противоположный безопасный или небезопасный пример и соответствующее документированное ограничение детектора. Для проблем aliasing или shadowing включите окружающие binding statements.
-
-
-## Воспроизведение и предлагаемое покрытие
-
-Укажите очищенную команду и наблюдаемые rule IDs/exit code. Предложите независимые positive и negative tests; не ограничивайтесь изменением regex. Проблемы безопасности в самом toolkit описываются согласно [SECURITY.md](../../SECURITY-RU.md).
diff --git a/.github/ISSUE_TEMPLATE/false_positive.md b/.github/ISSUE_TEMPLATE/false_positive.md
deleted file mode 100644
index dd09da5..0000000
--- a/.github/ISSUE_TEMPLATE/false_positive.md
+++ /dev/null
@@ -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).
diff --git a/.github/ISSUE_TEMPLATE/rule_request-RU.md b/.github/ISSUE_TEMPLATE/rule_request-RU.md
deleted file mode 100644
index 6c41df4..0000000
--- a/.github/ISSUE_TEMPLATE/rule_request-RU.md
+++ /dev/null
@@ -1,29 +0,0 @@
----
-name: Запрос нового правила обнаружения (RU)
-about: Предложить ограниченный сигнал для review с независимыми тестами
-title: "[Rule request] "
-labels: ""
-assignees: ""
----
-
-
-## Семейство, языки и существующее покрытие
-
-[English](rule_request.md) | Русский
-
-Укажите семейство безопасности, затронутые формы языка/API и подходящий CWE, если применимо. С какими существующими правилами есть пересечение? Предпочитайте расширение поддерживаемого детектора дублированию сигнала или увеличению рекламного счётчика правил.
-
-
-## Обнаруживаемая форма и ограничения
-
-Опишите точный локальный синтаксис, который можно обнаружить без исполнения кода, сетевого доступа или новых core dependencies. Отделяйте deployment risks от подтверждённых уязвимостей. Перечислите случаи, требующие ручного, межпроцедурного review или проверки бизнес-логики.
-
-
-## Независимые примеры
-
-Для каждой заявленной формы приведите как минимум два независимо написанных положительных и два безопасных/context-negative синтетических примера. Где применимо, включите comments, strings, одноимённые пользовательские функции, alias rebinding и более безопасные альтернативы.
-
-
-## Исправление и источники
-
-Объясните безопасное исправление с сохранением поведения service/checker и способ его проверки. Дайте ссылки на авторитетную документацию языка/API. Не отправляйте приватный игровой код, flags, secrets, logs или traffic. См. [участие в разработке](../../CONTRIBUTING-RU.md).
diff --git a/.github/ISSUE_TEMPLATE/rule_request.md b/.github/ISSUE_TEMPLATE/rule_request.md
deleted file mode 100644
index c431a40..0000000
--- a/.github/ISSUE_TEMPLATE/rule_request.md
+++ /dev/null
@@ -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).
diff --git a/.github/PULL_REQUEST_TEMPLATE-RU.md b/.github/PULL_REQUEST_TEMPLATE-RU.md
deleted file mode 100644
index 30cba27..0000000
--- a/.github/PULL_REQUEST_TEMPLATE-RU.md
+++ /dev/null
@@ -1,28 +0,0 @@
-
-## Результат и область изменений
-
-[English](PULL_REQUEST_TEMPLATE.md) | Русский
-
-Опишите видимый пользователю результат, сохранённую совместимость и явные ограничения. Ссылайтесь на issues, не копируя приватные данные оператора.
-
-
-## Проверки
-
-- [ ] Запущены targeted tests и полный локальный suite; указаны точные результаты/skips.
-- [ ] Сохранены поведение CLI `0/1/2`, read-only defaults и сопоставимость scope.
-- [ ] У новых и изменённых правил есть независимые positive/negative cases и честно описанные ограничения.
-- [ ] Проходят проверки счётчиков каталога, стабильных anchors, локальных ссылок, английского текста и парных русских переводов; команды и примеры остаются идентичными.
-- [ ] Не добавлены исполнение цели, скрытый сетевой доступ или раскрытие секретов.
-- [ ] Изменения требуют разрешения, проверяют ownership и имеют ограниченный rollback.
-- [ ] Offline packaging и publication checks охватывают изменённые материалы.
-- [ ] Закреплённые версии сторонних исходников и образов, происхождение и лицензии остаются явными.
-
-
-## Платформы и границы свидетельств
-
-Перечислите точные commits, platforms и выполненные tests. Невыполненные сценарии Mac, Docker Desktop, физических клиентов, непрерывного захвата и offline start отметьте NOT_RUN или BLOCKED. Не переносите на них выводы из синтетических Linux-проверок.
-
-
-## Релиз и безопасность
-
-Опишите требования migration/rollback, нерешённые условия релиза и действия оператора. Подтвердите отсутствие приватных endpoints, credentials, raw logs или PCAP в diff, предназначенной для публикации истории, screenshots, artifacts и обсуждении. Сообщение об уязвимости следует [SECURITY.md](../SECURITY-RU.md), а не публичной демонстрации эксплойта.
diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md
deleted file mode 100644
index b272950..0000000
--- a/.github/PULL_REQUEST_TEMPLATE.md
+++ /dev/null
@@ -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.
diff --git a/.github/workflows/macos-arm64.yml b/.github/workflows/macos-arm64.yml
deleted file mode 100644
index 5d4b20a..0000000
--- a/.github/workflows/macos-arm64.yml
+++ /dev/null
@@ -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"
diff --git a/.gitignore b/.gitignore
index ae17863..43fb6a2 100644
--- a/.gitignore
+++ b/.gitignore
@@ -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
diff --git a/CHANGELOG-RU.md b/CHANGELOG-RU.md
deleted file mode 100644
index 8cff94d..0000000
--- a/CHANGELOG-RU.md
+++ /dev/null
@@ -1,25 +0,0 @@
-# История изменений
-
-[English](CHANGELOG.md) | Русский
-
-
-
-## В разработке
-
-- Последовательные workflow администратора на двух языках: развёртывание, ручные патчи, исполнение Neo, отправка Farm и Packmate LIVE/FILE; единый выбор конфига и настоящие кнопки FILE UI.
-- SSH-развёртывание Linux LIVE с read-only doctor и отдельным офлайн-bundle AMD64; Python на целевой машине не требуется.
-- Чистые игровые данные из проверенных кешированных зависимостей без скачиваний/сборок; приватные вложения исключены из публикации исходников и core-архивов. Готовность release candidate и проверенный публичный доступ — разные условия.
-
-- Единая точка входа `durka.py` и один приватный конфиг для подготовки, запуска, статуса, остановки, сканирования и импорта закрытого PCAP.
-- Инструкции администратора и участника объясняют связку S4DFarm, Neo, Packmate и Defense-инструментов.
-- Офлайн-архивы core исключают runtime-данные и приватную конфигурацию оператора.
-- Сканер 1.8.0: 174 офлайн-правила для ревью, контекст инфраструктуры и сравнимые отчёты.
-- Расширены Flask config/routes/logging, Psycopg composition, PostgreSQL grants и JS driver/CORS/session; добавлено 156 независимых fixtures. Патчи остаются ручными.
-- Defense operations 2.2.0: baseline/drift, health checks, восстановление в staging и аудит deployment-политик.
-- Закреплённый deployment, нативные backup/recovery helpers и отдельный Linux LIVE-захват.
-- Английская документация и соседние русские переводы; 294 раздела по исправлению уязвимостей.
-
-
-## Политика релизов
-
-См. [версионирование](docs/development-RU.md#versioning). Core CI проверяет нативные инструменты, а не Docker Desktop, конкретный ноутбук или сеть соревнования.
diff --git a/CHANGELOG.md b/CHANGELOG.md
deleted file mode 100644
index 0c2c932..0000000
--- a/CHANGELOG.md
+++ /dev/null
@@ -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.
diff --git a/CONTRIBUTING-RU.md b/CONTRIBUTING-RU.md
deleted file mode 100644
index 827ee80..0000000
--- a/CONTRIBUTING-RU.md
+++ /dev/null
@@ -1,29 +0,0 @@
-
-# Участие в разработке
-
-[English](CONTRIBUTING.md) | Русский
-
-Начните с [разработки и покрытия правил](docs/development-RU.md). Изменения должны улучшать качество защитных сигналов или надёжность работы оператора, не исполняя сканируемый код и не ослабляя гарантии офлайн-работы и безопасности.
-
-1. Создайте отдельную ветку для конкретной задачи и сохраните посторонние изменения.
-2. Перед исправлением воспроизведите дефект на безвредных fixtures.
-3. Сохраняйте совместимость ядра со стандартной библиотекой Python 3.10+.
-4. Запустите полный набор unit tests и целевые проверки покрытия.
-5. Вместе с кодом обновляйте английскую документацию, парные переводы `-RU.md` и точные ограничения детекторов; сохраняйте команды, rule IDs и anchors.
-6. Проверьте [чеклист релиза и публикации](docs/release-checklist-RU.md).
-
-У каждой Markdown-страницы есть соседняя русская копия `-RU.md`. Английская версия остаётся основной; обе версии доступны офлайн. Сохраняйте переключатель языка, направляйте локальные ссылки перевода на русские страницы и обновляйте обе версии вместе. Команды и примеры кода должны оставаться идентичными.
-
-Не коммитьте реальные учётные данные, логи, захваты пакетов, профили оператора, адреса целей или пользовательские данные. Используйте минимальные синтетические примеры; никогда не указывайте действующую приватную цель в issue.
-
-
-## Правила и примеры
-
-Для каждого нового или существенно изменённого правила нужны как минимум два независимо написанных положительных и два безопасных/context-negative примера. Покройте все заявленные языковые формы, комментарии и строковые примеры, aliases/shadowing и безопасные альтернативы. Строки «до/после», скопированные только из метаданных правила, не являются независимым свидетельством.
-
-Сохраняйте существующие rule IDs и явные anchors каталога. Изменённая семантика должна входить в scope отчёта, чтобы несовместимые сканирования нельзя было сравнить с ложным результатом «чисто». Описывайте, какие выводы правило сделать не может.
-
-
-## Review и релизы
-
-Записывайте точные закреплённые версии исходников и образов, а также платформы, на которых выполнялись проверки. Не приравнивайте CI к приёмке на целевом компьютере, Docker Desktop, физических клиентах, захвату трафика или офлайн-стеку. Для чувствительных сообщений следуйте [политике безопасности](SECURITY-RU.md) и сохраняйте указание авторства upstream.
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
deleted file mode 100644
index b115002..0000000
--- a/CONTRIBUTING.md
+++ /dev/null
@@ -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.
diff --git a/LICENSE b/LICENSE
index 5d74879..3b80646 100644
--- a/LICENSE
+++ b/LICENSE
@@ -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
diff --git a/README-RU.md b/README-RU.md
deleted file mode 100644
index 946ff1b..0000000
--- a/README-RU.md
+++ /dev/null
@@ -1,100 +0,0 @@
-
-# DurkaHelper
-
-[English](README.md) | Русский
-
-Офлайн-инструменты Defense для Attack/Defense CTF: разбор исходников, исследование трафика, проверка патчей и запуск общих командных инструментов из одного репозитория.
-
-
-## Что за что отвечает
-
-| Инструмент | Для чего нужен |
-|---|---|
-| **Сканер DurkaHelper** | Найти подозрительный код/конфигурацию в **локальной копии исходников** и открыть инструкцию исправления. Удалённые хосты не сканирует, патчи не применяет. |
-| **Packmate** | Смотреть запросы/ответы и искать по трафику. На Docker Desktop — закрытые PCAP; LIVE — на разрешённом Linux-узле, который видит нужный трафик. |
-| **S4DFarm** | Собирать флаги, показывать их статус и отправлять в систему соревнования. |
-| **Neo** | Распределять командные скрипты между исполнителями и целями; передавать найденные флаги в S4DFarm. |
-
-Защищаемые сервисы остаются на Vulnbox. Проверенные патчи применяйте там обычным способом развёртывания сервиса. Ферма обслуживает флаги, а не распространение патчей.
-
-
-## Быстрый старт
-
-Для разбора исходников достаточно Python 3.10+; устанавливать пакеты через pip не нужно:
-
-```bash
-git clone https://github.com/Nyarlad/DurkaHelper.git
-cd DurkaHelper
-python3 durka.py scan /path/to/service --patches
-```
-
-Код завершения 1 означает находки для проверки. Начните с одного сервиса и [базы исправлений](docs/vulnerabilities/README-RU.md). Находка — повод проверить код, а не доказанная уязвимость.
-
-Чтобы поднять общие инструменты, запустите Docker Desktop на macOS или Docker Engine с Compose на Linux:
-
-```bash
-python3 durka.py init
-```
-
-Заполните `local/durka.json`: LAN-адрес для доступа команды, адреса команд/сервисов, формат флага и настройки отправки соревнования. Пароли и ключ Neo генерируются автоматически. Файл приватный; `local/` исключён из Git.
-
-Для участников и native workers Neo нужен реальный Ethernet IPv4. Loopback подходит для демо на одном ноутбуке со встроенным worker.
-
-```bash
-python3 durka.py setup
-python3 durka.py up
-python3 durka.py status
-```
-
-`setup` скачивает закреплённые исходники/образы и собирает стек; выполните его до отключения Интернета. `up` поднимает ферму, координатор Neo и Packmate. Исполнение скриптов и отправка флагов включаются отдельно, когда всё готово:
-
-```bash
-python3 durka.py worker
-python3 durka.py submit
-```
-
-Перед отправкой прочитайте [инструкцию администратора](docs/MACOS_FULL_DEPLOYMENT_AND_TESTING-RU.md). Поддерживаемый адаптер — `ructf_http`; для другого протокола нужен совместимый адаптер. На Apple Silicon Packmate работает через эмуляцию amd64: прогоните стек на своём ноутбуке.
-
-
-## Во время игры
-
-1. Админ поднимает инструменты и передаёт LAN-адреса и учётные данные.
-2. Защитники копируют исходники сервиса, сканируют их и изучают подозрительный трафик.
-3. Применяют небольшой патч на Vulnbox, проверяют сервис/checker и повторяют скан.
-4. Авторы скриптов тестируют работу, загружают её в Neo и смотрят флаги в S4DFarm.
-5. Админ следит за доступностью, диском и backup. Для завершения — `python3 durka.py down`.
-
-Основные маршруты: [workflow администратора 01–05](docs/ADMIN_WORKFLOWS-RU.md), [инструкция участника](docs/participant-guide-RU.md), [памятка админа для печати](docs/TEAM_LAN_ADMIN_CHEATSHEET-RU.md). Справочники: [индекс документации](docs/README-RU.md).
-
-
-## Найти, исправить и проверить
-
-**294 раздела, 174 правила сканера.** Это число рецептов проверки и сигналов, а не отдельных доказанных эксплойтов.
-
-| Язык / уровень | Разделов |
-|---|---:|
-| [Python](docs/vulnerabilities/python-RU.md) | 40 |
-| [JavaScript / TypeScript](docs/vulnerabilities/javascript-RU.md) | 28 |
-| [PHP](docs/vulnerabilities/php-RU.md) | 23 |
-| [Go](docs/vulnerabilities/go-RU.md) | 19 |
-| [Java](docs/vulnerabilities/java-RU.md) | 18 |
-| [C# / .NET](docs/vulnerabilities/csharp-RU.md) | 20 |
-| [C / C++](docs/vulnerabilities/c-cpp-RU.md) | 28 |
-| [Ruby / Rails](docs/vulnerabilities/ruby-RU.md) | 18 |
-| [Rust](docs/vulnerabilities/rust-RU.md) | 18 |
-| [SQL / базы данных](docs/vulnerabilities/sql-RU.md) | 18 |
-| [Конфигурация / границы доверия](docs/vulnerabilities/configuration-RU.md) | 64 |
-
-
-## Разработка
-
-Тесты и synthetic-стенды нужны разработчикам; перед каждым игровым действием полный suite запускать не требуется.
-
-```bash
-python3 -m unittest discover -s tests
-python3 scripts/scanner_coverage.py --check
-```
-
-[Вклад в проект](CONTRIBUTING-RU.md) · [Безопасность](SECURITY-RU.md) · [Изменения](CHANGELOG-RU.md) · [Возможности](docs/CAPABILITY_INVENTORY-RU.md)
-
-Работайте только с разрешёнными системами. Учётные данные, исходники, флаги и PCAP держите приватно. DurkaHelper распространяется по [MIT](LICENSE), внешние инструменты — по [своим лицензиям](THIRD_PARTY_NOTICES-RU.md).
diff --git a/README.md b/README.md
index fcafe7a..7f66eac 100644
--- a/README.md
+++ b/README.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).
diff --git a/SECURITY-RU.md b/SECURITY-RU.md
deleted file mode 100644
index 102bcee..0000000
--- a/SECURITY-RU.md
+++ /dev/null
@@ -1,24 +0,0 @@
-
-# Политика безопасности
-
-[English](SECURITY.md) | Русский
-
-Используйте DurkaHelper только для разрешённого защитного review и инфраструктуры соревнований. Считайте деревья исходников, конфигурацию и отчёты недоверенными и чувствительными входными данными. Ядро не исполняет сканируемые исходники, не применяет патчи автоматически и не запускает эксплуатацию уязвимостей.
-
-
-## Как сообщить о проблеме безопасности
-
-**Не публикуйте** учётные данные, приватные адреса, реальные захваты трафика или неочищенный эксплойт против настоящего сервиса в публичном issue.
-
-Проверенный приватный канал сообщений — **условие публикации**. Прежде чем открыть репозиторий, сопровождающий должен включить и проверить GitHub private vulnerability reporting либо описать здесь другой согласованный приватный канал. Этот репозиторий не утверждает, что приватные сообщения уже включены, и не указывает непроверенный email.
-
-Если на странице Security в GitHub есть **Report a vulnerability**, перед отправкой убедитесь, что кнопка открывает приватную форму. Иначе запросите приватный контакт через публичный issue без содержательных подробностей; не включайте чувствительные данные до подтверждения канала.
-
-Укажите затронутый commit, платформу, минимальное синтетическое воспроизведение, ожидаемое и наблюдаемое поведение, а также последствия. Удалите секреты из имён файлов, вывода и вложений.
-
-
-## Поддерживаемая граница безопасности
-
-Поддерживается только текущая сопровождаемая ревизия; перенос исправлений на старые закреплённые версии toolchain не обещается. У внешних интеграций сохраняются собственные upstream-политики и лицензии. Закрепление версии повышает воспроизводимость, но не обеспечивает постоянное устранение уязвимостей.
-
-Особенно важно сообщать об исполнении исходников, раскрытии секретов, path traversal, обходе защиты от symlink/race, небезопасном восстановлении или перезаписи, обходе сравнения scope, непреднамеренном создании Docker-ресурсов и false negatives проверки публикации. Чистый статический scan или поиск секретов не доказывает безопасность.
diff --git a/SECURITY.md b/SECURITY.md
deleted file mode 100644
index 338de03..0000000
--- a/SECURITY.md
+++ /dev/null
@@ -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.
diff --git a/THIRD_PARTY_NOTICES-RU.md b/THIRD_PARTY_NOTICES-RU.md
deleted file mode 100644
index 016984b..0000000
--- a/THIRD_PARTY_NOTICES-RU.md
+++ /dev/null
@@ -1,18 +0,0 @@
-
-# Уведомления о сторонних компонентах
-
-[English](THIRD_PARTY_NOTICES.md) | Русский
-
-Собственный код DurkaHelper распространяется по [лицензии MIT](LICENSE). У сторонних проектов, скопированных примеров и ссылочных материалов сохраняются собственные условия и указание авторства.
-
-| Компонент | Происхождение |
-|---|---|
-| S4DFarm | [Закреплённые исходники](https://github.com/C4T-BuT-S4D/S4DFarm/tree/3b8b057c95e0467c6afb3a47648e8b6befd1a815) |
-| Neo | [Закреплённые исходники сервера](https://github.com/C4T-BuT-S4D/neo/tree/2f2a4eb63f9715155844284f253ba786d330c9ae), релиз v2.4.2, записанный в lock |
-| Packmate | [Закреплённые исходники](https://gitlab.com/packmate/Packmate/-/tree/938031f1dedfbedabef5b049368ed5b6ba6a900a); overlay развёртывания не меняет upstream-код |
-| Зависимости контейнеров и runtime | Точные идентификаторы в [toolchain lock](config/toolchain.lock.json) и [integration image lock](config/integration-images.lock.json) |
-| Разборы A/D и документация API | Ссылки на источники и авторство сохранены в [каталоге](docs/vulnerabilities/README-RU.md) |
-
-Наличие checkout исходников, контейнерного образа или кешированного пакета не означает автоматического разрешения на распространение. Перед публикацией внешнего офлайн-toolchain составьте реестр лицензий, уведомлений, обязательств по предоставлению исходников и разрешений на распространение бинарников. Лицензирование и установка Docker Desktop зависят от применимых к оператору условий; DurkaHelper не распространяет Docker Desktop.
-
-Инструмент артефактов записывает заявленные метаданные происхождения и лицензий, но не выносит юридическое заключение. До завершения review внешние кеши и экспорты образов остаются приватными артефактами оператора. При обезличивании операторских данных не удаляйте указание авторства.
diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md
deleted file mode 100644
index cc29ffa..0000000
--- a/THIRD_PARTY_NOTICES.md
+++ /dev/null
@@ -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.
diff --git a/components/farm/README.md b/components/farm/README.md
new file mode 100644
index 0000000..46cbdda
--- /dev/null
+++ b/components/farm/README.md
@@ -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`.
diff --git a/components/farm/compose.yaml b/components/farm/compose.yaml
new file mode 100644
index 0000000..46a7f5d
--- /dev/null
+++ b/components/farm/compose.yaml
@@ -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
diff --git a/components/farm/server/.dockerignore b/components/farm/server/.dockerignore
new file mode 100644
index 0000000..8b0206d
--- /dev/null
+++ b/components/farm/server/.dockerignore
@@ -0,0 +1,8 @@
+**/__pycache__/
+**/*.py[cod]
+**/.pytest_cache/
+**/.venv/
+front/node_modules/
+front/dist/
+.git/
+*.log
diff --git a/components/farm/server/app/__init__.py b/components/farm/server/app/__init__.py
new file mode 100644
index 0000000..0350663
--- /dev/null
+++ b/components/farm/server/app/__init__.py
@@ -0,0 +1,3 @@
+from app_flask import app
+
+__all__ = ('app',)
diff --git a/components/farm/server/app/api.py b/components/farm/server/app/api.py
new file mode 100644
index 0000000..a86d4a2
--- /dev/null
+++ b/components/farm/server/app/api.py
@@ -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()
+ ])
diff --git a/components/farm/server/app/app_flask.py b/components/farm/server/app/app_flask.py
new file mode 100644
index 0000000..c1d92a6
--- /dev/null
+++ b/components/farm/server/app/app_flask.py
@@ -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')
diff --git a/components/farm/server/app/auth.py b/components/farm/server/app/auth.py
new file mode 100644
index 0000000..73d3604
--- /dev/null
+++ b/components/farm/server/app/auth.py
@@ -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
diff --git a/components/farm/server/app/config.py b/components/farm/server/app/config.py
new file mode 100644
index 0000000..f341897
--- /dev/null
+++ b/components/farm/server/app/config.py
@@ -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()
diff --git a/components/farm/server/app/constants.py b/components/farm/server/app/constants.py
new file mode 100644
index 0000000..2b809f0
--- /dev/null
+++ b/components/farm/server/app/constants.py
@@ -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')
diff --git a/components/farm/server/app/database.py b/components/farm/server/app/database.py
new file mode 100644
index 0000000..dcc07e4
--- /dev/null
+++ b/components/farm/server/app/database.py
@@ -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)
diff --git a/components/farm/server/app/factory.py b/components/farm/server/app/factory.py
new file mode 100644
index 0000000..df69c2a
--- /dev/null
+++ b/components/farm/server/app/factory.py
@@ -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
diff --git a/components/farm/server/app/log.py b/components/farm/server/app/log.py
new file mode 100644
index 0000000..a75562c
--- /dev/null
+++ b/components/farm/server/app/log.py
@@ -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
diff --git a/components/farm/server/app/models.py b/components/farm/server/app/models.py
new file mode 100644
index 0000000..70ab204
--- /dev/null
+++ b/components/farm/server/app/models.py
@@ -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
diff --git a/components/farm/server/app/protocols/__init__.py b/components/farm/server/app/protocols/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/components/farm/server/app/protocols/ctfcup_tcp.py b/components/farm/server/app/protocols/ctfcup_tcp.py
new file mode 100644
index 0000000..5044748
--- /dev/null
+++ b/components/farm/server/app/protocols/ctfcup_tcp.py
@@ -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()
diff --git a/components/farm/server/app/protocols/faust.py b/components/farm/server/app/protocols/faust.py
new file mode 100644
index 0000000..96f279f
--- /dev/null
+++ b/components/farm/server/app/protocols/faust.py
@@ -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()
diff --git a/components/farm/server/app/protocols/ructf_http.py b/components/farm/server/app/protocols/ructf_http.py
new file mode 100644
index 0000000..e2b1362
--- /dev/null
+++ b/components/farm/server/app/protocols/ructf_http.py
@@ -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)
diff --git a/components/farm/server/app/protocols/ructf_tcp.py b/components/farm/server/app/protocols/ructf_tcp.py
new file mode 100644
index 0000000..7e35d92
--- /dev/null
+++ b/components/farm/server/app/protocols/ructf_tcp.py
@@ -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()
diff --git a/components/farm/server/app/protocols/volgactf.py b/components/farm/server/app/protocols/volgactf.py
new file mode 100644
index 0000000..481280d
--- /dev/null
+++ b/components/farm/server/app/protocols/volgactf.py
@@ -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
diff --git a/components/farm/server/app/resources/schema.sql b/components/farm/server/app/resources/schema.sql
new file mode 100644
index 0000000..1228218
--- /dev/null
+++ b/components/farm/server/app/resources/schema.sql
@@ -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);
diff --git a/components/farm/server/app/sender.py b/components/farm/server/app/sender.py
new file mode 100644
index 0000000..bf06532
--- /dev/null
+++ b/components/farm/server/app/sender.py
@@ -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()
diff --git a/components/farm/server/app/tasks.py b/components/farm/server/app/tasks.py
new file mode 100644
index 0000000..1082619
--- /dev/null
+++ b/components/farm/server/app/tasks.py
@@ -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()
diff --git a/components/farm/server/app/utils.py b/components/farm/server/app/utils.py
new file mode 100644
index 0000000..d18c435
--- /dev/null
+++ b/components/farm/server/app/utils.py
@@ -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]
diff --git a/components/farm/server/app/validators/volgactf.py b/components/farm/server/app/validators/volgactf.py
new file mode 100644
index 0000000..824fe1d
--- /dev/null
+++ b/components/farm/server/app/validators/volgactf.py
@@ -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
diff --git a/components/farm/server/docker/front/Dockerfile b/components/farm/server/docker/front/Dockerfile
new file mode 100644
index 0000000..cdc2628
--- /dev/null
+++ b/components/farm/server/docker/front/Dockerfile
@@ -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
diff --git a/components/farm/server/docker/front/app.conf b/components/farm/server/docker/front/app.conf
new file mode 100644
index 0000000..2ab09b3
--- /dev/null
+++ b/components/farm/server/docker/front/app.conf
@@ -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;
+ }
+}
diff --git a/components/farm/server/docker/server/Dockerfile b/components/farm/server/docker/server/Dockerfile
new file mode 100644
index 0000000..0c45014
--- /dev/null
+++ b/components/farm/server/docker/server/Dockerfile
@@ -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"]
diff --git a/components/farm/server/front/.prettierrc.json b/components/farm/server/front/.prettierrc.json
new file mode 100644
index 0000000..66e2335
--- /dev/null
+++ b/components/farm/server/front/.prettierrc.json
@@ -0,0 +1,8 @@
+{
+ "$schema": "https://json.schemastore.org/prettierrc",
+ "semi": false,
+ "tabWidth": 2,
+ "singleQuote": true,
+ "printWidth": 100,
+ "trailingComma": "none"
+}
\ No newline at end of file
diff --git a/components/farm/server/front/eslint.config.cjs b/components/farm/server/front/eslint.config.cjs
new file mode 100644
index 0000000..7f22509
--- /dev/null
+++ b/components/farm/server/front/eslint.config.cjs
@@ -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
+]
diff --git a/components/farm/server/front/index.html b/components/farm/server/front/index.html
new file mode 100644
index 0000000..a28ccac
--- /dev/null
+++ b/components/farm/server/front/index.html
@@ -0,0 +1,18 @@
+
+
+
+
+
+
+
+
+
+
+
+ wahrwelt / Farm
+
+
+
+
+
+
diff --git a/components/farm/server/front/package.json b/components/farm/server/front/package.json
new file mode 100644
index 0000000..6e528eb
--- /dev/null
+++ b/components/farm/server/front/package.json
@@ -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"
+ }
+}
diff --git a/components/farm/server/front/pnpm-workspace.yaml b/components/farm/server/front/pnpm-workspace.yaml
new file mode 100644
index 0000000..4a17e8d
--- /dev/null
+++ b/components/farm/server/front/pnpm-workspace.yaml
@@ -0,0 +1,3 @@
+# Скрипт сборки watcher не запускается: он нужен только для режима наблюдения Sass.
+allowBuilds:
+ '@parcel/watcher': false
diff --git a/components/farm/server/front/public/logo.jpg b/components/farm/server/front/public/logo.jpg
new file mode 100644
index 0000000..2bf7f7d
Binary files /dev/null and b/components/farm/server/front/public/logo.jpg differ
diff --git a/components/farm/server/front/public/manifest.webmanifest b/components/farm/server/front/public/manifest.webmanifest
new file mode 100644
index 0000000..2ee696e
--- /dev/null
+++ b/components/farm/server/front/public/manifest.webmanifest
@@ -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"
+ }
+ ]
+}
diff --git a/components/farm/server/front/src/App.vue b/components/farm/server/front/src/App.vue
new file mode 100644
index 0000000..16c680e
--- /dev/null
+++ b/components/farm/server/front/src/App.vue
@@ -0,0 +1,37 @@
+
+
+
+
+
+
+
+
+
diff --git a/components/farm/server/front/src/components/FlagsForm.vue b/components/farm/server/front/src/components/FlagsForm.vue
new file mode 100644
index 0000000..19845b6
--- /dev/null
+++ b/components/farm/server/front/src/components/FlagsForm.vue
@@ -0,0 +1,186 @@
+
+
+
+ Фильтр флагов
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/components/farm/server/front/src/components/FlagsSubmit.vue b/components/farm/server/front/src/components/FlagsSubmit.vue
new file mode 100644
index 0000000..7e98ef5
--- /dev/null
+++ b/components/farm/server/front/src/components/FlagsSubmit.vue
@@ -0,0 +1,61 @@
+
+
+
+ Ручная отправка
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/components/farm/server/front/src/components/FlagsTable.vue b/components/farm/server/front/src/components/FlagsTable.vue
new file mode 100644
index 0000000..2fd40fe
--- /dev/null
+++ b/components/farm/server/front/src/components/FlagsTable.vue
@@ -0,0 +1,155 @@
+
+
+
+ Всего флагов: {{ scope.pagination.rowsNumber }}
+
+
+
+
+
+
+
+ {{ message }}
+
+
+
+
+ {{ props.col.label }}
+
+
+
+
+
+ {{ props.value }}
+
+
+
+
+
+
+
+
+
+
+
diff --git a/components/farm/server/front/src/components/LoginForm.vue b/components/farm/server/front/src/components/LoginForm.vue
new file mode 100644
index 0000000..b9823a3
--- /dev/null
+++ b/components/farm/server/front/src/components/LoginForm.vue
@@ -0,0 +1,47 @@
+
+
+
+ Введите пароль сервера
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/components/farm/server/front/src/components/PaginationCustom.vue b/components/farm/server/front/src/components/PaginationCustom.vue
new file mode 100644
index 0000000..cc47067
--- /dev/null
+++ b/components/farm/server/front/src/components/PaginationCustom.vue
@@ -0,0 +1,83 @@
+
+
+
+
+
+
+
diff --git a/components/farm/server/front/src/components/TeamsTable.vue b/components/farm/server/front/src/components/TeamsTable.vue
new file mode 100644
index 0000000..d748bba
--- /dev/null
+++ b/components/farm/server/front/src/components/TeamsTable.vue
@@ -0,0 +1,64 @@
+
+
+
+
+
+ {{ message }}
+
+
+
+
+ {{ props.col.label }}
+
+
+
+
+
+ {{ props.value }}
+
+
+
+
+
+
+
+
+
+
diff --git a/components/farm/server/front/src/config/index.js b/components/farm/server/front/src/config/index.js
new file mode 100644
index 0000000..3f796ec
--- /dev/null
+++ b/components/farm/server/front/src/config/index.js
@@ -0,0 +1,6 @@
+const serverUrl = window.location.origin;
+const apiUrl = `${serverUrl}/api`;
+
+const flagsPerPage = 30;
+
+export { apiUrl, flagsPerPage, serverUrl };
diff --git a/components/farm/server/front/src/layouts/BaseLayout.vue b/components/farm/server/front/src/layouts/BaseLayout.vue
new file mode 100644
index 0000000..9dddd74
--- /dev/null
+++ b/components/farm/server/front/src/layouts/BaseLayout.vue
@@ -0,0 +1,41 @@
+
+
+
+
+
+ wahrwelt / Farm
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/components/farm/server/front/src/main.js b/components/farm/server/front/src/main.js
new file mode 100644
index 0000000..2ba6e5d
--- /dev/null
+++ b/components/farm/server/front/src/main.js
@@ -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");
diff --git a/components/farm/server/front/src/models/flag.js b/components/farm/server/front/src/models/flag.js
new file mode 100644
index 0000000..e5334f6
--- /dev/null
+++ b/components/farm/server/front/src/models/flag.js
@@ -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;
diff --git a/components/farm/server/front/src/models/team.js b/components/farm/server/front/src/models/team.js
new file mode 100644
index 0000000..95fd29a
--- /dev/null
+++ b/components/farm/server/front/src/models/team.js
@@ -0,0 +1,8 @@
+class Team {
+ constructor({ name, address }) {
+ this.name = name;
+ this.address = address;
+ }
+}
+
+export default Team;
diff --git a/components/farm/server/front/src/quasar-user-options.js b/components/farm/server/front/src/quasar-user-options.js
new file mode 100644
index 0000000..3fc5be8
--- /dev/null
+++ b/components/farm/server/front/src/quasar-user-options.js
@@ -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 },
+};
diff --git a/components/farm/server/front/src/router/index.js b/components/farm/server/front/src/router/index.js
new file mode 100644
index 0000000..f9a112e
--- /dev/null
+++ b/components/farm/server/front/src/router/index.js
@@ -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;
diff --git a/components/farm/server/front/src/services/api.js b/components/farm/server/front/src/services/api.js
new file mode 100644
index 0000000..9afa616
--- /dev/null
+++ b/components/farm/server/front/src/services/api.js
@@ -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;
diff --git a/components/farm/server/front/src/services/interceptors.js b/components/farm/server/front/src/services/interceptors.js
new file mode 100644
index 0000000..897fb0a
--- /dev/null
+++ b/components/farm/server/front/src/services/interceptors.js
@@ -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 };
diff --git a/components/farm/server/front/src/store/index.js b/components/farm/server/front/src/store/index.js
new file mode 100644
index 0000000..243839f
--- /dev/null
+++ b/components/farm/server/front/src/store/index.js
@@ -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: {},
+});
diff --git a/components/farm/server/front/src/styles/quasar.scss b/components/farm/server/front/src/styles/quasar.scss
new file mode 100644
index 0000000..eeba173
--- /dev/null
+++ b/components/farm/server/front/src/styles/quasar.scss
@@ -0,0 +1 @@
+@use "./quasar.variables.scss" as *;
diff --git a/components/farm/server/front/src/styles/quasar.variables.scss b/components/farm/server/front/src/styles/quasar.variables.scss
new file mode 100644
index 0000000..0555848
--- /dev/null
+++ b/components/farm/server/front/src/styles/quasar.variables.scss
@@ -0,0 +1,12 @@
+// Цвета Quasar можно настроить в соответствии с оформлением интерфейса.
+
+$primary: #027BE3;
+$secondary: #26A69A;
+$accent: #9C27B0;
+
+$dark: #1D1D1D;
+
+$positive: #21BA45;
+$negative: #C10015;
+$info: #31CCEC;
+$warning: #F2C037;
diff --git a/components/farm/server/front/src/views/Flags.vue b/components/farm/server/front/src/views/Flags.vue
new file mode 100644
index 0000000..37ca1b7
--- /dev/null
+++ b/components/farm/server/front/src/views/Flags.vue
@@ -0,0 +1,30 @@
+
+
+
+
+
+
+
+
+
diff --git a/components/farm/server/front/src/views/Login.vue b/components/farm/server/front/src/views/Login.vue
new file mode 100644
index 0000000..326aef8
--- /dev/null
+++ b/components/farm/server/front/src/views/Login.vue
@@ -0,0 +1,16 @@
+
+
+
+
+
+
+
+
diff --git a/components/farm/server/front/src/views/Teams.vue b/components/farm/server/front/src/views/Teams.vue
new file mode 100644
index 0000000..1a13dfa
--- /dev/null
+++ b/components/farm/server/front/src/views/Teams.vue
@@ -0,0 +1,21 @@
+
+
+
+
+
+
+
+
diff --git a/components/farm/server/front/vite.config.js b/components/farm/server/front/vite.config.js
new file mode 100644
index 0000000..2c3f8e8
--- /dev/null
+++ b/components/farm/server/front/vite.config.js
@@ -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
+ }
+ }
+ }
+ }
+})
diff --git a/components/farm/server/requirements.txt b/components/farm/server/requirements.txt
new file mode 100644
index 0000000..4febb86
--- /dev/null
+++ b/components/farm/server/requirements.txt
@@ -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
diff --git a/components/farm/server/tests/test_service.py b/components/farm/server/tests/test_service.py
new file mode 100644
index 0000000..19cbd87
--- /dev/null
+++ b/components/farm/server/tests/test_service.py
@@ -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()
diff --git a/components/neo/.dockerignore b/components/neo/.dockerignore
new file mode 100644
index 0000000..7c60afb
--- /dev/null
+++ b/components/neo/.dockerignore
@@ -0,0 +1,10 @@
+.git
+.env
+.env.*
+data
+dist
+volumes
+*.db
+**/__pycache__
+**/*.py[cod]
+**/tests
diff --git a/components/neo/Dockerfile b/components/neo/Dockerfile
new file mode 100644
index 0000000..36eb14e
--- /dev/null
+++ b/components/neo/Dockerfile
@@ -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"]
diff --git a/components/neo/README.md b/components/neo/README.md
new file mode 100644
index 0000000..3ff9b5b
--- /dev/null
+++ b/components/neo/README.md
@@ -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` с нижней
+границей версии. Если скриптам нужны дополнительные библиотеки, добавьте их туда.
diff --git a/components/neo/client_env/Dockerfile b/components/neo/client_env/Dockerfile
new file mode 100644
index 0000000..afcdc08
--- /dev/null
+++ b/components/neo/client_env/Dockerfile
@@ -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"]
diff --git a/components/neo/client_env/entrypoint.sh b/components/neo/client_env/entrypoint.sh
new file mode 100644
index 0000000..36c7fdc
--- /dev/null
+++ b/components/neo/client_env/entrypoint.sh
@@ -0,0 +1,9 @@
+#!/bin/sh
+set -eu
+
+if [ -z "${NEO_CLIENT_ID:-}" ]; then
+ NEO_CLIENT_ID="$(hostname)"
+ export NEO_CLIENT_ID
+fi
+
+exec "$@"
diff --git a/components/neo/client_env/requirements.txt b/components/neo/client_env/requirements.txt
new file mode 100644
index 0000000..02fa2ea
--- /dev/null
+++ b/components/neo/client_env/requirements.txt
@@ -0,0 +1 @@
+requests>=2.34.2
diff --git a/components/neo/cmd/client/cli/add.go b/components/neo/cmd/client/cli/add.go
new file mode 100644
index 0000000..4f1c2b5
--- /dev/null
+++ b/components/neo/cmd/client/cli/add.go
@@ -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
+}
diff --git a/components/neo/cmd/client/cli/add_test.go b/components/neo/cmd/client/cli/add_test.go
new file mode 100644
index 0000000..c59f731
--- /dev/null
+++ b/components/neo/cmd/client/cli/add_test.go
@@ -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)
+}
diff --git a/components/neo/cmd/client/cli/broadcast.go b/components/neo/cmd/client/cli/broadcast.go
new file mode 100644
index 0000000..647b273
--- /dev/null
+++ b/components/neo/cmd/client/cli/broadcast.go
@@ -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
+}
diff --git a/components/neo/cmd/client/cli/cli.go b/components/neo/cmd/client/cli/cli.go
new file mode 100644
index 0000000..170bd5a
--- /dev/null
+++ b/components/neo/cmd/client/cli/cli.go
@@ -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("команда не реализована")
+}
diff --git a/components/neo/cmd/client/cli/dry_run.go b/components/neo/cmd/client/cli/dry_run.go
new file mode 100644
index 0000000..cb6df61
--- /dev/null
+++ b/components/neo/cmd/client/cli/dry_run.go
@@ -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
+}
diff --git a/components/neo/cmd/client/cli/info.go b/components/neo/cmd/client/cli/info.go
new file mode 100644
index 0000000..576510b
--- /dev/null
+++ b/components/neo/cmd/client/cli/info.go
@@ -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()
+}
diff --git a/components/neo/cmd/client/cli/info_test.go b/components/neo/cmd/client/cli/info_test.go
new file mode 100644
index 0000000..c0a73a4
--- /dev/null
+++ b/components/neo/cmd/client/cli/info_test.go
@@ -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")
+}
diff --git a/components/neo/cmd/client/cli/run.go b/components/neo/cmd/client/cli/run.go
new file mode 100644
index 0000000..1f58b57
--- /dev/null
+++ b/components/neo/cmd/client/cli/run.go
@@ -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
+}
diff --git a/components/neo/cmd/client/cli/set_disabled.go b/components/neo/cmd/client/cli/set_disabled.go
new file mode 100644
index 0000000..0d7cf72
--- /dev/null
+++ b/components/neo/cmd/client/cli/set_disabled.go
@@ -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
+}
diff --git a/components/neo/cmd/client/cli/single.go b/components/neo/cmd/client/cli/single.go
new file mode 100644
index 0000000..a981733
--- /dev/null
+++ b/components/neo/cmd/client/cli/single.go
@@ -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
+}
diff --git a/components/neo/cmd/client/cli/tail.go b/components/neo/cmd/client/cli/tail.go
new file mode 100644
index 0000000..9f0877f
--- /dev/null
+++ b/components/neo/cmd/client/cli/tail.go
@@ -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
+}
diff --git a/components/neo/cmd/client/cli/test.go b/components/neo/cmd/client/cli/test.go
new file mode 100644
index 0000000..aa8aa16
--- /dev/null
+++ b/components/neo/cmd/client/cli/test.go
@@ -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
+}
diff --git a/components/neo/cmd/client/cli/test_test.go b/components/neo/cmd/client/cli/test_test.go
new file mode 100644
index 0000000..b2bf5fe
--- /dev/null
+++ b/components/neo/cmd/client/cli/test_test.go
@@ -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
+}
diff --git a/components/neo/cmd/client/cli/update.go b/components/neo/cmd/client/cli/update.go
new file mode 100644
index 0000000..2d9c16f
--- /dev/null
+++ b/components/neo/cmd/client/cli/update.go
@@ -0,0 +1,109 @@
+package cli
+
+import (
+ "context"
+ "fmt"
+ "time"
+
+ "github.com/samber/lo"
+ "github.com/sirupsen/logrus"
+ "github.com/spf13/cobra"
+ "google.golang.org/protobuf/types/known/durationpb"
+
+ "github.com/c4t-but-s4d/neo/v2/internal/client"
+
+ epb "github.com/c4t-but-s4d/neo/v2/proto/go/exploits"
+)
+
+type updateCLI struct {
+ *baseCLI
+ exploitID string
+ runEvery *time.Duration
+ timeout *time.Duration
+ endless *bool
+ disabled *bool
+}
+
+func NewUpdateCLI(cmd *cobra.Command, args []string, cfg *client.Config) NeoCLI {
+ c := &updateCLI{
+ baseCLI: &baseCLI{cfg: cfg},
+ exploitID: args[0],
+ }
+
+ if cmd.Flags().Changed("interval") {
+ runEvery, err := cmd.Flags().GetDuration("interval")
+ if err != nil {
+ logrus.Fatalf("Не удалось прочитать интервал запуска: %v", err)
+ }
+ c.runEvery = &runEvery
+ }
+ if cmd.Flags().Changed("timeout") {
+ timeout, err := cmd.Flags().GetDuration("timeout")
+ if err != nil {
+ logrus.Fatalf("Не удалось прочитать тайм-аут запуска: %v", err)
+ }
+ c.timeout = &timeout
+ }
+ if cmd.Flags().Changed("endless") {
+ endless, err := cmd.Flags().GetBool("endless")
+ if err != nil {
+ logrus.Fatalf("Не удалось прочитать параметр бесконечного режима: %v", err)
+ }
+ c.endless = &endless
+ }
+ if cmd.Flags().Changed("disabled") {
+ disabled, err := cmd.Flags().GetBool("disabled")
+ if err != nil {
+ logrus.Fatalf("Не удалось прочитать параметр отключения: %v", err)
+ }
+ c.disabled = &disabled
+ }
+
+ return c
+}
+
+func (uc *updateCLI) Run(ctx context.Context) error {
+ logrus.Infof("Изменение настроек эксплойта с id = %s", uc.exploitID)
+
+ c, err := uc.client()
+ if err != nil {
+ return fmt.Errorf("не удалось создать клиент: %w", err)
+ }
+
+ resp, err := c.Exploit(ctx, uc.exploitID)
+ if err != nil {
+ logrus.Fatalf("Эксплойт с id = %s не найден", uc.exploitID)
+ }
+ es := resp.GetState()
+ escfg := es.GetConfig()
+
+ runEvery := escfg.GetRunEvery()
+ if uc.runEvery != nil {
+ runEvery = durationpb.New(*uc.runEvery)
+ }
+ timeout := escfg.GetTimeout()
+ if uc.timeout != nil {
+ timeout = durationpb.New(*uc.timeout)
+ }
+
+ newState := &epb.ExploitState{
+ ExploitId: es.GetExploitId(),
+ File: es.GetFile(),
+ Version: es.GetVersion(),
+ Config: &epb.ExploitConfiguration{
+ Entrypoint: escfg.GetEntrypoint(),
+ IsArchive: escfg.GetIsArchive(),
+ RunEvery: runEvery,
+ Timeout: timeout,
+ Endless: lo.FromPtrOr(uc.endless, escfg.GetEndless()),
+ Disabled: lo.FromPtrOr(uc.disabled, escfg.GetDisabled()),
+ },
+ }
+
+ ns, err := c.UpdateExploit(ctx, newState)
+ if err != nil {
+ return fmt.Errorf("не удалось обновить эксплойт: %w", err)
+ }
+ logrus.Infof("Настройки эксплойта %s обновлены", ns.GetExploitId())
+ return nil
+}
diff --git a/components/neo/cmd/client/cli/utils.go b/components/neo/cmd/client/cli/utils.go
new file mode 100644
index 0000000..7e5a4f9
--- /dev/null
+++ b/components/neo/cmd/client/cli/utils.go
@@ -0,0 +1,23 @@
+package cli
+
+import (
+ "bytes"
+
+ "github.com/samber/lo"
+
+ "github.com/c4t-but-s4d/neo/v2/proto/go/exploits"
+)
+
+func isBinary(data []byte) bool {
+ return len(data) >= 4 && bytes.Equal(data[:4], []byte("\x7fELF"))
+}
+
+func getExploitFromState(state *exploits.ServerState, exploitID string) *exploits.ExploitState {
+ exp, ok := lo.Find(state.Exploits, func(s *exploits.ExploitState) bool {
+ return s.ExploitId == exploitID
+ })
+ if !ok {
+ return nil
+ }
+ return exp
+}
diff --git a/components/neo/cmd/client/cmd/add.go b/components/neo/cmd/client/cmd/add.go
new file mode 100644
index 0000000..1cdef20
--- /dev/null
+++ b/components/neo/cmd/client/cmd/add.go
@@ -0,0 +1,39 @@
+package cmd
+
+import (
+ "time"
+
+ "github.com/sirupsen/logrus"
+ "github.com/spf13/cobra"
+
+ "github.com/c4t-but-s4d/neo/v2/cmd/client/cli"
+ "github.com/c4t-but-s4d/neo/v2/internal/client"
+)
+
+// addCmd описывает команду добавления эксплойта.
+var addCmd = &cobra.Command{
+ Use: "add",
+ Short: "Добавить эксплойт",
+ Args: cobra.ExactArgs(1),
+ Run: func(cmd *cobra.Command, args []string) {
+ cfg := client.MustUnmarshalConfig()
+ cli := cli.NewAdd(cmd, args, cfg)
+ ctx := cmd.Context()
+ if err := cli.Run(ctx); err != nil {
+ logrus.Fatalf("Не удалось добавить эксплойт: %v", err)
+ }
+ logrus.Debug("Добавление завершено")
+ },
+}
+
+func init() {
+ rootCmd.AddCommand(addCmd)
+
+ addCmd.PersistentFlags().String("id", "", "имя эксплойта")
+ addCmd.PersistentFlags().BoolP("dir", "d", false, "добавить эксплойт как каталог")
+ addCmd.PersistentFlags().DurationP("interval", "i", time.Second*30, "интервал запуска")
+ addCmd.PersistentFlags().DurationP("timeout", "t", time.Second*30, "тайм-аут одного запуска")
+ addCmd.PersistentFlags().BoolP("endless", "e", false, "запускать эксплойт в бесконечном режиме")
+ addCmd.PersistentFlags().Bool("disabled", false, "добавить эксплойт в отключенном состоянии")
+ addCmd.PersistentFlags().Bool("yes", false, "подтвердить добавление новой версии без вопроса")
+}
diff --git a/components/neo/cmd/client/cmd/add_test.go b/components/neo/cmd/client/cmd/add_test.go
new file mode 100644
index 0000000..310b925
--- /dev/null
+++ b/components/neo/cmd/client/cmd/add_test.go
@@ -0,0 +1,13 @@
+package cmd
+
+import "testing"
+
+func TestAddCommandHasOptionalYesFlag(t *testing.T) {
+ flag := addCmd.PersistentFlags().Lookup("yes")
+ if flag == nil {
+ t.Fatal("параметр --yes отсутствует")
+ }
+ if flag.Value.Type() != "bool" || flag.DefValue != "false" {
+ t.Fatalf("параметр --yes имеет тип %q и значение по умолчанию %q", flag.Value.Type(), flag.DefValue)
+ }
+}
diff --git a/components/neo/cmd/client/cmd/broadcast.go b/components/neo/cmd/client/cmd/broadcast.go
new file mode 100644
index 0000000..977d92b
--- /dev/null
+++ b/components/neo/cmd/client/cmd/broadcast.go
@@ -0,0 +1,29 @@
+package cmd
+
+import (
+ "github.com/sirupsen/logrus"
+ "github.com/spf13/cobra"
+
+ "github.com/c4t-but-s4d/neo/v2/cmd/client/cli"
+ "github.com/c4t-but-s4d/neo/v2/internal/client"
+)
+
+// broadcastCmd описывает команду отправки команды worker-клиентам.
+var broadcastCmd = &cobra.Command{
+ Use: "broadcast",
+ Short: "Выполнить команду на всех подключенных клиентах",
+ Run: func(cmd *cobra.Command, args []string) {
+ cfg := client.MustUnmarshalConfig()
+ cli := cli.NewBroadcast(cmd, args, cfg)
+ ctx := cmd.Context()
+ if err := cli.Run(ctx); err != nil {
+ logrus.Fatalf("Не удалось разослать команду: %v", err)
+ }
+ logrus.Debug("Рассылка завершена")
+ },
+}
+
+func init() {
+ rootCmd.AddCommand(broadcastCmd)
+ broadcastCmd.Flags().StringP("command", "r", "", "команда для запуска")
+}
diff --git a/components/neo/cmd/client/cmd/disable.go b/components/neo/cmd/client/cmd/disable.go
new file mode 100644
index 0000000..59e21c1
--- /dev/null
+++ b/components/neo/cmd/client/cmd/disable.go
@@ -0,0 +1,29 @@
+package cmd
+
+import (
+ "github.com/sirupsen/logrus"
+ "github.com/spf13/cobra"
+
+ "github.com/c4t-but-s4d/neo/v2/cmd/client/cli"
+ "github.com/c4t-but-s4d/neo/v2/internal/client"
+)
+
+// disableCmd описывает команду отключения эксплойта.
+var disableCmd = &cobra.Command{
+ Use: "disable",
+ Short: "Отключить эксплойт по идентификатору",
+ Args: cobra.ExactArgs(1),
+ Run: func(cmd *cobra.Command, args []string) {
+ cfg := client.MustUnmarshalConfig()
+ cli := cli.NewSetDisabled(cmd, args, cfg, true)
+ ctx := cmd.Context()
+ if err := cli.Run(ctx); err != nil {
+ logrus.Fatalf("Не удалось отключить эксплойт: %v", err)
+ }
+ logrus.Debug("Отключение завершено")
+ },
+}
+
+func init() {
+ rootCmd.AddCommand(disableCmd)
+}
diff --git a/components/neo/cmd/client/cmd/dry_run.go b/components/neo/cmd/client/cmd/dry_run.go
new file mode 100644
index 0000000..a71778b
--- /dev/null
+++ b/components/neo/cmd/client/cmd/dry_run.go
@@ -0,0 +1,34 @@
+package cmd
+
+import (
+ "runtime"
+
+ "github.com/sirupsen/logrus"
+ "github.com/spf13/cobra"
+
+ "github.com/c4t-but-s4d/neo/v2/cmd/client/cli"
+ "github.com/c4t-but-s4d/neo/v2/internal/client"
+)
+
+// dryRunCmd описывает локальный запуск эксплойта.
+var dryRunCmd = &cobra.Command{
+ Use: "dry-run",
+ Short: "Запустить эксплойт локально",
+ Args: cobra.ExactArgs(1),
+ Run: func(cmd *cobra.Command, args []string) {
+ cfg := client.MustUnmarshalConfig()
+ cli := cli.NewDryRun(cmd, args, cfg)
+ ctx := cmd.Context()
+ if err := cli.Run(ctx); err != nil {
+ logrus.Fatalf("Ошибка: %v", err)
+ }
+ logrus.Debug("Локальный запуск завершен")
+ },
+}
+
+func init() {
+ rootCmd.AddCommand(dryRunCmd)
+ dryRunCmd.Flags().StringP("team_ip", "p", "", "IP команды для запуска")
+ dryRunCmd.Flags().StringP("team_id", "d", "", "идентификатор команды для запуска")
+ dryRunCmd.Flags().IntP("jobs", "j", runtime.NumCPU()*cli.JobsPerCPU, "число параллельных заданий")
+}
diff --git a/components/neo/cmd/client/cmd/enable.go b/components/neo/cmd/client/cmd/enable.go
new file mode 100644
index 0000000..71ae8af
--- /dev/null
+++ b/components/neo/cmd/client/cmd/enable.go
@@ -0,0 +1,29 @@
+package cmd
+
+import (
+ "github.com/sirupsen/logrus"
+ "github.com/spf13/cobra"
+
+ "github.com/c4t-but-s4d/neo/v2/cmd/client/cli"
+ "github.com/c4t-but-s4d/neo/v2/internal/client"
+)
+
+// enableCmd описывает команду включения эксплойта.
+var enableCmd = &cobra.Command{
+ Use: "enable",
+ Short: "Включить эксплойт по идентификатору",
+ Args: cobra.ExactArgs(1),
+ Run: func(cmd *cobra.Command, args []string) {
+ cfg := client.MustUnmarshalConfig()
+ cli := cli.NewSetDisabled(cmd, args, cfg, false)
+ ctx := cmd.Context()
+ if err := cli.Run(ctx); err != nil {
+ logrus.Fatalf("Не удалось включить эксплойт: %v", err)
+ }
+ logrus.Debug("Включение завершено")
+ },
+}
+
+func init() {
+ rootCmd.AddCommand(enableCmd)
+}
diff --git a/components/neo/cmd/client/cmd/info.go b/components/neo/cmd/client/cmd/info.go
new file mode 100644
index 0000000..bff861e
--- /dev/null
+++ b/components/neo/cmd/client/cmd/info.go
@@ -0,0 +1,28 @@
+package cmd
+
+import (
+ "github.com/sirupsen/logrus"
+ "github.com/spf13/cobra"
+
+ "github.com/c4t-but-s4d/neo/v2/cmd/client/cli"
+ "github.com/c4t-but-s4d/neo/v2/internal/client"
+)
+
+// infoCmd описывает команду просмотра текущего состояния.
+var infoCmd = &cobra.Command{
+ Use: "info",
+ Short: "Показать текущее состояние",
+ Run: func(cmd *cobra.Command, args []string) {
+ cfg := client.MustUnmarshalConfig()
+ cli := cli.NewInfo(cmd, args, cfg)
+ ctx := cmd.Context()
+ if err := cli.Run(ctx); err != nil {
+ logrus.Fatalf("Ошибка: %v", err)
+ }
+ logrus.Debug("Просмотр состояния завершен")
+ },
+}
+
+func init() {
+ rootCmd.AddCommand(infoCmd)
+}
diff --git a/components/neo/cmd/client/cmd/root.go b/components/neo/cmd/client/cmd/root.go
new file mode 100644
index 0000000..1c4f81f
--- /dev/null
+++ b/components/neo/cmd/client/cmd/root.go
@@ -0,0 +1,72 @@
+package cmd
+
+import (
+ "context"
+ "fmt"
+ "os"
+ "strings"
+
+ "github.com/sirupsen/logrus"
+ "github.com/spf13/cobra"
+ "github.com/spf13/viper"
+
+ "github.com/c4t-but-s4d/neo/v2/internal/logger"
+)
+
+// rootCmd описывает основную команду клиента.
+var rootCmd = &cobra.Command{
+ Use: "client",
+ Short: "Клиент Neo",
+}
+
+// Execute запускает выбранную команду клиента.
+func Execute(ctx context.Context) {
+ if err := rootCmd.ExecuteContext(ctx); err != nil {
+ fmt.Println(err)
+ os.Exit(1)
+ }
+}
+
+func init() {
+ cobra.OnInitialize(initConfig)
+ rootCmd.PersistentFlags().StringP("config", "c", "client_config.yml", "путь к файлу конфигурации")
+ rootCmd.PersistentFlags().BoolP("verbose", "v", false, "включить подробные журналы")
+ rootCmd.PersistentFlags().String("host", "127.0.0.1:5005", "адрес сервера")
+ rootCmd.PersistentFlags().String("metrics_host", "", "адрес Pushgateway для метрик")
+
+ mustBindPersistent(rootCmd, "config")
+ mustBindPersistent(rootCmd, "host")
+ mustBindPersistent(rootCmd, "verbose")
+ mustBindPersistent(rootCmd, "metrics_host")
+}
+
+func mustBindPersistent(c *cobra.Command, flag string) {
+ if err := viper.BindPFlag(flag, c.PersistentFlags().Lookup(flag)); err != nil {
+ logrus.Fatalf("Не удалось связать параметр %s: %v", flag, err)
+ }
+}
+
+// initConfig загружает файл конфигурации и переменные окружения.
+func initConfig() {
+ logger.Init()
+
+ viper.SetConfigFile(viper.GetString("config"))
+ viper.SetConfigType("yaml")
+
+ viper.SetEnvPrefix("NEO")
+ viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
+ viper.AutomaticEnv() // считывать совпадающие переменные окружения
+ viper.SetDefault("allow_broadcast_commands", false)
+
+ // Если файл конфигурации найден, загрузить его.
+ if err := viper.ReadInConfig(); err == nil {
+ logrus.Info("Используется файл конфигурации:", viper.ConfigFileUsed())
+ }
+
+ if viper.GetBool("verbose") {
+ logrus.SetLevel(logrus.DebugLevel)
+ } else {
+ logrus.SetLevel(logrus.InfoLevel)
+ }
+
+}
diff --git a/components/neo/cmd/client/cmd/run.go b/components/neo/cmd/client/cmd/run.go
new file mode 100644
index 0000000..bd4b187
--- /dev/null
+++ b/components/neo/cmd/client/cmd/run.go
@@ -0,0 +1,38 @@
+package cmd
+
+import (
+ "runtime"
+
+ "github.com/sirupsen/logrus"
+ "github.com/spf13/cobra"
+
+ "github.com/c4t-but-s4d/neo/v2/cmd/client/cli"
+ "github.com/c4t-but-s4d/neo/v2/internal/client"
+)
+
+// runCmd описывает команду запуска клиента.
+var runCmd = &cobra.Command{
+ Use: "run",
+ Short: "Запустить клиент Neo",
+ Run: func(cmd *cobra.Command, args []string) {
+ cfg := client.MustUnmarshalConfig()
+ cli := cli.NewRun(cmd, args, cfg)
+ ctx := cmd.Context()
+ if err := cli.Run(ctx); err != nil {
+ logrus.Fatalf("Ошибка: %v", err)
+ }
+ logrus.Debug("Работа завершена")
+ },
+}
+
+func init() {
+ rootCmd.AddCommand(runCmd)
+ runCmd.Flags().IntP("jobs", "j", runtime.NumCPU()*cli.JobsPerCPU, "число обычных заданий")
+ runCmd.Flags().IntP("endless-jobs", "e", 0, "число заданий бесконечного режима; 0 отключает этот режим")
+ runCmd.Flags().Float64(
+ "timeout-autoscale-target",
+ 1.5,
+ "предельная загрузка обычных заданий; масштабирование тайм-аутов удерживает ее ниже этого значения."+
+ " Значение 0 отключает масштабирование",
+ )
+}
diff --git a/components/neo/cmd/client/cmd/single.go b/components/neo/cmd/client/cmd/single.go
new file mode 100644
index 0000000..6af1838
--- /dev/null
+++ b/components/neo/cmd/client/cmd/single.go
@@ -0,0 +1,29 @@
+package cmd
+
+import (
+ "github.com/sirupsen/logrus"
+ "github.com/spf13/cobra"
+
+ "github.com/c4t-but-s4d/neo/v2/cmd/client/cli"
+ "github.com/c4t-but-s4d/neo/v2/internal/client"
+)
+
+// singleRunCmd описывает разовый запуск эксплойта.
+var singleRunCmd = &cobra.Command{
+ Use: "single",
+ Short: "Немедленно запустить эксплойт один раз для всех команд",
+ Args: cobra.ExactArgs(1),
+ Run: func(cmd *cobra.Command, args []string) {
+ cfg := client.MustUnmarshalConfig()
+ cli := cli.NewSingleRun(cmd, args, cfg)
+ ctx := cmd.Context()
+ if err := cli.Run(ctx); err != nil {
+ logrus.Fatalf("Не удалось выполнить разовый запуск: %v", err)
+ }
+ logrus.Debug("Разовый запуск завершен")
+ },
+}
+
+func init() {
+ rootCmd.AddCommand(singleRunCmd)
+}
diff --git a/components/neo/cmd/client/cmd/tail.go b/components/neo/cmd/client/cmd/tail.go
new file mode 100644
index 0000000..10c4909
--- /dev/null
+++ b/components/neo/cmd/client/cmd/tail.go
@@ -0,0 +1,32 @@
+package cmd
+
+import (
+ "github.com/sirupsen/logrus"
+ "github.com/spf13/cobra"
+
+ "github.com/c4t-but-s4d/neo/v2/cmd/client/cli"
+ "github.com/c4t-but-s4d/neo/v2/internal/client"
+)
+
+// tailCmd описывает команду просмотра журналов эксплойта.
+var tailCmd = &cobra.Command{
+ Use: "tail",
+ Short: "Показать журнал эксплойта",
+ Args: cobra.ExactArgs(1),
+ Run: func(cmd *cobra.Command, args []string) {
+ cfg := client.MustUnmarshalConfig()
+ cli := cli.NewTail(cmd, args, cfg)
+ ctx := cmd.Context()
+ if err := cli.Run(ctx); err != nil {
+ logrus.Fatalf("Не удалось показать журнал: %v", err)
+ }
+ logrus.Debug("Просмотр журнала завершен")
+ },
+}
+
+func init() {
+ rootCmd.AddCommand(tailCmd)
+
+ tailCmd.PersistentFlags().Int64("version", 0, "версия эксплойта")
+ tailCmd.PersistentFlags().IntP("count", "n", -1, "число строк; -1 означает показать все")
+}
diff --git a/components/neo/cmd/client/cmd/test.go b/components/neo/cmd/client/cmd/test.go
new file mode 100644
index 0000000..5710a61
--- /dev/null
+++ b/components/neo/cmd/client/cmd/test.go
@@ -0,0 +1,68 @@
+package cmd
+
+import (
+ "fmt"
+ "os"
+ "time"
+
+ "github.com/spf13/cobra"
+
+ "github.com/c4t-but-s4d/neo/v2/cmd/client/cli"
+)
+
+var testCmd = &cobra.Command{
+ Use: "test FILE HOST",
+ Short: "Локально запустить файл для одной цели",
+ Long: "Запускает локальный файл без подключения к Neo или Farm и показывает вывод, код завершения и совпадения с заданным выражением.",
+ Args: func(cmd *cobra.Command, args []string) error {
+ if len(args) != 2 {
+ return fmt.Errorf("ожидаются ровно два аргумента: файл задания и адрес цели")
+ }
+ return nil
+ },
+ Run: func(cmd *cobra.Command, args []string) {
+ runTestCommand(cmd, args, os.Exit)
+ },
+}
+
+func runTestCommand(cmd *cobra.Command, args []string, exit func(int)) {
+ timeout, err := cmd.Flags().GetDuration("timeout")
+ if err != nil {
+ _, _ = fmt.Fprintf(cmd.ErrOrStderr(), "Не удалось прочитать тайм-аут: %v\n", err)
+ exit(1)
+ return
+ }
+ flagPattern, err := cmd.Flags().GetString("flag-regexp")
+ if err != nil {
+ _, _ = fmt.Fprintf(cmd.ErrOrStderr(), "Не удалось прочитать выражение флага: %v\n", err)
+ exit(1)
+ return
+ }
+ includeDir, err := cmd.Flags().GetBool("dir")
+ if err != nil {
+ _, _ = fmt.Fprintf(cmd.ErrOrStderr(), "Не удалось прочитать параметр --dir: %v\n", err)
+ exit(1)
+ return
+ }
+ result, err := cli.RunTest(cmd.Context(), args[0], args[1], timeout, flagPattern, includeDir)
+ if err != nil {
+ _, _ = fmt.Fprintf(cmd.ErrOrStderr(), "Локальный запуск не выполнен: %v\n", err)
+ exit(1)
+ return
+ }
+ if err := result.WriteTo(cmd.OutOrStdout(), cmd.ErrOrStderr()); err != nil {
+ _, _ = fmt.Fprintf(cmd.ErrOrStderr(), "Не удалось показать результат: %v\n", err)
+ exit(1)
+ return
+ }
+ if result.ExitCode != 0 {
+ exit(result.ExitCode)
+ }
+}
+
+func init() {
+ rootCmd.AddCommand(testCmd)
+ testCmd.Flags().Duration("timeout", 30*time.Second, "тайм-аут локального запуска")
+ testCmd.Flags().String("flag-regexp", "", "обязательное регулярное выражение для поиска флагов в выводе")
+ testCmd.Flags().Bool("dir", false, "скопировать папку с соседними файлами для запуска")
+}
diff --git a/components/neo/cmd/client/cmd/test_test.go b/components/neo/cmd/client/cmd/test_test.go
new file mode 100644
index 0000000..b1b347e
--- /dev/null
+++ b/components/neo/cmd/client/cmd/test_test.go
@@ -0,0 +1,82 @@
+package cmd
+
+import (
+ "bytes"
+ "context"
+ "os"
+ "path/filepath"
+ "testing"
+ "time"
+
+ "github.com/spf13/cobra"
+)
+
+func TestTestCommandFlagsAndArguments(t *testing.T) {
+ if testCmd.Use != "test FILE HOST" {
+ t.Fatalf("команда = %q", testCmd.Use)
+ }
+ if err := testCmd.Args(testCmd, []string{"job.py", "host"}); err != nil {
+ t.Fatalf("команда отклонила допустимые аргументы: %v", err)
+ }
+ if err := testCmd.Args(testCmd, []string{"job.py"}); err == nil {
+ t.Fatal("команда приняла запуск без адреса цели")
+ }
+ if err := testCmd.Args(testCmd, []string{"job.py", "host", "extra"}); err == nil {
+ t.Fatal("команда приняла лишний аргумент")
+ }
+ timeout := testCmd.Flags().Lookup("timeout")
+ if timeout == nil || timeout.DefValue != (30*time.Second).String() {
+ t.Fatalf("значение тайм-аута по умолчанию = %v", timeout)
+ }
+ pattern := testCmd.Flags().Lookup("flag-regexp")
+ if pattern == nil {
+ t.Fatal("параметр --flag-regexp отсутствует")
+ }
+ includeDir := testCmd.Flags().Lookup("dir")
+ if includeDir == nil || includeDir.DefValue != "false" {
+ t.Fatal("параметр --dir отсутствует или включен по умолчанию")
+ }
+}
+
+func TestTestCommandReportsMissingPatternInRussian(t *testing.T) {
+ command := &cobra.Command{}
+ command.SetContext(context.Background())
+ command.Flags().Duration("timeout", time.Second, "")
+ command.Flags().String("flag-regexp", "", "")
+ command.Flags().Bool("dir", false, "")
+ var stderr bytes.Buffer
+ command.SetErr(&stderr)
+ var exitCode int
+ runTestCommand(command, []string{"unused.py", "target"}, func(code int) { exitCode = code })
+ if exitCode != 1 {
+ t.Fatalf("код выхода команды = %d, ожидался 1", exitCode)
+ }
+ if !bytes.Contains(stderr.Bytes(), []byte("--flag-regexp обязателен")) {
+ t.Fatalf("ошибка об обязательном параметре не показана по-русски: %q", stderr.String())
+ }
+}
+
+func TestTestCommandPropagatesJobExitCode(t *testing.T) {
+ jobFile := filepath.Join(t.TempDir(), "job.sh")
+ if err := os.WriteFile(jobFile, []byte("#!/bin/sh\nexit 7\n"), 0700); err != nil {
+ t.Fatal(err)
+ }
+
+ command := &cobra.Command{}
+ command.SetContext(context.Background())
+ command.Flags().Duration("timeout", time.Second, "")
+ command.Flags().String("flag-regexp", `FLAG[0-9]+=`, "")
+ command.Flags().Bool("dir", false, "")
+ var stdout, stderr bytes.Buffer
+ command.SetOut(&stdout)
+ command.SetErr(&stderr)
+ var exitCode int
+ runTestCommand(command, []string{jobFile, "target"}, func(code int) { exitCode = code })
+
+ if exitCode != 7 {
+ t.Fatalf("код выхода команды = %d, ожидался 7", exitCode)
+ }
+ if !bytes.Contains(stdout.Bytes(), []byte("код выхода: 7\n")) {
+ t.Fatalf("в stdout нет кода завершения задания: %q", stdout.String())
+ }
+}
diff --git a/components/neo/cmd/client/cmd/update.go b/components/neo/cmd/client/cmd/update.go
new file mode 100644
index 0000000..28d5e8a
--- /dev/null
+++ b/components/neo/cmd/client/cmd/update.go
@@ -0,0 +1,36 @@
+package cmd
+
+import (
+ "time"
+
+ "github.com/sirupsen/logrus"
+ "github.com/spf13/cobra"
+
+ "github.com/c4t-but-s4d/neo/v2/cmd/client/cli"
+ "github.com/c4t-but-s4d/neo/v2/internal/client"
+)
+
+// updateCmd описывает команду изменения настроек эксплойта.
+var updateCmd = &cobra.Command{
+ Use: "update",
+ Short: "Изменить настройки эксплойта",
+ Example: "neo update exploit_name -i 2m -t 2m",
+ Args: cobra.ExactArgs(1),
+ Run: func(cmd *cobra.Command, args []string) {
+ cfg := client.MustUnmarshalConfig()
+ cli := cli.NewUpdateCLI(cmd, args, cfg)
+ ctx := cmd.Context()
+ if err := cli.Run(ctx); err != nil {
+ logrus.Fatalf("Не удалось изменить настройки эксплойта: %v", err)
+ }
+ logrus.Debug("Изменение настроек завершено")
+ },
+}
+
+func init() {
+ rootCmd.AddCommand(updateCmd)
+ updateCmd.PersistentFlags().DurationP("interval", "i", time.Second*30, "интервал запуска")
+ updateCmd.PersistentFlags().DurationP("timeout", "t", time.Second*30, "тайм-аут одного запуска")
+ updateCmd.PersistentFlags().BoolP("endless", "e", false, "запускать эксплойт в бесконечном режиме")
+ updateCmd.PersistentFlags().Bool("disabled", false, "отключить эксплойт")
+}
diff --git a/components/neo/cmd/client/main.go b/components/neo/cmd/client/main.go
new file mode 100644
index 0000000..f3eb67f
--- /dev/null
+++ b/components/neo/cmd/client/main.go
@@ -0,0 +1,32 @@
+package main
+
+import (
+ "context"
+ "log"
+ "os"
+ "os/signal"
+
+ "github.com/c4t-but-s4d/neo/v2/cmd/client/cmd"
+ "github.com/c4t-but-s4d/neo/v2/internal/client"
+)
+
+func main() {
+ if err := client.HardenProcess(); err != nil {
+ log.Fatalf("Не удалось ограничить чтение памяти worker через /proc: %v", err)
+ }
+ ctx, cancel := context.WithCancel(context.Background())
+ done := make(chan interface{}, 1)
+ go func() {
+ cmd.Execute(ctx)
+ done <- nil
+ }()
+ c := make(chan os.Signal, 1)
+ signal.Notify(c, os.Interrupt)
+
+ select {
+ case <-c:
+ cancel()
+ <-done
+ case <-done:
+ }
+}
diff --git a/components/neo/cmd/server/main.go b/components/neo/cmd/server/main.go
new file mode 100644
index 0000000..ce3f0ca
--- /dev/null
+++ b/components/neo/cmd/server/main.go
@@ -0,0 +1,201 @@
+package main
+
+import (
+ "context"
+ "fmt"
+ "net"
+ "net/http"
+ "os/signal"
+ "regexp"
+ "strings"
+ "sync"
+ "syscall"
+ "time"
+
+ "github.com/prometheus/client_golang/prometheus/promhttp"
+ "github.com/sirupsen/logrus"
+ "github.com/spf13/pflag"
+ "github.com/spf13/viper"
+ "google.golang.org/grpc"
+ _ "google.golang.org/grpc/encoding/gzip"
+
+ "github.com/c4t-but-s4d/neo/v2/internal/logger"
+ "github.com/c4t-but-s4d/neo/v2/internal/server/config"
+ "github.com/c4t-but-s4d/neo/v2/internal/server/exploits"
+ "github.com/c4t-but-s4d/neo/v2/internal/server/fs"
+ logs "github.com/c4t-but-s4d/neo/v2/internal/server/logs"
+ "github.com/c4t-but-s4d/neo/v2/pkg/grpcauth"
+ "github.com/c4t-but-s4d/neo/v2/pkg/neosync"
+ epb "github.com/c4t-but-s4d/neo/v2/proto/go/exploits"
+ fspb "github.com/c4t-but-s4d/neo/v2/proto/go/fileserver"
+ logspb "github.com/c4t-but-s4d/neo/v2/proto/go/logs"
+)
+
+func main() {
+ logger.Init()
+ if err := setupConfig(); err != nil {
+ logrus.Fatalf("Не удалось подготовить конфигурацию: %v", err)
+ }
+
+ cfg, err := readConfig()
+ if err != nil {
+ logrus.Fatalf("Не удалось прочитать конфигурацию: %v", err)
+ }
+
+ setLogLevel(cfg)
+
+ initCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+ fc := exploits.NewFarmClient(cfg.FarmConfig)
+ if err := fc.FillConfig(initCtx, &cfg.FarmConfig); err != nil {
+ logrus.Fatalf("Не удалось получить конфигурацию Farm: %v", err)
+ }
+ if strings.TrimSpace(cfg.FarmConfig.FlagRegexp) == "" {
+ logrus.Fatal("В конфигурации Farm не задан FLAG_FORMAT")
+ }
+ if _, err := regexp.Compile(cfg.FarmConfig.FlagRegexp); err != nil {
+ logrus.Fatalf("В конфигурации Farm неверный FLAG_FORMAT: %v", err)
+ }
+
+ st, err := exploits.NewBoltStorage(cfg.DBPath)
+ if err != nil {
+ logrus.Fatalf("Не удалось создать хранилище Bolt: %v", err)
+ }
+
+ logStore, err := logs.NewLogStorage(initCtx, cfg.RedisURL)
+ if err != nil {
+ logrus.Fatalf("Не удалось создать хранилище журналов: %v", err)
+ }
+
+ exploitsServer := exploits.New(cfg, st)
+ fsServer, err := fs.New(cfg)
+ if err != nil {
+ logrus.Fatalf("Не удалось создать файловый сервер: %v", err)
+ }
+ logsServer := logs.New(logStore)
+
+ lis, err := net.Listen("tcp", cfg.Addr)
+ if err != nil {
+ logrus.Fatalf("Не удалось открыть сетевой порт: %v", err)
+ }
+
+ authInterceptor := grpcauth.NewServerInterceptorWithWorkerKey(cfg.GrpcAuthKey, cfg.WorkerKey)
+ opts := []grpc.ServerOption{
+ grpc.UnaryInterceptor(authInterceptor.Unary()),
+ grpc.StreamInterceptor(authInterceptor.Stream()),
+ grpc.MaxRecvMsgSize(4 * 1024 * 1024),
+ grpc.MaxSendMsgSize(4 * 1024 * 1024),
+ }
+
+ s := grpc.NewServer(opts...)
+ epb.RegisterServiceServer(s, exploitsServer)
+ fspb.RegisterServiceServer(s, fsServer)
+ logspb.RegisterServiceServer(s, logsServer)
+ metricsMux := http.NewServeMux()
+ metricsMux.Handle("/metrics", promhttp.Handler())
+ metricsServer := &http.Server{
+ Addr: viper.GetString("metrics.address"),
+ Handler: metricsMux,
+ ReadHeaderTimeout: 5 * time.Second,
+ }
+
+ runCtx, cancel := signal.NotifyContext(context.Background(), syscall.SIGTERM, syscall.SIGINT)
+ defer cancel()
+
+ wg := sync.WaitGroup{}
+
+ wg.Add(4)
+ go func() {
+ defer wg.Done()
+ logrus.Infof("Запуск метрик на %s", metricsServer.Addr)
+ if err := metricsServer.ListenAndServe(); err != nil && err != http.ErrServerClosed {
+ logrus.Errorf("Ошибка сервера метрик: %v", err)
+ cancel()
+ }
+ }()
+ go func() {
+ defer wg.Done()
+ exploitsServer.HeartBeat(runCtx)
+ }()
+ go func() {
+ defer wg.Done()
+ exploitsServer.UpdateMetrics(runCtx)
+ }()
+ go func() {
+ defer wg.Done()
+ <-runCtx.Done()
+ logrus.Info("Получен сигнал остановки, сервер завершает работу")
+ s.GracefulStop()
+ shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer shutdownCancel()
+ if err := metricsServer.Shutdown(shutdownCtx); err != nil {
+ logrus.Errorf("Ошибка остановки сервера метрик: %v", err)
+ }
+ }()
+
+ logrus.Infof("Запуск сервера на %s", cfg.Addr)
+ if err := s.Serve(lis); err != nil {
+ logrus.Fatalf("Ошибка сервера: %v", err)
+ }
+
+ select {
+ case <-neosync.AwaitWG(&wg):
+ logrus.Info("Остановка завершена")
+ case <-time.After(10 * time.Second):
+ logrus.Warn("Истекло время ожидания остановки")
+ }
+}
+
+func setupConfig() error {
+ pflag.BoolP("debug", "v", false, "Enable verbose logging")
+ pflag.StringP("config", "c", "server_config.yml", "Path to config file")
+ pflag.Parse()
+
+ if err := viper.BindPFlags(pflag.CommandLine); err != nil {
+ return fmt.Errorf("связь параметров командной строки: %w", err)
+ }
+
+ viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
+ viper.SetEnvPrefix("NEO")
+ viper.AutomaticEnv()
+
+ viper.MustBindEnv("grpc_auth_key")
+ viper.MustBindEnv("worker_key", "NEO_WORKER_KEY")
+ viper.MustBindEnv("farm.password")
+ viper.MustBindEnv("farm.url")
+
+ viper.SetDefault("config", "server_config.yml")
+ viper.SetDefault("ping_every", time.Second*5)
+ viper.SetDefault("submit_every", time.Second*2)
+ viper.SetDefault("metrics.address", "127.0.0.1:3000")
+ viper.SetDefault("addr", ":5005")
+
+ return nil
+}
+
+func readConfig() (*config.Config, error) {
+ viper.SetConfigFile(viper.GetString("config"))
+ viper.SetConfigType("yaml")
+
+ if err := viper.ReadInConfig(); err != nil {
+ return nil, fmt.Errorf("чтение конфигурации YAML: %w", err)
+ }
+
+ cfg := &config.Config{}
+ if err := viper.Unmarshal(cfg); err != nil {
+ return nil, fmt.Errorf("разбор конфигурации: %w", err)
+ }
+ if err := cfg.Validate(); err != nil {
+ return nil, fmt.Errorf("неверная конфигурация: %w", err)
+ }
+
+ return cfg, nil
+}
+
+func setLogLevel(cfg *config.Config) {
+ if cfg.Debug {
+ logrus.SetLevel(logrus.DebugLevel)
+ } else {
+ logrus.SetLevel(logrus.InfoLevel)
+ }
+}
diff --git a/components/neo/compose.yaml b/components/neo/compose.yaml
new file mode 100644
index 0000000..c3504a4
--- /dev/null
+++ b/components/neo/compose.yaml
@@ -0,0 +1,120 @@
+services:
+ neo:
+ build:
+ context: .
+ additional_contexts:
+ project: ../..
+ dockerfile: Dockerfile
+ environment:
+ NEO_GRPC_AUTH_KEY: ${NEO_KEY:?Задайте NEO_KEY}
+ NEO_WORKER_KEY: ${NEO_WORKER_KEY:?Задайте NEO_WORKER_KEY}
+ NEO_FARM_PASSWORD: ${FARM_PASSWORD:?Задайте FARM_PASSWORD}
+ NEO_FARM_URL: ${FARM_URL:-http://farm:5000}
+ ports:
+ - "${BIND_ADDRESS:-127.0.0.1}:${NEO_PORT:-5005}:5005"
+ expose:
+ - "5005"
+ volumes:
+ - neo-data:/data
+ tmpfs:
+ - /tmp:rw,noexec,nosuid,nodev,size=64m,uid=10001,gid=10001,mode=0700
+ networks:
+ - default
+ - neo-data
+ depends_on:
+ neo-redis:
+ condition: service_healthy
+ read_only: true
+ cap_drop:
+ - ALL
+ security_opt:
+ - no-new-privileges:true
+ pids_limit: 128
+ mem_limit: 1g
+ init: true
+ healthcheck:
+ test: ["CMD", "wget", "-q", "-O", "/dev/null", "http://127.0.0.1:3000/metrics"]
+ interval: 10s
+ timeout: 3s
+ retries: 6
+ start_period: 10s
+ restart: unless-stopped
+
+ neo-redis:
+ build:
+ context: .
+ dockerfile: redis.Dockerfile
+ user: "999:1000"
+ command: ["redis-server", "--appendonly", "yes", "--appendfsync", "everysec"]
+ volumes:
+ - neo-redis-data:/data
+ networks:
+ - neo-data
+ tmpfs:
+ - /tmp:rw,noexec,nosuid,nodev,size=32m
+ read_only: true
+ cap_drop:
+ - ALL
+ security_opt:
+ - no-new-privileges:true
+ pids_limit: 128
+ mem_limit: 512m
+ healthcheck:
+ test: ["CMD", "redis-cli", "ping"]
+ interval: 5s
+ timeout: 3s
+ retries: 12
+ restart: unless-stopped
+
+ neo-worker:
+ profiles:
+ - worker
+ build:
+ context: .
+ additional_contexts:
+ project: ../..
+ dockerfile: client_env/Dockerfile
+ environment:
+ NEO_HOST: neo:5005
+ NEO_GRPC_AUTH_KEY: ${NEO_WORKER_KEY:?Задайте NEO_WORKER_KEY}
+ NEO_EXPLOIT_DIR: /work/exploits
+ NEO_METRICS_HOST: ""
+ NEO_ALLOW_BROADCAST_COMMANDS: "false"
+ NEO_WORKER_JOBS: ${NEO_WORKER_JOBS:-2}
+ command:
+ - /usr/local/bin/neo
+ - --config
+ - /etc/neo/client_config.yml
+ - run
+ - --jobs
+ - ${NEO_WORKER_JOBS:-2}
+ - --endless-jobs
+ - ${NEO_WORKER_ENDLESS_JOBS:-0}
+ depends_on:
+ neo:
+ condition: service_healthy
+ networks:
+ - default
+ tmpfs:
+ - /work:rw,nosuid,nodev,size=1g,uid=10001,gid=10001,mode=0700,exec
+ - /tmp:rw,noexec,nosuid,nodev,size=128m,uid=10001,gid=10001,mode=0700
+ read_only: true
+ user: "10001:10001"
+ cap_drop:
+ - ALL
+ security_opt:
+ - no-new-privileges:true
+ pids_limit: 128
+ mem_limit: 2g
+ cpus: 2.0
+ init: true
+ stop_grace_period: 10s
+ restart: unless-stopped
+
+volumes:
+ neo-data:
+ neo-redis-data:
+
+networks:
+ neo-data:
+ internal: true
diff --git a/components/neo/configs/client/config.yml b/components/neo/configs/client/config.yml
new file mode 100644
index 0000000..78a17a5
--- /dev/null
+++ b/components/neo/configs/client/config.yml
@@ -0,0 +1,6 @@
+host: "neo:5005"
+metrics_host: ""
+exploit_dir: "/work/exploits"
+grpc_auth_key: ""
+use_tls: false
+allow_broadcast_commands: false
diff --git a/components/neo/configs/server/config.yml b/components/neo/configs/server/config.yml
new file mode 100644
index 0000000..360cdd1
--- /dev/null
+++ b/components/neo/configs/server/config.yml
@@ -0,0 +1,14 @@
+addr: ":5005"
+db_path: "/data/db.db"
+redis_url: "redis://neo-redis:6379/0"
+base_dir: "/data/exploits"
+ping_every: "5s"
+submit_every: "2s"
+metrics:
+ address: "127.0.0.1:3000"
+
+farm:
+ url: "http://farm:5000"
+ password: ""
+
+env: {}
diff --git a/components/neo/go.mod b/components/neo/go.mod
new file mode 100644
index 0000000..88268eb
--- /dev/null
+++ b/components/neo/go.mod
@@ -0,0 +1,46 @@
+module github.com/c4t-but-s4d/neo/v2
+
+go 1.27.2
+
+require (
+ github.com/denisbrodbeck/machineid v1.0.1
+ github.com/google/go-cmp v0.7.0
+ github.com/google/uuid v1.6.0
+ github.com/mitchellh/mapstructure v1.5.0
+ github.com/prometheus/client_golang v1.25.0
+ github.com/prometheus/common v0.72.1
+ github.com/redis/go-redis/v9 v9.23.0
+ github.com/samber/lo v1.53.0
+ github.com/sirupsen/logrus v1.10.2
+ github.com/spaolacci/murmur3 v1.1.0
+ github.com/spf13/cobra v1.10.2
+ github.com/spf13/pflag v1.0.10
+ github.com/spf13/viper v1.21.0
+ github.com/stretchr/testify v1.12.1
+ go.etcd.io/bbolt v1.5.0
+ go.uber.org/goleak v1.3.0
+ golang.org/x/sys v0.49.0
+ google.golang.org/grpc v1.84.0
+ google.golang.org/protobuf v1.36.12
+)
+
+require (
+ github.com/beorn7/perks v1.0.1 // indirect
+ github.com/cespare/xxhash/v2 v2.3.0 // indirect
+ github.com/fsnotify/fsnotify v1.10.1 // indirect
+ github.com/go-viper/mapstructure/v2 v2.5.0 // indirect
+ github.com/inconshreveable/mousetrap v1.1.0 // indirect
+ github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
+ github.com/pelletier/go-toml/v2 v2.4.3 // indirect
+ github.com/prometheus/client_model v0.6.3 // indirect
+ github.com/prometheus/procfs v0.22.0 // indirect
+ github.com/sagikazarmark/locafero v0.12.0 // indirect
+ github.com/spf13/afero v1.15.0 // indirect
+ github.com/spf13/cast v1.10.0 // indirect
+ github.com/subosito/gotenv v1.6.0 // indirect
+ go.uber.org/atomic v1.12.0 // indirect
+ go.yaml.in/yaml/v3 v3.0.5 // indirect
+ golang.org/x/net v0.61.0 // indirect
+ golang.org/x/text v0.43.0 // indirect
+ google.golang.org/genproto/googleapis/rpc v0.0.0-20261012220534-4341edf3f941 // indirect
+)
diff --git a/components/neo/go.sum b/components/neo/go.sum
new file mode 100644
index 0000000..d8acf09
--- /dev/null
+++ b/components/neo/go.sum
@@ -0,0 +1,107 @@
+github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
+github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
+github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs=
+github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c=
+github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA=
+github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0=
+github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
+github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
+github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=
+github.com/denisbrodbeck/machineid v1.0.1 h1:geKr9qtkB876mXguW2X6TU4ZynleN6ezuMSRhl4D7AQ=
+github.com/denisbrodbeck/machineid v1.0.1/go.mod h1:dJUwb7PTidGDeYyUBmXZ2GphQBbjJCrnectwCyxcUSI=
+github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8=
+github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0=
+github.com/fsnotify/fsnotify v1.10.1 h1:b0/UzAf9yR5rhf3RPm9gf3ehBPpf0oZKIjtpKrx59Ho=
+github.com/fsnotify/fsnotify v1.10.1/go.mod h1:TLheqan6HD6GBK6PrDWyDPBaEV8LspOxvPSjC+bVfgo=
+github.com/go-viper/mapstructure/v2 v2.5.0 h1:vM5IJoUAy3d7zRSVtIwQgBj7BiWtMPfmPEgAXnvj1Ro=
+github.com/go-viper/mapstructure/v2 v2.5.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=
+github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
+github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
+github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
+github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
+github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
+github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
+github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
+github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
+github.com/klauspost/compress v1.20.1 h1:T7kKElXUMXrUJ2E9QhQhxFtcK5rPyLdsGZvdbLMPdiQ=
+github.com/klauspost/compress v1.20.1/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI=
+github.com/klauspost/cpuid/v2 v2.4.0 h1:S6Hrbc7+ywsr0r+RLapfGBHfyefhCTwEh3A0tV913Dw=
+github.com/klauspost/cpuid/v2 v2.4.0/go.mod h1:19jmZ9mjzoF//ddRSUsv0zfBTJWh3QJh9FNxZTMrGxU=
+github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
+github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
+github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
+github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
+github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc=
+github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw=
+github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY=
+github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo=
+github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA=
+github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ=
+github.com/pelletier/go-toml/v2 v2.4.3 h1:GTRvJQutkOSftxIFD5xw9aepkYNuPWmVJpffdDPYVpY=
+github.com/pelletier/go-toml/v2 v2.4.3/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
+github.com/prometheus/client_golang v1.25.0 h1:cDtW1TcFsMi1RJc8khwCKB4VhzwV04aKqbYtNOXuiK0=
+github.com/prometheus/client_golang v1.25.0/go.mod h1:j2X/4/kaQHLPnmyEU8zjmkndo1T317VpCIQEml8LTKk=
+github.com/prometheus/client_model v0.6.3 h1:O0jaTVAYNxTHYInEPFJt5I3+sN8zqBtVMPTB1qyxiEo=
+github.com/prometheus/client_model v0.6.3/go.mod h1:gpN5P9S7Rr6Yr92PiQ+Ixvhf6JZEkF1dnxsYL2aPBEM=
+github.com/prometheus/common v0.72.1 h1:ZAiQed/nk8IIcsdzb2TlJu23NEUDyDLQ9TXTN2WRK6Y=
+github.com/prometheus/common v0.72.1/go.mod h1:1IoBY4IRaJnhs2ESjNzjilP1cJ/P8pimGoomq7zRXrA=
+github.com/prometheus/procfs v0.22.0 h1:6q9+/JL9IKAPbCmBrv9n5O5Ty3NKnciV5X7YGw0oics=
+github.com/prometheus/procfs v0.22.0/go.mod h1:CvmFr/GVhIjIvWJZW3tgkODBQMRIf0EyWMQLHCHab58=
+github.com/redis/go-redis/v9 v9.23.0 h1:/TTVdJa8BRNsybwwGGnmiYktHNlUXtbOQxlWpHBPL3s=
+github.com/redis/go-redis/v9 v9.23.0/go.mod h1:EWP2UUk+XDaI1s5nQB5mablZN6vccXlmBQTyfnF87D0=
+github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8=
+github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs=
+github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
+github.com/sagikazarmark/locafero v0.12.0 h1:/NQhBAkUb4+fH1jivKHWusDYFjMOOKU88eegjfxfHb4=
+github.com/sagikazarmark/locafero v0.12.0/go.mod h1:sZh36u/YSZ918v0Io+U9ogLYQJ9tLLBmM4eneO6WwsI=
+github.com/samber/lo v1.53.0 h1:t975lj2py4kJPQ6haz1QMgtId2gtmfktACxIXArw3HM=
+github.com/samber/lo v1.53.0/go.mod h1:4+MXEGsJzbKGaUEQFKBq2xtfuznW9oz/WrgyzMzRoM0=
+github.com/sirupsen/logrus v1.10.2 h1:G2SED73/qrAu6YwbdxOD6peLkCBI3z7L+ykJFTXJBBo=
+github.com/sirupsen/logrus v1.10.2/go.mod h1:SLEg8TqYulVKKfIGHldVp2K2aYz2DKSVBq4g/H5bR7Q=
+github.com/spaolacci/murmur3 v1.1.0 h1:7c1g84S4BPRrfL5Xrdp6fOJ206sU9y293DDHaoy0bLI=
+github.com/spaolacci/murmur3 v1.1.0/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA=
+github.com/spf13/afero v1.15.0 h1:b/YBCLWAJdFWJTN9cLhiXXcD7mzKn9Dm86dNnfyQw1I=
+github.com/spf13/afero v1.15.0/go.mod h1:NC2ByUVxtQs4b3sIUphxK0NioZnmxgyCrfzeuq8lxMg=
+github.com/spf13/cast v1.10.0 h1:h2x0u2shc1QuLHfxi+cTJvs30+ZAHOGRic8uyGTDWxY=
+github.com/spf13/cast v1.10.0/go.mod h1:jNfB8QC9IA6ZuY2ZjDp0KtFO2LZZlg4S/7bzP6qqeHo=
+github.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU=
+github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4=
+github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
+github.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk=
+github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
+github.com/spf13/viper v1.21.0 h1:x5S+0EU27Lbphp4UKm1C+1oQO+rKx36vfCoaVebLFSU=
+github.com/spf13/viper v1.21.0/go.mod h1:P0lhsswPGWD/1lZJ9ny3fYnVqxiegrlNrEmgLjbTCAY=
+github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE=
+github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg=
+github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8=
+github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU=
+github.com/zeebo/xxh3 v1.1.0 h1:s7DLGDK45Dyfg7++yxI0khrfwq9661w9EN78eP/UZVs=
+github.com/zeebo/xxh3 v1.1.0/go.mod h1:IisAie1LELR4xhVinxWS5+zf1lA4p0MW4T+w+W07F5s=
+go.etcd.io/bbolt v1.5.0 h1:S7GAl7Fxv12yohbwFfIbQCGDWbQbtDGPET4P/bD4lxU=
+go.etcd.io/bbolt v1.5.0/go.mod h1:mkltfYE5aUHQxUct9N9V+Kp7aSjFqjgrhcXIS70Lrdk=
+go.uber.org/atomic v1.12.0 h1:BvcXdFKuviU4fTL/f+SxdQ5qJX/Jix8pAkgdUcb3XOE=
+go.uber.org/atomic v1.12.0/go.mod h1:I6c4cg+6HCxRjfjSsYtApoFILnpc0CGUdGkXVqbYVNk=
+go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
+go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
+go.yaml.in/yaml/v2 v2.4.4 h1:tuyd0P+2Ont/d6e2rl3be67goVK4R6deVxCUX5vyPaQ=
+go.yaml.in/yaml/v2 v2.4.4/go.mod h1:gMZqIpDtDqOfM0uNfy0SkpRhvUryYH0Z6wdMYcacYXQ=
+go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
+go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw=
+go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
+golang.org/x/net v0.61.0 h1:RR+6j/BTBCrggOLugxa+66R8FvoN6MHlzDlZIbN9YFw=
+golang.org/x/net v0.61.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI=
+golang.org/x/sync v0.24.0 h1:iqiDrGoDgyuvAKrhLQthUEzU/R378N78gXbBjxed7oA=
+golang.org/x/sync v0.24.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
+golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA=
+golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
+golang.org/x/text v0.43.0 h1:1QivrlhwAsnMOcqgOdl9my7s9OyZl8O5/UGUTJVXoWc=
+golang.org/x/text v0.43.0/go.mod h1:hbSIYA/amXcRXTFSZqh8tWHEoqRvvbKPJ2uz/KU+a+s=
+gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4=
+gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E=
+google.golang.org/genproto/googleapis/rpc v0.0.0-20261012220534-4341edf3f941 h1:QG6hS4zFplRZvOQedzei4t2pT/zkQc3VR1u+S9/rcAw=
+google.golang.org/genproto/googleapis/rpc v0.0.0-20261012220534-4341edf3f941/go.mod h1:OaIUM3+LpYcK2GXM4FTmhWoIq371Owdr+Cc7/BsYHHc=
+google.golang.org/grpc v1.84.0 h1:soMyaPJ8pAak5PIQ0DGBUir0XRo2fRoMqhNWMLlLxO0=
+google.golang.org/grpc v1.84.0/go.mod h1:ljCht0DrxQrXBDRTZp52Qxh3Ffk8CdYm2sj4O2QN2C0=
+google.golang.org/protobuf v1.36.12 h1:pJOKDDOyeXErUroCihFAd5LQuwXBSpVnKGrj5o/fwxc=
+google.golang.org/protobuf v1.36.12/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
+gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
diff --git a/components/neo/internal/client/client.go b/components/neo/internal/client/client.go
new file mode 100644
index 0000000..83ae861
--- /dev/null
+++ b/components/neo/internal/client/client.go
@@ -0,0 +1,256 @@
+package client
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "io"
+
+ "github.com/sirupsen/logrus"
+ "google.golang.org/grpc"
+
+ "github.com/c4t-but-s4d/neo/v2/pkg/filestream"
+ epb "github.com/c4t-but-s4d/neo/v2/proto/go/exploits"
+ fspb "github.com/c4t-but-s4d/neo/v2/proto/go/fileserver"
+ logspb "github.com/c4t-but-s4d/neo/v2/proto/go/logs"
+)
+
+func New(cc grpc.ClientConnInterface, id string) *Client {
+ return &Client{
+ exploits: epb.NewServiceClient(cc),
+ fs: fspb.NewServiceClient(cc),
+ logs: logspb.NewServiceClient(cc),
+ ID: id,
+ }
+}
+
+type Client struct {
+ exploits epb.ServiceClient
+ fs fspb.ServiceClient
+ logs logspb.ServiceClient
+
+ ID string
+ Weight int
+}
+
+func (nc *Client) GetServerState(ctx context.Context) (*epb.ServerState, error) {
+ resp, err := nc.exploits.Ping(
+ ctx,
+ &epb.PingRequest{
+ ClientId: nc.ID,
+ Payload: &epb.PingRequest_ServerInfoRequest{
+ ServerInfoRequest: &epb.PingRequest_ServerInfo{},
+ },
+ },
+ )
+ if err != nil {
+ return nil, fmt.Errorf("запрос проверки связи: %w", err)
+ }
+ return resp.State, nil
+}
+
+func (nc *Client) Heartbeat(ctx context.Context) (*epb.ServerState, error) {
+ resp, err := nc.exploits.Ping(
+ ctx,
+ &epb.PingRequest{
+ ClientId: nc.ID,
+ Payload: &epb.PingRequest_HeartbeatRequest{
+ HeartbeatRequest: &epb.PingRequest_Heartbeat{
+ Weight: int32(nc.Weight),
+ },
+ },
+ },
+ )
+ if err != nil {
+ return nil, fmt.Errorf("запрос проверки связи: %w", err)
+ }
+ return resp.State, nil
+}
+
+func (nc *Client) Leave(ctx context.Context) error {
+ if _, err := nc.exploits.Ping(
+ ctx,
+ &epb.PingRequest{
+ ClientId: nc.ID,
+ Payload: &epb.PingRequest_LeaveRequest{
+ LeaveRequest: &epb.PingRequest_Leave{},
+ },
+ },
+ ); err != nil {
+ return fmt.Errorf("запрос проверки связи: %w", err)
+ }
+ return nil
+}
+
+func (nc *Client) Exploit(ctx context.Context, id string) (*epb.ExploitResponse, error) {
+ req := &epb.ExploitRequest{
+ ExploitId: id,
+ }
+ resp, err := nc.exploits.Exploit(ctx, req)
+ if err != nil {
+ return nil, fmt.Errorf("запрос эксплойта: %w", err)
+ }
+ return resp, nil
+}
+
+func (nc *Client) UpdateExploit(ctx context.Context, state *epb.ExploitState) (*epb.ExploitState, error) {
+ req := &epb.UpdateExploitRequest{State: state}
+ resp, err := nc.exploits.UpdateExploit(ctx, req)
+ if err != nil {
+ return nil, fmt.Errorf("запрос обновления эксплойта: %w", err)
+ }
+ return resp.State, nil
+}
+
+func (nc *Client) DownloadFile(ctx context.Context, info *fspb.FileInfo, out io.Writer) error {
+ resp, err := nc.fs.DownloadFile(ctx, info)
+ if err != nil {
+ return fmt.Errorf("запрос скачивания файла: %w", err)
+ }
+ if err := filestream.SaveLimit(resp, out, filestream.MaxFileSize); err != nil {
+ return fmt.Errorf("сохранение скачанного файла: %w", err)
+ }
+ if err := resp.CloseSend(); err != nil {
+ return fmt.Errorf("закрытие потока: %w", err)
+ }
+ return nil
+}
+
+func (nc *Client) UploadFile(ctx context.Context, r io.Reader) (*fspb.FileInfo, error) {
+ client, err := nc.fs.UploadFile(ctx)
+ if err != nil {
+ return nil, fmt.Errorf("запрос загрузки файла: %w", err)
+ }
+ if err := filestream.Load(r, client); err != nil {
+ return nil, fmt.Errorf("передача файла в поток: %w", err)
+ }
+ fileInfo, err := client.CloseAndRecv()
+ if err != nil {
+ return nil, fmt.Errorf("закрытие потока и чтение ответа о загрузке: %w", err)
+ }
+ return fileInfo, nil
+}
+
+func (nc *Client) BroadcastCommand(ctx context.Context, command string) error {
+ req := &epb.BroadcastRequest{Command: command}
+ if _, err := nc.exploits.BroadcastCommand(ctx, req); err != nil {
+ return fmt.Errorf("запрос рассылки команды: %w", err)
+ }
+ return nil
+}
+
+func (nc *Client) SingleRun(ctx context.Context, exploitID string) error {
+ req := &epb.SingleRunRequest{ExploitId: exploitID}
+ if _, err := nc.exploits.SingleRun(ctx, req); err != nil {
+ return fmt.Errorf("запрос одиночного запуска: %w", err)
+ }
+ return nil
+}
+
+func (nc *Client) SetExploitDisabled(ctx context.Context, id string, disabled bool) error {
+ resp, err := nc.Exploit(ctx, id)
+ if err != nil {
+ return fmt.Errorf("получение текущей конфигурации эксплойта: %w", err)
+ }
+
+ req := &epb.UpdateExploitRequest{State: resp.State}
+ req.State.Config.Disabled = disabled
+
+ if _, err := nc.exploits.UpdateExploit(ctx, req); err != nil {
+ return fmt.Errorf("запрос изменения состояния эксплойта: %w", err)
+ }
+ return nil
+}
+
+func (nc *Client) ListenBroadcasts(ctx context.Context) (<-chan *epb.BroadcastSubscribeResponse, error) {
+ stream, err := nc.exploits.BroadcastSubscribe(ctx, &epb.BroadcastSubscribeRequest{})
+ if err != nil {
+ return nil, fmt.Errorf("создание потока запросов рассылки: %w", err)
+ }
+
+ results := make(chan *epb.BroadcastSubscribeResponse)
+ go func() {
+ defer close(results)
+ for {
+ cmd, err := stream.Recv()
+ if !checkStreamError("broadcast", err, stream.Context().Err()) {
+ return
+ }
+ select {
+ case results <- cmd:
+ case <-ctx.Done():
+ logrus.Debugf("Контекст рассылки отменен")
+ return
+ }
+ }
+ }()
+
+ return results, nil
+}
+
+func (nc *Client) ListenSingleRuns(ctx context.Context) (<-chan *epb.SingleRunSubscribeResponse, error) {
+ stream, err := nc.exploits.SingleRunSubscribe(ctx, &epb.SingleRunSubscribeRequest{})
+ if err != nil {
+ return nil, fmt.Errorf("создание потока одиночных запусков: %w", err)
+ }
+
+ results := make(chan *epb.SingleRunSubscribeResponse)
+ go func() {
+ defer close(results)
+ for {
+ er, err := stream.Recv()
+ if !checkStreamError("single runs", err, stream.Context().Err()) {
+ return
+ }
+ select {
+ case results <- er:
+ case <-ctx.Done():
+ logrus.Warningf("Контекст одиночного запуска отменен")
+ return
+ }
+ }
+ }()
+
+ return results, nil
+}
+
+func (nc *Client) AddLogLines(ctx context.Context, lines ...*logspb.LogLine) error {
+ req := logspb.AddLogLinesRequest{Lines: lines}
+ if _, err := nc.logs.AddLogLines(ctx, &req); err != nil {
+ return fmt.Errorf("отправка пакета строк журнала (%d): %w", len(lines), err)
+ }
+ return nil
+}
+
+func (nc *Client) SearchLogLines(ctx context.Context, exploit string, version int64) (<-chan []*logspb.LogLine, error) {
+ req := logspb.SearchLogLinesRequest{
+ Exploit: exploit,
+ Version: version,
+ }
+ stream, err := nc.logs.SearchLogLines(ctx, &req)
+ if err != nil {
+ return nil, fmt.Errorf("запрос к серверу: %w", err)
+ }
+
+ results := make(chan []*logspb.LogLine)
+ go func() {
+ defer close(results)
+ for {
+ resp, err := stream.Recv()
+ if err != nil {
+ if !errors.Is(err, io.EOF) {
+ logrus.Errorf("Ошибка чтения строк журнала: %v", err)
+ }
+ return
+ }
+ select {
+ case results <- resp.Lines:
+ case <-ctx.Done():
+ logrus.Debugf("Контекст чтения журнала отменен")
+ return
+ }
+ }
+ }()
+
+ return results, nil
+}
diff --git a/components/neo/internal/client/config.go b/components/neo/internal/client/config.go
new file mode 100644
index 0000000..74e7bac
--- /dev/null
+++ b/components/neo/internal/client/config.go
@@ -0,0 +1,23 @@
+package client
+
+import (
+ "github.com/sirupsen/logrus"
+ "github.com/spf13/viper"
+)
+
+func MustUnmarshalConfig() *Config {
+ cfg := new(Config)
+ if err := viper.Unmarshal(&cfg); err != nil {
+ logrus.Fatalf("Не удалось разобрать структуру конфигурации: %v", err)
+ }
+ return cfg
+}
+
+type Config struct {
+ Host string `mapstructure:"host"`
+ MetricsHost string `mapstructure:"metrics_host"`
+ ExploitDir string `mapstructure:"exploit_dir"`
+ GrpcAuthKey string `mapstructure:"grpc_auth_key"`
+ UseTLS bool `mapstructure:"use_tls"`
+ AllowBroadcastCommands bool `mapstructure:"allow_broadcast_commands"`
+}
diff --git a/components/neo/internal/client/process_linux.go b/components/neo/internal/client/process_linux.go
new file mode 100644
index 0000000..094c32b
--- /dev/null
+++ b/components/neo/internal/client/process_linux.go
@@ -0,0 +1,11 @@
+//go:build linux
+
+package client
+
+import "golang.org/x/sys/unix"
+
+// HardenProcess не дает заданиям с тем же UID читать память и окружение
+// worker через /proc, сохраняя возможность запускать дочерние процессы.
+func HardenProcess() error {
+ return unix.Prctl(unix.PR_SET_DUMPABLE, 0, 0, 0, 0)
+}
diff --git a/components/neo/internal/client/process_linux_test.go b/components/neo/internal/client/process_linux_test.go
new file mode 100644
index 0000000..e853654
--- /dev/null
+++ b/components/neo/internal/client/process_linux_test.go
@@ -0,0 +1,17 @@
+//go:build linux
+
+package client
+
+import (
+ "testing"
+
+ "github.com/stretchr/testify/require"
+ "golang.org/x/sys/unix"
+)
+
+func TestHardenProcessDisablesDumpability(t *testing.T) {
+ require.NoError(t, HardenProcess())
+ dumpable, err := unix.PrctlRetInt(unix.PR_GET_DUMPABLE, 0, 0, 0, 0)
+ require.NoError(t, err)
+ require.Zero(t, dumpable)
+}
diff --git a/components/neo/internal/client/process_other.go b/components/neo/internal/client/process_other.go
new file mode 100644
index 0000000..48de1b5
--- /dev/null
+++ b/components/neo/internal/client/process_other.go
@@ -0,0 +1,5 @@
+//go:build !linux
+
+package client
+
+func HardenProcess() error { return nil }
diff --git a/components/neo/internal/client/utils.go b/components/neo/internal/client/utils.go
new file mode 100644
index 0000000..1d7d10a
--- /dev/null
+++ b/components/neo/internal/client/utils.go
@@ -0,0 +1,25 @@
+package client
+
+import (
+ "context"
+ "errors"
+ "io"
+
+ "github.com/sirupsen/logrus"
+)
+
+func checkStreamError(tp string, err error, streamErr error) bool {
+ if errors.Is(err, io.EOF) {
+ logrus.Errorf("Поток %s закрыт", tp)
+ return false
+ }
+ if errors.Is(streamErr, context.Canceled) {
+ logrus.Debugf("Контекст потока %s отменен", tp)
+ return false
+ }
+ if err != nil {
+ logrus.Errorf("Ошибка чтения из потока %s: %v", tp, err)
+ return false
+ }
+ return true
+}
diff --git a/components/neo/internal/config/config.go b/components/neo/internal/config/config.go
new file mode 100644
index 0000000..cef6589
--- /dev/null
+++ b/components/neo/internal/config/config.go
@@ -0,0 +1,47 @@
+package config
+
+import (
+ "fmt"
+ "regexp"
+ "time"
+
+ "google.golang.org/protobuf/types/known/durationpb"
+
+ epb "github.com/c4t-but-s4d/neo/v2/proto/go/exploits"
+)
+
+type ExploitsConfig struct {
+ PingEvery time.Duration
+ SubmitEvery time.Duration
+ FarmURL string
+ FarmPassword string
+ FlagRegexp *regexp.Regexp
+ Environ []string
+}
+
+func ToProto(c *ExploitsConfig) *epb.Config {
+ return &epb.Config{
+ FarmUrl: c.FarmURL,
+ FarmPassword: c.FarmPassword,
+ FlagRegexp: c.FlagRegexp.String(),
+ PingEvery: durationpb.New(c.PingEvery),
+ SubmitEvery: durationpb.New(c.SubmitEvery),
+ Environ: c.Environ,
+ }
+}
+
+func FromProto(config *epb.Config) (*ExploitsConfig, error) {
+ var (
+ cfg ExploitsConfig
+ err error
+ )
+ if cfg.FlagRegexp, err = regexp.Compile(config.FlagRegexp); err != nil {
+ return nil, fmt.Errorf("компиляция регулярного выражения: %w", err)
+ }
+ cfg.FarmURL = config.FarmUrl
+ cfg.FarmPassword = config.FarmPassword
+ cfg.PingEvery = config.PingEvery.AsDuration()
+ cfg.SubmitEvery = config.SubmitEvery.AsDuration()
+ cfg.Environ = config.Environ
+ return &cfg, nil
+}
diff --git a/components/neo/internal/exploit/cache.go b/components/neo/internal/exploit/cache.go
new file mode 100644
index 0000000..a7ed26b
--- /dev/null
+++ b/components/neo/internal/exploit/cache.go
@@ -0,0 +1,73 @@
+package exploit
+
+import (
+ "sync"
+ "time"
+
+ epb "github.com/c4t-but-s4d/neo/v2/proto/go/exploits"
+)
+
+func NewCache() *Cache {
+ return &Cache{
+ states: make(map[string]*State),
+ m: sync.RWMutex{},
+ }
+}
+
+// Cache хранит исполняемые файлы в памяти клиента.
+// Кэш не сохраняется на диск, поэтому после перезапуска файлы загружаются заново.
+type Cache struct {
+ states map[string]*State
+ m sync.RWMutex
+}
+
+func (c *Cache) Exploits() (res []*State) {
+ c.m.RLock()
+ defer c.m.RUnlock()
+
+ for _, v := range c.states {
+ res = append(res, v)
+ }
+ return
+}
+
+func (c *Cache) Exploit(id string) (res *State, ok bool) {
+ c.m.RLock()
+ defer c.m.RUnlock()
+ res, ok = c.states[id]
+ return
+}
+
+func (c *Cache) Diff(exs []*epb.ExploitState) []*epb.ExploitState {
+ c.m.RLock()
+ defer c.m.RUnlock()
+
+ var diff []*epb.ExploitState
+ for _, ex := range exs {
+ state, exists := c.states[ex.ExploitId]
+ if !exists {
+ diff = append(diff, ex)
+ continue
+ }
+ if state.Version != ex.Version {
+ diff = append(diff, ex)
+ }
+ }
+ return diff
+}
+
+func (c *Cache) Update(exs []*State) {
+ c.m.Lock()
+ defer c.m.Unlock()
+ for _, ex := range exs {
+ c.states[ex.ID] = ex
+ }
+}
+
+func (c *Cache) UpdateLastRun(exploitID string, t time.Time) {
+ c.m.Lock()
+ defer c.m.Unlock()
+ if ex, ok := c.states[exploitID]; ok {
+ ex.LastRun = t
+ }
+}
diff --git a/components/neo/internal/exploit/cache_test.go b/components/neo/internal/exploit/cache_test.go
new file mode 100644
index 0000000..1cd1812
--- /dev/null
+++ b/components/neo/internal/exploit/cache_test.go
@@ -0,0 +1,202 @@
+package exploit
+
+import (
+ "testing"
+
+ "github.com/google/go-cmp/cmp"
+ "github.com/google/go-cmp/cmp/cmpopts"
+ "google.golang.org/protobuf/testing/protocmp"
+
+ epb "github.com/c4t-but-s4d/neo/v2/proto/go/exploits"
+)
+
+func TestCache_Diff(t *testing.T) {
+ for _, tc := range []struct {
+ have []*State
+ new []*epb.ExploitState
+ diff []*epb.ExploitState
+ }{
+ {
+ have: nil,
+ new: nil,
+ diff: nil,
+ },
+ {
+ have: []*State{
+ {ID: "1", Version: 1},
+ },
+ new: []*epb.ExploitState{{
+ ExploitId: "1",
+ Version: 1,
+ File: nil,
+ }},
+ diff: nil,
+ },
+ {
+ have: []*State{
+ {ID: "1", Version: 1},
+ },
+ new: []*epb.ExploitState{{
+ ExploitId: "2",
+ Version: 1,
+ File: nil,
+ }},
+ diff: []*epb.ExploitState{{
+ ExploitId: "2",
+ Version: 1,
+ File: nil,
+ }},
+ },
+ {
+ have: []*State{
+ {ID: "1", Version: 1},
+ },
+ new: []*epb.ExploitState{{
+ ExploitId: "1",
+ Version: 2,
+ File: nil,
+ }},
+ diff: []*epb.ExploitState{{
+ ExploitId: "1",
+ Version: 2,
+ File: nil,
+ }},
+ },
+ {
+ have: []*State{
+ {ID: "1", Version: 1},
+ {ID: "2", Version: 1},
+ },
+ new: []*epb.ExploitState{
+ {
+ ExploitId: "1",
+ Version: 2,
+ File: nil,
+ },
+ {
+ ExploitId: "2",
+ Version: 1,
+ File: nil,
+ },
+ {
+ ExploitId: "3",
+ Version: 1,
+ File: nil,
+ },
+ },
+ diff: []*epb.ExploitState{
+ {
+ ExploitId: "1",
+ Version: 2,
+ File: nil,
+ },
+ {
+ ExploitId: "3",
+ Version: 1,
+ File: nil,
+ },
+ },
+ },
+ {
+ have: []*State{
+ {ID: "1", Version: 1},
+ {ID: "2", Version: 1},
+ },
+ new: nil,
+ diff: nil,
+ },
+ {
+ have: []*State{
+ {ID: "1", Version: 1, Endless: false},
+ },
+ new: []*epb.ExploitState{
+ {
+ ExploitId: "1",
+ Version: 2,
+ Config: &epb.ExploitConfiguration{Endless: true},
+ },
+ },
+ diff: []*epb.ExploitState{
+ {
+ ExploitId: "1",
+ Version: 2,
+ Config: &epb.ExploitConfiguration{Endless: true},
+ },
+ },
+ },
+ {
+ have: []*State{
+ {ID: "1", Version: 1, Endless: true},
+ },
+ new: []*epb.ExploitState{
+ {
+ ExploitId: "1",
+ Version: 2,
+ Config: &epb.ExploitConfiguration{Endless: false},
+ },
+ },
+ diff: []*epb.ExploitState{
+ {
+ ExploitId: "1",
+ Version: 2,
+ Config: &epb.ExploitConfiguration{Endless: false},
+ },
+ },
+ },
+ {
+ have: nil,
+ new: []*epb.ExploitState{
+ {
+ ExploitId: "1",
+ Version: 2,
+ Config: &epb.ExploitConfiguration{Endless: true},
+ },
+ },
+ diff: []*epb.ExploitState{
+ {
+ ExploitId: "1",
+ Version: 2,
+ Config: &epb.ExploitConfiguration{Endless: true},
+ },
+ },
+ },
+ {
+ have: nil,
+ new: []*epb.ExploitState{
+ {
+ ExploitId: "1",
+ Version: 2,
+ Config: &epb.ExploitConfiguration{Endless: false},
+ },
+ },
+ diff: []*epb.ExploitState{
+ {
+ ExploitId: "1",
+ Version: 2,
+ Config: &epb.ExploitConfiguration{Endless: false},
+ },
+ },
+ },
+ } {
+ c := NewCache()
+ c.Update(tc.have)
+ got := c.Diff(tc.new)
+ if diff := cmp.Diff(tc.diff, got, protocmp.Transform(), cmpopts.EquateEmpty()); diff != "" {
+ t.Errorf("Diff() mismatch (-want +got):\n%s", diff)
+ }
+ }
+}
+
+func TestCache_Exploits(t *testing.T) {
+ c := NewCache()
+ data := []*State{{
+ ID: "1",
+ Version: 1,
+ Dir: "/test",
+ Path: "kek",
+ }}
+ c.Update(data)
+ if diff := cmp.Diff(data, c.Exploits(), cmpopts.EquateEmpty()); diff != "" {
+ t.Errorf("Diff() mismatch (-want +got):\n%s", diff)
+ }
+}
diff --git a/components/neo/internal/exploit/metrics.go b/components/neo/internal/exploit/metrics.go
new file mode 100644
index 0000000..f5179a0
--- /dev/null
+++ b/components/neo/internal/exploit/metrics.go
@@ -0,0 +1,51 @@
+package exploit
+
+import (
+ "github.com/prometheus/client_golang/prometheus"
+ "github.com/prometheus/client_golang/prometheus/promauto"
+)
+
+type Metrics struct {
+ FlagsSubmitted *prometheus.CounterVec
+ Teams prometheus.Gauge
+ Queue *prometheus.GaugeVec
+}
+
+func NewMetrics(namespace string) *Metrics {
+ const subsystem = "exploit_runner"
+
+ return &Metrics{
+ FlagsSubmitted: promauto.NewCounterVec(
+ prometheus.CounterOpts{
+ Namespace: namespace,
+ Subsystem: subsystem,
+ Name: "flags_submitted_total",
+ Help: "Number of exploits finished",
+ },
+ []string{
+ "target_id",
+ "target_ip",
+ "exploit_id",
+ "exploit_version",
+ "exploit_type",
+ },
+ ),
+
+ Teams: promauto.NewGauge(prometheus.GaugeOpts{
+ Namespace: namespace,
+ Subsystem: subsystem,
+ Name: "teams",
+ Help: "Number of teams scheduled for the current runner",
+ }),
+
+ Queue: promauto.NewGaugeVec(
+ prometheus.GaugeOpts{
+ Namespace: namespace,
+ Subsystem: subsystem,
+ Name: "queue",
+ Help: "Number of exploits in the queue",
+ },
+ []string{"type"},
+ ),
+ }
+}
diff --git a/components/neo/internal/exploit/models.go b/components/neo/internal/exploit/models.go
new file mode 100644
index 0000000..d74df74
--- /dev/null
+++ b/components/neo/internal/exploit/models.go
@@ -0,0 +1,70 @@
+package exploit
+
+import (
+ "time"
+
+ "github.com/prometheus/client_golang/prometheus"
+ "github.com/samber/lo"
+
+ "github.com/c4t-but-s4d/neo/v2/internal/models"
+)
+
+type FarmRequest struct {
+ Flag string `json:"flag"`
+ Exploit string `json:"sploit"`
+ Team string `json:"team"`
+}
+
+type FullResult struct {
+ Exploit *models.Exploit
+ Target *models.Target
+ Flag string
+}
+
+func NewFullResult(exploit *models.Exploit, target *models.Target, flag string) *FullResult {
+ return &FullResult{
+ Exploit: exploit,
+ Target: target,
+ Flag: flag,
+ }
+}
+
+func (r *FullResult) FarmRequest() *FarmRequest {
+ return &FarmRequest{
+ Flag: r.Flag,
+ Exploit: "[neo] " + r.Exploit.ID,
+ Team: r.Target.ID,
+ }
+}
+
+func (r *FullResult) MetricLabels() prometheus.Labels {
+ return lo.Assign(r.Exploit.MetricLabels(), r.Target.MetricLabels())
+}
+
+type State struct {
+ ID string
+ Version int64
+ Dir string
+ Path string
+ Disabled bool
+ Endless bool
+ RunEvery time.Duration
+ LastRun time.Time
+ ScaledTimeout time.Duration
+ Timeout time.Duration
+}
+
+func (s *State) ExploitType() models.ExploitType {
+ if s.Endless {
+ return models.ExploitTypeEndless
+ }
+ return models.ExploitTypeRecurrent
+}
+
+func (s *State) ToModel() *models.Exploit {
+ return &models.Exploit{
+ ID: s.ID,
+ Version: s.Version,
+ Type: s.ExploitType(),
+ }
+}
diff --git a/components/neo/internal/exploit/runner.go b/components/neo/internal/exploit/runner.go
new file mode 100644
index 0000000..5f01108
--- /dev/null
+++ b/components/neo/internal/exploit/runner.go
@@ -0,0 +1,459 @@
+package exploit
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "os"
+ "os/exec"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/google/go-cmp/cmp"
+ "github.com/google/go-cmp/cmp/cmpopts"
+ "github.com/prometheus/client_golang/prometheus"
+ "github.com/prometheus/client_golang/prometheus/push"
+ "github.com/prometheus/common/expfmt"
+ "github.com/sirupsen/logrus"
+
+ "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/models"
+ "github.com/c4t-but-s4d/neo/v2/internal/queue"
+ "github.com/c4t-but-s4d/neo/v2/pkg/joblogger"
+ epb "github.com/c4t-but-s4d/neo/v2/proto/go/exploits"
+)
+
+var (
+ ErrFinishedUnexpectedly = errors.New("служба завершилась неожиданно")
+)
+
+func NewRunner(
+ clientID string,
+ maxJobs, maxEndlessJobs int,
+ timeoutScaleTarget float64,
+ clientConfig *client.Config,
+ c *client.Client,
+ logSender joblogger.Sender,
+) *Runner {
+ var metricsPusher *push.Pusher
+ if strings.TrimSpace(clientConfig.MetricsHost) != "" {
+ metricsPusher = push.New(clientConfig.MetricsHost, "neo_runner").
+ Grouping("client_id", clientID).
+ Format(expfmt.FmtOpenMetrics_1_0_0).
+ Gatherer(prometheus.DefaultGatherer)
+ }
+ return &Runner{
+ storage: NewStorage(NewCache(), clientConfig.ExploitDir, c),
+ cfg: &config.ExploitsConfig{},
+ client: c,
+
+ maxJobs: maxJobs,
+ maxEndlessJobs: maxEndlessJobs,
+ timeoutScaleTarget: timeoutScaleTarget,
+ allowBroadcastCommands: clientConfig.AllowBroadcastCommands,
+
+ singleRuns: make(chan *epb.SingleRunSubscribeResponse),
+ restarts: make(chan struct{}, 1),
+ logSender: logSender,
+ metricsPusher: metricsPusher,
+ metrics: NewMetrics("neo"),
+ logger: logrus.WithField("component", "exploit-runner"),
+ }
+}
+
+type Runner struct {
+ storage *Storage
+ teams map[string]string
+ cfg *config.ExploitsConfig
+ client *client.Client
+ logSender joblogger.Sender
+ metricsPusher *push.Pusher
+ metrics *Metrics
+
+ maxJobs int
+ maxEndlessJobs int
+ timeoutScaleTarget float64
+ allowBroadcastCommands bool
+
+ simpleLoop *submitLoop
+ endlessLoop *submitLoop
+
+ singleRuns chan *epb.SingleRunSubscribeResponse
+ restarts chan struct{}
+
+ logger *logrus.Entry
+}
+
+func (r *Runner) Run(ctx context.Context) error {
+ r.printGreeting()
+
+ state, err := r.pingHeartbeat(ctx)
+ if err != nil {
+ return fmt.Errorf("отправка сигнала проверки связи: %w", err)
+ }
+ if err := r.onServerStateUpdate(ctx, state); err != nil {
+ return fmt.Errorf("обновление состояния сервера: %w", err)
+ }
+
+ // Очистить накопленные сигналы обновления.
+ select {
+ case <-r.restarts:
+ default:
+ }
+
+ wg := sync.WaitGroup{}
+
+ srvCtx, srvCancel := context.WithCancel(ctx)
+ defer srvCancel()
+
+ // Ошибка не завершает работу: циклы повторяют попытки бесконечно.
+ wg.Add(3)
+ go func() {
+ defer wg.Done()
+ if err := retryLoop(srvCtx, "broadcast", -1, 3*time.Second, r.listenBroadcast); err != nil && !errors.Is(err, context.Canceled) {
+ r.logger.WithError(err).Error("Ошибка цикла приема рассылок")
+ }
+ }()
+ go func() {
+ defer wg.Done()
+ if err := retryLoop(srvCtx, "single runs", -1, 3*time.Second, r.listenSingleRuns); err != nil && !errors.Is(err, context.Canceled) {
+ r.logger.WithError(err).Error("Ошибка цикла приема одиночных запусков")
+ }
+ }()
+ go func() {
+ defer wg.Done()
+ r.startPushingMetrics(srvCtx)
+ }()
+ defer func() {
+ r.logger.Info("Остановка вспомогательных служб")
+ srvCancel()
+ r.logger.Info("Ожидание остановки вспомогательных служб")
+ wg.Wait()
+ }()
+
+ r.eventLoop(ctx)
+
+ r.logger.Info("Worker завершает работу, отправка сигнала выхода")
+ leaveCtx, cancel := context.WithTimeout(context.Background(), time.Second*5)
+ defer cancel()
+ if err := r.client.Leave(leaveCtx); err != nil {
+ return fmt.Errorf("не удалось отправить сигнал выхода: %w", err)
+ }
+
+ return nil
+}
+
+func (r *Runner) eventLoop(ctx context.Context) {
+ defer r.logger.Info("Цикл событий остановлен")
+
+ var loopsWg sync.WaitGroup
+ loopsCancel := r.runWorkers(ctx, &loopsWg)
+
+ stopLoops := func() {
+ r.logger.Info("Остановка циклов отправки")
+ loopsCancel()
+ r.logger.Info("Ожидание остановки циклов отправки")
+ loopsWg.Wait()
+ }
+ defer stopLoops()
+
+ r.scheduleEndlessExploits()
+
+ runTicker := time.NewTicker(time.Second)
+ defer runTicker.Stop()
+
+ savedPingEvery := r.cfg.PingEvery
+ pingTicker := time.NewTicker(savedPingEvery)
+
+ for {
+ select {
+ case <-pingTicker.C:
+ r.logger.Debug("Отправка сигнала проверки связи")
+ state, err := r.pingHeartbeat(ctx)
+ if err != nil {
+ r.logger.WithError(err).Error("Ошибка периодической проверки связи")
+ return
+ }
+ if err := r.onServerStateUpdate(ctx, state); err != nil {
+ r.logger.WithError(err).Error("Ошибка обработки обновления состояния сервера")
+ } else if r.cfg.PingEvery != savedPingEvery {
+ savedPingEvery = r.cfg.PingEvery
+ pingTicker.Reset(savedPingEvery)
+ }
+
+ case <-r.restarts:
+ r.logger.Info("Получен запрос на перезапуск циклов")
+ stopLoops()
+ loopsCancel = r.runWorkers(ctx, &loopsWg)
+ r.scheduleEndlessExploits()
+
+ case <-runTicker.C:
+ r.logger.Debug("Планирование периодических эксплойтов")
+ r.scheduleRecurrentExploits()
+
+ case req := <-r.singleRuns:
+ r.logger.Infof("Обработка одиночного запуска эксплойта %s", req.GetExploitId())
+
+ // Обновить конфигурацию, чтобы запрошенный эксплойт был загружен.
+ if _, err := r.pingHeartbeat(ctx); err != nil {
+ r.logger.WithError(err).Error("Ошибка обновления конфигурации перед одиночным запуском")
+ }
+ if err := r.submitExploit(r.simpleLoop, req.ExploitId); err != nil {
+ r.logger.WithError(err).Errorf("Ошибка добавления эксплойта %s в очередь одиночного запуска", req.ExploitId)
+ }
+
+ case <-ctx.Done():
+ return
+ }
+ }
+}
+
+func (r *Runner) pingHeartbeat(ctx context.Context) (*epb.ServerState, error) {
+ state, err := r.client.Heartbeat(ctx)
+ if err != nil {
+ return nil, fmt.Errorf("отправка сигнала проверки связи: %w", err)
+ }
+ return state, nil
+}
+
+func (r *Runner) runWorkers(ctx context.Context, wg *sync.WaitGroup) context.CancelFunc {
+ r.simpleLoop = newSubmitLoop(r.maxJobs, r.cfg, r.metrics, queue.NewSimpleQueueFactory())
+ r.endlessLoop = newSubmitLoop(r.maxEndlessJobs, r.cfg, r.metrics, queue.NewEndlessQueueFactory())
+
+ loopsCtx, loopsCancel := context.WithCancel(ctx)
+ r.logger.Info("Запуск циклов отправки")
+ wg.Add(2)
+ go func() {
+ defer wg.Done()
+ r.simpleLoop.Start(loopsCtx)
+ r.logger.Info("Обычный цикл отправки завершен")
+ }()
+ go func() {
+ defer wg.Done()
+ r.endlessLoop.Start(loopsCtx)
+ r.logger.Info("Бесконечный цикл отправки завершен")
+ }()
+ return loopsCancel
+}
+
+func (r *Runner) scheduleRecurrentExploits() {
+ exs := r.storage.Exploits()
+ now := time.Now()
+ for _, ex := range exs {
+ if ex.Disabled || ex.Endless {
+ continue
+ }
+ if ex.LastRun.Add(ex.RunEvery).After(now) {
+ continue
+ }
+ if err := r.submitExploit(r.simpleLoop, ex.ID); err != nil {
+ r.logger.WithError(err).Errorf("Ошибка добавления периодического эксплойта %s в очередь", ex.ID)
+ }
+ }
+}
+
+func (r *Runner) scheduleEndlessExploits() {
+ exs := r.storage.Exploits()
+ for _, ex := range exs {
+ if ex.Disabled || !ex.Endless {
+ continue
+ }
+ if err := r.submitExploit(r.endlessLoop, ex.ID); err != nil {
+ r.logger.WithError(err).Errorf("Ошибка добавления бесконечного эксплойта %s в очередь, перезапуск циклов", ex.ID)
+ // Перезапустить циклы, чтобы бесконечный эксплойт не завис в очереди.
+ // Перезапуск также повторяет запуск и помогает обнаруживать ошибки по журналам.
+ r.restartLoops()
+ }
+ }
+}
+
+func (r *Runner) submitExploit(l *submitLoop, id string) error {
+ ex, ok := r.storage.Exploit(id)
+ if !ok {
+ return fmt.Errorf("эксплойт %v не найден", id)
+ }
+
+ jobs := CreateExploitJobs(ex, r.teams, r.cfg.Environ, r.logSender)
+ for _, t := range jobs {
+ r.logger.Infof("Добавление задания: %v", t)
+ if err := l.Add(t); err != nil {
+ return fmt.Errorf("добавление задания в очередь: %w", err)
+ }
+ }
+
+ r.storage.UpdateLastRun(ex.ID, time.Now())
+ return nil
+}
+
+func (r *Runner) restartLoops() {
+ select {
+ case r.restarts <- struct{}{}:
+ default:
+ }
+}
+
+func (r *Runner) listenBroadcast(ctx context.Context) error {
+ resp, err := r.client.ListenBroadcasts(ctx)
+ if err != nil {
+ return fmt.Errorf("запрос потока рассылок: %w", err)
+ }
+ for {
+ select {
+ case cmd, ok := <-resp:
+ if !ok {
+ r.logger.Error("Канал рассылок закрыт")
+ return ErrFinishedUnexpectedly
+ }
+ r.logger.Info("Получена команда рассылки")
+ if err := r.handleBroadcastCommand(ctx, cmd); err != nil {
+ r.logger.WithError(err).Error("Ошибка обработки команды рассылки")
+ }
+ case <-ctx.Done():
+ return ctx.Err()
+ }
+ }
+}
+
+func (r *Runner) listenSingleRuns(ctx context.Context) error {
+ resp, err := r.client.ListenSingleRuns(ctx)
+ if err != nil {
+ return fmt.Errorf("запрос потока одиночных запусков: %w", err)
+ }
+ for {
+ select {
+ case req, ok := <-resp:
+ if !ok {
+ r.logger.Error("Канал одиночных запусков закрыт")
+ return ErrFinishedUnexpectedly
+ }
+ r.logger.Infof("Получен запрос на одиночный запуск эксплойта %s", req.GetExploitId())
+ r.singleRuns <- req
+ case <-ctx.Done():
+ return ctx.Err()
+ }
+ }
+}
+
+func (r *Runner) startPushingMetrics(ctx context.Context) {
+ if r.metricsPusher == nil {
+ return
+ }
+ t := time.NewTicker(time.Second * 1)
+ defer t.Stop()
+ for {
+ select {
+ case <-t.C:
+ if err := r.metricsPusher.PushContext(ctx); err != nil {
+ r.logger.WithError(err).Error("Ошибка отправки метрик")
+ }
+ case <-ctx.Done():
+ return
+ }
+ }
+}
+
+func (r *Runner) handleBroadcastCommand(ctx context.Context, cmd *epb.BroadcastSubscribeResponse) error {
+ if !r.allowBroadcastCommands {
+ return fmt.Errorf("выполнение широковещательных shell-команд отключено")
+ }
+ if cmd == nil || strings.TrimSpace(cmd.Command) == "" {
+ return fmt.Errorf("пустая shell-команда")
+ }
+ c := exec.CommandContext(ctx, "/bin/bash", "-c", cmd.Command)
+ c.Stdout = os.Stdout
+ c.Stderr = os.Stderr
+ if err := c.Run(); err != nil {
+ return fmt.Errorf("выполнение команды: %w", err)
+ }
+ return nil
+}
+
+func (r *Runner) onServerStateUpdate(ctx context.Context, state *epb.ServerState) error {
+ cfg, err := config.FromProto(state.Config)
+ if err != nil {
+ return fmt.Errorf("разбор конфигурации: %w", err)
+ }
+ r.cfg = cfg
+
+ cid := r.client.ID
+ teamsChanged := false
+ if ipbuck, ok := state.ClientTeamMap[cid]; !ok {
+ r.logger.Warning("Клиент отсутствует в списке команд")
+ } else {
+ if diff := cmp.Diff(r.teams, ipbuck.Teams, cmpopts.EquateEmpty()); diff != "" {
+ r.teams = ipbuck.Teams
+ teamsChanged = true
+ r.logger.Info("Состав команд изменился, запланирован перезапуск циклов")
+ r.restartLoops()
+ }
+ r.metrics.Teams.Set(float64(len(r.teams)))
+ }
+
+ exploitsChanged := r.storage.UpdateExploits(ctx, state.Exploits)
+ if r.timeoutScaleTarget > 0 && (exploitsChanged || teamsChanged) {
+ r.storage.ScaleTimeouts(r.maxJobs, len(r.teams), r.timeoutScaleTarget)
+ }
+
+ if exploitsChanged {
+ r.logger.Info("Список эксплойтов изменился, запланирован перезапуск циклов")
+ r.restartLoops()
+ }
+
+ return nil
+}
+
+func (r *Runner) printGreeting() {
+ fmt.Println(` _
+ ___| |__ ___ _ __ ___ ___ _ __ _ _ _ __ _ __ ___ _ __
+ / __| '_ \/ __| | '_ \ / _ \/ _ \ | '__| | | | '_ \| '_ \ / _ \ '__|
+ | (__| |_) \__ \ | | | | __/ (_) | | | | |_| | | | | | | | __/ |
+ \___|_.__/|___/ |_| |_|\___|\___/ |_| \__,_|_| |_|_| |_|\___|_|
+ `)
+}
+
+func CreateExploitJobs(
+ ex *State,
+ teams map[string]string,
+ environ []string,
+ sender joblogger.Sender,
+) (jobs []*queue.Job) {
+ for id, ip := range teams {
+ jobs = append(jobs, queue.NewJob(
+ models.NewExploit(ex.ID, ex.Version, ex.ExploitType()),
+ models.NewTarget(id, ip),
+ ex.Path,
+ ex.Dir,
+ environ,
+ ex.ScaledTimeout,
+ joblogger.New(ex.ID, ex.Version, ip, sender),
+ ))
+ }
+ return
+}
+
+func retryLoop(ctx context.Context, name string, retries int, interval time.Duration, f func(ctx context.Context) error) error {
+ t := time.NewTimer(interval)
+ defer t.Stop()
+
+ var err error
+ for attempts := 0; retries == -1 || attempts < retries; attempts++ {
+ logrus.Infof("Запуск цикла %s", name)
+ err = f(ctx)
+ if err == nil || errors.Is(err, context.Canceled) {
+ logrus.Infof("Цикл %s завершает работу", name)
+ return err
+ }
+ if retries == -1 || attempts+1 < retries {
+ logrus.Errorf("Цикл %s завершился с ошибкой %v, перезапуск", name, err)
+ t.Reset(interval)
+ select {
+ case <-t.C:
+ case <-ctx.Done():
+ return ctx.Err()
+ }
+ }
+ }
+ return err
+}
diff --git a/components/neo/internal/exploit/runner_test.go b/components/neo/internal/exploit/runner_test.go
new file mode 100644
index 0000000..a4c8d21
--- /dev/null
+++ b/components/neo/internal/exploit/runner_test.go
@@ -0,0 +1,134 @@
+package exploit
+
+import (
+ "context"
+ "io"
+ "testing"
+ "time"
+
+ "github.com/prometheus/client_golang/prometheus"
+ "github.com/sirupsen/logrus"
+ "github.com/stretchr/testify/require"
+ "google.golang.org/protobuf/types/known/durationpb"
+
+ "github.com/c4t-but-s4d/neo/v2/internal/client"
+ epb "github.com/c4t-but-s4d/neo/v2/proto/go/exploits"
+)
+
+func TestRunner_onServerStateUpdateRescalesOnTeamChange(t *testing.T) {
+ st, cleanup := mockStorage()
+ defer func() {
+ require.NoError(t, cleanup())
+ }()
+ st.cache.Update([]*State{{
+ ID: "check",
+ Version: 1,
+ RunEvery: time.Minute,
+ Timeout: time.Minute,
+ ScaledTimeout: time.Minute,
+ }})
+
+ r := &Runner{
+ storage: st,
+ client: &client.Client{ID: "worker"},
+ maxJobs: 1,
+ timeoutScaleTarget: 1,
+ teams: map[string]string{},
+ restarts: make(chan struct{}, 1),
+ metrics: &Metrics{Teams: prometheus.NewGauge(prometheus.GaugeOpts{Name: "neo_test_teams", Help: "team count"})},
+ logger: logrus.NewEntry(logrus.New()),
+ }
+
+ state := &epb.ServerState{
+ Config: &epb.Config{
+ FlagRegexp: ".*",
+ PingEvery: durationpb.New(time.Minute),
+ SubmitEvery: durationpb.New(time.Second),
+ },
+ ClientTeamMap: map[string]*epb.TeamBucket{
+ "worker": {Teams: map[string]string{}},
+ },
+ Exploits: []*epb.ExploitState{{ExploitId: "check", Version: 1}},
+ }
+
+ // Эксплойт уже загружен, поэтому повторное состояние не меняет его версию.
+ require.NoError(t, r.onServerStateUpdate(context.Background(), state))
+ got, ok := st.Exploit("check")
+ require.True(t, ok)
+ require.Equal(t, time.Minute, got.ScaledTimeout)
+
+ state.ClientTeamMap["worker"] = &epb.TeamBucket{Teams: map[string]string{
+ "team-a": "192.0.2.1",
+ "team-b": "192.0.2.2",
+ }}
+ require.NoError(t, r.onServerStateUpdate(context.Background(), state))
+
+ got, ok = st.Exploit("check")
+ require.True(t, ok)
+ require.Equal(t, time.Minute, got.Timeout)
+ require.Equal(t, 30*time.Second, got.ScaledTimeout)
+}
+
+func Test_retryLoop(t *testing.T) {
+ tests := []struct {
+ name string
+ retries int
+ doRetries int
+ returnErr error
+ lastErr error
+ wantErr error
+ }{
+ {
+ "simple",
+ 1,
+ 1,
+ ErrFinishedUnexpectedly,
+ nil,
+ nil,
+ },
+ {
+ "endless retries",
+ -1,
+ 100,
+ ErrFinishedUnexpectedly,
+ nil,
+ nil,
+ },
+ {
+ "return last error",
+ 1,
+ 5,
+ io.EOF,
+ nil,
+ io.EOF,
+ },
+ {
+ "context cancelled",
+ 5,
+ 3,
+ ErrFinishedUnexpectedly,
+ context.Canceled,
+ context.Canceled,
+ },
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ cnt := 0
+ f := func(context.Context) error {
+ cnt++
+ if cnt < tt.doRetries {
+ return tt.returnErr
+ }
+ return tt.lastErr
+ }
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ require.ErrorIs(t, retryLoop(ctx, "test", tt.retries, time.Millisecond, f), tt.wantErr)
+ if tt.retries != -1 && tt.doRetries > tt.retries {
+ require.Equal(t, tt.retries, cnt)
+ } else {
+ require.Equal(t, tt.doRetries, cnt)
+ }
+ })
+ }
+}
diff --git a/components/neo/internal/exploit/storage.go b/components/neo/internal/exploit/storage.go
new file mode 100644
index 0000000..30094c1
--- /dev/null
+++ b/components/neo/internal/exploit/storage.go
@@ -0,0 +1,305 @@
+package exploit
+
+import (
+ "context"
+ "fmt"
+ "io"
+ "math"
+ "os"
+ "path/filepath"
+ "strings"
+ "time"
+
+ "github.com/sirupsen/logrus"
+
+ "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"
+)
+
+func NewStorage(cache *Cache, exploitDir string, client *client.Client) *Storage {
+ return &Storage{
+ cache: cache,
+ exploitDir: exploitDir,
+ client: client,
+ }
+}
+
+type Storage struct {
+ cache *Cache
+ exploitDir string
+ client *client.Client
+}
+
+func (s *Storage) Exploits() (res []*State) {
+ return s.cache.Exploits()
+}
+
+func (s *Storage) Exploit(id string) (res *State, ok bool) {
+ return s.cache.Exploit(id)
+}
+
+func (s *Storage) UpdateLastRun(exploitID string, t time.Time) {
+ s.cache.UpdateLastRun(exploitID, t)
+}
+
+func (s *Storage) UpdateExploits(ctx context.Context, exs []*epb.ExploitState) bool {
+ diff := s.cache.Diff(exs)
+ if len(diff) == 0 {
+ return false
+ }
+
+ logrus.Infof("Обнаружены обновленные эксплойты: %d", len(diff))
+ states := make([]*State, 0, len(diff))
+ for _, ex := range diff {
+ st, err := s.updateExploit(ctx, ex.ExploitId)
+ if err != nil {
+ logrus.Errorf("Не удалось обновить или скачать эксплойт %s:%d: %v", ex.ExploitId, ex.Version, err)
+ continue
+ }
+ states = append(states, st)
+ }
+ s.cache.Update(states)
+ return true
+}
+
+func (s *Storage) ScaleTimeouts(workers, teams int, target float64) {
+ exploits := s.cache.Exploits()
+
+ // Alpha показывает долю времени worker, занятую заданиями.
+ // Например, при тайм-ауте 10 секунд и запуске каждые 20 секунд одно
+ // задание занимает половину времени на каждую команду. При четырех командах
+ // это соответствует двум полностью занятым worker.
+ // В этом примере Alpha равен 10/20 = 0.5; при двух worker итог будет
+ // 0.5 * 4 / 2 = 1, то есть все worker будут заняты.
+ // Если значение ниже цели, тайм-ауты можно увеличить; если выше -
+ // пропорционально уменьшить относительно исходных значений.
+ // Target задает желаемое Alpha. Значение 1 обычно неэффективно, так как
+ // задания часто завершаются до тайм-аута.
+ // Бесконечные задания не масштабируются.
+ // Тайм-ауты округляются вниз до целой секунды.
+ fallback := func(reason string) {
+ logrus.Warnf("Масштабирование тайм-аутов пропущено (%s), используются исходные значения", reason)
+ for _, ex := range exploits {
+ if ex.Endless {
+ continue
+ }
+ newTimeout := positiveTimeout(ex.Timeout)
+ logrus.Infof("Тайм-аут эксплойта %s: %s -> %s", ex.ID, ex.ScaledTimeout, newTimeout)
+ ex.ScaledTimeout = newTimeout
+ }
+ }
+
+ if workers <= 0 || teams <= 0 || !isPositiveFinite(target) {
+ fallback("некорректные число worker, число команд или цель")
+ return
+ }
+
+ alpha := 0.0
+ hasTimedExploits := false
+ for _, ex := range exploits {
+ if ex.Endless {
+ continue
+ }
+ hasTimedExploits = true
+ if ex.Timeout <= 0 || ex.RunEvery <= 0 {
+ fallback("исходный тайм-аут или интервал неположителен")
+ return
+ }
+
+ load := float64(ex.Timeout) / float64(ex.RunEvery)
+ if !isPositiveFinite(load) {
+ fallback("нагрузка эксплойта не является конечной")
+ return
+ }
+ alpha += load
+ if !isPositiveFinite(alpha) {
+ fallback("суммарная нагрузка не является конечной")
+ return
+ }
+ }
+ if !hasTimedExploits {
+ return
+ }
+
+ alpha *= float64(teams) / float64(workers)
+ if !isPositiveFinite(alpha) {
+ fallback("суммарная нагрузка равна нулю или не является конечной")
+ return
+ }
+ logrus.Infof("Масштабирование тайм-аутов: alpha = %.2f, цель = %.2f", alpha, target)
+
+ scaleFactor := target / alpha
+ if !isPositiveFinite(scaleFactor) {
+ fallback("коэффициент масштабирования не является конечным")
+ return
+ }
+
+ const maxDurationSeconds = float64((1<<63 - 1) / int64(time.Second))
+ for _, ex := range exploits {
+ if ex.Endless {
+ continue
+ }
+
+ scaledSeconds := float64(ex.Timeout) / float64(time.Second) * scaleFactor
+ newTimeout := positiveTimeout(ex.Timeout)
+ if math.IsNaN(scaledSeconds) || math.IsInf(scaledSeconds, 0) || scaledSeconds > maxDurationSeconds {
+ logrus.Warnf("Результат масштабирования эксплойта %s вне допустимого диапазона, используется исходный тайм-аут", ex.ID)
+ } else {
+ // Тайм-ауты округляются вниз до целой секунды, но не могут быть меньше секунды.
+ seconds := math.Floor(scaledSeconds)
+ if seconds < 1 {
+ seconds = 1
+ }
+ newTimeout = time.Duration(seconds) * time.Second
+ }
+
+ logrus.Infof("Тайм-аут эксплойта %s: %s -> %s", ex.ID, ex.ScaledTimeout, newTimeout)
+ ex.ScaledTimeout = newTimeout
+ }
+}
+
+func isPositiveFinite(value float64) bool {
+ return value > 0 && !math.IsNaN(value) && !math.IsInf(value, 0)
+}
+
+func positiveTimeout(timeout time.Duration) time.Duration {
+ if timeout > 0 {
+ return timeout
+ }
+ return time.Second
+}
+
+func (s *Storage) updateExploit(ctx context.Context, exploitID string) (*State, error) {
+ if err := validateExploitID(exploitID); err != nil {
+ return nil, err
+ }
+ // Получить актуальное состояние эксплойта.
+ resp, err := s.client.Exploit(ctx, exploitID)
+ if err != nil {
+ return nil, fmt.Errorf("запрос состояния эксплойта: %w", err)
+ }
+
+ state := resp.State
+ if state == nil {
+ return nil, fmt.Errorf("состояние эксплойта отсутствует")
+ }
+ if state.File == nil {
+ return nil, fmt.Errorf("файл эксплойта отсутствует")
+ }
+ if state.Config == nil {
+ return nil, fmt.Errorf("конфигурация эксплойта отсутствует")
+ }
+ if state.ExploitId != exploitID || state.Version <= 0 {
+ return nil, fmt.Errorf("идентификатор или версия эксплойта недопустимы")
+ }
+
+ if err := os.MkdirAll(s.exploitDir, 0700); err != nil {
+ return nil, fmt.Errorf("создание каталога эксплойтов: %w", err)
+ }
+
+ // Создать временный файл для загрузки.
+ f, err := os.CreateTemp(s.exploitDir, "DOWNLOAD")
+ if err != nil {
+ return nil, fmt.Errorf("создание временного файла: %w", err)
+ }
+ defer func() {
+ _ = f.Close()
+ _ = os.Remove(f.Name())
+ }()
+
+ // Загрузить исполняемый файл во временный файл.
+ if err := s.client.DownloadFile(ctx, state.File, f); err != nil {
+ return nil, fmt.Errorf("загрузка файла: %w", err)
+ }
+ // Перейти в начало файла, чтобы использовать его как io.Reader.
+ if _, err := f.Seek(0, io.SeekStart); err != nil {
+ return nil, fmt.Errorf("переход к началу загруженного файла: %w", err)
+ }
+
+ oPath := filepath.Join(s.exploitDir, fmt.Sprintf("%s_%d", state.ExploitId, state.Version))
+ if _, err := os.Lstat(oPath); err == nil {
+ return nil, fmt.Errorf("каталог этой версии эксплойта уже существует")
+ } else if !os.IsNotExist(err) {
+ return nil, fmt.Errorf("проверка каталога версии эксплойта: %w", err)
+ }
+ keepFiles := false
+ defer func() {
+ if !keepFiles {
+ _ = os.RemoveAll(oPath)
+ }
+ }()
+ if state.Config.IsArchive && (strings.ContainsAny(state.Config.Entrypoint, "\\\x00") || !filepath.IsLocal(state.Config.Entrypoint)) {
+ return nil, fmt.Errorf("путь к точке входа архива недопустим")
+ }
+
+ var entryPath string
+ if entryPath, err = saveExploit(f, oPath, state.Config); err != nil {
+ return nil, fmt.Errorf("сохранение эксплойта: %w", err)
+ }
+ logrus.Infof("Каталог эксплойта: %s, точка входа: %s", oPath, entryPath)
+
+ if entryPath, err = prepareEntry(entryPath); err != nil {
+ return nil, fmt.Errorf("подготовка точки входа: %w", err)
+ }
+
+ res := &State{
+ ID: state.ExploitId,
+ Version: state.Version,
+ Dir: "",
+ Path: entryPath,
+ Disabled: state.Config.Disabled,
+ Endless: state.Config.Endless,
+ RunEvery: state.Config.RunEvery.AsDuration(),
+ ScaledTimeout: state.Config.Timeout.AsDuration(),
+ Timeout: state.Config.Timeout.AsDuration(),
+ }
+ if state.Config.IsArchive {
+ res.Dir = oPath
+ }
+ keepFiles = true
+ return res, nil
+}
+
+func saveExploit(f *os.File, outPath string, cfg *epb.ExploitConfiguration) (string, error) {
+ if cfg.IsArchive {
+ if err := archive.Untar(outPath, f); err != nil {
+ return "", fmt.Errorf("распаковка архива: %w", err)
+ }
+ return filepath.Join(outPath, cfg.Entrypoint), nil
+ }
+
+ if err := f.Close(); err != nil {
+ return "", fmt.Errorf("закрытие файла: %w", err)
+ }
+ if err := os.Link(f.Name(), outPath); err != nil {
+ return "", fmt.Errorf("перемещение файла %s в %s: %w", f.Name(), outPath, err)
+ }
+ return outPath, nil
+}
+
+func prepareEntry(path string) (string, error) {
+ absPath, err := filepath.Abs(path)
+ if err != nil {
+ return "", fmt.Errorf("получение абсолютного пути: %w", err)
+ }
+ info, err := os.Lstat(absPath)
+ if err != nil {
+ return "", fmt.Errorf("проверка точки входа: %w", err)
+ }
+ if !info.Mode().IsRegular() {
+ return "", fmt.Errorf("точка входа не является обычным файлом")
+ }
+ if err := os.Chmod(absPath, 0755); err != nil {
+ return "", fmt.Errorf("установка разрешений файла: %w", err)
+ }
+ return absPath, nil
+}
+
+func validateExploitID(id string) error {
+ if id == "" || len(id) > 128 || id == "." || id == ".." ||
+ strings.ContainsAny(id, "/\\\x00") || !filepath.IsLocal(id) {
+ return fmt.Errorf("недопустимый идентификатор эксплойта")
+ }
+ return nil
+}
diff --git a/components/neo/internal/exploit/storage_test.go b/components/neo/internal/exploit/storage_test.go
new file mode 100644
index 0000000..5cbd13e
--- /dev/null
+++ b/components/neo/internal/exploit/storage_test.go
@@ -0,0 +1,343 @@
+package exploit
+
+import (
+ "fmt"
+ "io"
+ "math"
+ "os"
+ "path"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/google/go-cmp/cmp"
+ "github.com/google/go-cmp/cmp/cmpopts"
+ "github.com/stretchr/testify/require"
+
+ "github.com/c4t-but-s4d/neo/v2/pkg/archive"
+ epb "github.com/c4t-but-s4d/neo/v2/proto/go/exploits"
+)
+
+func mockStorage() (*Storage, func() error) {
+ name, err := os.MkdirTemp("", "testStorage")
+ if err != nil {
+ panic(err)
+ }
+
+ return NewStorage(NewCache(), name, nil), func() error {
+ if err != nil {
+ return fmt.Errorf("remove exploit storage: %w", os.RemoveAll(name))
+ }
+ return nil
+ }
+}
+
+func TestStorage_Exploit(t *testing.T) {
+ st, cleanup := mockStorage()
+ defer func() {
+ require.NoError(t, cleanup())
+ }()
+ st.cache.Update([]*State{
+ {ID: "1", Version: 1},
+ })
+ res, ok := st.Exploit("1")
+ require.True(t, ok)
+ require.EqualValues(t, 1, res.Version)
+}
+
+func Test_saveExploit(t *testing.T) {
+ f, err := os.CreateTemp("", "")
+ require.NoError(t, err)
+ defer func(f *os.File) {
+ require.Error(t, f.Close())
+ require.NoError(t, os.Remove(f.Name()))
+ }(f)
+ testData := []byte("test")
+ _, err = f.Write(testData)
+ require.NoError(t, err)
+
+ outfile := filepath.Join(t.TempDir(), "result")
+ cfg := &epb.ExploitConfiguration{
+ Entrypoint: "kek",
+ IsArchive: false,
+ }
+ entry, err := saveExploit(f, outfile, cfg)
+ require.NoError(t, err)
+ require.Equal(t, outfile, entry)
+
+ data, err := os.ReadFile(outfile)
+ require.NoError(t, err)
+
+ if diff := cmp.Diff(data, testData, cmpopts.EquateEmpty()); diff != "" {
+ t.Errorf("Runner.saveExploit() returned data mismatch (-want +got):\n%s", diff)
+ }
+}
+
+func Test_saveExploitArchive(t *testing.T) {
+ dir, err := os.MkdirTemp("", "TEMP_TAR")
+ require.NoError(t, err)
+
+ remove := func(name string) {
+ require.NoError(t, os.RemoveAll(name))
+ }
+
+ defer remove(dir)
+
+ writeFile := func(name string, content []byte) error {
+ f, err := os.Create(name)
+ if err != nil {
+ return fmt.Errorf("os.Create() got unexpected error = %w", err)
+ }
+ if _, err := f.Write(content); err != nil {
+ return fmt.Errorf("f.Write() got unexpected error = %w", err)
+ }
+ if err := f.Close(); err != nil {
+ return fmt.Errorf("f.Close() got unexpected error = %w", err)
+ }
+ return nil
+ }
+
+ exploitFile := "exp.py"
+ exploitData := []byte("print(1);")
+ require.NoError(t, writeFile(path.Join(dir, exploitFile), exploitData))
+
+ secondFile := "t.txt"
+ secondData := []byte("123")
+ require.NoError(t, writeFile(path.Join(dir, secondFile), secondData))
+
+ tarFile, err := os.CreateTemp("", "ARCHIVE")
+ require.NoError(t, err)
+ defer remove(tarFile.Name())
+
+ require.NoError(t, archive.Tar(dir, tarFile))
+
+ _, err = tarFile.Seek(0, io.SeekStart)
+ require.NoError(t, err)
+
+ outDir, err := os.MkdirTemp("", "TEMP_UNTAR")
+ require.NoError(t, err)
+
+ defer remove(outDir)
+
+ cfg := &epb.ExploitConfiguration{
+ Entrypoint: exploitFile,
+ IsArchive: true,
+ }
+
+ entry, err := saveExploit(tarFile, outDir, cfg)
+ require.NoError(t, err)
+
+ entryDir, entryPath := path.Split(entry)
+ entryDir = path.Clean(entryDir)
+
+ require.Equal(t, outDir, entryDir)
+ require.Equal(t, cfg.Entrypoint, entryPath)
+
+ entryContent, err := os.ReadFile(entry)
+ require.NoError(t, err)
+
+ if diff := cmp.Diff(exploitData, entryContent, cmpopts.EquateEmpty()); diff != "" {
+ t.Errorf("Runner.saveExploit() returned entrypoint data mismatch (-want +got):\n%s", diff)
+ }
+
+ additionalContent, err := os.ReadFile(path.Join(entryDir, secondFile))
+ require.NoError(t, err)
+
+ if diff := cmp.Diff(secondData, additionalContent, cmpopts.EquateEmpty()); diff != "" {
+ t.Errorf("Runner.saveExploit() returned additional data mismatch (-want +got):\n%s", diff)
+ }
+}
+
+func Test_prepareEntry(t *testing.T) {
+ f, err := os.CreateTemp("", "exec")
+ require.NoError(t, err)
+ defer func() {
+ require.NoError(t, os.Remove(f.Name()))
+ }()
+ require.NoError(t, f.Close())
+
+ entry, err := prepareEntry(f.Name())
+ require.NoError(t, err)
+ require.True(t, strings.Contains(entry, f.Name()))
+
+ fi, err := os.Stat(entry)
+ require.NoError(t, err)
+ // Файл должен быть исполняемым.
+ require.NotZero(t, fi.Mode()&0111)
+}
+
+func TestStorage_Scale(t *testing.T) {
+ st, cleanup := mockStorage()
+ defer func() {
+ require.NoError(t, cleanup())
+ }()
+
+ // При teams = 2 * workers таймаут задания должен уменьшиться вдвое.
+ st.cache.Update([]*State{
+ {
+ ID: "1",
+ Version: 1,
+ RunEvery: time.Minute,
+ ScaledTimeout: time.Minute,
+ Timeout: time.Minute,
+ },
+ })
+ st.ScaleTimeouts(10, 20, 1)
+
+ res, ok := st.Exploit("1")
+ require.True(t, ok)
+ require.EqualValues(t, 1, res.Version)
+ require.EqualValues(t, time.Minute, res.RunEvery)
+ require.EqualValues(t, 30*time.Second, res.ScaledTimeout)
+
+ // При workers = 2 * teams таймаут должен удвоиться.
+ st.ScaleTimeouts(20, 10, 1)
+
+ res, ok = st.Exploit("1")
+ require.True(t, ok)
+ require.EqualValues(t, time.Minute, res.RunEvery)
+ require.EqualValues(t, 2*time.Minute, res.ScaledTimeout)
+
+ // Новое задание сохраняет масштабирование исходных таймаутов.
+ st.cache.Update([]*State{
+ {
+ ID: "2",
+ Version: 1,
+ RunEvery: time.Minute,
+ ScaledTimeout: time.Minute,
+ Timeout: time.Minute,
+ },
+ })
+ st.ScaleTimeouts(20, 10, 1)
+
+ res, ok = st.Exploit("1")
+ require.True(t, ok)
+ require.EqualValues(t, time.Minute, res.RunEvery)
+ require.EqualValues(t, time.Minute, res.ScaledTimeout)
+
+ res, ok = st.Exploit("2")
+ require.True(t, ok)
+ require.EqualValues(t, time.Minute, res.RunEvery)
+ require.EqualValues(t, time.Minute, res.ScaledTimeout)
+
+ // При target = 2 таймауты заданий должны увеличиться.
+ st.ScaleTimeouts(20, 10, 2)
+
+ res, ok = st.Exploit("1")
+ require.True(t, ok)
+ require.EqualValues(t, 2*time.Minute, res.ScaledTimeout)
+
+ res, ok = st.Exploit("2")
+ require.True(t, ok)
+ require.EqualValues(t, 2*time.Minute, res.ScaledTimeout)
+}
+
+func TestStorage_ScaleTimeoutsInvalidInputs(t *testing.T) {
+ tests := []struct {
+ name string
+ workers int
+ teams int
+ target float64
+ timeout time.Duration
+ runEvery time.Duration
+ want time.Duration
+ }{
+ {
+ name: "zero workers preserves configured timeout",
+ workers: 0,
+ teams: 2,
+ target: 1,
+ timeout: time.Minute,
+ runEvery: time.Minute,
+ want: time.Minute,
+ },
+ {
+ name: "zero teams preserves configured timeout",
+ workers: 2,
+ teams: 0,
+ target: 1,
+ timeout: time.Minute,
+ runEvery: time.Minute,
+ want: time.Minute,
+ },
+ {
+ name: "zero alpha uses minimum timeout",
+ workers: 2,
+ teams: 2,
+ target: 1,
+ timeout: 0,
+ runEvery: time.Minute,
+ want: time.Second,
+ },
+ {
+ name: "zero interval preserves configured timeout",
+ workers: 2,
+ teams: 2,
+ target: 1,
+ timeout: time.Minute,
+ runEvery: 0,
+ want: time.Minute,
+ },
+ {
+ name: "non-finite target preserves configured timeout",
+ workers: 2,
+ teams: 2,
+ target: math.NaN(),
+ timeout: time.Minute,
+ runEvery: time.Minute,
+ want: time.Minute,
+ },
+ {
+ name: "infinite target preserves configured timeout",
+ workers: 2,
+ teams: 2,
+ target: math.Inf(1),
+ timeout: time.Minute,
+ runEvery: time.Minute,
+ want: time.Minute,
+ },
+ {
+ name: "subsecond result is clamped to one second",
+ workers: 1,
+ teams: 1,
+ target: math.SmallestNonzeroFloat64,
+ timeout: 30 * time.Second,
+ runEvery: 30 * time.Second,
+ want: time.Second,
+ },
+ {
+ name: "overflow preserves configured timeout",
+ workers: 1,
+ teams: 1,
+ target: math.MaxFloat64,
+ timeout: 30 * time.Second,
+ runEvery: 30 * time.Second,
+ want: 30 * time.Second,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ st, cleanup := mockStorage()
+ defer func() {
+ require.NoError(t, cleanup())
+ }()
+
+ st.cache.Update([]*State{{
+ ID: "check",
+ Version: 1,
+ RunEvery: tt.runEvery,
+ Timeout: tt.timeout,
+ ScaledTimeout: time.Minute,
+ }})
+
+ st.ScaleTimeouts(tt.workers, tt.teams, tt.target)
+
+ got, ok := st.Exploit("check")
+ require.True(t, ok)
+ require.Equal(t, tt.want, got.ScaledTimeout)
+ require.Greater(t, got.ScaledTimeout, time.Duration(0))
+ })
+ }
+}
diff --git a/components/neo/internal/exploit/submit_loop.go b/components/neo/internal/exploit/submit_loop.go
new file mode 100644
index 0000000..650cde9
--- /dev/null
+++ b/components/neo/internal/exploit/submit_loop.go
@@ -0,0 +1,186 @@
+package exploit
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "fmt"
+ "io"
+ "net/http"
+ "sync"
+ "time"
+
+ "github.com/sirupsen/logrus"
+
+ "github.com/c4t-but-s4d/neo/v2/internal/config"
+ "github.com/c4t-but-s4d/neo/v2/internal/queue"
+)
+
+const maxFarmResponseBytes = 1 << 20
+
+var farmHTTPClient = &http.Client{Timeout: 3 * time.Second}
+
+type submitLoop struct {
+ q queue.Queue
+ maxJobs int
+ cfg *config.ExploitsConfig
+ metrics *Metrics
+ factory queue.Factory
+
+ logger *logrus.Entry
+}
+
+func newSubmitLoop(
+ maxJobs int,
+ cfg *config.ExploitsConfig,
+ metrics *Metrics,
+ factory queue.Factory,
+) *submitLoop {
+ return &submitLoop{
+ q: factory.Create(maxJobs),
+ maxJobs: maxJobs,
+ factory: factory,
+ metrics: metrics,
+ cfg: cfg,
+
+ logger: logrus.WithFields(logrus.Fields{
+ "component": "submit_loop",
+ "queue": factory.Type(),
+ }),
+ }
+}
+
+// Start выполняется синхронно и блокируется до отмены контекста.
+func (l *submitLoop) Start(ctx context.Context) {
+ l.logger.Info("Запуск")
+ defer l.logger.Info("Остановлено")
+
+ var (
+ queueWG sync.WaitGroup
+ queueCtx context.Context
+ queueCancel context.CancelFunc
+ )
+ startQueue := func() {
+ l.logger.Info("Запуск очереди")
+ queueWG.Add(1)
+ queueCtx, queueCancel = context.WithCancel(ctx)
+
+ go func() {
+ defer queueWG.Done()
+ l.q.Start(queueCtx)
+ l.logger.Info("Очередь завершена")
+ }()
+ }
+ startQueue()
+
+ stopQueue := func() {
+ l.logger.Info("Остановка очереди")
+ queueCancel()
+ l.logger.Info("Ожидание остановки очереди")
+ queueWG.Wait()
+ }
+ defer stopQueue()
+
+ t := time.NewTicker(l.cfg.SubmitEvery)
+ defer t.Stop()
+
+ var results []*FullResult
+ flush := func() {
+ if len(results) == 0 {
+ return
+ }
+ l.logger.Infof("Отправка флагов: %d", len(results))
+ if err := l.submitResults(ctx, results); err != nil {
+ l.logger.Errorf("Не удалось отправить флаги Farm (%d): %v", len(results), err)
+ } else {
+ l.logger.Infof("Отправлено флагов в Farm: %d", len(results))
+
+ for _, result := range results {
+ l.metrics.FlagsSubmitted.With(result.MetricLabels()).Inc()
+ }
+
+ results = results[:0]
+ }
+ }
+ defer func() {
+ l.logger.Info("Последняя отправка накопленных флагов")
+ flush()
+ }()
+
+ queueCache := make(map[string]struct{})
+ for {
+ select {
+ case res, ok := <-l.q.Results():
+ if !ok {
+ l.logger.Warningf("Очередь завершилась неожиданно, перезапуск")
+ stopQueue()
+ l.q = l.factory.Create(l.maxJobs)
+ startQueue()
+ break
+ }
+
+ for _, match := range l.cfg.FlagRegexp.FindAll(res.Out, -1) {
+ flag := string(match)
+ if _, ok := queueCache[flag]; ok {
+ continue
+ }
+ results = append(results, NewFullResult(res.Exploit, res.Target, flag))
+ queueCache[flag] = struct{}{}
+ }
+ case <-t.C:
+ flush()
+ l.metrics.Queue.WithLabelValues(string(l.q.Type())).Set(float64(l.q.Size()))
+ case <-ctx.Done():
+ return
+ }
+ }
+}
+
+func (l *submitLoop) Add(t *queue.Job) error {
+ if err := l.q.Add(t); err != nil {
+ return fmt.Errorf("добавление задания в очередь: %w", err)
+ }
+ return nil
+}
+
+func (l *submitLoop) submitResults(ctx context.Context, results []*FullResult) error {
+ // Пока что используется только для стенда с возможностью внесения изменений.
+ url := l.cfg.FarmURL + "/api/post_flags"
+
+ toSend := make([]*FarmRequest, 0, len(results))
+ for _, fullRes := range results {
+ toSend = append(toSend, fullRes.FarmRequest())
+ }
+
+ data, err := json.Marshal(toSend)
+ if err != nil {
+ return fmt.Errorf("не удалось сериализовать результаты: %w", err)
+ }
+ req, err := http.NewRequestWithContext(ctx, "POST", url, bytes.NewReader(data))
+ if err != nil {
+ return fmt.Errorf("создание запроса: %w", err)
+ }
+ req.Header.Set("Authorization", l.cfg.FarmPassword)
+ req.Header.Add("X-Token", l.cfg.FarmPassword)
+ req.Header.Set("Content-Type", "application/json")
+ resp, err := farmHTTPClient.Do(req)
+ if err != nil {
+ return fmt.Errorf("выполнение запроса: %w", err)
+ }
+ defer func() {
+ if err := resp.Body.Close(); err != nil {
+ l.logger.Errorf("Ошибка закрытия ответа Farm: %v", err)
+ }
+ }()
+ read, err := io.Copy(io.Discard, io.LimitReader(resp.Body, maxFarmResponseBytes+1))
+ if err != nil {
+ return fmt.Errorf("чтение ответа Farm: %w", err)
+ }
+ if read > maxFarmResponseBytes {
+ return fmt.Errorf("ответ Farm превышает %d байт", maxFarmResponseBytes)
+ }
+ if resp.StatusCode != http.StatusOK {
+ return fmt.Errorf("Farm отклонил флаги, HTTP-код %d", resp.StatusCode)
+ }
+ return nil
+}
diff --git a/components/neo/internal/exploit/submit_loop_test.go b/components/neo/internal/exploit/submit_loop_test.go
new file mode 100644
index 0000000..ce6c229
--- /dev/null
+++ b/components/neo/internal/exploit/submit_loop_test.go
@@ -0,0 +1,372 @@
+package exploit
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "net/http"
+ "regexp"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/google/go-cmp/cmp"
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+ "go.uber.org/goleak"
+
+ "github.com/c4t-but-s4d/neo/v2/internal/config"
+ "github.com/c4t-but-s4d/neo/v2/internal/logger"
+ "github.com/c4t-but-s4d/neo/v2/internal/models"
+ "github.com/c4t-but-s4d/neo/v2/internal/queue"
+ "github.com/c4t-but-s4d/neo/v2/pkg/joblogger"
+ "github.com/c4t-but-s4d/neo/v2/pkg/neosync"
+ "github.com/c4t-but-s4d/neo/v2/pkg/testutils"
+)
+
+var (
+ errQueueFull = errors.New("queue is full")
+)
+
+func TestMain(m *testing.M) {
+ logger.Init()
+ goleak.VerifyTestMain(m)
+}
+
+func Test_newSubmitLoop(t *testing.T) {
+ q := newMockQueue()
+ factory := &mockQueueFactory{
+ q: q,
+ }
+ cfg := config.ExploitsConfig{
+ FarmURL: "127.0.0.1",
+ FarmPassword: "1234",
+ }
+
+ want := submitLoop{
+ q: q,
+ maxJobs: 5,
+ cfg: &cfg,
+ factory: factory,
+ }
+
+ got := newSubmitLoop(5, &cfg, NewMetrics(testutils.MetricsNamespace()), factory)
+
+ assert.Equal(t, want.maxJobs, got.maxJobs)
+ assert.Equal(t, want.cfg, got.cfg)
+ assert.Equal(t, want.q, got.q)
+}
+
+func Test_submitLoop_Add(t *testing.T) {
+ q := newMockQueue()
+
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ go q.Start(ctx)
+
+ factory := &mockQueueFactory{q: q}
+ cfg := config.ExploitsConfig{
+ FarmURL: "127.0.0.1",
+ FarmPassword: "1234",
+ }
+ sl := newSubmitLoop(1, &cfg, NewMetrics(testutils.MetricsNamespace()), factory)
+
+ sender := joblogger.NewRemoteSender(nil)
+ jobLogger := joblogger.New("id", 1, "127.0.0.1", sender)
+ job := queue.NewJob(
+ &models.Exploit{ID: "id", Version: 1, Type: models.ExploitTypeRecurrent},
+ &models.Target{ID: "12", IP: "127.0.0.1"},
+ "echo",
+ "",
+ nil,
+ time.Second*5,
+ jobLogger,
+ )
+ require.NoError(t, sl.Add(job), "Add() returned an unexpected error")
+
+ select {
+ case got := <-q.in:
+ require.Equal(t, got.String(), job.String(), "invalid job added")
+ default:
+ t.Errorf("Add(): queue is empty after adding job")
+ }
+}
+
+func Test_submitLoop_AddFullQueue(t *testing.T) {
+ q := &mockQueue{}
+ factory := &mockQueueFactory{q: q}
+
+ cfg := config.ExploitsConfig{
+ FarmURL: "127.0.0.1",
+ FarmPassword: "1234",
+ }
+ sl := newSubmitLoop(1, &cfg, NewMetrics(testutils.MetricsNamespace()), factory)
+
+ sender := joblogger.NewRemoteSender(nil)
+ jobLogger := joblogger.New("id", 1, "127.0.0.1", sender)
+ job := queue.NewJob(
+ &models.Exploit{ID: "id", Version: 1, Type: models.ExploitTypeRecurrent},
+ &models.Target{ID: "12", IP: "127.0.0.1"},
+ "echo",
+ "",
+ nil,
+ time.Second*5,
+ jobLogger,
+ )
+ // in/out are nil, so queue is always full.
+ require.ErrorIs(t, sl.Add(job), errQueueFull, "Add() did not return an error")
+}
+
+func Test_submitLoop_Run(t *testing.T) {
+ q := newMockQueue()
+ factory := &mockQueueFactory{q: q}
+
+ wg := sync.WaitGroup{}
+
+ wantResults := []*FarmRequest{
+ {
+ Flag: "AAAAA=",
+ Exploit: "[neo] test",
+ Team: "Target 1",
+ },
+ {
+ Flag: "BBBBB=",
+ Exploit: "[neo] another test",
+ Team: "Target 2",
+ },
+ }
+ outputs := []*queue.Output{
+ {
+ Exploit: &models.Exploit{ID: "test"},
+ Target: &models.Target{ID: "Target 1"},
+ Out: []byte("some large AAAAA= output"),
+ },
+ {
+ Exploit: &models.Exploit{ID: "another test"},
+ Target: &models.Target{ID: "Target 2"},
+ Out: []byte("some large BBBBB= output"),
+ },
+ }
+
+ wg.Add(1) // checker must be called once
+ checker := func(t *testing.T, r *http.Request) {
+ t.Helper()
+ t.Log("checker called")
+ defer t.Log("checker finished")
+ defer wg.Done()
+
+ auth := r.Header.Get("Authorization")
+ token := r.Header.Get("X-Token")
+ contentType := r.Header.Get("Content-Type")
+ require.Equal(t, "1234", auth, "Invalid auth header %v", auth)
+ require.Equal(t, auth, token, "Invalid X-Token header %v", token)
+ require.Equal(t, "application/json", contentType, "Invalid content type %v", contentType)
+
+ var results []*FarmRequest
+ err := json.NewDecoder(r.Body).Decode(&results)
+ require.NoError(t, err, "Could not json-decode request body: %v", err)
+
+ t.Logf("checker received results: %v", results)
+
+ diff := cmp.Diff(results, wantResults)
+ require.Equal(t, "", diff, "Invalid results returned: %v", diff)
+ }
+ s := testutils.NewCheckedTestServer(t, checker)
+ defer s.Close()
+
+ cfg := config.ExploitsConfig{
+ FarmURL: s.URL,
+ FarmPassword: "1234",
+ FlagRegexp: regexp.MustCompile("[AB]{5}="),
+ SubmitEvery: time.Second,
+ }
+ sl := newSubmitLoop(1, &cfg, NewMetrics(testutils.MetricsNamespace()), factory)
+
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+
+ slDone := make(chan struct{})
+ go func() {
+ defer close(slDone)
+ defer t.Logf("Submit loop stopped")
+ sl.Start(ctx)
+ }()
+
+ wg.Add(1) // outputs must be added
+ go func() {
+ defer wg.Done()
+ for _, out := range outputs {
+ t.Logf("sending output %v", out)
+ q.out <- out
+ }
+ }()
+
+ // Ждем результаты.
+ select {
+ case <-time.After(cfg.SubmitEvery * 2):
+ t.Errorf("Run(): test timed out")
+ case <-neosync.AwaitWG(&wg):
+ // Ждем завершения отправки.
+ time.Sleep(time.Millisecond * 200)
+ }
+
+ done := make(chan struct{})
+ go func() {
+ defer close(done)
+ cancel()
+ <-slDone // wait for submit loop to stop
+ }()
+
+ // Останавливаем очередь после обработки заданий.
+ select {
+ case <-time.After(time.Millisecond * 100):
+ t.Errorf("Run(): stop timed out")
+ case <-done:
+ }
+}
+
+func Test_submitLoop_submitResults(t *testing.T) {
+ tests := []struct {
+ name string
+ ctx context.Context
+ sendResults []*FullResult
+ wantResults []*FarmRequest
+ wantRequest bool
+ wantErr error
+ }{
+ {
+ "simple",
+ context.Background(),
+ []*FullResult{
+ {
+ &models.Exploit{ID: "exploit"},
+ &models.Target{ID: "team"},
+ "AAAAA=",
+ },
+ },
+ []*FarmRequest{
+ {
+ "AAAAA=",
+ "[neo] exploit",
+ "team",
+ },
+ },
+ true,
+ nil,
+ },
+ {
+ "cancelled context",
+ testutils.CanceledContext(),
+ []*FullResult{
+ {
+ &models.Exploit{ID: "exploit"},
+ &models.Target{ID: "team"},
+ "AAAAA=",
+ },
+ },
+ nil,
+ false,
+ context.Canceled,
+ },
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ s := testutils.NewCheckedTestServer(t, func(t *testing.T, r *http.Request) {
+ t.Helper()
+ t.Log("checker called")
+ defer t.Log("checker finished")
+
+ require.True(t, tt.wantRequest, "Unexpected request was made")
+
+ auth := r.Header.Get("Authorization")
+ token := r.Header.Get("X-Token")
+ contentType := r.Header.Get("Content-Type")
+ require.Equal(t, "1234", auth, "Invalid auth header %v", auth)
+ require.Equal(t, auth, token, "Invalid X-Token header %v", token)
+ require.Equal(t, "application/json", contentType, "Invalid content type %v", contentType)
+
+ var results []*FarmRequest
+ err := json.NewDecoder(r.Body).Decode(&results)
+ require.NoError(t, err, "Could not json-decode request body: %v", err)
+
+ t.Logf("checker received results: %v", results)
+
+ diff := cmp.Diff(results, tt.wantResults)
+ require.Equal(t, "", diff, "Invalid results returned: %v", diff)
+ })
+ defer s.Close()
+
+ loop := newSubmitLoop(
+ 1,
+ &config.ExploitsConfig{
+ FarmURL: s.URL,
+ FarmPassword: "1234",
+ },
+ NewMetrics(testutils.MetricsNamespace()),
+ &mockQueueFactory{},
+ )
+ require.ErrorIs(t, loop.submitResults(tt.ctx, tt.sendResults), tt.wantErr)
+ })
+ }
+}
+
+type mockQueue struct {
+ out chan *queue.Output
+ in chan *queue.Job
+}
+
+func (m *mockQueue) String() string {
+ return "MockQueue"
+}
+
+func newMockQueue() *mockQueue {
+ return &mockQueue{
+ in: make(chan *queue.Job, 100),
+ out: make(chan *queue.Output, 100),
+ }
+}
+
+func (m *mockQueue) Type() queue.Type {
+ return "mock"
+}
+
+func (m *mockQueue) Size() int {
+ return len(m.in)
+}
+
+func (m *mockQueue) Start(ctx context.Context) {
+ <-ctx.Done()
+}
+
+func (m *mockQueue) Add(job *queue.Job) error {
+ select {
+ case m.in <- job:
+ return nil
+ default:
+ return errQueueFull
+ }
+}
+
+func (m *mockQueue) Stop() {
+ close(m.in)
+ close(m.out)
+}
+
+func (m *mockQueue) Results() <-chan *queue.Output {
+ return m.out
+}
+
+type mockQueueFactory struct {
+ q *mockQueue
+}
+
+func (m mockQueueFactory) Create(int) queue.Queue {
+ if m.q == nil {
+ m.q = newMockQueue()
+ }
+ return m.q
+}
+
+func (m mockQueueFactory) Type() queue.Type {
+ return "mock"
+}
diff --git a/components/neo/internal/logger/formatter.go b/components/neo/internal/logger/formatter.go
new file mode 100644
index 0000000..20534ea
--- /dev/null
+++ b/components/neo/internal/logger/formatter.go
@@ -0,0 +1,214 @@
+package logger
+
+import (
+ "bytes"
+ "fmt"
+ "runtime"
+ "sort"
+ "strconv"
+ "strings"
+ "sync"
+ "time"
+ "unicode/utf8"
+
+ "github.com/sirupsen/logrus"
+)
+
+const (
+ red = 31
+ yellow = 33
+ blue = 36
+ gray = 37
+)
+
+const defaultTimestampFormat = "2006-01-02T15:04:05.000Z07:00"
+
+const (
+ CustomKeyFile = "@logger@file@"
+ CustomKeyFunc = "@logger@func@"
+)
+
+var baseTimestamp time.Time
+
+func init() {
+ baseTimestamp = time.Now()
+}
+
+// CustomFormatter форматирует записи журнала в текст.
+// Это форматтер logrus, настроенный для нужд Neo.
+type CustomFormatter struct {
+ // Показывать полную временную метку при выводе в терминал, а не время
+ // с начала работы программы.
+ FullTimestamp bool
+
+ // Формат временной метки. Используется тот же формат, что и в time.Format
+ // и time.Parse стандартной библиотеки.
+ TimestampFormat string
+
+ // Не сокращать название уровня журнала до четырех символов.
+ DisableLevelTruncation bool
+
+ // Дополнять название уровня пробелами до общей длины.
+ // Этот параметр включает DisableLevelTruncation.
+ PadLevelText bool
+
+ // CallerPrettyfier позволяет настроить значения полей функции и файла,
+ // когда включен ReportCaller. Пустое возвращенное значение удаляет
+ // соответствующее поле.
+ CallerPrettyfier func(*runtime.Frame) (function string, file string)
+
+ terminalInitOnce sync.Once
+
+ // Максимальная длина названия уровня, вычисляемая при инициализации.
+ levelTextMaxLength int
+}
+
+func (f *CustomFormatter) init() {
+ // Найти максимальную длину названия уровня.
+ for _, level := range logrus.AllLevels {
+ levelTextLength := utf8.RuneCount([]byte(level.String()))
+ if levelTextLength > f.levelTextMaxLength {
+ f.levelTextMaxLength = levelTextLength
+ }
+ }
+}
+
+// Format формирует одну запись журнала.
+func (f *CustomFormatter) Format(entry *logrus.Entry) ([]byte, error) {
+ data := make(logrus.Fields)
+ for k, v := range entry.Data {
+ data[k] = v
+ }
+ keys := make([]string, 0, len(data))
+ for k := range data {
+ if k == CustomKeyFile || k == CustomKeyFunc {
+ continue
+ }
+ keys = append(keys, k)
+ }
+
+ sort.Strings(keys)
+
+ var b *bytes.Buffer
+ if entry.Buffer != nil {
+ b = entry.Buffer
+ } else {
+ b = &bytes.Buffer{}
+ }
+
+ f.terminalInitOnce.Do(func() { f.init() })
+
+ timestampFormat := f.TimestampFormat
+ if timestampFormat == "" {
+ timestampFormat = defaultTimestampFormat
+ }
+ f.printColored(b, entry, keys, data, timestampFormat)
+
+ b.WriteByte('\n')
+ return b.Bytes(), nil
+}
+
+func (f *CustomFormatter) printColored(b *bytes.Buffer, entry *logrus.Entry, keys []string, data logrus.Fields, timestampFormat string) {
+ var levelColor int
+ switch entry.Level {
+ case logrus.DebugLevel, logrus.TraceLevel:
+ levelColor = gray
+ case logrus.WarnLevel:
+ levelColor = yellow
+ case logrus.ErrorLevel, logrus.FatalLevel, logrus.PanicLevel:
+ levelColor = red
+ case logrus.InfoLevel:
+ levelColor = blue
+ default:
+ levelColor = blue
+ }
+
+ levelText := strings.ToUpper(entry.Level.String())
+ if !f.DisableLevelTruncation && !f.PadLevelText {
+ levelText = levelText[0:4]
+ }
+ if f.PadLevelText {
+ // Сформировать шаблон выравнивания, например "%-6s" или "%-7s",
+ // на основе максимальной длины названия уровня.
+ formatString := "%-" + strconv.Itoa(f.levelTextMaxLength) + "s"
+ // Дополнить название уровня пробелами, например:
+ // - "INFO "
+ // - "WARNING"
+ levelText = fmt.Sprintf(formatString, levelText)
+ }
+
+ // Удалить завершающий перевод строки, чтобы поведение совпадало
+ // с text_formatter из logrus и стандартным пакетом log.
+ entry.Message = strings.TrimSuffix(entry.Message, "\n")
+
+ caller := ""
+ if entry.HasCaller() {
+ var (
+ funcVal string
+ fileVal string
+ ok bool
+ )
+ if fileVal, ok = data[CustomKeyFile].(string); ok && fileVal != "" {
+ delete(data, CustomKeyFile)
+ }
+ if funcVal, ok = data[CustomKeyFunc].(string); ok && funcVal != "" {
+ delete(data, CustomKeyFunc)
+ }
+ if fileVal == "" && funcVal == "" {
+ if f.CallerPrettyfier != nil {
+ funcVal, fileVal = f.CallerPrettyfier(entry.Caller)
+ } else {
+ fileVal = fmt.Sprintf("%s:%d", entry.Caller.File, entry.Caller.Line)
+ funcVal = fmt.Sprintf("%s()", entry.Caller.Function)
+ }
+ }
+
+ b := strings.Builder{}
+ if fileVal != "" {
+ b.WriteByte(' ')
+ b.WriteString(fileVal)
+ }
+ if funcVal != "" {
+ b.WriteByte(' ')
+ b.WriteString(funcVal)
+ }
+ caller = b.String()
+ }
+
+ switch {
+ case !f.FullTimestamp:
+ _, _ = fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m[%04d]%s %-44s ", levelColor, levelText, int(entry.Time.Sub(baseTimestamp)/time.Second), caller, entry.Message)
+ default:
+ _, _ = fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m[%s]%s %-44s ", levelColor, levelText, entry.Time.Format(timestampFormat), caller, entry.Message)
+ }
+ for _, k := range keys {
+ v := data[k]
+ _, _ = fmt.Fprintf(b, " \x1b[%dm%s\x1b[0m=", levelColor, k)
+ f.appendValue(b, v)
+ }
+}
+
+func (f *CustomFormatter) needsQuoting(text string) bool {
+ for _, ch := range text {
+ if !((ch >= 'a' && ch <= 'z') ||
+ (ch >= 'A' && ch <= 'Z') ||
+ (ch >= '0' && ch <= '9') ||
+ ch == '-' || ch == '.' || ch == '_' || ch == '/' || ch == '@' || ch == '^' || ch == '+') {
+ return true
+ }
+ }
+ return false
+}
+
+func (f *CustomFormatter) appendValue(b *bytes.Buffer, value interface{}) {
+ stringVal, ok := value.(string)
+ if !ok {
+ stringVal = fmt.Sprint(value)
+ }
+
+ if !f.needsQuoting(stringVal) {
+ b.WriteString(stringVal)
+ } else {
+ b.WriteString(fmt.Sprintf("%q", stringVal))
+ }
+}
diff --git a/components/neo/internal/logger/init.go b/components/neo/internal/logger/init.go
new file mode 100644
index 0000000..1acdda3
--- /dev/null
+++ b/components/neo/internal/logger/init.go
@@ -0,0 +1,35 @@
+package logger
+
+import (
+ "fmt"
+ "os"
+ "path/filepath"
+ "runtime"
+ "sync"
+
+ "github.com/sirupsen/logrus"
+)
+
+var once = sync.Once{}
+
+func Init() {
+ once.Do(func() {
+ logrus.SetFormatter(&CustomFormatter{
+ FullTimestamp: true,
+ TimestampFormat: "2006-01-02T15:04:05.000Z07:00",
+ DisableLevelTruncation: false,
+ CallerPrettyfier: func(f *runtime.Frame) (string, string) {
+ filename := filepath.Base(f.File)
+ return "", fmt.Sprintf("%s:%d", filename, f.Line)
+ },
+ })
+ logrus.SetReportCaller(true)
+ })
+ if ll := os.Getenv("NEO_LOG_LEVEL"); ll != "" {
+ level, err := logrus.ParseLevel(ll)
+ if err != nil {
+ logrus.Fatalf("Не удалось разобрать уровень журналирования %v: %v", ll, err)
+ }
+ logrus.SetLevel(level)
+ }
+}
diff --git a/components/neo/internal/models/exploit.go b/components/neo/internal/models/exploit.go
new file mode 100644
index 0000000..212caa3
--- /dev/null
+++ b/components/neo/internal/models/exploit.go
@@ -0,0 +1,40 @@
+package models
+
+import (
+ "fmt"
+
+ "github.com/prometheus/client_golang/prometheus"
+)
+
+type ExploitType string
+
+const (
+ ExploitTypeRecurrent ExploitType = "recurrent"
+ ExploitTypeEndless ExploitType = "endless"
+)
+
+type Exploit struct {
+ ID string
+ Version int64
+ Type ExploitType
+}
+
+func NewExploit(id string, version int64, exploitType ExploitType) *Exploit {
+ return &Exploit{
+ ID: id,
+ Version: version,
+ Type: exploitType,
+ }
+}
+
+func (i *Exploit) String() string {
+ return fmt.Sprintf("Exploit(%s_%d, type=%s)", i.ID, i.Version, i.Type)
+}
+
+func (i *Exploit) MetricLabels() prometheus.Labels {
+ return prometheus.Labels{
+ "exploit_id": i.ID,
+ "exploit_version": fmt.Sprintf("%d", i.Version),
+ "exploit_type": string(i.Type),
+ }
+}
diff --git a/components/neo/internal/models/target.go b/components/neo/internal/models/target.go
new file mode 100644
index 0000000..b7657be
--- /dev/null
+++ b/components/neo/internal/models/target.go
@@ -0,0 +1,27 @@
+package models
+
+import (
+ "fmt"
+
+ "github.com/prometheus/client_golang/prometheus"
+)
+
+type Target struct {
+ ID string
+ IP string
+}
+
+func NewTarget(teamID, teamIP string) *Target {
+ return &Target{
+ ID: teamID,
+ IP: teamIP,
+ }
+}
+
+func (i *Target) String() string {
+ return fmt.Sprintf("Target(id=%s, ip=%s)", i.ID, i.IP)
+}
+
+func (i *Target) MetricLabels() prometheus.Labels {
+ return prometheus.Labels{"target_id": i.ID, "target_ip": i.IP}
+}
diff --git a/components/neo/internal/queue/endless.go b/components/neo/internal/queue/endless.go
new file mode 100644
index 0000000..5a51135
--- /dev/null
+++ b/components/neo/internal/queue/endless.go
@@ -0,0 +1,188 @@
+package queue
+
+import (
+ "bufio"
+ "context"
+ "errors"
+ "fmt"
+ "os"
+ "sync"
+ "time"
+
+ "github.com/google/uuid"
+ "github.com/sirupsen/logrus"
+
+ "github.com/c4t-but-s4d/neo/v2/pkg/neosync"
+)
+
+const (
+ endlessDebounce = 3 * time.Second
+)
+
+// Проверки типов во время компиляции.
+var (
+ _ Queue = (*endlessQueue)(nil)
+)
+
+type endlessQueue struct {
+ out chan *Output
+ c chan *Job
+ maxJobs int
+ metrics *Metrics
+ logger *logrus.Entry
+}
+
+func NewEndlessQueue(maxJobs int) Queue {
+ queueID := uuid.NewString()[:8]
+ return &endlessQueue{
+ out: make(chan *Output, resultBufferSize),
+ c: make(chan *Job, jobBufferSize),
+ maxJobs: maxJobs,
+ metrics: NewMetrics("neo", queueID, TypeEndless),
+ logger: logrus.WithFields(logrus.Fields{
+ "component": "endless_queue",
+ "id": queueID,
+ }),
+ }
+}
+
+func (q *endlessQueue) Type() Type {
+ return TypeEndless
+}
+
+func (q *endlessQueue) Size() int {
+ return len(q.c)
+}
+
+// Start выполняется синхронно. Чтобы остановить очередь, отмените контекст.
+func (q *endlessQueue) Start(ctx context.Context) {
+ q.logger.WithField("jobs", q.maxJobs).Info("Запуск очереди")
+
+ q.metrics.MaxJobs.Add(float64(q.maxJobs))
+ defer q.metrics.MaxJobs.Sub(float64(q.maxJobs))
+
+ wg := sync.WaitGroup{}
+ wg.Add(q.maxJobs)
+ for i := 0; i < q.maxJobs; i++ {
+ go func() {
+ defer wg.Done()
+ q.worker(ctx)
+ }()
+ }
+ wg.Wait()
+
+ q.logger.Info("Очередь остановлена")
+}
+
+func (q *endlessQueue) Results() <-chan *Output {
+ return q.out
+}
+
+func (q *endlessQueue) Add(task *Job) error {
+ select {
+ case q.c <- task:
+ return nil
+ default:
+ return ErrQueueFull
+ }
+}
+
+func (q *endlessQueue) String() string {
+ return "EndlessQueue"
+}
+
+func (q *endlessQueue) worker(ctx context.Context) {
+ for {
+ select {
+ case <-ctx.Done():
+ return
+ case job := <-q.c:
+ for {
+ select {
+ case <-ctx.Done():
+ return
+ default:
+ }
+
+ err := q.runExploit(ctx, job)
+ switch {
+ case errors.Is(err, context.Canceled):
+ return
+ case err != nil:
+ job.logger.Errorf("Бесконечный эксплойт завершился с ошибкой: %v", err)
+ neosync.Sleep(ctx, endlessDebounce)
+ default:
+ job.logger.Errorf("Бесконечный эксплойт завершился неожиданно")
+ neosync.Sleep(ctx, endlessDebounce)
+ }
+ }
+ }
+ }
+}
+
+func (q *endlessQueue) runExploit(ctx context.Context, job *Job) error {
+ cmd := job.Command(ctx)
+ job.logger.Infof("Бесконечный запуск задания: %s", cmd)
+
+ // os.Pipe работает быстрее io.Pipe.
+ r, w, err := os.Pipe()
+ if err != nil {
+ return fmt.Errorf("создание канала вывода: %w", err)
+ }
+
+ exploitLabels := job.Exploit.MetricLabels()
+
+ errC := make(chan error, 1)
+ go func() {
+ defer func(w *os.File) {
+ if err := w.Close(); err != nil {
+ job.logger.Errorf("Ошибка закрытия канала вывода: %v", err)
+ }
+ }(w)
+
+ cmd.Stdout = w
+ cmd.Stderr = w
+
+ q.metrics.ExploitInstancesRunning.With(exploitLabels).Inc()
+ defer q.metrics.ExploitInstancesRunning.With(exploitLabels).Dec()
+
+ errC <- cmd.Run()
+ }()
+
+ readDone := make(chan struct{})
+ defer func() {
+ job.logger.Infof("Ожидание завершения чтения вывода")
+ <-readDone
+ }()
+
+ go func() {
+ defer close(readDone)
+ scanner := bufio.NewScanner(r)
+ for scanner.Scan() {
+ q.out <- NewOutput(job, scanner.Bytes())
+ }
+ if err := scanner.Err(); err != nil && ctx.Err() == nil {
+ job.logger.Errorf("Ошибка чтения вывода бесконечного задания: %v", err)
+ }
+ }()
+
+ select {
+ case <-ctx.Done():
+ <-errC
+ q.metrics.ExploitsFinished.With(exploitLabels).Inc()
+ return nil
+ case err := <-errC:
+ // Ожидаемая ошибка при отмене контекста.
+ if ctx.Err() != nil {
+ q.metrics.ExploitsFinished.With(exploitLabels).Inc()
+ return nil
+ }
+
+ job.logger.Errorf("Бесконечный эксплойт %v завершился: %v", job, err)
+ q.metrics.ExploitsFailed.With(exploitLabels).Inc()
+ if err != nil {
+ return fmt.Errorf("ошибка бесконечного эксплойта %v: %w", job, err)
+ }
+ return nil
+ }
+}
diff --git a/components/neo/internal/queue/endless_factory.go b/components/neo/internal/queue/endless_factory.go
new file mode 100644
index 0000000..5f4fda0
--- /dev/null
+++ b/components/neo/internal/queue/endless_factory.go
@@ -0,0 +1,15 @@
+package queue
+
+type endlessQueueFactory struct{}
+
+func (f endlessQueueFactory) Create(maxJobs int) Queue {
+ return NewEndlessQueue(maxJobs)
+}
+
+func (f endlessQueueFactory) Type() Type {
+ return TypeEndless
+}
+
+func NewEndlessQueueFactory() Factory {
+ return endlessQueueFactory{}
+}
diff --git a/components/neo/internal/queue/endless_test.go b/components/neo/internal/queue/endless_test.go
new file mode 100644
index 0000000..a20c6fc
--- /dev/null
+++ b/components/neo/internal/queue/endless_test.go
@@ -0,0 +1,88 @@
+package queue
+
+import (
+ "context"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/sirupsen/logrus"
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+ "go.uber.org/goleak"
+
+ "github.com/c4t-but-s4d/neo/v2/internal/logger"
+ "github.com/c4t-but-s4d/neo/v2/internal/models"
+ "github.com/c4t-but-s4d/neo/v2/pkg/testutils"
+)
+
+func TestMain(m *testing.M) {
+ logger.Init()
+ logrus.SetLevel(logrus.DebugLevel)
+ goleak.VerifyTestMain(m)
+}
+
+func Test_endlessQueue_Add(t *testing.T) {
+ makeQueue := func(s int) *endlessQueue {
+ q := NewEndlessQueue(1).(*endlessQueue)
+ q.c = make(chan *Job, s)
+ return q
+ }
+ for _, tc := range []struct {
+ q *endlessQueue
+ t *Job
+ wantTask *Job
+ wantErr error
+ }{
+ {q: makeQueue(100), t: &Job{executable: "1"}, wantErr: nil},
+ {q: makeQueue(1), t: &Job{executable: "1"}, wantErr: nil},
+ {q: makeQueue(0), t: &Job{executable: "1"}, wantErr: ErrQueueFull},
+ } {
+ tc.t.logger = testutils.DummyJobLogger("1", "127.0.0.1")
+ err := tc.q.Add(tc.t)
+ require.ErrorIs(t, err, tc.wantErr)
+ if err != nil {
+ continue
+ }
+ require.Equal(t, tc.t.executable, (<-tc.q.c).executable)
+ }
+}
+
+func Test_endlessQueue_Start(t *testing.T) {
+ q := NewEndlessQueue(10)
+ task := &Job{
+ Exploit: &models.Exploit{ID: "kek"},
+ Target: &models.Target{
+ ID: "id",
+ IP: "ip",
+ },
+ executable: "echo",
+ dir: "",
+ timeout: time.Second * 2,
+ logger: testutils.DummyJobLogger("echo", "ip"),
+ }
+ require.NoError(t, q.Add(task))
+
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+
+ wg := sync.WaitGroup{}
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ q.Start(ctx)
+ }()
+
+ select {
+ case <-time.After(time.Second * 3):
+ t.Fatal("timeout")
+ case out := <-q.Results():
+ assert.Equal(t, task.Exploit, out.Exploit)
+ assert.Equal(t, task.Target, out.Target)
+ assert.Equal(t, task.Target.IP, string(out.Out))
+ break
+ }
+
+ cancel()
+ wg.Wait()
+}
diff --git a/components/neo/internal/queue/job.go b/components/neo/internal/queue/job.go
new file mode 100644
index 0000000..6abde76
--- /dev/null
+++ b/components/neo/internal/queue/job.go
@@ -0,0 +1,112 @@
+package queue
+
+import (
+ "context"
+ "fmt"
+ "os"
+ "os/exec"
+ "strings"
+ "syscall"
+ "time"
+
+ "github.com/c4t-but-s4d/neo/v2/internal/models"
+ "github.com/c4t-but-s4d/neo/v2/pkg/joblogger"
+)
+
+func NewJob(
+ exploit *models.Exploit,
+ target *models.Target,
+ executable, dir string,
+ environ []string,
+ timeout time.Duration,
+ logger *joblogger.JobLogger,
+) *Job {
+ return &Job{
+ Exploit: exploit,
+ Target: target,
+
+ executable: executable,
+ dir: dir,
+ timeout: timeout,
+ environ: environ,
+ logger: logger,
+ }
+}
+
+type Job struct {
+ Exploit *models.Exploit
+ Target *models.Target
+
+ executable string
+ dir string
+ environ []string
+ timeout time.Duration
+ logger *joblogger.JobLogger
+}
+
+func (t *Job) String() string {
+ return fmt.Sprintf(
+ "Job(exploit=%v, target=%v, path=%s, timeout=%v, env-vars=%d)",
+ t.Exploit,
+ t.Target,
+ t.executable,
+ t.timeout,
+ len(t.environ),
+ )
+}
+
+func (t *Job) Command(ctx context.Context) *exec.Cmd {
+ cmd := exec.CommandContext(ctx, t.executable, t.Target.IP)
+ cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
+ cmd.Cancel = func() error {
+ if cmd.Process == nil {
+ return os.ErrProcessDone
+ }
+ if err := syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL); err != nil && err != syscall.ESRCH {
+ return err
+ }
+ return nil
+ }
+ cmd.WaitDelay = 2 * time.Second
+ if t.dir != "" {
+ cmd.Dir = t.dir
+ }
+
+ cmd.Env = jobEnvironment(os.Environ(), t.environ)
+
+ // Отключить буферизацию вывода скриптов Python.
+ cmd.Env = append(cmd.Env, "PYTHONUNBUFFERED=1")
+ // Отключить использование терминала в pwntools.
+ cmd.Env = append(cmd.Env, "PWNLIB_NOTERM=1")
+ return cmd
+}
+
+var controlPlaneSecrets = map[string]struct{}{
+ "NEO_GRPC_AUTH_KEY": {},
+ "NEO_WORKER_KEY": {},
+ "NEO_KEY": {},
+ "GRPC_AUTH_KEY": {},
+ "FARM_PASSWORD": {},
+ "NEO_FARM_PASSWORD": {},
+}
+
+func jobEnvironment(base, extra []string) []string {
+ values := make([]string, 0, len(base)+len(extra))
+ positions := make(map[string]int, len(base)+len(extra))
+ for _, entry := range append(append([]string(nil), base...), extra...) {
+ key, _, ok := strings.Cut(entry, "=")
+ if !ok {
+ continue
+ }
+ if _, secret := controlPlaneSecrets[strings.ToUpper(key)]; secret {
+ continue
+ }
+ if pos, exists := positions[key]; exists {
+ values[pos] = entry
+ continue
+ }
+ positions[key] = len(values)
+ values = append(values, entry)
+ }
+ return values
+}
diff --git a/components/neo/internal/queue/job_test.go b/components/neo/internal/queue/job_test.go
new file mode 100644
index 0000000..e045d1b
--- /dev/null
+++ b/components/neo/internal/queue/job_test.go
@@ -0,0 +1,45 @@
+package queue
+
+import (
+ "context"
+ "os"
+ "path/filepath"
+ "testing"
+ "time"
+
+ "github.com/c4t-but-s4d/neo/v2/internal/models"
+ "github.com/stretchr/testify/require"
+)
+
+func TestJobEnvironmentDoesNotPassControlPlaneSecrets(t *testing.T) {
+ env := jobEnvironment(
+ []string{"PATH=/usr/bin", "NEO_GRPC_AUTH_KEY=worker-secret", "NEO_FARM_PASSWORD=farm-secret"},
+ []string{"NEO_WORKER_KEY=worker-secret", "TEAM_TOKEN=job-token", "MODE=old", "MODE=new"},
+ )
+ require.Equal(t, []string{"PATH=/usr/bin", "TEAM_TOKEN=job-token", "MODE=new"}, env)
+}
+
+func TestJobStringDoesNotIncludeEnvironmentValues(t *testing.T) {
+ job := NewJob(nil, &models.Target{IP: "127.0.0.1"}, "/bin/true", "", []string{"NEO_GRPC_AUTH_KEY=worker-secret"}, time.Second, nil)
+ require.NotContains(t, job.String(), "worker-secret")
+ require.NotContains(t, job.Command(context.Background()).Env, "NEO_GRPC_AUTH_KEY=worker-secret")
+}
+
+func TestJobTimeoutKillsChildProcesses(t *testing.T) {
+ dir := t.TempDir()
+ marker := filepath.Join(dir, "child-finished")
+ script := filepath.Join(dir, "job.sh")
+ contents := "#!/bin/sh\n(sleep 0.5; printf done > \"" + marker + "\") &\nwait\n"
+ require.NoError(t, os.WriteFile(script, []byte(contents), 0700))
+
+ ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
+ defer cancel()
+ job := NewJob(nil, &models.Target{IP: "127.0.0.1"}, script, dir, nil, time.Second, nil)
+ started := time.Now()
+ err := job.Command(ctx).Run()
+ require.Error(t, err)
+ require.Less(t, time.Since(started), time.Second)
+ time.Sleep(600 * time.Millisecond)
+ _, err = os.Stat(marker)
+ require.ErrorIs(t, err, os.ErrNotExist)
+}
diff --git a/components/neo/internal/queue/metrics.go b/components/neo/internal/queue/metrics.go
new file mode 100644
index 0000000..7f9eee1
--- /dev/null
+++ b/components/neo/internal/queue/metrics.go
@@ -0,0 +1,78 @@
+package queue
+
+import (
+ "github.com/prometheus/client_golang/prometheus"
+ "github.com/prometheus/client_golang/prometheus/promauto"
+)
+
+type Metrics struct {
+ ExploitInstancesRunning *prometheus.GaugeVec
+ ExploitsFinished *prometheus.CounterVec
+ ExploitsFailed *prometheus.CounterVec
+ ExploitRunTime *prometheus.HistogramVec
+
+ MaxJobs prometheus.Gauge
+}
+
+func NewMetrics(namespace, id string, queueType Type) *Metrics {
+ const subsystem = "exploit_queue"
+ exploitLabels := []string{"exploit_id", "exploit_version", "exploit_type"}
+ constLabels := prometheus.Labels{
+ "queue_type": queueType.String(),
+ "queue_id": id,
+ }
+
+ return &Metrics{
+ ExploitInstancesRunning: promauto.NewGaugeVec(
+ prometheus.GaugeOpts{
+ Namespace: namespace,
+ Subsystem: subsystem,
+ Name: "exploit_instances_running",
+ Help: "Number of exploit instances currently running",
+ ConstLabels: constLabels,
+ },
+ exploitLabels,
+ ),
+ ExploitsFinished: promauto.NewCounterVec(
+ prometheus.CounterOpts{
+ Namespace: namespace,
+ Subsystem: subsystem,
+ Name: "exploits_finished_total",
+ Help: "Number of exploits finished",
+ ConstLabels: constLabels,
+ },
+ exploitLabels,
+ ),
+ ExploitsFailed: promauto.NewCounterVec(
+ prometheus.CounterOpts{
+ Namespace: namespace,
+ Subsystem: subsystem,
+ Name: "exploits_failed_total",
+ Help: "Number of exploits failed",
+ ConstLabels: constLabels,
+ },
+ exploitLabels,
+ ),
+ ExploitRunTime: promauto.NewHistogramVec(
+ prometheus.HistogramOpts{
+ Namespace: namespace,
+ Subsystem: subsystem,
+ Name: "exploit_run_time_seconds",
+ Help: "Time it took to run an exploit",
+ ConstLabels: constLabels,
+ Buckets: prometheus.ExponentialBucketsRange(0.001, 300, 30),
+ },
+ exploitLabels,
+ ),
+
+ MaxJobs: promauto.NewGauge(
+ prometheus.GaugeOpts{
+ Namespace: namespace,
+ Subsystem: subsystem,
+ Name: "max_jobs",
+ Help: "Maximum number of jobs for the current runner",
+ ConstLabels: constLabels,
+ },
+ ),
+ }
+}
diff --git a/components/neo/internal/queue/output.go b/components/neo/internal/queue/output.go
new file mode 100644
index 0000000..a395172
--- /dev/null
+++ b/components/neo/internal/queue/output.go
@@ -0,0 +1,25 @@
+package queue
+
+import (
+ "fmt"
+
+ "github.com/c4t-but-s4d/neo/v2/internal/models"
+)
+
+type Output struct {
+ Exploit *models.Exploit
+ Target *models.Target
+ Out []byte
+}
+
+func NewOutput(job *Job, out []byte) *Output {
+ return &Output{
+ Exploit: job.Exploit,
+ Target: job.Target,
+ Out: out,
+ }
+}
+
+func (o *Output) String() string {
+ return fmt.Sprintf("%s (%s): %s", o.Exploit, o.Target, o.Out)
+}
diff --git a/components/neo/internal/queue/queue.go b/components/neo/internal/queue/queue.go
new file mode 100644
index 0000000..ab4a954
--- /dev/null
+++ b/components/neo/internal/queue/queue.go
@@ -0,0 +1,37 @@
+package queue
+
+import (
+ "context"
+ "errors"
+ "fmt"
+)
+
+var (
+ ErrQueueFull = errors.New("очередь заданий заполнена")
+)
+
+type Type string
+
+func (t Type) String() string {
+ return string(t)
+}
+
+const (
+ TypeSimple Type = "simple"
+ TypeEndless Type = "endless"
+)
+
+type Factory interface {
+ Create(maxJobs int) Queue
+ Type() Type
+}
+
+type Queue interface {
+ Start(context.Context)
+ Add(*Job) error
+ Results() <-chan *Output
+ Type() Type
+ Size() int
+
+ fmt.Stringer
+}
diff --git a/components/neo/internal/queue/simple.go b/components/neo/internal/queue/simple.go
new file mode 100644
index 0000000..0676ba9
--- /dev/null
+++ b/components/neo/internal/queue/simple.go
@@ -0,0 +1,150 @@
+package queue
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "os/exec"
+ "sync"
+ "time"
+
+ "github.com/google/uuid"
+ "github.com/sirupsen/logrus"
+)
+
+const (
+ jobBufferSize = 1000
+ resultBufferSize = 1000
+)
+
+// Проверки типов во время компиляции.
+var (
+ _ Queue = (*simpleQueue)(nil)
+)
+
+type simpleQueue struct {
+ out chan *Output
+ c chan *Job
+ maxJobs int
+ metrics *Metrics
+ logger *logrus.Entry
+}
+
+func NewSimpleQueue(maxJobs int) Queue {
+ id := uuid.NewString()[:8]
+
+ return &simpleQueue{
+ out: make(chan *Output, resultBufferSize),
+ c: make(chan *Job, jobBufferSize),
+ maxJobs: maxJobs,
+ metrics: NewMetrics("neo", id, TypeSimple),
+ logger: logrus.WithFields(logrus.Fields{
+ "component": "simple_queue",
+ "id": id,
+ }),
+ }
+}
+
+func (q *simpleQueue) Type() Type {
+ return TypeSimple
+}
+
+func (q *simpleQueue) Size() int {
+ return len(q.c)
+}
+
+// Start выполняется синхронно. Чтобы остановить очередь, отмените контекст.
+func (q *simpleQueue) Start(ctx context.Context) {
+ q.logger.WithField("jobs", q.maxJobs).Info("Запуск очереди")
+
+ q.metrics.MaxJobs.Add(float64(q.maxJobs))
+ defer q.metrics.MaxJobs.Sub(float64(q.maxJobs))
+
+ wg := sync.WaitGroup{}
+ wg.Add(q.maxJobs)
+ for i := 0; i < q.maxJobs; i++ {
+ go func() {
+ defer wg.Done()
+ q.worker(ctx)
+ }()
+ }
+ wg.Wait()
+
+ q.logger.Info("Очередь остановлена")
+}
+
+func (q *simpleQueue) Results() <-chan *Output {
+ return q.out
+}
+
+func (q *simpleQueue) Add(task *Job) error {
+ select {
+ case q.c <- task:
+ return nil
+ default:
+ return ErrQueueFull
+ }
+}
+
+func (q *simpleQueue) String() string {
+ return "SimpleQueue"
+}
+
+func (q *simpleQueue) worker(ctx context.Context) {
+ for {
+ select {
+ case <-ctx.Done():
+ return
+ case task := <-q.c:
+ res, err := q.runExploit(ctx, task)
+
+ exploitLabels := task.Exploit.MetricLabels()
+
+ var exitErr *exec.ExitError
+ switch {
+ case err == nil:
+ task.logger.Infof("Задание выполнено")
+ q.metrics.ExploitsFinished.With(exploitLabels).Inc()
+ case errors.Is(err, context.Canceled):
+ // При перезапуске очереди ожидается ошибка.
+ q.metrics.ExploitsFinished.With(exploitLabels).Inc()
+ return
+ case errors.As(err, &exitErr):
+ if exitErr.ExitCode() == -1 {
+ task.logger.Warningf("Эксплойт завершился по сигналу: %v", exitErr)
+ } else {
+ task.logger.Warningf("Ошибка при выполнении эксплойта: %v", err)
+ }
+ q.metrics.ExploitsFailed.With(exploitLabels).Inc()
+
+ default:
+ task.logger.Errorf("Не удалось выполнить задание: %v", err)
+ q.metrics.ExploitsFailed.With(exploitLabels).Inc()
+ }
+ q.out <- NewOutput(task, res)
+ }
+ }
+}
+
+func (q *simpleQueue) runExploit(ctx context.Context, task *Job) ([]byte, error) {
+ cmdCtx, cancel := context.WithTimeout(ctx, task.timeout)
+ defer cancel()
+
+ cmd := task.Command(cmdCtx)
+ task.logger.Infof("Запуск задания: %v", cmd)
+
+ start := time.Now()
+ exploitLabels := task.Exploit.MetricLabels()
+ q.metrics.ExploitInstancesRunning.With(exploitLabels).Inc()
+ defer func() {
+ q.metrics.ExploitInstancesRunning.With(exploitLabels).Dec()
+ q.metrics.ExploitRunTime.With(exploitLabels).Observe(time.Since(start).Seconds())
+ }()
+
+ // Процесс завершится при отмене контекста.
+ out, err := cmd.CombinedOutput()
+ if err != nil {
+ err = fmt.Errorf("ошибка выполнения команды: %w", err)
+ }
+ return out, err
+}
diff --git a/components/neo/internal/queue/simple_factory.go b/components/neo/internal/queue/simple_factory.go
new file mode 100644
index 0000000..0c2bdb6
--- /dev/null
+++ b/components/neo/internal/queue/simple_factory.go
@@ -0,0 +1,15 @@
+package queue
+
+type simpleQueueFactory struct{}
+
+func (f simpleQueueFactory) Create(maxJobs int) Queue {
+ return NewSimpleQueue(maxJobs)
+}
+
+func (f simpleQueueFactory) Type() Type {
+ return TypeSimple
+}
+
+func NewSimpleQueueFactory() Factory {
+ return simpleQueueFactory{}
+}
diff --git a/components/neo/internal/queue/simple_test.go b/components/neo/internal/queue/simple_test.go
new file mode 100644
index 0000000..3ab21fc
--- /dev/null
+++ b/components/neo/internal/queue/simple_test.go
@@ -0,0 +1,174 @@
+package queue
+
+import (
+ "context"
+ "os/exec"
+ "testing"
+ "time"
+
+ "github.com/google/go-cmp/cmp"
+ "github.com/google/go-cmp/cmp/cmpopts"
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+
+ "github.com/c4t-but-s4d/neo/v2/internal/models"
+ "github.com/c4t-but-s4d/neo/v2/pkg/testutils"
+)
+
+func TestSimpleQueue_Add(t *testing.T) {
+ makeQueue := func(s int) *simpleQueue {
+ q := NewSimpleQueue(1).(*simpleQueue)
+ q.c = make(chan *Job, s)
+ return q
+ }
+ for _, tc := range []struct {
+ q *simpleQueue
+ t *Job
+ wantTask *Job
+ wantErr error
+ }{
+ {
+ q: makeQueue(100),
+ t: &Job{
+ Exploit: &models.Exploit{ID: "kek"},
+ Target: &models.Target{ID: "t", IP: "i"},
+ executable: "1",
+ },
+ wantErr: nil,
+ },
+ {
+ q: makeQueue(1),
+ t: &Job{
+ Exploit: &models.Exploit{ID: "kek"},
+ Target: &models.Target{ID: "t", IP: "i"},
+ executable: "1",
+ },
+ wantErr: nil,
+ },
+ {
+ q: makeQueue(0),
+ t: &Job{
+ Exploit: &models.Exploit{ID: "kek"},
+ Target: &models.Target{ID: "t", IP: "i"},
+ executable: "1",
+ },
+ wantErr: ErrQueueFull,
+ },
+ } {
+ tc.t.logger = testutils.DummyJobLogger(tc.t.Exploit.ID, tc.t.Target.IP)
+ err := tc.q.Add(tc.t)
+ require.ErrorIs(t, err, tc.wantErr)
+ if err != nil {
+ continue
+ }
+ require.Equal(t, tc.t.executable, (<-tc.q.c).executable)
+ }
+}
+
+func TestSimpleQueue_runExploit(t *testing.T) {
+ for _, tc := range []struct {
+ q *simpleQueue
+ t *Job
+ ctx context.Context
+ wantErr error
+ wantData []byte
+ }{
+ {
+ q: NewSimpleQueue(1).(*simpleQueue),
+ t: &Job{
+ Exploit: &models.Exploit{ID: "echo"},
+ executable: "echo",
+ Target: &models.Target{ID: "id", IP: "ip"},
+ timeout: time.Second * 5,
+ },
+ wantErr: nil,
+ wantData: []byte("ip\n"),
+ ctx: context.Background(),
+ },
+ {
+ q: NewSimpleQueue(1).(*simpleQueue),
+ t: &Job{
+ Exploit: &models.Exploit{ID: "bad executable"},
+ executable: "notfoundcli",
+ Target: &models.Target{ID: "id", IP: "ip"},
+ timeout: time.Second * 5,
+ },
+ wantErr: exec.ErrNotFound,
+ wantData: nil,
+ ctx: context.Background(),
+ },
+ {
+ q: NewSimpleQueue(1).(*simpleQueue),
+ t: &Job{
+ Exploit: &models.Exploit{ID: "cancelled ctx"},
+ executable: "echo",
+ Target: &models.Target{ID: "id", IP: "ip"},
+ timeout: time.Second * 5,
+ },
+ wantErr: context.Canceled,
+ wantData: nil,
+ ctx: testutils.CanceledContext(),
+ },
+ {
+ q: NewSimpleQueue(1).(*simpleQueue),
+ t: &Job{
+ Exploit: &models.Exploit{ID: "timed out ctx"},
+ executable: "echo",
+ Target: &models.Target{ID: "id", IP: "ip"},
+ timeout: time.Second * 5,
+ },
+ wantErr: context.DeadlineExceeded,
+ wantData: nil,
+ ctx: testutils.TimedOutContext(),
+ },
+ {
+ q: NewSimpleQueue(1).(*simpleQueue),
+ t: &Job{
+ Exploit: &models.Exploit{ID: "zero timeout"},
+ executable: "echo",
+ Target: &models.Target{ID: "id", IP: "ip"},
+ timeout: time.Second * 0,
+ },
+ wantErr: context.DeadlineExceeded,
+ wantData: nil,
+ ctx: context.Background(),
+ },
+ } {
+ tc.t.logger = testutils.DummyJobLogger(tc.t.Exploit.ID, tc.t.Target.IP)
+ data, err := tc.q.runExploit(tc.ctx, tc.t)
+ require.ErrorIs(t, err, tc.wantErr)
+
+ if diff := cmp.Diff(data, tc.wantData, cmpopts.EquateEmpty()); diff != "" {
+ t.Errorf("simpleQueue.runExploit() returned data mismatch (-want +got):\n%s", diff)
+ }
+ }
+}
+
+func TestSimpleQueue_Start(t *testing.T) {
+ q := NewSimpleQueue(10)
+ task := &Job{
+ Exploit: &models.Exploit{ID: "kek"},
+ Target: &models.Target{
+ ID: "id",
+ IP: "ip",
+ },
+ executable: "echo",
+ dir: "",
+ timeout: time.Second * 2,
+ logger: testutils.DummyJobLogger("echo", "ip"),
+ }
+ require.NoError(t, q.Add(task))
+
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+
+ go q.Start(ctx)
+ select {
+ case <-time.After(time.Second * 3):
+ t.Fatal("timeout")
+ case out := <-q.Results():
+ assert.Equal(t, task.Exploit, out.Exploit)
+ assert.Equal(t, task.Target, out.Target)
+ assert.Equal(t, task.Target.IP+"\n", string(out.Out))
+ }
+}
diff --git a/components/neo/internal/server/common/logging.go b/components/neo/internal/server/common/logging.go
new file mode 100644
index 0000000..cd3e3b8
--- /dev/null
+++ b/components/neo/internal/server/common/logging.go
@@ -0,0 +1,37 @@
+package common
+
+import (
+ "context"
+
+ "github.com/sirupsen/logrus"
+ "google.golang.org/grpc"
+ "google.golang.org/grpc/codes"
+ "google.golang.org/grpc/status"
+)
+
+type LoggingServer struct {
+ Logger *logrus.Entry
+}
+
+func NewLoggingServer(serverName string) LoggingServer {
+ return LoggingServer{Logger: logrus.WithField("server", serverName)}
+}
+
+func (s *LoggingServer) WrapErrorf(ctx context.Context, code codes.Code, fmt string, values ...any) error {
+ err := status.Errorf(code, fmt, values...)
+ s.GetMethodLogger(ctx).Errorf("%v", err)
+ return err // nolint
+}
+
+func (s *LoggingServer) LogRequest(ctx context.Context, r any) {
+ // Данные RPC могут содержать секреты или вывод недоверенной программы.
+ // Записывать только тип запроса, но не его значения.
+ s.GetMethodLogger(ctx).Infof("Request type: %T", r)
+}
+
+func (s *LoggingServer) GetMethodLogger(ctx context.Context) *logrus.Entry {
+ if method, ok := grpc.Method(ctx); ok {
+ return s.Logger.WithField("method", method)
+ }
+ return s.Logger
+}
diff --git a/components/neo/internal/server/config/config.go b/components/neo/internal/server/config/config.go
new file mode 100644
index 0000000..8b5aedd
--- /dev/null
+++ b/components/neo/internal/server/config/config.go
@@ -0,0 +1,69 @@
+package config
+
+import (
+ "encoding/json"
+ "fmt"
+ "io"
+ "net/url"
+ "strings"
+ "time"
+
+ "github.com/c4t-but-s4d/neo/v2/pkg/grpcauth"
+)
+
+type Config struct {
+ Debug bool `mapstructure:"debug"`
+ Addr string `mapstructure:"addr"`
+ DBPath string `mapstructure:"db_path"`
+ RedisURL string `mapstructure:"redis_url"`
+ BaseDir string `mapstructure:"base_dir"`
+ PingEvery time.Duration `mapstructure:"ping_every"`
+ SubmitEvery time.Duration `mapstructure:"submit_every"`
+ FarmConfig FarmConfig `mapstructure:"farm"`
+ GrpcAuthKey string `mapstructure:"grpc_auth_key"`
+ WorkerKey string `mapstructure:"worker_key"`
+ Environ map[string]string `mapstructure:"env"`
+ MetricsNamespace string `mapstructure:"metrics_namespace"`
+}
+
+type FarmConfig struct {
+ URL string `mapstructure:"url"`
+ Password string `mapstructure:"password"`
+ FlagRegexp string `json:"FLAG_FORMAT"`
+ Teams map[string]string `json:"TEAMS"`
+}
+
+func (cfg *Config) Validate() error {
+ if err := grpcauth.ValidateKeyPair(cfg.GrpcAuthKey, cfg.WorkerKey); err != nil {
+ return err
+ }
+ if strings.TrimSpace(cfg.FarmConfig.Password) == "" {
+ return fmt.Errorf("farm.password обязателен")
+ }
+ u, err := url.Parse(cfg.FarmConfig.URL)
+ if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" || u.User != nil {
+ return fmt.Errorf("farm.url должен быть HTTP(S) адресом без учетных данных")
+ }
+ if cfg.Addr == "" || cfg.DBPath == "" || cfg.BaseDir == "" || cfg.RedisURL == "" {
+ return fmt.Errorf("обязательны поля addr, db_path, base_dir и redis_url")
+ }
+ if cfg.PingEvery <= 0 || cfg.SubmitEvery <= 0 {
+ return fmt.Errorf("ping_every и submit_every должны быть положительными")
+ }
+ return nil
+}
+
+func (cfg *FarmConfig) ParseJSON(r io.Reader) error {
+ dec := json.NewDecoder(r)
+ if err := dec.Decode(cfg); err != nil {
+ return fmt.Errorf("разбор JSON: %w", err)
+ }
+ var extra any
+ if err := dec.Decode(&extra); err != io.EOF {
+ if err == nil {
+ return fmt.Errorf("после объекта JSON обнаружены лишние данные")
+ }
+ return fmt.Errorf("проверка конца JSON: %w", err)
+ }
+ return nil
+}
diff --git a/components/neo/internal/server/config/config_test.go b/components/neo/internal/server/config/config_test.go
new file mode 100644
index 0000000..c64cb7f
--- /dev/null
+++ b/components/neo/internal/server/config/config_test.go
@@ -0,0 +1,43 @@
+package config
+
+import (
+ "testing"
+ "time"
+
+ "github.com/stretchr/testify/require"
+)
+
+func validTestConfig() *Config {
+ return &Config{
+ Addr: ":5005",
+ DBPath: "/data/db.db",
+ RedisURL: "redis://neo-redis:6379/0",
+ BaseDir: "/data/exploits",
+ PingEvery: time.Second,
+ SubmitEvery: time.Second,
+ GrpcAuthKey: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
+ WorkerKey: "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
+ FarmConfig: FarmConfig{
+ URL: "http://farm:5000",
+ Password: "farm-secret",
+ },
+ }
+}
+
+func TestValidateRequiresDifferentAdminAndWorkerKeys(t *testing.T) {
+ cfg := validTestConfig()
+ require.NoError(t, cfg.Validate())
+
+ cfg.WorkerKey = cfg.GrpcAuthKey
+ require.ErrorContains(t, cfg.Validate(), "должны различаться")
+}
+
+func TestValidateRequiresFarmCredentialsAndHTTPURL(t *testing.T) {
+ cfg := validTestConfig()
+ cfg.FarmConfig.Password = ""
+ require.ErrorContains(t, cfg.Validate(), "farm.password")
+
+ cfg = validTestConfig()
+ cfg.FarmConfig.URL = "http://user:pass@farm:5000"
+ require.ErrorContains(t, cfg.Validate(), "без учетных данных")
+}
diff --git a/components/neo/internal/server/exploits/farm.go b/components/neo/internal/server/exploits/farm.go
new file mode 100644
index 0000000..795a162
--- /dev/null
+++ b/components/neo/internal/server/exploits/farm.go
@@ -0,0 +1,66 @@
+package exploits
+
+import (
+ "bytes"
+ "context"
+ "fmt"
+ "io"
+ "net/http"
+ "strings"
+ "time"
+
+ "github.com/sirupsen/logrus"
+
+ "github.com/c4t-but-s4d/neo/v2/internal/server/config"
+)
+
+func NewFarmClient(cfg config.FarmConfig) *FarmClient {
+ return &FarmClient{
+ url: strings.TrimRight(cfg.URL, "/"),
+ password: cfg.Password,
+ client: http.Client{
+ Timeout: 3 * time.Second,
+ },
+ }
+}
+
+type FarmClient struct {
+ url string
+ password string
+ client http.Client
+}
+
+const maxFarmConfigBytes = 1 << 20
+
+func (fc *FarmClient) FillConfig(ctx context.Context, cfg *config.FarmConfig) error {
+ url := fmt.Sprintf("%s/api/get_config", fc.url)
+ req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
+ if err != nil {
+ return fmt.Errorf("создание запроса к Farm: %w", err)
+ }
+ req.Header.Set("Authorization", fc.password)
+ req.Header.Set("X-Token", fc.password)
+ resp, err := fc.client.Do(req)
+ if err != nil {
+ return fmt.Errorf("выполнение запроса к Farm: %w", err)
+ }
+ defer func() {
+ if err := resp.Body.Close(); err != nil {
+ logrus.Errorf("Не удалось закрыть ответ Farm: %v", err)
+ }
+ }()
+ if resp.StatusCode != http.StatusOK {
+ return fmt.Errorf("Farm вернул HTTP %d", resp.StatusCode)
+ }
+ body, err := io.ReadAll(io.LimitReader(resp.Body, maxFarmConfigBytes+1))
+ if err != nil {
+ return fmt.Errorf("чтение конфигурации Farm: %w", err)
+ }
+ if len(body) > maxFarmConfigBytes {
+ return fmt.Errorf("конфигурация Farm превышает %d байт", maxFarmConfigBytes)
+ }
+ if err := cfg.ParseJSON(bytes.NewReader(body)); err != nil {
+ return fmt.Errorf("разбор ответа Farm: %w", err)
+ }
+ return nil
+}
diff --git a/components/neo/internal/server/exploits/metrics.go b/components/neo/internal/server/exploits/metrics.go
new file mode 100644
index 0000000..55f8cef
--- /dev/null
+++ b/components/neo/internal/server/exploits/metrics.go
@@ -0,0 +1,21 @@
+package exploits
+
+import (
+ "github.com/prometheus/client_golang/prometheus"
+ "github.com/prometheus/client_golang/prometheus/promauto"
+)
+
+type Metrics struct {
+ AliveClients prometheus.Gauge
+}
+
+func NewMetrics(namespace string) *Metrics {
+ return &Metrics{
+ AliveClients: promauto.NewGauge(prometheus.GaugeOpts{
+ Namespace: namespace,
+ Subsystem: "server",
+ Name: "alive_clients",
+ Help: "Number of alive clients",
+ }),
+ }
+}
diff --git a/components/neo/internal/server/exploits/server.go b/components/neo/internal/server/exploits/server.go
new file mode 100644
index 0000000..bf7f021
--- /dev/null
+++ b/components/neo/internal/server/exploits/server.go
@@ -0,0 +1,236 @@
+package exploits
+
+import (
+ "context"
+ "fmt"
+ "path/filepath"
+ "regexp"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/google/uuid"
+ "google.golang.org/grpc/codes"
+
+ "github.com/c4t-but-s4d/neo/v2/internal/config"
+ "github.com/c4t-but-s4d/neo/v2/internal/server/common"
+ serverConfig "github.com/c4t-but-s4d/neo/v2/internal/server/config"
+ "github.com/c4t-but-s4d/neo/v2/pkg/gstream"
+ "github.com/c4t-but-s4d/neo/v2/pkg/hostbucket"
+ "github.com/c4t-but-s4d/neo/v2/pkg/pubsub"
+ epb "github.com/c4t-but-s4d/neo/v2/proto/go/exploits"
+)
+
+func New(cfg *serverConfig.Config, storage *CachedStorage) *Server {
+ ems := &Server{
+ LoggingServer: common.NewLoggingServer("exploits"),
+ storage: storage,
+ buckets: hostbucket.New(cfg.FarmConfig.Teams),
+ visits: newVisitsMap(),
+ singleRunPubSub: pubsub.NewPubSub[*epb.SingleRunRequest](),
+ broadcastPubSub: pubsub.NewPubSub[*epb.BroadcastRequest](),
+ metrics: NewMetrics(cfg.MetricsNamespace),
+ }
+ ems.UpdateConfig(cfg)
+ return ems
+}
+
+type Server struct {
+ epb.UnimplementedServiceServer
+ common.LoggingServer
+
+ storage *CachedStorage
+ config *config.ExploitsConfig
+ cfgMutex sync.RWMutex
+ buckets *hostbucket.HostBucket
+ visits *visitsMap
+ metrics *Metrics
+
+ singleRunPubSub *pubsub.PubSub[*epb.SingleRunRequest]
+ broadcastPubSub *pubsub.PubSub[*epb.BroadcastRequest]
+}
+
+func (s *Server) Ping(ctx context.Context, r *epb.PingRequest) (*epb.PingResponse, error) {
+ s.LogRequest(ctx, r)
+ if r == nil {
+ return nil, s.WrapErrorf(ctx, codes.InvalidArgument, "требуется запрос Ping")
+ }
+
+ switch p := r.Payload.(type) {
+ case *epb.PingRequest_ServerInfoRequest:
+ // Пропустить эту запись.
+ case *epb.PingRequest_HeartbeatRequest:
+ s.cfgMutex.RLock()
+ defer s.cfgMutex.RUnlock()
+ s.visits.Add(r.ClientId)
+ s.buckets.AddNode(r.ClientId, int(p.HeartbeatRequest.Weight))
+ case *epb.PingRequest_LeaveRequest:
+ s.visits.MarkInvalid(r.ClientId)
+ default:
+ return nil, s.WrapErrorf(ctx, codes.InvalidArgument, "неизвестный тип данных: %T", p)
+ }
+
+ return &epb.PingResponse{
+ State: &epb.ServerState{
+ ClientTeamMap: s.buckets.Buckets(),
+ Exploits: s.storage.States(),
+ Config: config.ToProto(s.config),
+ },
+ }, nil
+}
+
+func (s *Server) Exploit(ctx context.Context, r *epb.ExploitRequest) (*epb.ExploitResponse, error) {
+ s.LogRequest(ctx, r)
+ if r == nil || !validExploitID(r.ExploitId) {
+ return nil, s.WrapErrorf(ctx, codes.InvalidArgument, "неверный идентификатор эксплойта")
+ }
+
+ state, ok := s.storage.GetState(r.ExploitId)
+ if !ok {
+ return nil, s.WrapErrorf(ctx, codes.NotFound, "эксплойт %q не найден", r.ExploitId)
+ }
+ return &epb.ExploitResponse{
+ State: state,
+ }, nil
+}
+
+func (s *Server) UpdateExploit(ctx context.Context, r *epb.UpdateExploitRequest) (*epb.UpdateExploitResponse, error) {
+ s.LogRequest(ctx, r)
+ if r == nil || r.State == nil || r.State.Config == nil || r.State.File == nil ||
+ !validExploitID(r.State.ExploitId) || !validFileUUID(r.State.File.Uuid) {
+ return nil, s.WrapErrorf(ctx, codes.InvalidArgument, "неверное состояние эксплойта")
+ }
+ if r.State.Config.IsArchive && (r.State.Config.Entrypoint == "" ||
+ strings.ContainsAny(r.State.Config.Entrypoint, "\\\x00") || !filepath.IsLocal(r.State.Config.Entrypoint)) {
+ return nil, s.WrapErrorf(ctx, codes.InvalidArgument, "неверный путь точки входа в архиве")
+ }
+
+ newState, err := s.storage.UpdateExploitVersion(r.State)
+ if err != nil {
+ return nil, s.WrapErrorf(ctx, codes.Internal, "Не удалось обновить версию эксплойта: %v", err)
+ }
+ return &epb.UpdateExploitResponse{State: newState}, nil
+}
+
+func validExploitID(id string) bool {
+ return id != "" && len(id) <= 128 && id != "." && id != ".." &&
+ !strings.ContainsAny(id, "/\\\x00") && filepath.IsLocal(id)
+}
+
+func validFileUUID(id string) bool {
+ parsed, err := uuid.Parse(id)
+ return err == nil && parsed.String() == id
+}
+
+func (s *Server) BroadcastCommand(ctx context.Context, r *epb.BroadcastRequest) (*epb.BroadcastResponse, error) {
+ s.LogRequest(ctx, r)
+
+ s.broadcastPubSub.Publish(r)
+ return &epb.BroadcastResponse{}, nil
+}
+
+func (s *Server) BroadcastSubscribe(r *epb.BroadcastSubscribeRequest, stream epb.Service_BroadcastSubscribeServer) error {
+ s.LogRequest(stream.Context(), r)
+
+ wstream := gstream.Wrap[
+ epb.BroadcastRequest,
+ epb.BroadcastSubscribeResponse,
+ ](
+ stream,
+ func(t *epb.BroadcastRequest) *epb.BroadcastSubscribeResponse {
+ return &epb.BroadcastSubscribeResponse{Command: t.Command}
+ },
+ )
+
+ sub := s.broadcastPubSub.Subscribe(wstream.Send)
+ defer s.broadcastPubSub.Unsubscribe(sub)
+
+ sub.Run(stream.Context())
+ return nil
+}
+
+func (s *Server) SingleRun(ctx context.Context, r *epb.SingleRunRequest) (*epb.SingleRunResponse, error) {
+ s.LogRequest(ctx, r)
+
+ s.singleRunPubSub.Publish(r)
+ return &epb.SingleRunResponse{}, nil
+}
+
+func (s *Server) SingleRunSubscribe(r *epb.SingleRunSubscribeRequest, stream epb.Service_SingleRunSubscribeServer) error {
+ s.LogRequest(stream.Context(), r)
+
+ wstream := gstream.Wrap[
+ epb.SingleRunRequest,
+ epb.SingleRunSubscribeResponse,
+ ](
+ stream,
+ func(t *epb.SingleRunRequest) *epb.SingleRunSubscribeResponse {
+ return &epb.SingleRunSubscribeResponse{ExploitId: t.ExploitId}
+ },
+ )
+
+ sub := s.singleRunPubSub.Subscribe(wstream.Send)
+ defer s.singleRunPubSub.Unsubscribe(sub)
+
+ sub.Run(stream.Context())
+ return nil
+}
+
+func (s *Server) HeartBeat(ctx context.Context) {
+ ticker := time.NewTicker(s.config.PingEvery)
+ defer ticker.Stop()
+ for {
+ select {
+ case <-ticker.C:
+ s.Logger.Info("Проверка клиентов")
+ s.checkClients()
+ case <-ctx.Done():
+ return
+ }
+ }
+}
+
+func (s *Server) UpdateMetrics(ctx context.Context) {
+ ticker := time.NewTicker(time.Second * 5)
+ defer ticker.Stop()
+ for {
+ select {
+ case <-ticker.C:
+ s.Logger.Info("Обновление метрик")
+ s.updateMetrics()
+ case <-ctx.Done():
+ return
+ }
+ }
+}
+
+func (s *Server) UpdateConfig(cfg *serverConfig.Config) {
+ env := make([]string, 0, len(cfg.Environ))
+ for k, v := range cfg.Environ {
+ env = append(env, fmt.Sprintf("%s=%s", k, v))
+ }
+
+ s.cfgMutex.Lock()
+ defer s.cfgMutex.Unlock()
+ s.config = &config.ExploitsConfig{
+ PingEvery: cfg.PingEvery,
+ SubmitEvery: cfg.SubmitEvery,
+ FarmURL: cfg.FarmConfig.URL,
+ FarmPassword: cfg.FarmConfig.Password,
+ FlagRegexp: regexp.MustCompile(cfg.FarmConfig.FlagRegexp),
+ Environ: env,
+ }
+ s.buckets.UpdateTeams(cfg.FarmConfig.Teams)
+}
+
+func (s *Server) checkClients() {
+ alive, dead := s.visits.Invalidate(time.Now(), s.config.PingEvery)
+ s.Logger.Infof("Проверка связи: недоступные клиенты %v, доступные клиенты %v", dead, alive)
+ for _, c := range dead {
+ s.buckets.DeleteNode(c)
+ }
+}
+
+func (s *Server) updateMetrics() {
+ s.metrics.AliveClients.Set(float64(s.visits.Size()))
+}
diff --git a/components/neo/internal/server/exploits/server_test.go b/components/neo/internal/server/exploits/server_test.go
new file mode 100644
index 0000000..42a8dee
--- /dev/null
+++ b/components/neo/internal/server/exploits/server_test.go
@@ -0,0 +1,165 @@
+package exploits
+
+import (
+ "context"
+ "fmt"
+ "testing"
+ "time"
+
+ "github.com/google/go-cmp/cmp"
+ "github.com/google/uuid"
+ "github.com/stretchr/testify/require"
+ "google.golang.org/protobuf/testing/protocmp"
+
+ "github.com/c4t-but-s4d/neo/v2/internal/server/config"
+ "github.com/c4t-but-s4d/neo/v2/pkg/hostbucket"
+ epb "github.com/c4t-but-s4d/neo/v2/proto/go/exploits"
+ fspb "github.com/c4t-but-s4d/neo/v2/proto/go/fileserver"
+)
+
+func testServer(t *testing.T) (*Server, func()) {
+ t.Helper()
+
+ db, cleanupDB := testDB()
+ st, err := NewStorage(db)
+ require.NoError(t, err)
+
+ require.NoError(t, err)
+
+ cfg := &config.Config{
+ BaseDir: t.TempDir(),
+ MetricsNamespace: fmt.Sprintf("tests_%s", uuid.NewString()[:8]),
+ }
+ es := New(cfg, st)
+ return es, cleanupDB
+}
+
+func TestServer_UpdateExploit(t *testing.T) {
+ es, clean := testServer(t)
+ defer clean()
+ fileID := uuid.NewString()
+ cfg := &epb.ExploitConfiguration{
+ Entrypoint: "bin",
+ IsArchive: false,
+ }
+ r := &epb.UpdateExploitRequest{
+ State: &epb.ExploitState{
+ ExploitId: "1",
+ File: &fspb.FileInfo{Uuid: fileID},
+ Config: cfg,
+ },
+ }
+ resp, err := es.UpdateExploit(context.Background(), r)
+ require.NoError(t, err)
+ want := &epb.ExploitState{
+ ExploitId: "1",
+ Version: 1,
+ File: r.State.File,
+ Config: cfg,
+ }
+ if diff := cmp.Diff(want, resp.State, protocmp.Transform()); diff != "" {
+ t.Errorf("UpdateExploit() mismatch (-want +got):\n%s", diff)
+ }
+}
+
+func TestServer_Exploit(t *testing.T) {
+ es, clean := testServer(t)
+ defer clean()
+ fileID := uuid.NewString()
+ cfg := &epb.ExploitConfiguration{
+ Entrypoint: "bin",
+ IsArchive: false,
+ }
+ state := &epb.ExploitState{
+ ExploitId: "1",
+ File: &fspb.FileInfo{Uuid: fileID},
+ Config: cfg,
+ }
+ req := &epb.UpdateExploitRequest{State: state}
+ ctx := context.Background()
+ _, err := es.UpdateExploit(ctx, req)
+ require.NoError(t, err)
+ resp, err := es.Exploit(ctx, &epb.ExploitRequest{ExploitId: state.ExploitId})
+ require.NoError(t, err)
+ wantState := &epb.ExploitState{
+ ExploitId: "1",
+ Version: 1,
+ File: state.File,
+ Config: cfg,
+ }
+ if diff := cmp.Diff(wantState, resp.State, protocmp.Transform()); diff != "" {
+ t.Errorf("Exploit() state mismatch (-want +got):\n%s", diff)
+ }
+}
+
+func TestServer_Ping(t *testing.T) {
+ es, clean := testServer(t)
+ defer clean()
+ fileID := uuid.NewString()
+ es.buckets = hostbucket.New(map[string]string{"id1": "ip1", "id2": "ip2"})
+ es.config.FarmURL = "test"
+ ctx := context.Background()
+ cfg := &epb.ExploitConfiguration{
+ Entrypoint: "bin",
+ IsArchive: false,
+ }
+ state := &epb.ExploitState{
+ ExploitId: "1",
+ File: &fspb.FileInfo{Uuid: fileID},
+ Config: cfg,
+ }
+ r := &epb.UpdateExploitRequest{State: state}
+ updateResp, err := es.UpdateExploit(ctx, r)
+ require.NoError(t, err)
+
+ const clientID = "id1"
+ req := &epb.PingRequest{
+ ClientId: clientID,
+ Payload: &epb.PingRequest_HeartbeatRequest{
+ HeartbeatRequest: &epb.PingRequest_Heartbeat{},
+ },
+ }
+ resp, err := es.Ping(ctx, req)
+ require.NoError(t, err)
+ want := []*epb.ExploitState{updateResp.State}
+ if diff := cmp.Diff(want, resp.State.Exploits, protocmp.Transform()); diff != "" {
+ t.Errorf("Ping() states mismatch (-want +got):\n%s", diff)
+ }
+ if diff := cmp.Diff(es.buckets.Buckets(), resp.State.ClientTeamMap, protocmp.Transform()); diff != "" {
+ t.Errorf("Ping() bucket mismatch (-want +got):\n%s", diff)
+ }
+ require.NotEmpty(t, es.buckets.Buckets()[clientID].Teams)
+ require.Equal(t, es.config.FarmURL, resp.State.Config.FarmUrl)
+ require.True(t, es.visits.visits["id1"].Before(time.Now()))
+}
+
+func TestServer_BroadcastCommand(t *testing.T) {
+ es, clean := testServer(t)
+ defer clean()
+
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+
+ var received *epb.BroadcastRequest
+ signal := make(chan struct{})
+ handler := func(msg *epb.BroadcastRequest) error {
+ received = msg
+ close(signal)
+ return nil
+ }
+ testSub := es.broadcastPubSub.Subscribe(handler)
+ defer es.broadcastPubSub.Unsubscribe(testSub)
+ go testSub.Run(ctx)
+
+ r := &epb.BroadcastRequest{Command: "echo 123"}
+ _, err := es.BroadcastCommand(ctx, r)
+ require.NoError(t, err)
+
+ select {
+ case <-signal:
+ break
+ case <-time.After(time.Millisecond * 100):
+ t.Errorf("Handler was not called in time")
+ }
+ require.Equal(t, r, received)
+}
diff --git a/components/neo/internal/server/exploits/storage.go b/components/neo/internal/server/exploits/storage.go
new file mode 100644
index 0000000..c6b4035
--- /dev/null
+++ b/components/neo/internal/server/exploits/storage.go
@@ -0,0 +1,133 @@
+package exploits
+
+import (
+ "fmt"
+ "strings"
+ "sync"
+
+ "github.com/samber/lo"
+ "github.com/sirupsen/logrus"
+ bolt "go.etcd.io/bbolt"
+ "google.golang.org/protobuf/proto"
+
+ epb "github.com/c4t-but-s4d/neo/v2/proto/go/exploits"
+)
+
+const (
+ stateBucketKey = "states"
+)
+
+func NewBoltStorage(path string) (*CachedStorage, error) {
+ db, err := bolt.Open(path, 0755, nil)
+ if err != nil {
+ return nil, fmt.Errorf("открытие базы Bolt %s: %w", path, err)
+ }
+ return NewStorage(db)
+}
+
+func NewStorage(db *bolt.DB) (*CachedStorage, error) {
+ cs := &CachedStorage{
+ stateCache: nil,
+ bdb: db,
+ }
+ if err := cs.initDB(); err != nil {
+ return nil, err
+ }
+ cs.initCache()
+ return cs, nil
+}
+
+type CachedStorage struct {
+ stateCache map[string]*epb.ExploitState
+ m sync.RWMutex
+ bdb *bolt.DB
+}
+
+func (cs *CachedStorage) States() []*epb.ExploitState {
+ cs.m.RLock()
+ defer cs.m.RUnlock()
+ return lo.Values(cs.stateCache)
+}
+
+func (cs *CachedStorage) GetState(exploitID string) (*epb.ExploitState, bool) {
+ cs.m.RLock()
+ defer cs.m.RUnlock()
+ val, ok := cs.stateCache[exploitID]
+ return val, ok
+}
+
+func (cs *CachedStorage) UpdateExploitVersion(newState *epb.ExploitState) (*epb.ExploitState, error) {
+ cs.m.Lock()
+ defer cs.m.Unlock()
+ if state, ok := cs.stateCache[newState.ExploitId]; ok {
+ newState.Version = state.Version + 1
+ } else {
+ newState.Version = 1
+ }
+
+ key := []byte(fmt.Sprintf("%s:%d", newState.ExploitId, newState.Version))
+ stateBytes, err := proto.Marshal(newState)
+ if err != nil {
+ return nil, fmt.Errorf("сериализация состояния: %w", err)
+ }
+
+ if err := cs.bdb.Update(func(tx *bolt.Tx) error {
+ b := tx.Bucket([]byte(stateBucketKey))
+ if err := b.Put(key, stateBytes); err != nil {
+ return fmt.Errorf("сохранение состояния в базе: %w", err)
+ }
+ return nil
+ }); err != nil {
+ return nil, fmt.Errorf("обновление состояния в базе: %w", err)
+ }
+
+ cs.stateCache[newState.ExploitId] = newState
+ return newState, nil
+}
+
+func (cs *CachedStorage) initCache() {
+ cs.m.Lock()
+ defer cs.m.Unlock()
+ if cs.stateCache == nil {
+ cs.stateCache = make(map[string]*epb.ExploitState)
+ if err := cs.readDB(); err != nil {
+ logrus.Errorf("Не удалось прочитать данные эксплойта из базы: %v", err)
+ }
+ }
+}
+
+func (cs *CachedStorage) readDB() error {
+ if err := cs.bdb.View(func(tx *bolt.Tx) error {
+ b := tx.Bucket([]byte(stateBucketKey))
+ if err := b.ForEach(func(k, v []byte) error {
+ key := string(k)
+ eID := strings.Split(key, ":")[0]
+ es := new(epb.ExploitState)
+ if err := proto.Unmarshal(v, es); err != nil {
+ return fmt.Errorf("разбор состояния эксплойта: %w", err)
+ }
+ if v, ok := cs.stateCache[eID]; !ok || es.Version > v.Version {
+ cs.stateCache[eID] = es
+ }
+ return nil
+ }); err != nil {
+ return fmt.Errorf("чтение состояний эксплойтов: %w", err)
+ }
+ return nil
+ }); err != nil {
+ return fmt.Errorf("чтение состояния из базы: %w", err)
+ }
+ return nil
+}
+
+func (cs *CachedStorage) initDB() error {
+ if err := cs.bdb.Update(func(tx *bolt.Tx) error {
+ if _, err := tx.CreateBucketIfNotExists([]byte(stateBucketKey)); err != nil {
+ return fmt.Errorf("создание раздела состояний: %w", err)
+ }
+ return nil
+ }); err != nil {
+ return fmt.Errorf("инициализация базы: %w", err)
+ }
+ return nil
+}
diff --git a/components/neo/internal/server/exploits/storage_test.go b/components/neo/internal/server/exploits/storage_test.go
new file mode 100644
index 0000000..490894d
--- /dev/null
+++ b/components/neo/internal/server/exploits/storage_test.go
@@ -0,0 +1,148 @@
+package exploits
+
+import (
+ "fmt"
+ "os"
+ "testing"
+
+ "github.com/google/go-cmp/cmp"
+ "github.com/sirupsen/logrus"
+ "github.com/stretchr/testify/require"
+ bolt "go.etcd.io/bbolt"
+ "google.golang.org/protobuf/proto"
+ "google.golang.org/protobuf/testing/protocmp"
+
+ epb "github.com/c4t-but-s4d/neo/v2/proto/go/exploits"
+ fspb "github.com/c4t-but-s4d/neo/v2/proto/go/fileserver"
+)
+
+func testDB() (*bolt.DB, func()) {
+ tmpFile, err := os.CreateTemp("", "db")
+ if err != nil {
+ panic(err)
+ }
+ db, err := bolt.Open(tmpFile.Name(), 0755, nil)
+ if err != nil {
+ panic(err)
+ }
+ return db, func() {
+ defer func(name string) {
+ err := os.Remove(name)
+ if err != nil {
+ logrus.Errorf("Error removing file: %v", err)
+ }
+ }(tmpFile.Name())
+ if err := db.Close(); err != nil {
+ panic(err)
+ }
+ }
+}
+
+func TestCachedStorage_States(t *testing.T) {
+ db, cleanup := testDB()
+ defer cleanup()
+ cs, err := NewStorage(db)
+ require.NoError(t, err)
+ for i := 0; i < 5; i++ {
+ state := &epb.ExploitState{
+ ExploitId: fmt.Sprintf("%d", i),
+ File: &fspb.FileInfo{Uuid: "1"},
+ Config: &epb.ExploitConfiguration{
+ Entrypoint: "./kek",
+ IsArchive: false,
+ },
+ }
+ _, err := cs.UpdateExploitVersion(state)
+ require.NoError(t, err)
+ }
+ require.Len(t, cs.States(), 5)
+}
+
+func TestCachedStorage_UpdateStates(t *testing.T) {
+ db, cleanup := testDB()
+ defer cleanup()
+ cs, err := NewStorage(db)
+ require.NoError(t, err)
+ state := &epb.ExploitState{
+ ExploitId: "1",
+ File: &fspb.FileInfo{Uuid: "1"},
+ Config: &epb.ExploitConfiguration{
+ Entrypoint: "./kek",
+ IsArchive: false,
+ },
+ }
+ _, err = cs.UpdateExploitVersion(state)
+ require.NoError(t, err)
+ require.EqualValues(t, 1, state.Version)
+ s, _ := cs.GetState(state.ExploitId)
+ if diff := cmp.Diff(state, s, protocmp.Transform()); diff != "" {
+ t.Errorf("UpdateExploitVersion(): unexpected state diff: (-want +got):\n%s", diff)
+ }
+ state = &epb.ExploitState{
+ ExploitId: "1",
+ File: &fspb.FileInfo{Uuid: "2"},
+ Config: &epb.ExploitConfiguration{
+ Entrypoint: "./kek2",
+ IsArchive: true,
+ },
+ }
+ _, err = cs.UpdateExploitVersion(state)
+ require.NoError(t, err)
+ require.Len(t, cs.States(), 1)
+ require.EqualValues(t, 2, state.Version)
+
+ s, _ = cs.GetState(state.ExploitId)
+ if diff := cmp.Diff(state, s, protocmp.Transform()); diff != "" {
+ t.Errorf("UpdateExploitVersion(): unexpected state diff: (-want +got):\n%s", diff)
+ }
+}
+
+func TestCachedStorage_UpdateExploitVersionDB(t *testing.T) {
+ db, cleanup := testDB()
+ defer cleanup()
+ cs, err := NewStorage(db)
+ require.NoError(t, err)
+
+ state := &epb.ExploitState{
+ ExploitId: "1",
+ File: &fspb.FileInfo{Uuid: "1"},
+ Config: &epb.ExploitConfiguration{
+ Entrypoint: "./kek",
+ IsArchive: false,
+ },
+ }
+ _, err = cs.UpdateExploitVersion(state)
+ require.NoError(t, err)
+ require.NoError(t, cs.readDB())
+ require.Len(t, cs.States(), 1)
+}
+
+// Проверка чтения кешированного хранилища из базы.
+func TestCachedStorage_readDB(t *testing.T) {
+ db, cleanup := testDB()
+ defer cleanup()
+ state := &epb.ExploitState{
+ ExploitId: "1",
+ Version: 1,
+ Config: &epb.ExploitConfiguration{
+ Entrypoint: "./kek",
+ IsArchive: false,
+ },
+ }
+ cs, err := NewStorage(db)
+ require.NoError(t, err)
+ require.NoError(t, cs.bdb.Update(func(tx *bolt.Tx) error {
+ b := tx.Bucket([]byte(stateBucketKey))
+ stateBytes, err := proto.Marshal(state)
+ require.NoError(t, err)
+ stateKey := []byte(fmt.Sprintf("%s:%d", state.ExploitId, state.Version))
+ if err := b.Put(stateKey, stateBytes); err != nil {
+ return fmt.Errorf("setting state in db: %w", err)
+ }
+ return nil
+ }))
+ require.NoError(t, cs.readDB())
+ if diff := cmp.Diff(state, cs.stateCache["1"], protocmp.Transform()); diff != "" {
+ t.Errorf("readDB(): unexpected diff for exploit with id = 1")
+ }
+}
diff --git a/components/neo/internal/server/exploits/visits.go b/components/neo/internal/server/exploits/visits.go
new file mode 100644
index 0000000..dcdf331
--- /dev/null
+++ b/components/neo/internal/server/exploits/visits.go
@@ -0,0 +1,56 @@
+package exploits
+
+import (
+ "sync"
+ "time"
+)
+
+const beatThreshold = 3
+
+func newVisitsMap() *visitsMap {
+ return &visitsMap{
+ visits: make(map[string]time.Time),
+ }
+}
+
+type visitsMap struct {
+ visits map[string]time.Time
+ m sync.Mutex
+}
+
+func (vm *visitsMap) Add(cid string) {
+ vm.m.Lock()
+ defer vm.m.Unlock()
+ vm.visits[cid] = time.Now()
+}
+
+// MarkInvalid сбрасывает время клиента, чтобы следующий вызов Invalidate удалил его.
+func (vm *visitsMap) MarkInvalid(cid string) {
+ vm.m.Lock()
+ defer vm.m.Unlock()
+ if _, ok := vm.visits[cid]; !ok {
+ return
+ }
+ vm.visits[cid] = time.Unix(0, 0)
+}
+
+func (vm *visitsMap) Invalidate(now time.Time, pingEvery time.Duration) (alive, dead []string) {
+ vm.m.Lock()
+ defer vm.m.Unlock()
+
+ for k, v := range vm.visits {
+ if v.Add(pingEvery * beatThreshold).Before(now) {
+ delete(vm.visits, k)
+ dead = append(dead, k)
+ } else {
+ alive = append(alive, k)
+ }
+ }
+ return alive, dead
+}
+
+func (vm *visitsMap) Size() int {
+ vm.m.Lock()
+ defer vm.m.Unlock()
+ return len(vm.visits)
+}
diff --git a/components/neo/internal/server/exploits/visits_test.go b/components/neo/internal/server/exploits/visits_test.go
new file mode 100644
index 0000000..fb7dcb1
--- /dev/null
+++ b/components/neo/internal/server/exploits/visits_test.go
@@ -0,0 +1,102 @@
+package exploits
+
+import (
+ "testing"
+ "time"
+
+ "github.com/google/go-cmp/cmp"
+ "github.com/google/go-cmp/cmp/cmpopts"
+
+ "github.com/c4t-but-s4d/neo/v2/pkg/testutils"
+)
+
+func TestVisitsMap_Invalidate(t *testing.T) {
+ generate := func(m map[string]time.Time) *visitsMap {
+ vm := newVisitsMap()
+ vm.visits = m
+ return vm
+ }
+ for _, tc := range []struct {
+ vm *visitsMap
+ dur string
+ now time.Time
+ want []string
+ }{
+ {
+ vm: generate(map[string]time.Time{"1": time.Unix(10, 0), "2": time.Unix(30, 0)}),
+ dur: "5s",
+ now: time.Unix(35, 0),
+ want: []string{"1"},
+ },
+ {
+ vm: generate(map[string]time.Time{"1": time.Unix(10, 0), "2": time.Unix(30, 0)}),
+ dur: "50s",
+ now: time.Unix(35, 0),
+ want: []string{},
+ },
+ {
+ vm: generate(map[string]time.Time{"1": time.Unix(10, 0), "2": time.Unix(30, 0)}),
+ dur: "1s",
+ now: time.Unix(35, 0),
+ want: []string{"1", "2"},
+ },
+ {
+ vm: generate(map[string]time.Time{"1": time.Unix(10, 0), "2": time.Unix(30, 0)}),
+ dur: "5s",
+ now: time.Unix(15, 0),
+ want: []string{},
+ },
+ } {
+ d, _ := time.ParseDuration(tc.dur)
+ _, invalid := tc.vm.Invalidate(tc.now, d)
+ if diff := cmp.Diff(tc.want, invalid, cmpopts.SortSlices(testutils.LessString), cmpopts.EquateEmpty()); diff != "" {
+ t.Errorf("Invalidate() ids mismatch (-want +got):\n%s", diff)
+ }
+ }
+}
+
+func Test_visitsMap_MarkForDeletion(t *testing.T) {
+ generate := func(m map[string]time.Time) *visitsMap {
+ vm := newVisitsMap()
+ vm.visits = m
+ return vm
+ }
+ for _, tc := range []struct {
+ vm *visitsMap
+ dur string
+ now time.Time
+ mark []string
+ want []string
+ }{
+ {
+ vm: generate(map[string]time.Time{"1": time.Unix(900, 0), "2": time.Unix(995, 0)}),
+ dur: "5s",
+ now: time.Unix(1000, 0),
+ mark: []string{"2"},
+ want: []string{"1", "2"},
+ },
+ {
+ vm: generate(map[string]time.Time{"1": time.Unix(900, 0), "2": time.Unix(995, 0)}),
+ dur: "100s",
+ now: time.Unix(1000, 0),
+ mark: []string{"1"},
+ want: []string{"1"},
+ },
+ {
+ vm: generate(map[string]time.Time{"1": time.Unix(900, 0), "2": time.Unix(995, 0)}),
+ dur: "100s",
+ now: time.Unix(1000, 0),
+ mark: []string{"1", "2"},
+ want: []string{"1", "2"},
+ },
+ } {
+ d, _ := time.ParseDuration(tc.dur)
+ for _, cid := range tc.mark {
+ tc.vm.MarkInvalid(cid)
+ }
+ _, invalid := tc.vm.Invalidate(tc.now, d)
+ if diff := cmp.Diff(tc.want, invalid, cmpopts.SortSlices(testutils.LessString), cmpopts.EquateEmpty()); diff != "" {
+ t.Errorf("MarkInvalid() ids mismatch (-want +got):\n%s", diff)
+ }
+ }
+}
diff --git a/components/neo/internal/server/fs/fs.go b/components/neo/internal/server/fs/fs.go
new file mode 100644
index 0000000..00044b2
--- /dev/null
+++ b/components/neo/internal/server/fs/fs.go
@@ -0,0 +1,88 @@
+package fs
+
+import (
+ "fmt"
+ "io"
+ "os"
+ "path/filepath"
+ "strings"
+
+ "github.com/google/uuid"
+)
+
+type fileInterface interface {
+ io.ReadWriteCloser
+ Name() string
+}
+
+type filesystem interface {
+ Create(string) (fileInterface, error)
+ Open(string) (fileInterface, error)
+ Remove(string) error
+}
+
+type osFs struct {
+ root *os.Root
+}
+
+func newOsFs(dir string) (*osFs, error) {
+ abs, err := filepath.Abs(dir)
+ if err != nil {
+ return nil, fmt.Errorf("определение пути каталога %s: %w", dir, err)
+ }
+ if err := os.MkdirAll(abs, 0700); err != nil {
+ return nil, fmt.Errorf("создание каталога %s: %w", dir, err)
+ }
+ root, err := os.OpenRoot(abs)
+ if err != nil {
+ return nil, fmt.Errorf("открытие каталога %s: %w", dir, err)
+ }
+ return &osFs{root: root}, nil
+}
+
+func (o *osFs) Create(f string) (fileInterface, error) {
+ if err := validateFileID(f); err != nil {
+ return nil, err
+ }
+ fi, err := o.root.OpenFile(f, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0600)
+ if err != nil {
+ return nil, fmt.Errorf("создание файла %s в %s: %w", f, o.root.Name(), err)
+ }
+ return fi, nil
+}
+
+func (o *osFs) Open(f string) (fileInterface, error) {
+ if err := validateFileID(f); err != nil {
+ return nil, err
+ }
+ info, err := o.root.Lstat(f)
+ if err != nil {
+ return nil, fmt.Errorf("открытие файла %s в %s: %w", f, o.root.Name(), err)
+ }
+ if !info.Mode().IsRegular() {
+ return nil, fmt.Errorf("путь %s в %s не является обычным файлом", f, o.root.Name())
+ }
+ fi, err := o.root.Open(f)
+ if err != nil {
+ return nil, fmt.Errorf("повторное открытие файла %s в %s: %w", f, o.root.Name(), err)
+ }
+ return fi, nil
+}
+
+func (o *osFs) Remove(f string) error {
+ if err := validateFileID(f); err != nil {
+ return err
+ }
+ if err := o.root.Remove(f); err != nil && !os.IsNotExist(err) {
+ return fmt.Errorf("удаление файла %s в %s: %w", f, o.root.Name(), err)
+ }
+ return nil
+}
+
+func validateFileID(id string) error {
+ parsed, err := uuid.Parse(id)
+ if err != nil || parsed.String() != id || strings.ContainsAny(id, `/\\`) {
+ return fmt.Errorf("неверный идентификатор файла")
+ }
+ return nil
+}
diff --git a/components/neo/internal/server/fs/fs_test.go b/components/neo/internal/server/fs/fs_test.go
new file mode 100644
index 0000000..e37273f
--- /dev/null
+++ b/components/neo/internal/server/fs/fs_test.go
@@ -0,0 +1,35 @@
+package fs
+
+import (
+ "os"
+ "path/filepath"
+ "testing"
+
+ "github.com/google/uuid"
+ "github.com/stretchr/testify/require"
+)
+
+func TestOSFSRejectsTraversalAndSymlink(t *testing.T) {
+ rootPath := t.TempDir()
+ root, err := newOsFs(rootPath)
+ require.NoError(t, err)
+ t.Cleanup(func() { _ = root.root.Close() })
+
+ _, err = root.Create("../outside")
+ require.Error(t, err)
+
+ id := uuid.NewString()
+ outside := filepath.Join(t.TempDir(), "outside")
+ require.NoError(t, os.WriteFile(outside, []byte("secret"), 0600))
+ require.NoError(t, os.Symlink(outside, filepath.Join(rootPath, id)))
+ _, err = root.Open(id)
+ require.Error(t, err)
+ require.Equal(t, "secret", mustRead(t, outside))
+}
+
+func mustRead(t *testing.T, name string) string {
+ t.Helper()
+ data, err := os.ReadFile(name)
+ require.NoError(t, err)
+ return string(data)
+}
diff --git a/components/neo/internal/server/fs/server.go b/components/neo/internal/server/fs/server.go
new file mode 100644
index 0000000..cf23a55
--- /dev/null
+++ b/components/neo/internal/server/fs/server.go
@@ -0,0 +1,86 @@
+package fs
+
+import (
+ "fmt"
+
+ "github.com/google/uuid"
+ "github.com/sirupsen/logrus"
+ "google.golang.org/grpc/codes"
+
+ "github.com/c4t-but-s4d/neo/v2/internal/server/common"
+ serverConfig "github.com/c4t-but-s4d/neo/v2/internal/server/config"
+ "github.com/c4t-but-s4d/neo/v2/internal/server/utils"
+ "github.com/c4t-but-s4d/neo/v2/pkg/filestream"
+ fspb "github.com/c4t-but-s4d/neo/v2/proto/go/fileserver"
+)
+
+func New(cfg *serverConfig.Config) (*Server, error) {
+ fs, err := newOsFs(cfg.BaseDir)
+ if err != nil {
+ return nil, fmt.Errorf("создание файлового хранилища: %w", err)
+ }
+ ems := &Server{
+ LoggingServer: common.NewLoggingServer("fileserver"),
+
+ fs: fs,
+ }
+ return ems, nil
+}
+
+type Server struct {
+ fspb.UnimplementedServiceServer
+ common.LoggingServer
+
+ fs filesystem
+}
+
+func (s *Server) UploadFile(stream fspb.Service_UploadFileServer) (retErr error) {
+ info := &fspb.FileInfo{Uuid: uuid.NewString()}
+ s.GetMethodLogger(stream.Context()).Infof("New file upload: %v", info)
+
+ of, err := s.fs.Create(info.Uuid)
+ if err != nil {
+ return utils.WrapErrorf(codes.Internal, "Не удалось создать файл: %v", err)
+ }
+ defer func() {
+ if cerr := of.Close(); cerr != nil {
+ if retErr == nil {
+ retErr = utils.WrapErrorf(codes.Internal, "Не удалось закрыть файл назначения")
+ }
+ }
+ if retErr != nil {
+ if rerr := s.fs.Remove(info.Uuid); rerr != nil {
+ logrus.Errorf("Не удалось удалить незавершенную загрузку: %v", rerr)
+ }
+ }
+ }()
+
+ if err := filestream.SaveLimit(stream, of, filestream.MaxFileSize); err != nil {
+ return utils.WrapErrorf(codes.ResourceExhausted, "Не удалось принять файл из потока: %v", err)
+ }
+ if err := stream.SendAndClose(info); err != nil {
+ return utils.WrapErrorf(codes.Internal, "Не удалось отправить ответ и закрыть соединение: %v", err)
+ }
+ return nil
+}
+
+func (s *Server) DownloadFile(fi *fspb.FileInfo, stream fspb.Service_DownloadFileServer) error {
+ s.LogRequest(stream.Context(), fi)
+ if fi == nil {
+ return utils.WrapErrorf(codes.InvalidArgument, "Требуется идентификатор файла")
+ }
+
+ f, err := s.fs.Open(fi.Uuid)
+ if err != nil {
+ return utils.WrapErrorf(codes.NotFound, "Не удалось найти файл с uuid %s: %v", fi.Uuid, err)
+ }
+ defer func() {
+ if err := f.Close(); err != nil {
+ logrus.Errorf("Не удалось закрыть скачанный файл: %v", err)
+ }
+ }()
+ if err := filestream.Load(f, stream); err != nil {
+ return utils.WrapErrorf(codes.NotFound, "Не удалось найти файл с uuid %s: %v", fi.Uuid, err)
+ }
+ return nil
+}
diff --git a/components/neo/internal/server/logs/logline.go b/components/neo/internal/server/logs/logline.go
new file mode 100644
index 0000000..b0da198
--- /dev/null
+++ b/components/neo/internal/server/logs/logline.go
@@ -0,0 +1,72 @@
+package server
+
+import (
+ "fmt"
+ "strconv"
+
+ "github.com/mitchellh/mapstructure"
+
+ logspb "github.com/c4t-but-s4d/neo/v2/proto/go/logs"
+)
+
+func NewLogLineFromValues(vals map[string]interface{}) (*LogLine, error) {
+ var line LogLine
+ if err := mapstructure.Decode(vals, &line); err != nil {
+ return nil, fmt.Errorf("разбор структуры строки журнала: %w", err)
+ }
+ return &line, nil
+}
+
+func NewLogLineFromProto(p *logspb.LogLine) *LogLine {
+ return &LogLine{
+ Exploit: p.Exploit,
+ Version: strconv.FormatInt(p.Version, 10),
+ Message: p.Message,
+ Level: p.Level,
+ Team: p.Team,
+ }
+}
+
+type LogLine struct {
+ Exploit string `mapstructure:"exploit"`
+ Version string `mapstructure:"version"`
+ Message string `mapstructure:"message"`
+ Level string `mapstructure:"level"`
+ Team string `mapstructure:"team"`
+}
+
+func (l *LogLine) String() string {
+ return fmt.Sprintf("Line(%s.v%s)", l.Exploit, l.Version)
+}
+
+func (l *LogLine) DumpValues() (map[string]interface{}, error) {
+ res := make(map[string]interface{})
+ if err := mapstructure.Decode(l, &res); err != nil {
+ return nil, fmt.Errorf("кодирование структуры строки журнала: %w", err)
+ }
+ return res, nil
+}
+
+func (l *LogLine) EstimateSize() int {
+ const (
+ estNum = 5
+ estDenom = 4
+ structSize = 8 * 5
+ )
+ sizeEst := structSize + len(l.Exploit) + len(l.Version) + len(l.Message) + len(l.Level) + len(l.Team)
+ return sizeEst * estNum / estDenom
+}
+
+func (l *LogLine) ToProto() (*logspb.LogLine, error) {
+ version, err := strconv.ParseInt(l.Version, 10, 64)
+ if err != nil {
+ return nil, fmt.Errorf("преобразование версии %v: %w", l.Version, err)
+ }
+ return &logspb.LogLine{
+ Exploit: l.Exploit,
+ Version: version,
+ Message: l.Message,
+ Level: l.Level,
+ Team: l.Team,
+ }, nil
+}
diff --git a/components/neo/internal/server/logs/server.go b/components/neo/internal/server/logs/server.go
new file mode 100644
index 0000000..7264dd9
--- /dev/null
+++ b/components/neo/internal/server/logs/server.go
@@ -0,0 +1,93 @@
+package server
+
+import (
+ "context"
+ "fmt"
+
+ "google.golang.org/grpc/codes"
+ "google.golang.org/protobuf/types/known/emptypb"
+
+ "github.com/c4t-but-s4d/neo/v2/internal/server/common"
+ "github.com/c4t-but-s4d/neo/v2/internal/server/utils"
+ "github.com/c4t-but-s4d/neo/v2/pkg/gstream"
+ logspb "github.com/c4t-but-s4d/neo/v2/proto/go/logs"
+)
+
+const (
+ logLinesBatchSize = 100
+ maxMsgSize = 4 * 1024 * 1024
+)
+
+func New(storage *LogStorage) *Server {
+ return &Server{
+ LoggingServer: common.NewLoggingServer("logs"),
+
+ storage: storage,
+ }
+}
+
+type Server struct {
+ logspb.UnimplementedServiceServer
+ common.LoggingServer
+
+ storage *LogStorage
+}
+
+func (s *Server) AddLogLines(ctx context.Context, lines *logspb.AddLogLinesRequest) (*emptypb.Empty, error) {
+ s.GetMethodLogger(ctx).Infof("New request with %d lines", len(lines.Lines))
+
+ decoded := make([]LogLine, 0, len(lines.Lines))
+ for _, line := range lines.Lines {
+ decoded = append(decoded, *NewLogLineFromProto(line))
+ }
+ if err := s.storage.Add(ctx, decoded); err != nil {
+ return nil, utils.WrapErrorf(codes.Internal, "добавление строк журнала: %v", err)
+ }
+ return &emptypb.Empty{}, nil
+}
+
+func (s *Server) SearchLogLines(req *logspb.SearchLogLinesRequest, stream logspb.Service_SearchLogLinesServer) error {
+ s.LogRequest(stream.Context(), req)
+
+ opts := GetOptions{
+ Exploit: req.Exploit,
+ Version: req.Version,
+ }
+ lines, err := s.storage.Get(stream.Context(), opts)
+ if err != nil {
+ return utils.WrapErrorf(codes.Internal, "поиск строк журнала: %v", err)
+ }
+
+ cache := gstream.NewDynamicSizeCache[*LogLine, logspb.SearchLogLinesResponse](
+ stream,
+ maxMsgSize,
+ func(lines []*LogLine) (*logspb.SearchLogLinesResponse, error) {
+ resp := &logspb.SearchLogLinesResponse{
+ Lines: make([]*logspb.LogLine, 0, len(lines)),
+ }
+ for _, line := range lines {
+ protoLine, err := line.ToProto()
+ if err != nil {
+ return nil, fmt.Errorf("преобразование строки журнала: %w", err)
+ }
+ resp.Lines = append(resp.Lines, protoLine)
+ }
+ return resp, nil
+ },
+ )
+
+ for i, line := range lines {
+ if err := cache.Queue(line); err != nil {
+ return utils.WrapErrorf(codes.Internal, "добавление строки журнала в очередь: %v", err)
+ }
+ if (i-1+logLinesBatchSize)%logLinesBatchSize == 0 {
+ if err := cache.Flush(); err != nil {
+ return utils.WrapErrorf(codes.Internal, "отправка накопленных строк: %v", err)
+ }
+ }
+ }
+ if err := cache.Flush(); err != nil {
+ return utils.WrapErrorf(codes.Internal, "отправка последних строк: %v", err)
+ }
+ return nil
+}
diff --git a/components/neo/internal/server/logs/storage.go b/components/neo/internal/server/logs/storage.go
new file mode 100644
index 0000000..c2feace
--- /dev/null
+++ b/components/neo/internal/server/logs/storage.go
@@ -0,0 +1,80 @@
+package server
+
+import (
+ "context"
+ "fmt"
+ "strconv"
+
+ "github.com/redis/go-redis/v9"
+)
+
+const (
+ linesPerSploitLimit = 100000
+)
+
+func NewLogStorage(ctx context.Context, redisURL string) (*LogStorage, error) {
+ opts, err := redis.ParseURL(redisURL)
+ if err != nil {
+ return nil, fmt.Errorf("неверный адрес Redis: %w", err)
+ }
+ c := redis.NewClient(opts)
+ if err := c.Ping(ctx).Err(); err != nil {
+ return nil, fmt.Errorf("подключение к Redis: %w", err)
+ }
+ return &LogStorage{rdb: c}, nil
+}
+
+type LogStorage struct {
+ rdb *redis.Client
+}
+
+func (s *LogStorage) Add(ctx context.Context, lines []LogLine) error {
+ if _, err := s.rdb.Pipelined(ctx, func(pipe redis.Pipeliner) error {
+ for _, line := range lines {
+ key := getRedisStream(line.Exploit, line.Version)
+ vals, err := line.DumpValues()
+ if err != nil {
+ return fmt.Errorf("сериализация строки журнала: %w", err)
+ }
+ args := redis.XAddArgs{
+ Stream: key,
+ MaxLen: linesPerSploitLimit,
+ Approx: true,
+ Values: vals,
+ }
+ if err := pipe.XAdd(ctx, &args).Err(); err != nil {
+ return fmt.Errorf("добавление строки журнала: %w", err)
+ }
+ }
+ return nil
+ }); err != nil {
+ return fmt.Errorf("выполнение пакета команд Redis: %w", err)
+ }
+ return nil
+}
+
+func (s *LogStorage) Get(ctx context.Context, opts GetOptions) ([]*LogLine, error) {
+ key := getRedisStream(opts.Exploit, strconv.FormatInt(opts.Version, 10))
+ res, err := s.rdb.XRange(ctx, key, "-", "+").Result()
+ if err != nil {
+ return nil, fmt.Errorf("чтение потока %s: %w", key, err)
+ }
+ lines := make([]*LogLine, 0, len(res))
+ for _, msg := range res {
+ line, err := NewLogLineFromValues(msg.Values)
+ if err != nil {
+ return nil, fmt.Errorf("разбор строки журнала из Redis: %w", err)
+ }
+ lines = append(lines, line)
+ }
+ return lines, nil
+}
+
+type GetOptions struct {
+ Exploit string
+ Version int64
+}
+
+func getRedisStream(exploit string, version string) string {
+ return fmt.Sprintf("logs:%s:%s", exploit, version)
+}
diff --git a/components/neo/internal/server/utils/logging.go b/components/neo/internal/server/utils/logging.go
new file mode 100644
index 0000000..f709bf2
--- /dev/null
+++ b/components/neo/internal/server/utils/logging.go
@@ -0,0 +1,13 @@
+package utils
+
+import (
+ "github.com/sirupsen/logrus"
+ "google.golang.org/grpc/codes"
+ "google.golang.org/grpc/status"
+)
+
+func WrapErrorf(code codes.Code, fmt string, values ...interface{}) error {
+ err := status.Errorf(code, fmt, values...)
+ logrus.Errorf("%v", err)
+ return err // nolint
+}
diff --git a/components/neo/pkg/archive/targz.go b/components/neo/pkg/archive/targz.go
new file mode 100644
index 0000000..1b1e8ab
--- /dev/null
+++ b/components/neo/pkg/archive/targz.go
@@ -0,0 +1,167 @@
+package archive
+
+import (
+ "archive/tar"
+ "compress/gzip"
+ "errors"
+ "fmt"
+ "io"
+ "os"
+ "path/filepath"
+ "strings"
+
+ "github.com/sirupsen/logrus"
+)
+
+const (
+ maxArchiveEntries = 10000
+ maxArchiveExpanded = 512 << 20
+)
+
+func Untar(dst string, r io.Reader) error {
+ abs, err := filepath.Abs(dst)
+ if err != nil {
+ return fmt.Errorf("определение пути назначения: %w", err)
+ }
+ if err := os.MkdirAll(abs, 0700); err != nil {
+ return fmt.Errorf("создание каталога %s: %w", dst, err)
+ }
+ root, err := os.OpenRoot(abs)
+ if err != nil {
+ return fmt.Errorf("открытие каталога назначения %s: %w", dst, err)
+ }
+ defer root.Close()
+
+ gzr, err := gzip.NewReader(r)
+ if err != nil {
+ return fmt.Errorf("создание gzip-читателя: %w", err)
+ }
+ defer func() {
+ if err := gzr.Close(); err != nil {
+ logrus.Errorf("Ошибка закрытия gzip-потока: %v", err)
+ }
+ }()
+
+ tr := tar.NewReader(gzr)
+ entries := 0
+ var expanded int64
+ for {
+ header, err := tr.Next()
+ if errors.Is(err, io.EOF) {
+ return nil
+ }
+ if err != nil {
+ return fmt.Errorf("чтение заголовка архива: %w", err)
+ }
+ if header == nil {
+ continue
+ }
+
+ entries++
+ if entries > maxArchiveEntries {
+ return fmt.Errorf("в архиве больше %d записей", maxArchiveEntries)
+ }
+ if strings.Contains(header.Name, `\`) || !filepath.IsLocal(header.Name) {
+ return fmt.Errorf("небезопасный путь в архиве: %q", header.Name)
+ }
+ name := filepath.Clean(header.Name)
+ if name == "." && header.Typeflag != tar.TypeDir {
+ return fmt.Errorf("у файла в архиве пустой путь")
+ }
+
+ switch header.Typeflag {
+ case tar.TypeDir:
+ if name != "." {
+ if err := root.MkdirAll(name, 0700); err != nil {
+ return fmt.Errorf("создание каталога %s: %w", name, err)
+ }
+ }
+ case tar.TypeReg, tar.TypeRegA:
+ if header.Size < 0 || header.Size > maxArchiveExpanded-expanded {
+ return fmt.Errorf("распакованный архив превышает %d байт", maxArchiveExpanded)
+ }
+ parent := filepath.Dir(name)
+ if parent != "." {
+ if err := root.MkdirAll(parent, 0700); err != nil {
+ return fmt.Errorf("создание каталога %s: %w", parent, err)
+ }
+ }
+ mode := os.FileMode(0600) | (os.FileMode(header.Mode) & 0100)
+ f, err := root.OpenFile(name, os.O_CREATE|os.O_EXCL|os.O_WRONLY, mode)
+ if err != nil {
+ return fmt.Errorf("создание файла %s: %w", name, err)
+ }
+ if _, err := io.CopyN(f, tr, header.Size); err != nil {
+ _ = f.Close()
+ _ = root.Remove(name)
+ return fmt.Errorf("копирование файла %s: %w", name, err)
+ }
+ if err := f.Close(); err != nil {
+ _ = root.Remove(name)
+ return fmt.Errorf("закрытие файла %s: %w", name, err)
+ }
+ expanded += header.Size
+ default:
+ return fmt.Errorf("неподдерживаемый тип записи архива %q", header.Name)
+ }
+ }
+}
+
+func Tar(src string, w io.Writer) error {
+ root, err := filepath.Abs(src)
+ if err != nil {
+ return fmt.Errorf("определение исходного каталога: %w", err)
+ }
+ if _, err := os.Stat(root); err != nil {
+ return fmt.Errorf("исходные данные недоступны: %w", err)
+ }
+
+ gzw := gzip.NewWriter(w)
+ tw := tar.NewWriter(gzw)
+ walkErr := filepath.Walk(root, func(file string, fi os.FileInfo, err error) error {
+ if err != nil {
+ return err
+ }
+ if fi.Mode()&os.ModeSymlink != 0 || !fi.Mode().IsRegular() && !fi.IsDir() {
+ return fmt.Errorf("неподдерживаемый тип исходного файла: %s", file)
+ }
+ name, err := filepath.Rel(root, file)
+ if err != nil {
+ return fmt.Errorf("определение пути архива: %w", err)
+ }
+ header, err := tar.FileInfoHeader(fi, fi.Name())
+ if err != nil {
+ return fmt.Errorf("создание заголовка архива: %w", err)
+ }
+ header.Name = name
+ if err := tw.WriteHeader(header); err != nil {
+ return fmt.Errorf("запись заголовка архива: %w", err)
+ }
+ if fi.IsDir() {
+ return nil
+ }
+ f, err := os.Open(file)
+ if err != nil {
+ return fmt.Errorf("открытие файла %s: %w", file, err)
+ }
+ _, copyErr := io.Copy(tw, f)
+ closeErr := f.Close()
+ if copyErr != nil {
+ return fmt.Errorf("копирование файла %s: %w", file, copyErr)
+ }
+ if closeErr != nil {
+ return fmt.Errorf("закрытие файла %s: %w", file, closeErr)
+ }
+ return nil
+ })
+ if closeErr := tw.Close(); walkErr == nil {
+ walkErr = closeErr
+ }
+ if closeErr := gzw.Close(); walkErr == nil {
+ walkErr = closeErr
+ }
+ if walkErr != nil {
+ return fmt.Errorf("упаковка каталога %s: %w", src, walkErr)
+ }
+ return nil
+}
diff --git a/components/neo/pkg/archive/targz_test.go b/components/neo/pkg/archive/targz_test.go
new file mode 100644
index 0000000..1d9dc33
--- /dev/null
+++ b/components/neo/pkg/archive/targz_test.go
@@ -0,0 +1,91 @@
+package archive
+
+import (
+ "archive/tar"
+ "bytes"
+ "compress/gzip"
+ "fmt"
+ "os"
+ "path/filepath"
+ "testing"
+
+ "github.com/stretchr/testify/require"
+)
+
+func testTarGz(t *testing.T, headers []tar.Header, bodies [][]byte) *bytes.Buffer {
+ t.Helper()
+ var buf bytes.Buffer
+ gz := gzip.NewWriter(&buf)
+ tw := tar.NewWriter(gz)
+ for i := range headers {
+ require.NoError(t, tw.WriteHeader(&headers[i]))
+ if headers[i].Typeflag == tar.TypeReg || headers[i].Typeflag == tar.TypeRegA {
+ if len(bodies[i]) > 0 {
+ _, err := tw.Write(bodies[i])
+ require.NoError(t, err)
+ }
+ }
+ }
+ require.NoError(t, tw.Close())
+ require.NoError(t, gz.Close())
+ return &buf
+}
+
+func TestUntarRejectsEscapingPathsAndLinks(t *testing.T) {
+ for _, header := range []tar.Header{
+ {Name: "../outside", Typeflag: tar.TypeReg, Mode: 0600, Size: 1},
+ {Name: "/tmp/outside", Typeflag: tar.TypeReg, Mode: 0600, Size: 1},
+ {Name: "link", Typeflag: tar.TypeSymlink, Linkname: "../outside", Mode: 0777},
+ {Name: "hardlink", Typeflag: tar.TypeLink, Linkname: "../outside", Mode: 0600},
+ } {
+ t.Run(header.Name, func(t *testing.T) {
+ dst := t.TempDir()
+ archive := testTarGz(t, []tar.Header{header}, [][]byte{{'x'}})
+ require.Error(t, Untar(dst, archive))
+ require.NoError(t, filepath.WalkDir(dst, func(_ string, d os.DirEntry, err error) error {
+ if err != nil {
+ return err
+ }
+ if d.Type()&os.ModeSymlink != 0 {
+ t.Errorf("archive created a symlink: %s", d.Name())
+ }
+ return nil
+ }))
+ })
+ }
+}
+
+func TestUntarRejectsExpandedSizeLimit(t *testing.T) {
+ var buf bytes.Buffer
+ gz := gzip.NewWriter(&buf)
+ tw := tar.NewWriter(gz)
+ require.NoError(t, tw.WriteHeader(&tar.Header{
+ Name: "large", Typeflag: tar.TypeReg, Mode: 0600, Size: maxArchiveExpanded + 1,
+ }))
+ require.NoError(t, gz.Close())
+ require.ErrorContains(t, Untar(t.TempDir(), &buf), "превышает")
+}
+
+func TestUntarPreservesOnlyOwnerExecute(t *testing.T) {
+ dst := t.TempDir()
+ archive := testTarGz(t, []tar.Header{
+ {Name: "main", Typeflag: tar.TypeReg, Mode: 0755, Size: 1},
+ {Name: "helper", Typeflag: tar.TypeReg, Mode: 0755, Size: 1},
+ }, [][]byte{{'m'}, {'h'}})
+ require.NoError(t, Untar(dst, archive))
+ for _, name := range []string{"main", "helper"} {
+ info, err := os.Stat(filepath.Join(dst, name))
+ require.NoError(t, err)
+ require.Equal(t, os.FileMode(0700), info.Mode().Perm())
+ }
+}
+
+func TestUntarRejectsTooManyEntries(t *testing.T) {
+ headers := make([]tar.Header, maxArchiveEntries+1)
+ bodies := make([][]byte, len(headers))
+ for i := range headers {
+ headers[i] = tar.Header{Name: fmt.Sprintf("entry/%d", i), Typeflag: tar.TypeDir, Mode: 0700}
+ }
+ archive := testTarGz(t, headers, bodies)
+ require.ErrorContains(t, Untar(t.TempDir(), archive), "больше")
+}
diff --git a/components/neo/pkg/filestream/filestream.go b/components/neo/pkg/filestream/filestream.go
new file mode 100644
index 0000000..901c440
--- /dev/null
+++ b/components/neo/pkg/filestream/filestream.go
@@ -0,0 +1,70 @@
+package filestream
+
+import (
+ "errors"
+ "fmt"
+ "io"
+
+ fspb "github.com/c4t-but-s4d/neo/v2/proto/go/fileserver"
+)
+
+const (
+ chunkSize = 2 * 1024 * 1024 // 2MB
+ // MaxFileSize ограничивает размер файлов, передаваемых по gRPC.
+ MaxFileSize int64 = 128 << 20
+)
+
+type DownloadStream interface {
+ Recv() (*fspb.FileStream, error)
+}
+
+type UploadStream interface {
+ Send(*fspb.FileStream) error
+}
+
+func Save(stream DownloadStream, out io.Writer) error {
+ return SaveLimit(stream, out, 0)
+}
+
+// SaveLimit копирует поток с ограничением размера. Нулевой лимит означает,
+// что размер не ограничен; так сохраняется совместимость с вызывающим кодом,
+// который устанавливает собственный предел.
+func SaveLimit(stream DownloadStream, out io.Writer, limit int64) error {
+ var total int64
+ for {
+ in, err := stream.Recv()
+ if errors.Is(err, io.EOF) {
+ return nil
+ }
+ if err != nil {
+ return fmt.Errorf("чтение из потока: %w", err)
+ }
+ if limit > 0 && (int64(len(in.Chunk)) > limit-total) {
+ return fmt.Errorf("размер файла превышает лимит %d байт", limit)
+ }
+ n, err := out.Write(in.Chunk)
+ if err != nil {
+ return fmt.Errorf("запись части потока: %w", err)
+ }
+ if n != len(in.Chunk) {
+ return io.ErrShortWrite
+ }
+ total += int64(n)
+ }
+}
+
+func Load(in io.Reader, stream UploadStream) error {
+ b := make([]byte, chunkSize)
+ for {
+ n, err := in.Read(b)
+ if errors.Is(err, io.EOF) {
+ return nil
+ }
+ if err != nil {
+ return fmt.Errorf("чтение содержимого: %w", err)
+ }
+ if err := stream.Send(&fspb.FileStream{Chunk: b[:n]}); err != nil {
+ return fmt.Errorf("отправка части в поток: %w", err)
+ }
+ }
+}
diff --git a/components/neo/pkg/filestream/filestream_test.go b/components/neo/pkg/filestream/filestream_test.go
new file mode 100644
index 0000000..64e1689
--- /dev/null
+++ b/components/neo/pkg/filestream/filestream_test.go
@@ -0,0 +1,137 @@
+package filestream
+
+import (
+ "bytes"
+ "errors"
+ "fmt"
+ "io"
+ "strings"
+ "testing"
+
+ "github.com/google/go-cmp/cmp"
+ "github.com/stretchr/testify/require"
+
+ fspb "github.com/c4t-but-s4d/neo/v2/proto/go/fileserver"
+)
+
+type failedReadWriter struct {
+}
+
+var errTestWrite = errors.New("test read write error")
+
+func (rw *failedReadWriter) Write(_ []byte) (n int, err error) {
+ return 0, errTestWrite
+}
+
+func (rw *failedReadWriter) Read(_ []byte) (n int, err error) {
+ return 0, errTestWrite
+}
+
+type mockUploadStream struct {
+ withError bool
+ buf bytes.Buffer
+}
+
+func (ms *mockUploadStream) Send(s *fspb.FileStream) error {
+ ms.buf.Write(s.Chunk)
+ if ms.withError {
+ return errTestWrite
+ }
+ return nil
+}
+
+type mockDownloadStream struct {
+ withError bool
+ data *strings.Reader
+ chunkSize int
+}
+
+func (ms *mockDownloadStream) Recv() (*fspb.FileStream, error) {
+ if ms.chunkSize == 0 {
+ ms.chunkSize = chunkSize
+ }
+ if ms.withError {
+ return nil, errTestWrite
+ }
+ b := make([]byte, ms.chunkSize)
+ n, err := ms.data.Read(b)
+ if err != nil {
+ return nil, fmt.Errorf("reading stream content: %w", err)
+ }
+ return &fspb.FileStream{Chunk: b[:n]}, nil
+}
+
+func TestLoad(t *testing.T) {
+ for _, tc := range []struct {
+ reader io.Reader
+ stream *mockUploadStream
+ want string
+ err error
+ }{
+ {
+ reader: strings.NewReader("somedata"),
+ stream: &mockUploadStream{withError: false},
+ want: "somedata",
+ err: nil,
+ },
+ {
+ reader: &failedReadWriter{},
+ stream: &mockUploadStream{withError: false},
+ want: "",
+ err: errTestWrite,
+ },
+ {
+ reader: strings.NewReader("somedata"),
+ stream: &mockUploadStream{withError: true},
+ want: "somedata",
+ err: errTestWrite,
+ },
+ } {
+ require.ErrorIs(t, Load(tc.reader, tc.stream), tc.err)
+ if diff := cmp.Diff(tc.want, tc.stream.buf.String()); diff != "" {
+ t.Errorf("Load() result mismatch (-want +got):\n%s", diff)
+ }
+ }
+}
+
+func TestSave(t *testing.T) {
+ for _, tc := range []struct {
+ writer *strings.Builder
+ stream *mockDownloadStream
+ want string
+ err error
+ }{
+ {
+ writer: &strings.Builder{},
+ stream: &mockDownloadStream{data: strings.NewReader("abacaba")},
+ want: "abacaba",
+ err: nil,
+ },
+ {
+ writer: &strings.Builder{},
+ stream: &mockDownloadStream{data: strings.NewReader("abacaba"), chunkSize: 1},
+ want: "abacaba",
+ err: nil,
+ },
+ {
+ writer: &strings.Builder{},
+ stream: &mockDownloadStream{data: strings.NewReader("abacaba"), withError: true},
+ want: "",
+ err: errTestWrite,
+ },
+ } {
+ require.ErrorIs(t, Save(tc.stream, tc.writer), tc.err)
+ if diff := cmp.Diff(tc.want, tc.writer.String()); diff != "" {
+ t.Errorf("Save() result mismatch (-want +got):\n%s", diff)
+ }
+ }
+}
+
+func TestSaveLimitRejectsOversizedStream(t *testing.T) {
+ writer := &strings.Builder{}
+ stream := &mockDownloadStream{data: strings.NewReader("123456"), chunkSize: 3}
+
+ err := SaveLimit(stream, writer, 5)
+ require.ErrorContains(t, err, "превышает лимит")
+ require.Equal(t, "123", writer.String())
+}
diff --git a/components/neo/pkg/grpcauth/token.go b/components/neo/pkg/grpcauth/token.go
new file mode 100644
index 0000000..5b01d50
--- /dev/null
+++ b/components/neo/pkg/grpcauth/token.go
@@ -0,0 +1,156 @@
+package grpcauth
+
+import (
+ "context"
+ "crypto/sha256"
+ "crypto/subtle"
+ "fmt"
+
+ "google.golang.org/grpc"
+ "google.golang.org/grpc/codes"
+ "google.golang.org/grpc/metadata"
+ "google.golang.org/grpc/status"
+)
+
+const authKey = "authorization"
+
+var workerMethods = map[string]struct{}{
+ "/exploits.Service/Ping": {},
+ "/exploits.Service/Exploit": {},
+ "/exploits.Service/BroadcastSubscribe": {},
+ "/exploits.Service/SingleRunSubscribe": {},
+ "/fileserver.Service/DownloadFile": {},
+ "/logs.Service/AddLogLines": {},
+}
+
+const MinKeyLength = 32
+
+func ValidateKey(key string) error {
+ if len(key) < MinKeyLength {
+ return fmt.Errorf("ключ gRPC должен содержать не менее %d байт", MinKeyLength)
+ }
+ return nil
+}
+
+func ValidateKeyPair(adminKey, workerKey string) error {
+ if err := ValidateKey(adminKey); err != nil {
+ return fmt.Errorf("админский ключ: %w", err)
+ }
+ if err := ValidateKey(workerKey); err != nil {
+ return fmt.Errorf("ключ worker: %w", err)
+ }
+ if keyMatches(adminKey, workerKey) {
+ return fmt.Errorf("админский ключ и ключ worker должны различаться")
+ }
+ return nil
+}
+
+func keyMatches(expected, provided string) bool {
+ expectedHash := sha256.Sum256([]byte(expected))
+ providedHash := sha256.Sum256([]byte(provided))
+ return subtle.ConstantTimeCompare(expectedHash[:], providedHash[:]) == 1
+}
+
+func NewServerInterceptor(key string) *ServerTokenInterceptor {
+ return &ServerTokenInterceptor{
+ adminKey: key,
+ }
+}
+
+func NewServerInterceptorWithWorkerKey(adminKey, workerKey string) *ServerTokenInterceptor {
+ return &ServerTokenInterceptor{adminKey: adminKey, workerKey: workerKey}
+}
+
+type ServerTokenInterceptor struct {
+ adminKey string
+ workerKey string
+}
+
+func (ti *ServerTokenInterceptor) authorize(ctx context.Context, method string) error {
+ md, ok := metadata.FromIncomingContext(ctx)
+ if !ok {
+ return status.Errorf(codes.Unauthenticated, "метаданные не переданы")
+ }
+ values := md[authKey]
+ if len(values) != 1 {
+ return status.Errorf(codes.Unauthenticated, "токен авторизации не передан")
+ }
+ adminMatch := keyMatches(ti.adminKey, values[0])
+ workerMatch := keyMatches(ti.workerKey, values[0])
+ if adminMatch {
+ return nil
+ }
+ if !workerMatch {
+ return status.Errorf(codes.Unauthenticated, "передан неверный токен")
+ }
+ if _, allowed := workerMethods[method]; !allowed {
+ return status.Errorf(codes.PermissionDenied, "токен worker не разрешает этот вызов")
+ }
+ return nil
+}
+
+func (ti *ServerTokenInterceptor) Unary() grpc.UnaryServerInterceptor {
+ return func(
+ ctx context.Context,
+ req interface{},
+ info *grpc.UnaryServerInfo,
+ handler grpc.UnaryHandler,
+ ) (interface{}, error) {
+ if err := ti.authorize(ctx, info.FullMethod); err != nil {
+ return nil, err
+ }
+ return handler(ctx, req)
+ }
+}
+
+func (ti *ServerTokenInterceptor) Stream() grpc.StreamServerInterceptor {
+ return func(
+ srv interface{},
+ stream grpc.ServerStream,
+ info *grpc.StreamServerInfo,
+ handler grpc.StreamHandler,
+ ) error {
+ if err := ti.authorize(stream.Context(), info.FullMethod); err != nil {
+ return err
+ }
+ return handler(srv, stream)
+ }
+}
+
+func NewClientInterceptor(key string) *ClientTokenInterceptor {
+ return &ClientTokenInterceptor{token: key}
+}
+
+type ClientTokenInterceptor struct {
+ token string
+}
+
+func (interceptor *ClientTokenInterceptor) attachToken(ctx context.Context) context.Context {
+ return metadata.AppendToOutgoingContext(ctx, authKey, interceptor.token)
+}
+
+func (interceptor *ClientTokenInterceptor) Unary() grpc.UnaryClientInterceptor {
+ return func(
+ ctx context.Context,
+ method string,
+ req, reply interface{},
+ cc *grpc.ClientConn,
+ invoker grpc.UnaryInvoker,
+ opts ...grpc.CallOption,
+ ) error {
+ return invoker(interceptor.attachToken(ctx), method, req, reply, cc, opts...)
+ }
+}
+
+func (interceptor *ClientTokenInterceptor) Stream() grpc.StreamClientInterceptor {
+ return func(
+ ctx context.Context,
+ desc *grpc.StreamDesc,
+ cc *grpc.ClientConn,
+ method string,
+ streamer grpc.Streamer,
+ opts ...grpc.CallOption,
+ ) (grpc.ClientStream, error) {
+ return streamer(interceptor.attachToken(ctx), desc, cc, method, opts...)
+ }
+}
diff --git a/components/neo/pkg/grpcauth/token_test.go b/components/neo/pkg/grpcauth/token_test.go
new file mode 100644
index 0000000..5898506
--- /dev/null
+++ b/components/neo/pkg/grpcauth/token_test.go
@@ -0,0 +1,96 @@
+package grpcauth
+
+import (
+ "context"
+ "testing"
+
+ epb "github.com/c4t-but-s4d/neo/v2/proto/go/exploits"
+ fspb "github.com/c4t-but-s4d/neo/v2/proto/go/fileserver"
+ lpb "github.com/c4t-but-s4d/neo/v2/proto/go/logs"
+ "github.com/stretchr/testify/require"
+ "google.golang.org/grpc"
+ "google.golang.org/grpc/codes"
+ "google.golang.org/grpc/metadata"
+ "google.golang.org/grpc/status"
+)
+
+const (
+ testAdminKey = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
+ testWorkerKey = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"
+)
+
+func authContext(key string) context.Context {
+ return metadata.NewIncomingContext(context.Background(), metadata.Pairs(authKey, key))
+}
+
+func TestWorkerTokenMethodAccess(t *testing.T) {
+ interceptor := NewServerInterceptorWithWorkerKey(testAdminKey, testWorkerKey)
+ for method := range workerMethods {
+ require.NoError(t, interceptor.authorize(authContext(testWorkerKey), method), method)
+ }
+}
+
+func TestWorkerTokenCannotCallAdministrativeOrUnknownMethods(t *testing.T) {
+ interceptor := NewServerInterceptorWithWorkerKey(testAdminKey, testWorkerKey)
+ services := []struct {
+ name string
+ methods []string
+ streams []string
+ }{
+ {epb.Service_ServiceDesc.ServiceName, methodNames(epb.Service_ServiceDesc.Methods), streamNames(epb.Service_ServiceDesc.Streams)},
+ {fspb.Service_ServiceDesc.ServiceName, methodNames(fspb.Service_ServiceDesc.Methods), streamNames(fspb.Service_ServiceDesc.Streams)},
+ {lpb.Service_ServiceDesc.ServiceName, methodNames(lpb.Service_ServiceDesc.Methods), streamNames(lpb.Service_ServiceDesc.Streams)},
+ }
+ for _, service := range services {
+ for _, method := range append(service.methods, service.streams...) {
+ fullMethod := "/" + service.name + "/" + method
+ _, workerAllowed := workerMethods[fullMethod]
+ err := interceptor.authorize(authContext(testWorkerKey), fullMethod)
+ if workerAllowed {
+ require.NoError(t, err, fullMethod)
+ } else {
+ require.Equal(t, codes.PermissionDenied, status.Code(err), fullMethod)
+ }
+ }
+ }
+ err := interceptor.authorize(authContext(testWorkerKey), "/unknown.Service/Method")
+ require.Equal(t, codes.PermissionDenied, status.Code(err))
+}
+
+func methodNames(methods []grpc.MethodDesc) []string {
+ result := make([]string, 0, len(methods))
+ for _, method := range methods {
+ result = append(result, method.MethodName)
+ }
+ return result
+}
+
+func streamNames(streams []grpc.StreamDesc) []string {
+ result := make([]string, 0, len(streams))
+ for _, stream := range streams {
+ result = append(result, stream.StreamName)
+ }
+ return result
+}
+
+func TestAdminTokenCanCallAllMethods(t *testing.T) {
+ interceptor := NewServerInterceptorWithWorkerKey(testAdminKey, testWorkerKey)
+ require.NoError(t, interceptor.authorize(authContext(testAdminKey), "/unknown.Service/Method"))
+}
+
+func TestAuthorizationComparisonRejectsMismatchesAtEveryPosition(t *testing.T) {
+ interceptor := NewServerInterceptorWithWorkerKey(testAdminKey, testWorkerKey)
+ for i := range testAdminKey {
+ wrong := []byte(testAdminKey)
+ wrong[i] ^= 1
+ err := interceptor.authorize(authContext(string(wrong)), "/exploits.Service/Ping")
+ require.Equal(t, codes.Unauthenticated, status.Code(err))
+ }
+}
+
+func TestValidateKeyPair(t *testing.T) {
+ require.NoError(t, ValidateKeyPair(testAdminKey, testWorkerKey))
+ require.Error(t, ValidateKeyPair(testAdminKey, testAdminKey))
+ require.Error(t, ValidateKeyPair("short", testWorkerKey))
+ require.Error(t, ValidateKeyPair(testAdminKey, "short"))
+}
diff --git a/components/neo/pkg/gstream/dynsize.go b/components/neo/pkg/gstream/dynsize.go
new file mode 100644
index 0000000..d8c167e
--- /dev/null
+++ b/components/neo/pkg/gstream/dynsize.go
@@ -0,0 +1,74 @@
+package gstream
+
+import (
+ "context"
+ "fmt"
+ "sync"
+)
+
+type Sizable interface {
+ EstimateSize() int
+}
+
+type BatcherFunc[S, D any] func(t []S) (D, error)
+
+func NewDynamicSizeCache[T Sizable, M any](s WStream[M], maxSize int, bf BatcherFunc[T, *M]) *DynamicSizeCache[T, M] {
+ return &DynamicSizeCache[T, M]{
+ stream: s,
+ batcher: bf,
+ maxSize: maxSize,
+ }
+}
+
+type DynamicSizeCache[T Sizable, M any] struct {
+ stream WStream[M]
+ batcher BatcherFunc[T, *M]
+ maxSize int
+ curSize int
+ queue []T
+ mu sync.Mutex
+}
+
+func (d *DynamicSizeCache[T, M]) Queue(ts ...T) error {
+ d.mu.Lock()
+ defer d.mu.Unlock()
+
+ for _, t := range ts {
+ d.curSize += t.EstimateSize()
+ d.queue = append(d.queue, t)
+ if d.curSize >= d.maxSize {
+ if err := d.flushUnlocked(); err != nil {
+ return fmt.Errorf("отправка накопленных данных: %w", err)
+ }
+ }
+ }
+ return nil
+}
+
+func (d *DynamicSizeCache[T, M]) Flush() error {
+ d.mu.Lock()
+ defer d.mu.Unlock()
+ return d.flushUnlocked()
+}
+
+func (d *DynamicSizeCache[T, M]) Context() context.Context {
+ return d.stream.Context()
+}
+
+// flushUnlocked вызывается при удерживаемой блокировке.
+func (d *DynamicSizeCache[T, M]) flushUnlocked() error {
+ if len(d.queue) == 0 {
+ return nil
+ }
+
+ m, err := d.batcher(d.queue)
+ if err != nil {
+ return fmt.Errorf("преобразование накопленных данных: %w", err)
+ }
+ if err := d.stream.Send(m); err != nil {
+ return fmt.Errorf("отправка накопленных данных в поток: %w", err)
+ }
+ d.curSize = 0
+ d.queue = d.queue[:0]
+ return nil
+}
diff --git a/components/neo/pkg/gstream/dynsize_test.go b/components/neo/pkg/gstream/dynsize_test.go
new file mode 100644
index 0000000..8ff3a20
--- /dev/null
+++ b/components/neo/pkg/gstream/dynsize_test.go
@@ -0,0 +1,75 @@
+package gstream
+
+import (
+ "context"
+ "errors"
+ "testing"
+
+ "github.com/stretchr/testify/require"
+)
+
+func TestDynamicSizeCacheSimple(t *testing.T) {
+ s := &mockWStream{}
+ cache := NewDynamicSizeCache[*mockSizable, []*mockSizable](
+ s,
+ 10,
+ func(a []*mockSizable) (*[]*mockSizable, error) {
+ return &a, nil
+ },
+ )
+ gen := func(a int) *mockSizable {
+ return &mockSizable{size: a}
+ }
+ require.NoError(t, cache.Queue(gen(5), gen(3)))
+ require.Empty(t, s.sent)
+
+ require.NoError(t, cache.Flush())
+ require.Equal(t, [][]*mockSizable{{gen(5), gen(3)}}, s.sent)
+ s.sent = nil
+
+ require.NoError(t, cache.Queue(gen(5), gen(3)))
+ require.NoError(t, cache.Queue(gen(2), gen(3)))
+ require.Equal(t, [][]*mockSizable{{gen(5), gen(3), gen(2)}}, s.sent)
+ require.NoError(t, cache.Flush())
+ require.Equal(t, [][]*mockSizable{{gen(5), gen(3), gen(2)}, {gen(3)}}, s.sent)
+}
+
+func TestDynamicSizeCache_ErrorPropagation(t *testing.T) {
+ mockErr := errors.New("mock error")
+ s := &mockWStream{returnErr: mockErr}
+ cache := NewDynamicSizeCache[*mockSizable, []*mockSizable](
+ s,
+ 5,
+ func(a []*mockSizable) (*[]*mockSizable, error) {
+ return &a, nil
+ },
+ )
+ err := cache.Queue(&mockSizable{size: 5})
+ require.ErrorIs(t, err, mockErr)
+ require.NotEqual(t, mockErr, err)
+ require.Equal(t, [][]*mockSizable{{&mockSizable{size: 5}}}, s.sent)
+}
+
+type mockSizable struct {
+ size int
+}
+
+func (s *mockSizable) EstimateSize() int {
+ return s.size
+}
+
+type mockWStream struct {
+ sent [][]*mockSizable
+ returnErr error
+}
+
+func (m *mockWStream) Send(t *[]*mockSizable) error {
+ tmp := make([]*mockSizable, len(*t))
+ copy(tmp, *t)
+ m.sent = append(m.sent, tmp)
+ return m.returnErr
+}
+
+func (m *mockWStream) Context() context.Context {
+ return context.Background()
+}
diff --git a/components/neo/pkg/gstream/stream.go b/components/neo/pkg/gstream/stream.go
new file mode 100644
index 0000000..4de45fb
--- /dev/null
+++ b/components/neo/pkg/gstream/stream.go
@@ -0,0 +1,13 @@
+package gstream
+
+import "context"
+
+type RStream[T any] interface {
+ Recv() (*T, error)
+ Context() context.Context
+}
+
+type WStream[T any] interface {
+ Send(*T) error
+ Context() context.Context
+}
diff --git a/components/neo/pkg/gstream/wrap.go b/components/neo/pkg/gstream/wrap.go
new file mode 100644
index 0000000..5120139
--- /dev/null
+++ b/components/neo/pkg/gstream/wrap.go
@@ -0,0 +1,29 @@
+package gstream
+
+import (
+ "context"
+ "fmt"
+)
+
+type wrappedWStream[In, Out any] struct {
+ original WStream[Out]
+ mapper func(*In) *Out
+}
+
+func Wrap[In, Out any](original WStream[Out], mapper func(*In) *Out) WStream[In] {
+ return &wrappedWStream[In, Out]{
+ original: original,
+ mapper: mapper,
+ }
+}
+
+func (w *wrappedWStream[In, Out]) Send(t *In) error {
+ if err := w.original.Send(w.mapper(t)); err != nil {
+ return fmt.Errorf("отправка в исходный поток: %w", err)
+ }
+ return nil
+}
+
+func (w *wrappedWStream[In, Out]) Context() context.Context {
+ return w.original.Context()
+}
diff --git a/components/neo/pkg/hostbucket/hostbucket.go b/components/neo/pkg/hostbucket/hostbucket.go
new file mode 100644
index 0000000..6c6d4ad
--- /dev/null
+++ b/components/neo/pkg/hostbucket/hostbucket.go
@@ -0,0 +1,125 @@
+package hostbucket
+
+import (
+ "sync"
+
+ "github.com/google/go-cmp/cmp"
+ "github.com/google/go-cmp/cmp/cmpopts"
+
+ "github.com/c4t-but-s4d/neo/v2/pkg/rendezvous"
+ epb "github.com/c4t-but-s4d/neo/v2/proto/go/exploits"
+)
+
+func New(teams map[string]string) *HostBucket {
+ return &HostBucket{
+ buck: make(map[string]*epb.TeamBucket),
+ nodes: nil,
+ teams: teams,
+ r: rendezvous.New(),
+ }
+}
+
+type HostBucket struct {
+ m sync.RWMutex
+ buck map[string]*epb.TeamBucket
+ nodes []*node
+ teams map[string]string
+ r *rendezvous.Rendezvous
+}
+
+// TODO: ускорить добавление и удаление IP-адресов
+func (hb *HostBucket) UpdateTeams(teams map[string]string) {
+ lessFunc := func(s1, s2 string) bool {
+ return s1 < s2
+ }
+ if !cmp.Equal(teams, hb.teams, cmpopts.SortSlices(lessFunc)) {
+ hb.m.Lock()
+ defer hb.m.Unlock()
+ hb.teams = teams
+ hb.rehash()
+ }
+}
+
+func (hb *HostBucket) Buckets() map[string]*epb.TeamBucket {
+ hb.m.RLock()
+ defer hb.m.RUnlock()
+
+ clone := make(map[string]*epb.TeamBucket, len(hb.buck))
+ for k, v := range hb.buck {
+ clone[k] = v
+ }
+ return clone
+}
+
+func (hb *HostBucket) Exists(id string) (exists bool) {
+ hb.m.RLock()
+ defer hb.m.RUnlock()
+ _, exists = hb.buck[id]
+ return
+}
+
+func (hb *HostBucket) AddNode(id string, weight int) {
+ hb.m.Lock()
+ defer hb.m.Unlock()
+
+ if _, ok := hb.buck[id]; ok {
+ return
+ }
+
+ hb.buck[id] = &epb.TeamBucket{}
+ n := &node{
+ id: id,
+ weight: weight,
+ }
+ hb.nodes = append(hb.nodes, n)
+ // TODO: ускорить добавление узлов
+ hb.rehash()
+}
+
+func (hb *HostBucket) DeleteNode(id string) bool {
+ hb.m.Lock()
+ defer hb.m.Unlock()
+ if _, ok := hb.buck[id]; !ok {
+ return false
+ }
+ for i, n := range hb.nodes {
+ if n.id == id {
+ last := len(hb.nodes) - 1
+ hb.nodes[i] = hb.nodes[last]
+ hb.nodes[last] = nil
+ hb.nodes = hb.nodes[:last]
+ delete(hb.buck, id)
+
+ // TODO: ускорить удаление узлов
+ hb.rehash()
+ return true
+ }
+ }
+ return false
+}
+
+func (hb *HostBucket) rehash() {
+ for _, v := range hb.buck {
+ v.Reset()
+ }
+ if len(hb.nodes) == 0 {
+ return
+ }
+ for id, ip := range hb.teams {
+ bestHash := 0.0
+ bestNode := ""
+
+ for _, n := range hb.nodes {
+ hash := hb.r.Calculate(n.id, n.weight, id)
+ if bestNode == "" || hash > bestHash {
+ bestNode = n.id
+ bestHash = hash
+ }
+ }
+
+ if hb.buck[bestNode].Teams == nil {
+ hb.buck[bestNode].Teams = make(map[string]string)
+ }
+ hb.buck[bestNode].Teams[id] = ip
+ }
+}
diff --git a/components/neo/pkg/hostbucket/hostbucket_test.go b/components/neo/pkg/hostbucket/hostbucket_test.go
new file mode 100644
index 0000000..0b3f95f
--- /dev/null
+++ b/components/neo/pkg/hostbucket/hostbucket_test.go
@@ -0,0 +1,256 @@
+package hostbucket
+
+import (
+ "fmt"
+ "math"
+ "testing"
+
+ "github.com/denisbrodbeck/machineid"
+ "github.com/google/go-cmp/cmp"
+ "github.com/google/go-cmp/cmp/cmpopts"
+ "github.com/stretchr/testify/require"
+
+ "github.com/c4t-but-s4d/neo/v2/pkg/testutils"
+)
+
+func TestHostBucket_Add(t *testing.T) {
+ for _, tc := range []struct {
+ b *HostBucket
+ users []string
+ want map[string]int
+ }{
+ {
+ b: New(map[string]string{"id1": "ip1"}),
+ users: []string{"u1"},
+ want: map[string]int{"u1": 1},
+ },
+ {
+ b: New(map[string]string{"id1": "ip1", "id2": "ip2", "id3": "ip3"}),
+ users: []string{},
+ want: map[string]int{},
+ },
+ } {
+ for _, u := range tc.users {
+ tc.b.AddNode(u, 1)
+ }
+ b := tc.b.Buckets()
+ gotTeams := make(map[string]string)
+ for cid, wantn := range tc.want {
+ ipb := b[cid]
+ require.Len(t, ipb.Teams, wantn)
+ for k, v := range ipb.Teams {
+ gotTeams[k] = v
+ }
+ }
+ if diff := cmp.Diff(tc.b.teams, gotTeams, cmpopts.SortSlices(testutils.LessString)); diff != "" && len(tc.want) > 0 {
+ t.Errorf("HostBucket.AddNode() summary ips mismatch (-want +got):\n%s", diff)
+ }
+ }
+}
+
+func TestHostBucket_Add_Distribution(t *testing.T) {
+ populate := func(idCount, ipCount, weightMax int) *HostBucket {
+ teams := make(map[string]string)
+ for i := 0; i < ipCount; i++ {
+ id := fmt.Sprintf("team-%d", i)
+ teams[id] = testutils.RandomIP()
+ }
+ hb := New(teams)
+
+ mid, err := machineid.ID()
+ require.NoError(t, err)
+ for i := 0; i < idCount; i++ {
+ id := testutils.RandomString(len(mid))
+ w := testutils.RandomInt(1, weightMax+1)
+ hb.AddNode(id, w)
+ }
+ return hb
+ }
+
+ for _, tc := range []struct {
+ ipCount int
+ idCount int
+ maxDeviation float64
+ weightMax int
+ runs int
+ }{
+ {
+ 100,
+ 5,
+ 1.5,
+ 32,
+ 100,
+ },
+ {
+ 1000,
+ 10,
+ 1,
+ 32,
+ 100,
+ },
+ } {
+ for i := 0; i < tc.runs; i++ {
+ b := populate(tc.idCount, tc.ipCount, tc.weightMax)
+ sizes := make([]float64, tc.idCount)
+ meanSize := 0.0
+ for i := range sizes {
+ id := b.nodes[i].id
+ sizes[i] = float64(len(b.buck[id].Teams)) / float64(b.nodes[i].weight)
+ meanSize += sizes[i]
+ }
+ meanSize /= float64(len(sizes))
+
+ for i := range sizes {
+ deviation := math.Abs((sizes[i] - meanSize) / meanSize)
+ require.Truef(
+ t,
+ deviation <= tc.maxDeviation,
+ "Deviation for bucket %s too large: %f > %f, target size: %f, weight %d, got size: %f",
+ b.nodes[i].id,
+ deviation,
+ tc.maxDeviation,
+ meanSize,
+ b.nodes[i].weight,
+ sizes[i],
+ )
+ }
+ }
+ }
+}
+
+func TestHostBucket_Balancing(t *testing.T) {
+ populate := func(ipCount, idCount int) *HostBucket {
+ teams := make(map[string]string)
+ for i := 0; i < ipCount; i++ {
+ id := fmt.Sprintf("team-%d", i)
+ teams[id] = testutils.RandomIP()
+ }
+ hb := New(teams)
+
+ mid, err := machineid.ID()
+ require.NoError(t, err)
+ for i := 0; i < idCount; i++ {
+ id := testutils.RandomString(len(mid))
+ hb.AddNode(id, 1)
+ }
+ return hb
+ }
+
+ for _, tc := range []struct {
+ ipCount int
+ idCount int
+ maxMoved float64
+ cntAdd int
+ cntDelete int
+ }{
+ {
+ 100,
+ 5,
+ 0.3,
+ 0,
+ 1,
+ },
+ {
+ 1000,
+ 10,
+ 0.2,
+ 1,
+ 0,
+ },
+ } {
+ b := populate(tc.ipCount, tc.idCount)
+
+ beforeByIP := make(map[string]string)
+ for _, n := range b.nodes {
+ for _, ip := range b.buck[n.id].Teams {
+ beforeByIP[ip] = n.id
+ }
+ }
+
+ getCntMoved := func() int {
+ cntMoved := 0
+ for _, n := range b.nodes {
+ for _, ip := range b.buck[n.id].Teams {
+ if n.id != beforeByIP[ip] {
+ cntMoved++
+ }
+ beforeByIP[ip] = n.id
+ }
+ }
+ return cntMoved
+ }
+
+ for i := 0; i < tc.cntDelete; i++ {
+ toDelete := testutils.RandomInt(0, tc.idCount)
+ b.DeleteNode(b.nodes[toDelete].id)
+ }
+ cntMoved := getCntMoved()
+ movedFraction := float64(cntMoved) / float64(tc.ipCount)
+ require.Truef(
+ t,
+ movedFraction <= tc.maxMoved,
+ "Too many ips moved after delete: %f%%, %d of %d",
+ movedFraction*100,
+ cntMoved,
+ tc.ipCount,
+ )
+
+ mid, err := machineid.ID()
+ require.NoError(t, err)
+ for i := 0; i < tc.cntAdd; i++ {
+ id := testutils.RandomString(len(mid))
+ b.AddNode(id, 1)
+ }
+ cntMoved = getCntMoved()
+ movedFraction = float64(cntMoved) / float64(tc.ipCount)
+ require.Truef(
+ t,
+ movedFraction <= tc.maxMoved,
+ "Too many ips moved after delete: %f%%, %d of %d",
+ movedFraction*100,
+ cntMoved,
+ tc.ipCount,
+ )
+ }
+}
+
+func TestHostBucket_Delete(t *testing.T) {
+ populate := func(teams map[string]string, ids []string) *HostBucket {
+ hb := New(teams)
+ for _, id := range ids {
+ hb.AddNode(id, 1)
+ }
+ return hb
+ }
+ for _, tc := range []struct {
+ b *HostBucket
+ delete []string
+ want map[string]int
+ }{
+ {
+ b: populate(map[string]string{"team1": "ip1", "team2": "ip2"}, []string{"id1", "id2"}),
+ delete: []string{"id1"},
+ want: map[string]int{"id2": 2},
+ },
+ {
+ b: populate(map[string]string{"team1": "ip1", "team2": "ip2"}, []string{"id1"}),
+ delete: []string{"id1"},
+ want: map[string]int{},
+ },
+ } {
+ for _, tid := range tc.delete {
+ tc.b.DeleteNode(tid)
+ }
+ gotTeams := make(map[string]string)
+ for cid, wantn := range tc.want {
+ ipb := tc.b.buck[cid]
+ require.Len(t, ipb.Teams, wantn)
+ for k, v := range ipb.Teams {
+ gotTeams[k] = v
+ }
+ }
+ if diff := cmp.Diff(tc.b.teams, gotTeams, cmpopts.SortSlices(testutils.LessString)); diff != "" && len(tc.want) > 0 {
+ t.Errorf("HostBucket.DeleteNode() summary ips mismatch (-want +got):\n%s", diff)
+ }
+ }
+}
diff --git a/components/neo/pkg/hostbucket/node.go b/components/neo/pkg/hostbucket/node.go
new file mode 100644
index 0000000..f913a16
--- /dev/null
+++ b/components/neo/pkg/hostbucket/node.go
@@ -0,0 +1,6 @@
+package hostbucket
+
+type node struct {
+ id string
+ weight int
+}
diff --git a/components/neo/pkg/joblogger/logger.go b/components/neo/pkg/joblogger/logger.go
new file mode 100644
index 0000000..c6e33ae
--- /dev/null
+++ b/components/neo/pkg/joblogger/logger.go
@@ -0,0 +1,103 @@
+package joblogger
+
+import (
+ "fmt"
+ "runtime"
+ "strings"
+
+ "github.com/sirupsen/logrus"
+
+ "github.com/c4t-but-s4d/neo/v2/internal/logger"
+ logspb "github.com/c4t-but-s4d/neo/v2/proto/go/logs"
+)
+
+// Ограничение длины сообщения журнала - 1 МиБ.
+const maxMessageLength = 1024 * 1024
+
+func New(exploit string, version int64, team string, sender Sender) *JobLogger {
+ return &JobLogger{
+ exploit: exploit,
+ version: version,
+ team: team,
+ sender: sender,
+ }
+}
+
+type JobLogger struct {
+ exploit string
+ version int64
+ team string
+ sender Sender
+}
+
+func (l *JobLogger) Debugf(format string, args ...interface{}) {
+ l.logProxy(logrus.DebugLevel, format, args...)
+ msg := fmt.Sprintf(format, args...)
+ l.sender.Add(l.newLine(msg, "debug"))
+}
+
+func (l *JobLogger) Infof(format string, args ...interface{}) {
+ l.logProxy(logrus.InfoLevel, format, args...)
+ msg := fmt.Sprintf(format, args...)
+ l.sender.Add(l.newLine(msg, "info"))
+}
+
+func (l *JobLogger) Warningf(format string, args ...interface{}) {
+ l.logProxy(logrus.WarnLevel, format, args...)
+ msg := fmt.Sprintf(format, args...)
+ l.sender.Add(l.newLine(msg, "warning"))
+}
+
+func (l *JobLogger) Errorf(format string, args ...interface{}) {
+ l.logProxy(logrus.ErrorLevel, format, args...)
+ msg := fmt.Sprintf(format, args...)
+ l.sender.Add(l.newLine(msg, "error"))
+}
+
+func (l *JobLogger) newLine(msg, level string) *logspb.LogLine {
+ return &logspb.LogLine{
+ Exploit: l.exploit,
+ Version: l.version,
+ Message: sanitizeMessage(msg),
+ Level: level,
+ Team: l.team,
+ }
+}
+
+func (l *JobLogger) getLogger() *logrus.Entry {
+ return logrus.WithFields(logrus.Fields{
+ "exploit": l.exploit,
+ "version": l.version,
+ "team": l.team,
+ })
+}
+
+func (l *JobLogger) logProxy(level logrus.Level, format string, args ...interface{}) {
+ if logrus.IsLevelEnabled(level) {
+ l.
+ getLogger().
+ WithField(logger.CustomKeyFile, fileInfo(3)).
+ Logf(level, format, args...)
+ }
+}
+
+func sanitizeMessage(msg string) string {
+ if len(msg) > maxMessageLength {
+ msg = msg[:maxMessageLength]
+ }
+ return msg
+}
+
+func fileInfo(skip int) string {
+ _, file, line, ok := runtime.Caller(skip)
+ if !ok {
+ file = "??>"
+ line = 1
+ } else {
+ slash := strings.LastIndex(file, "/")
+ if slash >= 0 {
+ file = file[slash+1:]
+ }
+ }
+ return fmt.Sprintf("%s:%d", file, line)
+}
diff --git a/components/neo/pkg/joblogger/sender.go b/components/neo/pkg/joblogger/sender.go
new file mode 100644
index 0000000..fcc45b3
--- /dev/null
+++ b/components/neo/pkg/joblogger/sender.go
@@ -0,0 +1,83 @@
+package joblogger
+
+import (
+ "context"
+ "fmt"
+ "sync"
+ "time"
+
+ "github.com/sirupsen/logrus"
+
+ "github.com/c4t-but-s4d/neo/v2/internal/client"
+ logspb "github.com/c4t-but-s4d/neo/v2/proto/go/logs"
+)
+
+const (
+ sendInterval = time.Second
+)
+
+type Sender interface {
+ Add(lines ...*logspb.LogLine)
+}
+
+func NewDummySender() *DummySender {
+ return &DummySender{}
+}
+
+type DummySender struct{}
+
+func (s *DummySender) Add(...*logspb.LogLine) {
+}
+
+func NewRemoteSender(client *client.Client) *RemoteSender {
+ return &RemoteSender{
+ client: client,
+ queue: make([]*logspb.LogLine, 0, 1000),
+ }
+}
+
+type RemoteSender struct {
+ client *client.Client
+ queue []*logspb.LogLine
+ mu sync.Mutex
+}
+
+func (s *RemoteSender) Add(lines ...*logspb.LogLine) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ s.queue = append(s.queue, lines...)
+}
+
+func (s *RemoteSender) Start(ctx context.Context) {
+ ticker := time.NewTicker(sendInterval)
+ defer ticker.Stop()
+
+ for {
+ select {
+ case <-ticker.C:
+ if err := s.send(ctx); err != nil {
+ logrus.Errorf("Не удалось отправить журналы: %v", err)
+ }
+ case <-ctx.Done():
+ return
+ }
+ }
+}
+
+func (s *RemoteSender) send(ctx context.Context) error {
+ s.mu.Lock()
+ batch := make([]*logspb.LogLine, len(s.queue))
+ copy(batch, s.queue)
+ s.queue = s.queue[:0]
+ s.mu.Unlock()
+
+ if len(batch) == 0 {
+ logrus.Debugf("Отправка записей журнала: %d", len(batch))
+ } else {
+ logrus.Infof("Отправка записей журнала: %d", len(batch))
+ }
+ if err := s.client.AddLogLines(ctx, batch...); err != nil {
+ return fmt.Errorf("отправка пакета на сервер: %w", err)
+ }
+ return nil
+}
diff --git a/components/neo/pkg/neosync/sleep.go b/components/neo/pkg/neosync/sleep.go
new file mode 100644
index 0000000..a2084e4
--- /dev/null
+++ b/components/neo/pkg/neosync/sleep.go
@@ -0,0 +1,16 @@
+package neosync
+
+import (
+ "context"
+ "time"
+)
+
+func Sleep(ctx context.Context, d time.Duration) {
+ t := time.NewTimer(d)
+ defer t.Stop()
+
+ select {
+ case <-ctx.Done():
+ case <-t.C:
+ }
+}
diff --git a/components/neo/pkg/neosync/wg.go b/components/neo/pkg/neosync/wg.go
new file mode 100644
index 0000000..b21eeb7
--- /dev/null
+++ b/components/neo/pkg/neosync/wg.go
@@ -0,0 +1,12 @@
+package neosync
+
+import "sync"
+
+func AwaitWG(wg *sync.WaitGroup) <-chan struct{} {
+ c := make(chan struct{})
+ go func() {
+ wg.Wait()
+ close(c)
+ }()
+ return c
+}
diff --git a/components/neo/pkg/pubsub/pubsub.go b/components/neo/pkg/pubsub/pubsub.go
new file mode 100644
index 0000000..9b8bfb1
--- /dev/null
+++ b/components/neo/pkg/pubsub/pubsub.go
@@ -0,0 +1,37 @@
+package pubsub
+
+import "sync"
+
+type PubSub[T any] struct {
+ subs map[string]*Subscription[T]
+ mu sync.RWMutex
+}
+
+func NewPubSub[T any]() *PubSub[T] {
+ return &PubSub[T]{
+ subs: make(map[string]*Subscription[T]),
+ }
+}
+
+func (ps *PubSub[T]) Publish(msg T) {
+ ps.mu.RLock()
+ defer ps.mu.RUnlock()
+ for _, sub := range ps.subs {
+ sub.Push(msg)
+ }
+}
+
+func (ps *PubSub[T]) Subscribe(onMsg MessageHandler[T]) *Subscription[T] {
+ ps.mu.Lock()
+ defer ps.mu.Unlock()
+
+ sub := NewSubscription(onMsg)
+ ps.subs[sub.GetID()] = sub
+ return sub
+}
+
+func (ps *PubSub[T]) Unsubscribe(sub *Subscription[T]) {
+ ps.mu.Lock()
+ defer ps.mu.Unlock()
+ delete(ps.subs, sub.GetID())
+}
diff --git a/components/neo/pkg/pubsub/pubsub_test.go b/components/neo/pkg/pubsub/pubsub_test.go
new file mode 100644
index 0000000..f2726bf
--- /dev/null
+++ b/components/neo/pkg/pubsub/pubsub_test.go
@@ -0,0 +1,262 @@
+package pubsub
+
+import (
+ "context"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/stretchr/testify/require"
+ "go.uber.org/goleak"
+
+ "github.com/c4t-but-s4d/neo/v2/pkg/neosync"
+)
+
+func TestMain(m *testing.M) {
+ goleak.VerifyTestMain(m)
+}
+
+func TestPubSub_single(t *testing.T) {
+ p := NewPubSub[string]()
+
+ wg := sync.WaitGroup{}
+ wg.Add(1)
+
+ sub := p.Subscribe(func(msg string) error {
+ require.Equal(t, "blah-blah", msg)
+ wg.Done()
+ return nil
+ })
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ go sub.Run(ctx)
+
+ p.Publish("blah-blah")
+ wg.Wait()
+}
+
+func TestPubSub_nonBlockPublish(t *testing.T) {
+ p := NewPubSub[string]()
+
+ wg := sync.WaitGroup{}
+ wg.Add(11)
+
+ sub := p.Subscribe(func(msg string) error {
+ require.Equal(t, "pew-pew", msg)
+ wg.Done()
+ return nil
+ })
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ go sub.Run(ctx)
+
+ done := make(chan struct{})
+ go func() {
+ for i := 0; i < 11; i++ {
+ p.Publish("pew-pew")
+ }
+ close(done)
+ }()
+
+ select {
+ case <-time.After(1 * time.Second):
+ t.Fatal("publish method must not be blocked")
+ case <-done:
+ }
+
+ wg.Wait()
+}
+
+func TestPubSub_multipleSubscribers(t *testing.T) {
+ p := NewPubSub[string]()
+
+ wgFirst := sync.WaitGroup{}
+ wgFirst.Add(1)
+ wgSecond := sync.WaitGroup{}
+ wgSecond.Add(1)
+
+ sub1 := p.Subscribe(func(msg string) error {
+ require.Equal(t, "blah", msg)
+ wgFirst.Done()
+ return nil
+ })
+ ctx1, cancel1 := context.WithCancel(context.Background())
+ defer cancel1()
+ go sub1.Run(ctx1)
+
+ sub2 := p.Subscribe(func(msg string) error {
+ require.Equal(t, "blah", msg)
+ wgSecond.Done()
+ return nil
+ })
+ ctx2, cancel2 := context.WithCancel(context.Background())
+ defer cancel2()
+ go sub2.Run(ctx2)
+
+ p.Publish("blah")
+
+ wgFirst.Wait()
+ wgSecond.Wait()
+}
+
+func TestPubSub_slowpoke(t *testing.T) {
+ p := NewPubSub[string]()
+
+ const samples = 100
+
+ wgSlow := sync.WaitGroup{}
+ wgSlow.Add(samples)
+ slowCtx, slowCancel := context.WithCancel(context.Background())
+ defer func() {
+ slowCancel()
+ wgSlow.Wait()
+ }()
+
+ slowSub := p.Subscribe(func(msg string) error {
+ defer wgSlow.Done()
+
+ select {
+ case <-slowCtx.Done():
+ return nil
+ default:
+ time.Sleep(1 * time.Second)
+ }
+ return nil
+ })
+ go slowSub.Run(slowCtx)
+
+ fastWg := sync.WaitGroup{}
+ fastWg.Add(samples)
+
+ fastSub := p.Subscribe(func(msg string) error {
+ require.Equal(t, "pew-pew", msg)
+ fastWg.Done()
+ return nil
+ })
+ fastCtx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ go fastSub.Run(fastCtx)
+
+ for i := 0; i < samples; i++ {
+ p.Publish("pew-pew")
+ }
+
+ select {
+ case <-time.After(1 * time.Second):
+ t.Fatal("publish blocks on slowpoke?")
+ case <-neosync.AwaitWG(&fastWg):
+ // ok
+ }
+}
+
+func TestPubSub_unsubscribe(t *testing.T) {
+ p := NewPubSub[string]()
+
+ sub1 := p.Subscribe(func(msg string) error {
+ t.Error("first subscriber must not be called")
+ return nil
+ })
+ ctx1, cancel1 := context.WithCancel(context.Background())
+ defer cancel1()
+ go sub1.Run(ctx1)
+
+ p.Unsubscribe(sub1)
+
+ wg := sync.WaitGroup{}
+ wg.Add(1)
+
+ sub2 := p.Subscribe(func(msg string) error {
+ require.Equal(t, "pew-pew", msg)
+ wg.Done()
+ return nil
+ })
+ ctx2, cancel2 := context.WithCancel(context.Background())
+ defer cancel2()
+ go sub2.Run(ctx2)
+
+ p.Publish("pew-pew")
+
+ wg.Wait()
+}
+
+func TestPubSub_sequencePublishers(t *testing.T) {
+ p := NewPubSub[string]()
+
+ wg := sync.WaitGroup{}
+ wg.Add(10)
+
+ sub := p.Subscribe(func(msg string) error {
+ require.Equal(t, "pew-pew", msg)
+ wg.Done()
+ return nil
+ })
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ go sub.Run(ctx)
+
+ for i := 0; i < 10; i++ {
+ p.Publish("pew-pew")
+ }
+
+ wg.Wait()
+}
+
+func TestPubSub_concurrentPublishers(t *testing.T) {
+ p := NewPubSub[string]()
+
+ wg := sync.WaitGroup{}
+ wg.Add(10)
+
+ sub := p.Subscribe(func(msg string) error {
+ require.Equal(t, "pew-pew", msg)
+ wg.Done()
+ return nil
+ })
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ go sub.Run(ctx)
+
+ for i := 0; i < 10; i++ {
+ go p.Publish("pew-pew")
+ }
+
+ wg.Wait()
+}
+
+func TestPubSub_msgOrder(t *testing.T) {
+ p := NewPubSub[uint64]()
+
+ wg := sync.WaitGroup{}
+ wg.Add(15)
+
+ c := uint64(0)
+
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+
+ sub := p.Subscribe(func(msg uint64) error {
+ expected := atomic.AddUint64(&c, 1)
+ require.Equal(t, expected, msg)
+ wg.Done()
+ return nil
+ })
+ go sub.Run(ctx)
+
+ for i := uint64(1); i < 11; i++ {
+ if i == 6 {
+ c := uint64(5)
+ sub := p.Subscribe(func(msg uint64) error {
+ expected := atomic.AddUint64(&c, 1)
+ require.Equal(t, expected, msg)
+ wg.Done()
+ return nil
+ })
+ go sub.Run(ctx)
+ }
+
+ p.Publish(i)
+ }
+
+ wg.Wait()
+}
diff --git a/components/neo/pkg/pubsub/subscription.go b/components/neo/pkg/pubsub/subscription.go
new file mode 100644
index 0000000..1d62b71
--- /dev/null
+++ b/components/neo/pkg/pubsub/subscription.go
@@ -0,0 +1,73 @@
+package pubsub
+
+import (
+ "context"
+ "sync"
+
+ "github.com/google/uuid"
+ "github.com/sirupsen/logrus"
+)
+
+type MessageHandler[T any] func(T) error
+
+type Subscription[T any] struct {
+ id string
+ queue []T
+ mu sync.Mutex
+ notify chan struct{}
+ h MessageHandler[T]
+}
+
+func NewSubscription[T any](onMsg MessageHandler[T]) *Subscription[T] {
+ id := uuid.NewString()
+ return &Subscription[T]{
+ id: id,
+ queue: nil,
+ notify: make(chan struct{}, 1),
+ h: onMsg,
+ }
+}
+
+func (s *Subscription[T]) Run(ctx context.Context) {
+ for {
+ select {
+ case _, ok := <-s.notify:
+ if !ok {
+ return
+ }
+ for {
+ s.mu.Lock()
+ if len(s.queue) == 0 {
+ s.mu.Unlock()
+ break
+ }
+ cmd := s.queue[0]
+ s.queue = s.queue[1:]
+ s.mu.Unlock()
+
+ logrus.Debugf("Обработка сообщения типа %T в подписке %s", cmd, s.id)
+ if err := s.h(cmd); err != nil {
+ logrus.Errorf("Ошибка обработчика сообщения подписки: %v", err)
+ continue
+ }
+ }
+ case <-ctx.Done():
+ return
+ }
+ }
+}
+
+func (s *Subscription[T]) Push(msg T) {
+ s.mu.Lock()
+ s.queue = append(s.queue, msg)
+ s.mu.Unlock()
+
+ select {
+ case s.notify <- struct{}{}:
+ default:
+ }
+}
+
+func (s *Subscription[T]) GetID() string {
+ return s.id
+}
diff --git a/components/neo/pkg/pubsub/subscription_test.go b/components/neo/pkg/pubsub/subscription_test.go
new file mode 100644
index 0000000..3000a05
--- /dev/null
+++ b/components/neo/pkg/pubsub/subscription_test.go
@@ -0,0 +1,58 @@
+package pubsub
+
+import (
+ "context"
+ "testing"
+ "time"
+
+ "github.com/stretchr/testify/require"
+)
+
+func TestNewSubscription(t *testing.T) {
+ sub := NewSubscription[int](nil)
+ newSub := NewSubscription[int](nil)
+ require.NotEqual(t, sub.GetID(), newSub.GetID(), "id is not random")
+}
+
+func Test_subscription_Push(t *testing.T) {
+ sub := &Subscription[string]{
+ id: "test",
+ queue: nil,
+ notify: make(chan struct{}),
+ h: nil,
+ }
+ sub.Push("test")
+ require.Equal(t, []string{"test"}, sub.queue)
+}
+
+func Test_subscription_Run(t *testing.T) {
+ var received string
+ signal := make(chan struct{})
+ handler := func(msg string) error {
+ received = msg
+ close(signal)
+ return nil
+ }
+ sub := &Subscription[string]{
+ id: "test",
+ queue: nil,
+ notify: make(chan struct{}, 1),
+ h: handler,
+ }
+
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ go sub.Run(ctx)
+
+ const msg = "message"
+ sub.Push(msg)
+
+ select {
+ case <-signal:
+ break
+ case <-time.After(time.Millisecond * 100):
+ t.Errorf("Handler was not called in time")
+ }
+
+ require.Equal(t, msg, received)
+}
diff --git a/components/neo/pkg/rendezvous/rendezvous.go b/components/neo/pkg/rendezvous/rendezvous.go
new file mode 100644
index 0000000..799e0a4
--- /dev/null
+++ b/components/neo/pkg/rendezvous/rendezvous.go
@@ -0,0 +1,51 @@
+package rendezvous
+
+import (
+ "hash"
+ "sync"
+
+ "github.com/sirupsen/logrus"
+ "github.com/spaolacci/murmur3"
+)
+
+type Rendezvous struct {
+ hcache map[string]uint64
+ mu sync.RWMutex
+ h hash.Hash64
+}
+
+func New() *Rendezvous {
+ return &Rendezvous{
+ hcache: make(map[string]uint64),
+ h: murmur3.New64WithSeed(1337),
+ }
+}
+
+func (r *Rendezvous) checkCache(key string) (uint64, bool) {
+ r.mu.RLock()
+ defer r.mu.RUnlock()
+ raw, ok := r.hcache[key]
+ return raw, ok
+}
+
+func (r *Rendezvous) calcHash(key string) uint64 {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+
+ r.h.Reset()
+ if _, err := r.h.Write([]byte(key)); err != nil {
+ logrus.Fatalf("Не удалось вычислить хэш: %v", err)
+ }
+ rawVal := r.h.Sum64()
+ r.hcache[key] = rawVal
+ return rawVal
+}
+
+func (r *Rendezvous) Calculate(node string, weight int, value string) float64 {
+ key := combineKey(node, value)
+ if raw, ok := r.checkCache(key); ok {
+ return weightHash(raw, weight)
+ }
+ raw := r.calcHash(key)
+ return weightHash(raw, weight)
+}
diff --git a/components/neo/pkg/rendezvous/rendezvous_test.go b/components/neo/pkg/rendezvous/rendezvous_test.go
new file mode 100644
index 0000000..e35ffb0
--- /dev/null
+++ b/components/neo/pkg/rendezvous/rendezvous_test.go
@@ -0,0 +1,38 @@
+package rendezvous
+
+import (
+ "testing"
+
+ "github.com/stretchr/testify/require"
+)
+
+func TestRendezvous_Calculate(t *testing.T) {
+ tests := []struct {
+ name string
+ nodeID string
+ nodeWeight int
+ value string
+ }{
+ {
+ "simple_test",
+ "kek",
+ 1,
+ "lol",
+ },
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ r := New()
+ hash := r.Calculate(tt.nodeID, tt.nodeWeight, tt.value)
+ if hash == 0 {
+ t.Error("Zero hash returned")
+ }
+
+ k := combineKey(tt.nodeID, tt.value)
+ rhash, ok := r.checkCache(k)
+ require.True(t, ok)
+ needHash := weightHash(rhash, tt.nodeWeight)
+ require.Equal(t, needHash, hash)
+ })
+ }
+}
diff --git a/components/neo/pkg/rendezvous/utils.go b/components/neo/pkg/rendezvous/utils.go
new file mode 100644
index 0000000..3337360
--- /dev/null
+++ b/components/neo/pkg/rendezvous/utils.go
@@ -0,0 +1,14 @@
+package rendezvous
+
+import "math"
+
+const maxUInt64 = float64(^uint64(0))
+
+func combineKey(nodeID, value string) string {
+ return nodeID + ":" + value
+}
+
+func weightHash(hash uint64, weight int) float64 {
+ scale := 1.0 / -math.Log(float64(hash)/maxUInt64)
+ return scale * float64(weight)
+}
diff --git a/components/neo/pkg/testutils/testutils.go b/components/neo/pkg/testutils/testutils.go
new file mode 100644
index 0000000..c5b25f4
--- /dev/null
+++ b/components/neo/pkg/testutils/testutils.go
@@ -0,0 +1,78 @@
+package testutils
+
+import (
+ "context"
+ "fmt"
+ "math/rand"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+ "time"
+
+ "github.com/google/uuid"
+
+ "github.com/c4t-but-s4d/neo/v2/pkg/joblogger"
+)
+
+const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
+
+var seededRand = rand.New(rand.NewSource(1337))
+
+func LessString(v1, v2 string) bool {
+ return v1 < v2
+}
+
+func CanceledContext() context.Context {
+ ctx, c := context.WithCancel(context.Background())
+ defer c()
+ return ctx
+}
+
+func TimedOutContext() context.Context {
+ ctx, c := context.WithTimeout(context.Background(), time.Second*0)
+ defer c()
+ return ctx
+}
+
+func RandomStringWithCharset(length int, charset string) string {
+ b := make([]byte, length)
+ for i := range b {
+ b[i] = charset[seededRand.Intn(len(charset))]
+ }
+ return string(b)
+}
+
+func RandomString(length int) string {
+ return RandomStringWithCharset(length, charset)
+}
+
+func RandomInt(min, max int) int {
+ n := seededRand.Intn(max - min)
+ return min + n
+}
+
+func RandomIP() string {
+ gen := func() int {
+ return RandomInt(0, 256)
+ }
+ return fmt.Sprintf("%d.%d.%d.%d", gen(), gen(), gen(), gen())
+}
+
+func MetricsNamespace() string {
+ return fmt.Sprintf("test_%s", uuid.NewString()[:8])
+}
+
+type HTTPRequestChecker func(*testing.T, *http.Request)
+
+func NewCheckedTestServer(t *testing.T, checker HTTPRequestChecker) *httptest.Server {
+ t.Helper()
+ s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ checker(t, r)
+ w.WriteHeader(http.StatusOK)
+ }))
+ return s
+}
+
+func DummyJobLogger(name, team string) *joblogger.JobLogger {
+ return joblogger.New(name, 1, team, joblogger.NewDummySender())
+}
diff --git a/components/neo/proto/buf.gen.yaml b/components/neo/proto/buf.gen.yaml
new file mode 100644
index 0000000..9d3ad12
--- /dev/null
+++ b/components/neo/proto/buf.gen.yaml
@@ -0,0 +1,15 @@
+version: v1
+managed:
+ enabled: true
+ go_package_prefix:
+ default: github.com/c4t-but-s4d/neo/v2/proto/go
+plugins:
+ # Go
+ - name: go
+ out: go
+ opt:
+ - paths=source_relative
+ - name: go-grpc
+ out: go
+ opt:
+ - paths=source_relative
diff --git a/components/neo/proto/buf.yaml b/components/neo/proto/buf.yaml
new file mode 100644
index 0000000..310c5fd
--- /dev/null
+++ b/components/neo/proto/buf.yaml
@@ -0,0 +1,12 @@
+version: v1
+breaking:
+ use:
+ - WIRE_JSON
+lint:
+ use:
+ - DEFAULT
+ except:
+ - PACKAGE_VERSION_SUFFIX
+ - RPC_REQUEST_STANDARD_NAME
+ - RPC_RESPONSE_STANDARD_NAME
+ - RPC_REQUEST_RESPONSE_UNIQUE
diff --git a/components/neo/proto/exploits/api.proto b/components/neo/proto/exploits/api.proto
new file mode 100644
index 0000000..6cfc5de
--- /dev/null
+++ b/components/neo/proto/exploits/api.proto
@@ -0,0 +1,125 @@
+syntax = "proto3";
+package exploits;
+
+option go_package = "exploits";
+
+import "fileserver/api.proto";
+
+import "google/protobuf/duration.proto";
+
+message TeamBucket {
+ map teams = 1;
+}
+
+message ExploitConfiguration {
+ string entrypoint = 1;
+ bool is_archive = 2;
+ google.protobuf.Duration run_every = 3;
+ google.protobuf.Duration timeout = 4;
+ bool disabled = 5;
+ bool endless = 6;
+}
+
+message ExploitState {
+ string exploit_id = 1;
+ int64 version = 2;
+ fileserver.FileInfo file = 3;
+ ExploitConfiguration config = 6;
+}
+
+message Config {
+ string farm_url = 1;
+ string farm_password = 2;
+ string flag_regexp = 3;
+ google.protobuf.Duration ping_every = 4;
+ google.protobuf.Duration submit_every = 5;
+ repeated string environ = 6;
+}
+
+message ServerState {
+ // Распределение опросов по клиентам
+ map client_team_map = 1;
+ repeated ExploitState exploits = 2;
+ Config config = 3;
+}
+
+message PingRequest {
+ string client_id = 1;
+
+ message ServerInfo {
+ }
+
+ message Heartbeat {
+ int32 weight = 1;
+ }
+
+ message Leave {
+ }
+
+ oneof payload {
+ ServerInfo server_info_request = 2;
+ Heartbeat heartbeat_request = 3;
+ Leave leave_request = 4;
+ }
+}
+
+message PingResponse {
+ ServerState state = 1;
+}
+
+message ExploitRequest {
+ string exploit_id = 1;
+}
+
+message ExploitResponse {
+ ExploitState state = 1;
+}
+
+message UpdateExploitRequest {
+ ExploitState state = 1;
+}
+
+message UpdateExploitResponse {
+ ExploitState state = 1;
+}
+
+message BroadcastRequest {
+ string command = 1;
+}
+
+message BroadcastResponse {
+}
+
+message BroadcastSubscribeRequest {
+}
+
+message BroadcastSubscribeResponse {
+ string command = 1;
+}
+
+message SingleRunRequest {
+ string exploit_id = 1;
+}
+
+message SingleRunResponse {
+}
+
+message SingleRunSubscribeRequest {
+}
+
+message SingleRunSubscribeResponse {
+ string exploit_id = 1;
+}
+
+service Service {
+ rpc Ping (PingRequest) returns (PingResponse) {}
+
+ rpc Exploit(ExploitRequest) returns (ExploitResponse) {}
+ rpc UpdateExploit(UpdateExploitRequest) returns (UpdateExploitResponse) {}
+
+ rpc BroadcastCommand(BroadcastRequest) returns (BroadcastResponse) {}
+ rpc BroadcastSubscribe(BroadcastSubscribeRequest) returns (stream BroadcastSubscribeResponse) {}
+
+ rpc SingleRun(SingleRunRequest) returns (SingleRunResponse) {}
+ rpc SingleRunSubscribe(SingleRunSubscribeRequest) returns (stream SingleRunSubscribeResponse) {}
+}
diff --git a/components/neo/proto/fileserver/api.proto b/components/neo/proto/fileserver/api.proto
new file mode 100644
index 0000000..9f2ae21
--- /dev/null
+++ b/components/neo/proto/fileserver/api.proto
@@ -0,0 +1,17 @@
+syntax = "proto3";
+package fileserver;
+
+option go_package = "fileserver";
+
+message FileInfo {
+ string uuid = 1;
+}
+
+message FileStream {
+ bytes chunk = 1;
+}
+
+service Service {
+ rpc UploadFile(stream FileStream) returns (FileInfo) {}
+ rpc DownloadFile(FileInfo) returns (stream FileStream) {}
+}
diff --git a/components/neo/proto/go/exploits/api.pb.go b/components/neo/proto/go/exploits/api.pb.go
new file mode 100644
index 0000000..76e67b5
--- /dev/null
+++ b/components/neo/proto/go/exploits/api.pb.go
@@ -0,0 +1,1742 @@
+// Code generated by protoc-gen-go. DO NOT EDIT.
+// versions:
+// protoc-gen-go v1.28.1
+// protoc (unknown)
+// source: exploits/api.proto
+
+package exploits
+
+import (
+ fileserver "github.com/c4t-but-s4d/neo/v2/proto/go/fileserver"
+ protoreflect "google.golang.org/protobuf/reflect/protoreflect"
+ protoimpl "google.golang.org/protobuf/runtime/protoimpl"
+ durationpb "google.golang.org/protobuf/types/known/durationpb"
+ reflect "reflect"
+ sync "sync"
+)
+
+const (
+ // Verify that this generated code is sufficiently up-to-date.
+ _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
+ // Verify that runtime/protoimpl is sufficiently up-to-date.
+ _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
+)
+
+type TeamBucket struct {
+ state protoimpl.MessageState
+ sizeCache protoimpl.SizeCache
+ unknownFields protoimpl.UnknownFields
+
+ Teams map[string]string `protobuf:"bytes,1,rep,name=teams,proto3" json:"teams,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"`
+}
+
+func (x *TeamBucket) Reset() {
+ *x = TeamBucket{}
+ if protoimpl.UnsafeEnabled {
+ mi := &file_exploits_api_proto_msgTypes[0]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+ }
+}
+
+func (x *TeamBucket) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*TeamBucket) ProtoMessage() {}
+
+func (x *TeamBucket) ProtoReflect() protoreflect.Message {
+ mi := &file_exploits_api_proto_msgTypes[0]
+ if protoimpl.UnsafeEnabled && x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use TeamBucket.ProtoReflect.Descriptor instead.
+func (*TeamBucket) Descriptor() ([]byte, []int) {
+ return file_exploits_api_proto_rawDescGZIP(), []int{0}
+}
+
+func (x *TeamBucket) GetTeams() map[string]string {
+ if x != nil {
+ return x.Teams
+ }
+ return nil
+}
+
+type ExploitConfiguration struct {
+ state protoimpl.MessageState
+ sizeCache protoimpl.SizeCache
+ unknownFields protoimpl.UnknownFields
+
+ Entrypoint string `protobuf:"bytes,1,opt,name=entrypoint,proto3" json:"entrypoint,omitempty"`
+ IsArchive bool `protobuf:"varint,2,opt,name=is_archive,json=isArchive,proto3" json:"is_archive,omitempty"`
+ RunEvery *durationpb.Duration `protobuf:"bytes,3,opt,name=run_every,json=runEvery,proto3" json:"run_every,omitempty"`
+ Timeout *durationpb.Duration `protobuf:"bytes,4,opt,name=timeout,proto3" json:"timeout,omitempty"`
+ Disabled bool `protobuf:"varint,5,opt,name=disabled,proto3" json:"disabled,omitempty"`
+ Endless bool `protobuf:"varint,6,opt,name=endless,proto3" json:"endless,omitempty"`
+}
+
+func (x *ExploitConfiguration) Reset() {
+ *x = ExploitConfiguration{}
+ if protoimpl.UnsafeEnabled {
+ mi := &file_exploits_api_proto_msgTypes[1]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+ }
+}
+
+func (x *ExploitConfiguration) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*ExploitConfiguration) ProtoMessage() {}
+
+func (x *ExploitConfiguration) ProtoReflect() protoreflect.Message {
+ mi := &file_exploits_api_proto_msgTypes[1]
+ if protoimpl.UnsafeEnabled && x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use ExploitConfiguration.ProtoReflect.Descriptor instead.
+func (*ExploitConfiguration) Descriptor() ([]byte, []int) {
+ return file_exploits_api_proto_rawDescGZIP(), []int{1}
+}
+
+func (x *ExploitConfiguration) GetEntrypoint() string {
+ if x != nil {
+ return x.Entrypoint
+ }
+ return ""
+}
+
+func (x *ExploitConfiguration) GetIsArchive() bool {
+ if x != nil {
+ return x.IsArchive
+ }
+ return false
+}
+
+func (x *ExploitConfiguration) GetRunEvery() *durationpb.Duration {
+ if x != nil {
+ return x.RunEvery
+ }
+ return nil
+}
+
+func (x *ExploitConfiguration) GetTimeout() *durationpb.Duration {
+ if x != nil {
+ return x.Timeout
+ }
+ return nil
+}
+
+func (x *ExploitConfiguration) GetDisabled() bool {
+ if x != nil {
+ return x.Disabled
+ }
+ return false
+}
+
+func (x *ExploitConfiguration) GetEndless() bool {
+ if x != nil {
+ return x.Endless
+ }
+ return false
+}
+
+type ExploitState struct {
+ state protoimpl.MessageState
+ sizeCache protoimpl.SizeCache
+ unknownFields protoimpl.UnknownFields
+
+ ExploitId string `protobuf:"bytes,1,opt,name=exploit_id,json=exploitId,proto3" json:"exploit_id,omitempty"`
+ Version int64 `protobuf:"varint,2,opt,name=version,proto3" json:"version,omitempty"`
+ File *fileserver.FileInfo `protobuf:"bytes,3,opt,name=file,proto3" json:"file,omitempty"`
+ Config *ExploitConfiguration `protobuf:"bytes,6,opt,name=config,proto3" json:"config,omitempty"`
+}
+
+func (x *ExploitState) Reset() {
+ *x = ExploitState{}
+ if protoimpl.UnsafeEnabled {
+ mi := &file_exploits_api_proto_msgTypes[2]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+ }
+}
+
+func (x *ExploitState) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*ExploitState) ProtoMessage() {}
+
+func (x *ExploitState) ProtoReflect() protoreflect.Message {
+ mi := &file_exploits_api_proto_msgTypes[2]
+ if protoimpl.UnsafeEnabled && x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use ExploitState.ProtoReflect.Descriptor instead.
+func (*ExploitState) Descriptor() ([]byte, []int) {
+ return file_exploits_api_proto_rawDescGZIP(), []int{2}
+}
+
+func (x *ExploitState) GetExploitId() string {
+ if x != nil {
+ return x.ExploitId
+ }
+ return ""
+}
+
+func (x *ExploitState) GetVersion() int64 {
+ if x != nil {
+ return x.Version
+ }
+ return 0
+}
+
+func (x *ExploitState) GetFile() *fileserver.FileInfo {
+ if x != nil {
+ return x.File
+ }
+ return nil
+}
+
+func (x *ExploitState) GetConfig() *ExploitConfiguration {
+ if x != nil {
+ return x.Config
+ }
+ return nil
+}
+
+type Config struct {
+ state protoimpl.MessageState
+ sizeCache protoimpl.SizeCache
+ unknownFields protoimpl.UnknownFields
+
+ FarmUrl string `protobuf:"bytes,1,opt,name=farm_url,json=farmUrl,proto3" json:"farm_url,omitempty"`
+ FarmPassword string `protobuf:"bytes,2,opt,name=farm_password,json=farmPassword,proto3" json:"farm_password,omitempty"`
+ FlagRegexp string `protobuf:"bytes,3,opt,name=flag_regexp,json=flagRegexp,proto3" json:"flag_regexp,omitempty"`
+ PingEvery *durationpb.Duration `protobuf:"bytes,4,opt,name=ping_every,json=pingEvery,proto3" json:"ping_every,omitempty"`
+ SubmitEvery *durationpb.Duration `protobuf:"bytes,5,opt,name=submit_every,json=submitEvery,proto3" json:"submit_every,omitempty"`
+ Environ []string `protobuf:"bytes,6,rep,name=environ,proto3" json:"environ,omitempty"`
+}
+
+func (x *Config) Reset() {
+ *x = Config{}
+ if protoimpl.UnsafeEnabled {
+ mi := &file_exploits_api_proto_msgTypes[3]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+ }
+}
+
+func (x *Config) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*Config) ProtoMessage() {}
+
+func (x *Config) ProtoReflect() protoreflect.Message {
+ mi := &file_exploits_api_proto_msgTypes[3]
+ if protoimpl.UnsafeEnabled && x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use Config.ProtoReflect.Descriptor instead.
+func (*Config) Descriptor() ([]byte, []int) {
+ return file_exploits_api_proto_rawDescGZIP(), []int{3}
+}
+
+func (x *Config) GetFarmUrl() string {
+ if x != nil {
+ return x.FarmUrl
+ }
+ return ""
+}
+
+func (x *Config) GetFarmPassword() string {
+ if x != nil {
+ return x.FarmPassword
+ }
+ return ""
+}
+
+func (x *Config) GetFlagRegexp() string {
+ if x != nil {
+ return x.FlagRegexp
+ }
+ return ""
+}
+
+func (x *Config) GetPingEvery() *durationpb.Duration {
+ if x != nil {
+ return x.PingEvery
+ }
+ return nil
+}
+
+func (x *Config) GetSubmitEvery() *durationpb.Duration {
+ if x != nil {
+ return x.SubmitEvery
+ }
+ return nil
+}
+
+func (x *Config) GetEnviron() []string {
+ if x != nil {
+ return x.Environ
+ }
+ return nil
+}
+
+type ServerState struct {
+ state protoimpl.MessageState
+ sizeCache protoimpl.SizeCache
+ unknownFields protoimpl.UnknownFields
+
+ // Ping distribution by client
+ ClientTeamMap map[string]*TeamBucket `protobuf:"bytes,1,rep,name=client_team_map,json=clientTeamMap,proto3" json:"client_team_map,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"`
+ Exploits []*ExploitState `protobuf:"bytes,2,rep,name=exploits,proto3" json:"exploits,omitempty"`
+ Config *Config `protobuf:"bytes,3,opt,name=config,proto3" json:"config,omitempty"`
+}
+
+func (x *ServerState) Reset() {
+ *x = ServerState{}
+ if protoimpl.UnsafeEnabled {
+ mi := &file_exploits_api_proto_msgTypes[4]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+ }
+}
+
+func (x *ServerState) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*ServerState) ProtoMessage() {}
+
+func (x *ServerState) ProtoReflect() protoreflect.Message {
+ mi := &file_exploits_api_proto_msgTypes[4]
+ if protoimpl.UnsafeEnabled && x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use ServerState.ProtoReflect.Descriptor instead.
+func (*ServerState) Descriptor() ([]byte, []int) {
+ return file_exploits_api_proto_rawDescGZIP(), []int{4}
+}
+
+func (x *ServerState) GetClientTeamMap() map[string]*TeamBucket {
+ if x != nil {
+ return x.ClientTeamMap
+ }
+ return nil
+}
+
+func (x *ServerState) GetExploits() []*ExploitState {
+ if x != nil {
+ return x.Exploits
+ }
+ return nil
+}
+
+func (x *ServerState) GetConfig() *Config {
+ if x != nil {
+ return x.Config
+ }
+ return nil
+}
+
+type PingRequest struct {
+ state protoimpl.MessageState
+ sizeCache protoimpl.SizeCache
+ unknownFields protoimpl.UnknownFields
+
+ ClientId string `protobuf:"bytes,1,opt,name=client_id,json=clientId,proto3" json:"client_id,omitempty"`
+ // Types that are assignable to Payload:
+ //
+ // *PingRequest_ServerInfoRequest
+ // *PingRequest_HeartbeatRequest
+ // *PingRequest_LeaveRequest
+ Payload isPingRequest_Payload `protobuf_oneof:"payload"`
+}
+
+func (x *PingRequest) Reset() {
+ *x = PingRequest{}
+ if protoimpl.UnsafeEnabled {
+ mi := &file_exploits_api_proto_msgTypes[5]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+ }
+}
+
+func (x *PingRequest) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*PingRequest) ProtoMessage() {}
+
+func (x *PingRequest) ProtoReflect() protoreflect.Message {
+ mi := &file_exploits_api_proto_msgTypes[5]
+ if protoimpl.UnsafeEnabled && x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use PingRequest.ProtoReflect.Descriptor instead.
+func (*PingRequest) Descriptor() ([]byte, []int) {
+ return file_exploits_api_proto_rawDescGZIP(), []int{5}
+}
+
+func (x *PingRequest) GetClientId() string {
+ if x != nil {
+ return x.ClientId
+ }
+ return ""
+}
+
+func (m *PingRequest) GetPayload() isPingRequest_Payload {
+ if m != nil {
+ return m.Payload
+ }
+ return nil
+}
+
+func (x *PingRequest) GetServerInfoRequest() *PingRequest_ServerInfo {
+ if x, ok := x.GetPayload().(*PingRequest_ServerInfoRequest); ok {
+ return x.ServerInfoRequest
+ }
+ return nil
+}
+
+func (x *PingRequest) GetHeartbeatRequest() *PingRequest_Heartbeat {
+ if x, ok := x.GetPayload().(*PingRequest_HeartbeatRequest); ok {
+ return x.HeartbeatRequest
+ }
+ return nil
+}
+
+func (x *PingRequest) GetLeaveRequest() *PingRequest_Leave {
+ if x, ok := x.GetPayload().(*PingRequest_LeaveRequest); ok {
+ return x.LeaveRequest
+ }
+ return nil
+}
+
+type isPingRequest_Payload interface {
+ isPingRequest_Payload()
+}
+
+type PingRequest_ServerInfoRequest struct {
+ ServerInfoRequest *PingRequest_ServerInfo `protobuf:"bytes,2,opt,name=server_info_request,json=serverInfoRequest,proto3,oneof"`
+}
+
+type PingRequest_HeartbeatRequest struct {
+ HeartbeatRequest *PingRequest_Heartbeat `protobuf:"bytes,3,opt,name=heartbeat_request,json=heartbeatRequest,proto3,oneof"`
+}
+
+type PingRequest_LeaveRequest struct {
+ LeaveRequest *PingRequest_Leave `protobuf:"bytes,4,opt,name=leave_request,json=leaveRequest,proto3,oneof"`
+}
+
+func (*PingRequest_ServerInfoRequest) isPingRequest_Payload() {}
+
+func (*PingRequest_HeartbeatRequest) isPingRequest_Payload() {}
+
+func (*PingRequest_LeaveRequest) isPingRequest_Payload() {}
+
+type PingResponse struct {
+ state protoimpl.MessageState
+ sizeCache protoimpl.SizeCache
+ unknownFields protoimpl.UnknownFields
+
+ State *ServerState `protobuf:"bytes,1,opt,name=state,proto3" json:"state,omitempty"`
+}
+
+func (x *PingResponse) Reset() {
+ *x = PingResponse{}
+ if protoimpl.UnsafeEnabled {
+ mi := &file_exploits_api_proto_msgTypes[6]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+ }
+}
+
+func (x *PingResponse) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*PingResponse) ProtoMessage() {}
+
+func (x *PingResponse) ProtoReflect() protoreflect.Message {
+ mi := &file_exploits_api_proto_msgTypes[6]
+ if protoimpl.UnsafeEnabled && x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use PingResponse.ProtoReflect.Descriptor instead.
+func (*PingResponse) Descriptor() ([]byte, []int) {
+ return file_exploits_api_proto_rawDescGZIP(), []int{6}
+}
+
+func (x *PingResponse) GetState() *ServerState {
+ if x != nil {
+ return x.State
+ }
+ return nil
+}
+
+type ExploitRequest struct {
+ state protoimpl.MessageState
+ sizeCache protoimpl.SizeCache
+ unknownFields protoimpl.UnknownFields
+
+ ExploitId string `protobuf:"bytes,1,opt,name=exploit_id,json=exploitId,proto3" json:"exploit_id,omitempty"`
+}
+
+func (x *ExploitRequest) Reset() {
+ *x = ExploitRequest{}
+ if protoimpl.UnsafeEnabled {
+ mi := &file_exploits_api_proto_msgTypes[7]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+ }
+}
+
+func (x *ExploitRequest) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*ExploitRequest) ProtoMessage() {}
+
+func (x *ExploitRequest) ProtoReflect() protoreflect.Message {
+ mi := &file_exploits_api_proto_msgTypes[7]
+ if protoimpl.UnsafeEnabled && x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use ExploitRequest.ProtoReflect.Descriptor instead.
+func (*ExploitRequest) Descriptor() ([]byte, []int) {
+ return file_exploits_api_proto_rawDescGZIP(), []int{7}
+}
+
+func (x *ExploitRequest) GetExploitId() string {
+ if x != nil {
+ return x.ExploitId
+ }
+ return ""
+}
+
+type ExploitResponse struct {
+ state protoimpl.MessageState
+ sizeCache protoimpl.SizeCache
+ unknownFields protoimpl.UnknownFields
+
+ State *ExploitState `protobuf:"bytes,1,opt,name=state,proto3" json:"state,omitempty"`
+}
+
+func (x *ExploitResponse) Reset() {
+ *x = ExploitResponse{}
+ if protoimpl.UnsafeEnabled {
+ mi := &file_exploits_api_proto_msgTypes[8]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+ }
+}
+
+func (x *ExploitResponse) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*ExploitResponse) ProtoMessage() {}
+
+func (x *ExploitResponse) ProtoReflect() protoreflect.Message {
+ mi := &file_exploits_api_proto_msgTypes[8]
+ if protoimpl.UnsafeEnabled && x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use ExploitResponse.ProtoReflect.Descriptor instead.
+func (*ExploitResponse) Descriptor() ([]byte, []int) {
+ return file_exploits_api_proto_rawDescGZIP(), []int{8}
+}
+
+func (x *ExploitResponse) GetState() *ExploitState {
+ if x != nil {
+ return x.State
+ }
+ return nil
+}
+
+type UpdateExploitRequest struct {
+ state protoimpl.MessageState
+ sizeCache protoimpl.SizeCache
+ unknownFields protoimpl.UnknownFields
+
+ State *ExploitState `protobuf:"bytes,1,opt,name=state,proto3" json:"state,omitempty"`
+}
+
+func (x *UpdateExploitRequest) Reset() {
+ *x = UpdateExploitRequest{}
+ if protoimpl.UnsafeEnabled {
+ mi := &file_exploits_api_proto_msgTypes[9]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+ }
+}
+
+func (x *UpdateExploitRequest) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*UpdateExploitRequest) ProtoMessage() {}
+
+func (x *UpdateExploitRequest) ProtoReflect() protoreflect.Message {
+ mi := &file_exploits_api_proto_msgTypes[9]
+ if protoimpl.UnsafeEnabled && x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use UpdateExploitRequest.ProtoReflect.Descriptor instead.
+func (*UpdateExploitRequest) Descriptor() ([]byte, []int) {
+ return file_exploits_api_proto_rawDescGZIP(), []int{9}
+}
+
+func (x *UpdateExploitRequest) GetState() *ExploitState {
+ if x != nil {
+ return x.State
+ }
+ return nil
+}
+
+type UpdateExploitResponse struct {
+ state protoimpl.MessageState
+ sizeCache protoimpl.SizeCache
+ unknownFields protoimpl.UnknownFields
+
+ State *ExploitState `protobuf:"bytes,1,opt,name=state,proto3" json:"state,omitempty"`
+}
+
+func (x *UpdateExploitResponse) Reset() {
+ *x = UpdateExploitResponse{}
+ if protoimpl.UnsafeEnabled {
+ mi := &file_exploits_api_proto_msgTypes[10]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+ }
+}
+
+func (x *UpdateExploitResponse) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*UpdateExploitResponse) ProtoMessage() {}
+
+func (x *UpdateExploitResponse) ProtoReflect() protoreflect.Message {
+ mi := &file_exploits_api_proto_msgTypes[10]
+ if protoimpl.UnsafeEnabled && x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use UpdateExploitResponse.ProtoReflect.Descriptor instead.
+func (*UpdateExploitResponse) Descriptor() ([]byte, []int) {
+ return file_exploits_api_proto_rawDescGZIP(), []int{10}
+}
+
+func (x *UpdateExploitResponse) GetState() *ExploitState {
+ if x != nil {
+ return x.State
+ }
+ return nil
+}
+
+type BroadcastRequest struct {
+ state protoimpl.MessageState
+ sizeCache protoimpl.SizeCache
+ unknownFields protoimpl.UnknownFields
+
+ Command string `protobuf:"bytes,1,opt,name=command,proto3" json:"command,omitempty"`
+}
+
+func (x *BroadcastRequest) Reset() {
+ *x = BroadcastRequest{}
+ if protoimpl.UnsafeEnabled {
+ mi := &file_exploits_api_proto_msgTypes[11]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+ }
+}
+
+func (x *BroadcastRequest) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*BroadcastRequest) ProtoMessage() {}
+
+func (x *BroadcastRequest) ProtoReflect() protoreflect.Message {
+ mi := &file_exploits_api_proto_msgTypes[11]
+ if protoimpl.UnsafeEnabled && x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use BroadcastRequest.ProtoReflect.Descriptor instead.
+func (*BroadcastRequest) Descriptor() ([]byte, []int) {
+ return file_exploits_api_proto_rawDescGZIP(), []int{11}
+}
+
+func (x *BroadcastRequest) GetCommand() string {
+ if x != nil {
+ return x.Command
+ }
+ return ""
+}
+
+type BroadcastResponse struct {
+ state protoimpl.MessageState
+ sizeCache protoimpl.SizeCache
+ unknownFields protoimpl.UnknownFields
+}
+
+func (x *BroadcastResponse) Reset() {
+ *x = BroadcastResponse{}
+ if protoimpl.UnsafeEnabled {
+ mi := &file_exploits_api_proto_msgTypes[12]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+ }
+}
+
+func (x *BroadcastResponse) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*BroadcastResponse) ProtoMessage() {}
+
+func (x *BroadcastResponse) ProtoReflect() protoreflect.Message {
+ mi := &file_exploits_api_proto_msgTypes[12]
+ if protoimpl.UnsafeEnabled && x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use BroadcastResponse.ProtoReflect.Descriptor instead.
+func (*BroadcastResponse) Descriptor() ([]byte, []int) {
+ return file_exploits_api_proto_rawDescGZIP(), []int{12}
+}
+
+type BroadcastSubscribeRequest struct {
+ state protoimpl.MessageState
+ sizeCache protoimpl.SizeCache
+ unknownFields protoimpl.UnknownFields
+}
+
+func (x *BroadcastSubscribeRequest) Reset() {
+ *x = BroadcastSubscribeRequest{}
+ if protoimpl.UnsafeEnabled {
+ mi := &file_exploits_api_proto_msgTypes[13]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+ }
+}
+
+func (x *BroadcastSubscribeRequest) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*BroadcastSubscribeRequest) ProtoMessage() {}
+
+func (x *BroadcastSubscribeRequest) ProtoReflect() protoreflect.Message {
+ mi := &file_exploits_api_proto_msgTypes[13]
+ if protoimpl.UnsafeEnabled && x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use BroadcastSubscribeRequest.ProtoReflect.Descriptor instead.
+func (*BroadcastSubscribeRequest) Descriptor() ([]byte, []int) {
+ return file_exploits_api_proto_rawDescGZIP(), []int{13}
+}
+
+type BroadcastSubscribeResponse struct {
+ state protoimpl.MessageState
+ sizeCache protoimpl.SizeCache
+ unknownFields protoimpl.UnknownFields
+
+ Command string `protobuf:"bytes,1,opt,name=command,proto3" json:"command,omitempty"`
+}
+
+func (x *BroadcastSubscribeResponse) Reset() {
+ *x = BroadcastSubscribeResponse{}
+ if protoimpl.UnsafeEnabled {
+ mi := &file_exploits_api_proto_msgTypes[14]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+ }
+}
+
+func (x *BroadcastSubscribeResponse) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*BroadcastSubscribeResponse) ProtoMessage() {}
+
+func (x *BroadcastSubscribeResponse) ProtoReflect() protoreflect.Message {
+ mi := &file_exploits_api_proto_msgTypes[14]
+ if protoimpl.UnsafeEnabled && x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use BroadcastSubscribeResponse.ProtoReflect.Descriptor instead.
+func (*BroadcastSubscribeResponse) Descriptor() ([]byte, []int) {
+ return file_exploits_api_proto_rawDescGZIP(), []int{14}
+}
+
+func (x *BroadcastSubscribeResponse) GetCommand() string {
+ if x != nil {
+ return x.Command
+ }
+ return ""
+}
+
+type SingleRunRequest struct {
+ state protoimpl.MessageState
+ sizeCache protoimpl.SizeCache
+ unknownFields protoimpl.UnknownFields
+
+ ExploitId string `protobuf:"bytes,1,opt,name=exploit_id,json=exploitId,proto3" json:"exploit_id,omitempty"`
+}
+
+func (x *SingleRunRequest) Reset() {
+ *x = SingleRunRequest{}
+ if protoimpl.UnsafeEnabled {
+ mi := &file_exploits_api_proto_msgTypes[15]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+ }
+}
+
+func (x *SingleRunRequest) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*SingleRunRequest) ProtoMessage() {}
+
+func (x *SingleRunRequest) ProtoReflect() protoreflect.Message {
+ mi := &file_exploits_api_proto_msgTypes[15]
+ if protoimpl.UnsafeEnabled && x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use SingleRunRequest.ProtoReflect.Descriptor instead.
+func (*SingleRunRequest) Descriptor() ([]byte, []int) {
+ return file_exploits_api_proto_rawDescGZIP(), []int{15}
+}
+
+func (x *SingleRunRequest) GetExploitId() string {
+ if x != nil {
+ return x.ExploitId
+ }
+ return ""
+}
+
+type SingleRunResponse struct {
+ state protoimpl.MessageState
+ sizeCache protoimpl.SizeCache
+ unknownFields protoimpl.UnknownFields
+}
+
+func (x *SingleRunResponse) Reset() {
+ *x = SingleRunResponse{}
+ if protoimpl.UnsafeEnabled {
+ mi := &file_exploits_api_proto_msgTypes[16]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+ }
+}
+
+func (x *SingleRunResponse) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*SingleRunResponse) ProtoMessage() {}
+
+func (x *SingleRunResponse) ProtoReflect() protoreflect.Message {
+ mi := &file_exploits_api_proto_msgTypes[16]
+ if protoimpl.UnsafeEnabled && x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use SingleRunResponse.ProtoReflect.Descriptor instead.
+func (*SingleRunResponse) Descriptor() ([]byte, []int) {
+ return file_exploits_api_proto_rawDescGZIP(), []int{16}
+}
+
+type SingleRunSubscribeRequest struct {
+ state protoimpl.MessageState
+ sizeCache protoimpl.SizeCache
+ unknownFields protoimpl.UnknownFields
+}
+
+func (x *SingleRunSubscribeRequest) Reset() {
+ *x = SingleRunSubscribeRequest{}
+ if protoimpl.UnsafeEnabled {
+ mi := &file_exploits_api_proto_msgTypes[17]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+ }
+}
+
+func (x *SingleRunSubscribeRequest) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*SingleRunSubscribeRequest) ProtoMessage() {}
+
+func (x *SingleRunSubscribeRequest) ProtoReflect() protoreflect.Message {
+ mi := &file_exploits_api_proto_msgTypes[17]
+ if protoimpl.UnsafeEnabled && x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use SingleRunSubscribeRequest.ProtoReflect.Descriptor instead.
+func (*SingleRunSubscribeRequest) Descriptor() ([]byte, []int) {
+ return file_exploits_api_proto_rawDescGZIP(), []int{17}
+}
+
+type SingleRunSubscribeResponse struct {
+ state protoimpl.MessageState
+ sizeCache protoimpl.SizeCache
+ unknownFields protoimpl.UnknownFields
+
+ ExploitId string `protobuf:"bytes,1,opt,name=exploit_id,json=exploitId,proto3" json:"exploit_id,omitempty"`
+}
+
+func (x *SingleRunSubscribeResponse) Reset() {
+ *x = SingleRunSubscribeResponse{}
+ if protoimpl.UnsafeEnabled {
+ mi := &file_exploits_api_proto_msgTypes[18]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+ }
+}
+
+func (x *SingleRunSubscribeResponse) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*SingleRunSubscribeResponse) ProtoMessage() {}
+
+func (x *SingleRunSubscribeResponse) ProtoReflect() protoreflect.Message {
+ mi := &file_exploits_api_proto_msgTypes[18]
+ if protoimpl.UnsafeEnabled && x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use SingleRunSubscribeResponse.ProtoReflect.Descriptor instead.
+func (*SingleRunSubscribeResponse) Descriptor() ([]byte, []int) {
+ return file_exploits_api_proto_rawDescGZIP(), []int{18}
+}
+
+func (x *SingleRunSubscribeResponse) GetExploitId() string {
+ if x != nil {
+ return x.ExploitId
+ }
+ return ""
+}
+
+type PingRequest_ServerInfo struct {
+ state protoimpl.MessageState
+ sizeCache protoimpl.SizeCache
+ unknownFields protoimpl.UnknownFields
+}
+
+func (x *PingRequest_ServerInfo) Reset() {
+ *x = PingRequest_ServerInfo{}
+ if protoimpl.UnsafeEnabled {
+ mi := &file_exploits_api_proto_msgTypes[21]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+ }
+}
+
+func (x *PingRequest_ServerInfo) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*PingRequest_ServerInfo) ProtoMessage() {}
+
+func (x *PingRequest_ServerInfo) ProtoReflect() protoreflect.Message {
+ mi := &file_exploits_api_proto_msgTypes[21]
+ if protoimpl.UnsafeEnabled && x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use PingRequest_ServerInfo.ProtoReflect.Descriptor instead.
+func (*PingRequest_ServerInfo) Descriptor() ([]byte, []int) {
+ return file_exploits_api_proto_rawDescGZIP(), []int{5, 0}
+}
+
+type PingRequest_Heartbeat struct {
+ state protoimpl.MessageState
+ sizeCache protoimpl.SizeCache
+ unknownFields protoimpl.UnknownFields
+
+ Weight int32 `protobuf:"varint,1,opt,name=weight,proto3" json:"weight,omitempty"`
+}
+
+func (x *PingRequest_Heartbeat) Reset() {
+ *x = PingRequest_Heartbeat{}
+ if protoimpl.UnsafeEnabled {
+ mi := &file_exploits_api_proto_msgTypes[22]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+ }
+}
+
+func (x *PingRequest_Heartbeat) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*PingRequest_Heartbeat) ProtoMessage() {}
+
+func (x *PingRequest_Heartbeat) ProtoReflect() protoreflect.Message {
+ mi := &file_exploits_api_proto_msgTypes[22]
+ if protoimpl.UnsafeEnabled && x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use PingRequest_Heartbeat.ProtoReflect.Descriptor instead.
+func (*PingRequest_Heartbeat) Descriptor() ([]byte, []int) {
+ return file_exploits_api_proto_rawDescGZIP(), []int{5, 1}
+}
+
+func (x *PingRequest_Heartbeat) GetWeight() int32 {
+ if x != nil {
+ return x.Weight
+ }
+ return 0
+}
+
+type PingRequest_Leave struct {
+ state protoimpl.MessageState
+ sizeCache protoimpl.SizeCache
+ unknownFields protoimpl.UnknownFields
+}
+
+func (x *PingRequest_Leave) Reset() {
+ *x = PingRequest_Leave{}
+ if protoimpl.UnsafeEnabled {
+ mi := &file_exploits_api_proto_msgTypes[23]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+ }
+}
+
+func (x *PingRequest_Leave) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*PingRequest_Leave) ProtoMessage() {}
+
+func (x *PingRequest_Leave) ProtoReflect() protoreflect.Message {
+ mi := &file_exploits_api_proto_msgTypes[23]
+ if protoimpl.UnsafeEnabled && x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use PingRequest_Leave.ProtoReflect.Descriptor instead.
+func (*PingRequest_Leave) Descriptor() ([]byte, []int) {
+ return file_exploits_api_proto_rawDescGZIP(), []int{5, 2}
+}
+
+var File_exploits_api_proto protoreflect.FileDescriptor
+
+var file_exploits_api_proto_rawDesc = []byte{
+ 0x0a, 0x12, 0x65, 0x78, 0x70, 0x6c, 0x6f, 0x69, 0x74, 0x73, 0x2f, 0x61, 0x70, 0x69, 0x2e, 0x70,
+ 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x08, 0x65, 0x78, 0x70, 0x6c, 0x6f, 0x69, 0x74, 0x73, 0x1a, 0x14,
+ 0x66, 0x69, 0x6c, 0x65, 0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x2f, 0x61, 0x70, 0x69, 0x2e, 0x70,
+ 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x1e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f,
+ 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x64, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x2e, 0x70,
+ 0x72, 0x6f, 0x74, 0x6f, 0x22, 0x7d, 0x0a, 0x0a, 0x54, 0x65, 0x61, 0x6d, 0x42, 0x75, 0x63, 0x6b,
+ 0x65, 0x74, 0x12, 0x35, 0x0a, 0x05, 0x74, 0x65, 0x61, 0x6d, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28,
+ 0x0b, 0x32, 0x1f, 0x2e, 0x65, 0x78, 0x70, 0x6c, 0x6f, 0x69, 0x74, 0x73, 0x2e, 0x54, 0x65, 0x61,
+ 0x6d, 0x42, 0x75, 0x63, 0x6b, 0x65, 0x74, 0x2e, 0x54, 0x65, 0x61, 0x6d, 0x73, 0x45, 0x6e, 0x74,
+ 0x72, 0x79, 0x52, 0x05, 0x74, 0x65, 0x61, 0x6d, 0x73, 0x1a, 0x38, 0x0a, 0x0a, 0x54, 0x65, 0x61,
+ 0x6d, 0x73, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x12, 0x10, 0x0a, 0x03, 0x6b, 0x65, 0x79, 0x18, 0x01,
+ 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x6b, 0x65, 0x79, 0x12, 0x14, 0x0a, 0x05, 0x76, 0x61, 0x6c,
+ 0x75, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x3a,
+ 0x02, 0x38, 0x01, 0x22, 0xf8, 0x01, 0x0a, 0x14, 0x45, 0x78, 0x70, 0x6c, 0x6f, 0x69, 0x74, 0x43,
+ 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x1e, 0x0a, 0x0a,
+ 0x65, 0x6e, 0x74, 0x72, 0x79, 0x70, 0x6f, 0x69, 0x6e, 0x74, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09,
+ 0x52, 0x0a, 0x65, 0x6e, 0x74, 0x72, 0x79, 0x70, 0x6f, 0x69, 0x6e, 0x74, 0x12, 0x1d, 0x0a, 0x0a,
+ 0x69, 0x73, 0x5f, 0x61, 0x72, 0x63, 0x68, 0x69, 0x76, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x08,
+ 0x52, 0x09, 0x69, 0x73, 0x41, 0x72, 0x63, 0x68, 0x69, 0x76, 0x65, 0x12, 0x36, 0x0a, 0x09, 0x72,
+ 0x75, 0x6e, 0x5f, 0x65, 0x76, 0x65, 0x72, 0x79, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19,
+ 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66,
+ 0x2e, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x08, 0x72, 0x75, 0x6e, 0x45, 0x76,
+ 0x65, 0x72, 0x79, 0x12, 0x33, 0x0a, 0x07, 0x74, 0x69, 0x6d, 0x65, 0x6f, 0x75, 0x74, 0x18, 0x04,
+ 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72,
+ 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52,
+ 0x07, 0x74, 0x69, 0x6d, 0x65, 0x6f, 0x75, 0x74, 0x12, 0x1a, 0x0a, 0x08, 0x64, 0x69, 0x73, 0x61,
+ 0x62, 0x6c, 0x65, 0x64, 0x18, 0x05, 0x20, 0x01, 0x28, 0x08, 0x52, 0x08, 0x64, 0x69, 0x73, 0x61,
+ 0x62, 0x6c, 0x65, 0x64, 0x12, 0x18, 0x0a, 0x07, 0x65, 0x6e, 0x64, 0x6c, 0x65, 0x73, 0x73, 0x18,
+ 0x06, 0x20, 0x01, 0x28, 0x08, 0x52, 0x07, 0x65, 0x6e, 0x64, 0x6c, 0x65, 0x73, 0x73, 0x22, 0xa9,
+ 0x01, 0x0a, 0x0c, 0x45, 0x78, 0x70, 0x6c, 0x6f, 0x69, 0x74, 0x53, 0x74, 0x61, 0x74, 0x65, 0x12,
+ 0x1d, 0x0a, 0x0a, 0x65, 0x78, 0x70, 0x6c, 0x6f, 0x69, 0x74, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20,
+ 0x01, 0x28, 0x09, 0x52, 0x09, 0x65, 0x78, 0x70, 0x6c, 0x6f, 0x69, 0x74, 0x49, 0x64, 0x12, 0x18,
+ 0x0a, 0x07, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x18, 0x02, 0x20, 0x01, 0x28, 0x03, 0x52,
+ 0x07, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x12, 0x28, 0x0a, 0x04, 0x66, 0x69, 0x6c, 0x65,
+ 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x14, 0x2e, 0x66, 0x69, 0x6c, 0x65, 0x73, 0x65, 0x72,
+ 0x76, 0x65, 0x72, 0x2e, 0x46, 0x69, 0x6c, 0x65, 0x49, 0x6e, 0x66, 0x6f, 0x52, 0x04, 0x66, 0x69,
+ 0x6c, 0x65, 0x12, 0x36, 0x0a, 0x06, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x18, 0x06, 0x20, 0x01,
+ 0x28, 0x0b, 0x32, 0x1e, 0x2e, 0x65, 0x78, 0x70, 0x6c, 0x6f, 0x69, 0x74, 0x73, 0x2e, 0x45, 0x78,
+ 0x70, 0x6c, 0x6f, 0x69, 0x74, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x75, 0x72, 0x61, 0x74, 0x69,
+ 0x6f, 0x6e, 0x52, 0x06, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x22, 0xfb, 0x01, 0x0a, 0x06, 0x43,
+ 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x12, 0x19, 0x0a, 0x08, 0x66, 0x61, 0x72, 0x6d, 0x5f, 0x75, 0x72,
+ 0x6c, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x66, 0x61, 0x72, 0x6d, 0x55, 0x72, 0x6c,
+ 0x12, 0x23, 0x0a, 0x0d, 0x66, 0x61, 0x72, 0x6d, 0x5f, 0x70, 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72,
+ 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0c, 0x66, 0x61, 0x72, 0x6d, 0x50, 0x61, 0x73,
+ 0x73, 0x77, 0x6f, 0x72, 0x64, 0x12, 0x1f, 0x0a, 0x0b, 0x66, 0x6c, 0x61, 0x67, 0x5f, 0x72, 0x65,
+ 0x67, 0x65, 0x78, 0x70, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0a, 0x66, 0x6c, 0x61, 0x67,
+ 0x52, 0x65, 0x67, 0x65, 0x78, 0x70, 0x12, 0x38, 0x0a, 0x0a, 0x70, 0x69, 0x6e, 0x67, 0x5f, 0x65,
+ 0x76, 0x65, 0x72, 0x79, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x67, 0x6f, 0x6f,
+ 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x44, 0x75, 0x72,
+ 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x09, 0x70, 0x69, 0x6e, 0x67, 0x45, 0x76, 0x65, 0x72, 0x79,
+ 0x12, 0x3c, 0x0a, 0x0c, 0x73, 0x75, 0x62, 0x6d, 0x69, 0x74, 0x5f, 0x65, 0x76, 0x65, 0x72, 0x79,
+ 0x18, 0x05, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e,
+ 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f,
+ 0x6e, 0x52, 0x0b, 0x73, 0x75, 0x62, 0x6d, 0x69, 0x74, 0x45, 0x76, 0x65, 0x72, 0x79, 0x12, 0x18,
+ 0x0a, 0x07, 0x65, 0x6e, 0x76, 0x69, 0x72, 0x6f, 0x6e, 0x18, 0x06, 0x20, 0x03, 0x28, 0x09, 0x52,
+ 0x07, 0x65, 0x6e, 0x76, 0x69, 0x72, 0x6f, 0x6e, 0x22, 0x95, 0x02, 0x0a, 0x0b, 0x53, 0x65, 0x72,
+ 0x76, 0x65, 0x72, 0x53, 0x74, 0x61, 0x74, 0x65, 0x12, 0x50, 0x0a, 0x0f, 0x63, 0x6c, 0x69, 0x65,
+ 0x6e, 0x74, 0x5f, 0x74, 0x65, 0x61, 0x6d, 0x5f, 0x6d, 0x61, 0x70, 0x18, 0x01, 0x20, 0x03, 0x28,
+ 0x0b, 0x32, 0x28, 0x2e, 0x65, 0x78, 0x70, 0x6c, 0x6f, 0x69, 0x74, 0x73, 0x2e, 0x53, 0x65, 0x72,
+ 0x76, 0x65, 0x72, 0x53, 0x74, 0x61, 0x74, 0x65, 0x2e, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x54,
+ 0x65, 0x61, 0x6d, 0x4d, 0x61, 0x70, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x52, 0x0d, 0x63, 0x6c, 0x69,
+ 0x65, 0x6e, 0x74, 0x54, 0x65, 0x61, 0x6d, 0x4d, 0x61, 0x70, 0x12, 0x32, 0x0a, 0x08, 0x65, 0x78,
+ 0x70, 0x6c, 0x6f, 0x69, 0x74, 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x16, 0x2e, 0x65,
+ 0x78, 0x70, 0x6c, 0x6f, 0x69, 0x74, 0x73, 0x2e, 0x45, 0x78, 0x70, 0x6c, 0x6f, 0x69, 0x74, 0x53,
+ 0x74, 0x61, 0x74, 0x65, 0x52, 0x08, 0x65, 0x78, 0x70, 0x6c, 0x6f, 0x69, 0x74, 0x73, 0x12, 0x28,
+ 0x0a, 0x06, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x10,
+ 0x2e, 0x65, 0x78, 0x70, 0x6c, 0x6f, 0x69, 0x74, 0x73, 0x2e, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67,
+ 0x52, 0x06, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x1a, 0x56, 0x0a, 0x12, 0x43, 0x6c, 0x69, 0x65,
+ 0x6e, 0x74, 0x54, 0x65, 0x61, 0x6d, 0x4d, 0x61, 0x70, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x12, 0x10,
+ 0x0a, 0x03, 0x6b, 0x65, 0x79, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x6b, 0x65, 0x79,
+ 0x12, 0x2a, 0x0a, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32,
+ 0x14, 0x2e, 0x65, 0x78, 0x70, 0x6c, 0x6f, 0x69, 0x74, 0x73, 0x2e, 0x54, 0x65, 0x61, 0x6d, 0x42,
+ 0x75, 0x63, 0x6b, 0x65, 0x74, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x3a, 0x02, 0x38, 0x01,
+ 0x22, 0xd9, 0x02, 0x0a, 0x0b, 0x50, 0x69, 0x6e, 0x67, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74,
+ 0x12, 0x1b, 0x0a, 0x09, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20,
+ 0x01, 0x28, 0x09, 0x52, 0x08, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x49, 0x64, 0x12, 0x52, 0x0a,
+ 0x13, 0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x5f, 0x69, 0x6e, 0x66, 0x6f, 0x5f, 0x72, 0x65, 0x71,
+ 0x75, 0x65, 0x73, 0x74, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x20, 0x2e, 0x65, 0x78, 0x70,
+ 0x6c, 0x6f, 0x69, 0x74, 0x73, 0x2e, 0x50, 0x69, 0x6e, 0x67, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73,
+ 0x74, 0x2e, 0x53, 0x65, 0x72, 0x76, 0x65, 0x72, 0x49, 0x6e, 0x66, 0x6f, 0x48, 0x00, 0x52, 0x11,
+ 0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x49, 0x6e, 0x66, 0x6f, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73,
+ 0x74, 0x12, 0x4e, 0x0a, 0x11, 0x68, 0x65, 0x61, 0x72, 0x74, 0x62, 0x65, 0x61, 0x74, 0x5f, 0x72,
+ 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1f, 0x2e, 0x65,
+ 0x78, 0x70, 0x6c, 0x6f, 0x69, 0x74, 0x73, 0x2e, 0x50, 0x69, 0x6e, 0x67, 0x52, 0x65, 0x71, 0x75,
+ 0x65, 0x73, 0x74, 0x2e, 0x48, 0x65, 0x61, 0x72, 0x74, 0x62, 0x65, 0x61, 0x74, 0x48, 0x00, 0x52,
+ 0x10, 0x68, 0x65, 0x61, 0x72, 0x74, 0x62, 0x65, 0x61, 0x74, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73,
+ 0x74, 0x12, 0x42, 0x0a, 0x0d, 0x6c, 0x65, 0x61, 0x76, 0x65, 0x5f, 0x72, 0x65, 0x71, 0x75, 0x65,
+ 0x73, 0x74, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1b, 0x2e, 0x65, 0x78, 0x70, 0x6c, 0x6f,
+ 0x69, 0x74, 0x73, 0x2e, 0x50, 0x69, 0x6e, 0x67, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x2e,
+ 0x4c, 0x65, 0x61, 0x76, 0x65, 0x48, 0x00, 0x52, 0x0c, 0x6c, 0x65, 0x61, 0x76, 0x65, 0x52, 0x65,
+ 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x0c, 0x0a, 0x0a, 0x53, 0x65, 0x72, 0x76, 0x65, 0x72, 0x49,
+ 0x6e, 0x66, 0x6f, 0x1a, 0x23, 0x0a, 0x09, 0x48, 0x65, 0x61, 0x72, 0x74, 0x62, 0x65, 0x61, 0x74,
+ 0x12, 0x16, 0x0a, 0x06, 0x77, 0x65, 0x69, 0x67, 0x68, 0x74, 0x18, 0x01, 0x20, 0x01, 0x28, 0x05,
+ 0x52, 0x06, 0x77, 0x65, 0x69, 0x67, 0x68, 0x74, 0x1a, 0x07, 0x0a, 0x05, 0x4c, 0x65, 0x61, 0x76,
+ 0x65, 0x42, 0x09, 0x0a, 0x07, 0x70, 0x61, 0x79, 0x6c, 0x6f, 0x61, 0x64, 0x22, 0x3b, 0x0a, 0x0c,
+ 0x50, 0x69, 0x6e, 0x67, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x2b, 0x0a, 0x05,
+ 0x73, 0x74, 0x61, 0x74, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x15, 0x2e, 0x65, 0x78,
+ 0x70, 0x6c, 0x6f, 0x69, 0x74, 0x73, 0x2e, 0x53, 0x65, 0x72, 0x76, 0x65, 0x72, 0x53, 0x74, 0x61,
+ 0x74, 0x65, 0x52, 0x05, 0x73, 0x74, 0x61, 0x74, 0x65, 0x22, 0x2f, 0x0a, 0x0e, 0x45, 0x78, 0x70,
+ 0x6c, 0x6f, 0x69, 0x74, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x1d, 0x0a, 0x0a, 0x65,
+ 0x78, 0x70, 0x6c, 0x6f, 0x69, 0x74, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52,
+ 0x09, 0x65, 0x78, 0x70, 0x6c, 0x6f, 0x69, 0x74, 0x49, 0x64, 0x22, 0x3f, 0x0a, 0x0f, 0x45, 0x78,
+ 0x70, 0x6c, 0x6f, 0x69, 0x74, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x2c, 0x0a,
+ 0x05, 0x73, 0x74, 0x61, 0x74, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x16, 0x2e, 0x65,
+ 0x78, 0x70, 0x6c, 0x6f, 0x69, 0x74, 0x73, 0x2e, 0x45, 0x78, 0x70, 0x6c, 0x6f, 0x69, 0x74, 0x53,
+ 0x74, 0x61, 0x74, 0x65, 0x52, 0x05, 0x73, 0x74, 0x61, 0x74, 0x65, 0x22, 0x44, 0x0a, 0x14, 0x55,
+ 0x70, 0x64, 0x61, 0x74, 0x65, 0x45, 0x78, 0x70, 0x6c, 0x6f, 0x69, 0x74, 0x52, 0x65, 0x71, 0x75,
+ 0x65, 0x73, 0x74, 0x12, 0x2c, 0x0a, 0x05, 0x73, 0x74, 0x61, 0x74, 0x65, 0x18, 0x01, 0x20, 0x01,
+ 0x28, 0x0b, 0x32, 0x16, 0x2e, 0x65, 0x78, 0x70, 0x6c, 0x6f, 0x69, 0x74, 0x73, 0x2e, 0x45, 0x78,
+ 0x70, 0x6c, 0x6f, 0x69, 0x74, 0x53, 0x74, 0x61, 0x74, 0x65, 0x52, 0x05, 0x73, 0x74, 0x61, 0x74,
+ 0x65, 0x22, 0x45, 0x0a, 0x15, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x45, 0x78, 0x70, 0x6c, 0x6f,
+ 0x69, 0x74, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x2c, 0x0a, 0x05, 0x73, 0x74,
+ 0x61, 0x74, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x16, 0x2e, 0x65, 0x78, 0x70, 0x6c,
+ 0x6f, 0x69, 0x74, 0x73, 0x2e, 0x45, 0x78, 0x70, 0x6c, 0x6f, 0x69, 0x74, 0x53, 0x74, 0x61, 0x74,
+ 0x65, 0x52, 0x05, 0x73, 0x74, 0x61, 0x74, 0x65, 0x22, 0x2c, 0x0a, 0x10, 0x42, 0x72, 0x6f, 0x61,
+ 0x64, 0x63, 0x61, 0x73, 0x74, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x18, 0x0a, 0x07,
+ 0x63, 0x6f, 0x6d, 0x6d, 0x61, 0x6e, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x63,
+ 0x6f, 0x6d, 0x6d, 0x61, 0x6e, 0x64, 0x22, 0x13, 0x0a, 0x11, 0x42, 0x72, 0x6f, 0x61, 0x64, 0x63,
+ 0x61, 0x73, 0x74, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x1b, 0x0a, 0x19, 0x42,
+ 0x72, 0x6f, 0x61, 0x64, 0x63, 0x61, 0x73, 0x74, 0x53, 0x75, 0x62, 0x73, 0x63, 0x72, 0x69, 0x62,
+ 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x22, 0x36, 0x0a, 0x1a, 0x42, 0x72, 0x6f, 0x61,
+ 0x64, 0x63, 0x61, 0x73, 0x74, 0x53, 0x75, 0x62, 0x73, 0x63, 0x72, 0x69, 0x62, 0x65, 0x52, 0x65,
+ 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x18, 0x0a, 0x07, 0x63, 0x6f, 0x6d, 0x6d, 0x61, 0x6e,
+ 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x63, 0x6f, 0x6d, 0x6d, 0x61, 0x6e, 0x64,
+ 0x22, 0x31, 0x0a, 0x10, 0x53, 0x69, 0x6e, 0x67, 0x6c, 0x65, 0x52, 0x75, 0x6e, 0x52, 0x65, 0x71,
+ 0x75, 0x65, 0x73, 0x74, 0x12, 0x1d, 0x0a, 0x0a, 0x65, 0x78, 0x70, 0x6c, 0x6f, 0x69, 0x74, 0x5f,
+ 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, 0x65, 0x78, 0x70, 0x6c, 0x6f, 0x69,
+ 0x74, 0x49, 0x64, 0x22, 0x13, 0x0a, 0x11, 0x53, 0x69, 0x6e, 0x67, 0x6c, 0x65, 0x52, 0x75, 0x6e,
+ 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x1b, 0x0a, 0x19, 0x53, 0x69, 0x6e, 0x67,
+ 0x6c, 0x65, 0x52, 0x75, 0x6e, 0x53, 0x75, 0x62, 0x73, 0x63, 0x72, 0x69, 0x62, 0x65, 0x52, 0x65,
+ 0x71, 0x75, 0x65, 0x73, 0x74, 0x22, 0x3b, 0x0a, 0x1a, 0x53, 0x69, 0x6e, 0x67, 0x6c, 0x65, 0x52,
+ 0x75, 0x6e, 0x53, 0x75, 0x62, 0x73, 0x63, 0x72, 0x69, 0x62, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f,
+ 0x6e, 0x73, 0x65, 0x12, 0x1d, 0x0a, 0x0a, 0x65, 0x78, 0x70, 0x6c, 0x6f, 0x69, 0x74, 0x5f, 0x69,
+ 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, 0x65, 0x78, 0x70, 0x6c, 0x6f, 0x69, 0x74,
+ 0x49, 0x64, 0x32, 0xb9, 0x04, 0x0a, 0x07, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x12, 0x37,
+ 0x0a, 0x04, 0x50, 0x69, 0x6e, 0x67, 0x12, 0x15, 0x2e, 0x65, 0x78, 0x70, 0x6c, 0x6f, 0x69, 0x74,
+ 0x73, 0x2e, 0x50, 0x69, 0x6e, 0x67, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x16, 0x2e,
+ 0x65, 0x78, 0x70, 0x6c, 0x6f, 0x69, 0x74, 0x73, 0x2e, 0x50, 0x69, 0x6e, 0x67, 0x52, 0x65, 0x73,
+ 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x00, 0x12, 0x40, 0x0a, 0x07, 0x45, 0x78, 0x70, 0x6c, 0x6f,
+ 0x69, 0x74, 0x12, 0x18, 0x2e, 0x65, 0x78, 0x70, 0x6c, 0x6f, 0x69, 0x74, 0x73, 0x2e, 0x45, 0x78,
+ 0x70, 0x6c, 0x6f, 0x69, 0x74, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x19, 0x2e, 0x65,
+ 0x78, 0x70, 0x6c, 0x6f, 0x69, 0x74, 0x73, 0x2e, 0x45, 0x78, 0x70, 0x6c, 0x6f, 0x69, 0x74, 0x52,
+ 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x00, 0x12, 0x52, 0x0a, 0x0d, 0x55, 0x70, 0x64,
+ 0x61, 0x74, 0x65, 0x45, 0x78, 0x70, 0x6c, 0x6f, 0x69, 0x74, 0x12, 0x1e, 0x2e, 0x65, 0x78, 0x70,
+ 0x6c, 0x6f, 0x69, 0x74, 0x73, 0x2e, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x45, 0x78, 0x70, 0x6c,
+ 0x6f, 0x69, 0x74, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x1f, 0x2e, 0x65, 0x78, 0x70,
+ 0x6c, 0x6f, 0x69, 0x74, 0x73, 0x2e, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x45, 0x78, 0x70, 0x6c,
+ 0x6f, 0x69, 0x74, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x00, 0x12, 0x4d, 0x0a,
+ 0x10, 0x42, 0x72, 0x6f, 0x61, 0x64, 0x63, 0x61, 0x73, 0x74, 0x43, 0x6f, 0x6d, 0x6d, 0x61, 0x6e,
+ 0x64, 0x12, 0x1a, 0x2e, 0x65, 0x78, 0x70, 0x6c, 0x6f, 0x69, 0x74, 0x73, 0x2e, 0x42, 0x72, 0x6f,
+ 0x61, 0x64, 0x63, 0x61, 0x73, 0x74, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x1b, 0x2e,
+ 0x65, 0x78, 0x70, 0x6c, 0x6f, 0x69, 0x74, 0x73, 0x2e, 0x42, 0x72, 0x6f, 0x61, 0x64, 0x63, 0x61,
+ 0x73, 0x74, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x00, 0x12, 0x63, 0x0a, 0x12,
+ 0x42, 0x72, 0x6f, 0x61, 0x64, 0x63, 0x61, 0x73, 0x74, 0x53, 0x75, 0x62, 0x73, 0x63, 0x72, 0x69,
+ 0x62, 0x65, 0x12, 0x23, 0x2e, 0x65, 0x78, 0x70, 0x6c, 0x6f, 0x69, 0x74, 0x73, 0x2e, 0x42, 0x72,
+ 0x6f, 0x61, 0x64, 0x63, 0x61, 0x73, 0x74, 0x53, 0x75, 0x62, 0x73, 0x63, 0x72, 0x69, 0x62, 0x65,
+ 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x24, 0x2e, 0x65, 0x78, 0x70, 0x6c, 0x6f, 0x69,
+ 0x74, 0x73, 0x2e, 0x42, 0x72, 0x6f, 0x61, 0x64, 0x63, 0x61, 0x73, 0x74, 0x53, 0x75, 0x62, 0x73,
+ 0x63, 0x72, 0x69, 0x62, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x00, 0x30,
+ 0x01, 0x12, 0x46, 0x0a, 0x09, 0x53, 0x69, 0x6e, 0x67, 0x6c, 0x65, 0x52, 0x75, 0x6e, 0x12, 0x1a,
+ 0x2e, 0x65, 0x78, 0x70, 0x6c, 0x6f, 0x69, 0x74, 0x73, 0x2e, 0x53, 0x69, 0x6e, 0x67, 0x6c, 0x65,
+ 0x52, 0x75, 0x6e, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x1b, 0x2e, 0x65, 0x78, 0x70,
+ 0x6c, 0x6f, 0x69, 0x74, 0x73, 0x2e, 0x53, 0x69, 0x6e, 0x67, 0x6c, 0x65, 0x52, 0x75, 0x6e, 0x52,
+ 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x00, 0x12, 0x63, 0x0a, 0x12, 0x53, 0x69, 0x6e,
+ 0x67, 0x6c, 0x65, 0x52, 0x75, 0x6e, 0x53, 0x75, 0x62, 0x73, 0x63, 0x72, 0x69, 0x62, 0x65, 0x12,
+ 0x23, 0x2e, 0x65, 0x78, 0x70, 0x6c, 0x6f, 0x69, 0x74, 0x73, 0x2e, 0x53, 0x69, 0x6e, 0x67, 0x6c,
+ 0x65, 0x52, 0x75, 0x6e, 0x53, 0x75, 0x62, 0x73, 0x63, 0x72, 0x69, 0x62, 0x65, 0x52, 0x65, 0x71,
+ 0x75, 0x65, 0x73, 0x74, 0x1a, 0x24, 0x2e, 0x65, 0x78, 0x70, 0x6c, 0x6f, 0x69, 0x74, 0x73, 0x2e,
+ 0x53, 0x69, 0x6e, 0x67, 0x6c, 0x65, 0x52, 0x75, 0x6e, 0x53, 0x75, 0x62, 0x73, 0x63, 0x72, 0x69,
+ 0x62, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x00, 0x30, 0x01, 0x42, 0x89,
+ 0x01, 0x0a, 0x0c, 0x63, 0x6f, 0x6d, 0x2e, 0x65, 0x78, 0x70, 0x6c, 0x6f, 0x69, 0x74, 0x73, 0x42,
+ 0x08, 0x41, 0x70, 0x69, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x2f, 0x67, 0x69, 0x74,
+ 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x63, 0x34, 0x74, 0x2d, 0x62, 0x75, 0x74, 0x2d,
+ 0x73, 0x34, 0x64, 0x2f, 0x6e, 0x65, 0x6f, 0x2f, 0x76, 0x32, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f,
+ 0x2f, 0x67, 0x6f, 0x2f, 0x65, 0x78, 0x70, 0x6c, 0x6f, 0x69, 0x74, 0x73, 0xa2, 0x02, 0x03, 0x45,
+ 0x58, 0x58, 0xaa, 0x02, 0x08, 0x45, 0x78, 0x70, 0x6c, 0x6f, 0x69, 0x74, 0x73, 0xca, 0x02, 0x08,
+ 0x45, 0x78, 0x70, 0x6c, 0x6f, 0x69, 0x74, 0x73, 0xe2, 0x02, 0x14, 0x45, 0x78, 0x70, 0x6c, 0x6f,
+ 0x69, 0x74, 0x73, 0x5c, 0x47, 0x50, 0x42, 0x4d, 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0xea,
+ 0x02, 0x08, 0x45, 0x78, 0x70, 0x6c, 0x6f, 0x69, 0x74, 0x73, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74,
+ 0x6f, 0x33,
+}
+
+var (
+ file_exploits_api_proto_rawDescOnce sync.Once
+ file_exploits_api_proto_rawDescData = file_exploits_api_proto_rawDesc
+)
+
+func file_exploits_api_proto_rawDescGZIP() []byte {
+ file_exploits_api_proto_rawDescOnce.Do(func() {
+ file_exploits_api_proto_rawDescData = protoimpl.X.CompressGZIP(file_exploits_api_proto_rawDescData)
+ })
+ return file_exploits_api_proto_rawDescData
+}
+
+var file_exploits_api_proto_msgTypes = make([]protoimpl.MessageInfo, 24)
+var file_exploits_api_proto_goTypes = []interface{}{
+ (*TeamBucket)(nil), // 0: exploits.TeamBucket
+ (*ExploitConfiguration)(nil), // 1: exploits.ExploitConfiguration
+ (*ExploitState)(nil), // 2: exploits.ExploitState
+ (*Config)(nil), // 3: exploits.Config
+ (*ServerState)(nil), // 4: exploits.ServerState
+ (*PingRequest)(nil), // 5: exploits.PingRequest
+ (*PingResponse)(nil), // 6: exploits.PingResponse
+ (*ExploitRequest)(nil), // 7: exploits.ExploitRequest
+ (*ExploitResponse)(nil), // 8: exploits.ExploitResponse
+ (*UpdateExploitRequest)(nil), // 9: exploits.UpdateExploitRequest
+ (*UpdateExploitResponse)(nil), // 10: exploits.UpdateExploitResponse
+ (*BroadcastRequest)(nil), // 11: exploits.BroadcastRequest
+ (*BroadcastResponse)(nil), // 12: exploits.BroadcastResponse
+ (*BroadcastSubscribeRequest)(nil), // 13: exploits.BroadcastSubscribeRequest
+ (*BroadcastSubscribeResponse)(nil), // 14: exploits.BroadcastSubscribeResponse
+ (*SingleRunRequest)(nil), // 15: exploits.SingleRunRequest
+ (*SingleRunResponse)(nil), // 16: exploits.SingleRunResponse
+ (*SingleRunSubscribeRequest)(nil), // 17: exploits.SingleRunSubscribeRequest
+ (*SingleRunSubscribeResponse)(nil), // 18: exploits.SingleRunSubscribeResponse
+ nil, // 19: exploits.TeamBucket.TeamsEntry
+ nil, // 20: exploits.ServerState.ClientTeamMapEntry
+ (*PingRequest_ServerInfo)(nil), // 21: exploits.PingRequest.ServerInfo
+ (*PingRequest_Heartbeat)(nil), // 22: exploits.PingRequest.Heartbeat
+ (*PingRequest_Leave)(nil), // 23: exploits.PingRequest.Leave
+ (*durationpb.Duration)(nil), // 24: google.protobuf.Duration
+ (*fileserver.FileInfo)(nil), // 25: fileserver.FileInfo
+}
+var file_exploits_api_proto_depIdxs = []int32{
+ 19, // 0: exploits.TeamBucket.teams:type_name -> exploits.TeamBucket.TeamsEntry
+ 24, // 1: exploits.ExploitConfiguration.run_every:type_name -> google.protobuf.Duration
+ 24, // 2: exploits.ExploitConfiguration.timeout:type_name -> google.protobuf.Duration
+ 25, // 3: exploits.ExploitState.file:type_name -> fileserver.FileInfo
+ 1, // 4: exploits.ExploitState.config:type_name -> exploits.ExploitConfiguration
+ 24, // 5: exploits.Config.ping_every:type_name -> google.protobuf.Duration
+ 24, // 6: exploits.Config.submit_every:type_name -> google.protobuf.Duration
+ 20, // 7: exploits.ServerState.client_team_map:type_name -> exploits.ServerState.ClientTeamMapEntry
+ 2, // 8: exploits.ServerState.exploits:type_name -> exploits.ExploitState
+ 3, // 9: exploits.ServerState.config:type_name -> exploits.Config
+ 21, // 10: exploits.PingRequest.server_info_request:type_name -> exploits.PingRequest.ServerInfo
+ 22, // 11: exploits.PingRequest.heartbeat_request:type_name -> exploits.PingRequest.Heartbeat
+ 23, // 12: exploits.PingRequest.leave_request:type_name -> exploits.PingRequest.Leave
+ 4, // 13: exploits.PingResponse.state:type_name -> exploits.ServerState
+ 2, // 14: exploits.ExploitResponse.state:type_name -> exploits.ExploitState
+ 2, // 15: exploits.UpdateExploitRequest.state:type_name -> exploits.ExploitState
+ 2, // 16: exploits.UpdateExploitResponse.state:type_name -> exploits.ExploitState
+ 0, // 17: exploits.ServerState.ClientTeamMapEntry.value:type_name -> exploits.TeamBucket
+ 5, // 18: exploits.Service.Ping:input_type -> exploits.PingRequest
+ 7, // 19: exploits.Service.Exploit:input_type -> exploits.ExploitRequest
+ 9, // 20: exploits.Service.UpdateExploit:input_type -> exploits.UpdateExploitRequest
+ 11, // 21: exploits.Service.BroadcastCommand:input_type -> exploits.BroadcastRequest
+ 13, // 22: exploits.Service.BroadcastSubscribe:input_type -> exploits.BroadcastSubscribeRequest
+ 15, // 23: exploits.Service.SingleRun:input_type -> exploits.SingleRunRequest
+ 17, // 24: exploits.Service.SingleRunSubscribe:input_type -> exploits.SingleRunSubscribeRequest
+ 6, // 25: exploits.Service.Ping:output_type -> exploits.PingResponse
+ 8, // 26: exploits.Service.Exploit:output_type -> exploits.ExploitResponse
+ 10, // 27: exploits.Service.UpdateExploit:output_type -> exploits.UpdateExploitResponse
+ 12, // 28: exploits.Service.BroadcastCommand:output_type -> exploits.BroadcastResponse
+ 14, // 29: exploits.Service.BroadcastSubscribe:output_type -> exploits.BroadcastSubscribeResponse
+ 16, // 30: exploits.Service.SingleRun:output_type -> exploits.SingleRunResponse
+ 18, // 31: exploits.Service.SingleRunSubscribe:output_type -> exploits.SingleRunSubscribeResponse
+ 25, // [25:32] is the sub-list for method output_type
+ 18, // [18:25] is the sub-list for method input_type
+ 18, // [18:18] is the sub-list for extension type_name
+ 18, // [18:18] is the sub-list for extension extendee
+ 0, // [0:18] is the sub-list for field type_name
+}
+
+func init() { file_exploits_api_proto_init() }
+func file_exploits_api_proto_init() {
+ if File_exploits_api_proto != nil {
+ return
+ }
+ if !protoimpl.UnsafeEnabled {
+ file_exploits_api_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
+ switch v := v.(*TeamBucket); i {
+ case 0:
+ return &v.state
+ case 1:
+ return &v.sizeCache
+ case 2:
+ return &v.unknownFields
+ default:
+ return nil
+ }
+ }
+ file_exploits_api_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} {
+ switch v := v.(*ExploitConfiguration); i {
+ case 0:
+ return &v.state
+ case 1:
+ return &v.sizeCache
+ case 2:
+ return &v.unknownFields
+ default:
+ return nil
+ }
+ }
+ file_exploits_api_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} {
+ switch v := v.(*ExploitState); i {
+ case 0:
+ return &v.state
+ case 1:
+ return &v.sizeCache
+ case 2:
+ return &v.unknownFields
+ default:
+ return nil
+ }
+ }
+ file_exploits_api_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} {
+ switch v := v.(*Config); i {
+ case 0:
+ return &v.state
+ case 1:
+ return &v.sizeCache
+ case 2:
+ return &v.unknownFields
+ default:
+ return nil
+ }
+ }
+ file_exploits_api_proto_msgTypes[4].Exporter = func(v interface{}, i int) interface{} {
+ switch v := v.(*ServerState); i {
+ case 0:
+ return &v.state
+ case 1:
+ return &v.sizeCache
+ case 2:
+ return &v.unknownFields
+ default:
+ return nil
+ }
+ }
+ file_exploits_api_proto_msgTypes[5].Exporter = func(v interface{}, i int) interface{} {
+ switch v := v.(*PingRequest); i {
+ case 0:
+ return &v.state
+ case 1:
+ return &v.sizeCache
+ case 2:
+ return &v.unknownFields
+ default:
+ return nil
+ }
+ }
+ file_exploits_api_proto_msgTypes[6].Exporter = func(v interface{}, i int) interface{} {
+ switch v := v.(*PingResponse); i {
+ case 0:
+ return &v.state
+ case 1:
+ return &v.sizeCache
+ case 2:
+ return &v.unknownFields
+ default:
+ return nil
+ }
+ }
+ file_exploits_api_proto_msgTypes[7].Exporter = func(v interface{}, i int) interface{} {
+ switch v := v.(*ExploitRequest); i {
+ case 0:
+ return &v.state
+ case 1:
+ return &v.sizeCache
+ case 2:
+ return &v.unknownFields
+ default:
+ return nil
+ }
+ }
+ file_exploits_api_proto_msgTypes[8].Exporter = func(v interface{}, i int) interface{} {
+ switch v := v.(*ExploitResponse); i {
+ case 0:
+ return &v.state
+ case 1:
+ return &v.sizeCache
+ case 2:
+ return &v.unknownFields
+ default:
+ return nil
+ }
+ }
+ file_exploits_api_proto_msgTypes[9].Exporter = func(v interface{}, i int) interface{} {
+ switch v := v.(*UpdateExploitRequest); i {
+ case 0:
+ return &v.state
+ case 1:
+ return &v.sizeCache
+ case 2:
+ return &v.unknownFields
+ default:
+ return nil
+ }
+ }
+ file_exploits_api_proto_msgTypes[10].Exporter = func(v interface{}, i int) interface{} {
+ switch v := v.(*UpdateExploitResponse); i {
+ case 0:
+ return &v.state
+ case 1:
+ return &v.sizeCache
+ case 2:
+ return &v.unknownFields
+ default:
+ return nil
+ }
+ }
+ file_exploits_api_proto_msgTypes[11].Exporter = func(v interface{}, i int) interface{} {
+ switch v := v.(*BroadcastRequest); i {
+ case 0:
+ return &v.state
+ case 1:
+ return &v.sizeCache
+ case 2:
+ return &v.unknownFields
+ default:
+ return nil
+ }
+ }
+ file_exploits_api_proto_msgTypes[12].Exporter = func(v interface{}, i int) interface{} {
+ switch v := v.(*BroadcastResponse); i {
+ case 0:
+ return &v.state
+ case 1:
+ return &v.sizeCache
+ case 2:
+ return &v.unknownFields
+ default:
+ return nil
+ }
+ }
+ file_exploits_api_proto_msgTypes[13].Exporter = func(v interface{}, i int) interface{} {
+ switch v := v.(*BroadcastSubscribeRequest); i {
+ case 0:
+ return &v.state
+ case 1:
+ return &v.sizeCache
+ case 2:
+ return &v.unknownFields
+ default:
+ return nil
+ }
+ }
+ file_exploits_api_proto_msgTypes[14].Exporter = func(v interface{}, i int) interface{} {
+ switch v := v.(*BroadcastSubscribeResponse); i {
+ case 0:
+ return &v.state
+ case 1:
+ return &v.sizeCache
+ case 2:
+ return &v.unknownFields
+ default:
+ return nil
+ }
+ }
+ file_exploits_api_proto_msgTypes[15].Exporter = func(v interface{}, i int) interface{} {
+ switch v := v.(*SingleRunRequest); i {
+ case 0:
+ return &v.state
+ case 1:
+ return &v.sizeCache
+ case 2:
+ return &v.unknownFields
+ default:
+ return nil
+ }
+ }
+ file_exploits_api_proto_msgTypes[16].Exporter = func(v interface{}, i int) interface{} {
+ switch v := v.(*SingleRunResponse); i {
+ case 0:
+ return &v.state
+ case 1:
+ return &v.sizeCache
+ case 2:
+ return &v.unknownFields
+ default:
+ return nil
+ }
+ }
+ file_exploits_api_proto_msgTypes[17].Exporter = func(v interface{}, i int) interface{} {
+ switch v := v.(*SingleRunSubscribeRequest); i {
+ case 0:
+ return &v.state
+ case 1:
+ return &v.sizeCache
+ case 2:
+ return &v.unknownFields
+ default:
+ return nil
+ }
+ }
+ file_exploits_api_proto_msgTypes[18].Exporter = func(v interface{}, i int) interface{} {
+ switch v := v.(*SingleRunSubscribeResponse); i {
+ case 0:
+ return &v.state
+ case 1:
+ return &v.sizeCache
+ case 2:
+ return &v.unknownFields
+ default:
+ return nil
+ }
+ }
+ file_exploits_api_proto_msgTypes[21].Exporter = func(v interface{}, i int) interface{} {
+ switch v := v.(*PingRequest_ServerInfo); i {
+ case 0:
+ return &v.state
+ case 1:
+ return &v.sizeCache
+ case 2:
+ return &v.unknownFields
+ default:
+ return nil
+ }
+ }
+ file_exploits_api_proto_msgTypes[22].Exporter = func(v interface{}, i int) interface{} {
+ switch v := v.(*PingRequest_Heartbeat); i {
+ case 0:
+ return &v.state
+ case 1:
+ return &v.sizeCache
+ case 2:
+ return &v.unknownFields
+ default:
+ return nil
+ }
+ }
+ file_exploits_api_proto_msgTypes[23].Exporter = func(v interface{}, i int) interface{} {
+ switch v := v.(*PingRequest_Leave); i {
+ case 0:
+ return &v.state
+ case 1:
+ return &v.sizeCache
+ case 2:
+ return &v.unknownFields
+ default:
+ return nil
+ }
+ }
+ }
+ file_exploits_api_proto_msgTypes[5].OneofWrappers = []interface{}{
+ (*PingRequest_ServerInfoRequest)(nil),
+ (*PingRequest_HeartbeatRequest)(nil),
+ (*PingRequest_LeaveRequest)(nil),
+ }
+ type x struct{}
+ out := protoimpl.TypeBuilder{
+ File: protoimpl.DescBuilder{
+ GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
+ RawDescriptor: file_exploits_api_proto_rawDesc,
+ NumEnums: 0,
+ NumMessages: 24,
+ NumExtensions: 0,
+ NumServices: 1,
+ },
+ GoTypes: file_exploits_api_proto_goTypes,
+ DependencyIndexes: file_exploits_api_proto_depIdxs,
+ MessageInfos: file_exploits_api_proto_msgTypes,
+ }.Build()
+ File_exploits_api_proto = out.File
+ file_exploits_api_proto_rawDesc = nil
+ file_exploits_api_proto_goTypes = nil
+ file_exploits_api_proto_depIdxs = nil
+}
diff --git a/components/neo/proto/go/exploits/api_grpc.pb.go b/components/neo/proto/go/exploits/api_grpc.pb.go
new file mode 100644
index 0000000..ffd27fe
--- /dev/null
+++ b/components/neo/proto/go/exploits/api_grpc.pb.go
@@ -0,0 +1,376 @@
+// Code generated by protoc-gen-go-grpc. DO NOT EDIT.
+// versions:
+// - protoc-gen-go-grpc v1.2.0
+// - protoc (unknown)
+// source: exploits/api.proto
+
+package exploits
+
+import (
+ context "context"
+ grpc "google.golang.org/grpc"
+ codes "google.golang.org/grpc/codes"
+ status "google.golang.org/grpc/status"
+)
+
+// This is a compile-time assertion to ensure that this generated file
+// is compatible with the grpc package it is being compiled against.
+// Requires gRPC-Go v1.32.0 or later.
+const _ = grpc.SupportPackageIsVersion7
+
+// ServiceClient is the client API for Service service.
+//
+// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream.
+type ServiceClient interface {
+ Ping(ctx context.Context, in *PingRequest, opts ...grpc.CallOption) (*PingResponse, error)
+ Exploit(ctx context.Context, in *ExploitRequest, opts ...grpc.CallOption) (*ExploitResponse, error)
+ UpdateExploit(ctx context.Context, in *UpdateExploitRequest, opts ...grpc.CallOption) (*UpdateExploitResponse, error)
+ BroadcastCommand(ctx context.Context, in *BroadcastRequest, opts ...grpc.CallOption) (*BroadcastResponse, error)
+ BroadcastSubscribe(ctx context.Context, in *BroadcastSubscribeRequest, opts ...grpc.CallOption) (Service_BroadcastSubscribeClient, error)
+ SingleRun(ctx context.Context, in *SingleRunRequest, opts ...grpc.CallOption) (*SingleRunResponse, error)
+ SingleRunSubscribe(ctx context.Context, in *SingleRunSubscribeRequest, opts ...grpc.CallOption) (Service_SingleRunSubscribeClient, error)
+}
+
+type serviceClient struct {
+ cc grpc.ClientConnInterface
+}
+
+func NewServiceClient(cc grpc.ClientConnInterface) ServiceClient {
+ return &serviceClient{cc}
+}
+
+func (c *serviceClient) Ping(ctx context.Context, in *PingRequest, opts ...grpc.CallOption) (*PingResponse, error) {
+ out := new(PingResponse)
+ err := c.cc.Invoke(ctx, "/exploits.Service/Ping", in, out, opts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+func (c *serviceClient) Exploit(ctx context.Context, in *ExploitRequest, opts ...grpc.CallOption) (*ExploitResponse, error) {
+ out := new(ExploitResponse)
+ err := c.cc.Invoke(ctx, "/exploits.Service/Exploit", in, out, opts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+func (c *serviceClient) UpdateExploit(ctx context.Context, in *UpdateExploitRequest, opts ...grpc.CallOption) (*UpdateExploitResponse, error) {
+ out := new(UpdateExploitResponse)
+ err := c.cc.Invoke(ctx, "/exploits.Service/UpdateExploit", in, out, opts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+func (c *serviceClient) BroadcastCommand(ctx context.Context, in *BroadcastRequest, opts ...grpc.CallOption) (*BroadcastResponse, error) {
+ out := new(BroadcastResponse)
+ err := c.cc.Invoke(ctx, "/exploits.Service/BroadcastCommand", in, out, opts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+func (c *serviceClient) BroadcastSubscribe(ctx context.Context, in *BroadcastSubscribeRequest, opts ...grpc.CallOption) (Service_BroadcastSubscribeClient, error) {
+ stream, err := c.cc.NewStream(ctx, &Service_ServiceDesc.Streams[0], "/exploits.Service/BroadcastSubscribe", opts...)
+ if err != nil {
+ return nil, err
+ }
+ x := &serviceBroadcastSubscribeClient{stream}
+ if err := x.ClientStream.SendMsg(in); err != nil {
+ return nil, err
+ }
+ if err := x.ClientStream.CloseSend(); err != nil {
+ return nil, err
+ }
+ return x, nil
+}
+
+type Service_BroadcastSubscribeClient interface {
+ Recv() (*BroadcastSubscribeResponse, error)
+ grpc.ClientStream
+}
+
+type serviceBroadcastSubscribeClient struct {
+ grpc.ClientStream
+}
+
+func (x *serviceBroadcastSubscribeClient) Recv() (*BroadcastSubscribeResponse, error) {
+ m := new(BroadcastSubscribeResponse)
+ if err := x.ClientStream.RecvMsg(m); err != nil {
+ return nil, err
+ }
+ return m, nil
+}
+
+func (c *serviceClient) SingleRun(ctx context.Context, in *SingleRunRequest, opts ...grpc.CallOption) (*SingleRunResponse, error) {
+ out := new(SingleRunResponse)
+ err := c.cc.Invoke(ctx, "/exploits.Service/SingleRun", in, out, opts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+func (c *serviceClient) SingleRunSubscribe(ctx context.Context, in *SingleRunSubscribeRequest, opts ...grpc.CallOption) (Service_SingleRunSubscribeClient, error) {
+ stream, err := c.cc.NewStream(ctx, &Service_ServiceDesc.Streams[1], "/exploits.Service/SingleRunSubscribe", opts...)
+ if err != nil {
+ return nil, err
+ }
+ x := &serviceSingleRunSubscribeClient{stream}
+ if err := x.ClientStream.SendMsg(in); err != nil {
+ return nil, err
+ }
+ if err := x.ClientStream.CloseSend(); err != nil {
+ return nil, err
+ }
+ return x, nil
+}
+
+type Service_SingleRunSubscribeClient interface {
+ Recv() (*SingleRunSubscribeResponse, error)
+ grpc.ClientStream
+}
+
+type serviceSingleRunSubscribeClient struct {
+ grpc.ClientStream
+}
+
+func (x *serviceSingleRunSubscribeClient) Recv() (*SingleRunSubscribeResponse, error) {
+ m := new(SingleRunSubscribeResponse)
+ if err := x.ClientStream.RecvMsg(m); err != nil {
+ return nil, err
+ }
+ return m, nil
+}
+
+// ServiceServer is the server API for Service service.
+// All implementations must embed UnimplementedServiceServer
+// for forward compatibility
+type ServiceServer interface {
+ Ping(context.Context, *PingRequest) (*PingResponse, error)
+ Exploit(context.Context, *ExploitRequest) (*ExploitResponse, error)
+ UpdateExploit(context.Context, *UpdateExploitRequest) (*UpdateExploitResponse, error)
+ BroadcastCommand(context.Context, *BroadcastRequest) (*BroadcastResponse, error)
+ BroadcastSubscribe(*BroadcastSubscribeRequest, Service_BroadcastSubscribeServer) error
+ SingleRun(context.Context, *SingleRunRequest) (*SingleRunResponse, error)
+ SingleRunSubscribe(*SingleRunSubscribeRequest, Service_SingleRunSubscribeServer) error
+ mustEmbedUnimplementedServiceServer()
+}
+
+// UnimplementedServiceServer must be embedded to have forward compatible implementations.
+type UnimplementedServiceServer struct {
+}
+
+func (UnimplementedServiceServer) Ping(context.Context, *PingRequest) (*PingResponse, error) {
+ return nil, status.Errorf(codes.Unimplemented, "method Ping not implemented")
+}
+func (UnimplementedServiceServer) Exploit(context.Context, *ExploitRequest) (*ExploitResponse, error) {
+ return nil, status.Errorf(codes.Unimplemented, "method Exploit not implemented")
+}
+func (UnimplementedServiceServer) UpdateExploit(context.Context, *UpdateExploitRequest) (*UpdateExploitResponse, error) {
+ return nil, status.Errorf(codes.Unimplemented, "method UpdateExploit not implemented")
+}
+func (UnimplementedServiceServer) BroadcastCommand(context.Context, *BroadcastRequest) (*BroadcastResponse, error) {
+ return nil, status.Errorf(codes.Unimplemented, "method BroadcastCommand not implemented")
+}
+func (UnimplementedServiceServer) BroadcastSubscribe(*BroadcastSubscribeRequest, Service_BroadcastSubscribeServer) error {
+ return status.Errorf(codes.Unimplemented, "method BroadcastSubscribe not implemented")
+}
+func (UnimplementedServiceServer) SingleRun(context.Context, *SingleRunRequest) (*SingleRunResponse, error) {
+ return nil, status.Errorf(codes.Unimplemented, "method SingleRun not implemented")
+}
+func (UnimplementedServiceServer) SingleRunSubscribe(*SingleRunSubscribeRequest, Service_SingleRunSubscribeServer) error {
+ return status.Errorf(codes.Unimplemented, "method SingleRunSubscribe not implemented")
+}
+func (UnimplementedServiceServer) mustEmbedUnimplementedServiceServer() {}
+
+// UnsafeServiceServer may be embedded to opt out of forward compatibility for this service.
+// Use of this interface is not recommended, as added methods to ServiceServer will
+// result in compilation errors.
+type UnsafeServiceServer interface {
+ mustEmbedUnimplementedServiceServer()
+}
+
+func RegisterServiceServer(s grpc.ServiceRegistrar, srv ServiceServer) {
+ s.RegisterService(&Service_ServiceDesc, srv)
+}
+
+func _Service_Ping_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(PingRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(ServiceServer).Ping(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: "/exploits.Service/Ping",
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(ServiceServer).Ping(ctx, req.(*PingRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+func _Service_Exploit_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(ExploitRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(ServiceServer).Exploit(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: "/exploits.Service/Exploit",
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(ServiceServer).Exploit(ctx, req.(*ExploitRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+func _Service_UpdateExploit_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(UpdateExploitRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(ServiceServer).UpdateExploit(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: "/exploits.Service/UpdateExploit",
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(ServiceServer).UpdateExploit(ctx, req.(*UpdateExploitRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+func _Service_BroadcastCommand_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(BroadcastRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(ServiceServer).BroadcastCommand(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: "/exploits.Service/BroadcastCommand",
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(ServiceServer).BroadcastCommand(ctx, req.(*BroadcastRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+func _Service_BroadcastSubscribe_Handler(srv interface{}, stream grpc.ServerStream) error {
+ m := new(BroadcastSubscribeRequest)
+ if err := stream.RecvMsg(m); err != nil {
+ return err
+ }
+ return srv.(ServiceServer).BroadcastSubscribe(m, &serviceBroadcastSubscribeServer{stream})
+}
+
+type Service_BroadcastSubscribeServer interface {
+ Send(*BroadcastSubscribeResponse) error
+ grpc.ServerStream
+}
+
+type serviceBroadcastSubscribeServer struct {
+ grpc.ServerStream
+}
+
+func (x *serviceBroadcastSubscribeServer) Send(m *BroadcastSubscribeResponse) error {
+ return x.ServerStream.SendMsg(m)
+}
+
+func _Service_SingleRun_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(SingleRunRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(ServiceServer).SingleRun(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: "/exploits.Service/SingleRun",
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(ServiceServer).SingleRun(ctx, req.(*SingleRunRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+func _Service_SingleRunSubscribe_Handler(srv interface{}, stream grpc.ServerStream) error {
+ m := new(SingleRunSubscribeRequest)
+ if err := stream.RecvMsg(m); err != nil {
+ return err
+ }
+ return srv.(ServiceServer).SingleRunSubscribe(m, &serviceSingleRunSubscribeServer{stream})
+}
+
+type Service_SingleRunSubscribeServer interface {
+ Send(*SingleRunSubscribeResponse) error
+ grpc.ServerStream
+}
+
+type serviceSingleRunSubscribeServer struct {
+ grpc.ServerStream
+}
+
+func (x *serviceSingleRunSubscribeServer) Send(m *SingleRunSubscribeResponse) error {
+ return x.ServerStream.SendMsg(m)
+}
+
+// Service_ServiceDesc is the grpc.ServiceDesc for Service service.
+// It's only intended for direct use with grpc.RegisterService,
+// and not to be introspected or modified (even as a copy)
+var Service_ServiceDesc = grpc.ServiceDesc{
+ ServiceName: "exploits.Service",
+ HandlerType: (*ServiceServer)(nil),
+ Methods: []grpc.MethodDesc{
+ {
+ MethodName: "Ping",
+ Handler: _Service_Ping_Handler,
+ },
+ {
+ MethodName: "Exploit",
+ Handler: _Service_Exploit_Handler,
+ },
+ {
+ MethodName: "UpdateExploit",
+ Handler: _Service_UpdateExploit_Handler,
+ },
+ {
+ MethodName: "BroadcastCommand",
+ Handler: _Service_BroadcastCommand_Handler,
+ },
+ {
+ MethodName: "SingleRun",
+ Handler: _Service_SingleRun_Handler,
+ },
+ },
+ Streams: []grpc.StreamDesc{
+ {
+ StreamName: "BroadcastSubscribe",
+ Handler: _Service_BroadcastSubscribe_Handler,
+ ServerStreams: true,
+ },
+ {
+ StreamName: "SingleRunSubscribe",
+ Handler: _Service_SingleRunSubscribe_Handler,
+ ServerStreams: true,
+ },
+ },
+ Metadata: "exploits/api.proto",
+}
diff --git a/components/neo/proto/go/fileserver/api.pb.go b/components/neo/proto/go/fileserver/api.pb.go
new file mode 100644
index 0000000..5be2053
--- /dev/null
+++ b/components/neo/proto/go/fileserver/api.pb.go
@@ -0,0 +1,226 @@
+// Code generated by protoc-gen-go. DO NOT EDIT.
+// versions:
+// protoc-gen-go v1.28.1
+// protoc (unknown)
+// source: fileserver/api.proto
+
+package fileserver
+
+import (
+ protoreflect "google.golang.org/protobuf/reflect/protoreflect"
+ protoimpl "google.golang.org/protobuf/runtime/protoimpl"
+ reflect "reflect"
+ sync "sync"
+)
+
+const (
+ // Verify that this generated code is sufficiently up-to-date.
+ _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
+ // Verify that runtime/protoimpl is sufficiently up-to-date.
+ _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
+)
+
+type FileInfo struct {
+ state protoimpl.MessageState
+ sizeCache protoimpl.SizeCache
+ unknownFields protoimpl.UnknownFields
+
+ Uuid string `protobuf:"bytes,1,opt,name=uuid,proto3" json:"uuid,omitempty"`
+}
+
+func (x *FileInfo) Reset() {
+ *x = FileInfo{}
+ if protoimpl.UnsafeEnabled {
+ mi := &file_fileserver_api_proto_msgTypes[0]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+ }
+}
+
+func (x *FileInfo) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*FileInfo) ProtoMessage() {}
+
+func (x *FileInfo) ProtoReflect() protoreflect.Message {
+ mi := &file_fileserver_api_proto_msgTypes[0]
+ if protoimpl.UnsafeEnabled && x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use FileInfo.ProtoReflect.Descriptor instead.
+func (*FileInfo) Descriptor() ([]byte, []int) {
+ return file_fileserver_api_proto_rawDescGZIP(), []int{0}
+}
+
+func (x *FileInfo) GetUuid() string {
+ if x != nil {
+ return x.Uuid
+ }
+ return ""
+}
+
+type FileStream struct {
+ state protoimpl.MessageState
+ sizeCache protoimpl.SizeCache
+ unknownFields protoimpl.UnknownFields
+
+ Chunk []byte `protobuf:"bytes,1,opt,name=chunk,proto3" json:"chunk,omitempty"`
+}
+
+func (x *FileStream) Reset() {
+ *x = FileStream{}
+ if protoimpl.UnsafeEnabled {
+ mi := &file_fileserver_api_proto_msgTypes[1]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+ }
+}
+
+func (x *FileStream) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*FileStream) ProtoMessage() {}
+
+func (x *FileStream) ProtoReflect() protoreflect.Message {
+ mi := &file_fileserver_api_proto_msgTypes[1]
+ if protoimpl.UnsafeEnabled && x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use FileStream.ProtoReflect.Descriptor instead.
+func (*FileStream) Descriptor() ([]byte, []int) {
+ return file_fileserver_api_proto_rawDescGZIP(), []int{1}
+}
+
+func (x *FileStream) GetChunk() []byte {
+ if x != nil {
+ return x.Chunk
+ }
+ return nil
+}
+
+var File_fileserver_api_proto protoreflect.FileDescriptor
+
+var file_fileserver_api_proto_rawDesc = []byte{
+ 0x0a, 0x14, 0x66, 0x69, 0x6c, 0x65, 0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x2f, 0x61, 0x70, 0x69,
+ 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x0a, 0x66, 0x69, 0x6c, 0x65, 0x73, 0x65, 0x72, 0x76,
+ 0x65, 0x72, 0x22, 0x1e, 0x0a, 0x08, 0x46, 0x69, 0x6c, 0x65, 0x49, 0x6e, 0x66, 0x6f, 0x12, 0x12,
+ 0x0a, 0x04, 0x75, 0x75, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x75, 0x75,
+ 0x69, 0x64, 0x22, 0x22, 0x0a, 0x0a, 0x46, 0x69, 0x6c, 0x65, 0x53, 0x74, 0x72, 0x65, 0x61, 0x6d,
+ 0x12, 0x14, 0x0a, 0x05, 0x63, 0x68, 0x75, 0x6e, 0x6b, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52,
+ 0x05, 0x63, 0x68, 0x75, 0x6e, 0x6b, 0x32, 0x8b, 0x01, 0x0a, 0x07, 0x53, 0x65, 0x72, 0x76, 0x69,
+ 0x63, 0x65, 0x12, 0x3e, 0x0a, 0x0a, 0x55, 0x70, 0x6c, 0x6f, 0x61, 0x64, 0x46, 0x69, 0x6c, 0x65,
+ 0x12, 0x16, 0x2e, 0x66, 0x69, 0x6c, 0x65, 0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x2e, 0x46, 0x69,
+ 0x6c, 0x65, 0x53, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x1a, 0x14, 0x2e, 0x66, 0x69, 0x6c, 0x65, 0x73,
+ 0x65, 0x72, 0x76, 0x65, 0x72, 0x2e, 0x46, 0x69, 0x6c, 0x65, 0x49, 0x6e, 0x66, 0x6f, 0x22, 0x00,
+ 0x28, 0x01, 0x12, 0x40, 0x0a, 0x0c, 0x44, 0x6f, 0x77, 0x6e, 0x6c, 0x6f, 0x61, 0x64, 0x46, 0x69,
+ 0x6c, 0x65, 0x12, 0x14, 0x2e, 0x66, 0x69, 0x6c, 0x65, 0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x2e,
+ 0x46, 0x69, 0x6c, 0x65, 0x49, 0x6e, 0x66, 0x6f, 0x1a, 0x16, 0x2e, 0x66, 0x69, 0x6c, 0x65, 0x73,
+ 0x65, 0x72, 0x76, 0x65, 0x72, 0x2e, 0x46, 0x69, 0x6c, 0x65, 0x53, 0x74, 0x72, 0x65, 0x61, 0x6d,
+ 0x22, 0x00, 0x30, 0x01, 0x42, 0x95, 0x01, 0x0a, 0x0e, 0x63, 0x6f, 0x6d, 0x2e, 0x66, 0x69, 0x6c,
+ 0x65, 0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x42, 0x08, 0x41, 0x70, 0x69, 0x50, 0x72, 0x6f, 0x74,
+ 0x6f, 0x50, 0x01, 0x5a, 0x31, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f,
+ 0x63, 0x34, 0x74, 0x2d, 0x62, 0x75, 0x74, 0x2d, 0x73, 0x34, 0x64, 0x2f, 0x6e, 0x65, 0x6f, 0x2f,
+ 0x76, 0x32, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x67, 0x6f, 0x2f, 0x66, 0x69, 0x6c, 0x65,
+ 0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0xa2, 0x02, 0x03, 0x46, 0x58, 0x58, 0xaa, 0x02, 0x0a, 0x46,
+ 0x69, 0x6c, 0x65, 0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0xca, 0x02, 0x0a, 0x46, 0x69, 0x6c, 0x65,
+ 0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0xe2, 0x02, 0x16, 0x46, 0x69, 0x6c, 0x65, 0x73, 0x65, 0x72,
+ 0x76, 0x65, 0x72, 0x5c, 0x47, 0x50, 0x42, 0x4d, 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0xea,
+ 0x02, 0x0a, 0x46, 0x69, 0x6c, 0x65, 0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x62, 0x06, 0x70, 0x72,
+ 0x6f, 0x74, 0x6f, 0x33,
+}
+
+var (
+ file_fileserver_api_proto_rawDescOnce sync.Once
+ file_fileserver_api_proto_rawDescData = file_fileserver_api_proto_rawDesc
+)
+
+func file_fileserver_api_proto_rawDescGZIP() []byte {
+ file_fileserver_api_proto_rawDescOnce.Do(func() {
+ file_fileserver_api_proto_rawDescData = protoimpl.X.CompressGZIP(file_fileserver_api_proto_rawDescData)
+ })
+ return file_fileserver_api_proto_rawDescData
+}
+
+var file_fileserver_api_proto_msgTypes = make([]protoimpl.MessageInfo, 2)
+var file_fileserver_api_proto_goTypes = []interface{}{
+ (*FileInfo)(nil), // 0: fileserver.FileInfo
+ (*FileStream)(nil), // 1: fileserver.FileStream
+}
+var file_fileserver_api_proto_depIdxs = []int32{
+ 1, // 0: fileserver.Service.UploadFile:input_type -> fileserver.FileStream
+ 0, // 1: fileserver.Service.DownloadFile:input_type -> fileserver.FileInfo
+ 0, // 2: fileserver.Service.UploadFile:output_type -> fileserver.FileInfo
+ 1, // 3: fileserver.Service.DownloadFile:output_type -> fileserver.FileStream
+ 2, // [2:4] is the sub-list for method output_type
+ 0, // [0:2] is the sub-list for method input_type
+ 0, // [0:0] is the sub-list for extension type_name
+ 0, // [0:0] is the sub-list for extension extendee
+ 0, // [0:0] is the sub-list for field type_name
+}
+
+func init() { file_fileserver_api_proto_init() }
+func file_fileserver_api_proto_init() {
+ if File_fileserver_api_proto != nil {
+ return
+ }
+ if !protoimpl.UnsafeEnabled {
+ file_fileserver_api_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
+ switch v := v.(*FileInfo); i {
+ case 0:
+ return &v.state
+ case 1:
+ return &v.sizeCache
+ case 2:
+ return &v.unknownFields
+ default:
+ return nil
+ }
+ }
+ file_fileserver_api_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} {
+ switch v := v.(*FileStream); i {
+ case 0:
+ return &v.state
+ case 1:
+ return &v.sizeCache
+ case 2:
+ return &v.unknownFields
+ default:
+ return nil
+ }
+ }
+ }
+ type x struct{}
+ out := protoimpl.TypeBuilder{
+ File: protoimpl.DescBuilder{
+ GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
+ RawDescriptor: file_fileserver_api_proto_rawDesc,
+ NumEnums: 0,
+ NumMessages: 2,
+ NumExtensions: 0,
+ NumServices: 1,
+ },
+ GoTypes: file_fileserver_api_proto_goTypes,
+ DependencyIndexes: file_fileserver_api_proto_depIdxs,
+ MessageInfos: file_fileserver_api_proto_msgTypes,
+ }.Build()
+ File_fileserver_api_proto = out.File
+ file_fileserver_api_proto_rawDesc = nil
+ file_fileserver_api_proto_goTypes = nil
+ file_fileserver_api_proto_depIdxs = nil
+}
diff --git a/components/neo/proto/go/fileserver/api_grpc.pb.go b/components/neo/proto/go/fileserver/api_grpc.pb.go
new file mode 100644
index 0000000..e7a0f91
--- /dev/null
+++ b/components/neo/proto/go/fileserver/api_grpc.pb.go
@@ -0,0 +1,202 @@
+// Code generated by protoc-gen-go-grpc. DO NOT EDIT.
+// versions:
+// - protoc-gen-go-grpc v1.2.0
+// - protoc (unknown)
+// source: fileserver/api.proto
+
+package fileserver
+
+import (
+ context "context"
+ grpc "google.golang.org/grpc"
+ codes "google.golang.org/grpc/codes"
+ status "google.golang.org/grpc/status"
+)
+
+// This is a compile-time assertion to ensure that this generated file
+// is compatible with the grpc package it is being compiled against.
+// Requires gRPC-Go v1.32.0 or later.
+const _ = grpc.SupportPackageIsVersion7
+
+// ServiceClient is the client API for Service service.
+//
+// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream.
+type ServiceClient interface {
+ UploadFile(ctx context.Context, opts ...grpc.CallOption) (Service_UploadFileClient, error)
+ DownloadFile(ctx context.Context, in *FileInfo, opts ...grpc.CallOption) (Service_DownloadFileClient, error)
+}
+
+type serviceClient struct {
+ cc grpc.ClientConnInterface
+}
+
+func NewServiceClient(cc grpc.ClientConnInterface) ServiceClient {
+ return &serviceClient{cc}
+}
+
+func (c *serviceClient) UploadFile(ctx context.Context, opts ...grpc.CallOption) (Service_UploadFileClient, error) {
+ stream, err := c.cc.NewStream(ctx, &Service_ServiceDesc.Streams[0], "/fileserver.Service/UploadFile", opts...)
+ if err != nil {
+ return nil, err
+ }
+ x := &serviceUploadFileClient{stream}
+ return x, nil
+}
+
+type Service_UploadFileClient interface {
+ Send(*FileStream) error
+ CloseAndRecv() (*FileInfo, error)
+ grpc.ClientStream
+}
+
+type serviceUploadFileClient struct {
+ grpc.ClientStream
+}
+
+func (x *serviceUploadFileClient) Send(m *FileStream) error {
+ return x.ClientStream.SendMsg(m)
+}
+
+func (x *serviceUploadFileClient) CloseAndRecv() (*FileInfo, error) {
+ if err := x.ClientStream.CloseSend(); err != nil {
+ return nil, err
+ }
+ m := new(FileInfo)
+ if err := x.ClientStream.RecvMsg(m); err != nil {
+ return nil, err
+ }
+ return m, nil
+}
+
+func (c *serviceClient) DownloadFile(ctx context.Context, in *FileInfo, opts ...grpc.CallOption) (Service_DownloadFileClient, error) {
+ stream, err := c.cc.NewStream(ctx, &Service_ServiceDesc.Streams[1], "/fileserver.Service/DownloadFile", opts...)
+ if err != nil {
+ return nil, err
+ }
+ x := &serviceDownloadFileClient{stream}
+ if err := x.ClientStream.SendMsg(in); err != nil {
+ return nil, err
+ }
+ if err := x.ClientStream.CloseSend(); err != nil {
+ return nil, err
+ }
+ return x, nil
+}
+
+type Service_DownloadFileClient interface {
+ Recv() (*FileStream, error)
+ grpc.ClientStream
+}
+
+type serviceDownloadFileClient struct {
+ grpc.ClientStream
+}
+
+func (x *serviceDownloadFileClient) Recv() (*FileStream, error) {
+ m := new(FileStream)
+ if err := x.ClientStream.RecvMsg(m); err != nil {
+ return nil, err
+ }
+ return m, nil
+}
+
+// ServiceServer is the server API for Service service.
+// All implementations must embed UnimplementedServiceServer
+// for forward compatibility
+type ServiceServer interface {
+ UploadFile(Service_UploadFileServer) error
+ DownloadFile(*FileInfo, Service_DownloadFileServer) error
+ mustEmbedUnimplementedServiceServer()
+}
+
+// UnimplementedServiceServer must be embedded to have forward compatible implementations.
+type UnimplementedServiceServer struct {
+}
+
+func (UnimplementedServiceServer) UploadFile(Service_UploadFileServer) error {
+ return status.Errorf(codes.Unimplemented, "method UploadFile not implemented")
+}
+func (UnimplementedServiceServer) DownloadFile(*FileInfo, Service_DownloadFileServer) error {
+ return status.Errorf(codes.Unimplemented, "method DownloadFile not implemented")
+}
+func (UnimplementedServiceServer) mustEmbedUnimplementedServiceServer() {}
+
+// UnsafeServiceServer may be embedded to opt out of forward compatibility for this service.
+// Use of this interface is not recommended, as added methods to ServiceServer will
+// result in compilation errors.
+type UnsafeServiceServer interface {
+ mustEmbedUnimplementedServiceServer()
+}
+
+func RegisterServiceServer(s grpc.ServiceRegistrar, srv ServiceServer) {
+ s.RegisterService(&Service_ServiceDesc, srv)
+}
+
+func _Service_UploadFile_Handler(srv interface{}, stream grpc.ServerStream) error {
+ return srv.(ServiceServer).UploadFile(&serviceUploadFileServer{stream})
+}
+
+type Service_UploadFileServer interface {
+ SendAndClose(*FileInfo) error
+ Recv() (*FileStream, error)
+ grpc.ServerStream
+}
+
+type serviceUploadFileServer struct {
+ grpc.ServerStream
+}
+
+func (x *serviceUploadFileServer) SendAndClose(m *FileInfo) error {
+ return x.ServerStream.SendMsg(m)
+}
+
+func (x *serviceUploadFileServer) Recv() (*FileStream, error) {
+ m := new(FileStream)
+ if err := x.ServerStream.RecvMsg(m); err != nil {
+ return nil, err
+ }
+ return m, nil
+}
+
+func _Service_DownloadFile_Handler(srv interface{}, stream grpc.ServerStream) error {
+ m := new(FileInfo)
+ if err := stream.RecvMsg(m); err != nil {
+ return err
+ }
+ return srv.(ServiceServer).DownloadFile(m, &serviceDownloadFileServer{stream})
+}
+
+type Service_DownloadFileServer interface {
+ Send(*FileStream) error
+ grpc.ServerStream
+}
+
+type serviceDownloadFileServer struct {
+ grpc.ServerStream
+}
+
+func (x *serviceDownloadFileServer) Send(m *FileStream) error {
+ return x.ServerStream.SendMsg(m)
+}
+
+// Service_ServiceDesc is the grpc.ServiceDesc for Service service.
+// It's only intended for direct use with grpc.RegisterService,
+// and not to be introspected or modified (even as a copy)
+var Service_ServiceDesc = grpc.ServiceDesc{
+ ServiceName: "fileserver.Service",
+ HandlerType: (*ServiceServer)(nil),
+ Methods: []grpc.MethodDesc{},
+ Streams: []grpc.StreamDesc{
+ {
+ StreamName: "UploadFile",
+ Handler: _Service_UploadFile_Handler,
+ ClientStreams: true,
+ },
+ {
+ StreamName: "DownloadFile",
+ Handler: _Service_DownloadFile_Handler,
+ ServerStreams: true,
+ },
+ },
+ Metadata: "fileserver/api.proto",
+}
diff --git a/components/neo/proto/go/logs/api.pb.go b/components/neo/proto/go/logs/api.pb.go
new file mode 100644
index 0000000..b9757c8
--- /dev/null
+++ b/components/neo/proto/go/logs/api.pb.go
@@ -0,0 +1,406 @@
+// Code generated by protoc-gen-go. DO NOT EDIT.
+// versions:
+// protoc-gen-go v1.28.1
+// protoc (unknown)
+// source: logs/api.proto
+
+package logs
+
+import (
+ protoreflect "google.golang.org/protobuf/reflect/protoreflect"
+ protoimpl "google.golang.org/protobuf/runtime/protoimpl"
+ emptypb "google.golang.org/protobuf/types/known/emptypb"
+ reflect "reflect"
+ sync "sync"
+)
+
+const (
+ // Verify that this generated code is sufficiently up-to-date.
+ _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
+ // Verify that runtime/protoimpl is sufficiently up-to-date.
+ _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
+)
+
+type LogLine struct {
+ state protoimpl.MessageState
+ sizeCache protoimpl.SizeCache
+ unknownFields protoimpl.UnknownFields
+
+ Exploit string `protobuf:"bytes,1,opt,name=exploit,proto3" json:"exploit,omitempty"`
+ Version int64 `protobuf:"varint,2,opt,name=version,proto3" json:"version,omitempty"`
+ Message string `protobuf:"bytes,3,opt,name=message,proto3" json:"message,omitempty"`
+ Level string `protobuf:"bytes,4,opt,name=level,proto3" json:"level,omitempty"`
+ Team string `protobuf:"bytes,5,opt,name=team,proto3" json:"team,omitempty"`
+}
+
+func (x *LogLine) Reset() {
+ *x = LogLine{}
+ if protoimpl.UnsafeEnabled {
+ mi := &file_logs_api_proto_msgTypes[0]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+ }
+}
+
+func (x *LogLine) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*LogLine) ProtoMessage() {}
+
+func (x *LogLine) ProtoReflect() protoreflect.Message {
+ mi := &file_logs_api_proto_msgTypes[0]
+ if protoimpl.UnsafeEnabled && x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use LogLine.ProtoReflect.Descriptor instead.
+func (*LogLine) Descriptor() ([]byte, []int) {
+ return file_logs_api_proto_rawDescGZIP(), []int{0}
+}
+
+func (x *LogLine) GetExploit() string {
+ if x != nil {
+ return x.Exploit
+ }
+ return ""
+}
+
+func (x *LogLine) GetVersion() int64 {
+ if x != nil {
+ return x.Version
+ }
+ return 0
+}
+
+func (x *LogLine) GetMessage() string {
+ if x != nil {
+ return x.Message
+ }
+ return ""
+}
+
+func (x *LogLine) GetLevel() string {
+ if x != nil {
+ return x.Level
+ }
+ return ""
+}
+
+func (x *LogLine) GetTeam() string {
+ if x != nil {
+ return x.Team
+ }
+ return ""
+}
+
+type AddLogLinesRequest struct {
+ state protoimpl.MessageState
+ sizeCache protoimpl.SizeCache
+ unknownFields protoimpl.UnknownFields
+
+ Lines []*LogLine `protobuf:"bytes,1,rep,name=lines,proto3" json:"lines,omitempty"`
+}
+
+func (x *AddLogLinesRequest) Reset() {
+ *x = AddLogLinesRequest{}
+ if protoimpl.UnsafeEnabled {
+ mi := &file_logs_api_proto_msgTypes[1]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+ }
+}
+
+func (x *AddLogLinesRequest) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*AddLogLinesRequest) ProtoMessage() {}
+
+func (x *AddLogLinesRequest) ProtoReflect() protoreflect.Message {
+ mi := &file_logs_api_proto_msgTypes[1]
+ if protoimpl.UnsafeEnabled && x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use AddLogLinesRequest.ProtoReflect.Descriptor instead.
+func (*AddLogLinesRequest) Descriptor() ([]byte, []int) {
+ return file_logs_api_proto_rawDescGZIP(), []int{1}
+}
+
+func (x *AddLogLinesRequest) GetLines() []*LogLine {
+ if x != nil {
+ return x.Lines
+ }
+ return nil
+}
+
+type SearchLogLinesRequest struct {
+ state protoimpl.MessageState
+ sizeCache protoimpl.SizeCache
+ unknownFields protoimpl.UnknownFields
+
+ Exploit string `protobuf:"bytes,1,opt,name=exploit,proto3" json:"exploit,omitempty"`
+ Version int64 `protobuf:"varint,2,opt,name=version,proto3" json:"version,omitempty"`
+}
+
+func (x *SearchLogLinesRequest) Reset() {
+ *x = SearchLogLinesRequest{}
+ if protoimpl.UnsafeEnabled {
+ mi := &file_logs_api_proto_msgTypes[2]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+ }
+}
+
+func (x *SearchLogLinesRequest) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*SearchLogLinesRequest) ProtoMessage() {}
+
+func (x *SearchLogLinesRequest) ProtoReflect() protoreflect.Message {
+ mi := &file_logs_api_proto_msgTypes[2]
+ if protoimpl.UnsafeEnabled && x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use SearchLogLinesRequest.ProtoReflect.Descriptor instead.
+func (*SearchLogLinesRequest) Descriptor() ([]byte, []int) {
+ return file_logs_api_proto_rawDescGZIP(), []int{2}
+}
+
+func (x *SearchLogLinesRequest) GetExploit() string {
+ if x != nil {
+ return x.Exploit
+ }
+ return ""
+}
+
+func (x *SearchLogLinesRequest) GetVersion() int64 {
+ if x != nil {
+ return x.Version
+ }
+ return 0
+}
+
+type SearchLogLinesResponse struct {
+ state protoimpl.MessageState
+ sizeCache protoimpl.SizeCache
+ unknownFields protoimpl.UnknownFields
+
+ Lines []*LogLine `protobuf:"bytes,1,rep,name=lines,proto3" json:"lines,omitempty"`
+}
+
+func (x *SearchLogLinesResponse) Reset() {
+ *x = SearchLogLinesResponse{}
+ if protoimpl.UnsafeEnabled {
+ mi := &file_logs_api_proto_msgTypes[3]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+ }
+}
+
+func (x *SearchLogLinesResponse) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*SearchLogLinesResponse) ProtoMessage() {}
+
+func (x *SearchLogLinesResponse) ProtoReflect() protoreflect.Message {
+ mi := &file_logs_api_proto_msgTypes[3]
+ if protoimpl.UnsafeEnabled && x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use SearchLogLinesResponse.ProtoReflect.Descriptor instead.
+func (*SearchLogLinesResponse) Descriptor() ([]byte, []int) {
+ return file_logs_api_proto_rawDescGZIP(), []int{3}
+}
+
+func (x *SearchLogLinesResponse) GetLines() []*LogLine {
+ if x != nil {
+ return x.Lines
+ }
+ return nil
+}
+
+var File_logs_api_proto protoreflect.FileDescriptor
+
+var file_logs_api_proto_rawDesc = []byte{
+ 0x0a, 0x0e, 0x6c, 0x6f, 0x67, 0x73, 0x2f, 0x61, 0x70, 0x69, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f,
+ 0x12, 0x04, 0x6c, 0x6f, 0x67, 0x73, 0x1a, 0x1b, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x70,
+ 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x65, 0x6d, 0x70, 0x74, 0x79, 0x2e, 0x70, 0x72,
+ 0x6f, 0x74, 0x6f, 0x22, 0x81, 0x01, 0x0a, 0x07, 0x4c, 0x6f, 0x67, 0x4c, 0x69, 0x6e, 0x65, 0x12,
+ 0x18, 0x0a, 0x07, 0x65, 0x78, 0x70, 0x6c, 0x6f, 0x69, 0x74, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09,
+ 0x52, 0x07, 0x65, 0x78, 0x70, 0x6c, 0x6f, 0x69, 0x74, 0x12, 0x18, 0x0a, 0x07, 0x76, 0x65, 0x72,
+ 0x73, 0x69, 0x6f, 0x6e, 0x18, 0x02, 0x20, 0x01, 0x28, 0x03, 0x52, 0x07, 0x76, 0x65, 0x72, 0x73,
+ 0x69, 0x6f, 0x6e, 0x12, 0x18, 0x0a, 0x07, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x18, 0x03,
+ 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x12, 0x14, 0x0a,
+ 0x05, 0x6c, 0x65, 0x76, 0x65, 0x6c, 0x18, 0x04, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x6c, 0x65,
+ 0x76, 0x65, 0x6c, 0x12, 0x12, 0x0a, 0x04, 0x74, 0x65, 0x61, 0x6d, 0x18, 0x05, 0x20, 0x01, 0x28,
+ 0x09, 0x52, 0x04, 0x74, 0x65, 0x61, 0x6d, 0x22, 0x39, 0x0a, 0x12, 0x41, 0x64, 0x64, 0x4c, 0x6f,
+ 0x67, 0x4c, 0x69, 0x6e, 0x65, 0x73, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x23, 0x0a,
+ 0x05, 0x6c, 0x69, 0x6e, 0x65, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x0d, 0x2e, 0x6c,
+ 0x6f, 0x67, 0x73, 0x2e, 0x4c, 0x6f, 0x67, 0x4c, 0x69, 0x6e, 0x65, 0x52, 0x05, 0x6c, 0x69, 0x6e,
+ 0x65, 0x73, 0x22, 0x4b, 0x0a, 0x15, 0x53, 0x65, 0x61, 0x72, 0x63, 0x68, 0x4c, 0x6f, 0x67, 0x4c,
+ 0x69, 0x6e, 0x65, 0x73, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x18, 0x0a, 0x07, 0x65,
+ 0x78, 0x70, 0x6c, 0x6f, 0x69, 0x74, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x65, 0x78,
+ 0x70, 0x6c, 0x6f, 0x69, 0x74, 0x12, 0x18, 0x0a, 0x07, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e,
+ 0x18, 0x02, 0x20, 0x01, 0x28, 0x03, 0x52, 0x07, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x22,
+ 0x3d, 0x0a, 0x16, 0x53, 0x65, 0x61, 0x72, 0x63, 0x68, 0x4c, 0x6f, 0x67, 0x4c, 0x69, 0x6e, 0x65,
+ 0x73, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x23, 0x0a, 0x05, 0x6c, 0x69, 0x6e,
+ 0x65, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x0d, 0x2e, 0x6c, 0x6f, 0x67, 0x73, 0x2e,
+ 0x4c, 0x6f, 0x67, 0x4c, 0x69, 0x6e, 0x65, 0x52, 0x05, 0x6c, 0x69, 0x6e, 0x65, 0x73, 0x32, 0x9d,
+ 0x01, 0x0a, 0x07, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x12, 0x41, 0x0a, 0x0b, 0x41, 0x64,
+ 0x64, 0x4c, 0x6f, 0x67, 0x4c, 0x69, 0x6e, 0x65, 0x73, 0x12, 0x18, 0x2e, 0x6c, 0x6f, 0x67, 0x73,
+ 0x2e, 0x41, 0x64, 0x64, 0x4c, 0x6f, 0x67, 0x4c, 0x69, 0x6e, 0x65, 0x73, 0x52, 0x65, 0x71, 0x75,
+ 0x65, 0x73, 0x74, 0x1a, 0x16, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f,
+ 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x22, 0x00, 0x12, 0x4f, 0x0a,
+ 0x0e, 0x53, 0x65, 0x61, 0x72, 0x63, 0x68, 0x4c, 0x6f, 0x67, 0x4c, 0x69, 0x6e, 0x65, 0x73, 0x12,
+ 0x1b, 0x2e, 0x6c, 0x6f, 0x67, 0x73, 0x2e, 0x53, 0x65, 0x61, 0x72, 0x63, 0x68, 0x4c, 0x6f, 0x67,
+ 0x4c, 0x69, 0x6e, 0x65, 0x73, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x1c, 0x2e, 0x6c,
+ 0x6f, 0x67, 0x73, 0x2e, 0x53, 0x65, 0x61, 0x72, 0x63, 0x68, 0x4c, 0x6f, 0x67, 0x4c, 0x69, 0x6e,
+ 0x65, 0x73, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x00, 0x30, 0x01, 0x42, 0x71,
+ 0x0a, 0x08, 0x63, 0x6f, 0x6d, 0x2e, 0x6c, 0x6f, 0x67, 0x73, 0x42, 0x08, 0x41, 0x70, 0x69, 0x50,
+ 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x2b, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63,
+ 0x6f, 0x6d, 0x2f, 0x63, 0x34, 0x74, 0x2d, 0x62, 0x75, 0x74, 0x2d, 0x73, 0x34, 0x64, 0x2f, 0x6e,
+ 0x65, 0x6f, 0x2f, 0x76, 0x32, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x67, 0x6f, 0x2f, 0x6c,
+ 0x6f, 0x67, 0x73, 0xa2, 0x02, 0x03, 0x4c, 0x58, 0x58, 0xaa, 0x02, 0x04, 0x4c, 0x6f, 0x67, 0x73,
+ 0xca, 0x02, 0x04, 0x4c, 0x6f, 0x67, 0x73, 0xe2, 0x02, 0x10, 0x4c, 0x6f, 0x67, 0x73, 0x5c, 0x47,
+ 0x50, 0x42, 0x4d, 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0xea, 0x02, 0x04, 0x4c, 0x6f, 0x67,
+ 0x73, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
+}
+
+var (
+ file_logs_api_proto_rawDescOnce sync.Once
+ file_logs_api_proto_rawDescData = file_logs_api_proto_rawDesc
+)
+
+func file_logs_api_proto_rawDescGZIP() []byte {
+ file_logs_api_proto_rawDescOnce.Do(func() {
+ file_logs_api_proto_rawDescData = protoimpl.X.CompressGZIP(file_logs_api_proto_rawDescData)
+ })
+ return file_logs_api_proto_rawDescData
+}
+
+var file_logs_api_proto_msgTypes = make([]protoimpl.MessageInfo, 4)
+var file_logs_api_proto_goTypes = []interface{}{
+ (*LogLine)(nil), // 0: logs.LogLine
+ (*AddLogLinesRequest)(nil), // 1: logs.AddLogLinesRequest
+ (*SearchLogLinesRequest)(nil), // 2: logs.SearchLogLinesRequest
+ (*SearchLogLinesResponse)(nil), // 3: logs.SearchLogLinesResponse
+ (*emptypb.Empty)(nil), // 4: google.protobuf.Empty
+}
+var file_logs_api_proto_depIdxs = []int32{
+ 0, // 0: logs.AddLogLinesRequest.lines:type_name -> logs.LogLine
+ 0, // 1: logs.SearchLogLinesResponse.lines:type_name -> logs.LogLine
+ 1, // 2: logs.Service.AddLogLines:input_type -> logs.AddLogLinesRequest
+ 2, // 3: logs.Service.SearchLogLines:input_type -> logs.SearchLogLinesRequest
+ 4, // 4: logs.Service.AddLogLines:output_type -> google.protobuf.Empty
+ 3, // 5: logs.Service.SearchLogLines:output_type -> logs.SearchLogLinesResponse
+ 4, // [4:6] is the sub-list for method output_type
+ 2, // [2:4] is the sub-list for method input_type
+ 2, // [2:2] is the sub-list for extension type_name
+ 2, // [2:2] is the sub-list for extension extendee
+ 0, // [0:2] is the sub-list for field type_name
+}
+
+func init() { file_logs_api_proto_init() }
+func file_logs_api_proto_init() {
+ if File_logs_api_proto != nil {
+ return
+ }
+ if !protoimpl.UnsafeEnabled {
+ file_logs_api_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
+ switch v := v.(*LogLine); i {
+ case 0:
+ return &v.state
+ case 1:
+ return &v.sizeCache
+ case 2:
+ return &v.unknownFields
+ default:
+ return nil
+ }
+ }
+ file_logs_api_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} {
+ switch v := v.(*AddLogLinesRequest); i {
+ case 0:
+ return &v.state
+ case 1:
+ return &v.sizeCache
+ case 2:
+ return &v.unknownFields
+ default:
+ return nil
+ }
+ }
+ file_logs_api_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} {
+ switch v := v.(*SearchLogLinesRequest); i {
+ case 0:
+ return &v.state
+ case 1:
+ return &v.sizeCache
+ case 2:
+ return &v.unknownFields
+ default:
+ return nil
+ }
+ }
+ file_logs_api_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} {
+ switch v := v.(*SearchLogLinesResponse); i {
+ case 0:
+ return &v.state
+ case 1:
+ return &v.sizeCache
+ case 2:
+ return &v.unknownFields
+ default:
+ return nil
+ }
+ }
+ }
+ type x struct{}
+ out := protoimpl.TypeBuilder{
+ File: protoimpl.DescBuilder{
+ GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
+ RawDescriptor: file_logs_api_proto_rawDesc,
+ NumEnums: 0,
+ NumMessages: 4,
+ NumExtensions: 0,
+ NumServices: 1,
+ },
+ GoTypes: file_logs_api_proto_goTypes,
+ DependencyIndexes: file_logs_api_proto_depIdxs,
+ MessageInfos: file_logs_api_proto_msgTypes,
+ }.Build()
+ File_logs_api_proto = out.File
+ file_logs_api_proto_rawDesc = nil
+ file_logs_api_proto_goTypes = nil
+ file_logs_api_proto_depIdxs = nil
+}
diff --git a/components/neo/proto/go/logs/api_grpc.pb.go b/components/neo/proto/go/logs/api_grpc.pb.go
new file mode 100644
index 0000000..6624ebd
--- /dev/null
+++ b/components/neo/proto/go/logs/api_grpc.pb.go
@@ -0,0 +1,170 @@
+// Code generated by protoc-gen-go-grpc. DO NOT EDIT.
+// versions:
+// - protoc-gen-go-grpc v1.2.0
+// - protoc (unknown)
+// source: logs/api.proto
+
+package logs
+
+import (
+ context "context"
+ grpc "google.golang.org/grpc"
+ codes "google.golang.org/grpc/codes"
+ status "google.golang.org/grpc/status"
+ emptypb "google.golang.org/protobuf/types/known/emptypb"
+)
+
+// This is a compile-time assertion to ensure that this generated file
+// is compatible with the grpc package it is being compiled against.
+// Requires gRPC-Go v1.32.0 or later.
+const _ = grpc.SupportPackageIsVersion7
+
+// ServiceClient is the client API for Service service.
+//
+// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream.
+type ServiceClient interface {
+ AddLogLines(ctx context.Context, in *AddLogLinesRequest, opts ...grpc.CallOption) (*emptypb.Empty, error)
+ SearchLogLines(ctx context.Context, in *SearchLogLinesRequest, opts ...grpc.CallOption) (Service_SearchLogLinesClient, error)
+}
+
+type serviceClient struct {
+ cc grpc.ClientConnInterface
+}
+
+func NewServiceClient(cc grpc.ClientConnInterface) ServiceClient {
+ return &serviceClient{cc}
+}
+
+func (c *serviceClient) AddLogLines(ctx context.Context, in *AddLogLinesRequest, opts ...grpc.CallOption) (*emptypb.Empty, error) {
+ out := new(emptypb.Empty)
+ err := c.cc.Invoke(ctx, "/logs.Service/AddLogLines", in, out, opts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+func (c *serviceClient) SearchLogLines(ctx context.Context, in *SearchLogLinesRequest, opts ...grpc.CallOption) (Service_SearchLogLinesClient, error) {
+ stream, err := c.cc.NewStream(ctx, &Service_ServiceDesc.Streams[0], "/logs.Service/SearchLogLines", opts...)
+ if err != nil {
+ return nil, err
+ }
+ x := &serviceSearchLogLinesClient{stream}
+ if err := x.ClientStream.SendMsg(in); err != nil {
+ return nil, err
+ }
+ if err := x.ClientStream.CloseSend(); err != nil {
+ return nil, err
+ }
+ return x, nil
+}
+
+type Service_SearchLogLinesClient interface {
+ Recv() (*SearchLogLinesResponse, error)
+ grpc.ClientStream
+}
+
+type serviceSearchLogLinesClient struct {
+ grpc.ClientStream
+}
+
+func (x *serviceSearchLogLinesClient) Recv() (*SearchLogLinesResponse, error) {
+ m := new(SearchLogLinesResponse)
+ if err := x.ClientStream.RecvMsg(m); err != nil {
+ return nil, err
+ }
+ return m, nil
+}
+
+// ServiceServer is the server API for Service service.
+// All implementations must embed UnimplementedServiceServer
+// for forward compatibility
+type ServiceServer interface {
+ AddLogLines(context.Context, *AddLogLinesRequest) (*emptypb.Empty, error)
+ SearchLogLines(*SearchLogLinesRequest, Service_SearchLogLinesServer) error
+ mustEmbedUnimplementedServiceServer()
+}
+
+// UnimplementedServiceServer must be embedded to have forward compatible implementations.
+type UnimplementedServiceServer struct {
+}
+
+func (UnimplementedServiceServer) AddLogLines(context.Context, *AddLogLinesRequest) (*emptypb.Empty, error) {
+ return nil, status.Errorf(codes.Unimplemented, "method AddLogLines not implemented")
+}
+func (UnimplementedServiceServer) SearchLogLines(*SearchLogLinesRequest, Service_SearchLogLinesServer) error {
+ return status.Errorf(codes.Unimplemented, "method SearchLogLines not implemented")
+}
+func (UnimplementedServiceServer) mustEmbedUnimplementedServiceServer() {}
+
+// UnsafeServiceServer may be embedded to opt out of forward compatibility for this service.
+// Use of this interface is not recommended, as added methods to ServiceServer will
+// result in compilation errors.
+type UnsafeServiceServer interface {
+ mustEmbedUnimplementedServiceServer()
+}
+
+func RegisterServiceServer(s grpc.ServiceRegistrar, srv ServiceServer) {
+ s.RegisterService(&Service_ServiceDesc, srv)
+}
+
+func _Service_AddLogLines_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(AddLogLinesRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(ServiceServer).AddLogLines(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: "/logs.Service/AddLogLines",
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(ServiceServer).AddLogLines(ctx, req.(*AddLogLinesRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+func _Service_SearchLogLines_Handler(srv interface{}, stream grpc.ServerStream) error {
+ m := new(SearchLogLinesRequest)
+ if err := stream.RecvMsg(m); err != nil {
+ return err
+ }
+ return srv.(ServiceServer).SearchLogLines(m, &serviceSearchLogLinesServer{stream})
+}
+
+type Service_SearchLogLinesServer interface {
+ Send(*SearchLogLinesResponse) error
+ grpc.ServerStream
+}
+
+type serviceSearchLogLinesServer struct {
+ grpc.ServerStream
+}
+
+func (x *serviceSearchLogLinesServer) Send(m *SearchLogLinesResponse) error {
+ return x.ServerStream.SendMsg(m)
+}
+
+// Service_ServiceDesc is the grpc.ServiceDesc for Service service.
+// It's only intended for direct use with grpc.RegisterService,
+// and not to be introspected or modified (even as a copy)
+var Service_ServiceDesc = grpc.ServiceDesc{
+ ServiceName: "logs.Service",
+ HandlerType: (*ServiceServer)(nil),
+ Methods: []grpc.MethodDesc{
+ {
+ MethodName: "AddLogLines",
+ Handler: _Service_AddLogLines_Handler,
+ },
+ },
+ Streams: []grpc.StreamDesc{
+ {
+ StreamName: "SearchLogLines",
+ Handler: _Service_SearchLogLines_Handler,
+ ServerStreams: true,
+ },
+ },
+ Metadata: "logs/api.proto",
+}
diff --git a/components/neo/proto/logs/api.proto b/components/neo/proto/logs/api.proto
new file mode 100644
index 0000000..0dafb6a
--- /dev/null
+++ b/components/neo/proto/logs/api.proto
@@ -0,0 +1,32 @@
+syntax = "proto3";
+package logs;
+
+option go_package = "logs";
+
+import "google/protobuf/empty.proto";
+
+message LogLine {
+ string exploit = 1;
+ int64 version = 2;
+ string message = 3;
+ string level = 4;
+ string team = 5;
+}
+
+message AddLogLinesRequest {
+ repeated LogLine lines = 1;
+}
+
+message SearchLogLinesRequest {
+ string exploit = 1;
+ int64 version = 2;
+}
+
+message SearchLogLinesResponse {
+ repeated LogLine lines = 1;
+}
+
+service Service {
+ rpc AddLogLines(AddLogLinesRequest) returns (google.protobuf.Empty) {}
+ rpc SearchLogLines(SearchLogLinesRequest) returns (stream SearchLogLinesResponse) {}
+}
diff --git a/components/neo/redis.Dockerfile b/components/neo/redis.Dockerfile
new file mode 100644
index 0000000..f6964b1
--- /dev/null
+++ b/components/neo/redis.Dockerfile
@@ -0,0 +1,3 @@
+FROM redis:alpine
+
+RUN apk upgrade --no-cache
diff --git a/components/packmate/.dockerignore b/components/packmate/.dockerignore
new file mode 100644
index 0000000..d1007fc
--- /dev/null
+++ b/components/packmate/.dockerignore
@@ -0,0 +1,18 @@
+.git
+.gitignore
+.gitmodules
+.gitlab-ci.yml
+build
+out
+docs
+screenshots
+docker
+pcaps
+rsa_keys
+node_modules
+frontend/node_modules
+frontend/dist
+frontend/coverage
+*.log
+docker-compose.yml
+README_EN.md
diff --git a/components/packmate/Dockerfile b/components/packmate/Dockerfile
new file mode 100644
index 0000000..c7bec24
--- /dev/null
+++ b/components/packmate/Dockerfile
@@ -0,0 +1,37 @@
+FROM node:slim AS frontend
+WORKDIR /workspace/frontend
+COPY frontend/package.json ./
+RUN npm install --global npm \
+ && npm install --no-audit --no-fund --package-lock=false
+COPY frontend/ ./
+RUN npm test && npm run build
+
+FROM gradle:latest AS gradle-dist
+
+FROM eclipse-temurin:27-jdk AS app-build
+COPY --from=gradle-dist /opt/gradle /opt/gradle
+ENV GRADLE_HOME=/opt/gradle \
+ PATH=/opt/gradle/bin:$PATH \
+ JAVA_TOOL_OPTIONS=-Xmx2g
+WORKDIR /workspace
+COPY settings.gradle.kts build.gradle.kts ./
+COPY src/ ./src/
+COPY --from=frontend /workspace/frontend/dist/ ./src/main/resources/static/
+RUN gradle --no-daemon --max-workers=2 test bootJar
+
+FROM eclipse-temurin:27-jre
+RUN apt-get update \
+ && apt-get upgrade -y --no-install-recommends \
+ && apt-get install --no-install-recommends -y curl libpcap0.8 \
+ && rm -f /usr/bin/pebble \
+ && rm -rf /var/lib/apt/lists/* \
+ && mkdir -p /app \
+ && chown 10001:10001 /app
+WORKDIR /app
+COPY --from=app-build --chown=10001:10001 /workspace/build/libs/packmate-1.0.0.jar /app/packmate.jar
+COPY --from=project /LICENSE /usr/share/licenses/wahrwelt/LICENSE
+USER 10001:10001
+EXPOSE 65000
+HEALTHCHECK --interval=30s --timeout=5s --start-period=45s --retries=3 \
+ CMD curl --max-time 3 --fail --silent --output /dev/null "http://127.0.0.1:${SERVER_PORT:-65000}/healthz"
+ENTRYPOINT ["java", "-Djna.tmpdir=/jna-tmp", "-XX:MaxRAMPercentage=75.0", "-jar", "/app/packmate.jar"]
diff --git a/components/packmate/README.md b/components/packmate/README.md
new file mode 100644
index 0000000..e9ddfef
--- /dev/null
+++ b/components/packmate/README.md
@@ -0,0 +1,43 @@
+# Packmate
+
+Packmate показывает сетевые потоки, запросы и ответы, найденные шаблоны и службы. По умолчанию приложение разбирает локальный PCAP в режиме `FILE`; интерфейс доступен через адрес loopback хоста.
+
+## Запуск
+
+Из корня wahrwelt выполните `./control init`, затем запустите:
+
+```sh
+./control pack
+```
+
+Откройте `http://127.0.0.1:${PACKMATE_PORT:-65000}` и войдите с `PACKMATE_USERNAME` и `PACKMATE_PASSWORD` из корневого `.env`. Для анализа замените созданный `local/pcaps/capture.pcap` нужным файлом, затем нажмите `Старт FILE`. Пустой файл, созданный командой `init`, позволяет запустить сервис до добавления PCAP.
+
+Файл и каталог `local/rsa_keys` монтируются в контейнер только для чтения. Ключи RSA нужны только для поддерживаемого исходным проектом TLS_RSA_WITH_AES.
+
+Проверка готовности доступна по `GET /healthz` без авторизации и не возвращает сведений о конфигурации.
+
+## Режим LIVE
+
+LIVE не включен по умолчанию. Он использует host network, чтобы видеть трафик Linux-узла. Применяйте его только на собственном Linux-узле и только для трафика, который вы вправе анализировать. Укажите в корневом `.env` интерфейс, видящий этот трафик (`PACKMATE_INTERFACE_NAME`), локальный адрес (`PACKMATE_LOCAL_IP`) и при необходимости `PACKMATE_DB_PORT`, затем выполните:
+
+```sh
+docker compose -f compose.yaml -f components/packmate/compose.live.yaml up --build packmate packmate-db
+```
+
+Этот режим добавляет только `NET_RAW` и `NET_ADMIN`; он не использует `privileged` и Docker socket. База данных публикуется только на `127.0.0.1:${PACKMATE_DB_PORT:-65432}`, а веб-интерфейс слушает `BIND_ADDRESS` (по умолчанию `127.0.0.1`) и `PACKMATE_PORT`.
+
+## Переменные и проверки
+
+Остановка с сохранением данных: `./control pack down`. Журнал: `./control pack logs`.
+Корневой `.env` должен содержать непустые `PACKMATE_PASSWORD` и `PACKMATE_DB_PASSWORD`. Команда `./control init` создает файл с секретами, если его еще нет. Полный список переменных приведен в корневом [`.env.example`](../../.env.example).
+
+Локальные проверки из каталога компонента:
+
+```sh
+cd components/packmate/frontend
+npm install --package-lock=false && npm test && npm run typecheck && npm run build
+cd ../../..
+./control pack
+```
+
+Источники и лицензии перечислены в [общем LICENSE](../../LICENSE).
diff --git a/components/packmate/build.gradle.kts b/components/packmate/build.gradle.kts
new file mode 100644
index 0000000..da950dc
--- /dev/null
+++ b/components/packmate/build.gradle.kts
@@ -0,0 +1,72 @@
+plugins {
+ id("org.springframework.boot") version "latest.release"
+ id("java")
+}
+
+group = "ru.serega6531"
+version = "1.0.0"
+
+java {
+ toolchain {
+ languageVersion = JavaLanguageVersion.of(27)
+ }
+}
+
+configurations {
+ get("compileOnly").apply {
+ extendsFrom(configurations.annotationProcessor.get())
+ }
+}
+
+repositories {
+ mavenCentral()
+}
+
+dependencies {
+ implementation(platform("org.springframework.boot:spring-boot-dependencies:latest.release"))
+ implementation(platform("tools.jackson:jackson-bom:latest.release"))
+ implementation("org.apache.tomcat.embed:tomcat-embed-core:latest.release")
+ implementation("org.apache.tomcat.embed:tomcat-embed-el:latest.release")
+ implementation("org.apache.tomcat.embed:tomcat-embed-websocket:latest.release")
+ implementation("org.springframework.boot:spring-boot-starter-data-jpa")
+ implementation("org.springframework.boot:spring-boot-starter-webmvc")
+ implementation("org.springframework.boot:spring-boot-starter-security")
+ implementation("org.springframework.boot:spring-boot-starter-websocket")
+ implementation("org.springframework.session:spring-session-core")
+ implementation("org.apache.commons:commons-lang3:latest.release")
+ implementation("commons-io:commons-io:latest.release")
+
+ implementation("org.pcap4j:pcap4j-core:latest.release")
+ implementation("org.pcap4j:pcap4j-packetfactory-static:latest.release")
+
+ constraints {
+ implementation("net.java.dev.jna:jna:latest.release") {
+ because("Поддерживаем актуальную стабильную версию JNA для native libpcap.")
+ }
+ }
+
+ implementation("com.google.guava:guava:latest.release")
+ implementation("com.google.re2j:re2j:latest.release")
+ implementation("org.java-websocket:Java-WebSocket:latest.release")
+ implementation("org.bouncycastle:bcprov-jdk18on:latest.release")
+ implementation("org.bouncycastle:bctls-jdk18on:latest.release")
+ implementation("org.modelmapper:modelmapper:latest.release")
+ implementation("com.athaydes.rawhttp:rawhttp-core:latest.release")
+
+ compileOnly("org.jetbrains:annotations:latest.release")
+ compileOnly("org.projectlombok:lombok:latest.release")
+ runtimeOnly("org.postgresql:postgresql:latest.release")
+ annotationProcessor("org.projectlombok:lombok:latest.release")
+ testImplementation("org.springframework.boot:spring-boot-starter-test")
+ testImplementation("org.junit.jupiter:junit-jupiter:latest.release")
+ testRuntimeOnly("org.junit.platform:junit-platform-launcher:latest.release")
+}
+
+tasks.test {
+ useJUnitPlatform()
+ jvmArgs("-XX:+EnableDynamicAgentLoading", "-Djdk.attach.allowAttachSelf=true")
+}
+
+tasks.withType().configureEach {
+ options.release = 27
+}
diff --git a/components/packmate/compose.live.yaml b/components/packmate/compose.live.yaml
new file mode 100644
index 0000000..bd2e454
--- /dev/null
+++ b/components/packmate/compose.live.yaml
@@ -0,0 +1,19 @@
+services:
+ packmate:
+ environment:
+ PACKMATE_CAPTURE_MODE: LIVE
+ PACKMATE_INTERFACE_NAME: ${PACKMATE_INTERFACE_NAME:?Задайте PACKMATE_INTERFACE_NAME для режима LIVE}
+ PACKMATE_LOCAL_IP: ${PACKMATE_LOCAL_IP:?Задайте PACKMATE_LOCAL_IP для режима LIVE}
+ SERVER_ADDRESS: ${BIND_ADDRESS:-127.0.0.1}
+ SERVER_PORT: ${PACKMATE_PORT:-65000}
+ SPRING_DATASOURCE_URL: jdbc:postgresql://127.0.0.1:${PACKMATE_DB_PORT:-65432}/packmate
+ network_mode: host
+ networks: !reset []
+ ports: !reset []
+ cap_add:
+ - NET_RAW
+ - NET_ADMIN
+
+ packmate-db:
+ ports:
+ - "127.0.0.1:${PACKMATE_DB_PORT:-65432}:5432"
diff --git a/components/packmate/compose.yaml b/components/packmate/compose.yaml
new file mode 100644
index 0000000..ad1dcfa
--- /dev/null
+++ b/components/packmate/compose.yaml
@@ -0,0 +1,72 @@
+services:
+ packmate:
+ build:
+ context: .
+ additional_contexts:
+ project: ../..
+ dockerfile: Dockerfile
+ depends_on:
+ packmate-db:
+ condition: service_healthy
+ environment:
+ SERVER_ADDRESS: 0.0.0.0
+ SERVER_PORT: "65000"
+ SPRING_DATASOURCE_URL: jdbc:postgresql://packmate-db:5432/packmate
+ SPRING_DATASOURCE_USERNAME: packmate
+ SPRING_DATASOURCE_PASSWORD: ${PACKMATE_DB_PASSWORD:?Задайте PACKMATE_DB_PASSWORD}
+ PACKMATE_USERNAME: ${PACKMATE_USERNAME:-packmate}
+ PACKMATE_PASSWORD: ${PACKMATE_PASSWORD:?Задайте PACKMATE_PASSWORD}
+ PACKMATE_CAPTURE_MODE: ${PACKMATE_CAPTURE_MODE:-FILE}
+ PACKMATE_INTERFACE_NAME: ${PACKMATE_INTERFACE_NAME:-lo}
+ PACKMATE_PCAP_FILE: ${PACKMATE_PCAP_FILE:-/pcaps/capture.pcap}
+ PACKMATE_LOCAL_IP: ${PACKMATE_LOCAL_IP:-192.0.2.1}
+ ports:
+ - "${BIND_ADDRESS:-127.0.0.1}:${PACKMATE_PORT:-65000}:65000"
+ volumes:
+ - ../../local/pcaps:/pcaps:ro
+ - ../../local/rsa_keys:/app/rsa_keys:ro
+ networks:
+ - default
+ - packmate-data
+ read_only: true
+ tmpfs:
+ - /tmp:rw,noexec,nosuid,nodev,mode=1777,size=64m
+ - /jna-tmp:rw,exec,nosuid,nodev,uid=10001,gid=10001,mode=0700,size=16m
+ cap_drop:
+ - ALL
+ mem_limit: ${PACKMATE_MEMORY_LIMIT:-2g}
+ pids_limit: 256
+ security_opt:
+ - no-new-privileges:true
+ restart: unless-stopped
+
+ packmate-db:
+ build:
+ context: ../../containers
+ dockerfile: postgres.Dockerfile
+ environment:
+ POSTGRES_DB: packmate
+ POSTGRES_USER: packmate
+ POSTGRES_PASSWORD: ${PACKMATE_DB_PASSWORD:?Задайте PACKMATE_DB_PASSWORD}
+ volumes:
+ - packmate-db:/var/lib/postgresql
+ networks:
+ - packmate-data
+ healthcheck:
+ test: ["CMD-SHELL", "pg_isready -U packmate -d packmate"]
+ interval: 5s
+ timeout: 3s
+ retries: 12
+ start_period: 10s
+ mem_limit: 1g
+ pids_limit: 128
+ security_opt:
+ - no-new-privileges:true
+ restart: unless-stopped
+
+volumes:
+ packmate-db:
+
+networks:
+ packmate-data:
+ internal: true
diff --git a/components/packmate/frontend/index.html b/components/packmate/frontend/index.html
new file mode 100644
index 0000000..2276e0b
--- /dev/null
+++ b/components/packmate/frontend/index.html
@@ -0,0 +1,15 @@
+
+
+
+
+
+
+
+
+ wahrwelt / Packmate
+
+
+
+
+
+
diff --git a/components/packmate/frontend/package.json b/components/packmate/frontend/package.json
new file mode 100644
index 0000000..6a600d1
--- /dev/null
+++ b/components/packmate/frontend/package.json
@@ -0,0 +1,28 @@
+{
+ "name": "wahrwelt-packmate-ui",
+ "version": "1.0.0",
+ "private": true,
+ "type": "module",
+ "scripts": {
+ "dev": "vite --host 127.0.0.1",
+ "typecheck": "tsc --noEmit",
+ "test": "vitest run",
+ "build": "tsc --noEmit && vite build"
+ },
+ "dependencies": {
+ "react": ">=19.3.0",
+ "react-dom": ">=19.3.0"
+ },
+ "devDependencies": {
+ "@testing-library/jest-dom": ">=7.0.1",
+ "@testing-library/react": ">=16.3.3",
+ "@testing-library/user-event": ">=14.6.8",
+ "@types/react": ">=19.3.0",
+ "@types/react-dom": ">=19.3.0",
+ "@vitejs/plugin-react": ">=6.1.2",
+ "happy-dom": ">=21.0.1",
+ "typescript": ">=7.0.2",
+ "vite": ">=8.3.4",
+ "vitest": ">=5.0.4"
+ }
+}
diff --git a/components/packmate/frontend/public/logo.jpg b/components/packmate/frontend/public/logo.jpg
new file mode 100644
index 0000000..2bf7f7d
Binary files /dev/null and b/components/packmate/frontend/public/logo.jpg differ
diff --git a/components/packmate/frontend/src/App.test.tsx b/components/packmate/frontend/src/App.test.tsx
new file mode 100644
index 0000000..1d970b5
--- /dev/null
+++ b/components/packmate/frontend/src/App.test.tsx
@@ -0,0 +1,219 @@
+import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import App from "./App";
+import type { Packet, Service, Stream } from "./types";
+
+const { apiMock } = vi.hoisted(() => ({
+ apiMock: {
+ services: vi.fn(),
+ createService: vi.fn(),
+ updateService: vi.fn(),
+ deleteService: vi.fn(),
+ patterns: vi.fn(),
+ createPattern: vi.fn(),
+ updatePattern: vi.fn(),
+ setPatternEnabled: vi.fn(),
+ deletePattern: vi.fn(),
+ lookBack: vi.fn(),
+ streams: vi.fn(),
+ packets: vi.fn(),
+ setFavorite: vi.fn(),
+ pcapStarted: vi.fn(),
+ startPcap: vi.fn(),
+ },
+}));
+
+vi.mock("./api", () => ({ api: apiMock }));
+class MockWebSocket {
+ static instances: MockWebSocket[] = [];
+ onopen: (() => void) | null = null;
+ onmessage: ((event: MessageEvent) => void) | null = null;
+ onerror: (() => void) | null = null;
+ onclose: (() => void) | null = null;
+ close = vi.fn();
+
+ constructor(readonly url: string) {
+ MockWebSocket.instances.push(this);
+ }
+}
+
+function deferred() {
+ let resolve!: (value: T) => void;
+ const promise = new Promise((done) => { resolve = done; });
+ return { promise, resolve };
+}
+
+function service(port: number, name: string): Service {
+ return {
+ port,
+ name,
+ decryptTls: false,
+ http: false,
+ urldecodeHttpRequests: false,
+ mergeAdjacentPackets: false,
+ parseWebSockets: false,
+ };
+}
+
+function stream(id: number, port = 80): Stream {
+ return {
+ id,
+ service: port,
+ protocol: "TCP",
+ startTimestamp: 1_700_000_000_000,
+ endTimestamp: 1_700_000_000_100,
+ foundPatternsIds: [],
+ favorite: false,
+ ttl: 64,
+ userAgentHash: null,
+ sizeBytes: 10,
+ packetsCount: 1,
+ };
+}
+
+function packet(id: number, text: string): Packet {
+ return {
+ id,
+ matches: [],
+ timestamp: 1_700_000_000_000 + id,
+ incoming: true,
+ ungzipped: false,
+ webSocketParsed: false,
+ tlsDecrypted: false,
+ hasHttpBody: false,
+ content: btoa(String.fromCharCode(...new TextEncoder().encode(text))),
+ };
+}
+
+function pageOfStreams(firstId = 10): Stream[] {
+ return Array.from({ length: 10 }, (_, index) => stream(firstId - index));
+}
+
+function pageOfPackets(firstId = 100): Packet[] {
+ return Array.from({ length: 10 }, (_, index) => packet(firstId - index, `пакет-${firstId - index}`));
+}
+
+beforeEach(() => {
+ MockWebSocket.instances = [];
+ vi.stubGlobal("WebSocket", MockWebSocket);
+ window.history.replaceState({}, "", "/");
+ localStorage.clear();
+ localStorage.setItem("packmate.pageSize", "10");
+ for (const method of Object.values(apiMock)) {
+ method.mockReset();
+ }
+ apiMock.services.mockResolvedValue([service(80, "HTTP"), service(443, "HTTPS")]);
+ apiMock.patterns.mockResolvedValue([]);
+ apiMock.pcapStarted.mockResolvedValue(false);
+});
+
+it("получает события через WebSocket и сохраняет остановку короткого PCAP", async () => {
+ const startRequest = deferred();
+ apiMock.streams.mockResolvedValue([]);
+ apiMock.startPcap.mockReturnValue(startRequest.promise);
+ const view = render();
+ const startButton = await screen.findByTitle("Начать обработку PCAP-файла");
+ const socket = MockWebSocket.instances.at(-1)!;
+ expect(socket.url).toBe(`ws://${window.location.host}/api/ws`);
+
+ fireEvent.click(startButton);
+ await act(async () => {
+ socket.onmessage?.(new MessageEvent("message", {
+ data: JSON.stringify({ type: "PCAP_STARTED", value: null }),
+ }));
+ socket.onmessage?.(new MessageEvent("message", {
+ data: JSON.stringify({ type: "PCAP_STOPPED", value: null }),
+ }));
+ startRequest.resolve();
+ });
+
+ expect(screen.getByTitle("Начать обработку PCAP-файла")).toBeInTheDocument();
+ view.unmount();
+ expect(socket.close).toHaveBeenCalledOnce();
+});
+
+describe("смена выборки во время загрузки", () => {
+ it("не добавляет позднюю страницу потоков к выбранному другому сервису", async () => {
+ const oldPage = deferred();
+ apiMock.streams.mockImplementation((port: number | undefined, query: { startingFrom: number | null }) => {
+ if (port === 443) {
+ return Promise.resolve([stream(900, 443)]);
+ }
+ return query.startingFrom === null ? Promise.resolve(pageOfStreams()) : oldPage.promise;
+ });
+
+ render();
+ await screen.findByRole("button", { name: /#10 TCP/ });
+ fireEvent.click(screen.getByRole("button", { name: "Загрузить еще потоки" }));
+ await waitFor(() => expect(apiMock.streams).toHaveBeenCalledWith(
+ undefined,
+ expect.objectContaining({ startingFrom: 1 }),
+ expect.any(AbortSignal),
+ ));
+
+ fireEvent.click(screen.getByRole("button", { name: /HTTPS #443/ }));
+ await screen.findByRole("button", { name: /#900 TCP/ });
+
+ await act(async () => oldPage.resolve([stream(99, 80)]));
+ expect(screen.queryByRole("button", { name: /#99 TCP/ })).not.toBeInTheDocument();
+ expect(screen.getByRole("button", { name: /#900 TCP/ })).toBeInTheDocument();
+ });
+
+ it("игнорирует поздние пакеты старого потока и не снимает индикатор нового запроса", async () => {
+ const initialPage = deferred();
+ const currentPage = deferred();
+ apiMock.streams.mockResolvedValue(pageOfStreams());
+ apiMock.packets.mockImplementation((streamId: number, query: { startingFrom: number | null }) => {
+ if (streamId === 10 && query.startingFrom === null) {
+ return initialPage.promise;
+ }
+ if (streamId === 9 && query.startingFrom === null) {
+ return currentPage.promise;
+ }
+ return Promise.resolve([]);
+ });
+
+ render();
+ fireEvent.click(await screen.findByRole("button", { name: /#10 TCP/ }));
+ await waitFor(() => expect(apiMock.packets).toHaveBeenCalledWith(10, { startingFrom: null, pageSize: 10 }, expect.any(AbortSignal)));
+
+ fireEvent.click(screen.getByRole("button", { name: /#9 TCP/ }));
+ await waitFor(() => expect(apiMock.packets).toHaveBeenCalledWith(9, { startingFrom: null, pageSize: 10 }, expect.any(AbortSignal)));
+ await act(async () => initialPage.resolve(pageOfPackets(80)));
+ expect(screen.getByText("Загрузка пакетов...")).toBeInTheDocument();
+
+ await act(async () => currentPage.resolve([packet(1, "актуальный пакет")]));
+ expect(await screen.findByText("актуальный пакет")).toBeInTheDocument();
+ expect(screen.queryByText(/пакет-80/)).not.toBeInTheDocument();
+ });
+
+ it("отменяет позднюю дополнительную страницу пакетов после выбора другого потока", async () => {
+ const oldPage = deferred();
+ apiMock.streams.mockResolvedValue(pageOfStreams());
+ apiMock.packets.mockImplementation((streamId: number, query: { startingFrom: number | null }) => {
+ if (streamId === 10 && query.startingFrom === null) {
+ return Promise.resolve(pageOfPackets());
+ }
+ if (streamId === 10) {
+ return oldPage.promise;
+ }
+ return Promise.resolve([packet(2, "пакет выбранного потока")]);
+ });
+
+ render();
+ fireEvent.click(await screen.findByRole("button", { name: /#10 TCP/ }));
+ fireEvent.click(await screen.findByRole("button", { name: "Загрузить еще пакеты" }));
+ await waitFor(() => expect(apiMock.packets).toHaveBeenCalledWith(
+ 10,
+ { startingFrom: 91, pageSize: 10 },
+ expect.any(AbortSignal),
+ ));
+
+ fireEvent.click(screen.getByRole("button", { name: /#9 TCP/ }));
+ expect(await screen.findByText("пакет выбранного потока")).toBeInTheDocument();
+ await act(async () => oldPage.resolve([packet(80, "пакет-старого потока")]));
+
+ expect(screen.queryByText("пакет-старого потока")).not.toBeInTheDocument();
+ expect(screen.getByText("пакет выбранного потока")).toBeInTheDocument();
+ });
+});
diff --git a/components/packmate/frontend/src/App.tsx b/components/packmate/frontend/src/App.tsx
new file mode 100644
index 0000000..2334685
--- /dev/null
+++ b/components/packmate/frontend/src/App.tsx
@@ -0,0 +1,1224 @@
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import type { FormEvent, ReactNode } from "react";
+import { api, ApiError } from "./api";
+import { PacketView } from "./components/PacketView";
+import type {
+ CountersUpdate,
+ Pattern,
+ PatternActionType,
+ PatternDirectionType,
+ PatternInput,
+ PatternSearchType,
+ RouteState,
+ Service,
+ Stream,
+ SubscriptionMessage,
+} from "./types";
+
+type ServiceDialogState = { mode: "create" | "edit"; value: Service };
+type PatternDialogState = { mode: "create" | "edit"; value: PatternInput };
+
+const pageSizeStorageKey = "packmate.pageSize";
+const hexWidthStorageKey = "packmate.hexWidth";
+const lineBaseStorageKey = "packmate.lineBase";
+const hexdumpStorageKey = "packmate.hexdump";
+const themeStorageKey = "packmate.theme";
+const maxStreamsInMemory = 2000;
+
+function readNumber(key: string, fallback: number, minimum: number, maximum: number): number {
+ try {
+ const value = Number(localStorage.getItem(key));
+ return Number.isInteger(value) && value >= minimum && value <= maximum ? value : fallback;
+ } catch {
+ return fallback;
+ }
+}
+
+function readBoolean(key: string, fallback: boolean): boolean {
+ try {
+ const value = localStorage.getItem(key);
+ return value === null ? fallback : value === "true";
+ } catch {
+ return fallback;
+ }
+}
+
+function parseRoute(): RouteState {
+ const pieces = window.location.pathname.split("/").filter(Boolean);
+ const route: RouteState = {};
+ if (pieces[0] && /^\d+$/.test(pieces[0])) {
+ route.servicePort = Number(pieces[0]);
+ }
+ if (pieces[1] && /^\d+$/.test(pieces[1])) {
+ route.streamId = Number(pieces[1]);
+ }
+ const pattern = new URLSearchParams(window.location.search).get("pattern");
+ if (pattern && /^\d+$/.test(pattern)) {
+ route.patternId = Number(pattern);
+ }
+ return route;
+}
+
+function makePath(route: RouteState): string {
+ const path = route.servicePort === undefined
+ ? "/"
+ : route.streamId === undefined
+ ? `/${route.servicePort}`
+ : `/${route.servicePort}/${route.streamId}`;
+ return route.patternId === undefined ? path : `${path}?pattern=${route.patternId}`;
+}
+
+function emptyService(): Service {
+ return {
+ port: 0,
+ name: "",
+ decryptTls: false,
+ http: false,
+ urldecodeHttpRequests: false,
+ mergeAdjacentPackets: false,
+ parseWebSockets: false,
+ };
+}
+
+function emptyPattern(): PatternInput {
+ return {
+ name: "",
+ value: "",
+ color: "#ff5959",
+ searchType: "SUBSTRING",
+ directionType: "BOTH",
+ actionType: "FIND",
+ serviceId: null,
+ };
+}
+
+function isRecord(value: unknown): value is Record {
+ return typeof value === "object" && value !== null;
+}
+
+function errorText(error: unknown): string {
+ if (error instanceof ApiError) {
+ return error.message;
+ }
+ if (error instanceof Error && error.message === "Требуется войти в Packmate") {
+ return error.message;
+ }
+ if (error instanceof Error && error.message.startsWith("Ошибка сервера:")) {
+ return error.message;
+ }
+ return "Не удалось связаться с Packmate. Проверьте сервер и повторите попытку.";
+}
+
+function serviceName(services: Service[], port: number): string {
+ return services.find((service) => service.port === port)?.name ?? "Удаленный сервис";
+}
+
+function patternSummary(pattern: Pattern, services: Service[]): string {
+ const method = pattern.searchType === "REGEX"
+ ? `/${pattern.value}/`
+ : pattern.searchType === "SUBBYTES"
+ ? `0x${pattern.value}`
+ : `"${pattern.value}"`;
+ const action = pattern.actionType === "FIND" ? "подсвечивать" : "игнорировать";
+ const direction = pattern.directionType === "INPUT"
+ ? "в запросе"
+ : pattern.directionType === "OUTPUT"
+ ? "в ответе"
+ : "в запросе и ответе";
+ const service = pattern.serviceId === null
+ ? "для любого сервиса"
+ : `для ${serviceName(services, pattern.serviceId)} #${pattern.serviceId}`;
+ return `${method}; ${action} ${direction} ${service}`;
+}
+
+function streamMatches(stream: Stream, query: string, services: Service[]): boolean {
+ if (!query.trim()) {
+ return true;
+ }
+ const haystack = [
+ String(stream.id),
+ stream.protocol,
+ String(stream.service),
+ serviceName(services, stream.service),
+ stream.userAgentHash ?? "",
+ ].join(" ").toLocaleLowerCase("ru-RU");
+ return haystack.includes(query.trim().toLocaleLowerCase("ru-RU"));
+}
+
+function App() {
+ const [route, setRoute] = useState(parseRoute);
+ const [services, setServices] = useState([]);
+ const [patterns, setPatterns] = useState([]);
+ const [streams, setStreams] = useState([]);
+ const [packets, setPackets] = useState([]);
+ const [streamHasMore, setStreamHasMore] = useState(false);
+ const [packetHasMore, setPacketHasMore] = useState(false);
+ const [streamsLoading, setStreamsLoading] = useState(true);
+ const [packetsLoading, setPacketsLoading] = useState(false);
+ const [moreStreamsLoading, setMoreStreamsLoading] = useState(false);
+ const [morePacketsLoading, setMorePacketsLoading] = useState(false);
+ const [favoritesOnly, setFavoritesOnly] = useState(false);
+ const [pauseNewStreams, setPauseNewStreams] = useState(false);
+ const [hexdumpMode, setHexdumpMode] = useState(() => readBoolean(hexdumpStorageKey, false));
+ const [hexWidth, setHexWidth] = useState(() => readNumber(hexWidthStorageKey, 16, 1, 128));
+ const [lineBase, setLineBase] = useState(() => readNumber(lineBaseStorageKey, 10, 10, 16));
+ const [pageSize, setPageSize] = useState(() => readNumber(pageSizeStorageKey, 100, 10, 500));
+ const [theme, setTheme] = useState(() => {
+ try {
+ return localStorage.getItem(themeStorageKey) === "dark" ? "dark" : "light";
+ } catch {
+ return "light";
+ }
+ });
+ const [searchText, setSearchText] = useState("");
+ const [serviceDialog, setServiceDialog] = useState(null);
+ const [patternDialog, setPatternDialog] = useState(null);
+ const [lookBackPattern, setLookBackPattern] = useState(null);
+ const [lookBackMinutes, setLookBackMinutes] = useState(5);
+ const [settingsOpen, setSettingsOpen] = useState(false);
+ const [pcapStarted, setPcapStarted] = useState(true);
+ const [notice, setNotice] = useState("");
+ const [browsingHistory, setBrowsingHistory] = useState(false);
+ const [socketStatus, setSocketStatus] = useState("Подключение к событиям...");
+ const [counters, setCounters] = useState({
+ totalPackets: 0,
+ totalStreams: 0,
+ servicesPackets: {},
+ servicesStreams: {},
+ });
+ const [refreshKey, setRefreshKey] = useState(0);
+ const streamPageLock = useRef(null);
+ const packetPageLock = useRef(null);
+ const streamPageController = useRef(null);
+ const packetPageController = useRef(null);
+ const historyWindowRef = useRef(false);
+ const streamListRef = useRef(null);
+ const streamsRef = useRef([]);
+ const contextRef = useRef({ route, favoritesOnly, pauseNewStreams });
+ const streamQueryKey = JSON.stringify([
+ route.servicePort ?? null,
+ route.patternId ?? null,
+ favoritesOnly,
+ pageSize,
+ refreshKey,
+ ]);
+ const packetQueryKey = JSON.stringify([route.streamId ?? null, pageSize]);
+ const streamQueryKeyRef = useRef(streamQueryKey);
+ const packetQueryKeyRef = useRef(packetQueryKey);
+
+ contextRef.current = { route, favoritesOnly, pauseNewStreams };
+ streamsRef.current = streams;
+ streamQueryKeyRef.current = streamQueryKey;
+ packetQueryKeyRef.current = packetQueryKey;
+
+ const goTo = useCallback((next: RouteState) => {
+ const path = makePath(next);
+ if (path !== `${window.location.pathname}${window.location.search}`) {
+ window.history.pushState({}, "", path);
+ }
+ setRoute(next);
+ }, []);
+
+ const refreshServices = useCallback(async () => {
+ try {
+ setServices(await api.services());
+ } catch (error) {
+ setNotice(errorText(error));
+ }
+ }, []);
+
+ const refreshPatterns = useCallback(async () => {
+ try {
+ setPatterns(await api.patterns());
+ } catch (error) {
+ setNotice(errorText(error));
+ }
+ }, []);
+
+ useEffect(() => {
+ const onPopState = () => setRoute(parseRoute());
+ window.addEventListener("popstate", onPopState);
+ return () => window.removeEventListener("popstate", onPopState);
+ }, []);
+
+ useEffect(() => {
+ document.documentElement.dataset.theme = theme;
+ try {
+ localStorage.setItem(themeStorageKey, theme);
+ } catch {
+ setNotice("Браузер не сохраняет локальные настройки.");
+ }
+ }, [theme]);
+
+ useEffect(() => {
+ for (const [key, value] of [
+ [pageSizeStorageKey, pageSize],
+ [hexWidthStorageKey, hexWidth],
+ [lineBaseStorageKey, lineBase],
+ [hexdumpStorageKey, hexdumpMode],
+ ] as const) {
+ try {
+ localStorage.setItem(key, String(value));
+ } catch {
+ setNotice("Браузер не сохраняет локальные настройки.");
+ break;
+ }
+ }
+ }, [hexWidth, hexdumpMode, lineBase, pageSize]);
+
+ useEffect(() => {
+ void refreshServices();
+ void refreshPatterns();
+ void api.pcapStarted().then(setPcapStarted).catch((error: unknown) => setNotice(errorText(error)));
+ }, [refreshPatterns, refreshServices]);
+
+ useEffect(() => {
+ streamPageController.current?.abort();
+ streamPageController.current = null;
+ streamPageLock.current = null;
+ historyWindowRef.current = false;
+ setBrowsingHistory(false);
+ setMoreStreamsLoading(false);
+
+ const controller = new AbortController();
+ const queryKey = streamQueryKey;
+ setStreams([]);
+ setStreamHasMore(false);
+ setStreamsLoading(true);
+ void api.streams(route.servicePort, {
+ startingFrom: null,
+ pageSize,
+ pattern: route.patternId === undefined ? null : { id: route.patternId },
+ favorites: favoritesOnly,
+ }, controller.signal)
+ .then((page) => {
+ if (controller.signal.aborted || streamQueryKeyRef.current !== queryKey) {
+ return;
+ }
+ setStreams(page);
+ setStreamHasMore(page.length === pageSize);
+ })
+ .catch((error: unknown) => {
+ if (!controller.signal.aborted && streamQueryKeyRef.current === queryKey
+ && !(error instanceof DOMException && error.name === "AbortError")) {
+ setNotice(errorText(error));
+ }
+ })
+ .finally(() => {
+ if (!controller.signal.aborted && streamQueryKeyRef.current === queryKey) {
+ setStreamsLoading(false);
+ }
+ });
+ return () => {
+ controller.abort();
+ streamPageController.current?.abort();
+ };
+ }, [favoritesOnly, pageSize, refreshKey, route.patternId, route.servicePort, streamQueryKey]);
+
+ useEffect(() => {
+ packetPageController.current?.abort();
+ packetPageController.current = null;
+ packetPageLock.current = null;
+ setMorePacketsLoading(false);
+
+ if (route.streamId === undefined) {
+ setPackets([]);
+ setPacketHasMore(false);
+ setPacketsLoading(false);
+ return;
+ }
+ const controller = new AbortController();
+ const queryKey = packetQueryKey;
+ setPackets([]);
+ setPacketsLoading(true);
+ setPacketHasMore(false);
+ void api.packets(route.streamId, { startingFrom: null, pageSize }, controller.signal)
+ .then((page) => {
+ if (controller.signal.aborted || packetQueryKeyRef.current !== queryKey) {
+ return;
+ }
+ setPackets(page);
+ setPacketHasMore(page.length === pageSize);
+ })
+ .catch((error: unknown) => {
+ if (!controller.signal.aborted && packetQueryKeyRef.current === queryKey
+ && !(error instanceof DOMException && error.name === "AbortError")) {
+ setNotice(errorText(error));
+ }
+ })
+ .finally(() => {
+ if (!controller.signal.aborted && packetQueryKeyRef.current === queryKey) {
+ setPacketsLoading(false);
+ }
+ });
+ return () => {
+ controller.abort();
+ packetPageController.current?.abort();
+ };
+ }, [pageSize, packetQueryKey, route.streamId]);
+
+ const loadMoreStreams = useCallback(async () => {
+ const latest = streamsRef.current.at(-1);
+ const queryKey = streamQueryKeyRef.current;
+ const routeSnapshot = contextRef.current.route;
+ const favoritesSnapshot = contextRef.current.favoritesOnly;
+ if (!streamHasMore || streamPageLock.current === queryKey || !latest) {
+ return;
+ }
+ streamPageLock.current = queryKey;
+ const controller = new AbortController();
+ streamPageController.current = controller;
+ setMoreStreamsLoading(true);
+ try {
+ const page = await api.streams(routeSnapshot.servicePort, {
+ startingFrom: latest.id,
+ pageSize,
+ pattern: routeSnapshot.patternId === undefined
+ ? null
+ : { id: routeSnapshot.patternId },
+ favorites: favoritesSnapshot,
+ }, controller.signal);
+ if (controller.signal.aborted || streamQueryKeyRef.current !== queryKey) {
+ return;
+ }
+ const currentIds = new Set(streamsRef.current.map((stream) => stream.id));
+ const unique = page.filter((stream) => !currentIds.has(stream.id));
+ if (streamsRef.current.length + unique.length > maxStreamsInMemory) {
+ historyWindowRef.current = true;
+ setBrowsingHistory(true);
+ }
+ setStreams((current) => {
+ if (streamQueryKeyRef.current !== queryKey) {
+ return current;
+ }
+ const combined = [...current, ...unique];
+ if (combined.length > maxStreamsInMemory) {
+ return combined.slice(-maxStreamsInMemory);
+ }
+ return combined;
+ });
+ setStreamHasMore(unique.length > 0 && page.length === pageSize);
+ } catch (error) {
+ if (!controller.signal.aborted && streamQueryKeyRef.current === queryKey) {
+ setNotice(errorText(error));
+ }
+ } finally {
+ if (streamPageController.current === controller) {
+ streamPageController.current = null;
+ }
+ if (streamPageLock.current === queryKey) {
+ streamPageLock.current = null;
+ if (streamQueryKeyRef.current === queryKey) {
+ setMoreStreamsLoading(false);
+ }
+ }
+ }
+ }, [pageSize, streamHasMore]);
+
+ const loadMorePackets = useCallback(async () => {
+ const latest = packets.at(-1);
+ const queryKey = packetQueryKeyRef.current;
+ if (route.streamId === undefined || !packetHasMore
+ || packetPageLock.current === queryKey || !latest) {
+ return;
+ }
+ packetPageLock.current = queryKey;
+ const controller = new AbortController();
+ packetPageController.current = controller;
+ setMorePacketsLoading(true);
+ try {
+ const page = await api.packets(route.streamId, { startingFrom: latest.id, pageSize }, controller.signal);
+ if (controller.signal.aborted || packetQueryKeyRef.current !== queryKey) {
+ return;
+ }
+ const currentIds = new Set(packets.map((packet) => packet.id));
+ const unique = page.filter((packet) => !currentIds.has(packet.id));
+ setPackets((current) => packetQueryKeyRef.current === queryKey ? [...current, ...unique] : current);
+ setPacketHasMore(unique.length > 0 && page.length === pageSize);
+ } catch (error) {
+ if (!controller.signal.aborted && packetQueryKeyRef.current === queryKey) {
+ setNotice(errorText(error));
+ }
+ } finally {
+ if (packetPageController.current === controller) {
+ packetPageController.current = null;
+ }
+ if (packetPageLock.current === queryKey) {
+ packetPageLock.current = null;
+ if (packetQueryKeyRef.current === queryKey) {
+ setMorePacketsLoading(false);
+ }
+ }
+ }
+ }, [packetHasMore, packets, pageSize, route.streamId]);
+
+ const handleSocketMessage = useCallback((message: MessageEvent) => {
+ let event: SubscriptionMessage;
+ try {
+ event = JSON.parse(message.data) as SubscriptionMessage;
+ } catch {
+ setNotice("Получено некорректное сообщение от сервера.");
+ return;
+ }
+ const context = contextRef.current;
+ switch (event.type) {
+ case "NEW_STREAM": {
+ if (!isRecord(event.value) || typeof event.value.id !== "number") {
+ return;
+ }
+ const stream = event.value as unknown as Stream;
+ if (context.pauseNewStreams || (context.route.servicePort !== undefined && stream.service !== context.route.servicePort)) {
+ return;
+ }
+ if (context.favoritesOnly && !stream.favorite) {
+ return;
+ }
+ if (context.route.patternId !== undefined && !stream.foundPatternsIds.includes(context.route.patternId)) {
+ return;
+ }
+ if (historyWindowRef.current) {
+ setNotice((current) => current || "Вы просматриваете историю. Вернитесь к новым потокам, чтобы следить за текущими.");
+ return;
+ }
+ setStreams((current) => [stream, ...current.filter((item) => item.id !== stream.id)]
+ .slice(0, maxStreamsInMemory));
+ break;
+ }
+ case "SAVE_SERVICE":
+ case "DELETE_SERVICE":
+ void refreshServices();
+ break;
+ case "SAVE_PATTERN":
+ void refreshPatterns();
+ break;
+ case "ENABLE_PATTERN":
+ case "DISABLE_PATTERN": {
+ const id = typeof event.value === "number" ? event.value : Number(event.value);
+ if (Number.isInteger(id)) {
+ setPatterns((current) => current.map((pattern) =>
+ pattern.id === id ? { ...pattern, enabled: event.type === "ENABLE_PATTERN" } : pattern,
+ ));
+ }
+ break;
+ }
+ case "COUNTERS_UPDATE":
+ if (isRecord(event.value)) {
+ setCounters(event.value as unknown as CountersUpdate);
+ }
+ break;
+ case "PCAP_STARTED":
+ setPcapStarted(true);
+ setNotice("Обработка PCAP-файла началась.");
+ break;
+ case "PCAP_STOPPED":
+ setPcapStarted(false);
+ setNotice("Обработка PCAP завершена.");
+ break;
+ case "FINISH_LOOKBACK":
+ setNotice("Поиск в старых потоках завершен.");
+ setRefreshKey((current) => current + 1);
+ break;
+ default:
+ break;
+ }
+ }, [refreshPatterns, refreshServices]);
+
+ const socketMessageRef = useRef(handleSocketMessage);
+ socketMessageRef.current = handleSocketMessage;
+
+ useEffect(() => {
+ let disposed = false;
+ let socket: WebSocket | undefined;
+ let reconnectTimer: number | undefined;
+
+ const connect = () => {
+ if (disposed) {
+ return;
+ }
+ setSocketStatus("Подключение к событиям...");
+ const protocol = window.location.protocol === "https:" ? "wss:" : "ws:";
+ socket = new WebSocket(`${protocol}//${window.location.host}/api/ws`);
+ socket.onopen = () => setSocketStatus("События подключены");
+ socket.onmessage = (event) => socketMessageRef.current(event);
+ socket.onerror = () => setSocketStatus("Ожидание повторного подключения...");
+ socket.onclose = () => {
+ if (disposed) {
+ return;
+ }
+ setSocketStatus("Связь с событиями прервана; повторное подключение...");
+ reconnectTimer = window.setTimeout(connect, 3000);
+ };
+ };
+
+ connect();
+ return () => {
+ disposed = true;
+ if (reconnectTimer !== undefined) {
+ window.clearTimeout(reconnectTimer);
+ }
+ socket?.close();
+ };
+ }, []);
+
+ const visibleStreams = useMemo(
+ () => streams.filter((stream) => streamMatches(stream, searchText, services)),
+ [searchText, services, streams],
+ );
+ const selectedStream = streams.find((stream) => stream.id === route.streamId);
+ const selectedPattern = patterns.find((pattern) => pattern.id === route.patternId);
+ const activePatterns = patterns.filter((pattern) => !pattern.deleted);
+ const serviceByPort = useMemo(() => new Map(services.map((service) => [service.port, service])), [services]);
+ const streamsPerMinute = counters.totalStreams ?? 0;
+ const packetsPerStream = streamsPerMinute === 0
+ ? 0
+ : Math.round((counters.totalPackets / streamsPerMinute + Number.EPSILON) * 10) / 10;
+
+ const showServiceDialog = (service?: Service) => {
+ setServiceDialog(service
+ ? { mode: "edit", value: { ...service } }
+ : { mode: "create", value: emptyService() });
+ };
+
+ const showPatternDialog = (pattern?: Pattern) => {
+ setPatternDialog(pattern
+ ? { mode: "edit", value: { ...pattern } }
+ : { mode: "create", value: emptyPattern() });
+ };
+
+ const saveService = async (service: Service) => {
+ try {
+ if (serviceDialog?.mode === "edit") {
+ await api.updateService(serviceDialog.value.port, service);
+ } else {
+ await api.createService(service);
+ }
+ setServiceDialog(null);
+ await refreshServices();
+ setNotice(serviceDialog?.mode === "edit" ? "Сервис обновлен." : "Сервис создан.");
+ } catch (error) {
+ setNotice(errorText(error));
+ }
+ };
+
+ const deleteService = async (service: Service) => {
+ if (!window.confirm(`Удалить сервис "${service.name}" и его фильтр?`)) {
+ return;
+ }
+ try {
+ await api.deleteService(service.port);
+ setServiceDialog(null);
+ await refreshServices();
+ if (route.servicePort === service.port) {
+ goTo({ patternId: route.patternId });
+ }
+ setNotice("Сервис удален.");
+ } catch (error) {
+ setNotice(errorText(error));
+ }
+ };
+
+ const savePattern = async (pattern: PatternInput) => {
+ try {
+ if (patternDialog?.mode === "edit" && pattern.id !== undefined) {
+ await api.updatePattern(pattern.id, { name: pattern.name, color: pattern.color });
+ } else {
+ await api.createPattern(pattern);
+ }
+ setPatternDialog(null);
+ await refreshPatterns();
+ setNotice(patternDialog?.mode === "edit" ? "Паттерн обновлен." : "Паттерн создан.");
+ } catch (error) {
+ setNotice(errorText(error));
+ }
+ };
+
+ const togglePattern = async (pattern: Pattern) => {
+ try {
+ await api.setPatternEnabled(pattern.id, !pattern.enabled);
+ setPatterns((current) => current.map((item) => item.id === pattern.id
+ ? { ...item, enabled: !pattern.enabled }
+ : item));
+ setNotice(pattern.enabled ? "Паттерн приостановлен." : "Паттерн включен.");
+ } catch (error) {
+ setNotice(errorText(error));
+ }
+ };
+
+ const deletePattern = async (pattern: Pattern) => {
+ if (!window.confirm(`Удалить паттерн "${pattern.name}"?`)) {
+ return;
+ }
+ try {
+ await api.deletePattern(pattern.id);
+ await refreshPatterns();
+ if (route.patternId === pattern.id) {
+ goTo({ servicePort: route.servicePort });
+ }
+ setNotice("Паттерн удален.");
+ } catch (error) {
+ setNotice(errorText(error));
+ }
+ };
+
+ const openPattern = (pattern: Pattern) => {
+ if (pattern.actionType === "FIND") {
+ goTo({ servicePort: route.servicePort, patternId: pattern.id });
+ }
+ };
+
+ const toggleFavorite = async (stream: Stream) => {
+ try {
+ await api.setFavorite(stream.id, !stream.favorite);
+ setStreams((current) => current.map((item) => item.id === stream.id
+ ? { ...item, favorite: !stream.favorite }
+ : item));
+ if (favoritesOnly && stream.favorite) {
+ setRefreshKey((current) => current + 1);
+ }
+ } catch (error) {
+ setNotice(errorText(error));
+ }
+ };
+
+ const startPcap = async () => {
+ setPcapStarted(true);
+ try {
+ await api.startPcap();
+ setNotice("Команда запуска PCAP отправлена.");
+ } catch (error) {
+ setPcapStarted(false);
+ setNotice(errorText(error));
+ }
+ };
+
+ const runLookBack = async (event: FormEvent) => {
+ event.preventDefault();
+ if (lookBackPattern === null || lookBackMinutes < 1) {
+ return;
+ }
+ try {
+ await api.lookBack(lookBackPattern, lookBackMinutes);
+ setLookBackPattern(null);
+ setNotice("Поиск в старых потоках запущен.");
+ } catch (error) {
+ setNotice(errorText(error));
+ }
+ };
+
+ const goToStream = (stream: Stream) => {
+ goTo({ servicePort: stream.service, streamId: stream.id, patternId: route.patternId });
+ };
+
+ useEffect(() => {
+ const onKeyDown = (event: KeyboardEvent) => {
+ if (!event.ctrlKey || ["INPUT", "TEXTAREA", "SELECT"].includes((event.target as HTMLElement | null)?.tagName ?? "")) {
+ return;
+ }
+ const currentIndex = visibleStreams.findIndex((stream) => stream.id === route.streamId);
+ let next: Stream | undefined;
+ if (event.key === "ArrowUp") {
+ event.preventDefault();
+ next = visibleStreams[currentIndex - 1];
+ } else if (event.key === "ArrowDown") {
+ event.preventDefault();
+ next = visibleStreams[currentIndex + 1];
+ } else if (event.key === "Home") {
+ next = visibleStreams[0];
+ } else if (event.key === "End") {
+ next = visibleStreams.at(-1);
+ }
+ if (next) {
+ goToStream(next);
+ window.setTimeout(() => document.getElementById(`stream-${next?.id}`)?.scrollIntoView({
+ behavior: "smooth",
+ block: "center",
+ }), 0);
+ }
+ };
+ window.addEventListener("keydown", onKeyDown);
+ return () => window.removeEventListener("keydown", onKeyDown);
+ }, [goToStream, route.streamId, visibleStreams]);
+
+ const favoriteCount = streams.filter((stream) => stream.favorite).length;
+ const returnToLatest = () => {
+ historyWindowRef.current = false;
+ setBrowsingHistory(false);
+ setRefreshKey((current) => current + 1);
+ };
+
+ return (
+
+
+
+
+
+
+
+ {notice && (
+
+ {notice}
+
+
+ )}
+
+ Запрос
+ ,
+ ответ
+ {socketStatus}
+
+
+ {selectedStream && (
+
+ Поток #{selectedStream.id}
+ {selectedStream.protocol} / {serviceByPort.get(selectedStream.service)?.name ?? "Удаленный сервис"} #{selectedStream.service}
+ {selectedStream.sizeBytes} байт, {selectedStream.packetsCount} пакетов
+
+ )}
+ {route.streamId === undefined && Выберите поток слева, чтобы посмотреть пакеты.
}
+ {route.streamId !== undefined && packetsLoading && Загрузка пакетов...
}
+ {route.streamId !== undefined && !packetsLoading && packets.length === 0 && В этом потоке пока нет пакетов.
}
+ {packets.map((packet, index) => (
+
+ ))}
+ {packetHasMore && (
+
+ )}
+ {route.streamId !== undefined && !packetHasMore && packets.length > 0 && Больше пакетов нет
}
+
+
+
+ {serviceDialog && (
+
setServiceDialog(null)}
+ onSave={(service) => void saveService(service)}
+ onDelete={(service) => void deleteService(service)}
+ />
+ )}
+ {patternDialog && (
+ setPatternDialog(null)}
+ onSave={(pattern) => void savePattern(pattern)}
+ />
+ )}
+ {lookBackPattern !== null && (
+ setLookBackPattern(null)}>
+
+
+ )}
+ {settingsOpen && (
+ setSettingsOpen(false)}>
+
+
+
+
+
+
+
+
+
+ )}
+
+
+ );
+}
+
+function readInputNumber(value: string, fallback: number, minimum: number, maximum: number): number {
+ if (value === "") {
+ return fallback;
+ }
+ const parsed = Number(value);
+ return Number.isInteger(parsed) && parsed >= minimum && parsed <= maximum ? parsed : fallback;
+}
+
+interface OverlayProps {
+ title: string;
+ children: ReactNode;
+ onClose: () => void;
+}
+
+function Overlay({ title, children, onClose }: OverlayProps) {
+ useEffect(() => {
+ const onKeyDown = (event: KeyboardEvent) => {
+ if (event.key === "Escape") {
+ onClose();
+ }
+ };
+ window.addEventListener("keydown", onKeyDown);
+ return () => window.removeEventListener("keydown", onKeyDown);
+ }, [onClose]);
+
+ return (
+ {
+ if (event.target === event.currentTarget) {
+ onClose();
+ }
+ }}>
+
+
+ );
+}
+
+interface ServiceDialogProps {
+ state: ServiceDialogState;
+ onClose: () => void;
+ onSave: (service: Service) => void;
+ onDelete: (service: Service) => void;
+}
+
+function ServiceDialog({ state, onClose, onSave, onDelete }: ServiceDialogProps) {
+ const [service, setService] = useState(state.value);
+ useEffect(() => setService(state.value), [state.value]);
+ const updateBoolean = (field: keyof Service, checked: boolean) => {
+ setService((current) => ({ ...current, [field]: checked }));
+ };
+
+ return (
+
+
+
+ );
+}
+
+interface PatternDialogProps {
+ state: PatternDialogState;
+ services: Service[];
+ onClose: () => void;
+ onSave: (pattern: PatternInput) => void;
+}
+
+function PatternDialog({ state, services, onClose, onSave }: PatternDialogProps) {
+ const [pattern, setPattern] = useState(state.value);
+ const [validationMessage, setValidationMessage] = useState("");
+ useEffect(() => {
+ setPattern(state.value);
+ setValidationMessage("");
+ }, [state.value]);
+
+ const setField = (field: K, value: PatternInput[K]) => {
+ setPattern((current) => ({ ...current, [field]: value }));
+ };
+
+ const submit = (event: FormEvent) => {
+ event.preventDefault();
+ if (state.mode === "create" && pattern.searchType === "SUBBYTES") {
+ const normalized = pattern.value.replace(/\s+/g, "");
+ if (!/^(?:[\da-f]{2})+$/i.test(normalized)) {
+ setValidationMessage("Введите непустую последовательность байтов: пары шестнадцатеричных цифр.");
+ return;
+ }
+ onSave({ ...pattern, value: normalized.toLowerCase() });
+ return;
+ }
+ onSave(pattern);
+ };
+
+ return (
+
+
+
+ );
+}
+
+export default App;
diff --git a/components/packmate/frontend/src/api.ts b/components/packmate/frontend/src/api.ts
new file mode 100644
index 0000000..ba3ae97
--- /dev/null
+++ b/components/packmate/frontend/src/api.ts
@@ -0,0 +1,95 @@
+import type {
+ Packet,
+ Pattern,
+ PatternInput,
+ Service,
+ Stream,
+} from "./types";
+
+const apiRoot = "/api";
+
+export class ApiError extends Error {
+ readonly status: number;
+
+ constructor(status: number, serverMessage?: string) {
+ super(status === 401 ? "Требуется войти в Packmate" : serverMessage ?? `Ошибка сервера: ${status}`);
+ this.name = "ApiError";
+ this.status = status;
+ }
+}
+
+async function request(path: string, init: RequestInit = {}): Promise {
+ const headers = new Headers(init.headers);
+ if (init.body !== undefined && !headers.has("Content-Type")) {
+ headers.set("Content-Type", "application/json");
+ }
+
+ const response = await fetch(`${apiRoot}/${path.replace(/^\/+/, "")}`, {
+ ...init,
+ headers,
+ credentials: "same-origin",
+ });
+
+ if (!response.ok) {
+ let serverMessage: string | undefined;
+ if (response.status >= 400 && response.status < 500
+ && response.headers.get("Content-Type")?.includes("application/json")) {
+ try {
+ const body: unknown = await response.json();
+ if (typeof body === "object" && body !== null && "message" in body
+ && typeof body.message === "string") {
+ serverMessage = body.message.slice(0, 240);
+ }
+ } catch {
+ serverMessage = undefined;
+ }
+ }
+ throw new ApiError(response.status, serverMessage);
+ }
+ if (response.status === 204) {
+ return undefined as T;
+ }
+
+ const text = await response.text();
+ if (text.length === 0) {
+ return undefined as T;
+ }
+ return JSON.parse(text) as T;
+}
+
+function post(path: string, body?: unknown, signal?: AbortSignal): Promise {
+ return request(path, {
+ method: "POST",
+ body: body === undefined ? undefined : JSON.stringify(body),
+ signal,
+ });
+}
+
+export const api = {
+ services: () => request("service/"),
+ createService: (service: Service) => post("service/", service),
+ updateService: (port: number, service: Service) => post(`service/${port}`, service),
+ deleteService: (port: number) => request(`service/${port}`, { method: "DELETE" }),
+ patterns: () => request("pattern/"),
+ createPattern: (pattern: PatternInput) => post("pattern/", pattern),
+ updatePattern: (id: number, pattern: Pick) =>
+ post(`pattern/${id}`, pattern),
+ setPatternEnabled: (id: number, enabled: boolean) =>
+ post(`pattern/${id}/enable?enabled=${String(enabled)}`),
+ deletePattern: (id: number) => request(`pattern/${id}`, { method: "DELETE" }),
+ lookBack: (id: number, minutes: number) => post(`pattern/${id}/lookback`, minutes),
+ streams: (
+ servicePort: number | undefined,
+ payload: { startingFrom: number | null; pageSize: number; pattern: { id: number } | null; favorites: boolean },
+ signal?: AbortSignal,
+ ) => post(`stream/${servicePort ?? "all"}`, payload, signal),
+ packets: (
+ streamId: number,
+ payload: { startingFrom: number | null; pageSize: number },
+ signal?: AbortSignal,
+ ) => post(`packet/${streamId}`, payload, signal),
+ setFavorite: (streamId: number, favorite: boolean) =>
+ post(`stream/${streamId}/${favorite ? "favorite" : "unfavorite"}`),
+ pcapStarted: () => request("pcap/started"),
+ startPcap: () => post("pcap/start"),
+};
diff --git a/components/packmate/frontend/src/components/PacketView.tsx b/components/packmate/frontend/src/components/PacketView.tsx
new file mode 100644
index 0000000..52253f1
--- /dev/null
+++ b/components/packmate/frontend/src/components/PacketView.tsx
@@ -0,0 +1,106 @@
+import { useMemo } from "react";
+import { decodePacket, hexDump, packetSegments, packetText, pythonBytes, safePatternColor } from "../packet";
+import type { Packet, Pattern } from "../types";
+
+interface PacketViewProps {
+ packet: Packet;
+ previous?: Packet;
+ patterns: Pattern[];
+ hexdumpMode: boolean;
+ blockSize: number;
+ lineNumberBase: number;
+ notify: (message: string) => void;
+}
+
+function dateText(timestamp: number): string {
+ return new Intl.DateTimeFormat("ru-RU", {
+ dateStyle: "short",
+ timeStyle: "medium",
+ }).format(new Date(timestamp));
+}
+
+async function copyText(value: string): Promise {
+ if (navigator.clipboard?.writeText) {
+ await navigator.clipboard.writeText(value);
+ return;
+ }
+ const field = document.createElement("textarea");
+ field.value = value;
+ field.setAttribute("readonly", "");
+ field.style.position = "fixed";
+ field.style.opacity = "0";
+ document.body.append(field);
+ field.select();
+ const copied = document.execCommand("copy");
+ field.remove();
+ if (!copied) {
+ throw new Error("Буфер обмена недоступен");
+ }
+}
+
+export function PacketView({
+ packet,
+ previous,
+ patterns,
+ hexdumpMode,
+ blockSize,
+ lineNumberBase,
+ notify,
+}: PacketViewProps) {
+ const bytes = useMemo(() => decodePacket(packet.content), [packet.content]);
+ const segments = useMemo(() => packetSegments(packet, patterns), [packet, patterns]);
+ const body = useMemo(
+ () => hexdumpMode ? hexDump(bytes, blockSize, lineNumberBase) : packetText(bytes),
+ [bytes, blockSize, hexdumpMode, lineNumberBase],
+ );
+ const flags = [
+ packet.ungzipped ? "GZIP" : "",
+ packet.webSocketParsed ? "WS" : "",
+ packet.tlsDecrypted ? "TLS" : "",
+ ].filter(Boolean);
+
+ const copy = async (value: string, label: string) => {
+ try {
+ await copyText(value);
+ notify(`${label}: скопировано`);
+ } catch {
+ notify("Не удалось скопировать данные");
+ }
+ };
+
+ return (
+
+
+
+ #{packet.id}
+
+ {previous && +{packet.timestamp - previous.timestamp} мс}
+ {packet.incoming ? "Запрос" : "Ответ"}
+ {flags.map((flag) => {flag})}
+
+
+
+
+
+
+
+
+ {hexdumpMode
+ ? body
+ : segments.map((segment, index) => segment.pattern
+ ? {segment.text}
+ : {segment.text})}
+
+
+ );
+}
+
+function bytesToHex(bytes: Uint8Array): string {
+ return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
+}
diff --git a/components/packmate/frontend/src/main.tsx b/components/packmate/frontend/src/main.tsx
new file mode 100644
index 0000000..1cba43b
--- /dev/null
+++ b/components/packmate/frontend/src/main.tsx
@@ -0,0 +1,15 @@
+import { StrictMode } from "react";
+import { createRoot } from "react-dom/client";
+import App from "./App";
+import "./styles.css";
+
+const root = document.getElementById("root");
+if (!root) {
+ throw new Error("Не найден корневой элемент интерфейса Packmate");
+}
+
+createRoot(root).render(
+
+
+ ,
+);
diff --git a/components/packmate/frontend/src/packet.test.tsx b/components/packmate/frontend/src/packet.test.tsx
new file mode 100644
index 0000000..84316ed
--- /dev/null
+++ b/components/packmate/frontend/src/packet.test.tsx
@@ -0,0 +1,79 @@
+import { render, screen } from "@testing-library/react";
+import { describe, expect, it } from "vitest";
+import { PacketView } from "./components/PacketView";
+import { decodePacket, hexDump, packetSegments } from "./packet";
+import type { Packet, Pattern } from "./types";
+
+const pattern: Pattern = {
+ id: 3,
+ enabled: true,
+ deleted: false,
+ name: "Маркер",
+ value: "secret",
+ color: "#ff5959",
+ searchType: "SUBSTRING",
+ directionType: "BOTH",
+ actionType: "FIND",
+ serviceId: null,
+};
+
+function packet(text: string): Packet {
+ return {
+ id: 8,
+ matches: [],
+ timestamp: 1_700_000_000_000,
+ incoming: true,
+ ungzipped: false,
+ webSocketParsed: false,
+ tlsDecrypted: false,
+ hasHttpBody: false,
+ content: btoa(String.fromCharCode(...new TextEncoder().encode(text))),
+ };
+}
+
+describe("отображение содержимого пакета", () => {
+ it("подсвечивает диапазон совпадения без преобразования байтового содержимого в HTML", () => {
+ const value = packet("до secret после ");
+ value.matches = [{ patternId: pattern.id, startPosition: 3, endPosition: 8 }];
+
+ const segments = packetSegments(value, [pattern]);
+ expect(segments).toEqual([
+ { text: "до " },
+ { text: "secret", pattern },
+ { text: " после " },
+ ]);
+
+ const view = render( undefined}
+ />);
+ expect(screen.getByText("secret").tagName).toBe("MARK");
+ expect(view.container.querySelector("script")).toBeNull();
+ expect(view.container.textContent).toContain("");
+ });
+
+ it("считает диапазон SUBBYTES в байтах, а не UTF-16 позициях", () => {
+ const bytes = new TextEncoder().encode("Жx");
+ const value: Packet = {
+ ...packet(""),
+ content: btoa(String.fromCharCode(...bytes)),
+ matches: [{ patternId: 3, startPosition: 2, endPosition: 2 }],
+ };
+ const bytePattern = { ...pattern, searchType: "SUBBYTES" as const, value: "78" };
+
+ expect(packetSegments(value, [bytePattern])).toEqual([
+ { text: "Ж" },
+ { text: "x", pattern: bytePattern },
+ ]);
+ });
+
+ it("строит читаемые строки HEX-дампа с выбранной шириной", () => {
+ expect(hexDump(decodePacket("AQIDBA=="), 2, 16)).toBe(
+ "0000000000: 01 02 |..|\n0000000002: 03 04 |..|",
+ );
+ });
+});
diff --git a/components/packmate/frontend/src/packet.ts b/components/packmate/frontend/src/packet.ts
new file mode 100644
index 0000000..eebe3a8
--- /dev/null
+++ b/components/packmate/frontend/src/packet.ts
@@ -0,0 +1,102 @@
+import type { FoundPattern, Packet, Pattern, PatternSearchType } from "./types";
+
+export interface TextSegment {
+ text: string;
+ pattern?: Pattern;
+}
+
+export function decodePacket(content: string): Uint8Array {
+ const binary = atob(content);
+ const bytes = new Uint8Array(binary.length);
+ for (let index = 0; index < binary.length; index += 1) {
+ bytes[index] = binary.charCodeAt(index);
+ }
+ return bytes;
+}
+
+export function packetText(bytes: Uint8Array): string {
+ return new TextDecoder("utf-8", { fatal: false }).decode(bytes);
+}
+
+function rangeForMatch(
+ bytes: Uint8Array,
+ match: FoundPattern,
+ searchType: PatternSearchType,
+): [number, number] {
+ if (searchType !== "SUBBYTES") {
+ return [match.startPosition, match.endPosition + 1];
+ }
+
+ const start = Math.max(0, Math.min(bytes.length, match.startPosition));
+ const end = Math.max(start, Math.min(bytes.length, match.endPosition + 1));
+ return [packetText(bytes.subarray(0, start)).length, packetText(bytes.subarray(0, end)).length];
+}
+
+export function packetSegments(packet: Packet, patterns: Pattern[]): TextSegment[] {
+ const bytes = decodePacket(packet.content);
+ const text = packetText(bytes);
+ const byId = new Map(patterns.map((pattern) => [pattern.id, pattern]));
+ const ranges = packet.matches
+ .flatMap((match) => {
+ const pattern = byId.get(match.patternId);
+ if (!pattern || pattern.deleted || pattern.actionType !== "FIND") {
+ return [];
+ }
+ const [start, end] = rangeForMatch(bytes, match, pattern.searchType);
+ const safeStart = Math.max(0, Math.min(text.length, start));
+ const safeEnd = Math.max(safeStart, Math.min(text.length, end));
+ return safeEnd > safeStart ? [{ start: safeStart, end: safeEnd, pattern }] : [];
+ })
+ .sort((left, right) => left.start - right.start || left.end - right.end);
+
+ const segments: TextSegment[] = [];
+ let cursor = 0;
+ for (const range of ranges) {
+ if (range.start < cursor) {
+ continue;
+ }
+ if (range.start > cursor) {
+ segments.push({ text: text.slice(cursor, range.start) });
+ }
+ segments.push({ text: text.slice(range.start, range.end), pattern: range.pattern });
+ cursor = range.end;
+ }
+ if (cursor < text.length || segments.length === 0) {
+ segments.push({ text: text.slice(cursor) });
+ }
+ return segments;
+}
+
+export function hexDump(bytes: Uint8Array, blockSize: number, lineNumberBase: number): string {
+ const width = Number.isFinite(blockSize) ? Math.max(1, Math.min(128, Math.trunc(blockSize))) : 16;
+ const base = lineNumberBase === 16 ? 16 : 10;
+ const rows: string[] = [];
+
+ for (let offset = 0; offset < bytes.length; offset += width) {
+ const block = bytes.subarray(offset, Math.min(offset + width, bytes.length));
+ const address = offset.toString(base).padStart(10, "0");
+ const hex = Array.from(block, (byte) => byte.toString(16).padStart(2, "0").toUpperCase());
+ const paddedHex = [...hex, ...Array.from({ length: width - block.length }, () => " ")]
+ .join(" ");
+ const chars = Array.from(block, (byte) =>
+ byte >= 0x20 && byte <= 0x7e ? String.fromCharCode(byte) : ".",
+ ).join("");
+ rows.push(`${address}: ${paddedHex} |${chars.padEnd(width, " ")}|`);
+ }
+
+ return rows.join("\n");
+}
+
+export function pythonBytes(bytes: Uint8Array): string {
+ return `b'${Array.from(bytes, (byte) => `\\x${byte.toString(16).padStart(2, "0")}`).join("")}'`;
+}
+
+export function safePatternColor(color: string): string {
+ if (/^#[\da-f]{3}(?:[\da-f]{3}|[\da-f]{5})?$/i.test(color)) {
+ return color;
+ }
+ if (/^(?:red|green|blue|orange|purple|teal|yellow|white|black|gray|grey)$/i.test(color)) {
+ return color;
+ }
+ return "#ff5959";
+}
diff --git a/components/packmate/frontend/src/styles.css b/components/packmate/frontend/src/styles.css
new file mode 100644
index 0000000..1c2118b
--- /dev/null
+++ b/components/packmate/frontend/src/styles.css
@@ -0,0 +1,992 @@
+:root {
+ color-scheme: light;
+ --topbar: #30343a;
+ --topbar-text: #f4f5f6;
+ --panel: #f7f8f9;
+ --panel-border: #d4d8dd;
+ --text: #22262b;
+ --muted: #68717b;
+ --accent: #087cf0;
+ --request: #fff6f4;
+ --response: #f0f9fc;
+ --highlight: #ffe083;
+ --danger: #d94050;
+ --shadow: 0 5px 18px rgb(0 0 0 / 20%);
+ font-family: "Open Sans", "Segoe UI", Arial, sans-serif;
+ color: var(--text);
+ background: var(--panel);
+ font-synthesis: none;
+ text-rendering: optimizeLegibility;
+}
+
+:root[data-theme="dark"] {
+ color-scheme: dark;
+ --topbar: #202328;
+ --topbar-text: #f4f5f6;
+ --panel: #24282d;
+ --panel-border: #444b53;
+ --text: #e4e8ec;
+ --muted: #aeb6bf;
+ --accent: #70b3ff;
+ --request: #34383e;
+ --response: #2b5378;
+ --highlight: #79651c;
+ --danger: #ff737f;
+ --shadow: 0 5px 18px rgb(0 0 0 / 45%);
+}
+
+* {
+ box-sizing: border-box;
+}
+
+body {
+ min-width: 360px;
+ min-height: 100vh;
+ margin: 0;
+ overflow: hidden;
+ color: var(--text);
+ background: var(--panel);
+ font-size: 14px;
+}
+
+button,
+input,
+select {
+ font: inherit;
+}
+
+button {
+ color: inherit;
+}
+
+button:focus-visible,
+input:focus-visible,
+select:focus-visible,
+summary:focus-visible {
+ outline: 3px solid #55a8ff;
+ outline-offset: 2px;
+}
+
+button:disabled {
+ cursor: wait;
+ opacity: 0.65;
+}
+
+.app-shell {
+ display: flex;
+ flex-direction: column;
+ height: 100vh;
+ min-height: 420px;
+}
+
+.topbar {
+ z-index: 4;
+ display: flex;
+ min-height: 54px;
+ align-items: center;
+ gap: 12px;
+ padding: 0 12px;
+ overflow-x: auto;
+ color: var(--topbar-text);
+ background: var(--topbar);
+ box-shadow: 0 2px 7px rgb(0 0 0 / 22%);
+ scrollbar-width: thin;
+}
+
+.brand {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ flex: none;
+ font-size: 20px;
+ font-weight: 500;
+ letter-spacing: 0.01em;
+ white-space: nowrap;
+}
+
+.brand img {
+ width: 56px;
+ height: 32px;
+ object-fit: cover;
+ border-radius: 3px;
+}
+
+.brand small {
+ font-size: 12px;
+ color: #c5cbd3;
+}
+
+.traffic-stats {
+ display: flex;
+ flex: none;
+ gap: 4px;
+ color: #9eb5c8;
+ white-space: nowrap;
+}
+
+.traffic-stats abbr {
+ text-decoration: underline dotted;
+ text-underline-offset: 3px;
+}
+
+.stats-separator {
+ color: #77818b;
+}
+
+.service-tabs {
+ display: flex;
+ min-width: max-content;
+ align-items: center;
+ gap: 4px;
+}
+
+.service-tabs > button,
+.service-tab > button {
+ min-height: 34px;
+ padding: 6px 8px;
+ border: 0;
+ border-radius: 3px;
+ color: #dce2e8;
+ background: transparent;
+ cursor: pointer;
+ white-space: nowrap;
+}
+
+.service-tabs > button:hover,
+.service-tab > button:hover,
+.service-tabs > button.active,
+.service-tab.active > button {
+ color: #fff;
+ background: #41474f;
+}
+
+.service-tab {
+ display: flex;
+ align-items: center;
+ white-space: nowrap;
+}
+
+.service-tab small {
+ color: #a8b0b8;
+}
+
+.service-tab > .service-edit {
+ min-width: 26px;
+ padding: 4px;
+ color: #dce2e8;
+}
+
+.service-tabs .add-service {
+ min-width: 32px;
+ color: #c5f1d1;
+ font-size: 21px;
+ font-weight: 700;
+}
+
+.pattern-menu {
+ position: relative;
+ flex: none;
+}
+
+.pattern-menu summary {
+ padding: 8px 5px;
+ border-radius: 3px;
+ cursor: pointer;
+ list-style: none;
+ white-space: nowrap;
+}
+
+.pattern-menu summary::-webkit-details-marker {
+ display: none;
+}
+
+.pattern-menu summary::after {
+ margin-left: 6px;
+ content: "▾";
+}
+
+.pattern-menu[open] summary,
+.pattern-menu summary:hover {
+ color: #fff;
+ background: #41474f;
+}
+
+.pattern-popover {
+ position: fixed;
+ top: 48px;
+ left: 192px;
+ z-index: 7;
+ width: min(740px, calc(100vw - 24px));
+ max-height: min(70vh, 720px);
+ padding: 8px;
+ overflow: auto;
+ border: 1px solid var(--panel-border);
+ border-radius: 5px;
+ color: var(--text);
+ background: var(--panel);
+ box-shadow: var(--shadow);
+}
+
+.pattern-add,
+.pattern-all {
+ display: block;
+ width: 100%;
+ padding: 9px 12px;
+ border: 0;
+ border-radius: 3px;
+ color: var(--text);
+ text-align: left;
+ background: transparent;
+ cursor: pointer;
+}
+
+.pattern-add {
+ color: #fff;
+ text-align: center;
+ background: var(--accent);
+}
+
+.pattern-all {
+ margin: 4px 0;
+ font-weight: 700;
+}
+
+.pattern-row {
+ display: flex;
+ min-height: 44px;
+ align-items: center;
+ justify-content: space-between;
+ gap: 8px;
+ padding: 6px 5px;
+ border-top: 1px solid var(--panel-border);
+}
+
+.pattern-select {
+ flex: 1;
+ min-width: 180px;
+ padding: 5px;
+ border: 0;
+ color: var(--text);
+ text-align: left;
+ background: transparent;
+ cursor: pointer;
+}
+
+.pattern-select:disabled {
+ cursor: default;
+ opacity: 1;
+}
+
+.pattern-select span {
+ overflow-wrap: anywhere;
+}
+
+.pattern-ignore .pattern-select {
+ opacity: 0.8;
+}
+
+.disabled-pattern {
+ text-decoration: line-through;
+}
+
+.pattern-actions {
+ display: flex;
+ flex: none;
+ gap: 4px;
+}
+
+.pattern-actions button {
+ padding: 5px 7px;
+ border: 1px solid var(--panel-border);
+ border-radius: 3px;
+ color: var(--text);
+ background: var(--panel);
+ cursor: pointer;
+}
+
+.pattern-actions button:hover {
+ border-color: var(--accent);
+}
+
+.selected-pattern {
+ flex: none;
+ max-width: 210px;
+ overflow: hidden;
+ color: #d5eaff;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.settings-button {
+ flex: none;
+ min-width: 34px;
+ margin-left: auto;
+ padding: 5px;
+ border: 0;
+ color: #e3e8ed;
+ font-size: 19px;
+ background: transparent;
+ cursor: pointer;
+}
+
+.workspace {
+ display: flex;
+ min-height: 0;
+ flex: 1;
+}
+
+.sidebar {
+ display: flex;
+ width: 25%;
+ min-width: 235px;
+ max-width: 360px;
+ flex: none;
+ flex-direction: column;
+ border-right: 1px solid var(--panel-border);
+ background: var(--panel);
+}
+
+.sidebar-toolbar {
+ display: flex;
+ min-height: 48px;
+ align-items: center;
+ gap: 5px;
+ padding: 7px 9px;
+ background: linear-gradient(#fff, #eef0f2);
+}
+
+:root[data-theme="dark"] .sidebar-toolbar {
+ background: linear-gradient(#2d3238, #25292e);
+}
+
+.tool-button {
+ min-width: 34px;
+ height: 34px;
+ padding: 2px 6px;
+ border: 1px solid currentColor;
+ border-radius: 4px;
+ background: transparent;
+ cursor: pointer;
+ font-size: 15px;
+ font-weight: 700;
+}
+
+.pause-button {
+ color: #259b4b;
+}
+
+.pause-button.selected {
+ color: #fff;
+ background: #d94250;
+}
+
+.favorite-button {
+ color: #dc3545;
+ font-size: 21px;
+}
+
+.favorite-button.selected {
+ color: #fff;
+ background: #dc3545;
+}
+
+.hex-button {
+ color: #087cf0;
+}
+
+.hex-button.selected {
+ color: #fff;
+ background: #087cf0;
+}
+
+.file-button {
+ color: #d28b00;
+}
+
+.to-top-button {
+ min-width: 36px;
+ margin-left: auto;
+ color: #07859a;
+ font-size: 22px;
+}
+
+.stream-search {
+ position: relative;
+ display: flex;
+ padding: 4px 9px 7px;
+ border-bottom: 1px solid var(--panel-border);
+}
+
+.stream-search input {
+ width: 100%;
+ min-width: 0;
+ padding: 7px 28px 7px 9px;
+ border: 1px solid var(--panel-border);
+ border-radius: 4px;
+ color: var(--text);
+ background: var(--panel);
+}
+
+.stream-search button {
+ position: absolute;
+ top: 7px;
+ right: 14px;
+ border: 0;
+ color: var(--muted);
+ font-size: 19px;
+ background: transparent;
+ cursor: pointer;
+}
+
+.stream-list {
+ min-height: 0;
+ flex: 1;
+ overflow: auto;
+ scrollbar-width: thin;
+}
+
+.stream-list ul {
+ margin: 0;
+ padding: 0;
+ list-style: none;
+}
+
+.stream-item {
+ position: relative;
+ border-bottom: 1px solid var(--panel-border);
+ transition: background-color 120ms ease;
+}
+
+.stream-item:hover {
+ background: color-mix(in srgb, var(--accent) 8%, var(--panel));
+}
+
+.stream-item.stream-selected {
+ background: color-mix(in srgb, var(--accent) 15%, var(--panel));
+ box-shadow: inset 3px 0 var(--accent);
+}
+
+.stream-item.stream-favorite {
+ background-color: color-mix(in srgb, #dc3545 9%, var(--panel));
+}
+
+.stream-select {
+ display: flex;
+ width: 100%;
+ flex-direction: column;
+ align-items: flex-start;
+ gap: 2px;
+ padding: 10px 36px 10px 17px;
+ border: 0;
+ color: var(--text);
+ line-height: 1.35;
+ text-align: left;
+ background: transparent;
+ cursor: pointer;
+ overflow-wrap: anywhere;
+}
+
+.stream-select strong {
+ font-weight: 700;
+}
+
+.stream-select time,
+.stream-ttl {
+ color: var(--muted);
+ font-size: 12px;
+}
+
+.stream-patterns {
+ line-height: 1.5;
+}
+
+.stream-star {
+ position: absolute;
+ top: 8px;
+ right: 8px;
+ padding: 0 3px;
+ border: 0;
+ color: #d94050;
+ font-size: 19px;
+ background: transparent;
+ cursor: pointer;
+}
+
+.stream-star.is-favorite {
+ color: #d94050;
+}
+
+.list-message {
+ padding: 9px 12px;
+ text-align: center;
+}
+
+.load-more {
+ display: block;
+ width: calc(100% - 18px);
+ margin: 9px;
+ padding: 8px;
+ border: 1px solid var(--panel-border);
+ border-radius: 4px;
+ color: var(--text);
+ background: var(--panel);
+ cursor: pointer;
+}
+
+.load-more:hover {
+ border-color: var(--accent);
+}
+
+.packet-pane {
+ min-width: 0;
+ flex: 1;
+ padding: 14px 22px 24px;
+ overflow: auto;
+ background: var(--panel);
+ scrollbar-width: thin;
+}
+
+.packet-legend {
+ position: sticky;
+ top: -14px;
+ z-index: 2;
+ display: flex;
+ min-height: 38px;
+ align-items: center;
+ gap: 4px;
+ padding: 3px 0;
+ background: var(--panel);
+}
+
+.legend-request {
+ padding: 1px 3px;
+ background: var(--request);
+ box-shadow: 0 0 3px 3px var(--request);
+}
+
+.legend-response {
+ padding: 1px 3px;
+ background: var(--response);
+ box-shadow: 0 0 3px 3px var(--response);
+}
+
+.socket-state {
+ margin-left: auto;
+ color: var(--muted);
+ font-size: 12px;
+}
+
+.theme-toggle {
+ margin-left: 10px;
+ padding: 5px 7px;
+ border: 1px solid var(--panel-border);
+ border-radius: 3px;
+ color: var(--text);
+ background: var(--panel);
+ cursor: pointer;
+}
+
+.stream-heading {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 7px 14px;
+ margin: 1px 0 10px;
+ padding: 8px 10px;
+ border-bottom: 1px solid var(--panel-border);
+ color: var(--muted);
+}
+
+.stream-heading strong {
+ color: var(--text);
+}
+
+.empty-detail {
+ margin: 32px 0;
+ color: var(--muted);
+ text-align: center;
+}
+
+.packet {
+ margin: 0 0 14px;
+ padding: 7px 0 9px;
+ border-bottom: 1px solid var(--panel-border);
+ box-shadow: 0 5px 8px -9px #4b4e51;
+}
+
+.packet-request {
+ background: var(--request);
+}
+
+.packet-response {
+ background: var(--response);
+}
+
+.packet-header {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ justify-content: space-between;
+ gap: 6px 12px;
+ padding: 2px 6px 7px;
+ border-bottom: 1px solid color-mix(in srgb, var(--panel-border) 75%, transparent);
+}
+
+.packet-meta,
+.packet-actions {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ gap: 4px 10px;
+}
+
+.packet-meta time,
+.packet-meta > span {
+ color: var(--muted);
+}
+
+.packet-direction {
+ color: var(--text) !important;
+ font-weight: 600;
+}
+
+.packet-flag {
+ padding: 1px 4px;
+ border: 1px solid var(--panel-border);
+ border-radius: 3px;
+ font-size: 11px;
+}
+
+.text-button {
+ padding: 2px 0;
+ border: 0;
+ color: var(--accent);
+ background: transparent;
+ cursor: pointer;
+}
+
+.text-button:hover {
+ text-decoration: underline;
+}
+
+.packet-content {
+ margin: 0;
+ padding: 11px 7px 8px;
+ overflow-x: auto;
+ color: var(--text);
+ font-family: "Ubuntu Mono", "Cascadia Mono", "Liberation Mono", monospace;
+ font-size: 13px;
+ line-height: 1.55;
+ white-space: pre-wrap;
+ overflow-wrap: anywhere;
+ tab-size: 4;
+}
+
+.packet-content mark {
+ padding: 0 1px;
+ color: #151515;
+ box-shadow: 0 0 1px 1px currentColor;
+ overflow-wrap: anywhere;
+}
+
+.packet-more,
+.packet-end {
+ max-width: 420px;
+ margin: 12px auto;
+ text-align: center;
+}
+
+.muted {
+ color: var(--muted);
+}
+
+.notice {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 12px;
+ margin: 0 0 8px;
+ padding: 7px 10px;
+ border: 1px solid color-mix(in srgb, var(--accent) 35%, var(--panel-border));
+ border-radius: 4px;
+ color: var(--text);
+ background: var(--panel);
+ box-shadow: 0 2px 6px rgb(0 0 0 / 10%);
+}
+
+.notice button {
+ border: 0;
+ color: var(--muted);
+ font-size: 19px;
+ background: transparent;
+ cursor: pointer;
+}
+
+.statusbar {
+ min-height: 22px;
+ padding: 3px 9px;
+ border-top: 1px solid var(--panel-border);
+ color: var(--muted);
+ font-size: 11px;
+ background: var(--panel);
+}
+
+.dialog-backdrop {
+ position: fixed;
+ inset: 0;
+ z-index: 10;
+ display: grid;
+ align-items: center;
+ justify-items: center;
+ padding: 18px;
+ overflow: auto;
+ background: rgb(0 0 0 / 55%);
+}
+
+.dialog {
+ width: min(780px, 100%);
+ max-height: min(92vh, 980px);
+ overflow: auto;
+ border: 1px solid #727982;
+ border-radius: 7px;
+ color: var(--text);
+ background: var(--panel);
+ box-shadow: var(--shadow);
+}
+
+.dialog-header {
+ position: sticky;
+ top: 0;
+ z-index: 1;
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ padding: 13px 20px;
+ border-bottom: 1px solid var(--panel-border);
+ background: var(--panel);
+}
+
+.dialog-header h2 {
+ margin: 0;
+ font-size: clamp(20px, 3vw, 28px);
+ font-weight: 400;
+}
+
+.dialog-close {
+ padding: 0 5px;
+ border: 0;
+ color: var(--muted);
+ font-size: 27px;
+ background: transparent;
+ cursor: pointer;
+}
+
+.dialog-body {
+ padding: 16px 20px 20px;
+}
+
+.form-field {
+ display: flex;
+ flex-direction: column;
+ gap: 7px;
+ margin-bottom: 16px;
+}
+
+.form-field > span {
+ font-size: 16px;
+ font-weight: 500;
+}
+
+.form-field input:not([type="checkbox"]):not([type="color"]),
+.form-field select {
+ width: 100%;
+ min-height: 42px;
+ padding: 8px 10px;
+ border: 1px solid #adb5bd;
+ border-radius: 4px;
+ color: var(--text);
+ background: var(--panel);
+}
+
+.form-field input[type="color"] {
+ width: 100%;
+ height: 44px;
+ padding: 4px;
+ border: 1px solid var(--panel-border);
+ border-radius: 4px;
+ background: var(--panel);
+ cursor: pointer;
+}
+
+.form-field small {
+ color: var(--muted);
+ line-height: 1.4;
+}
+
+.service-options {
+ display: grid;
+ gap: 12px;
+ margin: 5px 0 20px;
+ padding: 12px 13px;
+ border: 1px solid var(--panel-border);
+ border-radius: 4px;
+}
+
+.service-options legend {
+ padding: 0 6px;
+ font-size: 15px;
+}
+
+.service-options label {
+ display: flex;
+ align-items: center;
+ gap: 9px;
+}
+
+.service-options input {
+ width: 17px;
+ height: 17px;
+ accent-color: var(--accent);
+}
+
+.dialog-actions {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ justify-content: flex-end;
+ gap: 8px;
+ margin-top: 20px;
+ padding-top: 14px;
+ border-top: 1px solid var(--panel-border);
+}
+
+.dialog-actions button {
+ min-height: 38px;
+ padding: 8px 14px;
+ border: 1px solid transparent;
+ border-radius: 4px;
+ cursor: pointer;
+}
+
+.button-primary {
+ color: #fff;
+ background: #087cf0;
+}
+
+.button-secondary {
+ color: #fff;
+ background: #68717b;
+}
+
+.button-danger {
+ color: #fff;
+ background: #d94050;
+}
+
+.dialog-delete {
+ margin-right: auto;
+}
+
+.validation-message {
+ color: var(--danger);
+}
+
+.sr-only {
+ position: absolute;
+ width: 1px;
+ height: 1px;
+ padding: 0;
+ overflow: hidden;
+ clip: rect(0, 0, 0, 0);
+ white-space: nowrap;
+ border: 0;
+}
+
+@media (max-width: 900px) {
+ .topbar {
+ gap: 8px;
+ padding: 0 8px;
+ }
+
+ .sidebar {
+ width: 32%;
+ min-width: 210px;
+ }
+
+ .packet-pane {
+ padding-right: 14px;
+ padding-left: 14px;
+ }
+
+ .selected-pattern {
+ display: none;
+ }
+}
+
+@media (max-width: 650px) {
+ body {
+ overflow: auto;
+ }
+
+ .app-shell {
+ height: auto;
+ min-height: 100vh;
+ }
+
+ .topbar {
+ flex-wrap: wrap;
+ min-height: 54px;
+ padding: 6px 8px;
+ }
+
+ .brand {
+ font-size: 18px;
+ }
+
+ .service-tabs {
+ order: 5;
+ width: 100%;
+ overflow-x: auto;
+ }
+
+ .workspace {
+ flex-direction: column;
+ }
+
+ .sidebar {
+ width: 100%;
+ max-width: none;
+ min-width: 0;
+ max-height: 45vh;
+ border-right: 0;
+ border-bottom: 1px solid var(--panel-border);
+ }
+
+ .stream-list {
+ max-height: calc(45vh - 94px);
+ }
+
+ .packet-pane {
+ min-height: 48vh;
+ padding: 9px 10px 20px;
+ }
+
+ .pattern-popover {
+ top: 48px;
+ left: 8px;
+ }
+
+ .pattern-row {
+ align-items: flex-start;
+ flex-direction: column;
+ }
+
+ .pattern-actions {
+ flex-wrap: wrap;
+ padding-left: 5px;
+ }
+
+ .statusbar {
+ position: sticky;
+ bottom: 0;
+ }
+}
diff --git a/components/packmate/frontend/src/test/setup.ts b/components/packmate/frontend/src/test/setup.ts
new file mode 100644
index 0000000..bb32bff
--- /dev/null
+++ b/components/packmate/frontend/src/test/setup.ts
@@ -0,0 +1,5 @@
+import "@testing-library/jest-dom/vitest";
+import { cleanup } from "@testing-library/react";
+import { afterEach } from "vitest";
+
+afterEach(cleanup);
diff --git a/components/packmate/frontend/src/types.ts b/components/packmate/frontend/src/types.ts
new file mode 100644
index 0000000..5829d10
--- /dev/null
+++ b/components/packmate/frontend/src/types.ts
@@ -0,0 +1,80 @@
+export type PatternSearchType = "REGEX" | "SUBSTRING" | "SUBBYTES";
+export type PatternDirectionType = "INPUT" | "OUTPUT" | "BOTH";
+export type PatternActionType = "FIND" | "IGNORE";
+
+export interface Service {
+ port: number;
+ name: string;
+ decryptTls: boolean;
+ http: boolean;
+ urldecodeHttpRequests: boolean;
+ mergeAdjacentPackets: boolean;
+ parseWebSockets: boolean;
+}
+
+export interface Pattern {
+ id: number;
+ enabled: boolean;
+ deleted: boolean;
+ name: string;
+ value: string;
+ color: string;
+ searchType: PatternSearchType;
+ directionType: PatternDirectionType;
+ actionType: PatternActionType;
+ serviceId: number | null;
+}
+
+export interface PatternInput extends Omit {
+ id?: number;
+}
+
+export interface Stream {
+ id: number;
+ service: number;
+ protocol: string;
+ startTimestamp: number;
+ endTimestamp: number;
+ foundPatternsIds: number[];
+ favorite: boolean;
+ ttl: number;
+ userAgentHash: string | null;
+ sizeBytes: number;
+ packetsCount: number;
+}
+
+export interface FoundPattern {
+ patternId: number;
+ startPosition: number;
+ endPosition: number;
+}
+
+export interface Packet {
+ id: number;
+ matches: FoundPattern[];
+ timestamp: number;
+ incoming: boolean;
+ ungzipped: boolean;
+ webSocketParsed: boolean;
+ tlsDecrypted: boolean;
+ hasHttpBody: boolean;
+ content: string;
+}
+
+export interface RouteState {
+ servicePort?: number;
+ streamId?: number;
+ patternId?: number;
+}
+
+export interface CountersUpdate {
+ totalPackets: number;
+ totalStreams: number;
+ servicesPackets: Record;
+ servicesStreams: Record;
+}
+
+export interface SubscriptionMessage {
+ type: string;
+ value: unknown;
+}
diff --git a/components/packmate/frontend/src/vite-env.d.ts b/components/packmate/frontend/src/vite-env.d.ts
new file mode 100644
index 0000000..11f02fe
--- /dev/null
+++ b/components/packmate/frontend/src/vite-env.d.ts
@@ -0,0 +1 @@
+///
diff --git a/components/packmate/frontend/tsconfig.json b/components/packmate/frontend/tsconfig.json
new file mode 100644
index 0000000..da408a1
--- /dev/null
+++ b/components/packmate/frontend/tsconfig.json
@@ -0,0 +1,22 @@
+{
+ "compilerOptions": {
+ "target": "ES2022",
+ "useDefineForClassFields": true,
+ "lib": ["ES2022", "DOM", "DOM.Iterable"],
+ "module": "ESNext",
+ "skipLibCheck": true,
+ "moduleResolution": "bundler",
+ "allowImportingTsExtensions": true,
+ "verbatimModuleSyntax": true,
+ "moduleDetection": "force",
+ "noEmit": true,
+ "jsx": "react-jsx",
+ "strict": true,
+ "noUnusedLocals": true,
+ "noUnusedParameters": true,
+ "noFallthroughCasesInSwitch": true,
+ "noUncheckedIndexedAccess": true,
+ "noImplicitOverride": true
+ },
+ "include": ["src", "vite.config.ts"]
+}
diff --git a/components/packmate/frontend/vite.config.ts b/components/packmate/frontend/vite.config.ts
new file mode 100644
index 0000000..26c497d
--- /dev/null
+++ b/components/packmate/frontend/vite.config.ts
@@ -0,0 +1,21 @@
+import react from "@vitejs/plugin-react";
+import { defineConfig } from "vitest/config";
+
+export default defineConfig({
+ plugins: [react()],
+ base: "/",
+ server: {
+ proxy: {
+ "/api": {
+ target: process.env.PACKMATE_API_ORIGIN ?? "http://127.0.0.1:65000",
+ changeOrigin: true,
+ ws: true,
+ },
+ },
+ },
+ test: {
+ environment: "happy-dom",
+ setupFiles: ["./src/test/setup.ts"],
+ restoreMocks: true,
+ },
+});
diff --git a/components/packmate/settings.gradle.kts b/components/packmate/settings.gradle.kts
new file mode 100644
index 0000000..1d2c8af
--- /dev/null
+++ b/components/packmate/settings.gradle.kts
@@ -0,0 +1,6 @@
+pluginManagement {
+ repositories {
+ gradlePluginPortal()
+ }
+}
+rootProject.name = "packmate"
diff --git a/components/packmate/src/main/java/ru/serega6531/packmate/PackmateApplication.java b/components/packmate/src/main/java/ru/serega6531/packmate/PackmateApplication.java
new file mode 100644
index 0000000..a1ae6f3
--- /dev/null
+++ b/components/packmate/src/main/java/ru/serega6531/packmate/PackmateApplication.java
@@ -0,0 +1,13 @@
+package ru.serega6531.packmate;
+
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+
+@SpringBootApplication
+public class PackmateApplication {
+
+ public static void main(String[] args) {
+ SpringApplication.run(PackmateApplication.class, args);
+ }
+
+}
diff --git a/components/packmate/src/main/java/ru/serega6531/packmate/configuration/ApplicationConfiguration.java b/components/packmate/src/main/java/ru/serega6531/packmate/configuration/ApplicationConfiguration.java
new file mode 100644
index 0000000..5664230
--- /dev/null
+++ b/components/packmate/src/main/java/ru/serega6531/packmate/configuration/ApplicationConfiguration.java
@@ -0,0 +1,69 @@
+package ru.serega6531.packmate.configuration;
+
+import org.modelmapper.Converter;
+import org.modelmapper.ModelMapper;
+import org.modelmapper.TypeMap;
+import org.pcap4j.core.PcapNativeException;
+import org.springframework.boot.context.properties.ConfigurationPropertiesScan;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.scheduling.annotation.EnableAsync;
+import org.springframework.scheduling.annotation.EnableScheduling;
+import ru.serega6531.packmate.model.Pattern;
+import ru.serega6531.packmate.model.Stream;
+import ru.serega6531.packmate.model.pojo.StreamDto;
+import ru.serega6531.packmate.pcap.FilePcapWorker;
+import ru.serega6531.packmate.pcap.LivePcapWorker;
+import ru.serega6531.packmate.pcap.NoOpPcapWorker;
+import ru.serega6531.packmate.pcap.PcapWorker;
+import ru.serega6531.packmate.properties.PackmateProperties;
+import ru.serega6531.packmate.service.ServicesService;
+import ru.serega6531.packmate.service.StreamService;
+
+import java.net.UnknownHostException;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+@Configuration
+@EnableScheduling
+@EnableAsync
+@ConfigurationPropertiesScan("ru.serega6531.packmate.properties")
+public class ApplicationConfiguration {
+
+ @Bean(destroyMethod = "shutdown")
+ public PcapWorker pcapWorker(ServicesService servicesService,
+ StreamService streamService,
+ PackmateProperties properties
+ ) throws PcapNativeException, UnknownHostException {
+ return switch (properties.captureMode()) {
+ case LIVE -> new LivePcapWorker(servicesService, streamService, properties.localIp(), properties.interfaceName());
+ case FILE ->
+ new FilePcapWorker(servicesService, streamService, properties.localIp(), properties.pcapFile());
+ case VIEW -> new NoOpPcapWorker();
+ };
+ }
+
+ @Bean
+ public ModelMapper modelMapper() {
+ ModelMapper modelMapper = new ModelMapper();
+
+ addStreamMapper(modelMapper);
+
+ return modelMapper;
+ }
+
+ private void addStreamMapper(ModelMapper modelMapper) {
+ TypeMap streamMapper = modelMapper.createTypeMap(Stream.class, StreamDto.class);
+
+ Converter, Set> patternSetToIdSet = ctx -> ctx.getSource()
+ .stream()
+ .map(Pattern::getId)
+ .collect(Collectors.toSet());
+
+ streamMapper.addMappings(mapping ->
+ mapping.using(patternSetToIdSet)
+ .map(Stream::getFoundPatterns, StreamDto::setFoundPatternsIds)
+ );
+ }
+
+}
diff --git a/components/packmate/src/main/java/ru/serega6531/packmate/configuration/SameOriginMutationFilter.java b/components/packmate/src/main/java/ru/serega6531/packmate/configuration/SameOriginMutationFilter.java
new file mode 100644
index 0000000..3487762
--- /dev/null
+++ b/components/packmate/src/main/java/ru/serega6531/packmate/configuration/SameOriginMutationFilter.java
@@ -0,0 +1,79 @@
+package ru.serega6531.packmate.configuration;
+
+import jakarta.servlet.FilterChain;
+import jakarta.servlet.ServletException;
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletResponse;
+import org.springframework.web.filter.OncePerRequestFilter;
+
+import java.io.IOException;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.util.Locale;
+import java.util.Set;
+
+final class SameOriginMutationFilter extends OncePerRequestFilter {
+
+ private static final Set SAFE_METHODS = Set.of("GET", "HEAD", "OPTIONS", "TRACE");
+
+ @Override
+ protected void doFilterInternal(
+ HttpServletRequest request,
+ HttpServletResponse response,
+ FilterChain filterChain
+ ) throws ServletException, IOException {
+ String path = request.getRequestURI();
+ boolean apiMutation = path.startsWith("/api/")
+ && !SAFE_METHODS.contains(request.getMethod().toUpperCase(Locale.ROOT));
+ boolean websocketHandshake = (path.equals("/api/ws") || path.startsWith("/api/ws/"))
+ && "websocket".equalsIgnoreCase(request.getHeader("Upgrade"));
+ if ((apiMutation || websocketHandshake)
+ && !isSameOrigin(request)) {
+ response.setStatus(HttpServletResponse.SC_FORBIDDEN);
+ response.setContentType("application/json");
+ response.setCharacterEncoding("UTF-8");
+ response.getWriter().write("{\"message\":\"Источник запроса не совпадает с адресом Packmate.\"}");
+ return;
+ }
+
+ filterChain.doFilter(request, response);
+ }
+
+ private boolean isSameOrigin(HttpServletRequest request) {
+ String originHeader = request.getHeader("Origin");
+ if (originHeader == null || originHeader.isBlank()) {
+ return false;
+ }
+
+ try {
+ URI origin = new URI(originHeader);
+ String scheme = request.getScheme();
+ if (!origin.isAbsolute()
+ || origin.getHost() == null
+ || origin.getUserInfo() != null
+ || origin.getRawQuery() != null
+ || origin.getRawFragment() != null
+ || (origin.getRawPath() != null && !origin.getRawPath().isEmpty())
+ || scheme == null
+ || !origin.getScheme().equalsIgnoreCase(scheme)
+ || !origin.getHost().equalsIgnoreCase(request.getServerName())) {
+ return false;
+ }
+
+ int originPort = origin.getPort() == -1 ? defaultPort(origin.getScheme()) : origin.getPort();
+ return originPort == request.getServerPort();
+ } catch (URISyntaxException | IllegalArgumentException exception) {
+ return false;
+ }
+ }
+
+ private int defaultPort(String scheme) {
+ if ("http".equalsIgnoreCase(scheme)) {
+ return 80;
+ }
+ if ("https".equalsIgnoreCase(scheme)) {
+ return 443;
+ }
+ return -1;
+ }
+}
diff --git a/components/packmate/src/main/java/ru/serega6531/packmate/configuration/SecurityConfiguration.java b/components/packmate/src/main/java/ru/serega6531/packmate/configuration/SecurityConfiguration.java
new file mode 100644
index 0000000..bf98b2b
--- /dev/null
+++ b/components/packmate/src/main/java/ru/serega6531/packmate/configuration/SecurityConfiguration.java
@@ -0,0 +1,67 @@
+package ru.serega6531.packmate.configuration;
+
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.context.event.EventListener;
+import org.springframework.security.authentication.event.AuthenticationFailureBadCredentialsEvent;
+import org.springframework.security.config.annotation.web.builders.HttpSecurity;
+import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
+import org.springframework.security.core.userdetails.User;
+import org.springframework.security.core.userdetails.UserDetails;
+import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
+import org.springframework.security.crypto.password.PasswordEncoder;
+import org.springframework.security.provisioning.InMemoryUserDetailsManager;
+import org.springframework.security.web.SecurityFilterChain;
+import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
+import ru.serega6531.packmate.properties.PackmateProperties;
+import org.springframework.security.config.Customizer;
+
+@Configuration
+@EnableWebSecurity
+@Slf4j
+public class SecurityConfiguration {
+
+ @Bean
+ public InMemoryUserDetailsManager userDetailsService(PackmateProperties properties, PasswordEncoder passwordEncoder) {
+ if (properties.web().accountLogin() == null || properties.web().accountLogin().isBlank()) {
+ throw new IllegalStateException("Нужно задать PACKMATE_USERNAME.");
+ }
+ if (properties.web().accountPassword() == null || properties.web().accountPassword().isBlank()) {
+ throw new IllegalStateException("Нужно задать PACKMATE_PASSWORD.");
+ }
+
+ UserDetails user = User.builder()
+ .username(properties.web().accountLogin())
+ .password(passwordEncoder.encode(properties.web().accountPassword()))
+ .roles("USER")
+ .build();
+
+ return new InMemoryUserDetailsManager(user);
+ }
+
+ @Bean
+ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
+ return http
+ .csrf(csrf -> csrf.disable())
+ .addFilterBefore(new SameOriginMutationFilter(), BasicAuthenticationFilter.class)
+ .authorizeHttpRequests(auth -> auth
+ .requestMatchers("/healthz", "/site.webmanifest").permitAll()
+ .anyRequest().authenticated()
+ )
+ .httpBasic(Customizer.withDefaults())
+ .headers(headers -> headers.frameOptions(frameOptions -> frameOptions.sameOrigin()))
+ .build();
+ }
+
+ @Bean
+ public PasswordEncoder passwordEncoder() {
+ return new BCryptPasswordEncoder();
+ }
+
+ @EventListener
+ public void authenticationFailed(AuthenticationFailureBadCredentialsEvent e) {
+ log.info("Неудачная попытка входа");
+ }
+
+}
diff --git a/components/packmate/src/main/java/ru/serega6531/packmate/configuration/WebSocketConfiguration.java b/components/packmate/src/main/java/ru/serega6531/packmate/configuration/WebSocketConfiguration.java
new file mode 100644
index 0000000..64c65ec
--- /dev/null
+++ b/components/packmate/src/main/java/ru/serega6531/packmate/configuration/WebSocketConfiguration.java
@@ -0,0 +1,26 @@
+package ru.serega6531.packmate.configuration;
+
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.web.socket.config.annotation.EnableWebSocket;
+import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
+import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
+import ru.serega6531.packmate.controller.WebSocketHandler;
+
+@EnableWebSocket
+@Configuration
+public class WebSocketConfiguration implements WebSocketConfigurer {
+
+ private final WebSocketHandler webSocketHandler;
+
+ @Autowired
+ public WebSocketConfiguration(WebSocketHandler webSocketHandler) {
+ this.webSocketHandler = webSocketHandler;
+ }
+
+ @Override
+ public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
+ registry.addHandler(webSocketHandler, "/api/ws");
+ }
+
+}
diff --git a/components/packmate/src/main/java/ru/serega6531/packmate/controller/FrontendController.java b/components/packmate/src/main/java/ru/serega6531/packmate/controller/FrontendController.java
new file mode 100644
index 0000000..d233488
--- /dev/null
+++ b/components/packmate/src/main/java/ru/serega6531/packmate/controller/FrontendController.java
@@ -0,0 +1,18 @@
+package ru.serega6531.packmate.controller;
+
+import org.springframework.stereotype.Controller;
+import org.springframework.web.bind.annotation.GetMapping;
+
+@Controller
+public class FrontendController {
+
+ @GetMapping("/{servicePort:[0-9]+}")
+ public String serviceRoute() {
+ return "forward:/index.html";
+ }
+
+ @GetMapping("/{servicePort:[0-9]+}/{streamId:[0-9]+}")
+ public String streamRoute() {
+ return "forward:/index.html";
+ }
+}
diff --git a/components/packmate/src/main/java/ru/serega6531/packmate/controller/HealthController.java b/components/packmate/src/main/java/ru/serega6531/packmate/controller/HealthController.java
new file mode 100644
index 0000000..d63e53f
--- /dev/null
+++ b/components/packmate/src/main/java/ru/serega6531/packmate/controller/HealthController.java
@@ -0,0 +1,14 @@
+package ru.serega6531.packmate.controller;
+
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+@RestController
+public class HealthController {
+
+ @GetMapping("/healthz")
+ public ResponseEntity health() {
+ return ResponseEntity.ok().build();
+ }
+}
diff --git a/components/packmate/src/main/java/ru/serega6531/packmate/controller/PacketController.java b/components/packmate/src/main/java/ru/serega6531/packmate/controller/PacketController.java
new file mode 100644
index 0000000..1156ce2
--- /dev/null
+++ b/components/packmate/src/main/java/ru/serega6531/packmate/controller/PacketController.java
@@ -0,0 +1,31 @@
+package ru.serega6531.packmate.controller;
+
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.web.bind.annotation.PathVariable;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+import ru.serega6531.packmate.model.pojo.PacketDto;
+import ru.serega6531.packmate.model.pojo.PacketPagination;
+import ru.serega6531.packmate.service.StreamService;
+
+import java.util.List;
+
+@RestController
+@RequestMapping("/api/packet/")
+public class PacketController {
+
+ private final StreamService streamService;
+
+ @Autowired
+ public PacketController(StreamService streamService) {
+ this.streamService = streamService;
+ }
+
+ @PostMapping("/{streamId}")
+ public List getPacketsForStream(@PathVariable long streamId, @RequestBody PacketPagination pagination) {
+ return streamService.getPackets(streamId, pagination.getStartingFrom(), pagination.getPageSize());
+ }
+
+}
diff --git a/components/packmate/src/main/java/ru/serega6531/packmate/controller/PatternController.java b/components/packmate/src/main/java/ru/serega6531/packmate/controller/PatternController.java
new file mode 100644
index 0000000..4206a11
--- /dev/null
+++ b/components/packmate/src/main/java/ru/serega6531/packmate/controller/PatternController.java
@@ -0,0 +1,62 @@
+package ru.serega6531.packmate.controller;
+
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.web.bind.annotation.DeleteMapping;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.PathVariable;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestParam;
+import org.springframework.web.bind.annotation.RestController;
+import ru.serega6531.packmate.model.pojo.PatternCreateDto;
+import ru.serega6531.packmate.model.pojo.PatternDto;
+import ru.serega6531.packmate.model.pojo.PatternUpdateDto;
+import ru.serega6531.packmate.service.PatternService;
+
+import java.util.List;
+
+@RestController
+@RequestMapping("/api/pattern/")
+public class PatternController {
+
+ private final PatternService service;
+
+ @Autowired
+ public PatternController(PatternService service) {
+ this.service = service;
+ }
+
+ @GetMapping
+ public List getPatterns() {
+ return service.findAll()
+ .stream().map(service::toDto)
+ .toList();
+ }
+
+ @PostMapping("/{id}/enable")
+ public void enable(@PathVariable int id, @RequestParam boolean enabled) {
+ service.enable(id, enabled);
+ }
+
+ @DeleteMapping("/{id}")
+ public void delete(@PathVariable int id) {
+ service.delete(id);
+ }
+
+ @PostMapping("/{id}/lookback")
+ public void lookBack(@PathVariable int id, @RequestBody int minutes) {
+ service.lookBack(id, minutes);
+ }
+
+ @PostMapping
+ public PatternDto addPattern(@RequestBody PatternCreateDto dto) {
+ return service.create(dto);
+ }
+
+ @PostMapping("/{id}")
+ public PatternDto updatePattern(@PathVariable int id, @RequestBody PatternUpdateDto dto) {
+ return service.update(id, dto);
+ }
+
+}
diff --git a/components/packmate/src/main/java/ru/serega6531/packmate/controller/PatternValidationHandler.java b/components/packmate/src/main/java/ru/serega6531/packmate/controller/PatternValidationHandler.java
new file mode 100644
index 0000000..4bc9065
--- /dev/null
+++ b/components/packmate/src/main/java/ru/serega6531/packmate/controller/PatternValidationHandler.java
@@ -0,0 +1,26 @@
+package ru.serega6531.packmate.controller;
+
+import org.springframework.http.HttpStatus;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.bind.annotation.ExceptionHandler;
+import org.springframework.web.bind.annotation.RestControllerAdvice;
+import ru.serega6531.packmate.exception.PatternValidationException;
+import ru.serega6531.packmate.exception.RequestValidationException;
+
+import java.util.Map;
+
+@RestControllerAdvice
+public class PatternValidationHandler {
+
+ @ExceptionHandler(PatternValidationException.class)
+ public ResponseEntity