Claude MCP skill insecure deserialization — audit report export and PDF generation pipeline
JSON.parse + eval() on templateFn field — attacker with Redis write access stores an evil compiled function achieving RCE at export timeBSON.deserialize() — BSON Code type at css field triggers eval() in wkhtmltopdf CSS injection path achieving arbitrary code execution__proto__ property into the MessagePack payload escalating bulk export to include all org reportsalg:none bypassing signature verification and accessing any user's exportDESER14-001 — Redis-cached Handlebars template function triggers RCE at export time
The audit report export pipeline caches compiled Handlebars templates in Redis to avoid recompiling on every export request. The cache stores the compiled template as a serialized string using templateFn.toString(), then restores it at request time with eval(cacheEntry.templateFn) after JSON.parse. An attacker with write access to Redis (via a Redis SSRF vulnerability, a misconfigured Redis instance binding to 0.0.0.0, or a Redis AUTH bypass) can overwrite the cached template with an arbitrary JavaScript function body. The next time any user triggers an export, the injected function executes in the context of the export worker process, achieving remote code execution with the worker's service account privileges.
// DESER14-001 — VULNERABLE
// Compiled Handlebars template stored as string in Redis, eval'd at export time
// Attacker with Redis write access injects arbitrary function body → RCE on export
const redis = require('redis');
const Handlebars = require('handlebars');
async function getExportTemplate(templateName) {
const cached = await redis.get(`template:${templateName}`);
if (cached) {
const entry = JSON.parse(cached);
// UNSAFE: eval() on Redis-sourced string — attacker controls templateFn value
const templateFn = eval(`(${entry.templateFn})`);
return templateFn;
}
const source = await db.templates.findByName(templateName);
const compiled = Handlebars.compile(source.body);
// Stores compiled function as string in Redis — this is the attack vector
await redis.set(`template:${templateName}`, JSON.stringify({ templateFn: compiled.toString() }), 'EX', 3600);
return compiled;
}
Never store or restore compiled code objects from external caches: Compiled JavaScript functions are code, not data. Storing fn.toString() and later eval()-ing the result trusts an external cache (Redis) as a source of executable code. Redis is not designed to be a trusted code store: it has no signing, no integrity guarantees, and is frequently accessible to any process on the same network. The fix is to pre-compile templates at application startup from version-controlled source files and keep the compiled objects only in process memory. The source of truth for template content is your git repository, not a cache.
// DESER14-001 — FIXED
// Templates pre-compiled at startup from version-controlled files
// Redis holds only plain rendered output cache — never compiled functions
const templateCache = new Map(); // in-process, not Redis
async function initTemplates() {
// Load and compile all templates at startup from version-controlled .hbs files
const templateFiles = await fs.readdir(path.join(__dirname, 'templates'));
for (const file of templateFiles) {
if (!file.endsWith('.hbs')) continue;
const name = file.replace('.hbs', '');
const source = await fs.readFile(path.join(__dirname, 'templates', file), 'utf8');
templateCache.set(name, Handlebars.compile(source)); // compiled object in process memory
}
}
function getExportTemplate(templateName) {
const fn = templateCache.get(templateName);
if (!fn) throw new Error(`unknown template: ${templateName}`);
return fn; // returns pre-compiled in-memory function — no Redis, no eval
}
// Redis is used only for caching rendered HTML strings, not compiled functions
async function renderExport(templateName, context) {
const cacheKey = `rendered:${templateName}:${hashContext(context)}`;
const cached = await redis.get(cacheKey);
if (cached) return cached; // plain string, safe to return
const html = getExportTemplate(templateName)(context);
await redis.set(cacheKey, html, 'EX', 300);
return html;
}
DESER14-002 — BSON Code type in Redis report config achieves CSS injection RCE via wkhtmltopdf
The PDF generation pipeline stores per-report configuration objects in Redis using BSON serialization. When the PDF worker fetches the config, it calls BSON.deserialize() without disabling the promoteValues or restricting BSON types. The css field of the config object is passed directly to wkhtmltopdf via --user-style-sheet. An attacker who stores a BSON document with the css field as a BSON Code type causes BSON.deserialize() to restore a JavaScript Code object. When this object is coerced to a string for the wkhtmltopdf command argument, its toString() method returns the code body. If wkhtmltopdf evaluates the CSS content (some versions allow JavaScript in CSS via -webkit- extensions), or if the CSS string is logged and later evaluated, the payload executes.
// DESER14-002 — VULNERABLE
// BSON.deserialize() restores Code type objects from Redis
// css field as BSON Code type → .toString() returns injected JS body
// Passed to wkhtmltopdf without type validation
const BSON = require('bson');
async function getPdfConfig(reportId) {
const raw = await redis.getBuffer(`pdf-config:${reportId}`);
// BSON.deserialize() with default options restores Code type
const config = BSON.deserialize(raw); // config.css may be a BSON Code object
return config;
}
async function generatePdf(reportId, htmlPath) {
const config = await getPdfConfig(reportId);
// config.css.toString() on a BSON Code object returns the code body
// If attacker stored Code('body { background: red; } ')
// the string injection reaches wkhtmltopdf CSS processing
const pdfPath = `/tmp/${reportId}.pdf`;
execSync(`wkhtmltopdf --user-style-sheet /dev/stdin ${htmlPath} ${pdfPath}`, {
input: config.css, // BSON Code object coerced to string
});
return pdfPath;
}
// DESER14-002 — FIXED
// Store PDF configs as plain JSON in Redis (not BSON)
// Validate css field with Zod schema — reject BSON Code type after deserialize
// Use execFile to avoid shell injection in the PDF command
const { z } = require('zod');
const PdfConfigSchema = z.object({
pageSize: z.enum(['A4', 'Letter']),
margin: z.string().regex(/^\d+(mm|cm|in|px)$/),
// css must be a plain string — BSON Code objects are not plain strings
css: z.string().max(4096),
includeTableOfContents: z.boolean(),
});
async function getPdfConfig(reportId) {
const raw = await redis.get(`pdf-config:${reportId}`); // plain string, not Buffer
const parsed = JSON.parse(raw); // JSON.parse cannot produce Code objects
return PdfConfigSchema.parse(parsed); // Zod validates shape and types
}
async function generatePdf(reportId, htmlPath) {
const config = await getPdfConfig(reportId);
const pdfPath = `/tmp/${crypto.randomUUID()}.pdf`;
const cssFile = `/tmp/${crypto.randomUUID()}.css`;
// Write CSS to a temp file with content-type enforced
await fs.writeFile(cssFile, config.css, { encoding: 'utf8' });
// execFile with arg array — no shell expansion
await execFileAsync('wkhtmltopdf', [
'--user-style-sheet', cssFile,
'--disable-javascript', // disable JS execution in wkhtmltopdf
htmlPath, pdfPath
]);
await fs.unlink(cssFile);
return pdfPath;
}
BSON Code type is a hidden deserialization gadget: Unlike JSON (which cannot represent executable code), BSON has a native Code type for storing JavaScript functions used by MongoDB's server-side evaluation. When you call BSON.deserialize() on attacker-controlled input, any Code value in the document becomes a JavaScript object whose toString() returns arbitrary code. If that object reaches a string interpolation, a template literal, an exec() call, or any other code execution path, you have RCE. The fix is to store configs as plain JSON (which cannot contain Code objects) and to validate the parsed result with a strict schema before use.
DESER14-003 — MessagePack bulk export recipient list enables prototype pollution escalation
The bulk export job reads the recipient list from an S3 object encoded as MessagePack. The job uses msgpack.decode() and passes the result directly to Object.assign({}, recipientList) before iterating over recipients to generate and dispatch reports. An attacker who can write to the S3 bucket (through a misconfigured bucket policy, a companion SSRF that can upload objects, or compromised S3 credentials) can craft a MessagePack payload containing {"__proto__": {"isOrgAdmin": true, "exportAllOrgReports": true}}. The Object.assign call merges the __proto__ key into Object.prototype, poisoning all subsequent authorization checks in the same process that test user.isOrgAdmin or options.exportAllOrgReports.
// DESER14-003 — VULNERABLE
// MessagePack decode of S3 object + Object.assign enables prototype pollution
// Attacker crafts payload: {"__proto__": {"isOrgAdmin": true, "exportAllOrgReports": true}}
const msgpack = require('@msgpack/msgpack');
async function processBulkExport(jobId) {
const s3Object = await s3.getObject({ Bucket: 'export-jobs', Key: `${jobId}/recipients.msgpack` }).promise();
const recipientList = msgpack.decode(s3Object.Body); // may contain __proto__ key
// Object.assign with decoded data — if recipientList contains __proto__,
// this pollutes Object.prototype for the entire process
const options = Object.assign({}, recipientList);
for (const recipient of options.recipients) {
// Authorization check reads from (now-polluted) prototype chain
if (!recipient.isOrgAdmin && !options.exportAllOrgReports) {
// isOrgAdmin may be true via prototype pollution even for non-admin users
await generateAndSendReport(recipient.userId, options);
}
}
}
// DESER14-003 — FIXED
// Validate decoded MessagePack with Zod schema to reject unexpected keys
// Use null-prototype target object to prevent prototype pollution
// Never use Object.assign with decoded external data
const { z } = require('zod');
const RecipientSchema = z.object({
userId: z.string().uuid(),
email: z.string().email(),
reportIds: z.array(z.string().uuid()),
// Explicitly enumerate allowed keys — no __proto__, isOrgAdmin, or exportAllOrgReports
});
const BulkExportJobSchema = z.object({
recipients: z.array(RecipientSchema).max(500),
format: z.enum(['pdf', 'json', 'csv']),
requestedBy: z.string().uuid(),
requestedAt: z.string().datetime(),
});
async function processBulkExport(jobId) {
const s3Object = await s3.getObject({ Bucket: 'export-jobs', Key: `${jobId}/recipients.msgpack` }).promise();
const decoded = msgpack.decode(s3Object.Body);
// Zod validation rejects any key not in the schema (including __proto__)
const job = BulkExportJobSchema.parse(decoded);
for (const recipient of job.recipients) {
// Authorization check reads from DB — not from decoded object
const user = await db.users.findById(recipient.userId, { select: ['id', 'orgId', 'role'] });
if (!user) continue;
await generateAndSendReport(user, job.format);
}
}
DESER14-004 — Export token alg:none bypass grants access to any user's export
Export download links use a short-lived JWT to authenticate the download request without requiring the user to be logged in (allowing direct download from email links). The JWT is verified with jsonwebtoken.verify(token, secret) without specifying an algorithms option. The jsonwebtoken library's default behavior when algorithms is not specified is to accept any algorithm, including alg: "none". An attacker who intercepts or generates an export link can craft a JWT with {"alg":"none"} in the header, any sub (user ID) in the payload, and an empty signature. The library accepts this token because no algorithm restriction is enforced, granting the attacker access to any user's audit report export.
// DESER14-004 — VULNERABLE
// jsonwebtoken.verify() without algorithms option — accepts alg:none
// Attacker crafts: header={"alg":"none"} + payload={"sub":"victim-user-id","exportId":"xyz"} + empty sig
const jwt = require('jsonwebtoken');
router.get('/export/:exportId/download', async (req, res) => {
const token = req.query.token;
if (!token) return res.status(401).end();
let decoded;
try {
// UNSAFE: no algorithms option — accepts alg:none tokens
decoded = jwt.verify(token, process.env.EXPORT_JWT_SECRET);
} catch {
return res.status(401).end();
}
const exportJob = await db.exports.findById(req.params.exportId);
// decoded.sub is attacker-controlled via alg:none — bypasses signature check
if (exportJob.userId !== decoded.sub) return res.status(403).end();
res.sendFile(exportJob.filePath);
});
// DESER14-004 — FIXED
// Explicit algorithms allowlist — rejects alg:none and unexpected algorithms
// Export token is single-use and stored in DB — prevents replay after download
router.get('/export/:exportId/download', async (req, res) => {
const token = req.query.token;
if (!token) return res.status(401).end();
let decoded;
try {
// Explicit algorithms allowlist — only HS256 accepted; alg:none is rejected
decoded = jwt.verify(token, process.env.EXPORT_JWT_SECRET, {
algorithms: ['HS256'], // reject any other algorithm including 'none'
issuer: 'skillaudit-export',
audience: 'download',
});
} catch {
return res.status(401).end();
}
// Verify token has not been used before (single-use download link)
const used = await redis.get(`export-token-used:${decoded.jti}`);
if (used) return res.status(410).json({ error: 'link already used' });
const exportJob = await db.exports.findOne({
where: { id: req.params.exportId, userId: decoded.sub }, // ownership in DB query
});
if (!exportJob) return res.status(404).end();
// Mark token as used before sending file — prevents race-condition replay
await redis.set(`export-token-used:${decoded.jti}`, '1', 'EX', 3600);
res.sendFile(exportJob.filePath);
});
Always pin JWT algorithm explicitly: The jsonwebtoken library accepts alg:none by default when no algorithms option is provided. This is a known, documented behaviour — the library does not treat it as a bug. Every jwt.verify() call must include { algorithms: ['HS256'] } (or your chosen algorithm). Never rely on the library's defaults for security-critical options. Additionally, combine with a unique jti (JWT ID) claim and a Redis seen-token set to prevent token replay — a valid download token should be consumable exactly once.
Hardening summary
| Finding | Pattern | Fix |
|---|---|---|
| DESER14-001 | Compiled Handlebars template function stored in Redis; eval() on restore triggers RCE | Pre-compile templates at startup from version-controlled files; Redis holds only rendered strings |
| DESER14-002 | BSON Code type in Redis config restored by BSON.deserialize(); CSS injection path to wkhtmltopdf | Store configs as JSON; Zod schema post-parse; execFile with arg array; --disable-javascript |
| DESER14-003 | MessagePack __proto__ key in S3 bulk export object; Object.assign pollutes prototype | Zod schema validation rejects unknown keys; null-prototype target; never Object.assign decoded data |
| DESER14-004 | jwt.verify() without algorithm pin accepts alg:none; any export accessible | algorithms: ['HS256'] in verify options; single-use jti checked in Redis |
Related: SA-SKL-DESER13, SA-SKL-DESER12. Run SkillAudit to surface all DESER14 patterns in your MCP skill registry.