H
H
Hint2010-10-22 10:52:45
HTML
Hint, 2010-10-22 10:52:45

Is it safe to embed JSON in HTML

Is it safe to embed JSON with strings received from the user directly into the page code via the script tag? Is it possible to break JSON with the help of special html sequences by making XSS? The JSON is generated by the json_encode PHP function.

Example.

$queryData = json_encode(array('query' => isset($_GET['query']) ? $_GET['query'] : '', ...));


Page template:
<script type="text/javascript">
<?php echo 'var queryData = ' . $queryData . ';' ?>
</script>

Answer the question

In order to leave comments, you need to log in

3 answer(s)
K
Kolyaj, 2010-10-22
@Kolyaj

Valid JSON XSS cannot be called, and json_encode produces, of course, valid. Another thing is what you will do with this JSON further - if you display it on the page, then you must not forget to escape it yourself.

M
Mithgol, 2010-10-22
@Mithgol

<?php
echo json_encode(array('tzt'=>'\'')); // выдаёт {"tzt":"'"}
echo json_encode(array('tzt'=>'\"')); // выдаёт {"tzt":"\""}
echo json_encode(array('tzt'=>'</script>')); // выдаёт {"tzt":"<\/script>"}
echo json_encode(array('tzt'=>'<\\/script>')); // выдаёт {"tzt":"<\\\/script>"}
echo json_encode(array('tzt'=>"\x0")); // выдаёт {"tzt":"\u0000"}
?>

There doesn't seem to be any way to break the JSON. But I just violated the Habrahabr parser: in the last """-quotes (in the comment), instead of an empty space, "\u" should be displayed and immediately followed by "0000".

W
Wott, 2010-10-22
@Wott

Watching what and where to insert. JSON itself is a transport - if the user enters XSS in the comments, then it will honestly be transmitted through json escaped and all that, but as soon as it, like a piece of html, is inserted into the text of the page, then it will bite.
Again, if you return the form filled out by the user, and back to him - yes, let him insert at least something for health. But in public access is no longer good.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question