Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what does "JavaScript sanitization doesn't save you from innerHTML" mean?

I'm learning xss prevention through this ppt:http://stash.github.io/empirejs-2014/#/2/23, and I have a question on this page.

It says "JavaScript sanitization doesn't save you from innerHTML", and I tried a simple test like this:

<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>test</title>
</head>
<body>
  <div id="test"></div>
  <script>
    var userName = "Jeremy\x3Cscript\x3Ealert('boom')\x3C/script\x3E";
    document.getElementById('test').innerHTML = "<span>"+userName+"</span>";
  </script>
</body>
</html>

when I opened this html on my browser(chrome), I only saw the name "Jeremy",by using F12, I saw

<div id="test"><span>Jeremy<script>alert('boom')</script></span></div>

Although the script had been added to html, the alert box didn't come out.

"JavaScript sanitization doesn't save you from innerHTML" I think this means that the word "boom" should be alerted. Am I right?

like image 662
Kreja Avatar asked Jul 31 '15 02:07

Kreja


1 Answers

According to MDN, innerHTML prevents <script> elements from executing directly1, which means your test should not alert anything. However, it does not prevent event handlers from firing later on, which makes the following possible:

var name = "\x3Cimg src=x onerror=alert(1)\x3E";
document.getElementById('test').innerHTML = name; // shows the alert
<div id="test"></div>

(script adapted from the example in the article, with escape sequences although I'm not sure those are relevant outside of <script> elements)

Since <script> elements never execute when inserted via innerHTML, it's not clear to me what that slide is trying to convey with that example.


1 This is actually specified in HTML5. MDN links to a 2008 draft; in the current W3C Recommendation, it's located near the end of section 4.11.1, just before section 4.11.1.1 begins:

Note: When inserted using the document.write() method, script elements execute (typically synchronously), but when inserted using innerHTML and outerHTML attributes, they do not execute at all.

like image 140
BoltClock Avatar answered Sep 30 '22 20:09

BoltClock