PHP: Adding CSRF protection is super easy!

Published on Author YaniLeave a comment

Adding CSRF protection to a PHP script is really easy once you understand how and what it should be doing. You can look at CSRF protection like a pre-filled captcha, which adds a layer of protection as it can’t just be generated by somebody and match the one we have on the server.

I have written a class that makes it even easier. The only thing that’s really happening is that we’re making a token and putting it in a session. We then put the token in a hidden input in the form, so it gets sent in our POST request. Because the token is in the session, we just have to check if the posted token matches the one in our session.

This whole method of protection is called CSRF protection, as it makes it for attackers a lot harder to submit a form in the background, as they will have to send the correct token with it.

 

Here’s a very simple class that should work perfectly fine in every situation.

class CSRF
{
    public function __construct(){
        if(!session_id())
            session_start();
    }
    public function create()
    {
        return $_SESSION['csrf'] = substr(sha1(microtime() . session_id()), 0, 12);
    }
    public function verify()
    {
        if (isset($_POST['csrf']) && isset($_SESSION['csrf'])
        && is_string($_POST['csrf']) && $_POST['csrf'] == $_SESSION['csrf']) {
            return true;
        } else {
            return false;
        }
    }
    public function __toString()
    {
       return '<input type="hidden" name="csrf" value="' .$this->create(). '" />';
    }
}

 

The usage is very simple. In your login logic, you would just have something like this:

$csrf = new CSRF();

if(!$csrf->verify()){
  die('Invalid CSRF token');
} else {
  // Do login
}

 

An then in your form, you can simply add the hidden input like so:

echo $csrf;

 

And that’s it, your form is now protected from CSRF and it was super easy.

Enjoy!

 

Oh and I have also made a gist of this scrip, in case you want to push some updates:
https://gist.github.com/Yanikore/3431941ac9489f367bfe1c89de10d6a0

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *