Apply CSRF in the php application to prevent CSRF attacks

apply-csrf-in-the-php-application-to-prevent-csrf-attacks

Now a days, it is very important to implement secure an application form CSRF attacks. In this article we will apply CSRF in the php application to prevent CSRF attacks.

What is CSRF?

CSRF stands for Cross-site request forgery. It is a type of malicious exploit of a website where unauthorized commands are submitted from a user that the web application trusts. A CSRF token is a unique, unpredictable value that is generated by the server-side application and transmitted to the userin such a way that it is included in the HTTP request made by the user.

How to prevent CSRF attacks?

The CSRF attacks can be prevented by generating a security token at the server-side. This security token will then be verified when a form is submitted (or when a request is made). There is a term called as “origin policy”, it is important to keep the same origin policy. If the origin policy is same the attacker can’t even read the response that contains the token.

Let’s apply CSRF in the PHP application to prevent CSRF attacks

There are many ways to implement CSRF in the PHP application, so lets try an implementation using PHP session functions.

When using sessions we first have to start it using code below:

<?php
  session_start();
?>

Now, in the login process when the user credentials are authenticated you need to generate a unique, secure string and store in the session variable.

Add the following code to create a unique random string:

<?php
  $random_token = bin2hex(random_bytes(32));
  $_SESSION['csrfToken'] = $random_token;
?>

We have the unique string generated at server side which a hacker can not get while generating an attacking attempt.

The next step is to pass this string with the form as hidden field, the markup is:

<input type="hidden" name="csrfToken" value="<?php echo $_SESSION['csrfToken']; ?>" />

Now, we have to verify the generated string on the form process page to make sure the incoming request is from the “same origin”. The PHP code is:

<?php
  if (!hash_equals($_SESSION['csrfToken'], $_POST['csrfToken'])) {
    echo 'Error! CSRF attack detected';
    // redirection to access denied page or any other logic
    exit();
  }
?>

If token is not validated the form will not process, so in this way a hacker may send the request but the server will discard.

So, the application now prevent the CSRF attacks.

Related Posts