Injection from user input in $where JavaScript evaluation in MongoDB query

Critical Risk sql-injection
javamongodbnosql-injectionjavascript-evaluationwhere-clause

What it is

NoSQL injection vulnerability where untrusted data is interpolated into the $where clause, which executes JavaScript on the MongoDB server, potentially allowing attackers to execute arbitrary JavaScript on the database, exposing or modifying data.

â„šī¸ Configuration Fix

Configuration changes required - see explanation below.

💡 Explanation

â„šī¸ Configuration Fix

Configuration changes required - see explanation below.

💡 Explanation

Why it happens

Untrusted data is directly interpolated into MongoDB $where clauses that execute JavaScript.

Root causes

User Input in $where JavaScript

Untrusted data is directly interpolated into MongoDB $where clauses that execute JavaScript.

Missing Query Operator Usage

Using $where instead of MongoDB's typed query operators for data comparisons.

Fixes

1

Remove $where Usage

Replace $where JavaScript evaluation with MongoDB's typed query operators.

View implementation
Use Filters.eq(), Filters.lt(), Filters.regex() instead of $where with JavaScript strings
2

Use MongoDB Query Operators

Build queries with com.mongodb.client.model.Filters and typed operators for safe querying.

View implementation
Filters.and(Filters.eq("status", status), Filters.gt("age", minAge))
3

Validate and Whitelist Fields

If dynamic queries are needed, validate field names against a strict allow-list.

View implementation
Check field names against Set.of("name", "email", "status") before query construction

Detect This Vulnerability in Your Code

Sourcery automatically identifies injection from user input in $where javascript evaluation in mongodb query and many other security issues in your codebase.