Kelseyi

Published

- 2 min read

What Is Cross Site Request Forgery (CSRF) and How to Prevent It

img of What Is Cross Site Request Forgery (CSRF) and How to Prevent It

Cross-Site Request Forgery (CSRF) occurs when attackers trick users into performing unintended actions on a website where they are already authenticated.

Similar to reflected XSS attacks, CSRF attacks often involve the attacker creating a malicious link or website designed to exploit the user’s active session. For simpler CSRF attacks targeting GET endpoints, attackers may not even need a separate website. They can inject malicious code or links directly into the target site.

CSRF Attack Example

For example, say a POST endpoint for money transfer may look like this:

   POST /transfer HTTP/1.1
Host: bank.com
Content-Type: application/x-www-form-urlencoded
Cookie: session_id=abc123

amount=10000&to_account=123456
   <form action="https://bank.com/transfer" method="POST">
    <input type="hidden" name="amount" value="1000">
    <input type="hidden" name="to_account" value="987654">
</form>
<script>
    document.forms[0].submit();
</script>

The malicious website will set up an invisible form which will be automatically submitted when users visit the site. For users that are authorized in bank.com, the POST endpoint will be called with their cookies sent along, making it looks like the users are calling the endpoint deliberately, transferring away money from their accounts.

Another simpler example exploiting a GET endpoint:

   GET /delete-account?confirmation=true HTTP/1.1
Host: vulnerable.com
Cookie: session_id=abc123

Attackers can find ways to include this link on their site or vulnerable.com:

   // create a link in comment section
<a href="https://vulnerable.com/delete-account?confirmation=true">Click me!</a>

// or imbed an image
<img src="https://example.com/delete-account?confirmation=true" />

How to prevent CSRF

In order to prevent hackers from exploiting our website vulnerabilities via CSRF, there are some safety precautions that can be implemented to mitigate these attacks.

  1. CSRF tokens

    CSRF tokens are generated by servers per request or per user session, and they should be unpredictable and unique for each generation. Whenever users make a request, the CSRF token acts as a hidden field that gets sent along, so servers are able to check if the request originates from a valid source, not from malicious website as in previous examples.

  2. Setting cookies

    Most requests that perform sensitive actions often require cookies, setting cookies to be SameSite=Lax or SameSite=Strict can prevent your browsers from automatically send out cookies when requests are made in malicious sites. See more about setting cookies in the prevention part on XSS attacks.

References

https://portswigger.net/web-security/csrf