Friday 6 January 2017

CodeIgniter Security Classes

CodeIgniter Security Class

CodeIgniter contain security class methods which will help to create a secure application and process input data. The methods are given below.
  • XSS Filtering
  • CSRF (Cross-site Request Forgery)
  • Class Reference

XSS Filtering

XSS stands for Cross-site Scripting. It is used to disable JavaScript or other types of code that try to hijack cookies and perform other type of malicious acts. When it encounters anything harmful, it is rendered safe by converting the data to character entities.
XSS filtering uses xss_clean() method to filer data.
  1. $data = $this->security->xss_clean($data);  
There is an optional second parameter, is_image, which is used to test images for XSS attacks. When this parameter is set to TRUE, it doesn't return an altered string, instead it returns TRUE if image is safe and FALSE if it contains malicious information.
  1. if ($this->security->xss_clean($file, TRUE) === FALSE)  
  2.     {  
  3.         //file failed in xss test  
  4.     }  

CSRF (Cross-site Request Forgery)

To enable CSRF do the following settings in application/config/config.php file.
  1. $config['csrf_protection'] = TRUE;  
If you are using form helper, then a hidden csrf field will be automatically inserted in your form_open()/ field.
Otherwise, you can manually add it using,
get_csrf_token_name() (it returns name of csrf) and
get_csrf_hash() (it returns value of csrf).
Generated tokens may be kept same throughout the life of CSRF cookie or may be regenerated on every submission. The default generation of token provides a better security but it also have usability concerns as other tokens like multiple tabs/windows, asynchronous actions, etc become invalid. Regeneration behavior can be set in application/config/config.php file as shown below.
  1. $config['csrf_regenerate?] = TRUE;  

Class Reference

  1. Class CI_Security                  
  1. xss_clean ($str [, $is_image = FALSE])  
Parameters - $str (mixed) ? input string or an array of strings
Returns - XSS-clean data
Return-type - mixed
From input data it removes XSS exploits and returns the clean string.
  1. Sanitize_filename ($str [, $relative_path = FALSE])  
Parameters - $str (string) ? File name/path
$relative_path (bool) ? Whether tp preserve any directories in the file path
Returns - Sanitized file name/path
Return-type - string
It prevents directory traversal and other security threats by sanitizing filenames. It is mainly useful for files which were supplied via user input.
  1. Entity_decode (($str [, $charset = NULL])  
Parameters - $str (string) ? Input string
$charset (string) ? Character set of the input string
Returns - Entity-decoded string
Return-type - string
It tries to detect HTML entities that don't end in a semicolon because some browser allows that.
$charset parameter is left empty, then your configure value in $config['charset'] will be used.
  1. Get_random_bytes ($length)  
Parameters - $length (int) ? Output length
Returns - A binary system of random bytes or FALSE on failure.
Return-type - string
It is used for generating CSRF and XSS tokens.

Preventing, Enabling from CSRF

In this tutorial we'll learn to protect CodeIgniter application from the cross-site request forgery attack. It is one of the most common vulnerabilities in web application. CSRF protection is quite easy in CodeIgniter due to its built-in feature.

What is CSRF attack

A CSRF attack forces a logged-on victim's browser to send a forged HTTP request, including victim's session cookie and other authentication information, to a web application.
For example, suppose you have a site with a form. An attacker could create a bogus form on his site. This form could contain hidden inputs and malicious data. This form is not actually sent to the attacker's site, in fact it comes to your site. Thinking that the form is genuine, your site will process it.
Now just suppose that the attacker's form point towards the deletion form in your site. If a user is logged in and redirected to the attacker's site and when perform search, his account will be deleted without knowing him. That is the CSRF attack.

Token Method

To protect from CSRF we need to connect both the HTTP requests, form request and form submission. There are several ways to do this, but in CodeIgniter hidden field is used which is called CSRF token. The CSRF token is a random value that changes with every HTTP request sent.
When CSRF token is inserted in the website form, it also gets saved in the user's session. When the form is submitted, the website matches both the token, the submitted one and one saved in the session. If they match, request is made legitimate. The token value changes each time the page is loaded, which makes it tough for the hackers to guess the current token.

Enabling CSRF Protection

To enable CSRF make the following statement TRUE from FALSE in application/config/config.php file.
  1. $config['csrf_protection'] = TRUE;  

Token Generation

With each request a new CSRF token is generated. When object is created, name and value of the token are set.
  1. $this->csrf_cookie_name = $this->csrf_token_name;  
  2. $this->_csrf_set_hash();  
The function for it is,
  1. function _csrf_set_hash()  
  2. {  
  3.       if ($this->csrf_hash == '')  
  4.         {  
  5. if ( isset($_COOKIE[$this->csrf_cookie_name] ) AND  
  6.              $_COOKIE[$this->csrf_cookie_name] != '' )  
  7.            {  
  8.              $this->csrf_hash = $_COOKIE[$this->csrf_cookie_name];  
  9.           } else {  
  10.                $this->csrf_hash = md5(uniqid(rand(), TRUE));  
  11.          }  
  12.        }  
  13.     return $this->csrf_hash;  
  14. }  
First, function checks the cookie's existence. If it exists, its current value is used because when security class is instantiated multiple times, each request would overwrite the previous one.
Function also creates a globally available hash value and save it for further processing. The token's value is generated. Now it has to be inserted into every form of the website with the help of function form_open().
The method csrf_verify() is called each time a form is sent. This method does two things. If no POST data is received, the CSRF cookie is set. And if POST data is received, it checks the submitted value corresponds to the CSRF token value in session. In the second case, CSRF token value is discarded and generated again for the next request. This request is legitimate and whole process starts again.

No comments:

Post a Comment