SVG Upload Security Checklist: Six Checks, Fourteen Files
An SVG upload endpoint is usually defended by a list of string checks copied from a blog post: reject .php, look for <script, ban javascript:. I wrote those checks properly, ran them over fourteen files of 187 to 441 bytes — twelve hostile, two benign — and then placed every file that survived in eight different positions. The three text checks together reject 12 of the 14 files, but one hostile file passes all of them and one harmless file fails them, so the count is right and the answer is still wrong. The placement matters more than the checks: not one of the 14 executed or fetched anything inside an <img> tag or a CSS background, while 7 of 14 executed when the same bytes were opened as a document.
The useful version of this article is a checklist that says what each step is worth. Extension checks are worth nothing against an SVG; the first-bytes check catches the two files that are not really XML; the parser catches the one that will not parse; the text scan catches nine and misfires once; and rebuilding the tree from an allowlist is the only step that also removes what you did not think to ban. Every number below is from the same Chrome run, 157.0.8103.78, with a second origin logging requests so "it fetched something" is a fact rather than a guess.

The fourteen files
The corpus is deliberately boring: small files, each one attacking a different assumption. Sizes are the byte count on disk, which matters because a size cap is the one control that always works and never lies.
| File | Size | What it tries |
|---|---|---|
up-control | 187 B | A rectangle and a circle. The file that must never be rejected. |
up-script | 222 B | An inline <script> that sets a marker. |
up-onload | 215 B | onload on the root element, no script tag at all. |
up-entity | 323 B | An internal entity that hides javascript: in a link. |
up-nsprefix | 290 B | <html:script> with the XHTML namespace bound to a prefix. |
up-utf16 | 434 B | The onload file re-encoded as UTF-16 with a BOM. |
up-htmldoc | 253 B | A full HTML document with a script, named logo.svg. |
up-remote-img | 248 B | An <image> pointing at a second origin. |
up-import | 240 B | @import inside the file's own <style>. |
up-js-href | 287 B | A plain javascript: link around a rectangle. |
up-smil | 290 B | onbegin on an <animate>, zero interaction. |
up-dtd | 233 B | An external DTD reference in the doctype. |
up-laughs | 441 B | Six nested entities, five levels deep each. |
up-metadata | 260 B | The word <script> inside CDATA in <metadata>. Cannot run. |
Two of those files are benign on purpose. up-control is the file your checks must accept; up-metadata is the file your checks must also accept, and the text scan does not.
Check 1: the extension, and why it is worth nothing
Every file here is named .svg, so an extension allowlist accepts 14 of 14. That is not a criticism of the check — it belongs in the pipeline to stop .php and .exe — but it contributes zero information about an SVG, because the extension is chosen by the person uploading. The only version of this check that carries weight is the one that also decides how the file will be served, and that decision has to be made on bytes, not on the name.
The reason it matters is the same file in a different response. up-htmldoc is an HTML document. Served as image/svg+xml it produces 0×0 in an <img> tag and an error page when opened directly — the browser refuses it, which is the correct outcome. Served as text/html the same 253 bytes run their script. One header decides which of those two things happens, and no amount of filename checking will choose it for you.
Check 2: the first bytes
A byte-level allowlist is cheap and it catches the two files that are not XML at all: the UTF-16 copy (which starts FF FE) and the HTML document (which starts <!DOCTYPE html). Both are rejected before anything is parsed, which is also the cheapest place to reject them.
// The first bytes say what the file claims to be. UTF-16 and gzip do not start
// with '<', so a byte-level allowlist rejects them before anything parses.
function stageMagic(bytes) {
const b = new Uint8Array(bytes).slice(0, 200);
const head = new TextDecoder('latin1').decode(b).replace(/^\uFEFF|^\xFF\xFE|^\xFE\xFF/, '').trimStart();
return /^(<\?xml|<svg|<!--|<!DOCTYPE svg)/i.test(head)
? { ok: true }
: { ok: false, why: 'first bytes are not XML' };
}
The check is deliberately loose: it accepts a BOM-less XML declaration, a comment, and a doctype. It is not trying to validate the file — it is trying to avoid handing a decoder a stream it will misinterpret. The string scan further down the pipeline cannot see the UTF-16 file at all: measured on the raw bytes, that file contains a script and an onload, and the UTF-8 decode used by every scanner turns it into mojibake with no match. It still runs when opened as a document (all 4 placements that hand it to a parser in this run), which is the worst combination: invisible to the scanner, live in the browser.
Check 3: does it parse
One file fails here: the entity expansion. Chrome's XML parser refuses it outright, so the image never decodes and the <img> is 0×0. That is a real result — the browser is doing part of your job for you — but it is also the only file in the set where the parser is the thing that saves you. Every other payload is perfectly well-formed XML, which is worth saying out loud: "it parses" tells you nothing about whether it is safe, only whether the next check will get a chance to look at it.
Parsing also has to check the root. A file whose root element is <html> parses fine as XML; it just is not an SVG. Requiring localName === 'svg' in the SVG namespace rejects the HTML document even when the first-bytes check is skipped, and that is the version I would keep, because it is the property the rest of the pipeline assumes.
Check 4: the text scan, which gets one file wrong in each direction
Seven patterns, one pass over the raw text. This is the check that catches the most and the check that is easiest to trust too much.
const BAD_TEXT = [
[/<\s*script/i, 'script element'],
[/\son[a-z]+\s*=/i, 'event attribute'],
[/javascript\s*:/i, 'javascript: URL'],
[/@import/i, 'remote @import'],
[/\b(?:xlink:)?href\s*=\s*["']?\s*(?:https?:)?\/\//i, 'absolute URL'],
[/<!ENTITY/i, 'entity declaration'],
[/<!DOCTYPE[^>]*SYSTEM/i, 'external DTD'],
];
function stageScan(text) {
const hits = BAD_TEXT.filter(([re]) => re.test(text)).map(([, why]) => why);
return hits.length ? { ok: false, why: hits.join(', ') } : { ok: true };
}
It rejects 9 of the 14 files. Two of those deserve attention.
The miss. up-nsprefix contains <html:script xmlns:html="http://www.w3.org/1999/xhtml">. There is no <script substring, no on-attribute, no URL. Every one of the seven patterns passes it, and it executes in 3 of the three XML document placements — the same result as the namespace article found with a different toolchain. It is also worth noting where it does not run: not through server-side inlining into an HTML page, and not when the identical bytes are served as text/html, because the HTML parser treats a prefixed tag as an unknown element.
The false positive. up-metadata contains the literal text <script>window.x=1</script> inside a CDATA section in <metadata>. It cannot execute — CDATA is text, and <metadata> is not rendered — but the scan rejects it, because the scan reads bytes and a regex cannot tell text from markup. A user who uploads a design file exported from a tool that writes review notes into metadata gets a rejection they cannot act on.
That pair is the whole argument for keeping the scan as a triage step rather than as the gate. It is fast, it is cheap, and it is wrong in both directions on a corpus this small.
What the placement changes
Every file that survived the text checks — all fourteen, in fact, since placement was measured separately — was put in eight positions. The counts are the interesting part:
| Placement | Executed | Made a request | What that means for an upload feature |
|---|---|---|---|
<img src> | 0 / 14 | 0 / 14 | A preview thumbnail is inert. 12 of 14 still draw at 240×110. |
CSS background-image | 0 / 14 | 0 / 14 | Same as the image tag, and it is how most "icon picker" grids display files. |
innerHTML | 2 / 14 | 2 / 14 | Two files run with no interaction: the SMIL one and the javascript: link. |
| Server-side inline | 5 / 14 | 2 / 14 | Pasting the file into a template is a document, not an image. |
<object> | 7 / 14 | 2 / 14 | Seven files run, including the prefixed script the scanner missed. |
<iframe> | 5 / 14 | 2 / 14 | Identical to <object> in every cell. |
| Opened directly | 7 / 14 | 2 / 14 | What happens when the file URL is shared or previewed in a new tab. |
Same bytes as text/html | 6 / 14 | 2 / 14 | Six run; the entity payload stops working, the HTML document starts. |
Two details are easy to miss in that table. First, the two javascript: payloads do not set the marker variable at all — the returned string replaces the whole document, so the marker and the document it lived in are gone. Reading only window.__pwned scores them as inert. I had to re-run those two files measuring document length and text before the answer was right: both replaced the page in every placement they reached, and the entity version replaced it in the three XML placements while the HTML placements navigated to a 404 instead.
Second, innerHTML blocks <script> and onload but not onbegin: the SMIL payload runs there with no interaction, and so does the javascript: link. That is the same split the JavaScript article found, and it is the reason "we insert it with innerHTML" is not a mitigation.
Check 5: rebuild the tree from an allowlist
The last step does not ask what is bad. It asks what is allowed, copies that, and throws away the rest. Attributes are copied by hand; any href is re-checked for scheme; any url() pointing at another origin is dropped; style attributes are dropped; a <style> element keeps its rules but loses @import and remote url(); the doctype never reaches the output because the output is a new document.
function stageSanitise(doc) {
const SVG_NS = 'http://www.w3.org/2000/svg';
const OK_ELEMENTS = new Set(['svg', 'g', 'defs', 'symbol', 'use', 'path', 'rect', 'circle',
'ellipse', 'line', 'polyline', 'polygon', 'text', 'tspan', 'title', 'desc',
'linearGradient', 'radialGradient', 'stop', 'clipPath', 'mask', 'pattern',
'image', 'style']);
const OK_ATTRS = new Set(['xmlns', 'xmlns:xlink', 'viewBox', 'width', 'height', 'x', 'y',
'x1', 'y1', 'x2', 'y2', 'cx', 'cy', 'r', 'rx', 'ry', 'd', 'points', 'fill',
'stroke', 'stroke-width', 'stroke-linecap', 'stroke-linejoin', 'opacity',
'fill-opacity', 'stroke-opacity', 'transform', 'offset', 'stop-color', 'id',
'class', 'href', 'xlink:href', 'preserveAspectRatio', 'font-size', 'font-family',
'text-anchor', 'dominant-baseline', 'clip-path', 'mask', 'd', 'fx', 'fy',
'gradientUnits', 'gradientTransform', 'clipPathUnits', 'clip-rule', 'fill-rule']);
let removedElements = 0;
let removedAttributes = 0;
const out = document.implementation.createDocument(SVG_NS, 'svg', null);
const root = out.documentElement;
function safeUrl(v) {
const s = String(v).trim();
if (/^\s*(javascript|data|vbscript|file)\s*:/i.test(s)) return null;
if (/^(?:https?:)?\/\//i.test(s)) return null;
if (/^[a-z][a-z0-9+.-]*:/i.test(s) && !/^#/.test(s)) return null;
return s;
}
function copy(src, dst) {
for (const attr of [...src.attributes]) {
if (!OK_ATTRS.has(attr.name.toLowerCase()) && !OK_ATTRS.has(attr.name)) {
removedAttributes += 1;
continue;
}
let v = attr.value;
if (/href$/i.test(attr.name)) {
v = safeUrl(v);
if (v === null) { removedAttributes += 1; continue; }
}
// paint servers hide the same URL inside fill/stroke/filter/clip-path:
// fill="url(http://host/paint.svg#g)" is a fetch nobody calls an href.
if (/url\s*\(\s*['"]?(?:https?:)?\/\//i.test(v)) {
removedAttributes += 1;
continue;
}
if (/style$/i.test(attr.name)) { removedAttributes += 1; continue; }
try { dst.setAttribute(attr.name, v); } catch (e) { removedAttributes += 1; }
}
for (const child of [...src.children]) {
if (!OK_ELEMENTS.has(child.localName)) { removedElements += 1; continue; }
const el = out.createElementNS(SVG_NS, child.localName);
copy(child, el);
dst.appendChild(el);
}
if (src.localName === 'style') {
const css = (src.textContent || '').replace(/@import[^;]*;/gi, '')
.replace(/url\(\s*["']?(?:https?:)?\/\/[^)]*\)/gi, 'none');
dst.textContent = css;
} else if (['text', 'tspan', 'title', 'desc'].includes(src.localName)) {
dst.textContent = src.textContent;
}
}
copy(doc.documentElement, root);
const str = new XMLSerializer().serializeToString(out);
return { ok: true, svg: str, removedElements, removedAttributes,
bytes: new TextEncoder().encode(str).length };
}
Rebuilding the 11 files that got this far, then placing the results in five positions, gives 55 cells, 0 executions, 0 requests. The file the scan missed is caught here rather than by a rule: up-nsprefix loses one element (290 B → 189 B) because html:script is not on the list, and the rebuilt file scans clean.
Three caveats, all measured:
- The artwork goes with the anchor.
up-entityshrinks 323 B → 131 B and paints 0 pixels, because the rectangle lived inside the<a>that was dropped. A whitelist that does not know a common SVG element deletes the user's drawing along with the attack. Allowa, keephrefonly when it starts with#. - The CSS gap is real. The sanitizer above strips
@importwith a regex; a sanitizer that only walks attributes leaves two of the reference payloads in the companion article still talking to the network. Both passes are needed. - Rebuilding does not make the file trustworthy. It makes it boring: 182 bytes for the script payload, 189 for the prefixed one, 213 for the remote image, all of which draw the same 6,000 pixels.
The checklist, in the order that costs least
- Cap the size before reading the body. 256 KB is generous for an icon and stops the expansion payloads from ever reaching a parser.
- Decide the response header from the bytes, not the filename:
Content-Type: image/svg+xmlplusX-Content-Type-Options: nosniff. This alone turns the HTML document into a broken image. - Check the first bytes for XML; reject UTF-16 and anything that starts with
<!that is not an SVG doctype. - Parse, and require an SVG root in the SVG namespace. A file that does not parse is a file you never have to reason about.
- Run the text scan as triage, and log which pattern fired. Do not treat a hit as proof of danger, and do not treat a clean result as permission.
- Rebuild from an allowlist, including a pass over
<style>text, and serve the rebuilt file, never the uploaded one. - Show it in an
<img>tag or not at all. Every placement except<img>and CSS background is a document, and documents run code.
What this checklist does not do
It does not scan for known-bad files, and it does not stop a file that is valid, sanitized, and still malicious in a way no allowlist expresses — a legitimate filter that takes four seconds to render on a 4K canvas is a denial of service with no forbidden string in it. It does not cover the case where the uploaded file is served from the same origin as your application: the CSP article measured that a page policy does not reach inside an <object>, so a separate origin for user content is still the structural fix. And it does not replace the two things that catch what parsing cannot: a rendering budget, and a person looking at the thumbnail before it goes live.
The practical summary is one sentence: treat an upload as a document until you have rebuilt it into an image, and never let the two share an origin. The SVG Validator implements the parse and structural half of that on the client, and the SVG Editor is the quickest way to see what a file actually contains before you decide to keep it.
Try These Free Online Tools
No download required — convert, compress & optimize SVGs right in your browser



