如何从SVG文件中删除所有的javascript?

3
我们计划允许用户上传SVG文件和图标。但问题在于SVG文件可以包含JavaScript代码,因此非常容易受到注入攻击的威胁。
<svg 
xmlns="http://www.w3.org/2000/svg" 
width="780" height="550" 
onload="(function(){ alert('doing something nasty') })()">

当使用 SVG 文件时,将执行此代码。
我发现了这个很棒的管理 SVG 文件的库。这有助于删除类似 onEVENT='someJs()' 这样的属性,但这仍然无法让我晚上睡觉。
那么,有什么聪明的方法可以完全清除 SVG 文件中的 JS 代码呢?

通过<img>标签或作为背景图像加载SVG,然后不会运行任何JavaScript。 - Robert Longson
在子域上托管svg,并使用内容策略来阻止JavaScript。 - zero298
将图像在上传时转换为PNG格式 - pokeybit
1个回答

1

https://digi.ninja/blog/svg_xss.php详细阐述了这个问题。

它指出:

  1. Direct view - vulnerable - The file is linked to directly.

  2. Direct view with content-disposition: attachment - not vulnerable - Headers are sent to force the file to be downloaded.

  3. Direct view with CSP - not vulnerable - The Content Security Policy is set to disallow inline JavaScript.

  4. Image Tags - not vulnerable - The SVG is referenced through image tags which prevent scripts.

  5. Tags With CSP - not vulnerable - Image tags and the same CSP as above for double protection.

  6. 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"
    

预期这将移除JavaScript,但并没有。

  1. 在iframe中的图像 - 易受攻击 - SVG作为iframe的源加载,没有设置任何特殊属性。
  2. 在沙盒化的iframe中的图像 - 不易受攻击 - SVG作为iframe的源加载,但sandbox属性被设置为阻止脚本。

你也可以导出为不具有此问题的不同文件类型。以下是在Linux上使用Inkscape的CLI的示例:
inkscape --export-type="png" /home/x/Pictures/example.svg https://wiki.inkscape.org/wiki/index.php/Using_the_Command_Line 在“导出文件”下提供更多信息。

1
给访问者的注意事项:问题之一是 (3) 中的策略 "self" 不允许内联样式(无论是 <style> 还是 @style)。请参阅 https://github.com/w3c/webappsec-csp/issues/45 和 https://bugzilla.mozilla.org/show_bug.cgi?id=1262842 了解有关这些问题的讨论。 - Masklinn

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接