Is getting JSON data with jQuery safe?

The last time I looked (late 2008) the JQuery functions get() getJSON() etc internally eval the JSon string and so are exposed to the same security issue as eval.

Therefore it is a very good idea to use a parsing function that validates the JSON string to ensure it contains no dodgy non-JSON javascript code, before using eval() in any form.

You can find such a function at github.com/douglascrockford/JSON-js/blob/master/json2.js.

See JSON and Broswer Security for a good discussion of this area.

In summary, using JQuery’s JSON functions without parsing the input JSON (using the above linked function or similar) is not 100% safe.

NB: If this sort of parsing is still missing from getJSON (might have recently been added) it is even more important to understand this risk due to the cross domain capability, from the JQuery reference docs:

As of jQuery 1.2, you can load JSON
data located on another domain if you
specify a JSONP callback, which can be
done like so: “myurl?callback=?”.
jQuery automatically replaces the ?
with the correct method name to call,
calling your specified callback.

$.getJSON() is used to execute (rather than using eval) javascript code from remote sources (using the JSONP idiom if a callback is specified). When using this method, it is totally up to you to trust the source, because they will have control to your entire page (they can even be sending cookies around).

From Douglas Crockford site about The Script Tag Hack (jsonp):

So the script can access and use
its cookies. It can access the
originating server using the user’s
authorization. It can inspect the DOM
and the JavaScript global object, and
send any information it finds anywhere
in the world. The Script Tag Hack is
not secure and should be avoided.

Both IE 8 and Firefox 3.1 will have native JSON support, which will provide a safe alternative to eval(). I would expect other browsers to follow suit. I would also expect jQuery to change its implementation to use these native methods.

Read more here: Source link