Claude skill prototype pollution advanced security — SA-SKL-PROTOTYPE2
Basic prototype pollution via __proto__ key injection is a well-known attack and many validation libraries now strip it. The more dangerous patterns are the ones that bypass __proto__ filters: constructor.prototype path traversal that Zod passes through on object spread, array prototype pollution via numeric string keys in object-to-array assignments, the lodash _.merge() CVE that remains exploitable in pre-4.17.21 versions still found in many skill dependencies, and a custom JSON.parse reviver that merges parsed keys without filtering pollution paths. SA-SKL-PROTOTYPE2 covers all four with the precise bypass technique and an auditable fix using Zod strict schemas and Object.create(null).
Why prototype pollution persists despite known mitigations
Prototype pollution is unusual among injection vulnerabilities because the payload must traverse multiple processing steps to cause harm: the attacker-controlled object must be merged into another object via a path that walks the prototype chain, and then the polluted property must be read by security-sensitive code. Each step is separately defensible, but security teams often implement only the first defense (strip __proto__ from input) without understanding that constructor.prototype, __defineGetter__, and other paths achieve the same effect. SkillAudit finds skills where a Zod schema that explicitly strips __proto__ still allows constructor.prototype.isAdmin = true through on a subsequent object spread — not because Zod is broken, but because the developer misunderstood that Zod validates structure but does not prevent prototype mutation during the spread itself.
SA-SKL-PROTOTYPE2 in scope: PROTOTYPE2-001 (constructor.prototype bypass via object spread), PROTOTYPE2-002 (array prototype pollution via numeric key spread), PROTOTYPE2-003 (lodash _.merge CVE-2019-10744), PROTOTYPE2-004 (JSON.parse reviver merge without pollution filter). For the basic __proto__ pollution pattern, see SA-SKL-PROTOTYPE.
PROTOTYPE2-001 — constructor.prototype path bypasses __proto__ filter
When a developer learns about prototype pollution, they typically add a check for __proto__ keys in incoming objects. This is correct but incomplete. JavaScript's prototype chain can also be accessed via obj.constructor.prototype — the constructor property on every object references its constructor function, and the constructor's prototype property is the prototype chain object. Setting obj.constructor.prototype.isAdmin = true modifies Object.prototype exactly as obj.__proto__.isAdmin = true does. Zod strips unknown keys in strict mode but does not prevent the constructor key from being present in the validated object — and if that validated object is spread into another object, the spread copies the constructor reference, and subsequent property access on the spread target can modify the prototype chain.
// VULNERABLE: Zod strips __proto__ but constructor.prototype survives object spread
const { z } = require('zod');
const userPrefsSchema = z.object({
theme: z.enum(['dark', 'light']),
language: z.string().max(10),
notifications: z.boolean(),
});
app.post('/api/prefs', authMiddleware, (req, res) => {
const parsed = userPrefsSchema.parse(req.body);
// Zod validates structure — but input was: { theme: 'dark', constructor: { prototype: { isAdmin: true } } }
// Zod with .strict() would reject extra keys — but without .strict(), Zod passes { theme: 'dark', constructor: {...} }
// The 'constructor' key survives because it is a valid key name that Zod doesn't strip by default
// VULNERABLE: spread copies the constructor reference into prefs
const prefs = { ...req.user.prefs, ...parsed };
// { ...parsed } includes { constructor: { prototype: { isAdmin: true } } }
// This does NOT directly pollute Object.prototype — but:
// VULNERABLE: deep merge after spread DOES pollute:
const merged = deepMerge(req.user.prefs, parsed);
// deepMerge walks all keys including 'constructor' → 'prototype' → sets isAdmin = true
// Object.prototype.isAdmin === true after this call
await db.users.updatePrefs(req.user.id, prefs);
res.json({ ok: true });
});
// Later in auth middleware:
// if (user.isAdmin) { ... }
// user.isAdmin is undefined on the user object but Object.prototype.isAdmin === true
// Prototype chain lookup returns true — authentication bypass
// FIXED: Zod .strict() rejects unknown keys; Object.create(null) for merge accumulator
const { z } = require('zod');
const userPrefsSchema = z.object({
theme: z.enum(['dark', 'light']),
language: z.string().max(10),
notifications: z.boolean(),
}).strict(); // FIXED: .strict() rejects any key not in the schema definition
// { constructor: { prototype: ... } } → ZodError: Unrecognized key(s): 'constructor'
app.post('/api/prefs', authMiddleware, (req, res) => {
let parsed;
try {
parsed = userPrefsSchema.parse(req.body);
} catch (err) {
return res.status(400).json({ error: 'Invalid preferences' });
}
// FIXED: for deep merge, use Object.create(null) accumulator — no prototype chain
// Object.create(null) creates an object with NO prototype — cannot be polluted
const safePrefs = Object.create(null);
Object.assign(safePrefs, req.user.prefs); // Copy existing prefs to null-prototype object
for (const [key, value] of Object.entries(parsed)) {
// hasOwnProperty check on the validated object (not prototype chain)
if (Object.prototype.hasOwnProperty.call(parsed, key)) {
safePrefs[key] = value;
}
}
// FIXED: serialize through JSON to sanitize before storing
const sanitized = JSON.parse(JSON.stringify(safePrefs));
await db.users.updatePrefs(req.user.id, sanitized);
res.json({ ok: true });
});
.strict() and then passes the parsed object to a deep merge function; Zod without .strict() allows the constructor key through; a deep merge that walks constructor.prototype modifies Object.prototype globally, enabling authentication bypass for any subsequent code that reads properties from arbitrary objects; the attack bypasses defenses that only filter __proto__. Fix: add .strict() to all Zod schemas that process user input; use Object.create(null) as the accumulator for any merge operation on user-supplied objects; sanitize with JSON.parse(JSON.stringify()) before deep merging. Detection: SkillAudit flags Zod schemas without .strict() whose output is passed to a function matching deep-merge patterns (merge(, assign(, extend(, defaults().PROTOTYPE2-002 — Array prototype pollution via object spread with numeric keys
Prototype pollution is usually discussed in the context of Object.prototype, but Array.prototype can also be polluted. Array.prototype is in the prototype chain of every array: properties set on Array.prototype appear on every array in the process. The attack uses Object.assign([], userInput) where userInput is an attacker-controlled object with numeric string keys: { "0": "evil", "length": 1, "constructor": ... }. Object.assign copies own enumerable properties — numeric string keys from an object to an array create array elements. Combined with the constructor key, the assignment can walk the prototype chain. Even without prototype pollution, an unexpected array structure (arr[0] = "evil" when the application expects an empty array) can cause type confusion in downstream code.
// VULNERABLE: Object.assign to array with user-controlled object
app.post('/api/settings/tags', authMiddleware, (req, res) => {
// Expects: req.body = { tags: ['security', 'mcp'] }
const userTags = req.body.tags;
// VULNERABLE: if userTags is an object { "0": "evil", "length": 1 }, this creates array-like
const tags = Object.assign([], userTags);
// tags[0] = "evil", tags.length = 1
// If userTags = { "__proto__": { "polluted": true } }, Object.assign on [] may pollute
// Array.prototype in some JS engine versions
// Another variant: spread operator on user-controlled "array"
const tagList = [...userTags]; // If userTags.Symbol.iterator is poisoned, behavior is undefined
await db.users.updateTags(req.user.id, tags);
res.json({ tags });
});
// FIXED: Zod .array() schema validates element types and enforces no extra keys
const { z } = require('zod');
const tagsSchema = z.object({
tags: z.array(z.string().min(1).max(50).regex(/^[a-z0-9-]+$/)).max(20),
}).strict();
app.post('/api/settings/tags', authMiddleware, (req, res) => {
let parsed;
try {
parsed = tagsSchema.parse(req.body);
} catch (err) {
return res.status(400).json({ error: 'Invalid tags' });
}
// FIXED: parsed.tags is a validated JavaScript array with string elements only
// Zod ensures it is a real array, not an array-like object
// No prototype pollution possible — Zod reconstructs the array from scratch
// If you must use Object.assign on arrays, use a fresh array literal target:
// const safeTags = Object.assign([], parsed.tags); // OK because source is Zod-validated
// For user-controlled data that might be array-like objects:
// Convert to real array explicitly with Array.from() and validate
// const safeTags = Array.from(userInput, item => {
// if (typeof item !== 'string') throw new Error('Expected string');
// return item;
// });
await db.users.updateTags(req.user.id, parsed.tags);
res.json({ tags: parsed.tags });
});
Object.assign([], userInput) or spread ([...userInput]) on user-supplied data without first validating that the input is a proper array with typed elements; an attacker can supply an object with numeric string keys that creates an array-like structure with unexpected properties, potentially polluting Array.prototype or causing type confusion in downstream array operations. Fix: use z.array(z.string()) with .strict() in Zod to validate that input is a real array with correctly-typed elements before any array operations; never use Object.assign with user-supplied objects as the source when the target is an array. Detection: SkillAudit flags Object.assign([], ...) patterns where the source is from req.body, req.query, or other user-controlled input.PROTOTYPE2-003 — Prototype pollution via lodash _.merge (CVE-2019-10744)
CVE-2019-10744 is a prototype pollution vulnerability in lodash's _.merge() function prior to version 4.17.21. When _.merge(target, source) is called with a source object containing a __proto__ key (or its URL-encoded equivalent), lodash walks the key path and sets properties on Object.prototype. The CVE is well-known and lodash has been patched, but SkillAudit continues to find MCP skills using lodash versions prior to 4.17.21 — often transitively, through a dependency that pins an older version. Even with a patched lodash, calling _.merge(target, req.body) directly on user input is unsafe because lodash 4.17.21 blocks __proto__ but not constructor.prototype in all cases. The safe pattern is to validate user input with Zod before passing it to any merge function.
// VULNERABLE: lodash _.merge directly on req.body — CVE-2019-10744
const _ = require('lodash'); // version 4.17.15 — VULNERABLE
app.post('/api/config', authMiddleware, (req, res) => {
const defaultConfig = {
timeout: 30000,
retries: 3,
logLevel: 'info',
};
// VULNERABLE: lodash 4.17.15 _.merge processes __proto__ key
// Input: { "__proto__": { "isAdmin": true } }
// After this call: Object.prototype.isAdmin === true
const config = _.merge(defaultConfig, req.body);
// All subsequent objects in this process now have isAdmin = true via prototype chain
res.json({ config });
});
// Also vulnerable with nested payload:
// { "constructor": { "prototype": { "isAdmin": true } } }
// lodash 4.17.21+ blocks __proto__ but older versions do not block constructor path
// FIXED: validate with Zod before _.merge; upgrade lodash to 4.17.21+
const _ = require('lodash'); // version 4.17.21+ — FIXED for __proto__ path
const { z } = require('zod');
const configSchema = z.object({
timeout: z.number().int().min(1000).max(120000).optional(),
retries: z.number().int().min(0).max(10).optional(),
logLevel: z.enum(['debug', 'info', 'warn', 'error']).optional(),
}).strict(); // .strict() rejects constructor, __proto__, any unexpected key
app.post('/api/config', authMiddleware, (req, res) => {
let parsed;
try {
parsed = configSchema.parse(req.body);
} catch (err) {
return res.status(400).json({ error: 'Invalid config' });
}
// FIXED: parsed is a clean object with only the allowed keys
// Safe to _.merge because no __proto__ or constructor keys can be present
const config = _.merge(defaultConfig, parsed);
// Additional defense: use JSON.parse(JSON.stringify()) to strip any
// residual prototype references before merging
const sanitized = JSON.parse(JSON.stringify(parsed));
const safeConfig = _.merge({}, defaultConfig, sanitized);
res.json({ config: safeConfig });
});
// package.json — ensure lodash >= 4.17.21:
// "lodash": "^4.17.21"
// npm audit will catch this — run it in CI
_.merge(target, req.body) or equivalent with user-controlled input without prior Zod validation; lodash versions prior to 4.17.21 are vulnerable to CVE-2019-10744 where a __proto__ key in the source object directly modifies Object.prototype; even lodash 4.17.21+ can be exploited via the constructor.prototype path without Zod strict-mode validation; SkillAudit finds this pattern in transitive dependencies that pin older lodash versions. Fix: upgrade lodash to 4.17.21+; apply Zod schema with .strict() before any _.merge() call on user input; sanitize with JSON.parse(JSON.stringify()) before merging. Detection: SkillAudit flags _.merge(, merge(, deepmerge( calls where the second argument traces to req.body, req.query, or parsed user input without an intervening Zod parse call.PROTOTYPE2-004 — Prototype pollution via JSON.parse reviver
A JSON.parse reviver function receives each key-value pair during parsing and can transform or replace values. Some MCP skills use a custom reviver to perform post-parse transformation — converting date strings, decoding base64 fields, or flattening nested structures. If the reviver merges parsed keys into an accumulator object without filtering pollution paths, an attacker can supply a JSON payload with a __proto__ key whose string value passes JSON.parse validation and is then merged into the accumulator. The resulting object has a __proto__ property that, when Object.assign is used to merge the accumulator into another object, walks the prototype chain. This is distinct from the standard prototype pollution vector because the reviver operates on already-parsed JSON — the attacker cannot directly supply an object with a __proto__ key (JSON doesn't have that concept), but they can supply a string key path that the reviver re-interprets as a prototype path.
// VULNERABLE: custom JSON.parse reviver merges keys without pollution path filter
app.post('/api/audit/config', authMiddleware, (req, res) => {
let body;
try {
// VULNERABLE: custom reviver processes all keys including pollution paths
body = JSON.parse(req.rawBody, (key, value) => {
if (key === '') return value; // Root object — return as-is
// Custom transformation: convert dot-notation keys to nested object
// "settings.timeout" → { settings: { timeout: value } }
if (key.includes('.')) {
const parts = key.split('.');
let obj = {};
let current = obj;
for (let i = 0; i < parts.length - 1; i++) {
current[parts[i]] = {};
current = current[parts[i]];
}
current[parts[parts.length - 1]] = value;
// VULNERABLE: merge of obj back into accumulator via Object.assign
// Input: "__proto__.isAdmin" → obj = { __proto__: { isAdmin: true } }
// Object.assign({}, obj) pollutes Object.prototype
return Object.assign(this, obj); // 'this' is the accumulator — pollution!
}
return value;
});
} catch (err) {
return res.status(400).json({ error: 'Invalid JSON' });
}
});
// FIXED: validate with Zod after JSON.parse; reviver filters pollution paths
const { z } = require('zod');
// FIXED: simple reviver that only transforms safe, known keys
// Never interprets key paths — only transforms values
const safeReviver = (key, value) => {
if (key === '') return value; // Root object
// Only transform specific, known keys — not all keys
if (key === 'createdAt' || key === 'updatedAt') {
return new Date(value); // Date string conversion
}
// FIXED: explicitly block pollution paths
const POLLUTION_PATHS = ['__proto__', 'constructor', 'prototype'];
if (POLLUTION_PATHS.includes(key)) {
return undefined; // Drop the key entirely
}
return value;
};
const auditConfigSchema = z.object({
settings: z.object({
timeout: z.number().int().min(1000).max(120000),
rules: z.array(z.string()).max(50),
}).strict(),
metadata: z.object({
source: z.string().max(100),
}).strict().optional(),
}).strict();
app.post('/api/audit/config', authMiddleware, (req, res) => {
let parsed;
try {
// Parse with safe reviver that filters pollution paths
const rawParsed = JSON.parse(req.rawBody, safeReviver);
// Then validate structure with Zod strict schema
parsed = auditConfigSchema.parse(rawParsed);
} catch (err) {
return res.status(400).json({ error: 'Invalid config' });
}
// parsed is fully validated — no pollution paths, correct types, .strict() on all schemas
await processAuditConfig(parsed);
res.json({ ok: true });
});
JSON.parse reviver that interprets key paths (dot notation, bracket notation) and merges them into an accumulator object via Object.assign or _.merge without filtering __proto__, constructor, and prototype key segments; the reviver's path interpretation reintroduces prototype pollution vectors that plain JSON.parse would not allow; a JSON payload with the string key "__proto__.isAdmin" passes JSON.parse validation but is interpreted as a prototype path by the reviver. Fix: add an explicit block list for pollution path segments in any reviver that interprets keys as paths; always validate the reviver output with a Zod strict schema before use; prefer simple value-transformation revivers that do not interpret key paths. Detection: SkillAudit flags JSON.parse(input, reviver) where the reviver calls Object.assign, _.merge, or bracket notation assignment without a check against pollution path constants.SkillAudit detection summary — SA-SKL-PROTOTYPE2
| Pattern ID | Severity | What SkillAudit flags | Fix |
|---|---|---|---|
| PROTOTYPE2-001 | HIGH | Zod schemas without .strict() whose output is passed to deep-merge functions (merge, assign, extend, defaults) | Zod .strict() on all user input schemas; Object.create(null) accumulator; JSON.parse(JSON.stringify()) sanitization |
| PROTOTYPE2-002 | MEDIUM | Object.assign([], userInput) or spread on user-supplied data without Zod array schema validation | z.array(z.string()) with element type validation; never Object.assign with user-supplied source to array target |
| PROTOTYPE2-003 | HIGH | _.merge(target, req.body) without prior Zod validation; lodash <4.17.21 in package-lock.json | Lodash 4.17.21+; Zod .strict() before any _.merge(); JSON.parse(JSON.stringify()) sanitization before merge |
| PROTOTYPE2-004 | HIGH | JSON.parse(input, reviver) where reviver calls Object.assign or _.merge without pollution path filter | Block __proto__, constructor, prototype in reviver key checks; validate reviver output with Zod strict schema |
Related patterns: For basic __proto__ prototype pollution via query string parsing and JSON body parsing, see SA-SKL-PROTOTYPE. For multipart upload body parsing that can also be a source of polluted keys, see SA-SKL-MULTIPART2. For argument pollution in CLI-wrapping skills, see SA-SKL-ARGPOLLUTE.