A JavaScript Security Flaw

The following is a JavaScript security flaw:

<script>
  var str = "</script><script>alert('Pwned');</script>";
</script>

Don’t believe me? Try it for yourself. The browser ignores the fact that the <script> tags are inside a JavaScript String, invoking the alert() function.

The reason for this odd behavior is that the page gets rendered in various stages. First the HTML is parsed, and a render tree created. Only then, is the JavaScript actually executed. In the example above, the render tree see the <script> tags, and is oblivious to the fact that they’re inside a string; it has no concept of JavaScript. It strips these out, and evaluates the script nodes as usual with our injected message.

This behavior would be little more than a curiosity, were it not for the common pattern of injecting JSON into documents, say with ERB.

<script>
  var users = <%= @users.to_json.html_safe %>;
</script>

If you have the line above anywhere in your code, and @users includes some user submitted data, your application is vulnerable to a XSS attack.

If you’re using Rails, you can thwart this vulnerability by setting ActiveSupport.escape_html_entities_in_json to true. The default is false.

 
1,040
Kudos
 
1,040
Kudos

Now read this

JavaScript ‘wake’ event

For monocle.io I wanted to ensure that the list of posts is always kept up to date. This is especially a problem when the computer wakes up from a sleep, as the top posts are often way out of date! It turns out there is no JavaScript... Continue →