logo

Database

Javascript Unsanitized Dollarwhere Query

Description

Detects potential NoSQL injection vulnerabilities in JavaScript code when using unsanitized $where operators in MongoDB queries. This is dangerous because malicious user input in $where clauses can execute arbitrary JavaScript code on the database server.

Weakness:

106 - NoSQL injection

Category: Unexpected Injection

Detection Strategy

    Identifies MongoDB query operations that use the $where operator

    Checks if the $where clause contains dynamic values or user input without proper sanitization

    Reports a vulnerability when a $where query uses variables or expressions that could contain untrusted data

    Focuses on JavaScript code segments that construct MongoDB queries with $where conditions

Vulnerable code example

const MarsDB = require('marsdb')
const orders = new MarsDB.Collection('orders')

function vulnerableQuery(req, res) {
  const id = req.params.id  // Unsanitized user input
  
  // Vulnerable: Direct use of user input in NoSQL query
  orders.find({ $where: `this.orderId === '${id}'` })...

✅ Secure code example

const MarsDB = require('marsdb')
const orders = new MarsDB.Collection('orders')

function secureQuery(req, res) {
  // Sanitize and validate input by removing non-alphanumeric chars
  const id = String(req.params.id).replace(/[^\w-]+/g, '')
  
  // Safe: Use direct field comparison instead of $where when possible...