Claude MCP skill insecure deserialization — skill dependency graph and version resolution endpoints

SA-SKL-DESER22 documents four insecure deserialization vulnerabilities in MCP skill registry skill dependency graph and version resolution endpoints. The dependency graph computation endpoint deserializes user-supplied npm shrinkwrap data via yaml.load() with DEFAULT_FULL_SCHEMA, enabling a !!js/function gadget in the postInstall hook to achieve RCE at graph evaluation time; the version resolution pipeline reads pinned version configs from Redis as MessagePack with no null-prototype target, allowing __proto__.isAdmin:true to pollute Object.prototype and elevate all subsequent role checks; the dependency audit pipeline stores CVSS score fields in MongoDB as BSON Decimal128 and deserializes them via an eval()-adjacent path, achieving code execution during report generation; and the version constraint solver reads user-supplied semver ranges from Redis as node-serialize payloads, allowing an IIFE gadget to achieve RCE at constraint evaluation time.

Critical DESER22-001 — Dependency graph reads npm shrinkwrap via yaml.load(DEFAULT_FULL_SCHEMA); !!js/function in dependencies[].postInstall achieves RCE at dependency evaluation time
High DESER22-002 — Version resolution reads pinned config from Redis as MessagePack; __proto__.isAdmin:true key pollutes Object.prototype, elevating all role checks in the same process
Critical DESER22-003 — Dependency audit stores BSON Decimal128 at cvssScore field in MongoDB; promoteValues:true deserialization passes value through eval()-adjacent conversion path, achieving code execution during report generation
Critical DESER22-004 — Version constraint solver reads user-supplied semver range from Redis via node-serialize; IIFE gadget in constraint string achieves RCE at deserialize() call

DESER22-001 — YAML DEFAULT_FULL_SCHEMA RCE via npm shrinkwrap deserialization

MCP skill registries that resolve transitive dependencies often accept user-supplied npm-shrinkwrap.json or package-lock.json files. Some implementations convert these to YAML for a unified dependency data format before computing the dependency graph. When yaml.load() is called without an explicit schema restriction, it defaults to DEFAULT_FULL_SCHEMA, which supports the !!js/function tag. An attacker who can submit a malicious shrinkwrap file — either directly or by pushing to a repository that triggers an automated re-analysis — can embed a !!js/function value in the dependencies[n].postInstall field. The function body executes when the dependency graph code evaluates the hook, achieving RCE in the registry process.

Vulnerable
// DESER22-001 — VULNERABLE
const yaml = require('js-yaml');

async function buildDependencyGraph(shrinkwrapContent) {
  // DEFAULT_FULL_SCHEMA supports !!js/function — RCE on eval of hook fields
  const parsed = yaml.load(shrinkwrapContent); // VULNERABLE
  for (const [name, dep] of Object.entries(parsed.dependencies || {})) {
    if (dep.postInstall) {
      // Evaluates attacker-controlled function from YAML !!js/function tag
      await dep.postInstall(name, dep);
    }
  }
  return computeGraph(parsed);
}

YAML schemas and function deserialization: js-yaml’s DEFAULT_FULL_SCHEMA and DEFAULT_SAFE_SCHEMA (deprecated) allow !!js/function, !!js/regexp, and !!js/undefined tags. FAILSAFE_SCHEMA allows only strings, sequences, and mappings — it is the only schema safe for untrusted input. Never call yaml.load() on user-supplied data without an explicit schema; use yaml.load(input, { schema: yaml.FAILSAFE_SCHEMA }) and then apply a Zod schema to the parsed object.

Fixed
// DESER22-001 — FIXED
// FAILSAFE_SCHEMA; convert from JSON (not YAML) for structured dep data; Zod validation.
const yaml = require('js-yaml');
const { z } = require('zod');

const DepSchema = z.object({
  version: z.string().regex(/^\d+\.\d+\.\d+/),
  resolved: z.string().url().optional(),
  integrity: z.string().regex(/^sha512-/).optional(),
  // No postInstall field — not a trusted lifecycle hook from user data
});
const ShrinkwrapSchema = z.object({
  name: z.string(),
  version: z.string(),
  dependencies: z.record(DepSchema).optional().default({}),
});

async function buildDependencyGraph(shrinkwrapJson) {
  // Parse JSON directly — never YAML for structured npm data from user input
  const raw = JSON.parse(shrinkwrapJson);
  const parsed = ShrinkwrapSchema.parse(raw); // throws ZodError on unexpected fields
  return computeGraph(parsed);
}

DESER22-002 — MessagePack prototype pollution via pinned version config from Redis

Version resolution pipelines that support pinned dependency versions often cache the pinned version config in Redis to avoid repeated database lookups. When the cached value is encoded as MessagePack and decoded without a null-prototype target object, an attacker with write access to Redis can insert a MessagePack payload containing a __proto__ key with an isAdmin: true value. When the payload is decoded via msgpack.decode() into a plain {} target, the __proto__ key is assigned to the target’s prototype, polluting Object.prototype.isAdmin to true. All subsequent role checks in the same process that evaluate if (user.isAdmin) will return truthy, elevating every user to admin without any authentication bypass.

Vulnerable
// DESER22-002 — VULNERABLE
const msgpack = require('@msgpack/msgpack');

async function getPinnedVersionConfig(orgId, skillId) {
  const cached = await redis.getBuffer(`pinned:${orgId}:${skillId}`);
  if (!cached) return null;

  // Decoding into default {} target — __proto__ key pollutes Object.prototype
  const config = msgpack.decode(cached); // VULNERABLE — no null-prototype protection
  return config;
}

// Downstream role check — evaluates to true for all users after pollution
function requireAdmin(req, res, next) {
  if (req.user.isAdmin) return next(); // always true after Object.prototype.isAdmin = true
  res.status(403).json({ error: 'Admin required' });
}

Redis is a trust boundary: Even internal Redis instances can be compromised via SSRF, misconfigured network ACLs, or lateral movement. Any data read from Redis that influences security-sensitive control flow must be deserialized with prototype pollution protection and validated against a strict schema before use.

Fixed
// DESER22-002 — FIXED
// Null-prototype target; Zod schema; server-side role source (never from cached config).
const msgpack = require('@msgpack/msgpack');
const { z } = require('zod');

const PinnedConfigSchema = z.object({
  skillId: z.string().uuid(),
  pinnedVersion: z.string().regex(/^\d+\.\d+\.\d+/),
  pinnedBy: z.string().uuid(),
  pinnedAt: z.string().datetime(),
  // No isAdmin, role, or permission fields
});

async function getPinnedVersionConfig(orgId, skillId) {
  const cached = await redis.getBuffer(`pinned:${orgId}:${skillId}`);
  if (!cached) return null;

  // Decode into null-prototype object — __proto__ key becomes own property, not prototype assignment
  const raw = msgpack.decode(cached, { forceIntegerToFloat: false });
  const safe = Object.assign(Object.create(null), raw);
  return PinnedConfigSchema.parse(safe);
}

DESER22-003 — BSON Decimal128 eval path in dependency audit report generation

Dependency audit pipelines that store CVSS scores as numeric fields in MongoDB sometimes use BSON Decimal128 for precision. When the MongoDB Node.js driver is configured with { promoteValues: true } (a commonly misunderstood option), Decimal128 values are converted to JavaScript numbers via an internal path that in some driver versions passes the raw BSON bytes through an eval()-adjacent conversion function. An attacker who can insert a malicious document into the dependency audit collection — via an SSRF that reaches a MongoDB write path, or via a compromised dependency source that injects data into the audit pipeline — can craft a Decimal128 value at the cvssScore field that triggers code execution during report generation when the driver performs the type promotion.

Vulnerable
// DESER22-003 — VULNERABLE
const { MongoClient } = require('mongodb');

const client = new MongoClient(MONGO_URI, {
  promoteValues: true,  // VULNERABLE — promotes BSON types including Decimal128 via eval path
  promoteBuffers: true,
});

async function generateDependencyAuditReport(auditId) {
  const db = client.db('registry');
  // If attacker has inserted a malicious Decimal128 at cvssScore, code executes here
  const findings = await db.collection('depAuditFindings')
    .find({ auditId })
    .toArray(); // promoteValues triggers Decimal128 conversion — eval path
  return renderReport(findings);
}

Avoid promoteValues: true in the MongoDB driver for untrusted data: The safer approach is to explicitly map BSON types to primitives after retrieval, using controlled conversion code (e.g., bsonValue.toString() for Decimal128) rather than relying on driver-level type promotion that may change behavior across driver versions. Store numeric scores as plain BSON Double or Int32 when precision requirements allow it.

Fixed
// DESER22-003 — FIXED
// No promoteValues; explicit type mapping; Zod schema on deserialized document.
const { MongoClient, Decimal128 } = require('mongodb');
const { z } = require('zod');

const client = new MongoClient(MONGO_URI, {
  promoteValues: false, // keep BSON types as-is — explicit conversion below
  promoteBuffers: false,
});

const FindingSchema = z.object({
  cveId: z.string(),
  cvssScore: z.number().min(0).max(10),
  severity: z.enum(['CRITICAL', 'HIGH', 'MEDIUM', 'LOW', 'INFORMATIONAL']),
  packageName: z.string(),
});

function mapFinding(raw) {
  return {
    cveId: String(raw.cveId ?? ''),
    // Explicit Decimal128 → number conversion — no eval path
    cvssScore: raw.cvssScore instanceof Decimal128
      ? parseFloat(raw.cvssScore.toString())
      : Number(raw.cvssScore),
    severity: String(raw.severity ?? ''),
    packageName: String(raw.packageName ?? ''),
  };
}

async function generateDependencyAuditReport(auditId) {
  const findings = await client.db('registry')
    .collection('depAuditFindings')
    .find({ auditId })
    .toArray();
  return findings.map(f => FindingSchema.parse(mapFinding(f)));
}

DESER22-004 — node-serialize IIFE gadget in semver constraint solver

Version constraint solvers that need to persist user-supplied semver range expressions sometimes cache them in Redis to avoid re-parsing on every resolution request. If the cached value is stored and retrieved using node-serialize, an attacker who can write to the Redis key (via SSRF or a compromised upstream service) can insert an IIFE gadget: {"range":"_$$ND_FUNC$$_function(){require('child_process').execSync('id > /tmp/pwned')}()"}. When serialize.deserialize() is called on the Redis value, the IIFE executes immediately, achieving RCE in the registry process.

Vulnerable
// DESER22-004 — VULNERABLE
const serialize = require('node-serialize');

async function resolveVersionConstraint(orgId, skillId, constraintKey) {
  const cached = await redis.get(`constraint:${orgId}:${skillId}:${constraintKey}`);
  if (!cached) return null;

  // node-serialize evaluates $$ND_FUNC$$ IIFE gadgets at deserialize time — RCE
  const constraint = serialize.deserialize(cached); // VULNERABLE
  return semver.maxSatisfying(await getAvailableVersions(skillId), constraint.range);
}

Never use node-serialize for cached data: The node-serialize package was designed for internal use in controlled environments. Its deserialize() function intentionally supports executable JavaScript via IIFE gadgets. Any data path that calls node-serialize.deserialize() on data from an external store (Redis, MongoDB, message queue) is a critical RCE vulnerability. Replace all node-serialize usage with JSON.parse() followed by Zod validation.

Fixed
// DESER22-004 — FIXED
// JSON.parse + Zod semver validation; never node-serialize for cached user data.
const { z } = require('zod');
const semver = require('semver');

const ConstraintSchema = z.object({
  range: z.string().refine(v => semver.validRange(v) !== null, {
    message: 'Invalid semver range',
  }),
  createdAt: z.string().datetime(),
  createdBy: z.string().uuid(),
});

async function resolveVersionConstraint(orgId, skillId, constraintKey) {
  const cached = await redis.get(`constraint:${orgId}:${skillId}:${constraintKey}`);
  if (!cached) return null;

  const raw = JSON.parse(cached); // JSON only — no executable type tags
  const constraint = ConstraintSchema.parse(raw); // throws ZodError on invalid semver
  return semver.maxSatisfying(await getAvailableVersions(skillId), constraint.range);
}

Related advisories: For insecure deserialization in webhook payload signing and delivery retry endpoints, see SA-SKL-DESER21. For insecure deserialization in CI/CD integration config and pipeline trigger endpoints, see SA-SKL-DESER20. For SSRF in skill changelog and release notes fetch endpoints, see SA-SKL-SSRF39.

Scan your MCP server or Claude skill

SkillAudit checks for DESER22, DESER21, SSRF, injection, prototype pollution, and 50+ more vulnerability patterns — in 60 seconds, with a shareable grade badge.

Get early access