nosql-injection
Skill2 starsChanged 4 months agoMITView on GitHub
SAST detection methodology for NoSQL injection (CWE-943), including MongoDB operator injection ($ne/$gt/$regex type-confusion), $where JavaScript execution, aggregation-pipeline abuse, and GraphQL→Mongo flows. Use when reviewing code that queries MongoDB, Redis, CouchDB, or similar document stores. Writes confirmed findings to findings/02-nosql-injection.md.
6 other projects use a version of this.
Adopted by
Most recently taken up by
- emre-guler/websectheir own version, first seen Aug 27, 2026
- conjure-3301/skillstheir own version, first seen Aug 17, 2026
- thejefflarson/soundchecktheir own version, first seen Jul 31, 2026
- langbyyi/websec-skillstheir own version, first seen Jun 12, 2026
- JustineDevs/premortemtheir own version, first seen Jun 9, 2026
- yaklang/hack-skillstheir own version, first seen Apr 29, 2026
Used with
Projects with it also use path-traversal, ssti and 2 more.
Other files people use alongside this one.
Files found in the same public projects as a version of this one, more often than they turn up anywhere else. Each project counts once, large collections count for less, and this file's own repository is left out.
langbyyiSkillpath-traversal
Path traversal and LFI playbook. Use when file paths, download endpoints, include operations, archive extraction, or wrapper behavior may expose filesystem control.
Also in 3 projects that use this
SubhiSecSkillssti
Hunt Server-Side Template Injection (SSTI) in Jinja2, Twig, Freemarker, Velocity, Smarty, ERB, Handlebars, Mustache, and Spring (SpEL). Use when input is reflected in a way that suggests template rendering — error pages, email templates, PDF generators, dynamic content systems.
Also in 3 projects that use this
SubhiSecSkillbusiness-logic
Hunt business logic flaws — race conditions, workflow state bypass, parameter pollution affecting logic, coupon/discount abuse, refund logic, multi-step process bypass, integer overflow, negative quantities, double-spend. Use when looking for non-CVE bugs that require understanding the app's intended workflow.
Also in 3 projects that use this
iAskShahramSkillfile-upload
Uploads a local file to Cloudflare R2 bucket `public` with wrangler and returns the public URL on assets.shahram.dev. Use when the user wants a public link, public URL, or to host/upload a local image or file to R2.
Also in 3 projects that use this
Other versions6 projects use a version of this.
Word for word · 0
None found.
Edited · 0
None found.
Wrote their own version · 6
- yaklang/hack-skills★ 2.4ksame name
- thejefflarson/soundcheck★ 20same name
- langbyyi/websec-skills★ 4same name
- emre-guler/websec★ 2same name
- JustineDevs/premortem★ 2same name
- conjure-3301/skills★ 0same name
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
In this repository49 other files it gives its agents.
- authentication-flawsSkill
- broken-access-control-idorSkill
- business-logic-flawsSkill
- cicd-and-pipeline-injectionSkill
- code-injectionSkill
- command-injectionSkill
- cors-misconfigurationSkill
- crlf-and-header-injectionSkill
- cross-site-scriptingSkill
- csrfSkill
- dependency-and-supply-chainSkill
- dom-clobbering-and-postmessageSkill
- graphql-injection-and-abuseSkill
- hardcoded-secretsSkill
- http-request-smugglingSkill
- iac-misconfigurationSkill
- information-disclosureSkill
- insecure-deserializationSkill
- insecure-randomnessSkill
- jwt-vulnerabilitiesSkill
- ldap-injectionSkill
- llm-and-ai-application-securitySkill
- mass-assignmentSkill
- memory-safetySkill
- mobile-android-securitySkill
- mobile-ios-securitySkill
- oauth-oidc-saml-flawsSkill
- open-redirectSkill
- path-traversal-and-file-inclusionSkill
- prototype-pollutionSkill
- race-conditions-and-toctouSkill
- redosSkill
- sast-final-reportSkill
- sast-finding-validationSkill
- sast-methodologySkill
- security-logging-and-monitoring-failuresSkill
- security-misconfiguration-and-headersSkill
- server-side-template-injectionSkill
- session-managementSkill
- smart-contract-securitySkill
- sql-injectionSkill
- ssrfSkill
- unrestricted-file-uploadSkill
- unsafe-parsers-and-yamlSkill
- weak-cryptographySkill
- web-cache-poisoning-and-deceptionSkill
- websocket-securitySkill
- xpath-and-xml-injectionSkill
- xxeSkill
The file
We split this skill into the rules it gives an agent
3 rules. 0 are common, 0 are distinctive, and 3 are very specific to this project.
0
Common
Most of the 6 edited versions we read keep these.
0
Distinctive
This author's own choices. Worth a look.
3
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 44
All HTTP inputs, but with a critical twist: the shape of the input is part of the attack.
- Very specific: line 77
Enforce the type: before it reaches the query: cast/validate that the value is a string/number (typeof x === 'string', pydantic/isinstance, …
- Very specific: line 83
Never use $where/$expr/mapReduce with user input.
“Common” is measured: kept by at least 6 in 10 of the 6 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
NoSQL Injection — SAST Methodology
Class: NoSQL Injection · CWE-943 · OWASP: A03 Injection
Findings file: findings/02-nosql-injection.md
1. Overview
NoSQL injection occurs when attacker-controlled data reaches a document-store
query and alters its structure — usually by smuggling query operators
($ne, $gt, $regex, $where) or JavaScript into a query object. Unlike SQL,
the classic vector is not string concatenation but type confusion: a field
the code expects to be a string arrives as an object ({"$ne": null}), because
JSON bodies and query strings can encode nested objects. The core test: does a
request value get placed into a query object as-is, letting the attacker choose
its type or inject operator keys?
2. Where it lives
- Query objects built directly from
req.body/req.queryin Node/Mongoose/ nativemongodb:User.find({ user: req.body.user, pass: req.body.pass }). $where,$expr,mapReduce, andgroupclauses that evaluate server-side JavaScript from interpolated input.- Aggregation pipelines assembled from user input (
$match,$lookup,$function,$accumulator). - Python/pymongo filters built from
request.jsondicts without type checks. - PHP MongoDB driver queries built from
$_GET/$_POSTarrays (PHP auto-parsesq[$ne]=1into a nested array). - Redis (Lua
EVAL,SORT ... GETpatterns), CouchDB (Mango$selectors, temporary views), and GraphQL resolvers that forward args straight into a Mongo filter.
3. Sources (tainted input)
All HTTP inputs, but with a critical twist: the shape of the input is part of
the attack. Query strings (?user[$ne]=), JSON bodies ({"user":{"$ne":null}}),
and multipart fields can all deserialize into nested objects/arrays before your
code sees them. Also second-order: operator strings stored in the DB, cache,
or a message queue and later spread into a new filter object. GraphQL variables
and webhook payloads are common indirect sources.
4. Sinks (dangerous operations)
// Node / Mongoose / mongodb — dangerous
User.find({ username: req.body.username, password: req.body.password });
// If body is {"username":"admin","password":{"$ne":null}} → auth bypass.
db.collection('u').find({ age: { $gt: req.query.age } }); // operator passthrough
User.find({ $where: `this.name == '${req.query.name}'` }); // JS execution → sandboxed RCE
db.collection('u').aggregate([{ $match: req.body.filter }]);// whole stage attacker-shaped
Model.find({ name: { $regex: req.query.q } }); // ReDoS / data exfil via regex# Python / pymongo — dangerous
db.users.find({"user": request.json["user"], "pw": request.json["pw"]})
# request.json can carry {"pw": {"$ne": null}} → returns first user
db.users.find({"$where": "this.pin == " + request.args["pin"]}) # JS injection// PHP — dangerous (nested-array parsing)
$c->users->find(['user' => $_GET['user'], 'pass' => $_GET['pass']]);
// URL ?user=admin&pass[$ne]= makes pass an array {'$ne': ''} → bypass5. Sanitizers / safe patterns
Safe:
- Enforce the type before it reaches the query: cast/validate that the value
is a string/number (
typeof x === 'string', pydantic/isinstance, schema validation withexpress-validator, Mongoose typed schemas withsanitizeFilter/strictQuery). - Reject or strip keys beginning with
$and containing.(e.g.mongo-sanitize,express-mongo-sanitize) before building the filter. - Never use
$where/$expr/mapReducewith user input; disable server-side JS (--noscripting). - For aggregation, build stages from a fixed template and bind only leaf values.
Fails / not a real sanitizer:
- HTML/SQL escaping — irrelevant to operator/type injection.
- Casting on one branch only, or after the filter object is built.
- Stripping
$but not the.dotted-path notation (or vice versa), or checking top-level keys but not nested ones inside$or/$andarrays. - Trusting Mongoose to coerce — coercion applies to typed schema paths;
Mixed,findon unindexed fields, orstrictQuery:falselet objects through. - Blocklisting the literal string
$wherewhile allowing$expr/$function.
6. Detection methodology
- Find sinks: grep for query APIs receiving request objects directly.
rg -n '\.(find|findOne|update|updateMany|deleteOne|deleteMany|aggregate|count|distinct)\s*\(' rg -n '\$where|\$expr|mapReduce|\$function|\$accumulator|\$regex' rg -n 'find\([^)]*req\.(body|query|params)|find\([^)]*request\.(json|args|form)' - Confirm passthrough: is a request value used as a query-object value or a
whole
$match/filterstage without a type check or$-key filter? - Trace type enforcement: is the value guaranteed to be a scalar before the query? Look for casts, schema validation, or a sanitize middleware applied globally and before the handler (not just on some routes).
- Check for JS-eval sinks: any
$where/$expr/$functionwith interpolated input is code injection inside the DB (see the code-injection skill for the sandbox-escape angle). - Confirm reachability: exposed route/GraphQL resolver? Pre-auth (login, password-reset, search endpoints are prime)?
- Classify: auth bypass, blind boolean/regex data exfiltration, ReDoS, or server-side JS execution.
7. Modern & niche variants
- Operator injection via type confusion: the flagship NoSQL bug.
{"$ne": null},{"$gt":""},{"$in":[...]}submitted where a string was expected. Bypasses login checks (password: {$ne: null}matches any user) and filters. Highest-value finding; look for any query field fed straight fromreq.body. $regexblind extraction: attacker supplies{"$regex":"^A"}and observes hit/no-hit to exfiltrate secrets (tokens, PINs) character-by-character — a blind boolean oracle. Also a ReDoS vector via catastrophic patterns.$where/$expr/$functionJavaScript execution: server evaluates a JS predicate. Interpolating input into the string yields JS injection running in the DB's (sandboxed but abusable) engine — infinite loops (DoS), data access across the doc, and historically sandbox escapes.- Aggregation-pipeline abuse: a whole
$match/$lookup/$groupstage taken from input.$lookupcan join across collections to leak other tenants' data;$function/$accumulatorrun JS;$out/$mergecan write to arbitrary collections. - Dynamic query objects: code spreads user input into the filter
(
{...req.query, tenantId}) — attacker overridestenantIdor injects$or. - PHP nested-array injection:
param[$ne]=in the query string becomes a PHP array; historically the easiest NoSQLi to reach. - GraphQL→Mongo: resolver forwards a
filter/wherearg object into a Mongo query, exposing operator injection through a typed-looking API. - Redis/CouchDB: Redis Lua
EVALwith interpolatedKEYS/ARGVor command injection via unescaped args; CouchDB Mango$selectors and temporary map/reduce views that execute user JavaScript.
8. Common false positives
- Values cast to a scalar (
String(x),parseInt, schema-validated) before the query — type confusion is closed. - Global
mongo-sanitize/express-mongo-sanitizemiddleware confirmed applied before all handlers. $where/$regexwith only hard-coded constants.- Mongoose queries on strictly typed schema paths where coercion rejects objects.
9. Severity & exploitability
Base High (data read/write). Critical if it yields authentication bypass,
cross-tenant reads via $lookup, arbitrary writes via $out/$merge, or if a
$where/$function sink reaches code execution — and higher still when pre-auth.
Lower to Medium if strictly read-only on non-sensitive data behind admin auth
or the input is provably scalar-constrained. See references/severity-model.md.
10. Remediation
Enforce scalar types on every query input via schema validation before building
the filter; reject keys starting with $ or containing .. Never pass whole
request objects into find/aggregate. Disable server-side JavaScript and avoid
$where/$expr/$function with any dynamic content. Bind only leaf values in
aggregation templates and apply least-privilege DB roles.
11. Output
Append each confirmed finding to findings/02-nosql-injection.md using
references/finding-template.md. Set Class: NoSQL Injection, CWE: CWE-943,
and in Chain potential name primitives such as auth bypass ({$ne:null} in
a login query), arbitrary data read (blind $regex / $lookup cross-tenant →
leaked secrets for other chains), arbitrary write ($out/$merge), or code
execution ($where/$function → consumed by the code-injection chain).
Primitives (controlled): provides DATA_READ,DATA_WRITE,SECRET_LEAK,AUTHZ_BYPASS (auth-bypass filter),CODE_EXEC ($where JS); consumes none
References
- CWE-943; OWASP A03:2021 Injection; OWASP Testing Guide — NoSQL Injection; MongoDB security checklist (disable server-side scripting).
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

