简体   繁体   中英

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

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?

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.

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. (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.)

For #2, encoding entities would work, or just insert a backslash in front of the slash in the content. 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 . 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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