init
This commit is contained in:
commit
303438d206
217 files changed
+66681
No files matched your search
@@ -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