简体   繁体   English

我们应如何防止“仅”破坏页面渲染的XSS攻击?

[英]How should we prevent XSS attacks that *only* break page rendering?

Suppose we have a form that allows entering a piece of markdown as a message body. 假设我们有一个允许输入降价部分作为消息正文的表单。 That text is then render in HTML as JSON on another page: 然后,该文本在另一页上以JSON格式呈现为HTML:

<html>
   <body>
       <script type="text/javascript">
       loadMessage({
           name: 'John Doe',
           message: '**Hello** World'
       });
       </script>
   </body>
</html>

Pretend that loadMessage uses a markdown parser (eg marked ) and outputs the HTML at runtime. 假设loadMessage使用markdown解析器(例如标记为 )并在运行时输出HTML。

I've identified a case where a malicious user could cause an error on the page: 我发现了一种恶意用户可能在页面上导致错误的情况:

<html>
   <body>
       <script type="text/javascript">
       loadMessage({
           name: 'John Doe',
           message: '</script>'
       });
       </script>
   </body>
</html>

Because </script> causes the browser to close the script block, an Unexpected token ILLEGAL exception is thrown. 因为</script>导致浏览器关闭脚本块,所以引发了Unexpected token ILLEGAL异常。 Marked is able to sanitize such an attack, but this attack is even before JavaScript execution. Marked可以清除此类攻击,但该攻击甚至在JavaScript执行之前就已进行。

  1. Strip all <script> and </script> when the initial form is submitted. 提交初始表单后,请剥离所有<script></script> This would mean updating a lot of our framework code (using ASP.NET MVC - so we'd have to extend the default ModelBinder). 这将意味着更新许多框架代码(使用ASP.NET MVC-因此我们必须扩展默认的ModelBinder)。
  2. Leverage the JSON formatter for this - convert to '</' + 'script>' when writing the JSON. 利用JSON格式化程序-编写JSON时将其转换为'</' + 'script>' We'd be keeping the source intact - but maybe that's a bad thing . 我们会保持原始状态不变-但这也许是一件坏事

How should we mitigate such an attack? 我们应该如何减轻这种攻击?

I might personally go along with stripping anything resembling the script tag, as such an approach would provide an extra layer of security against validation bugs in your Markdown parser. 我个人可能会剥离类似于脚本标签的内容,因为这种方法将为Markdown解析器中的验证错误提供额外的安全保护。 But your mileage may vary depending on your application. 但是您的里程可能会因您的应用程序而异。

If you do need to encode, see https://stackoverflow.com/a/236106/131903 for a reasonable encoding approach (that is, use \\x3c to replace the less-than sign). 如果确实需要编码,请参阅https://stackoverflow.com/a/236106/131903以获取合理的编码方法(即,使用\\ x3c替换小于号)。 This will work: 这将起作用:

<html>
  <script>
    alert("1 \x3c/script> 2");
  </script>
</html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM