We're planning on allowing users to upload SVG files and icons. The problem is that SVG files can contain JavaScript, and are thus very vulnerable for injection attacks.
<svg
xmlns="http://www.w3.org/2000/svg"
width="780" height="550"
onload="(function(){ alert('doing something nasty') })()">
would execute this code when the svg file is used.
I found this nice library to manage SVG files. This helps in being able to remove attributes like onEVENT='someJs()' ; but that's still not going to help me sleep at night.
So how could one completely sweep an SVG file of JS code in a clever way?
https://digi.ninja/blog/svg_xss.php details this rather well.
It states:
Direct view - vulnerable - The file is linked to directly.
Direct view with content-disposition: attachment - not vulnerable - Headers are sent to force the file to be downloaded.
Direct view with CSP - not vulnerable - The Content Security Policy is set to disallow inline JavaScript.
Image Tags - not vulnerable - The SVG is referenced through image tags which prevent scripts.
Tags With CSP - not vulnerable - Image tags and the same CSP as above for double protection.
Sanitised through Inkscape - vulnerable - This is a direct view but the file has been processed by the following command:
inkscape --file="xss.svg" --verb="FileVacuum" --export-plain-svg="sanitised.svg"
( It was expected that this would remove the JavaScript but it did not. )
You can also just export to a different filetype that doesn't have this issue. An example using Inkscape's CLI on Linux:
inkscape --export-type="png" /home/x/Pictures/example.svg
https://wiki.inkscape.org/wiki/index.php/Using_the_Command_Line has more information under "Export files".
Edit: the following projects can actually strip JavaScript out: