How to secure codeigniter Application?

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
  • CodeIgniter xss_clean

    XSS means Cross-site scripting, which is a type of security vulnerability found in web application. The XSS technique commonly used to trigger Javascript or other types of malicious code that attempt to hijack runnable code.

    Usage of xss_clean(), we can stop the data and filter up, if any disallowed data is encountered it is rendered by xss_clean function and safe convert into the character entities.

    Without the using of xss_clean(), encountered data via cookies and post, get method directly applied to the code, which is harmful.

    Codeigniter provides “security” class which contains methods that help you create a secure application.

    File name : index.php

    Load “security” class in controller’s constructor.

    $this->load->library("security");
    Executing xss_clean function using security class.

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

    $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.

    Codeigniter File : form.php

    <?php

    class Form extends CI_Controller {
    public function __construct() {

    //Load helper and library.
    parent::__construct();
    $this->load->helper('url');
    $this->load->helper('form');
    $this->load->library("security");
    }
    public function index() {

    // show view_form.php page.
    $this->load->view("view_form");
    }
    public function data_submitted() {

    //Storing values through POST method
    $data['non_xss']= array(
    'employee_name' => $this->input->post('emp_name'),
    'employee_email' => $this->input->post('emp_email')
    );

    // Apply the xss_clean() of "security" library, which filtered data from passing through <script> tag.
    $data['xss_data'] = $this->security->xss_clean($data['non_xss']);
    // Send "non-xss" and "xss-clean" data in view.
    $this->load->view("view_form", $data);
    }
    }
    ?>

    View File : view_form.php

    <html>
    <head>
    <title>Codeigniter xss clean</title>
    <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>css/style.css">
    <link href='http://fonts.googleapis.com/css?family=Source+Sans+Pro|Open+Sans+Condensed:300|Raleway' rel='stylesheet' type='text/css'>
    </head>
    <body>
    <div class="main">
    <p class="main_note">Check xss_clean() and see the difference you have to enter data <br> between script tag. <b>&lt;script&gt;alert('Hello')&lt;/script&gt;</b> </p>
    <div id="content">
    <h2 id="form_head">Codelgniter xss clean Demo</h2>
    <div id="form_input">
    <?php

    //create form open tag
    echo form_open('form/data_submitted');

    //create label
    echo form_label('Employee Name');

    //create name input field
    $data_name = array(
    'name' => 'emp_name',
    'id' => 'emp_name_id',
    'class' => 'input_box',
    'placeholder' => 'Please Enter Name',
    'required' => 'required'
    );
    echo form_input($data_name);
    echo "<br>";
    echo "<br>";
    echo form_label('Employee Email-ID');

    //create email input field
    $data_email = array(
    'type' => 'email',
    'name' => 'emp_email',
    'id' => 'e_email_id',
    'class' => 'input_box',
    'placeholder' => 'Please Enter Email',
    'required' => 'required'
    );
    echo form_input($data_email);
    ?>
    </div>
    <div id="form_button">
    <?php echo form_submit('submit', 'Submit', "class=''submit"); ?>
    </div>
    <?php

    //Form close.
    echo form_close(); ?>
    </div>

    <?php //This div shown when values submitted. ?>
    <?php if (isset($_POST['submit'])) { ?>
    <p class="display_note">The data is shown without xss_clean(), when you enter data between script tag, it will be applied in the code.</p>
    <div class="display">
    <div class="result_head"><h3>For submission with no xss_clean</h3></div>
    <div class="data">
    <label>name :</label> <?php echo $non_xss['employee_name'] ?><br><br>
    <label>Email :</label> <?php echo $non_xss['employee_email'] ?><br><br>
    </div>
    </div>
    <p class="xss_note">This data is shown after xss_clean(), which filter the script tag.</p>
    <div class="xss_clean_display">
    <div class="result_head"><h3>For submission with xss_clean CodeIgniter</h3></div>
    <div class="data">
    <label>name :</label> <?php echo $xss_data['employee_name'] ?><br><br>
    <label>Email :</label> <?php echo $xss_data['employee_email'] ?><br><br>
    </div>
    </div>
    <p class="note"><b id='note_text'>Note:</b> For best explanation use <b>Firefox</b> or <b>IE Explorer</b></p>
    <?php } ?>
    </div>
    </body>
    </html>

    CSS File : style.css

    File name : index.php

    body {
    font-family: 'Raleway', sans-serif;
    }
    .main{
    width: 1015px;
    position: absolute;
    top: 10%;
    left: 20%;
    }
    #form_head{
    text-align: center;
    background-color: #FEFFED;
    border-bottom: 1px solid #9A9A9A;
    height: 66px;
    margin: 0 0 -29px 0;
    padding-top: 35px;
    border-radius: 8px 8px 0 0;
    color: rgb(97, 94, 94);;
    }
    #content {
    position: absolute;
    width: 481px;
    height: 335px;
    border: 2px solid gray;
    border-radius: 10px;
    margin-top: 70px;
    margin-left: -90px;
    }
    #form_input{
    margin-left: 50px;
    margin-top: 43px;
    }
    label{
    margin-right: 6px;
    font-weight: bold;
    }
    #form_button{
    padding: 0 21px 15px 15px;
    position: absolute;
    bottom: 0px;
    width: 445px;
    background-color: #FEFFED;
    border-radius: 0px 0px 8px 8px;
    border-top: 1px solid #9A9A9A;
    }
    .label_output{
    color:#4A85AB;
    margin-left: 10px;
    }
    .input_box{
    height:40px;
    width:240px;
    padding:20px;
    border-radius:3px;
    background-color: #FEFFED;
    font-family: 'Raleway', sans-serif;
    }
    input#e_email_id {
    margin-left: 16px;
    }
    input#emp_name_id {
    margin-left: 35px;
    }
    input#password_id {
    margin-left: 87px;
    }
    .display{
    position: absolute;
    height: 190px;
    width: 465px;
    margin-left: 550px;
    margin-top: 365px;
    border: 2px solid gray;
    border-radius: 10px;
    }
    .result_head{
    text-align: center;
    background-color: #FEFFED;
    border-bottom: 1px solid #9A9A9A;
    height: 35px;
    margin: 0 0 -29px 0;
    padding-top: 8px;
    padding-bottom: 22px;
    border-radius: 8px 8px 0 0;
    color: rgb(97, 94, 94);;
    }
    .data{
    margin-top: 50;
    margin-left: 60px;
    }
    .xss_clean_display{
    margin-top: 25px;
    border: 2px solid gray;
    border-radius: 10px;
    position: absolute;
    height: 190px;
    width: 465px;
    margin-left: 550px;
    border: 2px solid gray;
    border-radius: 10px;
    }
    .submit{
    font-size: 16px;
    background: linear-gradient(#ffbc00 5%, #ffdd7f 100%);
    border: 1px solid #e5a900;
    color: #4E4D4B;
    font-weight: bold;
    cursor: pointer;
    width: 300px;
    border-radius: 5px;
    padding: 10px 0;
    outline: none;
    margin-top: 20px;
    margin-left: 15%;
    }
    .submit:hover{
    background: linear-gradient(#ffdd7f 5%, #ffbc00 100%);
    }
    p.main_note {
    position: absolute;
    margin-left: -90px;
    margin-left: -87px;
    margin-top: 9px;
    }
    p.note {
    margin-top: 580px;
    margin-left: 240px;
    }
    p.xss_note {
    margin-left: 550px;
    margin-top: 10px;
    }
    p.display_note{
    position: absolute;
    margin-top: 300px;
    margin-left: 550px;
    }
    #note_text {
    color: red;
    }

    CSRF (Cross-site Request Forgery)

    To enable CSRF do the following settings in application/config/config.php file.
    $config['csrf_protection'] = TRUE;

    When you are creating form using form_open() function, it will automatically insert a CSRF as hidden field. You can also manually add the CSRF using the get_csrf_token_name() and get_csrf_hash() function. The get_csrf_token_name() function will return the name of the CSRF and get_csrf_hash() will return the hash value of CSRF.

    The CSRF token can be regenerated every time for submission or you can also keep it same throughout the life of CSRF cookie. By setting the value TRUE, in config array with key ‘csrf_regenerate’ will regenerate token as shown below.

    $config['csrf_regenerate'] = TRUE;
    You can also whitelist URLs from CSRF protection by setting it in the config array using the key ‘csrf_exclude_uris’ as shown below. You can also use regular expression.

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

    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.

    $config['csrf_regenerate?] = TRUE;

    Class Reference

    Class CI_Security


    SQL Injection Prevention

    SQL injection is an attack made on database query. In PHP, we are 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 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('emp_tbl',array
    ('status'=> active','email' => 'info@itechtuto.com'));
    ?>

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


    Hiding PHP 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.

    Database Error
    Even if you have turned off the PHP errors, MySQL errors are still open. You can turn this off in application/config/database.php. Set the db_debug option in $db array to FALSE as shown below. $db['default']['db_debug'] = FALSE;

    Error log
    Another way is to transfer the errors to log files. So, it will not be displayed to users on the site. Simply, set the log_threshold value in $config array to 1 in application/cofig/config.php file as shown below. $config['log_threshold'] = 1;





    Previous Next


    Trending Tutorials




    Review & Rating

    0.0 / 5

    0 Review

    5
    (0)

    4
    (0)

    3
    (0)

    2
    (0)

    1
    (0)

    Write Review Here