Advertisement
  1. Code
  2. PHP
  3. CodeIgniter

Protect a CodeIgniter Application Against CSRF

Scroll to top
9 min read

In today's tutorial, we will learn how to painlessly protect your CodeIgniter (pre 2.0) application against Cross-Site Request Forgery attacks. The library we'll be creating today will automate all of the protection mechanisms, making your site stronger and more secure.


Step 1 - Understanding the Attack Vector

Cross-Site Request Forgery attacks are based on unprotected forms on your sites.

An attacker could create a bogus form on his site - for example a search form. This form could have hidden inputs that contain malicious data. Now the form isn't actually sent to the attacker's site to perform the search; in reality, the form points to your site! Since your website will trust that the form is genuine, it goes through and executes the requested (and perhaps malicious) actions.

Imagine that a user is logged into your site, and is redirected to the attacker's site for some reason (phishing, XSS, you name it). The attacker's form could point to your account deletion form on your site. If the user performs a "search" on the attackers site, his account will then be deleted without him knowing!

There are numerous ways to prevent these sorts of attacks.

  • Check the HTTP Referer header and see if it belongs to your site. The problem with this method is that not all browsers submit this header (I personally had this problem once with IE7); it could be forged anyway.
  • Another method (the one we will use), is to include a random string (a "token") on each form, and store that token on the user's session. On each POST request, compare the submitted token to the one on store, and, if they differ, deny the request. Your site still needs to be protected against XSS though, because if it's not, this method becomes useless.

Step 2 - Planning

We'll need to do three things for each request:

  • If the request is a POST request, validate that the submitted token.
  • Generate a token in case there isn't one.
  • Inject the token into all forms. This makes the method seamless and painless, since no modification is needed on your views.

To do this automatically, we'll use CodeIgniter hooks. Hooks allow us to execute all actions on different parts of the request. We'll need three:

  • post_controller_constructor - To check the submitted token, we'll need a post_controller_constructor hook. Hooking this action before this event doesn't give us access to CodeIgniter's instance correctly.
  • Generate the Token - To generate the token, we'll use the same hook as before. This allows us to have access to it in case we needed to print it manually in our views.
  • display_override - To inject the token automatically in our views, we'll need to use the display_override hook. This is a tricky hook though, since, as its name implies, it overrides the display of the views. We need to output the content ourselves if we use this hook (check the CodeIgniter documentation for more info).

Step 3 - Token Generation

Let's get started. We'll go step by step in order to explain everything as thoroughly as possible. We'll create the method that generates the token first, so we can test everything correctly afterwards. Create a file in your system/application/hooks folder called "csrf.php", and paste the following code:

1
<?php
2
/**

3
 * CSRF Protection Class

4
 */
5
class CSRF_Protection
6
{
7
  /**

8
   * Holds CI instance

9
   *

10
   * @var CI instance

11
   */
12
  private $CI;
13
14
  /**

15
   * Name used to store token on session

16
   *

17
   * @var string

18
   */
19
  private static $token_name = 'li_token';
20
21
  /**

22
   * Stores the token

23
   *

24
   * @var string

25
   */
26
  private static $token;
27
28
  // -----------------------------------------------------------------------------------

29
30
  public function __construct()
31
  {
32
    $this->CI =& get_instance();
33
  }
34
}

Hopefully, what we've added above should look rather basic to you. We're creating a class, called CSRF_Protection, an instance variable to hold the CodeIgniter instance, two static variables to hold the name of the parameter that will store the token, and one to store the token itself for easy access throughout the class. Within the class constructor (__construct), we simply retrieve the CodeIgniter instance, and store it in our corresponding instance variable.

Note: The "name of the parameter" is the name of the field that holds the token. So on the forms, it's the name of the hidden input.

After the class constructor, paste the following code:

1
/**

2
 * Generates a CSRF token and stores it on session. Only one token per session is generated.

3
 * This must be tied to a post-controller hook, and before the hook

4
 * that calls the inject_tokens method().

5
 *

6
 * @return void

7
 * @author Ian Murray

8
 */
9
public function generate_token()
10
{
11
  // Load session library if not loaded

12
  $this->CI->load->library('session');
13
14
  if ($this->CI->session->userdata(self::$token_name) === FALSE)
15
  {
16
    // Generate a token and store it on session, since old one appears to have expired.

17
    self::$token = md5(uniqid() . microtime() . rand());
18
19
    $this->CI->session->set_userdata(self::$token_name, self::$token);
20
  }
21
  else
22
  {
23
    // Set it to local variable for easy access

24
    self::$token = $this->CI->session->userdata(self::$token_name);
25
  }
26
}

Step by step:

  • We load the session library, in case it's not being loaded automatically. We need this to store the token.
  • We determine if the token was already generated. If the userdata method returns FALSE, then the token is not yet present.
  • We generate a token and store it in the class variable for easy access. The token could be almost anything really. I used those three functions to ensure that it's very random.
  • We then store it in the session variable with the name configured previously.
  • If the token was already present, we don't generate it and instead store it in the class variable for easy access.

Step 4 - Token Validation

We need to ensure that the token was submitted, and is valid in case the request is a POST request. Go ahead and paste the following code into your csrf.php file:

1
/**

2
 * Validates a submitted token when POST request is made.

3
 *

4
 * @return void

5
 * @author Ian Murray

6
 */
7
public function validate_tokens()
8
{
9
  // Is this a post request?

10
  if ($_SERVER['REQUEST_METHOD'] == 'POST')
11
  {
12
    // Is the token field set and valid?

13
    $posted_token = $this->CI->input->post(self::$token_name);
14
    if ($posted_token === FALSE || $posted_token != $this->CI->session->userdata(self::$token_name))
15
    {
16
      // Invalid request, send error 400.

17
      show_error('Request was invalid. Tokens did not match.', 400);
18
    }
19
  }
20
}
  • Above, we validate the request, but only if it's a POST request, which means that a form was, in fact, submitted. We check this by taking a look at the REQUEST_METHOD within the $_SERVER super global.
  • Check if the token was actually posted. If the output of $this->CI->input->post(self::$token_name) is FALSE, then the token was never posted.
  • If the token wasn't posted or if it's not equal to the one we generated, then deny the request with a "Bad Request" error.

Step 5 - Inject Tokens into the Views

This is the fun part! We need to inject the tokens in all forms. To make life easier for ourselves, we are going to place two meta tags within our <head> (Rails-like). That way, we can include the token in AJAX requests as well.

Append the following code to your csrf.php file:

1
/**

2
 * This injects hidden tags on all POST forms with the csrf token.

3
 * Also injects meta headers in <head> of output (if exists) for easy access

4
 * from JS frameworks.

5
 *

6
 * @return void

7
 * @author Ian Murray

8
 */
9
public function inject_tokens()
10
{
11
  $output = $this->CI->output->get_output();
12
13
  // Inject into form

14
  $output = preg_replace('/(<(form|FORM)[^>]*(method|METHOD)="(post|POST)"[^>]*>)/',
15
                         '$0<input type="hidden" name="' . self::$token_name . '" value="' . self::$token . '">', 
16
                         $output);
17
18
  // Inject into <head>

19
  $output = preg_replace('/(<\/head>)/',
20
                         '<meta name="csrf-name" content="' . self::$token_name . '">' . "\n" . '<meta name="csrf-token" content="' . self::$token . '">' . "\n" . '$0', 
21
                         $output);
22
23
  $this->CI->output->_display($output);
24
}
  • Since this is a display_override hook, we need to retrieve the generated output from CodeIgniter. We do this by using the $this->CI->output->get_output() method.
  • To inject the tags in our forms, we'll use regular expressions. The expression ensures that we inject a hidden input tag (which contains our generated token) only into forms with a method of type POST.
  • We also need to inject our meta tags into the header (if present). This is simple, since the closing head tag should only be present once per file.
  • Lastly, since we're using the display_override hook, the default method to display your view will not be called. This method includes all sorts of things, which we should not - just for the purposes of injecting some code. Calling it ourselves solves this.

Step 6 - Hooks

Last, but not least, we need to create the hooks themselves - so our methods get called. Paste the following code into your system/application/config/hooks.php file:

1
//

2
// CSRF Protection hooks, don't touch these unless you know what you're

3
// doing.

4
//

5
// THE ORDER OF THESE HOOKS IS EXTREMELY IMPORTANT!!

6
//

7
8
// THIS HAS TO GO FIRST IN THE post_controller_constructor HOOK LIST.

9
$hook['post_controller_constructor'][] = array( // Mind the "[]", this is not the only post_controller_constructor hook

10
  'class'    => 'CSRF_Protection',
11
  'function' => 'validate_tokens',
12
  'filename' => 'csrf.php',
13
  'filepath' => 'hooks'
14
);
15
16
// Generates the token (MUST HAPPEN AFTER THE VALIDATION HAS BEEN MADE, BUT BEFORE THE CONTROLLER

17
// IS EXECUTED, OTHERWISE USER HAS NO ACCESS TO A VALID TOKEN FOR CUSTOM FORMS).

18
$hook['post_controller_constructor'][] = array( // Mind the "[]", this is not the only post_controller_constructor hook

19
  'class'    => 'CSRF_Protection',
20
  'function' => 'generate_token',
21
  'filename' => 'csrf.php',
22
  'filepath' => 'hooks'
23
);
24
25
// This injects tokens on all forms

26
$hook['display_override'] = array(
27
  'class'    => 'CSRF_Protection',
28
  'function' => 'inject_tokens',
29
  'filename' => 'csrf.php',
30
  'filepath' => 'hooks'
31
);
  • The first hook calls the validate_tokens method. This is not the only post_controller_constructor hook, so we need to add those brackets ("[]"). Refer to the documentation on CodeIgniter hooks for more info.
  • The second hook, which is also a post_controller_constructor, generates the token in case it hasn't been generated yet.
  • The third one is the display override. This hook will inject our tokens into the form and the header.

Wrapping Up

With minimal effort, we've built quite a nice library for ourselves.

You can use this library in any project, and it will automagically protect your site against CSRF.

If you'd like to contribute to this little project, please leave a comment below, or fork the project on GitHub. Alternatively, as of CodeIgniter v2.0, protection against CSRF attacks is now built into the framework!

Advertisement
Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.