简体   繁体   English

XSS:分配此javascript字符串后,为什么会触发警报?

[英]XSS: Why does an alert get fired when this javascript string is assigned?

I'm investigating an XSS issue, which can be duplicated in the following simple html file, which when loaded, shows an alert with the value of "1". 我正在调查一个XSS问题,可以在以下简单的html文件中重复该问题,该文件在加载时显示的警报值为“ 1”。

Why does this work? 为什么这样做? The title string has an alert script tag in it, but I'm surprised the browser renders it, as that </script> tag is in a string? title字符串中包含一个警报脚本标签,但令我惊讶的是浏览器呈现了它,因为</script>标签位于字符串中?

test.html test.html

<html>
    <head>
      <script>
        var title = "</script><svg/onload=alert(1)>";
      </script>
    </head>
  <body></body>
</html>

EDIT: Note, I've simplified the example to a simple string assignment. 编辑:注意,我已将示例简化为简单的字符串分配。

Because the </script> inside the title string ends your script, so the following svg is part of the HTML. 由于title字符串中的</script>结束了脚本,因此以下svg是HTML的一部分。

To protect against that: 为了防止这种情况:

  1. Don't use inline script, or 不要使用内联脚本,或者

  2. If you do, any user-sourced input you render in it needs to not have </script> in it. 如果这样做,则您在其中呈现的任何基于用户源的输入都不必包含</script> (I'd probably be paranoid and allow for whitespace between the < and / and script and > ; in a JavaScript regex, <\\s*/\\s*script\\s*> with the m flag.) (我可能会偏执,并允许</script以及>之间的空格;在JavaScript正则表达式中,带有m标志的<\\s*/\\s*script\\s*> 。)

For #2, encoding entities would work, or just insert a backslash in front of the slash in the content. 对于#2,编码实体将起作用,或者仅在内容中的斜杠前面插入反斜杠。 If you do that (server side), then you'd have: 如果这样做(服务器端),那么您将拥有:

<html>
    <head>
      <script>
        var test = {
          "id" : 12181,
          "title" : "<\\/script><svg/onload=alert(1)>",
          "email" : null
        };
      </script>

    </head>
  <body>
  </body>
</html>

...which won't alert. ...不会发出警报。 (I only added one backslash, but of course, that's inside a string literal, so it will get escaped.) (我只添加了一个反斜杠,但是,当然,它在字符串文字中,因此可以转义。)

However , if you're putting untrusted content in your pages, you'd be well-served by reading through the owasp.org XSS (Cross Site Scripting) Prevention Cheat Sheet . 但是 ,如果您要在页面中放置不受信任的内容,请阅读owasp.org XSS(跨站点脚本)预防速查表 ,这将为您提供良好的服务。 The above may be sufficient for this one specific use , but you may want to go further and you certainly will want to do HTML escaping on any content you include in HTML (rather than script) elements, in attributes (which are HTML text, even if they're onclick and such), etc. 上面的内容对于这一特定用途可能就足够了,但是您可能想走得更远,并且您当然希望对包含在HTML(而不是脚本)元素,属性(甚至是HTML文本,甚至是HTML元素)中的任何内容进行HTML转义。如果它们是onclick等),等等。

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

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