← Security advisories

Claude MCP skill insecure deserialization — skill search index and ranking computation endpoints — SA-SKL-DESER40

SA-SKL-DESER40 documents four insecure deserialization vulnerabilities in MCP skill registry search index and ranking computation endpoints. Search infrastructure processes every skill in the registry — a deserialization gadget placed in the search index config or ranking model achieves code execution at the moment of every query, every index rebuild, and every ranking computation. These are not low-frequency batch operations; they execute hundreds of times per second in production registries. DESER40-001 exploits yaml.load() with DEFAULT_FULL_SCHEMA on Redis-cached search index config to execute arbitrary JavaScript at document index time. DESER40-002 exploits BSON Code type deserialization from MongoDB to eval() arbitrary code at ranking computation time. DESER40-003 exploits MessagePack prototype pollution to disable search authentication globally. DESER40-004 exploits node-serialize IIFE gadgets to achieve RCE at search aggregation time.

SA-SKL-DESER40 findings at a glance
CRITICALDESER40-001 — search index config reads from Redis as YAML via yaml.load() DEFAULT_FULL_SCHEMA; !!js/function in indexConfig.onDocumentIndex achieves RCE at every document indexing event; fix: FAILSAFE_SCHEMA; JSON for all index config; Zod IndexConfigSchema; named-event dispatch table
CRITICALDESER40-002 — ranking model reads from MongoDB as BSON; BSON Code type at rankingModelFn field triggers eval() during ranking computation for every search query; fix: reject BSON Code; promoteValues:false; Zod string-only schema; named-ranker lookup
CRITICALDESER40-003 — search result queue stored in Redis as MessagePack; __proto__.skipSearchAuth:true pollutes Object.prototype, disabling authentication checks for all subsequent search API requests in process; fix: null-prototype target; Zod strict(); JSON instead of MessagePack
CRITICALDESER40-004 — search aggregation reads via node-serialize; IIFE gadget achieves RCE at search aggregation time reachable from any authenticated consumer of the search API; fix: JSON.parse + Zod; detect and reject _$$ND_FUNC$$_ payloads; sealed config at deploy time

DESER40-001 — YAML RCE on search index config stored in Redis

Severity: CRITICAL

The search indexing worker reads its configuration document from Redis using yaml.load(buffer, { schema: yaml.DEFAULT_FULL_SCHEMA }). The DEFAULT_FULL_SCHEMA permits the !!js/function tag, which causes js-yaml to compile the tagged string as a JavaScript function using the new Function() constructor. An attacker who can write to the Redis key that holds the index config document — via a misconfigured Redis ACL, a Redis SSRF from another application component, or a compromised Redis replica — can place a !!js/function payload at the indexConfig.onDocumentIndex callback field. This function executes in the Node.js process context at every document indexing event: skill creation, skill update, and full index rebuild. The search indexing worker typically holds cloud storage write permissions, database admin credentials, and the Anthropic API key used for embedding generation. All are available to the injected function.

Vulnerable
// Search index worker — unsafe YAML deserialization of Redis config
const configBuf = await redis.get('search:index:config');
const indexConfig = yaml.load(configBuf, {
  schema: yaml.DEFAULT_FULL_SCHEMA,  // permits !!js/function
});

indexWorker.on('document', async (doc) => {
  await indexConfig.onDocumentIndex(doc);  // attacker function executes here
});
Fixed
// Search index worker — safe config deserialization
const IndexConfigSchema = z.object({
  indexName: z.string().regex(/^[a-z0-9_-]{1,64}$/),
  fields: z.array(z.string().regex(/^[a-zA-Z0-9_.]{1,128}$/)).max(32),
  onDocumentIndex: z.enum(['default', 'embedding_only', 'full_text_only']),
});

const configBuf = await redis.get('search:index:config');
const rawConfig = JSON.parse(configBuf);  // JSON only — no YAML
const indexConfig = IndexConfigSchema.parse(rawConfig);

const dispatchTable = {
  default: defaultIndexHandler,
  embedding_only: embeddingOnlyHandler,
  full_text_only: fullTextOnlyHandler,
};

indexWorker.on('document', async (doc) => {
  await dispatchTable[indexConfig.onDocumentIndex](doc); // no eval, no dynamic call
});

DESER40-002 — BSON Code eval on ranking model function field

Severity: CRITICAL

The search ranking service reads its ranking model document from MongoDB using the default BSON deserialization options. MongoDB's BSON library maps the Code BSON type to a JavaScript object with a code string property by default. When the application subsequently calls the ranking function stored in the rankingModelFn field, it passes the BSON Code object to eval() to convert the stored code string to an executable function. An attacker who can write to the MongoDB collection storing ranking models — via a MongoDB injection in another endpoint, a compromised MongoDB user, or a misconfigured Atlas role — can store a BSON Code document with arbitrary JavaScript. This function executes in the ranking computation path for every search query processed by the registry, giving the attacker persistent code execution that runs hundreds of times per second.

Vulnerable
// Ranking service — unsafe BSON Code deserialization
const rankingModel = await db.collection('ranking_models').findOne({ active: true });
// rankingModel.rankingModelFn is a BSON Code object
const rankFn = eval(`(${rankingModel.rankingModelFn.code})`); // RCE here

searchResults.sort((a, b) => rankFn(a, b, queryContext));
Fixed
// Ranking service — safe ranking model lookup
const RankingModelSchema = z.object({
  modelName: z.enum(['bm25', 'semantic', 'hybrid', 'recency_boost']),
  weights: z.object({
    textScore: z.number().min(0).max(1),
    semanticScore: z.number().min(0).max(1),
    recencyScore: z.number().min(0).max(1),
  }).strict(),
});

const rawModel = await db.collection('ranking_models').findOne(
  { active: true },
  { projection: { rankingModelFn: 0 } }  // never load function field
);
const model = RankingModelSchema.parse(rawModel);

const rankerLookup = {
  bm25: bm25Ranker,
  semantic: semanticRanker,
  hybrid: hybridRanker,
  recency_boost: recencyBoostRanker,
};

searchResults.sort((a, b) => rankerLookup[model.modelName](a, b, model.weights, queryContext));

Never store executable code in a database and retrieve it for eval. Ranking models should be named references to server-side implementations, not serialized functions. Any field that could be passed to eval(), new Function(), or vm.runInContext() is an RCE waiting to happen once an attacker gains write access to the data store.

DESER40-003 — MessagePack prototype pollution disables search authentication

Severity: CRITICAL

The search result queue is serialized to Redis using MessagePack. When the search worker deserializes queue entries using msgpack.decode(buffer) with default options, it passes the decoded object directly to Object.assign(target, decoded) without validating that none of the keys are __proto__. A queue entry containing {"__proto__": {"skipSearchAuth": true}} pollutes Object.prototype for the entire Node.js process. All subsequent request objects created with {} or new Object() inherit skipSearchAuth: true. The search authentication middleware checks if (req.skipSearchAuth) return next() — which now evaluates to true for every request, disabling authentication globally until the process restarts. The fix decodes into a null-prototype object and validates with Zod.strict() which rejects unexpected keys including __proto__.

Vulnerable
// Search worker — MessagePack queue entry prototype pollution
const entry = msgpack.decode(queueBuffer);  // could contain __proto__
Object.assign(queueEntry, entry);           // pollutes Object.prototype

// In search middleware — now bypassed for every request
router.use((req, res, next) => {
  if (req.skipSearchAuth) return next();  // __proto__ pollution makes this true for all
  return requireSession(req, res, next);
});
Fixed
// Search worker — safe queue entry deserialization
const SearchQueueEntrySchema = z.object({
  queryId: z.string().uuid(),
  query: z.string().max(512),
  userId: z.string().uuid().optional(),
  timestamp: z.number().int().positive(),
}).strict();  // rejects __proto__ and any extra keys

const raw = JSON.parse(queueBuffer.toString());  // JSON only — no MessagePack
const entry = SearchQueueEntrySchema.parse(
  Object.assign(Object.create(null), raw)  // null-prototype target blocks __proto__ merge
);

DESER40-004 — node-serialize IIFE gadget achieves RCE at search aggregation time

Severity: CRITICAL

The search aggregation service reads intermediate results from a shared cache using node-serialize's unserialize() function. The node-serialize library supports Immediately Invoked Function Expressions (IIFEs) via the _$$ND_FUNC$$_ marker prefix. Any object property whose value begins with this marker is deserialized by passing the function string to eval() and immediately calling the result. An attacker who can write to the shared cache — via a cache SSRF, a compromised cache node, or a Redis injection — places a payload at any key the aggregation service reads. The IIFE executes in the Node.js process context at the moment of deserialization, before any validation of the aggregation result. The search aggregation worker holds database read credentials, the Anthropic embedding API key, and cloud object storage access keys used to serve skill artifacts. The fix replaces node-serialize with JSON.parse combined with Zod schema validation and an explicit pre-parse check for the IIFE marker string.

Vulnerable
// Search aggregation — node-serialize IIFE RCE
const { unserialize } = require('node-serialize');

const cached = await redis.get(`search:agg:${queryHash}`);
const agg = unserialize(cached);  // IIFE in payload executes here: RCE
return agg.results;
Fixed
// Search aggregation — safe deserialization with IIFE detection
const SearchAggSchema = z.object({
  results: z.array(z.object({
    skillId: z.string().uuid(),
    score: z.number(),
    rank: z.number().int().nonneg(),
  })).max(100),
  totalHits: z.number().int().nonneg(),
  tookMs: z.number().nonneg(),
});

const cached = await redis.get(`search:agg:${queryHash}`);
if (!cached) return null;

// Reject any payload containing the node-serialize IIFE marker
if (cached.includes('_$$ND_FUNC$$_')) {
  logger.error({ queryHash }, 'Rejected node-serialize IIFE marker in search cache');
  await redis.del(`search:agg:${queryHash}`);  // evict poisoned entry
  return null;
}

const agg = SearchAggSchema.parse(JSON.parse(cached));

Remediation summary

FindingSeverityPrimary remediationSecondary hardening
DESER40-001CriticalReplace YAML with JSON for all index config; use FAILSAFE_SCHEMA if YAML is required; Zod schema validation; named-event dispatch tableRestrict Redis ACLs; audit all yaml.load() callsites for schema argument; never use DEFAULT_FULL_SCHEMA on untrusted input
DESER40-002CriticalReject BSON Code type; promoteValues:false; Zod string-only schema; named-ranker lookup table; never eval stored codeAudit MongoDB collections for BSON Code documents; restrict MongoDB write permissions; seal ranking model at deploy time
DESER40-003CriticalReplace MessagePack with JSON; null-prototype decode target; Zod strict() schema rejecting extra keys including __proto__Add process monitor to alert on skipSearchAuth usage; never use Object.assign without null-prototype guard
DESER40-004CriticalReplace node-serialize with JSON.parse + Zod; pre-parse IIFE marker check; evict poisoned cache entriesRemove node-serialize from dependency tree entirely; audit all unserialize() callsites; consider sealed config at build time

Scan your MCP skill registry search and ranking infrastructure for DESER40 patterns. SkillAudit checks search index config loading, ranking model deserialization, queue entry parsing, and aggregation cache reading for unsafe deserialization patterns. See also SA-SKL-DESER39 and SA-SKL-DESER38. Connect at skillaudit.dev.