Claude MCP skill insecure deserialization — Redis pub/sub and cache invalidation security — SA-SKL-DESER4
Message queues and cache invalidation channels are trusted data paths — the assumption is that only internal services write to them. When an attacker gains indirect write access (via SSRF to a Redis admin endpoint, SQL injection enabling a crafted NOTIFY, or a compromised worker process), unsanitised deserialization of queue messages can escalate from cache inconsistency to remote code execution. SA-SKL-DESER4 covers four patterns unique to Redis pub/sub, BullMQ job queues, PostgreSQL NOTIFY/LISTEN, and WebSocket message deserialization in MCP skill registries.
SUBSCRIBE callback deserializes message body with JSON.parse() without schema validation; attacker with write access to Redis (via SSRF to Redis HTTP admin at port 7379, or via exposed CONFIG SET) crafts a message with an unexpected structure; downstream code destructures the message and passes unsanitised fields to database queries or file operations — crash-and-leak or SQL injection pivotjob.data.scriptPath is replaced with an arbitrary file path; job processor passes job.data.scriptPath directly to execFile() without path validation — arbitrary file execution on the worker hostNOTIFY/LISTEN used for cache invalidation; pg client parses notification payload with JSON.parse(); attacker who can execute SQL (via SQL injection in search endpoint) sends a crafted NOTIFY with malicious payload; downstream cache handler processes attacker-controlled data without schema validationJSON.parse() — attacker sends {"__proto__":{"isAdmin":true}}; combined with Object.assign(req.session, parsedMessage) in the WebSocket message handler, prototype pollution sets isAdmin on Object.prototype; subsequent authorization checks using req.user.isAdmin return true for all usersDESER4-001 — Redis SUBSCRIBE without schema validation
MCP skill registries commonly use Redis pub/sub to propagate cache invalidation events between horizontally-scaled instances: when a skill is updated on one server, it publishes a skill:updated message to Redis, and all servers subscribe to invalidate their local cache. The subscriber processes these messages with JSON.parse() and immediately uses the parsed fields to perform cache operations or database lookups. An attacker who gains write access to Redis — via SSRF to the Redis HTTP admin port, via a misconfigured Redis that accepts unauthenticated connections, or via Redis CONFIG SET abuse — can publish a crafted message that causes the subscriber to pass attacker-controlled data to downstream operations.
// VULNERABLE — DESER4-001
// Redis SUBSCRIBE callback: no schema validation on parsed message.
// Attacker with Redis write access publishes:
// PUBLISH skill:updated '{"skillId":"' + "'; DROP TABLE skills; --" + '","version":1}'
// Downstream query uses skillId without sanitisation.
const subscriber = redis.createClient();
subscriber.subscribe('skill:updated');
subscriber.on('message', (channel, message) => {
const event = JSON.parse(message); // No validation — trusts whatever Redis holds
// VULNERABLE: event.skillId used in a raw query context downstream
cache.del(`skill:${event.skillId}`);
db.query(`SELECT * FROM skills WHERE id = '${event.skillId}'`); // SQL injection via Redis
if (event.forceRefresh) {
skillLoader.loadSkillFromDisk(event.scriptPath); // path traversal via Redis
}
});
// FIXED — DESER4-001
// Fix: Validate the message schema with Zod immediately after JSON.parse().
// Accept only the exact shape expected; reject the message if it doesn't match.
// Use parameterised queries; never string-interpolate Redis message fields.
const { z } = require('zod');
const SkillUpdatedSchema = z.object({
skillId: z.string().uuid(), // FIX: enforce UUID format — no SQL metacharacters
version: z.number().int().positive(),
forceRefresh: z.boolean().optional(), // FIX: optional boolean only — no arbitrary fields
// FIX: scriptPath removed — file paths never come from Redis messages
});
subscriber.on('message', (channel, message) => {
let raw;
try {
raw = JSON.parse(message);
} catch {
logger.warn({ channel }, 'Invalid JSON in Redis message — discarded');
return;
}
const result = SkillUpdatedSchema.safeParse(raw);
if (!result.success) {
// FIX: Reject the message; log for alerting; never process attacker-shaped data
logger.warn({ channel, issues: result.error.issues }, 'Redis message schema mismatch — discarded');
return;
}
const { skillId, version } = result.data;
cache.del(`skill:${skillId}`);
// FIX: Parameterised query — skillId is a UUID, safe to use as parameter
db.query('SELECT * FROM skills WHERE id = $1', [skillId]);
});
Redis is not a trusted boundary: Internal services often treat Redis as fully trusted — the assumption is that only your own code writes to it. But SSRF vulnerabilities (scanning the LAN for Redis on port 6379/7379) and misconfigured Redis instances (no AUTH, no bind address restriction) are common enough that Redis must be treated as an adversarial input source for deserialization purposes. Schema validation on every Redis message is cheap and eliminates the entire class of Redis-driven injection attacks.
DESER4-002 — BullMQ job data injection leading to execFile
BullMQ workers that process skill audit jobs retrieve job data from Redis and pass it to audit sub-processes. The job data structure typically includes a scriptPath field — the path to the skill script to audit — which the worker passes to execFile() to run the static analysis tool. When an attacker can inject arbitrary job data into the BullMQ queue (via the same Redis write vector as DESER4-001), they can replace scriptPath with any path on the worker's filesystem, causing the worker to execute an arbitrary file.
// VULNERABLE — DESER4-002
// BullMQ worker processes audit jobs. job.data comes from Redis.
// Attacker injects into the queue:
// LPUSH bull:audit:wait '{"id":"evil","data":{"skillId":"x","scriptPath":"/tmp/evil.sh"}}'
// Worker passes scriptPath to execFile — /tmp/evil.sh executes as the worker process.
const auditWorker = new Worker('audit', async (job) => {
const { skillId, scriptPath } = job.data; // VULNERABLE: trusts job.data from Redis
// VULNERABLE: scriptPath from job data passed directly to execFile
const result = await execFileAsync('/usr/bin/node', [
'/app/audit/runner.js',
'--script', scriptPath, // attacker controls this
'--skill-id', skillId,
]);
return JSON.parse(result.stdout);
}, { connection: redis });
// FIXED — DESER4-002
// Fix 1: Validate job.data schema with Zod before processing.
// Fix 2: Derive the scriptPath from the skillId via a trusted database lookup —
// never accept file paths from the job queue.
// Fix 3: Validate the derived path is within the expected sandbox directory.
const { z } = require('zod');
const path = require('path');
const AuditJobSchema = z.object({
skillId: z.string().uuid(),
requestedBy: z.string().uuid(),
});
const SKILL_SANDBOX_DIR = '/app/sandboxes/skills';
const auditWorker = new Worker('audit', async (job) => {
// FIX 1: Validate job data schema
const data = AuditJobSchema.parse(job.data);
// FIX 2: Derive path from trusted DB lookup using the validated UUID
const skill = await db.skills.findById(data.skillId);
if (!skill) throw new Error(`Skill ${data.skillId} not found`);
// FIX 3: Validate path is within sandbox directory
const scriptPath = path.resolve(SKILL_SANDBOX_DIR, skill.sandboxDir, 'index.js');
if (!scriptPath.startsWith(SKILL_SANDBOX_DIR + path.sep)) {
throw new Error(`Path traversal detected for skill ${data.skillId}`);
}
const result = await execFileAsync('/usr/bin/node', [
'/app/audit/runner.js',
'--script', scriptPath,
'--skill-id', data.skillId,
]);
return JSON.parse(result.stdout);
}, { connection: redis });
Never pass file paths through queues: The pattern "enqueue a path, dequeue and execute it" is a recurring source of path traversal and arbitrary code execution vulnerabilities. The correct pattern is to enqueue an identifier (a UUID, a database row ID), then resolve the path in the worker via a trusted database lookup, then validate the resolved path against the expected sandbox directory. This way the queue message contains no actionable data — it's a pointer, not an instruction.
DESER4-003 — PostgreSQL NOTIFY/LISTEN payload without schema validation
Some MCP registries use PostgreSQL's built-in NOTIFY/LISTEN mechanism for cache invalidation, taking advantage of the existing database connection. The pg Node.js client exposes notification payloads as raw strings via the notification event; most implementations parse these with JSON.parse() and immediately process the result. The vulnerability arises when the same database connection accepts SQL from an injection point: an attacker who can execute arbitrary SQL can issue a SELECT pg_notify('cache:invalidate', '{"table":"skills","id":"malicious-payload"}') that injects a crafted cache invalidation message. The cache handler processes the attacker-controlled payload without validation.
// VULNERABLE — DESER4-003
// PostgreSQL NOTIFY/LISTEN for cache invalidation.
// Attacker exploits SQL injection in /api/skills/search to execute:
// SELECT pg_notify('cache:invalidate', '{"table":"skills","id":"../../../etc/passwd"}');
// Cache handler processes the payload and passes event.id to file operations.
pgClient.query('LISTEN "cache:invalidate"');
pgClient.on('notification', (msg) => {
const event = JSON.parse(msg.payload); // No validation
// VULNERABLE: event.table and event.id used without validation
if (event.table === 'skills') {
cache.del(`skill:${event.id}`); // path traversal via id
skillFileCache.delete(`/data/${event.table}/${event.id}.json`); // traversal
}
});
// FIXED — DESER4-003
// Fix: Zod schema validation on notification payload.
// Validate table name against an allowlist — never use arbitrary strings as file paths.
// Use UUID validation on the id field.
const { z } = require('zod');
const CacheInvalidateSchema = z.object({
table: z.enum(['skills', 'audits', 'users', 'orgs']), // FIX: enum allowlist
id: z.string().uuid(), // FIX: UUID only
});
pgClient.on('notification', (msg) => {
let raw;
try { raw = JSON.parse(msg.payload); }
catch { logger.warn('Invalid JSON in NOTIFY payload'); return; }
const result = CacheInvalidateSchema.safeParse(raw);
if (!result.success) {
logger.warn({ issues: result.error.issues }, 'NOTIFY payload schema mismatch — discarded');
return;
}
const { table, id } = result.data;
// FIX: table is enum-validated; id is UUID-validated
cache.del(`${table}:${id}`);
// FIX: No file operations keyed on notification data
});
DESER4-004 — WebSocket prototype pollution via JSON.parse and Object.assign
JavaScript's JSON.parse() is safe against executable deserialization gadgets unlike eval() or node-serialize — it cannot execute code. However, JSON.parse('{"__proto__":{"isAdmin":true}}') returns a plain object with a property literally named "__proto__". When this object is passed to Object.assign(target, parsed), the __proto__ property assignment modifies Object.prototype, poisoning it for all subsequent objects in the process. If the application uses Object.assign(req.session, wsMessage) to merge WebSocket message fields into the session, an attacker can set arbitrary properties on Object.prototype — including privilege flags like isAdmin.
// VULNERABLE — DESER4-004
// WebSocket message handler merges parsed message into session via Object.assign.
// Attacker sends:
// {"__proto__": {"isAdmin": true}}
// Object.assign copies __proto__ key — this triggers prototype pollution.
// All subsequent {} objects inherit isAdmin:true from Object.prototype.
wss.on('connection', (ws, req) => {
ws.on('message', (data) => {
const msg = JSON.parse(data.toString()); // safe by itself
// VULNERABLE: Object.assign with untrusted parsed message — prototype pollution
Object.assign(req.session, msg);
// Now Object.prototype.isAdmin === true for every object in this process
if (req.session.action === 'refresh') {
broadcastToUser(req.session.userId);
}
});
});
// Elsewhere in the app — now broken for all users:
function requireAdmin(req, res, next) {
if (req.user.isAdmin) return next(); // true for everyone after the attack
res.status(403).json({ error: 'Forbidden' });
}
// FIXED — DESER4-004
// Fix 1: Validate message schema with Zod — only allow expected shapes.
// Fix 2: Never merge untrusted data into session/req with Object.assign.
// Fix 3: Use Object.create(null) for intermediate objects when merging is unavoidable.
// Fix 4: Use hasOwnProperty checks (or Object.hasOwn) for privilege flags, not prototype lookup.
const { z } = require('zod');
const WsMessageSchema = z.discriminatedUnion('action', [
z.object({ action: z.literal('refresh') }),
z.object({ action: z.literal('ping') }),
z.object({
action: z.literal('subscribe'),
channel: z.string().max(64).regex(/^[a-z0-9:_-]+$/),
}),
]);
wss.on('connection', (ws, req) => {
ws.on('message', (data) => {
let raw;
try { raw = JSON.parse(data.toString()); }
catch { ws.send(JSON.stringify({ error: 'Invalid JSON' })); return; }
// FIX 1: Validate schema — only expected actions; no __proto__ or unknown keys
const result = WsMessageSchema.safeParse(raw);
if (!result.success) {
ws.send(JSON.stringify({ error: 'Invalid message shape' }));
return;
}
// FIX 2: Use only the validated, typed message — never assign raw parsed data to session
const msg = result.data;
if (msg.action === 'refresh') {
broadcastToUser(req.session.userId);
}
});
});
// FIX 4: Use Object.hasOwn for privilege checks — not prototype lookup
function requireAdmin(req, res, next) {
if (Object.hasOwn(req.user, 'isAdmin') && req.user.isAdmin === true) return next();
res.status(403).json({ error: 'Forbidden' });
}
JSON.parse is not the problem — Object.assign is: JSON.parse('{"__proto__":{"isAdmin":true}}') returns {"__proto__": {"isAdmin": true}} as a plain object where "__proto__" is a string key — it does not modify the prototype chain by itself. The pollution happens when Object.assign(target, parsed) iterates over the parsed object's keys and sets "__proto__" as a property assignment, which does trigger prototype mutation. The defence is Zod schema validation (which rejects the __proto__ key as unexpected) combined with never passing untrusted parsed objects to Object.assign targeting live objects.
Summary — SA-SKL-DESER4 at a glance
| Pattern | Root cause | Fix | Severity |
|---|---|---|---|
| DESER4-001 | Redis SUBSCRIBE message processed without schema validation | Zod validation on all Redis pub/sub payloads | CRITICAL |
| DESER4-002 | BullMQ job data scriptPath passed to execFile without validation | Validate schema; derive path from DB, not job data | CRITICAL |
| DESER4-003 | PostgreSQL NOTIFY payload processed without schema validation | Zod with enum table allowlist and UUID id validation | HIGH |
| DESER4-004 | WebSocket JSON.parse result merged into session via Object.assign | Zod discriminated union; never Object.assign untrusted data | HIGH |
SkillAudit's deserialization scanner checks all four SA-SKL-DESER4 patterns: it inspects Redis SUBSCRIBE handlers for schema validation, BullMQ workers for file path derivation patterns, PostgreSQL NOTIFY handlers for payload validation, and WebSocket handlers for prototype-pollution-vulnerable Object.assign calls. See also SA-SKL-DESER3 (skill configuration loading and plugin manifest deserialization).