Claude skill prototype pollution via URL query string parsers — SA-SKL-PROTOTYPE6
Prototype pollution via URL query strings is a path that bypasses body-level defences: CSP headers, JSON schema validation on request bodies, and bodyParser size limits all leave the query string unguarded. SA-SKL-PROTOTYPE6 covers four patterns where query string parsers inject __proto__ or constructor.prototype keys into the global object chain: the qs library's default allowPrototypes setting; query-string v5's dot-notation nested object parsing; Express req.query spread directly into a Mongoose filter; and a JSON merge-patch body containing __proto__ passed to _.merge().
Query strings: the unguarded prototype pollution surface
Prototype pollution attacks work by inserting a property onto Object.prototype so that every plain object in the process inherits that property via the prototype chain. The classic vector is a JSON body with {"__proto__": {"admin": true}} — well-documented and widely patched. What is less commonly addressed is that URL query strings are parsed into JavaScript objects by the same libraries that parse JSON, with the same nested-key semantics, but without the validation layer that many teams apply to request bodies.
MCP skill servers that expose HTTP endpoints — for webhooks, audit callbacks, search parameters, or configuration APIs — parse query strings on every GET request. If the parser creates nested objects from bracket notation (?a[b]=1 → {a: {b: 1}}) without blocking the special keys __proto__, constructor, and prototype, then a crafted URL can silently pollute Object.prototype for the lifetime of the process. SkillAudit's SA-SKL-PROTOTYPE6 scanner checks for all four patterns in a single scan, covering both the query parser configuration and downstream usage of parsed query objects.
allowPrototypes: false — ?__proto__[admin]=true pollutes Object.prototype?name.__proto__.admin=true creates nested __proto__ key__proto__ passed to _.merge() — pollution scoped to process lifetimePROTOTYPE6-001 — qs.parse() default allowPrototypes setting enables __proto__ pollution
The qs library is the default query string parser for Express when express.urlencoded() is used (it also processes the query string when app.set('query parser', 'extended') is in effect). By default, older versions of qs (before 6.10.3) accepted __proto__ as a bracket-notation key and created a nested object under __proto__, which JavaScript's object assignment semantics then applied to Object.prototype. A GET request to /api/skills?__proto__[admin]=true would cause every subsequently created plain object in the process to have an admin: 'true' property inherited via the prototype chain.
The fix is to explicitly pass { allowPrototypes: false } to qs.parse(), or to upgrade to qs 6.10.3+ where this is the default. Additionally, switch to URLSearchParams for query string parsing wherever nested objects are not needed — URLSearchParams does not support bracket-notation nesting and therefore cannot create __proto__ keys.
// VULNERABLE — qs.parse() without allowPrototypes:false (older qs versions)
import qs from 'qs';
app.get('/api/skills', (req, res) => {
// Express uses qs.parse internally for req.query when query parser is 'extended'
// Equivalent to:
const query = qs.parse(req.url.split('?')[1]);
// GET /api/skills?__proto__[admin]=true
// qs creates: { __proto__: { admin: 'true' } }
// JS assignment semantics apply this to Object.prototype
// Now: ({}).admin === 'true' — every plain object in this process inherits admin:true
// Any downstream check: if (user.admin) escalates to admin for all users
const filter = { ...query }; // spread copies enumerable own AND prototype properties
res.json(await Skill.find(filter));
});
// FIXED — allowPrototypes:false + URLSearchParams for flat query params
import qs from 'qs';
// Option A: qs with allowPrototypes:false (use in Express middleware override)
app.set('query parser', (str) => qs.parse(str, {
allowPrototypes: false, // blocks __proto__, constructor, prototype keys
allowDots: false, // also disable dot-notation to close PROTOTYPE6-002 vector
depth: 2, // limit nesting depth — reduces attack surface
}));
// Option B: URLSearchParams — no nested object support; cannot create __proto__ keys
app.get('/api/skills', (req, res) => {
const params = new URLSearchParams(req.url.split('?')[1] ?? '');
// Explicit allowlist of permitted filter keys
const ALLOWED_KEYS = new Set(['name', 'category', 'minScore', 'maxScore']);
const filter = {};
for (const [key, value] of params) {
if (ALLOWED_KEYS.has(key)) {
filter[key] = value; // only allowlisted keys; never __proto__
}
}
res.json(await Skill.find(filter));
});
PROTOTYPE6-002 — query-string v5 dot-notation parses __proto__ as nested object key
The query-string package v5 and earlier supported dot-notation nested object parsing: ?a.b=1 produces {a: {b: 1}}. This notation is less well-known than bracket notation but equally dangerous for prototype pollution: ?name.__proto__.admin=true creates an object with a name property whose value is an object with a __proto__ key, which then sets Object.prototype.admin = 'true'. The attack is subtler because the __proto__ key is nested rather than top-level, but the pollution effect is identical.
The fix is to upgrade to query-string v7 or later, which does not support nested object parsing and therefore cannot create __proto__ keys via any notation. Alternatively, replace query-string with URLSearchParams which parses query strings as flat key-value pairs with no nested-object semantics. If nested query parameters are genuinely needed, use qs with allowPrototypes: false and an explicit depth limit.
// VULNERABLE — query-string v5 with dot-notation; creates nested __proto__ key
import queryString from 'query-string'; // v5.x with dot notation support
app.get('/api/search', (req, res) => {
// query-string v5: parseUrl with dotNotation:true (may be default depending on version)
const { query } = queryString.parseUrl(req.url, { parseBooleans: true });
// GET /api/search?term=skill&term.__proto__.admin=true
// Parses to: { term: { value: 'skill', __proto__: { admin: true } } }
// The nested __proto__ assignment pollutes Object.prototype
// All subsequent ({}).admin === true for the life of the process
const results = skills.filter(s => s.name.includes(query.term));
res.json(results);
});
// FIXED — upgrade to query-string v7+ (no nested objects) or URLSearchParams
// Option A: upgrade to query-string v7 — no nested object support
import queryString from 'query-string'; // v7.x
app.get('/api/search', (req, res) => {
// v7 does NOT parse dot-notation or bracket-notation into nested objects
// ?term.__proto__.admin=true is treated as the literal key "term.__proto__.admin"
const params = queryString.parse(req.search); // flat key-value pairs only
// Allowlist the keys you care about
const term = typeof params.term === 'string' ? params.term : '';
const category = typeof params.category === 'string' ? params.category : '';
const results = skills.filter(s =>
s.name.includes(term) &&
(!category || s.category === category)
);
res.json(results);
});
// Option B: URLSearchParams — built-in, zero deps, no nested object risk
app.get('/api/search', (req, res) => {
const url = new URL(req.url, 'http://localhost');
const term = url.searchParams.get('term') ?? '';
const category = url.searchParams.get('category') ?? '';
// URLSearchParams never creates nested objects — cannot pollute __proto__
res.json(skills.filter(s => s.name.includes(term)));
});
PROTOTYPE6-003 — Express req.query spread into Mongoose filter
Even when the query string parser itself is patched, spreading req.query directly into a Mongoose filter object introduces prototype pollution risk and also allows arbitrary key injection into database queries. If Object.prototype has been polluted — by any vector, not just the current request — spreading a query object copies both own properties and inherited prototype properties into the new object. This means that pollution from an earlier request (or from an npm package that loaded a poisoned config) can flow into database queries from completely unrelated requests that do not themselves use any dangerous input.
The fix is an Ajv schema validation on all query parameters before they are used as database filter inputs. Define a strict schema with additionalProperties: false and an explicit set of allowed properties. Never spread req.query directly into Mongoose methods (find(), findOne(), aggregate()). Construct the filter object explicitly from individual validated parameters.
// VULNERABLE — req.query spread into Mongoose filter; prototype pollution flows through
import Skill from './models/skill.js';
app.get('/api/skills', async (req, res) => {
// VULNERABLE: spread copies own + prototype-chain properties
// If Object.prototype.admin was polluted earlier, { ...req.query } includes {admin: 'true'}
// Also: attacker sends ?$where=function(){return true} — Mongoose NoSQL injection
const filter = { ...req.query };
// Mongoose receives { name: 'x', admin: 'true' } or { $where: 'function()...' }
// $where injection allows arbitrary JS execution in MongoDB query context
const skills = await Skill.find(filter);
res.json(skills);
});
// FIXED — Ajv schema validation; explicit filter construction; no req.query spread
import Skill from './models/skill.js';
import Ajv from 'ajv';
import addFormats from 'ajv-formats';
const ajv = new Ajv({ coerceTypes: true });
addFormats(ajv);
const querySchema = {
type: 'object',
properties: {
name: { type: 'string', maxLength: 100, pattern: '^[a-zA-Z0-9 _-]+$' },
category: { type: 'string', enum: ['security', 'productivity', 'data', 'integration'] },
minScore: { type: 'number', minimum: 0, maximum: 100 },
maxScore: { type: 'number', minimum: 0, maximum: 100 },
page: { type: 'integer', minimum: 1, maximum: 1000, default: 1 },
limit: { type: 'integer', minimum: 1, maximum: 100, default: 20 },
},
additionalProperties: false, // blocks __proto__, $where, and any other unexpected key
};
const validateQuery = ajv.compile(querySchema);
app.get('/api/skills', async (req, res) => {
const params = { ...req.query }; // coerce only — not passed to Mongoose directly
if (!validateQuery(params)) {
return res.status(400).json({ error: 'Invalid query parameters', details: validateQuery.errors });
}
// Build filter explicitly from validated, typed parameters — never spread directly
const filter = {};
if (params.name) filter.name = { $regex: escapeRegex(params.name), $options: 'i' };
if (params.category) filter.category = params.category;
if (params.minScore !== undefined || params.maxScore !== undefined) {
filter.score = {};
if (params.minScore !== undefined) filter.score.$gte = params.minScore;
if (params.maxScore !== undefined) filter.score.$lte = params.maxScore;
}
const skills = await Skill.find(filter)
.skip((params.page - 1) * params.limit)
.limit(params.limit)
.select('-__v');
res.json(skills);
});
PROTOTYPE6-004 — JSON merge-patch with __proto__ passed to _.merge() pollutes prototype
RFC 7396 defines JSON Merge Patch as a simple way to partially update a JSON document: the patch is a JSON object where each key with a non-null value is applied to the target, and null values delete the key. Libraries implement this by deep-merging the patch object into the target. When _.merge(target, patch) from lodash (versions before 4.17.21) or similar deep merge utilities receive a patch body containing {"__proto__": {"admin": true}}, the merge traverses the patch keys and assigns admin: true to Object.prototype. Unlike a request-scoped object, Object.prototype pollution persists for the entire process lifetime — subsequent requests from all users are affected.
The fix has four layers: validate the merge-patch body with Ajv using additionalProperties: false, which rejects unknown keys including __proto__; use structuredClone() on the result to cut the prototype chain before assigning to any application object; use lodash 4.17.21+ which has the prototype pollution fix; and copy only explicitly allowlisted keys from the patch rather than blindly merging the entire body.
// VULNERABLE — PATCH body with __proto__ passed to _.merge()
import _ from 'lodash'; // older version without prototype pollution patch
app.patch('/api/skills/:id', express.json(), async (req, res) => {
const skill = await Skill.findById(req.params.id);
if (!skill) return res.status(404).json({ error: 'Not found' });
// VULNERABLE: req.body = { "__proto__": { "admin": true } }
// _.merge traverses __proto__ key and sets Object.prototype.admin = true
// All future objects in this process now have admin:true via prototype chain
// This is not request-scoped — it persists until the process restarts
_.merge(skill, req.body);
await skill.save();
res.json(skill);
});
// FIXED — Ajv validation + lodash 4.17.21+ + structuredClone + explicit key copy
import _ from 'lodash'; // ^4.17.21 — prototype pollution fixed in this version
import Ajv from 'ajv';
import addFormats from 'ajv-formats';
const ajv = new Ajv({ removeAdditional: 'all' }); // strips unknown keys
addFormats(ajv);
const patchSchema = {
type: 'object',
properties: {
name: { type: 'string', minLength: 1, maxLength: 200 },
description: { type: 'string', maxLength: 2000 },
category: { type: 'string', enum: ['security', 'productivity', 'data', 'integration'] },
public: { type: 'boolean' },
},
// additionalProperties:false + removeAdditional:'all' — __proto__ is stripped before merge
additionalProperties: false,
};
const validatePatch = ajv.compile(patchSchema);
app.patch('/api/skills/:id', express.json({ limit: '100kb' }), async (req, res) => {
// Step 1: schema validation strips __proto__, constructor, prototype, and unknown keys
const patch = { ...req.body };
if (!validatePatch(patch)) {
return res.status(400).json({ error: 'Invalid patch', details: validatePatch.errors });
}
const skill = await Skill.findById(req.params.id);
if (!skill) return res.status(404).json({ error: 'Not found' });
// Step 2: lodash 4.17.21+ has prototype pollution fix — safe to use _.merge
// But structuredClone first to cut prototype chain on the validated patch
const safePatch = structuredClone(patch); // deep clone; prototype chain is cut
_.merge(skill, safePatch);
// Step 3: alternatively, explicit key copy (most defensive)
// Avoids relying on lodash version; works with any merge utility
const ALLOWED_PATCH_KEYS = ['name', 'description', 'category', 'public'];
for (const key of ALLOWED_PATCH_KEYS) {
if (Object.prototype.hasOwnProperty.call(patch, key)) {
skill[key] = patch[key];
}
}
await skill.save();
res.json(skill);
});
Summary table — SA-SKL-PROTOTYPE6 patterns
| ID | Severity | Root cause | Fix |
|---|---|---|---|
| PROTOTYPE6-001 | HIGH | qs.parse() default allows __proto__ bracket-notation key | allowPrototypes: false + qs 6.10.3+ or URLSearchParams |
| PROTOTYPE6-002 | HIGH | query-string v5 dot-notation parses ?name.__proto__.admin into nested __proto__ | Upgrade to query-string v7+ or use URLSearchParams |
| PROTOTYPE6-003 | HIGH | req.query spread into Mongoose filter — NoSQL injection + pollution flow-through | Ajv strict schema + explicit filter construction; never spread req.query |
| PROTOTYPE6-004 | HIGH | merge-patch body with __proto__ passed to _.merge() — process-lifetime pollution | Ajv removeAdditional + lodash 4.17.21+ + structuredClone + explicit key copy |
SkillAudit scans for all four SA-SKL-PROTOTYPE6 patterns automatically. Run a free scan at skillaudit.dev or see related patterns: SA-SKL-PROTOTYPE5, SA-SKL-ESCAPE5.