codeigniterSecuring your web application

Introduction

Remember CodeIgniter is a development Framework. It doesn't strive to make you're application secure. It merely gives you the tools to do it yourself. If you look at CI's Security page, it pretty clear they are expecting the developer to understand Application Security and build it into their application.

If WebApp security is relatively new for you, I would start with OWASP. It might be advantageous to look at look other frameworks such as Zend or Cake which I believe do more upfront things

Syntax

  • $freshdata = $this->security->xss_clean($user_input_data);

Parameters

array of user inputblank
insert array of user input in xss_filter($array of user input)Blank

XSS Prevention

XSS means cross-site scripting. CodeIgniter comes with XSS filtering security. This filter will prevent any malicious JavaScript code or any other code that attempts to hijack cookie and do malicious activities. To filter data through the XSS filter, use the xss_clean() method as shown below.

$data = $this->security->xss_clean($data);

You should use this function only when you are submitting data. The optional second Boolean parameter can also be used to check image file for XSS attack. This is useful for file upload facility. If its value is true, means image is safe and not otherwise.

SQL Injection Prevention

SQL injection is an attack made on the database query. In PHP, we use mysql_real_escape_string() function to prevent this along with other techniques but CodeIgniter provides inbuilt functions and libraries to prevent this.

We can prevent SQL Injection in CodeIgniter in the following three ways −

  • Escaping Queries
  • Query Biding
  • Active Record Class

Escaping Queries

<?php
   $username = $this->input->post('username');
   $query = 'SELECT * FROM subscribers_tbl WHERE user_name = '.
   $this->db->escape($email);
   $this->db->query($query);
?>

$this->db->escape() function automatically adds single quotes around the data and determines the data type so that it can escape only string data.

Query Biding

<?php
   $sql = "SELECT * FROM some_table WHERE id = ? AND status = ? AND author = ?";
   $this->db->query($sql, array(3, 'live', 'Rick'));
?>

In the above example, the question mark(?) will be replaced by the array in the second parameter of the query() function. The main advantage of building query this way is that the values are automatically escaped which produce safe queries. CodeIgniter engine does it for you automatically, so you do not have to remember it.

Active Record Class

<?php
   $this->db->get_where('subscribers_tbl',array('status'=> active','email' => '[email protected]'));
?>

Using active records, query syntax is generated by each database adapter. It also allows safer queries, since the values escape automatically.

Hiding PHP Errors

In production environment, we often do not want to display any error message to the users. It is good if it is enabled in the development environment for debugging purposes. These error messages may contain some information, which we should not show to the site users for security reasons.

There are three CodeIgniter files related with errors. PHP Error Reporting Level

Different environment requires different levels of error reporting. By default, development will show errors but testing and live will hide them. There is a file called index.php in root directory of CodeIgniter, which is used for this purpose. If we pass zero as argument to error_reporting() function then that will hide all the errors.

CSRF Prevention

CSRF stands for cross-site request forgery. You can prevent this attack by enabling an option in the application/config/config.php file as shown below.

$config['csrf_protection'] = TRUE;

When you create a form using the form_open() function, it will automatically insert a CSRF token in a hidden field. You can also manually add the CSRF token using the get_csrf_token_name() and get_csrf_hash() function. As their names suggest, the get_csrf_token_name() function will return the name of the CSRF token, while get_csrf_hash() will return the hash.

The CSRF token can be regenerated every time for submission or you can also keep it the same throughout the life of the CSRF cookie. Setting the configuration option ‘csrf_regenerate’ will force regeneration of the token as shown below.

$config['csrf_regenerate'] = TRUE;

You can whitelist URLs from CSRF protection by setting matches for them in the configuration array using the key ‘csrf_exclude_uris’ as shown below. You can also use regular expressions.

$config['csrf_exclude_uris'] = array('api/person/add');

Remove Abuse Data from User input

// XSS Filtering
$data = array(
             'name'=> '<script>Abuse Data</script>'
        );
$data = $this->security->xss_clean($data); // Clean Data

// Escaping Queries
<?php $username = $this->input->post('username'); $query = 'SELECT * FROM subscribers_tbl WHERE user_name = '. $this->db->escape($email); $this->db->query($query); ?>

XSS Prevention on User Input

Don't rely on any user input. user input everything like <script> tag or any javascript alert(); so we have to prevent this all data will no run in our browser. so we have to use xss prevention method to restrict our secure data to kept in hacker hand and also it's developer's responsibility to user's input validation and solve error by programatically.

so, check this is a example of xss prevention in CodeIgniter.

$data = array(
            'name' => "<script>alert('abc')</script>",
            'email' => "[email protected]"
        );
var_dump($data);
// Print array without xss cleaning/xss filtering

array(2) { ["name"]=> string(29) "" ["email"]=> string(19) "[email protected]" } // Result with alert

// now print data after xss filtering

$data = $this->security->xss_clean($data);
var_dump($data);

//Print array without xss cleaning/xss filtering
array(2) { ["name"]=> string(38) "[removed]alert('abc')[removed]" ["email"]=> string(19) "[email protected]" } // Result Without alert

so, after added xss_filtering we don't have any issue to run any abuse code which input by user. and CodeIgniter replace this abuse tag with [removed] keyword.