Is json_encode a sufficient XSS protection?

advertisements

I have a stdClass object in PHP, something like

$o = new stdClass;
$o->foo = $bar

The variable $bar contains an untrusted string.

Is the following PHP template code sufficient XSS protection

<script type="text/javascript">
    var o = <?php echo json_encode($o); ?>;
</script>

My initial gut reaction is that is is safe, as encoding an object as JSON will ensure any potential javascript exploits will be rendered inert by being included as JSON string property objects. Something like this

$o = new stdClass;
$o->foo = "<script type=\"text/javascript\">alert(document.cookie)</script>";
?>
<script type="text/javascript">
    var o = <?php echo json_encode($o) ?>;
</script>

Resulting in output like this

<script type="text/javascript">
    var o = {"foo":"<script type=\"text\/javascript\">alert(document.cookie) <\/script>"};
</script>

If this is known unsafe, is there's a standard, mature way of serializing a simple stdClass object to a JSON string for use in a the <script/> portion of an HTML document.

In anticipation of the first quick answer, I realize that stripping out any HTML tags, or otherwise XSS filtering each element of the JSON object would work, but I'm looking for a concise way of doing this. Similar to how this

//$eBar = addslashes($bar);
$sql = sprtinf("SELECT * FROM table WHERE foo = '%s'",mysql_real_escape_string($bar));

and this

$sql = $db->select('SELECT * from table where foo = ?', $bar);

are (in most contexts) functionally equivalent, but the later is considered better, more secure code since the end programmer user doesn't need to worry about escaping schemes.


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.