Remix.run Logo
The woes of sanitizing SVGs(muffin.ink)
133 points by varun_ch 5 hours ago | 52 comments
simonw 4 hours ago | parent | next [-]

I'm glad this article includes the only credible fix for the HTTP leak problems: CSP.

A useful thing I learned recently is that, while CSP headers are usually set using HTTP headers, you can also reliably set them directly in HTML - for example for HTML generated directly on a page where HTTP headers don't come into play:

  <iframe sandbox="allow-scripts" srcdoc="
    <meta http-equiv='Content-Security-Policy'
        content='default-src none; script-src unsafe-inline; style-src unsafe-inline;'>
    <!-- untrusted content here -->
  "></iframe>
It feels like this shouldn't work, because JavaScript in the untrusted content could use the DOM to delete or alter that meta tag... but it turns out all modern browsers specifically lock that down, treating those CSP rules as permanent as soon as that meta tag has loaded before any malicious code has the chance to subvert them.

I had Claude Code run some experiments to help demonstrate this a few weeks ago: https://github.com/simonw/research/tree/main/test-csp-iframe...

amluto 2 hours ago | parent | next [-]

An idea I’ve been kicking around (which isn’t quite applicable to this use case, I think) is to aggressively restrict the Sec-Fetch- headers on user content. If a server is willing to serve up an untrustworthy SVG, it could refuse to serve it at all unless Sec-Fetch-Dest has the correct value, and ‘document’ and ‘iframe’ would not be correct values. This would make it more difficult to fool a user or their browser by, for example, linking to an SVG file, or using a less-secure mechanism like embed to load it.

This should be in addition to heavily restricting CSP on user content. (Hmm, surely all images should be served with the CSP header set.)

bawolff an hour ago | parent [-]

You can bypass the sec-fetch headers via service workers i think.

A better approach here would be to just serve svg with Content-security-policy: script-src 'none'; sandbox

amluto an hour ago | parent [-]

But you can't make a link to https://your.domain/my_phishing_page.svg work as a phishing page using service workers unless you've pretty thoroughly pwned the site already. (And you can constrain what gets to run as a service worker using Sec-Fetch-Dest!)

I suppose an actual exception is Content-Disposition. If you want the user to save a file, you need to serve it with dest == document as far as I know.

rafram 4 hours ago | parent | prev | next [-]

And any additional CSP directives can only narrow what's allowed. Also works with headers plus <meta> - <meta>s can restrict the CSP even more than what the headers specified, but they can't widen it.

recursive 4 hours ago | parent | prev | next [-]

I did not know about `srcdoc`, but it looks like that's still vulnerable to injection by using a double quote and </iframe> to escape the sandbox. If this is constructed in a hygienic way using DOM manipulation, it seems like it could work, but it definitely seems possible to screw up.

rafram 3 hours ago | parent | next [-]

If you're constructing your unsandboxed parent document HTML using string concatenation, you might as well not use the sandboxed iframe at all. But presumably someone who bothers to sandbox untrusted content also knows about setAttribute(), or the srcdoc JS property.

simonw 3 hours ago | parent | prev | next [-]

You can entity-encode the content in the srcdoc= attribute to robustly solve that problem, or populate it via the DOM.

tracker1 4 hours ago | parent | prev [-]

s/"/&quot;/g

tracker1 4 hours ago | parent | prev [-]

Nice, favorited... thinking this could be useful for an email reader to support css, but not scripts.

andybak 5 hours ago | parent | prev | next [-]

My first thought is "support a tiny subset of svg that probably still covers 90% of real-world use cases".

I do feel that's there's two distinct types of svg - "bunch of paths with fills" and "clever dangerous stuff" where most real SVGs are of the former type.

Fully expect this to be shot down by someone that's thought about this problem for longer than the 120 seconds I just spent. :)

pupppet 37 minutes ago | parent | next [-]

This is what happens when there isn't an adult in the room to reign things in, you get project overreach. SVGs should never have supported scripting. You want scripting in SVGs, fine, make it a different file format.

I can't imagine the cumulative number of man hours wasted on this problem when the vast majority of users were just looking for a way to make their logos look sharp.

afavour 4 hours ago | parent | prev | next [-]

I think you're right but the lack of industry standard for this kind of thing kills it. People want to be able to take the output of whatever tool they use that exports SVG and put it in a browser. Which isn't an unfair request. But you wouldn't have a guarantee it wouldn't filter out the tool using some obscure SVG functionality.

I'd love to see an agreed standard like OpenGL vs OpenGL ES for SVG. SVG-ES. Everyone agrees on the static, non-scripted elements that should work.

varun_ch 4 hours ago | parent [-]

The way linked SVGs render from within img tags is basically perfect for SVG images (which as I understand is not standardized but is largely the same across browsers). External resources and scripting are blocked while still rendering nearly all SVGs correctly. And of course, any CSS is scoped to the SVG.

If someone formalizes this as a new format, please give it a new name! tvg tiny vector graphics? savg safe vector graphics?

And keep the scope as simple as possible so it actually ships! Don’t try implementing a binary format or something.

hackeman300 4 hours ago | parent | next [-]

Someone did this already and did call it tinyVG! https://tinyvg.tech/

sbrother 3 hours ago | parent | prev | next [-]

Maybe I'm missing something as I am not a frontend developer, but when you embed SVGs in an img tag as part of a Phoenix LiveView or even just a static component, you no longer get the ability to dynamically change paths/fills/colors with events coming from the server. Even if it's as simple as having a shape that you want to fill with a brand/highlight color, which at least for me is a common use case.

ambicapter 4 hours ago | parent | prev [-]

.rvg, Restricted Vector Graphics?

bawolff an hour ago | parent | prev | next [-]

> My first thought is "support a tiny subset of svg that probably still covers 90% of real-world use cases".

It sounds like the linked post was about someone using a blacklist instead of a whitelist. It doesnt matter how tiny your subset is if you allow through stuff you don't recognize.

For the most part svg is safe. The dangerous parts are pretty obvious - script tag, image tag, feImage tag, attributes starting with on, embedding html in <foreignObject>, DTD tricks, namespace tricks, CSS that loads external stuff (keep in mind also presentational attributes. Its not just style attribute/tag).

The rest of it is pretty safe.

Avamander an hour ago | parent | prev | next [-]

There's the SVG Tiny profile that some implementations use, like BIMI/VMCs.

hackeman300 4 hours ago | parent | prev | next [-]

Seems like someone already implemented your idea. https://tinyvg.tech/

varun_ch 5 hours ago | parent | prev | next [-]

I wonder if it would be best if this was at the browser level as some sort of new format. Otherwise surely it would be really slow/cumbersome to deal with these in ‘user space’

whycome 4 hours ago | parent | prev | next [-]

It always seems like any animated svg loses all of the animation after sanitizing

bawolff an hour ago | parent [-]

There are 3 different methods of animating svgs so it probably depends.

RobotToaster 3 hours ago | parent | prev | next [-]

You'd lose a lot of useful features, like SMIL animation.

andybak 3 hours ago | parent [-]

But you'd gain adoption. A fair trade.

harperlee 5 hours ago | parent | prev | next [-]

Fwiw I just thought the same, parse (don’t validate) the bits you like and recreate / reject the input.

LorenPechtel 4 hours ago | parent | prev | next [-]

Yeah, I think that's the real answer.

Look at what Microsoft did with Excel--the dangerous stuff is behind a switch.

Thus, solution:

Add two bits to the tag.

SVG1 does not execute any sort of script.

SVG2 does not follow links.

SVG3 is actually SVG1 + SVG2 as these are bit flags, not numbers.

Additional bits are reserved for future use if any other issues are found.

The only real safety is in the engine, not by any sanitizer.

bawolff an hour ago | parent | next [-]

Which is essentially already how it works. See https://svgwg.org/specs/integration/#secure-animated-mode

cachius 2 hours ago | parent | prev [-]

What switch?

duped 4 hours ago | parent | prev [-]

So if you are building something where you control every SVG ever produced and rendered then this is totally reasonable.

If you ever need to interface with other tools that generate SVG you now need to have a way of essentially transpiling SVG from the wild into your tamed SVGs. Oftentimes this is done by hand, by a software developer and designer (sometimes the same person).

And this is for basic functionality that your designers expect and have trivial controls for in their vector editors, like "add a drop shadow."

The article goes into some issues with sanitization itself, and except for <script> these are a bunch of reasonable things that someone might expect to work or not have issues with. Sandboxing rendering isn't an unreasonable approach if you're not writing the parser and renderer yourself.

evilpie 3 hours ago | parent | prev | next [-]

The HTML Sanitizer API has a subset of SVG that is allowed by the default configuration. It won't help you with sanitizing CSS at all however, style is simply not allowed by default.

https://developer.mozilla.org/en-US/docs/Web/API/HTML_Saniti...

https://developer.mozilla.org/en-US/docs/Web/API/HTML_Saniti...

philo23 4 hours ago | parent | prev | next [-]

It'd be nice if there was a sandbox attribute you could add to inline <svg> tags, like the <iframe sandbox> attribute that'd let you opt out of all the potentially "dynamic" stuff inside of an SVG like scripts and event handlers, or even just literally sandbox the entire thing from accessing the "parent" HTML page's context/cookies/etc just like an iframe.

I'm sure it'd just open up a whole other can of worms though... not to mention having to wait for browsers to actually support it.

The real solution here is definitely CSP + basic sanitisation though.

chocmake 3 hours ago | parent | next [-]

Most of the aspects the author was critiquing are actually just regular CSS features, they simply don't want any external requests. Effectively they want inlined SVGs to be treated like how the browsers treat IMG-embedded SVGs (no scripting or external requests loaded).

Sanitization-wise it's already possible to strip scripting from SVGs and anything else you want, it's just that a library like DOMPurify to avoid ballooning in size doesn't include say a preset to handle the extra parsing necessary to make them behave like browsers treat IMG embeds, so it's up to devs to add their own.

But yeah, a world where a simple attribute to achieve the same effect as an IMG embed but for inlined SVGs would be nice.

simonw 3 hours ago | parent | prev | next [-]

Thankfully if you have CSP you don't need even basic sanitization, which is useful because most of the problems in this article are demonstrations of how simple sanitization isn't simple at all.

bawolff an hour ago | parent | prev | next [-]

I dont see how that could work, as an <svg> tag in html is not a document boundry. How can you prevent it from accessing a parent doc when its not a separate document.

There is iframe srcdoc if you want to do this.

philo23 an hour ago | parent [-]

> How can you prevent it from accessing a parent doc when its not a separate document.

By turning it into a document boundary when you use the sandbox attribute, kinda similar to loading an svg file inside of an <img> tag.

and yeah you could get 90% of the way there with an iframe srcdoc, but I was imagining some kind of cross between an <iframe> sandboxed into its own origin, and an <img> where it still has its own intrinsic size.

but it was mainly just a throw away thought, I've not really thought it through much deeper than that.

somat 15 minutes ago | parent | prev [-]

img src="file.svg"

does that work for you?

spankalee 5 hours ago | parent | prev | next [-]

This is, by the way, why Google Slides doesn't have SVG support even though there's a nearly 15 year old ticket requesting the feature.

ikkun 4 hours ago | parent | prev | next [-]

I do wish tinyVG or similar would take off, but I don't see that ever actually happening. the only thing I think it's missing is animation support, which is pretty niche but not as niche as <script> tags.

https://tinyvg.tech/

bawolff 2 hours ago | parent | prev | next [-]

These aren't really SVG specific issues. They are all pretty standard XSS that apply to html and are very well known vectors.

Like this post didn't even mention presentational attributes, like how cursor attribute can contain a url that gets loaded. Or any of the other tricky parts of svg sanitization, like using dtd to bypass things.

Springtime 4 hours ago | parent | prev | next [-]

It seems the reason they're inlined in the page at all is to measure things briefly like bounding boxes (not sure the full extent as it didn't cover that), before subsequent removal. I'm not familiar with Scratch and its use of user-submitted SVGs but I'd be curious to read more about what they're doing that required it be inlined specifically.

(This isn't a comment on the challenges in proper sanitization fwiw, as I've needed to do various of the same things myself)

jancsika 3 hours ago | parent | prev | next [-]

For the "<script>" stuff: regardless of how the thing is spelled or otherwise obscured, the HTML5 parser eventually knows when it's gotten hold of a script tag. Oops, we got one in a NOSCRIPTTAG context. Let's poop out.

Tag names, attributes, attribute values, event callback default-cancelers... so many ways to declare that this node and its children shouldn't parse/evaluate scripts.

As Jay-Z said: "I've got 99 solutions, fixing a problem ain't one"

kevinmgranger 3 hours ago | parent | prev | next [-]

> This was fixed by using a regular expression to remove script tags.

The infamous you can't parse (X)HTML with regex¹ meme is from 2009, yet this fix was done in 2019. I guess the SO answer never mentioned SVG.

1: https://stackoverflow.com/revisions/1732454/1

shaguoer 4 hours ago | parent | prev | next [-]

This is exactly the kind of content I come to HN for.

etchalon 4 hours ago | parent | prev | next [-]

I don't understand why it wasn't immediately understood that SVG is as dangerous as HTML.

It is not, and never was, an image format. It's a markup language.

recursive 11 minutes ago | parent [-]

A markup language can be an image format. The "G" is for "Graphics" after all.

Theodores 2 hours ago | parent | prev | next [-]

Maybe we need a dumbed down version 3 of SVG where the browser knows it is not to do anything that requires fetching a URL, to make the image as harmless as a JPG.

This version 3 could have the version number changed to 2 in order to do cool SVG things, so full-fat SVG as version 2 is now. But you could just flip to 2 to a 3 on upload, so any embedded URLs are harmless.

This could be useful for the creator too, as it is helpful to have layers of source images in bitmap format to work with, and you can easily export such things accidentally.

NooneAtAll3 3 hours ago | parent | prev | next [-]

wait... scratch is just a browser?

Devasta 2 hours ago | parent | prev | next [-]

> In 2019, a few months after the initial release of Scratch 3, Scratch discovered that SVGs can contain <script> tags that Scratch would cause to be executed when the SVG loads. This is known as an XSS.

> Example from Scratch's test suite:

  <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
    "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
  <svg version="1.1" xmlns="http://www.w3.org/2000/svg">
    <circle cx="250" cy="250" r="50" fill="red" />
    <script type="text/javascript"><![CDATA[
        alert('from the svg!')
    ]]></script>
  </svg>


Is this really an issue? This is the method that the chrome teams polyfill to replace XSLT suggests you do. https://github.com/mfreed7/xslt_polyfill/tree/main#usage
esafak 4 hours ago | parent | prev | next [-]

Is there a browser-friendly vector alternative?

simonw 3 hours ago | parent [-]

SVG in an <img> tag can't execute scripts.

SpyCoder77 4 hours ago | parent | prev [-]

I did not expect to see GarboMuffin.