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.
Programmer Bruce
  • 64,977
  • 7
  • 99
  • 97
user324289
  • 175
  • 2
  • 7
  • 2
    That kinda depends on what you eventually do with `a` doesn't it? – chustar May 06 '11 at 15:24
  • Where is `$bad` actually coming from? Not that it matters since `json_encode` only creates valid [JSON](http://json.org/), which is "non-executable". – Kevin Peno May 06 '11 at 15:25
  • @kevin, `json_encode` creates valid json – Naftali May 06 '11 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! – user324289 May 06 '11 at 15:34

2 Answers2

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)

Lekensteyn
  • 64,486
  • 22
  • 159
  • 192
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.

gouchaoer
  • 535
  • 2
  • 7
  • 22
  • This is the correct answer. In short most things aren't safe and this proves it. – JoeMoe1984 Oct 25 '16 at 04:08
  • 1
    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. – Sergei Morozov Apr 24 '19 at 17:42