NoSQL Injection - MongoDB

ID

nosql_injection_mongodb

Severity

critical

Kind

Injection

CWE

943

Description

NoSQL Injection in MongoDB occurs when user-supplied input is incorporated into database queries without proper validation or sanitization. Attackers can manipulate query logic by injecting NoSQL operators such as $ne, $gt, or $where, or by inserting arbitrary JavaScript into server-side evaluated expressions. Unlike traditional SQL injection, NoSQL injection exploits the JSON-based and operator-driven query structures that MongoDB uses, enabling boolean-based, operator-based, and JavaScript code injection attacks.

Rationale

Successful exploitation of a NoSQL injection vulnerability can allow an attacker to bypass authentication mechanisms, extract or modify sensitive data, escalate privileges, or cause denial of service. In cases where MongoDB evaluates server-side JavaScript, an attacker may also achieve remote code execution on the underlying server, making the impact potentially more severe than traditional SQL injection.

Remediation

Never incorporate raw user input directly into MongoDB queries. Always validate and sanitize all user-supplied data on the server side before it reaches the database layer.

Use parameterized queries or the driver’s built-in query builder methods instead of constructing query objects from untrusted input. Avoid using operators that evaluate arbitrary code, such as $where, mapReduce, or group, with any data derived from user input.

Enforce strict schema validation on the database side, for example by using Mongoose schemas in Node.js applications, to reject unexpected field types or structures. Apply the principle of least privilege to database accounts so that even a successful injection has limited impact.

Keep all MongoDB drivers and server versions up to date to benefit from the latest security fixes and hardening measures.