blog posts

CSRF

What is Csrf Token in Laravel?

The popular Laravel framework, while being simple, has many tips and details that require careful and time-consuming learning. One of the important points in the security discussion is CSRF protection in Laravel, which protects web applications against Cross-Site Request Forgery attacks. Knowing this type of attacks and ways to deal with them is one of the important things that every Laravel programmer should be aware of.

If you are a Laravel programmer or have a website and you don’t want your website to be damaged by a CSRF attack in Laravel, Learn’s programming training website until the end of this article. stay with Son

What is a CSRF attack?

CSRF stands for Cross-Site Request Forgery, which means forging a request through a site. CSRF is a security hole on the web that allows an attacker to trick users into doing things they don’t intend to do. This attack allows an attacker to bypass policies designed to prevent different websites from interfering with each other. For example, assume that users of the google.com website will delete their browser cookies by entering the google.com/logout address and log out. Now, if one of the users on another site (for example, in a busy forum) sends an image with the following img tag and other people in that forum see this image, a request is sent to the Google site from their browser and it causes everyone to Those who have seen that image will be kicked out of their Google account.

< img  src = "https://www.google.com/logout/"  alt = ""  /> 

Of course, this example was a simple and non-dangerous one. There are other very dangerous situations.

How does CSRF work?

CSRF makes web applications unable to distinguish between valid requests and forged requests controlled by an attacker. There are many ways an attacker can try to exploit a CSRF security hole. In the following, to better understand this type of attack, we will describe how CSRF attacks are done in Laravel with an example.

Let’s say someone named Bob has an online bank account at samplebank.com. He visits this site regularly to conduct his transactions. Bob doesn’t know that samplebank.com is vulnerable to CSRF attacks. Meanwhile, an attacker plans to use this security hole to transfer $5000 from Bob’s account to another account.

To successfully perform this attack:

  • An attacker must create an exploit URL.
  • The attacker must trick Bob into clicking on the exploit URL.
  • To login and work with the account, Bob needs an active session on samplebank.com.

Next, Bob sends a GET request to transfer money on the bank’s website. In this way, the request to transfer 500 dollars to another account (with account number 213367) may be as follows:

GET https: //samplebank.com/onlinebanking/transfer?amount=500&accountNumber=213367  

As we said earlier, an attacker would need to create a malicious url to transfer $5,000 to account 425654 in order to successfully conduct a CSRF attack.

https: //samplebank.com/onlinebanking/transfer?amount=5000&accountNumber=425654 

Consider the case where the img tag is used. In this case, the attacker sends Bob an email containing an image. Upon receiving it, Bob’s browser will open the url in the img tag automatically. As a result, without Bob’s intervention, the unwanted request is sent to the bank’s website. If Bob has an active session on samplebank.com. The site recognizes this url as a money transfer request from Bob, and then the desired amount is transferred to the account specified by the attacker.

 

However, note that there are some limitations for a successful CSRF attack. Including:

  • This attack will be successful only if the user has an active session on a vulnerable website.
  • An attacker needs to find a valid url to manipulate it with malicious intent. The desired url is required to change the status on the target site.
  • Finally, the attacker must find the appropriate values ​​for the url parameters. Otherwise, the target website may reject the malicious request.

What is CSRF Protection?

 

Laravel provides an easy solution called CSRF Protection to protect against CSRF attacks. CSRF protection in Laravel is such that for each active user in the application, the program generates a CSRF token. This token is used to confirm whether the request being sent is from a real person or not.

Whenever you create an HTML form on the page, identified by the <form> tag, you must include the CSRF token inside it, so that Laravel’s CSRF protection can validate the request. If you do not do this, your request will be failed or rejected. To do this, just put @ CSRF in your form tag. Like the following code:

< form  method = "POST"  action = "/profile" >   
  @csrf    
...
 </ form > 

The VerifyCsrfToken middleware, located in the web middleware group, automatically verifies whether the token in the request matches the token stored in the session.

Preventing CSRF attacks in PHP

In the following, we will introduce some methods to prevent such damages in php.

Prevent CSRF attacks in Laravel by checking page headers

This can help prevent CSRF attacks. If the request is sent from another domain, this request must be fake, so it should be blocked.

Preventing CSRF attacks in Laravel by validating captcha in forms

Captcha verification is a good way to prevent CSRF attacks on forms. Initially, the CAPTCHA verification process was created to prevent bots. But in addition, captcha can be used to prevent CSRF attacks. Since the captcha is randomly generated on the user side, the attacker cannot guess the pattern. So he will never be able to send the correct captcha with the fake request and all fake requests will be blocked. Note that this method is not very user-friendly. Most users don’t like to fill a lot of captchas on the website so we should try to find ways to prevent CSRF without adding extra burden on users.

Preventing CSRF attacks in Laravel using tokens

Using tokens is the safest way to prevent CSRF attacks. Unlike captcha, this method has nothing to do with users, so users will never know that something has been added to protect them. In this method, the website generates a random token in each form as a hidden value. This token is associated with user session. After the form is submitted, the website checks whether a random token is provided by the request. If the answer is positive, the correctness of the token is checked.

Using this method, developers can easily identify whether the request was made by an attacker or not. For example:

[html] </ pre > 
< form  action = "accountdelete.php"  method = "post" > < input  type = "hidden"  name = "CSRFToken"  value = "OWY4NmQdwODE4hODRjN2DQ2NTJlhMmZlYWEwYzU1KYWQwMTVhM2JmLNGYxYjJiMGI4jTZDE1ZDZjMTViMGYwMGEwOA=="  /> </ form > 
< pre > 
[/html]
 

What is CSRF token?

The CSRF token is a unique, secret and unpredictable value that is generated by the application on the server side and included in each user request. When the user’s request is submitted, the application on the server side confirms that this request contains the expected token, if it does not exist or is invalid, the application rejects the request. The effectiveness of the token depends on the way it is generated, so always try to generate the token in a way that is unpredictable.

You can use the following code to generate a token.

$randomtoken  = md5(uniqid(rand(),  true )); 

Or

$randomtoken  = base64_encode( openssl_random_pseudo_bytes( 32 )); 

After the user enters and creates a login session, create randomgtoken$ and add it to the session.

$_SESSION [‘csrfToken’]= $randomtoken 

Also, for each form, add the following hidden tag.

< input  type = ’hidden’  name = ’csrfToken’  value = ' <?php  echo ( $_SESSION [‘csrfTOken’])  ?> ’ /> 

CSRF token is unique for each session. In each new session, the token is created again. You can also use a single token for all forms, but it is safer to use different tokens. In the following, we will introduce some classes and open source php library to protect against CSRF attacks. These include:

Protect against CSRF attacks using the NoCSRF class

NoCSRF is a simple anti-CSRF class that generates tokens. You can also learn how to implement this class on your website by using the many simple examples   account in the NoCSRF GitHub .

Protecting against CSRF attacks using the csrf class by Skookum

csrf by Skookum   is another php class for CSRF protection . This class is free and available to everyone. You can copy and use it in your web application.

Protection against CSRF attacks using the anticsurf library

anticsurf is one of the small php libraries that can be used to prevent attacks in web applications. This library claims to be a strong defense against these types of attacks. It also uses a one-time token that has a time limit. by visiting the anticsurf site. You can download it and get more information

How to create a CSRF attack?

Manually building the HTML required for a attack can be time-consuming. Especially in cases where the desired request has a large number of parameters or there are other items in the request. The easiest way to create a CSRF attack is to use the PoC generator toolset (a tool for easier attack design) included in the Burp Suite Professional .

Follow these steps to create a CSRF attack:

  • Select any type of request you want to test in Burp Suite Professional.
  • Click on the right menu and select Engagement tools / Generate PoC.
  • Using Burp Suite you can create HTML that triggers selected requests (minus cookies, which are automatically added by the victim’s browser).
  • To fine-tune different aspects of the attack, you can change various options in PoC generato.
  • Finally, copy the generated html into a web page. Then view it in the browser where the vulnerable website was opened. After that, check whether the desired request was made successfully or not.

Disable CSRF on specific routes in Laravel

Sometimes, depending on the situation, we need to disable in Laravel in some specific paths. For this, we go to the VerifyCsrfToken file through the following path.

\App\Http\Middleware\VerifyCsrfToken 

In this class, there is an except$ array. To disable on certain routes, just put the desired url in this array. After doing this, the target routes are excluded from CSRF checking in Laravel.

Why should we use CSRF Protection in Laravel?

In this article, we tried to fully describe attacks, how they work and how to prevent such damage. Note that this security hole is one of the serious damages of the website, which can be very dangerous and destroy a business overnight if security measures are not followed. If you use Laravel, you can easily prevent such attacks by using Protection in Laravel.