简体   繁体   中英

How to prevent XSS in a JavaScript platform using a PHP JSON API?

I'm looking for a way to prevent XSS in my pure javascript platform which calls a PHP API that returns JSON data using json_encode().

Take this basic example:

<script>alert('hello world');</script>

Let's say the above is stored in a database field which is grabbed by PHP and returned to the browser using json_encode():

<?php
echo json_encode(array('name'=>"<script>alert('hello world');</script>"), JSON_HEX_QUOT|JSON_HEX_TAG|JSON_HEX_AMP|JSON_HEX_APOS);
?>

As you can see, i've used a few json options in hopes this would sanitize the data for javascript usage. However, when I do the following in JavaScript, the alert still executes:

<script>
$('.nameField').html(jsonData.name);
</script>

From what i've read, the json options are the best practice for json_encoded data, but yet it still executes.

Where am I going wrong?

You're looking at the wrong layer. The threat here is not the JSON, it is the HTML inside the JSON. (There might be a threat in the JSON layer too, there isn't enough information in your question to tell.)

The options you've provided look like they should successfully prevent an XSS attack if you were to echo the JSON into a <script> element in order to cause it to be parsed as an array literal.

… but that isn't what you are doing.

You have done something unspecified to put the parsed JSON into a variable called jsonData .

At this point, any JSON-specific XSS protection is irrelevant. It is past the point where it matters.

You are taking the HTML out of the JSON and processing it with jQuery and injecting it into the DOM.

The way to defend against that is to not tell jQuery that it should treat it as HTML.

Use the .text() method instead of the .html() method.

Cover it with htmlentities($javascript, ENT_QUOTES | ENT_HTML5, 'UTF-8'); .

If you need to show exact HTML on the page use one of PHP libs like htmlpurifier .

However, you can still insert it with JQuery .text() instead of .html() as mentioned below, but it's better to escape it if possible.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM