Alex Rivera | Logout

What is the correct way to encode an inline javascript object, in order to protect it from XSS?

Asked 2010-08-16T00:25:43.967
13

It turns out the following which looks like valid javascript, is not:

<html> 
<body>
<script>
 json = {test: "</script><script>alert('hello');</script>"};
</script>
</body>
</html>

The same text, when returned JSON via an ajax api works just as expected. However when rendered in-line results in a basic XSS issues.

Given an arbitrary correct JSON string, what do I need to do server side to make it safe for in-line rendering?

EDIT Ideally I would like the fix to work with the following string as well:

json = {test: "<\/script><script>alert('hello');<\/script>"};

Meaning, I have no idea how my underlying library is encoding the / char, it may have chosen to encode it, or it may have not. (so its likely a regex fix is more robust)

Edit
Report

1 Answer

1

I found this list of characters to be escaped for JSON strings:

\b  Backspace (ascii code 08)
\f  Form feed (ascii code 0C)
\n  New line
\r  Carriage return
\t  Tab
\v  Vertical tab
\'  Apostrophe or single quote
\"  Double quote
\\  Backslash character

Using PHP? If so: json_encode

 echo json_encode("<\/script><script>alert(\"hello\");<\/script>");

Output:

 "<\\\/script><script>alert(\"hello\");<\\\/script>"

Another example:

 echo json_encode("</script><script>alert(\"hello\");</script>");

Output:

 "<\/script><script>alert(\"hello\");<\/script>"
answered 2010-08-16T00:32:56.453

Your Answer