Claude skill NoSQL injection security
MCP skills that use NoSQL databases — MongoDB for audit history, Redis for rate limiting and session state, DynamoDB for serverless persistence, Elasticsearch for search — face injection vulnerabilities that differ from SQL injection in mechanism but are equally severe in impact. NoSQL injection attacks typically exploit the structured query object model: when user-supplied values are merged into a query object without type validation, the attacker can inject query operators ($gt, $where), script bodies, reserved keywords, or dynamic field names that change the semantics of the query. SA-SKL-NOSQL covers four NoSQL injection patterns specific to Node.js MCP skill deployments.
NoSQL injection is different from SQL injection in that there is no string interpolation and no termination character to escape. The attack surface is the structured data type: a MongoDB query accepts JavaScript objects, and if user input is an object rather than a string, the user’s object keys become query operators. A login check that expects username to be a string will behave unexpectedly if the value is { $gt: "" } — a MongoDB operator object that matches all usernames greater than the empty string. The common thread across all four SA-SKL-NOSQL patterns is that user-supplied values must be validated as the expected primitive type before they are incorporated into a database query or script, and any path that allows an object, array, or string to be interpreted as a query operator or script body is an injection point.
SA-SKL-NOSQL-001: MongoDB operator injection — { $gt: '' } matches all documents
MongoDB query filters are JavaScript objects. The MongoDB Node.js driver passes these objects directly to the query engine without any escaping layer analogous to SQL parameter binding. When a MCP skill constructs a MongoDB filter by directly incorporating a tool argument value as a field value, and that value is an object rather than a primitive, the object’s keys are interpreted as query operators. A value of { $gt: "" } for a username field means “username greater than empty string” — which matches all documents. A value of { $ne: null } means “username not equal to null” — also matches all documents. The $where operator accepts a JavaScript function string and executes it in the MongoDB engine, enabling full code execution within the database process:
// VULNERABLE: user input directly used as MongoDB query value without type check
import { MongoClient } from 'mongodb';
const db = client.db('skillaudit');
// Tool: look up user by username
const lookupUserTool: Tool = {
name: 'lookup_user',
inputSchema: { type: 'object', properties: { username: {} } }, // no type constraint
handler: async (args: { username: unknown }) => {
// No type validation — args.username may be an object, not a string
const user = await db.collection('users').findOne({
username: args.username, // <-- injection point: object value becomes operator
});
return user ? { found: true, email: user.email } : { found: false };
},
};
// ATTACK 1: $gt operator — matches all users, returns first document
// args.username = { "$gt": "" }
// Query: { username: { $gt: "" } } → returns first user (sorted by _id)
// Impact: authentication bypass — attacker learns a valid username + email
// ATTACK 2: $ne operator — matches all non-null usernames
// args.username = { "$ne": null }
// Query: { username: { $ne: null } } → matches all users with any username
// Impact: data enumeration
// ATTACK 3: $regex with denial of service
// args.username = { "$regex": "^(a+)+$", "$options": "i" }
// Query: { username: { $regex: "^(a+)+$" } } → catastrophic backtracking
// MongoDB evaluates regex against all documents → query hangs; DoS
// ATTACK 4: $where with JavaScript execution (requires MongoDB version < 4.4 or specific config)
// args.username = { "$where": "function() { return this.role === 'admin' }" }
// Query: { username: { $where: "..." } } → executes JS in MongoDB engine
// Impact: returns all admin users; with more complex $where, side channel exfiltration
// ATTACK 5: Nested operator injection via JSON body parsing
// If args come from JSON body: POST /api/lookup { "username": { "$gt": "" } }
// express.json() parses the body and produces { username: { '$gt': '' } }
// args.username is now an object — passes directly to findOne
// SECURE: validate that field values are the expected primitive type before querying
const lookupUserToolSecure: Tool = {
name: 'lookup_user',
handler: async (args: { username: unknown }) => {
// Type guard: reject anything that is not a non-empty string
if (typeof args.username !== 'string' || args.username.trim() === '') {
throw new Error('username must be a non-empty string');
}
// Length limit prevents regex DoS
if (args.username.length > 200) {
throw new Error('username must not exceed 200 characters');
}
// Now safe: args.username is a string — MongoDB cannot interpret it as an operator
const user = await db.collection('users').findOne({ username: args.username });
return user ? { found: true, email: user.email } : { found: false };
},
};
// SECURE: use Zod to validate entire args object including nested fields
import { z } from 'zod';
const LookupSchema = z.object({
username: z.string().min(1).max(200).regex(/^[a-zA-Z0-9._-]+$/),
});
const handler = async (rawArgs: unknown) => {
const args = LookupSchema.parse(rawArgs); // throws on invalid type
const user = await db.collection('users').findOne({ username: args.username });
return user ?? null;
};
// ALSO SECURE: disable $where operator at the MongoDB server level
// In mongod.conf:
// security:
// javascriptEnabled: false
// Disables $where, $accumulator, and all server-side JavaScript execution
// No application-level code change required; prevents $where injection class-wide
MongoDB query values must be primitive types, not objects: When a MongoDB query filter is constructed as { username: args.username }, the MongoDB driver does not validate that args.username is a string. If it is an object like { $gt: "" }, the driver treats the object keys as MongoDB query operators. This is not a MongoDB bug — operator objects are the designed query mechanism. The fix is to validate that every field value incorporated into a query filter is the expected primitive type (string, number, boolean) before constructing the filter. A typeof args.field !== 'string' check before the query is sufficient to prevent operator injection for string fields.
findOne({ field: args.value }) without typeof args.value === 'string' check: attacker passes { "$gt": "" } as field value; query matches all documents; authentication bypass; { "$where": "..." } executes JavaScript in MongoDB engine; { "$regex": "^(a+)+$" } causes ReDoS DoS. Fix: validate that query field values are the expected primitive type with typeof before query construction; use Zod schema on tool arguments; disable javascriptEnabled in MongoDB config. Detection: db.collection().findOne({ field: args. without prior typeof args. check → HIGH.SA-SKL-NOSQL-002: Redis EVAL script injection — Lua script body constructed via string interpolation
Redis’s EVAL command executes a Lua script in the Redis engine. The EVAL API accepts the script body as a string, followed by a count of keys, then the key arguments, then additional value arguments. The safe pattern is to pass data as separate KEYS[i] and ARGV[i] arguments and reference them from within the Lua script: the data is never interpreted as Lua code. The vulnerable pattern is to construct the Lua script body via string interpolation, embedding user-supplied values directly into the script source. Because Lua uses string concatenation and control flow, an attacker who can inject into the script body can execute arbitrary Redis commands, delete all keys, or exfiltrate key values:
// VULNERABLE: Lua script body constructed via string template interpolation
import { createClient } from 'redis';
const redis = createClient();
// Tool: get value for user-supplied key (rate limit check by key name)
const rateLimitCheckTool: Tool = {
name: 'check_rate_limit',
handler: async (args: { key: string }) => {
// VULNERABLE: key interpolated directly into Lua script body
const script = `
return redis.call('get', '${args.key}')
`;
const result = await redis.eval(script, { numberOfKeys: 0 });
return { count: result };
},
};
// ATTACK: Lua injection via crafted key string
// args.key = "'); redis.call('del', 'ratelimit:*'); return redis.call('get', '"
// Resulting Lua: return redis.call('get', ''); redis.call('del', 'ratelimit:*'); return redis.call('get', '')
// All rate limit keys deleted → rate limit bypass for all users
// MORE DANGEROUS: exfiltrate all keys
// args.key = "x') local k=redis.call('keys','*') for i=1,#k do redis.call('del',k[i]) end return ('x"
// Resulting Lua: execute arbitrary Redis commands including DEL on all keys
// ATTACK 2: Lua injection via atomic operations
// Attacker deletes session keys, flushes rate limit counters, reads arbitrary keys
// Redis EVAL runs atomically — no other commands execute during the script
// Script can iterate all keys, read their values, delete them
// SECURE: use parameterized EVAL — data passed as KEYS[i] and ARGV[i] arguments
// Data in KEYS[i] and ARGV[i] is passed as opaque strings, never interpreted as Lua code
const rateLimitCheckToolSecure: Tool = {
name: 'check_rate_limit',
handler: async (args: { key: string }) => {
if (typeof args.key !== 'string' || !/^[a-zA-Z0-9:._-]+$/.test(args.key)) {
throw new Error('key contains invalid characters');
}
// Lua script uses KEYS[1] — data never touches the script body
const script = `
return redis.call('get', KEYS[1])
`;
const result = await redis.eval(script, {
keys: [args.key], // passed as KEYS[1] in Lua — not interpolated into script
arguments: [], // additional ARGV values if needed
});
return { count: result };
},
};
// SECURE VARIANT: use specific Redis commands instead of EVAL when possible
// EVAL is powerful but complex; prefer atomic command sequences:
const count = await redis.get(`ratelimit:${sanitizedKey}`);
// Or for atomic check-and-increment, use a pipeline:
const pipeline = redis.multi();
pipeline.incr(`ratelimit:${sanitizedKey}`);
pipeline.expire(`ratelimit:${sanitizedKey}`, 60);
const [newCount] = await pipeline.exec();
// Key sanitization: allowlist of characters safe for Redis key names
function sanitizeRedisKey(key: string): string {
if (typeof key !== 'string') throw new Error('key must be a string');
// Redis keys can contain any bytes, but we restrict to safe printable chars
const sanitized = key.replace(/[^a-zA-Z0-9:._-]/g, '');
if (sanitized.length === 0 || sanitized.length > 512) throw new Error('invalid key');
return sanitized;
}
Redis EVAL script injection is Lua code execution in the Redis process: Redis EVAL executes Lua scripts with full access to Redis commands via redis.call(). A Lua injection attack can delete all keys (redis.call('flushall')), read arbitrary key values, modify session tokens, reset rate limit counters, and cause data corruption that persists after the attack. The fix is to never interpolate user data into the Lua script body — always pass data as keys and arguments parameters to redis.eval() and reference them as KEYS[i] and ARGV[i] in the script. These values are opaque strings from Lua’s perspective: they cannot change the script’s control flow.
redis.eval(`... '${args.key}' ...`, { numberOfKeys: 0 }) with key interpolated into Lua script body: attacker injects Lua control flow or Redis commands; all rate limit keys deleted; session tokens read; flushall possible; denial of service. Fix: use parameterized EVAL with keys: [args.key] and reference KEYS[1] in Lua; prefer specific Redis commands over EVAL when possible. Detection: template literal containing args. variable passed as first argument to redis.eval( → HIGH.SA-SKL-NOSQL-003: DynamoDB FilterExpression injection — reserved keyword in unquoted field name
DynamoDB FilterExpression, KeyConditionExpression, and UpdateExpression strings use attribute name placeholders that must be quoted using ExpressionAttributeNames when the attribute name is a DynamoDB reserved keyword or contains special characters. If a tool argument is used directly as an attribute name in an expression string without an ExpressionAttributeNames mapping, and the attribute name happens to be (or is manipulated to be) a DynamoDB reserved word or an expression syntax character, the query fails with an error or behaves unexpectedly. More critically, if the attribute name is used as an expression key with user-supplied value, an attacker may inject expression syntax to manipulate the filter logic or cause query errors that reveal schema information:
// VULNERABLE: user-supplied field name used directly in DynamoDB expression string
import { DynamoDBClient, QueryCommand, ScanCommand } from '@aws-sdk/client-dynamodb';
import { marshall, unmarshall } from '@aws-sdk/util-dynamodb';
const ddb = new DynamoDBClient({});
// Tool: search audits by field value
const searchAuditsTool: Tool = {
name: 'search_audits',
inputSchema: {
type: 'object',
properties: {
fieldName: { type: 'string' },
fieldValue: { type: 'string' },
},
},
handler: async (args: { fieldName: string; fieldValue: string }) => {
const result = await ddb.send(new ScanCommand({
TableName: 'audits',
// VULNERABLE: args.fieldName used directly as attribute name in expression
FilterExpression: `${args.fieldName} = :val`,
ExpressionAttributeValues: {
':val': { S: args.fieldValue },
},
}));
return result.Items?.map(unmarshall) ?? [];
},
};
// ATTACK 1: DynamoDB reserved keyword injection
// DynamoDB has 573 reserved keywords (NAME, STATUS, TYPE, ROLE, etc.)
// args.fieldName = 'status' → FilterExpression: 'status = :val'
// DynamoDB throws: "Expression attribute name is a reserved word"
// Error message reveals schema structure to attacker
// ATTACK 2: Expression syntax injection via field name
// args.fieldName = 'x OR attribute_exists(adminFlag)'
// FilterExpression: 'x OR attribute_exists(adminFlag) = :val'
// Expression is malformed or returns unintended result set
// Depending on schema, may return all items where adminFlag exists
// ATTACK 3: Cross-attribute injection
// args.fieldName = 'userId'
// args.fieldValue = 'victim-user-id' (combined with expression injection in fieldName above)
// Returns audits belonging to any user whose adminFlag attribute exists
// SECURE: allowlist of valid field names; use ExpressionAttributeNames for all names
const ALLOWED_FILTER_FIELDS = new Set(['severity', 'status', 'createdAt', 'userId']);
const searchAuditsToolSecure: Tool = {
name: 'search_audits',
handler: async (args: { fieldName: string; fieldValue: string }) => {
// Validate field name against explicit allowlist
if (!ALLOWED_FILTER_FIELDS.has(args.fieldName)) {
throw new Error(`Field '${args.fieldName}' is not a searchable attribute`);
}
if (typeof args.fieldValue !== 'string' || args.fieldValue.length > 1000) {
throw new Error('fieldValue must be a string under 1000 characters');
}
// Use ExpressionAttributeNames for the field name — '#field' placeholder
// ExpressionAttributeNames maps '#field' to the actual attribute name
// DynamoDB treats '#field' as a name placeholder, not literal text
const result = await ddb.send(new ScanCommand({
TableName: 'audits',
FilterExpression: '#field = :val', // '#field' is a name placeholder
ExpressionAttributeNames: {
'#field': args.fieldName, // actual name passed separately — not in expression string
},
ExpressionAttributeValues: {
':val': { S: args.fieldValue }, // value passed separately — not in expression string
},
}));
return result.Items?.map(unmarshall) ?? [];
},
};
// BONUS: for UpdateExpression, use the same pattern for attribute names AND SET actions
await ddb.send(new UpdateItemCommand({
TableName: 'audits',
Key: { id: { S: auditId } },
UpdateExpression: 'SET #field = :val', // '#field' as name placeholder
ExpressionAttributeNames: { '#field': allowedFieldName },
ExpressionAttributeValues: { ':val': { S: newValue } },
ConditionExpression: 'attribute_exists(id)', // prevent upsert on non-existent items
}));
DynamoDB FilterExpression injection is not SQL injection, but user-controlled attribute names still cause unexpected query behavior: DynamoDB expression strings do not support arbitrary SQL-style operators, but they do support logical operators (AND, OR, NOT), function calls (attribute_exists(), begins_with(), contains()), and conditional expressions. An attacker who controls the field name in an expression string can inject these constructs, change the filter semantics, and cause the query to return a different result set than intended. The ExpressionAttributeNames mapping is DynamoDB’s designed mechanism for passing attribute names as opaque values: use it for all user-influenced attribute names, even those from an allowlist.
`${args.fieldName} = :val` without ExpressionAttributeNames: attacker injects expression syntax (OR attribute_exists(adminFlag)) changing filter semantics; reserved keyword injection causes error revealing schema structure. Fix: validate args.fieldName against an explicit Set allowlist; use ExpressionAttributeNames: { '#field': args.fieldName } with #field placeholder in expression. Detection: template literal expression string containing ${args. as attribute name without ExpressionAttributeNames mapping → MEDIUM.SA-SKL-NOSQL-004: Elasticsearch query injection — user-controlled field name as query object key enables script execution
Elasticsearch query DSL uses JSON query objects where keys represent field names and query types. When a tool accepts a field name from the user and uses it as a key in the Elasticsearch query object, the attacker can supply reserved Elasticsearch field names (_all, _source) or special query keys (script) that change query semantics or trigger server-side script execution. The script query type in Elasticsearch executes a Painless or Groovy script against each document, and injecting the string "script" as a field name in a match query context may cause the query object to be interpreted as a script execution request depending on the Elasticsearch version and security configuration:
// VULNERABLE: user-supplied field name used as dynamic key in Elasticsearch query
import { Client } from '@elastic/elasticsearch';
const es = new Client({ node: 'http://localhost:9200' });
// Tool: search audit documents by field
const searchDocsTool: Tool = {
name: 'search_audits',
handler: async (args: { field: string; value: string }) => {
const result = await es.search({
index: 'audits',
body: {
query: {
match: {
// VULNERABLE: args.field used as dynamic key in query object
[args.field]: args.value, // <-- if args.field = 'script', triggers script query
},
},
},
});
return result.hits.hits.map(h => h._source);
},
};
// ATTACK 1: _all field — matches all document fields (Elasticsearch < 6.0)
// args.field = '_all', args.value = 'admin'
// Query: { match: { _all: 'admin' } }
// Searches all document fields for 'admin' — returns all documents mentioning admin
// Leaks content from fields that were not intended to be searchable
// ATTACK 2: script field injection — Elasticsearch Groovy/Painless RCE (pre-7.x)
// args.field = 'script', args.value = '{"inline":"Runtime.exec(cmd)","lang":"groovy"}'
// Query: { match: { script: { ... } } }
// In old Elasticsearch with dynamic scripting enabled: Groovy script execution = RCE
// In newer Elasticsearch: Painless scripts with security manager = limited RCE
// ATTACK 3: _source field leak
// args.field = '_source', args.value = '*'
// Returns all fields in _source including fields with elevated privilege (tokens, secrets)
// ATTACK 4: query_string instead of match — full query DSL injection
// If the tool uses query_string instead of match:
// { query: { query_string: { query: `${args.field}:${args.value}` } } }
// args.value = 'x OR adminToken:*'
// Returns all documents with adminToken field present — data enumeration
// SECURE: allowlist of valid field names; use specific field query instead of dynamic key
const SEARCHABLE_FIELDS = new Set(['severity', 'status', 'repositoryUrl', 'userId']);
const searchDocsToolSecure: Tool = {
name: 'search_audits',
handler: async (args: { field: string; value: string }) => {
if (!SEARCHABLE_FIELDS.has(args.field)) {
throw new Error(`Field '${args.field}' is not searchable`);
}
if (typeof args.value !== 'string' || args.value.length > 500) {
throw new Error('value must be a string under 500 characters');
}
// Use term query for exact matches (keyword fields)
// term query does not analyze text — the value is matched exactly
const result = await es.search({
index: 'audits',
body: {
query: {
term: {
// args.field has been validated against allowlist — safe to use as key
[args.field]: args.value,
},
},
// Explicitly enumerate returned fields — do not return _source by default
_source: ['id', 'severity', 'status', 'createdAt'],
// Never: _source: true or omitting _source (returns all fields including sensitive ones)
},
});
return result.hits.hits.map(h => h._source);
},
};
// ADDITIONAL HARDENING: disable dynamic scripting in elasticsearch.yml
// script.allowed_types: none (disables all inline scripts)
// script.allowed_contexts: none
// Also: disable _all meta field in index mapping (deprecated in ES 6.0+, removed in 8.0)
// HARDENING: use search template API — separates query structure from user-supplied values
// Pre-registered template: query structure fixed; user supplies only parameter values
await es.renderSearchTemplate({
source: '{"query":{"term":{"{{field}}":"{{value}}"}},"_source":["id","severity","status"]}',
params: { field: validatedField, value: args.value },
});
Never use user-supplied strings as keys in Elasticsearch query DSL objects: Elasticsearch queries are JSON objects where both the key positions (query type, field name) and value positions can be meaningful. Using user input as a dynamic key ([args.field]: args.value) allows the user to supply query types (script, query_string, function_score) or meta-fields (_all, _source) instead of document field names, completely changing the query semantics. The fix is to validate the field name against an explicit Set allowlist of document field names before using it as a key. Even with an allowlist, avoid query_string queries with user-supplied values — use term (exact match) or match (analyzed text) queries instead, which cannot contain operator syntax.
[args.field]: args.value as dynamic query key without field allowlist: attacker supplies "script" as field name triggering Painless/Groovy script execution; "_all" returns cross-field data; query_string context enables operator injection returning unintended document sets. Fix: validate args.field against explicit Set allowlist; use term or match query; enumerate _source fields explicitly; disable inline scripting in elasticsearch.yml. Detection: [args.field]: as dynamic key in Elasticsearch query object without prior allowlist check → HIGH.Remediation summary
| Finding | Severity | Vulnerable pattern | Fix | Detection signal |
|---|---|---|---|---|
| NOSQL-001: MongoDB operator injection | HIGH | db.collection().findOne({ field: args.value }) without typeof check; { $gt: "" } matches all documents |
Validate typeof args.value === 'string' before query; use Zod schema; disable MongoDB javascriptEnabled |
db.collection().findOne({ field: args. without prior typeof args. primitive check |
| NOSQL-002: Redis EVAL script injection | HIGH | Template literal Lua script body with ${args.key} interpolation; Lua control flow injected |
Use parameterized eval(script, { keys: [args.key] }); prefer specific Redis commands over EVAL |
Template literal containing args. variable as first argument to redis.eval( |
| NOSQL-003: DynamoDB FilterExpression | MEDIUM | `${args.fieldName} = :val` in FilterExpression without ExpressionAttributeNames; reserved keyword injection |
Validate fieldName against allowlist; use ExpressionAttributeNames: { '#field': args.fieldName } |
Template literal expression string containing ${args. as attribute name |
| NOSQL-004: Elasticsearch query injection | HIGH | [args.field]: args.value as dynamic Elasticsearch query key without field allowlist |
Validate field against explicit Set allowlist; use term/match; enumerate _source fields; disable inline scripting |
[args.field]: as dynamic key in Elasticsearch query body without prior allowlist check |
SkillAudit detects all four SA-SKL-NOSQL-001 through NOSQL-004 patterns through static analysis and dataflow tracing: MongoDB query construction without primitive type validation, Redis EVAL with interpolated script bodies, DynamoDB expression strings with dynamic attribute names missing ExpressionAttributeNames, and Elasticsearch query DSL with user-controlled dynamic keys. For related security patterns see SA-SKL-SQL SQL injection security, SA-SKL-PROC child_process injection security, and SA-SKL-DESER deserialization security. See the complete SA-SKL attack surface reference for the full vulnerability taxonomy.
Scan your Claude skill for NoSQL injection vulnerabilities
SkillAudit detects MongoDB operator injection, Redis EVAL script injection, DynamoDB expression injection, and Elasticsearch query injection across the full SA-SKL-NOSQL family in 60 seconds.
Get your free audit