init
This commit is contained in:
commit
303438d206
217 files changed
+66681
No files matched your search
@@ -0,0 +1,170 @@
|
||||
<a id="administrator-workflows"></a>
|
||||
# Рабочие процессы администратора
|
||||
|
||||
[English](ADMIN_WORKFLOWS.md) | Русский
|
||||
|
||||
Практический маршрут для одного администратора и доверенной команды. Карточки и ручное переписывание hashes не требуются. Сохраните этот checkout, русские инструкции и приватные зависимости для офлайн-работы. [Короткая памятка для печати](TEAM_LAN_ADMIN_CHEATSHEET-RU.md).
|
||||
|
||||
<a id="roles-and-command-conventions"></a>
|
||||
## Роли и правила выполнения команд
|
||||
|
||||
DurkaHelper готовит и управляет стеком. S4DFarm собирает результаты и отправляет их жюри. Координатор Neo хранит задания и планирует исполнение; **workers выполняют их и отправляют совпадающие с форматом значения stdout прямо в ферму**. Участники подключают управляющие клиенты к одному координатору; отдельный worker каждому не нужен. Packmate анализирует трафик. Сканер проверяет локальные копии исходников; патчи применяются вручную штатным механизмом развёртывания сервиса.
|
||||
|
||||
Команды ниже выполняются **из корня DurkaHelper на Mac/Linux администратора**, кроме явно обозначенного терминала Neo. Выберите один конфиг и указывайте его во всех командах стека:
|
||||
|
||||
```bash
|
||||
DURKA_CONFIG=local/competition.json
|
||||
```
|
||||
|
||||
В каждом новом терминале задайте переменную снова. `local/durka.json` — конфиг CLI по умолчанию, встречающийся в старых тематических примерах; не запустите случайно второе окружение. Примерные адреса предназначены для документации, а не работы на соревновании. `doctor`, `status` и `scan` — read-only; `init`, `setup`, `configure`, `up`, `worker`, `submit`, импорт и `down` меняют приватные файлы или собственные сервисы. Не используйте общий prune, Docker reset или `down -v`.
|
||||
|
||||
<a id="workflow-01--deploy-and-prepare-offline"></a>
|
||||
## Workflow 01 — Развёртывание и подготовка офлайн
|
||||
|
||||
**Нужно заранее:** одобренные Python 3.10+, Git 2.30+, Docker Desktop/Engine с Compose v2; свободные диск и RAM; список команд, IP сервисов, формат флага, параметры жюри и разрешённый LAN-адрес от организаторов. Первая подготовка требует Интернета. Время: 30–60 минут впервые; около 5 минут для подготовленного запуска. [Первый запуск Mac](MACOS_FIRST_RUN-RU.md) описывает установку; [полный гайд](MACOS_FULL_DEPLOYMENT_AND_TESTING-RU.md) служит справочником.
|
||||
|
||||
Только для новой установки:
|
||||
|
||||
```bash
|
||||
python3 durka.py --config "$DURKA_CONFIG" init
|
||||
```
|
||||
|
||||
Откройте этот приватный JSON редактором. Сохраните сгенерированные credentials. В `profile.bind_address` укажите настоящий LAN IPv4 администратора для команды/native workers; выберите свободные `profile.ports.farm/neo/packmate`. Заполните `profile.farm.teams`, `flag_format`, `protocol_settings.SYSTEM_URL/SYSTEM_TOKEN`, `submit_limit`, `submit_period` и `flag_lifetime` по данным организаторов. `protocol: ructf_http` подходит только совместимому HTTP-интерфейсу. FILE `profile.packmate.local_ip` — **IP стороны сервиса в захваченных пакетах**, не адрес администратора. После подготовки не меняйте пути sources/workspace и платформу.
|
||||
|
||||
```bash
|
||||
python3 durka.py --config "$DURKA_CONFIG" doctor
|
||||
python3 durka.py --config "$DURKA_CONFIG" setup
|
||||
python3 durka.py --config "$DURKA_CONFIG" up
|
||||
python3 durka.py --config "$DURKA_CONFIG" status
|
||||
```
|
||||
|
||||
`setup` скачивает/собирает закреплённые зависимости: выполните его до поездки, не во время офлайн-игры. `up` использует подготовленные образы и запускает БД → Farm → координатор Neo → Packmate. Worker и отправка включаются отдельно. Откройте напечатанные URL Farm/Packmate, войдите, проверьте список команд и повторите с другого устройства. Внутренние БД не являются интерфейсами команды. У Neo нет web-dashboard. Передавайте UI credentials и ключ Neo приватно, вне публичных скриншотов.
|
||||
|
||||
**Уже подготовлено:** пропустите `init/setup`. Чтобы применить настройки организаторов, остановите native worker и собственный стек, измените тот же JSON, затем:
|
||||
|
||||
```bash
|
||||
python3 durka.py --config "$DURKA_CONFIG" configure
|
||||
python3 durka.py --config "$DURKA_CONFIG" up
|
||||
python3 durka.py --config "$DURKA_CONFIG" status
|
||||
```
|
||||
|
||||
`configure` требует остановленного стека и не меняет credentials, платформу или структуру хранилищ. При ошибке обновления оставьте стек остановленным и используйте `configure --rollback`. При проблемах LAN проверяйте фактические bind/IP, порты и согласованные настройки application firewall; не отключайте защиту сети целиком.
|
||||
|
||||
**Офлайн-проверка:** сохраните кеш исходников, образы/данные Docker, приватные конфиг/workspace, совместимый Neo binary и все зависимости скриптов. Отдельный Linux LIVE bundle готовится в Workflow 05. Разрешённым способом уберите Интернет, оставив нужную LAN; выполните `down`, `up`, `status`, войдите в оба UI, запустите безвредное задание Neo, просканируйте локальную копию и импортируйте закрытый PCAP. Это проверка перезапуска подготовленной машины, не установки на пустую машину. [Офлайн-подготовка и чистое окружение игры](offline-bundles-RU.md).
|
||||
|
||||
<a id="workflow-02--scan-patch-and-verify"></a>
|
||||
## Workflow 02 — Сканирование, патч и проверка
|
||||
|
||||
**Нужно:** разрешённая локальная копия исходников, порядок запуска/checker сервиса и ответственный за rollback. Рабочий каталог — корень репозитория; время 10–30 минут на небольшой патч, в зависимости от сервиса.
|
||||
|
||||
```bash
|
||||
python3 durka.py scan /path/to/service --patches
|
||||
```
|
||||
|
||||
Exit `1` — сигналы для разбора; `2` — неполный/некорректный вход. Прочитайте связанную рекомендацию, подтвердите применимость, сохраните оригиналы изменяемых файлов и при необходимости консистентный native backup БД. Примените один минимальный патч **вручную**. Прогоните regression tests сервиса, обычные login/read/write сценарии, старые данные и настоящий checker соревнования; повторите скан. Чистый скан или `/health` недостаточны. Единой restart-команды для всех Vulnbox нет: используйте механизм конкретного сервиса, а не `down/up` тулсета.
|
||||
|
||||
При регрессии восстановите предыдущие код/образ с сохранением текущих игровых данных. Не накатывайте старую БД поверх записей новых раундов. [Проверка патча](patch-validation-RU.md) содержит подробности; расширенные records для `patch-check` необязательны в этом ручном маршруте. [Backup/recovery](../deployment/README-RU.md#native-backup-and-quarantine-restore) относится к стеку тулсета, а не любому защищаемому сервису.
|
||||
|
||||
<a id="workflow-03--prepare-scripts-and-neo-execution"></a>
|
||||
## Workflow 03 — Скрипты и исполнение Neo
|
||||
|
||||
**Нужно:** совместимый Neo v2.4.2 client, приватный конфиг с реальными host/key координатора, согласованные ID заданий и разрешённый список команд. У каждого worker должны быть настоящий интерпретатор, пакеты, вспомогательные файлы и маршруты к Farm и разрешённым сервисам. Встроенный light-worker предоставляет shell, не произвольные Python/Sage packages. Время: 10–15 минут для первого безвредного задания. [Установка Neo и полные примеры](neo-RU.md).
|
||||
|
||||
В **отдельном терминале**, из корня репозитория, можно запустить shell-only worker:
|
||||
|
||||
```bash
|
||||
python3 durka.py --config "$DURKA_CONFIG" worker
|
||||
```
|
||||
|
||||
Или из каталога распакованного **Neo client** запустите один подготовленный native worker; для администрирования заданий оба одновременно не нужны:
|
||||
|
||||
```bash
|
||||
./neo --verbose=false --config client_config.yml run --jobs 1 --endless-jobs 0
|
||||
```
|
||||
|
||||
Используйте приватный клиентский конфиг с уникальным worker `client_id` и корректным каталогом заданий. В чистом deployment можно вместо него использовать с подготовленным binary сгенерированный `config/neo-native.yml`; после смены LAN исправьте host либо передайте `--host LAN_IP:NEO_PORT`. Внешним workers недоступно внутреннее имя Farm из loopback-профиля.
|
||||
|
||||
В каталоге **Neo client автора** создайте безвредный `exploits/ready.sh` из гайда Neo, затем:
|
||||
|
||||
```bash
|
||||
chmod u+x exploits/ready.sh
|
||||
./neo --verbose=false --config client_config.yml add --id ready-author-a --disabled --interval 1m --timeout 3s exploits/ready.sh
|
||||
./neo --verbose=false --config client_config.yml single ready-author-a
|
||||
./neo --verbose=false --config client_config.yml tail --count 20 ready-author-a
|
||||
```
|
||||
|
||||
Перед `single` дождитесь скачивания нового задания worker и перезапуска его execution loops. Ожидается `worker ready for ...`, не флаг. `single` охватывает **все настроенные команды**, не включает повторение. Каждый автор использует отдельный общий ID. После успешного разрешённого одиночного прогона намеренно проверьте расписание:
|
||||
|
||||
```bash
|
||||
./neo --verbose=false --config client_config.yml enable ready-author-a
|
||||
./neo --verbose=false --config client_config.yml tail --count 20 ready-author-a
|
||||
./neo --verbose=false --config client_config.yml disable ready-author-a
|
||||
```
|
||||
|
||||
Дождитесь следующих запусков с интервалом в минуту перед отключением. Cron не нужен; закрытие управляющего клиента не отключает задание. После отключения новых запусков остановите native worker через Ctrl+C; уже исполняемые задания могут завершиться. При сбое сначала проверьте наличие/скачивание worker, интерпретатор и маршруты. Не показывайте raw `neo info` или debug logs на экране: они могут раскрыть credentials.
|
||||
|
||||
<a id="workflow-04--farm-and-jury-submission"></a>
|
||||
## Workflow 04 — Ферма и отправка жюри
|
||||
|
||||
**Нужно:** согласованные endpoint/token жюри, точные regex флага, lifetime и rate limits; легитимное синтетическое либо предоставленное организаторами тестовое значение. Время: 5–10 минут. С placeholders отправку не включайте. [Справочник фермы](s4dfarm-RU.md).
|
||||
|
||||
Совместимый интерфейс ForcAD использует **HTTP PUT `/flags`**, JSON-массив флагов и заголовок `X-Team-Token`. Настройте полный URL организатора и приватный token через Workflow 01; не переносите путь, лимиты или token с другого соревнования. Поддерживаемый adapter — `ructf_http`; другой протокол требует отдельной проверки, не непроверенной подмены адаптера.
|
||||
|
||||
Убедитесь, что разрешённый тестовый stdout worker появился в Farm, затем из корня репозитория включите отправку:
|
||||
|
||||
```bash
|
||||
python3 durka.py --config "$DURKA_CONFIG" submit
|
||||
```
|
||||
|
||||
`QUEUED` подтверждает только приём в ферму. Проверьте окончательный статус **и ответ receiver**, а также жюри/scoreboard, если доступно. Invalid, duplicate и expired проверяйте на контролируемом синтетическом жюри; не делайте массовую повторную отправку на реальном событии. Deduplication Farm может подавить второе одинаковое значение до HTTP-запроса. `SKIPPED` бывает локальной политикой очереди, не ответом ForcAD. Если очередь зависла, проверьте включение отправки, endpoint/token, lifetime, rate limits и связь worker → Farm. Не печатайте tokens при диагностике.
|
||||
|
||||
Чтобы безопасно остановить отправку, отключите новые задания Neo, остановите native workers и выполните `down` выбранного стека. После `up` отправка включается явно снова. Перед включением проверьте восстановленные очереди: нельзя слепо переотправлять просроченные данные.
|
||||
|
||||
<a id="workflow-05--packmate-live-or-file"></a>
|
||||
## Workflow 05 — Packmate LIVE или FILE
|
||||
|
||||
**Нужно:** разрешённый источник трафика. Mac на обычном Ethernet не видит весь трафик Vulnbox. FILE анализирует закрытые файлы, **не является непрерывным LIVE**. Время: 10–20 минут для подготовленного Linux LIVE; 3–5 минут на FILE import. [Варианты трафика](traffic-capture-RU.md) и [инструкция удалённого LIVE](packmate-remote-RU.md).
|
||||
|
||||
На машине администратора при наличии Интернета один раз подготовьте **отдельную пару Linux AMD64 образов**. ARM64-образ БД с Mac не заменяет её:
|
||||
|
||||
```bash
|
||||
python3 durka.py traffic live bundle --output local/packmate-live-ready --download --apply
|
||||
```
|
||||
|
||||
Уже успешный bundle сохраните; команда требует нового output path. Python на целевой машине не нужен. Linux LIVE требует rootful Docker/Compose, проверенную SSH identity, явно разрешённый **интерфейс целиком** и согласие на host networking + NET_RAW. Privileged container, NET_ADMIN и Docker socket mount не нужны. Сначала выполните read-only discovery с настоящими разрешёнными host/key:
|
||||
|
||||
```bash
|
||||
python3 durka.py traffic live doctor --host example@vulnbox.example --key ~/.ssh/ctf_capture
|
||||
```
|
||||
|
||||
`--docker /absolute/approved-wrapper` нужен только если обычный `docker` недоступен пользователю; passwordless sudo не выбирается автоматически. Doctor не меняет права/firewall. Проверьте SSH fingerprint по доверенному каналу. Затем создайте новый приватный конфиг цели с фактическими результатами doctor:
|
||||
|
||||
```bash
|
||||
python3 durka.py traffic live init --host example@vulnbox.example --key ~/.ssh/ctf_capture --remote-dir /home/example/durka-packmate-live --interface eth0 --service-ip 192.0.2.10 --bind 192.0.2.20 --ui-port 65000 --db-port 55432
|
||||
```
|
||||
|
||||
**Конфигурация заполняется здесь, до `up`:** при необходимости измените `local/packmate-remote.json`. В его `profile` находятся interface, IP стороны сервиса, Linux UI bind/ports, TCP/UDP timeouts и retention. `bind` назначен Linux, не Mac. БД доступна только через loopback. **Названия сервисов, порты и шаблоны поиска регистрируются отдельно в UI Packmate**. Сгенерированные application properties/Compose не редактируйте. Правка JSON после deployment не перенастраивает работающую установку; перед созданием замены прочитайте удалённый гайд.
|
||||
|
||||
```bash
|
||||
python3 durka.py traffic live doctor --bundle local/packmate-live-ready
|
||||
python3 durka.py traffic live up --bundle local/packmate-live-ready --apply --host-network-approved --interface-scope-approved
|
||||
python3 durka.py traffic live status
|
||||
```
|
||||
|
||||
Это переносит и загружает готовые образы без Интернета на цели, затем запускает только собственный project. Меняются удалённые приватные файлы/контейнеры, используются одобренные capture privileges. Откройте напечатанный URL, войдите с данными приватного конфига; на Mac `traffic live password` копирует пароль, не печатая его. Зарегистрируйте реальные порты обоих сервисов. Выполните обычный известный запрос: проверьте запрос/ответ, направление относительно сервиса, timestamps и checker health, затем перезапуск capture через собственные `down --apply` / `up ...`. Retention ограничивает возраст, не жёсткий размер диска; следите за диском. Readiness/authentication PASS сами по себе не доказывают захват.
|
||||
|
||||
Для FILE получите **закрытый** PCAP разрешённым порядком захвата/передачи. Из checkout администратора:
|
||||
|
||||
```bash
|
||||
python3 durka.py --config "$DURKA_CONFIG" traffic import /path/to/closed-capture.pcap
|
||||
python3 durka.py --config "$DURKA_CONFIG" status
|
||||
```
|
||||
|
||||
Выберите/зарегистрируйте сервис в локальном UI Packmate и один раз нажмите **жёлтую кнопку обработки со стрелкой вниз**; не ищите подпись Start или Load PCAPs. Дождитесь обработки, найдите известный запрос и ответ, затем повторите с другим закрытым файлом. Import сохраняет предыдущий файл и перезапускает только Packmate. Пусто: проверьте IP сервиса, порт/шаблон, известный marker, состояние обработки и timestamps потоков; не предполагается наличие фильтра времени. На Apple Silicon Packmate использует AMD64 emulation; измерьте задержку локально.
|
||||
|
||||
**Остановка/восстановление:** остановите новые входные данные, сохраните нужные приватные данные, выполните `traffic live down --apply` только для этого настроенного Linux capture; `durka.py --config "$DURKA_CONFIG" down` — для локального стека. Оба сохраняют данные/образы. Не удаляйте live-файлы БД. Если LIVE запрещён или трафик не виден, используйте FILE как резерв и отмечайте отсутствие continuous capture. [Native recovery и отдельный restore](../deployment/README-RU.md#native-backup-and-quarantine-restore) и [офлайн-гайд](offline-bundles-RU.md) описывают восстановление; restore нужно проверить отдельно, прежде чем полагаться на него.
|
||||
|
||||
<a id="final-operator-checks"></a>
|
||||
## Финальные проверки оператора
|
||||
|
||||
Войдите с каждого участвующего устройства; выполните полезное действие UI и переподключение. Проверьте фактическую среду каждого скрипта, приём Farm → жюри, разрешённый LIVE либо closed FILE, офлайн-перезапуск под обычной нагрузкой. Маршруты события, capture permission и настройки организаторов проверяются на конкретном соревновании. Linux tests и hosted macOS CI не доказывают совместимость Docker Desktop, командной LAN или локальных правил. Невыполненные проверки — **NOT TESTED**, не готовность.
|
||||
@@ -0,0 +1,162 @@
|
||||
# Administrator workflows
|
||||
|
||||
English | [Русский](ADMIN_WORKFLOWS-RU.md)
|
||||
|
||||
The practical route for one administrator and a trusted team. No evidence cards or manually copied hashes are required. Keep this checkout, its Russian pages and private dependencies available offline. [Printable quick reference](TEAM_LAN_ADMIN_CHEATSHEET.md).
|
||||
|
||||
## Roles and command conventions
|
||||
|
||||
DurkaHelper prepares and controls the stack. S4DFarm collects results and submits them to the jury. Neo's coordinator stores tasks and schedules execution; **workers execute them and send matching stdout values directly to the farm**. Participants use control clients connected to the same coordinator; they do not each need a worker. Packmate analyzes traffic. The scanner reviews local source copies; patches are applied manually through the service's own deployment mechanism.
|
||||
|
||||
Commands below run in the **DurkaHelper repository root on the administrator's Mac/Linux machine**, except the explicitly marked Neo terminal. Choose one config and use it on every stack command:
|
||||
|
||||
```bash
|
||||
DURKA_CONFIG=local/competition.json
|
||||
```
|
||||
|
||||
Set this variable again in each new terminal. `local/durka.json` is the CLI default and appears in older topic examples; do not accidentally operate a second deployment. Example addresses are documentation values, not working event targets. Read-only commands are `doctor`, `status` and `scan`; `init`, `setup`, `configure`, `up`, `worker`, `submit`, imports and `down` change private files or owned services. Never use global prune, Docker reset or `down -v`.
|
||||
|
||||
## Workflow 01 — Deploy and prepare offline
|
||||
|
||||
**Before:** approved Python 3.10+, Git 2.30+, Docker Desktop/Engine with Compose v2; sufficient disk and RAM; organizer's team map, service IPs, flag format, jury settings and permitted LAN address. First-time preparation needs Internet. Allow 30–60 minutes initially; about 5 minutes for a prepared start. [First Mac run](MACOS_FIRST_RUN.md) covers installation; [full guide](MACOS_FULL_DEPLOYMENT_AND_TESTING.md) is the reference.
|
||||
|
||||
For a new installation only:
|
||||
|
||||
```bash
|
||||
python3 durka.py --config "$DURKA_CONFIG" init
|
||||
```
|
||||
|
||||
Edit that private JSON in an editor. Preserve generated credentials. Set `profile.bind_address` to the administrator's actual LAN IPv4 for team/native-worker access; choose free `profile.ports.farm/neo/packmate`. Set `profile.farm.teams`, `flag_format`, `protocol_settings.SYSTEM_URL/SYSTEM_TOKEN`, `submit_limit`, `submit_period` and `flag_lifetime` from the organizers. Keep `protocol: ructf_http` only for the compatible HTTP interface. Set FILE `profile.packmate.local_ip` to the **service-side IP in captured packets**, not the administrator's address. Leave source/workspace paths and platform unchanged after preparation.
|
||||
|
||||
```bash
|
||||
python3 durka.py --config "$DURKA_CONFIG" doctor
|
||||
python3 durka.py --config "$DURKA_CONFIG" setup
|
||||
python3 durka.py --config "$DURKA_CONFIG" up
|
||||
python3 durka.py --config "$DURKA_CONFIG" status
|
||||
```
|
||||
|
||||
`setup` downloads/builds pinned dependencies; do it before travel, not during an offline game. `up` uses prepared images and starts databases → Farm → Neo coordinator → Packmate. Worker and submission are separate opt-ins. Open the printed Farm/Packmate URLs, authenticate, check the team map and repeat from a second device. Internal databases are not team interfaces. Neo has no web dashboard. Share UI credentials and the Neo key privately, away from public screenshots.
|
||||
|
||||
**Already prepared:** skip `init/setup`. To apply organizer settings, stop the native worker and owned stack, edit the same JSON, then:
|
||||
|
||||
```bash
|
||||
python3 durka.py --config "$DURKA_CONFIG" configure
|
||||
python3 durka.py --config "$DURKA_CONFIG" up
|
||||
python3 durka.py --config "$DURKA_CONFIG" status
|
||||
```
|
||||
|
||||
`configure` requires a stopped stack and cannot change credentials, platform or storage layout. If its update fails, keep the stack stopped and use `configure --rollback`. If LAN fails, check actual bind/IP, ports and approved application firewall settings; do not disable network security globally.
|
||||
|
||||
**Offline checkpoint:** retain the source cache, Docker images/data, private config/workspace, compatible Neo binary and every script dependency. Prepare the separate Linux LIVE bundle in Workflow 05. Using a permitted arrangement with Internet absent but required LAN intact, run `down`, `up`, `status`; authenticate both UIs, run a harmless Neo task, scan a local copy and import a closed PCAP. This proves restart on the prepared machine, not installation on a blank machine. [Offline preparation and clean event state](offline-bundles.md).
|
||||
|
||||
## Workflow 02 — Scan, patch and verify
|
||||
|
||||
**Before:** an authorized local source copy, service startup/checker procedure and rollback owner. Run from the repository root; allow 10–30 minutes per small patch, depending on the service.
|
||||
|
||||
```bash
|
||||
python3 durka.py scan /path/to/service --patches
|
||||
```
|
||||
|
||||
Exit `1` means review findings; `2` means incomplete/invalid input. Read the linked remediation, confirm applicability and preserve original changed files plus a consistent native database backup when needed. Apply one minimal patch **manually**. Run the service's regression tests, normal login/read/write scenarios, old-data checks and actual competition checker; repeat the scan. A clean scan or `/health` alone is insufficient. No generic restart command exists for every Vulnbox: use the supplied service mechanism, not the toolkit's `down/up`.
|
||||
|
||||
If functionality regresses, restore previous code/image while preserving current game data. Do not restore an old database over new-round records. [Patch validation](patch-validation.md) gives detailed checks; its advanced `patch-check` records are optional for this manual route. [Backup/recovery](../deployment/README.md#native-backup-and-quarantine-restore) applies to the toolkit stack, not every protected service.
|
||||
|
||||
## Workflow 03 — Prepare scripts and Neo execution
|
||||
|
||||
**Before:** compatible Neo v2.4.2 client, private config with actual coordinator host/key, agreed task IDs and allowed team list. Every worker needs the script's actual interpreter, packages, auxiliary files and routes to both Farm and permitted services. The bundled light worker supplies shell, not arbitrary Python/Sage packages. Allow 10–15 minutes for the first harmless task. [Neo installation and complete examples](neo.md).
|
||||
|
||||
In a **separate terminal**, a shell-only worker can be started from the repository root:
|
||||
|
||||
```bash
|
||||
python3 durka.py --config "$DURKA_CONFIG" worker
|
||||
```
|
||||
|
||||
Alternatively, in the extracted **Neo client directory**, start one prepared native worker; do not start both merely to administer tasks:
|
||||
|
||||
```bash
|
||||
./neo --verbose=false --config client_config.yml run --jobs 1 --endless-jobs 0
|
||||
```
|
||||
|
||||
Use a private client config with a unique worker `client_id` and valid task directory. A generated clean deployment's `config/neo-native.yml` can be used with the prepared binary instead; after a LAN change update its host or pass `--host LAN_IP:NEO_PORT`. Outside workers cannot use the container-only Farm hostname from a loopback profile.
|
||||
|
||||
In the author's **Neo client directory**, create the harmless `exploits/ready.sh` from the Neo guide, then:
|
||||
|
||||
```bash
|
||||
chmod u+x exploits/ready.sh
|
||||
./neo --verbose=false --config client_config.yml add --id ready-author-a --disabled --interval 1m --timeout 3s exploits/ready.sh
|
||||
./neo --verbose=false --config client_config.yml single ready-author-a
|
||||
./neo --verbose=false --config client_config.yml tail --count 20 ready-author-a
|
||||
```
|
||||
|
||||
Wait for the worker to download the new task and restart its execution loops before `single`. Expected: `worker ready for ...`, not a flag. `single` covers **all configured teams**, without enabling recurrence. Each author uses a distinct shared ID. After a successful permitted single run, deliberately test scheduling:
|
||||
|
||||
```bash
|
||||
./neo --verbose=false --config client_config.yml enable ready-author-a
|
||||
./neo --verbose=false --config client_config.yml tail --count 20 ready-author-a
|
||||
./neo --verbose=false --config client_config.yml disable ready-author-a
|
||||
```
|
||||
|
||||
Observe subsequent one-minute runs before disabling. No cron is needed; closing the control client does not disable a task. Stop a native worker with Ctrl+C after disabling future work; already running jobs may finish. For failures, first check worker presence/download, interpreter and routes. Avoid raw `neo info` or debug logs on screen: they may disclose credentials.
|
||||
|
||||
## Workflow 04 — Farm and jury submission
|
||||
|
||||
**Before:** approved jury endpoint/token, exact flag regex, lifetime and rate limits; a legitimate synthetic or organizer-provided test value. Allow 5–10 minutes. Do not enable against placeholders. [Farm reference](s4dfarm.md).
|
||||
|
||||
ForcAD's compatible interface uses **HTTP PUT `/flags`**, a JSON array of flags and the `X-Team-Token` header. Configure the full organizer-provided URL and private token via Workflow 01; do not assume the path, limits or token from another event. The maintained adapter is `ructf_http`; another protocol requires separate validation, not an untested adapter substitution.
|
||||
|
||||
Confirm the worker's permitted test output appears in Farm, then enable submission from the repository root:
|
||||
|
||||
```bash
|
||||
python3 durka.py --config "$DURKA_CONFIG" submit
|
||||
```
|
||||
|
||||
`QUEUED` proves ingestion only. Verify the final status **and receiver response**, plus jury/scoreboard confirmation where provided. Use a controlled synthetic jury to check invalid, duplicate and expired results; do not mass-resubmit to a real event. Farm deduplication may suppress a second identical value before any HTTP request. `SKIPPED` can be local queue policy, not a ForcAD response. If queued indefinitely, check enabled submission, endpoint/token, lifetime, rate limits and worker-to-Farm reachability. Never print tokens during diagnostics.
|
||||
|
||||
To stop submission safely, disable future Neo tasks, stop native workers and run the selected stack's `down`. Restart with `up`; submission must be explicitly enabled again. Review restored queues before enabling: expired recovered data must not be replayed blindly.
|
||||
|
||||
## Workflow 05 — Packmate LIVE or FILE
|
||||
|
||||
**Before:** an authorized traffic source. A Mac on ordinary Ethernet does not see all Vulnbox traffic. FILE is closed-file analysis, **not continuous LIVE**. Allow 10–20 minutes for a prepared Linux LIVE deployment; 3–5 minutes per FILE import. [Traffic choices](traffic-capture.md) and [remote LIVE instructions](packmate-remote.md).
|
||||
|
||||
On the administrator's machine, while online, prepare the **separate Linux AMD64 image pair** once. A Mac's ARM64 database image is not a substitute:
|
||||
|
||||
```bash
|
||||
python3 durka.py traffic live bundle --output local/packmate-live-ready --download --apply
|
||||
```
|
||||
|
||||
Keep an already successful bundle; this command requires a new output path. Target Python is not required. Linux LIVE needs rootful Docker/Compose, verified SSH identity, an explicitly permitted **whole interface**, and approval for host networking + NET_RAW. No privileged container, NET_ADMIN or Docker socket mount is required. First run read-only discovery, using the actual authorized host/key:
|
||||
|
||||
```bash
|
||||
python3 durka.py traffic live doctor --host example@vulnbox.example --key ~/.ssh/ctf_capture
|
||||
```
|
||||
|
||||
Use `--docker /absolute/approved-wrapper` only if ordinary `docker` is unavailable to that user; passwordless sudo is not automatically selected. No permission/firewall changes are made by doctor. Verify the SSH fingerprint through a trusted channel. Then initialize a new private target config using actual doctor results:
|
||||
|
||||
```bash
|
||||
python3 durka.py traffic live init --host example@vulnbox.example --key ~/.ssh/ctf_capture --remote-dir /home/example/durka-packmate-live --interface eth0 --service-ip 192.0.2.10 --bind 192.0.2.20 --ui-port 65000 --db-port 55432
|
||||
```
|
||||
|
||||
**Configuration happens here, before `up`:** edit `local/packmate-remote.json` if necessary. Its `profile` holds interface, service-side IP, Linux UI bind/ports, TCP/UDP timeouts and retention. `bind` is an address assigned to Linux, not the Mac. The database is loopback-only. Service **names, ports and search patterns are registered separately in the Packmate UI**. Do not edit generated application properties/Compose files. Editing JSON after deployment does not reconfigure the running installation; see the remote guide before creating a replacement.
|
||||
|
||||
```bash
|
||||
python3 durka.py traffic live doctor --bundle local/packmate-live-ready
|
||||
python3 durka.py traffic live up --bundle local/packmate-live-ready --apply --host-network-approved --interface-scope-approved
|
||||
python3 durka.py traffic live status
|
||||
```
|
||||
|
||||
This transfers and loads prepared images without target Internet, then starts only the owned project. It changes remote private files/containers and uses approved capture privileges. Open its printed URL, authenticate using the private config; on Mac `traffic live password` copies the password without printing it. Register both services' real ports. Produce a normal known request: verify its request/response, service-side direction, timestamps and checker health, then test capture restart using scoped `down --apply` / `up ...`. Retention limits age, not hard disk capacity; watch disk usage. Readiness/authentication PASS alone does not prove captured traffic.
|
||||
|
||||
For FILE, obtain a **closed** PCAP through the permitted capture/transfer procedure. On the administrator's repository checkout:
|
||||
|
||||
```bash
|
||||
python3 durka.py --config "$DURKA_CONFIG" traffic import /path/to/closed-capture.pcap
|
||||
python3 durka.py --config "$DURKA_CONFIG" status
|
||||
```
|
||||
|
||||
Select/register the service in the local Packmate UI and click the **yellow downward-arrow processing button** once; do not look for a Start or Load PCAPs label. Wait for processing, find the known request and matching response, then repeat with another closed file. The import retains the previous file and restarts only Packmate. Empty results: check service IP, port/pattern, known marker, processing state and stream timestamps; do not assume a time-filter UI exists. Packmate uses AMD64 emulation on Apple Silicon; measure latency locally.
|
||||
|
||||
**Shutdown/recovery:** stop new input, preserve required private data, run `traffic live down --apply` for that configured Linux capture only; run `durka.py --config "$DURKA_CONFIG" down` for the local stack. Both retain persistent data/images. Never delete live database files. If LIVE is forbidden or has no traffic visibility, use FILE as a fallback and label continuous capture unavailable. [Native recovery and quarantined restore](../deployment/README.md#native-backup-and-quarantine-restore) and [offline guide](offline-bundles.md) cover recovery; test restore separately before relying on it.
|
||||
|
||||
## Final operator checks
|
||||
|
||||
Authenticate each participating device; exercise a useful UI action and reconnect. Verify each actual script environment, Farm-to-jury acceptance, authorized LIVE or closed FILE flow, offline restart under normal load. Event routes, capture permission and organizer settings require event-specific verification. Linux tests and hosted macOS CI do not prove Docker Desktop, team LAN or local policy compatibility. Keep unperformed checks **NOT TESTED**, not ready.
|
||||
@@ -0,0 +1,28 @@
|
||||
# Возможности и ограничения
|
||||
|
||||
[English](CAPABILITY_INVENTORY.md) | Русский
|
||||
|
||||
<a id="capabilities-and-limits"></a>
|
||||
|
||||
Для установки используйте [основную инструкцию](MACOS_FULL_DEPLOYMENT_AND_TESTING-RU.md), для работы — [шпаргалку администратора](TEAM_LAN_ADMIN_CHEATSHEET-RU.md).
|
||||
|
||||
| Инструмент | Что делает | Важное ограничение |
|
||||
|---|---|---|
|
||||
| Сканер DurkaHelper | Проверяет локальные исходники/конфиги; 174 правила и справочник из 294 разделов | Находки требуют ревью; нет удалённой эксплуатации или автоматических патчей |
|
||||
| Defense operations | Baseline, изменения файлов, health, сравнение патчей, восстановление файлов в staging | Явная область проверки; HTTP health не заменяет checker соревнования |
|
||||
| S4DFarm | Принимает флаги и отправляет их на соревнование | Поддерживается существующий адаптер ructf_http; патчи ферма не распространяет |
|
||||
| Neo | Координирует командные скрипты и workers | Включайте только доверенные задачи; зависимости скрипта должны быть в worker |
|
||||
| Packmate FILE | Ищет request/response в закрытом PCAP | Не непрерывный захват; опубликованный образ на Apple Silicon использует amd64 |
|
||||
| Packmate LIVE | Захватывает трафик в разрешённой Linux-точке наблюдения | Подключённый к LAN Mac не видит автоматически весь трафик Vulnbox |
|
||||
| Deployment helpers | Готовят закреплённые компоненты, сохраняют данные, останавливают только свой проект | Нужен Docker runtime; на Windows поддерживается core, а не этот deployment |
|
||||
| Recovery helpers | Нативные dumps и восстановление в отдельный candidate | Нет слепой перезаписи production или повтора очереди |
|
||||
| Офлайн-работа | Core без скачиваний; подготовленный deployment без pulls/builds | Внешний runtime нужно установить и кешировать заранее; одной копии репозитория мало |
|
||||
|
||||
<a id="support"></a>
|
||||
## Поддержка
|
||||
|
||||
Core использует Python 3.10+ и только стандартную библиотеку. Тестами покрыты Windows, Linux x86-64 и hosted macOS ARM64; Docker-интеграция проверяется на Linux x86-64. Реальный Mac, Docker Desktop, видимость трафика и устройства команды требуют локальной репетиции. Логи CI находятся в GitHub Actions, а не в отчётах внутри репозитория.
|
||||
|
||||
Версии и идентификаторы образов сопровождаются в [toolchain.lock.json](../config/toolchain.lock.json). Проверки выполняются автоматически: оператор не заполняет SHA-формы.
|
||||
|
||||
Чистый scan не доказывает безопасность сервиса. Успех в лаборатории не доказывает, что сеть соревнования разрешает захват или что все участники имеют доступ к инструментам.
|
||||
@@ -0,0 +1,25 @@
|
||||
# Capabilities and limits
|
||||
|
||||
English | [Русский](CAPABILITY_INVENTORY-RU.md)
|
||||
|
||||
Use the [main guide](MACOS_FULL_DEPLOYMENT_AND_TESTING.md) for setup and the [admin sheet](TEAM_LAN_ADMIN_CHEATSHEET.md) during operation.
|
||||
|
||||
| Tool | What it does | Important limit |
|
||||
|---|---|---|
|
||||
| DurkaHelper scanner | Reviews local source/configuration; 174 rules and a 294-section remediation guide | Findings need review; no remote exploit or automatic patching |
|
||||
| Defense operations | Baseline, file drift, health, patch comparison, staged file recovery | Explicit scope; HTTP health is not a competition checker |
|
||||
| S4DFarm | Receives flags and submits them to the competition | Only the existing ructf_http adapter is maintained; it does not distribute patches |
|
||||
| Neo | Coordinates team scripts and workers | Enable trusted tasks deliberately; script dependencies must exist in the worker |
|
||||
| Packmate FILE | Searches request/response streams from a closed PCAP | Not continuous capture; published image uses amd64 on Apple Silicon |
|
||||
| Packmate LIVE | Captures at an authorized Linux observation point | A LAN-connected Mac does not automatically see Vulnbox traffic |
|
||||
| Deployment helpers | Prepare pinned components, preserve data, stop only their own project | Docker runtime required; Windows supports the core, not this deployment |
|
||||
| Recovery helpers | Native dumps and isolated candidate restores | No blind production overwrite or queue replay |
|
||||
| Offline operation | Core without downloads; prepared deployment without pulls/builds | Install/cache the external runtime first; copying the repository alone is not enough |
|
||||
|
||||
## Support
|
||||
|
||||
The core is Python 3.10+ standard-library-only. Windows, Linux x86-64 and hosted macOS ARM64 are covered by tests; Docker-based integration is exercised on Linux x86-64. The actual Mac, Docker Desktop, traffic visibility and team devices still need a local rehearsal. CI logs live in GitHub Actions, not as reports inside this repository.
|
||||
|
||||
Versions and image identities are maintained in [toolchain.lock.json](../config/toolchain.lock.json). They are checked automatically: operators do not fill SHA forms.
|
||||
|
||||
A passing scan is not proof that a service is secure. A passing lab is not proof that the event network permits capture or that every participant can reach the tools.
|
||||
@@ -0,0 +1,107 @@
|
||||
<a id="first-mac-run"></a>
|
||||
# Первый запуск на Mac
|
||||
|
||||
[English](MACOS_FIRST_RUN.md) | Русский
|
||||
|
||||
Это короткий маршрут оператора, а не заявление о готовности ноутбука. Все шаги с runtime Mac ниже имеют статус **PENDING: требуется проверка на реальном Mac**. Выполняйте их только после согласования Docker Desktop, локальных сервисов, Ethernet. Подробная установка, поля конфигурации и backup описаны в [полном руководстве](MACOS_FULL_DEPLOYMENT_AND_TESTING-RU.md).
|
||||
|
||||
<a id="1-read-only-preflight"></a>
|
||||
## 1. Preflight без изменений
|
||||
|
||||
Из корня репозитория, через нативный ARM64 Python:
|
||||
|
||||
```bash
|
||||
python3 durka.py doctor
|
||||
```
|
||||
|
||||
`doctor` не устанавливает, не скачивает, не выполняет pull/build, не запускает сервисы, не меняет конфигурацию и не исполняет Neo. Он проверяет фактическую macOS/архитектуру, Python 3.10+, Git 2.30+, локальный Desktop Engine, Compose v2+, ресурсы, нужные порты и подготовленные образы. Пароли и имена процессов не выводятся. `READY` относится к конкретной проверке, не ко всему соревнованию.
|
||||
|
||||
Коды: `0` — все проверки готовы; `1` — предупреждения/неподтверждённые проверки; `2` — блокер. До setup отсутствие конфига/образов/клиента ожидаемо. Эмуляция Packmate остаётся предупреждением, offline/LAN — `NOT VERIFIED` даже при совпадении кеша. Занятые порты могут принадлежать уже поднятому стеку; не убивайте чужой процесс ради снятия предупреждения.
|
||||
|
||||
Если Python/Git отсутствуют, сначала подготовьте согласованные установки. Сверьте реальные версии macOS и Docker Desktop с требованиями разрешённой установки; ранее названная версия не является проверкой. Запустите Desktop вручную после согласования. Начните с 4 CPU / 8 ГиБ RAM и бюджета диска 96 ГиБ, затем измерьте нагрузку.
|
||||
|
||||
<a id="2-first-setup-while-online"></a>
|
||||
## 2. Первая подготовка с Интернетом
|
||||
|
||||
Этот шаг записывает приватный конфиг и подготавливает зависимости. Держите конфиг/пароли приватными.
|
||||
|
||||
```bash
|
||||
python3 durka.py init
|
||||
```
|
||||
|
||||
Отредактируйте `local/durka.json`: оставьте `bind_address` равным `127.0.0.1`, выберите Darwin ARM64/Desktop, режим FILE и задайте `profile.packmate.local_ip` равным `192.0.2.20` для synthetic PCAP ниже. Оставьте пример URL/token фермы; **не выполняйте `submit`**. Поддерживаемый adapter — `ructf_http`, что не означает совместимость с любым соревнованием. Другие протоколы требуют отдельной проверки.
|
||||
|
||||
После согласования, при доступном Интернете:
|
||||
|
||||
```bash
|
||||
python3 durka.py setup
|
||||
```
|
||||
|
||||
Подготовьте закреплённый Neo **v2.4.2 Darwin ARM64** по [инструкции Neo](neo-RU.md). Разместите executable в `local/neo-client/neo` либо укажите настоящий путь через `doctor --neo-client PATH`. Сохраните release/config/tasks офлайн. Doctor проверяет executable Mach-O ARM64 header, но не аутентифицирует клиент и не доказывает его версию. Используйте закреплённый release, не произвольный бинарник с подходящим header.
|
||||
|
||||
<a id="3-start-and-check-the-tools"></a>
|
||||
## 3. Поднять и проверить инструменты
|
||||
|
||||
```bash
|
||||
python3 durka.py doctor
|
||||
python3 durka.py up
|
||||
python3 durka.py status
|
||||
```
|
||||
|
||||
Порядок задаёт kit: базы → S4DFarm → координатор Neo → Packmate. Worker и отправка на соревнование остаются выключены. Ожидаем работающие сервисы и адреса Farm/Packmate. Neo — координатор скриптов, не веб-панель. Ферма собирает флаги, не раскатывает патчи. Packmate FILE ищет в закрытом capture, не снимает трафик LAN.
|
||||
|
||||
Войдите в Farm с данными из приватного конфига и проверьте team/config view. Startup уже аутентифицирует `/api/get_config`; одна login-страница не проверяет API. Войдите в Packmate. Не выводите `neo info`, expanded Compose config или raw logs на трансляцию.
|
||||
|
||||
<a id="4-synthetic-end-to-end-checks"></a>
|
||||
## 4. Synthetic-проверки полного пути
|
||||
|
||||
Создайте новый закрытый capture существующим fixture и импортируйте. Команды записывают только локальный synthetic-файл и меняют input Packmate этого deployment; старый input/data сохраняются.
|
||||
|
||||
```bash
|
||||
python3 -c 'from integration.synthetic_pcap import make_pcap; from pathlib import Path; p = Path("local/first-run.pcap"); f = p.open("xb"); f.write(make_pcap("0123456789abcdef01234567")); f.close(); p.chmod(0o600)'
|
||||
python3 durka.py traffic import local/first-run.pcap
|
||||
python3 durka.py scan lab --patches
|
||||
python3 scripts/defense_ops.py preflight --profile config/defense-profile.example.json
|
||||
python3 integration/vulnbox_handoff.py
|
||||
```
|
||||
|
||||
В Packmate добавьте сервис на порту **18080**, substring pattern `0123456789abcdef01234567`, затем один раз нажмите жёлтую кнопку разбора FILE со стрелкой вниз в боковой панели, а не ищите надпись «Start». Найдите GET `/durkahelper-smoke/…` и ответ `DURKAHELPER_RESPONSE_…` с верными направлениями. На намеренно уязвимом lab scanner ожидаемо возвращает `1`, это не поломка установки; Defense preflight и handoff должны вернуть `0`/PASS.
|
||||
|
||||
Выполните [безвредную readiness-задачу Neo](neo-RU.md#first-harmless-task), затем явно запустите `python3 durka.py worker` и однократно выполните эту disabled-задачу. Ожидайте readiness-сообщение в ограниченном `tail`; нет запроса к цели и принятого флага. В выбранном worker image должны быть реальные зависимости скрипта: default light image не является универсальной средой Python/Sage. После проверки остановите worker вместе с deployment.
|
||||
|
||||
[Изолированная complete-stack процедура](../integration/README-RU.md#release-candidate-acceptance) дополнительно проверяет synthetic Neo→Farm→mock receiver, отказ auth, native restore и точные payload Packmate. Это Linux AMD64 fixture, не доказательство Desktop или нативного Darwin client. Не направляйте его в операторский workspace или реальный endpoint отправки.
|
||||
|
||||
<a id="5-offline-restart-and-workload-rehearsal"></a>
|
||||
## 5. Offline, restart и нагрузка
|
||||
|
||||
Сохраните Ethernet/LAN, но отключите Интернет согласованным способом. Не сбрасывайте Desktop и не чистите образы. Выполните cold start подготовленных сервисов:
|
||||
|
||||
```bash
|
||||
python3 durka.py down
|
||||
python3 durka.py up
|
||||
python3 durka.py status
|
||||
```
|
||||
|
||||
Ожидаем отсутствие downloads/builds; сохраняются настройки Farm, disabled-задача Neo и service/pattern/старые streams Packmate. FILE parsing не возобновляется автоматически: нажимайте кнопку разбора FILE только для намеренной обработки текущего capture. Повторите безвредную задачу Neo после явного запуска worker. Новые PCAP импортируются отдельно, это не бесконечный FILE pipe. Следуйте [offline-инструкции](offline-bundles-RU.md) и [native backup/recovery](MACOS_FULL_DEPLOYMENT_AND_TESTING-RU.md) до появления ценных данных; сохранённый каталог не является backup.
|
||||
|
||||
Запустите подготовленный стек под обычной нагрузкой минимум на 60 минут; проверьте отзывчивость, рост диска, memory pressure и повторный импорт PCAP. Hosted macOS CI не доказывает Docker Desktop, LAN и совместимость с локальными правилами.
|
||||
|
||||
<a id="6-failures-and-safe-shutdown"></a>
|
||||
## 6. Ошибки и безопасная остановка
|
||||
|
||||
При ошибке не идите дальше: `status`, затем `doctor`; откройте [troubleshooting](MACOS_FULL_DEPLOYMENT_AND_TESTING-RU.md). Изменение конфига после setup требует `down` → edit → `configure` → `up`; при прерванной конфигурации может понадобиться `configure --rollback`. Недостающие образы подготовьте при Интернете, не во время игры. Клиент неверной архитектуры замените проверенным клиентом, не запускайте через непроверенный обход.
|
||||
|
||||
```bash
|
||||
python3 durka.py down
|
||||
```
|
||||
|
||||
Останавливается только свой deployment, включая worker; данные и образы остаются. Нельзя `down -v`, общий `prune`, широкое удаление и Desktop reset. Native dumps или консистентную остановленную копию восстанавливают в новое изолированное окружение, не поверх live database files.
|
||||
|
||||
<a id="remaining-manual-gates"></a>
|
||||
## Оставшиеся ручные gates
|
||||
|
||||
- Реальный Mac: согласованная установка, auth/execution нативного клиента, полный стек в Desktop, offline start, recovery и обычная нагрузка.
|
||||
- Домашний Ethernet: Mac и второй PC должны войти и выполнить полезные действия в Farm/Neo/Packmate, затем reconnect после restart; localhost/TCP connect недостаточны. Используйте [шпаргалку админа](TEAM_LAN_ADMIN_CHEATSHEET-RU.md).
|
||||
- Только на площадке: повторите доступ участников и доступность checker по офлайн [game-day checklist](game-day-RU.md). AI и изменения кода не должны требоваться.
|
||||
- Capture: подготовьте и [разрешённый Linux LIVE, и передачу закрытого PCAP](traffic-capture-RU.md). Mac на коммутаторе не видит трафик Vulnbox автоматически. Один FILE fallback не закрывает continuous-capture requirement.
|
||||
- Протокол: проверьте adapter настоящего соревнования до включения отправки; replay восстановленных очередей остаётся выключен до проверки.
|
||||
@@ -0,0 +1,99 @@
|
||||
# First Mac run
|
||||
|
||||
English | [Русский](MACOS_FIRST_RUN-RU.md)
|
||||
|
||||
This is the short operator route, not a claim that this machine is ready. All Mac runtime steps below are **PENDING real-Mac acceptance**. Run them only after approval for Docker Desktop, local services, Ethernet access. Installation details, configuration fields and backup procedures live in the [full guide](MACOS_FULL_DEPLOYMENT_AND_TESTING.md).
|
||||
|
||||
## 1. Read-only preflight
|
||||
|
||||
From the repository root, using native ARM64 Python:
|
||||
|
||||
```bash
|
||||
python3 durka.py doctor
|
||||
```
|
||||
|
||||
`doctor` does not install, download, pull, build, start services, change configuration or execute Neo. It checks the actual macOS/architecture, Python 3.10+, Git 2.30+, local Desktop Engine, Compose v2+, resources, configured ports and prepared runtime images. It never prints credentials or listener names. `READY` applies to the named check, not the whole competition.
|
||||
|
||||
Exit codes: `0` all checks ready; `1` warnings/unverified checks; `2` a blocker. Missing config/images/client before setup is expected. Packmate emulation remains a warning, and offline/LAN acceptance remains `NOT VERIFIED` even when cached images match. Occupied ports may belong to your already-running stack; do not kill another process to clear a warning.
|
||||
|
||||
If Python/Git are absent, prepare them using approved installers first. Check the actual macOS and Docker Desktop versions against the approved installation requirements; a previously reported version is not evidence. Start Desktop manually after approval. Start with 4 CPUs / 8 GiB RAM and a 96 GiB disk budget, then measure rather than assume performance.
|
||||
|
||||
## 2. First setup while online
|
||||
|
||||
This step writes private configuration and prepares dependencies. Keep the config/passwords private.
|
||||
|
||||
```bash
|
||||
python3 durka.py init
|
||||
```
|
||||
|
||||
Edit `local/durka.json`: keep `bind_address` at `127.0.0.1`, choose the Darwin ARM64/Desktop profile, FILE mode and `profile.packmate.local_ip` set to `192.0.2.20` for the synthetic capture below. Keep the example farm submission URL/token; **do not run `submit`**. The farm's maintained adapter is `ructf_http`, not an assertion about any event's protocol. Other protocols require separate compatibility validation.
|
||||
|
||||
After approval, with Internet available:
|
||||
|
||||
```bash
|
||||
python3 durka.py setup
|
||||
```
|
||||
|
||||
Prepare the locked Neo **v2.4.2 Darwin ARM64** client using [Neo installation](neo.md). Put its executable at `local/neo-client/neo`, or pass its actual path to `doctor --neo-client PATH`. Keep the release/config/task directory available offline. Doctor checks an executable Mach-O ARM64 header; it does not authenticate the client or prove its version. Use only the locked release, not an arbitrary binary with a matching header.
|
||||
|
||||
## 3. Start and check the tools
|
||||
|
||||
```bash
|
||||
python3 durka.py doctor
|
||||
python3 durka.py up
|
||||
python3 durka.py status
|
||||
```
|
||||
|
||||
Order is handled by the kit: databases → S4DFarm → Neo coordinator → Packmate. Worker and competition submission remain disabled. Expected: services are running and Farm/Packmate addresses are printed. Neo is a script coordinator, not a web dashboard. Farm collects flags; it does not deploy patches. Packmate FILE searches a closed capture, not live LAN packets.
|
||||
|
||||
Log in to Farm using the private config and confirm its team/config view. Startup already authenticates `/api/get_config`; a login screen alone is not an API test. Log in to Packmate. Never print `neo info`, expanded Compose config or raw logs on a broadcast.
|
||||
|
||||
## 4. Synthetic end-to-end checks
|
||||
|
||||
Generate a new closed capture with the existing fixture, then import it. These commands write only a local synthetic file and change this deployment's Packmate input; previous input/data are retained.
|
||||
|
||||
```bash
|
||||
python3 -c 'from integration.synthetic_pcap import make_pcap; from pathlib import Path; p = Path("local/first-run.pcap"); f = p.open("xb"); f.write(make_pcap("0123456789abcdef01234567")); f.close(); p.chmod(0o600)'
|
||||
python3 durka.py traffic import local/first-run.pcap
|
||||
python3 durka.py scan lab --patches
|
||||
python3 scripts/defense_ops.py preflight --profile config/defense-profile.example.json
|
||||
python3 integration/vulnbox_handoff.py
|
||||
```
|
||||
|
||||
In Packmate add service port **18080**, a substring pattern `0123456789abcdef01234567`, then press the yellow downward-arrow FILE-processing button in the sidebar once; do not look for a literal "Start" label. Find the GET `/durkahelper-smoke/…` and response `DURKAHELPER_RESPONSE_…`, with correct directions. Scanner findings on the deliberately vulnerable lab mean expected exit `1`, not installation failure; Defense preflight and handoff should exit `0`/report PASS.
|
||||
|
||||
Use the [harmless Neo readiness task](neo.md#first-harmless-task), then explicitly start `python3 durka.py worker` and run that disabled task once. Expect the readiness message in its bounded `tail`; no target request and no accepted flag. The selected worker image must contain the script's actual dependencies: the default light image is not a generic Python/Sage environment. Stop the worker with the deployment when finished.
|
||||
|
||||
The [isolated complete-stack procedure](../integration/README.md#release-candidate-acceptance) additionally checks synthetic Neo→Farm→mock receiver, auth failures, native restore and known Packmate payloads. It is a Linux AMD64 fixture, not proof about Desktop or the native Darwin client. Do not point it at your operator workspace or real submission endpoint.
|
||||
|
||||
## 5. Offline, restart and workload rehearsal
|
||||
|
||||
Keep Ethernet/LAN but disconnect Internet using an approved arrangement. Do not reset Desktop or prune images. Cold-start the prepared services:
|
||||
|
||||
```bash
|
||||
python3 durka.py down
|
||||
python3 durka.py up
|
||||
python3 durka.py status
|
||||
```
|
||||
|
||||
Expected: no downloads/builds; Farm settings, disabled Neo task and Packmate service/pattern/previous streams persist. FILE parsing does not automatically resume: press the FILE-processing button only when intentionally processing the current capture. Repeat the harmless Neo task after explicitly starting the worker. New PCAP imports are deliberate replacements, not an endless FILE pipe. Follow [offline operation](offline-bundles.md) and [native backup/recovery](MACOS_FULL_DEPLOYMENT_AND_TESTING.md) before adding valuable data; retaining a directory is not a backup.
|
||||
|
||||
Run the prepared stack under normal workload for at least 60 minutes; check responsiveness, disk growth, memory pressure and repeated PCAP imports. Hosted macOS CI does not prove Docker Desktop, LAN or local policy compatibility.
|
||||
|
||||
## 6. Failures and safe shutdown
|
||||
|
||||
On failure stop progressing: `status`, then `doctor`; use the [troubleshooting guide](MACOS_FULL_DEPLOYMENT_AND_TESTING.md). A config edit after setup needs `down` → edit → `configure` → `up`; interrupted configuration may require `configure --rollback`. Missing images must be prepared while online, not fixed mid-game. A wrong-architecture client must be replaced with the reviewed client, not run through an unplanned workaround.
|
||||
|
||||
```bash
|
||||
python3 durka.py down
|
||||
```
|
||||
|
||||
This stops only the owned deployment, including its worker, retaining data and images. Do not use `down -v`, global `prune`, broad deletion or Desktop reset. Native dumps or a consistent stopped copy must be restored into a new isolated environment, never over live database files.
|
||||
|
||||
## Remaining manual gates
|
||||
|
||||
- Real Mac: approved installation, native client authentication/execution, complete-stack Desktop checks, offline startup, recovery load.
|
||||
- Home Ethernet rehearsal: Mac plus a second PC must authenticate and perform useful Farm/Neo/Packmate actions, then reconnect after restart; localhost/TCP connect alone is insufficient. Use the [admin cheat sheet](TEAM_LAN_ADMIN_CHEATSHEET.md).
|
||||
- Event-only: repeat participant access and checker availability using the offline [game-day checklist](game-day.md). No AI or code changes should be required.
|
||||
- Capture: prepare both [approved Linux LIVE and closed-PCAP transfer](traffic-capture.md). A Mac on the switch does not automatically see Vulnbox traffic. FILE fallback alone does not satisfy a continuous-capture requirement.
|
||||
- Protocol: validate the actual competition adapter before enabling real submission; keep replay of recovered queues disabled until reviewed.
|
||||
@@ -0,0 +1,167 @@
|
||||
<a id="set-up-and-run-the-team-tools-on-macos"></a>
|
||||
# Установка и работа командных инструментов на macOS
|
||||
|
||||
[English](MACOS_FULL_DEPLOYMENT_AND_TESTING.md) | Русский
|
||||
|
||||
Маршрут админа: от клонирования до работающего командного стека. Участникам нужна [инструкция участника](participant-guide-RU.md). Все команды ниже выполняются из корня репозитория DurkaHelper.
|
||||
|
||||
Первое развёртывание выполняйте по короткой [first-run инструкции](MACOS_FIRST_RUN-RU.md), начиная с read-only `python3 durka.py doctor`. Полное руководство — справочник настроек/recovery, а не доказательство пройденной репетиции на реальном Mac.
|
||||
|
||||
<a id="1-know-the-layout"></a>
|
||||
## 1. Как устроено
|
||||
|
||||
DurkaHelper запускается нативно в Python. Docker Desktop поднимает S4DFarm, координатор/worker Neo и Packmate FILE. Защищаемые сервисы остаются на Vulnbox в Ethernet-сети. Ноутбук обслуживает инструменты, а не развёртывание защищаемых сервисов.
|
||||
|
||||
Ферма = флаги и отправка. Neo = распределение/исполнение скриптов. Packmate = анализ трафика. Сканер = разбор локальных исходников. [Схема связей](team-setup-RU.md).
|
||||
|
||||
<a id="2-install-prerequisites"></a>
|
||||
## 2. Установить необходимое
|
||||
|
||||
Установите Git, Python 3.10+ и Docker Desktop разрешённым для вашей машины способом. Запустите Docker Desktop и проверьте:
|
||||
|
||||
```bash
|
||||
uname -m
|
||||
python3 --version
|
||||
git --version
|
||||
docker version
|
||||
docker compose version
|
||||
```
|
||||
|
||||
Apple Silicon должен показать `arm64`. Закреплённый образ Packmate существует только для amd64, поэтому используется эмуляция Docker Desktop. Начальный бюджет — 4 CPU, 8 GiB RAM и 96 GiB диска Docker; уточните его по своей нагрузке. Оставьте место на диске хоста для PCAP и backup.
|
||||
|
||||
|
||||
<a id="3-clone-and-configure"></a>
|
||||
## 3. Клонировать и заполнить конфиг
|
||||
|
||||
```bash
|
||||
git clone https://github.com/Nyarlad/DurkaHelper.git
|
||||
cd DurkaHelper
|
||||
python3 durka.py init
|
||||
```
|
||||
|
||||
Откройте `local/durka.json` в редакторе. Пароли/ключ уже сгенерированы. Измените:
|
||||
|
||||
| Настройка | Что указать |
|
||||
|---|---|
|
||||
| `profile.bind_address` | Ethernet IPv4 для доступа команды; `127.0.0.1` оставьте только для прогона на одном ноутбуке |
|
||||
| `profile.ports` | По умолчанию ферма 8080, Neo 5005, Packmate 65000; меняйте, если порт занят |
|
||||
| `profile.farm.teams` | Названия команд и реальные адреса сервисов/Vulnbox |
|
||||
| `profile.farm.flag_format` | Regex флага от организаторов |
|
||||
| `profile.farm.protocol_settings` | URL/token отправки соревнования |
|
||||
| `profile.farm.submit_limit / submit_period / flag_lifetime` | Лимиты и время соревнования |
|
||||
| `profile.packmate.local_ip` | IP стороны сервиса, представленный в PCAP |
|
||||
| `credentials` | Сгенерированные пароль фермы, ключ Neo и логин/пароль Packmate; выдавайте только нужное |
|
||||
|
||||
Для native workers участников нужен настоящий Ethernet bind: координатор передаёт им LAN URL фермы. Loopback-демо поддерживает внутренний маршрут фермы только для встроенного worker.
|
||||
|
||||
Текущий адаптер — `ructf_http`. Для другого протокола не включайте отправку, пока не будет совместимого адаптера. Инструменты и просмотр трафика можно запустить с выключенной отправкой.
|
||||
|
||||
В `local/` лежат приватный конфиг, скачанные исходники, данные стека и captures. Не показывайте его в Git. Для домашнего прогона настройки отправки могут оставаться примерами, пока сама отправка выключена.
|
||||
|
||||
На соревновании остановите стек, отредактируйте LAN/команды/отправку/Packmate, примените конфигурацию и запустите снова. Данные/образы сохраняются; скачивания и пересборка не нужны:
|
||||
|
||||
```bash
|
||||
python3 durka.py down
|
||||
python3 durka.py configure
|
||||
python3 durka.py up
|
||||
```
|
||||
|
||||
Редактируйте `local/durka.json` между `down` и `configure`. Замена платформы или credentials — отдельная подготовка.
|
||||
|
||||
<a id="4-prepare-while-internet-is-available"></a>
|
||||
## 4. Подготовить при доступном Интернете
|
||||
|
||||
```bash
|
||||
python3 durka.py setup
|
||||
```
|
||||
|
||||
Команда получает закреплённые версии исходников/образов, готовит приватный workspace и собирает ферму/Neo. Это может занять несколько минут. Проверки версий и образов выполняются автоматически; переписывать checksum руками не нужно.
|
||||
|
||||
Выполняйте подготовку на машине, с которой будете работать. Linux amd64-кеш не содержит нативные зависимости Mac и не подтверждает скорость Apple Silicon. До отключения сохраните Docker Desktop, Python, репозиторий, образы, клиент Neo и нужные скрипты/зависимости.
|
||||
|
||||
<a id="5-start-and-check-access"></a>
|
||||
## 5. Поднять и проверить доступ
|
||||
|
||||
```bash
|
||||
python3 durka.py up
|
||||
python3 durka.py status
|
||||
```
|
||||
|
||||
Запуск включает UI/API фермы, координатор Neo и UI Packmate. Создаётся пустой PCAP, поэтому интерфейс работает до первого capture. Отправка флагов и worker пока выключены.
|
||||
|
||||
Откройте URL фермы и Packmate из `status`; войдите с данными приватного конфига. Затем откройте те же LAN-адреса с другой физической машины. `localhost` у участника указывает на его машину, а не на ваш ноутбук.
|
||||
|
||||
Передайте участникам только нужные URL/пароль фермы, URL/логин Packmate и адрес/ключ Neo. Database/Redis/Docker не раздаются команде. Если macOS запросит входящие соединения, разрешите нужное приложение в рамках своей политики; не отключайте firewall.
|
||||
|
||||
<a id="6-traffic-and-scripts"></a>
|
||||
## 6. Трафик и скрипты
|
||||
|
||||
Для первого маршрута на Mac получите закрытый разрешённый PCAP и импортируйте:
|
||||
|
||||
```bash
|
||||
python3 durka.py traffic import /path/to/closed-capture.pcap
|
||||
```
|
||||
|
||||
Откройте Packmate, зарегистрируйте сервис и шаблон поиска, затем один раз начните обработку. Найдите известные запрос и ответ. Для следующих файлов используйте ту же команду импорта. Она заменяет активный файл, сохраняя предыдущий. Все варианты, Linux/Vulnbox LIVE и ограниченный ручной захват — в [работе с трафиком](traffic-capture-RU.md).
|
||||
|
||||
Для исполнения командных скриптов установите совместимый клиент Neo v2.4.2 авторам скриптов и следуйте [Neo](neo-RU.md). Когда скрипты готовы, запустите worker админа:
|
||||
|
||||
```bash
|
||||
python3 durka.py worker
|
||||
```
|
||||
|
||||
Встроенный light-worker содержит shell, но не полный Python/Sage. До использования подготовьте совместимые workers с реальными зависимостями скриптов. Им нужны маршруты до координатора, фермы и разрешённых сервисов-целей.
|
||||
|
||||
<a id="7-enable-submission-and-defend"></a>
|
||||
## 7. Включить отправку и защищать
|
||||
|
||||
После проверки реального адаптера, endpoint, формата флага и списка команд:
|
||||
|
||||
```bash
|
||||
python3 durka.py submit
|
||||
```
|
||||
|
||||
Смотрите accepted/rejected/expired в ферме. Доступный UI ещё не означает принятие флагов соревнованием.
|
||||
|
||||
Для каждого сервиса скопируйте исходники с Vulnbox в приватный рабочий каталог и запустите скан:
|
||||
|
||||
```bash
|
||||
python3 durka.py scan /path/to/service --patches
|
||||
```
|
||||
|
||||
Прочитайте связанную инструкцию, сохраните оригинал, примените небольшой патч на Vulnbox и проверьте доступность/checker. Повторите скан исходников. Сканер читает файлы; по SSH в цели не заходит, код не запускает и фиксы не развёртывает.
|
||||
|
||||
<a id="8-rehearse-offline-and-with-load"></a>
|
||||
## 8. Прогнать офлайн и под нагрузкой
|
||||
|
||||
Дома используйте Mac и отдельный ПК в проводной LAN: войдите в ферму/Packmate, подключите Neo, импортируйте известный трафик, выполните безвредный скрипт и переподключитесь после перезапуска своего приложения. Затем отключите Интернет, сохранив LAN, и повторите запуск/работу.
|
||||
|
||||
Проверьте инструменты под обычной нагрузкой не менее 60 минут. Следите за памятью/CPU Docker, ростом PCAP/БД и свободным диском. На событии повторите проверку доступа каждого устройства и выберите подготовленный разрешённый источник трафика.
|
||||
|
||||
<a id="9-backup-stop-and-recover"></a>
|
||||
## 9. Backup, остановка и восстановление
|
||||
|
||||
`down` останавливает deployment и сохраняет данные/образы. Это не backup. Перед рискованным патчем сохраните оригинальные файлы сервиса и используйте native dump его БД.
|
||||
|
||||
Для общего FILE-стека [native backup и recovery](../deployment/README-RU.md#native-backup-and-quarantine-restore) используют dumps и новый изолированный restore. Backup намеренно останавливает запись в исходный стек. Recovery очищает Redis-очереди/кеш/сессии нового кандидата, чтобы не переотправить старую работу; используйте процедуру, только если эта потеря приемлема.
|
||||
|
||||
```bash
|
||||
python3 durka.py down
|
||||
```
|
||||
|
||||
Сначала остановите задания/захват, затем стек. Для обычного shutdown не используйте `docker compose down -v` или общий `docker system prune`.
|
||||
|
||||
<a id="10-common-problems"></a>
|
||||
## 10. Частые проблемы
|
||||
|
||||
| Симптом | Следующий шаг |
|
||||
|---|---|
|
||||
| Docker недоступен | Запустить Docker Desktop, дождаться Engine, повторить `status` |
|
||||
| UI работает локально, с ПК нет | Проверить Ethernet bind/IP, точный URL/порт, политику входящих соединений macOS и разрешённый LAN-путь |
|
||||
| Флаги есть, отправки нет | Включить её только после проверки адаптера, URL/token и expiry |
|
||||
| Задание Neo падает | Наличие worker, интерпретатор/зависимости и маршруты до цели |
|
||||
| Packmate пустой | IP сервиса, регистрация сервиса/шаблона, закрытый capture и известный трафик |
|
||||
| Apple Silicon тормозит | Эмуляция и ресурсы Docker; уменьшить capture/нагрузку или использовать разрешённый Linux-узел |
|
||||
| Заканчивается диск | Остановить новый захват/импорт, сохранить нужное и удалить только определённые старые приватные файлы |
|
||||
|
||||
Для удаления выполните `down`, сохраните нужные backups, затем удалите только свой остановленный deployment/source/data из `local/`. Удаление Docker Desktop и общих образов — отдельная задача администрирования машины.
|
||||
@@ -0,0 +1,156 @@
|
||||
# Set up and run the team tools on macOS
|
||||
|
||||
English | [Русский](MACOS_FULL_DEPLOYMENT_AND_TESTING-RU.md)
|
||||
|
||||
This is the administrator's route from checkout to a usable team stack. Participants use the [participant guide](participant-guide.md). All commands below run from the DurkaHelper repository root.
|
||||
|
||||
For the first deployment, follow the shorter [first-run procedure](MACOS_FIRST_RUN.md), starting with read-only `python3 durka.py doctor`. This full guide is the configuration/recovery reference, not proof of a completed real-Mac rehearsal.
|
||||
|
||||
## 1. Know the layout
|
||||
|
||||
DurkaHelper runs natively in Python. Docker Desktop runs S4DFarm, the Neo coordinator/worker and Packmate FILE. Protected services stay on the Vulnbox over Ethernet. The laptop hosts tools, not the protected service deployment.
|
||||
|
||||
Farm = flags and submission. Neo = script distribution/execution. Packmate = traffic analysis. Scanner = local source review. [Connection diagram](team-setup.md).
|
||||
|
||||
## 2. Install prerequisites
|
||||
|
||||
Install Git, Python 3.10+ and Docker Desktop through the software source permitted on your machine. Start Docker Desktop and check:
|
||||
|
||||
```bash
|
||||
uname -m
|
||||
python3 --version
|
||||
git --version
|
||||
docker version
|
||||
docker compose version
|
||||
```
|
||||
|
||||
Apple Silicon should report `arm64`. Packmate's retained image is amd64-only, so this stack uses Docker Desktop's amd64 emulation. A starting resource budget is 4 CPUs, 8 GiB RAM and 96 GiB Docker disk; adjust after measuring your workload. Have enough host disk for PCAP and backups.
|
||||
|
||||
|
||||
## 3. Clone and configure
|
||||
|
||||
```bash
|
||||
git clone https://github.com/Nyarlad/DurkaHelper.git
|
||||
cd DurkaHelper
|
||||
python3 durka.py init
|
||||
```
|
||||
|
||||
Open `local/durka.json` in your editor. Passwords/key are already generated. Change these values:
|
||||
|
||||
| Setting | Put here |
|
||||
|---|---|
|
||||
| `profile.bind_address` | Your Ethernet IPv4 for team access; keep `127.0.0.1` only for a laptop-only rehearsal |
|
||||
| `profile.ports` | Farm 8080, Neo 5005 and Packmate 65000 by default; change only if occupied |
|
||||
| `profile.farm.teams` | Competition team names and actual service/Vulnbox addresses |
|
||||
| `profile.farm.flag_format` | Organizer's flag regex |
|
||||
| `profile.farm.protocol_settings` | Submission URL/token from the competition |
|
||||
| `profile.farm.submit_limit / submit_period / flag_lifetime` | Competition limits and timing |
|
||||
| `profile.packmate.local_ip` | The service-side IP represented in your PCAP |
|
||||
| `credentials` | Generated farm password, Neo key and Packmate login/password; distribute only the needed values |
|
||||
|
||||
Native teammate workers require the actual Ethernet bind: the coordinator advertises that LAN farm URL to them. A loopback demo supports only the in-stack worker's internal farm route.
|
||||
|
||||
The current adapter is `ructf_http`. Do not enable submission for a different protocol until it has a compatible adapter. You can start the tools and inspect traffic while submission remains off.
|
||||
|
||||
`local/` holds private configuration, downloaded sources, deployment data and incoming captures. Keep it out of Git. For a home rehearsal, submission settings can stay as examples while submission remains off.
|
||||
|
||||
At the event, stop the stack, edit the LAN/team/submission/Packmate settings, apply configuration and start. Data/images remain; no download or rebuild is needed:
|
||||
|
||||
```bash
|
||||
python3 durka.py down
|
||||
python3 durka.py configure
|
||||
python3 durka.py up
|
||||
```
|
||||
|
||||
Edit `local/durka.json` between `down` and `configure`. Changing platform or credentials is separate preparation.
|
||||
|
||||
## 4. Prepare while Internet is available
|
||||
|
||||
```bash
|
||||
python3 durka.py setup
|
||||
```
|
||||
|
||||
This fetches the exact source versions, pulls pinned images, prepares the private workspace and builds the farm/Neo components. It can take several minutes. Version and image checks run automatically; no manual checksum copying is required.
|
||||
|
||||
Do this on the machine you will use. A Linux amd64 cache does not contain native Mac prerequisites or establish Apple Silicon performance. Keep Docker Desktop, Python, the repository, cached images, the Neo client and your scripts/dependencies available before disconnecting.
|
||||
|
||||
## 5. Start and check access
|
||||
|
||||
```bash
|
||||
python3 durka.py up
|
||||
python3 durka.py status
|
||||
```
|
||||
|
||||
Start includes farm UI/API, Neo coordinator and Packmate UI. It creates an empty PCAP so the UI can start before the first capture. Submission and the worker remain off.
|
||||
|
||||
Open the farm and Packmate URLs printed by `status`; log in with values from your private config. Then open those same LAN URLs from another physical machine. `localhost` on a teammate's machine points at that teammate, not at your laptop.
|
||||
|
||||
Give teammates only the farm URL/password, Packmate URL/login and Neo address/key they need. Database/Redis/Docker endpoints are not shared. If macOS asks about incoming connections, permit the relevant application under your allowed policy; do not disable the firewall.
|
||||
|
||||
## 6. Traffic and scripts
|
||||
|
||||
For the initial Mac route, obtain a closed authorized PCAP and import it:
|
||||
|
||||
```bash
|
||||
python3 durka.py traffic import /path/to/closed-capture.pcap
|
||||
```
|
||||
|
||||
Open Packmate, register the service and search pattern, then start processing once. Find a known request and response. For repeated files, use the same import command. It replaces the active file while preserving the previous one. Full options, Linux/Vulnbox LIVE and bounded manual capture are in [traffic capture](traffic-capture.md).
|
||||
|
||||
For team script execution, install a compatible Neo v2.4.2 client on each script writer's machine and follow [Neo](neo.md). When scripts are ready, start the administrator's worker:
|
||||
|
||||
```bash
|
||||
python3 durka.py worker
|
||||
```
|
||||
|
||||
The bundled light worker has a shell, not a complete Python/Sage environment. Add compatible workers with your actual script dependencies before relying on them. Workers need routes to the coordinator, farm and permitted service targets.
|
||||
|
||||
## 7. Enable submission and defend
|
||||
|
||||
After checking the real adapter, endpoint, flag format and team map:
|
||||
|
||||
```bash
|
||||
python3 durka.py submit
|
||||
```
|
||||
|
||||
Watch accepted/rejected/expired statuses in the farm. A reachable UI does not prove the competition accepts flags.
|
||||
|
||||
For each service, copy source from the Vulnbox to your private working directory and scan:
|
||||
|
||||
```bash
|
||||
python3 durka.py scan /path/to/service --patches
|
||||
```
|
||||
|
||||
Review the linked fix recipe, back up the original, apply a small patch on the Vulnbox and verify availability/checker behavior. Rerun the source scan. The scanner reads files; it does not SSH into targets, execute their code or deploy a fix.
|
||||
|
||||
## 8. Rehearse offline and with load
|
||||
|
||||
At home, use the Mac and a separate PC on wired LAN: log in to farm/Packmate, connect Neo, import known traffic, run one harmless script and reconnect after a scoped restart. Then disconnect Internet while keeping LAN and repeat startup/use.
|
||||
|
||||
Run the tools under normal workload for at least 60 minutes. Watch Docker memory, CPU, PCAP/database growth and available disk. At the event, repeat the access test on each teammate's device and choose the prepared permitted capture path.
|
||||
|
||||
## 9. Backup, stop and recover
|
||||
|
||||
`down` stops this deployment and retains its data/images. It is not a backup. Before a risky service patch, retain that service's original files and use its database's native dump procedure.
|
||||
|
||||
For the shared maintained FILE stack, [native backup and recovery](../deployment/README.md#native-backup-and-quarantine-restore) uses native database dumps and a new isolated restore. Backup intentionally pauses the source. Recovery resets the new candidate's Redis queues/cache/sessions to prevent replay; use that procedure only when this loss is acceptable.
|
||||
|
||||
```bash
|
||||
python3 durka.py down
|
||||
```
|
||||
|
||||
Stop script activity/capture first; then stop the stack if applicable. Never use `docker compose down -v` or broad `docker system prune` as routine shutdown.
|
||||
|
||||
## 10. Common problems
|
||||
|
||||
| Symptom | Next action |
|
||||
|---|---|
|
||||
| Docker cannot connect | Start Docker Desktop, wait for Engine, rerun `status` |
|
||||
| UI works locally, not from the PC | Correct Ethernet bind/IP, exact URL/port, macOS incoming-connection policy and allowed LAN path |
|
||||
| Farm has flags but no submissions | Enable submission only after checking adapter, URL/token and expiry |
|
||||
| Neo task fails | Check worker presence, interpreter/dependencies and target routes |
|
||||
| Packmate is empty | Correct service-side IP, service/pattern registration, closed capture and known traffic |
|
||||
| Apple Silicon is slow | Check emulation and Docker resources; reduce capture volume/workload or use an allowed Linux capture node |
|
||||
| Disk is filling | Stop new capture/import, retain needed data and remove only identified old private files |
|
||||
|
||||
For removal, run `down`, retain needed backups and then delete only your stopped `local/` deployment/source/data directories. Removing Docker Desktop or shared images is a separate machine administration task.
|
||||
@@ -0,0 +1,36 @@
|
||||
<a id="documentation"></a>
|
||||
# Документация
|
||||
|
||||
[English](README.md) | Русский
|
||||
|
||||
Начните со своей роли. У английских страниц есть русский перевод рядом; обе версии доступны офлайн.
|
||||
|
||||
<a id="main-routes"></a>
|
||||
## Основные маршруты
|
||||
|
||||
| Ваша задача | Что читать |
|
||||
|---|---|
|
||||
| Поднять общие инструменты | [Последовательные workflow 01–05](ADMIN_WORKFLOWS-RU.md) → [памятка для печати](TEAM_LAN_ADMIN_CHEATSHEET-RU.md); [первый запуск Mac](MACOS_FIRST_RUN-RU.md) для установки |
|
||||
| Защищать сервис или писать скрипты | [Инструкция участника](participant-guide-RU.md) → [шпаргалка защитника](defense-cheatsheet-RU.md) |
|
||||
| Разобраться с трафиком | [Захват/импорт](traffic-capture-RU.md) → [Packmate](packmate-RU.md) |
|
||||
| Запустить Linux LIVE с ноутбука | [SSH doctor, офлайн-образы и запуск](packmate-remote-RU.md) |
|
||||
| Проверить находку | [Справочник сканера](offline-scanner-RU.md) → [база исправлений](vulnerabilities/README-RU.md) |
|
||||
|
||||
<a id="how-the-stack-fits-together"></a>
|
||||
## Как связан стек
|
||||
|
||||
[Схема команды](team-setup-RU.md) объясняет связи. [S4DFarm](s4dfarm-RU.md) собирает/отправляет флаги; [Neo](neo-RU.md) распределяет скрипты; [Packmate](packmate-RU.md) помогает разбирать трафик. Патчи Vulnbox применяются обычным способом развёртывания сервиса.
|
||||
|
||||
Основная точка входа — `python3 durka.py`. Конфигурация хранится в исключённом из Git `local/durka.json`; обязательных evidence-форм и ручного переписывания checksum в этом маршруте нет.
|
||||
|
||||
<a id="references"></a>
|
||||
## Справочники
|
||||
|
||||
| Тема | Страницы |
|
||||
|---|---|
|
||||
| Defense | [Процесс](defense-RU.md), [разбор исходников](code-review-RU.md), [проверка патчей](patch-validation-RU.md), [игровой день](game-day-RU.md) |
|
||||
| Развёртывание | [Справочник kit](../deployment/README-RU.md), [подготовка офлайн](offline-bundles-RU.md), [локальные утилиты](local-tools-RU.md) |
|
||||
| Разработка | [Вклад в проект](../CONTRIBUTING-RU.md), [новые правила](development-RU.md), [synthetic lab](../lab/README-RU.md), [integration-стенды](../integration/README-RU.md), [релиз](release-checklist-RU.md) |
|
||||
| Проект | [Текущие возможности](CAPABILITY_INVENTORY-RU.md), [правила соревнований](competition-rules-RU.md), [лицензии](../THIRD_PARTY_NOTICES-RU.md) |
|
||||
|
||||
Расширенные скрипты сохраняют preview и явные параметры для записи/restore. Открывайте эти справочники по необходимости; это не дополнительные шаги для каждого участника.
|
||||
@@ -0,0 +1,32 @@
|
||||
# Documentation
|
||||
|
||||
English | [Русский](README-RU.md)
|
||||
|
||||
Start with your role. English pages have a Russian translation alongside; both are available offline.
|
||||
|
||||
## Main routes
|
||||
|
||||
| You are… | Read this |
|
||||
|---|---|
|
||||
| Hosting shared tools | [Ordered workflows 01–05](ADMIN_WORKFLOWS.md) → [printable admin cheat sheet](TEAM_LAN_ADMIN_CHEATSHEET.md); [first Mac run](MACOS_FIRST_RUN.md) for installation |
|
||||
| Defending a service or writing scripts | [Participant guide](participant-guide.md) → [defense cheat sheet](defense-cheatsheet.md) |
|
||||
| Investigating traffic | [Capture/import workflow](traffic-capture.md) → [Packmate](packmate.md) |
|
||||
| Deploying Linux LIVE from a laptop | [SSH doctor, offline images and startup](packmate-remote.md) |
|
||||
| Reviewing a finding | [Scanner reference](offline-scanner.md) → [fix catalog](vulnerabilities/README.md) |
|
||||
|
||||
## How the stack fits together
|
||||
|
||||
[Team topology](team-setup.md) explains the connections. [S4DFarm](s4dfarm.md) collects/submits flags; [Neo](neo.md) distributes scripts; [Packmate](packmate.md) lets defenders inspect traffic. Vulnbox patches use your normal service deployment workflow.
|
||||
|
||||
The ordinary entrypoint is `python3 durka.py`. Configuration belongs in ignored `local/durka.json`; this route has no mandatory evidence forms or manually copied checksums.
|
||||
|
||||
## References
|
||||
|
||||
| Subject | Pages |
|
||||
|---|---|
|
||||
| Defense | [Workflow](defense.md), [source review](code-review.md), [patch verification](patch-validation.md), [game day](game-day.md) |
|
||||
| Deployment | [Kit reference](../deployment/README.md), [offline preparation](offline-bundles.md), [local utilities](local-tools.md) |
|
||||
| Development | [Contributor guide](../CONTRIBUTING.md), [rule development](development.md), [synthetic lab](../lab/README.md), [integration fixtures](../integration/README.md), [release checklist](release-checklist.md) |
|
||||
| Project | [Current capabilities](CAPABILITY_INVENTORY.md), [competition rules](competition-rules.md), [licenses](../THIRD_PARTY_NOTICES.md) |
|
||||
|
||||
Advanced scripts retain previews and explicit parameters for filesystem/restore operations. Read their references when needed; they are not extra setup steps for every participant.
|
||||
@@ -0,0 +1,97 @@
|
||||
<a id="administrator-cheat-sheet"></a>
|
||||
# Шпаргалка администратора
|
||||
|
||||
[English](TEAM_LAN_ADMIN_CHEATSHEET.md) | Русский
|
||||
|
||||
Вы поднимаете общую ферму, координатор Neo и Packmate. После настройки для обычной работы нужны эти команды, а не форма валидации. Распечатайте страницу и сохраните [workflow 01–05](ADMIN_WORKFLOWS-RU.md) офлайн.
|
||||
|
||||
<a id="start"></a>
|
||||
## Запуск
|
||||
|
||||
Запустите Docker Desktop/Engine и подключите Ethernet. Из корня репозитория:
|
||||
|
||||
```bash
|
||||
DURKA_CONFIG=local/competition.json
|
||||
python3 durka.py --config "$DURKA_CONFIG" up
|
||||
python3 durka.py --config "$DURKA_CONFIG" status
|
||||
```
|
||||
|
||||
Откройте ферму и Packmate. Войдите, затем повторите с отдельного ПК или устройства участника. URL используют реальный Ethernet-адрес; `localhost` работает только для вас. В каждом терминале задайте переменную с настоящим путём подготовленного конфига. Смена игровых настроек: остановить native workers, down, изменить этот конфиг, configure, затем up; всегда с тем же --config.
|
||||
|
||||
<a id="share-access"></a>
|
||||
## Выдать доступ
|
||||
|
||||
| Что передать участникам | Откуда взять |
|
||||
|---|---|
|
||||
| URL и пароль фермы | URL из `status`; `credentials.farm_password` в выбранном приватном конфиге |
|
||||
| Neo host:port и ключ | Адрес из `status`; `credentials.neo_key` |
|
||||
| URL, логин и пароль Packmate | URL из `status`; `credentials.packmate_user / packmate_password` |
|
||||
| Доступ к Vulnbox/сервису | Разрешённый команде порядок доступа к сервисам |
|
||||
|
||||
Передайте учётные данные приватно, отдельно от трансляции/скриншотов. Пароли БД и Docker-доступ участникам не нужны. Их страница — [инструкция участника](participant-guide-RU.md).
|
||||
|
||||
<a id="enable-work"></a>
|
||||
## Включить работу
|
||||
|
||||
Когда скрипты/зависимости готовы:
|
||||
|
||||
```bash
|
||||
python3 durka.py --config "$DURKA_CONFIG" worker
|
||||
```
|
||||
|
||||
Когда протокол, endpoint/token и список команд соревнования правильные:
|
||||
|
||||
```bash
|
||||
python3 durka.py --config "$DURKA_CONFIG" submit
|
||||
```
|
||||
|
||||
Координатор раздаёт задания; workers выполняют и отправляют совпадающий stdout в Farm; Farm отправляет жюри. Встроенный worker — shell-only. Авторы используют один координатор и разные ID: регистрация выключенным → дождаться скачивания worker → single → проверить → намеренно включить → отключить. [Точные примеры Neo](neo-RU.md#one-shot-and-scheduled-harmless-example). QUEUED не означает приём жюри. Патчи применяются штатным механизмом сервиса.
|
||||
|
||||
<a id="traffic"></a>
|
||||
## Трафик
|
||||
|
||||
Для закрытого PCAP:
|
||||
|
||||
```bash
|
||||
python3 durka.py --config "$DURKA_CONFIG" traffic import /path/to/closed-capture.pcap
|
||||
```
|
||||
|
||||
В Packmate зарегистрируйте сервис/порт/шаблон и один раз нажмите жёлтую кнопку обработки со стрелкой вниз. [Workflow 05](ADMIN_WORKFLOWS-RU.md#workflow-05--packmate-live-or-file) описывает LIVE doctor, офлайн-bundle и развёртывание. Capture settings — в приватном local/packmate-remote.json; порты/шаблоны сервисов — в UI. Ethernet на Mac не обеспечивает видимость; FILE не является LIVE.
|
||||
|
||||
<a id="check-the-team"></a>
|
||||
## Проверить команду
|
||||
|
||||
Дома используйте Mac и отдельный ПК. На соревновании повторите с каждым рабочим устройством:
|
||||
|
||||
- Войти в ферму и Packmate по LAN-адресам.
|
||||
- Найти один и тот же известный запрос/ответ в Packmate.
|
||||
- Подключить клиент Neo, выполнить согласованный безвредный скрипт и увидеть результат.
|
||||
- Переподключиться после обрыва клиента или перезапуска своего приложения.
|
||||
- Держать обычную нагрузку; следить за памятью и диском.
|
||||
|
||||
Заполнять форму не требуется. Исправьте ошибки до использования этого устройства/маршрута.
|
||||
|
||||
<a id="if-something-breaks"></a>
|
||||
## Если что-то сломалось
|
||||
|
||||
| Симптом | Что проверить |
|
||||
|---|---|
|
||||
| Все UI недоступны | `status`, Ethernet IP/bind, Docker и опубликованные порты |
|
||||
| Не работает только одно устройство | Его URL, маршрут, учётные данные и версия клиента |
|
||||
| Флаги ждут в ферме | Отправка включена? Адаптер/token/expiry правильные? |
|
||||
| Скрипты Neo падают | Есть worker? Интерпретатор/зависимости? Маршруты? |
|
||||
| Packmate пустой | Известный трафик, правильный IP сервиса, регистрация и источник файла/LIVE |
|
||||
| Быстро растёт диск | Остановить новый capture; сохранить нужное и удалить только выбранные старые приватные данные |
|
||||
|
||||
Перед рискованными изменениями нужен backup. [Native recovery стека](../deployment/README-RU.md#native-backup-and-quarantine-restore) останавливает запись и восстанавливает в новое хранилище; не копируйте live-файлы БД обычным backup.
|
||||
|
||||
<a id="finish"></a>
|
||||
## Завершение
|
||||
|
||||
Остановите новые скрипты/захват, сохраните backups, затем:
|
||||
|
||||
```bash
|
||||
python3 durka.py --config "$DURKA_CONFIG" down
|
||||
```
|
||||
|
||||
Данные и образы сохраняются. Не используйте общий prune и `down -v`. [Полная установка](MACOS_FULL_DEPLOYMENT_AND_TESTING-RU.md).
|
||||
@@ -0,0 +1,89 @@
|
||||
# Administrator cheat sheet
|
||||
|
||||
English | [Русский](TEAM_LAN_ADMIN_CHEATSHEET-RU.md)
|
||||
|
||||
You host the shared farm, Neo coordinator and Packmate. Once configured, ordinary game operation needs these commands, not a validation form. Print this page and keep [workflows 01–05](ADMIN_WORKFLOWS.md) offline.
|
||||
|
||||
## Start
|
||||
|
||||
Start Docker Desktop/Engine and connect Ethernet. From the repository root:
|
||||
|
||||
```bash
|
||||
DURKA_CONFIG=local/competition.json
|
||||
python3 durka.py --config "$DURKA_CONFIG" up
|
||||
python3 durka.py --config "$DURKA_CONFIG" status
|
||||
```
|
||||
|
||||
Open the farm and Packmate URLs. Log in, then repeat from the separate PC or a teammate's device. The URLs use your actual Ethernet address; `localhost` is only for you. Set the variable in every terminal and select your actual prepared config. For changed event settings: stop native workers, down, edit this config, configure, then up; use the same --config.
|
||||
|
||||
## Share access
|
||||
|
||||
| Give teammates | Where it comes from |
|
||||
|---|---|
|
||||
| Farm URL and password | URL from `status`; `credentials.farm_password` in the selected private config |
|
||||
| Neo host:port and key | Address from `status`; `credentials.neo_key` |
|
||||
| Packmate URL, login and password | URL from `status`; `credentials.packmate_user / packmate_password` |
|
||||
| Vulnbox/service access | The team's authorized service-access procedure |
|
||||
|
||||
Send credentials privately, separately from broadcast/screenshots. Do not share database passwords or Docker access. Participants use the [participant guide](participant-guide.md).
|
||||
|
||||
## Enable work
|
||||
|
||||
When scripts/dependencies are ready:
|
||||
|
||||
```bash
|
||||
python3 durka.py --config "$DURKA_CONFIG" worker
|
||||
```
|
||||
|
||||
When competition protocol, endpoint/token and team map are correct:
|
||||
|
||||
```bash
|
||||
python3 durka.py --config "$DURKA_CONFIG" submit
|
||||
```
|
||||
|
||||
The coordinator assigns tasks; workers execute and send matching stdout to Farm; Farm submits to the jury. The bundled worker is shell-only. Authors share a coordinator and use distinct task IDs: register disabled → wait for worker download → single → inspect → enable deliberately → disable. [Exact Neo examples](neo.md#one-shot-and-scheduled-harmless-example). QUEUED is not acceptance. Patches use the service's normal deployment.
|
||||
|
||||
## Traffic
|
||||
|
||||
For a closed PCAP:
|
||||
|
||||
```bash
|
||||
python3 durka.py --config "$DURKA_CONFIG" traffic import /path/to/closed-capture.pcap
|
||||
```
|
||||
|
||||
In Packmate, register the service/port/pattern and click the yellow downward-arrow processing button once. [Workflow 05](ADMIN_WORKFLOWS.md#workflow-05--packmate-live-or-file) covers LIVE doctor, offline bundle and deployment. Capture settings are in private local/packmate-remote.json; service ports/patterns are in the UI. Mac Ethernet alone does not provide visibility; FILE is not LIVE.
|
||||
|
||||
## Check the team
|
||||
|
||||
At home, use the Mac and a separate PC. At the event, repeat with every participating device:
|
||||
|
||||
- Log into farm and Packmate using the LAN URLs.
|
||||
- Find the same known request/response in Packmate.
|
||||
- Authenticate the Neo client, execute a harmless agreed script and confirm its result.
|
||||
- Reconnect after a client interruption or scoped restart.
|
||||
- Run normal workload; watch memory and disk.
|
||||
|
||||
No form is required. Fix failures before relying on that device/path.
|
||||
|
||||
## If something breaks
|
||||
|
||||
| Symptom | Check |
|
||||
|---|---|
|
||||
| All UIs unreachable | `status`, Ethernet IP/bind, Docker and published ports |
|
||||
| Only one device fails | Its URL, route, credentials and client version |
|
||||
| Flags wait in farm | Submission enabled? Correct adapter/token/expiry? |
|
||||
| Neo scripts fail | Worker present? Interpreter/dependencies? Routes? |
|
||||
| Packmate empty | Known traffic, correct service IP, registration and file/LIVE source |
|
||||
| Disk grows rapidly | Stop incoming capture; retain needed files and prune only selected old private data |
|
||||
|
||||
Back up before risky changes. [Native stack recovery](../deployment/README.md#native-backup-and-quarantine-restore) pauses writers and restores to new storage; never copy live database files as ordinary backups.
|
||||
|
||||
## Finish
|
||||
|
||||
Stop new scripts/capture, retain backups, then:
|
||||
|
||||
```bash
|
||||
python3 durka.py --config "$DURKA_CONFIG" down
|
||||
```
|
||||
|
||||
Data and images remain. Avoid broad prune and `down -v`. [Full setup](MACOS_FULL_DEPLOYMENT_AND_TESTING.md).
|
||||
@@ -0,0 +1,33 @@
|
||||
<a id="review-an-owned-service"></a>
|
||||
# Review своего сервиса
|
||||
|
||||
[English](code-review.md) | Русский
|
||||
|
||||
Работайте с локальной копией исходников, которую вам разрешено проверять. Используйте [сканер](offline-scanner-RU.md) и [каталог](vulnerabilities/README-RU.md), чтобы найти конкретные места для review.
|
||||
|
||||
<a id="identify-startup-and-dependencies"></a>
|
||||
## Определите запуск и зависимости
|
||||
|
||||
Свидетельство: `REVIEWED`; эффект `READ-ONLY`; рабочий каталог — checkout сервиса. Требование: ripgrep. Ожидается: список возможных манифестов без исполнения кода. Пути в выводе могут быть приватными. Rollback: не нужен.
|
||||
|
||||
~~~bash
|
||||
rg --files -g 'Dockerfile*' -g '*compose*' -g '*requirements*' -g '*lock*' \
|
||||
-g 'pyproject.toml' -g 'package.json' -g 'composer.json' -g 'go.mod' \
|
||||
-g 'pom.xml' -g '*gradle*' -g '*.csproj' -g 'Cargo.toml' -g 'Gemfile' \
|
||||
-g 'Makefile' -g 'CMakeLists.txt'
|
||||
~~~
|
||||
|
||||
Проследите entrypoint → процесс → конфигурация → маршруты → данные. Никогда не запускайте неизвестные install hooks или исходники только ради их изучения. Сверьте lockfiles с фактически развёрнутым образом и runtime.
|
||||
|
||||
<a id="trace-a-request"></a>
|
||||
## Проследите запрос
|
||||
|
||||
1. Источник ввода: body, URL, cookie, header, сохранённая запись, задача или файл.
|
||||
2. Проверенный субъект и разрешение на конкретный объект.
|
||||
3. Разбор, нормализация, сериализация, шаблоны и преобразования типов.
|
||||
4. Чувствительная операция и её фактические аргументы.
|
||||
5. Исключения, callbacks, awaits и альтернативные пути к той же операции.
|
||||
|
||||
Ручные рецепты rg показывают, с чего начать; отсутствие совпадений не подтверждает безопасность. Сопоставьте обычный собственный запрос с разрешёнными логами/PCAP, затем воспроизведите один инвариант на изолированной копии. У запрещённой операции не должно быть запрещённого побочного эффекта.
|
||||
|
||||
После минимального совместимого патча повторите регрессионный тест, обычный пользовательский сценарий и чтение старых записей. Следуйте [процедуре deployment и rollback](patch-validation-RU.md).
|
||||
@@ -0,0 +1,30 @@
|
||||
# Review an owned service
|
||||
|
||||
English | [Русский](code-review-RU.md)
|
||||
|
||||
Work on a local authorized source copy. Use the [scanner](offline-scanner.md) and [catalog](vulnerabilities/README.md) to locate concrete review points.
|
||||
|
||||
## Identify startup and dependencies
|
||||
|
||||
Evidence: `REVIEWED`; effect `READ-ONLY`; cwd the service checkout. Prerequisite: ripgrep. Expected: candidate manifests, not executed code. Output paths may be private. Rollback: none.
|
||||
|
||||
~~~bash
|
||||
rg --files -g 'Dockerfile*' -g '*compose*' -g '*requirements*' -g '*lock*' \
|
||||
-g 'pyproject.toml' -g 'package.json' -g 'composer.json' -g 'go.mod' \
|
||||
-g 'pom.xml' -g '*gradle*' -g '*.csproj' -g 'Cargo.toml' -g 'Gemfile' \
|
||||
-g 'Makefile' -g 'CMakeLists.txt'
|
||||
~~~
|
||||
|
||||
Trace entrypoint → process → configuration → routes → data. Never run unknown install hooks or source merely to inspect it. Compare lockfiles with the actual deployed image/runtime.
|
||||
|
||||
## Trace a request
|
||||
|
||||
1. Input source: body, URL, cookie, header, stored record, task or file.
|
||||
2. Verified actor and permission for the specific object.
|
||||
3. Parsing, normalization, serialization, templates and casts.
|
||||
4. Sensitive operation and its actual arguments.
|
||||
5. Exceptions, callbacks, awaits and alternative paths to the same operation.
|
||||
|
||||
Manual rg recipes identify where to start; zero matches do not establish safety. Correlate a normal owned request from approved logs/PCAP, then reproduce one invariant on an isolated copy. A denied operation must have no forbidden side effect.
|
||||
|
||||
After a compatible minimal patch, repeat the regression test, normal user workflow and reading of old records. Follow [deployment and rollback](patch-validation.md).
|
||||
@@ -0,0 +1,23 @@
|
||||
<a id="competition-scope-and-rules"></a>
|
||||
# Область и правила соревнования
|
||||
|
||||
[English](competition-rules.md) | Русский
|
||||
|
||||
DurkaHelper не содержит настроек конкретного турнира. Перед использованием проверьте действующие правила организаторов и официальные разъяснения; разрешение на одном мероприятии не переносится на другое.
|
||||
|
||||
| Область | Что подтвердить перед применением |
|
||||
|---|---|
|
||||
| Подготовленные материалы | Локальные скрипты, копии исходников и доступ к репозиториям |
|
||||
| AI / внешние API | Различия ограничений при подготовке и во время соревнования; сканер не обращается к AI |
|
||||
| Изменения сервисов | Разрешения на изменения кода, конфигурации, зависимостей, restart и migrations |
|
||||
| Сетевая политика | Разрешённые порты, фильтрация, proxies и изменения контейнерной сети |
|
||||
| Зарезервированная инфраструктура | Аккаунты организаторов, checkers, мониторинг и защищённые каталоги |
|
||||
| Размещение | Разрешённые локальные hosts/containers и источники запросов |
|
||||
| Трафик/данные | Разрешение на захват, точка наблюдения, хранение/передача и ограничения ресурсов |
|
||||
| Коммуникации | Каналы команды, внешняя помощь и публикация |
|
||||
| Протокол отправки | Endpoint/transport, аутентификация, формат флагов, ответы, квоты, tick/lifetime |
|
||||
| Доступность | Семантика checker, SLA, сохранение старых данных и окна для патчей |
|
||||
|
||||
Рецепт усиления безопасности не даёт разрешения менять чужую инфраструктуру. Если настройка защищена, исправляйте в разрешённых границах приложения с сохранением функциональности; уточняйте спорные изменения до их применения.
|
||||
|
||||
Описанная соревновательная топология использует проводную LAN без VPN. Не предполагайте, что разрешено менять адресацию, конфигурацию коммутатора, firewall или параметры захвата. Офлайн-сканер не отправляет запросов; у health probes и инфраструктурных инструментов явно указаны другие эффекты.
|
||||
@@ -0,0 +1,22 @@
|
||||
# Competition scope and rules
|
||||
|
||||
English | [Русский](competition-rules-RU.md)
|
||||
|
||||
DurkaHelper contains no tournament-specific settings. Confirm current organizer rules and official clarifications before use; permission at one event does not transfer to another.
|
||||
|
||||
| Area | Confirm before applying |
|
||||
|---|---|
|
||||
| Prepared material | Local scripts, source copies and repository access |
|
||||
| AI / external APIs | Preparation versus competition-time restrictions; the scanner calls no AI |
|
||||
| Service changes | Code, configuration, dependencies, restart and migration permissions |
|
||||
| Network policy | Allowed ports, filtering, proxies and container-network changes |
|
||||
| Reserved infrastructure | Organizer accounts, checkers, monitoring and protected directories |
|
||||
| Placement | Permitted local hosts/containers and allowed request sources |
|
||||
| Traffic/data | Capture permission, observation point, storage/transfer and resource bounds |
|
||||
| Communication | Team channels, outside help and publication |
|
||||
| Submission protocol | Endpoint/transport, authentication, flag format, responses, quotas, tick/lifetime |
|
||||
| Availability | Checker semantics, SLA, legacy-data retention and patch windows |
|
||||
|
||||
A hardening recipe is not permission to alter someone else's infrastructure. If a setting is protected, fix within the authorized application boundary while preserving functionality; clarify uncertain changes before applying them.
|
||||
|
||||
The documented competition topology uses wired LAN without VPN. Do not assume permission to change addressing, switch configuration, firewall or capture settings. The offline scanner makes no requests; health probes and infrastructure tools have explicitly different effects.
|
||||
@@ -0,0 +1,44 @@
|
||||
<a id="defense-operator-workflow"></a>
|
||||
# Рабочий процесс оператора защиты
|
||||
|
||||
[English](defense.md) | Русский
|
||||
|
||||
[Шпаргалка](defense-cheatsheet-RU.md) · [Каталог](vulnerabilities/README-RU.md) · [Проверка патчей](patch-validation-RU.md)
|
||||
|
||||
<a id="before-the-first-change"></a>
|
||||
## До первого изменения
|
||||
|
||||
Подтвердите разрешённую область и [контракт соревнования](competition-rules-RU.md). Назначьте одного ответственного за deployment каждого сервиса. Запишите фактическую ревизию кода/образа, механизм запуска, источники конфигурации, нужные порты, расположение данных и способ rollback.
|
||||
|
||||
Выполните обычную пользовательскую операцию и сохраните синтетические или разрешённые старые записи для регрессионных проверок. Исправный health endpoint не доказывает работу входа, авторизации, сохранения данных или совместимость с checker.
|
||||
|
||||
Создайте ограниченный [baseline](local-tools-RU.md#defense-operations), scan исходников и согласованный health profile. Сохраняйте read-only копии исходников; никогда не используйте общий inventory процессов/контейнеров для раскрытия посторонних workloads.
|
||||
|
||||
<a id="repeated-loop"></a>
|
||||
## Повторяющийся цикл
|
||||
|
||||
1. Следите за статусом checker, явно заданными health checks и поведением приложения.
|
||||
2. Сравнивайте snapshots для выявления изменений файлов, конфигурации, процессов и listeners.
|
||||
3. Локально изучайте минимальный нужный интервал логов и трафика.
|
||||
4. Проследите подозрительную операцию до инварианта в исходниках.
|
||||
5. Добавьте падающий регрессионный тест и внесите минимальный совместимый патч.
|
||||
6. Повторите проверки владельца/другого пользователя/анонимного пользователя, старых данных и доступности.
|
||||
7. Разверните через отрепетированный процесс; наблюдайте и откатите код/образ при регрессии.
|
||||
|
||||
Не меняйте попутно ключи, схемы, runtime и не удаляйте функциональность. Старые данные, созданные в последующих раундах, должны пережить rollback кода.
|
||||
|
||||
<a id="triage-and-evidence"></a>
|
||||
## Разбор подозрений и свидетельства
|
||||
|
||||
Находка сканера или подозрительно выглядящий запрос — гипотеза, а не доказательство компрометации. Сравните с нормальным трафиком, timestamps и фактическими изменениями состояния. Приватно сохраняйте только необходимые свидетельства; записывайте нормализованные события и очищенные hashes через [timeline/evidence tools](local-tools-RU.md#patch-evidence-timelines-and-export).
|
||||
|
||||
Не публикуйте raw logs, PCAP, cookies, flags, request bodies, Neo info или expanded Compose configuration. Диагностические терминалы и интерфейсы с секретами остаются приватными.
|
||||
|
||||
<a id="recovery"></a>
|
||||
## Восстановление
|
||||
|
||||
Проверьте резервную копию, прежде чем на неё полагаться. Восстановите в новую изолированную staging-среду и проверьте данные и функциональность до любого согласованного production-действия. Используйте нативные dumps БД или контролируемые консистентные cold copies; копия живого файла БД не является надёжным backup.
|
||||
|
||||
Начальные цели репетиции: RPO пять минут и RTO десять минут, измеряемые для каждого компонента. Синтетические прогоны длительностью меньше секунды не доказывают достижение этих целей на реальном объёме данных. Submission и workers остаются остановленными до review восстановленных и просроченных очередей.
|
||||
|
||||
При неполных свидетельствах указывайте partial/blocked вместо «безопасно». Для эксплуатационных сбоев используйте [runbook игрового дня](game-day-RU.md), для доступа к общим инструментам — [шпаргалку администратора](TEAM_LAN_ADMIN_CHEATSHEET-RU.md).
|
||||
@@ -0,0 +1,21 @@
|
||||
<a id="defender-quick-sheet"></a>
|
||||
# Краткая шпаргалка защитника
|
||||
|
||||
[English](defense-cheatsheet.md) | Русский
|
||||
|
||||
Перед изменением уточните разрешённый сервис, порядок запуска/пути данных, checker и ответственного за rollback. Сохраните предыдущие код/образ и подходящий backup. Карточка и ручное переписывание hashes не требуются.
|
||||
|
||||
| Ситуация | Действие |
|
||||
|---|---|
|
||||
| Первый доступ | Обычный пользовательский сценарий, образец старых данных, inventory/baseline, scan исходников |
|
||||
| Сигнал сканера | Откройте точную ссылку каталога; проследите ввод → проверка → опасная операция |
|
||||
| Подозрительный запрос | Сравните с нормальным трафиком в коротком временном окне; не публикуйте raw evidence |
|
||||
| Предложен патч | Один падающий regression test, минимальное изменение, проверки своего/чужого/анонимного пользователя и старых данных |
|
||||
| Deployment | Один ответственный, точный собственный сервис, сохранённый предыдущий образ/код и актуальные данные |
|
||||
| Регрессия доступности | Сохраните причину; выполните отрепетированный rollback кода, не перезаписывайте новые раунды старой БД |
|
||||
| Нет трафика | Проверьте разрешённую точку захвата; общая LAN не означает видимость пакетов |
|
||||
| Неясный результат | Partial/blocked, никогда не ложное «чисто» |
|
||||
|
||||
[Сканер](offline-scanner-RU.md) · [Рецепты по языкам](vulnerabilities/README-RU.md) · [Чеклист патча](patch-validation-RU.md) · [Игровой день](game-day-RU.md) · [Шпаргалка администратора](TEAM_LAN_ADMIN_CHEATSHEET-RU.md)
|
||||
|
||||
Никогда не используйте общий prune, down -v, непроверенную ротацию учётных данных, широкие изменения firewall или произвольное исполнение исходников как быстрый обход проблемы. Согласованные изменения состояния требуют rollback. Игровые checkers важнее удобного зелёного /health endpoint.
|
||||
@@ -0,0 +1,20 @@
|
||||
# Defender quick sheet
|
||||
|
||||
English | [Русский](defense-cheatsheet-RU.md)
|
||||
|
||||
Before a change, know the authorized service, startup/data paths, checker and rollback owner. Keep the previous code/image and a suitable backup. No service card or manually copied hashes are required.
|
||||
|
||||
| Situation | Action |
|
||||
|---|---|
|
||||
| First access | Normal user journey, old-data sample, inventory/baseline, source scan |
|
||||
| Scanner signal | Open the exact catalog link; trace input → validation → sink |
|
||||
| Suspicious request | Compare normal traffic and small timestamp window; do not publish raw evidence |
|
||||
| Proposed patch | One failing regression, minimal change, own/other/anonymous and old-data checks |
|
||||
| Deployment | One owner, exact owned service, retained previous image/code and current data |
|
||||
| Availability regression | Preserve cause; apply rehearsed code rollback, not an old DB over new rounds |
|
||||
| Missing traffic | Verify authorized capture point; same LAN does not imply packet visibility |
|
||||
| Unclear result | Partial/blocked, never false-clean |
|
||||
|
||||
[Scanner](offline-scanner.md) · [Language recipes](vulnerabilities/README.md) · [Patch checklist](patch-validation.md) · [Game day](game-day.md) · [Admin quick sheet](TEAM_LAN_ADMIN_CHEATSHEET.md)
|
||||
|
||||
Never use broad prune, down -v, unreviewed credential rotation, blanket firewall changes or arbitrary source execution as a shortcut. Approved state changes need a rollback. Competition checkers outrank a convenient green /health endpoint.
|
||||
@@ -0,0 +1,39 @@
|
||||
# Defense operator workflow
|
||||
|
||||
English | [Русский](defense-RU.md)
|
||||
|
||||
[Quick sheet](defense-cheatsheet.md) · [Catalog](vulnerabilities/README.md) · [Patch verification](patch-validation.md)
|
||||
|
||||
## Before the first change
|
||||
|
||||
Confirm authorized scope and the [competition contract](competition-rules.md). Assign one deployment owner per service. Record the actual code/image revision, startup mechanism, configuration sources, required ports, data locations and rollback method.
|
||||
|
||||
Run a normal user operation and retain synthetic/authorized old records for regression checks. A healthy endpoint does not prove login, authorization, persistence or checker compatibility.
|
||||
|
||||
Create a scoped [baseline](local-tools.md#defense-operations), source scan and approved health profile. Preserve read-only source copies; never use broad process/container inventory to expose unrelated workloads.
|
||||
|
||||
## Repeated loop
|
||||
|
||||
1. Observe checker status, explicit health checks and application behavior.
|
||||
2. Compare snapshots for file/configuration/process/listener drift.
|
||||
3. Review the smallest relevant log/traffic interval locally.
|
||||
4. Trace a suspicious operation to an invariant in source.
|
||||
5. Add a failing regression test and make the smallest compatible patch.
|
||||
6. Repeat owner/other-user/anonymous, legacy-data and availability checks.
|
||||
7. Deploy through the rehearsed path; monitor and roll back the code/image if regression occurs.
|
||||
|
||||
Do not rotate keys, migrate schemas, replace runtimes or remove functionality as incidental changes. Old data created in later rounds must survive code rollback.
|
||||
|
||||
## Triage and evidence
|
||||
|
||||
A scanner finding or suspicious-looking request is a hypothesis, not proof of compromise. Compare with normal traffic, timestamps and actual state changes. Preserve only required evidence privately; record normalized events and sanitized hashes using [timeline/evidence tools](local-tools.md#patch-evidence-timelines-and-export).
|
||||
|
||||
Do not publish raw logs, PCAP, cookies, flags, request bodies, Neo info or expanded Compose configuration. Keep diagnostic terminals and secret-bearing interfaces private.
|
||||
|
||||
## Recovery
|
||||
|
||||
Verify the backup before relying on it. Restore into a new isolated staging environment and check data/functionality before any approved production action. Use database-native dumps or controlled consistent cold copies; copying a live database file is not a reliable backup.
|
||||
|
||||
Initial rehearsal objectives are RPO five minutes and RTO ten minutes, measured per component. Synthetic subsecond drills do not prove these objectives for real data volumes. Submission and workers remain stopped until restored/expired queues are reviewed.
|
||||
|
||||
When evidence is incomplete, report partial/blocked rather than safe. Use the [game-day runbook](game-day.md) for operational failures and the [admin sheet](TEAM_LAN_ADMIN_CHEATSHEET.md) for shared-tool access.
|
||||
@@ -0,0 +1,64 @@
|
||||
<a id="development-contracts-and-rule-coverage"></a>
|
||||
# Разработка, контракты и покрытие правил
|
||||
|
||||
[English](development.md) | Русский
|
||||
|
||||
[Руководство для участников](../CONTRIBUTING-RU.md) · [Релизный чеклист](release-checklist-RU.md)
|
||||
|
||||
<a id="architecture"></a>
|
||||
## Архитектура
|
||||
|
||||
Ядро остаётся на стандартной библиотеке Python 3.10+. Сканирование исходников, сравнение отчётов, защитные операции, упаковка и синтетические интеграции имеют отдельные entrypoints. Никогда не импортируйте целевой сервис, не выполняйте его install hooks или shell-команды из профиля и не включайте онлайн-обновления незаметно.
|
||||
|
||||
| Область | Источник истины |
|
||||
|---|---|
|
||||
| Поведение и метаданные сканера | [defense_scan.py](../scripts/defense_scan.py), [набор правил](../rules/defense.json) |
|
||||
| Scope/context | [scope v2](../schemas/scanner-scope.v2.schema.json), [context v1](../schemas/scanner-context.v1.schema.json) |
|
||||
| Операции | [defense_ops.py](../scripts/defense_ops.py), [profile](../schemas/profile.v1.schema.json), [snapshot](../schemas/snapshot.v1.schema.json), [comparison](../schemas/comparison.v1.schema.json) |
|
||||
| Recovery/evidence | [backup manifest](../schemas/backup-manifest.v1.schema.json), [events](../schemas/event.v1.schema.json), [validation records](../schemas/validation-record.v1.schema.json) |
|
||||
| Политика deployment | [model](../schemas/deployment-model.v1.schema.json), [policy](../schemas/deployment-policy.v1.schema.json), [audit](../schemas/deployment-audit.v1.schema.json) |
|
||||
| Внешние артефакты | [v2 complete-target/image-export manifest](../schemas/toolchain-manifest.v2.schema.json), [устаревший v1 inventory](../schemas/toolchain-manifest.v1.schema.json), [pins](../config/toolchain.lock.json) |
|
||||
|
||||
Профили декларативны. Адаптеры платформ используют фиксированные read-only команды, прошедшие review. Invalid/partial/incomparable input завершается кодом 2; обычные находки и проваленные проверки — кодом 1. Запись новых артефактов требует явного пути; операционные изменения требуют явного разрешения и ограниченного rollback.
|
||||
|
||||
<a id="add-or-change-a-rule"></a>
|
||||
## Добавление или изменение правила
|
||||
|
||||
1. Опишите инвариант, языковой API и ссылки на первоисточники.
|
||||
2. При одинаковой семантике расширяйте существующий ID/семейство; не дублируйте детектор ради увеличения счётчика.
|
||||
3. Напишите на английском title, reason, fix, check, limitations, family, подходящий CWE, review priority и signal kind. Сохраняйте существующие IDs и anchors каталога.
|
||||
4. Добавьте независимо написанные positive и safe/context-negative строки в corpus fixtures. Для каждой заявленной языковой формы нужны как минимум два разных положительных и два отрицательных примера.
|
||||
5. Проверьте комментарии/строковые примеры, aliases/rebinding/shadowing, одноимённые пользовательские функции и безопасные альтернативы, соответствующие движку.
|
||||
6. Добавьте или обновите точный контракт детектора и рекомендации по патчу в связанном разделе каталога.
|
||||
7. Запустите targeted tests, ledger, полный suite и относящиеся к изменению платформенные проверки.
|
||||
|
||||
Авторские примеры правила «до/после» не считаются независимыми свидетельствами. Повторяющиеся строки исходников не увеличивают покрытие. Новые правила должны соответствовать независимой цели; пробелы старых правил остаются видимыми и не заменяются придуманным покрытием.
|
||||
|
||||
Текущий реестр: 174 правила, 251 пара правило-язык и 347 независимых fixture-записей. Эти числа не утверждают, что каждая старая пара соответствует новой цели.
|
||||
|
||||
Свидетельство: `REVIEWED`; эффект `READ-ONLY` для coverage и временный `WORKSPACE-WRITE` для unit tests. Рабочий каталог — корень; нужны Python 3.10+ и ripgrep. Ожидается отсутствие новых обязательных пробелов покрытия, падающих тестов и сломанных локальных ссылок.
|
||||
|
||||
```bash
|
||||
python3 scripts/scanner_coverage.py --check --json
|
||||
python3 -m unittest discover -s tests -v
|
||||
```
|
||||
|
||||
Тестовый код никогда не исполняет уязвимые fixture-строки. Контейнерные fixtures запускаются отдельно по выбору и требуют согласованных daemon/workspace. Дорогие regex, malformed documents, oversized files, path/race failures, поведение no-network/no-exec и вывод без секретов входят в обязательную регрессию.
|
||||
|
||||
<a id="versioning"></a>
|
||||
## Версионирование
|
||||
|
||||
Версии CLI обозначают поведение, а не обещание прохождения всех deployment gates. Сохраняйте обратно совместимые flags и стабильные rule IDs. Расширение вывода может потребовать minor version; изменение смысла требует нового schema/scope-контракта и согласованного обновления потребителей.
|
||||
|
||||
Scanner 1.8.0 сохраняет scope v2 и повышает semantic revision до bounded-source-signals.v3. Readers читают старую семантику v2, но старый/новый scope несопоставимы (exit 2). Перед проверкой патча пересканируйте обе стороны одной версией сканера и с одинаковым контекстом. Любое изменение scope или очистки метаданных должно одновременно обновлять defense_diff, patch-check, tests и docs.
|
||||
|
||||
Toolchain manifest v2 различает `complete-target` и намеренно частичный scope `image-export`, привязывая полноту к сопровождаемому контракту deployment. Исторические v1 image и mixed inventories читаются только как частичные устаревшие данные и не могут быть собраны как полный комплект. При переносе полных комплектов требуется независимо сохранённый ожидаемый digest манифеста. Структурно полный и аутентифицированный манифест всё ещё требует независимой репетиции офлайн-runtime и проверки лицензий.
|
||||
|
||||
Человекочитаемые статусы проверки: PASS/FAIL/PARTIAL/BLOCKED/NOT_RUN/SKIPPED_NOT_APPLICABLE; validation-record.v1 использует их варианты в нижнем регистре. Не превращайте not_run в pass.
|
||||
|
||||
<a id="evidence-and-ci"></a>
|
||||
## Свидетельства и CI
|
||||
|
||||
Записывайте commit/tree, platform/interpreter, версии инструментов, команды, scope, результаты и ограничения. Проверяйте точно распакованный bundle, а не только checkout. Исторические свидетельства — неизменяемый контекст, а не сертификация следующего commit.
|
||||
|
||||
Ручной macOS ARM64 workflow — один ограниченный job на standard runner с минимальными permissions и закреплёнными action SHAs. Он проверяет архитектуру, тесты ядра, CLI и упаковку; он не обращается к приватным тестовым хостам и не валидирует Docker Desktop или физических LAN-клиентов. Используйте только включённую квоту и перед dispatch проверяйте, что платные расходы отключены.
|
||||
@@ -0,0 +1,65 @@
|
||||
# Development, contracts and rule coverage
|
||||
|
||||
English | [Русский](development-RU.md)
|
||||
|
||||
[Contributor guide](../CONTRIBUTING.md) · [Release checklist](release-checklist.md)
|
||||
|
||||
## Architecture
|
||||
|
||||
The core remains Python 3.10+ standard library. Source scanning, report comparison, defensive operations, packaging and synthetic integration are separate entrypoints. Never import a target service, execute its install hooks, evaluate profile shell commands or silently enable online updates.
|
||||
|
||||
| Area | Source of truth |
|
||||
|---|---|
|
||||
| Scanner behavior / metadata | [defense_scan.py](../scripts/defense_scan.py), [rule pack](../rules/defense.json) |
|
||||
| Scope/context | [scope v2](../schemas/scanner-scope.v2.schema.json), [context v1](../schemas/scanner-context.v1.schema.json) |
|
||||
| Operations | [defense_ops.py](../scripts/defense_ops.py), [profile](../schemas/profile.v1.schema.json), [snapshot](../schemas/snapshot.v1.schema.json), [comparison](../schemas/comparison.v1.schema.json) |
|
||||
| Recovery/evidence | [backup manifest](../schemas/backup-manifest.v1.schema.json), [events](../schemas/event.v1.schema.json), [validation records](../schemas/validation-record.v1.schema.json) |
|
||||
| Deployment policy | [model](../schemas/deployment-model.v1.schema.json), [policy](../schemas/deployment-policy.v1.schema.json), [audit](../schemas/deployment-audit.v1.schema.json) |
|
||||
| External artifacts | [v2 complete-target/image-export manifest](../schemas/toolchain-manifest.v2.schema.json), [legacy v1 inventory](../schemas/toolchain-manifest.v1.schema.json), [pins](../config/toolchain.lock.json) |
|
||||
|
||||
Profiles are declarative. Platform adapters use fixed reviewed read-only commands. Invalid/partial/incomparable input exits 2; ordinary findings/check failures exit 1. New artifact writes require explicit destinations; operational mutations use explicit approval and scoped rollback.
|
||||
|
||||
## Add or change a rule
|
||||
|
||||
1. State the invariant, language-specific API and primary-source references.
|
||||
2. Prefer extending an existing ID/family when semantics are the same; do not duplicate a detector to inflate counts.
|
||||
3. Write English title, reason, fix, check, limitations, family, applicable CWE, review priority and signal kind. Preserve existing IDs and catalog anchors.
|
||||
4. Add independently written positive and safe/context-negative strings to the fixture corpus. Every claimed language form needs at least two distinct positives and two negatives.
|
||||
5. Test comments/string examples, aliases/rebinding/shadowing, similarly named user functions and safe alternatives appropriate to the engine.
|
||||
6. Add/update the exact detector contract and patch guidance in the linked catalog section.
|
||||
7. Run targeted tests, the ledger, the full suite and relevant platform checks.
|
||||
|
||||
Authored rule before/after examples do not count as independent evidence. Duplicate source strings do not increase coverage. New rules require the independent target; legacy gaps stay visible rather than receiving invented coverage.
|
||||
|
||||
Current inventory: 174 rules, 251 rule-language pairs and 347 independent fixture records. These numbers are not a statement that every legacy pair meets the new target.
|
||||
|
||||
Evidence: `REVIEWED`; effect `READ-ONLY` for coverage and temporary `WORKSPACE-WRITE` for unit tests. Cwd root; Python 3.10+ and ripgrep. Expected: no new required coverage gaps, test failures or broken local links.
|
||||
|
||||
```bash
|
||||
python3 scripts/scanner_coverage.py --check --json
|
||||
python3 -m unittest discover -s tests -v
|
||||
```
|
||||
|
||||
Test code never executes vulnerable fixture strings. Container fixtures are separately opt-in and require an approved daemon/workspace. Expensive regex, malformed documents, oversized files, path/race failures, no-network/no-exec behavior and secret-safe output are regression requirements.
|
||||
|
||||
## Versioning
|
||||
|
||||
CLI versions identify behavior, not a promise that all deployment gates passed. Preserve backward-compatible flags and stable rule IDs. Additive outputs may require a minor version; changed meaning requires a new schema/scope contract and coordinated consumers.
|
||||
|
||||
Scanner 1.8.0 retains scope v2 and advances its semantic revision to bounded-source-signals.v3. Readers accept historical v2 semantics, but old/new semantic scopes are incomparable (exit 2). Rescan both sides with the same scanner/context before patch verification. Any change to scope or metadata sanitization must update defense_diff, patch-check, tests and docs together.
|
||||
|
||||
Toolchain manifest v2 distinguishes `complete-target` from the deliberately
|
||||
partial `image-export` scope and binds completeness to the maintained deployment
|
||||
contract. Historical v1 image and mixed inventories remain readable only as
|
||||
partial legacy data and cannot be assembled as a full kit. Transported complete
|
||||
kits require an independently retained expected manifest digest. A structurally
|
||||
complete and authenticated manifest still needs an independent offline runtime
|
||||
rehearsal and license review.
|
||||
|
||||
Human validation statuses use PASS/FAIL/PARTIAL/BLOCKED/NOT_RUN/SKIPPED_NOT_APPLICABLE; validation-record.v1 uses the lowercase equivalents. Do not coerce not_run into pass.
|
||||
|
||||
## Evidence and CI
|
||||
|
||||
Record commit/tree, platform/interpreter, tool versions, commands, scope, results and limitations. Test the exact extracted bundle, not just the checkout. Historical evidence is immutable context, not certification of a later commit.
|
||||
|
||||
The manual macOS ARM64 workflow is one bounded standard-runner job with minimal permissions and pinned action SHAs. It verifies architecture, core tests, CLI and packaging; it neither accesses private test hosts nor validates Docker Desktop or physical LAN clients. Use included quota only and verify spending remains disabled before dispatch.
|
||||
@@ -0,0 +1,59 @@
|
||||
<a id="game-day-runbook"></a>
|
||||
# Runbook игрового дня
|
||||
|
||||
[English](game-day.md) | Русский
|
||||
|
||||
Это краткое руководство по работе после успешной [репетиции развёртывания](MACOS_FULL_DEPLOYMENT_AND_TESTING-RU.md). Соблюдайте область разрешений организаторов и назначайте одного ответственного за deployment каждого сервиса.
|
||||
|
||||
<a id="receive-a-service"></a>
|
||||
## Получение сервиса
|
||||
|
||||
Найдите настоящие пути его исходников, запуска, конфигурации и данных, а также неизменяемую ревизию. Держите проекты игровых сервисов отдельно от проектов командных S4DFarm/Neo/Packmate.
|
||||
|
||||
Свидетельство: `REVIEWED`; эффект `READ-ONLY`; рабочий каталог — фактический Compose-каталог разрешённого сервиса. Требование: правильный daemon/project и согласованный доступ. Ожидается: список и состояние сервисов только этого проекта; локальный вывод может раскрывать пути. Rollback: не нужен.
|
||||
|
||||
```bash
|
||||
pwd
|
||||
docker compose config --services
|
||||
docker compose ps -a
|
||||
```
|
||||
|
||||
Если при deployment используются явные параметры project/file, используйте те же самые параметры. Не печатайте expanded configuration. Выполните один обычный пользовательский сценарий и сохраните разрешённый образец старых данных. Затем создайте ограниченный baseline и scan исходников.
|
||||
|
||||
<a id="availability-failure"></a>
|
||||
## Сбой доступности
|
||||
|
||||
Сохраните время сбоя и последнее изменение. Изучайте только состояние затронутого проекта, здоровье зависимостей и ограниченные приватные логи; логи могут содержать секреты и должны оставаться вне публичного экспорта evidence. На общих системах избегайте общих списков всех контейнеров и процессов хоста.
|
||||
|
||||
| Симптом | Следующая проверка |
|
||||
|---|---|
|
||||
| Компонент остановлен или перезапускается | Причина выхода, параметры запуска, готовность зависимостей |
|
||||
| UI работает, но действия не проходят | База данных, persistence, точный API и аутентификация |
|
||||
| На хосте работает, teammate не подключается | Ethernet-адрес, опубликованный порт, политика хоста, путь клиента |
|
||||
| Сбой начался после патча | Точный diff и отрепетированный rollback кода/образа |
|
||||
| Health проходит, checker падает | Настоящая семантика checker, обычный сценарий и старые данные |
|
||||
| Очередь не движется | Согласованный протокол, лимиты, ответ receiver и состояние submission |
|
||||
| Neo не подключается | Правильная версия клиента, адрес/key coordinator и доступность farm |
|
||||
| Packmate не показывает streams | Видимость источника, режим, регистрация сервиса и временное окно |
|
||||
|
||||
Перезапуск не восстанавливает потерянные данные. Не используйте down -v, не удаляйте volumes и не меняйте сеть на основании подозрения. Перед перезапуском разберитесь с сохранением данных.
|
||||
|
||||
<a id="suspicious-traffic"></a>
|
||||
## Подозрительный трафик
|
||||
|
||||
Используйте согласованную точку наблюдения и короткий временной интервал. Сравните request/response, method/path, типы параметров, size/status и события приложения с нормальным поведением. Сохраняйте только необходимые приватные свидетельства.
|
||||
|
||||
Общая LAN не означает видимость пакетов. UI Packmate без известного request/response не подтверждает рабочий захват. Импорт FILE — запасной вариант, а не доказательство непрерывного LIVE-анализа.
|
||||
|
||||
<a id="patch-loop"></a>
|
||||
## Цикл патча
|
||||
|
||||
[Review кода](code-review-RU.md) → [рецепт каталога](vulnerabilities/README-RU.md) → [regression/deployment/rollback](patch-validation-RU.md). Сохраняйте нормальное поведение и текущие данные; не удаляйте нужную функцию только ради исчезновения сигнала.
|
||||
|
||||
Для явно заданных health checks приватно адаптируйте [services.example.json](../config/services.example.json); никогда не вставляйте пароли в URL. Свидетельство: `REVIEWED`; эффект `READ-ONLY` GETs; рабочий каталог — корень; ожидается true для всех настроенных проверок.
|
||||
|
||||
```bash
|
||||
python3 scripts/http_probe.py local/services.json --timeout 2 --workers 2
|
||||
```
|
||||
|
||||
Это проверяет настроенное HTTP-поведение, а не Neo gRPC, полноценный вход или семантику игрового checker. Форматы и ограничения описаны в [локальных инструментах](local-tools-RU.md). При сбоях общей инфраструктуры используйте [шпаргалку администратора](TEAM_LAN_ADMIN_CHEATSHEET-RU.md).
|
||||
@@ -0,0 +1,54 @@
|
||||
# Game-day runbook
|
||||
|
||||
English | [Русский](game-day-RU.md)
|
||||
|
||||
This is the short operating guide after a successful [deployment rehearsal](MACOS_FULL_DEPLOYMENT_AND_TESTING.md). Follow organizer scope and keep one deployment owner per service.
|
||||
|
||||
## Receive a service
|
||||
|
||||
Identify its real source/startup/configuration/data paths and immutable revision. Keep game-service projects separate from the team's S4DFarm/Neo/Packmate projects.
|
||||
|
||||
Evidence: `REVIEWED`; effect `READ-ONLY`; cwd the authorized service's actual Compose directory. Prerequisite: correct daemon/project and approved access. Expected: only that project's service list/state; local output may reveal paths. Rollback: none.
|
||||
|
||||
```bash
|
||||
pwd
|
||||
docker compose config --services
|
||||
docker compose ps -a
|
||||
```
|
||||
|
||||
If deployment uses explicit project/file options, use those exact same options. Do not print expanded configuration. Execute one normal user scenario and save an authorized old-data sample. Then establish the scoped baseline and source scan.
|
||||
|
||||
## Availability failure
|
||||
|
||||
Preserve the failure timestamp and last change. Inspect only the affected project's state, dependency health and bounded private logs; logs can contain secrets and must stay out of public evidence exports. Avoid unscoped host-wide container/process listings on shared systems.
|
||||
|
||||
| Symptom | Next check |
|
||||
|---|---|
|
||||
| Stopped/restarting component | Exit reason, startup settings, dependency readiness |
|
||||
| UI works but actions fail | Database, persistence, exact API/authentication |
|
||||
| Host works but teammate cannot connect | Ethernet address, published port, host policy, client path |
|
||||
| Failure started after patch | Exact diff and rehearsed code/image rollback |
|
||||
| Health passes but checker fails | Real checker semantics, normal scenario and old data |
|
||||
| Queue is not moving | Approved protocol, limits, receiver response and submission state |
|
||||
| Neo cannot connect | Correct client version, coordinator address/key and farm reachability |
|
||||
| Packmate has no streams | Source visibility, mode, service registration and time window |
|
||||
|
||||
Restarting does not repair lost data. Do not use down -v, delete volumes or mutate networking on suspicion. Understand persistence before restarting.
|
||||
|
||||
## Suspicious traffic
|
||||
|
||||
Use an approved observation point and a short timestamp range. Compare request/response, method/path, parameter types, size/status and application events with normal behavior. Retain only the needed private evidence.
|
||||
|
||||
Same LAN does not imply packet visibility. A Packmate UI with no known request/response is not a working capture setup. FILE import is a fallback, not proof of continuous LIVE analysis.
|
||||
|
||||
## Patch loop
|
||||
|
||||
[Review code](code-review.md) → [catalog recipe](vulnerabilities/README.md) → [regression/deployment/rollback](patch-validation.md). Preserve normal behavior and current data; do not remove a required feature merely to silence a signal.
|
||||
|
||||
For explicit health checks, privately adapt [services.example.json](../config/services.example.json); never put passwords in URLs. Evidence: `REVIEWED`; effect `READ-ONLY` GETs; cwd root; expected all configured checks true.
|
||||
|
||||
```bash
|
||||
python3 scripts/http_probe.py local/services.json --timeout 2 --workers 2
|
||||
```
|
||||
|
||||
This checks configured HTTP behavior, not Neo gRPC, full login or game checker semantics. [Local tools](local-tools.md) document formats and limits. Shared infrastructure failures use the [administrator sheet](TEAM_LAN_ADMIN_CHEATSHEET.md).
|
||||
@@ -0,0 +1,95 @@
|
||||
<a id="local-tools-and-cli-reference"></a>
|
||||
# Локальные инструменты и справочник CLI
|
||||
|
||||
[English](local-tools.md) | Русский
|
||||
|
||||
Расширенный справочник CLI, Python 3.10+, только стандартная библиотека. Для обычной установки используйте [полную инструкцию](MACOS_FULL_DEPLOYMENT_AND_TESTING-RU.md), для scan — [справочник сканера](offline-scanner-RU.md). Результаты храните приватно. См. [возможности и ограничения](CAPABILITY_INVENTORY-RU.md).
|
||||
|
||||
<a id="defense-operations"></a>
|
||||
## Защитные операции
|
||||
|
||||
`scripts/defense_ops.py` 2.2.0 использует декларативный [profile.v1](../schemas/profile.v1.schema.json); профили не содержат shell-команд. Начните с [синтетического примера](../config/defense-profile.example.json) и явно выберите свои root, files, checks и limits.
|
||||
|
||||
|
||||
```bash
|
||||
python3 scripts/defense_ops.py preflight --profile config/defense-profile.example.json
|
||||
python3 scripts/defense_ops.py snapshot --profile config/defense-profile.example.json \
|
||||
--root . --output ../private-results/baseline.json
|
||||
python3 scripts/defense_ops.py compare ../private-results/baseline.json ../private-results/current.json
|
||||
```
|
||||
|
||||
Адаптеры охватывают platform, processes, listeners, services и ограниченные Compose metadata там, где это поддерживается. Отсутствующие инструменты/права или неполный сбор означают partial, а не свидетельствуют об отсутствии изменений. Сравнение baseline требует одинакового scope.
|
||||
|
||||
Health проверяет только явно настроенные HTTP GET endpoints, без неявных proxies или redirects. Он проверяет status и ограниченное содержимое, а не полное поведение приложения.
|
||||
|
||||
|
||||
```bash
|
||||
python3 scripts/defense_ops.py health --profile config/defense-profile.example.json
|
||||
```
|
||||
|
||||
<a id="backup-and-staging-restore"></a>
|
||||
## Backup и восстановление в staging
|
||||
|
||||
Копируются только явно выбранные regular files/trees и заранее созданные native database dumps. Живые файлы БД не являются поддерживаемым способом backup. Инструмент ограничивает количество и объём, проверяет стабильность источника и SHA-256.
|
||||
|
||||
|
||||
```bash
|
||||
python3 scripts/defense_ops.py backup create --profile config/defense-profile.example.json \
|
||||
--root . --output ../private-results/backup-01
|
||||
python3 scripts/defense_ops.py backup verify ../private-results/backup-01
|
||||
python3 scripts/defense_ops.py restore-stage ../private-results/backup-01 \
|
||||
--target ../private-results/restore-01
|
||||
python3 scripts/defense_ops.py restore-stage ../private-results/backup-01 \
|
||||
--target ../private-results/restore-01 --apply --approval-id restore-rehearsal-01
|
||||
```
|
||||
|
||||
Staging target должен быть новым/пустым согласно prechecks; перезапись production отсутствует. Symlinks, traversal, специальные файлы, tampering, нестабильные входы и неподдерживаемая безопасная публикация приводят к отказу. Windows не поддерживает POSIX-путь изменения данных.
|
||||
|
||||
<a id="deployment-audit"></a>
|
||||
## Аудит deployment
|
||||
|
||||
`audit-deployment` проверяет заявленные allowlisted metadata по явной policy: roles, image pins/architecture, ports, mounts, privileges и требования health/resources. Он не запускает Compose, не исследует live daemon и не разбирает произвольный YAML. Используйте [deployment kit](../deployment/README-RU.md), чтобы создать очищенные model/policy из доверенной конфигурации.
|
||||
|
||||
|
||||
```bash
|
||||
python3 scripts/defense_ops.py audit-deployment \
|
||||
--model ../private-deployment/run-01/runtime-model.json \
|
||||
--policy ../private-deployment/run-01/runtime-policy.json
|
||||
```
|
||||
|
||||
Не редактируйте model вручную, чтобы скрыть риски. Post-build source hash связывает точные bytes runtime Compose; policy намеренно показывает нерешённые проблемы root-user, отсутствия health и эмуляции.
|
||||
|
||||
<a id="patch-evidence-timelines-and-export"></a>
|
||||
## Свидетельства патча, timeline и экспорт
|
||||
|
||||
[Проверка патчей](patch-validation-RU.md) объясняет строгую привязку evidence. Статусы Validation-record — значения schema в нижнем регистре: pass, fail, partial, blocked, not_run и skipped_not_applicable. Запись not_run не является pass.
|
||||
|
||||
Timeline принимает нормализованные записи [event.v1](../schemas/event.v1.schema.json), а не произвольные raw application logs. Evidence export копирует только поддерживаемые structured/sanitized records, исключает raw PCAP/config/credentials и проверяет checksums.
|
||||
|
||||
|
||||
```bash
|
||||
python3 scripts/defense_ops.py timeline --events ../private-results/events.jsonl \
|
||||
--output ../private-results/timeline.json
|
||||
python3 scripts/defense_ops.py evidence --profile config/defense-profile.example.json \
|
||||
--input ../private-results/baseline.json --output ../private-results/evidence-01
|
||||
```
|
||||
|
||||
<a id="small-standalone-utilities"></a>
|
||||
## Небольшие самостоятельные утилиты
|
||||
|
||||
| Утилита | Назначение / ограничения |
|
||||
|---|---|
|
||||
| [http_probe.py](../scripts/http_probe.py) | Явные одноразовые GET; по умолчанию четыре workers, socket timeout три секунды, body 1 MiB; без proxies/redirects, обычная TLS verification |
|
||||
| [log_summary.py](../scripts/log_summary.py) | Только ограниченные JSONL-счётчики; необязательные поля level/integer status, число malformed records, без вывода message/header/body |
|
||||
| [backup_config.py](../scripts/backup_config.py) | Allowlisted scalar JSON fields и SHA-256; без databases, volumes или полного восстановления |
|
||||
| [health_service.py](../lab/health_service.py) | Синтетический loopback-сервис /health и /version |
|
||||
|
||||
Эффект: probes `READ-ONLY`, log summary `READ-ONLY`, config backup `WORKSPACE-WRITE`. Рабочий каталог — корень. Это демонстрационные входы; для probe сначала [запустите лабораторию](../lab/README-RU.md).
|
||||
|
||||
```bash
|
||||
python3 scripts/http_probe.py config/services.example.json
|
||||
python3 scripts/log_summary.py lab/fixtures/events.jsonl
|
||||
python3 scripts/backup_config.py config/backup.example.json --root lab/fixtures
|
||||
```
|
||||
|
||||
HTTP probe завершается кодом 0/все ожидаемые ответы, 1/провал проверки, 2/неверная конфигурация. Log summary возвращает 1 при malformed input, а не просто при HTTP error statuses. Config backup создаёт новый каталог artifacts/config-backups/config-*; никогда не заменяйте полную конфигурацию сервиса этим частичным экспортом. Секрет под произвольным именем поля нельзя надёжно обнаружить — локально проверяйте allowlist и значения.
|
||||
@@ -0,0 +1,89 @@
|
||||
# Local tools and CLI reference
|
||||
|
||||
English | [Русский](local-tools-RU.md)
|
||||
|
||||
Advanced CLI reference, Python 3.10+, standard library only. For normal setup use the [complete deployment guide](MACOS_FULL_DEPLOYMENT_AND_TESTING.md); for scanning use the [scanner reference](offline-scanner.md). Keep outputs private. See [capabilities and limits](CAPABILITY_INVENTORY.md).
|
||||
|
||||
## Defense operations
|
||||
|
||||
`scripts/defense_ops.py` 2.2.0 uses declarative [profile.v1](../schemas/profile.v1.schema.json); profiles contain no shell commands. Start from the [synthetic example](../config/defense-profile.example.json) and explicitly select your own root, files, checks and limits.
|
||||
|
||||
|
||||
```bash
|
||||
python3 scripts/defense_ops.py preflight --profile config/defense-profile.example.json
|
||||
python3 scripts/defense_ops.py snapshot --profile config/defense-profile.example.json \
|
||||
--root . --output ../private-results/baseline.json
|
||||
python3 scripts/defense_ops.py compare ../private-results/baseline.json ../private-results/current.json
|
||||
```
|
||||
|
||||
Adapters cover platform, processes, listeners, services and scoped Compose metadata where supported. Missing tools/permissions or incomplete collection is partial, never evidence that nothing changed. Baseline comparison requires matching scope.
|
||||
|
||||
Health only checks explicitly configured HTTP GET endpoints, without ambient proxies or redirects. It validates status and bounded content, not complete application behavior.
|
||||
|
||||
|
||||
```bash
|
||||
python3 scripts/defense_ops.py health --profile config/defense-profile.example.json
|
||||
```
|
||||
|
||||
## Backup and staging restore
|
||||
|
||||
Only explicitly selected regular files/trees and already-created native database dumps are copied. Live database files are not a supported backup mechanism. The tool bounds counts/bytes, checks source stability and verifies SHA-256.
|
||||
|
||||
|
||||
```bash
|
||||
python3 scripts/defense_ops.py backup create --profile config/defense-profile.example.json \
|
||||
--root . --output ../private-results/backup-01
|
||||
python3 scripts/defense_ops.py backup verify ../private-results/backup-01
|
||||
python3 scripts/defense_ops.py restore-stage ../private-results/backup-01 \
|
||||
--target ../private-results/restore-01
|
||||
python3 scripts/defense_ops.py restore-stage ../private-results/backup-01 \
|
||||
--target ../private-results/restore-01 --apply --approval-id restore-rehearsal-01
|
||||
```
|
||||
|
||||
The staging target must be new/empty as required by prechecks; no production overwrite exists. Symlinks, traversal, special files, tampering, unstable inputs and unsupported secure publication fail closed. Windows does not support the POSIX mutation path.
|
||||
|
||||
## Deployment audit
|
||||
|
||||
`audit-deployment` checks declared, allowlisted metadata against explicit policy: roles, image pins/architecture, ports, mounts, privileges and health/resource expectations. It does not run Compose, inspect the live daemon or parse arbitrary YAML. Use the [deployment kit](../deployment/README.md) to generate the sanitized model/policy from trusted configuration.
|
||||
|
||||
|
||||
```bash
|
||||
python3 scripts/defense_ops.py audit-deployment \
|
||||
--model ../private-deployment/run-01/runtime-model.json \
|
||||
--policy ../private-deployment/run-01/runtime-policy.json
|
||||
```
|
||||
|
||||
Do not hand-edit the model to conceal risks. A post-build source hash binds the exact runtime Compose bytes; the policy intentionally exposes unresolved root-user, missing health and emulation issues.
|
||||
|
||||
## Patch evidence, timelines and export
|
||||
|
||||
[Patch verification](patch-validation.md) explains strict evidence binding. Validation-record statuses are lowercase schema values: pass, fail, partial, blocked, not_run and skipped_not_applicable. A not_run entry is not a pass.
|
||||
|
||||
Timeline accepts normalized [event.v1](../schemas/event.v1.schema.json) records, not arbitrary raw application logs. Evidence export copies only supported structured/sanitized records, excludes raw PCAP/config/credentials and verifies checksums.
|
||||
|
||||
|
||||
```bash
|
||||
python3 scripts/defense_ops.py timeline --events ../private-results/events.jsonl \
|
||||
--output ../private-results/timeline.json
|
||||
python3 scripts/defense_ops.py evidence --profile config/defense-profile.example.json \
|
||||
--input ../private-results/baseline.json --output ../private-results/evidence-01
|
||||
```
|
||||
|
||||
## Small standalone utilities
|
||||
|
||||
| Utility | Purpose / limits |
|
||||
|---|---|
|
||||
| [http_probe.py](../scripts/http_probe.py) | Explicit one-shot GETs; default four workers, three-second socket timeout, 1 MiB body; no proxies/redirects, normal TLS verification |
|
||||
| [log_summary.py](../scripts/log_summary.py) | Bounded JSONL counters only; optional level/integer status fields, malformed counts, no message/header/body output |
|
||||
| [backup_config.py](../scripts/backup_config.py) | Allowlisted scalar JSON fields and SHA-256; no databases, volumes or full restoration |
|
||||
| [health_service.py](../lab/health_service.py) | Synthetic loopback /health and /version service |
|
||||
|
||||
Effect: probes `READ-ONLY`, log summary `READ-ONLY`, config backup `WORKSPACE-WRITE`. Cwd root. These are demo inputs; [start the lab](../lab/README.md) first for the probe.
|
||||
|
||||
```bash
|
||||
python3 scripts/http_probe.py config/services.example.json
|
||||
python3 scripts/log_summary.py lab/fixtures/events.jsonl
|
||||
python3 scripts/backup_config.py config/backup.example.json --root lab/fixtures
|
||||
```
|
||||
|
||||
HTTP probe exits 0/all expected responses, 1/check failure, 2/invalid configuration. Log summary exits 1 for malformed input, not merely HTTP error statuses. Config backup writes a fresh artifacts/config-backups/config-* directory; never replace a full service configuration with this partial export. A secret under an arbitrary field name cannot be detected reliably—review the allowlist and values locally.
|
||||
+169
@@ -0,0 +1,169 @@
|
||||
<a id="neo-distribute-and-run-team-scripts"></a>
|
||||
# Neo: распределить и выполнить командные скрипты
|
||||
|
||||
[English](neo.md) | Русский
|
||||
|
||||
Neo хранит командные скрипты на координаторе и распределяет исполнение между подключёнными workers и командами из списка фермы. Workers передают подходящие флаги в S4DFarm. Это полезно, когда одному ноутбуку не нужно запускать каждый скрипт против каждой цели. Защитные патчи Neo не развёртывает.
|
||||
|
||||
<a id="administrator"></a>
|
||||
## Администратор
|
||||
|
||||
`python3 durka.py up` запускает координатор. `python3 durka.py worker` — встроенный light-worker. Участникам передайте LAN-адрес координатора из `status` и приватный `credentials.neo_key`.
|
||||
|
||||
Из окружения worker должны быть доступны координатор, ферма и разрешённые цели. Light-image содержит shell; для Python/Sage и других зависимостей нужны отдельно подготовленные совместимые workers. Ферму запускайте перед Neo.
|
||||
|
||||
Перед выдачей native clients/workers настройте настоящий Ethernet bind. Loopback-демо использует встроенный worker и внутренний URL фермы; внешним workers этот container-only адрес недоступен.
|
||||
|
||||
<a id="install-a-client"></a>
|
||||
## Установить клиент
|
||||
|
||||
Используйте [релиз v2.4.2](https://github.com/C4T-BuT-S4D/neo/releases/tag/v2.4.2), совпадающий с поддерживаемой версией клиента/worker:
|
||||
|
||||
| Машина | Файл |
|
||||
|---|---|
|
||||
| Apple Silicon Mac | `neo_client_2.4.2_darwin_arm64.zip` |
|
||||
| Intel Mac | `neo_client_2.4.2_darwin_amd64.zip` |
|
||||
| Linux amd64 | `neo_client_2.4.2_linux_amd64.tar.gz` |
|
||||
| Linux arm64 | `neo_client_2.4.2_linux_arm64.tar.gz` |
|
||||
|
||||
Скачайте/распакуйте до соревнования. В архиве есть `neo`, `client_config.yml` и каталог `exploits`. Команды ниже запускаются из распакованного каталога. Нативного клиента Windows в релизе нет; используйте разрешённое Linux-окружение/worker.
|
||||
|
||||
Отредактируйте `client_config.yml`:
|
||||
|
||||
```yaml
|
||||
host: "<ADMIN_ETHERNET_IPV4>:5005"
|
||||
grpc_auth_key: "<PRIVATE_NEO_KEY_FROM_ADMIN>"
|
||||
exploit_dir: "exploits"
|
||||
```
|
||||
|
||||
Замените placeholders; конфиг приватный. Если macOS запросит разрешение, используйте обычную процедуру допуска приложений. Не показывайте ключ в скриншотах и аргументах shell.
|
||||
|
||||
```bash
|
||||
./neo --verbose=false --config client_config.yml --help
|
||||
```
|
||||
|
||||
<a id="first-harmless-task"></a>
|
||||
## Первое безвредное задание
|
||||
|
||||
Создайте в редакторе `exploits/ready.sh`:
|
||||
|
||||
```sh
|
||||
#!/bin/sh
|
||||
# flush=True: printf writes immediately; this task makes no target request.
|
||||
printf 'worker ready for %s\n' "$1"
|
||||
```
|
||||
|
||||
Разрешите исполнение и запустите локально:
|
||||
|
||||
```bash
|
||||
chmod u+x exploits/ready.sh
|
||||
./exploits/ready.sh 192.0.2.1
|
||||
```
|
||||
|
||||
Зарегистрируйте **выключенным**, чтобы не запустить периодическую работу:
|
||||
|
||||
```bash
|
||||
./neo --verbose=false --config client_config.yml add \
|
||||
--id ready --disabled --interval 1h --timeout 3s exploits/ready.sh
|
||||
```
|
||||
|
||||
Попросите админа включить worker, затем единичный прогон:
|
||||
|
||||
```bash
|
||||
./neo --verbose=false --config client_config.yml single ready
|
||||
./neo --verbose=false --config client_config.yml tail --count 20 ready
|
||||
```
|
||||
|
||||
`single` выполняется один раз на **всех настроенных командах**. Пример только печатает readiness и не обращается к ним. Это не флаг; accepted flags в ферме появляться не должны. Ищите ready-сообщение; периодическое исполнение остаётся выключенным.
|
||||
|
||||
<a id="real-scripts-and-recurring-execution"></a>
|
||||
## Настоящие скрипты и периодическое исполнение
|
||||
|
||||
Скрипт получает IP цели первым аргументом. Нужны доступный interpreter/shebang и flush stdout; флаги нужного формата идут в ферму. Сначала локальный тест. Не загружайте недоверенные скрипты в workers.
|
||||
|
||||
Зарегистрируйте скрипт с явными ID, interval и timeout той же disabled-first командой `add`. После успешного разрешённого single-прогона включите или выключите этот ID:
|
||||
|
||||
```bash
|
||||
./neo --verbose=false --config client_config.yml enable <TASK_ID>
|
||||
./neo --verbose=false --config client_config.yml disable <TASK_ID>
|
||||
```
|
||||
|
||||
При добавлении существующего ID Neo спрашивает перед заменой версии. До периодического исполнения проверьте реальные зависимости worker, scope и правила соревнования. CLI задают [upstream-команды](https://github.com/C4T-BuT-S4D/neo/tree/2f2a4eb63f9715155844284f253ba786d330c9ae/cmd/client).
|
||||
|
||||
Собственный совместимый native-worker:
|
||||
|
||||
```bash
|
||||
./neo --verbose=false --config client_config.yml run --jobs 1
|
||||
```
|
||||
|
||||
Команда работает на переднем плане; остановка Ctrl+C. Сначала подготовьте зависимости этого окружения. Поведение native Mac/runtime нужно прогнать на самой машине.
|
||||
|
||||
<a id="team-workflow-clients-coordinator-and-workers"></a>
|
||||
## Командный workflow: клиенты, координатор и workers
|
||||
|
||||
Один бинарник `neo` выполняет две роли: команды `add`, `single`, `enable`, `disable`, `tail` — это управляющий клиент; `run` превращает процесс в исполняющий worker. Координатор хранит скрипты/настройки и распределяет цели между workers. Сам сервер скрипты не исполняет.
|
||||
|
||||
```text
|
||||
Author A's client ──┐
|
||||
Author B's client ──┼──> coordinator ──> connected worker(s) ──> script stdout
|
||||
Admin's client ────┘ │
|
||||
└──> S4DFarm queue ──> jury
|
||||
```
|
||||
|
||||
Worker выделяет из stdout значения, подходящие под настроенный формат флага, и отправляет их прямо в ферму. Адрес/данные входа фермы и настройки команд он получает от координатора. Поэтому одного доступа к координатору недостаточно: исполняющий worker должен видеть ещё и ферму. Приём в ферму и отправка из неё жюрейке — отдельные действия; `QUEUED` не означает `ACCEPTED`.
|
||||
|
||||
1. **Админ:** из корня DurkaHelper запускает существующий стек через `python3 durka.py up`. Приватно выдаёт адрес/ключ координатора. Запускает один подготовленный worker: встроенный `python3 durka.py worker` либо native `./neo ... run` ниже. Для управления заданиями оба одновременно не нужны. Light Docker-worker не содержит произвольные зависимости скриптов.
|
||||
2. **Каждый автор:** использует приватный клиентский конфиг с тем же координатором. Выбирает разные ID заданий, например `ready-author-a` и `ready-author-b`: ID общие, а не отдельные для каждого участника. Каждому worker задаёт отдельный `client_id`. Общий ключ даёт доступ доверенной команде, а не персональную read-only роль.
|
||||
3. **Регистрация:** загружает скрипт выключенным. До единичного прогона ждёт загрузки скрипта worker и перезапуска его рабочих циклов. Зависимости и вспомогательные файлы нужны в окружении worker, а не только на ноутбуке автора.
|
||||
4. **Наблюдение:** проверяет вывод задания, затем запись и статус в ферме. Закрытие управляющего клиента автора не останавливает включённое задание, пока координатор и worker работают. Выключать нужно конкретное задание явно.
|
||||
5. **Отправка:** админ отдельно включает согласованный receiver фермы. Успех подтверждается ответом жюрейки; напечатанного значения или записи в очереди недостаточно.
|
||||
|
||||
<a id="one-shot-and-scheduled-harmless-example"></a>
|
||||
### Безвредный пример: один раз и по расписанию
|
||||
|
||||
Используйте `ready.sh` из [первого безвредного задания](#first-harmless-task). Команды выполняются из распакованного каталога клиента Neo на машине админа **или** участника, с её приватным `client_config.yml`. Они меняют общие задания, поэтому используйте свой согласованный ID.
|
||||
|
||||
```bash
|
||||
./neo --verbose=false --config client_config.yml add \
|
||||
--id ready-author-a --disabled --interval 1m --timeout 3s exploits/ready.sh
|
||||
```
|
||||
|
||||
Админ запускает совместимый worker в **отдельном терминале**, из его распакованного каталога клиента:
|
||||
|
||||
```bash
|
||||
./neo --verbose=false --config client_config.yml run --jobs 1 --endless-jobs 0
|
||||
```
|
||||
|
||||
После сообщений о загрузке скрипта и готовности рабочих циклов автор или админ запускает один прогон:
|
||||
|
||||
```bash
|
||||
./neo --verbose=false --config client_config.yml single ready-author-a
|
||||
./neo --verbose=false --config client_config.yml tail --count 20 ready-author-a
|
||||
```
|
||||
|
||||
Ожидается `worker ready for ...`; это не флаг. `single` охватывает настроенный список команд и не включает расписание. Для осознанной проверки периодического запуска:
|
||||
|
||||
```bash
|
||||
./neo --verbose=false --config client_config.yml enable ready-author-a
|
||||
# Observe subsequent runs; the configured interval is one minute.
|
||||
./neo --verbose=false --config client_config.yml tail --count 20 ready-author-a
|
||||
./neo --verbose=false --config client_config.yml disable ready-author-a
|
||||
```
|
||||
|
||||
Cron не нужен. Интервал относится к зарегистрированному заданию, а не к терминалу автора. Native-worker останавливается через Ctrl+C; выключение задания прекращает будущие периодические прогоны, но уже начатая работа может завершиться. Чтобы выполнять на физической машине координатора, запустите там отдельный worker: один сервер исполнителем не является.
|
||||
|
||||
<a id="troubleshooting"></a>
|
||||
## Диагностика
|
||||
|
||||
| Симптом | Что проверить |
|
||||
|---|---|
|
||||
| Не проходит вход | Точный LAN-адрес/порт координатора и общий ключ |
|
||||
| Задание ждёт | Worker запущен и его job slots не исчерпаны |
|
||||
| Только что добавленное задание не найдено | Дождитесь загрузки worker и перезапуска рабочих циклов, затем повторите единичный прогон |
|
||||
| Ошибка скрипта/interpreter | Shebang, executable file и зависимости именно исполняющего worker |
|
||||
| Результат есть, флагов нет | Формат флага и route/authentication worker→farm |
|
||||
| Ферма rejected/expired | Receiver adapter, token, tick/lifetime и актуальный список команд |
|
||||
|
||||
Сырой `info` и debug могут содержать пароль фермы. Используйте `--verbose=false` и не показывайте диагностику в трансляции/публичных reports. Логи скриптов тоже могут содержать приватные данные.
|
||||
|
||||
[Инструкция участника](participant-guide-RU.md) · [Ферма](s4dfarm-RU.md) · [Установка админа](MACOS_FULL_DEPLOYMENT_AND_TESTING-RU.md)
|
||||
+161
@@ -0,0 +1,161 @@
|
||||
# Neo: distribute and run team scripts
|
||||
|
||||
English | [Русский](neo-RU.md)
|
||||
|
||||
Neo saves team scripts on a coordinator and distributes executions across connected workers and the farm's team list. Workers send matching flags to S4DFarm. It is useful when one laptop should not run every script for every target. It does not deploy defensive patches.
|
||||
|
||||
## Administrator
|
||||
|
||||
`python3 durka.py up` starts the coordinator. `python3 durka.py worker` starts the bundled light worker. Give participants the LAN coordinator address from `status` and the private `credentials.neo_key`.
|
||||
|
||||
Workers need the coordinator, farm and permitted targets reachable from their environment. The light image includes a shell; Python/Sage or other dependencies need separately prepared compatible workers. Start the farm before Neo.
|
||||
|
||||
Configure an actual Ethernet bind before sharing with native clients/workers. A loopback demo uses the in-stack worker and an internal farm URL; outside workers cannot use that container-only address.
|
||||
|
||||
## Install a client
|
||||
|
||||
Use the [v2.4.2 release](https://github.com/C4T-BuT-S4D/neo/releases/tag/v2.4.2), matching the maintained client/worker version:
|
||||
|
||||
| Machine | Asset |
|
||||
|---|---|
|
||||
| Apple Silicon Mac | `neo_client_2.4.2_darwin_arm64.zip` |
|
||||
| Intel Mac | `neo_client_2.4.2_darwin_amd64.zip` |
|
||||
| Linux amd64 | `neo_client_2.4.2_linux_amd64.tar.gz` |
|
||||
| Linux arm64 | `neo_client_2.4.2_linux_arm64.tar.gz` |
|
||||
|
||||
Download/extract before leaving for the event. The archive contains `neo`, `client_config.yml` and an `exploits` directory. Run the commands below from that extracted directory. Windows has no native client in this release; use a permitted Linux environment/worker.
|
||||
|
||||
Edit `client_config.yml`:
|
||||
|
||||
```yaml
|
||||
host: "<ADMIN_ETHERNET_IPV4>:5005"
|
||||
grpc_auth_key: "<PRIVATE_NEO_KEY_FROM_ADMIN>"
|
||||
exploit_dir: "exploits"
|
||||
```
|
||||
|
||||
Replace the placeholders; keep the config private. Follow the normal application approval procedure on macOS if prompted. Never put the key in a screenshot or shell argument.
|
||||
|
||||
```bash
|
||||
./neo --verbose=false --config client_config.yml --help
|
||||
```
|
||||
|
||||
## First harmless task
|
||||
|
||||
Create `exploits/ready.sh` in your editor with:
|
||||
|
||||
```sh
|
||||
#!/bin/sh
|
||||
# flush=True: printf writes immediately; this task makes no target request.
|
||||
printf 'worker ready for %s\n' "$1"
|
||||
```
|
||||
|
||||
Make it executable and run locally:
|
||||
|
||||
```bash
|
||||
chmod u+x exploits/ready.sh
|
||||
./exploits/ready.sh 192.0.2.1
|
||||
```
|
||||
|
||||
Register it **disabled** so it does not start recurring work:
|
||||
|
||||
```bash
|
||||
./neo --verbose=false --config client_config.yml add \
|
||||
--id ready --disabled --interval 1h --timeout 3s exploits/ready.sh
|
||||
```
|
||||
|
||||
Ask the admin to start the worker, then request one run:
|
||||
|
||||
```bash
|
||||
./neo --verbose=false --config client_config.yml single ready
|
||||
./neo --verbose=false --config client_config.yml tail --count 20 ready
|
||||
```
|
||||
|
||||
`single` runs once on **all configured teams**. This example only prints readiness and does not contact them. Its output is not a flag and should not produce accepted flags in the farm. Look for the ready message; recurring execution remains disabled.
|
||||
|
||||
## Real scripts and recurring execution
|
||||
|
||||
Scripts receive the target IP as their first argument. Use an available interpreter/shebang and flush stdout; flags matching the configured format go to the farm. Test locally first. Never load untrusted scripts into workers.
|
||||
|
||||
Register your script with an explicit ID, interval and timeout using the same disabled-first `add` command. After a permitted single run succeeds, enable or disable that exact ID:
|
||||
|
||||
```bash
|
||||
./neo --verbose=false --config client_config.yml enable <TASK_ID>
|
||||
./neo --verbose=false --config client_config.yml disable <TASK_ID>
|
||||
```
|
||||
|
||||
Adding an existing ID prompts before replacing its version. Check actual worker dependencies, scope and competition rules before enabling recurring execution. The maintained [upstream commands](https://github.com/C4T-BuT-S4D/neo/tree/2f2a4eb63f9715155844284f253ba786d330c9ae/cmd/client) define the CLI.
|
||||
|
||||
To contribute your own compatible native worker:
|
||||
|
||||
```bash
|
||||
./neo --verbose=false --config client_config.yml run --jobs 1
|
||||
```
|
||||
|
||||
This runs in the foreground; stop it with Ctrl+C. Prepare dependencies in that environment first. Native Mac/runtime behavior still needs a rehearsal on the actual machine.
|
||||
|
||||
## Team workflow: clients, coordinator and workers
|
||||
|
||||
The same `neo` binary has two roles: commands such as `add`, `single`, `enable`, `disable` and `tail` are a control client; `run` turns that process into an execution worker. The coordinator stores scripts/configuration and assigns targets to workers. It does not execute scripts itself.
|
||||
|
||||
```text
|
||||
Author A's client ──┐
|
||||
Author B's client ──┼──> coordinator ──> connected worker(s) ──> script stdout
|
||||
Admin's client ────┘ │
|
||||
└──> S4DFarm queue ──> jury
|
||||
```
|
||||
|
||||
Workers extract values matching the configured flag format from stdout and send them directly to the farm. The coordinator supplies the farm URL/authentication and team configuration. Reaching the coordinator alone is therefore insufficient: the executing worker must also reach the farm. Farm ingestion and farm-to-jury submission are separate operations; `QUEUED` is not `ACCEPTED`.
|
||||
|
||||
1. **Admin:** start the existing stack with `python3 durka.py up` from the DurkaHelper checkout. Share the coordinator address/key privately. Start one prepared worker: either the bundled `python3 durka.py worker`, or native `./neo ... run` below. Do not start both merely to manage tasks. The light Docker worker does not supply arbitrary script dependencies.
|
||||
2. **Each author:** use a private client config pointing to that same coordinator. Use distinct task IDs, for example `ready-author-a` and `ready-author-b`; task IDs are shared, not private per participant. Set a distinct `client_id` for each worker. The shared key is trusted-team access, not a read-only participant role.
|
||||
3. **Register:** upload a script disabled. Wait until the worker has downloaded it and its execution loops have restarted before requesting a single run. Dependencies and auxiliary files must exist in the worker's environment, not merely on the uploading laptop.
|
||||
4. **Observe:** inspect task output and then the farm entry/status. Closing an author's control client does not stop an enabled task while the coordinator and worker remain running. Disable that exact task explicitly.
|
||||
5. **Submission:** the admin separately enables the farm's approved receiver. Confirm the receiver's accepted response; a printed value or queue entry alone does not prove acceptance.
|
||||
|
||||
### One-shot and scheduled harmless example
|
||||
|
||||
Use the `ready.sh` from [First harmless task](#first-harmless-task). Run these commands from the extracted Neo client directory on either the admin's machine or a participant's machine, with that machine's private `client_config.yml`. They modify shared task state, so use your own agreed ID.
|
||||
|
||||
```bash
|
||||
./neo --verbose=false --config client_config.yml add \
|
||||
--id ready-author-a --disabled --interval 1m --timeout 3s exploits/ready.sh
|
||||
```
|
||||
|
||||
The administrator starts a compatible worker in a **separate terminal**, from its own extracted client directory:
|
||||
|
||||
```bash
|
||||
./neo --verbose=false --config client_config.yml run --jobs 1 --endless-jobs 0
|
||||
```
|
||||
|
||||
After its download/loop-ready messages, the author or admin requests one run:
|
||||
|
||||
```bash
|
||||
./neo --verbose=false --config client_config.yml single ready-author-a
|
||||
./neo --verbose=false --config client_config.yml tail --count 20 ready-author-a
|
||||
```
|
||||
|
||||
Expect `worker ready for ...`; this is not a flag. `single` covers the configured team list and does not enable recurrence. To test scheduling deliberately:
|
||||
|
||||
```bash
|
||||
./neo --verbose=false --config client_config.yml enable ready-author-a
|
||||
# Observe subsequent runs; the configured interval is one minute.
|
||||
./neo --verbose=false --config client_config.yml tail --count 20 ready-author-a
|
||||
./neo --verbose=false --config client_config.yml disable ready-author-a
|
||||
```
|
||||
|
||||
No cron job is needed. The interval belongs to the registered task, not to the author's terminal. A native worker stops with Ctrl+C; a disabled task stops future scheduled runs, but already running work may finish. To execute on the coordinator's physical machine, run a worker there as a separate process: the server alone is not an executor.
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
| Symptom | Check |
|
||||
|---|---|
|
||||
| Cannot authenticate | Exact coordinator LAN address/port and shared key |
|
||||
| Job remains waiting | A worker is running and has not exhausted its job slots |
|
||||
| Newly added task is not found | Wait for its worker download and execution-loop restart, then retry one run |
|
||||
| Script/interpreter failure | Shebang, executable file and dependencies on the executing worker |
|
||||
| Results exist but flags do not arrive | Correct flag format and worker-to-farm route/authentication |
|
||||
| Farm rejects/expires flags | Receiver adapter, token, tick/lifetime and current team map |
|
||||
|
||||
Raw `info` and debug output can include the farm password. Use `--verbose=false` and keep diagnostics off broadcasts/public reports. Script logs can also contain sensitive data.
|
||||
|
||||
[Participant guide](participant-guide.md) · [Farm](s4dfarm.md) · [Admin setup](MACOS_FULL_DEPLOYMENT_AND_TESTING.md)
|
||||
@@ -0,0 +1,66 @@
|
||||
# Офлайн-работа
|
||||
|
||||
[English](offline-bundles.md) | Русский
|
||||
|
||||
<a id="offline-operation"></a>
|
||||
<a id="prepare-the-machine-once"></a>
|
||||
## Подготовьте машину заранее
|
||||
|
||||
Сканеру нужен Python 3.10+; полному стеку — ещё Docker и кешированные образы. Установите их при наличии Интернета. Пройдите [установку на Mac](MACOS_FULL_DEPLOYMENT_AND_TESTING-RU.md), завершите `durka.py setup`, поднимите стек и проверьте его до выезда.
|
||||
|
||||
Сохраните репозиторий, приватный каталог `local/` и Docker data. Перед офлайн-запуском не удаляйте образы, не сбрасывайте Docker Desktop и не запускайте cleanup/prune. Setup может скачивать и собирать; обычный запуск использует подготовленные образы и не должен незаметно делать pull.
|
||||
|
||||
<a id="rehearse-without-internet"></a>
|
||||
## Репетиция без Интернета
|
||||
|
||||
<a id="prepare-clean-event-state-after-a-rehearsal"></a>
|
||||
### Чистое окружение соревнования после репетиции
|
||||
|
||||
Не удаляйте подготовленный workspace до создания замены. Сначала остановите native Neo worker (`Ctrl+C`) и выполните `down` с учебным конфигом. Сохраните кеш закреплённых исходников и Docker-образы. На том же подготовленном Mac/Linux:
|
||||
|
||||
```bash
|
||||
python3 durka.py --config local/event.json prepare-clean --from-config local/rehearsal.json
|
||||
python3 durka.py --config local/event.json prepare-clean --from-config local/rehearsal.json --apply
|
||||
```
|
||||
|
||||
Первая команда — read-only preview. Вторая создаёт **новые** приватный конфиг и `local/event-workspace`, используя проверенные сохранённые образы и локальные закреплённые исходники. Она ничего не скачивает, не собирает, не запускает контейнеры, не копирует прежние базы/задания/захваты и не удаляет репетицию. Создаются новые локальные пароли, placeholders для жюрейки/команд, пустые данные и пустой FILE-захват. Прежние локальные порты сохраняются; начальный bind нового стека — `127.0.0.1`. Отсутствующие образы, грязный/отсутствующий кеш исходников, работающий исходный deployment, удалённый Docker endpoint или существующие выходные пути блокируют подготовку. Частичный кандидат после сбоя сохраняется для проверки; повторяйте с новым именем конфига.
|
||||
|
||||
Заполните `local/event.json`: реальный LAN bind, команды, IP Vulnbox, формат флага и согласованные параметры отправки ForcAD. Затем выполните `configure`, `up` и `doctor` с `--config local/event.json`. Worker и отправка включаются отдельно; не включайте их с placeholders. Новый native Neo конфиг — `local/event-workspace/config/neo-native.yml`; используйте подготовленный бинарник, а не прежний учебный клиентский конфиг. После изменения LAN bind передайте Neo переопределение `--host MAC_LAN_IP:NEO_PORT` вместе с новым конфигом. Зависимости каждого скрипта готовятся отдельно.
|
||||
|
||||
Проверьте новую установку и запуск без Интернета до удаления учебных конфига/workspace. Сохраните репозиторий, закреплённый кеш исходников, образы, Neo binary и отдельный Linux LIVE bundle. Для фактического разрешённого узла/интерфейса создайте новый LIVE-конфиг: заполненный учебный конфиг непереносим. Это **чистые данные приложений на уже подготовленной машине**, а не офлайн-установщик для пустого Mac. Не используйте Docker prune/reset или широкое удаление `local/`.
|
||||
|
||||
Оставьте Ethernet/LAN, но отключите Интернет своим разрешённым способом. Не меняйте сеть соревнования.
|
||||
|
||||
```bash
|
||||
python3 durka.py down
|
||||
python3 durka.py up
|
||||
python3 durka.py status
|
||||
```
|
||||
|
||||
Откройте Farm и Packmate, проверьте Neo безвредным скриптом, просканируйте локальную копию сервиса и импортируйте закрытый синтетический PCAP. Остановите и запустите стек снова. Если что-то пытается скачиваться, исправьте подготовку ещё дома. Ручной PCAP-анализ остаётся доступен, когда LIVE-захват запрещён.
|
||||
|
||||
Это офлайн-перезапуск подготовленной машины, а не установка на пустую. Экспорт Docker images сам по себе не включает Python, Docker Desktop, локальный конфиг, лицензии или Neo client.
|
||||
|
||||
<a id="optional-core-archive"></a>
|
||||
## Необязательный архив core
|
||||
|
||||
Сопровождающий может создать архив только tracked-исходников из закоммиченного checkout. Родительский каталог должен существовать, путь архива должен быть новым.
|
||||
|
||||
```bash
|
||||
python3 scripts/build_offline_bundle.py --output ../offline-kit/durkahelper-core.tar.gz
|
||||
python3 scripts/build_offline_bundle.py --verify ../offline-kit/durkahelper-core.tar.gz
|
||||
```
|
||||
|
||||
В core-архив не входят ключи, локальные данные, логи и PCAP. Сторонних runtimes/images в нём тоже нет. Проверка автоматическая; для обычной работы переписывать хеш не нужно.
|
||||
|
||||
<a id="moving-an-external-cache"></a>
|
||||
## Перенос внешнего кеша
|
||||
|
||||
Для другой машины есть расширенные утилиты export/import: они сохраняют закреплённые образы и проверяют входную inventory. Это не часть обычного запуска.
|
||||
|
||||
```bash
|
||||
python3 scripts/toolchain_inventory.py --help
|
||||
python3 scripts/toolchain_bundle.py --help
|
||||
```
|
||||
|
||||
Низкоуровневые команды намеренно требуют независимо доверенного входа для импортируемых архивов. Не обходите эту проверку и не выдавайте частичный экспорт образов за полный установочный комплект. Заполненные inventories храните приватно. Перед распространением проверьте [лицензии](../THIRD_PARTY_NOTICES-RU.md); [developer fixtures](../integration/README-RU.md) проверяют изолированный cold start.
|
||||
@@ -0,0 +1,60 @@
|
||||
# Offline operation
|
||||
|
||||
English | [Русский](offline-bundles-RU.md)
|
||||
|
||||
## Prepare the machine once
|
||||
|
||||
The scanner needs Python 3.10+; the full stack also needs Docker and cached images. Install these while connected. Follow the [Mac setup](MACOS_FULL_DEPLOYMENT_AND_TESTING.md), finish `durka.py setup`, start the stack, and test it before leaving for the event.
|
||||
|
||||
Keep your repository, private `local/` directory and Docker data. Do not delete Docker images, reset Docker Desktop or run cleanup/prune before an offline start. Setup can download/build; normal startup uses prepared image identities and must not silently pull.
|
||||
|
||||
## Rehearse without Internet
|
||||
|
||||
### Prepare clean event state after a rehearsal
|
||||
|
||||
Do not delete the prepared workspace before creating its replacement. First stop the native Neo worker (`Ctrl+C`) and run `down` with the rehearsal config. Keep the pinned source cache and Docker images. On that same prepared Mac/Linux machine:
|
||||
|
||||
```bash
|
||||
python3 durka.py --config local/event.json prepare-clean --from-config local/rehearsal.json
|
||||
python3 durka.py --config local/event.json prepare-clean --from-config local/rehearsal.json --apply
|
||||
```
|
||||
|
||||
The first command is a read-only preview. The second writes a **new** private config and `local/event-workspace`, using verified existing image identities and local pinned source checkouts. It does not download, build, start containers, copy old databases/tasks/captures, or delete the rehearsal. It generates fresh local passwords, placeholder jury/team settings, empty persistent state and an empty FILE capture. The previous local ports are retained; the new bind is initially `127.0.0.1`. Missing images, dirty/missing source cache, a running source deployment, remote Docker endpoints or existing output paths block preparation. A failed partial candidate is retained for inspection; choose a new config filename before retrying.
|
||||
|
||||
Fill `local/event.json` with the actual LAN bind, team map, Vulnbox IP, flag format and approved ForcAD submission settings. Then run `configure`, `up` and `doctor` with `--config local/event.json`. Worker execution and submission remain opt-in; do not enable them with placeholder settings. The new native Neo config is `local/event-workspace/config/neo-native.yml`; use the prepared native binary, not the previous rehearsal client config. After changing the LAN bind, pass Neo's `--host MAC_LAN_IP:NEO_PORT` override to the new config. Prepare each script's dependencies separately.
|
||||
|
||||
Verify the new installation and disconnected startup before removing the old rehearsal config/workspace. Retain the repository, pinned source cache, cached images, Neo binary and separate Linux LIVE image bundle. Re-create the LIVE target config for the actual authorized host/interface; its populated rehearsal config is not portable. This prepares **fresh application state on an already prepared machine**, not an offline installer for a blank Mac. Do not use Docker prune/reset or broad deletion of `local/`.
|
||||
|
||||
Keep Ethernet/LAN access, but disconnect the Internet using your own permitted arrangement. Do not change event networking.
|
||||
|
||||
```bash
|
||||
python3 durka.py down
|
||||
python3 durka.py up
|
||||
python3 durka.py status
|
||||
```
|
||||
|
||||
Open Farm and Packmate, test Neo with a harmless script, scan a local service copy and import a closed synthetic PCAP. Stop and start again. If anything attempts a download, fix the preparation while still at home. Manual PCAP analysis remains available when LIVE capture is not permitted.
|
||||
|
||||
This is an offline restart on a prepared machine, not installation on an empty machine. Exporting Docker images alone does not include Python, Docker Desktop, local config, licenses or Neo client binaries.
|
||||
|
||||
## Optional core archive
|
||||
|
||||
Maintainers can create a tracked-only source archive from a committed checkout. The output parent must exist and the archive path must be new.
|
||||
|
||||
```bash
|
||||
python3 scripts/build_offline_bundle.py --output ../offline-kit/durkahelper-core.tar.gz
|
||||
python3 scripts/build_offline_bundle.py --verify ../offline-kit/durkahelper-core.tar.gz
|
||||
```
|
||||
|
||||
The core archive excludes keys, local data, logs and PCAP. It does not contain third-party runtimes/images. Verification is automatic; no hash needs to be transcribed for ordinary operation.
|
||||
|
||||
## Moving an external cache
|
||||
|
||||
For transport to another machine, advanced export/import utilities preserve pinned image identities and verify the incoming inventory. They are not part of routine startup.
|
||||
|
||||
```bash
|
||||
python3 scripts/toolchain_inventory.py --help
|
||||
python3 scripts/toolchain_bundle.py --help
|
||||
```
|
||||
|
||||
These lower-level commands deliberately require an independently trusted input for imported archives. Do not bypass that check or treat a partial image export as a complete installation kit. Keep populated inventories private. Review [third-party licenses](../THIRD_PARTY_NOTICES.md) before redistribution; the [developer fixtures](../integration/README.md) exercise isolated cold-start behavior.
|
||||
@@ -0,0 +1,121 @@
|
||||
<a id="offline-source-scanner"></a>
|
||||
# Офлайн-сканер исходников
|
||||
|
||||
[English](offline-scanner.md) | Русский
|
||||
|
||||
[Каталог](vulnerabilities/README-RU.md) · [Рабочий процесс оператора](defense-RU.md) · [Разработка](development-RU.md)
|
||||
|
||||
Scanner 1.8.0 использует 174 локальных правила: 30 Python AST, 143 regex и одно правило ограниченного анализа JS-токенов. Подсказки конкретных frameworks также расширяют существующие правила. Это детерминированный помощник для review с ограничениями ресурсов; он не является базой CVE, dependency resolver, детектором эксплойтов или движком межпроцедурного taint-анализа.
|
||||
|
||||
<a id="safe-first-scan"></a>
|
||||
## Первый безопасный scan
|
||||
|
||||
Свидетельство: `REVIEWED`; исторические прогоны записываются отдельно. Эффект: `READ-ONLY` (перенаправление stdout создаёт выбранный вами файл вывода). Рабочий каталог: корень DurkaHelper. Требования: Python 3.10+, разрешённая локальная копия сервиса и приватный каталог вывода. Входной код не исполняется, сетевых запросов нет. Rollback: не нужен; проверяйте вывод перед передачей другим.
|
||||
|
||||
```bash
|
||||
python3 -I -S scripts/defense_scan.py /path/to/service --patches
|
||||
python3 -I -S scripts/defense_scan.py /path/to/service --json
|
||||
python3 -I -S scripts/defense_scan.py --list-rules
|
||||
python3 -I -S scripts/defense_scan.py --explain PY-SQL
|
||||
```
|
||||
|
||||
Используйте показанный выше isolated/no-site режим интерпретатора, чтобы не загружать Python startup files, контролируемые целью. Сканер загружает свой доверенный rule pack, а не правила из сканируемого каталога. Не устанавливайте зависимости и не импортируйте цель только ради её изучения.
|
||||
|
||||
<a id="reading-a-finding"></a>
|
||||
## Как читать находку
|
||||
|
||||
Каждая находка содержит путь относительно root и физическую строку, стабильный rule ID, статическое объяснение, шаблон исправления, рекомендации проверки и точную ссылку на каталог. Новые metadata добавляют family, применимый CWE, review priority, signal kind и limitations. Это классификация для review, а не доказательство достижимости или эксплуатируемости.
|
||||
|
||||
Находки не включают raw source lines, argv, environment или обнаруженные значения секретов. Имена файлов и hashes всё равно могут быть чувствительными. Текстовый вывод безопасно представляет неподдерживаемые консолью символы; JSON переносим.
|
||||
|
||||
Корректное исправление может сохранить сигнал: например, проверенный dynamic URL или bounded reader всё ещё может совпадать с правилом. И наоборот, удаление или перенос кода может убрать совпадение, не исправляя авторизацию. Изучайте настоящий путь source-to-sink и проверяйте поведение.
|
||||
|
||||
<a id="infrastructure-context"></a>
|
||||
## Контекст инфраструктуры
|
||||
|
||||
Необязательный [пример context](../config/scanner-context.example.json) строго не содержит секретов:
|
||||
|
||||
```json
|
||||
{
|
||||
"schema": "durkahelper.scanner-context.v1",
|
||||
"infrastructure": ["docker-desktop", "compose", "vulnbox", "team-lan", "s4dfarm", "neo", "packmate"],
|
||||
"role": "both"
|
||||
}
|
||||
```
|
||||
|
||||
Свидетельство: `REVIEWED`; эффект `READ-ONLY`; рабочий каталог и требования те же, что для первого scan. Ожидается: те же применимые правила остаются включёнными, но получают контекстные приоритеты и объяснения. Это не подразумевает runtime discovery или разрешение на действия.
|
||||
|
||||
```bash
|
||||
python3 -I -S scripts/defense_scan.py /path/to/service \
|
||||
--context config/scanner-context.example.json --json
|
||||
```
|
||||
|
||||
Допустимые роли: defender, administrator и both. Context никогда не отключает правила, не выполняет команды, не разрешает сетевые операции и не раскрывает состояние работающего Docker. Его нормализованный смысл входит в scope fingerprint отчёта.
|
||||
|
||||
<a id="inputs-and-limits"></a>
|
||||
## Входы и ограничения
|
||||
|
||||
Поддерживаемые семейства исходников и конфигурации: Python, JavaScript/TypeScript, PHP, Go, Java, C#/.NET, C/C++, Ruby, Rust, SQL, templates, Dockerfiles, shell и распространённые форматы конфигурации. Язык определяется по имени файла; поддерживаемое имя не доказывает язык или версию runtime.
|
||||
|
||||
По умолчанию: 1 MiB на файл, 20 000 файлов, 10 000 находок. Сканер исключает распространённые dependency/build/cache-каталоги и похожие на секреты имена файлов, например форматы private keys и .env, не являющиеся примерами. Явные исключения записываются в scope. Оцените, требуется ли отдельный разрешённый review для excluded/generated/vendor code.
|
||||
|
||||
Свидетельство: `REVIEWED`; эффект `READ-ONLY`; рабочий каталог — корень. Эти параметры меняют покрытие и, следовательно, сопоставимость:
|
||||
|
||||
```bash
|
||||
python3 -I -S scripts/defense_scan.py /path/to/service \
|
||||
--exclude generated --max-bytes 1048576 --max-files 20000 --max-findings 10000 --json
|
||||
```
|
||||
|
||||
Symlink leaves, nonregular files, нечитаемые или нестабильные файлы, parsing failures и превышенные limits дают incomplete/partial, а не ложный clean success. Обычные ancestor links macOS отличаются от небезопасных input leaves. Никогда не ослабляйте эти защиты ради зелёного отчёта.
|
||||
|
||||
Regex-сканирование использует ограниченные перекрывающиеся окна: до 12 физических строк и 8 192 символов в окне с перекрытием в шесть строк. Слишком длинные физические строки пропускаются с partial issue. Шаблоны за границей окна, неизвестные wrappers и сгенерированные строки могут быть пропущены. У новых code-only детекторов есть лексические исключения; старые regex-детекторы всё ещё могут находить совпадения в комментариях или строковых примерах.
|
||||
|
||||
Python-анализ — ограниченный синтаксический обход AST с ограниченным отслеживанием import aliases/scalars и консервативной инвалидацией. Он не разрешает произвольные types, branches, dynamic imports или значения между function calls. Ошибки parse/node-limit сообщаются. Обработка aliases в JavaScript ограничена; это не полный parser или scope/taint engine.
|
||||
|
||||
<a id="json-scope-and-comparison"></a>
|
||||
## JSON, scope и сравнение
|
||||
|
||||
Отчёты включают tool version, timestamp, offline flag, scope, findings, issues, skipped counts, scanned counts, partial и exit code. Scope v2 связывает canonical root identity, rule fingerprint, path semantics, exclusions, limits и scanner context. Порядок context нормализуется перед hashing. Сравнения между версиями или scope не взаимозаменяемы.
|
||||
|
||||
Свидетельство: `REVIEWED`; эффект `READ-ONLY`. Рабочий каталог — корень; нужны два приватных JSON-отчёта заведомо сопоставимых scans. Ожидается: множества new/existing/not-observed либо exit 2 при неполном сравнении. Входные файлы не изменяются.
|
||||
|
||||
```bash
|
||||
python3 -I -S scripts/defense_diff.py before-scan.json after-scan.json --json
|
||||
```
|
||||
|
||||
Старые отчёты остаются читаемыми там, где это поддержано, но отсутствующий scope, различия v1/v2, изменения версии или partial reports не позволяют получить безусловно сопоставимый результат. Сопоставление использует path/line/rule: перенос строки может выглядеть как удалённый и добавленный сигнал. «Not observed» никогда не означает «уязвимость исправлена».
|
||||
|
||||
| Exit | Значение |
|
||||
|---|---|
|
||||
| 0 | Полный поддерживаемый scan без находок либо полное сравнение без новых сигналов, требующих действий |
|
||||
| 1 | Находки или новые сигналы, требующие review |
|
||||
| 2 | Invalid, partial, blocked или incomparable result; также отсутствие поддерживаемых входов |
|
||||
|
||||
<a id="coverage-and-next-steps"></a>
|
||||
## Покрытие и следующие шаги
|
||||
|
||||
Свидетельство: `REVIEWED`; эффект `READ-ONLY`; рабочий каталог — корень. Проверка анализирует только безвредные строки; snippets не исполняются.
|
||||
|
||||
```bash
|
||||
python3 scripts/scanner_coverage.py --check
|
||||
python3 scripts/scanner_coverage.py --json
|
||||
```
|
||||
|
||||
Ledger показывает пары rule/language, независимо написанные positives/negatives и честно отмеченные пробелы старых правил. Примеры «до/после» из metadata не считаются независимыми свидетельствами. Для исправлений используйте [каталог](vulnerabilities/README-RU.md) и [проверку патчей](patch-validation-RU.md); для контейнерной политики — [deployment audit](local-tools-RU.md#deployment-audit), не утверждая, что YAML regex доказывает runtime safety.
|
||||
|
||||
<a id="framework-and-database-boundaries"></a>
|
||||
|
||||
## Границы framework и базы данных
|
||||
|
||||
| Область | Расширенные сигналы | Ручная проверка |
|
||||
|---|---|---|
|
||||
| Flask | Явные debugger/session settings; auth order включая put/patch/delete; credentials в app.logger | Проверяйте зарегистрированный HTTP endpoint, не только вызов функции. Сохраняйте HttpOnly; не включайте Secure поверх HTTP-only checker. |
|
||||
| Psycopg | SQL(не-литерал), сырые/неизвестные части format/join/as_string; известный quoting подавляет этот сигнал | Bind values через реальный драйвер. Identifier экранирует имя, но не разрешает выбирать любую таблицу. |
|
||||
| PostgreSQL | ROLE/USER bypass, значимые PUBLIC grants, роли доступа к файлам/программам сервера | Проверьте runtime-роль, наследование и ownership. Меняйте только согласованные права сервиса; проверьте запросы, миграции и восстановление. |
|
||||
| JS/TS | SQL из request в известных pg/mysql bindings, reflective credentialed cors, отключённый session HttpOnly, прямые credentials в логах | Bind values, allowlist origins, сохраните HttpOnly и логируйте категории. Проверьте ошибки auth, sessions, реальные response headers и checker. |
|
||||
|
||||
JS-подсказки используют ограниченные токены, не полноценный парсер: 100 000 токенов на файл, 128 вложенных delimiters, 2 048 токенов на выражение. Распознаются точные default/namespace imports и прямые конструкторы драйверов. Наблюдаемое переприсваивание/parameter shadowing консервативно отключает binding во всём файле. Именованные импорты, неоднозначные regex, templates, динамические keys/spreads, полученные соединения, custom loggers и потоки между файлами проверяются вручную. Helper redact() не считается доверенным и не исполняется: его результат вне прямого поиска значений.
|
||||
|
||||
Сигналы Docker privilege/socket/root-user остаются включены. Проверьте локальные Compose/Dockerfile, затем deployment-model audit для bind, backend exposure, mounts, image pins и runtime policy. Скан исходников не проверяет работающий daemon. LIVE и закрытый PCAP описаны в [захвате трафика](traffic-capture-RU.md).
|
||||
|
||||
Версия 1.8.0 повышает semantic revision до v3. Старые revision-v2 отчёты читаются, но старое/новое сравнение завершается exit 2. Перед проверкой патча пересканируйте обе копии одной версией и с одинаковым контекстом; карточки с digest вручную заполнять не нужно.
|
||||
@@ -0,0 +1,112 @@
|
||||
# Offline source scanner
|
||||
|
||||
English | [Русский](offline-scanner-RU.md)
|
||||
|
||||
[Catalog](vulnerabilities/README.md) · [Operator workflow](defense.md) · [Development](development.md)
|
||||
|
||||
Scanner 1.8.0 uses 174 local rules: 30 Python AST, 143 regex and one bounded JavaScript-token rule. Framework-specific token hints also extend existing rules. It is a bounded, deterministic review assistant—not a CVE database, dependency resolver, exploit detector or interprocedural taint engine.
|
||||
|
||||
## Safe first scan
|
||||
|
||||
Evidence: `REVIEWED`; historical execution is recorded separately. Effect: `READ-ONLY` (stdout redirection creates your chosen output file). Cwd: DurkaHelper root. Prerequisites: Python 3.10+, an authorized local service copy and a private output directory. No input code executes and no network requests occur. Rollback: none; review output before sharing it.
|
||||
|
||||
```bash
|
||||
python3 -I -S scripts/defense_scan.py /path/to/service --patches
|
||||
python3 -I -S scripts/defense_scan.py /path/to/service --json
|
||||
python3 -I -S scripts/defense_scan.py --list-rules
|
||||
python3 -I -S scripts/defense_scan.py --explain PY-SQL
|
||||
```
|
||||
|
||||
Use the interpreter's isolated/no-site mode shown above to avoid loading target-controlled Python startup files. The scanner loads its own trusted rule pack, not rules supplied by the scanned directory. Do not install dependencies or import the target just to inspect it.
|
||||
|
||||
## Reading a finding
|
||||
|
||||
Each finding includes a root-relative path and physical line, stable rule ID, static explanation, fix template, verification guidance and an exact catalog link. New metadata adds family, CWE where applicable, review priority, signal kind and limitations. These are review classifications, not proof of reachability or exploitability.
|
||||
|
||||
Findings do not include raw source lines, argv, environment or discovered secret values. Filenames and hashes can still be sensitive. Text output safely represents unsupported console characters; JSON is portable.
|
||||
|
||||
A correct fix can retain a signal: for example a validated dynamic URL or bounded reader may still match. Conversely, deleting or moving code may remove a match without fixing authorization. Review the real source-to-sink path and verify behavior.
|
||||
|
||||
## Infrastructure context
|
||||
|
||||
The optional [context example](../config/scanner-context.example.json) is strictly non-secret:
|
||||
|
||||
```json
|
||||
{
|
||||
"schema": "durkahelper.scanner-context.v1",
|
||||
"infrastructure": ["docker-desktop", "compose", "vulnbox", "team-lan", "s4dfarm", "neo", "packmate"],
|
||||
"role": "both"
|
||||
}
|
||||
```
|
||||
|
||||
Evidence: `REVIEWED`; effect `READ-ONLY`; same cwd/prerequisites as the first scan. Expected: the same applicable rules remain enabled, with contextual priorities/explanations. No runtime discovery or permission is implied.
|
||||
|
||||
```bash
|
||||
python3 -I -S scripts/defense_scan.py /path/to/service \
|
||||
--context config/scanner-context.example.json --json
|
||||
```
|
||||
|
||||
Allowed roles are defender, administrator and both. Context never disables rules, executes commands, authorizes network operations or reveals running Docker state. Its normalized meaning participates in the report scope fingerprint.
|
||||
|
||||
## Inputs and limits
|
||||
|
||||
Supported source/configuration families include Python, JavaScript/TypeScript, PHP, Go, Java, C#/.NET, C/C++, Ruby, Rust, SQL, templates, Dockerfiles, shell and common configuration formats. Language detection is filename-based; a supported filename does not prove runtime language or version.
|
||||
|
||||
Defaults: 1 MiB per file, 20,000 files, 10,000 findings. The scanner excludes common dependency/build/cache directories and secret-like filenames such as private-key formats and non-example .env files. Explicit exclusions are recorded in scope. Review whether excluded/generated/vendor code needs a separate authorized review.
|
||||
|
||||
Evidence: `REVIEWED`; effect `READ-ONLY`; cwd root. These options change coverage and therefore comparability:
|
||||
|
||||
```bash
|
||||
python3 -I -S scripts/defense_scan.py /path/to/service \
|
||||
--exclude generated --max-bytes 1048576 --max-files 20000 --max-findings 10000 --json
|
||||
```
|
||||
|
||||
Symlink leaves, nonregular files, unreadable/unstable files, parsing failures and exceeded limits produce incomplete/partial results, not false-clean success. Normal macOS ancestor links are distinguished from unsafe input leaves. Never relax these protections to make a report green.
|
||||
|
||||
Regex scanning uses bounded overlapping windows: up to 12 physical lines and 8,192 characters per window, with six-line overlap. Oversized physical lines are omitted with a partial issue. Patterns spread beyond the window, unknown wrappers and generated strings can be missed. New code-only detectors have lexical exclusions; older regex detectors may still match comments or string examples.
|
||||
|
||||
Python analysis is bounded syntactic AST traversal, with limited import-alias/scalar tracking and conservative invalidation. It does not resolve arbitrary types, branches, dynamic imports or values across function calls. Parse/node-limit failures are reported. JavaScript alias handling is bounded rather than a complete parser or scope/taint engine.
|
||||
|
||||
## JSON, scope and comparison
|
||||
|
||||
Reports include tool version, timestamp, offline flag, scope, findings, issues, skipped counts, scanned counts, partial and exit code. Scope v2 binds canonical root identity, rule fingerprint, path semantics, exclusions, limits and scanner context. Context ordering is normalized before hashing. Cross-version or cross-scope comparisons are not interchangeable.
|
||||
|
||||
Evidence: `REVIEWED`; effect `READ-ONLY`. Cwd: root; prerequisites two private JSON reports from intentionally comparable scans. Expected: new/existing/not-observed sets, or exit 2 when comparison is incomplete. No input files are changed.
|
||||
|
||||
```bash
|
||||
python3 -I -S scripts/defense_diff.py before-scan.json after-scan.json --json
|
||||
```
|
||||
|
||||
Older reports remain readable where supported, but missing scope, v1/v2 differences, version changes or partial reports prevent an unqualified comparable result. Matching uses path/line/rule: moving a line can appear as a removed and added signal. “Not observed” never means “vulnerability fixed.”
|
||||
|
||||
| Exit | Meaning |
|
||||
|---|---|
|
||||
| 0 | Complete supported scan without findings; or complete comparison without actionable new signals |
|
||||
| 1 | Findings/new signals needing review |
|
||||
| 2 | Invalid, partial, blocked or incomparable result; also no supported input |
|
||||
|
||||
## Coverage and next steps
|
||||
|
||||
Evidence: `REVIEWED`; effect `READ-ONLY`; cwd root. The check evaluates inert strings only; it does not execute the snippets.
|
||||
|
||||
```bash
|
||||
python3 scripts/scanner_coverage.py --check
|
||||
python3 scripts/scanner_coverage.py --json
|
||||
```
|
||||
|
||||
The ledger reports rule/language pairs, independently authored positives/negatives and honest legacy gaps. Metadata before/after examples do not count as independent evidence. For fixes use the [catalog](vulnerabilities/README.md) and [patch verification](patch-validation.md); for container policy use [deployment auditing](local-tools.md#deployment-audit), not a claim that YAML regex proves runtime safety.
|
||||
|
||||
## Framework and database boundaries
|
||||
|
||||
| Area | Expanded signals | Manual verification |
|
||||
|---|---|---|
|
||||
| Flask | Explicit debugger/session config; auth order including put/patch/delete; credentials in app.logger | Test the registered HTTP endpoint, not just a function call. Keep HttpOnly; do not force Secure onto an HTTP-only checker. |
|
||||
| Psycopg | SQL(nonliteral), raw/unknown format/join/as_string pieces; known quoting compositions suppress this signal | Bind values using the deployed driver. Identifier quotes a name but does not authorize selection of any table. |
|
||||
| PostgreSQL | ROLE/USER bypass, meaningful PUBLIC grants, server file/program roles | Inspect the real runtime role, inheritance and ownership. Change only approved service rights; retest queries, migrations and recovery. |
|
||||
| JS/TS | Request SQL to recognized pg/mysql bindings, reflective credentialed cors, disabled session HttpOnly, direct credential logging | Bind values, allowlist origins, retain HttpOnly and log categories. Test failed auth, sessions, real response headers and the checker. |
|
||||
|
||||
JS hints use bounded tokens, not a complete parser: 100,000 tokens per file, 128 nested delimiters, 2,048 tokens per inspected expression. Exact default/namespace imports and direct driver constructors are recognized. Observed reassignment/parameter shadowing disables a binding conservatively file-wide. Named imports, regex ambiguity, templates, dynamic keys/spreads, acquired connections, custom loggers and cross-file flows remain manual. A helper called redact() is not trusted or executed: its return value lies outside direct-value detection.
|
||||
|
||||
Docker privilege/socket/root-user signals remain enabled. Scan local Compose/Dockerfile sources, then use deployment-model auditing for binds, backend exposure, mounts, image pins and runtime policy. Neither source scan verifies the running daemon. See [traffic capture](traffic-capture.md) for LIVE and closed-PCAP routes.
|
||||
|
||||
Version 1.8.0 advances semantic revision to v3. Old revision-v2 reports remain readable but old/new comparison exits 2. Rescan both copies with the same scanner/context before patch verification; no manual digest cards are required.
|
||||
@@ -0,0 +1,74 @@
|
||||
<a id="packmate-inspect-traffic"></a>
|
||||
# Packmate: разбор трафика
|
||||
|
||||
[English](packmate.md) | Русский
|
||||
|
||||
Packmate показывает запросы/ответы и ищет по содержимому потоков. Он помогает защитнику распознать атаку и проверить изменение нужного поведения после патча. DurkaHelper даёт конфигурацию и launch/import; upstream-исходники не меняются.
|
||||
|
||||
<a id="ui-services-and-patterns"></a>
|
||||
## Где настроить сервисы и поиск в UI
|
||||
|
||||
Порт веб-интерфейса задаётся при deployment (`--ui-port` для SSH LIVE).
|
||||
Это **не порт анализируемого приложения**. Интерфейс захвата и IP стороны
|
||||
сервиса задаются в приватном deployment-конфиге, не в форме создания сервиса.
|
||||
Шестерёнка справа открывает дополнительные настройки UI.
|
||||
|
||||
1. На верхней панели нажмите **+**: заполните **Name** и **Port** приложения.
|
||||
Для нескольких портов создайте отдельную запись на каждый. Без регистрации
|
||||
сервиса потоки не сохраняются. Для обычного HTTP расшифровка TLS не нужна.
|
||||
2. Выберите созданный сервис на верхней панели. В LIVE новые потоки появляются
|
||||
автоматически; кнопка запуска анализа есть только в FILE.
|
||||
3. Для подсветки откройте **Patterns → +**. Укажите узнаваемый синтетический
|
||||
текст, например `DEMO-`, поиск подстроки, оба направления и действие
|
||||
**Highlight**, не **Ignore**. При необходимости выберите конкретный сервис.
|
||||
4. Откройте новый поток и проверьте запрос и ответ. Новый pattern действует на
|
||||
последующие потоки; **Lookback** применяет его к уже сохранённым.
|
||||
**Pause** приостанавливает отображение в вашем браузере, не сам захват.
|
||||
|
||||
Эти действия изменяют настройки Packmate в его БД, а не приложение или сеть.
|
||||
Если UI пустой, сначала проверьте регистрацию порта и отсутствие фильтра по
|
||||
pattern; затем IP стороны сервиса и наличие разрешённого трафика.
|
||||
Элементы сверены с [upstream UI guide закреплённой версии](https://gitlab.com/packmate/Packmate/-/blob/938031f1dedfbedabef5b049368ed5b6ba6a900a/docs/USAGE_EN.md).
|
||||
|
||||
<a id="file-on-the-laptop"></a>
|
||||
## FILE на ноутбуке
|
||||
|
||||
```bash
|
||||
python3 durka.py up
|
||||
python3 durka.py traffic import /path/to/closed-capture.pcap
|
||||
python3 durka.py status
|
||||
```
|
||||
|
||||
Откройте URL Packmate. Логин/пароль — `credentials.packmate_user / packmate_password` из приватного конфига админа.
|
||||
|
||||
1. [Зарегистрируйте сервис и шаблон поиска в UI](#ui-services-and-patterns).
|
||||
2. Проверьте `profile.packmate.local_ip`: это IP стороны сервиса **в capture**, а не адрес ноутбука.
|
||||
3. В боковой панели один раз нажмите жёлтую кнопку разбора FILE со стрелкой вниз
|
||||
и найдите известные запрос/ответ с правильным направлением. Не ищите буквальную
|
||||
надпись «Start» или форму загрузки: сам файл уже передан import-командой.
|
||||
4. Для следующего закрытого файла повторите import; перезапустится только Packmate, БД/предыдущий файл сохранятся.
|
||||
|
||||
EOF не сбрасывает started upstream. Не меняйте активный файл вручную под работающим parser. Трафик может содержать пароли, cookies и флаги; не показывайте в публичных artifacts.
|
||||
|
||||
Import не меняет `local_ip`: он должен совпадать с реальным IP стороны сервиса
|
||||
в данном PCAP, а не адресом из другого демопримера. Если конфиг FILE требует
|
||||
изменения после setup, используйте [процедуру down → edit → configure → up](MACOS_FIRST_RUN-RU.md#6-failures-and-safe-shutdown),
|
||||
затем повторите import и нажмите кнопку разбора FILE.
|
||||
|
||||
<a id="live-on-linux"></a>
|
||||
## LIVE на Linux
|
||||
|
||||
LIVE требует разрешения и точки наблюдения, которая видит пакеты Vulnbox: сам Vulnbox или разрешённый Linux mirror/capture node. Обычный deployment Docker Desktop — только FILE.
|
||||
|
||||
Выберите и прогоните [вариант захвата](traffic-capture-RU.md) до игры. Бесконечный FILE pipe не равен LIVE: timeout незавершённых потоков/periodic cleanup привязаны к LIVE upstream. Ноутбук на том же switch не видит весь трафик автоматически.
|
||||
|
||||
<a id="resources-and-troubleshooting"></a>
|
||||
## Ресурсы и диагностика
|
||||
|
||||
Текущий образ Packmate только amd64; Apple Silicon использует эмуляцию. Следите за CPU, памятью, ростом БД/capture и диском. Очистка LIVE по возрасту — не жёсткая disk quota; у FILE нет периодической LIVE-очистки.
|
||||
|
||||
UI пустой: регистрация сервиса, pattern, IP стороны сервиса, время и известный capture. Направление TCP/UDP и содержимое полезнее статуса работающего контейнера.
|
||||
|
||||
Конфиг подавляет конкретный upstream authentication-failure logger, который иначе печатает введённые пароли. Используйте сгенерированную конфигурацию; не запускайте stock-логирование с приватными credentials.
|
||||
|
||||
[Работа с трафиком](traffic-capture-RU.md) · [Инструкция участника](participant-guide-RU.md) · [Upstream setup](https://gitlab.com/packmate/Packmate/-/blob/938031f1dedfbedabef5b049368ed5b6ba6a900a/docs/SETUP.md)
|
||||
@@ -0,0 +1,194 @@
|
||||
<a id="packmate-live-deploy-from-the-laptop-over-ssh"></a>
|
||||
# Packmate LIVE: запуск с ноутбука по SSH
|
||||
|
||||
[English](packmate-remote.md) | Русский
|
||||
|
||||
Все команды ниже выполняются **на ноутбуке из корня DurkaHelper**. На Vulnbox
|
||||
Python не нужен: программа переносит готовые конфиги и запускает Docker Compose.
|
||||
Это не заменяет [FILE import](traffic-capture-RU.md#file-on-the-laptop) на Mac.
|
||||
|
||||
<a id="requirements"></a>
|
||||
## Что требуется
|
||||
|
||||
- На ноутбуке: Python 3.10+, SSH; Docker нужен только для подготовки образов.
|
||||
Для комплекта требуется Docker CLI/Engine API 1.49+ с явным
|
||||
[выбором платформы](https://docs.docker.com/reference/cli/docker/image/inspect/).
|
||||
- На источнике трафика: native Linux **amd64**, локальный rootful Docker Engine,
|
||||
Compose v2, `sh`, `tar`, `ip`, `ss`, `stat`, `df`, `sha256sum`, `cut`, `awk`.
|
||||
- Работающий доступ по ключу и заранее проверенный SSH host key. Программа не
|
||||
принимает новый host key автоматически. Для ключа с passphrase сначала выполните
|
||||
`ssh-add ~/.ssh/ctf_capture` — парольная фраза не передаётся программе.
|
||||
- Разрешение на **весь выбранный интерфейс**, host networking и NET_RAW.
|
||||
Не используются privileged, NET_ADMIN, Docker socket mounts или установка пакетов.
|
||||
- Минимум 3 GiB доступной RAM и 5 GiB свободного диска перед запуском. Контейнеры
|
||||
ограничены суммарно 2 CPU / 2 GiB RAM. Очистка по возрасту — не жёсткая disk quota.
|
||||
|
||||
Неизменённый upstream Packmate кратко использует широкий TCP/UDP startup filter.
|
||||
Mac на обычном switch не видит автоматически трафик Vulnbox. Выбор интерфейса
|
||||
определяет разрешённый источник трафика; программа не создаёт зеркало и не меняет
|
||||
firewall или маршруты вручную. Docker создаёт только сети своего deployment.
|
||||
|
||||
<a id="1-read-only-doctor-before-configuration"></a>
|
||||
## 1. Read-only doctor — до настройки
|
||||
|
||||
Замените example hostname и путь ключа. Если используется уже одобренный Docker
|
||||
wrapper, передайте его абсолютный путь через `--docker`; shell-команды не допускаются.
|
||||
|
||||
```bash
|
||||
python3 durka.py traffic live doctor \
|
||||
--host example@vulnbox.example --key ~/.ssh/ctf_capture \
|
||||
--ui-port 65000 --db-port 55432
|
||||
```
|
||||
|
||||
Doctor собирает Engine ID, архитектуру, интерфейсы/IP, RAM, диск, доступность
|
||||
Compose/утилит, наличие amd64-образов и занятость двух портов. **Ничего не пишет
|
||||
на Vulnbox, не скачивает и не запускает.** PASS означает пригодность проверенных
|
||||
предпосылок, а не доказанную видимость трафика. WARNING для отсутствующих образов
|
||||
исправляется офлайн-комплектом. BLOCKED означает проблему доступа, платформы,
|
||||
ресурсов или портов; чужие процессы/контейнеры не останавливайте.
|
||||
|
||||
<a id="2-prepare-offline-images-before-the-event"></a>
|
||||
## 2. Подготовить офлайн-образы до соревнования
|
||||
|
||||
При доступном Интернете на ноутбуке и запущенном Docker:
|
||||
|
||||
```bash
|
||||
python3 durka.py traffic live bundle \
|
||||
--output local/packmate-live-images --download --apply
|
||||
```
|
||||
|
||||
Скачиваются **два закреплённых Linux amd64 образа**, даже на ARM64 Mac. Если они
|
||||
уже кешированы, уберите `--download`. Каталог должен быть новым. В нём находятся
|
||||
`images.tar` и автоматический manifest; вручную SHA заполнять не нужно. Сохраните
|
||||
оба файла вместе. Обычный ARM64 PostgreSQL из Mac-стека не заменяет amd64 образ.
|
||||
Проверка и экспорт явно выбирают Linux amd64, даже если в кеше одновременно
|
||||
есть ARM64-вариант; работающий Mac-стек не изменяется.
|
||||
Команда изменяет только локальные файлы и image cache, не запускает контейнеры.
|
||||
Не коммитьте архивы образов; перед публичным распространением отдельно проверьте upstream licenses.
|
||||
|
||||
<a id="3-create-one-private-configuration"></a>
|
||||
## 3. Создать один приватный конфиг
|
||||
|
||||
Примерные значения заменяются результатом doctor и правилами площадки:
|
||||
|
||||
```bash
|
||||
python3 durka.py traffic live init \
|
||||
--host example@vulnbox.example --key ~/.ssh/ctf_capture \
|
||||
--remote-dir /home/example/durka-packmate-live \
|
||||
--interface eth0 --service-ip 192.0.2.10 --bind 192.0.2.20 \
|
||||
--ui-port 65000 --db-port 55432
|
||||
```
|
||||
|
||||
`--service-ip` — IP стороны защищаемого сервиса **в захватываемом трафике**;
|
||||
`--bind` — назначенный Linux-хосту IP для UI. Они могут различаться.
|
||||
Interface index/MAC и Engine ID подставляются автоматически. Создаётся только
|
||||
локальный `local/packmate-remote.json` с новыми паролями; источник не меняется.
|
||||
Не публикуйте этот файл и не показывайте его публично. Повторный init не перезаписывает
|
||||
конфиг. Другой deployment: отдельные `--config` и `--remote-dir`.
|
||||
|
||||
<a id="where-the-deployment-configuration-lives"></a>
|
||||
## Где находится deployment-конфиг
|
||||
|
||||
На ноутбуке: `local/packmate-remote.json` (либо файл из `--config`).
|
||||
Он отдельный от farm/FILE-конфига. Пароли внутри: не показывайте файл публично
|
||||
и не коммитьте его. В секции `profile` находятся:
|
||||
|
||||
| Поле | Назначение | Значение по умолчанию при init |
|
||||
|---|---|---|
|
||||
| `interface` | Разрешённый Linux-интерфейс захвата | Выбирается через `--interface` |
|
||||
| `local_ip` | IP стороны сервиса в пакетах; определяет направление | `--service-ip` |
|
||||
| `bind_address`, `ui_port` | Linux-адрес и порт веб-интерфейса | `--bind`, порт 65000 |
|
||||
| `db_port` | PostgreSQL, только IPv4 loopback | 55432 |
|
||||
| `tcp_timeout_seconds`, `udp_timeout_seconds` | Таймауты потоков | 30 / 10 секунд |
|
||||
| `timeout_check_seconds` | Период проверки таймаутов | 5 секунд |
|
||||
| `retention_minutes`, `cleanup_interval_minutes` | Возраст удаления и период очистки | 60 / 1 минут |
|
||||
|
||||
Порты приложений и поисковые patterns задаются отдельно [в UI](packmate-RU.md#ui-services-and-patterns).
|
||||
На Linux `workspace/application.properties` и `runtime-compose.json` генерируются
|
||||
из этого конфига автоматически. Вручную на источнике их не редактируйте.
|
||||
|
||||
Адреса/порты/интерфейс выбирайте при `init`; таймауты и retention в `profile`
|
||||
можно настроить **до первого up**, сохранив права файла 0600. Engine ID,
|
||||
index/MAC интерфейса, project и images — автоматические проверки, не параметры
|
||||
для обхода ошибки doctor. Credentials не меняйте отдельно от существующей БД.
|
||||
|
||||
После deployment конфиг и runtime проверяются на точное соответствие.
|
||||
Изменение локального JSON **не обновляет** работающий Packmate: текущий launcher
|
||||
не поддерживает in-place reconfiguration. Сохраните исходный конфиг для безопасного
|
||||
`down`; другое deployment создавайте через отдельные `--config` и новый
|
||||
`--remote-dir`, проверив свободные порты и разрешения. Старые данные сохраняются,
|
||||
но история БД автоматически в новый workspace не переносится.
|
||||
|
||||
<a id="4-check-and-start"></a>
|
||||
## 4. Проверить и запустить
|
||||
|
||||
```bash
|
||||
python3 durka.py traffic live doctor --bundle local/packmate-live-images
|
||||
python3 durka.py traffic live up --bundle local/packmate-live-images \
|
||||
--apply --host-network-approved --interface-scope-approved
|
||||
```
|
||||
|
||||
Вторая команда **изменяет источник**: при необходимости загружает переданные
|
||||
образы, создаёт только новый приватный workspace и два своих контейнера.
|
||||
Интернет на Vulnbox не используется: нет pull/build/install, запуск всегда
|
||||
`--no-build --pull never`. Если закреплённые образы уже есть на источнике,
|
||||
`--bundle` можно убрать. Непроверенные/изменившиеся образы не принимаются.
|
||||
|
||||
Ожидается `status: PASS`, `authenticated_capture_started: true`, адрес UI.
|
||||
Авторизованная готовность проверяется через временный SSH tunnel; SSH forwarding
|
||||
должен быть разрешён. **Это ещё не подтверждение корректности трафика.**
|
||||
Проверка интерфейса/Engine повторяется; старый workspace не перезаписывается.
|
||||
|
||||
<a id="5-login-and-inspect-a-transaction"></a>
|
||||
## 5. Войти и проверить транзакцию
|
||||
|
||||
На Mac скопировать пароль, не выводя его на экран:
|
||||
|
||||
```bash
|
||||
python3 durka.py traffic live password
|
||||
```
|
||||
|
||||
Логин `operator`, пароль вставьте из буфера в UI по адресу из `up`. Команда
|
||||
изменяет только буфер Mac. На других ОС используйте приватное поле
|
||||
`credentials.password` без трансляции экрана. Зарегистрируйте сервисы/шаблоны
|
||||
в UI [по пошаговой инструкции](packmate-RU.md#ui-services-and-patterns), найдите известные **request и response**, проверьте направление, время,
|
||||
повторный запрос и доступность приложения. Статус контейнера этого не заменяет.
|
||||
|
||||
<a id="6-stop-and-start-again"></a>
|
||||
## 6. Остановка и повторный старт
|
||||
|
||||
```bash
|
||||
python3 durka.py traffic live status
|
||||
python3 durka.py traffic live down --apply
|
||||
python3 durka.py traffic live up --bundle local/packmate-live-images \
|
||||
--apply --host-network-approved --interface-scope-approved
|
||||
```
|
||||
|
||||
`down` останавливает только проект этого конфига и сохраняет PostgreSQL/настройки.
|
||||
Не использует `down -v`, `prune` или удаление каталогов. Проверки ownership не дают
|
||||
ему остановить чужой проект. Старый запуск другим helper не присваивается автоматически.
|
||||
|
||||
<a id="troubleshooting"></a>
|
||||
## Если не получилось
|
||||
|
||||
- SSH failed: сначала проверьте обычный SSH, fingerprint и `ssh-add`; ключ не
|
||||
копируйте на Vulnbox. Программа работает без интерактивных password prompts.
|
||||
- Порты заняты: выберите свободные при init или самостоятельно остановите
|
||||
**только известный свой** старый deployment. Firewall автоматически не меняется.
|
||||
- Missing/wrong-platform images: подготовьте комплект именно Linux amd64.
|
||||
- Interface/Engine changed: заново проверьте источник и разрешённый scope;
|
||||
не обходите проверку редактированием идентификаторов наугад.
|
||||
- Readiness timeout: свои контейнеры могли уже запуститься. Выполните `status`,
|
||||
затем при необходимости `down --apply`; данные сохраняются.
|
||||
- Неполный перенос: каталог сохраняется для диагностики, автоматически не
|
||||
удаляется и не перезаписывается. Новый workspace допустим только после проверки
|
||||
частичных ресурсов. Нет автоматической переустановки.
|
||||
- Нет Docker/Compose или разрешения: LIVE этим путём BLOCKED. Используйте FILE
|
||||
только при наличии разрешённого закрытого PCAP; это не continuous capture.
|
||||
|
||||
Python-free target обеспечивается отсутствием вызовов Python на источнике.
|
||||
Успешный Linux deployment не подтверждает Docker Desktop LIVE, реальную
|
||||
сеть площадки, нагрузку или disk quota. Проверка известной транзакции остаётся
|
||||
ручным обязательным шагом.
|
||||
|
||||
[Выбор LIVE/FILE](traffic-capture-RU.md) · [Packmate](packmate-RU.md)
|
||||
@@ -0,0 +1,182 @@
|
||||
# Packmate LIVE: deploy from the laptop over SSH
|
||||
|
||||
English | [Русский](packmate-remote-RU.md)
|
||||
|
||||
Run every command below **on the laptop, from the DurkaHelper repository root**.
|
||||
Python is not required on the Vulnbox: the program transfers rendered configuration
|
||||
and runs Docker Compose. This does not replace [FILE import](traffic-capture.md#file-on-the-laptop) on Mac.
|
||||
|
||||
## Requirements
|
||||
|
||||
- Laptop: Python 3.10+ and SSH; Docker is needed only to prepare image bundles.
|
||||
Bundle preparation requires Docker CLI/Engine API 1.49+ for explicit
|
||||
[platform selection](https://docs.docker.com/reference/cli/docker/image/inspect/).
|
||||
- Traffic source: native Linux **amd64**, local rootful Docker Engine, Compose v2,
|
||||
`sh`, `tar`, `ip`, `ss`, `stat`, `df`, `sha256sum`, `cut`, `awk`.
|
||||
- Working key authentication and a verified SSH host key. No automatic host-key
|
||||
acceptance. For a passphrase-protected identity, first run `ssh-add ~/.ssh/ctf_capture`;
|
||||
the program does not receive the passphrase.
|
||||
- Approval for the **entire selected interface**, host networking and NET_RAW.
|
||||
No privileged containers, NET_ADMIN, Docker socket mounts or package installation.
|
||||
- At least 3 GiB available RAM and 5 GiB free disk before startup. Combined limits
|
||||
are 2 CPU / 2 GiB RAM. Age cleanup is not a hard storage quota.
|
||||
|
||||
Unmodified upstream Packmate briefly uses a broad TCP/UDP startup filter.
|
||||
A Mac on an ordinary switch does not automatically see Vulnbox traffic. Placement
|
||||
defines permitted traffic visibility; the program does not create mirroring or
|
||||
manually change firewall/routes. Docker creates only this deployment's networks.
|
||||
|
||||
## 1. Read-only doctor, before configuration
|
||||
|
||||
Replace the example hostname and identity path. For an already approved Docker
|
||||
wrapper, pass its absolute path using `--docker`; shell commands are not accepted.
|
||||
|
||||
```bash
|
||||
python3 durka.py traffic live doctor \
|
||||
--host example@vulnbox.example --key ~/.ssh/ctf_capture \
|
||||
--ui-port 65000 --db-port 55432
|
||||
```
|
||||
|
||||
Doctor reports Engine identity, architecture, interfaces/IPs, RAM/disk, Compose
|
||||
and utility availability, cached amd64 images and the two requested ports.
|
||||
**No target writes, downloads or startup.** PASS covers checked prerequisites, not
|
||||
traffic visibility. WARNING for missing images requires an offline bundle. BLOCKED
|
||||
means access/platform/resource/port issues; do not stop unrelated workloads.
|
||||
|
||||
## 2. Prepare offline images before the event
|
||||
|
||||
With laptop Internet access and Docker running:
|
||||
|
||||
```bash
|
||||
python3 durka.py traffic live bundle \
|
||||
--output local/packmate-live-images --download --apply
|
||||
```
|
||||
|
||||
This downloads **two pinned Linux amd64 images**, including on an ARM64 Mac. Omit
|
||||
`--download` if both are cached. The output directory must be new. Keep `images.tar`
|
||||
and the automatic manifest together; no manual SHA forms are required. An ARM64
|
||||
PostgreSQL image from the Mac stack does not substitute for the amd64 image.
|
||||
Inspection and archive export explicitly select Linux amd64, even when the
|
||||
image cache also contains ARM64 variants; the running Mac stack is not changed.
|
||||
Only local files and the image cache change; no containers start.
|
||||
Do not commit image archives; review upstream licenses separately before public redistribution.
|
||||
|
||||
## 3. Create one private configuration
|
||||
|
||||
Replace example values using doctor results and event rules:
|
||||
|
||||
```bash
|
||||
python3 durka.py traffic live init \
|
||||
--host example@vulnbox.example --key ~/.ssh/ctf_capture \
|
||||
--remote-dir /home/example/durka-packmate-live \
|
||||
--interface eth0 --service-ip 192.0.2.10 --bind 192.0.2.20 \
|
||||
--ui-port 65000 --db-port 55432
|
||||
```
|
||||
|
||||
`--service-ip` is the protected service-side IP **in the captured traffic**;
|
||||
`--bind` is the Linux host's assigned UI IP. They may differ. Interface index/MAC
|
||||
and Engine identity are filled automatically. Only the local
|
||||
`local/packmate-remote.json` is created, with generated passwords; the source is
|
||||
unchanged. Never publish this private file. Init does not overwrite.
|
||||
Use separate `--config` and `--remote-dir` for another deployment.
|
||||
|
||||
## Where the deployment configuration lives
|
||||
|
||||
On the laptop: `local/packmate-remote.json`, or the file selected by `--config`.
|
||||
This is separate from the farm/FILE configuration. It contains passwords: keep
|
||||
it private and out of Git. The `profile` section includes:
|
||||
|
||||
| Field | Purpose | Default at init |
|
||||
|---|---|---|
|
||||
| `interface` | Approved Linux capture interface | Selected through `--interface` |
|
||||
| `local_ip` | Service-side IP in packets; determines direction | `--service-ip` |
|
||||
| `bind_address`, `ui_port` | Linux web-interface address and port | `--bind`, port 65000 |
|
||||
| `db_port` | PostgreSQL on IPv4 loopback only | 55432 |
|
||||
| `tcp_timeout_seconds`, `udp_timeout_seconds` | Stream timeouts | 30 / 10 seconds |
|
||||
| `timeout_check_seconds` | Timeout-check interval | 5 seconds |
|
||||
| `retention_minutes`, `cleanup_interval_minutes` | Deletion age and cleanup interval | 60 / 1 minutes |
|
||||
|
||||
Application ports and search patterns are configured separately [in the UI](packmate.md#ui-services-and-patterns).
|
||||
Linux `workspace/application.properties` and `runtime-compose.json` are generated
|
||||
automatically from this configuration. Do not edit those files manually.
|
||||
|
||||
Choose addresses/ports/interface during `init`; tune `profile` timeouts and
|
||||
retention **before the first up**, retaining mode 0600. Engine ID, interface
|
||||
index/MAC, project and images are automatic checks, not settings to bypass a
|
||||
doctor error. Do not rotate credentials independently of an existing database.
|
||||
|
||||
After deployment, configuration and runtime must match exactly. Editing local
|
||||
JSON **does not update** running Packmate: this launcher has no in-place
|
||||
reconfiguration. Retain the original config for safe `down`; create another
|
||||
deployment using a separate `--config` and new `--remote-dir`, checking free
|
||||
ports and approvals. Old data is retained, but database history is not
|
||||
automatically migrated into the new workspace.
|
||||
|
||||
## 4. Check and start
|
||||
|
||||
```bash
|
||||
python3 durka.py traffic live doctor --bundle local/packmate-live-images
|
||||
python3 durka.py traffic live up --bundle local/packmate-live-images \
|
||||
--apply --host-network-approved --interface-scope-approved
|
||||
```
|
||||
|
||||
The second command **changes the source**: loads transferred images if needed,
|
||||
creates only a new private workspace and two owned containers. No target Internet
|
||||
is used: no pull/build/install; startup always uses `--no-build --pull never`.
|
||||
Omit `--bundle` if the pinned images are already cached on the source. Changed or
|
||||
unverified images are refused.
|
||||
|
||||
Expect `status: PASS`, `authenticated_capture_started: true` and the UI URL.
|
||||
Authenticated readiness is checked through a temporary SSH tunnel, requiring
|
||||
permitted SSH forwarding. **Traffic correctness is still unverified.** Engine and
|
||||
interface identity are rechecked; an old workspace is not overwritten.
|
||||
|
||||
## 5. Login and inspect a transaction
|
||||
|
||||
On Mac, copy the password without printing it:
|
||||
|
||||
```bash
|
||||
python3 durka.py traffic live password
|
||||
```
|
||||
|
||||
Username is `operator`; paste the password into the UI at the URL returned by `up`.
|
||||
Only the Mac clipboard changes. On other operating systems use the private
|
||||
`credentials.password` field without screen broadcasting. Register services/patterns
|
||||
in the UI [using the step-by-step guide](packmate.md#ui-services-and-patterns), find known **request and response**, check direction/time/repetition and
|
||||
application health. A running container is not sufficient evidence.
|
||||
|
||||
## 6. Stop and start again
|
||||
|
||||
```bash
|
||||
python3 durka.py traffic live status
|
||||
python3 durka.py traffic live down --apply
|
||||
python3 durka.py traffic live up --bundle local/packmate-live-images \
|
||||
--apply --host-network-approved --interface-scope-approved
|
||||
```
|
||||
|
||||
Down stops only this configuration's project and retains PostgreSQL/settings.
|
||||
No `down -v`, prune or directory deletion. Ownership checks prevent foreign-project
|
||||
shutdown. Deployments created by older helpers are not automatically adopted.
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
- SSH failed: verify ordinary SSH, fingerprint and `ssh-add`. Do not copy the key
|
||||
to the Vulnbox. The program does not use interactive password prompts.
|
||||
- Ports occupied: choose free ports at init or manually stop **only a known owned**
|
||||
older deployment. Firewall is not automatically changed.
|
||||
- Missing/wrong-platform images: prepare the Linux amd64 bundle.
|
||||
- Engine/interface changed: review the source and permitted scope; do not guess
|
||||
replacement identifiers to bypass checks.
|
||||
- Readiness timeout: owned containers may already be running. Use `status`, then
|
||||
`down --apply` if necessary; data remains.
|
||||
- Incomplete transfer: the directory remains for inspection, with no automatic
|
||||
deletion/overwrite. Inspect partial resources before selecting another workspace.
|
||||
No automatic reinstall.
|
||||
- No Docker/Compose or approval: this LIVE path is BLOCKED. FILE requires an
|
||||
authorized closed PCAP and does not provide continuous capture.
|
||||
|
||||
The Python-free target path makes no target Python calls. Linux success does not
|
||||
validate Docker Desktop LIVE, the event network, sustained load or a hard disk
|
||||
quota. A known transaction remains a mandatory manual acceptance step.
|
||||
|
||||
[LIVE/FILE selection](traffic-capture.md) · [Packmate](packmate.md)
|
||||
@@ -0,0 +1,69 @@
|
||||
# Packmate: inspect traffic
|
||||
|
||||
English | [Русский](packmate-RU.md)
|
||||
|
||||
Packmate displays requests/responses and searches stream contents. It helps defenders recognize attacks and check whether a patch changed the relevant behavior. DurkaHelper supplies its configuration and launch/import tools; upstream source remains unchanged.
|
||||
|
||||
## UI services and patterns
|
||||
|
||||
The web-interface port is chosen during deployment (`--ui-port` for SSH LIVE).
|
||||
It is **not the monitored application's port**. The capture interface and
|
||||
service-side IP belong in the private deployment configuration, not the service
|
||||
creation form. The gear at the top right opens additional UI settings.
|
||||
|
||||
1. Click **+** in the top navigation bar and enter the application's **Name**
|
||||
and **Port**. Create an entry for each port. Unregistered services do not
|
||||
have their streams saved. Ordinary HTTP does not need TLS decryption.
|
||||
2. Select the service in the top bar. LIVE streams appear automatically; the
|
||||
analysis-start button is only available in FILE mode.
|
||||
3. For highlighting, open **Patterns → +**. Choose recognizable synthetic text,
|
||||
such as `DEMO-`, substring search, both directions and **Highlight**, not
|
||||
**Ignore**. Select a particular service if needed.
|
||||
4. Open a new stream and verify its request and response. New patterns apply
|
||||
to subsequent streams; **Lookback** applies them to saved streams.
|
||||
**Pause** pauses your browser's display, not packet capture.
|
||||
|
||||
These actions change Packmate's database settings, not the application or
|
||||
network. For an empty UI, first check the registered port and clear any pattern
|
||||
filter; then check the service-side IP and availability of authorized traffic.
|
||||
The controls were reviewed against the [pinned upstream UI guide](https://gitlab.com/packmate/Packmate/-/blob/938031f1dedfbedabef5b049368ed5b6ba6a900a/docs/USAGE_EN.md).
|
||||
|
||||
## FILE on the laptop
|
||||
|
||||
```bash
|
||||
python3 durka.py up
|
||||
python3 durka.py traffic import /path/to/closed-capture.pcap
|
||||
python3 durka.py status
|
||||
```
|
||||
|
||||
Open the printed Packmate URL. Use `credentials.packmate_user / packmate_password` from the admin's private config.
|
||||
|
||||
1. [Register the service and a search pattern in the UI](#ui-services-and-patterns).
|
||||
2. Check `profile.packmate.local_ip`: it is the service-side IP **in the capture**, not the laptop's address.
|
||||
3. Press the yellow downward-arrow FILE-processing button in the sidebar once
|
||||
and find a known request and response in the correct direction. Do not look
|
||||
for a literal "Start" label or an upload form: the import command already supplied the file.
|
||||
4. For a new closed file, run the import command again; it restarts only Packmate and preserves its database/previous file.
|
||||
|
||||
EOF does not reset upstream's started state. Do not replace the active file manually underneath a running parser. Imported traffic can contain passwords, cookies and flags; keep it out of public artifacts.
|
||||
|
||||
Import does not change `local_ip`: it must match the actual service-side IP in
|
||||
this PCAP, not an address copied from another demo. To change a FILE config after
|
||||
setup, follow [down → edit → configure → up](MACOS_FIRST_RUN.md#6-failures-and-safe-shutdown),
|
||||
then repeat the import and press the FILE-processing button.
|
||||
|
||||
## LIVE on Linux
|
||||
|
||||
LIVE needs permission and an observation point that actually sees the Vulnbox's packets: the Vulnbox itself or an approved Linux mirror/capture node. Docker Desktop's normal deployment is FILE-only.
|
||||
|
||||
Choose and rehearse a [capture path](traffic-capture.md) before the game. An endless FILE pipe is not LIVE: incomplete-flow timeout/periodic cleanup are tied to upstream LIVE mode. A laptop on the same switch does not see all traffic automatically.
|
||||
|
||||
## Resources and troubleshooting
|
||||
|
||||
The current Packmate image is amd64-only; Apple Silicon uses emulation. Watch CPU, memory, database/capture growth and free disk. LIVE age cleanup is not a hard disk quota; FILE has no periodic LIVE cleanup.
|
||||
|
||||
Empty UI: verify service registration, pattern, service-side IP, time range and a known capture. TCP/UDP direction and payload are better checks than a running container.
|
||||
|
||||
The maintained configuration suppresses upstream's specific authentication-failure logger that otherwise prints attempted passwords. Use the generated config; do not run stock upstream logging with private credentials.
|
||||
|
||||
[Traffic workflow](traffic-capture.md) · [Participant guide](participant-guide.md) · [Upstream setup](https://gitlab.com/packmate/Packmate/-/blob/938031f1dedfbedabef5b049368ed5b6ba6a900a/docs/SETUP.md)
|
||||
@@ -0,0 +1,47 @@
|
||||
<a id="participant-guide"></a>
|
||||
# Инструкция участника
|
||||
|
||||
[English](participant-guide.md) | Русский
|
||||
|
||||
Ферму устанавливать и конфиг админа заполнять не нужно. Получите у админа LAN URL/логины фермы и Packmate; авторам скриптов также нужны адрес/ключ координатора Neo.
|
||||
|
||||
<a id="defend-a-service"></a>
|
||||
## Защитить сервис
|
||||
|
||||
1. Получите разрешённую локальную копию исходников сервиса Vulnbox.
|
||||
2. Из каталога DurkaHelper запустите скан:
|
||||
|
||||
```bash
|
||||
python3 durka.py scan /path/to/service --patches
|
||||
```
|
||||
|
||||
3. Откройте связанную [инструкцию исправления](vulnerabilities/README-RU.md), проверьте применимость сигнала и изучите нужные запрос/ответ в Packmate.
|
||||
4. Сохраните оригинальные файлы/native database backup, нужные сервису. Примените один небольшой фикс обычным способом доступа/деплоя команды на Vulnbox.
|
||||
5. Проверьте нормальное использование и checker соревнования, включая restart/сохранность данных, где нужно. Повторите скан исходников.
|
||||
|
||||
Сканер делает offline source review: удалённые Vulnbox не прощупывает, их код не исполняет. Exit 1 — находки; exit 2 — некорректный/неполный вход, который нужно проверить. Чистый отчёт не заменяет доступность и ручную проверку авторизации/бизнес-логики.
|
||||
|
||||
<a id="inspect-traffic"></a>
|
||||
## Разобрать трафик
|
||||
|
||||
Откройте LAN URL Packmate и войдите. Выберите свой сервис, ищите подозрительное значение/путь и изучайте запрос вместе с ответом. Для FILE попросите админа зарегистрировать сервис/шаблон до начала обработки.
|
||||
|
||||
Если трафика нет, проверьте timestamps потоков, IP стороны сервиса и порт/шаблон и то, импортировал ли админ закрытый файл или выбрал разрешённый LIVE-источник. Не предполагается наличие фильтра времени в UI. Один Ethernet на Mac не захватывает всю LAN автоматически. [Работа с трафиком](traffic-capture-RU.md).
|
||||
|
||||
<a id="write-and-distribute-scripts"></a>
|
||||
## Написать и распределить скрипты
|
||||
|
||||
Neo — исполнитель/распределитель скриптов. Ферма собирает полученные флаги. Начните с локального теста на разрешённой цели и явно определите зависимости.
|
||||
|
||||
Скрипт получает IP цели первым аргументом; флаги печатает в stdout без буферизации. Диагностику отделяйте от флагов. Shebang должен указывать интерпретатор, доступный у каждого worker. Встроенный light-worker содержит shell, а не Python/Sage и произвольные пакеты.
|
||||
|
||||
[Настройка Neo и первое задание](neo-RU.md) описывает совместимый клиент. Сначала зарегистрируйте доверенный скрипт выключенным, затем запросите единичный прогон до периодического исполнения. `single` Neo запускает один раз на **всех настроенных командах**, поэтому сверьте scope/список с админом.
|
||||
|
||||
Следите за исполнением и флагами/статусом в ферме. Ферма/Neo не являются автоматическим установщиком защитных патчей.
|
||||
|
||||
<a id="if-access-fails"></a>
|
||||
## Если нет доступа
|
||||
|
||||
Используйте LAN-адрес админа, а не `localhost`. Если ошибка только у вас — URL/порт, credentials и версия Neo. Если у всех — админ проверяет `python3 durka.py status` и LAN bind.
|
||||
|
||||
Не показывайте приватные исходники, credentials, флаги и трафик в общей трансляции. [Шпаргалка защитника](defense-cheatsheet-RU.md) · [Связи инструментов](team-setup-RU.md).
|
||||
@@ -0,0 +1,42 @@
|
||||
# Participant guide
|
||||
|
||||
English | [Русский](participant-guide-RU.md)
|
||||
|
||||
You do not need to install the farm or fill the administrator's config. Ask the admin for the farm/Packmate LAN URLs and logins; script writers also need the Neo coordinator address/key.
|
||||
|
||||
## Defend a service
|
||||
|
||||
1. Obtain an authorized local source copy of your Vulnbox service.
|
||||
2. From the DurkaHelper checkout, scan it:
|
||||
|
||||
```bash
|
||||
python3 durka.py scan /path/to/service --patches
|
||||
```
|
||||
|
||||
3. Open the linked [fix recipe](vulnerabilities/README.md), check whether the signal applies and inspect the relevant request/response in Packmate.
|
||||
4. Save the original files/native database backup needed by that service. Apply one small fix through the team's normal Vulnbox access/deployment procedure.
|
||||
5. Check legitimate use and the competition checker, including restart/data persistence where relevant. Repeat the source scan.
|
||||
|
||||
The scanner is offline source review: it neither probes remote Vulnboxes nor executes their code. Exit 1 means findings; exit 2 means invalid/partial input needing attention. A clean report does not replace an availability check or manual authorization/business-logic review.
|
||||
|
||||
## Inspect traffic
|
||||
|
||||
Open Packmate's LAN URL and log in. Select your service, search a suspicious value/path and examine both request and response. Ask the admin to register the service/pattern before FILE processing.
|
||||
|
||||
If traffic is missing, check stream timestamps, service-side IP and port/pattern and whether the admin has imported a closed file or chosen a permitted LIVE source. Do not assume a time-filter UI exists. A Mac connected to Ethernet does not capture the whole LAN automatically. [Traffic guide](traffic-capture.md).
|
||||
|
||||
## Write and distribute scripts
|
||||
|
||||
Neo is the script runner/distributor. The farm collects the resulting flags. Start with a local test against an allowed target and make dependencies explicit.
|
||||
|
||||
The script receives the target IP as its first command-line argument; print flags to stdout without buffering. Keep diagnostics distinct from flags. Include a shebang for the interpreter available on each worker. The bundled light worker has a shell, not Python/Sage and arbitrary packages.
|
||||
|
||||
Follow [Neo setup and first task](neo.md) to configure a compatible client. Register a trusted script disabled first, then request a single run before enabling recurring execution. Neo's `single` runs once on **all configured teams**, so check the team map/scope with the admin.
|
||||
|
||||
Watch execution output and the flags/status in the farm. Do not use the farm/Neo as an automatic defensive patch installer.
|
||||
|
||||
## If access fails
|
||||
|
||||
Use the admin's LAN address, not `localhost`. If only your device fails, compare URL/port, credentials and Neo version. If everyone fails, ask the admin to check `python3 durka.py status` and the LAN bind.
|
||||
|
||||
Keep private source, credentials, flags and traffic out of shared screen broadcasts. [Defender cheat sheet](defense-cheatsheet.md) · [Tool connections](team-setup.md).
|
||||
@@ -0,0 +1,89 @@
|
||||
<a id="patch-verification-deployment-and-rollback"></a>
|
||||
# Проверка патчей, deployment и rollback
|
||||
|
||||
[English](patch-validation.md) | Русский
|
||||
|
||||
[Шпаргалка защитника](defense-cheatsheet-RU.md) · [Каталог](vulnerabilities/README-RU.md)
|
||||
|
||||
За deployment каждого сервиса отвечает один человек. Все начальные проверки выполняются на изолированной локальной копии разрешённого сервиса. Адаптируйте production-команды только после подтверждения его фактического контракта запуска и данных. Обычный ручной маршрут: сохранить оригиналы, применить небольшой патч, прогнать regression/normal-user/checker проверки и повторить скан. Карточки и ручное переписывание hashes не нужны; раздел 4 — необязательная расширенная проверка evidence, не условие ручного исправления.
|
||||
|
||||
<a id="1-preserve-the-before-state"></a>
|
||||
## 1. Сохраните исходное состояние
|
||||
|
||||
Запишите ревизию кода и локальный diff, неизменяемый image ID, источники конфигурации, текущие данные и способ rollback. Это разные активы: откат кода не должен восстанавливать старую БД поверх записей новых раундов.
|
||||
|
||||
Свидетельство: `REVIEWED`; эффект `READ-ONLY`; рабочий каталог — checkout сервиса с Git. Ожидается: фактическая ревизия и существующие изменения. Вывод может содержать приватные пути; не транслируйте его. Rollback: не нужен.
|
||||
|
||||
```bash
|
||||
git status --short
|
||||
git rev-parse HEAD
|
||||
git diff --check
|
||||
```
|
||||
|
||||
Без Git приватно скопируйте только изменяемые файлы подходящими backup tools; проверка checksum может быть автоматической. Никогда не используйте общий git add, reset --hard или git clean как универсальный рабочий процесс. [Файловый backup](local-tools-RU.md#backup-and-staging-restore) ограничен, но базы данных требуют нативных консистентных dumps или проверенной процедуры копирования в остановленном состоянии.
|
||||
|
||||
<a id="2-required-behavioral-matrix"></a>
|
||||
## 2. Обязательная матрица поведения
|
||||
|
||||
| Проверка | Успешный результат |
|
||||
|---|---|
|
||||
| Регрессия дефекта | Один и тот же тест безопасного поведения падает до и проходит после |
|
||||
| Обычный пользователь | Работают login, create/read/update и ожидаемый sharing |
|
||||
| Авторизация | Владелец проходит; другой пользователь/tenant и анонимный caller получают отказ без side effects |
|
||||
| Старые данные | Записи до патча сохраняют формат и доступность |
|
||||
| Persistence | Новые записи переживают согласованный изолированный restart |
|
||||
| Альтернативные пути | Lists, exports, files, jobs и затронутые routes соблюдают то же правило |
|
||||
| Границы ввода | Empty/wrong-type/Unicode/maximum values соответствуют контракту |
|
||||
| Отказ зависимости | Ограниченный, очищенный отказ без авторизации по умолчанию |
|
||||
| Checker | Сохраняются настоящая семантика турнира и SLA |
|
||||
|
||||
Проверяйте отсутствие запрещённых эффектов, а не только status codes: denied reads не содержат чужого body, denied writes оставляют rows неизменными, blocked URLs никогда не вызывают HTTP client. [PY-SQL](vulnerabilities/python-RU.md#py-sql) содержит небольшой пример приватной заметки; проверяйте интеграцию route/session вместе с helper.
|
||||
|
||||
<a id="3-match-the-deployment-mechanism"></a>
|
||||
## 3. Учитывайте механизм deployment
|
||||
|
||||
| Механизм | Необходимое действие / ловушка |
|
||||
|---|---|
|
||||
| Source bind mount | Обновляйте только проверенные файлы; restart нужен только если его требует процесс |
|
||||
| Код скопирован в image | Соберите новый закреплённый image и пересоздайте собственный сервис; один restart не пересобирает image |
|
||||
| Native binary | Проверьте architecture/libraries/permissions и совместимость данных |
|
||||
| API и workers | Согласованно обновите зависимые процессы; старые workers могут сохранить старое поведение |
|
||||
|
||||
Изучите entrypoints на предмет destructive initialization/migrations и найдите persistent data. Не перенастраивайте игровые сети, не удаляйте volumes и не пересобирайте посторонние компоненты ради source patch.
|
||||
|
||||
До production-одобрения отрепетируйте точную rollback-команду на копии. Она должна восстанавливать code/image с сохранением текущих данных. Держите старый image локально; изменяемый тег latest не является целью rollback.
|
||||
|
||||
<a id="4-bound-evidence-to-this-patch"></a>
|
||||
## 4. Привяжите свидетельства к этому патчу
|
||||
|
||||
Соберите before/after snapshots и scans с одним предполагаемым scope, затем health и фактические regression-test records. Результат из другого прогона не подтверждает статус этого патча.
|
||||
|
||||
[Schema validation-record](../schemas/validation-record.v1.schema.json) использует lowercase statuses. Attributes каждой записи должны содержать точный SHA-256 входов before_snapshot, after_snapshot, before_scanner, after_scanner и health под соответствующими ключами *_sha256, а также один общий run_id. Время записи должно быть позже зависимых evidence.
|
||||
|
||||
Если deployment audit обязателен, включите его audit/model/policy hashes в ту же запись. Аудит пересчитывается по model/policy; его source hash должен соответствовать точной runtime configuration, зафиксированной в after-snapshot. Он проверяет заявленную конфигурацию, а не фактическое состояние работающего daemon.
|
||||
|
||||
Свидетельство: `REVIEWED`; эффект `READ-ONLY`; рабочий каталог — корень. Требования: подлинные приватные evidence по примерным путям, актуальные hashes/timestamps и совпадающий scope. Ожидается: 0/pass, 1/regression или 2/incomplete. Никогда не придумывайте pass records только ради выполнения условия приёмки. Rollback: не нужен.
|
||||
|
||||
```bash
|
||||
python3 scripts/defense_ops.py patch-check \
|
||||
--before ../private-results/before.json --after ../private-results/after.json \
|
||||
--before-scanner ../private-results/before-scan.json \
|
||||
--after-scanner ../private-results/after-scan.json \
|
||||
--health-result ../private-results/health.json \
|
||||
--validation-record ../private-results/regression.json \
|
||||
--deployment-audit ../private-results/deployment-audit.json \
|
||||
--deployment-model ../private-deployment/run-01/runtime-model.json \
|
||||
--deployment-policy ../private-deployment/run-01/runtime-policy.json \
|
||||
--require-deployment-audit
|
||||
```
|
||||
|
||||
Для изменений только исходников без deployment audit явно уберите все четыре deployment arguments. Обязательные health/scanner/validation evidence всё равно нужны. Отсутствующие, устаревшие, partial, not-run, несовпадающие или несопоставимые свидетельства не могут дать clean pass.
|
||||
|
||||
Для ожидаемого drift требуется явно проверенная [approved-drift record](../schemas/approved-drift.v1.schema.json), привязанная к обоим snapshot hashes и точным классифицированным изменениям; передайте её через --approved-drift. Общее wildcard-разрешение не поддерживается.
|
||||
|
||||
<a id="5-apply-observe-revert-if-necessary"></a>
|
||||
## 5. Примените, наблюдайте, при необходимости откатите
|
||||
|
||||
После явного разрешения используйте только отрепетированный путь deployment собственного сервиса. Сразу повторите health, фактические операции пользователей/checker и чтение старых данных, затем наблюдайте полный релевантный интервал раунда. При сбое сохраните очищенную incident timeline.
|
||||
|
||||
Сначала откатите code/image по записанному плану. Восстановление данных — отдельное решение с серьёзными последствиями: старый dump может стереть данные нового раунда. Не меняйте попутно ключи, schemas или runtime.
|
||||
@@ -0,0 +1,83 @@
|
||||
# Patch verification, deployment and rollback
|
||||
|
||||
English | [Русский](patch-validation-RU.md)
|
||||
|
||||
[Defender quick sheet](defense-cheatsheet.md) · [Catalog](vulnerabilities/README.md)
|
||||
|
||||
One person owns deployment for each service. All initial checks use an isolated local copy of an authorized service. Adapt production commands only after confirming its actual startup/data contract. For the ordinary manual route: preserve originals, apply one small patch, run regression/normal-user/checker tests and scan again. No cards or manually transcribed hashes are required; section 4 is an optional advanced automated evidence gate, not a prerequisite for manual patching.
|
||||
|
||||
## 1. Preserve the before-state
|
||||
|
||||
Record code revision/local diff, immutable image ID, configuration sources, current data and rollback method. These are different assets: reverting code must not restore an old database over new-round records.
|
||||
|
||||
Evidence: `REVIEWED`; effect `READ-ONLY`; cwd service checkout with Git. Expected: actual revision and existing modifications. Output may contain private paths; do not broadcast it. Rollback: none.
|
||||
|
||||
```bash
|
||||
git status --short
|
||||
git rev-parse HEAD
|
||||
git diff --check
|
||||
```
|
||||
|
||||
Without Git, privately copy only the files being changed with suitable backup tools; checksum verification can be automatic. Never use broad git add, reset --hard or git clean as a generic workflow. [File backup](local-tools.md#backup-and-staging-restore) is bounded, but databases require native consistent dumps or a verified stopped-copy procedure.
|
||||
|
||||
## 2. Required behavioral matrix
|
||||
|
||||
| Check | Passing result |
|
||||
|---|---|
|
||||
| Defect regression | The same safe-behavior test fails before and passes after |
|
||||
| Normal user | Login, create/read/update and expected sharing work |
|
||||
| Authorization | Owner succeeds; another user/tenant and anonymous caller fail without side effects |
|
||||
| Old data | Pre-patch records retain their format and accessibility |
|
||||
| Persistence | New records survive an approved isolated restart |
|
||||
| Alternative paths | Lists, exports, files, jobs and affected routes enforce the same rule |
|
||||
| Input boundaries | Empty/wrong-type/Unicode/maximum values follow the contract |
|
||||
| Dependency failure | Bounded, sanitized failure without default authorization |
|
||||
| Checker | Actual tournament semantics and SLA remain satisfied |
|
||||
|
||||
Check absence of forbidden effects, not only status codes: denied reads contain no foreign body, denied writes leave rows unchanged and blocked URLs never call the HTTP client. [PY-SQL](vulnerabilities/python.md#py-sql) provides a small private-note example; test route/session integration as well as its helper.
|
||||
|
||||
## 3. Match the deployment mechanism
|
||||
|
||||
| Mechanism | Required action / pitfall |
|
||||
|---|---|
|
||||
| Source bind mount | Update only reviewed files; restart only if the process needs it |
|
||||
| Code copied into an image | Build a new pinned image and recreate the owned service; restart alone does not rebuild |
|
||||
| Native binary | Verify architecture/libraries/permissions and data compatibility |
|
||||
| API plus workers | Update dependent processes consistently; old workers may retain old behavior |
|
||||
|
||||
Inspect entrypoints for destructive initialization/migrations and locate persistent data. Do not reconfigure game networks, remove volumes or rebuild unrelated components to apply a source patch.
|
||||
|
||||
Before production approval, rehearse the exact rollback command on a copy. It must restore code/image while preserving current data. Keep the old image locally; a mutable latest tag is not a rollback target.
|
||||
|
||||
## 4. Bound evidence to this patch
|
||||
|
||||
Collect before/after snapshots and scans with the same intended scope, followed by health and actual regression-test records. A result reused from another run cannot establish this patch's status.
|
||||
|
||||
The [validation-record schema](../schemas/validation-record.v1.schema.json) uses lowercase statuses. Each record's attributes must contain the exact SHA-256 of before_snapshot, after_snapshot, before_scanner, after_scanner and health inputs under their corresponding *_sha256 keys, plus one common run_id. Record time must follow the dependent evidence.
|
||||
|
||||
If deployment audit is required, include its audit/model/policy hashes in the same record. The audit is recomputed from model/policy; its source hash must correspond to the exact runtime configuration captured in the after-snapshot. It checks declared configuration, not running-daemon truth.
|
||||
|
||||
Evidence: `REVIEWED`; effect `READ-ONLY`; cwd root. Prerequisites: genuine private evidence at the example paths, current hashes/timestamps and matching scope. Expected: 0/pass, 1/regression or 2/incomplete. Never fabricate pass records merely to satisfy this gate. Rollback: none.
|
||||
|
||||
```bash
|
||||
python3 scripts/defense_ops.py patch-check \
|
||||
--before ../private-results/before.json --after ../private-results/after.json \
|
||||
--before-scanner ../private-results/before-scan.json \
|
||||
--after-scanner ../private-results/after-scan.json \
|
||||
--health-result ../private-results/health.json \
|
||||
--validation-record ../private-results/regression.json \
|
||||
--deployment-audit ../private-results/deployment-audit.json \
|
||||
--deployment-model ../private-deployment/run-01/runtime-model.json \
|
||||
--deployment-policy ../private-deployment/run-01/runtime-policy.json \
|
||||
--require-deployment-audit
|
||||
```
|
||||
|
||||
For source-only changes without deployment audit, omit all four deployment arguments explicitly. Required health/scanner/validation evidence still applies. Missing, stale, partial, not-run, mismatched or incomparable evidence cannot yield a clean pass.
|
||||
|
||||
Expected drift needs an explicitly reviewed [approved-drift record](../schemas/approved-drift.v1.schema.json), bound to both snapshot hashes and the exact categorized changes; pass it with --approved-drift. A broad wildcard approval is not supported.
|
||||
|
||||
## 5. Apply, observe, revert if necessary
|
||||
|
||||
After explicit approval, use only the rehearsed owned-service deployment path. Immediately repeat health, actual user/checker operations and old-data reads, then monitor a full relevant round window. Preserve a sanitized incident timeline if failure occurs.
|
||||
|
||||
Rollback code/image first according to the recorded plan. Data restoration is a separate high-impact decision: an old dump may erase new-round data. Do not rotate keys, migrate schemas or replace runtimes as incidental fixes.
|
||||
@@ -0,0 +1,61 @@
|
||||
<a id="release-and-publication-checklist"></a>
|
||||
# Чеклист релиза и публикации
|
||||
|
||||
[English](release-checklist.md) | Русский
|
||||
|
||||
Чеклист сопровождающего, а не форма оператора. Для развёртывания используйте [инструкцию Mac](MACOS_FULL_DEPLOYMENT_AND_TESTING-RU.md). Готовность к публикации и к соревнованию учитываются отдельно.
|
||||
|
||||
<a id="source-and-tests"></a>
|
||||
## Исходники и тесты
|
||||
|
||||
- [ ] Одобренный source commit и чистое tracked tree; без посторонних изменений.
|
||||
- [ ] Полный unit suite и coverage ledger проходят, включая docs links/anchors, английский текст и соответствие парных русских переводов; команды и примеры остаются идентичными.
|
||||
- [ ] Новые и изменённые правила соответствуют независимому positive/negative coverage языков.
|
||||
- [ ] Точно распакованный core bundle проходит; archive manifest/checksums проверены.
|
||||
- [ ] Внешние kits проходят строгий verifier; частичный экспорт образов не выдаётся за полный toolchain. Релиз только core не заявляет наличие сторонних runtimes.
|
||||
- [ ] Результаты Linux integration и macOS ARM64 CI относятся к явно указанным commits.
|
||||
- [ ] Заявленная поддержка соответствует текущей странице возможностей; generated outputs остаются вне Git.
|
||||
|
||||
<a id="publication-safety"></a>
|
||||
## Безопасность публикации
|
||||
|
||||
Запускайте из корня репозитория. Эти read-only проверки показывают категории и расположения, а не найденные значения секретов.
|
||||
|
||||
```bash
|
||||
python3 scripts/publication_check.py --root . --allowlist config/publication-allowlist.json
|
||||
python3 scripts/publication_check.py --root . --history --ref HEAD \
|
||||
--allowlist config/publication-allowlist.json
|
||||
```
|
||||
|
||||
- [ ] Проверьте каждый ref, предназначенный для публикации, а не только HEAD; checker принимает повторяющиеся явные --ref arguments.
|
||||
- [ ] При необходимости используйте игнорируемый приватный denylist для строк локальных endpoints/identities; никогда не коммитьте его.
|
||||
- [ ] Отдельно проверьте candidate archives, screenshots, CI artifacts и PR material. Проверка текста/истории не является OCR скриншотов и не доказывает безопасность удалённых артефактов.
|
||||
- [ ] Нет keys/tokens, заполненных profiles, raw logs/PCAP, игровых данных, личных путей или описания частного deployment оператора.
|
||||
- [ ] Синтетические исключения точны, узки и обоснованы; никогда не исключайте целиком tests/docs.
|
||||
- [ ] Сохраняйте законное авторство, citations и license attribution.
|
||||
- [ ] Подтвердите работающий приватный канал сообщений об уязвимостях согласно [SECURITY](../SECURITY-RU.md).
|
||||
- [ ] Правомерность распространения сторонних binaries/images проверена; иначе распространяйте только core.
|
||||
- [ ] Заявления version/changelog/support соответствуют точному релизу.
|
||||
|
||||
Изменение видимости репозитория, удаление refs, переписывание истории или публикация сторонних артефактов — отдельные осознанные действия. Не автоматизируйте их как косметическую уборку.
|
||||
|
||||
<a id="release-candidate-and-public-access"></a>
|
||||
## Релиз-кандидат и публичный доступ
|
||||
|
||||
`RELEASE_CANDIDATE_READY` означает фиксированный source commit и core-архив, прошедшие применимые релизные проверки, с указанными оставшимися platform/event gates. Это не означает публичность репозитория или сертификацию игровой среды.
|
||||
|
||||
`PUBLIC_RELEASE_VERIFIED` дополнительно требует явного разрешения владельца на публикацию и успешного анонимного доступа к выбранному репозиторию, README, workflow оператора и скачиванию исходников. До разрешения проверьте все открываемые ветки/историю, PR material и CI assets; сохраните законную историю и тестовые fixtures. Нельзя молча удалять исторические материалы или переписывать commits ради зелёной проверки.
|
||||
|
||||
Если правила соревнования требуют публичность, это обязательное условие до игры. Приватный release candidate его не закрывает. [Workflow администратора](ADMIN_WORKFLOWS-RU.md) — рабочий маршрут; локальные результаты проверок остаются приватными.
|
||||
|
||||
<a id="competition-gate"></a>
|
||||
## Условия готовности к соревнованию
|
||||
|
||||
- [ ] Проверены архитектура реального целевого Mac, точные версии OS/Desktop и ресурсный бюджет.
|
||||
- [ ] Отрепетированы functional paths farm/coordinator/worker/Packmate и native recovery.
|
||||
- [ ] Нет нерешённого P0 failure, partial result или непринятого blocker.
|
||||
- [ ] Полный offline cold start проходит без скрытых downloads.
|
||||
- [ ] Каждое физическое устройство teammate проходит полезные сценарии с аутентификацией и reconnect.
|
||||
- [ ] Разрешённый непрерывный capture видит известный двусторонний трафик при ограниченном storage.
|
||||
- [ ] Не менее 60 минут совместной нагрузки toolchain; в источнике захвата нет секретов.
|
||||
- [ ] Новый оператор может пройти английское руководство без AI.
|
||||
@@ -0,0 +1,56 @@
|
||||
# Release and publication checklist
|
||||
|
||||
English | [Русский](release-checklist-RU.md)
|
||||
|
||||
Maintainer checklist, not an operator form. For deployment use the [Mac guide](MACOS_FULL_DEPLOYMENT_AND_TESTING.md). Publication readiness and competition readiness are separate.
|
||||
|
||||
## Source and tests
|
||||
|
||||
- [ ] Approved source commit and clean tracked tree; no unrelated changes.
|
||||
- [ ] Full unit suite and coverage ledger pass, including English prose, paired Russian translations, identical code examples and links/anchors in both languages.
|
||||
- [ ] New/changed rules meet independent positive/negative language coverage.
|
||||
- [ ] Exact extracted core bundle passes; archive manifest/checksums verified.
|
||||
- [ ] External kits pass the strict verifier; partial image exports are not advertised as a complete toolchain. A core-only release does not claim to contain third-party runtimes.
|
||||
- [ ] Linux integration results and macOS ARM64 CI refer to explicit commits.
|
||||
- [ ] Support claims match the current capability page; generated run outputs remain outside Git.
|
||||
|
||||
## Publication safety
|
||||
|
||||
Run from the repository root. These read-only checks report categories and locations, not matched secret values.
|
||||
|
||||
```bash
|
||||
python3 scripts/publication_check.py --root . --allowlist config/publication-allowlist.json
|
||||
python3 scripts/publication_check.py --root . --history --ref HEAD \
|
||||
--allowlist config/publication-allowlist.json
|
||||
```
|
||||
|
||||
- [ ] Inspect every ref intended for publication, not only HEAD; the checker accepts repeated explicit --ref arguments.
|
||||
- [ ] Use an ignored private denylist for local endpoint/identity strings when appropriate; never commit it.
|
||||
- [ ] Review candidate archives, screenshots, CI artifacts and PR material separately. Text/history checking is not screenshot OCR or a proof that remote artifacts are safe.
|
||||
- [ ] No keys/tokens, populated profiles, raw logs/PCAP, game data, personal paths or operator-specific deployment narrative.
|
||||
- [ ] Synthetic exceptions are exact, narrow and justified; never broadly exempt tests/docs.
|
||||
- [ ] Preserve legitimate authorship, citations and license attribution.
|
||||
- [ ] Confirm a working private vulnerability-reporting channel as required by [SECURITY](../SECURITY.md).
|
||||
- [ ] Third-party binary/image redistribution is reviewed; otherwise distribute core only.
|
||||
- [ ] Version/changelog/support claims match the exact release.
|
||||
|
||||
Changing repository visibility, deleting refs, rewriting history or publishing third-party artifacts are separate deliberate actions. Do not automate them as a cosmetic cleanup.
|
||||
|
||||
## Release candidate and public access
|
||||
|
||||
`RELEASE_CANDIDATE_READY` means a fixed source commit and its core archive passed the applicable release checks, with remaining platform/event gates disclosed. It does not mean the repository is public or the competition environment is certified.
|
||||
|
||||
`PUBLIC_RELEASE_VERIFIED` additionally requires the owner's explicit publication approval and successful anonymous access to the intended repository, README, operator workflows and source download. Review all exposed branches/history, PR material and CI assets before that approval; retain legitimate history and test fixtures. Never silently delete historical material or rewrite commits to make a check green.
|
||||
|
||||
Public availability is a pre-event gate wherever required by the competition rules. A private release candidate does not satisfy that requirement. The [administrator workflows](ADMIN_WORKFLOWS.md) are the operational route; local validation outputs remain private.
|
||||
|
||||
## Competition gate
|
||||
|
||||
- [ ] Actual target-Mac architecture, exact OS/Desktop version and resource budget verified.
|
||||
- [ ] Farm/coordinator/worker/Packmate functional paths and native recovery rehearsed.
|
||||
- [ ] No unresolved P0 failure, partial result or unaccepted blocker.
|
||||
- [ ] Full offline cold start succeeds without hidden downloads.
|
||||
- [ ] Every physical teammate device passes authenticated useful scenarios and reconnect.
|
||||
- [ ] Approved continuous capture sees known bidirectional traffic with bounded storage.
|
||||
- [ ] At least 60 minutes of combined toolchain load; no secret-bearing capture source.
|
||||
- [ ] A new operator can follow the English or Russian guide without AI; both routes remain complete.
|
||||
@@ -0,0 +1,36 @@
|
||||
<a id="s4dfarm-flags-and-submission"></a>
|
||||
# S4DFarm: флаги и отправка
|
||||
|
||||
[English](s4dfarm.md) | Русский
|
||||
|
||||
S4DFarm собирает флаги команды, ставит их в очередь отправки и показывает accepted/rejected/expired. Neo автоматически передаёт найденные флаги. **Патчи сервисов ферма не распространяет.**
|
||||
|
||||
<a id="start-through-durkahelper"></a>
|
||||
## Запуск через DurkaHelper
|
||||
|
||||
```bash
|
||||
python3 durka.py up
|
||||
python3 durka.py status
|
||||
```
|
||||
|
||||
Откройте URL фермы; пароль — `credentials.farm_password` в приватном `local/durka.json`. Передайте участникам LAN URL/пароль, а не конфигурацию PostgreSQL/Redis.
|
||||
|
||||
<a id="configure-the-competition"></a>
|
||||
## Настроить соревнование
|
||||
|
||||
В `local/durka.json` задайте реальные команды, regex флага, лимиты/время отправки и URL/token в `profile.farm.protocol_settings`. Kit поддерживает `ructf_http`; отсутствующий upstream default adapter не используется.
|
||||
|
||||
Отправка изначально выключена. После проверки соответствия receiver соревнованию:
|
||||
|
||||
```bash
|
||||
python3 durka.py submit
|
||||
```
|
||||
|
||||
Смотрите конечный статус легитимного флага. Работающий UI, очередь или успешный вход Neo ещё не доказывают принятие. Если очередь стоит: отправка включена, адаптер/token, expiry и ответы receiver.
|
||||
|
||||
<a id="change-configuration-or-recover"></a>
|
||||
## Изменить конфиг или восстановить
|
||||
|
||||
Настройки площадки: остановить, отредактировать приватный конфиг, выполнить `python3 durka.py configure`, затем запустить. Не переотправляйте старые/просроченные очереди после recovery. [Native recovery](../deployment/README-RU.md#native-backup-and-quarantine-restore) восстанавливает в новое хранилище и намеренно очищает Redis кандидата.
|
||||
|
||||
Точные версии — в [toolchain lock](../config/toolchain.lock.json); подготовка DurkaHelper использует их автоматически. [Установка админа](MACOS_FULL_DEPLOYMENT_AND_TESTING-RU.md) · [Neo](neo-RU.md) · [Upstream](https://github.com/C4T-BuT-S4D/S4DFarm)
|
||||
@@ -0,0 +1,32 @@
|
||||
# S4DFarm: flags and submission
|
||||
|
||||
English | [Русский](s4dfarm-RU.md)
|
||||
|
||||
S4DFarm collects flags from the team, queues them for submission and shows accepted/rejected/expired results. Neo sends discovered flags to it automatically. **It does not distribute service patches.**
|
||||
|
||||
## Start through DurkaHelper
|
||||
|
||||
```bash
|
||||
python3 durka.py up
|
||||
python3 durka.py status
|
||||
```
|
||||
|
||||
Open the printed farm URL; the password is `credentials.farm_password` in private `local/durka.json`. Give teammates that LAN URL/password, not the PostgreSQL/Redis configuration.
|
||||
|
||||
## Configure the competition
|
||||
|
||||
In `local/durka.json`, set the actual team map, flag regex, submit limits/timing and `profile.farm.protocol_settings` URL/token. The kit currently supports `ructf_http`; the upstream's absent default adapter is not used.
|
||||
|
||||
Submission starts disabled. After checking that the receiver matches the competition:
|
||||
|
||||
```bash
|
||||
python3 durka.py submit
|
||||
```
|
||||
|
||||
Watch a legitimate flag's final status. A running UI, queue entry or successful Neo login does not prove submission acceptance. If queues stall, check submission enabled, adapter/token, expiry and receiver responses.
|
||||
|
||||
## Change configuration or recover
|
||||
|
||||
For event settings: stop, edit the private config, run `python3 durka.py configure`, then start. Keep old/expired recovered queues from replaying. The [native recovery procedure](../deployment/README.md#native-backup-and-quarantine-restore) restores into new storage and deliberately clears candidate Redis state.
|
||||
|
||||
Exact upstream versions live in the [toolchain lock](../config/toolchain.lock.json); DurkaHelper preparation handles them. [Admin setup](MACOS_FULL_DEPLOYMENT_AND_TESTING.md) · [Neo](neo.md) · [Upstream](https://github.com/C4T-BuT-S4D/S4DFarm)
|
||||
@@ -0,0 +1,39 @@
|
||||
<a id="how-the-teams-tools-connect"></a>
|
||||
# Как связаны командные инструменты
|
||||
|
||||
[English](team-setup.md) | Русский
|
||||
|
||||
Один администратор поднимает общий стек. Участники открывают его LAN-интерфейсы и подключают клиенты Neo. Защищаемые сервисы остаются на Vulnbox.
|
||||
|
||||
```text
|
||||
Teammates ──Ethernet──> Farm UI/API ──> competition flag receiver
|
||||
├───────────> Neo coordinator ──> workers ──> permitted targets
|
||||
└───────────> Packmate UI
|
||||
Vulnbox traffic ──> approved Linux LIVE, or closed PCAP ──> Packmate FILE
|
||||
Service source copy ──> DurkaHelper scan ──> reviewed patch ──> Vulnbox
|
||||
```
|
||||
|
||||
<a id="who-owns-what"></a>
|
||||
## Кто за что отвечает
|
||||
|
||||
Админ отвечает за общий конфиг, запуск, учётные данные, отправку и backups. Защитники — за review, патчи и regression-тесты сервиса. Авторы — за свои скрипты/зависимости и результаты в ферме. Workers Neo выполняют доверенный командный код.
|
||||
|
||||
Ферма отправляет **флаги**, Neo распределяет **скрипты**. Патчи сервисов они автоматически не развёртывают. Используйте обычный доступ/деплой Vulnbox вашей команды.
|
||||
|
||||
Автор загружает скрипт в общий координатор Neo; подготовленный worker исполняет его и передаёт подходящие результаты stdout прямо в ферму. Несколько авторов могут пользоваться одним worker: каждому запускать свой не обязательно. См. [workflow клиентов/workers и примеры разового запуска и расписания](neo-RU.md#team-workflow-clients-coordinator-and-workers). Отправка из фермы включается отдельно; попадание в очередь ещё не подтверждает приём жюрейкой.
|
||||
|
||||
<a id="addresses"></a>
|
||||
## Адреса
|
||||
|
||||
Используйте Ethernet IPv4 админа и порты из `python3 durka.py status`. По умолчанию: ферма 8080, Neo 5005, Packmate 65000. Участникам не нужны `localhost`, Docker DNS и `host.docker.internal`.
|
||||
|
||||
Database, Redis и Docker остаются приватными. Клиентам/workers Neo нужен доступ к координатору и ферме; workers также нужны разрешённые маршруты до целей. Используйте только разрешённые площадкой порты и доступ.
|
||||
|
||||
<a id="first-check"></a>
|
||||
## Первая проверка
|
||||
|
||||
Дома проверьте машину админа и отдельный ПК. На площадке каждый участник должен войти, выполнить полезное действие и переподключиться. Ethernet link или открытого TCP-порта недостаточно.
|
||||
|
||||
Ноутбук не видит автоматически весь трафик коммутируемой LAN. Выберите [разрешённый LIVE или импорт PCAP](traffic-capture-RU.md).
|
||||
|
||||
[Установка админа](MACOS_FULL_DEPLOYMENT_AND_TESTING-RU.md) · [Шпаргалка админа](TEAM_LAN_ADMIN_CHEATSHEET-RU.md) · [Инструкция участника](participant-guide-RU.md)
|
||||
@@ -0,0 +1,35 @@
|
||||
# How the team's tools connect
|
||||
|
||||
English | [Русский](team-setup-RU.md)
|
||||
|
||||
One administrator hosts the shared stack. Teammates open its LAN UIs and connect Neo clients. Protected services remain on the Vulnbox.
|
||||
|
||||
```text
|
||||
Teammates ──Ethernet──> Farm UI/API ──> competition flag receiver
|
||||
├───────────> Neo coordinator ──> workers ──> permitted targets
|
||||
└───────────> Packmate UI
|
||||
Vulnbox traffic ──> approved Linux LIVE, or closed PCAP ──> Packmate FILE
|
||||
Service source copy ──> DurkaHelper scan ──> reviewed patch ──> Vulnbox
|
||||
```
|
||||
|
||||
## Who owns what
|
||||
|
||||
The admin owns shared configuration, startup, credentials, submission and backups. Defenders own review, patches and service regression tests. Script authors own their scripts/dependencies and confirm results in the farm. Neo workers execute trusted team code.
|
||||
|
||||
The farm submits **flags**; Neo distributes **scripts**. Neither automatically deploys service patches. Use the team's existing Vulnbox access/deployment procedure.
|
||||
|
||||
An author uploads to the shared Neo coordinator; a prepared worker executes the script and sends matching stdout results directly to the farm. Authors can share one worker and need not run one each. See the [client/worker workflow and one-shot/scheduled examples](neo.md#team-workflow-clients-coordinator-and-workers). The farm's submission process is enabled separately; queue ingestion is not jury acceptance.
|
||||
|
||||
## Addresses
|
||||
|
||||
Use the admin's Ethernet IPv4 and the ports printed by `python3 durka.py status`. Defaults: farm 8080, Neo 5005, Packmate 65000. Teammates do not use `localhost`, Docker service names or `host.docker.internal`.
|
||||
|
||||
Database, Redis and Docker endpoints stay private. Neo clients/workers need access to both coordinator and farm; workers additionally need allowed routes to targets. Use only ports and access permitted by the event.
|
||||
|
||||
## First check
|
||||
|
||||
At home, test the admin machine and a separate PC. At the venue, have each teammate log in, perform a useful action and reconnect. A connected Ethernet link or open TCP port alone is not enough.
|
||||
|
||||
The laptop does not automatically see all traffic on a switched LAN. Choose [approved LIVE or PCAP import](traffic-capture.md).
|
||||
|
||||
[Administrator setup](MACOS_FULL_DEPLOYMENT_AND_TESTING.md) · [Admin cheat sheet](TEAM_LAN_ADMIN_CHEATSHEET.md) · [Participant guide](participant-guide.md)
|
||||
@@ -0,0 +1,129 @@
|
||||
<a id="traffic-live-or-pcap-import"></a>
|
||||
# Трафик: LIVE или импорт PCAP
|
||||
|
||||
[English](traffic-capture.md) | Русский
|
||||
|
||||
Подготовьте оба пути до соревнования. На месте выберите разрешённый организаторами; обычный FILE import не требует изменения кода.
|
||||
|
||||
<a id="choose-a-route"></a>
|
||||
## Выбрать вариант
|
||||
|
||||
| Что доступно | Использовать |
|
||||
|---|---|
|
||||
| Разрешено запустить capture на Vulnbox/native Linux и виден трафик его интерфейса | Packmate LIVE на этом Linux-узле |
|
||||
| Предоставлен разрешённый Linux mirror/capture интерфейс | Packmate LIVE там; зеркало дают организаторы |
|
||||
| Только закрытые PCAP или разрешённый SSH/tcpdump | Передать закрытые файлы и использовать Packmate FILE на ноутбуке |
|
||||
| Разрешённого источника нет | Продолжить разбор исходников; анализ трафика недоступен |
|
||||
|
||||
Mac на том же Ethernet switch не видит автоматически пакеты Vulnbox. Поддерживаемый маршрут Docker Desktop — только FILE. Бесконечный FILE pipe не заменяет LIVE: upstream привязывает timeout незавершённых потоков и periodic cleanup к LIVE.
|
||||
|
||||
<a id="file-on-the-laptop"></a>
|
||||
## FILE на ноутбуке
|
||||
|
||||
Поднимите стек, получите **закрытый** capture и импортируйте:
|
||||
|
||||
```bash
|
||||
python3 durka.py up
|
||||
python3 durka.py traffic import /path/to/closed-capture.pcap
|
||||
python3 durka.py status
|
||||
```
|
||||
|
||||
Команда сама проверяет файл, сохраняет предыдущий capture и перезапускает только Packmate. БД и другие инструменты продолжают работать. Ручные SHA/карточки не нужны.
|
||||
|
||||
В Packmate зарегистрируйте сервис/шаблон, проверьте IP стороны сервиса в конфиге и один раз нажмите жёлтую кнопку разбора FILE со стрелкой вниз в боковой панели. Найдите известные запрос/ответ. Подробности и отличие от загрузки файла — в [инструкции UI](packmate-RU.md#file-on-the-laptop). Каждый новый файл — той же import-командой и кнопкой разбора. EOF не сбрасывает upstream parser; не копируйте новый capture поверх активного FILE.
|
||||
|
||||
Передача на носителе тоже подходит. Captures приватные: внутри могут быть cookies, учётные данные и флаги.
|
||||
|
||||
<a id="capture-a-closed-file-on-linux"></a>
|
||||
## Получить закрытый файл на Linux
|
||||
|
||||
Лучше использовать файлы организаторов. Если capture разрешён и `tcpdump`/`timeout` уже установлены, запускайте в приватном каталоге источника. Замените все placeholders разрешённым интерфейсом/сервисом/портами и **новым** именем файла:
|
||||
|
||||
```bash
|
||||
umask 077
|
||||
timeout --signal=INT 60 tcpdump -i <APPROVED_INTERFACE> -p -nn -s 65535 \
|
||||
-c 1000 -w <NEW_PRIVATE_PREFIX>.pcap \
|
||||
'host <SERVICE_IPV4> and (tcp port <TCP_PORT> or udp port <UDP_PORT>)'
|
||||
```
|
||||
|
||||
Дождитесь завершения процесса до передачи. Это до 60 секунд или 1 000 пакетов, примерно 66 MB плюс overhead формата. Код `timeout` 124 может быть ожидаемым; другие ошибки захвата нужно проверить. Рецепт основан на [tcpdump manual](https://github.com/the-tcpdump-group/tcpdump/blob/master/tcpdump.1.in); это проверенная по инструкции процедура, а не тест интерфейса вашей площадки.
|
||||
|
||||
При существующем разрешённом SSH identity и доверенном host key:
|
||||
|
||||
```bash
|
||||
scp -o StrictHostKeyChecking=yes -P <SSH_PORT> \
|
||||
<USER>@<SOURCE_HOST>:<EXACT_CLOSED_FILE> ./incoming-01.pcap
|
||||
python3 durka.py traffic import ./incoming-01.pcap
|
||||
```
|
||||
|
||||
Эти две команды запускаются на ноутбуке из корня репозитория. Сохраните source до успешного импорта/использования. Файл, в который ещё идёт запись, не передавайте.
|
||||
|
||||
<a id="host-interface-live"></a>
|
||||
## Host-interface LIVE
|
||||
|
||||
Для обычного запуска с ноутбука используйте [SSH deployment с doctor и офлайн-образами](packmate-remote-RU.md).
|
||||
Python на Vulnbox не требуется. Ниже — низкоуровневый Linux helper для расширенных ручных процедур.
|
||||
|
||||
Это ветка Linux-админа, отдельная от Docker Desktop. Требуются native Linux amd64, стандартный локальный rootful Docker Engine, кешированные закреплённые образы Packmate/PostgreSQL и разрешение на **весь выбранный интерфейс**. Закреплённый upstream при запуске кратко применяет широкий TCP/UDP filter.
|
||||
|
||||
Launcher использует host networking и NET_RAW; не privileged и не NET_ADMIN. БД остаётся на IPv4 loopback; firewall, маршруты и switch не меняются.
|
||||
|
||||
Посмотрите нужные Engine/interface:
|
||||
|
||||
```bash
|
||||
docker info --format '{{.ID}}'
|
||||
ip -json link show
|
||||
```
|
||||
|
||||
Укажите увиденные Engine ID/interface name/index/MAC и реальные адреса в приватном `local/packmate-host.json`:
|
||||
|
||||
```json
|
||||
{
|
||||
"schema": "durkahelper.packmate-host.v1",
|
||||
"daemon_id": "REPLACE_ENGINE_ID",
|
||||
"interface": "eth0", "ifindex": 2, "interface_mac": "02:00:00:00:00:01",
|
||||
"local_ip": "192.0.2.10", "bind_address": "192.0.2.20",
|
||||
"ui_port": 65000, "db_port": 55432,
|
||||
"tcp_timeout_seconds": 30, "udp_timeout_seconds": 10,
|
||||
"timeout_check_seconds": 5, "retention_minutes": 60,
|
||||
"cleanup_interval_minutes": 1
|
||||
}
|
||||
```
|
||||
|
||||
Это примеры значений. `local_ip` — IP стороны сервиса в трафике; `bind_address` — адрес UI для команды. Отдельный приватный credentials JSON содержит `username`, `password`, `db_password`; пароли — разные сгенерированные safe ASCII длиной 20–128. Файлы должны лежать в owner-only каталоге.
|
||||
|
||||
На разрешённом Linux-хосте подготовьте новый workspace и запустите:
|
||||
|
||||
```bash
|
||||
python3 deployment/packmate_host.py prepare \
|
||||
--workspace ../private-deployment/host-live-01 \
|
||||
--profile local/packmate-host.json \
|
||||
--credentials local/packmate-host-credentials.json \
|
||||
--apply --approval-id host-live-prepare
|
||||
python3 deployment/packmate_host.py up \
|
||||
--workspace ../private-deployment/host-live-01 \
|
||||
--capture-approval '<INTERFACE>:<IFINDEX>:<MAC>' \
|
||||
--host-network-approved --interface-scope-approved \
|
||||
--apply --approval-id host-live-start
|
||||
```
|
||||
|
||||
Зарегистрируйте сервисы/шаблоны в UI и проверьте известные TCP/UDP запросы/ответы, направление, задержку, незавершённые потоки и restart. Видимость пакетов обеспечивается разрешённым размещением host/mirror. Очистка по возрасту — не жёсткая disk quota: следите за ростом хранилища.
|
||||
|
||||
Остановить только этот capture deployment с сохранением данных:
|
||||
|
||||
```bash
|
||||
python3 deployment/packmate_host.py down \
|
||||
--workspace ../private-deployment/host-live-01 \
|
||||
--apply --approval-id host-live-stop
|
||||
```
|
||||
|
||||
Для разрешённого существующего container namespace — отдельный [container LIVE reference](../deployment/README-RU.md#approved-linux-container-namespace-live). Прямые helpers поддерживают контролируемые cache/bootstrap операции; для другого offline-хоста смотрите их `--help`.
|
||||
|
||||
<a id="check-before-relying-on-traffic"></a>
|
||||
## Проверить до использования
|
||||
|
||||
Найдите известную транзакцию, а не только работающий UI. Проверьте оба направления, время, характерные TCP/UDP, рост диска и restart. Остановите capture при неверном scope, утечке секретов или приближении к пределу диска.
|
||||
|
||||
FILE — отложенный анализ. Если необходим непрерывный анализ, одних закрытых файлов недостаточно. Прогоните оба разрешённых пути и подготовьте capture-зависимости/образы до выезда.
|
||||
|
||||
[Packmate](packmate-RU.md) · [Шпаргалка админа](TEAM_LAN_ADMIN_CHEATSHEET-RU.md)
|
||||
@@ -0,0 +1,123 @@
|
||||
# Traffic: LIVE or PCAP import
|
||||
|
||||
English | [Русский](traffic-capture-RU.md)
|
||||
|
||||
Prepare both routes before the event. Choose the one the organizers permit; no code changes are needed for normal FILE import.
|
||||
|
||||
## Choose a route
|
||||
|
||||
| What is available | Use |
|
||||
|---|---|
|
||||
| You may run capture on the Vulnbox/native Linux node and see its interface traffic | Packmate LIVE on that Linux node |
|
||||
| An approved Linux mirror/capture interface is provided | Packmate LIVE there; organizers provide the mirror |
|
||||
| Only closed PCAP files or authorized SSH/tcpdump access | Transfer closed files and use Packmate FILE on the laptop |
|
||||
| No permitted traffic source | Continue source review; traffic analysis is unavailable |
|
||||
|
||||
A Mac on the same Ethernet switch does not automatically see Vulnbox packets. Docker Desktop's maintained route is FILE-only. An endless FILE pipe is not a substitute for LIVE: this upstream ties incomplete-flow timeouts and periodic cleanup to LIVE.
|
||||
|
||||
## FILE on the laptop
|
||||
|
||||
Start the stack, obtain a **closed** capture and import:
|
||||
|
||||
```bash
|
||||
python3 durka.py up
|
||||
python3 durka.py traffic import /path/to/closed-capture.pcap
|
||||
python3 durka.py status
|
||||
```
|
||||
|
||||
The command checks the file internally, retains the prior capture and restarts only Packmate. Its database and other tools remain running. No manual SHA/card is needed.
|
||||
|
||||
In Packmate: register the service/pattern, check the service-side IP in the configuration and press the yellow downward-arrow FILE-processing button in the sidebar once. Find a known request and response. See the [UI guide](packmate.md#file-on-the-laptop) for the distinction between importing and processing. Repeat the import command and processing button for each new file. EOF does not reset the upstream parser; do not copy a new capture directly over a running FILE input.
|
||||
|
||||
Manual media delivery is valid too. Keep captures private: they can contain cookies, credentials and flags.
|
||||
|
||||
## Capture a closed file on Linux
|
||||
|
||||
Prefer organizer-provided files. If you have permitted capture access and existing `tcpdump`/`timeout`, run this from a private directory on the source. Replace all placeholders with the approved interface/service/ports and a **new** filename:
|
||||
|
||||
```bash
|
||||
umask 077
|
||||
timeout --signal=INT 60 tcpdump -i <APPROVED_INTERFACE> -p -nn -s 65535 \
|
||||
-c 1000 -w <NEW_PRIVATE_PREFIX>.pcap \
|
||||
'host <SERVICE_IPV4> and (tcp port <TCP_PORT> or udp port <UDP_PORT>)'
|
||||
```
|
||||
|
||||
Wait for the process to exit before transferring. This records up to 60 seconds or 1,000 packets, approximately 66 MB plus format overhead. `timeout` exit 124 may be expected; other capture errors need checking. The recipe follows the [tcpdump manual](https://github.com/the-tcpdump-group/tcpdump/blob/master/tcpdump.1.in) and is a reviewed procedure, not a test of your event interface.
|
||||
|
||||
With an existing approved SSH identity and trusted host key:
|
||||
|
||||
```bash
|
||||
scp -o StrictHostKeyChecking=yes -P <SSH_PORT> \
|
||||
<USER>@<SOURCE_HOST>:<EXACT_CLOSED_FILE> ./incoming-01.pcap
|
||||
python3 durka.py traffic import ./incoming-01.pcap
|
||||
```
|
||||
|
||||
Run these two commands on the laptop from the repository root. Keep the source until import/use succeeds. Never transfer a file still being written.
|
||||
|
||||
## Host-interface LIVE
|
||||
|
||||
For normal laptop-operated startup use [SSH deployment with doctor and offline images](packmate-remote.md).
|
||||
No Python is required on the Vulnbox. The low-level Linux helper below remains available for advanced manual procedures.
|
||||
|
||||
This is the Linux administrator's branch, separate from Docker Desktop. Requirements: native Linux amd64, standard local rootful Docker Engine, cached pinned Packmate/PostgreSQL images and permission for the **entire selected interface**. The pinned upstream briefly uses a broad TCP/UDP filter during startup.
|
||||
|
||||
The launcher uses host networking and NET_RAW; not privileged or NET_ADMIN. It leaves the database on IPv4 loopback and does not change firewall, routes or switch configuration.
|
||||
|
||||
Inspect the intended Engine/interface:
|
||||
|
||||
```bash
|
||||
docker info --format '{{.ID}}'
|
||||
ip -json link show
|
||||
```
|
||||
|
||||
Put the observed Engine ID/interface name/index/MAC and actual addresses in a private `local/packmate-host.json`:
|
||||
|
||||
```json
|
||||
{
|
||||
"schema": "durkahelper.packmate-host.v1",
|
||||
"daemon_id": "REPLACE_ENGINE_ID",
|
||||
"interface": "eth0", "ifindex": 2, "interface_mac": "02:00:00:00:00:01",
|
||||
"local_ip": "192.0.2.10", "bind_address": "192.0.2.20",
|
||||
"ui_port": 65000, "db_port": 55432,
|
||||
"tcp_timeout_seconds": 30, "udp_timeout_seconds": 10,
|
||||
"timeout_check_seconds": 5, "retention_minutes": 60,
|
||||
"cleanup_interval_minutes": 1
|
||||
}
|
||||
```
|
||||
|
||||
These values are examples. `local_ip` means the service-side IP in the traffic; `bind_address` serves the team's UI. Use a separate private credentials JSON with `username`, `password`, `db_password`; passwords are distinct generated 20–128 character safe ASCII values. Keep these files under an owner-only directory.
|
||||
|
||||
On the approved Linux host, prepare a new workspace and start:
|
||||
|
||||
```bash
|
||||
python3 deployment/packmate_host.py prepare \
|
||||
--workspace ../private-deployment/host-live-01 \
|
||||
--profile local/packmate-host.json \
|
||||
--credentials local/packmate-host-credentials.json \
|
||||
--apply --approval-id host-live-prepare
|
||||
python3 deployment/packmate_host.py up \
|
||||
--workspace ../private-deployment/host-live-01 \
|
||||
--capture-approval '<INTERFACE>:<IFINDEX>:<MAC>' \
|
||||
--host-network-approved --interface-scope-approved \
|
||||
--apply --approval-id host-live-start
|
||||
```
|
||||
|
||||
Register services/patterns in the UI and verify known TCP/UDP requests/responses, direction, delay, unfinished flows and restart. Packet visibility must come from the approved host/mirror placement. Age cleanup is not a hard disk quota: watch storage growth.
|
||||
|
||||
To stop only this capture deployment and retain data:
|
||||
|
||||
```bash
|
||||
python3 deployment/packmate_host.py down \
|
||||
--workspace ../private-deployment/host-live-01 \
|
||||
--apply --approval-id host-live-stop
|
||||
```
|
||||
|
||||
For an already approved existing container namespace, use the separate [container LIVE reference](../deployment/README.md#approved-linux-container-namespace-live). Direct helpers also support controlled cache/bootstrap operations; see their `--help` when preparing a different offline host.
|
||||
|
||||
## Check before relying on traffic
|
||||
|
||||
Find a known transaction, not just a running UI. Check both directions, timestamps, representative TCP/UDP, storage growth and restart. Stop capture if it observes the wrong scope, exposes secrets or approaches disk limits.
|
||||
|
||||
FILE is delayed analysis. If continuous analysis is required, a closed-file fallback alone does not satisfy that requirement. Rehearse both allowed paths and keep capture dependencies/images ready before leaving.
|
||||
|
||||
[Packmate](packmate.md) · [Admin cheat sheet](TEAM_LAN_ADMIN_CHEATSHEET.md)
|
||||
@@ -0,0 +1,50 @@
|
||||
<a id="vulnerability-and-remediation-catalog"></a>
|
||||
|
||||
# Каталог уязвимостей и исправлений
|
||||
|
||||
[English](README.md) | Русский
|
||||
|
||||
Для каждого языка — отдельный файл; SQL и конфигурация рассматриваются отдельно. Инструкции доступны локально и работают без Интернета; ссылки на первичные источники находятся рядом с соответствующими случаями.
|
||||
|
||||
**294 раздела, 174 правила сканера.** Число разделов не равно числу независимых CWE: реализации на разных языках отличаются.
|
||||
|
||||
| Язык / уровень | Разделы |
|
||||
|---|---:|
|
||||
| [Python](python-RU.md) | 40 |
|
||||
| [JavaScript / TypeScript](javascript-RU.md) | 28 |
|
||||
| [PHP](php-RU.md) | 23 |
|
||||
| [Go](go-RU.md) | 19 |
|
||||
| [Java](java-RU.md) | 18 |
|
||||
| [C# / .NET](csharp-RU.md) | 20 |
|
||||
| [C / C++](c-cpp-RU.md) | 28 |
|
||||
| [Ruby / Rails](ruby-RU.md) | 18 |
|
||||
| [Rust](rust-RU.md) | 18 |
|
||||
| [SQL / базы данных](sql-RU.md) | 18 |
|
||||
| [Конфигурация / границы доверия](configuration-RU.md) | 64 |
|
||||
|
||||
<a id="find-and-fix"></a>
|
||||
|
||||
## Найти и исправить
|
||||
|
||||
1. Запустите [офлайн-сканер](../offline-scanner-RU.md) на локальной копии сервиса, которую вам разрешено проверять.
|
||||
2. Откройте ссылку на конкретный раздел для каждой находки.
|
||||
3. Просмотрите разделы языка и конфигурации, предназначенные только для ручной проверки; их команды rg находят код для анализа, а не подтверждённые уязвимости.
|
||||
4. Внесите совместимое исправление и проверьте поведение для владельца и другого пользователя, старые данные и checker соревнования. Используйте [проверку патча](../patch-validation-RU.md).
|
||||
|
||||
Каждый раздел построен по схеме **Поиск → Уязвимый вариант → Исправление → Проверка**.
|
||||
Покрытие: **174 автоматических сигнала и 120 разделов только для ручной проверки**.
|
||||
Две темы, ранее проверявшиеся только вручную, теперь имеют намеренно узкие автоматические сигналы; ручной поиск остаётся необходимым для остальных форм.
|
||||
|
||||
Пустой отчёт не доказывает безопасность. Пользовательские wrappers, сгенерированный код, defaults конкретных версий и бизнес-логика требуют ручного анализа. Сканер не импортирует и не исполняет код цели и не обращается к сетевой базе уязвимостей.
|
||||
|
||||
<a id="example-boundaries"></a>
|
||||
|
||||
## Границы применимости примеров
|
||||
|
||||
Функции вроде validateOwnedResource и evaluateAllowedExpression обозначают логику, которую нужно реализовать самостоятельно; это не готовые зависимости. Шаблоны патчей никогда не применяются автоматически. Сохраняйте штатное поведение, границы авторизации, старые данные и совместимость с checker.
|
||||
|
||||
Отделяйте данные от кода и аргументов. Массив argv без shell всё ещё допускает опасные опции вызываемой программы; проверяйте собственный контракт утилиты. Парсер или проверка типа не заменяет авторизацию. Корректное исправление может сохранить синтаксический сигнал сканера.
|
||||
|
||||
Исторические A/D-примеры сохраняют зафиксированные версии источников и авторство. Проверка семантики исходников не доказывает, что каждый пример запускался на всех поддерживаемых runtime. Каталог не предлагает устанавливать устаревшие версии, упомянутые для объяснения исторического поведения.
|
||||
|
||||
См. [покрытие и разработку правил](../development-RU.md): независимые положительные и отрицательные fixtures и заявленные ограничения детекторов.
|
||||
@@ -0,0 +1,44 @@
|
||||
# Vulnerability and remediation catalog
|
||||
|
||||
English | [Русский](README-RU.md)
|
||||
|
||||
One file per language, with SQL and configuration reviewed separately. Recipes are local and usable offline; primary references remain beside their relevant cases.
|
||||
|
||||
**294 sections, 174 scanner rules.** A section count is not a count of independent CWEs: language-specific implementations differ.
|
||||
|
||||
| Language / layer | Sections |
|
||||
|---|---:|
|
||||
| [Python](python.md) | 40 |
|
||||
| [JavaScript / TypeScript](javascript.md) | 28 |
|
||||
| [PHP](php.md) | 23 |
|
||||
| [Go](go.md) | 19 |
|
||||
| [Java](java.md) | 18 |
|
||||
| [C# / .NET](csharp.md) | 20 |
|
||||
| [C / C++](c-cpp.md) | 28 |
|
||||
| [Ruby / Rails](ruby.md) | 18 |
|
||||
| [Rust](rust.md) | 18 |
|
||||
| [SQL / databases](sql.md) | 18 |
|
||||
| [Configuration / trust boundaries](configuration.md) | 64 |
|
||||
|
||||
## Find and fix
|
||||
|
||||
1. Run the [offline scanner](../offline-scanner.md) against an authorized local service checkout.
|
||||
2. Open each finding's exact section link.
|
||||
3. Review manual-only language and configuration sections; their rg searches identify code to trace, not confirmed vulnerabilities.
|
||||
4. Implement a compatible fix and verify owner/other-user behavior, legacy data and the competition checker. Use [patch verification](../patch-validation.md).
|
||||
|
||||
Every section follows **Search → Vulnerable example → Fix → Verification**.
|
||||
Coverage: **174 automatic signals and 120 manual-only sections**.
|
||||
Two formerly manual topics now have deliberately narrow automatic signals; their manual searches remain necessary for uncovered forms.
|
||||
|
||||
An empty report does not prove safety. Custom wrappers, generated code, version-specific defaults and business logic need manual review. The scanner does not import or execute the target or consult an online vulnerability feed.
|
||||
|
||||
## Example boundaries
|
||||
|
||||
Helpers such as validateOwnedResource and evaluateAllowedExpression represent logic you must implement; they are not ready-made dependencies. Patch templates are never applied automatically. Preserve normal behavior, authorization boundaries, legacy data and checker compatibility.
|
||||
|
||||
Keep data separate from code and arguments. A shell-free argv array still permits dangerous options accepted by the invoked program; validate the utility's own contract. A parser or type assertion is not authorization. Correct fixes may retain syntactic findings.
|
||||
|
||||
Historical A/D cases retain their source pins and attribution. Reviewed source semantics are not proof that every example has run under every supported language runtime. The catalog does not prescribe installing obsolete versions mentioned to explain historical behavior.
|
||||
|
||||
See [coverage and rule development](../development.md) for independent positive/negative fixtures and declared detector limits.
|
||||
@@ -0,0 +1,946 @@
|
||||
<a id="c--c-find-fix-and-verify"></a>
|
||||
|
||||
# C / C++: поиск и исправление
|
||||
|
||||
[English](c-cpp.md) | Русский
|
||||
|
||||
[Вся база](README-RU.md) · [Сканер](../offline-scanner-RU.md) · [Проверка патча](../patch-validation-RU.md)
|
||||
|
||||
28 разделов. Формат: **Поиск → Уязвимый вариант → Исправление → Проверка**.
|
||||
Команды `rg` выполняются в корне локальной копии сервиса и только читают файлы. Субъект/владелец определяется по проверенной сессии, а не данным запроса. Примеры нужно адаптировать к реальным API и контракту.
|
||||
|
||||
Автоматические находки — ограниченные синтаксические сигналы для проверки. AST-анализ не разрешает типы и не отслеживает данные между функциями; regex не заменяет парсер языка. Комментарии, строки и одноимённые пользовательские API могут давать совпадения. Проверьте фактическое исполнение, входные данные, авторизацию и границы доверия.
|
||||
|
||||
<a id="contents"></a>
|
||||
|
||||
## Содержание
|
||||
|
||||
- [C-BOUNDS — Неограниченное копирование C/C++](#c-bounds)
|
||||
- [C-FORMAT — Переменная как format string](#c-format)
|
||||
- [C-SHELL — Shell в C/C++](#c-shell)
|
||||
- [C-PRNG — Обычный PRNG/LCG в возможном секрете](#c-prng)
|
||||
- [C-SNPRINTF-FORMAT — Переменная как формат ограниченного printf](#c-snprintf-format)
|
||||
- [C-RECV-TERMINATOR — Результат recv/read используется как индекс](#c-recv-terminator)
|
||||
- [C-ATOI — atoi без проверки результата](#c-atoi)
|
||||
- [C-REALLOC — Перезапись единственного указателя realloc](#c-realloc)
|
||||
- [C-SIZE-OVERFLOW — Переполнение арифметики размера](#c-size-overflow)
|
||||
- [CPP-LIFETIME — Указатель/view переживает владельца](#cpp-lifetime)
|
||||
- [C-PARTIAL-IO — TCP не сохраняет границы сообщений](#c-partial-io)
|
||||
- [C-SIGNED-LENGTH — Знаковая длина становится большим size_t](#c-signed-length)
|
||||
- [C-DOUBLE-FREE — Несколько владельцев освобождают один объект](#c-double-free)
|
||||
- [C-UNINITIALIZED — Выдача padding и незаполненного хвоста](#c-uninitialized)
|
||||
- [C-TEMPFILE-RACE — Предсказуемое имя и check-then-open](#c-tempfile-race)
|
||||
- [C-JIT-RETURN — Не все пути JIT-функции завершаются](#c-jit-return)
|
||||
- [C-HEADER-SECRET — Особая ветка по заголовку меняет секрет](#c-header-secret)
|
||||
- [C-OBJECT-TOCTOU — Проверили объект, затем заново прочитали изменяемую ссылку](#c-object-toctou)
|
||||
- [C-EXEC-FAILURE — Ошибка exec оставляет дочерний процесс на серверном пути](#c-exec-failure)
|
||||
- [CPP-CACHED-LIFETIME — Кэш хранит указатель после освобождения объекта](#cpp-cached-lifetime)
|
||||
- [C-BLOCK-TAIL — Обработка блока по четыре байта портит хвост буфера](#c-block-tail)
|
||||
- [C-ALLOC-FAILURE — Ошибка выделения памяти превращается в запись по NULL](#c-alloc-failure)
|
||||
- [C-FD-NUL — Утечка fd усиливает off-by-one в read_line](#c-fd-nul)
|
||||
- [C-REENTRANCY-AUTH — Callback между auth-проверкой и подписью](#c-reentrancy-auth)
|
||||
- [C-BUILTIN-TYPES — Не проверен тип аргумента в одной перегрузке builtin](#c-builtin-types)
|
||||
- [C-HASH-INDEX — Индекс хеш-таблицы сдвинут за верхнюю границу](#c-hash-index)
|
||||
- [C-STRNCPY — strncpy может оставить строку без NUL](#c-strncpy)
|
||||
- [C-COPY-LENGTH — Длина копирования берётся напрямую из strlen источника](#c-copy-length)
|
||||
|
||||
<a id="c-bounds"></a>
|
||||
|
||||
<a id="c-bounds-unbounded-cc-copy"></a>
|
||||
|
||||
## C-BOUNDS. Неограниченное копирование C/C++
|
||||
|
||||
**Поиск:** скрипт, правило C-BOUNDS. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain C-BOUNDS. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
~~~c
|
||||
strcpy(destination, source);
|
||||
~~~
|
||||
|
||||
**Исправление:** Проверять ёмкость/длину до копирования. snprintf проверять по результату; механический strncpy не решает всё.
|
||||
|
||||
~~~c
|
||||
size_t n = strlen(source);
|
||||
if (n >= capacity) return ERROR;
|
||||
memcpy(destination, source, n + 1);
|
||||
~~~
|
||||
|
||||
**Проверка:** Пустой/граничный/слишком большой вход; ASan/UBSan если доступны.
|
||||
|
||||
<details>
|
||||
<summary>Развёрнутый пример и ограничения</summary>
|
||||
|
||||
```c
|
||||
/* Vulnerable: capacity and available source length are unchecked. */
|
||||
char dst[64];
|
||||
memcpy(dst, src, client_len);
|
||||
dst[client_len] = '\0';
|
||||
```
|
||||
|
||||
**Патч для поля протокола, которое является C-строкой без встроенного NUL:**
|
||||
|
||||
<!-- example: c-copy-text -->
|
||||
```c
|
||||
#include <stdbool.h>
|
||||
#include <stddef.h>
|
||||
#include <string.h>
|
||||
|
||||
bool copy_text(char *dst, size_t capacity, const char *src,
|
||||
size_t available, size_t requested) {
|
||||
if (dst == NULL || src == NULL || capacity == 0) return false;
|
||||
if (requested > available || requested >= capacity) return false;
|
||||
if (memchr(src, '\0', requested) != NULL) return false;
|
||||
memmove(dst, src, requested);
|
||||
dst[requested] = '\0';
|
||||
return true;
|
||||
}
|
||||
```
|
||||
|
||||
`available` — фактически доступные байты, не заявленный клиентом размер.
|
||||
Знаковую длину проверить на отрицательность **до** перевода в `size_t`.
|
||||
`memmove` допускает перекрытие; при отказе функция не меняет dst. Вызывающий
|
||||
код обязан обработать `false`, а не отправлять прежнее содержимое буфера.
|
||||
|
||||
**Проверить:** пустая строка, capacity−1, capacity, недостаточный src,
|
||||
нулевая вместимость, NUL внутри текста; при отказе буфер не изменён.
|
||||
Для бинарных данных встроенный NUL допустим: нужен иной контракт с явной длиной.
|
||||
Молчаливое усечение через `strncpy` может испортить ID/данные checker.
|
||||
|
||||
</details>
|
||||
|
||||
<a id="c-format"></a>
|
||||
|
||||
<a id="c-format-variable-used-as-a-format-string"></a>
|
||||
|
||||
## C-FORMAT. Переменная как format string
|
||||
|
||||
**Поиск:** скрипт, правило C-FORMAT. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain C-FORMAT. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
~~~c
|
||||
printf(message);
|
||||
~~~
|
||||
|
||||
**Исправление:** Фиксированный формат и проверенные аргументы; бинарным данным явная длина.
|
||||
|
||||
~~~c
|
||||
printf("%s", message);
|
||||
~~~
|
||||
|
||||
**Проверка:** Символы процента печатаются текстом.
|
||||
|
||||
<details>
|
||||
<summary>Развёрнутый пример и ограничения</summary>
|
||||
|
||||
```c
|
||||
/* Vulnerable: message controls the format and argument interpretation. */
|
||||
printf(message);
|
||||
```
|
||||
|
||||
**Патч, если message — корректная NUL-терминированная строка:**
|
||||
|
||||
<!-- example: c-write-message -->
|
||||
```c
|
||||
#include <stdbool.h>
|
||||
#include <stdio.h>
|
||||
|
||||
bool write_message(FILE *out, const char *message) {
|
||||
if (out == NULL || message == NULL) return false;
|
||||
return fputs(message, out) != EOF;
|
||||
}
|
||||
```
|
||||
|
||||
Альтернатива — `fprintf(out, "%s", message)` с фиксированным форматом.
|
||||
Для сетевого буфера с известной длиной использовать проверенный размер и
|
||||
`fwrite`, не предполагать наличие NUL. Ошибку записи обработать отдельно.
|
||||
|
||||
**Проверить:** строка с `%s`, `%%` и Unicode выводится буквально; пустая строка
|
||||
допустима; текст не получает лишний перевод строки, если это важно протоколу.
|
||||
|
||||
</details>
|
||||
|
||||
<a id="c-shell"></a>
|
||||
|
||||
<a id="c-shell-cc-shell-execution"></a>
|
||||
|
||||
## C-SHELL. Shell в C/C++
|
||||
|
||||
**Поиск:** скрипт, правило C-SHELL. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain C-SHELL. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
~~~c
|
||||
system(command);
|
||||
~~~
|
||||
|
||||
**Исправление:** execve/posix_spawn с фиксированной программой/argv; проверить аргументы и ошибки.
|
||||
|
||||
~~~c
|
||||
run_fixed_tool(validated_filename); // fixed executable + argv inside
|
||||
~~~
|
||||
|
||||
**Проверка:** Спецсимволы не интерпретируются shell.
|
||||
|
||||
<a id="c-prng"></a>
|
||||
|
||||
<a id="c-prng-ordinary-prnglcg-near-a-possible-secret"></a>
|
||||
|
||||
## C-PRNG. Обычный PRNG/LCG в возможном секрете
|
||||
|
||||
**Поиск:** скрипт, правило C-PRNG. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain C-PRNG. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
~~~c
|
||||
srand((unsigned)time(NULL));
|
||||
token = rand();
|
||||
~~~
|
||||
|
||||
**Исправление:** Для секрета системный CSPRNG/поддержанная криптобиблиотека, проверка результата. Обычная игровая случайность может использовать PRNG.
|
||||
|
||||
~~~c
|
||||
if (!fill_from_os_csprng(token, sizeof token)) return ERROR; // implement using supported OS/library API
|
||||
~~~
|
||||
|
||||
**Проверка:** Нет seed от времени/const и предсказуемого fallback; формат токена совместим.
|
||||
|
||||
**Вариант A/D:** Идентификатор доступа из LCG со временем в seed. **ENOWARS / piratesay, автор.** Идентификатор разрешал сменить пользователя,
|
||||
а генератор зависел от времени старта.
|
||||
|
||||
**Патч:** системный CSPRNG и серверная привязка credential к пользователю.
|
||||
Скрытый константный seed не является надёжным исправлением.
|
||||
**Тест:** новые идентификаторы/старые сессии по плану перехода, ошибка источника
|
||||
энтропии без fallback. **Поиск:** C-PRNG; самодельные генераторы требуют чтения.
|
||||
|
||||
[исходник/разбор 1](https://github.com/enowars/enowars8-service-piratesay/blob/32973478dbe903d0a2446539ecbddf3b1c334e60/documentation/README.md); [исходник/разбор 2](https://github.com/enowars/enowars8-service-piratesay/blob/32973478dbe903d0a2446539ecbddf3b1c334e60/service_source/src/cli.c); [исходник/разбор 3](https://github.com/enowars/enowars8-service-piratesay/blob/32973478dbe903d0a2446539ecbddf3b1c334e60/service_source/src/session.c).
|
||||
|
||||
<a id="c-snprintf-format"></a>
|
||||
|
||||
<a id="c-snprintf-format-variable-format-in-bounded-printf"></a>
|
||||
|
||||
## C-SNPRINTF-FORMAT. Переменная как формат ограниченного printf
|
||||
|
||||
**Поиск:** скрипт, правило C-SNPRINTF-FORMAT. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain C-SNPRINTF-FORMAT. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
~~~c
|
||||
snprintf(out, capacity, message);
|
||||
~~~
|
||||
|
||||
**Исправление:** Фиксированный формат. Лимит размера буфера не делает недоверенную format string безопасной; проследить собственные wrappers/macros.
|
||||
|
||||
~~~c
|
||||
snprintf(out, capacity, "%s", message);
|
||||
~~~
|
||||
|
||||
**Проверка:** Проценты выводятся как текст; длина/усечение обработаны; внутренний wrapper может оставаться сигналом.
|
||||
|
||||
**Вариант A/D:** Format string внутри «безопасной» обёртки. **ENOWARS / piratesay, автор.** Ограниченная запись в буфер и фильтрация
|
||||
нескольких спецификаторов не мешали следующему слою снова интерпретировать
|
||||
пользовательский текст как формат.
|
||||
|
||||
**Патч:** фиксированный формат на последнем sink, данные отдельным аргументом;
|
||||
проследить macro → wrapper → printf-family. **Тест:** проценты печатаются
|
||||
буквально, усечение обрабатывается. **Поиск:** C-FORMAT, C-SNPRINTF-FORMAT;
|
||||
произвольные имена обёрток автоматически не распознаются.
|
||||
|
||||
[исходник/разбор 1](https://github.com/enowars/enowars8-service-piratesay/blob/32973478dbe903d0a2446539ecbddf3b1c334e60/documentation/README.md); [исходник/разбор 2](https://github.com/enowars/enowars8-service-piratesay/blob/32973478dbe903d0a2446539ecbddf3b1c334e60/service_source/src/cli.c); [исходник/разбор 3](https://github.com/enowars/enowars8-service-piratesay/blob/32973478dbe903d0a2446539ecbddf3b1c334e60/service_source/src/session.c).
|
||||
|
||||
<a id="c-recv-terminator"></a>
|
||||
|
||||
<a id="c-recv-terminator-recvread-result-used-as-an-index"></a>
|
||||
|
||||
## C-RECV-TERMINATOR. Результат recv/read используется как индекс
|
||||
|
||||
**Поиск:** скрипт, правило C-RECV-TERMINATOR. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain C-RECV-TERMINATOR. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
~~~c
|
||||
n = recv(fd, buffer, sizeof buffer, 0);
|
||||
buffer[n] = '\0';
|
||||
~~~
|
||||
|
||||
**Исправление:** Оставить место для NUL, проверить отрицательную длину/EOF до индексации, учитывать неполное чтение. Сигнал может остаться на правильном коде.
|
||||
|
||||
~~~c
|
||||
ssize_t n = recv(fd, buffer, sizeof buffer - 1, 0);
|
||||
if (n <= 0) return ERROR;
|
||||
buffer[n] = '\0';
|
||||
~~~
|
||||
|
||||
**Проверка:** recv=-1, EOF, полный буфер, короткое чтение и обычное сообщение.
|
||||
|
||||
<a id="c-atoi"></a>
|
||||
|
||||
<a id="c-atoi-atoi-without-checked-conversion"></a>
|
||||
|
||||
## C-ATOI. atoi без проверки результата
|
||||
|
||||
**Поиск:** скрипт, правило C-ATOI. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain C-ATOI. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
~~~c
|
||||
int size = atoi(input);
|
||||
~~~
|
||||
|
||||
**Исправление:** Полный разбор числа: знак, диапазон, end pointer и errno; проверить арифметику до allocation/copy.
|
||||
|
||||
~~~c
|
||||
// use strtol/strtoull with errno, end pointer, sign and application bounds checks
|
||||
~~~
|
||||
|
||||
**Проверка:** Пусто, хвост текста, отрицательное число, overflow, граничный допустимый размер.
|
||||
|
||||
**Основание:** [первичный материал](https://cmu-sei.github.io/secure-coding-standards/sei-cert-c-coding-standard/rules/error-handling-err/err34-c/).
|
||||
|
||||
<a id="c-realloc"></a>
|
||||
|
||||
<a id="c-realloc-overwriting-the-only-pointer-with-realloc"></a>
|
||||
|
||||
## C-REALLOC. Перезапись единственного указателя realloc
|
||||
|
||||
**Поиск:** скрипт, правило C-REALLOC. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain C-REALLOC. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
~~~c
|
||||
buffer = realloc(buffer, size);
|
||||
~~~
|
||||
|
||||
**Исправление:** Проверенный ненулевой size, временный указатель и обработка ошибки. Отдельно обработать size=0 по контракту, не полагаться на переносимую семантику realloc(p,0).
|
||||
|
||||
~~~c
|
||||
void *next = realloc(buffer, size);
|
||||
if (next == NULL) { /* preserve buffer; handle error */ }
|
||||
else { buffer = next; }
|
||||
~~~
|
||||
|
||||
**Проверка:** Fault injection allocation error сохраняет старый buffer; нет утечки/double free.
|
||||
|
||||
**Основание:** [первичный материал](https://cmu-sei.github.io/secure-coding-standards/sei-cert-c-coding-standard/recommendations/memory-management-mem/mem04-c/).
|
||||
|
||||
<a id="c-size-overflow"></a>
|
||||
|
||||
<a id="c-size-overflow-size-arithmetic-overflow"></a>
|
||||
|
||||
## C-SIZE-OVERFLOW. Переполнение арифметики размера
|
||||
|
||||
**Поиск:** вручную; отдельного правила сканера нет.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'malloc|calloc|resize|reserve|sizeof|memcpy' .
|
||||
~~~
|
||||
|
||||
Перед умножением/сложением проверить SIZE_MAX и application limit; знак до cast.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
malloc(count * sizeof(Item)) выделяет меньше, чем последующее копирование после overflow.
|
||||
|
||||
**Исправление:** Проверенное умножение/сложение и фактическая capacity; отдельно обработать ноль и allocation failure.
|
||||
|
||||
**Проверка:** Ноль, граница, переполнение произведения/суммы, отрицательный вход и прежний буфер.
|
||||
|
||||
<details>
|
||||
<summary>Развёрнутый пример и ограничения</summary>
|
||||
|
||||
```c
|
||||
/* Vulnerable: count * sizeof(Item) can overflow. */
|
||||
Item *items = malloc(count * sizeof(*items));
|
||||
```
|
||||
|
||||
**Патч проверки арифметики и согласованного лимита:**
|
||||
|
||||
<!-- example: c-array-bytes -->
|
||||
```c
|
||||
#include <stdbool.h>
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
|
||||
bool array_bytes(size_t count, size_t item_size, size_t max_bytes, size_t *out) {
|
||||
if (out == NULL || item_size == 0) return false;
|
||||
if (count > SIZE_MAX / item_size) return false;
|
||||
size_t total = count * item_size;
|
||||
if (total > max_bytes) return false;
|
||||
*out = total;
|
||||
return true;
|
||||
}
|
||||
```
|
||||
|
||||
Перед `malloc` вызвать с `sizeof(*items)` и лимитом по контракту; проверить
|
||||
результат выделения. Нулевой count обрабатывать отдельно согласно протоколу:
|
||||
не выводить ошибку только из того, что `malloc(0)` вернул NULL. Размер out при
|
||||
отказе не использовать. При добавлении заголовка/терминатора проверить также
|
||||
сложение; эта функция проверяет только произведение.
|
||||
|
||||
**Проверить:** ноль, единица, ровно допустимый бюджет, превышение бюджета,
|
||||
произведение больше SIZE_MAX; ошибка не ведёт к копированию в старый/NULL-буфер.
|
||||
|
||||
</details>
|
||||
|
||||
<a id="cpp-lifetime"></a>
|
||||
|
||||
<a id="cpp-lifetime-a-pointer-or-view-outlives-its-owner"></a>
|
||||
|
||||
## CPP-LIFETIME. Указатель/view переживает владельца
|
||||
|
||||
**Поиск:** вручную; отдельного правила сканера нет.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'c_str\(|string_view|span|return.*data|return.*&' .
|
||||
~~~
|
||||
|
||||
Найти владельца данных и его destruction/reallocation; проверить async callback и lambda captures.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
Возвращён c_str временной string или string_view локального буфера.
|
||||
|
||||
**Исправление:** Вернуть владеющий объект/копию; при async передать владение до завершения, view сам по себе lifetime не продлевает.
|
||||
|
||||
**Проверка:** Результат существует после возврата, следующий вызов его не портит, async дожидается окончания.
|
||||
|
||||
<details>
|
||||
<summary>Развёрнутый пример и ограничения</summary>
|
||||
|
||||
```cpp
|
||||
// Vulnerable: the temporary string dies before the returned pointer is used.
|
||||
const char* make_label(const std::string& name) {
|
||||
return (std::string("hello ") + name).c_str();
|
||||
}
|
||||
```
|
||||
|
||||
**Патч: вернуть владеющий объект, а не указатель в уничтоженное хранилище:**
|
||||
|
||||
<!-- example: cpp-label -->
|
||||
```cpp
|
||||
#include <string>
|
||||
|
||||
std::string make_label(const std::string& name) {
|
||||
return std::string("hello ") + name;
|
||||
}
|
||||
```
|
||||
|
||||
Вызывающий код хранит `std::string label = make_label(name);`. Его `c_str()`
|
||||
можно передать синхронному API, которое не удерживает указатель дольше жизни
|
||||
строки. Для асинхронной операции нужно передать владение/копию. `string_view`
|
||||
сам по себе не продлевает жизнь строки и не является исправлением.
|
||||
|
||||
**Проверить:** результат существует после выхода из функции; последовательные
|
||||
вызовы не меняют прошлые результаты; пустое имя и Unicode; асинхронный путь
|
||||
удерживает данные до завершения операции.
|
||||
|
||||
</details>
|
||||
|
||||
<a id="c-partial-io"></a>
|
||||
|
||||
<a id="c-partial-io-tcp-does-not-preserve-message-boundaries"></a>
|
||||
|
||||
## C-PARTIAL-IO. TCP не сохраняет границы сообщений
|
||||
|
||||
**Поиск:** вручную; отдельного правила сканера нет.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'recv|read\(|send|write\(|Content-Length|length' .
|
||||
~~~
|
||||
|
||||
Сверить frame length с накопленными байтами и циклы short read/write, EINTR/EOF.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
Один recv принят за целый запрос; send передал только часть приватного ответа, следующий кадр склеился.
|
||||
|
||||
**Исправление:** Явный framing и ограниченный накопительный буфер, проверка частичных операций и timeout; не менять протокол checker.
|
||||
|
||||
**Проверка:** Фрагментация по каждому байту, два кадра вместе, EOF посредине и обычное сообщение.
|
||||
|
||||
<a id="c-signed-length"></a>
|
||||
|
||||
<a id="c-signed-length-signed-lengths-become-huge-size_t-values"></a>
|
||||
|
||||
## C-SIGNED-LENGTH. Знаковая длина становится большим size_t
|
||||
|
||||
**Поиск:** вручную; отдельного правила сканера нет.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'ssize_t|size_t|uint32_t|int.*len|memcpy|recv' .
|
||||
~~~
|
||||
|
||||
Проследить все casts между чтением/разбором и allocation/index.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
Отрицательный read или пользовательский int приводится к unsigned до проверки.
|
||||
|
||||
**Исправление:** Проверить error/sign/range до преобразования, сверить вместимость источника и приёмника.
|
||||
|
||||
**Проверка:** read=-1, EOF, отрицательное поле, максимум и нормальный payload.
|
||||
|
||||
<a id="c-double-free"></a>
|
||||
|
||||
<a id="c-double-free-multiple-owners-free-the-same-object"></a>
|
||||
|
||||
## C-DOUBLE-FREE. Несколько владельцев освобождают один объект
|
||||
|
||||
**Поиск:** вручную; отдельного правила сканера нет.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'free\(|delete|unique_ptr|shared_ptr|goto.*fail' .
|
||||
~~~
|
||||
|
||||
Пройти success/error cleanup и передачу владения; найти два shared_ptr из одного raw pointer.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
Error path и внешний caller освобождают объект дважды, либо reset уничтожает ещё используемый объект.
|
||||
|
||||
**Исправление:** Единый owner/RAII и явная передача владения; обнуление одного alias не исправляет остальные.
|
||||
|
||||
**Проверка:** Ошибка на каждом шаге создания, повторный cleanup, нормальный жизненный цикл.
|
||||
|
||||
<a id="c-uninitialized"></a>
|
||||
|
||||
<a id="c-uninitialized-exposing-padding-or-uninitialized-tails"></a>
|
||||
|
||||
## C-UNINITIALIZED. Выдача padding и незаполненного хвоста
|
||||
|
||||
**Поиск:** вручную; отдельного правила сканера нет.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'malloc|struct|send|write|sizeof|memcpy' .
|
||||
~~~
|
||||
|
||||
Сравнить реально заполненные поля с sizeof отправляемого struct и padding.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
send(fd, &record, sizeof record, ...) выдаёт padding либо остаток предыдущего содержимого.
|
||||
|
||||
**Исправление:** Явная сериализация полей и длины, инициализация буфера; не публиковать native layout как протокол.
|
||||
|
||||
**Проверка:** Разные компиляторы/layout, короткий ввод, отсутствие незаполненных байтов в ответе.
|
||||
|
||||
<a id="c-tempfile-race"></a>
|
||||
|
||||
<a id="c-tempfile-race-temporary-filename-without-atomic-creation"></a>
|
||||
|
||||
## C-TEMPFILE-RACE. Предсказуемое имя и check-then-open
|
||||
|
||||
**Поиск:** скрипт, правило C-TEMPFILE-RACE. Запуск: python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain C-TEMPFILE-RACE. Regex: tmpnam/tempnam/mktemp. Самописные схемы имени, reopen после mkstemp и TOCTOU по каталогу остаются ручными.
|
||||
|
||||
Дополнительный ручной поиск для непокрытых форм:
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'tmpnam|mktemp|access\(|stat\(|fopen|open\(' .
|
||||
~~~
|
||||
|
||||
Проследить промежуток existence check → open и права родительского каталога.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
Имя в общем /tmp проверено, затем открыто с перезаписью по подменённой ссылке.
|
||||
|
||||
**Исправление:** Атомарное создание mkstemp/open с O_EXCL и нужной политикой links, private temp dir, restrictive mode; descriptor-based работа.
|
||||
|
||||
**Проверка:** Коллизия имени, symlink, параллельное создание, ошибка записи и cleanup.
|
||||
|
||||
|
||||
**Сигнал сканера — пример до:**
|
||||
|
||||
~~~native
|
||||
char name[L_tmpnam];
|
||||
tmpnam(name);
|
||||
FILE *f = fopen(name, "w");
|
||||
~~~
|
||||
|
||||
**Шаблон исправления:**
|
||||
|
||||
~~~native
|
||||
char name[] = "/tmp/app-XXXXXX";
|
||||
int fd = mkstemp(name);
|
||||
if (fd < 0) return ERROR;
|
||||
unlink(name);
|
||||
/* use fd; close(fd) on every exit */
|
||||
~~~
|
||||
|
||||
Первичная документация: [документация 1](https://pubs.opengroup.org/onlinepubs/9799919799/functions/mkstemp.html).
|
||||
|
||||
<a id="c-jit-return"></a>
|
||||
|
||||
<a id="c-jit-return-not-every-jit-function-path-terminates"></a>
|
||||
|
||||
## C-JIT-RETURN. Не все пути JIT-функции завершаются
|
||||
|
||||
**Поиск:** вручную; отдельного правила сканера нет.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'return|emit|jit|compile|bytecode' .
|
||||
~~~
|
||||
|
||||
Построить выходы CFG функции: условный return не закрывает другую ветвь и fall-through.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
**Основание:** dcs, авторский разбор RuCTF: условный return ошибочно считался
|
||||
достаточным; выполнение продолжалось за телом функции.
|
||||
**Искать:** самодельные VM/JIT/DSL, проверка return через поиск узла вместо
|
||||
анализа достижимости, размещение констант рядом с инструкциями.
|
||||
|
||||
**Исправление:** анализ графа потока: каждый достижимый выход обязан возвращать
|
||||
значение либо завершаться определённой ошибкой. Разделять код и данные,
|
||||
проверять индексы/типы до генерации.
|
||||
|
||||
**Проверка:** обе ветви условия, вложенные
|
||||
условия, пустая функция и штатные вычисления. Запретить JIT целиком можно
|
||||
только если сохранён функциональный контракт.
|
||||
|
||||
**Вариант A/D:** Основание и версия: [исходник/разбор 1](https://github.com/HackerDom/ructf-finals-2023/blob/a7442769909e08c39716cb18d3d1c3a99324bbf8/writeups/dcs/README.md).
|
||||
|
||||
**Основание:** [первичный материал](https://github.com/HackerDom/ructf-finals-2023/blob/a7442769909e08c39716cb18d3d1c3a99324bbf8/writeups/dcs/README.md).
|
||||
|
||||
<a id="c-header-secret"></a>
|
||||
|
||||
<a id="c-header-secret-a-special-header-branch-changes-a-secret"></a>
|
||||
|
||||
## C-HEADER-SECRET. Особая ветка по заголовку меняет секрет
|
||||
|
||||
**Поиск:** вручную; отдельного правила сканера нет.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'getenv|HTTP_USER_AGENT|SECRET_KEY|constructor' .
|
||||
~~~
|
||||
|
||||
Прочитать init/constructor и ветви debug/test: клиентский заголовок не должен менять ключ.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
**Основание:** reversaar, анализ C-исходника saarCTF: специальный путь,
|
||||
связанный с HTTP_USER_AGENT, изменял SECRET_KEY.
|
||||
**Искать:** constructor/init-хуки, getenv заголовков, magic constants,
|
||||
debug/test/admin-ветки в release, скрытые переключатели подписи.
|
||||
|
||||
**Исправление:** удалить именно посторонний переход состояния; конфигурация секретов
|
||||
не зависит от клиентского запроса. Просмотреть код запуска, не только маршруты.
|
||||
|
||||
**Проверка:** разные заголовки не меняют ключ, права и формат хранения; обычная
|
||||
инициализация сохранена. Сканер не содержит сигнатуры конкретного magic value;
|
||||
связь входа с секретом проверяется вручную.
|
||||
|
||||
**Вариант A/D:** Основание и версия: [исходник/разбор 1](https://github.com/saarsec/saarctf-2024/blob/3a06d18974ca177c6dd251a11bdf9b4b334f382a/reversaar/service/src/array.c).
|
||||
|
||||
**Основание:** [первичный материал](https://github.com/saarsec/saarctf-2024/blob/3a06d18974ca177c6dd251a11bdf9b4b334f382a/reversaar/service/src/array.c).
|
||||
|
||||
<a id="c-object-toctou"></a>
|
||||
|
||||
<a id="c-object-toctou-re-reading-mutable-references-after-authorization"></a>
|
||||
|
||||
## C-OBJECT-TOCTOU. Проверили объект, затем заново прочитали изменяемую ссылку
|
||||
|
||||
**Поиск:** вручную; отдельного правила сканера нет.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'background|fork|exec|open|read' .
|
||||
~~~
|
||||
|
||||
Найти повторное чтение изменяемого объекта после проверки и внешнего вызова; сверить identity/snapshot.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
**RuCTF / memos, автор.** Между проверкой доступа к фону и чтением фона
|
||||
выполнялась внешняя операция; другой запрос мог заменить выбранный объект.
|
||||
|
||||
**Исправление:** работать с тем же проверенным снимком/дескриптором, либо атомарно
|
||||
проверять версию перед использованием.
|
||||
|
||||
**Проверка:** контролируемое чередование
|
||||
двух запросов через барьер, штатная длительная обработка.
|
||||
|
||||
**Вариант A/D:** Основание и версия: [исходник/разбор 1](https://github.com/HackerDom/ructf-2023/blob/0cc333e44f2ba6908ff6c5d613146e3b00173315/writeups/memos/README.md).
|
||||
|
||||
**Основание:** [первичный материал](https://github.com/HackerDom/ructf-2023/blob/0cc333e44f2ba6908ff6c5d613146e3b00173315/writeups/memos/README.md).
|
||||
|
||||
<a id="c-exec-failure"></a>
|
||||
|
||||
<a id="c-exec-failure-failed-exec-leaves-a-child-on-the-server-path"></a>
|
||||
|
||||
## C-EXEC-FAILURE. Ошибка exec оставляет дочерний процесс на серверном пути
|
||||
|
||||
**Поиск:** вручную; отдельного правила сканера нет.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'fork|execve|execvp|waitpid' .
|
||||
~~~
|
||||
|
||||
Пройти ветвь каждого отрицательного возврата fork/exec и завершение child, включая аргументы сверх лимита.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
**RuCTF / memos, автор.** После неудачного execve дочерний процесс мог продолжить
|
||||
логику сервиса.
|
||||
|
||||
**Исправление:** проверять fork/exec/wait; после ошибки exec в дочерней ветви завершаться
|
||||
через _exit с ошибкой, закрывая лишние дескрипторы.
|
||||
|
||||
**Проверка:** исполняемый файл
|
||||
недоступен, аргументы превышают лимит, fork неуспешен — второй сервер не возникает.
|
||||
|
||||
**Вариант A/D:** Основание и версия: [исходник/разбор 1](https://github.com/HackerDom/ructf-2023/blob/0cc333e44f2ba6908ff6c5d613146e3b00173315/writeups/memos/README.md).
|
||||
|
||||
**Основание:** [первичный материал](https://github.com/HackerDom/ructf-2023/blob/0cc333e44f2ba6908ff6c5d613146e3b00173315/writeups/memos/README.md).
|
||||
|
||||
<a id="cpp-cached-lifetime"></a>
|
||||
|
||||
<a id="cpp-cached-lifetime-cached-pointers-survive-object-destruction"></a>
|
||||
|
||||
## CPP-CACHED-LIFETIME. Кэш хранит указатель после освобождения объекта
|
||||
|
||||
**Поиск:** вручную; отдельного правила сканера нет.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'cache|delete|free|flush|shared_ptr|weak_ptr' .
|
||||
~~~
|
||||
|
||||
Найти владельца cached pointer и момент освобождения; проследить вызов метода после eviction.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
**RuCTF / perune, автор.** Последующий обход кэша вызывал виртуальный метод
|
||||
у освобождённого объекта.
|
||||
|
||||
**Исправление:** явное владение, удаление всех ссылок при destruction, безопасные
|
||||
handles/weak references или проверяемый generation ID.
|
||||
|
||||
**Проверка:** разные порядки
|
||||
создания/удаления/flush, доступный sanitizer; не считать отсутствие падения
|
||||
доказательством.
|
||||
|
||||
**Вариант A/D:** Основание и версия: [исходник/разбор 1](https://github.com/HackerDom/ructf-2023/blob/0cc333e44f2ba6908ff6c5d613146e3b00173315/writeups/perune/readme.md).
|
||||
|
||||
**Основание:** [первичный материал](https://github.com/HackerDom/ructf-2023/blob/0cc333e44f2ba6908ff6c5d613146e3b00173315/writeups/perune/readme.md).
|
||||
|
||||
<a id="c-block-tail"></a>
|
||||
|
||||
<a id="c-block-tail-four-byte-block-processing-corrupts-the-tail"></a>
|
||||
|
||||
## C-BLOCK-TAIL. Обработка блока по четыре байта портит хвост буфера
|
||||
|
||||
**Поиск:** вручную; отдельного правила сканера нет.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'xor|chacha|uint32_t|length|remaining' .
|
||||
~~~
|
||||
|
||||
Проверить обработку остатка длины 1–3 байта при шаге четыре; сопоставить фактическую allocation.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
**ECSC / Diese HSM, автор.** XOR проходил за конец при длине, не кратной слову.
|
||||
|
||||
**Исправление:** полные блоки плюс отдельный ограниченный хвост, проверка выравнивания.
|
||||
|
||||
**Проверка:** длины 0–9, края буфера, canary и допустимые nonce.
|
||||
|
||||
**Вариант A/D:** Основание и версия: [исходник/разбор 1](https://github.com/ECSC2024/ECSC2024-CTF-AD/blob/2a92e17384ad228072a84fb076a35066fe2ffeff/sources/Diese/README.md); [исходник/разбор 2](https://github.com/ECSC2024/ECSC2024-CTF-AD/blob/2a92e17384ad228072a84fb076a35066fe2ffeff/sources/Diese/webapp/src/classes/Utils.class.php); [исходник/разбор 3](https://github.com/ECSC2024/ECSC2024-CTF-AD/blob/2a92e17384ad228072a84fb076a35066fe2ffeff/sources/Diese/hsm/src/msg.c).
|
||||
|
||||
**Основание:** [первичный материал](https://github.com/ECSC2024/ECSC2024-CTF-AD/blob/2a92e17384ad228072a84fb076a35066fe2ffeff/sources/Diese/README.md).
|
||||
|
||||
<a id="c-alloc-failure"></a>
|
||||
|
||||
<a id="c-alloc-failure-allocation-failure-becomes-a-null-write"></a>
|
||||
|
||||
## C-ALLOC-FAILURE. Ошибка выделения памяти превращается в запись по NULL
|
||||
|
||||
**Поиск:** вручную; отдельного правила сканера нет.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'malloc|calloc|alloc|memcpy' .
|
||||
~~~
|
||||
|
||||
Проследить NULL/ошибку allocation до первой записи, включая собственный allocator и адресное пространство firmware.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
**ECSC / Diese HSM, автор + код.** Результат allocator не проверяется;
|
||||
в firmware адрес 0 доступен.
|
||||
|
||||
**Исправление:** checked size arithmetic, лимит сообщения, обработка allocation failure
|
||||
во всей цепочке.
|
||||
|
||||
**Проверка:** отказ каждого выделения и усечённый пакет.
|
||||
|
||||
**Вариант A/D:** Основание и версия: [исходник/разбор 1](https://github.com/ECSC2024/ECSC2024-CTF-AD/blob/2a92e17384ad228072a84fb076a35066fe2ffeff/sources/Diese/README.md); [исходник/разбор 2](https://github.com/ECSC2024/ECSC2024-CTF-AD/blob/2a92e17384ad228072a84fb076a35066fe2ffeff/sources/Diese/webapp/src/classes/Utils.class.php); [исходник/разбор 3](https://github.com/ECSC2024/ECSC2024-CTF-AD/blob/2a92e17384ad228072a84fb076a35066fe2ffeff/sources/Diese/hsm/src/msg.c).
|
||||
|
||||
**Основание:** [первичный материал](https://github.com/ECSC2024/ECSC2024-CTF-AD/blob/2a92e17384ad228072a84fb076a35066fe2ffeff/sources/Diese/README.md).
|
||||
|
||||
<a id="c-fd-nul"></a>
|
||||
|
||||
<a id="c-fd-nul-descriptor-leaks-amplify-a-read_line-off-by-one"></a>
|
||||
|
||||
## C-FD-NUL. Утечка fd усиливает off-by-one в read_line
|
||||
|
||||
**Поиск:** вручную; отдельного правила сканера нет.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'read_line|open|close|fopen|fclose' .
|
||||
~~~
|
||||
|
||||
Просмотреть закрытие fd в ветвях login error и запись NUL при заполненном буфере.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
**ECSC / CookingNonna, автор.** Неудачный login оставлял fd, а терминатор
|
||||
мог записаться за полный буфер.
|
||||
|
||||
**Исправление:** единый cleanup для всех отказов; резервировать байт под NUL, проверять
|
||||
read/EOF и возвращаемые значения open относительно -1.
|
||||
|
||||
**Проверка:** capacity 0/1/max, длинная строка, серия отказов без роста fd.
|
||||
|
||||
**Вариант A/D:** Основание и версия: [исходник/разбор 1](https://github.com/ECSC2024/ECSC2024-CTF-AD/blob/2a92e17384ad228072a84fb076a35066fe2ffeff/sources/CookingNonna/README.md).
|
||||
|
||||
**Основание:** [первичный материал](https://github.com/ECSC2024/ECSC2024-CTF-AD/blob/2a92e17384ad228072a84fb076a35066fe2ffeff/sources/CookingNonna/README.md).
|
||||
|
||||
<a id="c-reentrancy-auth"></a>
|
||||
|
||||
<a id="c-reentrancy-auth-a-callback-runs-between-authorization-and-signing"></a>
|
||||
|
||||
## C-REENTRANCY-AUTH. Callback между auth-проверкой и подписью
|
||||
|
||||
**Поиск:** вручную; отдельного правила сканера нет.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'callback|SignToken|Len|ByRef' .
|
||||
~~~
|
||||
|
||||
Найти вызов пользовательской функции после owner-check; проверить, может ли она менять подписываемые аргументы.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
**ICC / MaScroll, автор.** Переопределяемый Len мог изменить аргумент по ссылке
|
||||
после проверки владельца.
|
||||
|
||||
**Исправление:** валидировать неизменяемую копию, не вызывать пользовательский код
|
||||
между проверкой и чувствительной операцией.
|
||||
|
||||
**Проверка:** callback изменяет исходный объект, но подписывается только проверенный.
|
||||
|
||||
**Вариант A/D:** Основание и версия: [исходник/разбор 1](https://github.com/CybersecNatLab/ICC2023-AD-CTF/blob/8ffa184ff2ce8f648258ed3c02ee2270e8e1c56c/sources/MaScroll/README.md).
|
||||
|
||||
**Основание:** [первичный материал](https://github.com/CybersecNatLab/ICC2023-AD-CTF/blob/8ffa184ff2ce8f648258ed3c02ee2270e8e1c56c/sources/MaScroll/README.md).
|
||||
|
||||
<a id="c-builtin-types"></a>
|
||||
|
||||
<a id="c-builtin-types-one-builtin-overload-omits-argument-type-checks"></a>
|
||||
|
||||
## C-BUILTIN-TYPES. Не проверен тип аргумента в одной перегрузке builtin
|
||||
|
||||
**Поиск:** вручную; отдельного правила сканера нет.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'FastRand|CryptoRand|variant|overload|builtin' .
|
||||
~~~
|
||||
|
||||
Сравнить типы всех аргументов каждой перегрузки, включая общий первый аргумент и error path.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
**ICC / MaScroll, автор.** Вариант вызова генератора пропускал проверку типа,
|
||||
а ошибка памяти затрагивала криптографическое состояние.
|
||||
|
||||
**Исправление:** единая проверка type/arity/length для всех перегрузок, корректные
|
||||
владение и буферы.
|
||||
|
||||
**Проверка:** матрица типов и числа аргументов;
|
||||
ошибка не меняет состояние RNG/подписи.
|
||||
|
||||
**Вариант A/D:** Основание и версия: [исходник/разбор 1](https://github.com/CybersecNatLab/ICC2023-AD-CTF/blob/8ffa184ff2ce8f648258ed3c02ee2270e8e1c56c/sources/MaScroll/README.md).
|
||||
|
||||
**Основание:** [первичный материал](https://github.com/CybersecNatLab/ICC2023-AD-CTF/blob/8ffa184ff2ce8f648258ed3c02ee2270e8e1c56c/sources/MaScroll/README.md).
|
||||
|
||||
<a id="c-hash-index"></a>
|
||||
|
||||
<a id="c-hash-index-hash-table-indices-exceed-the-upper-boundary"></a>
|
||||
|
||||
## C-HASH-INDEX. Индекс хеш-таблицы сдвинут за верхнюю границу
|
||||
|
||||
**Поиск:** вручную; отдельного правила сканера нет.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'TABLE_SIZE|capacity|hash|table\[' .
|
||||
~~~
|
||||
|
||||
Для каждой ветви вычислить min/max индекса и размер массива; проверить insert/find и переключение структур.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
**DEF CON / bisbee, код + header.** Формула остаток по TABLE_SIZE плюс один
|
||||
используется для массива из TABLE_SIZE элементов.
|
||||
|
||||
**Исправление:** индекс в диапазоне [0, capacity), согласованный со всеми операциями;
|
||||
проверить перенос между list и hashmap и счётчики при обновлении.
|
||||
|
||||
**Проверка:** первый/последний bucket, collision, повторное обновление, переключение
|
||||
представления.
|
||||
|
||||
**Вариант A/D:** Основание и версия: [исходник/разбор 1](https://github.com/Nautilus-Institute/finals-2024/blob/f17456fed4ff40e6f4f1237ed4b82c242e52ec67/bisbee/src/service/src/main.rs); [исходник/разбор 2](https://github.com/Nautilus-Institute/finals-2024/blob/f17456fed4ff40e6f4f1237ed4b82c242e52ec67/bisbee/src/db/kv.c); [исходник/разбор 3](https://github.com/Nautilus-Institute/finals-2024/blob/f17456fed4ff40e6f4f1237ed4b82c242e52ec67/bisbee/src/db/kv.h); [исходник/разбор 4](https://github.com/Nautilus-Institute/finals-2024/blob/f17456fed4ff40e6f4f1237ed4b82c242e52ec67/bisbee/src/db/kv_hashmap.c); [исходник/разбор 5](https://github.com/Nautilus-Institute/finals-2024/blob/f17456fed4ff40e6f4f1237ed4b82c242e52ec67/bisbee/src/db/kv_hashmap.h); [исходник/разбор 6](https://github.com/Nautilus-Institute/finals-2024/blob/f17456fed4ff40e6f4f1237ed4b82c242e52ec67/bisbee/src/db/kv_list.c).
|
||||
|
||||
**Основание:** [первичный материал](https://github.com/Nautilus-Institute/finals-2024/blob/f17456fed4ff40e6f4f1237ed4b82c242e52ec67/bisbee/src/service/src/main.rs).
|
||||
|
||||
<a id="c-strncpy"></a>
|
||||
|
||||
<a id="c-strncpy-strncpy-may-omit-nul-termination"></a>
|
||||
|
||||
## C-STRNCPY. strncpy может оставить строку без NUL
|
||||
|
||||
**Поиск:** скрипт, правило C-STRNCPY. Запуск: python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain C-STRNCPY. Regex: strncpy. Наличие последующего NUL и фактическая ёмкость анализируются вручную; memcpy без проверки длины не является исправлением.
|
||||
|
||||
**Уязвимый вариант:** strncpy при длинном входе не добавляет терминатор; последующее строковое API читает за буфером.
|
||||
|
||||
~~~native
|
||||
strncpy(out, input, sizeof out);
|
||||
puts(out);
|
||||
~~~
|
||||
|
||||
**Исправление:** Выбрать контракт: отклонять слишком длинный вход или явно обрезать с местом для NUL. Для бинарных данных передавать длину вместо строкового API.
|
||||
|
||||
~~~native
|
||||
size_t n = bounded_input_length;
|
||||
if (n >= sizeof out) return ERROR;
|
||||
memcpy(out, input, n);
|
||||
out[n] = '\0';
|
||||
~~~
|
||||
|
||||
**Проверка:** Вход длиной capacity-1/capacity/capacity+1 и пустой не вызывает чтения за границей; тихое усечение не меняет identity.
|
||||
|
||||
Первичная документация: [документация 1](https://pubs.opengroup.org/onlinepubs/9799919799/functions/strncpy.html).
|
||||
|
||||
<a id="c-copy-length"></a>
|
||||
|
||||
<a id="c-copy-length-copy-length-comes-directly-from-source-strlen"></a>
|
||||
|
||||
## C-COPY-LENGTH. Длина копирования берётся напрямую из strlen источника
|
||||
|
||||
**Поиск:** правило сканера C-COPY-LENGTH. Точный контракт детектора: `--explain C-COPY-LENGTH`. Regex с лексическими исключениями: memcpy/memmove с простыми первыми двумя аргументами и strlen/strnlen непосредственно в выражении длины. Не доказывает отсутствие предшествующих проверок или фактические размеры буферов; одноимённые пользовательские API и макросы требуют проверки.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
~~~native
|
||||
memcpy(dest, input, strlen(input) + 1);
|
||||
~~~
|
||||
|
||||
**Исправление:** Перед копированием проверьте доступную для чтения длину источника и ёмкость назначения, включая завершающий символ и переполнение арифметики.
|
||||
|
||||
~~~native
|
||||
size_t n = validated_length;
|
||||
if (n >= capacity) return ERROR;
|
||||
memcpy(dest, input, n + 1);
|
||||
~~~
|
||||
|
||||
**Проверка:** Проверьте пустой ввод, границы ёмкости, отсутствие завершающего символа и переполнение; по возможности используйте санитайзеры.
|
||||
|
||||
[Первичный источник 1](https://pubs.opengroup.org/onlinepubs/9799919799/functions/memcpy.html)
|
||||
@@ -0,0 +1,824 @@
|
||||
# C / C++: find, fix and verify
|
||||
|
||||
English | [Русский](c-cpp-RU.md)
|
||||
|
||||
[Catalog](README.md) · [Scanner](../offline-scanner.md) · [Patch verification](../patch-validation.md)
|
||||
|
||||
28 sections. Each follows **Search → Vulnerable example → Fix → Verification**.
|
||||
Run `rg` from a local service checkout; searches only read files. Derive the actor/owner from a verified session, not request data. Adapt examples to the actual API and contract.
|
||||
|
||||
## Contents
|
||||
|
||||
- [C-BOUNDS — Unbounded C/C++ copy](#c-bounds)
|
||||
- [C-FORMAT — Variable used as a format string](#c-format)
|
||||
- [C-SHELL — C/C++ shell execution](#c-shell)
|
||||
- [C-PRNG — Ordinary PRNG/LCG near a possible secret](#c-prng)
|
||||
- [C-SNPRINTF-FORMAT — Variable format in bounded printf](#c-snprintf-format)
|
||||
- [C-RECV-TERMINATOR — recv/read result used as an index](#c-recv-terminator)
|
||||
- [C-ATOI — atoi without checked conversion](#c-atoi)
|
||||
- [C-REALLOC — Overwriting the only pointer with realloc](#c-realloc)
|
||||
- [C-SIZE-OVERFLOW — Size arithmetic overflow](#c-size-overflow)
|
||||
- [CPP-LIFETIME — A pointer or view outlives its owner](#cpp-lifetime)
|
||||
- [C-PARTIAL-IO — TCP does not preserve message boundaries](#c-partial-io)
|
||||
- [C-SIGNED-LENGTH — Signed lengths become huge size_t values](#c-signed-length)
|
||||
- [C-DOUBLE-FREE — Multiple owners free the same object](#c-double-free)
|
||||
- [C-UNINITIALIZED — Exposing padding or uninitialized tails](#c-uninitialized)
|
||||
- [C-TEMPFILE-RACE — Temporary filename without atomic creation](#c-tempfile-race)
|
||||
- [C-JIT-RETURN — Not every JIT function path terminates](#c-jit-return)
|
||||
- [C-HEADER-SECRET — A special header branch changes a secret](#c-header-secret)
|
||||
- [C-OBJECT-TOCTOU — Re-reading mutable references after authorization](#c-object-toctou)
|
||||
- [C-EXEC-FAILURE — Failed exec leaves a child on the server path](#c-exec-failure)
|
||||
- [CPP-CACHED-LIFETIME — Cached pointers survive object destruction](#cpp-cached-lifetime)
|
||||
- [C-BLOCK-TAIL — Four-byte block processing corrupts the tail](#c-block-tail)
|
||||
- [C-ALLOC-FAILURE — Allocation failure becomes a NULL write](#c-alloc-failure)
|
||||
- [C-FD-NUL — Descriptor leaks amplify a read_line off-by-one](#c-fd-nul)
|
||||
- [C-REENTRANCY-AUTH — A callback runs between authorization and signing](#c-reentrancy-auth)
|
||||
- [C-BUILTIN-TYPES — One builtin overload omits argument-type checks](#c-builtin-types)
|
||||
- [C-HASH-INDEX — Hash-table indices exceed the upper boundary](#c-hash-index)
|
||||
- [C-STRNCPY — strncpy may omit NUL termination](#c-strncpy)
|
||||
- [C-COPY-LENGTH — Copy length comes directly from source strlen](#c-copy-length)
|
||||
|
||||
<a id="c-bounds"></a>
|
||||
|
||||
## C-BOUNDS. Unbounded C/C++ copy
|
||||
|
||||
**Search:** scanner rule C-BOUNDS. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain C-BOUNDS` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
~~~c
|
||||
strcpy(destination, source);
|
||||
~~~
|
||||
|
||||
**Fix:** Check length/capacity before copying and check snprintf's result; mechanical strncpy replacement is insufficient.
|
||||
|
||||
~~~c
|
||||
size_t n = strlen(source);
|
||||
if (n >= capacity) return ERROR;
|
||||
memcpy(destination, source, n + 1);
|
||||
~~~
|
||||
|
||||
**Verification:** Test empty, boundary and oversized input; use ASan/UBSan where available.
|
||||
|
||||
<details>
|
||||
<summary>Expanded example and limitations</summary>
|
||||
|
||||
```c
|
||||
/* Vulnerable: capacity and available source length are unchecked. */
|
||||
char dst[64];
|
||||
memcpy(dst, src, client_len);
|
||||
dst[client_len] = '\0';
|
||||
```
|
||||
|
||||
**Patch for a protocol field defined as a C string without embedded NUL:**
|
||||
|
||||
<!-- example: c-copy-text -->
|
||||
|
||||
```c
|
||||
#include <stdbool.h>
|
||||
#include <stddef.h>
|
||||
#include <string.h>
|
||||
|
||||
bool copy_text(char *dst, size_t capacity, const char *src,
|
||||
size_t available, size_t requested) {
|
||||
if (dst == NULL || src == NULL || capacity == 0) return false;
|
||||
if (requested > available || requested >= capacity) return false;
|
||||
if (memchr(src, '\0', requested) != NULL) return false;
|
||||
memmove(dst, src, requested);
|
||||
dst[requested] = '\0';
|
||||
return true;
|
||||
}
|
||||
```
|
||||
|
||||
available means bytes actually accessible, not the client's claimed size. Reject negative signed lengths **before** conversion to size_t. memmove permits overlap; failure leaves dst unchanged. The caller must handle false rather than transmit old buffer contents.
|
||||
|
||||
**Check:** Empty string, capacity−1, capacity, insufficient source, zero capacity and embedded NUL; rejection leaves the buffer unchanged. Binary data may contain NUL and needs a different explicit-length contract. Silent strncpy truncation can corrupt identifiers or checker data.
|
||||
|
||||
</details>
|
||||
|
||||
<a id="c-format"></a>
|
||||
|
||||
## C-FORMAT. Variable used as a format string
|
||||
|
||||
**Search:** scanner rule C-FORMAT. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain C-FORMAT` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
~~~c
|
||||
printf(message);
|
||||
~~~
|
||||
|
||||
**Fix:** Use a fixed format and checked arguments; pass explicit lengths for binary data.
|
||||
|
||||
~~~c
|
||||
printf("%s", message);
|
||||
~~~
|
||||
|
||||
**Verification:** Percent characters print without interpreting directives.
|
||||
|
||||
<details>
|
||||
<summary>Expanded example and limitations</summary>
|
||||
|
||||
```c
|
||||
/* Vulnerable: message controls the format and argument interpretation. */
|
||||
printf(message);
|
||||
```
|
||||
|
||||
**Patch when message is a valid NUL-terminated string:**
|
||||
|
||||
<!-- example: c-write-message -->
|
||||
|
||||
```c
|
||||
#include <stdbool.h>
|
||||
#include <stdio.h>
|
||||
|
||||
bool write_message(FILE *out, const char *message) {
|
||||
if (out == NULL || message == NULL) return false;
|
||||
return fputs(message, out) != EOF;
|
||||
}
|
||||
```
|
||||
|
||||
Alternatively use fprintf(out, "%s", message) with a fixed format. For length-delimited network buffers use validated length and fwrite rather than assuming NUL termination. Handle write errors separately.
|
||||
|
||||
**Check:** %s, %% and Unicode print literally; empty strings work; avoid extra newlines if the protocol forbids them.
|
||||
|
||||
</details>
|
||||
|
||||
<a id="c-shell"></a>
|
||||
|
||||
## C-SHELL. C/C++ shell execution
|
||||
|
||||
**Search:** scanner rule C-SHELL. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain C-SHELL` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
~~~c
|
||||
system(command);
|
||||
~~~
|
||||
|
||||
**Fix:** Use execve/posix_spawn with fixed program and validated argv; handle errors.
|
||||
|
||||
~~~c
|
||||
run_fixed_tool(validated_filename); // fixed executable + argv inside
|
||||
~~~
|
||||
|
||||
**Verification:** Metacharacters are not interpreted by a shell.
|
||||
|
||||
<a id="c-prng"></a>
|
||||
|
||||
## C-PRNG. Ordinary PRNG/LCG near a possible secret
|
||||
|
||||
**Search:** scanner rule C-PRNG. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain C-PRNG` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
~~~c
|
||||
srand((unsigned)time(NULL));
|
||||
token = rand();
|
||||
~~~
|
||||
|
||||
**Fix:** Use system CSPRNG/supported crypto and check results; ordinary non-security randomness may use a PRNG.
|
||||
|
||||
~~~c
|
||||
if (!fill_from_os_csprng(token, sizeof token)) return ERROR; // implement using supported OS/library API
|
||||
~~~
|
||||
|
||||
**Verification:** No predictable seed/fallback exists; token format stays compatible.
|
||||
|
||||
**A/D variant:** Access identifiers from a time-seeded LCG. **ENOWARS / piratesay, author write-up.** An identifier permitted user switching while its generator depended on startup time.
|
||||
|
||||
**Patch:** System CSPRNG and server-side credential/user binding. A hidden constant seed is not a sound fix. **Test:** New IDs and old sessions according to migration policy; entropy failure without fallback. **Search:** C-PRNG; inspect custom generators manually.
|
||||
|
||||
[source/write-up 1](https://github.com/enowars/enowars8-service-piratesay/blob/32973478dbe903d0a2446539ecbddf3b1c334e60/documentation/README.md); [source/write-up 2](https://github.com/enowars/enowars8-service-piratesay/blob/32973478dbe903d0a2446539ecbddf3b1c334e60/service_source/src/cli.c); [source/write-up 3](https://github.com/enowars/enowars8-service-piratesay/blob/32973478dbe903d0a2446539ecbddf3b1c334e60/service_source/src/session.c).
|
||||
|
||||
<a id="c-snprintf-format"></a>
|
||||
|
||||
## C-SNPRINTF-FORMAT. Variable format in bounded printf
|
||||
|
||||
**Search:** scanner rule C-SNPRINTF-FORMAT. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain C-SNPRINTF-FORMAT` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
~~~c
|
||||
snprintf(out, capacity, message);
|
||||
~~~
|
||||
|
||||
**Fix:** Use a fixed format; buffer limits do not secure untrusted format strings. Trace wrappers/macros.
|
||||
|
||||
~~~c
|
||||
snprintf(out, capacity, "%s", message);
|
||||
~~~
|
||||
|
||||
**Verification:** Percent characters stay text, truncation is handled; legitimate wrappers may still match.
|
||||
|
||||
**A/D variant:** Format strings in a 'safe' wrapper. **ENOWARS / piratesay, author write-up.** Bounded writes and filtering a few specifiers did not stop another layer interpreting user text as a format.
|
||||
|
||||
**Patch:** Fixed format at the final sink, data passed separately; trace macro → wrapper → printf-family. **Test:** Literal percent signs and handled truncation. **Search:** C-FORMAT, C-SNPRINTF-FORMAT; arbitrary wrapper names are not recognized automatically.
|
||||
|
||||
[source/write-up 1](https://github.com/enowars/enowars8-service-piratesay/blob/32973478dbe903d0a2446539ecbddf3b1c334e60/documentation/README.md); [source/write-up 2](https://github.com/enowars/enowars8-service-piratesay/blob/32973478dbe903d0a2446539ecbddf3b1c334e60/service_source/src/cli.c); [source/write-up 3](https://github.com/enowars/enowars8-service-piratesay/blob/32973478dbe903d0a2446539ecbddf3b1c334e60/service_source/src/session.c).
|
||||
|
||||
<a id="c-recv-terminator"></a>
|
||||
|
||||
## C-RECV-TERMINATOR. recv/read result used as an index
|
||||
|
||||
**Search:** scanner rule C-RECV-TERMINATOR. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain C-RECV-TERMINATOR` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
~~~c
|
||||
n = recv(fd, buffer, sizeof buffer, 0);
|
||||
buffer[n] = '\0';
|
||||
~~~
|
||||
|
||||
**Fix:** Reserve NUL space, handle negative/EOF results before indexing, and handle short reads. Correct code may still match.
|
||||
|
||||
~~~c
|
||||
ssize_t n = recv(fd, buffer, sizeof buffer - 1, 0);
|
||||
if (n <= 0) return ERROR;
|
||||
buffer[n] = '\0';
|
||||
~~~
|
||||
|
||||
**Verification:** Test errors, EOF, full buffer, short reads and normal messages.
|
||||
|
||||
<a id="c-atoi"></a>
|
||||
|
||||
## C-ATOI. atoi without checked conversion
|
||||
|
||||
**Search:** scanner rule C-ATOI. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain C-ATOI` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
~~~c
|
||||
int size = atoi(input);
|
||||
~~~
|
||||
|
||||
**Fix:** Use checked conversion with end-pointer, range and errno validation; define the accepted numeric grammar.
|
||||
|
||||
~~~c
|
||||
// use strtol/strtoull with errno, end pointer, sign and application bounds checks
|
||||
~~~
|
||||
|
||||
**Verification:** Empty, trailing junk, signs and overflow fail; permitted boundary values work.
|
||||
|
||||
**Reference:** [primary source](https://cmu-sei.github.io/secure-coding-standards/sei-cert-c-coding-standard/rules/error-handling-err/err34-c/).
|
||||
|
||||
<a id="c-realloc"></a>
|
||||
|
||||
## C-REALLOC. Overwriting the only pointer with realloc
|
||||
|
||||
**Search:** scanner rule C-REALLOC. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain C-REALLOC` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
~~~c
|
||||
buffer = realloc(buffer, size);
|
||||
~~~
|
||||
|
||||
**Fix:** Keep the original pointer until allocation succeeds; handle zero size and overflow according to the intended contract.
|
||||
|
||||
~~~c
|
||||
void *next = realloc(buffer, size);
|
||||
if (next == NULL) { /* preserve buffer; handle error */ }
|
||||
else { buffer = next; }
|
||||
~~~
|
||||
|
||||
**Verification:** Allocation failure leaks no original allocation and does not cause invalid access.
|
||||
|
||||
**Reference:** [primary source](https://cmu-sei.github.io/secure-coding-standards/sei-cert-c-coding-standard/recommendations/memory-management-mem/mem04-c/).
|
||||
|
||||
<a id="c-size-overflow"></a>
|
||||
|
||||
## C-SIZE-OVERFLOW. Size arithmetic overflow
|
||||
|
||||
**Search:** manual review; no separate scanner rule.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'malloc|calloc|resize|reserve|sizeof|memcpy' .
|
||||
~~~
|
||||
|
||||
Check SIZE_MAX and the application limit before multiplying/adding; check sign before casting.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
`malloc(count * sizeof(Item))` allocates less than the later copy requires after overflow.
|
||||
|
||||
**Fix:** Checked multiplication/addition and actual capacity; handle zero and allocation failure separately.
|
||||
|
||||
**Verification:** Zero, boundaries, product/sum overflow, negative inputs and existing buffers.
|
||||
|
||||
<details>
|
||||
<summary>Expanded example and limitations</summary>
|
||||
|
||||
```c
|
||||
/* Vulnerable: count * sizeof(Item) can overflow. */
|
||||
Item *items = malloc(count * sizeof(*items));
|
||||
```
|
||||
|
||||
**Patch for arithmetic and the agreed size limit:**
|
||||
|
||||
<!-- example: c-array-bytes -->
|
||||
|
||||
```c
|
||||
#include <stdbool.h>
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
|
||||
bool array_bytes(size_t count, size_t item_size, size_t max_bytes, size_t *out) {
|
||||
if (out == NULL || item_size == 0) return false;
|
||||
if (count > SIZE_MAX / item_size) return false;
|
||||
size_t total = count * item_size;
|
||||
if (total > max_bytes) return false;
|
||||
*out = total;
|
||||
return true;
|
||||
}
|
||||
```
|
||||
|
||||
Call this before malloc with sizeof(*items) and a contractual limit; check allocation success. Handle count zero explicitly: malloc(0) returning NULL does not alone imply failure. Never use out after rejection. Adding headers/terminators needs a separate addition check; this function checks only multiplication.
|
||||
|
||||
**Check:** Zero, one, exact budget, budget overflow and products above SIZE_MAX; errors never copy into stale/NULL buffers.
|
||||
|
||||
</details>
|
||||
|
||||
<a id="cpp-lifetime"></a>
|
||||
|
||||
## CPP-LIFETIME. A pointer or view outlives its owner
|
||||
|
||||
**Search:** manual review; no separate scanner rule.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'c_str\(|string_view|span|return.*data|return.*&' .
|
||||
~~~
|
||||
|
||||
Identify the data owner and destruction/reallocation points; inspect async callbacks and lambda captures.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
A temporary string's c_str or a local buffer's string_view is returned.
|
||||
|
||||
**Fix:** Return an owning object/copy; transfer ownership through async completion. A view does not extend lifetime.
|
||||
|
||||
**Verification:** Results survive return, later calls do not corrupt them, and async work retains data until completion.
|
||||
|
||||
<details>
|
||||
<summary>Expanded example and limitations</summary>
|
||||
|
||||
```cpp
|
||||
// Vulnerable: the temporary string dies before the returned pointer is used.
|
||||
const char* make_label(const std::string& name) {
|
||||
return (std::string("hello ") + name).c_str();
|
||||
}
|
||||
```
|
||||
|
||||
**Patch: return an owning object, not a pointer into destroyed storage:**
|
||||
|
||||
<!-- example: cpp-label -->
|
||||
|
||||
```cpp
|
||||
#include <string>
|
||||
|
||||
std::string make_label(const std::string& name) {
|
||||
return std::string("hello ") + name;
|
||||
}
|
||||
```
|
||||
|
||||
The caller stores std::string label = make_label(name). Its c_str may be passed to a synchronous API that does not retain the pointer past the string's lifetime. Async operations need ownership/copies. string_view alone neither prolongs lifetime nor fixes this issue.
|
||||
|
||||
**Check:** Results remain valid after return and subsequent calls, including empty names and Unicode; async paths retain data through completion.
|
||||
|
||||
</details>
|
||||
|
||||
<a id="c-partial-io"></a>
|
||||
|
||||
## C-PARTIAL-IO. TCP does not preserve message boundaries
|
||||
|
||||
**Search:** manual review; no separate scanner rule.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'recv|read\(|send|write\(|Content-Length|length' .
|
||||
~~~
|
||||
|
||||
Compare frame length with accumulated bytes and review short-read/write loops, EINTR and EOF.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
One recv is treated as a complete request, or a partial send causes the next frame to merge with a private response.
|
||||
|
||||
**Fix:** Explicit framing, bounded accumulation, partial-operation handling and timeouts; retain the checker protocol.
|
||||
|
||||
**Verification:** Byte-by-byte fragmentation, two coalesced frames, mid-frame EOF and normal messages.
|
||||
|
||||
<a id="c-signed-length"></a>
|
||||
|
||||
## C-SIGNED-LENGTH. Signed lengths become huge size_t values
|
||||
|
||||
**Search:** manual review; no separate scanner rule.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'ssize_t|size_t|uint32_t|int.*len|memcpy|recv' .
|
||||
~~~
|
||||
|
||||
Trace every cast between reading/parsing and allocation/indexing.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
A negative read result or client integer is converted to unsigned before validation.
|
||||
|
||||
**Fix:** Check errors, sign and range before conversion; verify source/destination capacity.
|
||||
|
||||
**Verification:** read=-1, EOF, negative fields, maximum and normal payloads.
|
||||
|
||||
<a id="c-double-free"></a>
|
||||
|
||||
## C-DOUBLE-FREE. Multiple owners free the same object
|
||||
|
||||
**Search:** manual review; no separate scanner rule.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'free\(|delete|unique_ptr|shared_ptr|goto.*fail' .
|
||||
~~~
|
||||
|
||||
Trace success/error cleanup and ownership transfers; look for two shared_ptr instances built from one raw pointer.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
An error path and its caller both free an object, or reset destroys an object still in use.
|
||||
|
||||
**Fix:** One explicit owner/RAII with explicit ownership transfer; clearing one alias does not repair others.
|
||||
|
||||
**Verification:** Failure at every construction step, repeated cleanup and normal lifecycle.
|
||||
|
||||
<a id="c-uninitialized"></a>
|
||||
|
||||
## C-UNINITIALIZED. Exposing padding or uninitialized tails
|
||||
|
||||
**Search:** manual review; no separate scanner rule.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'malloc|struct|send|write|sizeof|memcpy' .
|
||||
~~~
|
||||
|
||||
Compare initialized fields with transmitted struct sizeof and padding.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
`send(fd, &record, sizeof record, ...)` exposes padding or previous contents.
|
||||
|
||||
**Fix:** Explicit field/length serialization and initialized buffers; never use native layout as an implicit wire protocol.
|
||||
|
||||
**Verification:** Different compiler/layout choices, short input and no uninitialized response bytes.
|
||||
|
||||
<a id="c-tempfile-race"></a>
|
||||
|
||||
## C-TEMPFILE-RACE. Temporary filename without atomic creation
|
||||
|
||||
**Search:** scanner rule C-TEMPFILE-RACE. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain C-TEMPFILE-RACE` for details. Regex: tmpnam/tempnam/mktemp. Custom filename schemes, reopening after mkstemp and directory TOCTOU need manual review.
|
||||
|
||||
Additional manual search for forms outside automatic coverage:
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'tmpnam|mktemp|access\(|stat\(|fopen|open\(' .
|
||||
~~~
|
||||
|
||||
Trace existence-check → open and parent-directory permissions.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
A shared temporary filename is checked, then opened for overwrite through a replaced symlink.
|
||||
|
||||
**Fix:** Create a private file atomically, retain its fd, check errors/modes and close/remove it on all paths.
|
||||
|
||||
**Verification:** Concurrent operations get separate fds; existing files/symlinks are not overwritten.
|
||||
|
||||
**Scanner example before:**
|
||||
|
||||
~~~native
|
||||
char name[L_tmpnam];
|
||||
tmpnam(name);
|
||||
FILE *f = fopen(name, "w");
|
||||
~~~
|
||||
|
||||
**Fix template:**
|
||||
|
||||
~~~native
|
||||
char name[] = "/tmp/app-XXXXXX";
|
||||
int fd = mkstemp(name);
|
||||
if (fd < 0) return ERROR;
|
||||
unlink(name);
|
||||
/* use fd; close(fd) on every exit */
|
||||
~~~
|
||||
|
||||
Primary documentation: [reference 1](https://pubs.opengroup.org/onlinepubs/9799919799/functions/mkstemp.html).
|
||||
|
||||
<a id="c-jit-return"></a>
|
||||
|
||||
## C-JIT-RETURN. Not every JIT function path terminates
|
||||
|
||||
**Search:** manual review; no separate scanner rule.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'return|emit|jit|compile|bytecode' .
|
||||
~~~
|
||||
|
||||
Map function control-flow exits; a conditional return does not cover the other branch or fall-through.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
**Reference:** dcs, RuCTF author write-up: a conditional return was mistakenly considered sufficient and execution continued beyond the function. **Search:** Custom VMs/JITs/DSLs, searching for a return node rather than reachability analysis, and constants placed next to instructions.
|
||||
|
||||
**Fix:** Control-flow analysis requiring every reachable exit to return a value or terminate with a defined error. Separate code/data and validate indices/types before generation.
|
||||
|
||||
**Verification:** Both conditional branches, nesting, empty functions and normal computations. Disabling JIT entirely is acceptable only if the functional contract remains intact.
|
||||
|
||||
**A/D variant:** Source and version: [source/write-up 1](https://github.com/HackerDom/ructf-finals-2023/blob/a7442769909e08c39716cb18d3d1c3a99324bbf8/writeups/dcs/README.md).
|
||||
|
||||
**Reference:** [primary source](https://github.com/HackerDom/ructf-finals-2023/blob/a7442769909e08c39716cb18d3d1c3a99324bbf8/writeups/dcs/README.md).
|
||||
|
||||
<a id="c-header-secret"></a>
|
||||
|
||||
## C-HEADER-SECRET. A special header branch changes a secret
|
||||
|
||||
**Search:** manual review; no separate scanner rule.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'getenv|HTTP_USER_AGENT|SECRET_KEY|constructor' .
|
||||
~~~
|
||||
|
||||
Read init/constructor and debug/test branches; client headers must not change keys.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
**Reference:** reversaar, saarCTF C-source analysis: a special HTTP_USER_AGENT-linked path modified SECRET_KEY. **Search:** Constructor/init hooks, header getenv, magic constants, debug/test/admin branches in release builds and hidden signing switches.
|
||||
|
||||
**Fix:** Remove the unintended transition specifically; secret configuration must not depend on requests. Inspect startup code, not only routes.
|
||||
|
||||
**Verification:** Different headers do not change keys, privileges or storage format; normal initialization survives. There is no scanner signature for the specific magic value; manually trace input-to-secret relationships.
|
||||
|
||||
**A/D variant:** Source and version: [source/write-up 1](https://github.com/saarsec/saarctf-2024/blob/3a06d18974ca177c6dd251a11bdf9b4b334f382a/reversaar/service/src/array.c).
|
||||
|
||||
**Reference:** [primary source](https://github.com/saarsec/saarctf-2024/blob/3a06d18974ca177c6dd251a11bdf9b4b334f382a/reversaar/service/src/array.c).
|
||||
|
||||
<a id="c-object-toctou"></a>
|
||||
|
||||
## C-OBJECT-TOCTOU. Re-reading mutable references after authorization
|
||||
|
||||
**Search:** manual review; no separate scanner rule.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'background|fork|exec|open|read' .
|
||||
~~~
|
||||
|
||||
Find repeated mutable-object reads after checks/external calls; compare object identity and snapshots.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
**RuCTF / memos, author write-up.** An external operation occurred between checking background access and reading it; another request could replace the selected object.
|
||||
|
||||
**Fix:** Use the same validated snapshot/descriptor or atomically check its version before use.
|
||||
|
||||
**Verification:** Barrier-controlled request interleaving and legitimate long-running operations.
|
||||
|
||||
**A/D variant:** Source and version: [source/write-up 1](https://github.com/HackerDom/ructf-2023/blob/0cc333e44f2ba6908ff6c5d613146e3b00173315/writeups/memos/README.md).
|
||||
|
||||
**Reference:** [primary source](https://github.com/HackerDom/ructf-2023/blob/0cc333e44f2ba6908ff6c5d613146e3b00173315/writeups/memos/README.md).
|
||||
|
||||
<a id="c-exec-failure"></a>
|
||||
|
||||
## C-EXEC-FAILURE. Failed exec leaves a child on the server path
|
||||
|
||||
**Search:** manual review; no separate scanner rule.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'fork|execve|execvp|waitpid' .
|
||||
~~~
|
||||
|
||||
Trace every fork/exec error and child termination, including oversized argument vectors.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
**RuCTF / memos, author write-up.** A child could continue server logic after execve failed.
|
||||
|
||||
**Fix:** Check fork/exec/wait; on child-side exec failure close extra descriptors and terminate with failing _exit.
|
||||
|
||||
**Verification:** Missing executables, excessive arguments and fork failure never create a second server.
|
||||
|
||||
**A/D variant:** Source and version: [source/write-up 1](https://github.com/HackerDom/ructf-2023/blob/0cc333e44f2ba6908ff6c5d613146e3b00173315/writeups/memos/README.md).
|
||||
|
||||
**Reference:** [primary source](https://github.com/HackerDom/ructf-2023/blob/0cc333e44f2ba6908ff6c5d613146e3b00173315/writeups/memos/README.md).
|
||||
|
||||
<a id="cpp-cached-lifetime"></a>
|
||||
|
||||
## CPP-CACHED-LIFETIME. Cached pointers survive object destruction
|
||||
|
||||
**Search:** manual review; no separate scanner rule.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'cache|delete|free|flush|shared_ptr|weak_ptr' .
|
||||
~~~
|
||||
|
||||
Identify the cached pointer's owner and destruction point; trace method calls after eviction.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
**RuCTF / perune, author write-up.** Subsequent cache traversal called a virtual method on a freed object.
|
||||
|
||||
**Fix:** Explicit ownership, removal of every reference at destruction, safe handles/weak references or validated generation IDs.
|
||||
|
||||
**Verification:** Different create/delete/flush orderings and available sanitizers; absence of a crash proves nothing by itself.
|
||||
|
||||
**A/D variant:** Source and version: [source/write-up 1](https://github.com/HackerDom/ructf-2023/blob/0cc333e44f2ba6908ff6c5d613146e3b00173315/writeups/perune/readme.md).
|
||||
|
||||
**Reference:** [primary source](https://github.com/HackerDom/ructf-2023/blob/0cc333e44f2ba6908ff6c5d613146e3b00173315/writeups/perune/readme.md).
|
||||
|
||||
<a id="c-block-tail"></a>
|
||||
|
||||
## C-BLOCK-TAIL. Four-byte block processing corrupts the tail
|
||||
|
||||
**Search:** manual review; no separate scanner rule.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'xor|chacha|uint32_t|length|remaining' .
|
||||
~~~
|
||||
|
||||
Check one-to-three-byte remainders with a four-byte stride against actual allocation.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
**ECSC / Diese HSM, author write-up.** XOR crossed the end when length was not word-aligned.
|
||||
|
||||
**Fix:** Complete blocks followed by a separately bounded tail; check alignment.
|
||||
|
||||
**Verification:** Lengths 0–9, buffer boundaries, canaries and valid nonces.
|
||||
|
||||
**A/D variant:** Source and version: [source/write-up 1](https://github.com/ECSC2024/ECSC2024-CTF-AD/blob/2a92e17384ad228072a84fb076a35066fe2ffeff/sources/Diese/README.md); [source/write-up 2](https://github.com/ECSC2024/ECSC2024-CTF-AD/blob/2a92e17384ad228072a84fb076a35066fe2ffeff/sources/Diese/webapp/src/classes/Utils.class.php); [source/write-up 3](https://github.com/ECSC2024/ECSC2024-CTF-AD/blob/2a92e17384ad228072a84fb076a35066fe2ffeff/sources/Diese/hsm/src/msg.c).
|
||||
|
||||
**Reference:** [primary source](https://github.com/ECSC2024/ECSC2024-CTF-AD/blob/2a92e17384ad228072a84fb076a35066fe2ffeff/sources/Diese/README.md).
|
||||
|
||||
<a id="c-alloc-failure"></a>
|
||||
|
||||
## C-ALLOC-FAILURE. Allocation failure becomes a NULL write
|
||||
|
||||
**Search:** manual review; no separate scanner rule.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'malloc|calloc|alloc|memcpy' .
|
||||
~~~
|
||||
|
||||
Trace NULL/allocation failures to the first write, including custom allocators and firmware address spaces.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
**ECSC / Diese HSM, author and source.** An allocator result was unchecked while address zero was accessible in firmware.
|
||||
|
||||
**Fix:** Checked size arithmetic, message limits and allocation-failure handling across the entire chain.
|
||||
|
||||
**Verification:** Failure at every allocation and truncated packets.
|
||||
|
||||
**A/D variant:** Source and version: [source/write-up 1](https://github.com/ECSC2024/ECSC2024-CTF-AD/blob/2a92e17384ad228072a84fb076a35066fe2ffeff/sources/Diese/README.md); [source/write-up 2](https://github.com/ECSC2024/ECSC2024-CTF-AD/blob/2a92e17384ad228072a84fb076a35066fe2ffeff/sources/Diese/webapp/src/classes/Utils.class.php); [source/write-up 3](https://github.com/ECSC2024/ECSC2024-CTF-AD/blob/2a92e17384ad228072a84fb076a35066fe2ffeff/sources/Diese/hsm/src/msg.c).
|
||||
|
||||
**Reference:** [primary source](https://github.com/ECSC2024/ECSC2024-CTF-AD/blob/2a92e17384ad228072a84fb076a35066fe2ffeff/sources/Diese/README.md).
|
||||
|
||||
<a id="c-fd-nul"></a>
|
||||
|
||||
## C-FD-NUL. Descriptor leaks amplify a read_line off-by-one
|
||||
|
||||
**Search:** manual review; no separate scanner rule.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'read_line|open|close|fopen|fclose' .
|
||||
~~~
|
||||
|
||||
Inspect descriptor closure on login failures and NUL writes when buffers are full.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
**ECSC / CookingNonna, author write-up.** Failed login leaked an fd while a terminator could be written beyond a full buffer.
|
||||
|
||||
**Fix:** Unified cleanup for every failure; reserve NUL space, check read/EOF and compare open results with -1.
|
||||
|
||||
**Verification:** Capacities 0/1/max, long lines and repeated failures without descriptor growth.
|
||||
|
||||
**A/D variant:** Source and version: [source/write-up 1](https://github.com/ECSC2024/ECSC2024-CTF-AD/blob/2a92e17384ad228072a84fb076a35066fe2ffeff/sources/CookingNonna/README.md).
|
||||
|
||||
**Reference:** [primary source](https://github.com/ECSC2024/ECSC2024-CTF-AD/blob/2a92e17384ad228072a84fb076a35066fe2ffeff/sources/CookingNonna/README.md).
|
||||
|
||||
<a id="c-reentrancy-auth"></a>
|
||||
|
||||
## C-REENTRANCY-AUTH. A callback runs between authorization and signing
|
||||
|
||||
**Search:** manual review; no separate scanner rule.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'callback|SignToken|Len|ByRef' .
|
||||
~~~
|
||||
|
||||
Find user callbacks after ownership checks; determine whether they can mutate the signed arguments.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
**ICC / MaScroll, author write-up.** An overridable Len changed a reference argument after its owner check.
|
||||
|
||||
**Fix:** Validate an immutable copy; do not invoke user code between verification and the sensitive operation.
|
||||
|
||||
**Verification:** A callback changes the original, but only the checked copy is signed.
|
||||
|
||||
**A/D variant:** Source and version: [source/write-up 1](https://github.com/CybersecNatLab/ICC2023-AD-CTF/blob/8ffa184ff2ce8f648258ed3c02ee2270e8e1c56c/sources/MaScroll/README.md).
|
||||
|
||||
**Reference:** [primary source](https://github.com/CybersecNatLab/ICC2023-AD-CTF/blob/8ffa184ff2ce8f648258ed3c02ee2270e8e1c56c/sources/MaScroll/README.md).
|
||||
|
||||
<a id="c-builtin-types"></a>
|
||||
|
||||
## C-BUILTIN-TYPES. One builtin overload omits argument-type checks
|
||||
|
||||
**Search:** manual review; no separate scanner rule.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'FastRand|CryptoRand|variant|overload|builtin' .
|
||||
~~~
|
||||
|
||||
Compare every overload's argument types, including the common first argument and error paths.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
**ICC / MaScroll, author write-up.** One generator call form skipped type checks; the resulting memory error affected cryptographic state.
|
||||
|
||||
**Fix:** Uniform type/arity/length validation for every overload, with correct ownership and buffers.
|
||||
|
||||
**Verification:** Type/argument-count matrix; errors never modify RNG or signing state.
|
||||
|
||||
**A/D variant:** Source and version: [source/write-up 1](https://github.com/CybersecNatLab/ICC2023-AD-CTF/blob/8ffa184ff2ce8f648258ed3c02ee2270e8e1c56c/sources/MaScroll/README.md).
|
||||
|
||||
**Reference:** [primary source](https://github.com/CybersecNatLab/ICC2023-AD-CTF/blob/8ffa184ff2ce8f648258ed3c02ee2270e8e1c56c/sources/MaScroll/README.md).
|
||||
|
||||
<a id="c-hash-index"></a>
|
||||
|
||||
## C-HASH-INDEX. Hash-table indices exceed the upper boundary
|
||||
|
||||
**Search:** manual review; no separate scanner rule.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'TABLE_SIZE|capacity|hash|table\[' .
|
||||
~~~
|
||||
|
||||
Calculate min/max indices and array size for every branch; inspect insert/find and representation changes.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
**DEF CON / bisbee, source and header.** A remainder modulo TABLE_SIZE plus one indexed a TABLE_SIZE-element array.
|
||||
|
||||
**Fix:** Keep indices in [0, capacity), consistently across operations; review list/hashmap migration and update counters.
|
||||
|
||||
**Verification:** First/last buckets, collisions, repeated updates and representation switching.
|
||||
|
||||
**A/D variant:** Source and version: [source/write-up 1](https://github.com/Nautilus-Institute/finals-2024/blob/f17456fed4ff40e6f4f1237ed4b82c242e52ec67/bisbee/src/service/src/main.rs); [source/write-up 2](https://github.com/Nautilus-Institute/finals-2024/blob/f17456fed4ff40e6f4f1237ed4b82c242e52ec67/bisbee/src/db/kv.c); [source/write-up 3](https://github.com/Nautilus-Institute/finals-2024/blob/f17456fed4ff40e6f4f1237ed4b82c242e52ec67/bisbee/src/db/kv.h); [source/write-up 4](https://github.com/Nautilus-Institute/finals-2024/blob/f17456fed4ff40e6f4f1237ed4b82c242e52ec67/bisbee/src/db/kv_hashmap.c); [source/write-up 5](https://github.com/Nautilus-Institute/finals-2024/blob/f17456fed4ff40e6f4f1237ed4b82c242e52ec67/bisbee/src/db/kv_hashmap.h); [source/write-up 6](https://github.com/Nautilus-Institute/finals-2024/blob/f17456fed4ff40e6f4f1237ed4b82c242e52ec67/bisbee/src/db/kv_list.c).
|
||||
|
||||
**Reference:** [primary source](https://github.com/Nautilus-Institute/finals-2024/blob/f17456fed4ff40e6f4f1237ed4b82c242e52ec67/bisbee/src/service/src/main.rs).
|
||||
|
||||
<a id="c-strncpy"></a>
|
||||
|
||||
## C-STRNCPY. strncpy may omit NUL termination
|
||||
|
||||
**Search:** scanner rule C-STRNCPY. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain C-STRNCPY` for details. Regex: strncpy. Review later NUL termination and actual capacity; memcpy without length checks is not a fix.
|
||||
|
||||
**Vulnerable example:** strncpy does not terminate sufficiently long input; later string APIs read beyond the buffer.
|
||||
|
||||
~~~native
|
||||
strncpy(out, input, sizeof out);
|
||||
puts(out);
|
||||
~~~
|
||||
|
||||
**Fix:** Choose reject-too-long or explicit bounded truncation with NUL space; use explicit lengths for binary data.
|
||||
|
||||
~~~native
|
||||
size_t n = bounded_input_length;
|
||||
if (n >= sizeof out) return ERROR;
|
||||
memcpy(out, input, n);
|
||||
out[n] = '\0';
|
||||
~~~
|
||||
|
||||
**Verification:** Test empty/capacity-1/capacity/capacity+1; truncation cannot change identity.
|
||||
|
||||
Primary documentation: [reference 1](https://pubs.opengroup.org/onlinepubs/9799919799/functions/strncpy.html).
|
||||
|
||||
<a id="c-copy-length"></a>
|
||||
|
||||
## C-COPY-LENGTH. Copy length comes directly from source strlen
|
||||
|
||||
**Search:** scanner rule C-COPY-LENGTH. Use `--explain C-COPY-LENGTH` for the exact detector contract. Regex with lexical exclusions: memcpy/memmove with simple first two arguments and strlen/strnlen directly as length. Does not prove missing preceding checks or actual buffer sizes; custom same-named APIs and macros require review.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
~~~native
|
||||
memcpy(dest, input, strlen(input) + 1);
|
||||
~~~
|
||||
|
||||
**Fix:** Validate readable source length and destination capacity before copying, including terminator and arithmetic overflow.
|
||||
|
||||
~~~native
|
||||
size_t n = validated_length;
|
||||
if (n >= capacity) return ERROR;
|
||||
memcpy(dest, input, n + 1);
|
||||
~~~
|
||||
|
||||
**Verification:** Test empty input, capacity boundaries, missing terminator and overflow using sanitizers where available.
|
||||
|
||||
[Primary reference 1](https://pubs.opengroup.org/onlinepubs/9799919799/functions/memcpy.html)
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,688 @@
|
||||
<a id="c--net-find-fix-and-verify"></a>
|
||||
|
||||
# C# / .NET: поиск и исправление
|
||||
|
||||
[English](csharp.md) | Русский
|
||||
|
||||
[Вся база](README-RU.md) · [Сканер](../offline-scanner-RU.md) · [Проверка патча](../patch-validation-RU.md)
|
||||
|
||||
20 разделов. Формат: **Поиск → Уязвимый вариант → Исправление → Проверка**.
|
||||
Команды `rg` выполняются в корне локальной копии сервиса и только читают файлы. Субъект/владелец определяется по проверенной сессии, а не данным запроса. Примеры нужно адаптировать к реальным API и контракту.
|
||||
|
||||
Автоматические находки — ограниченные синтаксические сигналы для проверки. AST-анализ не разрешает типы и не отслеживает данные между функциями; regex не заменяет парсер языка. Комментарии, строки и одноимённые пользовательские API могут давать совпадения. Проверьте фактическое исполнение, входные данные, авторизацию и границы доверия.
|
||||
|
||||
<a id="contents"></a>
|
||||
|
||||
## Содержание
|
||||
|
||||
- [CS-DESERIALIZE — Типы при десериализации .NET](#cs-deserialize)
|
||||
- [CS-ENUM — Enum.TryParse требует проверки диапазона](#cs-enum)
|
||||
- [CS-SQL — Динамический SQL .NET](#cs-sql)
|
||||
- [CS-GUID-BYTES — Байтовый Guid на границе протокола](#cs-guid-bytes)
|
||||
- [CS-PROCESS — Создание процесса .NET](#cs-process)
|
||||
- [CS-IGNORE-FILTERS — Отключение global query filters](#cs-ignore-filters)
|
||||
- [CS-ALLOWANON — Маршрут с AllowAnonymous](#cs-allowanon)
|
||||
- [CS-MASS-ASSIGN — Клиентская сущность целиком обновляет БД](#cs-mass-assign)
|
||||
- [CS-XML — XML settings и внешние ресурсы](#cs-xml)
|
||||
- [CS-HTML-RAW — Html.Raw и IHtmlContent обходят encoding](#cs-html-raw)
|
||||
- [CS-PATH — Path.Combine и GetFullPath не проверяют owner](#cs-path)
|
||||
- [CS-ARCHIVE — ZipArchive entry выходит из каталога](#cs-archive)
|
||||
- [CS-CLAIMS — Неполная проверка JWT/claims](#cs-claims)
|
||||
- [CS-ASYNC-VOID — async void скрывает ошибку auth](#cs-async-void)
|
||||
- [CS-REGEX-TIMEOUT — Regex без бюджета на недоверенном вводе](#cs-regex-timeout)
|
||||
- [CS-AUTH-FILTER-REDUCE — Упрощение фильтра удаляет обязательное условие доступа](#cs-auth-filter-reduce)
|
||||
- [CS-COLLIDING-PRINCIPAL — Нормализованная сумма символов вместо уникального user ID](#cs-colliding-principal)
|
||||
- [CS-JWT-VALIDATION — Ослаблены параметры проверки токенов .NET](#cs-jwt-validation)
|
||||
- [CS-TLS-VALIDATION — HTTPS validation callback всегда разрешает](#cs-tls-validation)
|
||||
- [CS-LDAP-FILTER — Фильтр DirectorySearcher собирается конкатенацией](#cs-ldap-filter)
|
||||
|
||||
<a id="cs-deserialize"></a>
|
||||
|
||||
<a id="cs-deserialize-type-controlled-net-deserialization"></a>
|
||||
|
||||
## CS-DESERIALIZE. Типы при десериализации .NET
|
||||
|
||||
**Поиск:** скрипт, правило CS-DESERIALIZE. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain CS-DESERIALIZE. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
~~~csharp
|
||||
var formatter = new BinaryFormatter();
|
||||
~~~
|
||||
|
||||
**Исправление:** Явные DTO и поддержанный сериализатор, например System.Text.Json, с проверками схемы и размера; убрать неограниченное создание runtime-типов и мигрировать старые данные.
|
||||
|
||||
~~~csharp
|
||||
var value = JsonSerializer.Deserialize<MessageDto>(json); // validate fields
|
||||
~~~
|
||||
|
||||
**Проверка:** Произвольный тип не создаётся; старые записи мигрируют.
|
||||
|
||||
**Вариант A/D:** Десериализация запускает побочные эффекты сеттеров. **FAUST / todo-list, код + патч организаторов.** TypeNameHandling.Objects
|
||||
позволяет выбрать runtime-тип; у модели Filter установка полей вызывает запись
|
||||
в БД. Проверка результата после создания объекта может быть слишком поздней.
|
||||
|
||||
**Патч:** конкретный DTO без внешнего выбора типа, явная валидация и отдельная
|
||||
операция сохранения. **Тест:** неизвестный тип не создаёт ни объект, ни запись;
|
||||
штатный импорт/экспорт сохранён. **Поиск:** CS-DESERIALIZE.
|
||||
|
||||
[исходник/разбор 1](https://github.com/fausecteam/faustctf-2024-todo-list-service/blob/e9ee8b8807c64eeb6f71a72e16f709a558525d2c/patches/deserialize.patch); [исходник/разбор 2](https://github.com/fausecteam/faustctf-2024-todo-list-service/blob/e9ee8b8807c64eeb6f71a72e16f709a558525d2c/patches/TodoController.cs); [исходник/разбор 3](https://github.com/fausecteam/faustctf-2024-todo-list-service/blob/e9ee8b8807c64eeb6f71a72e16f709a558525d2c/service/service/Services/Serializer.cs); [исходник/разбор 4](https://github.com/fausecteam/faustctf-2024-todo-list-service/blob/e9ee8b8807c64eeb6f71a72e16f709a558525d2c/service/service/Services/UserManager.cs); [исходник/разбор 5](https://github.com/fausecteam/faustctf-2024-todo-list-service/blob/e9ee8b8807c64eeb6f71a72e16f709a558525d2c/service/service/Models/Filter.cs).
|
||||
|
||||
<a id="cs-enum"></a>
|
||||
|
||||
<a id="cs-enum-enumtryparse-requires-an-allowed-value-check"></a>
|
||||
|
||||
## CS-ENUM. Enum.TryParse требует проверки диапазона
|
||||
|
||||
**Поиск:** скрипт, правило CS-ENUM. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain CS-ENUM. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
~~~csharp
|
||||
bool ok = Enum.TryParse(input, out FilterKind kind);
|
||||
~~~
|
||||
|
||||
**Исправление:** После TryParse проверять Enum.IsDefined или явный набор; для Flags — разрешённая маска. Сигнал останется при правильном inline-патче.
|
||||
|
||||
~~~csharp
|
||||
if (!TryParseAllowedFilter(input, out FilterKind kind)) return BadRequest(); // helper validates named allowlist
|
||||
~~~
|
||||
|
||||
**Проверка:** Необъявленные числа/неразрешённые биты отвергаются; штатные фильтры доступны.
|
||||
|
||||
**Вариант A/D:** Числовое значение enum вне разрешённого набора. **Основание:** sneakers, авторский разбор RuCTF. TryParse может принять число,
|
||||
которому не соответствует объявленное имя.
|
||||
Сканер: CS-ENUM, в том числе на уже исправленных вызовах.
|
||||
|
||||
~~~csharp
|
||||
if (!Enum.TryParse<FilterKind>(input, out var kind) ||
|
||||
!Enum.IsDefined(typeof(FilterKind), kind))
|
||||
return BadRequest();
|
||||
~~~
|
||||
|
||||
Для Flags требуется отдельная разрешённая маска и политика комбинаций.
|
||||
**Тест:** все допустимые имена, необъявленные числа, отрицательные/слишком
|
||||
большие значения и комбинации. Это проверка значения, а не замена auth.
|
||||
|
||||
[исходник/разбор 1](https://github.com/HackerDom/ructf-finals-2023/blob/a7442769909e08c39716cb18d3d1c3a99324bbf8/writeups/sneakers/README.md).
|
||||
|
||||
<a id="cs-sql"></a>
|
||||
|
||||
<a id="cs-sql-dynamic-net-sql"></a>
|
||||
|
||||
## CS-SQL. Динамический SQL .NET
|
||||
|
||||
**Поиск:** скрипт, правило CS-SQL. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain CS-SQL. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
~~~csharp
|
||||
context.Notes.FromSqlRaw("SELECT * FROM notes WHERE name=" + name);
|
||||
~~~
|
||||
|
||||
**Исправление:** Параметризованный API конкретной ORM или провайдера и разрешённый набор идентификаторов; различать Raw и интерполируемый overload.
|
||||
|
||||
~~~csharp
|
||||
context.Notes.FromSqlRaw("SELECT * FROM notes WHERE name={0}", name);
|
||||
~~~
|
||||
|
||||
**Проверка:** Кавычки — данные; owner_id сохраняется.
|
||||
|
||||
<details>
|
||||
<summary>Развёрнутый пример и ограничения</summary>
|
||||
|
||||
```csharp
|
||||
// Vulnerable: interpolation has already put client data into SQL source.
|
||||
var rows = await db.Notes
|
||||
.FromSqlRaw($"SELECT * FROM Notes WHERE Title = '{title}'")
|
||||
.ToListAsync(ct);
|
||||
```
|
||||
|
||||
**Минимальный патч для простого поиска — LINQ с ограничением владельца:**
|
||||
|
||||
```csharp
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
var rows = await db.Notes
|
||||
.Where(n => n.OwnerId == currentUserId && n.Title == title)
|
||||
.ToListAsync(ct);
|
||||
```
|
||||
|
||||
Если сырой SQL нужен, `FromSqlInterpolated` принимает интерполированное выражение
|
||||
как `FormattableString` и параметризует значения. Не преобразовывать его сначала
|
||||
в обычную `string` и не возвращать затем в `FromSqlRaw`. Метод `FromSql` появился
|
||||
в EF Core 7; выбрать API своей версии. Имена колонок требуют фиксированного выбора.
|
||||
|
||||
**Проверить:** имя с апострофом/Unicode ищется буквально, чужие записи отсутствуют,
|
||||
пагинация и старые данные работают. Кастомный провайдер и перевод LINQ проверить
|
||||
на используемой БД, не только на in-memory substitute.
|
||||
|
||||
</details>
|
||||
|
||||
<a id="cs-guid-bytes"></a>
|
||||
|
||||
<a id="cs-guid-bytes-byte-order-guid-protocol-boundary"></a>
|
||||
|
||||
## CS-GUID-BYTES. Байтовый Guid на границе протокола
|
||||
|
||||
**Поиск:** скрипт, правило CS-GUID-BYTES. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain CS-GUID-BYTES. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
~~~csharp
|
||||
var value = new Guid(wireBytes);
|
||||
~~~
|
||||
|
||||
**Исправление:** Согласовать порядок байтов с другой стороной; использовать canonical text либо явное преобразование по протоколу, не разворачивать весь массив наугад.
|
||||
|
||||
~~~csharp
|
||||
var value = Guid.ParseExact(wireText, "D");
|
||||
~~~
|
||||
|
||||
**Проверка:** Несимметричные известные UUID совпадают в C#/Python; DB и cache сравнивают тот же ID.
|
||||
|
||||
<a id="cs-process"></a>
|
||||
|
||||
<a id="cs-process-net-process-creation"></a>
|
||||
|
||||
## CS-PROCESS. Создание процесса .NET
|
||||
|
||||
**Поиск:** скрипт, правило CS-PROCESS. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain CS-PROCESS. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
~~~csharp
|
||||
Process.Start("sh", "-c " + command);
|
||||
~~~
|
||||
|
||||
**Исправление:** Библиотечная операция либо фиксированный executable и ArgumentList. UseShellExecute=false не отменяет явный sh/cmd; учитывать option injection.
|
||||
|
||||
~~~csharp
|
||||
var digest = SHA256.HashData(Encoding.UTF8.GetBytes(text));
|
||||
~~~
|
||||
|
||||
**Проверка:** Кавычки — данные, штатный формат результата совпадает.
|
||||
|
||||
<details>
|
||||
<summary>Развёрнутый пример и ограничения</summary>
|
||||
|
||||
```csharp
|
||||
// Vulnerable on Linux: UseShellExecute=false does not prevent explicit /bin/sh.
|
||||
var psi = new System.Diagnostics.ProcessStartInfo("/bin/sh") { UseShellExecute = false };
|
||||
psi.ArgumentList.Add("-c");
|
||||
psi.ArgumentList.Add("printf '%s' '" + text + "' | sha256sum");
|
||||
System.Diagnostics.Process.Start(psi);
|
||||
```
|
||||
|
||||
**Патч для SHA-256 текста, .NET 6+:**
|
||||
|
||||
```csharp
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
|
||||
static string DigestText(string text)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(text);
|
||||
byte[] sum = SHA256.HashData(Encoding.UTF8.GetBytes(text));
|
||||
return Convert.ToHexString(sum).ToLowerInvariant();
|
||||
}
|
||||
```
|
||||
|
||||
Сохранить внешний формат результата и кодировку. Для действительно необходимого
|
||||
процесса задавать executable и `ArgumentList` отдельно; пользователь всё ещё
|
||||
не должен выбирать опасные опции программы. SHA-256 содержимого не подходит
|
||||
как самостоятельное хранение паролей.
|
||||
|
||||
**Проверить:** известный digest, пустой текст, Unicode, кавычки и переводы строк;
|
||||
нет дочернего процесса и утечки его окружения при ошибке.
|
||||
|
||||
</details>
|
||||
|
||||
**Основание:** [первичный материал](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.processstartinfo.argumentlist).
|
||||
|
||||
<a id="cs-ignore-filters"></a>
|
||||
|
||||
<a id="cs-ignore-filters-global-query-filters-disabled"></a>
|
||||
|
||||
## CS-IGNORE-FILTERS. Отключение global query filters
|
||||
|
||||
**Поиск:** скрипт, правило CS-IGNORE-FILTERS. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain CS-IGNORE-FILTERS. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
~~~csharp
|
||||
var rows = db.Notes.IgnoreQueryFilters().ToList();
|
||||
~~~
|
||||
|
||||
**Исправление:** Не отключать tenant/auth-фильтр ради soft-delete. Если bypass нужен администратору, явная авторизация и нужное ограничение в самом запросе.
|
||||
|
||||
~~~csharp
|
||||
var rows = db.Notes.Where(n => n.OwnerId == userId).ToList();
|
||||
~~~
|
||||
|
||||
**Проверка:** Два tenant, удалённая запись и export; проверять SQL реального провайдера.
|
||||
|
||||
**Основание:** [первичный материал](https://learn.microsoft.com/en-us/ef/core/querying/filters).
|
||||
|
||||
<a id="cs-allowanon"></a>
|
||||
|
||||
<a id="cs-allowanon-allowanonymous-route"></a>
|
||||
|
||||
## CS-ALLOWANON. Маршрут с AllowAnonymous
|
||||
|
||||
**Поиск:** скрипт, правило CS-ALLOWANON. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain CS-ALLOWANON. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
~~~csharp
|
||||
[AllowAnonymous]
|
||||
public IActionResult PrivateNote() => View();
|
||||
~~~
|
||||
|
||||
**Исправление:** Проверить effective metadata endpoint и ownership. AllowAnonymous может отменить требование Authorize; login/health могут быть публичными по контракту.
|
||||
|
||||
~~~csharp
|
||||
[Authorize]
|
||||
public IActionResult PrivateNote() => View();
|
||||
~~~
|
||||
|
||||
**Проверка:** Публичный login работает; приватный endpoint и вложенные операции требуют нужные права.
|
||||
|
||||
**Основание:** [первичный материал](https://learn.microsoft.com/en-us/aspnet/core/security/authorization/simple).
|
||||
|
||||
<a id="cs-mass-assign"></a>
|
||||
|
||||
<a id="cs-mass-assign-client-entities-update-the-database-wholesale"></a>
|
||||
|
||||
## CS-MASS-ASSIGN. Клиентская сущность целиком обновляет БД
|
||||
|
||||
**Поиск:** вручную; отдельного правила сканера нет.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'Update\(|TryUpdateModelAsync|Bind\(|FromBody|SaveChanges' .
|
||||
~~~
|
||||
|
||||
Сверить DTO, entity и изменяемые поля; не передаётся ли второй объект клиента после безопасной загрузки.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
db.Update(clientNote) применяет OwnerId/Role из JSON.
|
||||
|
||||
**Исправление:** DTO редактируемых полей, загрузка по ID+owner, явные присваивания; concurrency token если права могут меняться.
|
||||
|
||||
**Проверка:** Своё меняется, чужое и owner нет; null/отсутствующее поле различаются по контракту.
|
||||
|
||||
<details>
|
||||
<summary>Развёрнутый пример и ограничения</summary>
|
||||
|
||||
```csharp
|
||||
// Vulnerable: the supplied entity may contain OwnerId and administrative fields.
|
||||
db.Update(clientNote);
|
||||
await db.SaveChangesAsync(ct);
|
||||
```
|
||||
|
||||
**Патч:** отдельный DTO редактируемых полей и загрузка принадлежащей пользователю
|
||||
сущности. Тип DTO объявляется в проекте:
|
||||
|
||||
```csharp
|
||||
public sealed record EditNoteRequest(string? Title, string? Body);
|
||||
```
|
||||
|
||||
Фрагмент действия контроллера с параметрами `id` и `EditNoteRequest dto`:
|
||||
|
||||
```csharp
|
||||
if (dto.Title is null || dto.Body is null)
|
||||
return BadRequest();
|
||||
|
||||
var note = await db.Notes.SingleOrDefaultAsync(
|
||||
n => n.Id == id && n.OwnerId == currentUserId, ct);
|
||||
if (note is null)
|
||||
return NotFound();
|
||||
|
||||
note.Title = dto.Title;
|
||||
note.Body = dto.Body;
|
||||
await db.SaveChangesAsync(ct);
|
||||
return NoContent();
|
||||
```
|
||||
|
||||
Показан контракт полного обновления обоих полей, не JSON Merge Patch. При
|
||||
частичном обновлении отдельно различать отсутствующее поле и явный `null`.
|
||||
Не передавать в `Update` второй объект из запроса после загрузки безопасного.
|
||||
Если владельца можно менять конкурентно, проверка при чтении и последующая
|
||||
запись требуют подходящей транзакции/условного обновления/concurrency token.
|
||||
|
||||
**Проверить:** владелец меняет title/body; чужая запись и её владелец не меняются;
|
||||
присланный OwnerId не применяется; пустая строка сохраняется, если разрешена;
|
||||
неверный тип отвергается. Неизвестные JSON-поля могут игнорироваться сериализатором —
|
||||
не обещать их автоматический отказ без отдельной настройки.
|
||||
|
||||
</details>
|
||||
|
||||
**Основание:** [первичный материал](https://learn.microsoft.com/en-us/aspnet/core/mvc/models/model-binding).
|
||||
|
||||
<a id="cs-xml"></a>
|
||||
|
||||
<a id="cs-xml-xml-parser-permits-dtd-or-external-resolver"></a>
|
||||
|
||||
## CS-XML. XML settings и внешние ресурсы
|
||||
|
||||
**Поиск:** скрипт, правило CS-XML. Запуск: python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain CS-XML. Regex: DtdProcessing.Parse, XmlResolver=new XmlUrlResolver, ProhibitDtd=false. Точные defaults зависят от framework/API; отсутствие опасной строки не доказывает безопасность.
|
||||
|
||||
Дополнительный ручной поиск для непокрытых форм:
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'XmlReaderSettings|DtdProcessing|XmlResolver|XmlDocument|XslCompiledTransform' .
|
||||
~~~
|
||||
|
||||
Проверить явные settings и версию .NET; безопасные defaults нельзя переносить на каждый старый API.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
Разрешённый DTD/resolver загружает внешние ресурсы либо раздувает документ.
|
||||
|
||||
**Исправление:** DtdProcessing.Prohibit при ненужном DTD, XmlResolver=null и лимиты входа; передать настройки фактически используемому XmlReader. Для XSLT отдельно запретить ненужные document/script.
|
||||
|
||||
**Проверка:** Допустимый XML читается, внешние обращения отсутствуют, oversized expansion ограничен.
|
||||
|
||||
**Основание:** [первичный материал](https://learn.microsoft.com/en-us/dotnet/api/system.xml.xmlreadersettings).
|
||||
|
||||
|
||||
**Сигнал сканера — пример до:**
|
||||
|
||||
~~~csharp
|
||||
var settings = new XmlReaderSettings { DtdProcessing = DtdProcessing.Parse, XmlResolver = new XmlUrlResolver() };
|
||||
~~~
|
||||
|
||||
**Шаблон исправления:**
|
||||
|
||||
~~~csharp
|
||||
var settings = new XmlReaderSettings { DtdProcessing = DtdProcessing.Prohibit, XmlResolver = null, MaxCharactersInDocument = 1048576 };
|
||||
~~~
|
||||
|
||||
Первичная документация: [документация 1](https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca3075).
|
||||
|
||||
<a id="cs-html-raw"></a>
|
||||
|
||||
<a id="cs-html-raw-html-output-without-escaping"></a>
|
||||
|
||||
## CS-HTML-RAW. Html.Raw и IHtmlContent обходят encoding
|
||||
|
||||
**Поиск:** скрипт, правило CS-HTML-RAW. Запуск: python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain CS-HTML-RAW. Regex: Html.Raw и new HtmlString. Проверенный sanitizer не выводится из наличия вызова; доверенная статическая разметка может быть допустима.
|
||||
|
||||
Дополнительный ручной поиск для непокрытых форм:
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'Html.Raw|HtmlString|IHtmlContent|WriteLiteral' .
|
||||
~~~
|
||||
|
||||
Определить происхождение строки и реальный HTML/JS/attribute контекст Razor.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
Html.Raw(model.Text) выводит пользовательский HTML как доверенный.
|
||||
|
||||
**Исправление:** Штатный Razor encoding; sanitizer только когда rich text нужен, отдельная сериализация JS.
|
||||
|
||||
**Проверка:** Недоверенные теги, атрибуты и URL не могут выполнить скрипт; разрешённый текст и нужное форматирование отображаются корректно.
|
||||
|
||||
|
||||
**Сигнал сканера — пример до:**
|
||||
|
||||
~~~csharp
|
||||
@Html.Raw(Model.About)
|
||||
~~~
|
||||
|
||||
**Шаблон исправления:**
|
||||
|
||||
~~~csharp
|
||||
@Model.About
|
||||
~~~
|
||||
|
||||
Первичная документация: [документация 1](https://learn.microsoft.com/en-us/aspnet/core/security/cross-site-scripting).
|
||||
|
||||
<a id="cs-path"></a>
|
||||
|
||||
<a id="cs-path-pathcombine-and-getfullpath-do-not-check-ownership"></a>
|
||||
|
||||
## CS-PATH. Path.Combine и GetFullPath не проверяют owner
|
||||
|
||||
**Поиск:** вручную; отдельного правила сканера нет.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'Path.Combine|GetFullPath|File.Read|File.Write|PhysicalFile' .
|
||||
~~~
|
||||
|
||||
Сравнить полный путь/root с учётом ОС, separator и symlink; проверить право на выбранный ID.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
Абсолютный второй путь заменяет root либо строковый StartsWith путает соседний каталог.
|
||||
|
||||
**Исправление:** Серверное имя, корректный containment по компонентам, политика symlink; запись открывать без гонки подмены.
|
||||
|
||||
**Проверка:** Windows/Linux варианты, общий префикс, ссылка наружу, собственный/чужой файл.
|
||||
|
||||
<a id="cs-archive"></a>
|
||||
|
||||
<a id="cs-archive-ziparchive-entries-escape-the-directory"></a>
|
||||
|
||||
## CS-ARCHIVE. ZipArchive entry выходит из каталога
|
||||
|
||||
**Поиск:** вручную; отдельного правила сканера нет.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'ZipArchive|ExtractToFile|ExtractToDirectory|FullName' .
|
||||
~~~
|
||||
|
||||
Проверить конкретную версию API и собственный цикл по entries; наличие безопасного helper не защищает ручную запись.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
entry.FullName используется как путь без containment/лимита.
|
||||
|
||||
**Исправление:** Валидация root, links и фактического объёма, отдельное временное дерево и атомарная публикация.
|
||||
|
||||
**Проверка:** Штатный архив, absolute/traversal, дубли entry, превышение объёма.
|
||||
|
||||
**Основание:** [первичный материал](https://cheatsheetseries.owasp.org/cheatsheets/File_Upload_Cheat_Sheet.html).
|
||||
|
||||
<a id="cs-claims"></a>
|
||||
|
||||
<a id="cs-claims-incomplete-jwt-or-claims-validation"></a>
|
||||
|
||||
## CS-CLAIMS. Неполная проверка JWT/claims
|
||||
|
||||
**Поиск:** вручную; отдельного правила сканера нет.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'TokenValidationParameters|ValidateIssuer|ValidateAudience|RequireExpirationTime|FindFirst' .
|
||||
~~~
|
||||
|
||||
Сверить серверный issuer/audience/key/algorithm и трактовку отсутствующих claims; подпись не задаёт права объекта.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
Токен другого назначения принимается как auth либо отсутствующий subject превращается в default пользователя.
|
||||
|
||||
**Исправление:** Явный validation contract библиотеки, обязательный subject/purpose и resource auth; ротация ключа без бесконечного legacy fallback.
|
||||
|
||||
**Проверка:** Неверные issuer/audience/срок/назначение и валидная сессия со старыми данными.
|
||||
|
||||
<a id="cs-async-void"></a>
|
||||
|
||||
<a id="cs-async-void-async-void-hides-authorization-errors"></a>
|
||||
|
||||
## CS-ASYNC-VOID. async void скрывает ошибку auth
|
||||
|
||||
**Поиск:** вручную; отдельного правила сканера нет.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'async void|Task.Run|Authorize|async Task|GetAwaiter' .
|
||||
~~~
|
||||
|
||||
Проследить, что caller дожидается проверки; исключения из фонового действия не должны оставлять успешный ответ.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
Auth/запись запускается без await, обработчик продолжает выдачу данных.
|
||||
|
||||
**Исправление:** Task-returning pipeline и await; fail closed при ошибке и request-scoped cancellation.
|
||||
|
||||
**Проверка:** False/error/delay проверки не возвращают защищённые данные; корректный путь завершается.
|
||||
|
||||
<a id="cs-regex-timeout"></a>
|
||||
|
||||
<a id="cs-regex-timeout-untrusted-regex-input-without-a-budget"></a>
|
||||
|
||||
## CS-REGEX-TIMEOUT. Regex без бюджета на недоверенном вводе
|
||||
|
||||
**Поиск:** вручную; отдельного правила сканера нет.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'new Regex|Regex.Match|Regex.IsMatch|Regex.Replace' .
|
||||
~~~
|
||||
|
||||
Проверить timeout overload/NonBacktracking своего runtime и длину входа.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
Сложное выражение исчерпывает worker на длинном почти совпадающем тексте.
|
||||
|
||||
**Исправление:** Ограничить размер, упростить pattern; поддержанный timeout/NonBacktracking, обработать RegexMatchTimeoutException как отказ.
|
||||
|
||||
**Проверка:** Timeout не превращается в разрешение; обычные строки и допустимые regex-конструкции работают.
|
||||
|
||||
<a id="cs-auth-filter-reduce"></a>
|
||||
|
||||
<a id="cs-auth-filter-reduce-simplification-removes-a-mandatory-authorization-condition"></a>
|
||||
|
||||
## CS-AUTH-FILTER-REDUCE. Упрощение фильтра удаляет обязательное условие доступа
|
||||
|
||||
**Поиск:** вручную; отдельного правила сканера нет.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'Distinct|Remove|Reduce|AdminFilter|Equals' .
|
||||
~~~
|
||||
|
||||
Сравнить обязательное условие доступа до и после упрощения дерева запроса; проверить структурное равенство фильтров.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
**Основание:** sneakers, авторский разбор RuCTF. Равенство объектов-фильтров и
|
||||
упрощение выражения могли убрать AdminFilter.
|
||||
|
||||
**Искать:** distinct/remove/set/dedup/reduce над AST запросов; структурное
|
||||
равенство record вместо ожидаемой идентичности; объединение клиентских и
|
||||
серверных фильтров.
|
||||
|
||||
**Исправление:** обязательное условие auth добавлять вне
|
||||
пользовательского упрощения и проверять перед исполнением. Изменение record
|
||||
на class из одного разбора не универсальный рецепт.
|
||||
|
||||
**Проверка:** эквивалентные/повторённые/вложенные фильтры не расширяют права;
|
||||
порядок предикатов не влияет на доступ.
|
||||
|
||||
**Вариант A/D:** Основание и версия: [исходник/разбор 1](https://github.com/HackerDom/ructf-finals-2023/blob/a7442769909e08c39716cb18d3d1c3a99324bbf8/writeups/sneakers/README.md).
|
||||
|
||||
**Основание:** [первичный материал](https://github.com/HackerDom/ructf-finals-2023/blob/a7442769909e08c39716cb18d3d1c3a99324bbf8/writeups/sneakers/README.md).
|
||||
|
||||
<a id="cs-colliding-principal"></a>
|
||||
|
||||
<a id="cs-colliding-principal-a-normalized-character-sum-replaces-a-unique-user-id"></a>
|
||||
|
||||
## CS-COLLIDING-PRINCIPAL. Нормализованная сумма символов вместо уникального user ID
|
||||
|
||||
**Поиск:** вручную; отдельного правила сканера нет.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'UserId|UserName|ToLower|Reverse|Sum' .
|
||||
~~~
|
||||
|
||||
Сопоставить нормализованное имя, вычисленный ID и ключ owner во всех export/read/update.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
**FAUST / todo-list, код + патч организаторов.** Преобразования имени и сумма
|
||||
символов используются как идентификатор владельца; разные имена могут совпасть.
|
||||
|
||||
**Исправление:** авторизация по стабильному уникальному principal из доверенного
|
||||
хранилища, согласованная миграция записей. Исправить все пути чтения/экспорта.
|
||||
|
||||
**Проверка:** два имени с одинаковым старым ID не получают общий доступ.
|
||||
|
||||
**Вариант A/D:** Основание и версия: [исходник/разбор 1](https://github.com/fausecteam/faustctf-2024-todo-list-service/blob/e9ee8b8807c64eeb6f71a72e16f709a558525d2c/patches/deserialize.patch); [исходник/разбор 2](https://github.com/fausecteam/faustctf-2024-todo-list-service/blob/e9ee8b8807c64eeb6f71a72e16f709a558525d2c/patches/TodoController.cs); [исходник/разбор 3](https://github.com/fausecteam/faustctf-2024-todo-list-service/blob/e9ee8b8807c64eeb6f71a72e16f709a558525d2c/service/service/Services/Serializer.cs); [исходник/разбор 4](https://github.com/fausecteam/faustctf-2024-todo-list-service/blob/e9ee8b8807c64eeb6f71a72e16f709a558525d2c/service/service/Services/UserManager.cs); [исходник/разбор 5](https://github.com/fausecteam/faustctf-2024-todo-list-service/blob/e9ee8b8807c64eeb6f71a72e16f709a558525d2c/service/service/Models/Filter.cs).
|
||||
|
||||
**Основание:** [первичный материал](https://github.com/fausecteam/faustctf-2024-todo-list-service/blob/e9ee8b8807c64eeb6f71a72e16f709a558525d2c/patches/deserialize.patch).
|
||||
|
||||
<a id="cs-jwt-validation"></a>
|
||||
|
||||
<a id="cs-jwt-validation-weakened-net-token-validation"></a>
|
||||
|
||||
## CS-JWT-VALIDATION. Ослаблены параметры проверки токенов .NET
|
||||
|
||||
**Поиск:** скрипт, правило CS-JWT-VALIDATION. Запуск: python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain CS-JWT-VALIDATION. Regex: явные false для ValidateLifetime/Issuer/Audience, RequireSignedTokens/ExpirationTime. ValidateIssuerSigningKey=false отдельно не трактуется как отсутствие криптографической проверки.
|
||||
|
||||
**Уязвимый вариант:** Отключение lifetime/issuer/audience или требования подписи может принять токен вне назначенного контракта.
|
||||
|
||||
~~~csharp
|
||||
new TokenValidationParameters { ValidateLifetime = false, ValidateAudience = false, RequireSignedTokens = false };
|
||||
~~~
|
||||
|
||||
**Исправление:** Проверять обязательную подпись, ключ, время, издателя и получателя; custom validators должны сохранять эти инварианты.
|
||||
|
||||
~~~csharp
|
||||
new TokenValidationParameters { ValidateLifetime = true, ValidateAudience = true, ValidAudience = "notes", ValidateIssuer = true, ValidIssuer = "auth", RequireSignedTokens = true, RequireExpirationTime = true, IssuerSigningKey = trustedKey };
|
||||
~~~
|
||||
|
||||
**Проверка:** Неподписанный, просроченный и чужой токен не авторизует; штатный токен принимается.
|
||||
|
||||
Первичная документация: [документация 1](https://learn.microsoft.com/en-us/dotnet/api/microsoft.identitymodel.tokens.tokenvalidationparameters).
|
||||
|
||||
<a id="cs-tls-validation"></a>
|
||||
|
||||
<a id="cs-tls-validation-https-validation-callback-always-accepts"></a>
|
||||
|
||||
## CS-TLS-VALIDATION. HTTPS validation callback всегда разрешает
|
||||
|
||||
**Поиск:** скрипт, правило CS-TLS-VALIDATION. Запуск: python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain CS-TLS-VALIDATION. Regex: DangerousAcceptAnyServerCertificateValidator и простая true-lambda для certificate callbacks. Произвольные методы и body-lambda требуют ручного анализа.
|
||||
|
||||
**Уязвимый вариант:** Callback, безусловно принимающий сертификат, обходит стандартную проверку TLS.
|
||||
|
||||
~~~csharp
|
||||
handler.ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator;
|
||||
~~~
|
||||
|
||||
**Исправление:** Использовать стандартную проверку и доверенный CA; custom trust реализовать без безусловного true.
|
||||
|
||||
~~~csharp
|
||||
var handler = new HttpClientHandler();
|
||||
var client = new HttpClient(handler);
|
||||
~~~
|
||||
|
||||
**Проверка:** Корректный сертификат работает, чужое имя/CA и истечение дают ошибку.
|
||||
|
||||
Первичная документация: [документация 1](https://learn.microsoft.com/en-us/dotnet/api/system.net.http.httpclienthandler.dangerousacceptanyservercertificatevalidator).
|
||||
|
||||
<a id="cs-ldap-filter"></a>
|
||||
|
||||
<a id="cs-ldap-filter-directorysearcher-filter-concatenates-a-value"></a>
|
||||
|
||||
## CS-LDAP-FILTER. Фильтр DirectorySearcher собирается конкатенацией
|
||||
|
||||
**Поиск:** правило сканера CS-LDAP-FILTER. Точный контракт детектора: `--explain CS-LDAP-FILTER`. Regex с лексическими исключениями: new DirectorySearcher, первый аргумент которого — строковый литерал, объединённый с идентификатором. Не проверяет присваивания Filter, интерполированные строки, реализации вспомогательных функций и произвольные aliases типов.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
~~~csharp
|
||||
var query = new DirectorySearcher("(uid=" + name + ")");
|
||||
~~~
|
||||
|
||||
**Исправление:** Используйте проверенный конструктор LDAP-фильтров с экранированием для контекста фильтра и фиксированной политикой атрибутов и области поиска; вспомогательная функция реализуется в приложении.
|
||||
|
||||
~~~csharp
|
||||
var query = new DirectorySearcher(BuildReviewedLdapFilter(name)); // helper implements filter-context escaping
|
||||
~~~
|
||||
|
||||
**Проверка:** Метасимволы не добавляют условия и не расширяют результат; поддерживаемые поисковые запросы остаются совместимыми.
|
||||
|
||||
[Первичный источник 1](https://learn.microsoft.com/en-us/dotnet/api/system.directoryservices.directorysearcher.filter)
|
||||
@@ -0,0 +1,607 @@
|
||||
# C# / .NET: find, fix and verify
|
||||
|
||||
English | [Русский](csharp-RU.md)
|
||||
|
||||
[Catalog](README.md) · [Scanner](../offline-scanner.md) · [Patch verification](../patch-validation.md)
|
||||
|
||||
20 sections. Each follows **Search → Vulnerable example → Fix → Verification**.
|
||||
Run `rg` from a local service checkout; searches only read files. Derive the actor/owner from a verified session, not request data. Adapt examples to the actual API and contract.
|
||||
|
||||
## Contents
|
||||
|
||||
- [CS-DESERIALIZE — Type-controlled .NET deserialization](#cs-deserialize)
|
||||
- [CS-ENUM — Enum.TryParse requires an allowed-value check](#cs-enum)
|
||||
- [CS-SQL — Dynamic .NET SQL](#cs-sql)
|
||||
- [CS-GUID-BYTES — Byte-order Guid protocol boundary](#cs-guid-bytes)
|
||||
- [CS-PROCESS — .NET process creation](#cs-process)
|
||||
- [CS-IGNORE-FILTERS — Global query filters disabled](#cs-ignore-filters)
|
||||
- [CS-ALLOWANON — AllowAnonymous route](#cs-allowanon)
|
||||
- [CS-MASS-ASSIGN — Client entities update the database wholesale](#cs-mass-assign)
|
||||
- [CS-XML — XML parser permits DTD or external resolver](#cs-xml)
|
||||
- [CS-HTML-RAW — HTML output without escaping](#cs-html-raw)
|
||||
- [CS-PATH — Path.Combine and GetFullPath do not check ownership](#cs-path)
|
||||
- [CS-ARCHIVE — ZipArchive entries escape the directory](#cs-archive)
|
||||
- [CS-CLAIMS — Incomplete JWT or claims validation](#cs-claims)
|
||||
- [CS-ASYNC-VOID — async void hides authorization errors](#cs-async-void)
|
||||
- [CS-REGEX-TIMEOUT — Untrusted regex input without a budget](#cs-regex-timeout)
|
||||
- [CS-AUTH-FILTER-REDUCE — Simplification removes a mandatory authorization condition](#cs-auth-filter-reduce)
|
||||
- [CS-COLLIDING-PRINCIPAL — A normalized character sum replaces a unique user ID](#cs-colliding-principal)
|
||||
- [CS-JWT-VALIDATION — Weakened .NET token validation](#cs-jwt-validation)
|
||||
- [CS-TLS-VALIDATION — HTTPS validation callback always accepts](#cs-tls-validation)
|
||||
- [CS-LDAP-FILTER — DirectorySearcher filter concatenates a value](#cs-ldap-filter)
|
||||
|
||||
<a id="cs-deserialize"></a>
|
||||
|
||||
## CS-DESERIALIZE. Type-controlled .NET deserialization
|
||||
|
||||
**Search:** scanner rule CS-DESERIALIZE. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain CS-DESERIALIZE` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
~~~csharp
|
||||
var formatter = new BinaryFormatter();
|
||||
~~~
|
||||
|
||||
**Fix:** Use explicit DTOs and a supported serializer with schema/size checks; remove unrestricted type activation and migrate legacy data.
|
||||
|
||||
~~~csharp
|
||||
var value = JsonSerializer.Deserialize<MessageDto>(json); // validate fields
|
||||
~~~
|
||||
|
||||
**Verification:** Unknown types fail before side effects; valid records parse.
|
||||
|
||||
**A/D variant:** Deserialization triggers setter side effects. **FAUST / todo-list, source and organizer patch.** TypeNameHandling.Objects permits runtime-type selection; setting Filter model fields writes to the database. Checking the result after object construction may be too late.
|
||||
|
||||
**Patch:** A concrete DTO without external type selection, explicit validation and a separate persistence operation. **Test:** Unknown types create neither objects nor rows; normal import/export remains compatible. **Search:** CS-DESERIALIZE.
|
||||
|
||||
[source/write-up 1](https://github.com/fausecteam/faustctf-2024-todo-list-service/blob/e9ee8b8807c64eeb6f71a72e16f709a558525d2c/patches/deserialize.patch); [source/write-up 2](https://github.com/fausecteam/faustctf-2024-todo-list-service/blob/e9ee8b8807c64eeb6f71a72e16f709a558525d2c/patches/TodoController.cs); [source/write-up 3](https://github.com/fausecteam/faustctf-2024-todo-list-service/blob/e9ee8b8807c64eeb6f71a72e16f709a558525d2c/service/service/Services/Serializer.cs); [source/write-up 4](https://github.com/fausecteam/faustctf-2024-todo-list-service/blob/e9ee8b8807c64eeb6f71a72e16f709a558525d2c/service/service/Services/UserManager.cs); [source/write-up 5](https://github.com/fausecteam/faustctf-2024-todo-list-service/blob/e9ee8b8807c64eeb6f71a72e16f709a558525d2c/service/service/Models/Filter.cs).
|
||||
|
||||
<a id="cs-enum"></a>
|
||||
|
||||
## CS-ENUM. Enum.TryParse requires an allowed-value check
|
||||
|
||||
**Search:** scanner rule CS-ENUM. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain CS-ENUM` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
~~~csharp
|
||||
bool ok = Enum.TryParse(input, out FilterKind kind);
|
||||
~~~
|
||||
|
||||
**Fix:** Validate allowed named values; parsing success alone does not prove enum membership.
|
||||
|
||||
~~~csharp
|
||||
if (!TryParseAllowedFilter(input, out FilterKind kind)) return BadRequest(); // helper validates named allowlist
|
||||
~~~
|
||||
|
||||
**Verification:** Unnamed numeric values and unsupported flags fail; supported filters work.
|
||||
|
||||
**A/D variant:** Numeric enum values outside the allowed set. **Reference:** sneakers, RuCTF author write-up. TryParse may accept a number with no declared name. Scanner: CS-ENUM, including already-corrected call sites.
|
||||
|
||||
~~~csharp
|
||||
if (!Enum.TryParse<FilterKind>(input, out var kind) ||
|
||||
!Enum.IsDefined(typeof(FilterKind), kind))
|
||||
return BadRequest();
|
||||
~~~
|
||||
|
||||
Flags require an explicit allowed mask and combination policy. **Test:** Every allowed name, undeclared numbers, negative/oversized values and combinations. Value validation is not authorization.
|
||||
|
||||
[source/write-up 1](https://github.com/HackerDom/ructf-finals-2023/blob/a7442769909e08c39716cb18d3d1c3a99324bbf8/writeups/sneakers/README.md).
|
||||
|
||||
<a id="cs-sql"></a>
|
||||
|
||||
## CS-SQL. Dynamic .NET SQL
|
||||
|
||||
**Search:** scanner rule CS-SQL. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain CS-SQL` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
~~~csharp
|
||||
context.Notes.FromSqlRaw("SELECT * FROM notes WHERE name=" + name);
|
||||
~~~
|
||||
|
||||
**Fix:** Use provider-supported parameters and allowlisted identifiers.
|
||||
|
||||
~~~csharp
|
||||
context.Notes.FromSqlRaw("SELECT * FROM notes WHERE name={0}", name);
|
||||
~~~
|
||||
|
||||
**Verification:** Quotes cannot change SQL structure; tenant restrictions remain.
|
||||
|
||||
<details>
|
||||
<summary>Expanded example and limitations</summary>
|
||||
|
||||
```csharp
|
||||
// Vulnerable: interpolation has already put client data into SQL source.
|
||||
var rows = await db.Notes
|
||||
.FromSqlRaw($"SELECT * FROM Notes WHERE Title = '{title}'")
|
||||
.ToListAsync(ct);
|
||||
```
|
||||
|
||||
**Minimal patch for a simple search: owner-scoped LINQ:**
|
||||
|
||||
```csharp
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
var rows = await db.Notes
|
||||
.Where(n => n.OwnerId == currentUserId && n.Title == title)
|
||||
.ToListAsync(ct);
|
||||
```
|
||||
|
||||
When raw SQL is necessary, FromSqlInterpolated receives a FormattableString and parameterizes values. Do not first convert it to string and then pass it to FromSqlRaw. FromSql appeared in EF Core 7; select the installed version's API. Column names require fixed selection.
|
||||
|
||||
**Check:** Apostrophes/Unicode remain literal search data, foreign rows are absent, and pagination/old records work. Test custom providers and LINQ translation against the actual database, not only an in-memory substitute.
|
||||
|
||||
</details>
|
||||
|
||||
<a id="cs-guid-bytes"></a>
|
||||
|
||||
## CS-GUID-BYTES. Byte-order Guid protocol boundary
|
||||
|
||||
**Search:** scanner rule CS-GUID-BYTES. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain CS-GUID-BYTES` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
~~~csharp
|
||||
var value = new Guid(wireBytes);
|
||||
~~~
|
||||
|
||||
**Fix:** Agree on byte order with peers; use canonical text or explicit conversion, not arbitrary reversal.
|
||||
|
||||
~~~csharp
|
||||
var value = Guid.ParseExact(wireText, "D");
|
||||
~~~
|
||||
|
||||
**Verification:** Asymmetric UUID vectors agree across C#/Python, database and cache.
|
||||
|
||||
<a id="cs-process"></a>
|
||||
|
||||
## CS-PROCESS. .NET process creation
|
||||
|
||||
**Search:** scanner rule CS-PROCESS. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain CS-PROCESS` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
~~~csharp
|
||||
Process.Start("sh", "-c " + command);
|
||||
~~~
|
||||
|
||||
**Fix:** Prefer a library operation or fixed executable plus ArgumentList. UseShellExecute=false does not neutralize explicit sh/cmd or option injection.
|
||||
|
||||
~~~csharp
|
||||
var digest = SHA256.HashData(Encoding.UTF8.GetBytes(text));
|
||||
~~~
|
||||
|
||||
**Verification:** Quotes stay data and expected output format is preserved.
|
||||
|
||||
<details>
|
||||
<summary>Expanded example and limitations</summary>
|
||||
|
||||
```csharp
|
||||
// Vulnerable on Linux: UseShellExecute=false does not prevent explicit /bin/sh.
|
||||
var psi = new System.Diagnostics.ProcessStartInfo("/bin/sh") { UseShellExecute = false };
|
||||
psi.ArgumentList.Add("-c");
|
||||
psi.ArgumentList.Add("printf '%s' '" + text + "' | sha256sum");
|
||||
System.Diagnostics.Process.Start(psi);
|
||||
```
|
||||
|
||||
**Patch for text SHA-256, .NET 6+:**
|
||||
|
||||
```csharp
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
|
||||
static string DigestText(string text)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(text);
|
||||
byte[] sum = SHA256.HashData(Encoding.UTF8.GetBytes(text));
|
||||
return Convert.ToHexString(sum).ToLowerInvariant();
|
||||
}
|
||||
```
|
||||
|
||||
Preserve external formatting and encoding. If a process is genuinely required, separate executable and ArgumentList; users must still not select dangerous program options. Content SHA-256 is not standalone password storage.
|
||||
|
||||
**Check:** Known digest, empty text, Unicode, quotes/newlines; no child process or environment leakage on failure.
|
||||
|
||||
</details>
|
||||
|
||||
**Reference:** [primary source](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.processstartinfo.argumentlist).
|
||||
|
||||
<a id="cs-ignore-filters"></a>
|
||||
|
||||
## CS-IGNORE-FILTERS. Global query filters disabled
|
||||
|
||||
**Search:** scanner rule CS-IGNORE-FILTERS. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain CS-IGNORE-FILTERS` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
~~~csharp
|
||||
var rows = db.Notes.IgnoreQueryFilters().ToList();
|
||||
~~~
|
||||
|
||||
**Fix:** Do not disable tenant/auth filters merely for soft-delete; admin bypass requires explicit authorization and query restrictions.
|
||||
|
||||
~~~csharp
|
||||
var rows = db.Notes.Where(n => n.OwnerId == userId).ToList();
|
||||
~~~
|
||||
|
||||
**Verification:** Test two tenants, deleted records and exports against the actual provider SQL.
|
||||
|
||||
**Reference:** [primary source](https://learn.microsoft.com/en-us/ef/core/querying/filters).
|
||||
|
||||
<a id="cs-allowanon"></a>
|
||||
|
||||
## CS-ALLOWANON. AllowAnonymous route
|
||||
|
||||
**Search:** scanner rule CS-ALLOWANON. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain CS-ALLOWANON` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
~~~csharp
|
||||
[AllowAnonymous]
|
||||
public IActionResult PrivateNote() => View();
|
||||
~~~
|
||||
|
||||
**Fix:** Review effective endpoint metadata/ownership; AllowAnonymous may override Authorize. Login/health may be intentionally public.
|
||||
|
||||
~~~csharp
|
||||
[Authorize]
|
||||
public IActionResult PrivateNote() => View();
|
||||
~~~
|
||||
|
||||
**Verification:** Public login works; private endpoints and nested operations require authorization.
|
||||
|
||||
**Reference:** [primary source](https://learn.microsoft.com/en-us/aspnet/core/security/authorization/simple).
|
||||
|
||||
<a id="cs-mass-assign"></a>
|
||||
|
||||
## CS-MASS-ASSIGN. Client entities update the database wholesale
|
||||
|
||||
**Search:** manual review; no separate scanner rule.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'Update\(|TryUpdateModelAsync|Bind\(|FromBody|SaveChanges' .
|
||||
~~~
|
||||
|
||||
Compare DTOs, entities and mutable fields; ensure a second client object is not used after safely loading the owned one.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
`db.Update(clientNote)` applies OwnerId/Role from JSON.
|
||||
|
||||
**Fix:** Editable-fields DTO, lookup by ID+owner and explicit assignment; use concurrency tokens if ownership can change.
|
||||
|
||||
**Verification:** Owned fields change; another user's record/owner does not. Distinguish absent fields from null according to contract.
|
||||
|
||||
<details>
|
||||
<summary>Expanded example and limitations</summary>
|
||||
|
||||
```csharp
|
||||
// Vulnerable: the supplied entity may contain OwnerId and administrative fields.
|
||||
db.Update(clientNote);
|
||||
await db.SaveChangesAsync(ct);
|
||||
```
|
||||
|
||||
**Patch:** Separate editable-fields DTO and an owner-scoped entity lookup. Declare the DTO in the project:
|
||||
|
||||
```csharp
|
||||
public sealed record EditNoteRequest(string? Title, string? Body);
|
||||
```
|
||||
|
||||
Controller action fragment with parameters `id` and `EditNoteRequest dto`:
|
||||
|
||||
```csharp
|
||||
if (dto.Title is null || dto.Body is null)
|
||||
return BadRequest();
|
||||
|
||||
var note = await db.Notes.SingleOrDefaultAsync(
|
||||
n => n.Id == id && n.OwnerId == currentUserId, ct);
|
||||
if (note is null)
|
||||
return NotFound();
|
||||
|
||||
note.Title = dto.Title;
|
||||
note.Body = dto.Body;
|
||||
await db.SaveChangesAsync(ct);
|
||||
return NoContent();
|
||||
```
|
||||
|
||||
This is a full update of both fields, not JSON Merge Patch. For partial updates distinguish omitted fields from explicit null. Do not pass a second request object to Update after safely loading the first. Concurrent ownership changes require a suitable transaction, conditional mutation or concurrency token.
|
||||
|
||||
**Check:** Owners edit title/body; foreign records/owners remain unchanged; supplied OwnerId is ignored; empty strings persist if allowed; wrong types fail. Unknown JSON fields may be ignored by the serializer—do not promise rejection without explicit configuration.
|
||||
|
||||
</details>
|
||||
|
||||
**Reference:** [primary source](https://learn.microsoft.com/en-us/aspnet/core/mvc/models/model-binding).
|
||||
|
||||
<a id="cs-xml"></a>
|
||||
|
||||
## CS-XML. XML parser permits DTD or external resolver
|
||||
|
||||
**Search:** scanner rule CS-XML. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain CS-XML` for details. Regex: DtdProcessing.Parse, XmlResolver=new XmlUrlResolver and ProhibitDtd=false. Defaults depend on framework/API; absence of a match is not proof of safety.
|
||||
|
||||
Additional manual search for forms outside automatic coverage:
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'XmlReaderSettings|DtdProcessing|XmlResolver|XmlDocument|XslCompiledTransform' .
|
||||
~~~
|
||||
|
||||
Review explicit settings and the actual .NET version; modern safe defaults do not apply to every older API.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
An enabled DTD/resolver fetches external resources or expands the document.
|
||||
|
||||
**Fix:** Prohibit DTD, remove external resolver and bound input; pass these settings to the actual XmlReader.
|
||||
|
||||
**Verification:** Ordinary XML works; external resources/DTD fail and size is bounded.
|
||||
|
||||
**Reference:** [primary source](https://learn.microsoft.com/en-us/dotnet/api/system.xml.xmlreadersettings).
|
||||
|
||||
**Scanner example before:**
|
||||
|
||||
~~~csharp
|
||||
var settings = new XmlReaderSettings { DtdProcessing = DtdProcessing.Parse, XmlResolver = new XmlUrlResolver() };
|
||||
~~~
|
||||
|
||||
**Fix template:**
|
||||
|
||||
~~~csharp
|
||||
var settings = new XmlReaderSettings { DtdProcessing = DtdProcessing.Prohibit, XmlResolver = null, MaxCharactersInDocument = 1048576 };
|
||||
~~~
|
||||
|
||||
Primary documentation: [reference 1](https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca3075).
|
||||
|
||||
<a id="cs-html-raw"></a>
|
||||
|
||||
## CS-HTML-RAW. HTML output without escaping
|
||||
|
||||
**Search:** scanner rule CS-HTML-RAW. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain CS-HTML-RAW` for details. Regex: Html.Raw and new HtmlString. Sanitization is not inferred from a call; trusted static markup may be legitimate.
|
||||
|
||||
Additional manual search for forms outside automatic coverage:
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'Html.Raw|HtmlString|IHtmlContent|WriteLiteral' .
|
||||
~~~
|
||||
|
||||
Determine data origin and Razor's actual HTML, JavaScript or attribute context.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
`Html.Raw(model.Text)` treats user-controlled HTML as trusted.
|
||||
|
||||
**Fix:** Use regular Razor output or an allowlisted HTML sanitizer for supported rich text; consider URL/JS context.
|
||||
|
||||
**Verification:** Untrusted tags, attributes and URLs cannot execute script; permitted text renders.
|
||||
|
||||
**Scanner example before:**
|
||||
|
||||
~~~csharp
|
||||
@Html.Raw(Model.About)
|
||||
~~~
|
||||
|
||||
**Fix template:**
|
||||
|
||||
~~~csharp
|
||||
@Model.About
|
||||
~~~
|
||||
|
||||
Primary documentation: [reference 1](https://learn.microsoft.com/en-us/aspnet/core/security/cross-site-scripting).
|
||||
|
||||
<a id="cs-path"></a>
|
||||
|
||||
## CS-PATH. Path.Combine and GetFullPath do not check ownership
|
||||
|
||||
**Search:** manual review; no separate scanner rule.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'Path.Combine|GetFullPath|File.Read|File.Write|PhysicalFile' .
|
||||
~~~
|
||||
|
||||
Compare full path/root with OS, separator and symlink semantics; authorize the selected ID.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
An absolute second path replaces the root, or string StartsWith accepts a similarly named sibling directory.
|
||||
|
||||
**Fix:** Server-side names, component-aware containment and symlink policy; open writes without replacement races.
|
||||
|
||||
**Verification:** Windows/Linux forms, shared prefixes, outward links and own/foreign files.
|
||||
|
||||
<a id="cs-archive"></a>
|
||||
|
||||
## CS-ARCHIVE. ZipArchive entries escape the directory
|
||||
|
||||
**Search:** manual review; no separate scanner rule.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'ZipArchive|ExtractToFile|ExtractToDirectory|FullName' .
|
||||
~~~
|
||||
|
||||
Review the actual API version and custom entry loop; a safe helper does not protect separately implemented writes.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
`entry.FullName` becomes a path without containment or size limits.
|
||||
|
||||
**Fix:** Validate root/links and actual expanded volume; use a separate temporary tree and atomic publication.
|
||||
|
||||
**Verification:** Ordinary archives, absolute/traversal names, duplicate entries and expanded-size overflow.
|
||||
|
||||
**Reference:** [primary source](https://cheatsheetseries.owasp.org/cheatsheets/File_Upload_Cheat_Sheet.html).
|
||||
|
||||
<a id="cs-claims"></a>
|
||||
|
||||
## CS-CLAIMS. Incomplete JWT or claims validation
|
||||
|
||||
**Search:** manual review; no separate scanner rule.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'TokenValidationParameters|ValidateIssuer|ValidateAudience|RequireExpirationTime|FindFirst' .
|
||||
~~~
|
||||
|
||||
Review server-side issuer/audience/key/algorithm policy and missing claims; a signature does not authorize an object.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
A token intended for another purpose is accepted for authentication, or missing subject becomes a default user.
|
||||
|
||||
**Fix:** Explicit library validation contract, required subject/purpose and resource authorization; rotate keys without indefinite legacy fallback.
|
||||
|
||||
**Verification:** Wrong issuer/audience/expiry/purpose plus valid sessions and old data.
|
||||
|
||||
<a id="cs-async-void"></a>
|
||||
|
||||
## CS-ASYNC-VOID. async void hides authorization errors
|
||||
|
||||
**Search:** manual review; no separate scanner rule.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'async void|Task.Run|Authorize|async Task|GetAwaiter' .
|
||||
~~~
|
||||
|
||||
Ensure callers await verification; background exceptions must not leave successful responses.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
Authorization or writes start without await while the handler continues returning data.
|
||||
|
||||
**Fix:** A Task-returning pipeline with await, fail-closed errors and request-scoped cancellation.
|
||||
|
||||
**Verification:** False/error/delayed checks never return protected data; legitimate requests complete.
|
||||
|
||||
<a id="cs-regex-timeout"></a>
|
||||
|
||||
## CS-REGEX-TIMEOUT. Untrusted regex input without a budget
|
||||
|
||||
**Search:** manual review; no separate scanner rule.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'new Regex|Regex.Match|Regex.IsMatch|Regex.Replace' .
|
||||
~~~
|
||||
|
||||
Review timeout overloads/NonBacktracking support in the installed runtime and input length limits.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
A complex expression consumes a worker on a long near-match.
|
||||
|
||||
**Fix:** Bound size, simplify patterns, use supported timeout/NonBacktracking modes and treat RegexMatchTimeoutException as rejection.
|
||||
|
||||
**Verification:** Timeout never becomes permission; ordinary strings and required regex constructs still work.
|
||||
|
||||
<a id="cs-auth-filter-reduce"></a>
|
||||
|
||||
## CS-AUTH-FILTER-REDUCE. Simplification removes a mandatory authorization condition
|
||||
|
||||
**Search:** manual review; no separate scanner rule.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'Distinct|Remove|Reduce|AdminFilter|Equals' .
|
||||
~~~
|
||||
|
||||
Compare mandatory access conditions before and after query-tree simplification; inspect structural equality of filters.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
**Reference:** sneakers, RuCTF author write-up. Filter-object equality and expression simplification could remove AdminFilter.
|
||||
|
||||
**Search:** distinct/remove/set/dedup/reduce on query ASTs, record structural equality where identity was expected, and combinations of client/server filters.
|
||||
|
||||
**Fix:** Add mandatory authorization outside user-controlled simplification and verify it before execution. Changing record to class in one write-up is not a universal remedy.
|
||||
|
||||
**Verification:** Equivalent, duplicate and nested filters never broaden access; predicate order does not affect permissions.
|
||||
|
||||
**A/D variant:** Source and version: [source/write-up 1](https://github.com/HackerDom/ructf-finals-2023/blob/a7442769909e08c39716cb18d3d1c3a99324bbf8/writeups/sneakers/README.md).
|
||||
|
||||
**Reference:** [primary source](https://github.com/HackerDom/ructf-finals-2023/blob/a7442769909e08c39716cb18d3d1c3a99324bbf8/writeups/sneakers/README.md).
|
||||
|
||||
<a id="cs-colliding-principal"></a>
|
||||
|
||||
## CS-COLLIDING-PRINCIPAL. A normalized character sum replaces a unique user ID
|
||||
|
||||
**Search:** manual review; no separate scanner rule.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'UserId|UserName|ToLower|Reverse|Sum' .
|
||||
~~~
|
||||
|
||||
Compare normalized names, computed IDs and owner keys across export/read/update.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
**FAUST / todo-list, source and organizer patch.** Name transformations and character sums identify owners; different names can collide.
|
||||
|
||||
**Fix:** Authorize with stable unique principals from trusted storage and migrate existing records coherently. Fix every read/export path.
|
||||
|
||||
**Verification:** Two names sharing the old ID never share access.
|
||||
|
||||
**A/D variant:** Source and version: [source/write-up 1](https://github.com/fausecteam/faustctf-2024-todo-list-service/blob/e9ee8b8807c64eeb6f71a72e16f709a558525d2c/patches/deserialize.patch); [source/write-up 2](https://github.com/fausecteam/faustctf-2024-todo-list-service/blob/e9ee8b8807c64eeb6f71a72e16f709a558525d2c/patches/TodoController.cs); [source/write-up 3](https://github.com/fausecteam/faustctf-2024-todo-list-service/blob/e9ee8b8807c64eeb6f71a72e16f709a558525d2c/service/service/Services/Serializer.cs); [source/write-up 4](https://github.com/fausecteam/faustctf-2024-todo-list-service/blob/e9ee8b8807c64eeb6f71a72e16f709a558525d2c/service/service/Services/UserManager.cs); [source/write-up 5](https://github.com/fausecteam/faustctf-2024-todo-list-service/blob/e9ee8b8807c64eeb6f71a72e16f709a558525d2c/service/service/Models/Filter.cs).
|
||||
|
||||
**Reference:** [primary source](https://github.com/fausecteam/faustctf-2024-todo-list-service/blob/e9ee8b8807c64eeb6f71a72e16f709a558525d2c/patches/deserialize.patch).
|
||||
|
||||
<a id="cs-jwt-validation"></a>
|
||||
|
||||
## CS-JWT-VALIDATION. Weakened .NET token validation
|
||||
|
||||
**Search:** scanner rule CS-JWT-VALIDATION. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain CS-JWT-VALIDATION` for details. Regex: explicit false for ValidateLifetime/Issuer/Audience and RequireSignedTokens/ExpirationTime. ValidateIssuerSigningKey=false alone is not treated as missing signature verification.
|
||||
|
||||
**Vulnerable example:** Disabling lifetime/issuer/audience validation or signature requirements accepts tokens outside the intended contract.
|
||||
|
||||
~~~csharp
|
||||
new TokenValidationParameters { ValidateLifetime = false, ValidateAudience = false, RequireSignedTokens = false };
|
||||
~~~
|
||||
|
||||
**Fix:** Validate signature, key, time, issuer and audience; custom validators must retain these invariants.
|
||||
|
||||
~~~csharp
|
||||
new TokenValidationParameters { ValidateLifetime = true, ValidateAudience = true, ValidAudience = "notes", ValidateIssuer = true, ValidIssuer = "auth", RequireSignedTokens = true, RequireExpirationTime = true, IssuerSigningKey = trustedKey };
|
||||
~~~
|
||||
|
||||
**Verification:** Unsigned, expired and foreign tokens fail; valid tokens pass.
|
||||
|
||||
Primary documentation: [reference 1](https://learn.microsoft.com/en-us/dotnet/api/microsoft.identitymodel.tokens.tokenvalidationparameters).
|
||||
|
||||
<a id="cs-tls-validation"></a>
|
||||
|
||||
## CS-TLS-VALIDATION. HTTPS validation callback always accepts
|
||||
|
||||
**Search:** scanner rule CS-TLS-VALIDATION. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain CS-TLS-VALIDATION` for details. Regex: DangerousAcceptAnyServerCertificateValidator and simple true-lambdas for certificate callbacks. Arbitrary methods and block-bodied lambdas need manual review.
|
||||
|
||||
**Vulnerable example:** An unconditional certificate-accepting callback bypasses standard TLS validation.
|
||||
|
||||
~~~csharp
|
||||
handler.ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator;
|
||||
~~~
|
||||
|
||||
**Fix:** Use default certificate checks and trusted CA; custom trust must not unconditionally accept.
|
||||
|
||||
~~~csharp
|
||||
var handler = new HttpClientHandler();
|
||||
var client = new HttpClient(handler);
|
||||
~~~
|
||||
|
||||
**Verification:** Valid certificates work; wrong host/CA and expiry fail.
|
||||
|
||||
Primary documentation: [reference 1](https://learn.microsoft.com/en-us/dotnet/api/system.net.http.httpclienthandler.dangerousacceptanyservercertificatevalidator).
|
||||
|
||||
<a id="cs-ldap-filter"></a>
|
||||
|
||||
## CS-LDAP-FILTER. DirectorySearcher filter concatenates a value
|
||||
|
||||
**Search:** scanner rule CS-LDAP-FILTER. Use `--explain CS-LDAP-FILTER` for the exact detector contract. Regex with lexical exclusions: new DirectorySearcher with a first string literal concatenated with an identifier. Does not inspect Filter assignments, interpolated strings, helper implementations or arbitrary type aliases.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
~~~csharp
|
||||
var query = new DirectorySearcher("(uid=" + name + ")");
|
||||
~~~
|
||||
|
||||
**Fix:** Use a reviewed LDAP filter builder with filter-context escaping and fixed attribute/scope policy; the helper is application-specific.
|
||||
|
||||
~~~csharp
|
||||
var query = new DirectorySearcher(BuildReviewedLdapFilter(name)); // helper implements filter-context escaping
|
||||
~~~
|
||||
|
||||
**Verification:** Metacharacters cannot add conditions or broaden results; supported lookups remain compatible.
|
||||
|
||||
[Primary reference 1](https://learn.microsoft.com/en-us/dotnet/api/system.directoryservices.directorysearcher.filter)
|
||||
@@ -0,0 +1,682 @@
|
||||
<a id="go-find-fix-and-verify"></a>
|
||||
|
||||
# Go: поиск и исправление
|
||||
|
||||
[English](go.md) | Русский
|
||||
|
||||
[Вся база](README-RU.md) · [Сканер](../offline-scanner-RU.md) · [Проверка патча](../patch-validation-RU.md)
|
||||
|
||||
19 разделов. Формат: **Поиск → Уязвимый вариант → Исправление → Проверка**.
|
||||
Команды `rg` выполняются в корне локальной копии сервиса и только читают файлы. Субъект/владелец определяется по проверенной сессии, а не данным запроса. Примеры нужно адаптировать к реальным API и контракту.
|
||||
|
||||
Автоматические находки — ограниченные синтаксические сигналы для проверки. AST-анализ не разрешает типы и не отслеживает данные между функциями; regex не заменяет парсер языка. Комментарии, строки и одноимённые пользовательские API могут давать совпадения. Проверьте фактическое исполнение, входные данные, авторизацию и границы доверия.
|
||||
|
||||
<a id="contents"></a>
|
||||
|
||||
## Содержание
|
||||
|
||||
- [GO-SQL — Динамический SQL Go](#go-sql)
|
||||
- [GO-HASH-SUM — Непустой аргумент hash.Sum](#go-hash-sum)
|
||||
- [GO-HTML — Обход autoescape Go](#go-html)
|
||||
- [GO-TLS — InsecureSkipVerify](#go-tls)
|
||||
- [GO-SHELL — Go exec.Command запускает shell](#go-shell)
|
||||
- [GO-CRC — CRC используется как идентификатор/контроль доверия](#go-crc)
|
||||
- [GO-MATH-RAND — math/rand рядом с возможным секретом](#go-math-rand)
|
||||
- [GO-READALL-BODY — ReadAll тела запроса](#go-readall-body)
|
||||
- [GO-PPROF — pprof регистрируется на HTTP mux](#go-pprof)
|
||||
- [GO-FILESERVER — FileServer публикует дерево файлов](#go-fileserver)
|
||||
- [GO-AUTH-RETURN — После http.Error выполнение продолжается](#go-auth-return)
|
||||
- [GO-JSON-FIELDS — JSON в entity и неоднозначные ключи](#go-json-fields)
|
||||
- [GO-RACE — Общие map/slice и check-then-use](#go-race)
|
||||
- [GO-ERROR-DEFAULT — Игнорирование ошибки даёт нулевого субъекта](#go-error-default)
|
||||
- [GO-SSRF — Go HTTP client и redirects](#go-ssrf)
|
||||
- [GO-ZIP-PATH — filepath.Join не обеспечивает containment](#go-zip-path)
|
||||
- [GO-TLS-MIN — Явно разрешён устаревший TLS](#go-tls-min)
|
||||
- [GO-JWT-UNVERIFIED — JWT без подписи или проверки claims](#go-jwt-unverified)
|
||||
- [GO-UPLOAD-PATH — Имя multipart-файла напрямую включается в путь](#go-upload-path)
|
||||
|
||||
<a id="go-sql"></a>
|
||||
|
||||
<a id="go-sql-dynamic-go-sql"></a>
|
||||
|
||||
## GO-SQL. Динамический SQL Go
|
||||
|
||||
**Поиск:** скрипт, правило GO-SQL. Запуск: python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain GO-SQL. Regex: Query/QueryRow/Exec/Prepare и Context-варианты с конкатенацией или fmt.Sprintf. Простой context expression поддержан; сложный синтаксис/aliases fmt и заранее собранный SQL вручную.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
~~~go
|
||||
db.Query("SELECT id FROM notes WHERE name=" + name)
|
||||
~~~
|
||||
|
||||
**Исправление:** Передавать значения аргументами; placeholder зависит от драйвера. Идентификаторы выбирать из разрешённого набора.
|
||||
|
||||
~~~go
|
||||
db.Query("SELECT id FROM notes WHERE name=$1", name)
|
||||
~~~
|
||||
|
||||
**Проверка:** Кавычки — данные; права сохранены.
|
||||
|
||||
<details>
|
||||
<summary>Развёрнутый пример и ограничения</summary>
|
||||
|
||||
```go
|
||||
// Vulnerable: client input becomes SQL syntax.
|
||||
q := fmt.Sprintf("SELECT body FROM notes WHERE id = '%s'", inputID)
|
||||
err := db.QueryRowContext(ctx, q).Scan(&body)
|
||||
```
|
||||
|
||||
**Патч для приватной заметки:**
|
||||
|
||||
```go
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
)
|
||||
|
||||
func ReadPrivateNote(ctx context.Context, db *sql.DB, userID, noteID int64) (string, error) {
|
||||
var body string
|
||||
err := db.QueryRowContext(ctx,
|
||||
"SELECT body FROM notes WHERE id = $1 AND owner_id = $2",
|
||||
noteID, userID,
|
||||
).Scan(&body)
|
||||
return body, err
|
||||
}
|
||||
```
|
||||
|
||||
До вызова разобрать ID через проверяемое преобразование, не игнорировать ошибку
|
||||
парсинга. `sql.ErrNoRows` перевести в штатное отсутствие доступного объекта;
|
||||
при любой иной ошибке не выдавать `body` как успешный результат. Для MySQL/другого
|
||||
драйвера проверить синтаксис маркеров — он может отличаться.
|
||||
|
||||
**Проверить:** своё, чужое, отсутствующий объект; неверный ID; отмена/таймаут
|
||||
контекста; старые записи. В списках проверять ошибку `rows.Err()` после обхода.
|
||||
|
||||
</details>
|
||||
|
||||
<a id="go-hash-sum"></a>
|
||||
|
||||
<a id="go-hash-sum-non-empty-argument-to-hashsum"></a>
|
||||
|
||||
## GO-HASH-SUM. Непустой аргумент hash.Sum
|
||||
|
||||
**Поиск:** скрипт, правило GO-HASH-SUM. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain GO-HASH-SUM. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
~~~go
|
||||
digest := h.Sum(record.Hash[:])
|
||||
~~~
|
||||
|
||||
**Исправление:** Hash.Sum(b) добавляет digest к b, не хеширует b: сначала Write(data), потом Sum(nil). Проверить длину/все подписанные поля.
|
||||
|
||||
~~~go
|
||||
h.Write(record.Hash[:])
|
||||
digest := h.Sum(nil)
|
||||
~~~
|
||||
|
||||
**Проверка:** Результаты совпадают с известными тестовыми векторами; старые форматы digest мигрируют явно. Изменение каждого подписанного поля нарушает подпись.
|
||||
|
||||
**Вариант A/D:** Sum не хеширует свой аргумент. **Основание:** certified-transparency, анализ трёх файлов saarCTF.
|
||||
Checksum передавал Hash в Sum; ToHash копировал первые 32 байта результата.
|
||||
Из семантики Go следует: эти байты могли быть исходным Hash, а не digest
|
||||
ранее записанных Size/Timestamp. Полный сервис мы не воспроизводили.
|
||||
Сканер: GO-HASH-SUM.
|
||||
|
||||
~~~go
|
||||
// Before: return ToHash(h.Sum(record.Hash[:]))
|
||||
// After: include data in hash state, then extract only the digest.
|
||||
h.Write(record.Hash[:])
|
||||
return ToHash(h.Sum(nil))
|
||||
~~~
|
||||
|
||||
**Тест:** изменить по одному Size, Timestamp, Hash: каждая старая подпись должна
|
||||
перестать приниматься. Согласовать переход формата подписей и старые данные.
|
||||
Непустой Sum не всегда ошибка: buf[:0] может использоваться для выделенной
|
||||
заранее памяти. Поэтому сигнал требует чтения потребителя результата.
|
||||
|
||||
[исходник/разбор 1](https://github.com/saarsec/saarctf-2024/blob/3a06d18974ca177c6dd251a11bdf9b4b334f382a/certified-transparency/service/pkg/models/serialization.go); [исходник/разбор 2](https://github.com/saarsec/saarctf-2024/blob/3a06d18974ca177c6dd251a11bdf9b4b334f382a/certified-transparency/service/pkg/models/models.go); [исходник/разбор 3](https://github.com/saarsec/saarctf-2024/blob/3a06d18974ca177c6dd251a11bdf9b4b334f382a/certified-transparency/service/pkg/signatures.go).
|
||||
|
||||
<a id="go-html"></a>
|
||||
|
||||
<a id="go-html-go-autoescape-bypass"></a>
|
||||
|
||||
## GO-HTML. Обход autoescape Go
|
||||
|
||||
**Поиск:** скрипт, правило GO-HTML. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain GO-HTML. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
~~~go
|
||||
value := template.HTML(input)
|
||||
~~~
|
||||
|
||||
**Исправление:** Обычная строка в html/template; sanitizer только для предусмотренного богатого HTML.
|
||||
|
||||
~~~go
|
||||
value := input // string passed to html/template
|
||||
~~~
|
||||
|
||||
**Проверка:** Теги и кавычки пользователя отображаются текстом; предусмотренное форматирование работает.
|
||||
|
||||
<details>
|
||||
<summary>Развёрнутый пример и ограничения</summary>
|
||||
|
||||
```go
|
||||
// Vulnerable when message is client-controlled.
|
||||
err := page.Execute(w, template.HTML(message))
|
||||
```
|
||||
|
||||
**Патч для вывода обычного текста:**
|
||||
|
||||
```go
|
||||
import (
|
||||
"html/template"
|
||||
"io"
|
||||
)
|
||||
|
||||
func RenderMessage(w io.Writer, message string) error {
|
||||
page, err := template.New("message").Parse("<p>{{.}}</p>")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return page.Execute(w, message)
|
||||
}
|
||||
```
|
||||
|
||||
Шаблон фиксирован; данные — обычная строка. Использовать `html/template`, а не
|
||||
`text/template`, для HTML. Не заменять ошибку типом `template.JS`/`template.URL`:
|
||||
эти типы тоже выражают доверие к данным. В реальном приложении фиксированный
|
||||
шаблон можно разобрать один раз при старте. Если возможна ошибка рендеринга,
|
||||
учесть частично записанный HTTP-ответ: при необходимости сначала рендерить в буфер.
|
||||
|
||||
**Проверить:** разметка и кавычки отображаются текстом, Unicode сохранён;
|
||||
сервис не стал компилировать сам message; допустимое форматирование по контракту работает.
|
||||
|
||||
</details>
|
||||
|
||||
<a id="go-tls"></a>
|
||||
|
||||
<a id="go-tls-insecureskipverify"></a>
|
||||
|
||||
## GO-TLS. InsecureSkipVerify
|
||||
|
||||
**Поиск:** скрипт, правило GO-TLS. Запуск: python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain GO-TLS. Regex: InsecureSkipVerify: true и присваивание .InsecureSkipVerify = true, включая переносы строк; ==/!= и false не сигналят. Наличие VerifyConnection не снимает review: тип объекта, достижимость, callback и итоговую конфигурацию проверить вручную. Комментарии и строки могут совпадать.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
~~~go
|
||||
cfg := tls.Config{InsecureSkipVerify: true}
|
||||
~~~
|
||||
|
||||
**Исправление:** Вернуть штатную проверку сертификата и имени сервера; при необходимости настроить RootCAs/ServerName. Проверить пользовательские callbacks проверки.
|
||||
|
||||
~~~go
|
||||
cfg := tls.Config{InsecureSkipVerify: false}
|
||||
~~~
|
||||
|
||||
**Проверка:** Корректный сервер доступен; неверный сертификат отвергается.
|
||||
|
||||
Опасная настройка может появиться после создания конфига:
|
||||
|
||||
~~~go
|
||||
cfg := &tls.Config{}
|
||||
cfg.InsecureSkipVerify = true
|
||||
~~~
|
||||
|
||||
Для обычного TLS-клиента вернуть `false` и настроить `RootCAs`/`ServerName`
|
||||
для нужного сервера. Проверить доверенный сертификат, неизвестный CA,
|
||||
несовпадающее имя и истёкший срок, сохранив доступ к штатному внутреннему CA.
|
||||
|
||||
При `InsecureSkipVerify: true` приложение может реализовать собственную
|
||||
проверку в `VerifyConnection`. Если она полноценно проверяет требуемую цепочку
|
||||
и имя, флаг может быть обоснован; наличие callback само по себе этого не
|
||||
доказывает. Сканер не анализирует его тело и сохраняет сигнал после такого
|
||||
исправления. Сравнение `cfg.InsecureSkipVerify == true` не изменяет настройку
|
||||
и отдельно не получает GO-TLS. [Go: tls.Config](https://pkg.go.dev/crypto/tls#Config).
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'InsecureSkipVerify|VerifyConnection|VerifyPeerCertificate|RootCAs|ServerName|TLSClientConfig' .
|
||||
~~~
|
||||
|
||||
Связать конфигурацию с используемым transport, проследить все присваивания
|
||||
и возвраты ошибки в callback, включая возобновлённые TLS-сессии. Значение из
|
||||
переменной и эффективная конфигурация остаются ручной проверкой. Regex может
|
||||
совпасть с комментарием или текстовым примером; это не подтверждение выполнения.
|
||||
|
||||
<a id="go-shell"></a>
|
||||
|
||||
<a id="go-shell-go-execcommand-launches-a-shell"></a>
|
||||
|
||||
## GO-SHELL. Go exec.Command запускает shell
|
||||
|
||||
**Поиск:** скрипт, правило GO-SHELL. Запуск: python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain GO-SHELL. Regex: любой receiver.Command/CommandContext с буквальным shell и -c/-lc/-ec. Простой context expression, включая r.Context(), поддержан; вложенная запятая внутри context expression может скрыть вызов. Тип receiver и доверенность команды вручную.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
~~~go
|
||||
cmd := exec.Command("sh", "-c", command)
|
||||
~~~
|
||||
|
||||
**Исправление:** Фиксированный executable + argv. Для утилиты, читающей запись со stdin, передать её без shell и проверить разделители формата.
|
||||
|
||||
~~~go
|
||||
cmd := exec.Command("/usr/bin/file", "--", filename)
|
||||
~~~
|
||||
|
||||
**Проверка:** Спецсимволы остаются данными, опасные опции/разделители отвергаются; штатные допустимые аргументы работают.
|
||||
|
||||
<details>
|
||||
<summary>Развёрнутый пример и ограничения</summary>
|
||||
|
||||
```go
|
||||
// Vulnerable: exec.Command starts a shell that parses input text.
|
||||
out, err := exec.Command("sh", "-c", "printf '%s' '"+message+"' | sha256sum").Output()
|
||||
```
|
||||
|
||||
**Патч для SHA-256 содержимого:**
|
||||
|
||||
```go
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
)
|
||||
|
||||
func DigestText(message string) string {
|
||||
sum := sha256.Sum256([]byte(message))
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
```
|
||||
|
||||
Go-строка — байты; пример сохраняет их как есть. Если протокол требует именно
|
||||
UTF-8, его корректность проверить отдельно. Сохранить внешний формат ответа,
|
||||
который мог отличаться от сырого вывода `sha256sum`. Это не хеширование паролей.
|
||||
|
||||
**Проверить:** известный digest, пустая строка, Unicode, кавычки и переводы строк;
|
||||
нет запуска процесса. Для действительно нужной внешней команды задавать executable
|
||||
и аргументы отдельно, ограничивать время через контекст; аргументы всё ещё может
|
||||
интерпретировать сама программа.
|
||||
|
||||
</details>
|
||||
|
||||
**Вариант A/D:** Shell спрятан во внутреннем backend. **ENOWARS / replme, автор.** Внутренний обработчик помещал пароль в shell-команду.
|
||||
**Патч:** вызывать фиксированную утилиту без shell; данные передавать stdin
|
||||
с проверкой разделителей её формата. Ограничивать пароль только буквами
|
||||
без проверки контракта нельзя. **Тест:** пробелы и допустимые символы работают,
|
||||
разделители записи отвергаются. **Поиск:** GO-SHELL; проследить весь вызов.
|
||||
|
||||
[исходник/разбор 1](https://github.com/enowars/enowars8-service-replme/blob/3cdec50dd9a57f43f1c57f7b049319774a00e6c2/documentation/documentation/src/main.tex); [исходник/разбор 2](https://github.com/enowars/enowars8-service-replme/blob/3cdec50dd9a57f43f1c57f7b049319774a00e6c2/documentation/documentation/src/path-traversal.patch); [исходник/разбор 3](https://github.com/enowars/enowars8-service-replme/blob/3cdec50dd9a57f43f1c57f7b049319774a00e6c2/documentation/documentation/src/crc.patch); [исходник/разбор 4](https://github.com/enowars/enowars8-service-replme/blob/3cdec50dd9a57f43f1c57f7b049319774a00e6c2/service/backend/util/encoding.go); [исходник/разбор 5](https://github.com/enowars/enowars8-service-replme/blob/3cdec50dd9a57f43f1c57f7b049319774a00e6c2/service/backend/controller/repl.go); [исходник/разбор 6](https://github.com/enowars/enowars8-service-replme/blob/3cdec50dd9a57f43f1c57f7b049319774a00e6c2/service/image/service/user.go).
|
||||
|
||||
<a id="go-crc"></a>
|
||||
|
||||
<a id="go-crc-crc-near-an-identifier-or-trust-boundary"></a>
|
||||
|
||||
## GO-CRC. CRC используется как идентификатор/контроль доверия
|
||||
|
||||
**Поиск:** скрипт, правило GO-CRC. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain GO-CRC. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
~~~go
|
||||
resource := service.CRC.Calculate(username)
|
||||
~~~
|
||||
|
||||
**Исправление:** CRC не граница между пользователями. Для отображения ресурса — серверный уникальный ID/криптохеш + отдельная проверка владельца; для MAC — HMAC, не простой хеш.
|
||||
|
||||
~~~go
|
||||
resource := sha256.Sum256([]byte(username))
|
||||
~~~
|
||||
|
||||
**Проверка:** Разные пользователи не делят ресурс; коллизия не меняет владельца; есть миграция прежних ключей.
|
||||
|
||||
**Вариант A/D:** CRC как граница между ресурсами пользователей. **ENOWARS / replme, автор + патч.** CRC имени выбирал контейнер;
|
||||
коллизия объединяла чужие ресурсы.
|
||||
|
||||
**Патч:** серверный уникальный ID либо криптографическое отображение, отдельная
|
||||
проверка владельца и миграция существующих ресурсов. Криптохеш не заменяет auth.
|
||||
**Тест:** одинаковый checksum двух имён не даёт общий ресурс.
|
||||
**Поиск:** GO-CRC; PY-CRC покрывает аналогичный риск в Python.
|
||||
|
||||
[исходник/разбор 1](https://github.com/enowars/enowars8-service-replme/blob/3cdec50dd9a57f43f1c57f7b049319774a00e6c2/documentation/documentation/src/main.tex); [исходник/разбор 2](https://github.com/enowars/enowars8-service-replme/blob/3cdec50dd9a57f43f1c57f7b049319774a00e6c2/documentation/documentation/src/path-traversal.patch); [исходник/разбор 3](https://github.com/enowars/enowars8-service-replme/blob/3cdec50dd9a57f43f1c57f7b049319774a00e6c2/documentation/documentation/src/crc.patch); [исходник/разбор 4](https://github.com/enowars/enowars8-service-replme/blob/3cdec50dd9a57f43f1c57f7b049319774a00e6c2/service/backend/util/encoding.go); [исходник/разбор 5](https://github.com/enowars/enowars8-service-replme/blob/3cdec50dd9a57f43f1c57f7b049319774a00e6c2/service/backend/controller/repl.go); [исходник/разбор 6](https://github.com/enowars/enowars8-service-replme/blob/3cdec50dd9a57f43f1c57f7b049319774a00e6c2/service/image/service/user.go).
|
||||
|
||||
<a id="go-math-rand"></a>
|
||||
|
||||
<a id="go-math-rand-mathrand-near-a-possible-secret"></a>
|
||||
|
||||
## GO-MATH-RAND. math/rand рядом с возможным секретом
|
||||
|
||||
**Поиск:** скрипт, правило GO-MATH-RAND. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain GO-MATH-RAND. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
~~~go
|
||||
import "math/rand"
|
||||
rand.Seed(time.Now().UnixMilli())
|
||||
~~~
|
||||
|
||||
**Исправление:** Токены/секреты генерировать crypto/rand с обработкой ошибок. Перестановка алфавита/скрытый seed не заменяет CSPRNG.
|
||||
|
||||
~~~go
|
||||
import "crypto/rand"
|
||||
_, err := rand.Read(token)
|
||||
if err != nil { return err }
|
||||
~~~
|
||||
|
||||
**Проверка:** Источник энтропии и длина достаточны; ошибка генератора не создаёт предсказуемый fallback.
|
||||
|
||||
**Вариант A/D:** Go-токен с seed от времени. **RuCTF / werk, автор.** Обычный math/rand и время создания ограничивали
|
||||
непредсказуемость токена.
|
||||
**Патч:** crypto/rand, достаточная длина и проверка ошибок; перестановка алфавита
|
||||
не устраняет слабость генератора. **Тест:** контракт токена и отказ генератора
|
||||
без предсказуемой замены. **Поиск:** GO-MATH-RAND, включая alias импорта;
|
||||
кастомный PRNG анализировать отдельно.
|
||||
|
||||
[исходник/разбор 1](https://github.com/HackerDom/ructf-2023/blob/0cc333e44f2ba6908ff6c5d613146e3b00173315/writeups/werk/README.md).
|
||||
|
||||
<a id="go-readall-body"></a>
|
||||
|
||||
<a id="go-readall-body-readall-on-a-request-body"></a>
|
||||
|
||||
## GO-READALL-BODY. ReadAll тела запроса
|
||||
|
||||
**Поиск:** скрипт, правило GO-READALL-BODY. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain GO-READALL-BODY. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
~~~go
|
||||
body, err := io.ReadAll(r.Body)
|
||||
~~~
|
||||
|
||||
**Исправление:** Ограничить тело до чтения, корректно обработать превышение лимита. Правило не отслеживает ранее установленный MaxBytesReader.
|
||||
|
||||
~~~go
|
||||
r.Body = http.MaxBytesReader(w, r.Body, 1<<20)
|
||||
body, err := io.ReadAll(r.Body)
|
||||
if err != nil { return } // map to an appropriate client error
|
||||
~~~
|
||||
|
||||
**Проверка:** Лимит-1/лимит/лимит+1, stream без Content-Length; штатный максимальный документ работает.
|
||||
|
||||
<a id="go-pprof"></a>
|
||||
|
||||
<a id="go-pprof-pprof-registered-on-an-http-mux"></a>
|
||||
|
||||
## GO-PPROF. pprof регистрируется на HTTP mux
|
||||
|
||||
**Поиск:** скрипт, правило GO-PPROF. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain GO-PPROF. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
~~~go
|
||||
import _ "net/http/pprof"
|
||||
~~~
|
||||
|
||||
**Исправление:** Не публиковать DefaultServeMux с debug handlers как бизнес-API. Разделить mux и прикладную авторизацию диагностического endpoint.
|
||||
|
||||
~~~go
|
||||
// use a separate authenticated diagnostics mux when diagnostics is required
|
||||
~~~
|
||||
|
||||
**Проверка:** Обычный API работает; аноним не получает профиль/heap. Импорт сам по себе не доказывает доступность.
|
||||
|
||||
**Основание:** [первичный материал](https://pkg.go.dev/net/http/pprof).
|
||||
|
||||
<a id="go-fileserver"></a>
|
||||
|
||||
<a id="go-fileserver-fileserver-publishes-a-file-tree"></a>
|
||||
|
||||
## GO-FILESERVER. FileServer публикует дерево файлов
|
||||
|
||||
**Поиск:** скрипт, правило GO-FILESERVER. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain GO-FILESERVER. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
~~~go
|
||||
http.Handle("/", http.FileServer(http.Dir(".")))
|
||||
~~~
|
||||
|
||||
**Исправление:** Отдельный public root без секретов/БД, права на приватные файлы вне static handler; проверить symlink и directory listing.
|
||||
|
||||
~~~go
|
||||
http.Handle("/assets/", http.StripPrefix("/assets/", http.FileServer(http.Dir("./public"))))
|
||||
~~~
|
||||
|
||||
**Проверка:** Assets доступны; .env/исходники/чужие файлы и ссылка наружу недоступны.
|
||||
|
||||
**Основание:** [первичный материал](https://pkg.go.dev/net/http#FileServer).
|
||||
|
||||
<a id="go-auth-return"></a>
|
||||
|
||||
<a id="go-auth-return-execution-continues-after-httperror"></a>
|
||||
|
||||
## GO-AUTH-RETURN. После http.Error выполнение продолжается
|
||||
|
||||
**Поиск:** вручную; отдельного правила сканера нет.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'http.Error|WriteHeader|StatusForbidden|StatusUnauthorized' .
|
||||
~~~
|
||||
|
||||
Пройти код после каждой ветви отказа, deferred effects и goroutines.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
http.Error(w, ..., 403) записывает ответ, но не прекращает handler; затем данные читаются/меняются.
|
||||
|
||||
**Исправление:** Явный return до побочного эффекта; auth-result обязателен на всех путях, включая helper.
|
||||
|
||||
**Проверка:** Отказ не меняет БД и не дописывает приватный body; свой запрос работает.
|
||||
|
||||
<a id="go-json-fields"></a>
|
||||
|
||||
<a id="go-json-fields-json-entities-and-ambiguous-keys"></a>
|
||||
|
||||
## GO-JSON-FIELDS. JSON в entity и неоднозначные ключи
|
||||
|
||||
**Поиск:** вручную; отдельного правила сканера нет.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'json.NewDecoder|json.Unmarshal|Decode\(|DisallowUnknownFields' .
|
||||
~~~
|
||||
|
||||
Сверить exported поля entity, теги и повторные/разнорегистровые ключи; DisallowUnknownFields не решает дубли.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
Decode в модель принимает Owner/Role либо парсеры по-разному выбирают повторный ключ.
|
||||
|
||||
**Исправление:** Отдельный DTO, разрешённые поля, проверка EOF и типов; при подписи строгая политика дублей/канонизации.
|
||||
|
||||
**Проверка:** Лишнее auth-поле, второй JSON-документ, null и повторные ключи; штатный payload.
|
||||
|
||||
<a id="go-race"></a>
|
||||
|
||||
<a id="go-race-shared-mapslice-state-and-check-then-use"></a>
|
||||
|
||||
## GO-RACE. Общие map/slice и check-then-use
|
||||
|
||||
**Поиск:** вручную; отдельного правила сканера нет.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'map\[|sync.Mutex|RWMutex|go func|LoadOrStore|owner' .
|
||||
~~~
|
||||
|
||||
Определить владельца shared state; блокировка должна охватывать проверку и изменение, не отдельные обращения.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
Две goroutine проходят проверку баланса/прав и затем обе изменяют состояние.
|
||||
|
||||
**Исправление:** Атомарная операция/критическая секция либо транзакция БД; не удерживать глобальный lock на медленном I/O.
|
||||
|
||||
**Проверка:** Barrier-тест инварианта и race detector на подготовленном стенде; отсутствие race-отчёта не доказывает отсутствие логической гонки.
|
||||
|
||||
<a id="go-error-default"></a>
|
||||
|
||||
<a id="go-error-default-ignored-errors-produce-a-zero-principal"></a>
|
||||
|
||||
## GO-ERROR-DEFAULT. Игнорирование ошибки даёт нулевого субъекта
|
||||
|
||||
**Поиск:** вручную; отдельного правила сканера нет.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'ParseInt|Atoi|Unmarshal|Verify|Find|_, _|err' .
|
||||
~~~
|
||||
|
||||
Найти игнорируемые ошибки parse/auth/DB; проверить, не означает ли zero ID глобальный/default объект.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
id, _ := strconv.Atoi(input) превращает неправильный ввод в 0, который имеет особые права.
|
||||
|
||||
**Исправление:** Проверять ошибку и допустимый диапазон до операции; различать not found и backend failure.
|
||||
|
||||
**Проверка:** Неправильный ID/таймаут БД не авторизуют и не возвращают чужое; допустимый ноль по контракту обработан явно.
|
||||
|
||||
<a id="go-ssrf"></a>
|
||||
|
||||
<a id="go-ssrf-http-clients-and-redirects"></a>
|
||||
|
||||
## GO-SSRF. Go HTTP client и redirects
|
||||
|
||||
**Поиск:** вручную; отдельного правила сканера нет.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'http.Get|Client.Do|NewRequest|CheckRedirect|DialContext' .
|
||||
~~~
|
||||
|
||||
Проследить custom transport, redirect policy, DNS и повторное использование соединения.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
URL проверен до Client.Do, но redirect/transport уводит запрос к другому назначению.
|
||||
|
||||
**Исправление:** Фиксированные назначения либо единая policy URL/redirect/соединения, timeouts и лимит body; не блокировать легитимную private сеть без контракта.
|
||||
|
||||
**Проверка:** Mock redirect/DNS/timeout, обычный upstream, oversized response.
|
||||
|
||||
**Основание:** [первичный материал](https://cheatsheetseries.owasp.org/cheatsheets/Server_Side_Request_Forgery_Prevention_Cheat_Sheet.html).
|
||||
|
||||
<a id="go-zip-path"></a>
|
||||
|
||||
<a id="go-zip-path-filepathjoin-does-not-enforce-containment"></a>
|
||||
|
||||
## GO-ZIP-PATH. filepath.Join не обеспечивает containment
|
||||
|
||||
**Поиск:** вручную; отдельного правила сканера нет.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'archive/zip|archive/tar|filepath.Join|EvalSymlinks|MkdirAll' .
|
||||
~~~
|
||||
|
||||
Найти имена entries и ссылок; сравнить очищенный путь с root и фактическую операцию открытия.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
Join(root, entry) используется для записи без проверки выхода/ссылок.
|
||||
|
||||
**Исправление:** Проверить relative path и тип entry, безопасное открытие внутри каталога с политикой symlink, лимиты и уборка.
|
||||
|
||||
**Проверка:** Вложенный допустимый путь, выход наружу, link entry и изменение родителя между проверкой и записью.
|
||||
|
||||
**Основание:** [первичный материал](https://cheatsheetseries.owasp.org/cheatsheets/File_Upload_Cheat_Sheet.html).
|
||||
|
||||
<a id="go-tls-min"></a>
|
||||
|
||||
<a id="go-tls-min-obsolete-minimum-tls-version"></a>
|
||||
|
||||
## GO-TLS-MIN. Явно разрешён устаревший TLS
|
||||
|
||||
**Поиск:** скрипт, правило GO-TLS-MIN. Запуск: python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain GO-TLS-MIN. Regex: MinVersion:tls.VersionSSL30/TLS10/TLS11 и присваивание .MinVersion = этим константам, включая переносы строк; ==/!=, TLS12/TLS13 и 0 не сигналят. VersionSSL30 — устаревшая настройка, современный Go не поддерживает SSLv3. Тип объекта, итоговую конфигурацию и версию Go проверять вручную; числовые версии, import aliases, переменные и настройки listener вне Go не вычисляются.
|
||||
|
||||
**Уязвимый вариант:** Настройка понижает минимум для используемого TLS-клиента
|
||||
или сервера, если версия и режим runtime допускают эти старые протоколы.
|
||||
|
||||
~~~go
|
||||
cfg := &tls.Config{}
|
||||
cfg.MinVersion = tls.VersionTLS10
|
||||
~~~
|
||||
|
||||
**Исправление:** Выбрать минимум TLS 1.2/1.3 по совместимости checker и peer;
|
||||
сохранить проверку сертификата. Настроить Config до передачи TLS-функции:
|
||||
после начала использования его менять нельзя.
|
||||
|
||||
~~~go
|
||||
cfg := &tls.Config{}
|
||||
cfg.MinVersion = tls.VersionTLS12
|
||||
~~~
|
||||
|
||||
**Проверка:** Штатные peers соединяются; TLS ниже выбранного минимума отвергнут.
|
||||
Проверить итоговый Config, обработку ошибки соединения и старых клиентов до
|
||||
выкладки: поднятие минимума может нарушить совместимость.
|
||||
|
||||
Поле литерала `MinVersion: tls.VersionTLS10` и отдельное присваивание
|
||||
`cfg.MinVersion = tls.VersionTLS10` требуют одинакового просмотра.
|
||||
Сравнения `==`/`!=` не меняют настройку и не получают этот сигнал.
|
||||
`TLS12`/`TLS13` и `0` также не сигналят; `0` означает default конкретного runtime,
|
||||
а не подтверждённую политику безопасности.
|
||||
|
||||
`VersionSSL30` остаётся сигналом устаревшей настройки: наличие константы
|
||||
не означает, что современный Go поддерживает SSLv3.
|
||||
Версия, режим runtime и последующие переопределения влияют на реальное поведение.
|
||||
[Go: tls.Config](https://pkg.go.dev/crypto/tls#Config),
|
||||
[контракт MinVersion в Go 1.24](https://github.com/golang/go/blob/go1.24.0/src/crypto/tls/common.go#L756).
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'MinVersion|MaxVersion|TLSClientConfig|GetConfigForClient|crypto/tls|GODEBUG|GOFIPS140' .
|
||||
~~~
|
||||
|
||||
Связать объект с реальным TLS-клиентом/listener и проверить все изменения,
|
||||
возвращаемые callbacks конфигурации, aliases импорта, числовые константы и
|
||||
значения из окружения. Regex не устанавливает тип объекта или достижимость
|
||||
настройки и может совпасть с комментарием. Семантика сверена по первичным
|
||||
исходникам; Go runtime и TLS-соединения в этой проверке не запускались.
|
||||
|
||||
<a id="go-jwt-unverified"></a>
|
||||
|
||||
<a id="go-jwt-unverified-jwt-without-signature-or-claims-verification"></a>
|
||||
|
||||
## GO-JWT-UNVERIFIED. JWT без подписи или проверки claims
|
||||
|
||||
**Поиск:** скрипт, правило GO-JWT-UNVERIFIED. Запуск: python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain GO-JWT-UNVERIFIED. Regex: ParseUnverified и WithoutClaimsValidation; не доказывает использование результата для auth. Пример относится к golang-jwt/jwt/v5.
|
||||
|
||||
**Уязвимый вариант:** Разобранный токен не равен проверенному; ошибка или отключённая валидация не должны вести к авторизации.
|
||||
|
||||
~~~go
|
||||
token, _, err := parser.ParseUnverified(raw, &claims)
|
||||
~~~
|
||||
|
||||
**Исправление:** Использовать валидирующий API с доверенным keyfunc, алгоритмами и claims; проверять err до использования token/claims.
|
||||
|
||||
~~~go
|
||||
token, err := jwt.ParseWithClaims(raw, &claims, trustedKeyFunc, jwt.WithValidMethods([]string{"RS256"}), jwt.WithIssuer("auth"), jwt.WithAudience("notes"), jwt.WithExpirationRequired())
|
||||
if err != nil || !token.Valid { return ErrUnauthorized }
|
||||
~~~
|
||||
|
||||
**Проверка:** Подпись/срок/адресат проверяются; nil token при ошибке не вызывает panic; штатный токен принимается.
|
||||
|
||||
Первичная документация: [документация 1](https://pkg.go.dev/github.com/golang-jwt/jwt/v5).
|
||||
|
||||
<a id="go-upload-path"></a>
|
||||
|
||||
<a id="go-upload-path-multipart-filename-used-directly-in-a-joined-path"></a>
|
||||
|
||||
## GO-UPLOAD-PATH. Имя multipart-файла напрямую включается в путь
|
||||
|
||||
**Поиск:** правило сканера GO-UPLOAD-PATH. Точный контракт детектора: `--explain GO-UPLOAD-PATH`. Regex с лексическими исключениями: filepath.Join с простым первым аргументом и прямым header/fileHeader/file.Filename во втором. MIME-парсер может нормализовать имя файла; правило не доказывает traversal, тип импортированного объекта или отсутствие предшествующей валидации.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
~~~go
|
||||
path := filepath.Join(root, header.Filename)
|
||||
~~~
|
||||
|
||||
**Исправление:** Выбирайте серверное имя хранения без перезаписи существующих файлов, вне исполняемых и публичных корней; проверяйте права на скачивание, размер и тип загрузки.
|
||||
|
||||
~~~go
|
||||
path := filepath.Join(root, serverGeneratedID)
|
||||
~~~
|
||||
|
||||
**Проверка:** Другие разделители, traversal, коллизии и запросы от другого владельца не меняют выбранный путь хранения; обычные загрузки работают.
|
||||
|
||||
[Первичный источник 1](https://pkg.go.dev/mime/multipart#FileHeader)
|
||||
@@ -0,0 +1,577 @@
|
||||
# Go: find, fix and verify
|
||||
|
||||
English | [Русский](go-RU.md)
|
||||
|
||||
[Catalog](README.md) · [Scanner](../offline-scanner.md) · [Patch verification](../patch-validation.md)
|
||||
|
||||
19 sections. Each follows **Search → Vulnerable example → Fix → Verification**.
|
||||
Run `rg` from a local service checkout; searches only read files. Derive the actor/owner from a verified session, not request data. Adapt examples to the actual API and contract.
|
||||
|
||||
## Contents
|
||||
|
||||
- [GO-SQL — Dynamic Go SQL](#go-sql)
|
||||
- [GO-HASH-SUM — Non-empty argument to hash.Sum](#go-hash-sum)
|
||||
- [GO-HTML — Go autoescape bypass](#go-html)
|
||||
- [GO-TLS — InsecureSkipVerify](#go-tls)
|
||||
- [GO-SHELL — Go exec.Command launches a shell](#go-shell)
|
||||
- [GO-CRC — CRC near an identifier or trust boundary](#go-crc)
|
||||
- [GO-MATH-RAND — math/rand near a possible secret](#go-math-rand)
|
||||
- [GO-READALL-BODY — ReadAll on a request body](#go-readall-body)
|
||||
- [GO-PPROF — pprof registered on an HTTP mux](#go-pprof)
|
||||
- [GO-FILESERVER — FileServer publishes a file tree](#go-fileserver)
|
||||
- [GO-AUTH-RETURN — Execution continues after http.Error](#go-auth-return)
|
||||
- [GO-JSON-FIELDS — JSON entities and ambiguous keys](#go-json-fields)
|
||||
- [GO-RACE — Shared map/slice state and check-then-use](#go-race)
|
||||
- [GO-ERROR-DEFAULT — Ignored errors produce a zero principal](#go-error-default)
|
||||
- [GO-SSRF — HTTP clients and redirects](#go-ssrf)
|
||||
- [GO-ZIP-PATH — filepath.Join does not enforce containment](#go-zip-path)
|
||||
- [GO-TLS-MIN — Obsolete minimum TLS version](#go-tls-min)
|
||||
- [GO-JWT-UNVERIFIED — JWT without signature or claims verification](#go-jwt-unverified)
|
||||
- [GO-UPLOAD-PATH — Multipart filename used directly in a joined path](#go-upload-path)
|
||||
|
||||
<a id="go-sql"></a>
|
||||
|
||||
## GO-SQL. Dynamic Go SQL
|
||||
|
||||
**Search:** scanner rule GO-SQL. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain GO-SQL` for details. Regex: Query/QueryRow/Exec/Prepare and Context forms with concatenation or fmt.Sprintf. Simple context expressions are supported; review complex syntax, fmt aliases and preassembled SQL.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
~~~go
|
||||
db.Query("SELECT id FROM notes WHERE name=" + name)
|
||||
~~~
|
||||
|
||||
**Fix:** Bind values using actual driver placeholders; allowlist identifiers.
|
||||
|
||||
~~~go
|
||||
db.Query("SELECT id FROM notes WHERE name=$1", name)
|
||||
~~~
|
||||
|
||||
**Verification:** Quotes remain values; legitimate queries and ownership checks work.
|
||||
|
||||
<details>
|
||||
<summary>Expanded example and limitations</summary>
|
||||
|
||||
```go
|
||||
// Vulnerable: client input becomes SQL syntax.
|
||||
q := fmt.Sprintf("SELECT body FROM notes WHERE id = '%s'", inputID)
|
||||
err := db.QueryRowContext(ctx, q).Scan(&body)
|
||||
```
|
||||
|
||||
**Patch for a private note:**
|
||||
|
||||
```go
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
)
|
||||
|
||||
func ReadPrivateNote(ctx context.Context, db *sql.DB, userID, noteID int64) (string, error) {
|
||||
var body string
|
||||
err := db.QueryRowContext(ctx,
|
||||
"SELECT body FROM notes WHERE id = $1 AND owner_id = $2",
|
||||
noteID, userID,
|
||||
).Scan(&body)
|
||||
return body, err
|
||||
}
|
||||
```
|
||||
|
||||
Parse the ID with a checked conversion before this call. Map sql.ErrNoRows to the normal unavailable-object response; never return body as success for other errors. Verify placeholder syntax for MySQL or another driver.
|
||||
|
||||
**Check:** Owner, other user, missing object, invalid ID, context cancellation/timeout and old records. After list iteration check rows.Err().
|
||||
|
||||
</details>
|
||||
|
||||
<a id="go-hash-sum"></a>
|
||||
|
||||
## GO-HASH-SUM. Non-empty argument to hash.Sum
|
||||
|
||||
**Search:** scanner rule GO-HASH-SUM. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain GO-HASH-SUM` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
~~~go
|
||||
digest := h.Sum(record.Hash[:])
|
||||
~~~
|
||||
|
||||
**Fix:** Use Write to hash bytes and Sum(nil) for the digest; Sum appends a digest instead of hashing its argument.
|
||||
|
||||
~~~go
|
||||
h.Write(record.Hash[:])
|
||||
digest := h.Sum(nil)
|
||||
~~~
|
||||
|
||||
**Verification:** Known vectors match; legacy digest formats are migrated deliberately.
|
||||
|
||||
**A/D variant:** Sum does not hash its argument. **Reference:** certified-transparency, analysis of three saarCTF source files. Checksum passed Hash to Sum; ToHash copied the first 32 output bytes. Go semantics mean those bytes could be the original Hash rather than the digest of previously written Size/Timestamp. The full service was not reproduced. Scanner: GO-HASH-SUM.
|
||||
|
||||
~~~go
|
||||
// Before: return ToHash(h.Sum(record.Hash[:]))
|
||||
// After: include data in hash state, then extract only the digest.
|
||||
h.Write(record.Hash[:])
|
||||
return ToHash(h.Sum(nil))
|
||||
~~~
|
||||
|
||||
**Test:** Change Size, Timestamp and Hash individually; each old signature must fail. Plan signature-format migration and legacy-data compatibility. A nonempty Sum argument is not always wrong: buf[:0] can reuse preallocated storage. Inspect the consumer of the result.
|
||||
|
||||
[source/write-up 1](https://github.com/saarsec/saarctf-2024/blob/3a06d18974ca177c6dd251a11bdf9b4b334f382a/certified-transparency/service/pkg/models/serialization.go); [source/write-up 2](https://github.com/saarsec/saarctf-2024/blob/3a06d18974ca177c6dd251a11bdf9b4b334f382a/certified-transparency/service/pkg/models/models.go); [source/write-up 3](https://github.com/saarsec/saarctf-2024/blob/3a06d18974ca177c6dd251a11bdf9b4b334f382a/certified-transparency/service/pkg/signatures.go).
|
||||
|
||||
<a id="go-html"></a>
|
||||
|
||||
## GO-HTML. Go autoescape bypass
|
||||
|
||||
**Search:** scanner rule GO-HTML. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain GO-HTML` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
~~~go
|
||||
value := template.HTML(input)
|
||||
~~~
|
||||
|
||||
**Fix:** Pass strings to html/template; use trusted HTML only after a reviewed sanitizer if needed.
|
||||
|
||||
~~~go
|
||||
value := input // string passed to html/template
|
||||
~~~
|
||||
|
||||
**Verification:** User tags/quotes render as text; intended formatting works.
|
||||
|
||||
<details>
|
||||
<summary>Expanded example and limitations</summary>
|
||||
|
||||
```go
|
||||
// Vulnerable when message is client-controlled.
|
||||
err := page.Execute(w, template.HTML(message))
|
||||
```
|
||||
|
||||
**Patch for rendering ordinary text:**
|
||||
|
||||
```go
|
||||
import (
|
||||
"html/template"
|
||||
"io"
|
||||
)
|
||||
|
||||
func RenderMessage(w io.Writer, message string) error {
|
||||
page, err := template.New("message").Parse("<p>{{.}}</p>")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return page.Execute(w, message)
|
||||
}
|
||||
```
|
||||
|
||||
The template is fixed and the data is an ordinary string. Use html/template, not text/template, for HTML. Do not replace the problem with template.JS/template.URL, which also assert trust. A fixed template may be parsed once at startup. Account for partial HTTP responses on render failure; buffer first where necessary.
|
||||
|
||||
**Check:** Markup/quotes display as text, Unicode survives, message itself is never compiled, and contractual formatting remains available.
|
||||
|
||||
</details>
|
||||
|
||||
<a id="go-tls"></a>
|
||||
|
||||
## GO-TLS. InsecureSkipVerify
|
||||
|
||||
**Search:** scanner rule GO-TLS. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain GO-TLS` for details. Regex: InsecureSkipVerify:true and .InsecureSkipVerify=true assignments including newlines; ==, != and false do not match. VerifyConnection does not suppress review: inspect object type, reachability, callback and effective config. Comments/strings may match.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
~~~go
|
||||
cfg := tls.Config{InsecureSkipVerify: true}
|
||||
~~~
|
||||
|
||||
**Fix:** Use normal certificate/hostname verification and the required CA; review custom verification callbacks.
|
||||
|
||||
~~~go
|
||||
cfg := tls.Config{InsecureSkipVerify: false}
|
||||
~~~
|
||||
|
||||
**Verification:** Correct peers work and invalid certificates fail.
|
||||
|
||||
Dangerous configuration can be assigned after construction:
|
||||
|
||||
~~~go
|
||||
cfg := &tls.Config{}
|
||||
cfg.InsecureSkipVerify = true
|
||||
~~~
|
||||
|
||||
For an ordinary TLS client restore false and configure RootCAs/ServerName for the intended server. Test trusted certificates, unknown CAs, wrong names and expiry, preserving the legitimate internal CA.
|
||||
|
||||
With InsecureSkipVerify: true, an application may implement its own VerifyConnection validation. The flag can be justified only if that callback fully checks the required chain and name; a callback's mere presence proves nothing. The scanner does not analyze its body and retains the signal. Comparing cfg.InsecureSkipVerify == true does not change configuration and does not independently trigger GO-TLS. [Go: tls.Config](https://pkg.go.dev/crypto/tls#Config).
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'InsecureSkipVerify|VerifyConnection|VerifyPeerCertificate|RootCAs|ServerName|TLSClientConfig' .
|
||||
~~~
|
||||
|
||||
Connect the configuration to the transport actually used; trace every assignment and callback error return, including resumed TLS sessions. Variable values and effective configuration need manual review. Regex can match comments/examples; a match does not establish execution.
|
||||
|
||||
<a id="go-shell"></a>
|
||||
|
||||
## GO-SHELL. Go exec.Command launches a shell
|
||||
|
||||
**Search:** scanner rule GO-SHELL. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain GO-SHELL` for details. Regex: any receiver.Command/CommandContext with literal shell and -c/-lc/-ec. Simple context expressions including r.Context() work; nested commas may hide a call. Inspect receiver type and command trust.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
~~~go
|
||||
cmd := exec.Command("sh", "-c", command)
|
||||
~~~
|
||||
|
||||
**Fix:** Use fixed executable plus argv. Pass stdin records without a shell and validate their separators.
|
||||
|
||||
~~~go
|
||||
cmd := exec.Command("/usr/bin/file", "--", filename)
|
||||
~~~
|
||||
|
||||
**Verification:** Metacharacters stay data; dangerous options/separators fail; supported arguments work.
|
||||
|
||||
<details>
|
||||
<summary>Expanded example and limitations</summary>
|
||||
|
||||
```go
|
||||
// Vulnerable: exec.Command starts a shell that parses input text.
|
||||
out, err := exec.Command("sh", "-c", "printf '%s' '"+message+"' | sha256sum").Output()
|
||||
```
|
||||
|
||||
**Patch for a content SHA-256 digest:**
|
||||
|
||||
```go
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
)
|
||||
|
||||
func DigestText(message string) string {
|
||||
sum := sha256.Sum256([]byte(message))
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
```
|
||||
|
||||
Go strings contain bytes; this example preserves them unchanged. Validate UTF-8 separately if the protocol requires it. Preserve the external response format, which may differ from raw sha256sum output. This is not password hashing.
|
||||
|
||||
**Check:** Known digest, empty string, Unicode, quotes/newlines and no subprocess. If an external command is genuinely required, separate executable/arguments and bound runtime with context; the program may still interpret arguments as options.
|
||||
|
||||
</details>
|
||||
|
||||
**A/D variant:** Shell hidden in an internal backend. **ENOWARS / replme, author write-up.** An internal handler interpolated a password into a shell command. **Patch:** Call a fixed utility without shell; pass data over stdin while validating its format delimiters. Do not arbitrarily restrict passwords to letters without checking the contract. **Test:** Spaces/permitted characters work; record delimiters fail. **Search:** GO-SHELL and the complete call chain.
|
||||
|
||||
[source/write-up 1](https://github.com/enowars/enowars8-service-replme/blob/3cdec50dd9a57f43f1c57f7b049319774a00e6c2/documentation/documentation/src/main.tex); [source/write-up 2](https://github.com/enowars/enowars8-service-replme/blob/3cdec50dd9a57f43f1c57f7b049319774a00e6c2/documentation/documentation/src/path-traversal.patch); [source/write-up 3](https://github.com/enowars/enowars8-service-replme/blob/3cdec50dd9a57f43f1c57f7b049319774a00e6c2/documentation/documentation/src/crc.patch); [source/write-up 4](https://github.com/enowars/enowars8-service-replme/blob/3cdec50dd9a57f43f1c57f7b049319774a00e6c2/service/backend/util/encoding.go); [source/write-up 5](https://github.com/enowars/enowars8-service-replme/blob/3cdec50dd9a57f43f1c57f7b049319774a00e6c2/service/backend/controller/repl.go); [source/write-up 6](https://github.com/enowars/enowars8-service-replme/blob/3cdec50dd9a57f43f1c57f7b049319774a00e6c2/service/image/service/user.go).
|
||||
|
||||
<a id="go-crc"></a>
|
||||
|
||||
## GO-CRC. CRC near an identifier or trust boundary
|
||||
|
||||
**Search:** scanner rule GO-CRC. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain GO-CRC` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
~~~go
|
||||
resource := service.CRC.Calculate(username)
|
||||
~~~
|
||||
|
||||
**Fix:** CRC is not an ownership boundary. Use unique server-owned IDs plus authorization or HMAC for authenticity.
|
||||
|
||||
~~~go
|
||||
resource := sha256.Sum256([]byte(username))
|
||||
~~~
|
||||
|
||||
**Verification:** Collisions cannot change ownership; old IDs have a migration path.
|
||||
|
||||
**A/D variant:** CRC as the boundary between users' resources. **ENOWARS / replme, author and patch.** A name's CRC selected a container; collisions merged unrelated resources.
|
||||
|
||||
**Patch:** Server-generated unique IDs or a cryptographic mapping, separate ownership checks and migration of existing resources. A cryptographic hash is not authorization. **Test:** Equal checksums for different names must not share a resource. **Search:** GO-CRC; PY-CRC covers the analogous Python risk.
|
||||
|
||||
[source/write-up 1](https://github.com/enowars/enowars8-service-replme/blob/3cdec50dd9a57f43f1c57f7b049319774a00e6c2/documentation/documentation/src/main.tex); [source/write-up 2](https://github.com/enowars/enowars8-service-replme/blob/3cdec50dd9a57f43f1c57f7b049319774a00e6c2/documentation/documentation/src/path-traversal.patch); [source/write-up 3](https://github.com/enowars/enowars8-service-replme/blob/3cdec50dd9a57f43f1c57f7b049319774a00e6c2/documentation/documentation/src/crc.patch); [source/write-up 4](https://github.com/enowars/enowars8-service-replme/blob/3cdec50dd9a57f43f1c57f7b049319774a00e6c2/service/backend/util/encoding.go); [source/write-up 5](https://github.com/enowars/enowars8-service-replme/blob/3cdec50dd9a57f43f1c57f7b049319774a00e6c2/service/backend/controller/repl.go); [source/write-up 6](https://github.com/enowars/enowars8-service-replme/blob/3cdec50dd9a57f43f1c57f7b049319774a00e6c2/service/image/service/user.go).
|
||||
|
||||
<a id="go-math-rand"></a>
|
||||
|
||||
## GO-MATH-RAND. math/rand near a possible secret
|
||||
|
||||
**Search:** scanner rule GO-MATH-RAND. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain GO-MATH-RAND` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
~~~go
|
||||
import "math/rand"
|
||||
rand.Seed(time.Now().UnixMilli())
|
||||
~~~
|
||||
|
||||
**Fix:** Use crypto/rand and handle errors; alphabet shuffling/hidden seeds do not create a CSPRNG.
|
||||
|
||||
~~~go
|
||||
import "crypto/rand"
|
||||
_, err := rand.Read(token)
|
||||
if err != nil { return err }
|
||||
~~~
|
||||
|
||||
**Verification:** Entropy/length suffice and failure never creates a predictable fallback.
|
||||
|
||||
**A/D variant:** Go tokens seeded from time. **RuCTF / werk, author write-up.** math/rand and creation time constrained token unpredictability. **Patch:** crypto/rand, adequate length and error handling; permuting an alphabet does not fix a weak generator. **Test:** Token contract and generator failure without predictable fallback. **Search:** GO-MATH-RAND including import aliases; review custom PRNGs separately.
|
||||
|
||||
[source/write-up 1](https://github.com/HackerDom/ructf-2023/blob/0cc333e44f2ba6908ff6c5d613146e3b00173315/writeups/werk/README.md).
|
||||
|
||||
<a id="go-readall-body"></a>
|
||||
|
||||
## GO-READALL-BODY. ReadAll on a request body
|
||||
|
||||
**Search:** scanner rule GO-READALL-BODY. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain GO-READALL-BODY` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
~~~go
|
||||
body, err := io.ReadAll(r.Body)
|
||||
~~~
|
||||
|
||||
**Fix:** Limit the body before reading and handle excess size; the rule does not track earlier MaxBytesReader calls.
|
||||
|
||||
~~~go
|
||||
r.Body = http.MaxBytesReader(w, r.Body, 1<<20)
|
||||
body, err := io.ReadAll(r.Body)
|
||||
if err != nil { return } // map to an appropriate client error
|
||||
~~~
|
||||
|
||||
**Verification:** Test limit-1/limit/limit+1 and streams without Content-Length.
|
||||
|
||||
<a id="go-pprof"></a>
|
||||
|
||||
## GO-PPROF. pprof registered on an HTTP mux
|
||||
|
||||
**Search:** scanner rule GO-PPROF. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain GO-PPROF` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
~~~go
|
||||
import _ "net/http/pprof"
|
||||
~~~
|
||||
|
||||
**Fix:** Do not expose DefaultServeMux debug handlers as the business API; separate muxes and authorize diagnostic endpoints.
|
||||
|
||||
~~~go
|
||||
// use a separate authenticated diagnostics mux when diagnostics is required
|
||||
~~~
|
||||
|
||||
**Verification:** Normal API works; anonymous clients cannot obtain profiles/heap. Import alone does not prove exposure.
|
||||
|
||||
**Reference:** [primary source](https://pkg.go.dev/net/http/pprof).
|
||||
|
||||
<a id="go-fileserver"></a>
|
||||
|
||||
## GO-FILESERVER. FileServer publishes a file tree
|
||||
|
||||
**Search:** scanner rule GO-FILESERVER. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain GO-FILESERVER` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
~~~go
|
||||
http.Handle("/", http.FileServer(http.Dir(".")))
|
||||
~~~
|
||||
|
||||
**Fix:** Use a dedicated public root without secrets/databases; authorize private files separately and review symlinks/listing.
|
||||
|
||||
~~~go
|
||||
http.Handle("/assets/", http.StripPrefix("/assets/", http.FileServer(http.Dir("./public"))))
|
||||
~~~
|
||||
|
||||
**Verification:** Assets work; .env, source, foreign files and outward symlinks are unavailable.
|
||||
|
||||
**Reference:** [primary source](https://pkg.go.dev/net/http#FileServer).
|
||||
|
||||
<a id="go-auth-return"></a>
|
||||
|
||||
## GO-AUTH-RETURN. Execution continues after http.Error
|
||||
|
||||
**Search:** manual review; no separate scanner rule.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'http.Error|WriteHeader|StatusForbidden|StatusUnauthorized' .
|
||||
~~~
|
||||
|
||||
Trace execution after each denial, including deferred effects and goroutines.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
`http.Error(w, ..., 403)` writes a response but does not stop the handler; subsequent code reads or mutates data.
|
||||
|
||||
**Fix:** Explicit return before side effects; require a checked authorization result on every path, including helpers.
|
||||
|
||||
**Verification:** Denial does not mutate the database or append private response data; authorized requests work.
|
||||
|
||||
<a id="go-json-fields"></a>
|
||||
|
||||
## GO-JSON-FIELDS. JSON entities and ambiguous keys
|
||||
|
||||
**Search:** manual review; no separate scanner rule.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'json.NewDecoder|json.Unmarshal|Decode\(|DisallowUnknownFields' .
|
||||
~~~
|
||||
|
||||
Review exported entity fields, tags, duplicate keys and case variants; DisallowUnknownFields does not solve duplicates.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
Decoding into the model accepts Owner/Role, or parsers choose different duplicate keys.
|
||||
|
||||
**Fix:** Dedicated DTO, allowlisted fields, EOF/type validation; signed input requires an explicit duplicate-key/canonicalization policy.
|
||||
|
||||
**Verification:** Extra authorization fields, second JSON documents, nulls, duplicate keys and ordinary payloads.
|
||||
|
||||
<a id="go-race"></a>
|
||||
|
||||
## GO-RACE. Shared map/slice state and check-then-use
|
||||
|
||||
**Search:** manual review; no separate scanner rule.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'map\[|sync.Mutex|RWMutex|go func|LoadOrStore|owner' .
|
||||
~~~
|
||||
|
||||
Identify the shared-state owner; a lock must cover the check and mutation, not only individual accesses.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
Two goroutines both pass balance/authorization checks and mutate state.
|
||||
|
||||
**Fix:** An atomic operation/critical section or database transaction; avoid global locks across slow I/O.
|
||||
|
||||
**Verification:** Barrier-based invariant tests and race detector in an isolated environment. No race report does not prove the absence of logical races.
|
||||
|
||||
<a id="go-error-default"></a>
|
||||
|
||||
## GO-ERROR-DEFAULT. Ignored errors produce a zero principal
|
||||
|
||||
**Search:** manual review; no separate scanner rule.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'ParseInt|Atoi|Unmarshal|Verify|Find|_, _|err' .
|
||||
~~~
|
||||
|
||||
Find ignored parse/auth/database errors; determine whether zero identifies a global/default object.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
`id, _ := strconv.Atoi(input)` turns invalid input into zero with special privileges.
|
||||
|
||||
**Fix:** Check errors and range before use; distinguish not-found from backend failure.
|
||||
|
||||
**Verification:** Invalid IDs/database timeouts never authorize or expose another user's data; explicitly handle zero if it is valid by contract.
|
||||
|
||||
<a id="go-ssrf"></a>
|
||||
|
||||
## GO-SSRF. HTTP clients and redirects
|
||||
|
||||
**Search:** manual review; no separate scanner rule.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'http.Get|Client.Do|NewRequest|CheckRedirect|DialContext' .
|
||||
~~~
|
||||
|
||||
Trace custom transports, redirect policies, DNS and connection reuse.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
The URL is checked before Client.Do, but redirect/transport behavior reaches another destination.
|
||||
|
||||
**Fix:** Fixed destinations or a unified URL/redirect/connection policy, timeouts and body limits. Do not prohibit legitimate private-network destinations without checking the contract.
|
||||
|
||||
**Verification:** Mock redirects/DNS/timeouts, normal upstream and oversized responses.
|
||||
|
||||
**Reference:** [primary source](https://cheatsheetseries.owasp.org/cheatsheets/Server_Side_Request_Forgery_Prevention_Cheat_Sheet.html).
|
||||
|
||||
<a id="go-zip-path"></a>
|
||||
|
||||
## GO-ZIP-PATH. filepath.Join does not enforce containment
|
||||
|
||||
**Search:** manual review; no separate scanner rule.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'archive/zip|archive/tar|filepath.Join|EvalSymlinks|MkdirAll' .
|
||||
~~~
|
||||
|
||||
Inspect entry/link names; compare the cleaned path with the root and the actual open operation.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
`Join(root, entry)` writes without checking escapes or symlinks.
|
||||
|
||||
**Fix:** Validate relative paths and entry types, use safe directory-relative opening with a symlink policy, limits and cleanup.
|
||||
|
||||
**Verification:** Valid nested paths, escapes, link entries and parent replacement between check and write.
|
||||
|
||||
**Reference:** [primary source](https://cheatsheetseries.owasp.org/cheatsheets/File_Upload_Cheat_Sheet.html).
|
||||
|
||||
<a id="go-tls-min"></a>
|
||||
|
||||
## GO-TLS-MIN. Obsolete minimum TLS version
|
||||
|
||||
**Search:** scanner rule GO-TLS-MIN. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain GO-TLS-MIN` for details. Regex: MinVersion:tls.VersionSSL30/TLS10/TLS11 and assignments, including newlines; ==, !=, TLS12/TLS13 and 0 do not signal. SSL30 is obsolete and unsupported by modern Go. Review object/effective config/version; numbers, aliases, variables and external listener settings are not evaluated.
|
||||
|
||||
**Vulnerable example:** The setting lowers the minimum of the TLS client/server actually using it, if that runtime version/mode supports the old protocols.
|
||||
|
||||
~~~go
|
||||
cfg := &tls.Config{}
|
||||
cfg.MinVersion = tls.VersionTLS10
|
||||
~~~
|
||||
|
||||
**Fix:** Choose TLS 1.2/1.3 minimum compatible with checker/peers while retaining certificate checks.
|
||||
|
||||
~~~go
|
||||
cfg := &tls.Config{}
|
||||
cfg.MinVersion = tls.VersionTLS12
|
||||
~~~
|
||||
|
||||
**Verification:** Normal peers connect; versions below the chosen minimum fail.
|
||||
|
||||
Both MinVersion: tls.VersionTLS10 and cfg.MinVersion = tls.VersionTLS10 need review. Comparisons ==/!= do not change settings and do not trigger this signal. TLS12/TLS13 and 0 do not trigger it either; 0 selects the runtime default, not a verified security policy.
|
||||
|
||||
VersionSSL30 remains a legacy-configuration signal: the constant's existence does not mean modern Go supports SSLv3. Runtime version/mode and later overrides affect actual behavior. [Go: tls.Config](https://pkg.go.dev/crypto/tls#Config), [Go 1.24 MinVersion contract](https://github.com/golang/go/blob/go1.24.0/src/crypto/tls/common.go#L756).
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'MinVersion|MaxVersion|TLSClientConfig|GetConfigForClient|crypto/tls|GODEBUG|GOFIPS140' .
|
||||
~~~
|
||||
|
||||
Connect the object to the real TLS client/listener; review mutations, configuration callbacks, import aliases, numeric constants and environment-derived values. Regex establishes neither type nor reachability and may match comments. Semantics were reviewed against primary sources; this catalog review did not execute Go or TLS connections.
|
||||
|
||||
<a id="go-jwt-unverified"></a>
|
||||
|
||||
## GO-JWT-UNVERIFIED. JWT without signature or claims verification
|
||||
|
||||
**Search:** scanner rule GO-JWT-UNVERIFIED. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain GO-JWT-UNVERIFIED` for details. Regex: ParseUnverified and WithoutClaimsValidation; does not prove authentication uses the result. The example targets golang-jwt/jwt/v5.
|
||||
|
||||
**Vulnerable example:** Parsed does not mean verified; errors or disabled validation must never authorize a JWT.
|
||||
|
||||
~~~go
|
||||
token, _, err := parser.ParseUnverified(raw, &claims)
|
||||
~~~
|
||||
|
||||
**Fix:** Use a validating API with trusted keyfunc, algorithms and claims; check err before using token/claims.
|
||||
|
||||
~~~go
|
||||
token, err := jwt.ParseWithClaims(raw, &claims, trustedKeyFunc, jwt.WithValidMethods([]string{"RS256"}), jwt.WithIssuer("auth"), jwt.WithAudience("notes"), jwt.WithExpirationRequired())
|
||||
if err != nil || !token.Valid { return ErrUnauthorized }
|
||||
~~~
|
||||
|
||||
**Verification:** Signature/expiry/audience checks work, error nil tokens do not panic and valid tokens pass.
|
||||
|
||||
Primary documentation: [reference 1](https://pkg.go.dev/github.com/golang-jwt/jwt/v5).
|
||||
|
||||
<a id="go-upload-path"></a>
|
||||
|
||||
## GO-UPLOAD-PATH. Multipart filename used directly in a joined path
|
||||
|
||||
**Search:** scanner rule GO-UPLOAD-PATH. Use `--explain GO-UPLOAD-PATH` for the exact detector contract. Regex with lexical exclusions: filepath.Join with a simple first argument and a direct header/fileHeader/file.Filename second argument. The MIME parser may normalize filenames; the rule does not prove traversal, imported types or missing earlier validation.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
~~~go
|
||||
path := filepath.Join(root, header.Filename)
|
||||
~~~
|
||||
|
||||
**Fix:** Choose a non-overwriting server-side storage name outside executable/public roots; authorize downloads and enforce upload size/type.
|
||||
|
||||
~~~go
|
||||
path := filepath.Join(root, serverGeneratedID)
|
||||
~~~
|
||||
|
||||
**Verification:** Alternate separators, traversal, collisions and other-owner requests cannot change the chosen storage path; ordinary uploads work.
|
||||
|
||||
[Primary reference 1](https://pkg.go.dev/mime/multipart#FileHeader)
|
||||
@@ -0,0 +1,596 @@
|
||||
<a id="java-find-fix-and-verify"></a>
|
||||
|
||||
# Java: поиск и исправление
|
||||
|
||||
[English](java.md) | Русский
|
||||
|
||||
[Вся база](README-RU.md) · [Сканер](../offline-scanner-RU.md) · [Проверка патча](../patch-validation-RU.md)
|
||||
|
||||
18 разделов. Формат: **Поиск → Уязвимый вариант → Исправление → Проверка**.
|
||||
Команды `rg` выполняются в корне локальной копии сервиса и только читают файлы. Субъект/владелец определяется по проверенной сессии, а не данным запроса. Примеры нужно адаптировать к реальным API и контракту.
|
||||
|
||||
Автоматические находки — ограниченные синтаксические сигналы для проверки. AST-анализ не разрешает типы и не отслеживает данные между функциями; regex не заменяет парсер языка. Комментарии, строки и одноимённые пользовательские API могут давать совпадения. Проверьте фактическое исполнение, входные данные, авторизацию и границы доверия.
|
||||
|
||||
<a id="contents"></a>
|
||||
|
||||
## Содержание
|
||||
|
||||
- [JAVA-OBJECT — Java ObjectInputStream](#java-object)
|
||||
- [JAVA-RNG — java.util.Random в возможном секрете](#java-rng)
|
||||
- [JAVA-SQL — Динамический JDBC SQL](#java-sql)
|
||||
- [JAVA-PROCESS — Запуск процесса Java](#java-process)
|
||||
- [JAVA-JACKSON-TYPES — Jackson default typing](#java-jackson-types)
|
||||
- [JAVA-XML — XML parser требует явной политики внешних ресурсов](#java-xml)
|
||||
- [JAVA-EXPRESSION — Клиентский текст парсится как SpEL](#java-expression)
|
||||
- [JAVA-PATH — Path resolve без ограничения корня](#java-path)
|
||||
- [JAVA-ZIP-SLIP — ZipEntry становится выходным путём](#java-zip-slip)
|
||||
- [JAVA-SPRING-BIND — Spring binding в domain entity](#java-spring-bind)
|
||||
- [JAVA-SECURITY-MATCHER — Порядок matchers и method security](#java-security-matcher)
|
||||
- [JAVA-THREADLOCAL — ThreadLocal переносит пользователя следующему запросу](#java-threadlocal)
|
||||
- [JAVA-REGEX-DOS — Регулярное выражение блокирует поток](#java-regex-dos)
|
||||
- [JAVA-JNDI — Недоверенное имя JNDI lookup](#java-jndi)
|
||||
- [JAVA-ERROR-LEAK — Stack trace и SQL в API-ошибке](#java-error-leak)
|
||||
- [JAVA-HOSTNAME-VERIFY — Hostname verifier принимает любой сервер](#java-hostname-verify)
|
||||
- [JAVA-SPRING-CSRF — CSRF отключён в Spring Security](#java-spring-csrf)
|
||||
- [JAVA-LDAP-FILTER — Фильтр поиска JNDI собирается конкатенацией](#java-ldap-filter)
|
||||
|
||||
<a id="java-object"></a>
|
||||
|
||||
<a id="java-object-java-objectinputstream"></a>
|
||||
|
||||
## JAVA-OBJECT. Java ObjectInputStream
|
||||
|
||||
**Поиск:** скрипт, правило JAVA-OBJECT. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain JAVA-OBJECT. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
~~~java
|
||||
ObjectInputStream in = new ObjectInputStream(stream);
|
||||
~~~
|
||||
|
||||
**Исправление:** Внешний вход — типизированный формат со схемой; legacy — план миграции и фильтрации типов.
|
||||
|
||||
~~~java
|
||||
Message value = parseValidatedMessage(stream);
|
||||
~~~
|
||||
|
||||
**Проверка:** Произвольный граф классов не загружается.
|
||||
|
||||
<a id="java-rng"></a>
|
||||
|
||||
<a id="java-rng-javautilrandom-near-a-possible-secret"></a>
|
||||
|
||||
## JAVA-RNG. java.util.Random в возможном секрете
|
||||
|
||||
**Поиск:** скрипт, правило JAVA-RNG. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain JAVA-RNG. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
~~~java
|
||||
Random rng = new Random();
|
||||
~~~
|
||||
|
||||
**Исправление:** Для секретов SecureRandom.nextBytes без предсказуемого seed; хеширование малого пространства не добавляет энтропию.
|
||||
|
||||
~~~java
|
||||
SecureRandom rng = new SecureRandom();
|
||||
~~~
|
||||
|
||||
**Проверка:** Нет предсказуемого seed или резервного генератора; challenge/token имеет достаточную энтропию и совместимый формат, штатные токены работают.
|
||||
|
||||
**Вариант A/D:** Публичный PRNG и секретный challenge. **Основание:** 8-bit-oracle, разбор автора и Java-код saarCTF.
|
||||
Один java.util.Random использовался в публичных значениях и challenge.
|
||||
Хеш 32-битного значения не создаёт большего пространства секретов.
|
||||
Сканер: JAVA-RNG; наличие Random вне security-контекста допустимо.
|
||||
|
||||
**Патч:** SecureRandom.nextBytes достаточной длины без предсказуемого seed;
|
||||
публичная статистика не использует состояние генератора секретов.
|
||||
**Тест:** формат и одноразовость challenge, длина/источник случайности,
|
||||
сохранение обычного потока проверки. Не считать статистический тест доказательством
|
||||
криптографической стойкости.
|
||||
|
||||
[исходник/разбор 1](https://github.com/saarsec/saarctf-2024/blob/3a06d18974ca177c6dd251a11bdf9b4b334f382a/8-bit-oracle/README.md); [исходник/разбор 2](https://github.com/saarsec/saarctf-2024/blob/3a06d18974ca177c6dd251a11bdf9b4b334f382a/8-bit-oracle/service/_8BitOracle/src/Util.java).
|
||||
|
||||
<a id="java-sql"></a>
|
||||
|
||||
<a id="java-sql-dynamic-jdbc-sql"></a>
|
||||
|
||||
## JAVA-SQL. Динамический JDBC SQL
|
||||
|
||||
**Поиск:** скрипт, правило JAVA-SQL. Запуск: python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain JAVA-SQL. Regex: executeQuery/executeUpdate/execute/prepareStatement/prepareCall с конкатенацией или String.format. PreparedStatement не защищает уже собранный SQL; переменные SQL и formatter wrappers вручную.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
~~~java
|
||||
statement.executeQuery("SELECT id FROM notes WHERE name=" + name);
|
||||
~~~
|
||||
|
||||
**Исправление:** PreparedStatement + setString/setLong; identifiers фиксировать.
|
||||
|
||||
~~~java
|
||||
PreparedStatement q = connection.prepareStatement("SELECT id FROM notes WHERE name=?");
|
||||
q.setString(1, name);
|
||||
q.executeQuery();
|
||||
~~~
|
||||
|
||||
**Проверка:** Кавычки остаются данными; проверка владельца сохраняется.
|
||||
|
||||
<details>
|
||||
<summary>Развёрнутый пример и ограничения</summary>
|
||||
|
||||
```java
|
||||
// Vulnerable: inputId is interpolated into SQL without an owner constraint.
|
||||
ResultSet rs = statement.executeQuery("SELECT body FROM notes WHERE id = '" + inputId + "'");
|
||||
```
|
||||
|
||||
**Патч JDBC для приватной заметки:**
|
||||
|
||||
```java
|
||||
import java.sql.*;
|
||||
import java.util.Optional;
|
||||
|
||||
final class NoteReader {
|
||||
static Optional<String> read(Connection db, Long userId, long noteId) throws SQLException {
|
||||
if (userId == null) throw new SecurityException("authentication required");
|
||||
try (PreparedStatement st = db.prepareStatement(
|
||||
"SELECT body FROM notes WHERE id = ? AND owner_id = ?")) {
|
||||
st.setLong(1, noteId);
|
||||
st.setLong(2, userId);
|
||||
try (ResultSet rows = st.executeQuery()) {
|
||||
return rows.next() ? Optional.of(rows.getString("body")) : Optional.empty();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Пример предполагает `body NOT NULL`. Если схема разрешает NULL, сохранить
|
||||
его семантику отдельно от отсутствующей строки. Закрываются statement/result set,
|
||||
но не переданное соединение: его жизненным циклом управляет вызывающий код.
|
||||
Входной ID парсится с обработкой ошибок. `PreparedStatement` с уже склеенной
|
||||
SQL-строкой не исправляет проблему.
|
||||
|
||||
**Проверить:** своё/чужое/аноним; неверный и отсутствующий ID; прежние данные;
|
||||
ошибка БД не выдаёт успешный пустой ответ.
|
||||
|
||||
</details>
|
||||
|
||||
<a id="java-process"></a>
|
||||
|
||||
<a id="java-process-java-process-execution"></a>
|
||||
|
||||
## JAVA-PROCESS. Запуск процесса Java
|
||||
|
||||
**Поиск:** скрипт, правило JAVA-PROCESS. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain JAVA-PROCESS. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
~~~java
|
||||
Runtime.getRuntime().exec(command);
|
||||
~~~
|
||||
|
||||
**Исправление:** Предпочитать библиотечную операцию либо фиксированную программу с проверенными argv и ограничениями времени и вывода. ProcessBuilder не всегда shell, но shell -c и выбор executable клиентом опасны.
|
||||
|
||||
~~~java
|
||||
runValidatedConversion(inputPath); // fixed executable and validated argv inside
|
||||
~~~
|
||||
|
||||
**Проверка:** Клиент не меняет программу/опасные опции; конвертация работает.
|
||||
|
||||
<details>
|
||||
<summary>Развёрнутый пример и ограничения</summary>
|
||||
|
||||
```java
|
||||
// Vulnerable: ProcessBuilder does not protect an explicit shell command.
|
||||
Process p = new ProcessBuilder("sh", "-c", "printf '%s' '" + text + "' | sha256sum").start();
|
||||
```
|
||||
|
||||
**Патч для SHA-256 строки:**
|
||||
|
||||
```java
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.util.HexFormat;
|
||||
|
||||
final class ContentDigest {
|
||||
static String of(String text) throws NoSuchAlgorithmException {
|
||||
byte[] sum = MessageDigest.getInstance("SHA-256").digest(text.getBytes(StandardCharsets.UTF_8));
|
||||
return HexFormat.of().formatHex(sum);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`HexFormat` требует Java 17; на старом runtime использовать существующее
|
||||
проверенное кодирование hex, не обновлять весь сервис ради этого примера.
|
||||
Не делить один изменяемый `MessageDigest` между потоками. Сохранить ожидаемый
|
||||
формат ответа; этот digest не заменяет алгоритм хранения паролей.
|
||||
|
||||
**Проверить:** известный digest, пустой текст, Unicode и кавычки; `null` отклонён
|
||||
на входе API; внешняя программа не запускается.
|
||||
|
||||
</details>
|
||||
|
||||
<a id="java-jackson-types"></a>
|
||||
|
||||
<a id="java-jackson-types-jackson-default-typing"></a>
|
||||
|
||||
## JAVA-JACKSON-TYPES. Jackson default typing
|
||||
|
||||
**Поиск:** скрипт, правило JAVA-JACKSON-TYPES. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain JAVA-JACKSON-TYPES. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
~~~java
|
||||
mapper.enableDefaultTyping();
|
||||
~~~
|
||||
|
||||
**Исправление:** Конкретные DTO; если полиморфизм необходим — ограниченный набор подтипов/валидатор своей версии, не package-wide allowlist.
|
||||
|
||||
~~~java
|
||||
// deserialize into a fixed DTO without client-selected implementation types
|
||||
~~~
|
||||
|
||||
**Проверка:** Неизвестный тип отвергается до побочных эффектов; старый допустимый документ читается.
|
||||
|
||||
**Основание:** [первичный материал](https://github.com/FasterXML/jackson-docs/wiki/JacksonPolymorphicDeserialization).
|
||||
|
||||
<a id="java-xml"></a>
|
||||
|
||||
<a id="java-xml-xml-parser-needs-an-external-resource-policy"></a>
|
||||
|
||||
## JAVA-XML. XML parser требует явной политики внешних ресурсов
|
||||
|
||||
**Поиск:** скрипт, правило JAVA-XML. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain JAVA-XML. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
~~~java
|
||||
var f = DocumentBuilderFactory.newInstance();
|
||||
~~~
|
||||
|
||||
**Исправление:** Ограничить DTD/entities/schema/XSLT для конкретного factory, включить лимиты. Неподдержанный security feature не игнорировать.
|
||||
|
||||
~~~java
|
||||
var f = DocumentBuilderFactory.newInstance();
|
||||
f.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "");
|
||||
f.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, "");
|
||||
// also configure DTD/entity policy and parser-specific limits
|
||||
~~~
|
||||
|
||||
**Проверка:** Parser не читает внешние файлы/URL; допустимый XML и лимиты работают.
|
||||
|
||||
**Основание:** [первичный материал](https://docs.oracle.com/en/java/javase/17/security/java-api-xml-processing-jaxp-security-guide.html).
|
||||
|
||||
<a id="java-expression"></a>
|
||||
|
||||
<a id="java-expression-client-text-parsed-as-spel"></a>
|
||||
|
||||
## JAVA-EXPRESSION. Клиентский текст парсится как SpEL
|
||||
|
||||
**Поиск:** скрипт, правило JAVA-EXPRESSION. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain JAVA-EXPRESSION. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
~~~java
|
||||
parser.parseExpression(input).getValue(context);
|
||||
~~~
|
||||
|
||||
**Исправление:** Фиксированные операции и аргументы; если DSL нужен, минимальная грамматика и возможности evaluation context. Не отдавать полный reflection клиенту.
|
||||
|
||||
~~~java
|
||||
lookupAllowedOperation(operationId, validatedArguments);
|
||||
~~~
|
||||
|
||||
**Проверка:** Запрещённые операции не достигают runtime; разрешённые вычисления сохранены.
|
||||
|
||||
**Основание:** [первичный материал](https://docs.spring.io/spring-framework/reference/core/expressions.html).
|
||||
|
||||
<a id="java-path"></a>
|
||||
|
||||
<a id="java-path-path-resolve-without-a-root-boundary"></a>
|
||||
|
||||
## JAVA-PATH. Path resolve без ограничения корня
|
||||
|
||||
**Поиск:** вручную; отдельного правила сканера нет.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'resolve\(|readAllBytes|new File|Paths.get|toRealPath' .
|
||||
~~~
|
||||
|
||||
Сравнить Path root и target после нормализации/разрешения ссылки; проверить ownership и гонку открытия.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
Files.readAllBytes(base.resolve(name)) читает имя клиента без границы.
|
||||
|
||||
**Исправление:** Серверное имя из авторизованного ID либо Path containment, отдельная политика symlink и безопасное открытие; лимит чтения.
|
||||
|
||||
**Проверка:** Соседний каталог с общим префиксом, absolute path, symlink, чужой объект и штатный файл.
|
||||
|
||||
<details>
|
||||
<summary>Развёрнутый пример и ограничения</summary>
|
||||
|
||||
```java
|
||||
// Vulnerable: name can move the read outside the permitted directory.
|
||||
byte[] data = Files.readAllBytes(base.resolve(name));
|
||||
```
|
||||
|
||||
**Патч для существующих файлов в доверенном неизменяемом дереве:**
|
||||
|
||||
```java
|
||||
import java.io.IOException;
|
||||
import java.nio.file.*;
|
||||
|
||||
final class FileBoundary {
|
||||
static Path existingFile(Path base, String name) throws IOException {
|
||||
if (name == null || name.isEmpty()) throw new IllegalArgumentException("path required");
|
||||
Path relative = Path.of(name);
|
||||
if (relative.isAbsolute()) throw new IllegalArgumentException("relative path required");
|
||||
Path root = base.toRealPath();
|
||||
Path target = root.resolve(relative).toRealPath();
|
||||
if (!target.startsWith(root) || !Files.isRegularFile(target)) {
|
||||
throw new IllegalArgumentException("outside allowed directory");
|
||||
}
|
||||
return target;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Здесь `startsWith` — метод **Path**, не строковое сравнение. `toRealPath` требует
|
||||
существования и учитывает symlink. Если дерево может меняться между проверкой
|
||||
и открытием, остаётся TOCTOU: нужен подход с безопасным открытием относительно
|
||||
каталога, поддержанный платформой. Этот фрагмент не предназначен для записи
|
||||
или распаковки архивов. Проверка права на файл и лимит чтения требуются отдельно.
|
||||
|
||||
**Проверить:** разрешённый файл, соседний каталог с похожим именем, абсолютный
|
||||
путь, ссылка наружу, отсутствие файла, файл другого пользователя.
|
||||
|
||||
</details>
|
||||
|
||||
**Основание:** [первичный материал](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/nio/file/Path.html).
|
||||
|
||||
<a id="java-zip-slip"></a>
|
||||
|
||||
<a id="java-zip-slip-zipentry-becomes-an-output-path"></a>
|
||||
|
||||
## JAVA-ZIP-SLIP. ZipEntry становится выходным путём
|
||||
|
||||
**Поиск:** вручную; отдельного правила сканера нет.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'ZipInputStream|ZipFile|getName\(|resolve\(' .
|
||||
~~~
|
||||
|
||||
Пройти каждый entry → target → write, включая имена каталогов и metadata links.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
Имя из архива присоединено к каталогу без containment и контроля фактического дерева.
|
||||
|
||||
**Исправление:** Валидировать все пути/типы, не следовать недоверенным ссылкам, ограничить размер/entries и публиковать после успеха.
|
||||
|
||||
**Проверка:** Обычный архив, absolute/traversal entry, превышение объёма и уборка при отказе.
|
||||
|
||||
**Основание:** [первичный материал](https://cheatsheetseries.owasp.org/cheatsheets/File_Upload_Cheat_Sheet.html).
|
||||
|
||||
<a id="java-spring-bind"></a>
|
||||
|
||||
<a id="java-spring-bind-spring-binds-request-data-into-a-domain-entity"></a>
|
||||
|
||||
## JAVA-SPRING-BIND. Spring binding в domain entity
|
||||
|
||||
**Поиск:** вручную; отдельного правила сканера нет.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e '@ModelAttribute|@RequestBody|DataBinder|setAllowedFields|BeanUtils' .
|
||||
~~~
|
||||
|
||||
Сверить публичные setters, nested properties и поля владельца с данными запроса.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
Binder пишет owner/admin/status в entity до проверки доступа.
|
||||
|
||||
**Исправление:** Отдельный request DTO с разрешёнными полями и явное копирование после auth; ограничения вложенных путей.
|
||||
|
||||
**Проверка:** Служебные поля и nested update не меняются; допустимое частичное обновление работает.
|
||||
|
||||
<a id="java-security-matcher"></a>
|
||||
|
||||
<a id="java-security-matcher-matcher-ordering-and-method-security"></a>
|
||||
|
||||
## JAVA-SECURITY-MATCHER. Порядок matchers и method security
|
||||
|
||||
**Поиск:** вручную; отдельного правила сканера нет.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'SecurityFilterChain|requestMatchers|permitAll|PreAuthorize|EnableMethodSecurity' .
|
||||
~~~
|
||||
|
||||
Проверить первый подходящий matcher, все HTTP-методы, dispatch types и включение method security.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
Широкий permitAll срабатывает раньше приватного правила; аннотация метода не активна.
|
||||
|
||||
**Исправление:** Явная политика маршрутов с отказом по умолчанию для приватной области, проверка ресурса в service; согласовать публичные endpoint.
|
||||
|
||||
**Проверка:** Аноним, обычный user и admin проходят ожидаемые маршруты/методы; error/forward не обходят auth.
|
||||
|
||||
<a id="java-threadlocal"></a>
|
||||
|
||||
<a id="java-threadlocal-threadlocal-leaks-the-previous-requests-user"></a>
|
||||
|
||||
## JAVA-THREADLOCAL. ThreadLocal переносит пользователя следующему запросу
|
||||
|
||||
**Поиск:** вручную; отдельного правила сканера нет.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'ThreadLocal|SecurityContext|Executor|CompletableFuture|remove\(' .
|
||||
~~~
|
||||
|
||||
Сверить set/remove в finally и передачу контекста в thread pool.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
Поток переиспользуется после исключения с прежним principal.
|
||||
|
||||
**Исправление:** Штатный security-context lifecycle или явная очистка; async task получает минимальный неизменяемый контекст.
|
||||
|
||||
**Проверка:** Последовательные разные пользователи на одном worker и исключение между установкой/очисткой.
|
||||
|
||||
<a id="java-regex-dos"></a>
|
||||
|
||||
<a id="java-regex-dos-a-regular-expression-blocks-a-worker"></a>
|
||||
|
||||
## JAVA-REGEX-DOS. Регулярное выражение блокирует поток
|
||||
|
||||
**Поиск:** вручную; отдельного правила сканера нет.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'Pattern.compile|Matcher|matches\(|replaceAll' .
|
||||
~~~
|
||||
|
||||
Проверить вложенные квантификаторы и почти совпадающие длинные строки; timeout запроса не обязательно прерывает matcher.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
Backtracking на вводе клиента занимает worker вне установленного HTTP timeout.
|
||||
|
||||
**Исправление:** Упростить паттерн/детерминированный parser, ограничить длину, при нужде совместимый движок с ограниченной сложностью.
|
||||
|
||||
**Проверка:** Длинный неуспешный match завершается в бюджете; обычный формат и Unicode сохранены.
|
||||
|
||||
<a id="java-jndi"></a>
|
||||
|
||||
<a id="java-jndi-dynamic-jndi-lookup-name"></a>
|
||||
|
||||
## JAVA-JNDI. Недоверенное имя JNDI lookup
|
||||
|
||||
**Поиск:** скрипт, правило JAVA-JNDI. Запуск: python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain JAVA-JNDI. Regex: InitialContext.doLookup или ctx/context/initialContext.lookup с нестроковым аргументом. Произвольные имена объектов и косвенные вызовы искать вручную.
|
||||
|
||||
Дополнительный ручной поиск для непокрытых форм:
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'InitialContext|JndiTemplate|lookup\(|NamingManager' .
|
||||
~~~
|
||||
|
||||
Проследить имя/provider URL и локальные object factories; ограничения удалённого codebase не отменяют остальные эффекты.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
Клиент выбирает ресурс/службу для lookup с привилегиями приложения.
|
||||
|
||||
**Исправление:** Закрытая серверная карта доверенных локальных имён, ограниченные providers/factories и совместимый исправленный runtime. Обновление JDK не заменяет проверку входных данных.
|
||||
|
||||
**Проверка:** Чужая схема/имя не вызывает lookup; штатный datasource работает.
|
||||
|
||||
|
||||
**Сигнал сканера — пример до:**
|
||||
|
||||
~~~java
|
||||
Object value = context.lookup(requestName);
|
||||
~~~
|
||||
|
||||
**Шаблон исправления:**
|
||||
|
||||
~~~java
|
||||
Object value = context.lookup("java:comp/env/jdbc/Notes");
|
||||
~~~
|
||||
|
||||
Первичная документация: [документация 1](https://docs.oracle.com/en/java/javase/21/docs/api/java.naming/javax/naming/InitialContext.html).
|
||||
|
||||
<a id="java-error-leak"></a>
|
||||
|
||||
<a id="java-error-leak-stack-traces-and-sql-in-api-errors"></a>
|
||||
|
||||
## JAVA-ERROR-LEAK. Stack trace и SQL в API-ошибке
|
||||
|
||||
**Поиск:** вручную; отдельного правила сканера нет.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'printStackTrace|getMessage\(|ResponseEntity|ExceptionHandler' .
|
||||
~~~
|
||||
|
||||
Сравнить локальный журнал и клиентский body для ошибок auth/SQL/parser.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
Клиент получает SQL, пути, connection string или секретные параметры из exception.
|
||||
|
||||
**Исправление:** Штатная кодированная ошибка и correlation ID; чувствительные значения редактировать до логирования.
|
||||
|
||||
**Проверка:** Диагностика остаётся локально, ответы ошибок не содержат приватных данных.
|
||||
|
||||
<a id="java-hostname-verify"></a>
|
||||
|
||||
<a id="java-hostname-verify-hostname-verifier-accepts-every-peer"></a>
|
||||
|
||||
## JAVA-HOSTNAME-VERIFY. Hostname verifier принимает любой сервер
|
||||
|
||||
**Поиск:** скрипт, правило JAVA-HOSTNAME-VERIFY. Запуск: python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain JAVA-HOSTNAME-VERIFY. Regex: NoopHostnameVerifier/ALLOW_ALL_HOSTNAME_VERIFIER и setHostnameVerifier с простой true-lambda; сложные callbacks и TrustManager требуют ручного анализа.
|
||||
|
||||
**Уязвимый вариант:** Проверка цепочки сертификата без имени не подтверждает нужный сервер.
|
||||
|
||||
~~~java
|
||||
builder.setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE);
|
||||
~~~
|
||||
|
||||
**Исправление:** Вернуть стандартный verifier и доверенный trust store; не подменять его callback, всегда возвращающим true.
|
||||
|
||||
~~~java
|
||||
builder.setSSLHostnameVerifier(new DefaultHostnameVerifier());
|
||||
~~~
|
||||
|
||||
**Проверка:** Сертификат доверенного CA для другого hostname отклоняется; свой endpoint работает.
|
||||
|
||||
Первичная документация: [документация 1](https://hc.apache.org/httpcomponents-client-5.5.x/current/httpclient5/apidocs/org/apache/hc/client5/http/ssl/NoopHostnameVerifier.html).
|
||||
|
||||
<a id="java-spring-csrf"></a>
|
||||
|
||||
<a id="java-spring-csrf-spring-security-csrf-disabled"></a>
|
||||
|
||||
## JAVA-SPRING-CSRF. CSRF отключён в Spring Security
|
||||
|
||||
**Поиск:** скрипт, правило JAVA-SPRING-CSRF. Запуск: python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain JAVA-SPRING-CSRF. Regex: csrf().disable(), csrf(x -> x.disable()) и csrf(AbstractHttpConfigurer::disable). Отдельные security chains и матчеры просматривать вручную.
|
||||
|
||||
**Уязвимый вариант:** Cookie-auth операции могут потерять CSRF-защиту при глобальном disable.
|
||||
|
||||
~~~java
|
||||
http.csrf(csrf -> csrf.disable());
|
||||
~~~
|
||||
|
||||
**Исправление:** Сохранить защиту браузерных запросов; исключения ограничить конкретным bearer/webhook контрактом и проверить отсутствие cookie fallback.
|
||||
|
||||
~~~java
|
||||
http.csrf(Customizer.withDefaults());
|
||||
~~~
|
||||
|
||||
**Проверка:** Штатный запрос с CSRF работает, cookie POST без токена отвергнут; разрешённый API сценарий не сломан.
|
||||
|
||||
Первичная документация: [документация 1](https://docs.spring.io/spring-security/reference/servlet/exploits/csrf.html).
|
||||
|
||||
<a id="java-ldap-filter"></a>
|
||||
|
||||
<a id="java-ldap-filter-jndi-search-filter-assembled-by-concatenation"></a>
|
||||
|
||||
## JAVA-LDAP-FILTER. Фильтр поиска JNDI собирается конкатенацией
|
||||
|
||||
**Поиск:** правило сканера JAVA-LDAP-FILTER. Точный контракт детектора: `--explain JAVA-LDAP-FILTER`. Regex с лексическими исключениями: ctx/context/dirContext.search с простым первым аргументом и напрямую склеенным строковым фильтром. Не разрешает тип получателя, заранее собранные фильтры, wrappers и предшествующее экранирование.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
~~~java
|
||||
ctx.search(base, "(uid=" + name + ")", controls);
|
||||
~~~
|
||||
|
||||
**Исправление:** Используйте аргументы фильтра JNDI с фиксированным фильтром; сохраняйте явную область поиска и авторизацию.
|
||||
|
||||
~~~java
|
||||
ctx.search(base, "(uid={0})", new Object[] { name }, controls);
|
||||
~~~
|
||||
|
||||
**Проверка:** Метасимволы фильтра остаются значениями; недоступные пользователю записи не раскрываются, а допустимые поиски работают.
|
||||
|
||||
[Первичный источник 1](https://docs.oracle.com/javase/jndi/tutorial/ldap/search/search.html)
|
||||
@@ -0,0 +1,533 @@
|
||||
# Java: find, fix and verify
|
||||
|
||||
English | [Русский](java-RU.md)
|
||||
|
||||
[Catalog](README.md) · [Scanner](../offline-scanner.md) · [Patch verification](../patch-validation.md)
|
||||
|
||||
18 sections. Each follows **Search → Vulnerable example → Fix → Verification**.
|
||||
Run `rg` from a local service checkout; searches only read files. Derive the actor/owner from a verified session, not request data. Adapt examples to the actual API and contract.
|
||||
|
||||
## Contents
|
||||
|
||||
- [JAVA-OBJECT — Java ObjectInputStream](#java-object)
|
||||
- [JAVA-RNG — java.util.Random near a possible secret](#java-rng)
|
||||
- [JAVA-SQL — Dynamic JDBC SQL](#java-sql)
|
||||
- [JAVA-PROCESS — Java process execution](#java-process)
|
||||
- [JAVA-JACKSON-TYPES — Jackson default typing](#java-jackson-types)
|
||||
- [JAVA-XML — XML parser needs an external-resource policy](#java-xml)
|
||||
- [JAVA-EXPRESSION — Client text parsed as SpEL](#java-expression)
|
||||
- [JAVA-PATH — Path resolve without a root boundary](#java-path)
|
||||
- [JAVA-ZIP-SLIP — ZipEntry becomes an output path](#java-zip-slip)
|
||||
- [JAVA-SPRING-BIND — Spring binds request data into a domain entity](#java-spring-bind)
|
||||
- [JAVA-SECURITY-MATCHER — Matcher ordering and method security](#java-security-matcher)
|
||||
- [JAVA-THREADLOCAL — ThreadLocal leaks the previous request's user](#java-threadlocal)
|
||||
- [JAVA-REGEX-DOS — A regular expression blocks a worker](#java-regex-dos)
|
||||
- [JAVA-JNDI — Dynamic JNDI lookup name](#java-jndi)
|
||||
- [JAVA-ERROR-LEAK — Stack traces and SQL in API errors](#java-error-leak)
|
||||
- [JAVA-HOSTNAME-VERIFY — Hostname verifier accepts every peer](#java-hostname-verify)
|
||||
- [JAVA-SPRING-CSRF — Spring Security CSRF disabled](#java-spring-csrf)
|
||||
- [JAVA-LDAP-FILTER — JNDI search filter assembled by concatenation](#java-ldap-filter)
|
||||
|
||||
<a id="java-object"></a>
|
||||
|
||||
## JAVA-OBJECT. Java ObjectInputStream
|
||||
|
||||
**Search:** scanner rule JAVA-OBJECT. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain JAVA-OBJECT` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
~~~java
|
||||
ObjectInputStream in = new ObjectInputStream(stream);
|
||||
~~~
|
||||
|
||||
**Fix:** Prefer constrained DTO parsing over native object deserialization; migrate trusted legacy data separately.
|
||||
|
||||
~~~java
|
||||
Message value = parseValidatedMessage(stream);
|
||||
~~~
|
||||
|
||||
**Verification:** Unknown types cannot be constructed; ordinary messages stay compatible.
|
||||
|
||||
<a id="java-rng"></a>
|
||||
|
||||
## JAVA-RNG. java.util.Random near a possible secret
|
||||
|
||||
**Search:** scanner rule JAVA-RNG. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain JAVA-RNG` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
~~~java
|
||||
Random rng = new Random();
|
||||
~~~
|
||||
|
||||
**Fix:** Use SecureRandom and sufficient token length for secrets.
|
||||
|
||||
~~~java
|
||||
SecureRandom rng = new SecureRandom();
|
||||
~~~
|
||||
|
||||
**Verification:** No predictable seed or fallback exists; valid tokens work.
|
||||
|
||||
**A/D variant:** Public PRNG output and secret challenges. **Reference:** 8-bit-oracle, the author's write-up and saarCTF Java source. One java.util.Random instance generated both public values and challenges. Hashing a 32-bit value does not enlarge its secret space. Scanner: JAVA-RNG; Random outside a security context can be legitimate.
|
||||
|
||||
**Patch:** Use sufficiently long SecureRandom.nextBytes output without predictable seeds; public statistics must not share secret-generator state.
|
||||
**Test:** Challenge format and one-time use, randomness source/length and the normal verification workflow. Statistical tests do not prove cryptographic strength.
|
||||
|
||||
[Source/write-up 1](https://github.com/saarsec/saarctf-2024/blob/3a06d18974ca177c6dd251a11bdf9b4b334f382a/8-bit-oracle/README.md); [source/write-up 2](https://github.com/saarsec/saarctf-2024/blob/3a06d18974ca177c6dd251a11bdf9b4b334f382a/8-bit-oracle/service/_8BitOracle/src/Util.java).
|
||||
|
||||
<a id="java-sql"></a>
|
||||
|
||||
## JAVA-SQL. Dynamic JDBC SQL
|
||||
|
||||
**Search:** scanner rule JAVA-SQL. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain JAVA-SQL` for details. Regex: executeQuery/executeUpdate/execute/prepareStatement/prepareCall with concatenation or String.format. PreparedStatement does not secure already-built SQL; inspect SQL variables and formatter wrappers.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
~~~java
|
||||
statement.executeQuery("SELECT id FROM notes WHERE name=" + name);
|
||||
~~~
|
||||
|
||||
**Fix:** Bind values with PreparedStatement, not already-concatenated SQL; allowlist identifiers.
|
||||
|
||||
~~~java
|
||||
PreparedStatement q = connection.prepareStatement("SELECT id FROM notes WHERE name=?");
|
||||
q.setString(1, name);
|
||||
q.executeQuery();
|
||||
~~~
|
||||
|
||||
**Verification:** Quotes stay data and ownership remains enforced.
|
||||
|
||||
<details>
|
||||
<summary>Expanded example and limitations</summary>
|
||||
|
||||
```java
|
||||
// Vulnerable: inputId is interpolated into SQL without an owner constraint.
|
||||
ResultSet rs = statement.executeQuery("SELECT body FROM notes WHERE id = '" + inputId + "'");
|
||||
```
|
||||
|
||||
**JDBC patch for a private note:**
|
||||
|
||||
```java
|
||||
import java.sql.*;
|
||||
import java.util.Optional;
|
||||
|
||||
final class NoteReader {
|
||||
static Optional<String> read(Connection db, Long userId, long noteId) throws SQLException {
|
||||
if (userId == null) throw new SecurityException("authentication required");
|
||||
try (PreparedStatement st = db.prepareStatement(
|
||||
"SELECT body FROM notes WHERE id = ? AND owner_id = ?")) {
|
||||
st.setLong(1, noteId);
|
||||
st.setLong(2, userId);
|
||||
try (ResultSet rows = st.executeQuery()) {
|
||||
return rows.next() ? Optional.of(rows.getString("body")) : Optional.empty();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
The example assumes `body NOT NULL`. If NULL is allowed, distinguish it from a missing row. The statement/result set are closed, but not the caller-owned connection. Parse incoming IDs with error handling. PreparedStatement around an already concatenated query does not fix injection.
|
||||
|
||||
**Check:** Owner, other user, anonymous caller; invalid/missing IDs; old data; database errors must not become successful empty responses.
|
||||
|
||||
</details>
|
||||
|
||||
<a id="java-process"></a>
|
||||
|
||||
## JAVA-PROCESS. Java process execution
|
||||
|
||||
**Search:** scanner rule JAVA-PROCESS. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain JAVA-PROCESS` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
~~~java
|
||||
Runtime.getRuntime().exec(command);
|
||||
~~~
|
||||
|
||||
**Fix:** Use a library operation or fixed executable with validated argv and bounded time/output.
|
||||
|
||||
~~~java
|
||||
runValidatedConversion(inputPath); // fixed executable and validated argv inside
|
||||
~~~
|
||||
|
||||
**Verification:** Arguments cannot choose another operation; output stays compatible.
|
||||
|
||||
<details>
|
||||
<summary>Expanded example and limitations</summary>
|
||||
|
||||
```java
|
||||
// Vulnerable: ProcessBuilder does not protect an explicit shell command.
|
||||
Process p = new ProcessBuilder("sh", "-c", "printf '%s' '" + text + "' | sha256sum").start();
|
||||
```
|
||||
|
||||
**Patch for a string's SHA-256 digest:**
|
||||
|
||||
```java
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.util.HexFormat;
|
||||
|
||||
final class ContentDigest {
|
||||
static String of(String text) throws NoSuchAlgorithmException {
|
||||
byte[] sum = MessageDigest.getInstance("SHA-256").digest(text.getBytes(StandardCharsets.UTF_8));
|
||||
return HexFormat.of().formatHex(sum);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`HexFormat` requires Java 17; on older runtimes use the existing reviewed hex encoder rather than upgrading the entire service for this example. Never share mutable MessageDigest state across threads. Preserve the response format; this digest is not a password-storage algorithm.
|
||||
|
||||
**Check:** Known digest, empty text, Unicode and quotes; reject null at the API boundary; no external program runs.
|
||||
|
||||
</details>
|
||||
|
||||
<a id="java-jackson-types"></a>
|
||||
|
||||
## JAVA-JACKSON-TYPES. Jackson default typing
|
||||
|
||||
**Search:** scanner rule JAVA-JACKSON-TYPES. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain JAVA-JACKSON-TYPES` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
~~~java
|
||||
mapper.enableDefaultTyping();
|
||||
~~~
|
||||
|
||||
**Fix:** Prefer explicit DTOs; required polymorphism needs a narrow type set/validator for the installed version, not a package-wide allowlist.
|
||||
|
||||
~~~java
|
||||
// deserialize into a fixed DTO without client-selected implementation types
|
||||
~~~
|
||||
|
||||
**Verification:** Unknown types fail before side effects; valid documents remain readable.
|
||||
|
||||
**Reference:** [primary source](https://github.com/FasterXML/jackson-docs/wiki/JacksonPolymorphicDeserialization).
|
||||
|
||||
<a id="java-xml"></a>
|
||||
|
||||
## JAVA-XML. XML parser needs an external-resource policy
|
||||
|
||||
**Search:** scanner rule JAVA-XML. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain JAVA-XML` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
~~~java
|
||||
var f = DocumentBuilderFactory.newInstance();
|
||||
~~~
|
||||
|
||||
**Fix:** Restrict DTD/entities/schema/XSLT on the actual factory and set limits; never silently ignore unsupported security options.
|
||||
|
||||
~~~java
|
||||
var f = DocumentBuilderFactory.newInstance();
|
||||
f.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "");
|
||||
f.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, "");
|
||||
// also configure DTD/entity policy and parser-specific limits
|
||||
~~~
|
||||
|
||||
**Verification:** Parser reads no external files/URLs; ordinary XML and size limits work.
|
||||
|
||||
**Reference:** [primary source](https://docs.oracle.com/en/java/javase/17/security/java-api-xml-processing-jaxp-security-guide.html).
|
||||
|
||||
<a id="java-expression"></a>
|
||||
|
||||
## JAVA-EXPRESSION. Client text parsed as SpEL
|
||||
|
||||
**Search:** scanner rule JAVA-EXPRESSION. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain JAVA-EXPRESSION` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
~~~java
|
||||
parser.parseExpression(input).getValue(context);
|
||||
~~~
|
||||
|
||||
**Fix:** Use fixed operations/arguments or a restricted DSL and evaluation context; never expose arbitrary reflection.
|
||||
|
||||
~~~java
|
||||
lookupAllowedOperation(operationId, validatedArguments);
|
||||
~~~
|
||||
|
||||
**Verification:** Disallowed operations cannot reach runtime; approved calculations work.
|
||||
|
||||
**Reference:** [primary source](https://docs.spring.io/spring-framework/reference/core/expressions.html).
|
||||
|
||||
<a id="java-path"></a>
|
||||
|
||||
## JAVA-PATH. Path resolve without a root boundary
|
||||
|
||||
**Search:** manual review; no separate scanner rule.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'resolve\(|readAllBytes|new File|Paths.get|toRealPath' .
|
||||
~~~
|
||||
|
||||
Compare root and target Paths after normalization/link resolution; check ownership and open-time races.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
`Files.readAllBytes(base.resolve(name))` reads a client-selected name without a boundary.
|
||||
|
||||
**Fix:** Derive a server-side filename from an authorized ID, or enforce Path containment with an explicit symlink policy and safe opening; bound reads.
|
||||
|
||||
**Verification:** Sibling directory with a shared prefix, absolute path, symlink, another owner's object and a legitimate file.
|
||||
|
||||
<details>
|
||||
<summary>Expanded example and limitations</summary>
|
||||
|
||||
```java
|
||||
// Vulnerable: name can move the read outside the permitted directory.
|
||||
byte[] data = Files.readAllBytes(base.resolve(name));
|
||||
```
|
||||
|
||||
**Patch for existing files in a trusted immutable tree:**
|
||||
|
||||
```java
|
||||
import java.io.IOException;
|
||||
import java.nio.file.*;
|
||||
|
||||
final class FileBoundary {
|
||||
static Path existingFile(Path base, String name) throws IOException {
|
||||
if (name == null || name.isEmpty()) throw new IllegalArgumentException("path required");
|
||||
Path relative = Path.of(name);
|
||||
if (relative.isAbsolute()) throw new IllegalArgumentException("relative path required");
|
||||
Path root = base.toRealPath();
|
||||
Path target = root.resolve(relative).toRealPath();
|
||||
if (!target.startsWith(root) || !Files.isRegularFile(target)) {
|
||||
throw new IllegalArgumentException("outside allowed directory");
|
||||
}
|
||||
return target;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`startsWith` here is a **Path** method, not string-prefix comparison. `toRealPath` requires existence and resolves symlinks. A mutable tree still permits TOCTOU between checking and opening: use platform-supported directory-relative safe opening. This snippet is not for writing or archive extraction. Authorization and read limits remain separate requirements.
|
||||
|
||||
**Check:** Allowed file, similarly named sibling directory, absolute path, outward link, missing file and another user's file.
|
||||
|
||||
</details>
|
||||
|
||||
**Reference:** [primary source](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/nio/file/Path.html).
|
||||
|
||||
<a id="java-zip-slip"></a>
|
||||
|
||||
## JAVA-ZIP-SLIP. ZipEntry becomes an output path
|
||||
|
||||
**Search:** manual review; no separate scanner rule.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'ZipInputStream|ZipFile|getName\(|resolve\(' .
|
||||
~~~
|
||||
|
||||
Trace every entry through target selection to writing, including directory names and link metadata.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
An archive name is joined to a directory without containment or checking the actual filesystem tree.
|
||||
|
||||
**Fix:** Validate all paths/types, avoid untrusted links, limit expanded size/entries and publish only after success.
|
||||
|
||||
**Verification:** Ordinary archive, absolute/traversal entries, volume overflow and cleanup after rejection.
|
||||
|
||||
**Reference:** [primary source](https://cheatsheetseries.owasp.org/cheatsheets/File_Upload_Cheat_Sheet.html).
|
||||
|
||||
<a id="java-spring-bind"></a>
|
||||
|
||||
## JAVA-SPRING-BIND. Spring binds request data into a domain entity
|
||||
|
||||
**Search:** manual review; no separate scanner rule.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e '@ModelAttribute|@RequestBody|DataBinder|setAllowedFields|BeanUtils' .
|
||||
~~~
|
||||
|
||||
Compare public setters, nested properties and ownership fields with incoming data.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
The binder writes owner/admin/status into an entity before authorization.
|
||||
|
||||
**Fix:** A dedicated request DTO with allowed fields, copied explicitly after authorization; restrict nested paths.
|
||||
|
||||
**Verification:** Administrative fields and nested updates cannot change; legitimate partial updates work.
|
||||
|
||||
<a id="java-security-matcher"></a>
|
||||
|
||||
## JAVA-SECURITY-MATCHER. Matcher ordering and method security
|
||||
|
||||
**Search:** manual review; no separate scanner rule.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'SecurityFilterChain|requestMatchers|permitAll|PreAuthorize|EnableMethodSecurity' .
|
||||
~~~
|
||||
|
||||
Check the first matching rule, all HTTP methods, dispatch types and whether method security is actually enabled.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
A broad permitAll precedes a private rule, or the method annotation is inactive.
|
||||
|
||||
**Fix:** Explicit route policy with default denial for private areas and resource checks in the service layer; preserve intended public endpoints.
|
||||
|
||||
**Verification:** Anonymous, ordinary and administrator users get their expected routes/methods; error/forward dispatch does not bypass authorization.
|
||||
|
||||
<a id="java-threadlocal"></a>
|
||||
|
||||
## JAVA-THREADLOCAL. ThreadLocal leaks the previous request's user
|
||||
|
||||
**Search:** manual review; no separate scanner rule.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'ThreadLocal|SecurityContext|Executor|CompletableFuture|remove\(' .
|
||||
~~~
|
||||
|
||||
Review set/remove inside finally and context propagation into thread pools.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
A thread is reused after an exception with the previous principal still attached.
|
||||
|
||||
**Fix:** Use the framework's security-context lifecycle or explicit cleanup; give async tasks minimal immutable context.
|
||||
|
||||
**Verification:** Sequential different users on the same worker and an exception between context setup and cleanup.
|
||||
|
||||
<a id="java-regex-dos"></a>
|
||||
|
||||
## JAVA-REGEX-DOS. A regular expression blocks a worker
|
||||
|
||||
**Search:** manual review; no separate scanner rule.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'Pattern.compile|Matcher|matches\(|replaceAll' .
|
||||
~~~
|
||||
|
||||
Review nested quantifiers and long near-matches; request timeout does not necessarily interrupt the matcher.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
Backtracking on client input occupies a worker beyond the HTTP timeout.
|
||||
|
||||
**Fix:** Simplify the pattern or use a deterministic parser, limit input length and, where compatible, use a bounded-complexity engine.
|
||||
|
||||
**Verification:** Long failing matches finish within budget; normal formats and Unicode remain compatible.
|
||||
|
||||
<a id="java-jndi"></a>
|
||||
|
||||
## JAVA-JNDI. Dynamic JNDI lookup name
|
||||
|
||||
**Search:** scanner rule JAVA-JNDI. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain JAVA-JNDI` for details. Regex: InitialContext.doLookup or ctx/context/initialContext.lookup with a non-string argument. Inspect arbitrary receiver names and indirect calls manually.
|
||||
|
||||
Additional manual search for forms outside automatic coverage:
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'InitialContext|JndiTemplate|lookup\(|NamingManager' .
|
||||
~~~
|
||||
|
||||
Trace the name/provider URL and local object factories; disabling remote codebases does not remove other effects.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
The client selects the resource/service for a lookup using application privileges.
|
||||
|
||||
**Fix:** Use a closed map of trusted local names and restrict providers; JDK updates do not replace input validation.
|
||||
|
||||
**Verification:** Valid resources resolve; unknown/external names cannot initiate lookups or change backend.
|
||||
|
||||
**Scanner example before:**
|
||||
|
||||
~~~java
|
||||
Object value = context.lookup(requestName);
|
||||
~~~
|
||||
|
||||
**Fix template:**
|
||||
|
||||
~~~java
|
||||
Object value = context.lookup("java:comp/env/jdbc/Notes");
|
||||
~~~
|
||||
|
||||
Primary documentation: [reference 1](https://docs.oracle.com/en/java/javase/21/docs/api/java.naming/javax/naming/InitialContext.html).
|
||||
|
||||
<a id="java-error-leak"></a>
|
||||
|
||||
## JAVA-ERROR-LEAK. Stack traces and SQL in API errors
|
||||
|
||||
**Search:** manual review; no separate scanner rule.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'printStackTrace|getMessage\(|ResponseEntity|ExceptionHandler' .
|
||||
~~~
|
||||
|
||||
Compare private logs with client response bodies for authorization, SQL and parser failures.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
An exception exposes SQL, paths, connection strings or secret arguments to the client.
|
||||
|
||||
**Fix:** Return a standard encoded error with correlation ID; redact sensitive values before logging.
|
||||
|
||||
**Verification:** Diagnostics remain private; error responses contain no private data.
|
||||
|
||||
<a id="java-hostname-verify"></a>
|
||||
|
||||
## JAVA-HOSTNAME-VERIFY. Hostname verifier accepts every peer
|
||||
|
||||
**Search:** scanner rule JAVA-HOSTNAME-VERIFY. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain JAVA-HOSTNAME-VERIFY` for details. Regex: NoopHostnameVerifier/ALLOW_ALL_HOSTNAME_VERIFIER and setHostnameVerifier with a simple true-lambda. Review complex callbacks and TrustManager separately.
|
||||
|
||||
**Vulnerable example:** Certificate-chain validation without hostname validation does not authenticate the intended server.
|
||||
|
||||
~~~java
|
||||
builder.setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE);
|
||||
~~~
|
||||
|
||||
**Fix:** Restore the default verifier and trusted store instead of always-true callbacks.
|
||||
|
||||
~~~java
|
||||
builder.setSSLHostnameVerifier(new DefaultHostnameVerifier());
|
||||
~~~
|
||||
|
||||
**Verification:** Trusted CA certificates for another host fail; the intended endpoint works.
|
||||
|
||||
Primary documentation: [reference 1](https://hc.apache.org/httpcomponents-client-5.5.x/current/httpclient5/apidocs/org/apache/hc/client5/http/ssl/NoopHostnameVerifier.html).
|
||||
|
||||
<a id="java-spring-csrf"></a>
|
||||
|
||||
## JAVA-SPRING-CSRF. Spring Security CSRF disabled
|
||||
|
||||
**Search:** scanner rule JAVA-SPRING-CSRF. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain JAVA-SPRING-CSRF` for details. Regex: csrf().disable(), csrf(x -> x.disable()) and csrf(AbstractHttpConfigurer::disable). Review individual security chains and matchers.
|
||||
|
||||
**Vulnerable example:** Global disable can remove CSRF protection from cookie-authenticated operations.
|
||||
|
||||
~~~java
|
||||
http.csrf(csrf -> csrf.disable());
|
||||
~~~
|
||||
|
||||
**Fix:** Keep protection for browser routes; restrict exemptions to an explicit bearer/webhook contract with no cookie fallback.
|
||||
|
||||
~~~java
|
||||
http.csrf(Customizer.withDefaults());
|
||||
~~~
|
||||
|
||||
**Verification:** Valid CSRF requests work; cookie POST without a token fails; approved API scenarios work.
|
||||
|
||||
Primary documentation: [reference 1](https://docs.spring.io/spring-security/reference/servlet/exploits/csrf.html).
|
||||
|
||||
<a id="java-ldap-filter"></a>
|
||||
|
||||
## JAVA-LDAP-FILTER. JNDI search filter assembled by concatenation
|
||||
|
||||
**Search:** scanner rule JAVA-LDAP-FILTER. Use `--explain JAVA-LDAP-FILTER` for the exact detector contract. Regex with lexical exclusions: ctx/context/dirContext.search with a simple first argument and directly concatenated string filter. Does not resolve receiver types, prebuilt filters, wrappers or earlier escaping.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
~~~java
|
||||
ctx.search(base, "(uid=" + name + ")", controls);
|
||||
~~~
|
||||
|
||||
**Fix:** Use JNDI filter arguments with a fixed filter, and retain explicit search scope and authorization.
|
||||
|
||||
~~~java
|
||||
ctx.search(base, "(uid={0})", new Object[] { name }, controls);
|
||||
~~~
|
||||
|
||||
**Verification:** Filter metacharacters remain values; unauthorized entries stay inaccessible and valid searches work.
|
||||
|
||||
[Primary reference 1](https://docs.oracle.com/javase/jndi/tutorial/ldap/search/search.html)
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,869 @@
|
||||
# JavaScript / TypeScript: find, fix and verify
|
||||
|
||||
English | [Русский](javascript-RU.md)
|
||||
|
||||
[Catalog](README.md) · [Scanner](../offline-scanner.md) · [Patch verification](../patch-validation.md)
|
||||
|
||||
28 sections. Each follows **Search → Vulnerable example → Fix → Verification**.
|
||||
Run `rg` from a local service checkout; searches only read files. Derive the actor/owner from a verified session, not request data. Adapt examples to the actual API and contract.
|
||||
|
||||
## Contents
|
||||
|
||||
- [JS-SHELL — Shell API Node.js](#js-shell)
|
||||
- [JS-EVAL — Dynamic JavaScript execution](#js-eval)
|
||||
- [JS-SQL — Dynamic Node.js SQL](#js-sql)
|
||||
- [JS-NOSQL — Request body used as a MongoDB filter](#js-nosql)
|
||||
- [JS-MASS-ASSIGN — Mass assignment](#js-mass-assign)
|
||||
- [JS-PROTOTYPE — Deep merge of an untrusted object](#js-prototype)
|
||||
- [JS-TLS — Node.js TLS verification disabled](#js-tls)
|
||||
- [JS-HTML — HTML sink](#js-html)
|
||||
- [JS-TRUST-PROXY — Unrestricted trust in proxy headers](#js-trust-proxy)
|
||||
- [JS-CURL-ARGV — Node.js curl: review URL and options](#js-curl-argv)
|
||||
- [JS-SESSION-STATE — Sensitive session state assignment](#js-session-state)
|
||||
- [JS-VM — node:vm used as a security sandbox](#js-vm)
|
||||
- [JS-REGEX-DYNAMIC — Regex built from client text](#js-regex-dynamic)
|
||||
- [JS-TYPE-ASSERTION — TypeScript as does not validate JSON](#js-type-assertion)
|
||||
- [JS-AWAIT-AUTH — Missing await on authorization checks](#js-await-auth)
|
||||
- [JS-WEBSOCKET — Authorization only at the WebSocket handshake](#js-websocket)
|
||||
- [JS-GRAPHQL — Resolvers and batching bypass a common guard](#js-graphql)
|
||||
- [JS-SESSION-FIXATION — Session ID does not change at login](#js-session-fixation)
|
||||
- [JS-SSRF — fetch/axios redirects and repeated DNS resolution](#js-ssrf)
|
||||
- [JS-BUFFER-EXPOSURE — Uninitialized Buffer exposure](#js-buffer-exposure)
|
||||
- [JS-JWT-DECODE — JWT decoded without signature verification](#js-jwt-decode)
|
||||
- [JS-JWT-OPTIONS — Weakened JWT options](#js-jwt-options)
|
||||
- [JS-HTTP-PARSER — Lenient Node.js HTTP parser](#js-http-parser)
|
||||
- [JS-STATIC-DOTFILES — Static server allows dotfiles](#js-static-dotfiles)
|
||||
- [JS-QUERY-SHAPE — Parameters change type between middleware](#js-query-shape)
|
||||
- [JS-MIDDLEWARE-TRUST — Handlers assume middleware has run](#js-middleware-trust)
|
||||
- [JS-REDIRECT-INPUT — Request field passed directly to an Express-style redirect](#js-redirect-input)
|
||||
- [JS-LOG-CREDENTIALS — Credential-like value passed directly to console](#js-log-credentials)
|
||||
|
||||
<a id="js-shell"></a>
|
||||
|
||||
## JS-SHELL. Shell API Node.js
|
||||
|
||||
**Search:** scanner rule JS-SHELL. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain JS-SHELL` for details. Regex: bare exec/execSync, common child_process/cp receivers, shell:true/nonempty shell string and literal shell in spawn/execFile. Static ESM/CommonJS child_process imports support aliases and string bracket access; arbitrary object.exec is not a process call. Import hints are not scope/type/data-flow analysis: comments, shadowing and reassignment may match; review wrappers/dynamic imports.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
~~~javascript
|
||||
child_process.exec(command);
|
||||
~~~
|
||||
|
||||
**Fix:** Use a fixed executable and separate argv with validated options and bounded execution.
|
||||
|
||||
~~~javascript
|
||||
child_process.execFile('/usr/bin/file', ['--', filename], {timeout: 3000}, callback);
|
||||
~~~
|
||||
|
||||
**Verification:** Metacharacters stay data; dangerous options fail; normal commands work.
|
||||
|
||||
<details>
|
||||
<summary>Expanded example and limitations</summary>
|
||||
|
||||
```javascript
|
||||
// Vulnerable: a shell interprets the command string.
|
||||
exec("printf '%s' '" + req.body.text + "' | sha256sum", callback);
|
||||
```
|
||||
|
||||
**Patch for a content hash:**
|
||||
|
||||
<!-- example: js-sha256 -->
|
||||
|
||||
```javascript
|
||||
const { createHash } = require("node:crypto");
|
||||
|
||||
function digestText(text) {
|
||||
if (typeof text !== "string") throw new TypeError("string required");
|
||||
return createHash("sha256").update(text, "utf8").digest("hex");
|
||||
}
|
||||
```
|
||||
|
||||
For ESM use `import { createHash } from "node:crypto"`. Preserve encoding and the external result format. If an external program is genuinely needed, fix the executable and pass arguments separately; execFile does not automatically prevent dangerous program options.
|
||||
|
||||
**Check:** Known digest, empty string, Unicode, quotes/newlines and no child process. SHA-256 alone is unsuitable for password storage.
|
||||
|
||||
</details>
|
||||
|
||||
<a id="js-eval"></a>
|
||||
|
||||
## JS-EVAL. Dynamic JavaScript execution
|
||||
|
||||
**Search:** scanner rule JS-EVAL. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain JS-EVAL` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
~~~javascript
|
||||
const value = eval(input);
|
||||
~~~
|
||||
|
||||
**Fix:** Parse schema-validated data or a restricted DSL instead of evaluating JavaScript.
|
||||
|
||||
~~~javascript
|
||||
const value = JSON.parse(input); // validate schema
|
||||
~~~
|
||||
|
||||
**Verification:** Code-like input stays data; valid input works within limits.
|
||||
|
||||
<a id="js-sql"></a>
|
||||
|
||||
## JS-SQL. Dynamic Node.js SQL
|
||||
|
||||
**Search:** scanner rule JS-SQL. Use `--explain JS-SQL` for the exact detector contract. Legacy regex with comment/string exclusions: query/execute string construction or text/sql objects (receiver untyped). Bounded tokens also detect direct req/request.body/query/params property as SQL to a default/namespace imported pg Pool/Client or mysql/mysql2 createPool/createConnection binding. Named imports, acquired connections, SQL variables, tagged templates, wrappers and cross-file flows remain manual.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
~~~javascript
|
||||
db.query("SELECT id FROM notes WHERE name=" + name);
|
||||
~~~
|
||||
|
||||
**Fix:** Use driver-supported bind parameters and allowlist identifiers.
|
||||
|
||||
~~~javascript
|
||||
db.query("SELECT id FROM notes WHERE name=?", [name]);
|
||||
~~~
|
||||
|
||||
**Verification:** Quotes do not alter query structure; ownership restrictions remain.
|
||||
|
||||
<details>
|
||||
<summary>Expanded example and limitations</summary>
|
||||
|
||||
```javascript
|
||||
// Vulnerable: client input controls the query and ownership is unchecked.
|
||||
const result = await pool.query(`SELECT body FROM notes WHERE id = '${req.params.id}'`);
|
||||
```
|
||||
|
||||
**node-postgres (pg) patch for private notes:**
|
||||
|
||||
<!-- example: js-read-note -->
|
||||
|
||||
```javascript
|
||||
async function readPrivateNote(pool, currentUserId, noteId) {
|
||||
if (currentUserId == null) throw new Error("authentication required");
|
||||
const result = await pool.query(
|
||||
"SELECT body FROM notes WHERE id = $1 AND owner_id = $2",
|
||||
[noteId, currentUserId]
|
||||
);
|
||||
if (result.rows.length === 0) return null;
|
||||
return result.rows[0].body;
|
||||
}
|
||||
```
|
||||
|
||||
`null` means no accessible object; the route maps it to the API's normal response. Select column names/sorting direction from a fixed map, not request text. $1 placeholders are PostgreSQL-specific, not universal across JavaScript drivers.
|
||||
|
||||
**Check:** Owners can read, foreign records are absent, apostrophes remain data, wrong types do not change query meaning, and denied responses contain no foreign note body.
|
||||
|
||||
</details>
|
||||
|
||||
<a id="js-nosql"></a>
|
||||
|
||||
## JS-NOSQL. Request body used as a MongoDB filter
|
||||
|
||||
**Search:** scanner rule JS-NOSQL. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain JS-NOSQL` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
~~~javascript
|
||||
collection.findOne(req.body);
|
||||
~~~
|
||||
|
||||
**Fix:** Validate field types and build a server-owned filter with ownership constraints.
|
||||
|
||||
~~~javascript
|
||||
if (typeof req.body.name !== 'string') throw new Error('invalid');
|
||||
collection.findOne({name: req.body.name, ownerId: currentUser.id});
|
||||
~~~
|
||||
|
||||
**Verification:** Operator objects and unknown fields cannot widen the query; normal lookups work.
|
||||
|
||||
<details>
|
||||
<summary>Expanded example and limitations</summary>
|
||||
|
||||
```javascript
|
||||
// Vulnerable: title may be an operator object rather than a string.
|
||||
const note = await notes.findOne({ ownerId: currentUserId, title: req.body.title });
|
||||
```
|
||||
|
||||
**Patch:** Validate types and build the filter yourself. The example assumes ownerId already has the expected identifier type from trusted context.
|
||||
|
||||
<!-- example: js-title-filter -->
|
||||
|
||||
```javascript
|
||||
function privateTitleFilter(currentUserId, body) {
|
||||
if (currentUserId == null) throw new Error("authentication required");
|
||||
if (body === null || typeof body !== "object" || Array.isArray(body)) {
|
||||
throw new TypeError("object required");
|
||||
}
|
||||
if (!Object.prototype.hasOwnProperty.call(body, "title") || typeof body.title !== "string") {
|
||||
throw new TypeError("title must be a string");
|
||||
}
|
||||
return { ownerId: currentUserId, title: body.title };
|
||||
}
|
||||
// In the handler: await notes.findOne(privateTitleFilter(currentUserId, req.body));
|
||||
```
|
||||
|
||||
Do not fix this with String(req.body.title): objects become meaningless strings and the contract changes. Never spread the rest of req.body into the filter or mix it with server-side ownership predicates.
|
||||
|
||||
**Check:** Strings, Unicode and permitted empty titles work; objects, arrays and null titles fail **before database access**. A supplied ownerId never changes the filter.
|
||||
|
||||
</details>
|
||||
|
||||
<a id="js-mass-assign"></a>
|
||||
|
||||
## JS-MASS-ASSIGN. Mass assignment
|
||||
|
||||
**Search:** scanner rule JS-MASS-ASSIGN. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain JS-MASS-ASSIGN` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
~~~javascript
|
||||
Object.assign(user, req.body);
|
||||
~~~
|
||||
|
||||
**Fix:** Allowlist editable fields; derive owner, role and privileges on the server.
|
||||
|
||||
~~~javascript
|
||||
user.displayName = validateName(req.body.displayName);
|
||||
~~~
|
||||
|
||||
**Verification:** Additional/nested privilege fields fail or are ignored; normal edits work.
|
||||
|
||||
<details>
|
||||
<summary>Expanded example and limitations</summary>
|
||||
|
||||
```javascript
|
||||
// Vulnerable: clients can write ownerId/role and other administrative fields.
|
||||
Object.assign(note, req.body);
|
||||
```
|
||||
|
||||
**Patch for editing title and body:**
|
||||
|
||||
<!-- example: js-editable-note -->
|
||||
|
||||
```javascript
|
||||
function editableNoteFields(body) {
|
||||
if (body === null || typeof body !== "object" || Array.isArray(body)) {
|
||||
throw new TypeError("object required");
|
||||
}
|
||||
const result = {};
|
||||
for (const key of Object.keys(body)) {
|
||||
if (key !== "title" && key !== "body") throw new TypeError("unknown field");
|
||||
if (typeof body[key] !== "string") throw new TypeError("string required");
|
||||
result[key] = body[key];
|
||||
}
|
||||
return result;
|
||||
}
|
||||
// After authorization: update only editableNoteFields(req.body).
|
||||
```
|
||||
|
||||
A field allowlist does not authorize the record. Do not remove one key then deep-merge the rest: nested paths remain dangerous. Client JSON containing __proto__ must not enter arbitrary merging.
|
||||
|
||||
**Check:** Partial title updates and permitted empty bodies work; ownerId, role, unknown fields and nested objects fail; the original object is not mutated.
|
||||
|
||||
</details>
|
||||
|
||||
<a id="js-prototype"></a>
|
||||
|
||||
## JS-PROTOTYPE. Deep merge of an untrusted object
|
||||
|
||||
**Search:** scanner rule JS-PROTOTYPE. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain JS-PROTOTYPE` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
~~~javascript
|
||||
merge(settings, req.body);
|
||||
~~~
|
||||
|
||||
**Fix:** Copy only schema-approved fields and reject prototype-related keys at every level.
|
||||
|
||||
~~~javascript
|
||||
settings.theme = validateTheme(req.body.theme);
|
||||
~~~
|
||||
|
||||
**Verification:** Nested prototype keys cannot affect unrelated objects; supported settings apply.
|
||||
|
||||
<a id="js-tls"></a>
|
||||
|
||||
## JS-TLS. Node.js TLS verification disabled
|
||||
|
||||
**Search:** scanner rule JS-TLS. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain JS-TLS` for details. Regex: rejectUnauthorized:false/assignment only in JavaScript/config; NODE_TLS_REJECT_UNAUTHORIZED with exact 0 or paired quotes. Shell KEY=0 ends at whitespace, shell separators or end. Docker covers first ENV KEY=0 or whole-value ENV KEY 0, including paired quotes. 0.1, 0-disabled and quoted whitespace do not match; # or // suffix belongs to the shell/Docker value and semicolon belongs to Docker ENV. Comments/strings may match. Review Docker RUN/later ENV keys, concatenation, expansions, continuations, custom Agent and effective overrides.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
~~~javascript
|
||||
const options = {rejectUnauthorized: false};
|
||||
~~~
|
||||
|
||||
**Fix:** Enable peer/hostname checks and configure the trusted CA instead of disabling validation globally.
|
||||
|
||||
~~~javascript
|
||||
const options = {rejectUnauthorized: true};
|
||||
~~~
|
||||
|
||||
**Verification:** Valid certificates work; wrong CA/hostname and expiry fail.
|
||||
|
||||
The same risk can be configured outside JavaScript through process environment:
|
||||
|
||||
~~~dockerfile
|
||||
ENV NODE_TLS_REJECT_UNAUTHORIZED=0
|
||||
~~~
|
||||
|
||||
~~~bash
|
||||
NODE_TLS_REJECT_UNAUTHORIZED=0 node server.js
|
||||
~~~
|
||||
|
||||
Node.js disables normal validation only when the variable is exactly the string '0'. '0.1', '0-disabled' and '0 ' are not that flag; do not use these as fixes—remove the setting or explicitly restore validation. Merely comparing process.env.NODE_TLS_REJECT_UNAUTHORIZED === '0' disables nothing. [Node.js environment variable](https://nodejs.org/api/cli.html#node_tls_reject_unauthorizedvalue), [exact comparison in Node.js 22.14.0](https://github.com/nodejs/node/blob/v22.14.0/lib/internal/options.js).
|
||||
|
||||
For an internal CA retain the required trust through application CA settings or supported Node.js configuration. For example, with a preinstalled PEM file in the image:
|
||||
|
||||
~~~dockerfile
|
||||
ENV NODE_TLS_REJECT_UNAUTHORIZED=1
|
||||
ENV NODE_EXTRA_CA_CERTS=/etc/service-ca.pem
|
||||
~~~
|
||||
|
||||
Check the file's path, availability and CA contents. CA trust does not replace hostname validation. Per-client ca settings and custom Agents need separate review. Test the actual Node.js version against the normal internal server and reject wrong CAs, wrong names and expired certificates.
|
||||
|
||||
Docker supports ENV KEY=value and legacy ENV KEY value. In the latter, the entire remainder is the value: ENV NODE_TLS_REJECT_UNAUTHORIZED 0 extra is not exactly '0'. Runtime configuration can override image ENV. [Dockerfile ENV](https://docs.docker.com/reference/dockerfile/#env).
|
||||
|
||||
In Dockerfiles the scanner checks only the first ENV key. Manually search RUN NODE_TLS_REJECT_UNAUTHORIZED=0 node server.js and settings after another first key. Shell/Dockerfile token boundaries differ: 0#suffix and 0//suffix belong to the value; 0; separates shell commands but remains the value in ENV KEY=0;. Quotes around exact 0 are supported, including legacy ENV KEY "0".
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'NODE_TLS_REJECT_UNAUTHORIZED|NODE_EXTRA_CA_CERTS|rejectUnauthorized|https[.]Agent|tls[.]connect|env_file|environment:' .
|
||||
~~~
|
||||
|
||||
Connect Dockerfiles/build stages, Compose/manifests, startup shell and code to the environment of the actual running process. Review later assignments and per-request parameters. Regex does not evaluate substitutions, startup order or effective environment and is not a complete shell/Dockerfile/JavaScript parser. Comments/examples can signal and need context review.
|
||||
|
||||
<a id="js-html"></a>
|
||||
|
||||
## JS-HTML. HTML sink
|
||||
|
||||
**Search:** scanner rule JS-HTML. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain JS-HTML` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
~~~javascript
|
||||
element.innerHTML = message;
|
||||
~~~
|
||||
|
||||
**Fix:** Use textContent for text or a reviewed context-appropriate sanitizer for supported rich HTML.
|
||||
|
||||
~~~javascript
|
||||
element.textContent = message;
|
||||
~~~
|
||||
|
||||
**Verification:** User markup cannot execute; intended presentation remains usable.
|
||||
|
||||
<a id="js-trust-proxy"></a>
|
||||
|
||||
## JS-TRUST-PROXY. Unrestricted trust in proxy headers
|
||||
|
||||
**Search:** scanner rule JS-TRUST-PROXY. Use `--explain JS-TRUST-PROXY` for the exact detector contract. Regex with comment/string exclusions: .set('trust proxy', true). Receiver untyped; true may be valid behind proxies that overwrite forwarded headers. No effective topology or proxy-hop verification; inspect all direct entrypoints and the immediate peer.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
~~~javascript
|
||||
app.set('trust proxy', true);
|
||||
~~~
|
||||
|
||||
**Fix:** Trust actual immediate proxies, not client X-Forwarded-* as authentication; do not change organizer networking.
|
||||
|
||||
~~~javascript
|
||||
app.set('trust proxy', isKnownProxy); // implement topology-specific peer validation
|
||||
~~~
|
||||
|
||||
**Verification:** Spoofed direct headers grant no trusted identity/IP/scheme; proxy works.
|
||||
|
||||
<a id="js-curl-argv"></a>
|
||||
|
||||
## JS-CURL-ARGV. Node.js curl: review URL and options
|
||||
|
||||
**Search:** scanner rule JS-CURL-ARGV. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain JS-CURL-ARGV` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
~~~javascript
|
||||
spawn('/usr/bin/curl', [url, '-o', filename]);
|
||||
~~~
|
||||
|
||||
**Fix:** Separate argv does not prevent option injection. Prefer bounded HTTP APIs; otherwise fix curl options/protocols, use -- before validated URL and choose server-side output.
|
||||
|
||||
~~~javascript
|
||||
downloadValidatedHttpResource(url, destination); // bounded HTTP client, checked redirects/DNS and server-chosen output
|
||||
~~~
|
||||
|
||||
**Verification:** Leading-dash URLs, forbidden schemes/redirects and output paths fail; normal downloads work.
|
||||
|
||||
**A/D variant:** Separate argv do not protect against program options. **ECSC / duogesto, author write-up.** curl interpreted client text as an option. **Patch:** A constrained HTTP client or fixed options, --, permitted schemes/redirects and server-selected output. **Test:** Leading dashes, other protocols, foreign paths and normal URLs. **Search:** JS-CURL-ARGV; shell:false is insufficient.
|
||||
|
||||
[source/write-up 1](https://github.com/ECSC2024/ECSC2024-CTF-AD/blob/2a92e17384ad228072a84fb076a35066fe2ffeff/sources/duogesto/README.md); [source/write-up 2](https://github.com/ECSC2024/ECSC2024-CTF-AD/blob/2a92e17384ad228072a84fb076a35066fe2ffeff/sources/duogesto/backend/app.mjs).
|
||||
|
||||
<a id="js-session-state"></a>
|
||||
|
||||
## JS-SESSION-STATE. Sensitive session state assignment
|
||||
|
||||
**Search:** scanner rule JS-SESSION-STATE. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain JS-SESSION-STATE` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
~~~javascript
|
||||
const user = req.body;
|
||||
req.session.user = user;
|
||||
~~~
|
||||
|
||||
**Fix:** Build session DTOs from persisted validated records; bind related state server-side and reject client privilege fields.
|
||||
|
||||
~~~javascript
|
||||
req.session.user = {id: savedUser.id, friends: savedUser.friends}; // server-validated fields only
|
||||
~~~
|
||||
|
||||
**Verification:** Extra role/friends fields or endpoint reordering cannot change access; correct assignments may still match.
|
||||
|
||||
**A/D variant:** Unrelated endpoints overwrite operation context. **ECSC / duogesto, author write-up.** Another request changed the current task's author; completion combined an old answer with the new author. **Patch:** Store challenge ID, author and state together and verify their binding at completion. **Test:** Reordered requests and multiple tabs. **Search:** JS-SESSION-STATE; review semantics manually.
|
||||
|
||||
[source/write-up 1](https://github.com/ECSC2024/ECSC2024-CTF-AD/blob/2a92e17384ad228072a84fb076a35066fe2ffeff/sources/duogesto/README.md); [source/write-up 2](https://github.com/ECSC2024/ECSC2024-CTF-AD/blob/2a92e17384ad228072a84fb076a35066fe2ffeff/sources/duogesto/backend/app.mjs).
|
||||
|
||||
**A/D variant:** Safe database object, original request body in the session. **ECSC / duogesto, author write-up.** Session initialization retained client-supplied friends. **Patch:** Explicit session DTO from the verified persisted user; do not copy passwords or extra fields. **Test:** Registration with role/friends grants no privileges; ordinary login works. **Search:** JS-SESSION-STATE; account for the lack of taint analysis.
|
||||
|
||||
[source/write-up 1](https://github.com/ECSC2024/ECSC2024-CTF-AD/blob/2a92e17384ad228072a84fb076a35066fe2ffeff/sources/duogesto/README.md); [source/write-up 2](https://github.com/ECSC2024/ECSC2024-CTF-AD/blob/2a92e17384ad228072a84fb076a35066fe2ffeff/sources/duogesto/backend/app.mjs).
|
||||
|
||||
<a id="js-vm"></a>
|
||||
|
||||
## JS-VM. node:vm used as a security sandbox
|
||||
|
||||
**Search:** scanner rule JS-VM. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain JS-VM` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
~~~javascript
|
||||
vm.runInNewContext(userCode, context);
|
||||
~~~
|
||||
|
||||
**Fix:** node:vm is not a security boundary for untrusted code. Use a restricted grammar or a separately designed execution isolation system.
|
||||
|
||||
~~~javascript
|
||||
evaluateAllowedExpression(parsedInput); // implement a restricted grammar
|
||||
~~~
|
||||
|
||||
**Verification:** Disallowed syntax fails; supported expressions work under time/memory limits.
|
||||
|
||||
**Reference:** [primary source](https://nodejs.org/api/vm.html).
|
||||
|
||||
<a id="js-regex-dynamic"></a>
|
||||
|
||||
## JS-REGEX-DYNAMIC. Regex built from client text
|
||||
|
||||
**Search:** scanner rule JS-REGEX-DYNAMIC. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain JS-REGEX-DYNAMIC` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
~~~javascript
|
||||
const re = new RegExp(input);
|
||||
~~~
|
||||
|
||||
**Fix:** Use includes for literal search; bound regex grammar/complexity and input when regex is a feature. A Promise timeout cannot interrupt synchronous regex execution.
|
||||
|
||||
~~~javascript
|
||||
const found = text.includes(input);
|
||||
~~~
|
||||
|
||||
**Verification:** Long near-matches cannot block the event loop; Unicode/case semantics remain compatible.
|
||||
|
||||
**Reference:** [primary source](https://nodejs.org/en/learn/asynchronous-work/dont-block-the-event-loop).
|
||||
|
||||
<a id="js-type-assertion"></a>
|
||||
|
||||
## JS-TYPE-ASSERTION. TypeScript as does not validate JSON
|
||||
|
||||
**Search:** manual review; no separate scanner rule.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'as [A-Z]|JSON.parse|req.body|parseInt|Number\(' .
|
||||
~~~
|
||||
|
||||
Find unknown-to-type transitions; verify a real runtime schema before field access.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
`req.body as User` hides missing validation; parseInt accepts a numeric prefix.
|
||||
|
||||
**Fix:** A schema validator or explicit type/range/field checks, strict whole-string number parsing and separate server-derived IDs.
|
||||
|
||||
**Verification:** Arrays/null/objects replacing strings, numeric suffixes, NaN/Infinity and unsafe integers fail.
|
||||
|
||||
<a id="js-await-auth"></a>
|
||||
|
||||
## JS-AWAIT-AUTH. Missing await on authorization checks
|
||||
|
||||
**Search:** manual review; no separate scanner rule.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'authorize|isAllowed|verifyToken|Promise|async' .
|
||||
~~~
|
||||
|
||||
Check the return type of every authorization helper used in an if; Promise objects are truthy regardless of eventual result.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
`if (isAllowed(user, note))` with async isAllowed permits execution before the decision.
|
||||
|
||||
**Fix:** Await the check and explicitly deny exceptions; do not continue response handling after rejected Promises.
|
||||
|
||||
**Verification:** Async true/false/error and delay cases; private data is never read before verification completes.
|
||||
|
||||
<a id="js-websocket"></a>
|
||||
|
||||
## JS-WEBSOCKET. Authorization only at the WebSocket handshake
|
||||
|
||||
**Search:** manual review; no separate scanner rule.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'WebSocket|upgrade|on\(.message|subscribe|room|channel' .
|
||||
~~~
|
||||
|
||||
Compare handshake, every message/action, room joins and broadcasts; validate Origin separately from cookies.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
After login the client selects a foreign room or retains access after its privileges change.
|
||||
|
||||
**Fix:** Authenticate/authorize every operation and subscription, enforce session lifetime and permitted browser Origins, and bound messages.
|
||||
|
||||
**Verification:** Two users, role revocation, reconnect, foreign rooms and legitimate broadcast.
|
||||
|
||||
**Reference:** [primary source](https://cheatsheetseries.owasp.org/cheatsheets/WebSocket_Security_Cheat_Sheet.html).
|
||||
|
||||
<a id="js-graphql"></a>
|
||||
|
||||
## JS-GRAPHQL. Resolvers and batching bypass a common guard
|
||||
|
||||
**Search:** manual review; no separate scanner rule.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'resolver|resolve|GraphQL|DataLoader|context|mutation' .
|
||||
~~~
|
||||
|
||||
Inspect nested resolvers, node(id), loaders and mutations; DataLoader caches must be request/user-scoped.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
The root query is protected, but a nested resolver loads by ID without owner checks, or a shared loader returns another user's cached result.
|
||||
|
||||
**Fix:** Resource authorization in resolvers/services, request-scoped loaders and contractual depth/cost/batch limits.
|
||||
|
||||
**Verification:** Foreign nodes, nested paths, aliases/batching and normal pagination.
|
||||
|
||||
**Reference:** [primary source](https://cheatsheetseries.owasp.org/cheatsheets/GraphQL_Cheat_Sheet.html).
|
||||
|
||||
<a id="js-session-fixation"></a>
|
||||
|
||||
## JS-SESSION-FIXATION. Session ID does not change at login
|
||||
|
||||
**Search:** manual review; no separate scanner rule.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'session|regenerate|login|logout|sessionID' .
|
||||
~~~
|
||||
|
||||
Compare identifiers before/after login and the old ID's association with the new principal.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
A previously known anonymous session becomes authenticated.
|
||||
|
||||
**Fix:** Supported session-ID regeneration at privilege transitions, transferring only allowed state; logout invalidates server state.
|
||||
|
||||
**Verification:** Old IDs cannot authorize, shopping cart/permitted state survives and concurrent login does not lose sessions.
|
||||
|
||||
<a id="js-ssrf"></a>
|
||||
|
||||
## JS-SSRF. fetch/axios redirects and repeated DNS resolution
|
||||
|
||||
**Search:** manual review; no separate scanner rule.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'fetch\(|axios|undici|http.request|https.request' .
|
||||
~~~
|
||||
|
||||
Trace URLs to actual connections and every redirect; JS-CURL-ARGV covers only curl calls.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
The initial hostname is checked but connection/redirect behavior selects another address or scheme.
|
||||
|
||||
**Fix:** Server-defined destinations or policy covering normalized URLs, allowed IPs/ports and actual connections; bound response size/time.
|
||||
|
||||
**Verification:** Mock DNS/redirects, contractually allowed internal addresses, timeouts and oversized bodies.
|
||||
|
||||
**Reference:** [primary source](https://cheatsheetseries.owasp.org/cheatsheets/Server_Side_Request_Forgery_Prevention_Cheat_Sheet.html).
|
||||
|
||||
<a id="js-buffer-exposure"></a>
|
||||
|
||||
## JS-BUFFER-EXPOSURE. Uninitialized Buffer exposure
|
||||
|
||||
**Search:** scanner rule JS-BUFFER-EXPOSURE. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain JS-BUFFER-EXPOSURE` for details. Regex: Buffer.allocUnsafe/allocUnsafeSlow. Full initialization before disclosure may remove risk on review; inspect legacy new Buffer and incorrect lengths separately.
|
||||
|
||||
Additional manual search for forms outside automatic coverage:
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'allocUnsafe|allocUnsafeSlow|write\(|subarray|res.end|socket.write' .
|
||||
~~~
|
||||
|
||||
Compare allocation capacity, bytes actually initialized and transmitted length.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
`Buffer.allocUnsafe(n)` is transmitted whole after only partial initialization.
|
||||
|
||||
**Fix:** Initialize memory, emit only the written range and validate size/read results.
|
||||
|
||||
**Verification:** Short read, EOF and errors disclose no tail bytes; valid binary responses work.
|
||||
|
||||
**Reference:** [primary source](https://nodejs.org/api/buffer.html).
|
||||
|
||||
**Scanner example before:**
|
||||
|
||||
~~~javascript
|
||||
const out = Buffer.allocUnsafe(size);
|
||||
const n = await readInto(out);
|
||||
res.end(out);
|
||||
~~~
|
||||
|
||||
**Fix template:**
|
||||
|
||||
~~~javascript
|
||||
const out = Buffer.alloc(size);
|
||||
const n = await readInto(out);
|
||||
res.end(out.subarray(0, n));
|
||||
~~~
|
||||
|
||||
Primary documentation: [reference 1](https://nodejs.org/api/buffer.html#what-makes-bufferallocunsafe-and-bufferallocunsafeslow-unsafe).
|
||||
|
||||
<a id="js-jwt-decode"></a>
|
||||
|
||||
## JS-JWT-DECODE. JWT decoded without signature verification
|
||||
|
||||
**Search:** scanner rule JS-JWT-DECODE. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain JS-JWT-DECODE` for details. Regex: common jwt.decode/decodeJwt/jwtDecode and static ESM/CommonJS aliases for jsonwebtoken.decode/jose.decodeJwt. No scope/reassignment, re-export, dynamic import or claims-use analysis. Diagnostic decoding may be legitimate.
|
||||
|
||||
**Vulnerable example:** decode/decodeJwt extracts data without verification; it cannot establish an authenticated identity.
|
||||
|
||||
~~~javascript
|
||||
const user = jwt.decode(token);
|
||||
loadNotes(user.sub);
|
||||
~~~
|
||||
|
||||
**Fix:** Verify signature and claims before access; await asynchronous verification and reject errors before proceeding.
|
||||
|
||||
~~~javascript
|
||||
const claims = jwt.verify(token, key, { algorithms: ['RS256'], issuer: 'auth', audience: 'notes' });
|
||||
loadNotes(claims.sub);
|
||||
~~~
|
||||
|
||||
**Verification:** Modified payload, invalid signature and wrong issuer/audience grant no access.
|
||||
|
||||
Primary documentation: [reference 1](https://github.com/auth0/node-jsonwebtoken#jwtdecodetoken--options).
|
||||
|
||||
<a id="js-jwt-options"></a>
|
||||
|
||||
## JS-JWT-OPTIONS. Weakened JWT options
|
||||
|
||||
**Search:** scanner rule JS-JWT-OPTIONS. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain JS-JWT-OPTIONS` for details. Regex: ignoreExpiration/ignoreNotBefore/allowInvalidAsymmetricKeyTypes=true. Options may be separate from verify; inspect actual use.
|
||||
|
||||
**Vulnerable example:** Ignoring time constraints or accepting incompatible keys weakens token verification.
|
||||
|
||||
~~~javascript
|
||||
jwt.verify(token, key, { ignoreExpiration: true, ignoreNotBefore: true });
|
||||
~~~
|
||||
|
||||
**Fix:** Remove verification bypasses and fix algorithm/key/claims policy; require exp separately where needed.
|
||||
|
||||
~~~javascript
|
||||
jwt.verify(token, key, { algorithms: ['RS256'], issuer: 'auth', audience: 'notes' });
|
||||
~~~
|
||||
|
||||
**Verification:** Expired/premature tokens and wrong algorithms/key types fail.
|
||||
|
||||
Primary documentation: [reference 1](https://github.com/auth0/node-jsonwebtoken#jwtverifytoken-secretorpublickey-options-callback).
|
||||
|
||||
<a id="js-http-parser"></a>
|
||||
|
||||
## JS-HTTP-PARSER. Lenient Node.js HTTP parser
|
||||
|
||||
**Search:** scanner rule JS-HTTP-PARSER. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain JS-HTTP-PARSER` for details. Regex: insecureHTTPParser:true or --insecure-http-parser. This alone does not prove request smuggling.
|
||||
|
||||
**Vulnerable example:** Different proxy/backend parsing rules create ambiguous request boundaries.
|
||||
|
||||
~~~javascript
|
||||
http.createServer({ insecureHTTPParser: true }, handler);
|
||||
~~~
|
||||
|
||||
**Fix:** Use strict parsers on every hop and align framing/normalization; check NODE_OPTIONS and CLI flags.
|
||||
|
||||
~~~javascript
|
||||
http.createServer({ insecureHTTPParser: false }, handler);
|
||||
~~~
|
||||
|
||||
**Verification:** Conflicting framing fails at the first hop; valid keep-alive requests stay separate.
|
||||
|
||||
Primary documentation: [reference 1](https://nodejs.org/api/http.html#httpcreateserveroptions-requestlistener).
|
||||
|
||||
<a id="js-static-dotfiles"></a>
|
||||
|
||||
## JS-STATIC-DOTFILES. Static server allows dotfiles
|
||||
|
||||
**Search:** scanner rule JS-STATIC-DOTFILES. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain JS-STATIC-DOTFILES` for details. Regex: dotfiles:allow. Does not check actual root, middleware order, non-dot backups or symlinks.
|
||||
|
||||
**Vulnerable example:** A static root allowing dotfiles can expose configuration, history and keys.
|
||||
|
||||
~~~javascript
|
||||
app.use(express.static(root, { dotfiles: 'allow' }));
|
||||
~~~
|
||||
|
||||
**Fix:** Use a dedicated public root and deny dotfiles; allow required .well-known resources narrowly without secrets.
|
||||
|
||||
~~~javascript
|
||||
app.use(express.static(publicDir, { dotfiles: 'deny' }));
|
||||
~~~
|
||||
|
||||
**Verification:** Assets work; dotfiles, backups and files outside the root are unavailable.
|
||||
|
||||
Primary documentation: [reference 1](https://expressjs.com/en/4x/api.html#express.static).
|
||||
|
||||
<a id="js-query-shape"></a>
|
||||
|
||||
## JS-QUERY-SHAPE. Parameters change type between middleware
|
||||
|
||||
**Search:** manual review; no separate scanner rule.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'req\.(query|body|params)|URLSearchParams|querystring|qs\.|Object\.assign|\.\.\.' .
|
||||
~~~
|
||||
|
||||
Review repeated query keys, scalar/array/object forms, parser settings and params/query/body merge order. Compare the checked field with the value actually passed to database/authentication code.
|
||||
|
||||
**Vulnerable example:** A validator checks one string, the next layer selects the last value/object, or body overwrites an already verified params owner.
|
||||
|
||||
**Fix:** Parse once into a precisely typed DTO; reject duplicates/unexpected structures according to contract. Never merge client fields into server-established principal context.
|
||||
|
||||
**Verification:** Duplicates, bracket notation, nested objects and body/query conflicts cannot change owner/filter; ordinary requests retain their results.
|
||||
|
||||
Reference: [primary documentation](https://expressjs.com/en/4x/api.html#req.query). The explanation and adaptation recipe were written for this catalog.
|
||||
|
||||
<a id="js-middleware-trust"></a>
|
||||
|
||||
## JS-MIDDLEWARE-TRUST. Handlers assume middleware has run
|
||||
|
||||
**Search:** manual review; no separate scanner rule. This ID identifies a catalog section. The scanner does not establish Next.js version, routing topology or authorization on every execution path.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!node_modules/**' -g '!.git/**' -g 'middleware.*' -g 'proxy.*' -g 'next.config.*' -g '*.conf' -e 'matcher|NextResponse\.(next|rewrite|redirect)|x-middleware-subrequest|proxy_pass|proxy_set_header|standalone' .
|
||||
rg -n --hidden -g '!node_modules/**' -g '!.git/**' -e 'next/server|export.*(GET|POST|PUT|PATCH|DELETE)|use server|verifySession|authorize|"next"|next@' .
|
||||
~~~
|
||||
|
||||
Use the first search to map external entry → proxy/adapter → Next.js → matcher/rewrite → handler. Use the second to trace actual session/permission validation before reads/writes; inspect helper implementations and lockfiles, not only function names or package.json ranges. Test direct backend access bypassing the proxy. Locale/public-page middleware and handlers with independent authorization are similar-looking safe cases.
|
||||
|
||||
**Vulnerable example:** In CVE-2025-29927, an external x-middleware-subrequest reached Next.js recursion prevention and bypassed middleware. Handlers relying exclusively on middleware lost authorization. The postmortem confirms self-hosted next start and output: 'standalone' were affected; static export does not execute middleware. Vercel and the examined Netlify/Cloudflare Workers adapters were unaffected because of different routing. These are boundaries of that incident, not a guarantee for every platform configuration. [Developer postmortem](https://vercel.com/blog/postmortem-on-next-js-middleware-bypass).
|
||||
|
||||
Minimal vulnerable arrangement; verifySession and data functions are project helpers:
|
||||
|
||||
~~~javascript
|
||||
// middleware.js
|
||||
import { NextResponse } from 'next/server';
|
||||
import { verifySession } from './lib/auth.js';
|
||||
export async function middleware(req) {
|
||||
if (!(await verifySession(req))) {
|
||||
return NextResponse.redirect(new URL('/login', req.url));
|
||||
}
|
||||
return NextResponse.next();
|
||||
}
|
||||
export const config = { matcher: ['/api/notes/:path*'] };
|
||||
~~~
|
||||
|
||||
~~~javascript
|
||||
// app/api/notes/route.js
|
||||
import { listNotes } from '../../../lib/data.js';
|
||||
export async function GET(req) {
|
||||
return Response.json(await listNotes());
|
||||
}
|
||||
~~~
|
||||
|
||||
Historical advisory ranges: >=11.1.4 <12.3.5, >=13.0.0 <13.5.9, >=14.0.0 <14.2.25, >=15.0.0 <15.2.3. Versions 12.3.5, 13.5.9, 14.2.25 and 15.2.3 fix this specific CVE; the advisory lists no fixed 11.x release. [GHSA-f82v-jwr5-mffw](https://github.com/vercel/next.js/security/advisories/GHSA-f82v-jwr5-mffw).
|
||||
|
||||
**Fix:** Use a supported branch with current security updates. The historical minimum versions above are not present-day installation recommendations: a subsequent internal-header leakage fix required newer releases. [GHSA-223j-4rm8-mrmf](https://github.com/vercel/next.js/security/advisories/GHSA-223j-4rm8-mrmf), [project advisories](https://github.com/vercel/next.js/security/advisories). The upstream patch validates the internal header's origin; its regression test preserves the expected redirect when the header arrives externally. [Fix 52a078d and test](https://github.com/vercel/next.js/commit/52a078da3884efe6501613c7834a3d02a91676d2).
|
||||
|
||||
Validate sessions and operation permissions in handlers/data access, including Server Actions; middleware may retain early redirects for user experience. verifySession below must verify the session, while listNotesForUser must scope queries to that verified actor, not a request value. [Next.js authorization and DAL](https://nextjs.org/docs/app/guides/authentication).
|
||||
|
||||
~~~javascript
|
||||
// app/api/notes/route.js
|
||||
import { verifySession } from '../../../lib/auth.js';
|
||||
import { listNotesForUser } from '../../../lib/data.js';
|
||||
export async function GET(req) {
|
||||
const session = await verifySession(req);
|
||||
if (!session) return new Response(null, { status: 401 });
|
||||
return Response.json(await listNotesForUser(session.userId));
|
||||
}
|
||||
~~~
|
||||
|
||||
Unified owner/tenant policy and alternative endpoints are covered by [CFG-OBJECT-POLICY](configuration.md#cfg-object-policy).
|
||||
|
||||
A temporary mitigation at the **external** nginx boundary removes client-supplied headers before forwarding to Next.js. Add it to each relevant proxy location while preserving other required headers/settings:
|
||||
|
||||
~~~nginx
|
||||
proxy_set_header x-middleware-subrequest "";
|
||||
~~~
|
||||
|
||||
An empty value omits the header from upstream requests. proxy_set_header directives inherit only when none are defined at the current level: inspect every location and ingress and restrict the backend to trusted entrypoints. This is not a complete proxy configuration. [nginx proxy_set_header](https://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_set_header). Do not indiscriminately remove internal headers on every inter-service hop: legitimate middleware fetch uses them to prevent recursion.
|
||||
|
||||
**Verification:** In an authorized environment, repeat tests with and without the externally supplied header. Include:
|
||||
|
||||
| Path | Expected result |
|
||||
|---|---|
|
||||
| Page, read/write API, rewrite and alternative URL | Anonymous callers receive no private data; owner operations work; foreign data remains inaccessible. |
|
||||
| Server Action and direct handler call | Authorization runs independently of the page and middleware. |
|
||||
| Every external ingress and direct backend | Externally supplied internal headers never disable protection; unauthorized backend entry is unavailable. |
|
||||
| Internal middleware fetch | Expected responses/redirects work without recursive loops. |
|
||||
|
||||
Recheck cookies, sessions, response contracts and load after moving authorization: extra storage access and incompatible helpers can break normal operations. This catalog review checked sources and inert scanner examples; it did not execute Next.js or application HTTP tests. A clean scanner report does not prove this manual issue fixed.
|
||||
|
||||
<a id="js-redirect-input"></a>
|
||||
|
||||
## JS-REDIRECT-INPUT. Request field passed directly to an Express-style redirect
|
||||
|
||||
**Search:** scanner rule JS-REDIRECT-INPUT. Use `--explain JS-REDIRECT-INPUT` for the exact detector contract. Regex with lexical comment/string exclusions: res/response.redirect with direct req/request.query/body/params property, optionally following a literal status code. Not receiver typing or data-flow analysis; computed keys, aliases and upstream validation need review.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
~~~javascript
|
||||
res.redirect(req.query.next);
|
||||
~~~
|
||||
|
||||
**Fix:** Resolve redirects using a server-owned route table or an explicit normalized URL policy.
|
||||
|
||||
~~~javascript
|
||||
res.redirect('/account');
|
||||
~~~
|
||||
|
||||
**Verification:** External and scheme-relative destinations fail; approved navigation still works.
|
||||
|
||||
[Primary reference 1](https://expressjs.com/en/4x/api.html#res.redirect)
|
||||
|
||||
<a id="js-log-credentials"></a>
|
||||
|
||||
## JS-LOG-CREDENTIALS. Credential-like value passed directly to console
|
||||
|
||||
**Search:** scanner rule JS-LOG-CREDENTIALS. Use `--explain JS-LOG-CREDENTIALS` for details. Bounded JS tokens: console log/info/warn/error/debug/trace with direct sensitive names/properties, inline object/array values or concatenation. Observed console shadows/reassignments suppress hints file-wide. Templates, helper calls, custom loggers, dynamic keys and cross-file flows remain manual; absence of a signal does not verify redaction.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
~~~javascript
|
||||
console.warn(req.headers.authorization);
|
||||
~~~
|
||||
|
||||
**Fix:** Log stable event categories and approved identifiers, not credential values. Inspect failed-login and exception paths; implement and test any redaction helper independently.
|
||||
|
||||
~~~javascript
|
||||
console.warn('authentication failed');
|
||||
~~~
|
||||
|
||||
**Verification:** Synthetic canary credentials never appear in stdout, logs, exported evidence or screen broadcasts; failure categories remain useful.
|
||||
|
||||
[Primary reference](https://nodejs.org/api/console.html)
|
||||
@@ -0,0 +1,790 @@
|
||||
<a id="php-find-fix-and-verify"></a>
|
||||
|
||||
# PHP: поиск и исправление
|
||||
|
||||
[English](php.md) | Русский
|
||||
|
||||
[Вся база](README-RU.md) · [Сканер](../offline-scanner-RU.md) · [Проверка патча](../patch-validation-RU.md)
|
||||
|
||||
23 разделов. Формат: **Поиск → Уязвимый вариант → Исправление → Проверка**.
|
||||
Команды `rg` выполняются в корне локальной копии сервиса и только читают файлы. Субъект/владелец определяется по проверенной сессии, а не данным запроса. Примеры нужно адаптировать к реальным API и контракту.
|
||||
|
||||
Автоматические находки — ограниченные синтаксические сигналы для проверки. AST-анализ не разрешает типы и не отслеживает данные между функциями; regex не заменяет парсер языка. Комментарии, строки и одноимённые пользовательские API могут давать совпадения. Проверьте фактическое исполнение, входные данные, авторизацию и границы доверия.
|
||||
|
||||
<a id="contents"></a>
|
||||
|
||||
## Содержание
|
||||
|
||||
- [PHP-SQL — Динамический SQL PHP](#php-sql)
|
||||
- [PHP-OBJECT — unserialize внешних данных](#php-object)
|
||||
- [PHP-SHELL — Исполнение текста PHP/команды](#php-shell)
|
||||
- [PHP-INCLUDE — Клиентский путь include](#php-include)
|
||||
- [PHP-PREFIX-MAC — Хеш конкатенации вместо MAC](#php-prefix-mac)
|
||||
- [PHP-PARSE-STR — Нормализация ключей parse_str](#php-parse-str)
|
||||
- [PHP-LOOSE-COMPARE — Нестрогое сравнение токена или подписи](#php-loose-compare)
|
||||
- [PHP-UPLOAD — Перенос загруженного файла](#php-upload)
|
||||
- [PHP-DISPLAY-ERRORS — PHP показывает ошибки клиенту](#php-display-errors)
|
||||
- [PHP-XSS — HTML/атрибут/JS получают сырой текст](#php-xss)
|
||||
- [PHP-SESSION — PHP session: fixation, strict mode, старое состояние](#php-session)
|
||||
- [PHP-WRAPPERS — Файловый API принимает URL/wrapper](#php-wrappers)
|
||||
- [PHP-EXTRACT — extract и variable variables подменяют контекст](#php-extract)
|
||||
- [PHP-SERIALIZE-MAGIC — Magic methods и доверие данным из БД](#php-serialize-magic)
|
||||
- [PHP-CSRF — Cookie авторизует изменяющий запрос без CSRF](#php-csrf)
|
||||
- [PHP-REGEX-ERROR — Ошибка preg_match трактуется как разрешение](#php-regex-error)
|
||||
- [PHP-XML-FLAGS — XML разрешает подстановку сущностей и DTD](#php-xml-flags)
|
||||
- [PHP-TEMPLATE — Шаблон создаётся из динамического текста](#php-template)
|
||||
- [PHP-CURL-TLS — cURL не проверяет сертификат или имя](#php-curl-tls)
|
||||
- [PHP-URL-INCLUDE — Разрешён include удалённого ресурса](#php-url-include)
|
||||
- [PHP-SESSION-CONFIG — Ослабленные настройки PHP-сессии](#php-session-config)
|
||||
- [PHP-MASS-ASSIGN — Ключи массива выбирают колонки и права](#php-mass-assign)
|
||||
- [PHP-LDAP-FILTER — LDAP-фильтр склеивается с PHP-переменной](#php-ldap-filter)
|
||||
|
||||
<a id="php-sql"></a>
|
||||
|
||||
<a id="php-sql-dynamic-php-sql"></a>
|
||||
|
||||
## PHP-SQL. Динамический SQL PHP
|
||||
|
||||
**Поиск:** скрипт, правило PHP-SQL. Запуск: python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain PHP-SQL. Regex: query/exec/prepare со сборкой строки, double-quoted интерполяция, mysqli_query/pg_query с обычным аргументом соединения. Escaping, другие формы интерполяции и SQL из переменной полноценно не разбираются.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
~~~php
|
||||
$db->query("SELECT id FROM notes WHERE name=" . $name);
|
||||
~~~
|
||||
|
||||
**Исправление:** Prepared statements и связанные значения в API выбранного драйвера, например PDO prepare/execute; идентификаторы — из разрешённого набора, значения не подставлять вручную.
|
||||
|
||||
~~~php
|
||||
$stmt = $db->prepare("SELECT id FROM notes WHERE name = ?");
|
||||
$stmt->execute([$name]);
|
||||
~~~
|
||||
|
||||
**Проверка:** Кавычки остаются данными; ограничения владельца сохраняются.
|
||||
|
||||
<details>
|
||||
<summary>Развёрнутый пример и ограничения</summary>
|
||||
|
||||
```php
|
||||
// Vulnerable: client input is interpolated into SQL.
|
||||
$row = $pdo->query("SELECT body FROM notes WHERE id = '" . $_GET['id'] . "'")->fetch();
|
||||
```
|
||||
|
||||
**Патч PDO для приватной заметки:**
|
||||
|
||||
```php
|
||||
function readPrivateNote(PDO $pdo, ?int $userId, int $noteId): ?string {
|
||||
if ($userId === null) {
|
||||
throw new RuntimeException('authentication required');
|
||||
}
|
||||
$stmt = $pdo->prepare('SELECT body FROM notes WHERE id = :id AND owner_id = :owner');
|
||||
$stmt->bindValue(':id', $noteId, PDO::PARAM_INT);
|
||||
$stmt->bindValue(':owner', $userId, PDO::PARAM_INT);
|
||||
$stmt->execute();
|
||||
$row = $stmt->fetch(PDO::FETCH_ASSOC);
|
||||
return $row === false ? null : $row['body'];
|
||||
}
|
||||
```
|
||||
|
||||
До функции валидировать числовой ID: `(int) $_GET['id']` молча преобразует часть
|
||||
некорректных строк. Настроить обработку ошибок PDO; не возвращать клиенту текст
|
||||
SQL-исключения. Маркеры предназначены для значений, не имён таблиц/столбцов.
|
||||
Для поддерживающего драйвера можно использовать native prepares; не менять
|
||||
режим всего приложения вслепую, поскольку поведение драйверов различается.
|
||||
|
||||
**Проверить:** своё/чужое/нет сессии; отсутствующая запись; неверный ID; поиск
|
||||
другого строкового поля с апострофом не ломается. Сохранить общий доступ, если он есть.
|
||||
|
||||
</details>
|
||||
|
||||
<a id="php-object"></a>
|
||||
|
||||
<a id="php-object-untrusted-php-unserialize"></a>
|
||||
|
||||
## PHP-OBJECT. unserialize внешних данных
|
||||
|
||||
**Поиск:** скрипт, правило PHP-OBJECT. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain PHP-OBJECT. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
~~~php
|
||||
$value = unserialize($data);
|
||||
~~~
|
||||
|
||||
**Исправление:** JSON со схемой; совместимость старого формата отдельно. allowed_classes=false не заменяет схему.
|
||||
|
||||
~~~php
|
||||
$value = json_decode($data, true, 32, JSON_THROW_ON_ERROR); // validate schema
|
||||
~~~
|
||||
|
||||
**Проверка:** Объекты PHP не создаются; старые данные учтены.
|
||||
|
||||
<details>
|
||||
<summary>Развёрнутый пример и ограничения</summary>
|
||||
|
||||
```php
|
||||
// Vulnerable with untrusted input: object restoration has side effects.
|
||||
$profile = unserialize($_COOKIE['profile']);
|
||||
```
|
||||
|
||||
**Патч для простого профиля при совместимом JSON-контракте:**
|
||||
|
||||
```php
|
||||
function decodeProfile(string $raw): array {
|
||||
$value = json_decode($raw, false, 32, JSON_THROW_ON_ERROR);
|
||||
if (!($value instanceof stdClass)) {
|
||||
throw new InvalidArgumentException('object required');
|
||||
}
|
||||
$fields = get_object_vars($value);
|
||||
if (array_keys($fields) !== ['display_name'] || !is_string($fields['display_name'])) {
|
||||
throw new InvalidArgumentException('unexpected profile fields');
|
||||
}
|
||||
return ['display_name' => $fields['display_name']];
|
||||
}
|
||||
```
|
||||
|
||||
Глубина 32 — пример ограничения, не требование игры; размер тела ограничивать
|
||||
до парсинга по контракту. `role` и владелец задаются сервером. PHP прямо
|
||||
предостерегает от `unserialize` недоверенных данных даже с `allowed_classes`:
|
||||
один этот флаг не считать полным исправлением.
|
||||
|
||||
**Проверить:** корректный профиль, неизвестное поле, массив вместо объекта,
|
||||
неверный тип и ошибка JSON. Переход формата требует совместимости старых клиентов
|
||||
и данных; не оставлять fallback на `unserialize` для строки клиента.
|
||||
|
||||
</details>
|
||||
|
||||
<a id="php-shell"></a>
|
||||
|
||||
<a id="php-shell-php-code-or-shell-execution"></a>
|
||||
|
||||
## PHP-SHELL. Исполнение текста PHP/команды
|
||||
|
||||
**Поиск:** скрипт, правило PHP-SHELL. Запуск: python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain PHP-SHELL. Regex: eval/shell_exec/system/passthru/popen/exec и строковый/переменный proc_open. Literal argv-массив proc_open в первом аргументе, также с command: в PHP 8+, не помечается, кроме явного shell; массив поддержан PHP 7.4+. Исполняемый файл и опасные опции проверить вручную. Переставленные named arguments, backticks, variable functions, wrappers и действующая версия PHP требуют ручного анализа; одноимённые пользовательские функции и комментарии могут совпадать.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
~~~php
|
||||
shell_exec($command);
|
||||
~~~
|
||||
|
||||
**Исправление:** Библиотечная операция вместо shell; иначе фиксированные argv через API без оболочки.
|
||||
|
||||
~~~php
|
||||
$size = filesize($checkedPath);
|
||||
~~~
|
||||
|
||||
**Проверка:** Штатная функция сохранена; текст не исполняется.
|
||||
|
||||
`proc_open` принимает argv-массив начиная с PHP 7.4; именованный `command:` —
|
||||
с PHP 8.0. Массив передаётся процессу без неявной оболочки. Для действительно
|
||||
нужной утилиты можно сохранить вызов без shell, например на PHP 8+:
|
||||
|
||||
~~~php
|
||||
$process = proc_open(
|
||||
command: ['/usr/bin/file', '--', $checkedName],
|
||||
descriptor_spec: $descriptors,
|
||||
pipes: $pipes
|
||||
);
|
||||
~~~
|
||||
|
||||
Здесь путь к executable фиксирован, а `$checkedName` должен пройти проверку
|
||||
доступа и допустимого пути. `--` подходит только утилите, поддерживающей такой
|
||||
разделитель. `command: array('/usr/bin/file', '--', $checkedName)` также не
|
||||
получает PHP-SHELL. Исключение ограничено первым аргументом с литеральной
|
||||
формой массива; перестановка именованных аргументов и массив из переменной
|
||||
остаются сигналами для просмотра.
|
||||
[proc_open: массив и ограничения Windows](https://github.com/php/doc-en/blob/master/reference/exec/functions/proc-open.xml#L68),
|
||||
[PHP 8: именованные аргументы](https://www.php.net/manual/en/migration80.new-features.php#migration80.new-features.core.named-arguments),
|
||||
[сигнатура proc_open в PHP 8.0](https://github.com/php/php-src/blob/php-8.0.0/ext/standard/basic_functions.stub.php#L1156).
|
||||
|
||||
Явный запуск shell сохраняет риск и сигнал даже при массиве:
|
||||
|
||||
~~~php
|
||||
$process = proc_open(command: ['sh', '-c', $command], descriptor_spec: $descriptors, pipes: $pipes);
|
||||
~~~
|
||||
|
||||
Не превращать pipeline в argv простым разделением строки: перенести нужные
|
||||
операции в библиотеку либо явно связать процессы. Проверить executable,
|
||||
опции, `PATH`, рабочий каталог и окружение. На Windows экранирование массива
|
||||
рассчитано на совместимый с VC runtime разбор командной строки; произвольный
|
||||
parser программы может иметь другой контракт. Закрывать pipes и процесс,
|
||||
проверять ошибки, лимиты времени/вывода и прежний формат результата.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'proc_open|proc_close|proc_terminate|shell_exec|descriptor_spec|bypass_shell' .
|
||||
~~~
|
||||
|
||||
После совпадения проследить реальный argv и источник каждого аргумента.
|
||||
В разрешённом тестовом окружении проверить пробелы, кавычки, имя с ведущим
|
||||
дефисом, штатный файл и ошибку процесса. Отсутствие PHP-SHELL не доказывает
|
||||
безопасность аргументов. Здесь проверены исходники и поведение сканера;
|
||||
PHP runtime и найденные команды не запускались.
|
||||
|
||||
<a id="php-include"></a>
|
||||
|
||||
<a id="php-include-client-selected-include-path"></a>
|
||||
|
||||
## PHP-INCLUDE. Клиентский путь include
|
||||
|
||||
**Поиск:** скрипт, правило PHP-INCLUDE. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain PHP-INCLUDE. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
~~~php
|
||||
include $_GET['page'];
|
||||
~~~
|
||||
|
||||
**Исправление:** Фиксированная таблица разрешённых модулей; пользовательский текст хранить как данные.
|
||||
|
||||
~~~php
|
||||
$pages = ['home' => __DIR__ . '/pages/home.php'];
|
||||
if (!isset($pages[$page])) { throw new Exception('bad page'); }
|
||||
include $pages[$page];
|
||||
~~~
|
||||
|
||||
**Проверка:** Неизвестные имена/пути отвергаются; штатные страницы работают.
|
||||
|
||||
<details>
|
||||
<summary>Развёрнутый пример и ограничения</summary>
|
||||
|
||||
```php
|
||||
// Vulnerable: the client controls the executable PHP file path.
|
||||
include $_GET['page'];
|
||||
```
|
||||
|
||||
**Патч, если контракт — выбор одной из известных страниц:**
|
||||
|
||||
```php
|
||||
$pages = [
|
||||
'help' => __DIR__ . '/pages/help.php',
|
||||
'profile' => __DIR__ . '/pages/profile.php',
|
||||
];
|
||||
$page = $_GET['page'] ?? 'help';
|
||||
if (!is_string($page) || !array_key_exists($page, $pages)) {
|
||||
http_response_code(404);
|
||||
exit;
|
||||
}
|
||||
require $pages[$page];
|
||||
```
|
||||
|
||||
Пути заданы сервером. Требования авторизации `profile` остаются обязательными
|
||||
до выдачи приватных данных. `basename()` не ограничивает пользователя нужным
|
||||
набором страниц и не решает права. Если функция обещает загрузку пользовательского
|
||||
файла, `include` вообще не должен использоваться для его отображения.
|
||||
|
||||
**Проверить:** обе штатные страницы, неизвестное имя, массив вместо page;
|
||||
закрытая страница не открывается анониму; меняется только допустимый выбор страницы.
|
||||
|
||||
</details>
|
||||
|
||||
<a id="php-prefix-mac"></a>
|
||||
|
||||
<a id="php-prefix-mac-hash-concatenation-instead-of-mac"></a>
|
||||
|
||||
## PHP-PREFIX-MAC. Хеш конкатенации вместо MAC
|
||||
|
||||
**Поиск:** скрипт, правило PHP-PREFIX-MAC. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain PHP-PREFIX-MAC. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
~~~php
|
||||
$tag = sha1($key . $payload);
|
||||
~~~
|
||||
|
||||
**Исправление:** HMAC с секретом вместо sha1(secret || data). Проверять тег через hash_equals; версионировать формат и спланировать переход старых токенов.
|
||||
|
||||
~~~php
|
||||
$tag = hash_hmac('sha256', $payload, $key);
|
||||
~~~
|
||||
|
||||
**Проверка:** Изменение/добавление данных не проходит; подпись охватывает назначение и все auth-поля.
|
||||
|
||||
**Вариант A/D:** Secret-prefix hash ошибочно назван HMAC. **ECSC / Diese, автор + код.** Подпись построена как SHA1 от secret || data.
|
||||
**Патч:** настоящий HMAC и версия токена; безопасный переход старых подписей.
|
||||
**Тест:** изменение/добавление полей не принимается.
|
||||
**Поиск:** PHP-PREFIX-MAC; имя функции hmac само по себе ничего не гарантирует.
|
||||
|
||||
[исходник/разбор 1](https://github.com/ECSC2024/ECSC2024-CTF-AD/blob/2a92e17384ad228072a84fb076a35066fe2ffeff/sources/Diese/README.md); [исходник/разбор 2](https://github.com/ECSC2024/ECSC2024-CTF-AD/blob/2a92e17384ad228072a84fb076a35066fe2ffeff/sources/Diese/webapp/src/classes/Utils.class.php); [исходник/разбор 3](https://github.com/ECSC2024/ECSC2024-CTF-AD/blob/2a92e17384ad228072a84fb076a35066fe2ffeff/sources/Diese/hsm/src/msg.c).
|
||||
|
||||
<a id="php-parse-str"></a>
|
||||
|
||||
<a id="php-parse-str-parse_str-key-normalization"></a>
|
||||
|
||||
## PHP-PARSE-STR. Нормализация ключей parse_str
|
||||
|
||||
**Поиск:** скрипт, правило PHP-PARSE-STR. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain PHP-PARSE-STR. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
~~~php
|
||||
parse_str($token_data, $params);
|
||||
~~~
|
||||
|
||||
**Исправление:** Явная схема и allowlist полей до подписи и после разбора; учесть преобразование точек/пробелов в underscore, массивы и дубли ключей.
|
||||
|
||||
~~~php
|
||||
$params = parse_and_validate_canonical_share_dto($token_data); // one schema, duplicate policy, server-owned fields
|
||||
~~~
|
||||
|
||||
**Проверка:** Разные написания поля не меняют owner/doc_id; signer и verifier разбирают одинаково.
|
||||
|
||||
**Вариант A/D:** Нормализация ключей параметров после подписи. **ECSC / Diese, автор + код.** parse_str превращает некоторые разные имена
|
||||
в одинаковые, меняя смысл полей.
|
||||
**Патч:** allowlist и одна каноническая DTO-схема у signer/verifier; запрет
|
||||
неоднозначных дублей. **Тест:** точки, пробелы, underscore и массивы.
|
||||
**Поиск:** PHP-PARSE-STR; сам вызов не обязательно уязвим.
|
||||
|
||||
[исходник/разбор 1](https://github.com/ECSC2024/ECSC2024-CTF-AD/blob/2a92e17384ad228072a84fb076a35066fe2ffeff/sources/Diese/README.md); [исходник/разбор 2](https://github.com/ECSC2024/ECSC2024-CTF-AD/blob/2a92e17384ad228072a84fb076a35066fe2ffeff/sources/Diese/webapp/src/classes/Utils.class.php); [исходник/разбор 3](https://github.com/ECSC2024/ECSC2024-CTF-AD/blob/2a92e17384ad228072a84fb076a35066fe2ffeff/sources/Diese/hsm/src/msg.c).
|
||||
|
||||
<a id="php-loose-compare"></a>
|
||||
|
||||
<a id="php-loose-compare-loose-comparison-of-token-or-signature"></a>
|
||||
|
||||
## PHP-LOOSE-COMPARE. Нестрогое сравнение токена или подписи
|
||||
|
||||
**Поиск:** скрипт, правило PHP-LOOSE-COMPARE. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain PHP-LOOSE-COMPARE. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
~~~php
|
||||
$ok = $token == $provided;
|
||||
~~~
|
||||
|
||||
**Исправление:** Проверить тип; для тега hash_equals, для обычного значения ===, для пароля password_verify. Семантика числовых строк зависит от версии и операндов.
|
||||
|
||||
~~~php
|
||||
$ok = is_string($provided) && hash_equals($token, $provided);
|
||||
~~~
|
||||
|
||||
**Проверка:** Число/массив/числовая строка не превращаются в авторизацию; правильное значение принимается.
|
||||
|
||||
**Основание:** [первичный материал](https://www.php.net/manual/en/language.operators.comparison.php).
|
||||
|
||||
<a id="php-upload"></a>
|
||||
|
||||
<a id="php-upload-moving-an-uploaded-file"></a>
|
||||
|
||||
## PHP-UPLOAD. Перенос загруженного файла
|
||||
|
||||
**Поиск:** скрипт, правило PHP-UPLOAD. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain PHP-UPLOAD. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
~~~php
|
||||
move_uploaded_file($tmp, $webroot . $name);
|
||||
~~~
|
||||
|
||||
**Исправление:** Проверять upload error/размер/тип, серверное имя и отсутствие перезаписи, хранить вне исполняемого webroot; выдавать после auth.
|
||||
|
||||
~~~php
|
||||
move_uploaded_file($validatedTmp, $serverChosenPrivatePath);
|
||||
~~~
|
||||
|
||||
**Проверка:** Обычный upload/download, коллизия имени, чужой owner, неверный тип и полный диск. Вызов остаётся сигналом.
|
||||
|
||||
**Основание:** [первичный материал](https://www.php.net/manual/en/features.file-upload.php).
|
||||
|
||||
<a id="php-display-errors"></a>
|
||||
|
||||
<a id="php-display-errors-php-displays-errors-to-clients"></a>
|
||||
|
||||
## PHP-DISPLAY-ERRORS. PHP показывает ошибки клиенту
|
||||
|
||||
**Поиск:** скрипт, правило PHP-DISPLAY-ERRORS. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain PHP-DISPLAY-ERRORS. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
~~~php
|
||||
display_errors = On
|
||||
~~~
|
||||
|
||||
**Исправление:** Отключить клиентский вывод, включить локальный журнал без секретов; проверить эффективный php.ini/FPM pool и runtime ini_set.
|
||||
|
||||
~~~php
|
||||
display_errors = Off
|
||||
~~~
|
||||
|
||||
**Проверка:** Parse/DB/type error дают штатный ответ, диагностика сохраняется.
|
||||
|
||||
**Основание:** [первичный материал](https://www.php.net/manual/en/errorfunc.configuration.php).
|
||||
|
||||
<a id="php-xss"></a>
|
||||
|
||||
<a id="php-xss-raw-data-reaches-html-attributes-or-javascript"></a>
|
||||
|
||||
## PHP-XSS. HTML/атрибут/JS получают сырой текст
|
||||
|
||||
**Поиск:** вручную; отдельного правила сканера нет.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'echo|print|htmlspecialchars|json_encode|<script' .
|
||||
~~~
|
||||
|
||||
Определить контекст вывода; htmlspecialchars для текста не делает строку безопасным JavaScript.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
echo $title внутри HTML без encoding; вставка JSON в script без подходящего сериализатора.
|
||||
|
||||
**Исправление:** Autoescape шаблона или htmlspecialchars с ENT_QUOTES/ENT_SUBSTITUTE и UTF-8 для HTML; отдельное безопасное кодирование JS/URL.
|
||||
|
||||
**Проверка:** Кавычки/теги/Unicode показываются как данные; легитимное форматирование не ломается.
|
||||
|
||||
<details>
|
||||
<summary>Развёрнутый пример и ограничения</summary>
|
||||
|
||||
```php
|
||||
// Vulnerable with untrusted title: the browser interprets it as markup.
|
||||
echo '<p>' . $title . '</p>';
|
||||
```
|
||||
|
||||
**Патч для текстового содержимого HTML:**
|
||||
|
||||
```php
|
||||
echo '<p>' . htmlspecialchars($title, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8') . '</p>';
|
||||
```
|
||||
|
||||
`$title` перед этим проверен как строка. Сохранить исходный текст в БД и кодировать
|
||||
при выводе. Иначе повторное редактирование может накопить двойное экранирование.
|
||||
Этот пример не является кодированием JavaScript, CSS или проверкой URL; для этих
|
||||
контекстов другой механизм. Разрешённый по контракту HTML требует очистки
|
||||
допустимого подмножества, а не превращения всей разметки в текст.
|
||||
|
||||
**Проверить:** `<`, `>`, `&`, кавычки и Unicode показываются текстом; старая запись
|
||||
и цикл «сохранить → открыть → изменить» сохраняют исходное содержание.
|
||||
|
||||
</details>
|
||||
|
||||
<a id="php-session"></a>
|
||||
|
||||
<a id="php-session-session-fixation-strict-mode-and-stale-state"></a>
|
||||
|
||||
## PHP-SESSION. PHP session: fixation, strict mode, старое состояние
|
||||
|
||||
**Поиск:** вручную; отдельного правила сканера нет.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'session_start|session_regenerate_id|session.use_strict_mode|session_id' .
|
||||
~~~
|
||||
|
||||
Проследить принятие внешнего ID, регенерацию при login и запись роли в session.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
Внешний неизвестный ID принимается, после входа остаётся тем же.
|
||||
|
||||
**Исправление:** session.use_strict_mode, штатная регенерация с учётом concurrent requests, серверная роль; согласованные Secure/HttpOnly/SameSite.
|
||||
|
||||
**Проверка:** Прежний ID не авторизует, обычные параллельные запросы не теряют состояние.
|
||||
|
||||
**Основание:** [первичный материал](https://www.php.net/manual/en/session.security.ini.php).
|
||||
|
||||
<a id="php-wrappers"></a>
|
||||
|
||||
<a id="php-wrappers-filesystem-apis-accept-urls-or-wrappers"></a>
|
||||
|
||||
## PHP-WRAPPERS. Файловый API принимает URL/wrapper
|
||||
|
||||
**Поиск:** вручную; отдельного правила сканера нет.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'file_get_contents|fopen|copy\(|file_exists|is_file|phar|stream_context' .
|
||||
~~~
|
||||
|
||||
Проверить, что API принимает путь или stream URL; сопоставить версию PHP и нужные wrappers.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
Пользователь выбирает схему/локальный путь вместо разрешённого объекта; open_basedir не является полным sandbox.
|
||||
|
||||
**Исправление:** Серверный путь из авторизованного ID; для HTTP отдельный клиент с URL policy; запрет клиентского выбора wrapper.
|
||||
|
||||
**Проверка:** Штатный файл читается, внешний URL/чужой файл/нестандартная схема не достигают операции.
|
||||
|
||||
<a id="php-extract"></a>
|
||||
|
||||
<a id="php-extract-extract-overwrites-local-variables"></a>
|
||||
|
||||
## PHP-EXTRACT. extract и variable variables подменяют контекст
|
||||
|
||||
**Поиск:** скрипт, правило PHP-EXTRACT. Запуск: python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain PHP-EXTRACT. Regex: любой extract(...); доверенные шаблонные контексты требуют ручной классификации.
|
||||
|
||||
Дополнительный ручной поиск для непокрытых форм:
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'extract\(|parse_str|\$\$|GLOBALS|register_globals' .
|
||||
~~~
|
||||
|
||||
Сравнить импортируемые ключи с именами auth/config переменных; двухаргументный parse_str имеет иной риск, чем старое поведение.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
extract($_REQUEST) перезаписывает локальные переменные либо $$key выбирает чувствительное имя.
|
||||
|
||||
**Исправление:** Явно читать разрешённые поля в отдельный DTO; не импортировать клиентские ключи в symbol table. EXTR_SKIP уменьшает перезаписи, но не заменяет проверку схемы, типов и новых имён.
|
||||
|
||||
**Проверка:** role, authorized, путь и конфигурация не меняются при лишних ключах.
|
||||
|
||||
**Основание:** [первичный материал](https://www.php.net/manual/en/function.extract.php).
|
||||
|
||||
|
||||
**Сигнал сканера — пример до:**
|
||||
|
||||
~~~php
|
||||
extract($_POST);
|
||||
if ($is_admin) { show_private_data(); }
|
||||
~~~
|
||||
|
||||
**Шаблон исправления:**
|
||||
|
||||
~~~php
|
||||
$display_name = validate_display_name($_POST['display_name'] ?? '');
|
||||
~~~
|
||||
|
||||
Первичная документация: [документация 1](https://www.php.net/manual/en/function.extract.php).
|
||||
|
||||
<a id="php-serialize-magic"></a>
|
||||
|
||||
<a id="php-serialize-magic-magic-methods-and-trust-in-stored-data"></a>
|
||||
|
||||
## PHP-SERIALIZE-MAGIC. Magic methods и доверие данным из БД
|
||||
|
||||
**Поиск:** вручную; отдельного правила сканера нет.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e '__wakeup|__unserialize|__destruct|__toString|unserialize' .
|
||||
~~~
|
||||
|
||||
От места PHP-OBJECT пройти reachable classes и побочные эффекты; БД не становится доверенной после клиентской записи.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
Десериализованный объект вызывает файловую/сетевую операцию до проверки результата.
|
||||
|
||||
**Исправление:** DTO без выбора класса и побочных эффектов; совместимая миграция отдельно, не fallback на небезопасный parser.
|
||||
|
||||
**Проверка:** Неизвестный тип не вызывает эффектов; старый допустимый формат читается по плану.
|
||||
|
||||
<a id="php-csrf"></a>
|
||||
|
||||
<a id="php-csrf-cookies-authorize-mutations-without-csrf-protection"></a>
|
||||
|
||||
## PHP-CSRF. Cookie авторизует изменяющий запрос без CSRF
|
||||
|
||||
**Поиск:** вручную; отдельного правила сканера нет.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'csrf|POST|PUT|DELETE|REQUEST_METHOD|SameSite' .
|
||||
~~~
|
||||
|
||||
Проверить формы и JSON endpoint с cookie auth, исключения middleware и Origin/Referer policy.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
Браузер автоматически прикладывает cookie к изменению состояния из чужого контекста.
|
||||
|
||||
**Исправление:** Штатный CSRF token и проверка origin по архитектуре; SameSite дополняет, не заменяет серверную проверку. Bearer API имеет другой контекст.
|
||||
|
||||
**Проверка:** Неверный/отсутствующий token отклоняется; нормальная форма и предусмотренные API-клиенты работают.
|
||||
|
||||
<a id="php-regex-error"></a>
|
||||
|
||||
<a id="php-regex-error-preg_match-errors-become-permission"></a>
|
||||
|
||||
## PHP-REGEX-ERROR. Ошибка preg_match трактуется как разрешение
|
||||
|
||||
**Поиск:** вручную; отдельного правила сканера нет.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'preg_match|preg_last_error|preg_replace' .
|
||||
~~~
|
||||
|
||||
Различить false, 0 и 1; найти отрицание результата и лимиты regex.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
Ошибка движка при длинном вводе попадает в ветвь «запрещённое не найдено».
|
||||
|
||||
**Исправление:** Проверять результат === 1/0/false по смыслу, fail closed при ошибке; ограничить длину и сложность.
|
||||
|
||||
**Проверка:** Match/no-match/ошибка движка дают разные ожидаемые ответы, штатный Unicode поддержан.
|
||||
|
||||
**Основание:** [первичный материал](https://www.php.net/manual/en/function.preg-match.php).
|
||||
|
||||
<a id="php-xml-flags"></a>
|
||||
|
||||
<a id="php-xml-flags-xml-entity-substitution-or-dtd-enabled"></a>
|
||||
|
||||
## PHP-XML-FLAGS. XML разрешает подстановку сущностей и DTD
|
||||
|
||||
**Поиск:** скрипт, правило PHP-XML-FLAGS. Запуск: python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain PHP-XML-FLAGS. Regex: LIBXML_NOENT/DTDLOAD/DTDATTR/DTDVALID и substituteEntities/resolveExternals=true. Числовые маски из ini/БД не распознаются: вручную сопоставить каждый бит с константами runtime.
|
||||
|
||||
**Уязвимый вариант:** NOENT означает подстановку сущностей, а NONET сам по себе не запрещает доступ к локальному файлу.
|
||||
|
||||
~~~php
|
||||
$doc->loadXML($xml, LIBXML_NOENT | LIBXML_DTDLOAD | LIBXML_NONET);
|
||||
~~~
|
||||
|
||||
**Исправление:** Убрать подстановку/загрузку внешних DTD, установить лимиты и проверить версию libxml. На поддерживаемом runtime добавить LIBXML_NO_XXE; не полагаться на один NONET.
|
||||
|
||||
~~~php
|
||||
$doc->resolveExternals = false;
|
||||
$doc->substituteEntities = false;
|
||||
$doc->loadXML($boundedXml, LIBXML_NONET);
|
||||
~~~
|
||||
|
||||
**Проверка:** Обычный XML разбирается; внешний DTD/сущность не читает файл и не делает сетевой запрос, объём/вложенность ограничены.
|
||||
|
||||
Первичная документация: [документация 1](https://www.php.net/manual/en/libxml.constants.php), [документация 2](https://github.com/enowars/enowars7-service-oldschool#vulnerabilities).
|
||||
|
||||
<a id="php-template"></a>
|
||||
|
||||
<a id="php-template-template-built-from-dynamic-text"></a>
|
||||
|
||||
## PHP-TEMPLATE. Шаблон создаётся из динамического текста
|
||||
|
||||
**Поиск:** скрипт, правило PHP-TEMPLATE. Запуск: python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain PHP-TEMPLATE. Regex: createTemplate($...) и Smarty display/fetch с eval: или string:. Переменные loaders, custom filters и шаблоны из БД просматривать вручную.
|
||||
|
||||
**Уязвимый вариант:** Если пользовательские данные становятся исходником шаблона, возможности template engine становятся доступными пользователю.
|
||||
|
||||
~~~php
|
||||
$template = $twig->createTemplate($profileText);
|
||||
echo $template->render($vars);
|
||||
~~~
|
||||
|
||||
**Исправление:** Разделить доверенный шаблон и параметры; если продукт допускает шаблоны, отдельно ограничить sandbox, loader, доступные функции и ресурсы.
|
||||
|
||||
~~~php
|
||||
echo $twig->render('profile.html.twig', ['about' => $profileText]);
|
||||
~~~
|
||||
|
||||
**Проверка:** Текст шаблонных выражений в профиле отображается как данные; приватные шаблоны/файлы недоступны.
|
||||
|
||||
Первичная документация: [документация 1](https://twig.symfony.com/doc/3.x/api.html#loading-templates-from-a-string).
|
||||
|
||||
<a id="php-curl-tls"></a>
|
||||
|
||||
<a id="php-curl-tls-curl-certificate-or-hostname-checks-disabled"></a>
|
||||
|
||||
## PHP-CURL-TLS. cURL не проверяет сертификат или имя
|
||||
|
||||
**Поиск:** скрипт, правило PHP-CURL-TLS. Запуск: python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain PHP-CURL-TLS. Regex: CURLOPT_SSL_VERIFYPEER=false/0 и CURLOPT_SSL_VERIFYHOST=false/0/1, аргумент или setopt_array. Значения из переменных не вычисляются.
|
||||
|
||||
**Уязвимый вариант:** Отключение проверки сервера позволяет подменить результат исходящего HTTPS-запроса.
|
||||
|
||||
~~~php
|
||||
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
|
||||
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
|
||||
~~~
|
||||
|
||||
**Исправление:** Проверять peer и hostname, настроить доверенный CA. На VERIFYHOST использовать 2, не исторически неоднозначное 1.
|
||||
|
||||
~~~php
|
||||
curl_setopt_array($ch, [CURLOPT_SSL_VERIFYPEER => true, CURLOPT_SSL_VERIFYHOST => 2, CURLOPT_CAINFO => $trustedCA]);
|
||||
~~~
|
||||
|
||||
**Проверка:** Верный CA/hostname работает, чужой hostname/CA и истёкший сертификат дают ошибку без fallback.
|
||||
|
||||
Первичная документация: [документация 1](https://www.php.net/manual/en/function.curl-setopt.php).
|
||||
|
||||
<a id="php-url-include"></a>
|
||||
|
||||
<a id="php-url-include-remote-resource-inclusion-enabled"></a>
|
||||
|
||||
## PHP-URL-INCLUDE. Разрешён include удалённого ресурса
|
||||
|
||||
**Поиск:** скрипт, правило PHP-URL-INCLUDE. Запуск: python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain PHP-URL-INCLUDE. Regex: allow_url_include=On/1/true в ini/config или присваивании. Runtime overrides и фактический include path проверять отдельно.
|
||||
|
||||
**Уязвимый вариант:** URL include расширяет последствия управления путём PHP include/require.
|
||||
|
||||
~~~config
|
||||
allow_url_include = On
|
||||
~~~
|
||||
|
||||
**Исправление:** Отключить allow_url_include в действующей конфигурации SAPI; пути подключений выбирать из закрытой серверной таблицы.
|
||||
|
||||
~~~config
|
||||
allow_url_include = Off
|
||||
~~~
|
||||
|
||||
**Проверка:** Приложение загружает штатные модули; пользовательский URL не становится исполняемым кодом.
|
||||
|
||||
Первичная документация: [документация 1](https://www.php.net/manual/en/filesystem.configuration.php#ini.allow-url-include).
|
||||
|
||||
<a id="php-session-config"></a>
|
||||
|
||||
<a id="php-session-config-weakened-php-session-configuration"></a>
|
||||
|
||||
## PHP-SESSION-CONFIG. Ослабленные настройки PHP-сессии
|
||||
|
||||
**Поиск:** скрипт, правило PHP-SESSION-CONFIG. Запуск: python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain PHP-SESSION-CONFIG. Regex: явные опасные значения use_strict_mode/use_only_cookies/use_trans_sid. Пропущенные настройки и ini_set с аргументами остаются ручными.
|
||||
|
||||
**Уязвимый вариант:** Принятие навязанного session id и перенос id в URL создают фиксацию/утечку сессии.
|
||||
|
||||
~~~config
|
||||
session.use_strict_mode = 0
|
||||
session.use_only_cookies = 0
|
||||
session.use_trans_sid = 1
|
||||
~~~
|
||||
|
||||
**Исправление:** Включить strict mode и cookie-only transport, отключить URL rewriting; при auth сменить id, проверить custom session handler и флаги cookie.
|
||||
|
||||
~~~config
|
||||
session.use_strict_mode = 1
|
||||
session.use_only_cookies = 1
|
||||
session.use_trans_sid = 0
|
||||
~~~
|
||||
|
||||
**Проверка:** Навязанный неизвестный id не принимается, после login id меняется; URL/логи не содержат id, штатная сессия сохраняется.
|
||||
|
||||
Первичная документация: [документация 1](https://www.php.net/manual/en/session.configuration.php).
|
||||
|
||||
<a id="php-mass-assign"></a>
|
||||
|
||||
<a id="php-mass-assign-array-keys-choose-columns-and-privileges"></a>
|
||||
|
||||
## PHP-MASS-ASSIGN. Ключи массива выбирают колонки и права
|
||||
|
||||
**Поиск:** вручную; отдельного правила сканера нет.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e '\$_(POST|GET|REQUEST)|array_keys|array_merge|profileData|UPDATE|SET|fill\(|update\(' .
|
||||
~~~
|
||||
|
||||
Проследить не только значения, но и ключи массива от запроса до UPDATE/ORM и назначения owner/admin/association. Проверить вложенные поля и числовые индексы.
|
||||
|
||||
**Уязвимый вариант:** Параметризованы значения SQL, но имена колонок берутся из пользовательского массива; поле роли или связи с чужим объектом массово обновляется.
|
||||
|
||||
**Исправление:** Явно сопоставить разрешённые входные поля фиксированным колонкам и типам. Права, owner и связи проверять отдельно; placeholders не экранируют SQL identifiers.
|
||||
|
||||
**Проверка:** Неизвестная колонка, служебное поле и чужая связь отклонены без изменения состояния; разрешённые поля сохраняются.
|
||||
|
||||
Основание: [OWASP Mass Assignment](https://cheatsheetseries.owasp.org/cheatsheets/Mass_Assignment_Cheat_Sheet.html). Описание и рецепт адаптации составлены для этой базы.
|
||||
|
||||
**Вариант A/D:** в Oldschool массовое обновление позволяло менять служебную связь; имена колонок также попадали в SQL без ограничения. [Авторское описание](https://github.com/enowars/enowars7-service-oldschool#vulnerabilities).
|
||||
|
||||
<a id="php-ldap-filter"></a>
|
||||
|
||||
<a id="php-ldap-filter-ldap-filter-concatenates-a-php-variable"></a>
|
||||
|
||||
## PHP-LDAP-FILTER. LDAP-фильтр склеивается с PHP-переменной
|
||||
|
||||
**Поиск:** правило сканера PHP-LDAP-FILTER. Точный контракт детектора: `--explain PHP-LDAP-FILTER`. Regex с лексическими исключениями: ldap_search/list/read с простыми первыми двумя аргументами и строкой, напрямую объединённой с переменной в третьем аргументе. Переменная может уже быть экранирована; заранее собранные фильтры и интерполяция требуют ручной проверки.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
~~~php
|
||||
ldap_search($conn, $base, '(uid=' . $name . ')');
|
||||
~~~
|
||||
|
||||
**Исправление:** Экранируйте значения для контекста LDAP-фильтра, а не DN; имена атрибутов и область поиска должны быть доверенными.
|
||||
|
||||
~~~php
|
||||
$filter = '(uid=' . ldap_escape($name, '', LDAP_ESCAPE_FILTER) . ')';
|
||||
ldap_search($conn, $base, $filter);
|
||||
~~~
|
||||
|
||||
**Проверка:** Метасимволы LDAP в значении не расширяют результат; разрешённые поисковые запросы работают.
|
||||
|
||||
[Первичный источник 1](https://www.php.net/manual/en/function.ldap-escape.php)
|
||||
@@ -0,0 +1,692 @@
|
||||
# PHP: find, fix and verify
|
||||
|
||||
English | [Русский](php-RU.md)
|
||||
|
||||
[Catalog](README.md) · [Scanner](../offline-scanner.md) · [Patch verification](../patch-validation.md)
|
||||
|
||||
23 sections. Each follows **Search → Vulnerable example → Fix → Verification**.
|
||||
Run `rg` from a local service checkout; searches only read files. Derive the actor/owner from a verified session, not request data. Adapt examples to the actual API and contract.
|
||||
|
||||
## Contents
|
||||
|
||||
- [PHP-SQL — Dynamic PHP SQL](#php-sql)
|
||||
- [PHP-OBJECT — Untrusted PHP unserialize](#php-object)
|
||||
- [PHP-SHELL — PHP code or shell execution](#php-shell)
|
||||
- [PHP-INCLUDE — Client-selected include path](#php-include)
|
||||
- [PHP-PREFIX-MAC — Hash concatenation instead of MAC](#php-prefix-mac)
|
||||
- [PHP-PARSE-STR — parse_str key normalization](#php-parse-str)
|
||||
- [PHP-LOOSE-COMPARE — Loose comparison of token or signature](#php-loose-compare)
|
||||
- [PHP-UPLOAD — Moving an uploaded file](#php-upload)
|
||||
- [PHP-DISPLAY-ERRORS — PHP displays errors to clients](#php-display-errors)
|
||||
- [PHP-XSS — Raw data reaches HTML, attributes or JavaScript](#php-xss)
|
||||
- [PHP-SESSION — Session fixation, strict mode and stale state](#php-session)
|
||||
- [PHP-WRAPPERS — Filesystem APIs accept URLs or wrappers](#php-wrappers)
|
||||
- [PHP-EXTRACT — extract overwrites local variables](#php-extract)
|
||||
- [PHP-SERIALIZE-MAGIC — Magic methods and trust in stored data](#php-serialize-magic)
|
||||
- [PHP-CSRF — Cookies authorize mutations without CSRF protection](#php-csrf)
|
||||
- [PHP-REGEX-ERROR — preg_match errors become permission](#php-regex-error)
|
||||
- [PHP-XML-FLAGS — XML entity substitution or DTD enabled](#php-xml-flags)
|
||||
- [PHP-TEMPLATE — Template built from dynamic text](#php-template)
|
||||
- [PHP-CURL-TLS — cURL certificate or hostname checks disabled](#php-curl-tls)
|
||||
- [PHP-URL-INCLUDE — Remote resource inclusion enabled](#php-url-include)
|
||||
- [PHP-SESSION-CONFIG — Weakened PHP session configuration](#php-session-config)
|
||||
- [PHP-MASS-ASSIGN — Array keys choose columns and privileges](#php-mass-assign)
|
||||
- [PHP-LDAP-FILTER — LDAP filter concatenates a PHP variable](#php-ldap-filter)
|
||||
|
||||
<a id="php-sql"></a>
|
||||
|
||||
## PHP-SQL. Dynamic PHP SQL
|
||||
|
||||
**Search:** scanner rule PHP-SQL. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain PHP-SQL` for details. Regex: query/exec/prepare with concatenation, double-quoted interpolation and mysqli_query/pg_query with an ordinary connection argument. Escaping, other interpolation and SQL variables are not fully parsed.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
~~~php
|
||||
$db->query("SELECT id FROM notes WHERE name=" . $name);
|
||||
~~~
|
||||
|
||||
**Fix:** Use driver-supported prepared statements and bound values; allowlist identifiers.
|
||||
|
||||
~~~php
|
||||
$stmt = $db->prepare("SELECT id FROM notes WHERE name = ?");
|
||||
$stmt->execute([$name]);
|
||||
~~~
|
||||
|
||||
**Verification:** Quotes stay data and ownership conditions remain.
|
||||
|
||||
<details>
|
||||
<summary>Expanded example and limitations</summary>
|
||||
|
||||
```php
|
||||
// Vulnerable: client input is interpolated into SQL.
|
||||
$row = $pdo->query("SELECT body FROM notes WHERE id = '" . $_GET['id'] . "'")->fetch();
|
||||
```
|
||||
|
||||
**PDO patch for a private note:**
|
||||
|
||||
```php
|
||||
function readPrivateNote(PDO $pdo, ?int $userId, int $noteId): ?string {
|
||||
if ($userId === null) {
|
||||
throw new RuntimeException('authentication required');
|
||||
}
|
||||
$stmt = $pdo->prepare('SELECT body FROM notes WHERE id = :id AND owner_id = :owner');
|
||||
$stmt->bindValue(':id', $noteId, PDO::PARAM_INT);
|
||||
$stmt->bindValue(':owner', $userId, PDO::PARAM_INT);
|
||||
$stmt->execute();
|
||||
$row = $stmt->fetch(PDO::FETCH_ASSOC);
|
||||
return $row === false ? null : $row['body'];
|
||||
}
|
||||
```
|
||||
|
||||
Validate the numeric ID first: `(int) $_GET['id']` silently converts some invalid strings. Configure PDO error handling and do not return SQL exceptions to clients. Placeholders represent values, not table/column names. Native prepares may be appropriate for supported drivers, but do not change application-wide settings blindly; driver behavior differs.
|
||||
|
||||
**Check:** Owner, other user, no session, missing record, invalid ID and another searchable text field containing an apostrophe. Preserve intended sharing.
|
||||
|
||||
</details>
|
||||
|
||||
<a id="php-object"></a>
|
||||
|
||||
## PHP-OBJECT. Untrusted PHP unserialize
|
||||
|
||||
**Search:** scanner rule PHP-OBJECT. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain PHP-OBJECT` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
~~~php
|
||||
$value = unserialize($data);
|
||||
~~~
|
||||
|
||||
**Fix:** Prefer schema-validated JSON; migrate trusted legacy records separately. allowed_classes alone is not a complete input policy.
|
||||
|
||||
~~~php
|
||||
$value = json_decode($data, true, 32, JSON_THROW_ON_ERROR); // validate schema
|
||||
~~~
|
||||
|
||||
**Verification:** Unexpected object types fail without construction; valid records stay readable.
|
||||
|
||||
<details>
|
||||
<summary>Expanded example and limitations</summary>
|
||||
|
||||
```php
|
||||
// Vulnerable with untrusted input: object restoration has side effects.
|
||||
$profile = unserialize($_COOKIE['profile']);
|
||||
```
|
||||
|
||||
**Patch for a simple profile when the protocol supports JSON:**
|
||||
|
||||
```php
|
||||
function decodeProfile(string $raw): array {
|
||||
$value = json_decode($raw, false, 32, JSON_THROW_ON_ERROR);
|
||||
if (!($value instanceof stdClass)) {
|
||||
throw new InvalidArgumentException('object required');
|
||||
}
|
||||
$fields = get_object_vars($value);
|
||||
if (array_keys($fields) !== ['display_name'] || !is_string($fields['display_name'])) {
|
||||
throw new InvalidArgumentException('unexpected profile fields');
|
||||
}
|
||||
return ['display_name' => $fields['display_name']];
|
||||
}
|
||||
```
|
||||
|
||||
Depth 32 is an example bound, not a competition requirement; bound body size before parsing according to contract. Role and owner come from the server. PHP warns against untrusted unserialize even with allowed_classes: that flag alone is not a complete fix.
|
||||
|
||||
**Check:** Valid profile, unknown field, array instead of object, wrong type and malformed JSON. Format migration must support old clients/data; never retain unserialize fallback for client strings.
|
||||
|
||||
</details>
|
||||
|
||||
<a id="php-shell"></a>
|
||||
|
||||
## PHP-SHELL. PHP code or shell execution
|
||||
|
||||
**Search:** scanner rule PHP-SHELL. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain PHP-SHELL` for details. Regex: eval/shell_exec/system/passthru/popen/exec and string/variable proc_open. Literal argv arrays in proc_open's first argument (including PHP 8 command:) are excluded unless explicitly launching shell; arrays require PHP 7.4+. Review executable/options, reordered named arguments, backticks, variable functions, wrappers and runtime version. Custom same-named functions/comments may match.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
~~~php
|
||||
shell_exec($command);
|
||||
~~~
|
||||
|
||||
**Fix:** Prefer a library operation; otherwise use a fixed executable and validated argv without a shell.
|
||||
|
||||
~~~php
|
||||
$size = filesize($checkedPath);
|
||||
~~~
|
||||
|
||||
**Verification:** Metacharacters and dangerous options cannot change the operation.
|
||||
|
||||
proc_open accepts argv arrays from PHP 7.4; the named command argument requires PHP 8.0. Arrays pass arguments without an implicit shell. A genuinely required utility can run without shell, for example on PHP 8+:
|
||||
|
||||
~~~php
|
||||
$process = proc_open(
|
||||
command: ['/usr/bin/file', '--', $checkedName],
|
||||
descriptor_spec: $descriptors,
|
||||
pipes: $pipes
|
||||
);
|
||||
~~~
|
||||
|
||||
The executable is fixed; $checkedName still needs authorization and path checks. `--` is valid only for utilities supporting that separator. `command: array('/usr/bin/file', '--', $checkedName)` also avoids PHP-SHELL. The exclusion covers only a literal-array first argument; reordered named arguments and variable arrays remain review signals. [proc_open arrays and Windows limitations](https://github.com/php/doc-en/blob/master/reference/exec/functions/proc-open.xml#L68), [PHP 8 named arguments](https://www.php.net/manual/en/migration80.new-features.php#migration80.new-features.core.named-arguments), [PHP 8.0 proc_open signature](https://github.com/php/php-src/blob/php-8.0.0/ext/standard/basic_functions.stub.php#L1156).
|
||||
|
||||
Explicit shell execution remains risky and still signals even with an array:
|
||||
|
||||
~~~php
|
||||
$process = proc_open(command: ['sh', '-c', $command], descriptor_spec: $descriptors, pipes: $pipes);
|
||||
~~~
|
||||
|
||||
Do not convert a pipeline to argv by simply splitting text: move operations to a library or connect processes explicitly. Review executable, options, PATH, cwd and environment. On Windows array escaping assumes VC-runtime-compatible command-line parsing; other parsers may differ. Close pipes/processes and check errors, runtime/output limits and the old result format.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'proc_open|proc_close|proc_terminate|shell_exec|descriptor_spec|bypass_shell' .
|
||||
~~~
|
||||
|
||||
After a match trace actual argv and every argument's origin. In an authorized test environment check spaces, quotes, leading dashes, normal files and process failure. Absence of PHP-SHELL does not prove argument safety. This catalog review checked source and scanner behavior; it did not run PHP or the discovered commands.
|
||||
|
||||
<a id="php-include"></a>
|
||||
|
||||
## PHP-INCLUDE. Client-selected include path
|
||||
|
||||
**Search:** scanner rule PHP-INCLUDE. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain PHP-INCLUDE` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
~~~php
|
||||
include $_GET['page'];
|
||||
~~~
|
||||
|
||||
**Fix:** Select server-owned include paths from a closed allowlist, never client paths/URLs.
|
||||
|
||||
~~~php
|
||||
$pages = ['home' => __DIR__ . '/pages/home.php'];
|
||||
if (!isset($pages[$page])) { throw new Exception('bad page'); }
|
||||
include $pages[$page];
|
||||
~~~
|
||||
|
||||
**Verification:** Only approved pages load; traversal and remote schemes fail.
|
||||
|
||||
<details>
|
||||
<summary>Expanded example and limitations</summary>
|
||||
|
||||
```php
|
||||
// Vulnerable: the client controls the executable PHP file path.
|
||||
include $_GET['page'];
|
||||
```
|
||||
|
||||
**Patch when the contract selects one of several known pages:**
|
||||
|
||||
```php
|
||||
$pages = [
|
||||
'help' => __DIR__ . '/pages/help.php',
|
||||
'profile' => __DIR__ . '/pages/profile.php',
|
||||
];
|
||||
$page = $_GET['page'] ?? 'help';
|
||||
if (!is_string($page) || !array_key_exists($page, $pages)) {
|
||||
http_response_code(404);
|
||||
exit;
|
||||
}
|
||||
require $pages[$page];
|
||||
```
|
||||
|
||||
The server defines paths. The profile page still requires authorization before private data is returned. basename() neither restricts selection to the intended pages nor checks access. If the feature displays user-uploaded files, include must not implement that display.
|
||||
|
||||
**Check:** Both normal pages, unknown names and an array in place of page; anonymous callers cannot open private pages; only permitted selection changes.
|
||||
|
||||
</details>
|
||||
|
||||
<a id="php-prefix-mac"></a>
|
||||
|
||||
## PHP-PREFIX-MAC. Hash concatenation instead of MAC
|
||||
|
||||
**Search:** scanner rule PHP-PREFIX-MAC. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain PHP-PREFIX-MAC` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
~~~php
|
||||
$tag = sha1($key . $payload);
|
||||
~~~
|
||||
|
||||
**Fix:** Use HMAC rather than a hash of secret concatenated with data, compare with hash_equals and migrate/version old formats.
|
||||
|
||||
~~~php
|
||||
$tag = hash_hmac('sha256', $payload, $key);
|
||||
~~~
|
||||
|
||||
**Verification:** Changed/appended data fails; tags bind purpose and all authentication fields.
|
||||
|
||||
**A/D variant:** Secret-prefix hash mislabeled HMAC. **ECSC / Diese, author and source.** Signatures used SHA1(secret || data). **Patch:** Real HMAC, token versioning and safe migration of existing signatures. **Test:** Changed/added fields fail validation. **Search:** PHP-PREFIX-MAC; a function named hmac guarantees nothing.
|
||||
|
||||
[source/write-up 1](https://github.com/ECSC2024/ECSC2024-CTF-AD/blob/2a92e17384ad228072a84fb076a35066fe2ffeff/sources/Diese/README.md); [source/write-up 2](https://github.com/ECSC2024/ECSC2024-CTF-AD/blob/2a92e17384ad228072a84fb076a35066fe2ffeff/sources/Diese/webapp/src/classes/Utils.class.php); [source/write-up 3](https://github.com/ECSC2024/ECSC2024-CTF-AD/blob/2a92e17384ad228072a84fb076a35066fe2ffeff/sources/Diese/hsm/src/msg.c).
|
||||
|
||||
<a id="php-parse-str"></a>
|
||||
|
||||
## PHP-PARSE-STR. parse_str key normalization
|
||||
|
||||
**Search:** scanner rule PHP-PARSE-STR. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain PHP-PARSE-STR` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
~~~php
|
||||
parse_str($token_data, $params);
|
||||
~~~
|
||||
|
||||
**Fix:** Use identical schemas before signing/after parsing; account for dots/spaces becoming underscores, arrays and duplicate keys.
|
||||
|
||||
~~~php
|
||||
$params = parse_and_validate_canonical_share_dto($token_data); // one schema, duplicate policy, server-owned fields
|
||||
~~~
|
||||
|
||||
**Verification:** Alternate spellings cannot change owner/document; signer and verifier agree.
|
||||
|
||||
**A/D variant:** Parameter-key normalization after signing. **ECSC / Diese, author and source.** parse_str merges certain distinct names and changes field meaning. **Patch:** An allowlist and one canonical signer/verifier DTO schema; reject ambiguous duplicates. **Test:** Dots, spaces, underscores and arrays. **Search:** PHP-PARSE-STR; the call itself need not be vulnerable.
|
||||
|
||||
[source/write-up 1](https://github.com/ECSC2024/ECSC2024-CTF-AD/blob/2a92e17384ad228072a84fb076a35066fe2ffeff/sources/Diese/README.md); [source/write-up 2](https://github.com/ECSC2024/ECSC2024-CTF-AD/blob/2a92e17384ad228072a84fb076a35066fe2ffeff/sources/Diese/webapp/src/classes/Utils.class.php); [source/write-up 3](https://github.com/ECSC2024/ECSC2024-CTF-AD/blob/2a92e17384ad228072a84fb076a35066fe2ffeff/sources/Diese/hsm/src/msg.c).
|
||||
|
||||
<a id="php-loose-compare"></a>
|
||||
|
||||
## PHP-LOOSE-COMPARE. Loose comparison of token or signature
|
||||
|
||||
**Search:** scanner rule PHP-LOOSE-COMPARE. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain PHP-LOOSE-COMPARE` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
~~~php
|
||||
$ok = $token == $provided;
|
||||
~~~
|
||||
|
||||
**Fix:** Validate types; use hash_equals for tags, === for ordinary values and password_verify for passwords. Numeric-string semantics depend on version/operands.
|
||||
|
||||
~~~php
|
||||
$ok = is_string($provided) && hash_equals($token, $provided);
|
||||
~~~
|
||||
|
||||
**Verification:** Numbers, arrays and numeric strings cannot grant access; valid values work.
|
||||
|
||||
**Reference:** [primary source](https://www.php.net/manual/en/language.operators.comparison.php).
|
||||
|
||||
<a id="php-upload"></a>
|
||||
|
||||
## PHP-UPLOAD. Moving an uploaded file
|
||||
|
||||
**Search:** scanner rule PHP-UPLOAD. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain PHP-UPLOAD` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
~~~php
|
||||
move_uploaded_file($tmp, $webroot . $name);
|
||||
~~~
|
||||
|
||||
**Fix:** Check upload error/size/type; use non-overwriting server-generated names outside executable web roots and authorize downloads.
|
||||
|
||||
~~~php
|
||||
move_uploaded_file($validatedTmp, $serverChosenPrivatePath);
|
||||
~~~
|
||||
|
||||
**Verification:** Test upload/download, collisions, wrong owner/type and full disk. The call remains a review signal.
|
||||
|
||||
**Reference:** [primary source](https://www.php.net/manual/en/features.file-upload.php).
|
||||
|
||||
<a id="php-display-errors"></a>
|
||||
|
||||
## PHP-DISPLAY-ERRORS. PHP displays errors to clients
|
||||
|
||||
**Search:** scanner rule PHP-DISPLAY-ERRORS. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain PHP-DISPLAY-ERRORS` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
~~~php
|
||||
display_errors = On
|
||||
~~~
|
||||
|
||||
**Fix:** Disable client error output and retain redacted local logs; check effective php.ini/FPM and runtime ini_set.
|
||||
|
||||
~~~php
|
||||
display_errors = Off
|
||||
~~~
|
||||
|
||||
**Verification:** Parse/database/type errors yield expected public responses while private diagnostics remain.
|
||||
|
||||
**Reference:** [primary source](https://www.php.net/manual/en/errorfunc.configuration.php).
|
||||
|
||||
<a id="php-xss"></a>
|
||||
|
||||
## PHP-XSS. Raw data reaches HTML, attributes or JavaScript
|
||||
|
||||
**Search:** manual review; no separate scanner rule.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'echo|print|htmlspecialchars|json_encode|<script' .
|
||||
~~~
|
||||
|
||||
Identify the output context; htmlspecialchars for HTML text does not make a string safe JavaScript.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
`echo $title` inside HTML lacks encoding; JSON enters script without an appropriate serializer.
|
||||
|
||||
**Fix:** Template autoescape or htmlspecialchars with ENT_QUOTES/ENT_SUBSTITUTE and UTF-8 for HTML; separate safe JavaScript/URL handling.
|
||||
|
||||
**Verification:** Quotes, tags and Unicode render as data; legitimate formatting remains intact.
|
||||
|
||||
<details>
|
||||
<summary>Expanded example and limitations</summary>
|
||||
|
||||
```php
|
||||
// Vulnerable with untrusted title: the browser interprets it as markup.
|
||||
echo '<p>' . $title . '</p>';
|
||||
```
|
||||
|
||||
**Patch for HTML text content:**
|
||||
|
||||
```php
|
||||
echo '<p>' . htmlspecialchars($title, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8') . '</p>';
|
||||
```
|
||||
|
||||
Validate $title as a string first. Store original text and encode on output to avoid cumulative double escaping during edits. This is not JavaScript/CSS encoding or URL validation; those contexts need different mechanisms. Intentionally supported HTML requires sanitizing the permitted subset rather than turning all markup into text.
|
||||
|
||||
**Check:** <, >, &, quotes and Unicode render as text; existing records and save/open/edit cycles preserve original content.
|
||||
|
||||
</details>
|
||||
|
||||
<a id="php-session"></a>
|
||||
|
||||
## PHP-SESSION. Session fixation, strict mode and stale state
|
||||
|
||||
**Search:** manual review; no separate scanner rule.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'session_start|session_regenerate_id|session.use_strict_mode|session_id' .
|
||||
~~~
|
||||
|
||||
Trace externally supplied session IDs, login-time regeneration and role storage.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
An unknown external ID is accepted and remains unchanged after login.
|
||||
|
||||
**Fix:** session.use_strict_mode, supported regeneration with concurrent requests considered, server-derived roles and consistent Secure/HttpOnly/SameSite settings.
|
||||
|
||||
**Verification:** The old ID cannot authorize; normal parallel requests retain state.
|
||||
|
||||
**Reference:** [primary source](https://www.php.net/manual/en/session.security.ini.php).
|
||||
|
||||
<a id="php-wrappers"></a>
|
||||
|
||||
## PHP-WRAPPERS. Filesystem APIs accept URLs or wrappers
|
||||
|
||||
**Search:** manual review; no separate scanner rule.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'file_get_contents|fopen|copy\(|file_exists|is_file|phar|stream_context' .
|
||||
~~~
|
||||
|
||||
Determine whether each API accepts a path or stream URL; check installed PHP version and required wrappers.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
Users select a scheme/local path instead of an allowed object; open_basedir is not a complete sandbox.
|
||||
|
||||
**Fix:** Server-side paths derived from authorized IDs; a separate policy-constrained HTTP client for URLs; no client-selected wrapper.
|
||||
|
||||
**Verification:** Valid files load; external URLs, foreign files and unsupported schemes never reach the operation.
|
||||
|
||||
<a id="php-extract"></a>
|
||||
|
||||
## PHP-EXTRACT. extract overwrites local variables
|
||||
|
||||
**Search:** scanner rule PHP-EXTRACT. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain PHP-EXTRACT` for details. Regex: any extract(...); trusted template contexts need manual classification.
|
||||
|
||||
Additional manual search for forms outside automatic coverage:
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'extract\(|parse_str|\$\$|GLOBALS|register_globals' .
|
||||
~~~
|
||||
|
||||
Compare imported keys with authorization/config variable names; two-argument parse_str has a different risk from its historical behavior.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
`extract($_REQUEST)` overwrites locals, or `$$key` selects a sensitive variable.
|
||||
|
||||
**Fix:** Read explicit allowed fields. EXTR_SKIP reduces overwrites but does not replace schema/type and new-name controls.
|
||||
|
||||
**Verification:** Input is_admin/owner/config cannot alter access; approved values retain types.
|
||||
|
||||
**Reference:** [primary source](https://www.php.net/manual/en/function.extract.php).
|
||||
|
||||
**Scanner example before:**
|
||||
|
||||
~~~php
|
||||
extract($_POST);
|
||||
if ($is_admin) { show_private_data(); }
|
||||
~~~
|
||||
|
||||
**Fix template:**
|
||||
|
||||
~~~php
|
||||
$display_name = validate_display_name($_POST['display_name'] ?? '');
|
||||
~~~
|
||||
|
||||
Primary documentation: [reference 1](https://www.php.net/manual/en/function.extract.php).
|
||||
|
||||
<a id="php-serialize-magic"></a>
|
||||
|
||||
## PHP-SERIALIZE-MAGIC. Magic methods and trust in stored data
|
||||
|
||||
**Search:** manual review; no separate scanner rule.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e '__wakeup|__unserialize|__destruct|__toString|unserialize' .
|
||||
~~~
|
||||
|
||||
Trace PHP-OBJECT sinks to reachable classes and side effects; a database is not trusted merely because client input was stored there.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
A deserialized object performs file/network operations before its result is checked.
|
||||
|
||||
**Fix:** DTOs without type selection or side effects; separate compatible migration, not fallback to an unsafe parser.
|
||||
|
||||
**Verification:** Unknown types have no effects; legitimate legacy formats follow the migration plan.
|
||||
|
||||
<a id="php-csrf"></a>
|
||||
|
||||
## PHP-CSRF. Cookies authorize mutations without CSRF protection
|
||||
|
||||
**Search:** manual review; no separate scanner rule.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'csrf|POST|PUT|DELETE|REQUEST_METHOD|SameSite' .
|
||||
~~~
|
||||
|
||||
Review forms and cookie-authenticated JSON endpoints, middleware exceptions and Origin/Referer policies.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
The browser automatically attaches a cookie to state-changing requests from another context.
|
||||
|
||||
**Fix:** Framework CSRF tokens and architecture-appropriate origin checks. SameSite supplements, not replaces, server-side checks. Bearer APIs have a different threat context.
|
||||
|
||||
**Verification:** Wrong/missing tokens fail; normal forms and supported API clients work.
|
||||
|
||||
<a id="php-regex-error"></a>
|
||||
|
||||
## PHP-REGEX-ERROR. preg_match errors become permission
|
||||
|
||||
**Search:** manual review; no separate scanner rule.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'preg_match|preg_last_error|preg_replace' .
|
||||
~~~
|
||||
|
||||
Distinguish false, 0 and 1; find negated results and regex limits.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
An engine error on long input enters the 'prohibited content not found' branch.
|
||||
|
||||
**Fix:** Compare results strictly against 1/0/false according to meaning; fail closed on errors and bound length/complexity.
|
||||
|
||||
**Verification:** Match, no-match and engine errors produce distinct expected responses; normal Unicode remains supported.
|
||||
|
||||
**Reference:** [primary source](https://www.php.net/manual/en/function.preg-match.php).
|
||||
|
||||
<a id="php-xml-flags"></a>
|
||||
|
||||
## PHP-XML-FLAGS. XML entity substitution or DTD enabled
|
||||
|
||||
**Search:** scanner rule PHP-XML-FLAGS. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain PHP-XML-FLAGS` for details. Regex: LIBXML_NOENT/DTDLOAD/DTDATTR/DTDVALID and substituteEntities/resolveExternals=true. Numeric ini/database masks are not decoded; inspect bits against runtime constants.
|
||||
|
||||
**Vulnerable example:** NOENT substitutes entities; NONET alone does not prevent local-file access.
|
||||
|
||||
~~~php
|
||||
$doc->loadXML($xml, LIBXML_NOENT | LIBXML_DTDLOAD | LIBXML_NONET);
|
||||
~~~
|
||||
|
||||
**Fix:** Disable entity substitution/external DTD loading, bound input and check libxml version. Use LIBXML_NO_XXE where supported; NONET alone is insufficient.
|
||||
|
||||
~~~php
|
||||
$doc->resolveExternals = false;
|
||||
$doc->substituteEntities = false;
|
||||
$doc->loadXML($boundedXml, LIBXML_NONET);
|
||||
~~~
|
||||
|
||||
**Verification:** Ordinary XML works; entities/DTD read no files or network and nesting/size are limited.
|
||||
|
||||
Primary documentation: [reference 1](https://www.php.net/manual/en/libxml.constants.php), [reference 2](https://github.com/enowars/enowars7-service-oldschool#vulnerabilities).
|
||||
|
||||
<a id="php-template"></a>
|
||||
|
||||
## PHP-TEMPLATE. Template built from dynamic text
|
||||
|
||||
**Search:** scanner rule PHP-TEMPLATE. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain PHP-TEMPLATE` for details. Regex: createTemplate($...) and Smarty display/fetch with eval: or string:. Inspect variable loaders, custom filters and database templates.
|
||||
|
||||
**Vulnerable example:** When user data becomes template source, users gain the template engine's capabilities.
|
||||
|
||||
~~~php
|
||||
$template = $twig->createTemplate($profileText);
|
||||
echo $template->render($vars);
|
||||
~~~
|
||||
|
||||
**Fix:** Separate trusted template source from values; user templates need explicit sandbox/loader/function/resource policy.
|
||||
|
||||
~~~php
|
||||
echo $twig->render('profile.html.twig', ['about' => $profileText]);
|
||||
~~~
|
||||
|
||||
**Verification:** Profile template expressions remain data; private templates/files are unavailable.
|
||||
|
||||
Primary documentation: [reference 1](https://twig.symfony.com/doc/3.x/api.html#loading-templates-from-a-string).
|
||||
|
||||
<a id="php-curl-tls"></a>
|
||||
|
||||
## PHP-CURL-TLS. cURL certificate or hostname checks disabled
|
||||
|
||||
**Search:** scanner rule PHP-CURL-TLS. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain PHP-CURL-TLS` for details. Regex: CURLOPT_SSL_VERIFYPEER=false/0 and CURLOPT_SSL_VERIFYHOST=false/0/1 in arguments/setopt_array. Variable values are not evaluated.
|
||||
|
||||
**Vulnerable example:** Disabling server validation permits substitution of outbound HTTPS results.
|
||||
|
||||
~~~php
|
||||
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
|
||||
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
|
||||
~~~
|
||||
|
||||
**Fix:** Verify peer and hostname with the trusted CA; use VERIFYHOST=2, not historical ambiguous 1.
|
||||
|
||||
~~~php
|
||||
curl_setopt_array($ch, [CURLOPT_SSL_VERIFYPEER => true, CURLOPT_SSL_VERIFYHOST => 2, CURLOPT_CAINFO => $trustedCA]);
|
||||
~~~
|
||||
|
||||
**Verification:** Correct CA/host works; wrong CA/host and expiry fail without fallback.
|
||||
|
||||
Primary documentation: [reference 1](https://www.php.net/manual/en/function.curl-setopt.php).
|
||||
|
||||
<a id="php-url-include"></a>
|
||||
|
||||
## PHP-URL-INCLUDE. Remote resource inclusion enabled
|
||||
|
||||
**Search:** scanner rule PHP-URL-INCLUDE. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain PHP-URL-INCLUDE` for details. Regex: allow_url_include=On/1/true in ini/config/assignment. Review runtime overrides and effective include paths separately.
|
||||
|
||||
**Vulnerable example:** URL include increases the consequences of controlling an include/require path.
|
||||
|
||||
~~~config
|
||||
allow_url_include = On
|
||||
~~~
|
||||
|
||||
**Fix:** Disable allow_url_include in the effective SAPI config; select include paths from a closed server-side map.
|
||||
|
||||
~~~config
|
||||
allow_url_include = Off
|
||||
~~~
|
||||
|
||||
**Verification:** Normal modules load; client URLs cannot become executable code.
|
||||
|
||||
Primary documentation: [reference 1](https://www.php.net/manual/en/filesystem.configuration.php#ini.allow-url-include).
|
||||
|
||||
<a id="php-session-config"></a>
|
||||
|
||||
## PHP-SESSION-CONFIG. Weakened PHP session configuration
|
||||
|
||||
**Search:** scanner rule PHP-SESSION-CONFIG. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain PHP-SESSION-CONFIG` for details. Regex: explicit unsafe use_strict_mode/use_only_cookies/use_trans_sid values. Missing settings and ini_set argument forms need manual review.
|
||||
|
||||
**Vulnerable example:** Attacker-selected session IDs and IDs in URLs enable fixation or leakage.
|
||||
|
||||
~~~config
|
||||
session.use_strict_mode = 0
|
||||
session.use_only_cookies = 0
|
||||
session.use_trans_sid = 1
|
||||
~~~
|
||||
|
||||
**Fix:** Enable strict mode and cookie-only transport, disable URL rewriting and regenerate IDs at login; review custom handlers/cookies.
|
||||
|
||||
~~~config
|
||||
session.use_strict_mode = 1
|
||||
session.use_only_cookies = 1
|
||||
session.use_trans_sid = 0
|
||||
~~~
|
||||
|
||||
**Verification:** Unknown fixed IDs fail, login changes the ID, URLs/logs contain no IDs and sessions work.
|
||||
|
||||
Primary documentation: [reference 1](https://www.php.net/manual/en/session.configuration.php).
|
||||
|
||||
<a id="php-mass-assign"></a>
|
||||
|
||||
## PHP-MASS-ASSIGN. Array keys choose columns and privileges
|
||||
|
||||
**Search:** manual review; no separate scanner rule.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e '\$_(POST|GET|REQUEST)|array_keys|array_merge|profileData|UPDATE|SET|fill\(|update\(' .
|
||||
~~~
|
||||
|
||||
Trace keys as well as values from requests into UPDATE/ORM and owner/admin/association assignment. Review nested fields and numeric indices.
|
||||
|
||||
**Vulnerable example:** SQL values are parameterized but column names come from request keys; role fields or relationships to foreign objects are updated wholesale.
|
||||
|
||||
**Fix:** Explicitly map allowed input fields to fixed columns and types. Check privileges, owners and relationships separately; placeholders do not escape SQL identifiers.
|
||||
|
||||
**Verification:** Unknown columns, administrative fields and foreign relationships fail without mutation; allowed fields persist.
|
||||
|
||||
Reference: [OWASP Mass Assignment](https://cheatsheetseries.owasp.org/cheatsheets/Mass_Assignment_Cheat_Sheet.html). The explanation and adaptation recipe were written for this catalog.
|
||||
|
||||
**A/D variant:** Oldschool's mass update could change an administrative relationship; column names also entered SQL without restriction. [Author description](https://github.com/enowars/enowars7-service-oldschool#vulnerabilities).
|
||||
|
||||
<a id="php-ldap-filter"></a>
|
||||
|
||||
## PHP-LDAP-FILTER. LDAP filter concatenates a PHP variable
|
||||
|
||||
**Search:** scanner rule PHP-LDAP-FILTER. Use `--explain PHP-LDAP-FILTER` for the exact detector contract. Regex with lexical exclusions: ldap_search/list/read with simple first two arguments and a string concatenated directly with a variable as the third argument. Variables may already be escaped; prebuilt filters and interpolation need manual review.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
~~~php
|
||||
ldap_search($conn, $base, '(uid=' . $name . ')');
|
||||
~~~
|
||||
|
||||
**Fix:** Escape values for LDAP filter context, not DN context; keep attribute names and search scope trusted.
|
||||
|
||||
~~~php
|
||||
$filter = '(uid=' . ldap_escape($name, '', LDAP_ESCAPE_FILTER) . ')';
|
||||
ldap_search($conn, $base, $filter);
|
||||
~~~
|
||||
|
||||
**Verification:** LDAP metacharacters in a value do not widen results; authorized lookups work.
|
||||
|
||||
[Primary reference 1](https://www.php.net/manual/en/function.ldap-escape.php)
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,474 @@
|
||||
<a id="ruby--rails-find-fix-and-verify"></a>
|
||||
|
||||
# Ruby / Rails: поиск и исправление
|
||||
|
||||
[English](ruby.md) | Русский
|
||||
|
||||
[Вся база](README-RU.md) · [Сканер](../offline-scanner-RU.md) · [Проверка патча](../patch-validation-RU.md)
|
||||
|
||||
18 разделов. Формат: **Поиск → Уязвимый вариант → Исправление → Проверка**.
|
||||
Команды `rg` выполняются в корне локальной копии сервиса и только читают файлы. Субъект/владелец определяется по проверенной сессии, а не данным запроса. Примеры нужно адаптировать к реальным API и контракту.
|
||||
|
||||
Автоматические находки — ограниченные синтаксические сигналы для проверки. AST-анализ не разрешает типы и не отслеживает данные между функциями; regex не заменяет парсер языка. Комментарии, строки и одноимённые пользовательские API могут давать совпадения. Проверьте фактическое исполнение, входные данные, авторизацию и границы доверия.
|
||||
|
||||
<a id="contents"></a>
|
||||
|
||||
## Содержание
|
||||
|
||||
- [RUBY-OBJECT — Ruby Marshal/небезопасный YAML](#ruby-object)
|
||||
- [RUBY-SHELL — Shell-строка Ruby](#ruby-shell)
|
||||
- [RUBY-EVAL — Ruby eval/ERB из данных](#ruby-eval)
|
||||
- [RUBY-PERMIT-ALL — Rails разрешает все параметры](#ruby-permit-all)
|
||||
- [RUBY-CONSTANTIZE — Строка выбирает Ruby-класс](#ruby-constantize)
|
||||
- [RUBY-HTML-SAFE — Ruby html_safe/raw](#ruby-html-safe)
|
||||
- [RUBY-SQL — Интерполяция в SQL Ruby](#ruby-sql)
|
||||
- [RUBY-IDOR — ActiveRecord find без области владельца](#ruby-idor)
|
||||
- [RUBY-PATH — send_file и File.join на имени клиента](#ruby-path)
|
||||
- [RUBY-REDIRECT — redirect_to принимает внешний return_to](#ruby-redirect)
|
||||
- [RUBY-CSRF — Пропущенная forgery protection](#ruby-csrf)
|
||||
- [RUBY-REGEX-ANCHOR — ^ и $ проверяют строку внутри многострочного поля](#ruby-regex-anchor)
|
||||
- [RUBY-YAML-VERSION — YAML.load зависит от версии Psych](#ruby-yaml-version)
|
||||
- [RUBY-DESERIALIZE-COOKIE — Подписанная cookie не обязательно секретна](#ruby-deserialize-cookie)
|
||||
- [RUBY-SSRF — Net::HTTP/open-uri на вводе клиента](#ruby-ssrf)
|
||||
- [RUBY-CALLBACKS — Callbacks выполняют эффект до проверки прав](#ruby-callbacks)
|
||||
- [RUBY-TLS — Ruby HTTPS без проверки peer](#ruby-tls)
|
||||
- [RUBY-REDIRECT-INPUT — Rails redirect напрямую принимает параметры запроса](#ruby-redirect-input)
|
||||
|
||||
<a id="ruby-object"></a>
|
||||
|
||||
<a id="ruby-object-ruby-marshal-or-unsafe-yaml"></a>
|
||||
|
||||
## RUBY-OBJECT. Ruby Marshal/небезопасный YAML
|
||||
|
||||
**Поиск:** скрипт, правило RUBY-OBJECT. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain RUBY-OBJECT. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
~~~ruby
|
||||
record = Marshal.load(payload)
|
||||
~~~
|
||||
|
||||
**Исправление:** Внешний формат — JSON или ограниченный YAML.safe_load с явной политикой классов/aliases и схемой; legacy мигрировать отдельно.
|
||||
|
||||
~~~ruby
|
||||
record = JSON.parse(payload) # validate DTO schema and size
|
||||
~~~
|
||||
|
||||
**Проверка:** Произвольные объекты не создаются; старые законные данные сохранены.
|
||||
|
||||
<a id="ruby-shell"></a>
|
||||
|
||||
<a id="ruby-shell-ruby-shell-string"></a>
|
||||
|
||||
## RUBY-SHELL. Shell-строка Ruby
|
||||
|
||||
**Поиск:** скрипт, правило RUBY-SHELL. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain RUBY-SHELL. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
~~~ruby
|
||||
system(command)
|
||||
~~~
|
||||
|
||||
**Исправление:** Фиксированный executable + отдельные argv; запрет выбора опасных опций. Backticks и %x тоже вызывают shell.
|
||||
|
||||
~~~ruby
|
||||
system("/usr/bin/file", "--", filename)
|
||||
~~~
|
||||
|
||||
**Проверка:** Спецсимволы не становятся командами; штатные файлы обрабатываются.
|
||||
|
||||
<a id="ruby-eval"></a>
|
||||
|
||||
<a id="ruby-eval-ruby-evalerb-from-data"></a>
|
||||
|
||||
## RUBY-EVAL. Ruby eval/ERB из данных
|
||||
|
||||
**Поиск:** скрипт, правило RUBY-EVAL. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain RUBY-EVAL. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
~~~ruby
|
||||
result = eval(input)
|
||||
~~~
|
||||
|
||||
**Исправление:** Данные не исполнять; фиксированный ERB-шаблон + переменные или ограниченный парсер.
|
||||
|
||||
~~~ruby
|
||||
result = JSON.parse(input) # validate expected schema
|
||||
~~~
|
||||
|
||||
**Проверка:** Синтаксис Ruby не исполняется; штатный формат читается.
|
||||
|
||||
<a id="ruby-permit-all"></a>
|
||||
|
||||
<a id="ruby-permit-all-rails-permits-all-parameters"></a>
|
||||
|
||||
## RUBY-PERMIT-ALL. Rails разрешает все параметры
|
||||
|
||||
**Поиск:** скрипт, правило RUBY-PERMIT-ALL. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain RUBY-PERMIT-ALL. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
~~~ruby
|
||||
attrs = params.permit!
|
||||
~~~
|
||||
|
||||
**Исправление:** Явный набор редактируемых полей, owner/role из сервера; nested params ограничить отдельно.
|
||||
|
||||
~~~ruby
|
||||
attrs = params.require(:note).permit(:title, :body)
|
||||
~~~
|
||||
|
||||
**Проверка:** Owner/role/вложенные неизвестные поля не применяются; допустимое частичное изменение работает.
|
||||
|
||||
**Основание:** [первичный материал](https://guides.rubyonrails.org/action_controller_overview.html#strong-parameters).
|
||||
|
||||
<a id="ruby-constantize"></a>
|
||||
|
||||
<a id="ruby-constantize-string-selects-a-ruby-class"></a>
|
||||
|
||||
## RUBY-CONSTANTIZE. Строка выбирает Ruby-класс
|
||||
|
||||
**Поиск:** скрипт, правило RUBY-CONSTANTIZE. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain RUBY-CONSTANTIZE. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
~~~ruby
|
||||
klass = params[:type].constantize
|
||||
~~~
|
||||
|
||||
**Исправление:** Фиксированная карта типов с безопасным DTO. safe_constantize меняет обработку ошибки поиска, не ограничивает выбор класса.
|
||||
|
||||
~~~ruby
|
||||
klass = {"text" => TextNote}.fetch(validated_type)
|
||||
~~~
|
||||
|
||||
**Проверка:** Неизвестный тип не создаёт объектов; законные типы совместимы.
|
||||
|
||||
**Основание:** [первичный материал](https://api.rubyonrails.org/classes/ActiveSupport/Inflector.html).
|
||||
|
||||
<a id="ruby-html-safe"></a>
|
||||
|
||||
<a id="ruby-html-safe-ruby-html_saferaw"></a>
|
||||
|
||||
## RUBY-HTML-SAFE. Ruby html_safe/raw
|
||||
|
||||
**Поиск:** скрипт, правило RUBY-HTML-SAFE. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain RUBY-HTML-SAFE. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
~~~ruby
|
||||
value = params[:text].html_safe
|
||||
~~~
|
||||
|
||||
**Исправление:** Autoescape по контексту; для предусмотренного HTML sanitizer. Не путать обработку HTML с исходником ERB.
|
||||
|
||||
~~~ruby
|
||||
value = params[:text] # render with automatic escaping
|
||||
~~~
|
||||
|
||||
**Проверка:** Теги и кавычки — текст, разрешённое форматирование сохранилось.
|
||||
|
||||
**Основание:** [первичный материал](https://guides.rubyonrails.org/security.html).
|
||||
|
||||
<a id="ruby-sql"></a>
|
||||
|
||||
<a id="ruby-sql-ruby-sql-interpolation"></a>
|
||||
|
||||
## RUBY-SQL. Интерполяция в SQL Ruby
|
||||
|
||||
**Поиск:** скрипт, правило RUBY-SQL. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain RUBY-SQL. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
~~~ruby
|
||||
Note.where("title = '#{title}'")
|
||||
~~~
|
||||
|
||||
**Исправление:** Параметры/hash conditions; сортировка и имена полей из фиксированной карты. Сырой SQL внутри параметра не исправляется сам.
|
||||
|
||||
~~~ruby
|
||||
Note.where(title: title, owner_id: current_user.id)
|
||||
~~~
|
||||
|
||||
**Проверка:** Кавычки — данные; чужой owner не читается.
|
||||
|
||||
**Основание:** [первичный материал](https://guides.rubyonrails.org/active_record_querying.html).
|
||||
|
||||
<a id="ruby-idor"></a>
|
||||
|
||||
<a id="ruby-idor-activerecord-lookup-outside-the-owners-scope"></a>
|
||||
|
||||
## RUBY-IDOR. ActiveRecord find без области владельца
|
||||
|
||||
**Поиск:** вручную; отдельного правила сканера нет.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e '\.find\(|find_by|params\[:id\]|current_user' .
|
||||
~~~
|
||||
|
||||
Сверить read/update/destroy/export и association scope; strong params не выполняют авторизацию объекта.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
Note.find(params[:id]) получает запись любого пользователя.
|
||||
|
||||
**Исправление:** Поиск через current_user.notes либо явная policy/shared-access область; owner не из params.
|
||||
|
||||
**Проверка:** Своё/чужое/аноним, экспорт/удаление и предусмотренное sharing.
|
||||
|
||||
**Основание:** [первичный материал](https://cheatsheetseries.owasp.org/cheatsheets/Authorization_Cheat_Sheet.html).
|
||||
|
||||
<a id="ruby-path"></a>
|
||||
|
||||
<a id="ruby-path-client-filenames-reach-send_file-and-filejoin"></a>
|
||||
|
||||
## RUBY-PATH. send_file и File.join на имени клиента
|
||||
|
||||
**Поиск:** вручную; отдельного правила сканера нет.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'send_file|File.join|File.read|Pathname|realpath' .
|
||||
~~~
|
||||
|
||||
Проследить filename до открытия; join не проверяет containment, realpath не убирает TOCTOU.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
send_file(params[:path]) выбирает произвольный ресурс.
|
||||
|
||||
**Исправление:** Серверный storage ID после policy check, контролируемый root и links, лимит/Content-Disposition.
|
||||
|
||||
**Проверка:** Чужой ID, абсолютный путь, ссылка наружу и штатная загрузка.
|
||||
|
||||
<a id="ruby-redirect"></a>
|
||||
|
||||
<a id="ruby-redirect-redirect_to-accepts-an-external-return_to"></a>
|
||||
|
||||
## RUBY-REDIRECT. redirect_to принимает внешний return_to
|
||||
|
||||
**Поиск:** вручную; отдельного правила сканера нет.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'redirect_to|return_to|allow_other_host|url_from' .
|
||||
~~~
|
||||
|
||||
Сверить версию Rails и настройки open-redirect protection; raw return_to не превращать в доверенный URL.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
Внешнее назначение разрешено параметром/allow_other_host.
|
||||
|
||||
**Исправление:** Серверная карта путей либо штатный безопасный механизм версии Rails с проверкой host.
|
||||
|
||||
**Проверка:** Внутренний переход работает, внешний origin и неоднозначный путь отклоняются.
|
||||
|
||||
**Основание:** [первичный материал](https://guides.rubyonrails.org/security.html).
|
||||
|
||||
<a id="ruby-csrf"></a>
|
||||
|
||||
<a id="ruby-csrf-rails-controller-disables-csrf"></a>
|
||||
|
||||
## RUBY-CSRF. Пропущенная forgery protection
|
||||
|
||||
**Поиск:** скрипт, правило RUBY-CSRF. Запуск: python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain RUBY-CSRF. Regex: skip_forgery_protection, skip_before_action/filter :verify_authenticity_token и allow_forgery_protection=false. only/except анализировать вручную.
|
||||
|
||||
Дополнительный ручной поиск для непокрытых форм:
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'skip_forgery_protection|skip_before_action|protect_from_forgery|csrf' .
|
||||
~~~
|
||||
|
||||
Проверить исключения controller и применение cookie auth на JSON endpoint.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
Cookie-сессия сохраняется, а CSRF middleware отключено ради удобства API.
|
||||
|
||||
**Исправление:** Восстановить проверку для cookie-auth; token API отделить явно, не отключать весь controller.
|
||||
|
||||
**Проверка:** Правильный token принимается, чужой origin/пустой token отклоняются; API-клиент совместим.
|
||||
|
||||
**Основание:** [первичный материал](https://guides.rubyonrails.org/security.html).
|
||||
|
||||
|
||||
**Сигнал сканера — пример до:**
|
||||
|
||||
~~~ruby
|
||||
skip_forgery_protection
|
||||
skip_before_action :verify_authenticity_token
|
||||
~~~
|
||||
|
||||
**Шаблон исправления:**
|
||||
|
||||
~~~ruby
|
||||
protect_from_forgery with: :exception
|
||||
~~~
|
||||
|
||||
Первичная документация: [документация 1](https://api.rubyonrails.org/classes/ActionController/RequestForgeryProtection/ClassMethods.html).
|
||||
|
||||
<a id="ruby-regex-anchor"></a>
|
||||
|
||||
<a id="ruby-regex-anchor--and--match-a-line-inside-a-multiline-value"></a>
|
||||
|
||||
## RUBY-REGEX-ANCHOR. ^ и $ проверяют строку внутри многострочного поля
|
||||
|
||||
**Поиск:** вручную; отдельного правила сканера нет.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'validates|format:|Regexp|match\?|\^|\$' .
|
||||
~~~
|
||||
|
||||
Сравнить начало/конец строки и всего поля; проверить переводы строк и timeout regexp.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
Валидатор имени использует ^...$ и принимает подходящую строку внутри большего значения.
|
||||
|
||||
**Исправление:** Для целого значения \A и \z, проверка типа/длины; при разрешённых multiline выбрать соответствующий контракт.
|
||||
|
||||
**Проверка:** Переводы строк в начале/конце/середине и штатный Unicode.
|
||||
|
||||
**Основание:** [первичный материал](https://guides.rubyonrails.org/security.html).
|
||||
|
||||
<a id="ruby-yaml-version"></a>
|
||||
|
||||
<a id="ruby-yaml-version-yamlload-behavior-depends-on-psych-version"></a>
|
||||
|
||||
## RUBY-YAML-VERSION. YAML.load зависит от версии Psych
|
||||
|
||||
**Поиск:** вручную; отдельного правила сканера нет.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'YAML.load|Psych.load|safe_load|unsafe_load|Gemfile.lock' .
|
||||
~~~
|
||||
|
||||
Сверить фактическую Psych/Ruby версию и allowed classes/aliases; RUBY-OBJECT намеренно не считает каждый load unsafe.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
Ожидают safe semantics нового Psych, запускают старую версию с созданием произвольных объектов.
|
||||
|
||||
**Исправление:** Явный safe_load с минимальным набором типов и схемой; фиксировать совместимые зависимости локально.
|
||||
|
||||
**Проверка:** Произвольный класс/alias и старый допустимый документ; на фактическом runtime.
|
||||
|
||||
**Основание:** [первичный материал](https://docs.ruby-lang.org/en/3.3/Psych.html).
|
||||
|
||||
<a id="ruby-deserialize-cookie"></a>
|
||||
|
||||
<a id="ruby-deserialize-cookie-signed-cookies-are-not-necessarily-confidential"></a>
|
||||
|
||||
## RUBY-DESERIALIZE-COOKIE. Подписанная cookie не обязательно секретна
|
||||
|
||||
**Поиск:** вручную; отдельного правила сканера нет.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'cookies.signed|cookies.encrypted|session\[|secret_key_base' .
|
||||
~~~
|
||||
|
||||
Посмотреть, что хранится в cookie; отличить целостность от шифрования и ключ подписи от доступа к объекту.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
В signed cookie кладут приватный текст, полагая что подпись его скрывает.
|
||||
|
||||
**Исправление:** Для конфиденциальности encrypted cookie либо серверный session store; минимальные данные и срок, безопасная ротация ключей.
|
||||
|
||||
**Проверка:** Обычная сессия читается, клиент не видит приватное содержимое, изменённая cookie отвергается.
|
||||
|
||||
<a id="ruby-ssrf"></a>
|
||||
|
||||
<a id="ruby-ssrf-client-input-reaches-nethttp-or-open-uri"></a>
|
||||
|
||||
## RUBY-SSRF. Net::HTTP/open-uri на вводе клиента
|
||||
|
||||
**Поиск:** вручную; отдельного правила сканера нет.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'Net::HTTP|URI.open|open-uri|Faraday|HTTParty' .
|
||||
~~~
|
||||
|
||||
Найти URL parser, redirects и DNS в реальном adapter.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
URL/redirect ведёт к внутреннему ресурсу с доверием к приложению.
|
||||
|
||||
**Исправление:** Фиксированное назначение либо единая политика всех переходов/соединения и лимиты; URI.parse не авторизация.
|
||||
|
||||
**Проверка:** Mock redirect/DNS, запрещённая схема, timeout и штатный upstream.
|
||||
|
||||
**Основание:** [первичный материал](https://cheatsheetseries.owasp.org/cheatsheets/Server_Side_Request_Forgery_Prevention_Cheat_Sheet.html).
|
||||
|
||||
<a id="ruby-callbacks"></a>
|
||||
|
||||
<a id="ruby-callbacks-callbacks-cause-effects-before-authorization"></a>
|
||||
|
||||
## RUBY-CALLBACKS. Callbacks выполняют эффект до проверки прав
|
||||
|
||||
**Поиск:** вручную; отдельного правила сканера нет.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'before_save|after_save|after_commit|after_find|validate|authorize' .
|
||||
~~~
|
||||
|
||||
Сопоставить policy check, instantiation, callbacks и transaction boundary.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
Модель пишет файл/отправляет задачу в callback до auth либо до commit.
|
||||
|
||||
**Исправление:** Авторизация до изменения; внешние эффекты после подтверждённого commit, идемпотентность и компенсация по контракту.
|
||||
|
||||
**Проверка:** Rollback/отказ не оставляет эффектов, повторная задача не дублирует результат.
|
||||
|
||||
<a id="ruby-tls"></a>
|
||||
|
||||
<a id="ruby-tls-ruby-https-peer-verification-disabled"></a>
|
||||
|
||||
## RUBY-TLS. Ruby HTTPS без проверки peer
|
||||
|
||||
**Поиск:** скрипт, правило RUBY-TLS. Запуск: python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain RUBY-TLS. Regex: VERIFY_NONE. Не определяет, применён ли объект к реальному соединению.
|
||||
|
||||
**Уязвимый вариант:** VERIFY_NONE делает TLS-соединение непроверенным.
|
||||
|
||||
~~~ruby
|
||||
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
|
||||
~~~
|
||||
|
||||
**Исправление:** Вернуть проверку peer/hostname и доверенный CA; проверить настройки используемого HTTP-клиента.
|
||||
|
||||
~~~ruby
|
||||
http.verify_mode = OpenSSL::SSL::VERIFY_PEER
|
||||
http.ca_file = trusted_ca_file
|
||||
~~~
|
||||
|
||||
**Проверка:** Штатный сервер доступен, неверный сертификат не даёт полезного ответа.
|
||||
|
||||
Первичная документация: [документация 1](https://docs.ruby-lang.org/en/master/OpenSSL/SSL/SSLContext.html).
|
||||
|
||||
<a id="ruby-redirect-input"></a>
|
||||
|
||||
<a id="ruby-redirect-input-rails-redirect-takes-request-params-directly"></a>
|
||||
|
||||
## RUBY-REDIRECT-INPUT. Rails redirect напрямую принимает параметры запроса
|
||||
|
||||
**Поиск:** правило сканера RUBY-REDIRECT-INPUT. Точный контракт детектора: `--explain RUBY-REDIRECT-INPUT`. Regex с лексическими исключениями: redirect_to с params[...] или request.params[...], с необязательной открывающей скобкой. Defaults фреймворка могут уже запрещать внешние hosts; aliases, вспомогательные функции и allow_other_host требуют проверки.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
~~~ruby
|
||||
redirect_to params[:next]
|
||||
~~~
|
||||
|
||||
**Исправление:** Используйте маршруты, выбранные сервером, или явную политику redirect; сохраняйте проверки host в Rails и учитывайте установленную версию фреймворка.
|
||||
|
||||
~~~ruby
|
||||
redirect_to account_path
|
||||
~~~
|
||||
|
||||
**Проверка:** Чужие адреса и адреса вида //host отклоняются; обычная навигация работает.
|
||||
|
||||
[Первичный источник 1](https://api.rubyonrails.org/classes/ActionController/Redirecting.html)
|
||||
@@ -0,0 +1,431 @@
|
||||
# Ruby / Rails: find, fix and verify
|
||||
|
||||
English | [Русский](ruby-RU.md)
|
||||
|
||||
[Catalog](README.md) · [Scanner](../offline-scanner.md) · [Patch verification](../patch-validation.md)
|
||||
|
||||
18 sections. Each follows **Search → Vulnerable example → Fix → Verification**.
|
||||
Run `rg` from a local service checkout; searches only read files. Derive the actor/owner from a verified session, not request data. Adapt examples to the actual API and contract.
|
||||
|
||||
## Contents
|
||||
|
||||
- [RUBY-OBJECT — Ruby Marshal or unsafe YAML](#ruby-object)
|
||||
- [RUBY-SHELL — Ruby shell string](#ruby-shell)
|
||||
- [RUBY-EVAL — Ruby eval/ERB from data](#ruby-eval)
|
||||
- [RUBY-PERMIT-ALL — Rails permits all parameters](#ruby-permit-all)
|
||||
- [RUBY-CONSTANTIZE — String selects a Ruby class](#ruby-constantize)
|
||||
- [RUBY-HTML-SAFE — Ruby html_safe/raw](#ruby-html-safe)
|
||||
- [RUBY-SQL — Ruby SQL interpolation](#ruby-sql)
|
||||
- [RUBY-IDOR — ActiveRecord lookup outside the owner's scope](#ruby-idor)
|
||||
- [RUBY-PATH — Client filenames reach send_file and File.join](#ruby-path)
|
||||
- [RUBY-REDIRECT — redirect_to accepts an external return_to](#ruby-redirect)
|
||||
- [RUBY-CSRF — Rails controller disables CSRF](#ruby-csrf)
|
||||
- [RUBY-REGEX-ANCHOR — ^ and $ match a line inside a multiline value](#ruby-regex-anchor)
|
||||
- [RUBY-YAML-VERSION — YAML.load behavior depends on Psych version](#ruby-yaml-version)
|
||||
- [RUBY-DESERIALIZE-COOKIE — Signed cookies are not necessarily confidential](#ruby-deserialize-cookie)
|
||||
- [RUBY-SSRF — Client input reaches Net::HTTP or open-uri](#ruby-ssrf)
|
||||
- [RUBY-CALLBACKS — Callbacks cause effects before authorization](#ruby-callbacks)
|
||||
- [RUBY-TLS — Ruby HTTPS peer verification disabled](#ruby-tls)
|
||||
- [RUBY-REDIRECT-INPUT — Rails redirect takes request params directly](#ruby-redirect-input)
|
||||
|
||||
<a id="ruby-object"></a>
|
||||
|
||||
## RUBY-OBJECT. Ruby Marshal or unsafe YAML
|
||||
|
||||
**Search:** scanner rule RUBY-OBJECT. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain RUBY-OBJECT` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
~~~ruby
|
||||
record = Marshal.load(payload)
|
||||
~~~
|
||||
|
||||
**Fix:** Use JSON or bounded YAML.safe_load with class/alias policy and schema; migrate trusted legacy data separately.
|
||||
|
||||
~~~ruby
|
||||
record = JSON.parse(payload) # validate DTO schema and size
|
||||
~~~
|
||||
|
||||
**Verification:** Arbitrary objects are not built; old valid data works.
|
||||
|
||||
<a id="ruby-shell"></a>
|
||||
|
||||
## RUBY-SHELL. Ruby shell string
|
||||
|
||||
**Search:** scanner rule RUBY-SHELL. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain RUBY-SHELL` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
~~~ruby
|
||||
system(command)
|
||||
~~~
|
||||
|
||||
**Fix:** Use fixed executable plus separate validated argv; backticks and %x also invoke shell.
|
||||
|
||||
~~~ruby
|
||||
system("/usr/bin/file", "--", filename)
|
||||
~~~
|
||||
|
||||
**Verification:** Metacharacters cannot become commands; normal files work.
|
||||
|
||||
<a id="ruby-eval"></a>
|
||||
|
||||
## RUBY-EVAL. Ruby eval/ERB from data
|
||||
|
||||
**Search:** scanner rule RUBY-EVAL. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain RUBY-EVAL` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
~~~ruby
|
||||
result = eval(input)
|
||||
~~~
|
||||
|
||||
**Fix:** Use trusted templates plus values or a restricted parser instead of executing data.
|
||||
|
||||
~~~ruby
|
||||
result = JSON.parse(input) # validate expected schema
|
||||
~~~
|
||||
|
||||
**Verification:** Ruby syntax stays data; normal input parses.
|
||||
|
||||
<a id="ruby-permit-all"></a>
|
||||
|
||||
## RUBY-PERMIT-ALL. Rails permits all parameters
|
||||
|
||||
**Search:** scanner rule RUBY-PERMIT-ALL. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain RUBY-PERMIT-ALL` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
~~~ruby
|
||||
attrs = params.permit!
|
||||
~~~
|
||||
|
||||
**Fix:** Allowlist editable fields; choose owner/role server-side and constrain nested params separately.
|
||||
|
||||
~~~ruby
|
||||
attrs = params.require(:note).permit(:title, :body)
|
||||
~~~
|
||||
|
||||
**Verification:** Owner/role/unknown nested fields do not apply; valid partial edits work.
|
||||
|
||||
**Reference:** [primary source](https://guides.rubyonrails.org/action_controller_overview.html#strong-parameters).
|
||||
|
||||
<a id="ruby-constantize"></a>
|
||||
|
||||
## RUBY-CONSTANTIZE. String selects a Ruby class
|
||||
|
||||
**Search:** scanner rule RUBY-CONSTANTIZE. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain RUBY-CONSTANTIZE` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
~~~ruby
|
||||
klass = params[:type].constantize
|
||||
~~~
|
||||
|
||||
**Fix:** Use a fixed map of allowed DTO types; safe_constantize only changes lookup errors, not the allowed classes.
|
||||
|
||||
~~~ruby
|
||||
klass = {"text" => TextNote}.fetch(validated_type)
|
||||
~~~
|
||||
|
||||
**Verification:** Unknown types cannot create objects; valid types remain compatible.
|
||||
|
||||
**Reference:** [primary source](https://api.rubyonrails.org/classes/ActiveSupport/Inflector.html).
|
||||
|
||||
<a id="ruby-html-safe"></a>
|
||||
|
||||
## RUBY-HTML-SAFE. Ruby html_safe/raw
|
||||
|
||||
**Search:** scanner rule RUBY-HTML-SAFE. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain RUBY-HTML-SAFE` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
~~~ruby
|
||||
value = params[:text].html_safe
|
||||
~~~
|
||||
|
||||
**Fix:** Use context-appropriate autoescape or a sanitizer for permitted HTML; HTML data is not ERB source.
|
||||
|
||||
~~~ruby
|
||||
value = params[:text] # render with automatic escaping
|
||||
~~~
|
||||
|
||||
**Verification:** Tags/quotes remain text and approved formatting works.
|
||||
|
||||
**Reference:** [primary source](https://guides.rubyonrails.org/security.html).
|
||||
|
||||
<a id="ruby-sql"></a>
|
||||
|
||||
## RUBY-SQL. Ruby SQL interpolation
|
||||
|
||||
**Search:** scanner rule RUBY-SQL. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain RUBY-SQL` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
~~~ruby
|
||||
Note.where("title = '#{title}'")
|
||||
~~~
|
||||
|
||||
**Fix:** Bind values with the ORM/driver API; select identifiers from a server allowlist.
|
||||
|
||||
~~~ruby
|
||||
Note.where(title: title, owner_id: current_user.id)
|
||||
~~~
|
||||
|
||||
**Verification:** Quotes remain values and tenant/owner conditions hold.
|
||||
|
||||
**Reference:** [primary source](https://guides.rubyonrails.org/active_record_querying.html).
|
||||
|
||||
<a id="ruby-idor"></a>
|
||||
|
||||
## RUBY-IDOR. ActiveRecord lookup outside the owner's scope
|
||||
|
||||
**Search:** manual review; no separate scanner rule.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e '\.find\(|find_by|params\[:id\]|current_user' .
|
||||
~~~
|
||||
|
||||
Review read/update/destroy/export and association scopes; strong parameters do not authorize an object.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
`Note.find(params[:id])` can retrieve any user's record.
|
||||
|
||||
**Fix:** Query through `current_user.notes` or an explicit policy/shared-access scope; never take the owner from request parameters.
|
||||
|
||||
**Verification:** Owner, other user, anonymous caller, export/deletion and intended sharing.
|
||||
|
||||
**Reference:** [primary source](https://cheatsheetseries.owasp.org/cheatsheets/Authorization_Cheat_Sheet.html).
|
||||
|
||||
<a id="ruby-path"></a>
|
||||
|
||||
## RUBY-PATH. Client filenames reach send_file and File.join
|
||||
|
||||
**Search:** manual review; no separate scanner rule.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'send_file|File.join|File.read|Pathname|realpath' .
|
||||
~~~
|
||||
|
||||
Trace the filename to the open operation; join does not enforce containment, and realpath alone does not prevent TOCTOU.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
`send_file(params[:path])` selects an arbitrary resource.
|
||||
|
||||
**Fix:** Resolve a server-side storage ID after policy checks; control the root and symlinks, bound the response and set Content-Disposition.
|
||||
|
||||
**Verification:** Another owner's ID, absolute path, outward symlink and legitimate download.
|
||||
|
||||
<a id="ruby-redirect"></a>
|
||||
|
||||
## RUBY-REDIRECT. redirect_to accepts an external return_to
|
||||
|
||||
**Search:** manual review; no separate scanner rule.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'redirect_to|return_to|allow_other_host|url_from' .
|
||||
~~~
|
||||
|
||||
Check the installed Rails version and open-redirect protection settings; a raw return_to value is not a trusted URL.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
A parameter or `allow_other_host` permits an external destination.
|
||||
|
||||
**Fix:** Use a server-side route map or the installed Rails version's safe redirect mechanism with host validation.
|
||||
|
||||
**Verification:** Internal navigation works; external origins and ambiguous paths fail.
|
||||
|
||||
**Reference:** [primary source](https://guides.rubyonrails.org/security.html).
|
||||
|
||||
<a id="ruby-csrf"></a>
|
||||
|
||||
## RUBY-CSRF. Rails controller disables CSRF
|
||||
|
||||
**Search:** scanner rule RUBY-CSRF. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain RUBY-CSRF` for details. Regex: skip_forgery_protection, skip_before_action/filter :verify_authenticity_token and allow_forgery_protection=false. Review only/except conditions.
|
||||
|
||||
Additional manual search for forms outside automatic coverage:
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'skip_forgery_protection|skip_before_action|protect_from_forgery|csrf' .
|
||||
~~~
|
||||
|
||||
Review controller exceptions and cookie authentication on JSON endpoints.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
The cookie session remains active while CSRF middleware is disabled for API convenience.
|
||||
|
||||
**Fix:** Restore browser CSRF; narrow exceptions to an independently authenticated stateless API/webhook.
|
||||
|
||||
**Verification:** Valid POST works; missing/wrong authenticity token fails; authorized webhooks work.
|
||||
|
||||
**Reference:** [primary source](https://guides.rubyonrails.org/security.html).
|
||||
|
||||
**Scanner example before:**
|
||||
|
||||
~~~ruby
|
||||
skip_forgery_protection
|
||||
skip_before_action :verify_authenticity_token
|
||||
~~~
|
||||
|
||||
**Fix template:**
|
||||
|
||||
~~~ruby
|
||||
protect_from_forgery with: :exception
|
||||
~~~
|
||||
|
||||
Primary documentation: [reference 1](https://api.rubyonrails.org/classes/ActionController/RequestForgeryProtection/ClassMethods.html).
|
||||
|
||||
<a id="ruby-regex-anchor"></a>
|
||||
|
||||
## RUBY-REGEX-ANCHOR. ^ and $ match a line inside a multiline value
|
||||
|
||||
**Search:** manual review; no separate scanner rule.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'validates|format:|Regexp|match\?|\^|\$' .
|
||||
~~~
|
||||
|
||||
Distinguish line boundaries from whole-field boundaries; test newlines and regexp timeouts.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
A name validator uses ^...$ and accepts one matching line inside a larger value.
|
||||
|
||||
**Fix:** Use `\A` and `\z` for the whole value, plus type/length checks; explicitly define the contract if multiline input is allowed.
|
||||
|
||||
**Verification:** Newlines at the beginning, end and middle, plus ordinary Unicode.
|
||||
|
||||
**Reference:** [primary source](https://guides.rubyonrails.org/security.html).
|
||||
|
||||
<a id="ruby-yaml-version"></a>
|
||||
|
||||
## RUBY-YAML-VERSION. YAML.load behavior depends on Psych version
|
||||
|
||||
**Search:** manual review; no separate scanner rule.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'YAML.load|Psych.load|safe_load|unsafe_load|Gemfile.lock' .
|
||||
~~~
|
||||
|
||||
Check the actual Psych/Ruby version and permitted classes/aliases; RUBY-OBJECT deliberately does not classify every load as unsafe.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
The application assumes new Psych's safe semantics but runs an older object-instantiating version.
|
||||
|
||||
**Fix:** Explicit safe_load with minimal permitted types and a schema; pin compatible dependencies locally.
|
||||
|
||||
**Verification:** Arbitrary classes/aliases and legitimate legacy documents on the actual runtime.
|
||||
|
||||
**Reference:** [primary source](https://docs.ruby-lang.org/en/3.3/Psych.html).
|
||||
|
||||
<a id="ruby-deserialize-cookie"></a>
|
||||
|
||||
## RUBY-DESERIALIZE-COOKIE. Signed cookies are not necessarily confidential
|
||||
|
||||
**Search:** manual review; no separate scanner rule.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'cookies.signed|cookies.encrypted|session\[|secret_key_base' .
|
||||
~~~
|
||||
|
||||
Inspect cookie contents; distinguish integrity from encryption, and possession of a signing key from authorization to an object.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
Private text is placed in a signed cookie under the mistaken assumption that the signature hides it.
|
||||
|
||||
**Fix:** Use encrypted cookies or server-side session storage for confidentiality; minimize data and lifetime and plan safe key rotation.
|
||||
|
||||
**Verification:** Normal sessions remain readable, clients cannot see private contents, and tampering is rejected.
|
||||
|
||||
<a id="ruby-ssrf"></a>
|
||||
|
||||
## RUBY-SSRF. Client input reaches Net::HTTP or open-uri
|
||||
|
||||
**Search:** manual review; no separate scanner rule.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'Net::HTTP|URI.open|open-uri|Faraday|HTTParty' .
|
||||
~~~
|
||||
|
||||
Find URL parsing, redirects and DNS resolution in the actual adapter.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
A URL or redirect reaches an internal resource using the application's trust.
|
||||
|
||||
**Fix:** Use a fixed destination or a unified policy for every redirect and connection, with limits; URI.parse is not authorization.
|
||||
|
||||
**Verification:** Mock redirects/DNS, prohibited schemes, timeouts and the legitimate upstream.
|
||||
|
||||
**Reference:** [primary source](https://cheatsheetseries.owasp.org/cheatsheets/Server_Side_Request_Forgery_Prevention_Cheat_Sheet.html).
|
||||
|
||||
<a id="ruby-callbacks"></a>
|
||||
|
||||
## RUBY-CALLBACKS. Callbacks cause effects before authorization
|
||||
|
||||
**Search:** manual review; no separate scanner rule.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'before_save|after_save|after_commit|after_find|validate|authorize' .
|
||||
~~~
|
||||
|
||||
Compare the ordering of policy checks, instantiation, callbacks and transaction boundaries.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
A model writes a file or queues a task in a callback before authorization or commit.
|
||||
|
||||
**Fix:** Authorize before mutation; perform external effects after confirmed commit with contractual idempotency and compensation.
|
||||
|
||||
**Verification:** Rollback/denial leaves no effects; repeated tasks do not duplicate results.
|
||||
|
||||
<a id="ruby-tls"></a>
|
||||
|
||||
## RUBY-TLS. Ruby HTTPS peer verification disabled
|
||||
|
||||
**Search:** scanner rule RUBY-TLS. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain RUBY-TLS` for details. Regex: VERIFY_NONE. Does not establish whether the object is used for a real connection.
|
||||
|
||||
**Vulnerable example:** VERIFY_NONE leaves the TLS connection unverified.
|
||||
|
||||
~~~ruby
|
||||
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
|
||||
~~~
|
||||
|
||||
**Fix:** Restore peer/hostname checks and the trusted CA; verify actual HTTP client settings.
|
||||
|
||||
~~~ruby
|
||||
http.verify_mode = OpenSSL::SSL::VERIFY_PEER
|
||||
http.ca_file = trusted_ca_file
|
||||
~~~
|
||||
|
||||
**Verification:** Correct server works; invalid certificates cannot yield useful responses.
|
||||
|
||||
Primary documentation: [reference 1](https://docs.ruby-lang.org/en/master/OpenSSL/SSL/SSLContext.html).
|
||||
|
||||
<a id="ruby-redirect-input"></a>
|
||||
|
||||
## RUBY-REDIRECT-INPUT. Rails redirect takes request params directly
|
||||
|
||||
**Search:** scanner rule RUBY-REDIRECT-INPUT. Use `--explain RUBY-REDIRECT-INPUT` for the exact detector contract. Regex with lexical exclusions: redirect_to with params[...] or request.params[...], with optional opening parenthesis. Framework defaults may already reject external hosts; aliases, helpers and allow_other_host configuration need review.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
~~~ruby
|
||||
redirect_to params[:next]
|
||||
~~~
|
||||
|
||||
**Fix:** Use server-selected routes or an explicit redirect policy; preserve Rails' host checks and review the installed framework version.
|
||||
|
||||
~~~ruby
|
||||
redirect_to account_path
|
||||
~~~
|
||||
|
||||
**Verification:** Foreign and scheme-relative destinations fail; legitimate navigation works.
|
||||
|
||||
[Primary reference 1](https://api.rubyonrails.org/classes/ActionController/Redirecting.html)
|
||||
@@ -0,0 +1,512 @@
|
||||
<a id="rust-find-fix-and-verify"></a>
|
||||
|
||||
# Rust: поиск и исправление
|
||||
|
||||
[English](rust.md) | Русский
|
||||
|
||||
[Вся база](README-RU.md) · [Сканер](../offline-scanner-RU.md) · [Проверка патча](../patch-validation-RU.md)
|
||||
|
||||
18 разделов. Формат: **Поиск → Уязвимый вариант → Исправление → Проверка**.
|
||||
Команды `rg` выполняются в корне локальной копии сервиса и только читают файлы. Субъект/владелец определяется по проверенной сессии, а не данным запроса. Примеры нужно адаптировать к реальным API и контракту.
|
||||
|
||||
Автоматические находки — ограниченные синтаксические сигналы для проверки. AST-анализ не разрешает типы и не отслеживает данные между функциями; regex не заменяет парсер языка. Комментарии, строки и одноимённые пользовательские API могут давать совпадения. Проверьте фактическое исполнение, входные данные, авторизацию и границы доверия.
|
||||
|
||||
<a id="contents"></a>
|
||||
|
||||
## Содержание
|
||||
|
||||
- [RUST-UNSAFE-CONVERSION — Непроверенные преобразования и сырые указатели Rust](#rust-unsafe-conversion)
|
||||
- [RUST-SQL-FORMAT — SQL Rust через format!](#rust-sql-format)
|
||||
- [RUST-STATIC-MUT — Общее изменяемое состояние Rust](#rust-static-mut)
|
||||
- [RUST-AUTHORIZATION — Типизированный ID не проверяет owner](#rust-authorization)
|
||||
- [RUST-SERDE-FIELDS — serde entity принимает служебные поля](#rust-serde-fields)
|
||||
- [RUST-PANIC-INPUT — unwrap и byte slicing на входе](#rust-panic-input)
|
||||
- [RUST-COMMAND — Command запускает интерпретатор/опасные опции](#rust-command)
|
||||
- [RUST-LOCK-AWAIT — Блокировка удерживается через await](#rust-lock-await)
|
||||
- [RUST-UNBOUNDED-READ — Потенциально неограниченное чтение потока Rust](#rust-unbounded-read)
|
||||
- [RUST-FFI-OWNERSHIP — FFI удерживает pointer после drop](#rust-ffi-ownership)
|
||||
- [RUST-SSRF — reqwest redirects и политики URL](#rust-ssrf)
|
||||
- [RUST-NUMERIC-CAST — as обрезает значение размера](#rust-numeric-cast)
|
||||
- [RUST-DISTRIBUTED-CAS — Логическая гонка в распределённом состоянии](#rust-distributed-cas)
|
||||
- [RUST-FFI-LENGTH — В C передаётся объявленная длина вместо длины Rust-буфера](#rust-ffi-length)
|
||||
- [RUST-PATH-PREFIX — Валидация префикса имени и файловый fallback](#rust-path-prefix)
|
||||
- [RUST-FFI-ABI — Несовпадение возвращаемого типа C и Rust extern](#rust-ffi-abi)
|
||||
- [RUST-TLS — Rust HTTP принимает недействительный сертификат](#rust-tls)
|
||||
- [RUST-JWT-VALIDATION — Rust JWT: отключены обязательные проверки](#rust-jwt-validation)
|
||||
|
||||
<a id="rust-unsafe-conversion"></a>
|
||||
|
||||
<a id="rust-unsafe-conversion-rust-uncheckedraw-conversion"></a>
|
||||
|
||||
## RUST-UNSAFE-CONVERSION. Непроверенные преобразования и сырые указатели Rust
|
||||
|
||||
**Поиск:** скрипт, правило RUST-UNSAFE-CONVERSION. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain RUST-UNSAFE-CONVERSION. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
~~~rust
|
||||
let text = unsafe { std::str::from_utf8_unchecked(data) };
|
||||
~~~
|
||||
|
||||
**Исправление:** Использовать checked API; для необходимого unsafe доказать длину, выравнивание, lifetime, инициализацию и уникальность ссылок. Не убирать unsafe без понимания инвариантов.
|
||||
|
||||
~~~rust
|
||||
let text = std::str::from_utf8(data)?;
|
||||
~~~
|
||||
|
||||
**Проверка:** Неверный UTF-8/длина/индекс, EOF; по возможности Miri/sanitizers в подготовленной среде.
|
||||
|
||||
<a id="rust-sql-format"></a>
|
||||
|
||||
<a id="rust-sql-format-rust-sql-using-format"></a>
|
||||
|
||||
## RUST-SQL-FORMAT. SQL Rust через format!
|
||||
|
||||
**Поиск:** скрипт, правило RUST-SQL-FORMAT. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain RUST-SQL-FORMAT. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
~~~rust
|
||||
sqlx::query(&format!("SELECT * FROM notes WHERE name={}", name));
|
||||
~~~
|
||||
|
||||
**Исправление:** Параметры поддержанного драйвера/ORM, identifiers из allowlist; тип SQL placeholder зависит от БД.
|
||||
|
||||
~~~rust
|
||||
sqlx::query("SELECT * FROM notes WHERE name=$1").bind(name);
|
||||
~~~
|
||||
|
||||
**Проверка:** Кавычки — данные; условие владельца сохраняется.
|
||||
|
||||
<a id="rust-static-mut"></a>
|
||||
|
||||
<a id="rust-static-mut-shared-mutable-rust-state"></a>
|
||||
|
||||
## RUST-STATIC-MUT. Общее изменяемое состояние Rust
|
||||
|
||||
**Поиск:** скрипт, правило RUST-STATIC-MUT. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain RUST-STATIC-MUT. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
~~~rust
|
||||
static mut CURRENT_USER: u64 = 0;
|
||||
~~~
|
||||
|
||||
**Исправление:** Mutex/atomic для настоящего shared state; principal обычно должен быть per-request, один Mutex не исправит смешение пользователей.
|
||||
|
||||
~~~rust
|
||||
static CURRENT_USER: std::sync::Mutex<u64> = std::sync::Mutex::new(0);
|
||||
~~~
|
||||
|
||||
**Проверка:** Конкурентные запросы не делят principal; нет data race и неправильного lock scope.
|
||||
|
||||
**Основание:** [первичный материал](https://doc.rust-lang.org/reference/items/static-items.html).
|
||||
|
||||
<a id="rust-authorization"></a>
|
||||
|
||||
<a id="rust-authorization-a-typed-id-does-not-authorize-its-owner"></a>
|
||||
|
||||
## RUST-AUTHORIZATION. Типизированный ID не проверяет owner
|
||||
|
||||
**Поиск:** вручную; отдельного правила сканера нет.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'Path<|State<|Extension<|find_by_id|owner|tenant' .
|
||||
~~~
|
||||
|
||||
От extractor пройти до SELECT/UPDATE и проверки сессии; compile-time тип не связывает ID с пользователем.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
Десериализованный NoteId используется для загрузки чужой записи.
|
||||
|
||||
**Исправление:** Запрос по ID и серверному owner/policy; проверка tenant у вложенных объектов и задач.
|
||||
|
||||
**Проверка:** Своё/чужое/аноним, разные tenant и список/экспорт.
|
||||
|
||||
**Основание:** [первичный материал](https://cheatsheetseries.owasp.org/cheatsheets/Authorization_Cheat_Sheet.html).
|
||||
|
||||
<a id="rust-serde-fields"></a>
|
||||
|
||||
<a id="rust-serde-fields-serde-entities-accept-administrative-fields"></a>
|
||||
|
||||
## RUST-SERDE-FIELDS. serde entity принимает служебные поля
|
||||
|
||||
**Поиск:** вручную; отдельного правила сканера нет.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'Deserialize|flatten|default|deny_unknown_fields|serde' .
|
||||
~~~
|
||||
|
||||
Сверить DTO/entity, default role и flatten; deny_unknown_fields имеет ограничения совместимости с flatten.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
Клиент присылает owner/admin, default создаёт привилегию при отсутствующем поле.
|
||||
|
||||
**Исправление:** Отдельный DTO с разрешёнными полями, явная валидация и серверные auth-поля; не полагаться на тип bool как проверку полномочий.
|
||||
|
||||
**Проверка:** Лишнее/отсутствующее поле, null, вложенный объект и обычный payload.
|
||||
|
||||
<a id="rust-panic-input"></a>
|
||||
|
||||
<a id="rust-panic-input-unwrap-and-byte-slicing-on-request-input"></a>
|
||||
|
||||
## RUST-PANIC-INPUT. unwrap и byte slicing на входе
|
||||
|
||||
**Поиск:** вручную; отдельного правила сканера нет.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'unwrap\(|expect\(|\[[0-9]+\.\.|parse::<|from_utf8' .
|
||||
~~~
|
||||
|
||||
Сверить Result/Option и UTF-8 границы; определить, падает task, worker или процесс при panic.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
parse().unwrap() либо &name[..32] паникует на неправильном/коротком/многобайтовом вводе.
|
||||
|
||||
**Исправление:** Вернуть контролируемую ошибку, checked get/range и ограничение размера; не скрывать все ошибки пустым default.
|
||||
|
||||
**Проверка:** Некорректный UTF-8/число, короткая строка, многобайтовая граница и штатный запрос.
|
||||
|
||||
<a id="rust-command"></a>
|
||||
|
||||
<a id="rust-command-shell-launched-from-rust"></a>
|
||||
|
||||
## RUST-COMMAND. Command запускает интерпретатор/опасные опции
|
||||
|
||||
**Поиск:** скрипт, правило RUST-COMMAND. Запуск: python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain RUST-COMMAND. Regex: Command::new с буквальным sh/bash/dash/zsh/cmd/powershell/pwsh. Команда может быть доверенной; arg -c, переменные executable и .args проверять вручную.
|
||||
|
||||
Дополнительный ручной поиск для непокрытых форм:
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'Command::new|\.arg\(|\.args\(|sh|cmd.exe' .
|
||||
~~~
|
||||
|
||||
Сверить executable, каждый argv, окружение/cwd; отдельные аргументы не выключают опции программы.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
Command::new("sh").arg("-c").arg(input) запускает shell с клиентским текстом.
|
||||
|
||||
**Исправление:** Библиотечный API или фиксированный executable/argv и политика опций/путей, bounded output/time.
|
||||
|
||||
**Проверка:** Кавычки/ведущий дефис остаются данными либо отклоняются; штатная операция совместима.
|
||||
|
||||
|
||||
**Сигнал сканера — пример до:**
|
||||
|
||||
~~~rust
|
||||
Command::new("sh").arg("-c").arg(command).output()?;
|
||||
~~~
|
||||
|
||||
**Шаблон исправления:**
|
||||
|
||||
~~~rust
|
||||
Command::new("/usr/bin/file").arg("--").arg(validated_name).output()?;
|
||||
~~~
|
||||
|
||||
Первичная документация: [документация 1](https://doc.rust-lang.org/std/process/struct.Command.html).
|
||||
|
||||
<a id="rust-lock-await"></a>
|
||||
|
||||
<a id="rust-lock-await-holding-locks-across-await"></a>
|
||||
|
||||
## RUST-LOCK-AWAIT. Блокировка удерживается через await
|
||||
|
||||
**Поиск:** вручную; отдельного правила сканера нет.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'lock\(|\.await|Mutex|RwLock|DashMap' .
|
||||
~~~
|
||||
|
||||
Проверить область guard, повторный вход и порядок нескольких locks.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
Запрос держит lock во время I/O, второй путь ждёт ресурс и создаёт deadlock/истощение.
|
||||
|
||||
**Исправление:** Минимальная критическая секция, снимок/версия и повторная атомарная проверка; не отпускать lock между auth и mutation без защиты.
|
||||
|
||||
**Проверка:** Два запроса с barrier, cancellation и медленный upstream не блокируют всё приложение.
|
||||
|
||||
<a id="rust-unbounded-read"></a>
|
||||
|
||||
<a id="rust-unbounded-read-potentially-unbounded-rust-stream-read"></a>
|
||||
|
||||
## RUST-UNBOUNDED-READ. Потенциально неограниченное чтение потока Rust
|
||||
|
||||
**Поиск:** правило сканера RUST-UNBOUNDED-READ. Точный контракт детектора: `--explain RUST-UNBOUNDED-READ`. Regex с лексическими исключениями: stream/socket/request/reader.read_to_end/read_to_string. Имена получателя — подсказки, а не типы; уже ограниченный поток может дать совпадение, другие имена и wrappers могут быть пропущены.
|
||||
|
||||
Дополнительный ручной поиск форм, которые не покрывает автоматическое правило:
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'read_to_end|read_to_string|read_line|collect\(|to_bytes' .
|
||||
~~~
|
||||
|
||||
Проследите ограничения фактически прочитанных байтов и затраченного времени, в том числе для chunked-потоков.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
Управляемый клиентом поток накапливается в памяти до EOF.
|
||||
|
||||
**Исправление:** Ограничьте чтение, обнаруживайте limit+1 и задайте подходящий timeout; Read::take сам по себе молча останавливается на лимите.
|
||||
|
||||
**Проверка:** Проверьте EOF, limit-1, limit, limit+1 и медленный бесконечный источник; допустимые документы максимального размера должны обрабатываться.
|
||||
|
||||
|
||||
**Пример для сканера до исправления:**
|
||||
|
||||
~~~rust
|
||||
stream.read_to_end(&mut payload)?;
|
||||
~~~
|
||||
|
||||
**Шаблон исправления:**
|
||||
|
||||
~~~rust
|
||||
let mut bounded = stream.take(MAX_BYTES + 1);
|
||||
bounded.read_to_end(&mut payload)?;
|
||||
if payload.len() as u64 > MAX_BYTES { return Err(too_large()); }
|
||||
~~~
|
||||
|
||||
<a id="rust-ffi-ownership"></a>
|
||||
|
||||
<a id="rust-ffi-ownership-ffi-retains-a-pointer-after-drop"></a>
|
||||
|
||||
## RUST-FFI-OWNERSHIP. FFI удерживает pointer после drop
|
||||
|
||||
**Поиск:** вручную; отдельного правила сканера нет.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'CString|into_raw|from_raw|as_ptr|extern|free' .
|
||||
~~~
|
||||
|
||||
Сравнить lifetime, allocator и контракт удержания pointer обеими сторонами.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
C сохраняет as_ptr временного Rust-объекта; C free освобождает allocation другого allocator.
|
||||
|
||||
**Исправление:** Явная передача владения и парная функция освобождения; keep-alive до callback, FFI-safe типы и обработка panic boundary.
|
||||
|
||||
**Проверка:** Отложенный callback, повторное освобождение, ошибка C и штатный teardown.
|
||||
|
||||
**Основание:** [первичный материал](https://doc.rust-lang.org/nomicon/ffi.html).
|
||||
|
||||
<a id="rust-ssrf"></a>
|
||||
|
||||
<a id="rust-ssrf-reqwest-redirects-and-url-policies"></a>
|
||||
|
||||
## RUST-SSRF. reqwest redirects и политики URL
|
||||
|
||||
**Поиск:** вручную; отдельного правила сканера нет.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'reqwest|Client::builder|redirect|Url::parse|resolve' .
|
||||
~~~
|
||||
|
||||
Сверить URL, redirect policy и transport DNS; тип Url означает только успешный разбор.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
Разрешённый первый URL перенаправляет к другому trust zone.
|
||||
|
||||
**Исправление:** Серверная карта или policy назначения на каждом переходе и реальном соединении; лимиты.
|
||||
|
||||
**Проверка:** Mock DNS/redirect/timeout, обычный upstream и запрет недопустимых схем.
|
||||
|
||||
**Основание:** [первичный материал](https://cheatsheetseries.owasp.org/cheatsheets/Server_Side_Request_Forgery_Prevention_Cheat_Sheet.html).
|
||||
|
||||
<a id="rust-numeric-cast"></a>
|
||||
|
||||
<a id="rust-numeric-cast-as-truncates-a-size-value"></a>
|
||||
|
||||
## RUST-NUMERIC-CAST. as обрезает значение размера
|
||||
|
||||
**Поиск:** вручную; отдельного правила сканера нет.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e ' as u8| as u16| as u32| as usize|wrapping_|unchecked_' .
|
||||
~~~
|
||||
|
||||
Сверить исходный диапазон и целевой тип до allocation/index/DB ID.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
Широкое число обрезается через as, разные ID/размеры становятся одним.
|
||||
|
||||
**Исправление:** TryFrom/checked arithmetic и ограничения протокола; отрицательные значения отвергать до unsigned.
|
||||
|
||||
**Проверка:** Максимум, максимум+1, отрицательное и штатное значение, release/debug поведение.
|
||||
|
||||
<a id="rust-distributed-cas"></a>
|
||||
|
||||
<a id="rust-distributed-cas-logical-races-in-distributed-state"></a>
|
||||
|
||||
## RUST-DISTRIBUTED-CAS. Логическая гонка в распределённом состоянии
|
||||
|
||||
**Поиск:** вручную; отдельного правила сканера нет.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'etcd|txn|compare|round|version' .
|
||||
~~~
|
||||
|
||||
Сравнить revision при чтении и записи между workers; process-local Mutex не защищает удалённую транзакцию.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
**RuCTF / rustest, автор.** Несколько запросов проходили проверку одной версии
|
||||
раунда и независимо записывали результат.
|
||||
|
||||
**Исправление:** транзакция хранилища/CAS по версии и атомарное потребление одноразового
|
||||
состояния. Mutex одного процесса недостаточен при нескольких workers.
|
||||
|
||||
**Проверка:** параллельные ответы дают ровно один переход; retries не начисляют
|
||||
результат дважды.
|
||||
|
||||
**Вариант A/D:** Основание и версия: [исходник/разбор 1](https://github.com/HackerDom/ructf-2023/blob/0cc333e44f2ba6908ff6c5d613146e3b00173315/writeups/rustest/README.md).
|
||||
|
||||
**Основание:** [первичный материал](https://github.com/HackerDom/ructf-2023/blob/0cc333e44f2ba6908ff6c5d613146e3b00173315/writeups/rustest/README.md).
|
||||
|
||||
<a id="rust-ffi-length"></a>
|
||||
|
||||
<a id="rust-ffi-length-passing-declared-length-instead-of-rust-buffer-length-to-c"></a>
|
||||
|
||||
## RUST-FFI-LENGTH. В C передаётся объявленная длина вместо длины Rust-буфера
|
||||
|
||||
**Поиск:** вручную; отдельного правила сканера нет.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'extern|as_ptr|as_mut_ptr|size_t|memcpy' .
|
||||
~~~
|
||||
|
||||
Сопоставить pointer и length на Rust/C сторонах: длина выделенного среза, не объявленная клиентом.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
**DEF CON / bisbee, код.** FFI store_data получает decoded_data.as_ptr()
|
||||
и независимо выбранный block_size; C копирует size байт.
|
||||
|
||||
**Исправление:** проверить заявленный размер против реального среза и лимита,
|
||||
передавать длину проверенного буфера.
|
||||
|
||||
**Проверка:** размер меньше/равен/больше,
|
||||
ошибка декодирования, пустой ввод.
|
||||
|
||||
**Вариант A/D:** Основание и версия: [исходник/разбор 1](https://github.com/Nautilus-Institute/finals-2024/blob/f17456fed4ff40e6f4f1237ed4b82c242e52ec67/bisbee/src/service/src/main.rs); [исходник/разбор 2](https://github.com/Nautilus-Institute/finals-2024/blob/f17456fed4ff40e6f4f1237ed4b82c242e52ec67/bisbee/src/db/kv.c); [исходник/разбор 3](https://github.com/Nautilus-Institute/finals-2024/blob/f17456fed4ff40e6f4f1237ed4b82c242e52ec67/bisbee/src/db/kv.h); [исходник/разбор 4](https://github.com/Nautilus-Institute/finals-2024/blob/f17456fed4ff40e6f4f1237ed4b82c242e52ec67/bisbee/src/db/kv_hashmap.c); [исходник/разбор 5](https://github.com/Nautilus-Institute/finals-2024/blob/f17456fed4ff40e6f4f1237ed4b82c242e52ec67/bisbee/src/db/kv_hashmap.h); [исходник/разбор 6](https://github.com/Nautilus-Institute/finals-2024/blob/f17456fed4ff40e6f4f1237ed4b82c242e52ec67/bisbee/src/db/kv_list.c).
|
||||
|
||||
**Основание:** [первичный материал](https://github.com/Nautilus-Institute/finals-2024/blob/f17456fed4ff40e6f4f1237ed4b82c242e52ec67/bisbee/src/service/src/main.rs).
|
||||
|
||||
|
||||
**Вариант A/D:** в FlagDrive (ENOWARS10) ёмкость контейнера считали по всей структуре вместе со служебным флагом, а данные предназначались только для массива токена. Считать длину/ёмкость самого подмассива, отказаться от неверного reinterpretation и отдельно сохранять owner-проверку. Тест: максимальная длина токена и максимум+1 не меняют соседний признак полномочий. [Авторский разбор](https://github.com/enowars/enowars10-service-flagdrive/blob/d1575098fe2c516460136bb5fba11d9a1c4af3f7/documentation/FLAGSTORE_1.md). Это ошибка границ и преобразования памяти в конкретном сервисе, не утверждение о дефекте компилятора.
|
||||
|
||||
<a id="rust-path-prefix"></a>
|
||||
|
||||
<a id="rust-path-prefix-prefix-validation-and-filesystem-fallback"></a>
|
||||
|
||||
## RUST-PATH-PREFIX. Валидация префикса имени и файловый fallback
|
||||
|
||||
**Поиск:** вручную; отдельного правила сканера нет.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'username|canonicalize|create_dir|fs::read|fs::write' .
|
||||
~~~
|
||||
|
||||
Сравнить проверенный префикс и целый путь; проверить UTF-8 boundary и альтернативный filesystem fallback.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
**DEF CON / bisbee, код.** Проверяется часть username, целое имя используется
|
||||
в пути; при промахе внутренней БД происходит чтение файла.
|
||||
|
||||
**Исправление:** проверять полное имя и границы UTF-8, серверный storage path,
|
||||
одинаковая auth-политика основного и fallback пути.
|
||||
|
||||
**Проверка:** короткое/длинное/многобайтовое имя, разделители в хвосте, промах БД.
|
||||
|
||||
**Вариант A/D:** Основание и версия: [исходник/разбор 1](https://github.com/Nautilus-Institute/finals-2024/blob/f17456fed4ff40e6f4f1237ed4b82c242e52ec67/bisbee/src/service/src/main.rs); [исходник/разбор 2](https://github.com/Nautilus-Institute/finals-2024/blob/f17456fed4ff40e6f4f1237ed4b82c242e52ec67/bisbee/src/db/kv.c); [исходник/разбор 3](https://github.com/Nautilus-Institute/finals-2024/blob/f17456fed4ff40e6f4f1237ed4b82c242e52ec67/bisbee/src/db/kv.h); [исходник/разбор 4](https://github.com/Nautilus-Institute/finals-2024/blob/f17456fed4ff40e6f4f1237ed4b82c242e52ec67/bisbee/src/db/kv_hashmap.c); [исходник/разбор 5](https://github.com/Nautilus-Institute/finals-2024/blob/f17456fed4ff40e6f4f1237ed4b82c242e52ec67/bisbee/src/db/kv_hashmap.h); [исходник/разбор 6](https://github.com/Nautilus-Institute/finals-2024/blob/f17456fed4ff40e6f4f1237ed4b82c242e52ec67/bisbee/src/db/kv_list.c).
|
||||
|
||||
**Основание:** [первичный материал](https://github.com/Nautilus-Institute/finals-2024/blob/f17456fed4ff40e6f4f1237ed4b82c242e52ec67/bisbee/src/service/src/main.rs).
|
||||
|
||||
<a id="rust-ffi-abi"></a>
|
||||
|
||||
<a id="rust-ffi-abi-c-and-rust-extern-return-types-disagree"></a>
|
||||
|
||||
## RUST-FFI-ABI. Несовпадение возвращаемого типа C и Rust extern
|
||||
|
||||
**Поиск:** вручную; отдельного правила сканера нет.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'extern|store_data|c_void|size_t' .
|
||||
~~~
|
||||
|
||||
Сравнить C header/реализацию и Rust declaration: return type, signedness, layout и calling convention.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
**DEF CON / bisbee, код + header.** C store_data возвращает void,
|
||||
Rust объявляет i8 и использует полученный результат для выбора fallback.
|
||||
|
||||
**Исправление:** общий ABI-контракт/генерация bindings; статус только через действительно
|
||||
возвращаемое значение одинакового типа, обработка ошибок без неинициализированного
|
||||
результата.
|
||||
|
||||
**Проверка:** build с предупреждениями, размеры/знаковость/тип результата,
|
||||
штатные ошибки хранения.
|
||||
|
||||
**Вариант A/D:** Основание и версия: [исходник/разбор 1](https://github.com/Nautilus-Institute/finals-2024/blob/f17456fed4ff40e6f4f1237ed4b82c242e52ec67/bisbee/src/service/src/main.rs); [исходник/разбор 2](https://github.com/Nautilus-Institute/finals-2024/blob/f17456fed4ff40e6f4f1237ed4b82c242e52ec67/bisbee/src/db/kv.c); [исходник/разбор 3](https://github.com/Nautilus-Institute/finals-2024/blob/f17456fed4ff40e6f4f1237ed4b82c242e52ec67/bisbee/src/db/kv.h); [исходник/разбор 4](https://github.com/Nautilus-Institute/finals-2024/blob/f17456fed4ff40e6f4f1237ed4b82c242e52ec67/bisbee/src/db/kv_hashmap.c); [исходник/разбор 5](https://github.com/Nautilus-Institute/finals-2024/blob/f17456fed4ff40e6f4f1237ed4b82c242e52ec67/bisbee/src/db/kv_hashmap.h); [исходник/разбор 6](https://github.com/Nautilus-Institute/finals-2024/blob/f17456fed4ff40e6f4f1237ed4b82c242e52ec67/bisbee/src/db/kv_list.c).
|
||||
|
||||
**Основание:** [первичный материал](https://github.com/Nautilus-Institute/finals-2024/blob/f17456fed4ff40e6f4f1237ed4b82c242e52ec67/bisbee/src/service/src/main.rs).
|
||||
|
||||
<a id="rust-tls"></a>
|
||||
|
||||
<a id="rust-tls-rust-http-accepts-invalid-certificates"></a>
|
||||
|
||||
## RUST-TLS. Rust HTTP принимает недействительный сертификат
|
||||
|
||||
**Поиск:** скрипт, правило RUST-TLS. Запуск: python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain RUST-TLS. Regex: danger_accept_invalid_certs/hostnames(true), включая reqwest/native-tls-подобные builders. Значения из переменных и custom verifier вручную.
|
||||
|
||||
**Уязвимый вариант:** Опасные builder flags отключают проверку сертификата/имени.
|
||||
|
||||
~~~rust
|
||||
let client = reqwest::Client::builder().danger_accept_invalid_certs(true).build()?;
|
||||
~~~
|
||||
|
||||
**Исправление:** Использовать стандартную проверку; для внутреннего CA добавить доверенный root, не отключая проверки.
|
||||
|
||||
~~~rust
|
||||
let client = reqwest::Client::builder().add_root_certificate(trusted_ca).build()?;
|
||||
~~~
|
||||
|
||||
**Проверка:** Свой CA/hostname работает; чужой сертификат/hostname отвергнут.
|
||||
|
||||
Первичная документация: [документация 1](https://docs.rs/reqwest/latest/reqwest/struct.ClientBuilder.html).
|
||||
|
||||
<a id="rust-jwt-validation"></a>
|
||||
|
||||
<a id="rust-jwt-validation-rust-jwt-checks-disabled"></a>
|
||||
|
||||
## RUST-JWT-VALIDATION. Rust JWT: отключены обязательные проверки
|
||||
|
||||
**Поиск:** скрипт, правило RUST-JWT-VALIDATION. Запуск: python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain RUST-JWT-VALIDATION. Regex: insecure_disable_signature_validation, validate_exp/validate_aud=false и старые dangerous_*decode. API зависит от версии jsonwebtoken.
|
||||
|
||||
**Уязвимый вариант:** Отключённая подпись или expiry делает разобранные claims недостаточным основанием для доступа.
|
||||
|
||||
~~~rust
|
||||
validation.insecure_disable_signature_validation();
|
||||
validation.validate_exp = false;
|
||||
~~~
|
||||
|
||||
**Исправление:** Использовать проверяющий decode с доверенным ключом и контрактом Validation; проверить результат до доступа.
|
||||
|
||||
~~~rust
|
||||
let mut validation = Validation::new(Algorithm::RS256);
|
||||
validation.set_audience(&["notes"]);
|
||||
validation.set_issuer(&["auth"]);
|
||||
validation.set_required_spec_claims(&["exp", "sub", "iss", "aud"]);
|
||||
~~~
|
||||
|
||||
**Проверка:** Неверная подпись, истечение и отсутствие обязательного поля отклоняются.
|
||||
|
||||
Первичная документация: [документация 1](https://docs.rs/jsonwebtoken/latest/jsonwebtoken/struct.Validation.html).
|
||||
@@ -0,0 +1,457 @@
|
||||
# Rust: find, fix and verify
|
||||
|
||||
English | [Русский](rust-RU.md)
|
||||
|
||||
[Catalog](README.md) · [Scanner](../offline-scanner.md) · [Patch verification](../patch-validation.md)
|
||||
|
||||
18 sections. Each follows **Search → Vulnerable example → Fix → Verification**.
|
||||
Run `rg` from a local service checkout; searches only read files. Derive the actor/owner from a verified session, not request data. Adapt examples to the actual API and contract.
|
||||
|
||||
## Contents
|
||||
|
||||
- [RUST-UNSAFE-CONVERSION — Rust unchecked/raw conversion](#rust-unsafe-conversion)
|
||||
- [RUST-SQL-FORMAT — Rust SQL using format!](#rust-sql-format)
|
||||
- [RUST-STATIC-MUT — Shared mutable Rust state](#rust-static-mut)
|
||||
- [RUST-AUTHORIZATION — A typed ID does not authorize its owner](#rust-authorization)
|
||||
- [RUST-SERDE-FIELDS — serde entities accept administrative fields](#rust-serde-fields)
|
||||
- [RUST-PANIC-INPUT — unwrap and byte slicing on request input](#rust-panic-input)
|
||||
- [RUST-COMMAND — Shell launched from Rust](#rust-command)
|
||||
- [RUST-LOCK-AWAIT — Holding locks across await](#rust-lock-await)
|
||||
- [RUST-UNBOUNDED-READ — Potentially unbounded Rust stream read](#rust-unbounded-read)
|
||||
- [RUST-FFI-OWNERSHIP — FFI retains a pointer after drop](#rust-ffi-ownership)
|
||||
- [RUST-SSRF — reqwest redirects and URL policies](#rust-ssrf)
|
||||
- [RUST-NUMERIC-CAST — as truncates a size value](#rust-numeric-cast)
|
||||
- [RUST-DISTRIBUTED-CAS — Logical races in distributed state](#rust-distributed-cas)
|
||||
- [RUST-FFI-LENGTH — Passing declared length instead of Rust buffer length to C](#rust-ffi-length)
|
||||
- [RUST-PATH-PREFIX — Prefix validation and filesystem fallback](#rust-path-prefix)
|
||||
- [RUST-FFI-ABI — C and Rust extern return types disagree](#rust-ffi-abi)
|
||||
- [RUST-TLS — Rust HTTP accepts invalid certificates](#rust-tls)
|
||||
- [RUST-JWT-VALIDATION — Rust JWT checks disabled](#rust-jwt-validation)
|
||||
|
||||
<a id="rust-unsafe-conversion"></a>
|
||||
|
||||
## RUST-UNSAFE-CONVERSION. Rust unchecked/raw conversion
|
||||
|
||||
**Search:** scanner rule RUST-UNSAFE-CONVERSION. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain RUST-UNSAFE-CONVERSION` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
~~~rust
|
||||
let text = unsafe { std::str::from_utf8_unchecked(data) };
|
||||
~~~
|
||||
|
||||
**Fix:** Prefer checked APIs; necessary unsafe needs length, alignment, lifetime, initialization and aliasing proofs. Do not remove it blindly.
|
||||
|
||||
~~~rust
|
||||
let text = std::str::from_utf8(data)?;
|
||||
~~~
|
||||
|
||||
**Verification:** Test invalid UTF-8/length/index and EOF; use Miri/sanitizers where prepared.
|
||||
|
||||
<a id="rust-sql-format"></a>
|
||||
|
||||
## RUST-SQL-FORMAT. Rust SQL using format!
|
||||
|
||||
**Search:** scanner rule RUST-SQL-FORMAT. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain RUST-SQL-FORMAT` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
~~~rust
|
||||
sqlx::query(&format!("SELECT * FROM notes WHERE name={}", name));
|
||||
~~~
|
||||
|
||||
**Fix:** Use driver binding and allowlisted identifiers; placeholder syntax is database-specific.
|
||||
|
||||
~~~rust
|
||||
sqlx::query("SELECT * FROM notes WHERE name=$1").bind(name);
|
||||
~~~
|
||||
|
||||
**Verification:** Quotes remain data and ownership predicates work.
|
||||
|
||||
<a id="rust-static-mut"></a>
|
||||
|
||||
## RUST-STATIC-MUT. Shared mutable Rust state
|
||||
|
||||
**Search:** scanner rule RUST-STATIC-MUT. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain RUST-STATIC-MUT` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
~~~rust
|
||||
static mut CURRENT_USER: u64 = 0;
|
||||
~~~
|
||||
|
||||
**Fix:** Use ownership or synchronized primitives with clear invariants; review all unsafe accesses and cross-request state.
|
||||
|
||||
~~~rust
|
||||
static CURRENT_USER: std::sync::Mutex<u64> = std::sync::Mutex::new(0);
|
||||
~~~
|
||||
|
||||
**Verification:** Concurrent requests do not race or leak another user's data; ordinary operations work.
|
||||
|
||||
**Reference:** [primary source](https://doc.rust-lang.org/reference/items/static-items.html).
|
||||
|
||||
<a id="rust-authorization"></a>
|
||||
|
||||
## RUST-AUTHORIZATION. A typed ID does not authorize its owner
|
||||
|
||||
**Search:** manual review; no separate scanner rule.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'Path<|State<|Extension<|find_by_id|owner|tenant' .
|
||||
~~~
|
||||
|
||||
Trace extractors to SELECT/UPDATE and session verification; a compile-time type does not bind the ID to the caller.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
A deserialized NoteId loads another user's record.
|
||||
|
||||
**Fix:** Query by ID plus server-derived owner/policy; check tenant boundaries for nested resources and jobs.
|
||||
|
||||
**Verification:** Owner, other user, anonymous caller, cross-tenant access, lists and exports.
|
||||
|
||||
**Reference:** [primary source](https://cheatsheetseries.owasp.org/cheatsheets/Authorization_Cheat_Sheet.html).
|
||||
|
||||
<a id="rust-serde-fields"></a>
|
||||
|
||||
## RUST-SERDE-FIELDS. serde entities accept administrative fields
|
||||
|
||||
**Search:** manual review; no separate scanner rule.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'Deserialize|flatten|default|deny_unknown_fields|serde' .
|
||||
~~~
|
||||
|
||||
Compare request DTOs/entities, role defaults and flatten; deny_unknown_fields has compatibility limitations with flatten.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
The client supplies owner/admin, or a missing field's default grants privileges.
|
||||
|
||||
**Fix:** A separate allowlisted DTO, explicit validation and server-derived authorization fields; a bool type is not a permission check.
|
||||
|
||||
**Verification:** Extra/missing fields, nulls, nested objects and normal payloads.
|
||||
|
||||
<a id="rust-panic-input"></a>
|
||||
|
||||
## RUST-PANIC-INPUT. unwrap and byte slicing on request input
|
||||
|
||||
**Search:** manual review; no separate scanner rule.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'unwrap\(|expect\(|\[[0-9]+\.\.|parse::<|from_utf8' .
|
||||
~~~
|
||||
|
||||
Review Result/Option handling and UTF-8 boundaries; determine whether panic terminates a task, worker or process.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
`parse().unwrap()` or `&name[..32]` panics on malformed, short or multibyte input.
|
||||
|
||||
**Fix:** Controlled errors, checked get/ranges and size bounds; do not conceal every failure with an empty default.
|
||||
|
||||
**Verification:** Invalid UTF-8/numbers, short strings, multibyte boundaries and normal requests.
|
||||
|
||||
<a id="rust-command"></a>
|
||||
|
||||
## RUST-COMMAND. Shell launched from Rust
|
||||
|
||||
**Search:** scanner rule RUST-COMMAND. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain RUST-COMMAND` for details. Regex: Command::new with literal sh/bash/dash/zsh/cmd/powershell/pwsh. A command may be trusted; review -c, variable executables and .args.
|
||||
|
||||
Additional manual search for forms outside automatic coverage:
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'Command::new|\.arg\(|\.args\(|sh|cmd.exe' .
|
||||
~~~
|
||||
|
||||
Review the executable, every argument, environment and cwd; separate argv do not disable a program's dangerous options.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
`Command::new("sh").arg("-c").arg(input)` gives a shell client-controlled text.
|
||||
|
||||
**Fix:** Use a fixed executable, separate arguments, allowlisted options and bounded time/output.
|
||||
|
||||
**Verification:** Metacharacters stay data; dangerous options cannot change behavior.
|
||||
|
||||
**Scanner example before:**
|
||||
|
||||
~~~rust
|
||||
Command::new("sh").arg("-c").arg(command).output()?;
|
||||
~~~
|
||||
|
||||
**Fix template:**
|
||||
|
||||
~~~rust
|
||||
Command::new("/usr/bin/file").arg("--").arg(validated_name).output()?;
|
||||
~~~
|
||||
|
||||
Primary documentation: [reference 1](https://doc.rust-lang.org/std/process/struct.Command.html).
|
||||
|
||||
<a id="rust-lock-await"></a>
|
||||
|
||||
## RUST-LOCK-AWAIT. Holding locks across await
|
||||
|
||||
**Search:** manual review; no separate scanner rule.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'lock\(|\.await|Mutex|RwLock|DashMap' .
|
||||
~~~
|
||||
|
||||
Review guard scope, reentrancy and the ordering of multiple locks.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
A request holds a lock during I/O while another path waits on a dependent resource, causing deadlock or exhaustion.
|
||||
|
||||
**Fix:** Minimize critical sections; use snapshots/versions with a repeated atomic check. Do not release a lock between authorization and mutation without equivalent protection.
|
||||
|
||||
**Verification:** Barrier-controlled concurrent requests, cancellation and slow upstreams do not block the whole application.
|
||||
|
||||
<a id="rust-unbounded-read"></a>
|
||||
|
||||
## RUST-UNBOUNDED-READ. Potentially unbounded Rust stream read
|
||||
|
||||
**Search:** scanner rule RUST-UNBOUNDED-READ. Regex with lexical exclusions: stream/socket/request/reader.read_to_end/read_to_string. Receiver names are hints, not types; an already bounded receiver may match and other names/wrappers may be missed.
|
||||
|
||||
Additional manual search for forms outside automatic coverage:
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'read_to_end|read_to_string|read_line|collect\(|to_bytes' .
|
||||
~~~
|
||||
|
||||
Trace bounds on bytes actually read and time spent, including chunked streams.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
A client-controlled stream accumulates in memory until EOF.
|
||||
|
||||
**Fix:** Bound reads, detect limit+1 and enforce an appropriate timeout; Read::take alone silently stops at its limit.
|
||||
|
||||
**Verification:** Test EOF, limit-1, limit, limit+1 and a slow never-ending source; valid maximum documents work.
|
||||
|
||||
|
||||
**Scanner example before:**
|
||||
|
||||
~~~rust
|
||||
stream.read_to_end(&mut payload)?;
|
||||
~~~
|
||||
|
||||
**Fix template:**
|
||||
|
||||
~~~rust
|
||||
let mut bounded = stream.take(MAX_BYTES + 1);
|
||||
bounded.read_to_end(&mut payload)?;
|
||||
if payload.len() as u64 > MAX_BYTES { return Err(too_large()); }
|
||||
~~~
|
||||
|
||||
|
||||
<a id="rust-ffi-ownership"></a>
|
||||
|
||||
## RUST-FFI-OWNERSHIP. FFI retains a pointer after drop
|
||||
|
||||
**Search:** manual review; no separate scanner rule.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'CString|into_raw|from_raw|as_ptr|extern|free' .
|
||||
~~~
|
||||
|
||||
Compare lifetimes, allocators and both sides' pointer-retention contracts.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
C retains as_ptr from a temporary Rust object, or C free releases memory belonging to another allocator.
|
||||
|
||||
**Fix:** Explicit ownership transfer with a matching deallocator; keep owners alive through callbacks, use FFI-safe types and handle panic boundaries.
|
||||
|
||||
**Verification:** Delayed callbacks, duplicate frees, C-side errors and normal teardown.
|
||||
|
||||
**Reference:** [primary source](https://doc.rust-lang.org/nomicon/ffi.html).
|
||||
|
||||
<a id="rust-ssrf"></a>
|
||||
|
||||
## RUST-SSRF. reqwest redirects and URL policies
|
||||
|
||||
**Search:** manual review; no separate scanner rule.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'reqwest|Client::builder|redirect|Url::parse|resolve' .
|
||||
~~~
|
||||
|
||||
Review URL parsing, redirect policy and transport DNS; a Url value proves parsing, not permission.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
An initially permitted URL redirects into a different trust zone.
|
||||
|
||||
**Fix:** A server-side destination map or destination policy on every redirect and actual connection, with limits.
|
||||
|
||||
**Verification:** Mock DNS/redirects/timeouts, normal upstream access and prohibited schemes.
|
||||
|
||||
**Reference:** [primary source](https://cheatsheetseries.owasp.org/cheatsheets/Server_Side_Request_Forgery_Prevention_Cheat_Sheet.html).
|
||||
|
||||
<a id="rust-numeric-cast"></a>
|
||||
|
||||
## RUST-NUMERIC-CAST. as truncates a size value
|
||||
|
||||
**Search:** manual review; no separate scanner rule.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e ' as u8| as u16| as u32| as usize|wrapping_|unchecked_' .
|
||||
~~~
|
||||
|
||||
Check source range and destination type before allocation, indexing or database lookup.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
A wide integer is truncated by as, making distinct IDs/sizes identical.
|
||||
|
||||
**Fix:** TryFrom, checked arithmetic and protocol bounds; reject negative values before unsigned conversion.
|
||||
|
||||
**Verification:** Maximum, maximum+1, negative and normal values under release/debug behavior.
|
||||
|
||||
<a id="rust-distributed-cas"></a>
|
||||
|
||||
## RUST-DISTRIBUTED-CAS. Logical races in distributed state
|
||||
|
||||
**Search:** manual review; no separate scanner rule.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'etcd|txn|compare|round|version' .
|
||||
~~~
|
||||
|
||||
Compare read/write revisions across workers; a process-local Mutex does not protect a remote transaction.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
**RuCTF / rustest, author write-up.** Multiple requests checked the same round version and independently recorded a result.
|
||||
|
||||
**Fix:** Storage transactions/CAS on the version and atomic consumption of one-use state. A single process's Mutex is insufficient across workers.
|
||||
|
||||
**Verification:** Parallel answers produce exactly one state transition; retries never score twice.
|
||||
|
||||
**A/D variant:** Source and version: [source/write-up 1](https://github.com/HackerDom/ructf-2023/blob/0cc333e44f2ba6908ff6c5d613146e3b00173315/writeups/rustest/README.md).
|
||||
|
||||
**Reference:** [primary source](https://github.com/HackerDom/ructf-2023/blob/0cc333e44f2ba6908ff6c5d613146e3b00173315/writeups/rustest/README.md).
|
||||
|
||||
<a id="rust-ffi-length"></a>
|
||||
|
||||
## RUST-FFI-LENGTH. Passing declared length instead of Rust buffer length to C
|
||||
|
||||
**Search:** manual review; no separate scanner rule.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'extern|as_ptr|as_mut_ptr|size_t|memcpy' .
|
||||
~~~
|
||||
|
||||
Compare pointer/length pairs on both sides: the actual allocated slice length, not the client's claim.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
**DEF CON / bisbee, source.** FFI store_data receives decoded_data.as_ptr() and an independently selected block_size; C copies size bytes.
|
||||
|
||||
**Fix:** Check declared size against the actual slice and limit; pass the validated buffer's length.
|
||||
|
||||
**Verification:** Smaller, equal and larger sizes, decoding failures and empty input.
|
||||
|
||||
**A/D variant:** Source and version: [source/write-up 1](https://github.com/Nautilus-Institute/finals-2024/blob/f17456fed4ff40e6f4f1237ed4b82c242e52ec67/bisbee/src/service/src/main.rs); [source/write-up 2](https://github.com/Nautilus-Institute/finals-2024/blob/f17456fed4ff40e6f4f1237ed4b82c242e52ec67/bisbee/src/db/kv.c); [source/write-up 3](https://github.com/Nautilus-Institute/finals-2024/blob/f17456fed4ff40e6f4f1237ed4b82c242e52ec67/bisbee/src/db/kv.h); [source/write-up 4](https://github.com/Nautilus-Institute/finals-2024/blob/f17456fed4ff40e6f4f1237ed4b82c242e52ec67/bisbee/src/db/kv_hashmap.c); [source/write-up 5](https://github.com/Nautilus-Institute/finals-2024/blob/f17456fed4ff40e6f4f1237ed4b82c242e52ec67/bisbee/src/db/kv_hashmap.h); [source/write-up 6](https://github.com/Nautilus-Institute/finals-2024/blob/f17456fed4ff40e6f4f1237ed4b82c242e52ec67/bisbee/src/db/kv_list.c).
|
||||
|
||||
**Reference:** [primary source](https://github.com/Nautilus-Institute/finals-2024/blob/f17456fed4ff40e6f4f1237ed4b82c242e52ec67/bisbee/src/service/src/main.rs).
|
||||
|
||||
**A/D variant:** In FlagDrive (ENOWARS10), capacity was calculated over a whole structure including an administrative flag, although data belonged only in the token array. Use the subarray's actual length/capacity, remove invalid reinterpretation and retain separate ownership checks. Test maximum token length and maximum+1 without changing adjacent authorization state. [Author write-up](https://github.com/enowars/enowars10-service-flagdrive/blob/d1575098fe2c516460136bb5fba11d9a1c4af3f7/documentation/FLAGSTORE_1.md). This is a service-specific memory-boundary/conversion defect, not a claim of a compiler defect.
|
||||
|
||||
<a id="rust-path-prefix"></a>
|
||||
|
||||
## RUST-PATH-PREFIX. Prefix validation and filesystem fallback
|
||||
|
||||
**Search:** manual review; no separate scanner rule.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'username|canonicalize|create_dir|fs::read|fs::write' .
|
||||
~~~
|
||||
|
||||
Compare the validated prefix with the entire path; check UTF-8 boundaries and alternative filesystem fallbacks.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
**DEF CON / bisbee, source.** Only part of username is checked, while the full name forms a path; an internal database miss falls back to file reading.
|
||||
|
||||
**Fix:** Validate the complete name and UTF-8 boundaries, select storage paths server-side, and apply identical authorization to primary and fallback paths.
|
||||
|
||||
**Verification:** Short/long/multibyte names, separators in the suffix and database misses.
|
||||
|
||||
**A/D variant:** Source and version: [source/write-up 1](https://github.com/Nautilus-Institute/finals-2024/blob/f17456fed4ff40e6f4f1237ed4b82c242e52ec67/bisbee/src/service/src/main.rs); [source/write-up 2](https://github.com/Nautilus-Institute/finals-2024/blob/f17456fed4ff40e6f4f1237ed4b82c242e52ec67/bisbee/src/db/kv.c); [source/write-up 3](https://github.com/Nautilus-Institute/finals-2024/blob/f17456fed4ff40e6f4f1237ed4b82c242e52ec67/bisbee/src/db/kv.h); [source/write-up 4](https://github.com/Nautilus-Institute/finals-2024/blob/f17456fed4ff40e6f4f1237ed4b82c242e52ec67/bisbee/src/db/kv_hashmap.c); [source/write-up 5](https://github.com/Nautilus-Institute/finals-2024/blob/f17456fed4ff40e6f4f1237ed4b82c242e52ec67/bisbee/src/db/kv_hashmap.h); [source/write-up 6](https://github.com/Nautilus-Institute/finals-2024/blob/f17456fed4ff40e6f4f1237ed4b82c242e52ec67/bisbee/src/db/kv_list.c).
|
||||
|
||||
**Reference:** [primary source](https://github.com/Nautilus-Institute/finals-2024/blob/f17456fed4ff40e6f4f1237ed4b82c242e52ec67/bisbee/src/service/src/main.rs).
|
||||
|
||||
<a id="rust-ffi-abi"></a>
|
||||
|
||||
## RUST-FFI-ABI. C and Rust extern return types disagree
|
||||
|
||||
**Search:** manual review; no separate scanner rule.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'extern|store_data|c_void|size_t' .
|
||||
~~~
|
||||
|
||||
Compare C headers/implementation with Rust declarations: return type, signedness, layout and calling convention.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
**DEF CON / bisbee, source and header.** C store_data returns void; Rust declares i8 and uses that result to select a fallback.
|
||||
|
||||
**Fix:** A shared ABI contract/generated bindings; consume status only through a real, identically typed return value. Never base error handling on an uninitialized result.
|
||||
|
||||
**Verification:** Builds with warnings, size/signedness/return-type agreement and ordinary storage failures.
|
||||
|
||||
**A/D variant:** Source and version: [source/write-up 1](https://github.com/Nautilus-Institute/finals-2024/blob/f17456fed4ff40e6f4f1237ed4b82c242e52ec67/bisbee/src/service/src/main.rs); [source/write-up 2](https://github.com/Nautilus-Institute/finals-2024/blob/f17456fed4ff40e6f4f1237ed4b82c242e52ec67/bisbee/src/db/kv.c); [source/write-up 3](https://github.com/Nautilus-Institute/finals-2024/blob/f17456fed4ff40e6f4f1237ed4b82c242e52ec67/bisbee/src/db/kv.h); [source/write-up 4](https://github.com/Nautilus-Institute/finals-2024/blob/f17456fed4ff40e6f4f1237ed4b82c242e52ec67/bisbee/src/db/kv_hashmap.c); [source/write-up 5](https://github.com/Nautilus-Institute/finals-2024/blob/f17456fed4ff40e6f4f1237ed4b82c242e52ec67/bisbee/src/db/kv_hashmap.h); [source/write-up 6](https://github.com/Nautilus-Institute/finals-2024/blob/f17456fed4ff40e6f4f1237ed4b82c242e52ec67/bisbee/src/db/kv_list.c).
|
||||
|
||||
**Reference:** [primary source](https://github.com/Nautilus-Institute/finals-2024/blob/f17456fed4ff40e6f4f1237ed4b82c242e52ec67/bisbee/src/service/src/main.rs).
|
||||
|
||||
<a id="rust-tls"></a>
|
||||
|
||||
## RUST-TLS. Rust HTTP accepts invalid certificates
|
||||
|
||||
**Search:** scanner rule RUST-TLS. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain RUST-TLS` for details. Regex: danger_accept_invalid_certs/hostnames(true), including reqwest/native-tls-like builders. Review variable values and custom verifiers.
|
||||
|
||||
**Vulnerable example:** Dangerous builder flags disable certificate/hostname validation.
|
||||
|
||||
~~~rust
|
||||
let client = reqwest::Client::builder().danger_accept_invalid_certs(true).build()?;
|
||||
~~~
|
||||
|
||||
**Fix:** Use default validation and add the internal root CA instead of bypassing checks.
|
||||
|
||||
~~~rust
|
||||
let client = reqwest::Client::builder().add_root_certificate(trusted_ca).build()?;
|
||||
~~~
|
||||
|
||||
**Verification:** Correct CA/host works; invalid certificates/hostnames fail.
|
||||
|
||||
Primary documentation: [reference 1](https://docs.rs/reqwest/latest/reqwest/struct.ClientBuilder.html).
|
||||
|
||||
<a id="rust-jwt-validation"></a>
|
||||
|
||||
## RUST-JWT-VALIDATION. Rust JWT checks disabled
|
||||
|
||||
**Search:** scanner rule RUST-JWT-VALIDATION. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain RUST-JWT-VALIDATION` for details. Regex: insecure_disable_signature_validation, validate_exp/validate_aud=false and legacy dangerous_*decode. API depends on jsonwebtoken version.
|
||||
|
||||
**Vulnerable example:** Without signature or expiry validation, decoded claims are insufficient grounds for granting access.
|
||||
|
||||
~~~rust
|
||||
validation.insecure_disable_signature_validation();
|
||||
validation.validate_exp = false;
|
||||
~~~
|
||||
|
||||
**Fix:** Use verifying decode with a trusted key and Validation contract; check its result before access.
|
||||
|
||||
~~~rust
|
||||
let mut validation = Validation::new(Algorithm::RS256);
|
||||
validation.set_audience(&["notes"]);
|
||||
validation.set_issuer(&["auth"]);
|
||||
validation.set_required_spec_claims(&["exp", "sub", "iss", "aud"]);
|
||||
~~~
|
||||
|
||||
**Verification:** Invalid signatures, expiry and missing required fields fail.
|
||||
|
||||
Primary documentation: [reference 1](https://docs.rs/jsonwebtoken/latest/jsonwebtoken/struct.Validation.html).
|
||||
@@ -0,0 +1,513 @@
|
||||
<a id="sql--databases-find-fix-and-verify"></a>
|
||||
|
||||
# SQL / базы данных: поиск и исправление
|
||||
|
||||
[English](sql.md) | Русский
|
||||
|
||||
[Вся база](README-RU.md) · [Сканер](../offline-scanner-RU.md) · [Проверка патча](../patch-validation-RU.md)
|
||||
|
||||
18 разделов. Формат: **Поиск → Уязвимый вариант → Исправление → Проверка**.
|
||||
Команды `rg` выполняются в корне локальной копии сервиса и только читают файлы. Субъект/владелец определяется по проверенной сессии, а не данным запроса. Примеры нужно адаптировать к реальным API и контракту.
|
||||
|
||||
Автоматические находки — ограниченные синтаксические сигналы для проверки. AST-анализ не разрешает типы и не отслеживает данные между функциями; regex не заменяет парсер языка. Комментарии, строки и одноимённые пользовательские API могут давать совпадения. Проверьте фактическое исполнение, входные данные, авторизацию и границы доверия.
|
||||
|
||||
<a id="contents"></a>
|
||||
|
||||
## Содержание
|
||||
|
||||
- [SQL-UPSERT — Upsert/replace требует проверки владельца](#sql-upsert)
|
||||
- [SQL-DEFINER — SECURITY DEFINER и доверие search_path](#sql-definer)
|
||||
- [SQL-BYPASSRLS — Роль приложения обходит RLS](#sql-bypassrls)
|
||||
- [SQL-PUBLIC-GRANT — Широкая выдача прав PUBLIC](#sql-public-grant)
|
||||
- [SQL-RLS-POLICY — RLS: USING, WITH CHECK и объединение политик](#sql-rls-policy)
|
||||
- [SQL-IDENTIFIERS — Параметры не подставляют имена таблиц и ORDER BY](#sql-identifiers)
|
||||
- [SQL-COLLATION — Разная канонизация в auth и unique constraint](#sql-collation)
|
||||
- [SQL-TRANSACTION — Проверка и изменение вне одной атомарной операции](#sql-transaction)
|
||||
- [SQL-POOL-CONTEXT — Пул соединений сохраняет tenant/search_path](#sql-pool-context)
|
||||
- [SQL-SQLITE-FK — SQLite foreign_keys явно отключён](#sql-sqlite-fk)
|
||||
- [SQL-MYSQL-PRIVILEGES — MySQL FILE и административные права app](#sql-mysql-privileges)
|
||||
- [SQL-SECOND-ORDER — Сохранённое значение снова становится SQL](#sql-second-order)
|
||||
- [SQL-NESTED-DSL — Несколько уровней языка запроса](#sql-nested-dsl)
|
||||
- [SQL-RLS-DISABLE — PostgreSQL RLS отключают для таблицы](#sql-rls-disable)
|
||||
- [SQL-TOKEN-PREFIX — Секретный токен проверяется по префиксу или диапазону](#sql-token-prefix)
|
||||
- [SQL-NULL-AUTH — NULL меняет смысл проверки доступа](#sql-null-auth)
|
||||
- [SQL-RLS-ALLOW-ALL — Безусловное выражение в политике RLS](#sql-rls-allow-all)
|
||||
|
||||
- [SQL-SERVER-ROLE — Выданы роли PostgreSQL для файлов и программ сервера](#sql-server-role)
|
||||
|
||||
<a id="sql-upsert"></a>
|
||||
|
||||
<a id="sql-upsert-upsertreplace-requires-ownership-review"></a>
|
||||
|
||||
## SQL-UPSERT. Upsert/replace требует проверки владельца
|
||||
|
||||
**Поиск:** скрипт, правило SQL-UPSERT. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain SQL-UPSERT. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
~~~sql
|
||||
INSERT INTO notes(id, owner, body) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE body=VALUES(body);
|
||||
~~~
|
||||
|
||||
**Исправление:** Разделить создание и обновление; нормализация/колляция до проверки, ownership в атомарном UPDATE. Проверить число изменённых строк, уникальность и транзакцию.
|
||||
|
||||
~~~sql
|
||||
UPDATE notes SET body=? WHERE id=? AND owner=?;
|
||||
~~~
|
||||
|
||||
**Проверка:** Конфликт после case-fold/Unicode/триггера не обновляет чужую запись; штатное создание/редактирование сохранены.
|
||||
|
||||
**Вариант A/D:** Нормализация ключа после проверки + upsert. **RuCTF / rusi-trainer, автор.** Поиск прав использовал исходное имя, а триггер
|
||||
БД нормализовал ключ перед вставкой; конфликт превращал её в обновление.
|
||||
|
||||
**Патч:** единая канонизация и колляция, разделить insert/update, ownership
|
||||
в самой мутации. Замена СУБД не универсальное исправление.
|
||||
**Тест:** Unicode/case-варианты, конфликт уникальности, параллельная вставка.
|
||||
**Поиск:** SQL-UPSERT; триггер и сопоставление ключей вручную.
|
||||
|
||||
[исходник/разбор 1](https://github.com/HackerDom/ructf-2023/blob/0cc333e44f2ba6908ff6c5d613146e3b00173315/writeups/rusi-trainer/README.md).
|
||||
|
||||
<a id="sql-definer"></a>
|
||||
|
||||
<a id="sql-definer-security-definer-and-search_path-trust"></a>
|
||||
|
||||
## SQL-DEFINER. SECURITY DEFINER и доверие search_path
|
||||
|
||||
**Поиск:** скрипт, правило SQL-DEFINER. Запуск: из DurkaHelper — python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain SQL-DEFINER. Это синтаксический сигнал, не проверка потока данных: проследить вход, валидацию и все вызовы найденного API.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
~~~sql
|
||||
CREATE FUNCTION f() RETURNS int LANGUAGE sql SECURITY DEFINER AS $$ SELECT value FROM settings $$;
|
||||
~~~
|
||||
|
||||
**Исправление:** Если повышенные права не нужны — INVOKER. Иначе минимальный владелец, безопасный фиксированный search_path с pg_temp в конце, schema-qualified объекты и ограниченный EXECUTE.
|
||||
|
||||
~~~sql
|
||||
CREATE FUNCTION f() RETURNS int LANGUAGE sql SECURITY INVOKER AS $$ SELECT value FROM app.settings $$;
|
||||
~~~
|
||||
|
||||
**Проверка:** Пользователь не может подменить объект временной/доступной схемой; обычный вызов сохраняет права.
|
||||
|
||||
**Основание:** [первичный материал](https://www.postgresql.org/docs/current/sql-createfunction.html).
|
||||
|
||||
<a id="sql-bypassrls"></a>
|
||||
|
||||
<a id="sql-bypassrls-application-role-bypasses-rls"></a>
|
||||
|
||||
## SQL-BYPASSRLS. Роль приложения обходит RLS
|
||||
|
||||
**Поиск:** правило сканера SQL-BYPASSRLS. Подробности: `--explain SQL-BYPASSRLS`. Ограниченный SQL-поиск: CREATE/ALTER ROLE или USER с явным SUPERUSER/BYPASSRLS. Комментарии и строки исключены; keywords без кавычек, до 300 символов. Поздние overrides, владелец таблиц, наследуемые роли и фактическая runtime-политика требуют ручной проверки.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
~~~sql
|
||||
ALTER ROLE app BYPASSRLS;
|
||||
~~~
|
||||
|
||||
**Исправление:** Отдельная роль приложения без повышенных атрибутов; владельца таблицы проверять отдельно. FORCE RLS не ограничивает superuser/BYPASSRLS.
|
||||
|
||||
~~~sql
|
||||
ALTER ROLE app NOBYPASSRLS NOSUPERUSER;
|
||||
~~~
|
||||
|
||||
**Проверка:** SELECT/INSERT/UPDATE от реальной роли двух tenant; миграционная роль отдельно.
|
||||
|
||||
**Основание:** [первичный материал](https://www.postgresql.org/docs/current/ddl-rowsecurity.html).
|
||||
|
||||
<a id="sql-public-grant"></a>
|
||||
|
||||
<a id="sql-public-grant-broad-privileges-granted-to-public"></a>
|
||||
|
||||
## SQL-PUBLIC-GRANT. Широкая выдача прав PUBLIC
|
||||
|
||||
**Поиск:** правило сканера SQL-PUBLIC-GRANT. Подробности: `--explain SQL-PUBLIC-GRANT`. Ограниченный SQL-поиск: GRANT ALL или списки SELECT/INSERT/UPDATE/DELETE/TRUNCATE/REFERENCES/TRIGGER/CREATE/USAGE/EXECUTE/CONNECT/TEMPORARY/TEMP ON object TO PUBLIC. Комментарии/строки исключены; совпадение не пересекает statements. Quoted identifiers, defaults, сложные grants, реальные права и намеренно общие объекты проверяются вручную.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
~~~sql
|
||||
GRANT ALL ON notes TO PUBLIC;
|
||||
~~~
|
||||
|
||||
**Исправление:** Выдать конкретной роли необходимые действия; проверить старые и default privileges, sequences и функции. Не отзывать права чужой инфраструктуры.
|
||||
|
||||
~~~sql
|
||||
GRANT SELECT, INSERT, UPDATE ON notes TO app;
|
||||
~~~
|
||||
|
||||
**Проверка:** Нет доступа соседней роли; app создаёт ID/читает старые данные.
|
||||
|
||||
**Основание:** [первичный материал](https://www.postgresql.org/docs/current/sql-grant.html).
|
||||
|
||||
<a id="sql-rls-policy"></a>
|
||||
|
||||
<a id="sql-rls-policy-rls-using-with-check-and-policy-composition"></a>
|
||||
|
||||
## SQL-RLS-POLICY. RLS: USING, WITH CHECK и объединение политик
|
||||
|
||||
**Поиск:** вручную; отдельного правила сканера нет.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'CREATE POLICY|ROW LEVEL SECURITY|USING|WITH CHECK' .
|
||||
~~~
|
||||
|
||||
Сверить роль приложения, SELECT/UPDATE/INSERT, owner bypass и OR между permissive policies.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
Новая широкая policy делает прежнее ограничение бесполезным либо изменение tenant не контролируется.
|
||||
|
||||
**Исправление:** Политика чтения и нового состояния по контракту, тестировать effective role; ограничения RLS не заменяют object-level app policy.
|
||||
|
||||
**Проверка:** Чужая строка скрыта и tenant нельзя изменить; migrations/checker работают.
|
||||
|
||||
**Основание:** [первичный материал](https://www.postgresql.org/docs/current/ddl-rowsecurity.html).
|
||||
|
||||
<a id="sql-identifiers"></a>
|
||||
|
||||
<a id="sql-identifiers-parameters-do-not-substitute-table-names-or-order-by"></a>
|
||||
|
||||
## SQL-IDENTIFIERS. Параметры не подставляют имена таблиц и ORDER BY
|
||||
|
||||
**Поиск:** вручную; отдельного правила сканера нет.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'ORDER BY|table_name|column_name|quote_ident|identifier' .
|
||||
~~~
|
||||
|
||||
Найти все динамические identifiers и направление сортировки, отдельно от значений.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
Конкатенация order/column из запроса меняет синтаксис; placeholder для имени не работает как ожидается.
|
||||
|
||||
**Исправление:** Фиксированная карта допустимых identifiers/направлений, quoting API драйвера при необходимости; значения параметризовать.
|
||||
|
||||
**Проверка:** Разрешённая сортировка сохраняется, неизвестное поле/направление отвергаются.
|
||||
|
||||
<a id="sql-collation"></a>
|
||||
|
||||
<a id="sql-collation-authorization-and-uniqueness-use-different-canonicalization"></a>
|
||||
|
||||
## SQL-COLLATION. Разная канонизация в auth и unique constraint
|
||||
|
||||
**Поиск:** вручную; отдельного правила сканера нет.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'COLLATE|LOWER\(|UPPER\(|UNIQUE|TRIGGER|citext' .
|
||||
~~~
|
||||
|
||||
Сопоставить сравнение приложения, collation БД, trigger и уникальный индекс.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
Два имени различаются при проверке прав, но считаются одним при записи.
|
||||
|
||||
**Исправление:** Единая канонизация до проверки/записи и стабильный owner ID; миграция конфликтов, не просто смена всей БД.
|
||||
|
||||
**Проверка:** Case/Unicode/trailing spaces по реальной БД, старые ссылки и уникальность.
|
||||
|
||||
<a id="sql-transaction"></a>
|
||||
|
||||
<a id="sql-transaction-check-and-mutation-are-not-one-atomic-operation"></a>
|
||||
|
||||
## SQL-TRANSACTION. Проверка и изменение вне одной атомарной операции
|
||||
|
||||
**Поиск:** вручную; отдельного правила сканера нет.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'SELECT|UPDATE|DELETE|BEGIN|FOR UPDATE|version' .
|
||||
~~~
|
||||
|
||||
Сверить isolation level и where условия записи, число изменённых строк.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
Два запроса проходят SELECT-проверку и оба тратят ресурс/меняют чужое после смены owner.
|
||||
|
||||
**Исправление:** Условный UPDATE/DELETE с owner/version/остатком, транзакция и bounded retry; выбрать нужный уровень изоляции.
|
||||
|
||||
**Проверка:** Детерминированная гонка, conflict/rollback и штатная конкурентность.
|
||||
|
||||
<a id="sql-pool-context"></a>
|
||||
|
||||
<a id="sql-pool-context-connection-pools-retain-tenant-or-search_path"></a>
|
||||
|
||||
## SQL-POOL-CONTEXT. Пул соединений сохраняет tenant/search_path
|
||||
|
||||
**Поиск:** вручную; отдельного правила сканера нет.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'SET ROLE|SET search_path|set_config|tenant|pool|RESET' .
|
||||
~~~
|
||||
|
||||
Сравнить session-level SET и transaction-local SET; проверить возврат соединения после ошибки.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
Следующий запрос получает прежнюю роль/schema/tenant.
|
||||
|
||||
**Исправление:** SET LOCAL в корректной транзакции либо надёжный reset; owner не из client-controlled session variable.
|
||||
|
||||
**Проверка:** Два tenant на одном соединении, rollback/exception и обычный повторный запрос.
|
||||
|
||||
**Основание:** [первичный материал](https://www.postgresql.org/docs/current/ddl-schemas.html).
|
||||
|
||||
<a id="sql-sqlite-fk"></a>
|
||||
|
||||
<a id="sql-sqlite-fk-sqlite-foreign_keys-explicitly-disabled"></a>
|
||||
|
||||
## SQL-SQLITE-FK. SQLite foreign_keys явно отключён
|
||||
|
||||
**Поиск:** скрипт, правило SQL-SQLITE-FK. Запуск: python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain SQL-SQLITE-FK. Regex: PRAGMA foreign_keys=OFF/0/false или foreign_keys(OFF/0/false). Отсутствие ON, pool hooks и compile options требуют ручной проверки.
|
||||
|
||||
Дополнительный ручной поиск для непокрытых форм:
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'PRAGMA foreign_keys|sqlite3.connect|Data Source|FOREIGN KEY' .
|
||||
~~~
|
||||
|
||||
Проверить фактический PRAGMA после открытия каждого connection и до начала транзакции.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
DDL содержит FK, приложение считает ownership связи гарантированными, enforcement отключён.
|
||||
|
||||
**Исправление:** Включить foreign_keys для каждого соединения вне транзакции, проверить результат и существующие нарушения; отдельно мигрировать некорректные записи и обработать constraint errors.
|
||||
|
||||
**Проверка:** Каждое соединение сообщает foreign_keys=1; foreign_key_check не возвращает нарушений; недопустимый владелец отклоняется, каскады и старые данные совместимы.
|
||||
|
||||
**Основание:** [первичный материал](https://www.sqlite.org/pragma.html#pragma_foreign_keys).
|
||||
|
||||
|
||||
**Сигнал сканера — пример до:**
|
||||
|
||||
~~~sql
|
||||
PRAGMA foreign_keys = OFF;
|
||||
~~~
|
||||
|
||||
**Шаблон исправления:**
|
||||
|
||||
~~~sql
|
||||
PRAGMA foreign_keys = ON;
|
||||
~~~
|
||||
|
||||
Первичная документация: [документация 1](https://www.sqlite.org/foreignkeys.html).
|
||||
|
||||
<a id="sql-mysql-privileges"></a>
|
||||
|
||||
<a id="sql-mysql-privileges-mysql-runtime-user-has-admin-privileges"></a>
|
||||
|
||||
## SQL-MYSQL-PRIVILEGES. MySQL FILE и административные права app
|
||||
|
||||
**Поиск:** скрипт, правило SQL-MYSQL-PRIVILEGES. Запуск: python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain SQL-MYSQL-PRIVILEGES. Regex: GRANT с FILE/SUPER или ALL [PRIVILEGES] ON *.*. Другие опасные dynamic privileges, роли и уже выданные права вручную.
|
||||
|
||||
Дополнительный ручной поиск для непокрытых форм:
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'GRANT|FILE|SUPER|ALL PRIVILEGES|secure_file_priv|local_infile' .
|
||||
~~~
|
||||
|
||||
Прочитать SHOW GRANTS своей app-роли; проверить FILE, чтение/запись и настройки LOCAL INFILE обеих сторон.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
Обычное приложение имеет права файлового/административного доступа, которые усиливают ошибку запроса.
|
||||
|
||||
**Исправление:** Разделить runtime-аккаунт и аккаунт миграций; убрать ненужные глобальные привилегии и GRANT OPTION; ограничить hosts аккаунтов реальной топологией. Согласовать secure_file_priv и отключение ненужного LOCAL INFILE.
|
||||
|
||||
**Проверка:** SHOW GRANTS содержит только необходимые права; CRUD, миграции и checker работают, операция вне полномочий отвергается; аккаунты организаторов не менять.
|
||||
|
||||
**Основание:** [первичный материал](https://dev.mysql.com/doc/refman/8.4/en/privileges-provided.html).
|
||||
|
||||
|
||||
**Сигнал сканера — пример до:**
|
||||
|
||||
~~~sql
|
||||
GRANT FILE, SUPER ON *.* TO 'app'@'%';
|
||||
~~~
|
||||
|
||||
**Шаблон исправления:**
|
||||
|
||||
~~~sql
|
||||
GRANT SELECT, INSERT, UPDATE, DELETE ON appdb.* TO 'app'@'localhost';
|
||||
~~~
|
||||
|
||||
Первичная документация: [документация 1](https://dev.mysql.com/doc/refman/8.4/en/privileges-provided.html).
|
||||
|
||||
<a id="sql-second-order"></a>
|
||||
|
||||
<a id="sql-second-order-stored-data-becomes-sql-again"></a>
|
||||
|
||||
## SQL-SECOND-ORDER. Сохранённое значение снова становится SQL
|
||||
|
||||
**Поиск:** вручную; отдельного правила сканера нет.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'execute|query|EXECUTE|format\(|quote|SELECT' .
|
||||
~~~
|
||||
|
||||
Проследить значение из БД до второго запроса/export/job; хранение не делает данные доверенными.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
При insert значение параметризовано, позже строка из записи вставляется в динамический SQL.
|
||||
|
||||
**Исправление:** Параметризация на каждом sink, включая stored procedures и jobs; отдельная карта identifiers.
|
||||
|
||||
**Проверка:** Сохранённое значение с разделителем остаётся данными при последующей операции.
|
||||
|
||||
<a id="sql-nested-dsl"></a>
|
||||
|
||||
<a id="sql-nested-dsl-multiple-query-language-layers"></a>
|
||||
|
||||
## SQL-NESTED-DSL. Несколько уровней языка запроса
|
||||
|
||||
**Поиск:** вручную; отдельного правила сканера нет.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'LIKE|database|tenant|parse|execute' .
|
||||
~~~
|
||||
|
||||
Разделить внешний DSL, внутренний SQL и выбор базы; проверить интерпретацию разделителей на обоих уровнях.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
**Основание:** museumorphosis, авторский разбор RuCTF: собственный SQL DSL и
|
||||
плохая граница между запросом и выбором базы.
|
||||
**Искать:** SQL внутри строк другого языка, regex вместо полноценного парсера,
|
||||
пользовательский текст в LIKE, имя базы/tenant.
|
||||
|
||||
**Исправление:** параметры для значений на каждом уровне; выбор базы из проверенного
|
||||
серверного tenant; однозначный парсер DSL. Экранирование внутреннего SQL
|
||||
не доказывает безопасность внешнего языка.
|
||||
|
||||
**Проверка:** разделители обоих языков, обычные wildcard согласно контракту,
|
||||
попытка сменить базу, доступ только к своему tenant.
|
||||
|
||||
**Вариант A/D:** Основание и версия: [исходник/разбор 1](https://github.com/HackerDom/ructf-finals-2023/blob/a7442769909e08c39716cb18d3d1c3a99324bbf8/writeups/museumorphosis/README.md).
|
||||
|
||||
**Основание:** [первичный материал](https://github.com/HackerDom/ructf-finals-2023/blob/a7442769909e08c39716cb18d3d1c3a99324bbf8/writeups/museumorphosis/README.md).
|
||||
|
||||
<a id="sql-rls-disable"></a>
|
||||
|
||||
<a id="sql-rls-disable-postgresql-table-rls-disabled"></a>
|
||||
|
||||
## SQL-RLS-DISABLE. PostgreSQL RLS отключают для таблицы
|
||||
|
||||
**Поиск:** скрипт, правило SQL-RLS-DISABLE. Запуск: python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain SQL-RLS-DISABLE. Regex: ALTER TABLE ... DISABLE ROW LEVEL SECURITY. Отсутствие ENABLE, широкие политики и роль соединения не выводятся из текста.
|
||||
|
||||
**Уязвимый вариант:** Отключение RLS снимает серверную границу строк, если доступ полагается на политики.
|
||||
|
||||
~~~sql
|
||||
ALTER TABLE notes DISABLE ROW LEVEL SECURITY;
|
||||
~~~
|
||||
|
||||
**Исправление:** Установить нужные policies и включить RLS; runtime не должен быть superuser/BYPASSRLS. FORCE влияет на владельца, но не устраняет эти bypass-привилегии.
|
||||
|
||||
~~~sql
|
||||
ALTER TABLE notes ENABLE ROW LEVEL SECURITY;
|
||||
ALTER TABLE notes FORCE ROW LEVEL SECURITY;
|
||||
-- Install reviewed owner/tenant policies before serving traffic.
|
||||
~~~
|
||||
|
||||
**Проверка:** Проверить SELECT/INSERT/UPDATE/DELETE двумя runtime субъектами и чужим tenant; migration user отдельно.
|
||||
|
||||
Первичная документация: [документация 1](https://www.postgresql.org/docs/current/ddl-rowsecurity.html).
|
||||
|
||||
<a id="sql-token-prefix"></a>
|
||||
|
||||
<a id="sql-token-prefix-secret-token-checked-by-prefix-or-range"></a>
|
||||
|
||||
## SQL-TOKEN-PREFIX. Секретный токен проверяется по префиксу или диапазону
|
||||
|
||||
**Поиск:** скрипт, правило SQL-TOKEN-PREFIX. Запуск: python3 -I -S scripts/defense_scan.py /path/to/service --patches; подробности — --explain SQL-TOKEN-PREFIX. Regex: nonce/token/reset_token/api_key перед LIKE, >= или <= в SQL-тексте. Числовые счётчики и поиск служебных журналов могут быть допустимы; переименованные поля, substr, startsWith и сравнение части в приложении искать вручную.
|
||||
|
||||
**Уязвимый вариант:** Если nonce/token является bearer-секретом, частичное совпадение резко уменьшает пространство проверки.
|
||||
|
||||
~~~sql
|
||||
SELECT content FROM exports WHERE username = $1 AND nonce >= $2 AND nonce < $3;
|
||||
~~~
|
||||
|
||||
**Исправление:** Требовать полный канонический токен допустимой длины, точное совпадение и связь с пользователем/действием/сроком; не заменять проверку rate limit.
|
||||
|
||||
~~~sql
|
||||
SELECT content FROM exports WHERE username = $1 AND nonce = $2;
|
||||
-- Before querying: require the full canonical token, correct length/type and purpose.
|
||||
~~~
|
||||
|
||||
**Проверка:** Пустой, короткий, префиксный, лишний суффикс и токен другого пользователя отвергнуты; полный действующий токен работает.
|
||||
|
||||
Первичная документация: [документация 1](https://github.com/enowars/enowars10-service-flagdrive/blob/d1575098fe2c516460136bb5fba11d9a1c4af3f7/documentation/FLAGSTORE_0.md).
|
||||
|
||||
|
||||
**Вариант A/D:** авторы FlagDrive (ENOWARS10) описали выбор экспорта по короткому префиксу nonce. Исправление требует полной длины и точного равенства; правило отмечает SQL-диапазон, а смысл bearer-секрета проверяется вручную.
|
||||
|
||||
<a id="sql-null-auth"></a>
|
||||
|
||||
<a id="sql-null-auth-null-changes-authorization-logic"></a>
|
||||
|
||||
## SQL-NULL-AUTH. NULL меняет смысл проверки доступа
|
||||
|
||||
**Поиск:** вручную; отдельного правила сканера нет.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'NOT IN|!=|<>|IS NULL|IS NOT NULL|COALESCE|LEFT JOIN|owner|tenant' .
|
||||
~~~
|
||||
|
||||
Составить таблицу TRUE/FALSE/UNKNOWN для auth-условия и результата LEFT JOIN. Проследить, как приложение превращает nullable bool в разрешение/отказ, есть ли NULL в NOT IN subquery.
|
||||
|
||||
**Уязвимый вариант:** Условие отказа owner <> actor даёт UNKNOWN при NULL, и приложение проваливается в разрешённую ветку; отсутствующая ACL трактуется как default allow.
|
||||
|
||||
**Исправление:** Разрешать доступ только при явно истинной положительной проверке. Где NULL недопустим — NOT NULL и целостная связь; где допустим — задать его точный смысл, не подменять владельца общим значением через COALESCE.
|
||||
|
||||
**Проверка:** NULL owner, отсутствующая ACL, пустой join и NULL внутри подзапроса не дают доступа; обычные own/shared сценарии сохраняются.
|
||||
|
||||
Основание: [первичная документация/материал](https://www.postgresql.org/docs/current/functions-comparison.html). Описание и рецепт адаптации составлены для этой базы.
|
||||
|
||||
<a id="sql-rls-allow-all"></a>
|
||||
|
||||
<a id="sql-rls-allow-all-rls-policy-has-an-unconditional-expression"></a>
|
||||
|
||||
## SQL-RLS-ALLOW-ALL. Безусловное выражение в политике RLS
|
||||
|
||||
**Поиск:** правило сканера SQL-RLS-ALLOW-ALL. Точный контракт детектора: `--explain SQL-RLS-ALLOW-ALL`. Regex с лексическими исключениями: USING(true) или WITH CHECK(true). Может быть намеренным; правило не связывает выражения с CREATE POLICY, ролями и командами. Фактические политики и авторизация приложения требуют проверки.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
~~~sql
|
||||
CREATE POLICY open_notes ON notes USING (true);
|
||||
~~~
|
||||
|
||||
**Исправление:** Определите выражения USING и WITH CHECK с учётом ролей и арендаторов для реальной модели идентификации; проверьте сочетания разрешающих политик и роли, обходящие RLS.
|
||||
|
||||
~~~sql
|
||||
CREATE POLICY owned_notes ON notes USING (owner_id = current_user);
|
||||
~~~
|
||||
|
||||
**Проверка:** Два пользователя времени исполнения не могут читать или менять строки друг друга; INSERT и UPDATE проверяют нужного владельца, а допустимые операции работают.
|
||||
|
||||
[Первичный источник 1](https://www.postgresql.org/docs/current/sql-createpolicy.html)
|
||||
|
||||
<a id="sql-server-role"></a>
|
||||
<a id="sql-server-role-postgresql-server-fileprogram-role-granted"></a>
|
||||
|
||||
## SQL-SERVER-ROLE. Выданы роли PostgreSQL для файлов и программ сервера
|
||||
|
||||
**Поиск:** правило сканера SQL-SERVER-ROLE. Подробности: `--explain SQL-SERVER-ROLE`. Ограниченный SQL-поиск: GRANT списка ролей без кавычек, содержащего pg_read_server_files, pg_write_server_files или pg_execute_server_program перед TO. Комментарии/строки исключены; REVOKE и отдельный pg_monitor не дают сигнал. Quoted roles, наследование, поздние отзывы прав, версии и эффективные права проверяются вручную.
|
||||
|
||||
**Уязвимый вариант:**
|
||||
|
||||
~~~sql
|
||||
GRANT pg_read_server_files TO app;
|
||||
~~~
|
||||
|
||||
**Исправление:** Разделите роли приложения и администратора. Выдавайте необходимые права на объекты, а не файлы/программы сервера; проверяйте членство. Отзывайте только согласованные права своего сервиса с процедурой rollback.
|
||||
|
||||
~~~sql
|
||||
GRANT SELECT ON notes TO app;
|
||||
~~~
|
||||
|
||||
**Проверка:** Фактическая runtime-роль не читает/пишет файлы сервера и не запускает программы; обычные запросы, миграции и восстановление работают.
|
||||
|
||||
[Первичный источник](https://www.postgresql.org/docs/14/predefined-roles.html)
|
||||
@@ -0,0 +1,461 @@
|
||||
# SQL / databases: find, fix and verify
|
||||
|
||||
English | [Русский](sql-RU.md)
|
||||
|
||||
[Catalog](README.md) · [Scanner](../offline-scanner.md) · [Patch verification](../patch-validation.md)
|
||||
|
||||
18 sections. Each follows **Search → Vulnerable example → Fix → Verification**.
|
||||
Run `rg` from a local service checkout; searches only read files. Derive the actor/owner from a verified session, not request data. Adapt examples to the actual API and contract.
|
||||
|
||||
## Contents
|
||||
|
||||
- [SQL-UPSERT — Upsert/replace requires ownership review](#sql-upsert)
|
||||
- [SQL-DEFINER — SECURITY DEFINER and search_path trust](#sql-definer)
|
||||
- [SQL-BYPASSRLS — Application role bypasses RLS](#sql-bypassrls)
|
||||
- [SQL-PUBLIC-GRANT — Broad privileges granted to PUBLIC](#sql-public-grant)
|
||||
- [SQL-RLS-POLICY — RLS USING, WITH CHECK and policy composition](#sql-rls-policy)
|
||||
- [SQL-IDENTIFIERS — Parameters do not substitute table names or ORDER BY](#sql-identifiers)
|
||||
- [SQL-COLLATION — Authorization and uniqueness use different canonicalization](#sql-collation)
|
||||
- [SQL-TRANSACTION — Check and mutation are not one atomic operation](#sql-transaction)
|
||||
- [SQL-POOL-CONTEXT — Connection pools retain tenant or search_path](#sql-pool-context)
|
||||
- [SQL-SQLITE-FK — SQLite foreign_keys explicitly disabled](#sql-sqlite-fk)
|
||||
- [SQL-MYSQL-PRIVILEGES — MySQL runtime user has admin privileges](#sql-mysql-privileges)
|
||||
- [SQL-SECOND-ORDER — Stored data becomes SQL again](#sql-second-order)
|
||||
- [SQL-NESTED-DSL — Multiple query-language layers](#sql-nested-dsl)
|
||||
- [SQL-RLS-DISABLE — PostgreSQL table RLS disabled](#sql-rls-disable)
|
||||
- [SQL-TOKEN-PREFIX — Secret token checked by prefix or range](#sql-token-prefix)
|
||||
- [SQL-NULL-AUTH — NULL changes authorization logic](#sql-null-auth)
|
||||
- [SQL-RLS-ALLOW-ALL — RLS policy has an unconditional expression](#sql-rls-allow-all)
|
||||
- [SQL-SERVER-ROLE — PostgreSQL server file/program role granted](#sql-server-role)
|
||||
|
||||
<a id="sql-upsert"></a>
|
||||
|
||||
## SQL-UPSERT. Upsert/replace requires ownership review
|
||||
|
||||
**Search:** scanner rule SQL-UPSERT. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain SQL-UPSERT` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
~~~sql
|
||||
INSERT INTO notes(id, owner, body) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE body=VALUES(body);
|
||||
~~~
|
||||
|
||||
**Fix:** Separate create/update, normalize before authorization, enforce ownership in atomic UPDATE and check rows, uniqueness and transactions.
|
||||
|
||||
~~~sql
|
||||
UPDATE notes SET body=? WHERE id=? AND owner=?;
|
||||
~~~
|
||||
|
||||
**Verification:** Case/Unicode/trigger conflicts cannot update another owner; normal edits work.
|
||||
|
||||
**A/D variant:** Key normalization after authorization plus upsert. **RuCTF / rusi-trainer, author write-up.** Authorization used the original name, but a database trigger normalized the key before insertion; a conflict converted the insert into an update.
|
||||
|
||||
**Patch:** Apply consistent canonicalization/collation, separate insert from update, and enforce ownership in the mutation itself. Switching database engines is not a universal fix.
|
||||
**Test:** Unicode/case variants, uniqueness conflicts and concurrent inserts.
|
||||
**Search:** SQL-UPSERT; review triggers and key comparison manually.
|
||||
|
||||
[Source/write-up 1](https://github.com/HackerDom/ructf-2023/blob/0cc333e44f2ba6908ff6c5d613146e3b00173315/writeups/rusi-trainer/README.md).
|
||||
|
||||
<a id="sql-definer"></a>
|
||||
|
||||
## SQL-DEFINER. SECURITY DEFINER and search_path trust
|
||||
|
||||
**Search:** scanner rule SQL-DEFINER. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain SQL-DEFINER` for details. Bounded textual heuristic, not a language parser or taint analysis. Comments, strings and same-named APIs can match; inspect actual execution and trust boundaries.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
~~~sql
|
||||
CREATE FUNCTION f() RETURNS int LANGUAGE sql SECURITY DEFINER AS $$ SELECT value FROM settings $$;
|
||||
~~~
|
||||
|
||||
**Fix:** Prefer INVOKER unless elevated rights are needed; otherwise use a minimal owner, fixed safe search_path with pg_temp last, qualified names and restricted EXECUTE.
|
||||
|
||||
~~~sql
|
||||
CREATE FUNCTION f() RETURNS int LANGUAGE sql SECURITY INVOKER AS $$ SELECT value FROM app.settings $$;
|
||||
~~~
|
||||
|
||||
**Verification:** Callers cannot replace objects using temporary/writable schemas; valid calls work.
|
||||
|
||||
**Reference:** [primary source](https://www.postgresql.org/docs/current/sql-createfunction.html).
|
||||
|
||||
<a id="sql-bypassrls"></a>
|
||||
|
||||
## SQL-BYPASSRLS. Application role bypasses RLS
|
||||
|
||||
**Search:** scanner rule SQL-BYPASSRLS. Use `--explain SQL-BYPASSRLS` for the exact detector contract. Bounded SQL: CREATE/ALTER ROLE or USER with explicit SUPERUSER/BYPASSRLS, comments and quoted strings excluded, unquoted keywords and statements up to 300 characters. Later overrides, ownership, inherited roles and effective runtime policy remain manual.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
~~~sql
|
||||
ALTER ROLE app BYPASSRLS;
|
||||
~~~
|
||||
|
||||
**Fix:** Use a runtime role without elevated attributes and review table ownership separately; FORCE RLS does not constrain superuser/BYPASSRLS.
|
||||
|
||||
~~~sql
|
||||
ALTER ROLE app NOBYPASSRLS NOSUPERUSER;
|
||||
~~~
|
||||
|
||||
**Verification:** Actual runtime roles for two tenants cannot cross boundaries; migration role is separate.
|
||||
|
||||
**Reference:** [primary source](https://www.postgresql.org/docs/current/ddl-rowsecurity.html).
|
||||
|
||||
<a id="sql-public-grant"></a>
|
||||
|
||||
## SQL-PUBLIC-GRANT. Broad privileges granted to PUBLIC
|
||||
|
||||
**Search:** scanner rule SQL-PUBLIC-GRANT. Use `--explain SQL-PUBLIC-GRANT` for the exact detector contract. Bounded SQL: GRANT ALL or SELECT/INSERT/UPDATE/DELETE/TRUNCATE/REFERENCES/TRIGGER/CREATE/USAGE/EXECUTE/CONNECT/TEMPORARY/TEMP privilege lists ON an object TO PUBLIC. Comments/strings excluded; no cross-statement matching. Quoted identifiers, defaults, complex grants, effective rights and intentional public objects remain manual.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
~~~sql
|
||||
GRANT ALL ON notes TO PUBLIC;
|
||||
~~~
|
||||
|
||||
**Fix:** Grant only required actions to specific roles; review existing/default privileges, sequences and functions. Never revoke unrelated infrastructure rights.
|
||||
|
||||
~~~sql
|
||||
GRANT SELECT, INSERT, UPDATE ON notes TO app;
|
||||
~~~
|
||||
|
||||
**Verification:** Neighbor roles cannot read data; app ID generation and old records work.
|
||||
|
||||
**Reference:** [primary source](https://www.postgresql.org/docs/current/sql-grant.html).
|
||||
|
||||
<a id="sql-rls-policy"></a>
|
||||
|
||||
## SQL-RLS-POLICY. RLS USING, WITH CHECK and policy composition
|
||||
|
||||
**Search:** manual review; no separate scanner rule.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'CREATE POLICY|ROW LEVEL SECURITY|USING|WITH CHECK' .
|
||||
~~~
|
||||
|
||||
Review the application role, SELECT/UPDATE/INSERT, owner bypass and OR composition between permissive policies.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
A new broad policy makes an earlier restriction ineffective, or a tenant-changing update is unchecked.
|
||||
|
||||
**Fix:** Define policies for reads and resulting row state according to the contract; test the effective role. RLS does not replace application object-level authorization.
|
||||
|
||||
**Verification:** Other tenants' rows stay hidden, tenant changes are denied, and migrations/checkers still work.
|
||||
|
||||
**Reference:** [primary source](https://www.postgresql.org/docs/current/ddl-rowsecurity.html).
|
||||
|
||||
<a id="sql-identifiers"></a>
|
||||
|
||||
## SQL-IDENTIFIERS. Parameters do not substitute table names or ORDER BY
|
||||
|
||||
**Search:** manual review; no separate scanner rule.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'ORDER BY|table_name|column_name|quote_ident|identifier' .
|
||||
~~~
|
||||
|
||||
Find dynamic identifiers and sorting directions separately from data values.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
Concatenated request order/column values change syntax; an identifier placeholder does not behave as expected.
|
||||
|
||||
**Fix:** Map allowed identifiers/directions explicitly, using the driver's quoting API where required; parameterize values.
|
||||
|
||||
**Verification:** Permitted sorting remains available; unknown fields/directions are rejected.
|
||||
|
||||
<a id="sql-collation"></a>
|
||||
|
||||
## SQL-COLLATION. Authorization and uniqueness use different canonicalization
|
||||
|
||||
**Search:** manual review; no separate scanner rule.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'COLLATE|LOWER\(|UPPER\(|UNIQUE|TRIGGER|citext' .
|
||||
~~~
|
||||
|
||||
Compare application equality, database collation, triggers and the unique index.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
Two names differ during authorization but identify the same row during a write.
|
||||
|
||||
**Fix:** Canonicalize consistently before both checks and writes; use stable owner IDs and migrate conflicts rather than merely switching databases.
|
||||
|
||||
**Verification:** Case, Unicode and trailing spaces on the actual database, including old references and uniqueness.
|
||||
|
||||
<a id="sql-transaction"></a>
|
||||
|
||||
## SQL-TRANSACTION. Check and mutation are not one atomic operation
|
||||
|
||||
**Search:** manual review; no separate scanner rule.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'SELECT|UPDATE|DELETE|BEGIN|FOR UPDATE|version' .
|
||||
~~~
|
||||
|
||||
Review isolation level, write predicates and affected-row counts.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
Two requests pass a SELECT check and both spend the resource or modify an object after ownership changes.
|
||||
|
||||
**Fix:** Conditional UPDATE/DELETE with owner/version/balance predicates, transactions and bounded retries; choose the necessary isolation level.
|
||||
|
||||
**Verification:** Deterministic races, conflicts/rollback and legitimate concurrency.
|
||||
|
||||
<a id="sql-pool-context"></a>
|
||||
|
||||
## SQL-POOL-CONTEXT. Connection pools retain tenant or search_path
|
||||
|
||||
**Search:** manual review; no separate scanner rule.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'SET ROLE|SET search_path|set_config|tenant|pool|RESET' .
|
||||
~~~
|
||||
|
||||
Distinguish session SET from transaction-local SET; inspect connection return after exceptions.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
The next request inherits the previous role, schema or tenant.
|
||||
|
||||
**Fix:** SET LOCAL inside the correct transaction or reliable reset; do not derive ownership from client-controlled session variables.
|
||||
|
||||
**Verification:** Two tenants sharing a connection, rollback/exceptions and ordinary subsequent requests.
|
||||
|
||||
**Reference:** [primary source](https://www.postgresql.org/docs/current/ddl-schemas.html).
|
||||
|
||||
<a id="sql-sqlite-fk"></a>
|
||||
|
||||
## SQL-SQLITE-FK. SQLite foreign_keys explicitly disabled
|
||||
|
||||
**Search:** scanner rule SQL-SQLITE-FK. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain SQL-SQLITE-FK` for details. Regex: PRAGMA foreign_keys=OFF/0/false or foreign_keys(OFF/0/false). Review missing ON, pool hooks and compile options.
|
||||
|
||||
Additional manual search for forms outside automatic coverage:
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'PRAGMA foreign_keys|sqlite3.connect|Data Source|FOREIGN KEY' .
|
||||
~~~
|
||||
|
||||
Check the effective PRAGMA after every connection opens and before a transaction begins.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
The DDL declares foreign keys and the app trusts ownership relationships, but enforcement is disabled.
|
||||
|
||||
**Fix:** Enable FK on every connection outside transactions, verify the result and existing violations, and migrate invalid records separately.
|
||||
|
||||
**Verification:** Every connection reports foreign_keys=1; foreign_key_check is empty and invalid owners fail.
|
||||
|
||||
**Reference:** [primary source](https://www.sqlite.org/pragma.html#pragma_foreign_keys).
|
||||
|
||||
**Scanner example before:**
|
||||
|
||||
~~~sql
|
||||
PRAGMA foreign_keys = OFF;
|
||||
~~~
|
||||
|
||||
**Fix template:**
|
||||
|
||||
~~~sql
|
||||
PRAGMA foreign_keys = ON;
|
||||
~~~
|
||||
|
||||
Primary documentation: [reference 1](https://www.sqlite.org/foreignkeys.html).
|
||||
|
||||
<a id="sql-mysql-privileges"></a>
|
||||
|
||||
## SQL-MYSQL-PRIVILEGES. MySQL runtime user has admin privileges
|
||||
|
||||
**Search:** scanner rule SQL-MYSQL-PRIVILEGES. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain SQL-MYSQL-PRIVILEGES` for details. Regex: GRANT with FILE/SUPER or ALL [PRIVILEGES] ON *.*. Review other dangerous dynamic privileges, roles and existing grants.
|
||||
|
||||
Additional manual search for forms outside automatic coverage:
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'GRANT|FILE|SUPER|ALL PRIVILEGES|secure_file_priv|local_infile' .
|
||||
~~~
|
||||
|
||||
Read SHOW GRANTS for the application's own role; review FILE, file read/write and both sides of LOCAL INFILE configuration.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
An ordinary application has filesystem or administrative privileges that amplify a query bug.
|
||||
|
||||
**Fix:** Separate runtime/migration accounts; remove unnecessary global grants and GRANT OPTION; match account hosts to topology.
|
||||
|
||||
**Verification:** SHOW GRANTS contains only required actions; migrations/checker still work.
|
||||
|
||||
**Reference:** [primary source](https://dev.mysql.com/doc/refman/8.4/en/privileges-provided.html).
|
||||
|
||||
**Scanner example before:**
|
||||
|
||||
~~~sql
|
||||
GRANT FILE, SUPER ON *.* TO 'app'@'%';
|
||||
~~~
|
||||
|
||||
**Fix template:**
|
||||
|
||||
~~~sql
|
||||
GRANT SELECT, INSERT, UPDATE, DELETE ON appdb.* TO 'app'@'localhost';
|
||||
~~~
|
||||
|
||||
Primary documentation: [reference 1](https://dev.mysql.com/doc/refman/8.4/en/privileges-provided.html).
|
||||
|
||||
<a id="sql-second-order"></a>
|
||||
|
||||
## SQL-SECOND-ORDER. Stored data becomes SQL again
|
||||
|
||||
**Search:** manual review; no separate scanner rule.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'execute|query|EXECUTE|format\(|quote|SELECT' .
|
||||
~~~
|
||||
|
||||
Trace stored values into subsequent queries, exports and jobs; persistence does not make data trusted.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
The insert parameterizes a value, but a later operation concatenates it into SQL.
|
||||
|
||||
**Fix:** Parameterize every sink, including stored procedures and jobs; use a separate identifier allowlist.
|
||||
|
||||
**Verification:** A stored delimiter remains data in every subsequent operation.
|
||||
|
||||
<a id="sql-nested-dsl"></a>
|
||||
|
||||
## SQL-NESTED-DSL. Multiple query-language layers
|
||||
|
||||
**Search:** manual review; no separate scanner rule.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'LIKE|database|tenant|parse|execute' .
|
||||
~~~
|
||||
|
||||
Separate the outer DSL, inner SQL and database selection; inspect how both layers interpret delimiters.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
**Reference:** The museumorphosis author write-up from RuCTF describes a custom SQL DSL with an unsafe boundary between query text and database selection.
|
||||
**Search:** SQL inside another language's strings, regex instead of a real parser, user-controlled LIKE text and database/tenant names.
|
||||
|
||||
**Fix:** Parameterize values at each layer; derive database selection from a verified server-side tenant and use an unambiguous DSL parser. Escaping inner SQL does not prove the outer language safe.
|
||||
|
||||
**Verification:** Delimiters of both languages, contractual wildcards, attempted database changes and access restricted to the correct tenant.
|
||||
|
||||
**A/D variant:** Source and version: [source/write-up 1](https://github.com/HackerDom/ructf-finals-2023/blob/a7442769909e08c39716cb18d3d1c3a99324bbf8/writeups/museumorphosis/README.md).
|
||||
|
||||
**Reference:** [primary source](https://github.com/HackerDom/ructf-finals-2023/blob/a7442769909e08c39716cb18d3d1c3a99324bbf8/writeups/museumorphosis/README.md).
|
||||
|
||||
<a id="sql-rls-disable"></a>
|
||||
|
||||
## SQL-RLS-DISABLE. PostgreSQL table RLS disabled
|
||||
|
||||
**Search:** scanner rule SQL-RLS-DISABLE. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain SQL-RLS-DISABLE` for details. Regex: ALTER TABLE ... DISABLE ROW LEVEL SECURITY. Does not infer missing ENABLE, broad policies or connection role.
|
||||
|
||||
**Vulnerable example:** Disabling RLS removes the server-side row boundary when access depends on its policies.
|
||||
|
||||
~~~sql
|
||||
ALTER TABLE notes DISABLE ROW LEVEL SECURITY;
|
||||
~~~
|
||||
|
||||
**Fix:** Install intended policies and enable RLS; runtime must not be superuser/BYPASSRLS. FORCE constrains table owners, not these bypass roles.
|
||||
|
||||
~~~sql
|
||||
ALTER TABLE notes ENABLE ROW LEVEL SECURITY;
|
||||
ALTER TABLE notes FORCE ROW LEVEL SECURITY;
|
||||
-- Install reviewed owner/tenant policies before serving traffic.
|
||||
~~~
|
||||
|
||||
**Verification:** Test SELECT/INSERT/UPDATE/DELETE with two runtime identities/tenants and separate migration role.
|
||||
|
||||
Primary documentation: [reference 1](https://www.postgresql.org/docs/current/ddl-rowsecurity.html).
|
||||
|
||||
<a id="sql-token-prefix"></a>
|
||||
|
||||
## SQL-TOKEN-PREFIX. Secret token checked by prefix or range
|
||||
|
||||
**Search:** scanner rule SQL-TOKEN-PREFIX. Run from DurkaHelper: `python3 -I -S scripts/defense_scan.py /path/to/service --patches`; use `--explain SQL-TOKEN-PREFIX` for details. Regex: nonce/token/reset_token/api_key before LIKE, >= or <= in SQL text. Counters/log searches may be legitimate; inspect renamed fields, substr, startsWith and application-side partial comparisons.
|
||||
|
||||
**Vulnerable example:** If a nonce/token is a bearer secret, partial matching drastically reduces the effective search space.
|
||||
|
||||
~~~sql
|
||||
SELECT content FROM exports WHERE username = $1 AND nonce >= $2 AND nonce < $3;
|
||||
~~~
|
||||
|
||||
**Fix:** Require the complete canonical token with valid length/type, exact equality and binding to user/purpose/expiry; rate limiting is separate.
|
||||
|
||||
~~~sql
|
||||
SELECT content FROM exports WHERE username = $1 AND nonce = $2;
|
||||
-- Before querying: require the full canonical token, correct length/type and purpose.
|
||||
~~~
|
||||
|
||||
**Verification:** Empty, short, prefix, extra-suffix and foreign-user tokens fail; complete valid tokens work.
|
||||
|
||||
Primary documentation: [reference 1](https://github.com/enowars/enowars10-service-flagdrive/blob/d1575098fe2c516460136bb5fba11d9a1c4af3f7/documentation/FLAGSTORE_0.md).
|
||||
|
||||
**A/D variant:** FlagDrive's ENOWARS10 authors describe selecting exports by a short nonce prefix. Require full length and exact equality; the rule flags SQL range comparisons, while the bearer-secret meaning requires manual review.
|
||||
|
||||
<a id="sql-null-auth"></a>
|
||||
|
||||
## SQL-NULL-AUTH. NULL changes authorization logic
|
||||
|
||||
**Search:** manual review; no separate scanner rule.
|
||||
|
||||
~~~bash
|
||||
rg -n --hidden -g '!vendor/**' -g '!node_modules/**' -g '!.git/**' -e 'NOT IN|!=|<>|IS NULL|IS NOT NULL|COALESCE|LEFT JOIN|owner|tenant' .
|
||||
~~~
|
||||
|
||||
Construct a TRUE/FALSE/UNKNOWN table for authorization conditions and LEFT JOIN results. Trace nullable booleans into allow/deny decisions and check for NULL inside NOT IN subqueries.
|
||||
|
||||
**Vulnerable example:** A denial condition `owner <> actor` becomes UNKNOWN for NULL and execution falls through to allow; missing ACL entries become default allow.
|
||||
|
||||
**Fix:** Permit access only for an explicitly true positive check. Use NOT NULL and referential integrity where NULL is invalid; otherwise define its exact meaning. Do not merge owners into a shared COALESCE default.
|
||||
|
||||
**Verification:** NULL owners, missing ACLs, empty joins and NULL subquery values never grant access; ordinary own/shared cases remain valid.
|
||||
|
||||
Reference: [primary documentation](https://www.postgresql.org/docs/current/functions-comparison.html). The explanation and adaptation recipe were written for this catalog.
|
||||
|
||||
<a id="sql-rls-allow-all"></a>
|
||||
|
||||
## SQL-RLS-ALLOW-ALL. RLS policy has an unconditional expression
|
||||
|
||||
**Search:** scanner rule SQL-RLS-ALLOW-ALL. Use `--explain SQL-RLS-ALLOW-ALL` for the exact detector contract. Regex with lexical exclusions: USING(true) or WITH CHECK(true). May be intentional and does not associate expressions with CREATE POLICY, roles or commands; effective policies and application authorization require review.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
~~~sql
|
||||
CREATE POLICY open_notes ON notes USING (true);
|
||||
~~~
|
||||
|
||||
**Fix:** Define role/tenant-aware USING and WITH CHECK expressions for the actual identity model; review permissive-policy combinations and bypass roles.
|
||||
|
||||
~~~sql
|
||||
CREATE POLICY owned_notes ON notes USING (owner_id = current_user);
|
||||
~~~
|
||||
|
||||
**Verification:** Two runtime identities cannot read/change each other's rows; inserts and updates enforce the intended owner and valid operations work.
|
||||
|
||||
[Primary reference 1](https://www.postgresql.org/docs/current/sql-createpolicy.html)
|
||||
|
||||
<a id="sql-server-role"></a>
|
||||
|
||||
## SQL-SERVER-ROLE. PostgreSQL server file/program role granted
|
||||
|
||||
**Search:** scanner rule SQL-SERVER-ROLE. Use `--explain SQL-SERVER-ROLE` for details. Bounded SQL: unquoted GRANT role lists containing pg_read_server_files, pg_write_server_files or pg_execute_server_program before TO. Comments/strings excluded; REVOKE and pg_monitor alone do not signal. Quoted roles, inheritance, later revocations, versions and effective permissions remain manual.
|
||||
|
||||
**Vulnerable example:**
|
||||
|
||||
~~~sql
|
||||
GRANT pg_read_server_files TO app;
|
||||
~~~
|
||||
|
||||
**Fix:** Separate application and administrator roles. Grant only required object privileges, not server file/program access; review memberships and revoke only approved service-owned grants with rollback.
|
||||
|
||||
~~~sql
|
||||
GRANT SELECT ON notes TO app;
|
||||
~~~
|
||||
|
||||
**Verification:** The actual runtime role cannot read/write server files or execute server programs; ordinary queries, migrations and recovery still work.
|
||||
|
||||
[Primary reference](https://www.postgresql.org/docs/14/predefined-roles.html)
|
||||
Reference in new issue
Block a user