Nosql Injection with Jwt Tokens
How Nosql Injection Manifests in Jwt Tokens
Nosql injection in JWT tokens occurs when an attacker manipulates token claims to inject malicious NoSQL queries. This typically happens when JWT claims are directly used in database queries without proper sanitization.
The most common scenario involves MongoDB queries where JWT claims are embedded in query objects. For example, consider a Node.js application using Express and MongoDB:
const jwt = require('jsonwebtoken');
const express = require('express');
const { MongoClient } = require('mongodb');
const app = express();
const client = new MongoClient('mongodb://localhost:27017');
const db = client.db('test');
app.get('/api/users/:id', async (req, res) => {
const token = req.headers.authorization.split(' ')[1];
const decoded = jwt.verify(token, process.env.JWT_SECRET);
// Vulnerable: JWT claims directly used in query
const user = await db.collection('users').findOne({
_id: decoded.userId,
role: decoded.role
});
res.json(user);
An attacker can craft a JWT token with role claim containing MongoDB operators like $ne: null or $gt: 0. If the JWT secret is known or the token is improperly validated, the attacker can bypass authorization checks.
Another variant involves using JWT claims in aggregation pipelines:
// Vulnerable aggregation pipeline
const pipeline = [
{ $match: { userId: decoded.userId } },
{ $project: { data: decoded.filter } } // decoded.filter could contain $ operators
const result = await db.collection('data').aggregate(pipeline).toArray();Here, if decoded.filter contains MongoDB operators like $where or $expr, an attacker can execute arbitrary queries or access unauthorized data.
Even more dangerous is when JWT claims are used in $where clauses:
// Extremely vulnerable - $where with JWT claims
const query = {
$where: `this.ownerId == ${decoded.userId} && this.status == '${decoded.status}'`
const items = await db.collection('items').find(query).toArray();This allows attackers to inject JavaScript code through the JWT token, potentially leading to remote code execution on the MongoDB server.
Jwt Tokens-Specific Detection
Detecting NoSQL injection in JWT tokens requires analyzing both the token structure and how claims are used in database queries. The key indicators include:
1. JWT Claim Injection Patterns
Look for JWT claims containing MongoDB operators like $eq, $ne, $gt, $lt, $in, $nin, $or, $and, $where, $expr, $regex, $geoNear, $near, $nearSphere, $geoIntersects, $geoWithin, $center, $centerSphere, $polygon, $box, $slice, $elemMatch, $size, $all, $comment, $mod, $not, $nor, $exists, $type, $jsonSchema, $regex, $text, $search, $meta, $map, $reduce, $filter, $function, $accumulator, $collStats, $currentOp, $indexStats, $listLocalSessions, $listSessions, $facet, $bucket, $bucketAuto, $sortByCount, $graphLookup, $lookup, $unwind, $group, $project, $match, $redact, $replaceRoot, $replaceWith, $sample, $skip, $sort, $limit, $count, $sum, $avg, $min, $max, $stdDevPop, $stdDevSamp, $merge, $out, $indexStats, $currentOp, $listLocalSessions, $listSessions, $facet, $bucket, $bucketAuto, $sortByCount, $graphLookup, $lookup, $unwind, $group, $project, $match, $redact, $replaceRoot, $replaceWith, $sample, $skip, $sort, $limit, $count, $sum, $avg, $min, $max, $stdDevPop, $stdDevSamp, $merge, $out.
2. Dynamic Query Construction
Scan for patterns where JWT claims are used to build queries dynamically:
// Vulnerable pattern - dynamic query building
const query = { userId: decoded.userId };
if (decoded.filters) {
query.$and = Object.entries(decoded.filters).map(([key, value]) => ({ [key]: value }));
3. Aggregation Pipeline Injection
Check for aggregation pipelines where JWT claims determine pipeline stages:
// Vulnerable - pipeline stages from JWT
const stages = [
{ $match: { userId: decoded.userId } }
];
if (decoded.includeSensitive) {
stages.push({ $project: { sensitiveData: 1 } });
}4. Using middleBrick for Detection
middleBrick automatically scans JWT endpoints for NoSQL injection vulnerabilities by:
- Analyzing JWT token structure and claims
- Testing for MongoDB operator injection in claims
- Checking for dynamic query construction patterns
- Scanning aggregation pipeline vulnerabilities
- Detecting unsafe consumption of JWT claims
The scanner tests common injection patterns like:
// middleBrick test patterns
{ role: { $ne: null } } // bypass role checks
{ userId: { $in: [ObjectId(