view source01 <!DOCTYPE html> 

02 <head> 

03 <title>Oh no!</title> 

04 <script type="text/javascript"> 

05     var xss = "</script><script>alert('XSS');</script>"; 

06 </script> 

07 </head> 

08 <body> 

09 <p>And you thought parsers were smart.</p> 

10 </body> 

11 </html>





“That does not mean, however, that blocking < and > when ouputting user data in javascript isn’t necessary”, David said.

I was confused. How could those characters change the interpretation of a string?

“But for a javascript string, aren’t quotes and backslash the only meta characters that can change the way it’s interpreted?”, I replied.
“Good question”, David replied. “And while that is true for an isolated javascript, it is not true, when javascript and HTML are mixed in an HTML page. Consider the following…”

David grabbed the keyboard, and wrote the following HTML page:

view source1 <html> 

2 <body> 

3 <script> 

4 var a = "</script><script>alert('xss');</script>"; 

5 </script> 

6 </body> 

7 </html>

“What do you think will happen here?”, David asked.

So the attacker was able to insert a script tag in a javascript variable. That’s it. That shouldn’t matter, right? I opened the HTML in my browser. I was wrong…

“Ehm..”, I replied intelligently.
“Now why do you think that happened?”
“I have no clue… How are we breaking out of the variable?”, I asked.
“As mentioned, this happens because we are running javascript as a part of an HTML page. The HTML parser runs first, so what the browser ends up with, is something like this…”, he replied, and opened the HTML in Firefox with the firebug add-in.


“HTML is in blue, javascript in black. The browser interprets the contents as some HTML, then an unclosed javascript variable ‘a’, then some script that creates a popup, then a quote and a semicolon as HTML – it’s now outside the script tags, right – and last it sees an attempt to close a script tag that has never been opened. So as you see, we need to escape the < and > characters anyways. But we need to escape them for javascript instead of HTML. So we could do something like this.”

view source1 <html> 

2 <body> 

3 <script> 

4 var a = "\x3C/script\x3E\x3Cscript\x3Ealert('xss');\x3C/script\x3E"; 

5 </script> 

6 </body>