Claude MCP skill insecure deserialization — audit result export and report generation pipeline
SA-SKL-DESER19 documents four insecure deserialization vulnerabilities in MCP skill registry audit result export and report generation pipelines. These findings span eval'd Redis template strings enabling RCE at render time, per-user MongoDB CSS strings passed unsanitized to wkhtmltopdf enabling SSRF and local file read, node-serialize IIFE gadgets in cached XLSX column configs achieving RCE at deserialize(), and MessagePack-decoded diff configs causing prototype pollution that grants persistent admin access to any user in the same process.
${"$"}{require('child_process').execSync('id')} achieves RCE at template render time
exec(); attacker CSS with @import url("file:///etc/passwd") exfiltrates server files via rendered PDF
{"rce":"_$$ND_FUNC$$_function(){require('child_process').execSync('id')}()"} achieves RCE at deserialize() call
__proto__.adminOverride:true pollutes Object.prototype; all subsequent permission checks return truthy admin value for any user
DESER19-001 (Critical): Redis eval'd Handlebars template config achieves RCE at render time
MCP skill registry audit export pipelines often support per-user template customisation: users configure the layout, column selection, and formatting of their exported audit reports. When these template configurations are stored in Redis for performance and loaded at job execution time, the attack surface depends entirely on how the cached value is consumed. When the export job retrieves the template config and passes it directly to a JavaScript template engine configured with allowProtoPropertiesByDefault: true or, worse, passes the string directly to eval() for dynamic template compilation, any attacker who can write to the Redis key space achieves arbitrary code execution at the moment the export job runs.
Redis key-space write access is achievable through several vectors in a compromised infrastructure: a Redis instance lacking authentication, a misconfigured Redis ACL permitting writes from application network segments, or a Redis injection vulnerability in another endpoint that allows arbitrary key writes. Once the attacker controls the template config key, the payload executes in the context of the export worker process — typically with file system access, network access, and the service account credentials needed to reach the database. CVSS 9.8 (AV:N/AC:L/PR:N/UI:N/S:C/C:H/I:H/A:H).
// VULNERABLE — DESER19-001: Handlebars template config from Redis evaluated as template string
// File: workers/export-worker.js
const redis = require('redis');
const Handlebars = require('handlebars');
async function runExportJob(jobId, userId) {
const redisKey = `template_config:${userId}`;
// VULNERABILITY: templateStr is an attacker-controlled string from Redis
// Handlebars.compile() with no allowedProtoProperties restriction
// If runtime: registered as SafeString or helpers use eval, RCE is achievable
const templateStr = await redisClient.get(redisKey);
// Worse pattern: direct eval of the cached string
const render = eval(`(data) => \`${templateStr}\``); // ← RCE vector
const auditData = await db.getAuditResults(jobId);
const output = render(auditData);
await writeExportFile(jobId, output);
}
Fix: Never eval() strings retrieved from a cache layer. Store template configuration as a structured JSON object describing allowed fields, column order, and formatting options — not as a template string. At render time, map this config to a pre-compiled, server-controlled template using only the allowed fields as data bindings. Use Handlebars in strict mode with no-prototype helpers (allowProtoPropertiesByDefault: false, allowProtoMethodsByDefault: false). Validate the Redis-retrieved config with a Zod schema before use, rejecting any keys outside the expected config schema.
// FIXED — DESER19-001: JSON config from Redis validated with Zod; no eval; pre-compiled template
// File: workers/export-worker.js
const { z } = require('zod');
const Handlebars = require('handlebars');
const ExportConfigSchema = z.object({
columns: z.array(z.enum(['id','severity','title','file','line','remediation'])).max(10),
sortBy: z.enum(['severity','date','file']),
includeSummary: z.boolean(),
});
// Pre-compiled template — attacker cannot inject template syntax
const EXPORT_TEMPLATE = Handlebars.compile(`
{{#each findings}}
{{this.id}}: {{this.severity}} — {{this.title}}
{{/each}}
`, { strict: true, allowProtoPropertiesByDefault: false });
async function runExportJob(jobId, userId) {
const raw = await redisClient.get(`template_config:${userId}`);
const parsed = JSON.parse(raw);
// Validate against strict schema — any unexpected key throws
const config = ExportConfigSchema.parse(parsed);
const auditData = await db.getAuditResults(jobId, {
columns: config.columns,
sortBy: config.sortBy,
});
const output = EXPORT_TEMPLATE({ findings: auditData });
await writeExportFile(jobId, output);
}
DESER19-002 (High): MongoDB CSS string passed to wkhtmltopdf via exec() enables SSRF and local file read
PDF report generation in MCP skill registries commonly allows per-user CSS customisation: custom fonts, colour schemes, and logo placement for white-labelled audit reports. When this CSS is stored in MongoDB as a raw CSS string and passed directly to wkhtmltopdf via a shell exec() call, two attack surfaces open simultaneously. First, the CSS itself can contain @import url("file:///etc/passwd") or @import url("http://169.254.169.254/latest/meta-data/") directives that wkhtmltopdf fetches synchronously during PDF rendering. The fetched content is embedded in the rendered PDF and returned to the requesting user, constituting an SSRF and local file read vulnerability. Second, if the CSS string is interpolated into the shell command without proper escaping, semicolons or backticks in the CSS value enable command injection.
The practical impact is file exfiltration of any file readable by the wkhtmltopdf process user: /etc/passwd, service account private keys, application configuration files with database credentials, and cloud instance metadata endpoint responses. CVSS 8.1 (AV:N/AC:L/PR:L/UI:N/S:C/C:H/I:N/A:N).
// VULNERABLE — DESER19-002: per-user CSS from MongoDB passed to wkhtmltopdf via exec()
// File: workers/pdf-worker.js
const { exec } = require('child_process');
async function generatePdfReport(jobId, userId) {
const userConfig = await mongo.collection('report_configs').findOne({ userId });
// VULNERABILITY 1: raw CSS string written to temp file — may contain @import url(file://...)
// VULNERABILITY 2: exec() with interpolated path — CSS may contain shell metacharacters
const cssPath = `/tmp/report_${jobId}.css`;
await fs.writeFile(cssPath, userConfig.customCss); // attacker controls content
exec(`wkhtmltopdf --user-style-sheet ${cssPath} /tmp/report_${jobId}.html /tmp/report_${jobId}.pdf`,
(err, stdout, stderr) => {
if (err) throw err;
uploadReport(jobId, `/tmp/report_${jobId}.pdf`);
}
);
}
Fix: Sanitize user-supplied CSS before writing it to any file used in document rendering. Strip @import rules entirely and block url() values whose scheme is not data: using a CSS parser (e.g., postcss with a custom plugin). Switch from exec() to execFile() with an argument array to eliminate shell interpretation. Run wkhtmltopdf in a sandboxed process with --no-background, --disable-external-links, and --disable-javascript flags. Consider whether user CSS customisation is necessary at all — a parameterised template system (colour, logo URL from an allowlist) is safer than raw CSS injection.
// FIXED — DESER19-002: CSS sanitized via postcss; execFile() with arg array; sandbox flags
// File: workers/pdf-worker.js
const { execFile } = require('child_process');
const postcss = require('postcss');
async function sanitizeCss(rawCss) {
const result = await postcss([
// Strip @import rules entirely
{ postcssPlugin: 'strip-import', AtRule: { import: (node) => node.remove() } },
// Strip url() values with non-data: schemes
{
postcssPlugin: 'strip-external-url',
Declaration(decl) {
if (/url\s*\(\s*(?!data:)[^)]+\)/i.test(decl.value)) {
decl.remove();
}
}
},
]).process(rawCss, { from: undefined });
return result.css;
}
async function generatePdfReport(jobId, userId) {
const userConfig = await mongo.collection('report_configs').findOne({ userId });
const safeCss = await sanitizeCss(userConfig.customCss || '');
const cssPath = `/tmp/report_${jobId}.css`;
const htmlPath = `/tmp/report_${jobId}.html`;
const pdfPath = `/tmp/report_${jobId}.pdf`;
await fs.writeFile(cssPath, safeCss);
// execFile: no shell; arg array prevents injection
await new Promise((resolve, reject) => {
execFile('wkhtmltopdf', [
'--no-background',
'--disable-external-links',
'--disable-javascript',
'--user-style-sheet', cssPath,
htmlPath,
pdfPath,
], (err) => err ? reject(err) : resolve());
});
await uploadReport(jobId, pdfPath);
}
DESER19-003 (Critical): node-serialize IIFE gadget in Redis XLSX column config achieves RCE
XLSX export jobs in MCP skill registries often cache per-user column layout configurations in Redis for performance, avoiding a database round-trip on every export invocation. When the caching layer uses node-serialize (npm package node-serialize) to serialise and deserialise these configs, any string value in the deserialised object that matches the IIFE gadget pattern is executed immediately at deserialise time — before any application logic can inspect or validate the value. This is a well-known but persistently rediscovered vulnerability: node-serialize's deserialize() function uses eval() internally, and the special prefix _$$ND_FUNC$$_ marks a value as an immediately invoked function expression.
An attacker who can write to the Redis key space (see DESER19-001 for the prerequisite vectors) constructs a JSON payload with the IIFE gadget as any string value. When the export worker calls deserialize() on the retrieved Redis value, the gadget executes in the worker process context — full RCE with no further conditions. CVSS 9.8 (AV:N/AC:L/PR:N/UI:N/S:C/C:H/I:H/A:H).
// VULNERABLE — DESER19-003: node-serialize used for Redis XLSX column config
// File: workers/xlsx-worker.js
const serialize = require('node-serialize');
async function getColumnConfig(userId) {
const cached = await redisClient.get(`xlsx_config:${userId}`);
if (!cached) return getDefaultColumnConfig(userId);
// VULNERABILITY: node-serialize.deserialize() uses eval() internally
// IIFE gadget: {"rce":"_$$ND_FUNC$$_function(){require('child_process').execSync('id')}()"}
// The gadget executes at deserialize() call time — before any validation
return serialize.deserialize(cached); // ← RCE if attacker controls Redis key
}
async function runXlsxExport(jobId, userId) {
const config = await getColumnConfig(userId);
const auditData = await db.getAuditResults(jobId);
await buildXlsx(jobId, auditData, config);
}
Fix: Replace node-serialize with JSON.parse() followed by a strict Zod schema validation. node-serialize provides no security benefit over plain JSON for structured config data — it exists solely to serialise function objects, which is precisely the attack vector. Never use node-serialize, serialize-javascript, or any library that calls eval() during deserialisation on data that originates from a cache layer, a database, or any user-influenced source. Validate the parsed JSON structure with a narrow schema that enumerates exactly the expected fields and value types.
// FIXED — DESER19-003: JSON.parse + Zod schema; no node-serialize
// File: workers/xlsx-worker.js
const { z } = require('zod');
const XlsxConfigSchema = z.object({
columns: z.array(z.enum(['id','title','severity','file','line','cwe','remediation'])).min(1).max(15),
includeLineNumbers: z.boolean().default(true),
groupBySeverity: z.boolean().default(false),
maxRows: z.number().int().min(1).max(10000).default(1000),
});
async function getColumnConfig(userId) {
const cached = await redisClient.get(`xlsx_config:${userId}`);
if (!cached) return XlsxConfigSchema.parse({}); // defaults
// JSON.parse: no eval; Zod: strict field validation; any unexpected key throws
const parsed = JSON.parse(cached);
return XlsxConfigSchema.parse(parsed);
}
async function runXlsxExport(jobId, userId) {
const config = await getColumnConfig(userId);
const auditData = await db.getAuditResults(jobId);
await buildXlsx(jobId, auditData, config);
}
DESER19-004 (High): MessagePack diff config prototype pollution grants persistent admin escalation
Report comparison pipelines in MCP skill registries compute diffs between audit runs, identifying newly introduced findings, resolved findings, and severity changes. Per-user diff configuration (which fields to compare, severity threshold for regression detection, ignored findings) is sometimes stored in MongoDB as MessagePack-encoded binary to reduce storage costs. When the diff worker decodes this binary using a MessagePack library with default options and directly Object.assigns the decoded result into the request context or a plain {} target, an attacker who stores a diff config containing a __proto__ key in their MongoDB document can pollute Object.prototype.
Once Object.prototype.adminOverride is set to true, every subsequent JavaScript object in the same process inherits this property. All permission checks of the form if (user.adminOverride || user.role === 'admin') return truthy for any user — including anonymous API requests that reach the same process. The pollution persists for the lifetime of the worker process and affects every concurrent request. This is a process-wide privilege escalation with no per-request scope. CVSS 8.8 (AV:N/AC:L/PR:L/UI:N/S:C/C:H/I:H/A:N).
// VULNERABLE — DESER19-004: MessagePack decoded diff config Object.assign'd into context
// File: workers/diff-worker.js
const msgpack = require('@msgpack/msgpack');
async function getDiffConfig(userId) {
const doc = await mongo.collection('diff_configs').findOne({ userId });
if (!doc) return {};
// VULNERABILITY: MessagePack decode returns plain object including __proto__ key
// Object.assign into {} does NOT use a null prototype — __proto__ assignment
// writes to Object.prototype, polluting the entire process
const decoded = msgpack.decode(doc.configBinary);
return Object.assign({}, decoded); // ← prototype pollution if decoded contains __proto__
}
async function runDiffJob(jobId, userId) {
const config = await getDiffConfig(userId);
// After pollution: config.adminOverride === true for ALL objects process-wide
const baseline = await db.getAuditRun(config.baselineRunId);
const current = await db.getAuditRun(config.currentRunId);
await computeDiff(jobId, baseline, current, config);
}
Fix: Use a null-prototype target object when decoding untrusted structured data: Object.assign(Object.create(null), decoded) prevents __proto__ from reaching Object.prototype. Additionally, validate the decoded object with a Zod schema using .strict() which rejects any keys outside the allowed schema — including __proto__, constructor, and prototype. Never directly Object.assign decoded cache or database values into request context objects. Use structuredClone() for deep copying decoded data to strip prototype chain references before use.
// FIXED — DESER19-004: null-prototype target; Zod strict schema; no Object.assign into context
// File: workers/diff-worker.js
const msgpack = require('@msgpack/msgpack');
const { z } = require('zod');
const DiffConfigSchema = z.object({
baselineRunId: z.string().uuid(),
currentRunId: z.string().uuid(),
compareFields: z.array(z.enum(['severity','title','file','cwe'])).default(['severity','title']),
regressionThreshold: z.enum(['any','high','critical']).default('any'),
ignoredFindingIds: z.array(z.string().uuid()).default([]),
}).strict(); // .strict() rejects __proto__, constructor, prototype keys
async function getDiffConfig(userId) {
const doc = await mongo.collection('diff_configs').findOne({ userId });
if (!doc) return DiffConfigSchema.parse({});
// null-prototype target prevents __proto__ pollution
const decoded = msgpack.decode(doc.configBinary, { useBigInt64: false });
const safe = Object.assign(Object.create(null), decoded);
// Zod strict parse: any unexpected key (including __proto__) throws ZodError
return DiffConfigSchema.parse(safe);
}
Detection with tree-sitter queries
The highest-value patterns in this advisory are eval() applied to cache-retrieved strings (DESER19-001), use of the node-serialize deserialize() function on untrusted data (DESER19-003), and Object.assign({}, decoded) without a null-prototype target after MessagePack or similar decoding (DESER19-004). The following tree-sitter queries identify these patterns in Node.js codebases.
Query 1 — eval() applied to Redis/cache get result. Matches call expressions where eval() is called with a value derived from a Redis get() or similar cache retrieval call — the DESER19-001 structural signature.
; tree-sitter query: eval() applied to cache-retrieved value (DESER19-001)
; Matches: eval(cachedString) where cachedString derives from redis.get / cache.get
(variable_declarator
name: (identifier) @cache-var
value: (await_expression
(call_expression
function: (member_expression
property: (property_identifier) @method
(#match? @method "^(get|hget|hgetall)$")
)
)
)
) @cache-read
(call_expression
function: (identifier) @fn (#eq? @fn "eval")
arguments: (arguments
(identifier) @arg (#eq? @arg @cache-var)
)
) @eval-of-cache
; Each @eval-of-cache: eval() called on a cache-retrieved value.
; Fix: JSON.parse + Zod schema; never eval cached strings.
Query 2 — node-serialize deserialize() call. Matches any call to serialize.deserialize() or nodeSerialize.deserialize() — the DESER19-003 pattern. Any match represents a potential RCE if the argument originates from an untrusted source.
; tree-sitter query: node-serialize deserialize() call (DESER19-003)
; Matches: serialize.deserialize(...) / nodeSerialize.deserialize(...)
(call_expression
function: (member_expression
object: (identifier) @obj
(#match? @obj "^(serialize|nodeSerialize|ns|node_serialize)$")
property: (property_identifier) @method (#eq? @method "deserialize")
)
arguments: (arguments (_) @input)
) @node-serialize-call
; Each @node-serialize-call: potential RCE if @input originates from cache or user data.
; Fix: replace with JSON.parse() + Zod schema; remove node-serialize dependency entirely.
Query 3 — Object.assign({}, decoded) after MessagePack or binary decode. Matches Object.assign calls where the first argument is an empty object literal and the second argument is a variable assigned from a decode() call — the DESER19-004 prototype pollution pattern.
; tree-sitter query: Object.assign({}, decoded) after decode() call (DESER19-004)
; Matches: Object.assign({}, msgpackDecoded) — missing null-prototype target
(variable_declarator
name: (identifier) @decoded-var
value: (call_expression
function: (member_expression
property: (property_identifier) @decode-fn (#match? @decode-fn "^(decode|unpack|deserialize)$")
)
)
) @decode-call
(call_expression
function: (member_expression
object: (identifier) @obj-class (#eq? @obj-class "Object")
property: (property_identifier) @method (#eq? @method "assign")
)
arguments: (arguments
(object) @empty-target
(identifier) @src (#eq? @src @decoded-var)
)
) @proto-pollution-risk
; Each @proto-pollution-risk: Object.assign into plain {} from decoded binary data.
; Fix: use Object.assign(Object.create(null), decoded) + Zod strict schema.
Summary
| ID | Severity | Vector | Root cause | Fix |
|---|---|---|---|---|
| DESER19-001 | Critical | Redis Handlebars template eval | eval() applied to attacker-controlled Redis string; RCE at render time |
JSON config + Zod schema; pre-compiled server-controlled template; no eval |
| DESER19-002 | High | MongoDB CSS to wkhtmltopdf exec | Raw CSS with @import url(file://) passed to wkhtmltopdf; file read via rendered PDF |
postcss strip-import + strip-external-url; execFile() with arg array; sandbox flags |
| DESER19-003 | Critical | Redis node-serialize IIFE gadget | node-serialize.deserialize() executes IIFE gadget in _$$ND_FUNC$$_ values via eval |
JSON.parse + Zod schema; remove node-serialize dependency entirely |
| DESER19-004 | High | MongoDB MessagePack prototype pollution | Object.assign({}, decoded) allows __proto__ key to pollute Object.prototype process-wide |
Null-prototype target Object.create(null); Zod .strict() schema rejects __proto__ |
Deserialization hardening checklist for MCP skill registry operators: (1) Grep all worker and job files for eval( — flag any that evaluate strings retrieved from Redis, MongoDB, or any external source. (2) Grep for require('node-serialize') and require('serialize-javascript') — these libraries call eval internally and should never be used on untrusted data. (3) Review all MessagePack / BSON / binary decode call sites — confirm Object.assign targets use Object.create(null). (4) Grep for exec( in worker files — confirm all use execFile() with arg arrays instead. (5) Confirm wkhtmltopdf invocations include --disable-external-links and --disable-javascript. (6) Validate all Redis and MongoDB-retrieved structured data with Zod or Joi schemas using .strict() to reject unexpected keys. (7) Confirm CSS stored in MongoDB passes through a postcss sanitizer stripping @import and non-data-scheme url() before use in document rendering. (8) Run the three tree-sitter detection queries above in CI on every push to catch regressions in the export and report generation pipelines. See also: SA-SKL-SSRF36 for SSRF via CSS @import in adjacent fetch contexts.
Scan your MCP skills for DESER19 and 2400+ other patterns
SkillAudit continuously audits MCP server and Claude skill codebases for deserialization vulnerabilities, injection flaws, CORS misconfigurations, SSRF, and privilege escalation. Get findings in minutes.
Get started at skillaudit.dev