Treat an .svg file uploaded by an untrusted user with the exact same caution you would give an uploaded .html file. Because Scalable Vector Graphics is an XML application integrated directly into browser DOM engines, a valid SVG file can embed <script> blocks, SMIL animation event triggers, arbitrary HTML via <foreignObject>, and external entity definitions.
Allowing users to upload custom organization logos, profile badges, or diagram attachments without a layered defense creates an immediate Stored Cross-Site Scripting (XSS) vector.
1. Five Sneaky SVG XSS Payloads Beyond <script>
Naive regex filters that only strip <script> tags fail immediately against real-world SVG exploit vectors:
<!-- Vector 1: Root onload event handler -->
<svg xmlns="http://www.w3.org/2000/svg" onload="alert(document.domain)" />
<!-- Vector 2: SMIL animation timing event (fires without user interaction!) -->
<svg xmlns="http://www.w3.org/2000/svg">
<rect width="100" height="100">
<set attributeName="fill" to="red" begin="0s" onbegin="alert(origin)" />
</rect>
</svg>
<!-- Vector 3: Embedded HTML via <foreignObject> -->
<svg xmlns="http://www.w3.org/2000/svg">
<foreignObject width="200" height="200">
<body xmlns="http://www.w3.org/1999/xhtml">
<img src="x" onerror="alert('XSS via foreignObject')" />
</body>
</foreignObject>
</svg>
2. Why <img src="untrusted.svg"> Alone Is Not Enough
Browsers intentionally sandbox <img src="/uploads/logo.svg">: scripts do not run, <foreignObject> external loads are blocked, and interactive links are inert while rendered inside <img>.
The vulnerability triggers on direct navigation: an attacker uploads invoice-diagram.svg to https://app.example.com/uploads/invoice-diagram.svg and sends that direct link to an authenticated admin. When the browser navigates directly to an image/svg+xml URL on app.example.com, it renders as a top-level document on the same origin—granting full read/write access to localStorage, session APIs, and non-HttpOnly cookies!
3. Defense-in-Depth Checklist for Production SVG Handling
| Defense Layer | Implementation | What It Blocks |
|---|---|---|
| 1. Whitelist AST Sanitization | DOMPurify.sanitize(raw, { USE_PROFILES: { svg: true, svgFilters: true } }) |
Strips <script>, on*, <foreignObject>, javascript: hrefs |
| 2. Isolated Asset Hostname | Serve user uploads from uploads-usercontent.com (separate eTLD+1) |
Isolates cookies, localStorage, and origin permissions |
| 3. Strict SVG HTTP Headers | Content-Security-Policy: default-src 'none'; style-src 'unsafe-inline'; sandbox |
Blocks script execution even on direct top-level URL navigation |
| 4. Server XML Parser Hardening | Disable DTDs / external entities (resolve_entities = False) in libxml2/ImageMagick |
Prevents Server-Side Request Forgery (SSRF) and XML External Entity (XXE) |
Apache / .htaccess Header Lock for Uploaded SVG Directories
If your server stores static SVG uploads inside /uploads/, lock down execution at the HTTP header layer:
<IfModule mod_headers.c>
<FilesMatch "\.svgz?$">
Header set Content-Security-Policy "default-src 'none'; img-src data:; style-src 'unsafe-inline'; sandbox"
Header set X-Content-Type-Options "nosniff"
</FilesMatch>
</IfModule>
Client-Side Sanitization with DOMPurify Before Inline Rendering
Whenever rendering dynamic SVG strings in React, Vue, or vanilla JS, parse through an allowlist sanitizer rather than regexes:
import DOMPurify from 'dompurify';
export function sanitizeInlineSvg(dirtySvgString) {
return DOMPurify.sanitize(dirtySvgString, {
USE_PROFILES: { svg: true, svgFilters: true },
ADD_TAGS: ['use'],
FORBID_TAGS: ['script', 'foreignObject', 'iframe', 'object', 'embed'],
FORBID_ATTR: ['onload', 'onerror', 'onbegin', 'onend', 'onclick', 'onmouseover'],
});
}
For developer-authored icons in your own repo, run exports through our local SVG Code Optimizer and pair with our Production SVGO Pipeline Guide.
4. Server-Side Rasterizer Risks: XML External Entities (XXE) & "Billion Laughs" DoS
Client-side browser XSS isn't the only threat surface carried by untrusted .svg uploads. If your Node.js, PHP, Python, or Go backend converts user-uploaded SVGs into PNG/WebP thumbnails using outdated bindings to libxml2, librsvg, ImageMagick, or Inkscape, two server-side XML attacks apply:
- XML External Entity (XXE) Local File Disclosure & SSRF: Legacy XML parsers that expand
<!ENTITY>declarations inside<!DOCTYPE svg [...]>can be tricked into reading/etc/passwdor hitting AWS/GCP cloud metadata endpoints (http://169.254.169.254/latest/meta-data/) and rendering the stolen text directly onto the output PNG thumbnail! - Quadratic / Exponential Entity Expansion ("Billion Laughs" Memory Bomb): A 900-byte SVG defining ten nested XML entities (
&lol9;->10 × &lol8;) expands to 1 to 3 GB of RAM during XML parsing, crashing worker processes instantly.
<!-- Malicious DOCTYPE block that MUST be rejected before any XML/SVG parse -->
<!DOCTYPE svg [
<!ENTITY xxe SYSTEM "file:///etc/hostname">
]>
<svg xmlns="http://www.w3.org/2000/svg" width="400" height="100">
<text x="10" y="50">&xxe;</text>
</svg>
Rejecting <!DOCTYPE & <!ENTITY at the Ingestion Gate
Valid web SVG icons and illustrations have zero legitimate need for <!DOCTYPE> entity declarations, <script>, or <foreignObject>. Enforce a strict fast pre-check before passing any user buffer to an image library (sharp uses modern librsvg with network/entity loading disabled, which is far safer than legacy CLI ImageMagick delegates):
// Fast ingestion gate before DOMPurify or Sharp rasterization
export function assertSafeSvgEnvelope(rawBuffer) {
if (rawBuffer.byteLength > 512 * 1024) {
throw new Error('SVG exceeds 512 KB upload limit');
}
const head = rawBuffer.toString('utf8');
const forbiddenPatterns = [
/<!ENTITY/i,
/<!DOCTYPE[^>]*\[/i,
/<script[\s>]/i,
/<foreignObject[\s>]/i,
/javascript\s*:/i,
/data\s*:\s*text\/html/i,
];
for (const re of forbiddenPatterns) {
if (re.test(head)) {
throw new Error(`Rejected unsafe SVG token matching ${re}`);
}
}
return head;
}
5. Safe Storage & Delivery Headers Summary
When storing sanitized SVGs that users might open directly via URL:
- Force Attachment Download if Direct Viewing Isn't Needed: Content-Disposition: attachment; filename="graphic.svg" prevents browsers from rendering the XML inline as an active document.
- Prevent MIME Sniffing: Always send X-Content-Type-Options: nosniff (already configured in GraphicsGrotto's production .htaccess) so an attacker cannot disguise an SVG/HTML polyglot inside a .txt or .jpg extension.
- Strip External <image href="https://tracker.evil/pixel.png"> Beacons: Even without script execution, external <image> or @import URLs inside SVGs leak viewer IP addresses and user-agents unless stripped during sanitization!
Test clean XML output locally anytime with our client-side SVG Code Optimizer & Minifier.