11

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?

2
  • 3
    "Am I right?". No. innerHTML doesn't execute scripts. Commented Jul 31, 2015 at 2:56
  • innerHTML can be made to execute script through the use of inline attributes. Commented Aug 6, 2015 at 21:26

1 Answer 1

7

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.