6

Is this 100% safe against XSS? If not, can you please provide example bad string text showing me why it is not.

<html>
  <body>
    <script>
      <?php
        $bad = "some bad string.  please give example text that makes the below unsafe";
        echo "var a = ".json_encode($bad).";";
        echo "var b = ".json_encode(array($bad)).";";
      ?>
    </script>
  </body>
</html>

Thanks.
4
  • 2
    That kinda depends on what you eventually do with a doesn't it? Commented May 6, 2011 at 15:24
  • Where is $bad actually coming from? Not that it matters since json_encode only creates valid JSON, which is "non-executable". Commented May 6, 2011 at 15:25
  • @kevin, json_encode creates valid json Commented May 6, 2011 at 15:26
  • I'm mainly concerned about $bad containing javascript that is somehow executed. Based on Lekensteyn's answer below, it seems that this is impossible and so it is safe. But if anyone can show me otherwise it would certainly be a shock to my system! Commented May 6, 2011 at 15:34

2 Answers 2

5

In short, it's safe. Possible XSS would require escaping from the javascript string (") or script (</script>). Both strings are properly escaped:

"          becomes  \"
</script>  becomes  <\/script>

This is the the part about direct injection. Your application should take in account that some array elements may be missing. Another possibility is that an array element is not the type you would expect (e.g., an array instead of a string)

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

Comments

1

Definitely not!!!

Don't use json_encode to escape javascript.

for example:

json_encode<img src=# onerror=alert(1)>, this will escape nothing and output to brower. This is a xss.

use htmlspecialchars instead.

2 Comments

This is the correct answer. In short most things aren't safe and this proves it.
Isn't it still safe to use in Javascript context which the original question is about, not in HTML context? Of course, htmlspecialchars() is correct in HTML context.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.