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)
To start with, this is not JSON at all, it’s a Javascript object. JSON is a text format that is based on the Javascript syntax.
You can either make sure that the code doesn’t contain the
</character combination:Or if you are using XHTML you can make sure that the content in the script tag is interpreted as plain data: