Sunday, March 22, 2009

Secure JSON

Secure JSON: 1)A word of caution against using eval.
JSON data format is a subset of JavaScript notation, meaning that it is possible to use JavaScript eval to transform JSON data to live data. However, it is unsafe practice to assume that data reaching your code is safe. eval is capable of executing JavaScript's full notation, including calling functions and accessing cookies with all the privileges of a script. To ensure that the data is safe, YAHOO.lang.JSON.parse inspects the incoming string (using methods derived from Douglas Crockford's json2.js) and verifies it as valid JSON before giving it the green light to parse.

1 // Potentially UNSAFE
2 var data = eval('(' + shouldBeJsonData + ')');
3
4 // Safe
5 var data = YAHOO.lang.JSON.parse(shouldBeJsonData);

2) The server could also check the HTTP referer header in order to make sure the request has originated from the legitimate application and not from a malicious application. Historically speaking, the referer header has not been reliable, so we do not recommend using it as the basis for any security mechanisms.

You can use setRequestHeader() to add almost any header to the request. One idiosyncrasy is the referrer header: depending on the browser this may or may not be sent, and may or may not be writable. The table below sumarises this behaviour.

Referrer sent Referrer writable Can use custom headers
If you want to be sure of a server receiving the referrer, it’s recommended you use a custom header:

request.setRequestHeader('X-Referer', document.location);

It’s quite likely you’ll need to send more than just simple characters in the request, but if you range outside of alphanumeric characters you’ll have to encode them for use in a URI:

var params = 'moneySymbol=' + encodeURIComponent('€');
request.send(params);


3)When the server serializes an object, it should include a prefix (and potentially a
suffix) that makes it impossible to execute the JavaScript using a script tag. The legitimate
client application can remove this extraneous data before running the JavaScript. There are many
possible implementations of this approach


4) JSON Via Parse
The third and final method sends a raw object which must be parsed by a function. This could be referred to as the parse method. This is, by far, the safest and most secure way to transfer JSON data and it will be a part of the next version of Javascript due to be released in 2008. For now, it is, unfortunately, limited only to domains which you control.


5) Create a GUID at the server and pass it along to the client. Every request should include a parameter that is hard for the attacker to guess. In this case the GUID is required as a parameter to be passed to the server. The server will check for the GUID being the same as the one it has created for the current session.