Javatpoint Logo
Javatpoint Logo

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.


Token Generation

With each request a new CSRF token is generated. When object is created, name and value of the token are set.

The function for it is,

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.





Please Share

facebook twitter google plus pinterest

Learn Latest Tutorials


B.Tech / MCA