I have a stdClass
object in PHP, something like
$o = new stdClass;
$o->foo = $bar
The variable $bar
contains a
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
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.
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.
this will work ;)
...?payload=<img%20src=x%20onerror=alert(document.cookie);>
with json_encode ...
<?php echo json_encode($_GET['payload']); ?>
;)
As other answers have said; json_encode is not built for anti-xss protections. Unless you specifically encode the unsafe string (or sanitize properly) you're going to have a potential issue.
Furthermore, once that string is extracted from the JSON object, it is still potentially hazardous if injected into the page at any point. For example:
<?php $a->foo = "<script>alert(1)</script>"; ?>
var v = <?php echo json_encode($a); ?>
isn't likely to execute (although you can't be certain). But if you were to do:
$('#some-element').html(v.foo);
you would absolutely encounter a vulnerability.