Claude skill NoSQL injection via MongoDB query operator injection, Redis KEYS enumeration and Elasticsearch query_string in MCP skills — SA-SKL-INJECTION6
NoSQL databases offer schema flexibility and horizontal scalability, but that same flexibility means user input that is treated as a query object rather than a value can alter query semantics in ways that relational parameterized queries prevent by design. SA-SKL-INJECTION6 covers four injection patterns found in Claude MCP skill implementations: MongoDB findOne where the email field is a user-supplied object containing the $gt comparison operator that returns the first database user regardless of the supplied value; Mongoose Model.find(req.body) that spreads the entire request body as a MongoDB query, enabling time-based blind injection via the $where JavaScript operator; Redis KEYS with a user-controlled glob pattern that can enumerate all keys in the Redis keyspace including session tokens and API keys from other users; and Elasticsearch query_string with user input that accepts full Lucene syntax, enabling an attacker to query arbitrary fields including internal metadata fields that should not be searchable.
NoSQL injection root cause: input used as query structure, not query value
In a relational database with parameterized queries, the distinction between query structure and query value is enforced at the protocol level — the driver sends the SQL template and the parameter values as separate messages, and the database engine never conflates them. In a document database like MongoDB, the query is itself a JSON object where certain keys beginning with $ have special meaning as query operators. When user input (also a JSON object from the request body) is used directly as or merged into the MongoDB query object, the user can supply $gt, $where, $regex, or any other query operator as a key, changing the semantics of the query. The root cause fix is always the same: extract individual scalar fields explicitly from user input, never spread or assign an object from user input directly into a database query.
db.users.findOne({ email: req.body.email }) where email is an object; {"email": {"$gt": ""}} returns first user; authentication bypassModel.find(req.body) directly passes request body as Mongoose query; {"$where": "sleep(5000)"} executes JavaScript for time-based blind injectionKEYS req.query.pattern — attacker sends * to enumerate all keys including session tokens and API keys from all usersquery_string with user input supports Lucene syntax; title:* OR _exists_:passwordHash enumerates internal fieldsINJECTION6-001 — MongoDB $gt operator bypasses authentication check
When Express is configured with express.json() and a client sends a JSON body where the email field is an object ({"email": {"$gt": ""}}), the value of req.body.email is a JavaScript object {"$gt": ""}. If the application passes this directly as the value of the email field in a MongoDB query object, the resulting query is { email: { $gt: "" } }. This MongoDB query finds all documents where the email field is greater than the empty string — which matches the first document in the collection. In a login endpoint, this means the attacker can authenticate as the first user in the database (often the admin account) by supplying a JSON object as the email value instead of a string. The fix is to validate that the email value is a string before using it in any database query.
// VULNERABLE — req.body.email used directly in MongoDB query; $gt operator bypasses auth
import { MongoClient } from 'mongodb';
import bcrypt from 'bcrypt';
const client = new MongoClient(process.env.MONGO_URI);
const db = client.db('skillaudit');
app.post('/login', async (req, res) => {
const { email, password } = req.body;
// VULNERABLE: if email is {"$gt": ""}, query becomes {email: {$gt: ""}}
// Returns the first user document in the collection — often the admin account
const user = await db.collection('users').findOne({ email });
if (!user || !await bcrypt.compare(password ?? '', user.passwordHash)) {
return res.status(401).json({ error: 'Invalid credentials' });
}
const token = generateSessionToken(user._id);
res.json({ token });
});
// FIXED — type check + Joi string validation before database query
import { MongoClient } from 'mongodb';
import bcrypt from 'bcrypt';
import Joi from 'joi';
const loginSchema = Joi.object({
email: Joi.string().email().max(254).required(),
password: Joi.string().max(1024).required(),
});
app.post('/login', async (req, res) => {
// FIXED: validate types with Joi before any database interaction
const { error, value } = loginSchema.validate(req.body, { abortEarly: false });
if (error) {
return res.status(400).json({ error: 'Validation failed', details: error.details });
}
const { email, password } = value; // email is guaranteed to be a string here
// FIXED: email is validated as a string; $gt object injection impossible
const user = await db.collection('users').findOne({ email });
if (!user || !await bcrypt.compare(password, user.passwordHash)) {
return res.status(401).json({ error: 'Invalid credentials' });
}
const token = generateSessionToken(user._id);
res.json({ token });
});
INJECTION6-002 — Mongoose Model.find(req.body) enables $where time-based injection
The $where operator in MongoDB accepts a JavaScript expression (string or function) that is evaluated by the MongoDB JavaScript engine for each document in the collection. {"$where": "sleep(5000)"} causes MongoDB to pause execution for 5 seconds per document scanned, creating a time-based blind injection vector. An attacker can use variations of this to infer database contents by measuring response time — longer response times indicate more documents being scanned. Beyond timing attacks, $where can execute arbitrary JavaScript in the MongoDB server process. The root cause is spreading req.body directly as the Mongoose query object, which passes all user-controlled keys including $where as query operators. The fix is to never spread req.body into a database query — always extract the specific scalar fields the application needs.
// VULNERABLE — Mongoose Model.find(req.body) spreads request body as MongoDB query
import { Audit } from './models/Audit.js';
app.get('/api/audits', authenticate, async (req, res) => {
// VULNERABLE: req.body spread directly into Mongoose query
// Attacker sends: {"$where": "sleep(5000)"} — time-based blind injection
// Or: {"repoUrl": {"$regex": "^https://github.com/admin"}} — regex leak
// Or: {"userId": {"$ne": req.user.id}} — IDOR across all users' audits
const audits = await Audit.find(req.body);
res.json(audits);
});
// FIXED — explicit field extraction; never spread req.body into MongoDB query
import { Audit } from './models/Audit.js';
import Joi from 'joi';
const auditQuerySchema = Joi.object({
repoUrl: Joi.string().uri().optional(),
status: Joi.string().valid('pending', 'running', 'complete', 'failed').optional(),
limit: Joi.number().integer().min(1).max(100).default(20),
offset: Joi.number().integer().min(0).default(0),
});
app.get('/api/audits', authenticate, async (req, res) => {
const { error, value } = auditQuerySchema.validate(req.query);
if (error) return res.status(400).json({ error: 'Invalid query parameters' });
// FIXED: build query object from explicit scalar fields only
// Never use $where, $regex, or any operator from user input
const query = {
userId: req.user.id, // always scope to authenticated user
};
if (value.repoUrl) query.repoUrl = value.repoUrl; // exact string match only
if (value.status) query.status = value.status; // validated enum value
const audits = await Audit.find(query)
.skip(value.offset)
.limit(value.limit)
.select('-internalNotes -rawScanOutput');
res.json(audits);
});
INJECTION6-003 — Redis KEYS with user-controlled pattern enumerates all keys
The Redis KEYS command accepts a glob pattern and returns all matching keys in the entire keyspace. It is a blocking O(N) operation where N is the total number of keys — in a production keyspace with millions of entries, a single KEYS * command blocks Redis for seconds. When an MCP skill exposes a debugging or search endpoint that passes user input directly to KEYS, an attacker can send the pattern * to enumerate every key in the Redis instance, including session tokens for other users, API keys, rate limit counters, and cache entries. Even if the endpoint returns only the matching key names (not values), session token key names often include the token itself or enough of it to enable targeted attacks. The fix is to replace KEYS with the non-blocking SCAN command with a cursor, and to prefix-restrict the pattern to a user-scoped namespace so the user can only scan their own keys.
// VULNERABLE — Redis KEYS with user-controlled pattern; enumerates entire keyspace
import { createClient } from 'redis';
const redis = createClient({ url: process.env.REDIS_URL });
app.get('/api/audits/search', authenticate, async (req, res) => {
const { pattern } = req.query;
// VULNERABLE: attacker sends pattern='*' to enumerate all keys
// Returns: session:abc123def456..., apikey:user2:..., rl:1.2.3.4:..., etc.
// Also: KEYS is O(N) and blocks Redis — potential DoS on large keyspaces
const keys = await redis.keys(`audit:${pattern}`);
res.json({ keys });
});
// FIXED — SCAN with cursor + user-scoped prefix; pattern restricted to audit ID prefix
import { createClient } from 'redis';
const redis = createClient({ url: process.env.REDIS_URL });
app.get('/api/audits/search', authenticate, async (req, res) => {
const userId = req.user.id;
// FIXED: prefix restricts scan to this user's audit keys only
// User input appended after user-scoped prefix; * only matches within that namespace
const userPrefix = `audit:${userId}:`;
// Sanitize the user-supplied fragment to prevent glob metachar injection
// Only allow alphanumeric, dash, underscore in the search fragment
const fragment = (req.query.fragment ?? '').replace(/[^a-zA-Z0-9_-]/g, '');
const scanPattern = `${userPrefix}${fragment}*`;
// FIXED: SCAN is non-blocking; iterate with cursor until exhausted
const matchedKeys = [];
let cursor = 0;
do {
const result = await redis.scan(cursor, {
MATCH: scanPattern,
COUNT: 100, // hint: scan ~100 keys per iteration
});
cursor = result.cursor;
matchedKeys.push(...result.keys);
if (matchedKeys.length > 1000) break; // safety cap
} while (cursor !== 0);
res.json({ keys: matchedKeys });
});
INJECTION6-004 — Elasticsearch query_string exposes internal fields via Lucene syntax
The Elasticsearch query_string query type accepts a full Lucene query syntax string. This syntax supports specifying field names explicitly in the query (fieldname:value), wildcards (title:*), existence checks (_exists_:fieldname), and boolean operators. When an MCP skill passes user-supplied search input directly to query_string, an attacker can search for content in fields that were intended to be internal — passwordHash:*, apiKey:*, internalNotes:* — and use the search results to exfiltrate sensitive data. Even if the indexed document does not expose these fields in the response, the existence of results (or the absence of results) can confirm whether a field contains certain values. The fix is to use the match query type instead of query_string for user-supplied input, and to explicitly specify which fields are searchable.
// VULNERABLE — query_string with user input supports Lucene field syntax
import { Client } from '@elastic/elasticsearch';
const esClient = new Client({ node: process.env.ES_URL });
app.get('/api/audits/search', authenticate, async (req, res) => {
const { q } = req.query;
// VULNERABLE: query_string accepts Lucene syntax including field names
// Attacker sends: q=passwordHash:* OR _exists_:apiKey
// Or: q=internalNotes:confidential
const result = await esClient.search({
index: 'audits',
body: {
query: {
query_string: {
query: q, // VULNERABLE: full Lucene syntax, any field queryable
},
},
},
});
res.json(result.hits.hits.map(h => h._source));
});
// FIXED — match query on explicitly listed searchable fields only
import { Client } from '@elastic/elasticsearch';
import Joi from 'joi';
const esClient = new Client({ node: process.env.ES_URL });
const searchSchema = Joi.object({
q: Joi.string().max(200).required(),
page: Joi.number().integer().min(1).default(1),
});
// Whitelist of fields users are allowed to search — no internal metadata
const SEARCHABLE_FIELDS = ['repoName', 'description', 'findings.title'];
app.get('/api/audits/search', authenticate, async (req, res) => {
const { error, value } = searchSchema.validate(req.query);
if (error) return res.status(400).json({ error: 'Invalid search query' });
const { q, page } = value;
const pageSize = 20;
// FIXED: multi_match query limits search to whitelisted fields
// User input treated as plain text; no Lucene syntax interpretation
const result = await esClient.search({
index: 'audits',
body: {
query: {
bool: {
must: [
{
multi_match: {
query: q, // plain text match
fields: SEARCHABLE_FIELDS, // only these fields searched
type: 'best_fields',
// operator: 'and' for stricter matching
},
},
],
filter: [
// Always scope to the authenticated user's audits
{ term: { userId: req.user.id } },
],
},
},
_source: {
// Explicitly whitelist returned fields — never return internal fields
includes: ['repoName', 'repoUrl', 'grade', 'createdAt', 'findings.title'],
},
from: (page - 1) * pageSize,
size: pageSize,
},
});
res.json(result.hits.hits.map(h => h._source));
});
Related patterns: For SQL injection patterns in MCP skills that use relational databases alongside MongoDB, see SA-SKL-INJECTION5. For deserialization attacks on Redis-backed job queues where crafted payloads in Redis values trigger code execution, see SA-SKL-DESERIALIZE2. For SSRF via user-controlled webhook URLs that can reach internal Elasticsearch and Redis management ports, see SA-SKL-SSRF10.
| Finding | Severity | Vulnerable pattern | Fix |
|---|---|---|---|
INJECTION6-001 | Critical | findOne({ email: req.body.email }) where email is {"$gt":""} object; query returns first DB user; authentication bypass | typeof email !== 'string' check + Joi Joi.string().email() validation before any DB query |
INJECTION6-002 | Critical | Model.find(req.body) passes body as MongoDB query; {"$where":"sleep(5000)"} for time-based injection; {"userId":{"$ne":id}} for IDOR | Explicit field extraction; Joi schema validates shape and types; never spread req.body into any DB query |
INJECTION6-003 | High | redis.keys(`audit:${userInput}`) — attacker sends *; enumerates all keys including session tokens; O(N) blocks Redis | Replace KEYS with SCAN + cursor; prefix pattern with user-scoped namespace; sanitize input fragment |
INJECTION6-004 | High | Elasticsearch query_string with user input; Lucene syntax allows passwordHash:* field enumeration; internal field data exfiltration | multi_match query on explicit field whitelist; _source.includes limits returned fields; always filter by userId |