PHP Security Tutorial: Cross-Site Request Forgery (CSRF) Protection

September 15, 2019 posted by


in this tutorial I will talk about cross-site request forgery attack and I’m going to show how you can protect your forms by using some simple hash functions in PHP hey what’s up guys in Senaid here from codingpassiveincome.com the place will help others to become other developer much easier and faster than they will do it on their own so if that is something that interests you consider subscribing now for some of you that don’t know cross-site request forgery is an attack by a malicious website will send a request to a web application that I user is already authenticated from a very different website this way an attacker can access functionality in a target web application we are the victims already authenticated browser targets include web applications like social media in browser email clients online banking and then interfaces for network devices this is a very simple explanation and I hope so that this explanation will give you the basic understanding what is cross site request forgery now let me show you how to import protection in PHP so now i’m here at my sublime text and i just create the normal index.php file so as you can see first we need to define some PHP code and i’m going to write here what we need to do so first thing that you need to do is we need to start a session after that we need to create a key for hash_hmac function after that we need to create this file token and the last thing that we need to do is we need to accept the information from the form that we will create in HTML and validate this token so we need to validate token okay so I’m going just to create some basic HTML form nothing special okey I’ll say he form method will be post and action will be index.php a which is this a file so just have one input type will be text name will be username username and the placeholder will be what is your name very simple it will have one hidden button we will store our CSRF token okay and we will have on submit botton okay so this is one very simple HTML form let’s now just see so and see we have two inputs one is here amongst our text and then press submit nothing happends you should already know this so now we need to start our session okay after that we want to see do we have already created our session so if we are not we will create new key that we will use for has_hmac function and I’m going to create by calling two functions first is binary to hex and there I lose random bytes and i will use 32 so as you can see this function will create 32 random bytes and this one will covert that bite into the hex format so we can see what you got by using this that’s it and it is we are saving this hash into the session because we want to be sure that our key is always the same or otherwise we won’t be able to validate our CSRF tokens that is inside the form okay now the next thing is we need to create our CSRF token will do that by doing by calling hash_hmac function the type of the encryption that I prefer to use is 256 for the data we can write any type of the string but what I usually do is I’ll write some string and at the end of that string I will append the name of the current file that helps me so that if I have 10 different files on every file I will have a different CSRF token so that we we have protected each time on the different way our form so i will write here this is some string and I will stay index PHP and we have created the key it’s stored inside the session so does say key and down below we need to output this CSRF token let’s now test it check this as you can see here we have our CSRF token which is a very long token and it’s almost not possible to get this string because we are using some very powerful functions that are available only in the PHP 7 version so the next thing is we need to validate token so first thing is we are going to do is if isset post submit which means this part of the code here will execute only if this button is pressed so here we need to verify our token I I can do something like this CSRF equal post CSRF but that is not good enough protection so I want to do and show you some better a bit I will use the function hash equals and it will compare those tokens still say just do something here ECHO your name is token failed ok so now let’s test this hash ok now let’s see here and summit your name is Senaid Vwhich means that our CSRF token is validated but if we manipulate this token and put something here that is not correct let’s say like this and try to submit okay CSRF token failed and as you can see if we don’t have the correct CSRF token we will never execute this part of the code which is extremely important and on this way our form is protected so guys I hope so that this is very simple tutorial and there really isn’t a lot to learn so just you need to learn how to properly create key and also how to create the proper hash and validate that hash so there are just four different functions that you need to know so if you guys like this video please like it and share your friends and also if you have any questions I will be more than happy to answer it in the comments below take care

37 Comments

37 Replies to “PHP Security Tutorial: Cross-Site Request Forgery (CSRF) Protection”

  1. Kevin1003 says:

    Thank you sir!

  2. DA IG says:

    Great tutorial. Thanks Senaid.

  3. Lucian Constantin Nutu says:

    Very good, I learn a lot form your videos

  4. Lucian Constantin Nutu says:

    thank you

  5. John Rhey Boc says:

    Thank you 🙂

  6. John Rhey Boc says:

    can i use this via ajax?

  7. The Raider says:

    Sorry sir, //start session //create a key for hash_hmac function //create csrf token //validate token.
    Where do i write down these code in MVC ?

  8. Benito Esteban says:

    Hello thanks for the tut, I would like to ask you to zoom the screen for future tutorials

  9. Saad says:

    Great Tutorials With Great Explanation …………… Thanks Alot Senaid Sir

  10. Alvin Aliñabon says:

    lodi. simple and direct.

  11. teo says:

    i realy thank you bro, totaly helpful

  12. Mahmoud Samy says:

    Thank you very much

  13. Mail Master says:

    What's is uses…How attacker attack without this?

  14. Taras Chernata says:

    can I use this code for ajax ?
    for example: I have index.html and there're I have ajax request which is done by Jquery, my url for php is another file (send.php)

  15. spicytuna08 says:

    why put html and php code on the same page? if you put it separate pages, would it work?

  16. Santosh T says:

    <?php

    session_start();

    if (empty($_SESSION['key'])) {$_SESSION['key'] = bin2hex(openssl_random_pseudo_bytes(32)); }

    $csrf = hash_hmac('sha256','this is some string: test.php', $_SESSION['key']);

    if(isset($_POST['submit'])) {

    if(hash_equals($csrf, $_POST['csrf'])) {

    echo $regno1=$_POST['regno1'];

    echo "<script type='text/javascript'>alert('Insert Successfully!');window.location.href='test2.php';</script>";

    }

    else {

    echo 'CSRF Token Failed';

    }

    }

    ?>

    <form method="post" action="test2.php" >

    <input type="text" name="regno1" id="regno1" />

    <input type="hidden" name="csrf" value="<?php echo $csrf; ?>" />

    <input type="submit" name="submit" value="SUBMIT" />

    </form>

    once submit CSRF Token Failed. Pls kindly rectify the problem sir

  17. First Mill says:

    This was simple yet powerful. Thank you.

  18. Rest In Peace Bukan Channel Gaming says:

    amazing.. this video helps me so much. cheers dude

  19. MARCHING BAND PH TV says:

    More security More power Good Tutorial 😎😎 I learned alot

  20. AdiL IsmaiL says:

    Which LAPTOP

  21. CoutchPotato1981 says:

    Hi Senaid, big thanks for this tutorial and sharing informations.

    I have problems to understand the technic behind this method. After every page refresh the token is always the same. An attacker just need to visit the page and copy the token from the sourcecode into his faked form with hidden attribute, token name and token value. As long as the same session exists (max. 24 hours or until the browser was closed) he could use this token again and again to fire requests to my site.

    Does it make sense to generate a new token on every refresh and the token is available just for one request. Is this more safe?

    Best regards!

  22. piano0011 Lee says:

    This looks great! I thought that it would be good enough to use htmlspecialchars and strip_tags but I didn't know that I have to use this! I have an undefined$csrf error but then I am trying to post it to another page…..

  23. piano0011 Lee says:

    I also don't know why I got a failed for my $csrf value…. How do you get this to work when sending a form to another page?

  24. piano0011 Lee says:

    I finally got it to work whey trying out your code on its own but now I need to figure out where it goes in my login form…. I have two forms on my main page, I don't know where to add it… I also followed what you did at the end of the tutorial by changing the session value to check to see if it is working and I got it to work… It said failed when I have the wrong token but how would I set it back to the real token to make it true?

  25. Arpit Jain says:

    Very easy tutorial, Helps me so much. Thank You 🙂

  26. Michael Gonzalez says:

    the best tutorial for me so far, greetings from mexico .

  27. owais ahmed says:

    how can we expire csrf token?

  28. Jon Schneider says:

    I don't understand how it is secure if the user can just do an inspect element and see the token?

  29. Trivedi Akshay says:

    Very nice video sir

  30. Fedja Misirlic says:

    Hvala! Jako koristan tutorial!

  31. Premier Advertising & Media Ltd Kampala says:

    Coding Passive. You guy ur the best in this thing. i salute u bro

  32. Mervin Lee says:

    Is there a way to append the $csrf variable to the form action? such as something like this? <form class="signup-form" action="includes/signup2.php?'.$csrf.'" method="POST">
    <label>First name:</label> But my url looks weird: csrf=%27.$csrf.%27

  33. m.nageh says:

    any help in this ?

    https://www.quora.com/unanswered/How-I-can-manually-login-to-HG-router-using-curl

  34. m.nageh says:

    but simply anyone can grab the value from the response text of the http request !!

  35. Mail Master says:

    How I achieve this in ajax jquery. ??

  36. J G says:

    Is it really necessary to use the pepper? h_mac?

  37. Ptmp727 says:

    Great Video again, excellent explanation, But I am so confused over this, how does an attacker get access on the website in the first place? Apart from sending a dodgy email to someone

Leave a Comment

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