Preventing CSRF in Kohana

Recently I found myself a neat CSRF module for kohana:

http://github.com/synapsestudios/kohana-csrf

I liked its simple design, you generate a token for your form then validate the token when its submitted. Unfortunately, I can’t use this solely for my project. The first issue with this module is that It will require me to manually add support for every single form and be very careful when adding AJAX and regular forms together. So i forked it.

http://github.com/isieo/kohana-csrf

What i did was i add a controller that returns the token as JSON and included a “fake javascript” file. My javascript is simple, its a simple jQuery script that injects a hidden field containing the token that was requested via AJAX, the token is then validated by the the controller automatically which upon success un-assign the token element from the $_POST array and reject if invalid. With that, CSRF tokens are transparent to your front end designers(if you are working with one) and all you need to tell your javascript programmer to do is call getCSRFToken() and post it in every Ajax Call.

Example usage for normal forms:

<!DOCTYPE html>
<html>
    <head>
        ...
        <script src="jquery-goes-here.js" />
        <script src="<?=url::site('/csrf/javascript/csrf.js');?>" />
    </head>
    <body>
        ...
        <form action="" method="post">
            <input type="email" name="emailaddress" />
            <input type="submit" value="submit">
        </form>
    </body>
</html>

that will work out of the box! no including pesky <input type=”hidden”> crap in your form.

Example using an AJAX call in jQuery:

$.post("<?=url::site('/email/add');?>", 
         { 
           'email':'someone@example.com',
           'csrf-token' : getCSRFToken() 
         }
       );

All you need to do is to add the ‘csrf-token’ : getCSRFToken()  into the ajax request. simple, no need to do callbacks for ajax calls that doesn’t require them.

Security in using JSON for getting token. Some of you might argue that serving tokens in JSON isn’t secure but if you read about JSONP (yes JSON with a P), you will notice that JSON doesn’t work well cross domain.  I am no security expert but hey, Accodring to: robubu.com there are no current vulnerabilities in using “serialized object” JSON (php’s json_encode function returns that by default).

So there you go a simple and nice module to prevent CSRF in kohana, coupled with jQuery Pouplate Plugin you get “pure html” forms that will make your frontend guy happy and not bug you for any assistant.

Update: As of 3 hours prior from this post, supports Namespaces to support multiple forms. but still.. its quite troublesome trying to keep track of token namespaces when you have many forms in a the same page which is going to make the frontend guy and you cry.. Its still a great module to use if you are working alone or you have an application that needs to be super-duper-uber-hacker-proof secure.