DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 968,547 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Cover image for XSS: Problem with letting users upload SVG
TusharShahi
TusharShahi

Posted on

XSS: Problem with letting users upload SVG

Allowing user to upload stuff is cool. One customer facing app I was working on, allowed users to upload files.

These are some of the file extensions we allowed:

const acceptedFileTypes = [
  '.jpg',
  '.jpeg',
  '.png',
  '.svg'];
Enter fullscreen mode Exit fullscreen mode

We later found how that could be a problem with regards to security for our users.

This is how a simple svg file looks like:

A black circle

I just got it online after a simple google search. Here is the link.

This is how it looks like when you download and open the same file in VS code:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg xmlns="http://www.w3.org/2000/svg" width="500" height="500">
<circle cx="250" cy="250" r="210" fill="#fff" stroke="#000" stroke-width="8"/>
</svg>
Enter fullscreen mode Exit fullscreen mode

This looks like XML code. SVGs can have animations and for that they allow scripting. So the above file could be easily changed to something like:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg xmlns="http://www.w3.org/2000/svg" width="500" height="500">
<circle cx="250" cy="250" r="210" fill="#fff" stroke="#000" stroke-width="8"/>
<script type="text/javascript">
//Harmful JS here
</script>
</svg>
Enter fullscreen mode Exit fullscreen mode

Here is a simple demo. Try to open the image in new tab and you will see javascript running.

Imagine the possibilities of allowing hackers to run any script on another user's device.

This is an XSS attack, a stored one. This did not directly affect the app we made, but definitely could affect our users. Anyone opening the image in a new link could be vulnerable.

That is why it is always recommended to to only allow svgs from trusted sources.

Top comments (0)

In defense of the modern web

I expect I'll annoy everyone with this post: the anti-JavaScript crusaders, justly aghast at how much of the stuff we slather onto modern websites; the people arguing the web is a broken platform for interactive applications anyway and we should start over;

React users; the old guard with their artisanal JS and hand authored HTML; and Tom MacWright, someone I've admired from afar since I first became aware of his work on Mapbox many years ago. But I guess that's the price of having opinions.