AppSec & Frontend Security

How to Handle Untrusted SVG Uploads Safely

BT
BrivTools Application Security Team
9 min read
Diagram of checks for untrusted SVG files
Executive Summary: SVGs Are Code, Not Passive Pixels

Unlike raster formats (JPEG, PNG, WebP) which store compressed numeric pixel matrices, Scalable Vector Graphics (SVG) is a dialect of Extensible Markup Language (XML) defined by the W3C. An SVG document possesses a full Document Object Model (DOM), supports CSS styling, and can embed interactive scripting environments.

The Critical Developer Blind Spot:Developers treat user-uploaded avatar SVGs like normal images, failing to realize they just allowed users to upload arbitrary executable HTML and JavaScript to their origin.
The Exploitation Consequence:Full session cookie theft, administrative account takeover, unauthorized API mutations, and persistent malware injection via Stored Cross-Site Scripting (XSS).

1. How the browser context changes SVG risk

An SVG is XML. Browsers restrict active features in an image context, while a standalone SVG document or embedded document has a different processing context. Keep untrusted SVGs out of the application DOM and review how previews, downloads and direct navigation are delivered.

2. The Dangerous Myth: SVGO Is an Optimizer, NOT a Security Sanitizer

One of the most dangerous fallacies in modern web engineering is using svgo (SVG Optimizer) as an input validation or sanitization filter.

The Critical Distinction

SVGO’s Objective: Eliminate redundant precision digits, combine paths, strip editor metadata (like Adobe Illustrator tags), and reduce file size.

Security Sanitizer Objective: Parse the full XML syntax tree, remove dangerous DOM nodes, strip JavaScript attributes, validate safe URI schemes, and eliminate mutation XSS (mXSS) anomalies.

Use an optimizer for file size and a maintained, SVG-aware sanitizer for the allowlist. Review both in the actual delivery context.

3. Set the boundaries for uploaded graphics

Review XML parsing, external references, embedded markup and active features when choosing a policy. Enforce input and resource limits and allow only the features your product needs. Isolate any rendering process from private files, credentials and the network.

4. Serve user assets from an isolated origin

Use a separate origin that carries no application credentials for untrusted files. Keep restrictive response policies appropriate to the intended context and verify the final response at the CDN. If a file needs only to be downloaded, set a download disposition. Treat these controls as layers alongside validation and sanitization.

5. Production Sanitization Architecture: DOMPurify & Defanging

If your application must display inline SVG markup (to allow dynamic CSS hover states or theming), you must run user-provided vector markup through an audited AST-based sanitizer like DOMPurify with explicit SVG configurations:

import DOMPurify from 'isomorphic-dompurify';

export function sanitizeUserSvg(rawSvgString: string): string {
  // 1. Enforce strict SVG-only profile
  const clean = DOMPurify.sanitize(rawSvgString, {
    USE_PROFILES: { svg: true, svgFilters: true },
    ADD_TAGS: ['svg', 'path', 'circle', 'rect', 'line', 'polyline', 'polygon', 'g'],
    FORBID_TAGS: [
      'script',
      'foreignObject',
      'iframe',
      'object',
      'embed',
      'animate',
      'set',
      'use', // Mitigates external resource inclusion attacks
    ],
    FORBID_ATTR: [
      'onload',
      'onerror',
      'onclick',
      'onmouseover',
      'href',
      'xlink:href',
    ],
  });

  return clean;
}

Choose a policy based on what the upload is for

If customers only need a logo thumbnail, reject SVG or produce a new raster derivative in an isolated worker with input and resource limits. If vectors are required, review an SVG-specific allowlist and serve the sanitized result from a separate asset origin without application credentials. Validate the actual delivery context: a file embedded as an image and the same URL opened as its own document have different security properties.

OWASP’s file upload guidance. WebP vs. AVIF vs. SVG: Which Image Format Should You Use?.

6. Verify the upload and delivery controls

Check the original upload, generated derivatives and asset URLs in staging. Confirm that rejected file types are unavailable, previews show only the approved derivative, and direct navigation never opens an unsanitized original on the application origin. Repeat after changes to the sanitizer, CDN or image renderer.

7. Frequently Asked Technical Questions

Can an SVG file execute JavaScript when embedded via an <img> tag?+
Direct Answer Summary:No. When an SVG is rendered via a standard HTML <img> tag (e.g., <img src='avatar.svg' />), browsers enforce a strict security boundary that completely disables JavaScript execution, external network requests, and CSS resource loading.

However, the vulnerability arises when the user clicks 'Open image in new tab' (navigating to the raw SVG URL), or when the application serves the SVG with 'Content-Type: image/svg+xml' without CSP headers, or renders it inline via dangerouslySetInnerHTML or React SVG loaders. In those contexts, JavaScript executes with full origin privileges.

Why can't I just use SVGO to sanitize user-uploaded SVGs?+
Direct Answer Summary:SVGO is an optimization tool designed to reduce file size by stripping metadata and minifying path coordinates. It is NOT a security sanitizer and does not guarantee removal of obfuscated XSS payloads.

SVGO can easily be configured to leave scripts or interactive elements intact. True security sanitization requires an AST-aware sanitizer like DOMPurify configured with strict SVG profiles.

How should I serve an SVG download?+
Direct Answer Summary:Use the correct media type for approved SVG content and a download disposition when the file is intended to be downloaded.

Serve user files from an isolated asset origin and verify the effective response headers at the CDN.

How should an SVG upload pipeline parse XML?+
Direct Answer Summary:Disable external entity and DTD resolution for untrusted XML where your parser supports it.

Use a maintained parser with restrictive defaults, keep the renderer isolated and review resource limits before accepting untrusted files.

Interactive Client-Side Tool

Optimize & Clean SVG Vectors Client-Side

Strip editor bloat, minify path coordinates, and inspect vector markup securely in browser memory without sending private files to any server.

Profit Margin Toggles
S-Curve Ramp Delays
100% Client-Side Privacy
Open Free SVG OptimizerNo signup required • Instant calculations

Learn the workflow