Thursday, June 25, 2015

Implicit CSRF protection of ajax requests

Protecting form against CSRF is easy but what about ajax requests, here something more must be done.
It pretty straight forward to just  add the token to the data every time you make a ajax request, but what if you have a framework on top making the ajax request by it self. With frameworks using JQuery, in my case primefaces, this can be solved quite easy.

Primefaces uses the JQuery.ajax method when making ajax requests for many of its components, for example autocomplete. The easies way to do this would then offcourse be to change the underlaying function. Thanks to the way JQuery is built the core methods is very easy to override.

To override a core method in JQuery you just assign the function a new function... =/ like this.

JQuery.ajax = function(settings) {
...
}

The assign function should take the same arguments as the original function. In this case a key/value pair.

Now you just have to put something in the function to append the CSRF token. In my case:

//IPR Ergogroup AS
jQuery.ajax = function(settings) {
if (!settings.dataType)
settings.dataType = 'html';
if (typeof (settings.data) == typeof ('')) {
settings.data += '$CSRFToken=' + CSRFToken;
} else {
settings.data['CSRFToken'] = CSRFToken;
}
orginalMethod(settings);
}

To be able to invoke the original method after doing my stuff I save it to a variable berofe overiding it.
For further reading I recommend the OWASP top 10 publication. Which describes the top 10 security threats to web applications and how to protect against them.

No comments:

Post a Comment