Cross-Site Request Forgery (CSRF)

What is CSRF?

Cross-Site Request Forgery (CSRF) is a type of attack that forces a logged-in user to perform unwanted actions on a web application. The attacker tricks the user into submitting a malicious request to the web application, which the application then executes as if it were coming from the legitimate user.

How does CSRF work?

There are two main ways that CSRF attacks can be carried out:

  • Image tag attack:

The attacker embeds an image tag on a malicious website that points to a URL on the victim’s web application. When the victim visits the malicious website, the image tag automatically loads the URL from the victim’s web application, which can trigger an unintended action.

  • Link attack:

The attacker sends a link to the victim that, when clicked, sends a malicious request to the victim’s web application. The victim’s browser automatically submits the request, which can trigger an unintended action.

Examples of CSRF attacks:

  • Unauthorized money transfer from a bank account
  • Data leakage of personal information
  • Password change
  • Change e-mail address
  • Unauthorized purchase of goods

How to prevent CSRF attacks:

There are several ways to prevent CSRF attacks, including:

  • Using CSRF tokens:

A CSRF token is a random string that is generated for each user. By including the CSRF token in every request, it becomes more difficult for an attacker to forge a malicious request.

  • Setting the SameSite attribute:

The SameSite attribute is a cookie attribute that restricts the scope of a cookie to a specific website or domain. By setting the SameSite attribute, it can help prevent cookies from being used in CSRF attacks.

  • Validating the Referer header:

The Referer header is an HTTP header that indicates the URL of the page that linked to the current page. By validating the Referer header, it can help detect malicious requests.

  • Checking the login status:

Before performing a critical action, verify that the user is logged in. Prevent users who are not logged in from performing critical actions.

Conclusion

CSRF attacks can be very dangerous for users. It is important to take steps to protect yourself from CSRF attacks by using the abovementioned prevention techniques.

References:

https://www.youtube.com/watch?v=7bTNMSqCMI0&t=102s