Nosql Injection with Basic Auth
How NoSQL Injection Manifests in Basic Auth
NoSQL injection in Basic Auth contexts typically occurs when authentication logic uses user-supplied credentials to construct MongoDB queries without proper sanitization. When a client sends Basic Auth credentials, the Authorization header contains Base64-encoded username:password. The server decodes this and uses the username directly in a database query to validate credentials.
Consider this vulnerable Node.js/Express pattern:
const express = require('express');
const app = express();
app.use(express.json());
app.use((req, res, next) => {
const authHeader = req.headers.authorization;
if (!authHeader) return res.status(401).end();
const [username, password] = Buffer.from(
authHeader.split(' ')[1], 'base64'
).toString().split(':');
// VULNERABLE: Direct query construction
db.collection('users').findOne({
$or: [
{ username: username },
{ email: username }
],
password: password
}, (err, user) => {
if (err || !user) return res.status(401).end();
req.user = user;
next();
});
});The vulnerability emerges when MongoDB operators are injected through the username field. A malicious payload like:
username: ""}, $where: "this.password.includes('anything') || true", "{"password: "ignored"Base64-encodes to:
WyJ7XCJ1c2VybmFtZVwiOntcIiR3aGVyZSBcInRoaXMucGFzc3dvcmQua
W5kZXhPZignaWFtbXknKSB8fCB0cnVlXCIsXCJpZFwiOntcIiRjb3VudF
wiOjF9fSIsXCJwYXNzd29yZCI6XCJoaVwiXQ==This transforms the query into:
{ $or: [ { username: { $where: "this.password.includes('anything') || true" }, $inc: { $count: 1 } } ], password: "hi" }The $where operator executes arbitrary JavaScript on the database server, bypassing authentication entirely. Another common pattern uses $ne (not equals) to bypass password checks:
username: "admin", $ne: "realpassword"This creates a query that matches any user where the password doesn't equal "realpassword"—effectively authenticating as any user except the one with that specific password.
Basic Auth-Specific Detection
Detecting NoSQL injection in Basic Auth requires examining how credentials flow through your authentication pipeline. The key indicators are:
- Direct use of username/password in database queries without parameterization
- Construction of query objects using bracket notation with user input
- Absence of input validation on the decoded username field
- Support for alternate login identifiers (username OR email) that expand the query surface
middleBrick's scanner specifically targets these patterns by submitting crafted Basic Auth payloads and analyzing responses. For NoSQL injection detection, it tests with payloads containing MongoDB operators like $where, $ne, $gt, $regex, and $exists.
Manual testing involves:
curl -v -H "Authorization: Basic $(echo -n 'test