Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serving JSON and HTML securely to JavaScript

I am thinking of secure ways to serve HTML and JSON to JavaScript. Currently I am just outputting the JSON like:

ajax.php?type=article&id=15
{
 "name":    "something",
 "content": "some content"
}

but I do realize this is a security risk -- because the articles are created by users. So, someone could insert script tags (just an example) for the content and link to his article directly in the AJAX API. Thus, I am now wondering what's the best way to prevent such issues. One way would be to encode all non alphanumerical characters from the input, and then decode in JavaScript (and encode again when put in somewhere).

Another option could be to send some headers that force the browser to never render the response of the AJAX API requests (Content-Type and X-Content-Type-Options).

like image 590
Tower Avatar asked Jul 24 '10 11:07

Tower


2 Answers

If you set the Content-Type to application/json then NO Browser will execute JavaScript on that page. This is apart of RFC-4627, and Google uses this to protect them selves. Other Application/ Content types follow similar rules.

You still have to worry about DOM Based XSS, however this would be a problem with your JavaScript, not really the content of the json. Another more exotic security concern with Json is information leakage like this vulnerability in gmail.

Make sure to always test your code. There is the Sitewatch free xss scanner, or the open source Skipfish and finally you could test this manually with a simple <script>alert(/xss/)</script>.

like image 123
rook Avatar answered Sep 28 '22 01:09

rook


Instead of worrying about how you could encode the malicious code when you return it, you should probably take care that it does not even get into your database. A quick google search about preventing cross-site scripting and input validation might help you here. Cheers

like image 44
moxn Avatar answered Sep 28 '22 02:09

moxn