Looking for the vulnerability index of Invicti's legacy products?
MongoDB $where operator JavaScript injection - Vulnerability Database

MongoDB $where operator JavaScript injection

Description

This vulnerability occurs when user-supplied input is passed directly to MongoDB's $where operator without proper validation or sanitization. The $where operator executes JavaScript code on the MongoDB server, allowing attackers to inject malicious JavaScript that can manipulate query logic, execute arbitrary code, or cause denial of service through resource-intensive operations. This is a form of NoSQL injection specific to MongoDB's JavaScript execution capabilities.

Example of vulnerable code:

db.collection.find( { $where: function() { 
    return (this.name == $userData) } } );
An attacker could inject a payload like 'a'; sleep(5000) into $userData, resulting in the following executed query:
db.collection.find( { $where: function() { 
    return (this.name == 'a'; sleep(5000) ) } } );
This would cause the server to pause for 5 seconds, confirming the injection vulnerability.

Remediation

Take the following steps to remediate this vulnerability:

1. Eliminate use of JavaScript operators: Avoid using MongoDB operators that execute JavaScript code ($where, mapReduce, group) with user-supplied input. Rewrite queries using standard MongoDB query operators instead.

Replace vulnerable code:

db.collection.find( { $where: function() { 
    return (this.name == userData) } } );
With safe alternative:
db.collection.find( { name: userData } );
For complex conditions, use the $expr operator with aggregation expressions instead of $where.

2. Disable JavaScript execution: Set javascriptEnabled to false in your mongod.conf configuration file to prevent all JavaScript execution in MongoDB:
security:
  javascriptEnabled: false
This provides defense-in-depth protection against this entire class of attacks.

3. Input validation: If JavaScript operators cannot be avoided, implement strict input validation using allowlists for expected values and reject any input containing JavaScript syntax characters or keywords.

4. Apply principle of least privilege: Ensure MongoDB user accounts have only the minimum permissions required for their function to limit the impact of successful attacks.

Related Vulnerabilities