Ad

CVE-2026-82417

MEDIUM CVSS 4.0: 6,3 EPSS 0.26%
Обновлено 3 сентября 2026
Ljharb
Параметр Значение
CVSS 6,3 (MEDIUM)
Тип уязвимости CWE-248 (Необработанное исключение), CWE-703
Поставщик Ljharb
Публичный эксплойт Нет

### Резюме `qs.stringify` выдает `TypeError` при сериализации объекта, собственное свойство `constructor` которого имеет правдивый, невызываемый элемент `isBuffer`. `utils.isBuffer` создает буферы утиного типа, вызывая `obj.constructor.isBuffer(obj)` после проверки только того, что свойство истинно, поэтому такое значение, как `{constructor: { isBuffer: "x" } }`, вызывает вызов `TypeError: obj.constructor.isBuffer не является функцией`. ### Подробности `lib/stringify.js:127` вызывает `utils.isBuffer` для каждого непримитивного значения, которое он сериализует. `utils.isBuffer` (`lib/utils.js:332`) читает `obj.constructor.isBuffer` и вызывает его, не проверяя, является ли это функцией. `constructor` и `isBuffer` — это обычные имена свойств, поэтому любой объект, несущий их как собственные свойства, достигает непроверяемого вызова. Такой объект может быть построен на основе ненадежных входных данных. `qs.parse("x[constructor][isBuffer]=y", { PlainObjects: true })` или `{allowPrototypes: true }` сохраняет ключ `constructor` как собственное свойство (параметры анализа по умолчанию удаляют его), а `JSON.parse("{\"a\":{\"constructor\":{\"isBuffer\":\"x\"}}}")` создает ту же форму без использования опции qs. Express 4 с настройкой `query parser` по умолчанию и body-parser с `extended: true` оба вызывают `qs.parse` с `allowPrototypes: true`, поэтому в этих стеках `req.query` и `req.body` могут напрямую переносить форму. #### PoC ```js вар qs = require("qs"); qs.stringify(qs.parse("x[constructor][isBuffer]=y", { PlainObjects: true })); qs.stringify(JSON.parse("{\"a\":{\"constructor\":{\"isBuffer\":\"x\"}}}")); // Ошибка типа: obj.constructor.isBuffer не является функцией // в Object.isBuffer (lib/utils.js:332:78) // в stringify (lib/stringify.js:127:45) ``` #### Исправить `lib/utils.js`, примененный в e83d321 на `main` и выпущенный как v6.16.0: ```разница - return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj)); + return !!(obj.constructor && typeof obj.constructor.isBuffer === "функция" && obj.constructor.isBuffer(obj)); ``` Реальные экземпляры полифилов Buffer, Safer-buffer и Browserify Buffer сериализуются точно так же, как и раньше; удаляется только бросок. ### Затронутые версии `>=2.2.5 <6.16.0`, исправлено в версии 6.16.0.

Неохраняемый тип «утка» был представлен в версии 3768a75 и впервые выпущен в версии 2.2.5 (сентябрь 2014 г.). Версия 2.2.4 и более ранние версии использовали `Buffer.isBuffer` и не были затронуты. Каждый выпуск от v2.2.5 до v6.15.3 содержит незащищенный вызов. ### Влияние Неаутентифицированный запрос может привести к тому, что любой путь кода, который повторно сериализует данные, подвергшиеся воздействию злоумышленника, с помощью `qs.stringify` (например, перестроение строки запроса из `req.query` для перенаправления или восходящего запроса или сериализация проанализированного тела JSON) выдаст синхронный вызов.

В типичной HTTP-инфраструктуре Node.js выдача перехватывается границей ошибки платформы, и затронутый запрос возвращает 500; процесс сохраняется, и другие запросы не затрагиваются. Если вызов выполняется за пределами границы ошибки, например, в обработчике `async` Express 4 (где бросок становится необработанным отклонением обещания) или фоновом задании, процесс завершается, поэтому влияние в этом случае зависит от обработки ошибок приложения, а не от qs.

Показать оригинальное описание (EN)

### Summary `qs.stringify` throws a `TypeError` when it serializes an object whose own `constructor` property has a truthy, non-callable `isBuffer` member. `utils.isBuffer` duck-types buffers by calling `obj.constructor.isBuffer(obj)` after checking only that the property is truthy, so a value such as `{ constructor: { isBuffer: "x" } }` makes the call throw `TypeError: obj.constructor.isBuffer is not a function`. ### Details `lib/stringify.js:127` calls `utils.isBuffer` on every non-primitive value it serializes. `utils.isBuffer` (`lib/utils.js:332`) reads `obj.constructor.isBuffer` and invokes it without verifying that it is a function. `constructor` and `isBuffer` are ordinary property names, so any object carrying them as own properties reaches the unchecked call. Such an object can be built from untrusted input. `qs.parse("x[constructor][isBuffer]=y", { plainObjects: true })` or `{ allowPrototypes: true }` keeps the `constructor` key as an own property (the default parse options drop it), and `JSON.parse("{\"a\":{\"constructor\":{\"isBuffer\":\"x\"}}}")` produces the same shape with no qs option involved. Express 4 with its default `query parser` setting and body-parser with `extended: true` both call `qs.parse` with `allowPrototypes: true`, so on those stacks `req.query` and `req.body` can carry the shape directly. #### PoC ```js var qs = require("qs"); qs.stringify(qs.parse("x[constructor][isBuffer]=y", { plainObjects: true })); qs.stringify(JSON.parse("{\"a\":{\"constructor\":{\"isBuffer\":\"x\"}}}")); // TypeError: obj.constructor.isBuffer is not a function // at Object.isBuffer (lib/utils.js:332:78) // at stringify (lib/stringify.js:127:45) ``` #### Fix `lib/utils.js`, applied in e83d321 on `main` and released as v6.16.0: ```diff - return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj)); + return !!(obj.constructor && typeof obj.constructor.isBuffer === "function" && obj.constructor.isBuffer(obj)); ``` Real `Buffer`, `safer-buffer`, and browserify `buffer` polyfill instances serialize exactly as before; only the throw is removed. ### Affected versions `>=2.2.5 <6.16.0`, fixed in v6.16.0. The unguarded duck-type was introduced in 3768a75 and first shipped in v2.2.5 (September 2014). v2.2.4 and earlier used `Buffer.isBuffer` and are not affected. Every release from v2.2.5 through v6.15.3 contains the unguarded call. ### Impact An unauthenticated request can make any code path that re-serializes attacker-influenced data with `qs.stringify` (for example, rebuilding a query string from `req.query` for a redirect or an upstream request, or serializing a parsed JSON body) throw synchronously. In a typical Node.js HTTP framework the throw is caught by the framework error boundary and the affected request returns a 500; the process survives and other requests are unaffected. Where the call runs outside an error boundary, such as an `async` Express 4 handler (where the throw becomes an unhandled promise rejection) or a background job, the process exits, so the impact in that case depends on the application error handling rather than on qs.

Характеристики атаки

Способ атаки
По сети
Атака возможна удалённо
Сложность
Низкая
Легко эксплуатировать
Условия для атаки
Требуются
Нужны дополнительные условия
Нужны права
Не требуются
Права не нужны
Участие пользователя
Не требуется
Не нужно действие пользователя

Последствия

Конфиденциальность
Нет
Нет утечки данных
Целостность
Нет
Нет модификации данных
Доступность
Низкое
Частичное нарушение работы

Строка CVSS v4.0

Уязвимые продукты

ljharb:qs

Связанные уязвимости