SVG XXE and Entity Attacks: Inert in a Browser, Live on a Server
Yes, an SVG can carry an XXE payload, and the file only needs to be 286 bytes. But the payload does nothing in a browser: measured on seven files across six ways of putting an SVG on a page, Chrome 157 ran zero code and made zero requests, in every combination. The same seven files through a general-purpose XML parser on a server read 213 bytes of /etc/hosts into the drawing, made 1 request to another origin, injected 59 bytes of remote markup, and expanded a 390-byte file into 100,004 characters. Same bytes. Different parser. That is the whole finding.
Which makes this article a specification of where the danger sits: not in the image tag, not in the viewer, but in whatever code on your side opens the file to look at it.

image/svg+xml and a beacon counted on a second origin. The bottom half is the same seven files through CPython 3.13's expat parser with a naive entity resolver.What a DTD adds to a drawing
Everything on this page starts with two lines that no design tool writes and no image needs:
<!DOCTYPE svg [
<!ENTITY xxe SYSTEM "file:///etc/hosts">
]>
That block is a DTD — a document type definition — and it exists in XML so a parser can define named chunks of content and point at external files. In an SVG it buys an attacker four things at once:
| What the entity does | Payload | Who is exposed |
|---|---|---|
| Reads a local file into the document | xxe-file, 286 B | server parser only |
| Fetches a URL from wherever the parser runs | xxe-http, 297 B | server parser only |
| Splices remote markup into the drawing | xxe-markup, 218 B | server parser only |
| Expands into megabytes | xxe-laughs, 390 B | both, in different ways |
Stores a string — including a javascript: scheme | xxe-scheme, 365 B | any XML parser, then a click |
The last row is the one that keeps the browser interesting, and I will come back to it. The first three are pure server-side problems, because they need a parser that is allowed to resolve an identifier against the filesystem or the network — which is exactly what a library like Java's DocumentBuilder, PHP's DOMDocument or Python's expat will happily do when nobody told it otherwise.
The browser half: seven files, six modes, nothing
7 files, all with a DOCTYPE, between 218 and 390 bytes, embedded six ways: inside an <img>, injected with innerHTML, written into the page by the server, in an <object>, in an <iframe>, and opened as its own document. Code ran in 0 of the img cases. It also ran in 0 of the innerHTML cases and 0 of the server-inline ones. Requests to the second origin: 0 and 0 across all seven files and all six modes.
The reason is not caution on Chrome's part, it is a design decision with a visible side effect: the XML parser reads the DTD, then resolves an external entity to an empty string. The file still renders — xxe-file comes back at 200×60 with the frame and the fill intact — but the <text> that asked for &xxe; is empty. Measured text content of that file: 0 characters after trimming. So a file built to steal a secret from the server becomes a blank label in the browser, quietly, with no error in the console.
Two of the seven do not survive even that gracefully. xxe-param, which declares a parameter entity that pulls a remote DTD, and xxe-laughs, the nested expansion, both fail to parse: the image reports naturalWidth 0, and drawing the same bytes into a canvas throws an EncodingError. In the four modes where the file is parsed as a document, that is the entire outcome: a broken image. In the two HTML modes the markup is inserted and simply paints nothing useful.
I would not read that as protection. It means the payload is unresolved, not neutralised, and it says nothing about what the next parser in the chain will do with the same bytes.
The exception inside the browser: internal entities still work
External entities are dead in Chrome. Internal ones are not, and the difference matters because a filter that looks for the string SYSTEM will miss them.
xxe-attr is a 265-byte file whose only trick is <!ENTITY c "#e11d48"> followed by fill="&c;". It renders, and the fill comes out as exactly #e11d48: 23,906 pixels of that colour, no approximation. Internal entities are resolved by the XML parser, so any attribute value can be assembled from pieces at parse time — which is a way to write a file whose meaning is not visible in the attribute you grep for.
xxe-scheme goes further. It declares <!ENTITY j "javascript:window.__pwned=1"> and puts &j; in an xlink:href. Measured across the six modes, clicking the link ran the code in 1 of the four modes where the file is parsed as XML — <object>, <iframe> and opened directly — and in neither HTML mode. That is the mirror image of the case-sensitivity finding in the malware article: there, the HTML parser was the dangerous one because it lowercased OnLoad into onload; here the HTML parser is the safe one, because it throws the DTD away, leaves the literal text &j; in the attribute, and javascript: never appears.
So the browser answer is: an entity can define data, and that data can be a scheme, and a scheme needs a click. Nothing needs a request, and nothing needs an external entity.
The server half: the same seven files through expat
Now the same bytes, parsed where uploads actually land. The code below is the shape that ships: a handler that receives a SYSTEM identifier from the document and resolves it.
def resolve(sysid): # the vulnerable shape
if sysid.startswith("file://"):
return open(sysid[7:], "rb").read().decode("utf-8", "replace")
if sysid.startswith(("http://", "https://")):
return urllib.request.urlopen(sysid, timeout=3).read().decode("utf-8", "replace")
return None
parser = expat.ParserCreate()
parser.ExternalEntityRefHandler = lambda ctx, base, sid, pub: feed(parser, ctx, resolve(sid))
Measured against the seven files, lazily — one file per parse, the beacon log emptied in between:
| File | Resolves the SYSTEM id | No handler |
|---|---|---|
xxe-file | 213 B of /etc/hosts, 220 chars glued in | empty string, no read |
xxe-http | 1 request, 26 B returned | empty string, 0 requests |
xxe-markup | 59 B of remote SVG injected | empty string, 0 requests |
xxe-param | 7 chars — parameter entities need SetParamEntityParsing(ALWAYS) | same |
xxe-laughs | 100,004 chars in 5.9 ms | 100,004 chars — expansion is not opt-in |
Two details in that table are worth their own sentence. The remote fetch in row two took 28.4 ms and returned 26 bytes from a host the file chose — that is server-side request forgery with a 297-byte file as the vehicle. And the expansion in the last row happens whether or not there is a resolver at all, because internal entities are expanded by the parser itself; the 100,004 characters are produced at exactly the same size with no handler attached.
Also note what the third column says: a parser with no entity resolver behaves like Chrome. That is the default in some stacks and not in others, which is why "it looked fine on my machine" is not evidence of anything.
A hardened parser configuration stops three of seven
The usual recommendation is to configure the parser: turn off parameter entities, refuse to resolve external identifiers. It is good advice and it is not sufficient, and the gap is measurable. With SetParamEntityParsing(NEVER) and a handler that returns 0 for every identifier:
- 3 of the seven now raise instead of parsing — precisely the three that need an external file, with
error in processing external entity reference. - The other four parse normally. The drawing arrives; the entity is empty.
- The 100,004-character expansion still happens. Same number as before, because expansion is internal to the parser and no resolver setting touches it.
So configuration converts "the file works and does something" into "the file works and does nothing", which is genuinely better, while leaving the parser doing the most expensive thing it can be asked to do with a small file. The only setting that covers all seven is refusing the file.
The check that covers all seven: refuse the DTD before anything parses it
A DTD in an SVG has no legitimate use in a pipeline that accepts drawings from other people. No exporter writes one, no editor reads one, and the whole attack surface of this article is the four characters <!DOCTYPE. So the first check is a string test, before the file reaches any parser:
function scanEntities(src) {
const s = String(src);
const found = [];
if (/<!DOCTYPE/i.test(s)) found.push('DOCTYPE');
if (/<!ENTITY\s+%/i.test(s)) found.push('parameter entity');
else if (/<!ENTITY/i.test(s)) found.push('general entity');
if (/\bSYSTEM\s*["']/i.test(s)) found.push('SYSTEM identifier');
if (/\bPUBLIC\s*["']/i.test(s)) found.push('PUBLIC identifier');
const stripped = s.replace(/&(?:amp|lt|gt|quot|apos|#\d+|#x[0-9a-fA-F]+);/g, '');
const refs = stripped.match(/&[A-Za-z_][\w.-]*;/g);
if (refs) found.push('entity reference ' + [...new Set(refs)].join(' '));
return found;
}
Run against the seven files it returns a non-empty list for all seven; run against a normal 890-byte Figma export it returns []. It does not try to be clever about nested cases, and that is the point: the file either declares a DTD or it does not.
Refusing at that boundary is what the allowlist in the next snippet does, and it is the only check in this article that scores 7 of 7 without depending on parser flags:
const SVGNS_L = "http://www.w3.org/2000/svg";
const ALLOWED = new Set(('svg g defs symbol use path rect circle ellipse line polyline polygon text tspan ' +
'textPath title desc style linearGradient radialGradient stop clipPath mask pattern image ' +
'marker filter feGaussianBlur feOffset feBlend feColorMatrix feMerge feMergeNode ' +
'feComponentTransfer feFuncA feFuncR feFuncG feFuncB feFlood feComposite feDropShadow').split(' '));
const URL_ATTRS = new Set(['href', 'xlink:href', 'src', 'srcset']);
function safeParseSVG(src) {
// A DOCTYPE is the only reason an SVG needs an entity, and no export tool emits one.
if (/<!DOCTYPE/i.test(src) || /<!ENTITY/i.test(src)) {
return { error: 'declares a DTD', elements: 0, attributes: 0, removed: [], svg: '' };
}
const doc = new DOMParser().parseFromString(String(src), 'image/svg+xml');
if (doc.querySelector('parsererror')) return { error: 'not XML', elements: 0, attributes: 0, removed: [], svg: '' };
const removed = [];
let elements = 0;
let attributes = 0;
const walk = (node) => {
for (const child of [...node.children]) {
const name = child.localName;
if (!ALLOWED.has(name)) { // foreignObject, script, iframe, a … land here
removed.push(name);
elements++;
child.remove();
continue;
}
for (const attr of [...child.attributes]) {
const n = attr.name.toLowerCase();
const v = attr.value.trim();
const isUrl = URL_ATTRS.has(n) || n.endsWith(':href');
if (n.startsWith('on') || (isUrl && !/^#|^data:image\/|^[a-z0-9._/-]+$/i.test(v))) {
child.removeAttribute(attr.name);
attributes++;
}
}
walk(child);
}
};
walk(doc.documentElement);
return {
error: null, elements, attributes, removed: [...new Set(removed)],
svg: new XMLSerializer().serializeToString(doc.documentElement),
};
}
Called on the seven entity files, safeParseSVG returns declares a DTD and no output — the drawing is not repaired, it is refused. That is a policy decision worth stating out loud, because the alternative (strip the DTD and hope the rest still means something) produces a file whose fill may have been an entity, as in xxe-attr.
On a real 890-byte icon the same function is uneventful: 0 elements removed, 0 attributes removed, 889 bytes out against 890 in, a difference of one byte from serialisation. So the cost of the rule is paid by the files that break it, not by the normal ones.
If you accept SVG uploads, this is the list
Ordered by how much each step covers, measured on the seven files above:
- Reject
<!DOCTYPEat the edge, before any parser sees the bytes. Covers 7 of 7. - Configure the parser anyway. Java:
FEATURE_SECURE_PROCESSINGplusdisallow-doctype-decl; libxml2:XML_PARSE_NONETand noNOENT; Python:SetParamEntityParsing(NEVER)plus a handler that returns 0. Covers 3 of 7 on its own. - Cap the output size — count characters while parsing and abort past a few hundred kilobytes. The expansion is 100,004 characters from 390 bytes; the next nesting level is 1,000,040.
- Never parse as a privileged process. An entity resolver in a worker with no filesystem access and no route to internal hosts turns rows two and three of the table into errors instead of leaks.
- Serve what you store back as
text/plainor withContent-Disposition: attachmentif the user asked to download, per the header matrix in the malware article. - Let a browser do the rendering you need, since the browser's parser is the one measured here as inert. Convert to PNG or display inside
<img>rather than opening the file as a document.
For the file you are about to open by hand, the quick version is the same as ever: read the first ten lines in a text editor. A <!DOCTYPE in an icon is a decision someone made, and it was not a designer.
Frequently asked questions
What is XXE in an SVG file?
An XML external entity: a DOCTYPE block that declares a named entity pointing at a file or URL, which the parser then resolves while reading the document. In an SVG it can pull a local file or a remote URL into the drawing. Measured on seven files: Chrome resolved every external entity to an empty string and made no requests, while a server-side expat parser with a resolver read 213 bytes of /etc/hosts and made 1 request to a host the file named.
Can a browser be attacked by an SVG with a DOCTYPE?
Not by the external entities measured here: 0 code execution and 0 requests across 7 files and 6 embedding modes. Internal entities do still resolve, which is enough to assemble attribute values at parse time — a colour comes out exact, and a javascript: scheme stored in an entity runs on click in <object>, <iframe> and direct mode, though not when the markup is inlined into HTML.
Does removing the DOCTYPE make the file safe?
It removes this whole class of problem, which is why refusing the file is cleaner than editing it. Editing is fine when the DTD only defines a colour or a string — replace the reference with the literal value. It is not fine when the drawing depends on remote content, because then the picture you keep is not the picture the sender had.
Why does the same file behave differently on my server?
Because two parsers were asked two different questions. Chrome's XML parser reads a DTD and declines to resolve external identifiers; many server-side libraries resolve them by default, since that was the point of the feature. The file did not change. The code that opened it did — which is also why the fix belongs to the server, not to the image.
Related SVG Workflows
If you are about to accept a file from someone else, these are the next steps.
- Can SVG files contain malware — the 12-payload matrix this article builds on, including the header and CSP results.
- Sanitize SVG with an allowlist — the tree walk behind
safeParseSVG, and what it costs on a real icon. - SVG Validator — reports structural problems, and fails loudly on files that were assembled to look broken.
- SVG Editor — open the tree, see the
defsand the text nodes the DTD was filling, delete what you did not author. - SVG Optimiser — the size pass that runs after the security pass, not instead of it.
- SVG to PNG — flatten a file to pixels so nothing in it is ever parsed as a document again.
- Figma SVG clean code — what a normal export contains, so a doctored one stands out.
Inspect the file before a parser does
Open the markup, find the declaration that should not be there, and re-export clean. Everything runs in the browser with no upload.
Try These Free Online Tools
No download required — convert, compress & optimize SVGs right in your browser
SVG Editor
Open the tree, find the doctype or the entity reference, and delete the node you did not draw.
Open editorSVG Validator
Report the structural damage that makes a doctored file look merely broken.
Open validatorSVG to PNG
Flatten the drawing so nothing downstream ever parses it as an XML document.
Convert to PNGSVG Optimiser
Strip comments and dead definitions once the file is known to be clean.
Open optimiserSVG to Data URI
Inline an icon as an encoded URI instead of pasting raw markup into a page.
Encode itSVG Crop / Flip / Rotate
Fix the viewBox on a file that came back from someone else.
Adjust the box



