September 14, 2012

Cross-site request forgery (CSRF) – Ajax Fix

Cross-site request forgery (CSRF) – Ajax Fix

CSRF Security Class is great practice which is not really in practice commonly. The reason is workload of the scope of the project. Developers mostly don’t care about the form class of the CI and 20% or less people use form helper to generate 100% forms in their projects. I am one of those developers who developed numerous web based projects of medium to large nature but still i never fully used form helper for form related activities. And CSRF comes with form_open and form_close as CI says “If you use the form helper the form_open() function will automatically insert a hidden csrf field in your forms.” When i checked this class and realized that it is a useful thing so i reviewed my views and forms related pages. It was a huge work that i have to make changes in almost 82 pages in whole project. In which a couple of pages are not views but helper functions etc. The common step ahead is to leave as it is and plan it for the next time? Yes, its true.

But i figured out another possibility which i want to share for those projects which are lacking this security and can have this one easily. Here are few recommendations before implementation of CSRF:

  1. Use Template Parser
  2. Keep the CSRF config values dynamic so it will be hard to guess in form as hidden field

Now if you are using template parser then modify the parser library from system library folder to make a variable available in all the views with simple curly brackets e.g. {csrf_token}

If you are not using template parser then create form_hidden with the name and value given in the security class inside system folder.

Suppose that you made this token available in views either by template parser or by some helper function or form_hidden function. Now you have to find all the files which are having the tag ”

” ending. You have to replace all

with {csrf_token}

or some helper function with form ending tag. By this you will have all the forms pages updated.

Thats it, now your forms are security but your ajax calls won’t be accepted if you are not sending that csrf_token parameter in post or get type of ajax. For this you have two options, either you send this parameter for all the ajax requests or make your security class to ignore it by sensing the XMLHttpRequest. And use this code for ajax portion. By this you will prevent spamming activities through REFFERER HOST AND THE HTTP HOST matching. Now you can turn ON the option from config file. I will propose these changes to ellislab soon because this thing will encourage those developers who couldn’t implement this fix yet because of a lot of work to be redo.


Last updated: March 19, 2014