Is json_encode Sufficient XSS Protection?

Seems as through the best answer to this question lies in another question.

To sum up, PHP's JSON encoder escapes all non ASCII characters, so newlines/carriage returns can't be inserted to bollacks up the Javascript string portion of the JSON property. This may not be true of other JSON encoders.

However, passing in a raw string to JSON encode can lead to the usual litany of XSS attacks, the following combination of constants is suggested.

var v= <?php echo json_encode($value, JSON_HEX_QUOT|JSON_HEX_TAG|JSON_HEX_AMP|JSON_HEX_APOS); ?>;

or ensure the variable passed to json_encode is really an object.


this will work ;)

...?payload=<img%20src=x%20onerror=alert(document.cookie);>

with json_encode ...

<?php echo json_encode($_GET['payload']); ?>

;)


What I do is to evaluate the json object before assuming its safe. I think the method is evalJSON(true) in prototype and jquery has a similar implementation. I don't know much about xss standards with JSON but this helps me


XSS is very broad and it's actually impossible to know at any time whether untrusted data you are emitting is safe.

The answer is really that it depends on the situation. json_encode does no escaping on its own whatsoever -- you're only using it for serialization purposes. The escape function you want to use would be htmlspecialchars.

However, whether or not you even want to use htmlspecialchars depends. For example, will you insert the value of o.foo using innerHTML or textContent? The latter would lead to a double-escape, but the former would insert a script. What about if you were going to use eval (in JS)?

By the way addslashes is not functionally equivalent to mysql escaping.

I wouldn't mix JavaScript and PHP in this way to begin with, but that's another story.