Restrict JS in SVGs

Does anyone know of a way to prevent JS from running inside of an SVG

If you embed an SVG as an image, it's guaranteed to not run any contained JS:

<img src="https://example.com/dangerous.svg">

As a side effect this also prevents the SVG from loading any external resources. (See also: SVG as an Image)

If you feel fancy, an iframe sandbox would also prevent any script code from executing:

<iframe sandbox src="https://example.com/dangerous.svg"></iframe>

Note that if you're hosting user-provided SVGs, make sure users can't view them directly in the browser (by typing https://yoursite.example/user-images/dangerous.svg in the URL) since that would trigger the XSS anyway. Instead you need to serve untrusted files as attachments. (See also: Is it safe to store and replay user-provided mime types?)


Use an existing library / software tool that can parse and convert SVG, and that lets you remove scripts. One important rule in security is to avoid reinventing the wheel if you can avoid it.

Which library to use is out of scope for this site, but you could try looking (and possibly asking) on http://stackoverflow.com/, or on https://softwarerecs.stackexchange.com/ , particularly under the tag svg.

As usual, read (and heed) a site's question guidelines (e.g. What is required for a question to contain “enough information”?) before asking.

Tags:

Xss

Svg

Library