Complete Guide to CSRF Attacks: For Custom Coders

In this article, we’ll dive into a critical web application vulnerability known as CSRF (Cross-Site Request Forgery). If you’re new to cybersecurity, don’t worry, I’ll break down the concepts into pieces.

Before we begin, it’s essential to note that this article is especially for custom-coding users!

What is CSRF?

CSRF, or Cross-Site Request Forgery, is a vulnerability that allows an attacker to perform unintended actions without the user’s knowledge.

Scenario Breakdown

Let’s consider a web application with database interaction. In this scenario, every logged-in user can update their password and manage privacy settings.

But what if someone attempts to edit another user’s password without their knowledge? If this happens, it can turn into a nightmare.

Image Explanation

To illustrate, let’s break down how an attacker could exploit this vulnerability:

1. Forging a URL:

• The attacker forges a URL with the vulnerable site’s address.

2. Sending the Forged Link:

• The attacker sends the forged link to a legitimate user who is already logged in.

3. Executing the Attack:

• When the user clicks the link, it triggers an update request to the website’s server. As the legitimate user is logged in, the server processes the request, inadvertently changing the user’s password.

That’s how an attacker could successfully execute a CSRF attack on a web application.

What steps you can take to prevent CSRF attacks from happening?

1. Use an Anti-CSRF system

2. Always use SameSite Cookies

Let’s break down those 2 steps.

• Anti-CSRF system is used to verify the legitimacy of the logged-in user. So only the logged users can make the changes.

Let’s have a look at how a CSRF system can be implemented using PHP!

//Start the session before anything.  It's always a good practice. 

session_start();
// This if condition checks whether a SESSION named csrf_Token already exists or not. If not it'll create one. 

if (!isset($_SESSION['csrf_Token'])) { 

     

    //  This will generate a hex string with a value of 32 bits 

    $_SESSION['csrf_Token'] = bin2hex(random_bytes(32)); 

}

Now this part is where it’s going to check the values.

// catch the post request named update 

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

  

   // getting the form values 

    $username = $_POST['username']; 

    $password = $_POST['password']; 

    $csrf_token = $_POST['csrf_Token']; 

  

    //Comparing the csrf value with the current csrf session 

    if($_SESSION['csrf_Token'] !== $csrf_token){ 

  

        // value is not the same 

  

        echo "Token is invalid!"; 

        // unseting the CSRF session will generate a new value for each request. 

        unset($_SESSION['csrf_Token']); 

        exit(); 

    }else{ 

         

        // process the data 

        unset($_SESSION['csrf_Token']); 

        exit(); 

    }

With the code example above, you should be able to create a CSRF system.

Let’s jump to the SameSite section.

SameSite cookies play a significant role in controlling cookie behavior by restricting their accessibility to a defined set of parties based on certain options. These options, namely ‘Strict,’ ‘Lax,’ and ‘None,’ allow us to manage how cookies are sent with cross-site requests.

1. Let’s see how 'SameSite=Strict' works

Cookies with ‘SameSite=Strict’ will only be sent in a first-party context. This means cookies will only be sent if the request comes from the origin server

Handy for:

• Sensitive actions or user authentication-related cookies where you want to ensure the request comes directly from your site.

Let’s have a look at an image explanation of ‘SameSite=Strict’:

2. Let’s see how 'SameSite=Lax' works

Cookies with ‘SameSite=Lax’ attributes are more flexible than ‘SameSite=Strict.’ For example, when a user clicks on a link that takes them to another website, cookies with ‘SameSite=Lax’ will be sent with that request.

Handy for:

• Most scenarios where you want a balance between security and usability. It prevents CSRF attacks in many cases while allowing cookies for user-friendly interactions.

Let’s have a look at an image explanation of ‘SameSite=Lax’:

However, cookies set with ‘SameSite=Lax’ will not be shared if the request is a cross-site POST request.

3. Let’s see how 'SameSite=None' works!

If you set cookies with ‘SameSite=None’, cross-server requests can have access to your cookies. However, If you are using ‘SameSite=None’ make sure to use the ‘Secure’ attribute to ensure that the cookies are only sent over secure (HTTPS) connections.

Handy for:

• When you need to support cross-origin requests, such as embedding resources from your site on other secure sites, such as (loading images or scripts from your site).

Why use Secure for ‘SameSite=none’?

• Without the ‘Secure’ attribute, a cookie with ‘SameSite=None’ could be vulnerable to interception in transit, if the connection is not encrypted.

Conclusion:

With the above information, you now have a comprehensive understanding of how CSRF attacks can be executed and, more importantly, how to defend against them. Regularly testing and updating your site is a best practice for maintaining a robust defense against evolving security threats. Remember, CSRF protection is just one layer of your web application’s security. Stay connected with the flow, keep a good knowledge of new techniques and best practices, and continuously enhance your security measures to safeguard your users and data.

You can always use InfinityFree to host your sites for free and test them.

Thank you for the precious time you’ve put into reading this. Have a wonderful day!

11 Likes

Great guide! Can recaptcha work as an anti csrf measure for forms? I believe attackers can’t forge a recaptcha token from a remote site.

1 Like

I think so, yes.

ReCaptcha has a settings where you can whitelist specific websites where they CAPTCHA may be hosted. If you have that setup correctly so the CAPTCHA widget is only allowed on your own website, it should be pretty safe against cross site requests.

5 Likes