Oleg Popov
Oleg Popov

Reputation: 2514

PHP, Javascript JSON, XSS Protection

I am considered about XSS vulnerability!

I have web site, where All data b/w web server and client is transferred via XHR - JSON and browser javascript doing the rest to display the site.

When client submit data, here is my code BEFORE data to be recorded in DB (PHP):

$string = trim($_POST['user_input']);
$string = strip_tags($string);
$string = mysql_real_escape_string($string);

When the server getting data form database PHP code is following:

$string = htmlspecialchars($db_value);

and then

header('Content-Type: application/json; charset=utf-8');
print json_encode($string);

Is this enough to protect me against XSS?

Upvotes: 0

Views: 1373

Answers (2)

TheMonarch
TheMonarch

Reputation: 617

As a general rule of thumb, the other answer here is not correct. Using application/json for your content-type will fix some problems, but many clients tend to extract data from a JSON object and display it on a page. This leads to a classic attack.

The ONLY reliable method to stop XSS (and I say reliable because it's not fool-proof) is to sanitize data on the inbound stream (rejecting requests entirely is probably a better call) and encoding ALL output that has the potential to be displayed (ie: anything the user could have modified).

Also, don't accept the idea that methods not designed for security are inherently secure (json_encode is not meant for XSS security, and should not be used as such). Any suggestion that normal security practices are not necessary because of X should be viewed with skepticism if not outright disregarded.

Upvotes: 2

Explosion Pills
Explosion Pills

Reputation: 191779

That really depends. If the contents of $string post json_encode contain HTML entities and are displayed as html on a page then you would be vulnerable to XSS. If that's not the case (and it's not since you're using application/json anyway) then not only is there no need to use htmlspecialchars, it's probably undesirable because it alters the raw data you are trying to transfer via JSON.

I won't say that you are completely invulnerable to XSS because it is limited only by the imagination of evil people, but I would say that header('Content-Type: application/json;') provides sufficient protection in this instance.

On an unrelated note, stop using ext/mysql.

Upvotes: 1

Related Questions