Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I sometimes see that people wrap json_encode() in htmlspecialchars(). Why?

I usually do this:

echo json_encode($result);

But I see that people sometimes do this:

echo htmlspecialchars( json_encode($result), ENT_NOQUOTES );

Why would you use htmlspecialchars on JSON?

like image 247
Stann Avatar asked Jul 31 '11 21:07

Stann


1 Answers

I don't know php, so i'll assume htmlspecialchars escapes any html special characters.

Given that assumption then the use case is planting json data directly inside html content, a la

echo "<script>"
echo json_encode($result)
echo "</script>"

Given json encoding only encodes content to avoid escaping from the JS parser, this scenario would allow someone to insert JSON data that the html parser interpreted as ending the script tag.

Something like

{"foo": "</script><script>doSomethingEvil()</script>"}

would then reach the browser as

<script>{"foo": "</script><script>doSomethingEvil()</script>"}<script>

Which clearly results in doSomethingEvil() being executed. By escaping any html tokens you end up sending something like

<script>{"foo": "&lt;/script&gt;&lt;script&gt;doSomethingEvil()&lt;/script&gt;"}<script>

Instead, which avoids the XSS vulnerability.

A far better solution to this problem is to simply not send JSON data directly in an HTML source (JSON encoding just makes the content safe to embed in JS, not HTML)

like image 188
olliej Avatar answered Oct 09 '22 17:10

olliej