Помощник клиента HTTP по отладке print_header_field() в subsys/net/lib/http/http_client.c отформатировал срез вызова данных http_parser с преобразованием %s: snprintk(outprintk, len + 1, "%s", str). Парсер передает свои обратные вызовы указателю и длине в буфер приема вызывающего абонента, и эти байты не завершаются NUL. Аргумент размера snprintk() ограничивает только пункт назначения, в то время как преобразование %s измеряет исходный код первым — lib/os/cbprintf_complete.c использует strlen(), когда точность не задана, а lib/os/cbprintf_nano.c использует strlen() безоговорочно — поэтому чтение проходит мимо конца поля заголовка и мимо конца буфера приема, пока не найдет нулевой байт.
Срез достигает помощника из on_url(), on_header_field() и on_header_value(), который анализатор вызывает на байтах, которые http_wait_data() считывает прямо с сокета в поставляемое приложение recv_buf. Вредоносный или скомпрометированный сервер HTTP или атакующий, способный ответить на запрос открытого текста, поэтому контролирует как поле заголовка, так и байты, которые следуют за ним в буфере, и может гарантировать, что нулевой байт не появится до окончания буфера, заставляя перечитать. Встроенный набор tests/net/lib/http_client воспроизводит перечитанное под CONFIG_ASAN=y на обычном GET.
Воздействие ограничено. Весь корпус помощника компилируется только тогда, когда клиентский модуль журнала HTTP явно установлен на Debug (CONFIG_NET_HTTP_LOG_LEVEL_DBG=y, что не установлено глобальным CONFIG_LOG_DEFAULT_LEVEL), поэтому сборки по умолчанию не затрагиваются. Никакой записи out-of-bounds не происходит, и ни один из перечитанных байтов не излучается в журнал, поэтому нет раскрытия информации; следствием является чтение out-of-bounds, которое может привести к ошибке и панике на устройстве, где буфер примыкает к неотображенной или защищенной от MPU / MMU области.
Исправление копирует именно те байты, которые парсер предложил с помощью memcpy() и завершает их, вместо того, чтобы полагаться на преобразование %s (точности a %.*s было бы недостаточно, так как cbprintf_nano.c измеряет источник в полном объеме перед его применением).
Показать оригинальное описание (EN)
The HTTP client's debug helper print_header_field() in subsys/net/lib/http/http_client.c formatted an http_parser data-callback slice with a %s conversion: snprintk(output, len + 1, "%s", str). The parser hands its callbacks a pointer and a length into the caller's receive buffer, and those bytes are not NUL terminated. The size argument of snprintk() bounds only the destination, while the %s conversion measures the source first — lib/os/cbprintf_complete.c uses strlen() when no precision is given, and lib/os/cbprintf_nano.c uses strlen() unconditionally — so the read walks past the end of the header field and past the end of the receive buffer until it finds a zero byte. The slice reaches the helper from on_url(), on_header_field() and on_header_value(), which the parser invokes on bytes that http_wait_data() read straight off the socket into the application-supplied recv_buf. A malicious or compromised HTTP server, or an attacker able to answer a plaintext request, therefore controls both the header field and the bytes that follow it in the buffer, and can guarantee that no zero byte appears before the buffer ends, forcing the over-read. The in-tree tests/net/lib/http_client suite reproduces the over-read under CONFIG_ASAN=y on an ordinary GET. The impact is bounded. The whole helper body is compiled only when the HTTP client log module is explicitly set to Debug (CONFIG_NET_HTTP_LOG_LEVEL_DBG=y, which the global CONFIG_LOG_DEFAULT_LEVEL does not set), so default builds are unaffected. No out-of-bounds write occurs and none of the over-read bytes are emitted into the log, so there is no information disclosure; the consequence is an out-of-bounds read that can fault and panic the device where the buffer abuts an unmapped or MPU/MMU-protected region. The fix copies exactly the len bytes the parser offered with memcpy() and terminates them, instead of relying on a %s conversion (a %.*s precision would not have sufficed, since cbprintf_nano.c measures the source in full before applying it).
Характеристики атаки
Последствия
Строка CVSS v3.1