Course contentsShow
← Security
Lesson 599 of 3,05213. Web Security - Injection AttacksFree lesson

Server-Side JavaScript Injection

Exploiting NoSQL databases that execute JavaScript on the server through $where clauses and map-reduce functions.

Server-Side JavaScript Injection

What you'll learn: How attackers exploit NoSQL databases that execute JavaScript directly on the server to run malicious code.

The Core Vulnerability

Some NoSQL databases—particularly MongoDB—allow you to write queries using JavaScript expressions. When user input flows into these JavaScript contexts without proper validation, attackers can inject their own JavaScript code that runs on the database server itself.

Two primary attack vectors exist:

  1. $where clauses – MongoDB's $where operator evaluates JavaScript expressions to filter documents
  2. Map-reduce functions – Custom JavaScript code that processes data collections

Think of it like this: imagine a library (database) where you can write custom search instructions in a programming language. If the librarian blindly executes your instructions without checking them, you could write code that does far more than just search—like copying books, destroying records, or even controlling the library's computer system.

How It Works

When an application builds a MongoDB query like:

db.users.find({ $where: "this.username == '" + userInput + "'" })

An attacker could inject admin' || '1'=='1 to bypass authentication, or even inject code that sleeps, extracts data, or performs denial-of-service attacks.

Similarly, map-reduce functions accept JavaScript code directly. If user input constructs these functions, attackers control what executes on the server.

Why It's Dangerous

Unlike traditional SQL injection, you're not just manipulating query logic—you're executing arbitrary code in a Turing-complete language on the database server. This can lead to complete data exfiltration, authentication bypass, or even remote code execution depending on server configuration.

Key Takeaway: Server-side JavaScript injection occurs when user-controlled input flows into JavaScript execution contexts like MongoDB's $where clauses or map-reduce functions, allowing attackers to run arbitrary code on the database server—never trust user input in these contexts.