Updated November 18, 2026  ·  11 min read  ·  SVGVector

SVG <use> Element Security: A Reference Is Not a Sandbox

The folk remedy for a suspicious SVG is to wrap the dangerous part in a definition and point at it with <use>: the reasoning being that a referenced element is somehow inert, that whatever sits inside a <symbol> only becomes real when the browser decides to paint it, and that a reference to another file cannot reach the network. I built thirteen files to test that, between 167 and 12,417 bytes, and put each one through seven placements. Nothing ran inside an <img> tag — 0 of 13, and 0 requests — but a script parked inside a <symbol> ran in 3 of the 13 files once the file was served as a document, and a click handler defined inside that same symbol still fired. The reference did not hide anything. It only rearranged the markup.

There is one place where <use> genuinely narrows the attack surface, and it is worth separating from the rest: an href is only followed when it points at a fragment in the same document. Everything else — another origin, a relative path, a data: URI, javascript: — is refused. Chrome does not even send the request. That is a real restriction, and it is the only one you get.

Matrix of thirteen SVG files that hide their payloads behind use references, against seven placements. The img tag column is empty for every file. The inline, object, iframe and direct columns show filled dots for a script inside a symbol and for an image onerror inside a symbol, ringed dots for a click handler, and crosses for the external reference that Chrome attempts and then drops. Two files paint nothing at all: the data URI reference and the one with the broken xlink prefix.
Each cell is a run in Chrome 157.0.8103.78: load, wait, read a marker, click the centre of the drawing, read again. The last column serves the identical bytes as text/html so the HTML parser gets a turn. "Painted" counts non-white pixels when the file is opened directly as image/svg+xml.

What a <use> element is allowed to point at

Start with the part that works. A <use> whose href is a bare fragment such as #icon is resolved inside the same document, and the target is rendered as if it were written there. In my control file that paints 10,000 pixels in every placement that can paint anything, including an <img> tag.

Now the part that people assume works and does not. A <use> pointing at http://127.0.0.1:8972/ext/target.svg#a, on a second origin that logs every request it receives, produced a request event in all six document placements and exactly zero entries in the server log. The console explains it: Unsafe attempt to load URL http://127.0.0.1:8972/ext/target.svg from frame with URL .... Chrome attempted the load and dropped it before it left the browser. A same-origin relative reference (/ext/target.svg#a) was not even attempted: no request event, no log entry, and the drawing kept only the background rectangle.

The same rule covers the other two schemes that people worry about. A data: reference painted 0 pixels — not a partial draw, not a broken-image icon, nothing — and a javascript: URL produced the same "unsafe attempt" console line and no execution. So the practical answer for this element is unusually tidy:

href valueResolved?Leaves the browser?Executes?
#local-idyesnoonly what the target already contains
https://other-origin/x.svg#anono (attempted, then blocked)no
/same-origin/x.svg#anono (not attempted)no
data:image/svg+xml,...#anonono
javascript:...nonono

That table is the reason a sprite file is safe to keep, and the reason "just move it into a symbol" is not a mitigation: the restriction is about where the reference points, not about what the referenced markup is allowed to do once it is in the document.

A script inside a symbol still runs

Here is the measurement that contradicts the folklore. Take a file with a <symbol id="s"> containing a <script> and a rectangle, then one <use href="#s">. Served as a document — inline HTML, <object>, <iframe>, direct navigation, and the same bytes as text/html — the script ran in every one of them. In an <img> tag it did not, for the same reason no script runs there: the image loader decodes the file to pixels and never gives it a document.

The reason is mundane once you see it. The <script> inside a <symbol> is a child of the document. It is not rendered, but it is parsed, and SVG scripts execute when parsed. The <use> is irrelevant to whether that script runs; it is relevant only to whether the rectangle is painted. Anything else in this article follows from that distinction: a definition is not a container, it is just markup that happens not to be drawn.

The same holds for event attributes. A rectangle inside the symbol carrying onclick fired in 5 of the six document placements when I clicked the centre of the instantiated drawing, and it also fired after innerHTML insertion. An <image> inside the symbol pointing at a missing file fired onerror in the same set, after making one real request to the second origin. Removing the handler while leaving the <image> in place removed the execution but not the request — the fetch still happened when I re-ran the sanitised file.

Where innerHTML is different, and by how much

Inserting the same thirteen files with innerHTML gives 2 executions out of 13, against 3 when the file is served as a document. The gap is exactly the <script> payload: markup assigned to innerHTML does not execute script elements, which is well known, but it does keep event attributes working — the onclick and onerror payloads both ran.

So the ranking across placements, from the same table, is: <img> at 0, innerHTML at 2, and every document placement at 3. If your sanitised markup is being inserted into a live page rather than loaded as a file, you have removed one payload class out of three. That is worth knowing before you write "we strip script tags, so we are fine" in a security review.

The cost of a reference, measured

Two numbers make the "references are cheap recursion bombs" theory testable. A file with 400 <use> elements painting a grid of 11-pixel squares came to 12,417 bytes and painted 22,880 non-white pixels; its median DOMContentLoaded — measured over seven runs of the document itself — was 6 ms, against 5 ms for a file with a single reference. Width is essentially free.

Depth is not. I built chains where each level forwards to the level below, one reference per level, and measured 272 ms at 200 levels against 5 ms for the flat control — roughly 54× the parse-to-DOM time for a 7,197-byte file. The browser does not refuse the chain: 39 levels and 200 levels both paint the full 10,000 pixels. It just takes longer. A few hundred bytes can therefore buy a few hundred milliseconds of main-thread work, which is worth having on the record even though it is nowhere near the amplification numbers you get from entity expansion.

Two more properties worth knowing before you write a rule: a self-referencing group (<g id="a">...<use href="#a"/></g>) painted normally instead of hanging, and a <style> element inside a referenced symbol did not leak. My probe paragraph kept its original colour rgb(17, 24, 39) in both the inline and the innerHTML placement, so styles inside a symbol stay inside the symbol even though scripts do not.

Scanning and cleaning a file that uses references

The scanner below answers one question per reference: where does it point, and what does the target contain? It resolves local references, walks the chain, and reports seven kinds of finding — javascript, data-uri, external, dangling, cycle, script-in-target and handler-in-target — plus the same checks for executable content that is not behind a reference at all. Run over the 17 files in this set that were not doing anything wrong, it produced zero findings, so it is not one of those scanners that flags every file.

function scanUse(root) {
  const SVG = 'http://www.w3.org/2000/svg';
  const XLINK = 'http://www.w3.org/1999/xlink';
  const findings = [];
  const byId = new Map();
  for (const el of root.querySelectorAll('[id]')) byId.set(el.id, el);
  const hrefOf = (u) => u.getAttribute('href') || u.getAttributeNS(XLINK, 'href') || '';
  const uses = [...root.querySelectorAll('use')].filter((u) => u.namespaceURI === SVG);
  const targets = new Set();

  uses.forEach((use, index) => {
    const owner = use.getAttribute('id') || ('use#' + (index + 1));
    const href = hrefOf(use);
    if (/^\s*javascript:/i.test(href)) findings.push({ id: owner, kind: 'javascript', detail: href.slice(0, 40) });
    else if (/^\s*data:/i.test(href)) findings.push({ id: owner, kind: 'data-uri', detail: href.slice(0, 24) });
    else if (/^[a-z][a-z0-9+.-]*:/i.test(href) || href.startsWith('//')) findings.push({ id: owner, kind: 'external', detail: href });
    else if (!href.startsWith('#')) findings.push({ id: owner, kind: 'empty-or-relative', detail: href });
    else if (!byId.has(href.slice(1))) findings.push({ id: owner, kind: 'dangling', detail: href });
    else targets.add(href.slice(1));
  });

  // 顺着引用往里走:环、深度、以及「目标自己又引了外网」
  uses.forEach((use, index) => {
    const owner = use.getAttribute('id') || ('use#' + (index + 1));
    const href = hrefOf(use);
    if (!href.startsWith('#')) return;
    const walk = (id, stack) => {
      const el = byId.get(id);
      if (!el) return;
      for (const nested of el.querySelectorAll('use')) {
        const h = hrefOf(nested);
        if (!h.startsWith('#')) {
          findings.push({ id: owner, kind: 'nested-ref', detail: h.slice(0, 40) });
        } else if (stack.indexOf(h.slice(1)) !== -1) {
          findings.push({ id: owner, kind: 'cycle', detail: h });
        } else if (stack.length >= 200) {
          findings.push({ id: owner, kind: 'too-deep', detail: stack.length + 1 + ' levels' });
        } else {
          walk(h.slice(1), stack.concat(h.slice(1)));
        }
      }
    };
    walk(href.slice(1), [href.slice(1)]);
  });

  // 可执行内容:在被引用的目标里就是「藏起来的」,在别处就是「明摆着的」
  const inTarget = (el) => {
    let p = el.parentElement;
    while (p) { if (p.id && targets.has(p.id)) return true; p = p.parentElement; }
    return false;
  };
  for (const el of root.querySelectorAll('*')) {
    const where = inTarget(el) ? '-in-target' : '';
    if (el.namespaceURI === SVG && (el.localName === 'script' || el.localName === 'handler')) {
      findings.push({ id: el.id || '(no id)', kind: 'script' + where, detail: el.localName });
    }
    for (const attr of el.attributes) {
      if (/^on/i.test(attr.name)) findings.push({ id: el.id || '(no id)', kind: 'handler' + where, detail: el.localName + '@' + attr.name });
    }
  }

  const out = [];
  const seen = new Set();
  for (const f of findings) {
    const key = f.id + '|' + f.kind + '|' + f.detail;
    if (seen.has(key)) continue;
    seen.add(key);
    out.push(f);
  }
  return out;
}

The cleaner acts on those findings, and it has to touch the target as well as the reference: removing a <use> while leaving the symbol's script in place would leave the script running exactly as before. After cleaning, 37 of the files were served again in three document placements — 111 cells — and produced 0 executions. The benign control kept its 10,000 pixels and the 400-reference file kept its 22,880.

function sanitizeUse(root, options) {
  const SVG = 'http://www.w3.org/2000/svg';
  const XLINK = 'http://www.w3.org/1999/xlink';
  const opts = Object.assign({ maxLevels: 200, dropStyle: true }, options || {});
  const log = [];
  const byId = new Map();
  for (const el of root.querySelectorAll('[id]')) byId.set(el.id, el);
  const hrefOf = (u) => u.getAttribute('href') || u.getAttributeNS(XLINK, 'href') || '';

  // 1) 只留下指向本文件某个 id 的引用
  for (const use of [...root.querySelectorAll('use')]) {
    const href = hrefOf(use);
    if (!href.startsWith('#') || !byId.has(href.slice(1))) {
      log.push('removed use -> ' + (href || '(no href)'));
      use.remove();
    }
  }

  // 2) 目标里的脚本 / 事件属性 / 样式一起清掉:只删 use 不清目标等于没清
  for (const el of [root, ...root.querySelectorAll('*')]) {
    if (el.namespaceURI !== SVG) continue;
    if (el.localName === 'script' || el.localName === 'handler') {
      log.push('removed ' + el.localName + ' in #' + (el.parentElement && el.parentElement.id || '?'));
      el.remove();
      continue;
    }
    for (const attr of [...el.attributes]) {
      if (/^on/i.test(attr.name)) { log.push('stripped ' + el.localName + '@' + attr.name); el.removeAttribute(attr.name); }
    }
    if (opts.dropStyle && el.localName === 'style') { log.push('removed style'); el.remove(); }
  }

  // 3) 环与深度:去掉会绕回来的那一层
  const walk = (el, stack) => {
    if (!el) return;
    for (const nested of [...el.querySelectorAll('use')]) {
      if (!nested.isConnected) continue;
      const href = hrefOf(nested);
      if (!href.startsWith('#')) continue;
      const id = href.slice(1);
      if (stack.indexOf(id) !== -1 || stack.length >= opts.maxLevels) {
        log.push((stack.indexOf(id) !== -1 ? 'cycle' : 'depth') + ' use -> #' + id);
        nested.remove();
      } else walk(byId.get(id), stack.concat(id));
    }
  };
  for (const use of [...root.querySelectorAll('use')]) {
    const href = hrefOf(use);
    if (href.startsWith('#')) walk(byId.get(href.slice(1)), [href.slice(1)]);
  }
  return log;
}

A checklist for files you did not write

None of this replaces the earlier finding that the transport decides most of the outcome. If you want the wider picture, the JavaScript matrix covers twelve other payloads across the same six placements, and the malware overview puts the whole set in one place. What <use> adds to that picture is a specific false sense of safety: the markup looks inert because it is not on screen. It is parsed, it is in the document, and if the file ever gets served as a document, it runs.

Try These Free Online Tools

No download required — convert, compress & optimize SVGs right in your browser

Inspect

SVG Editor

Open the tree and see what the reference actually points at.

Open editor
Validate

SVG Validator

A file that does not parse is a file your scanner never read.

Open validator
Flatten

SVG to PNG

Pixels cannot run anything. This is the one-step mitigation.

Convert to PNG
Optimise

SVG Optimiser

Strip dead definitions once the file is known to be clean.

Open optimiser
Encode

SVG to Data URI

Inline the drawing instead of pasting its markup into the page.

Encode it
Inspect

SVG to Code

Read the markup as HTML or JSX before it goes near a page.

Convert to code