Cross-Site Request Forgery (CSRF)

 

What is Cross-Site Request Forgery (CSRF)?

CSRF (Cross-Site Request Forgery) is an attack where a malicious website tricks you into performing actions on a website you're already logged into, without your knowledge. It takes advantage of the fact that your browser automatically sends your login cookies or session tokens with requests, even if you didn’t mean to make them. e.g. Suppose the user logged in to https://my-bank.com in your browser Now the attacker will send you a fake website URL https://myshop.com Where there will be a button : Click here to get the best offers on branded products But there is a hidden request that the attacker has attached on click of the button that request goes to https://my-bank.com/debit?from=34343434&to=434434343&amount=10000 As the request is made cookies will be sent automatically with this request and if the mybank.com server depends only on cookie then it will give success to this request which was made internally in the https://myshop.com So this way user will become victim of CSRF attackHow CSRF Works

  1. The Scenario:

    • A user is logged into a website (e.g., a banking app at https://my-bank.com) and has an active session (cookies are stored in their browser).
  2. The Vulnerability:

    • The website performs sensitive actions (like transferring money) through HTTP requests that depend only on the session cookies or authentication tokens, without requiring additional user confirmation.
  3. The Attack:

    • An attacker tricks the user into making an unwanted request (like transferring money) by embedding a malicious request in a different website or email.

Step-by-Step Example of a CSRF Attack

1. The Victim's Situation

  • The victim logs into their online bank at https://my-bank.com.
  • The bank uses cookies to maintain the user’s session. For example:

    Set-Cookie: session_id=abc123; Secure; HttpOnly;
  • The victim’s browser automatically includes these cookies with every request to https://my-bank.com.

2. The Vulnerable Action

  • The bank allows money transfers using an HTTP POST request like this:

    POST /transfer HTTP/1.1 Host: my-bank.com Content-Type: application/x-www-form-urlencoded amount=5000&to_account=123456
  • The request relies only on the user’s authenticated session (via cookies) to verify the user.

3. The Attacker's Setup

  • The attacker creates a malicious website (e.g., https://attacker-site.com) and embeds a hidden form:

    <form action="https://my-bank.com/transfer" method="POST"> <input type="hidden" name="amount" value="5000"> <input type="hidden" name="to_account" value="123456"> </form> <script> document.forms[0].submit(); </script>
  • When the form is submitted, the browser includes the victim’s cookies for https://my-bank.com automatically.

4. The Victim is Tricked

  • The victim visits the malicious site (e.g., by clicking a link in an email or ad).
  • The browser submits the hidden form to https://my-bank.com using the victim’s session cookies.

5. The Attack Happens

  • The bank processes the request as if it came from the victim, transferring $5000 to the attacker’s account.

Why CSRF Happens

  • Trust in Cookies: Browsers automatically send cookies with requests to the associated domain, even if the request originates from another site.
  • No Verification: The server performs actions based solely on the presence of session cookies, without verifying the user’s intent.

Vulnerabilities of CSRF

  1. No CSRF Tokens:

    • If a website doesn’t include unique, user-specific tokens in requests, it can’t verify whether the request is legitimate or forged.
  2. Same-Site Cookies Not Enabled:

    • If cookies don’t have the SameSite attribute set, they are sent with cross-origin requests.
  3. No User Confirmation:

    • Sensitive actions (e.g., money transfers, account deletions) are executed without requiring user confirmation.
  4. No Referrer/Origin Validation:

    • The server doesn’t check whether the request originated from a trusted source.

Preventive Methods for CSRF

1. Use CSRF Tokens

  • Add a unique token to every form or API request.
  • The server checks the token against the user’s session to ensure the request is legitimate.
  • Example:
    • When rendering a form:

      <form action="/transfer" method="POST"> <input type="hidden" name="csrf_token" value="abc123"> <input type="text" name="amount" placeholder="Amount"> <input type="text" name="to_account" placeholder="Account Number"> <button type="submit">Transfer</button> </form>
    • On submission, the server validates the token:

      if (req.body.csrf_token !== session.csrf_token) { return res.status(403).send('Forbidden'); }

2. Enable Same-Site Cookies

  • Add the SameSite attribute to cookies to prevent them from being sent with cross-origin requests:

    Set-Cookie: session_id=abc123; SameSite=Strict; Secure; HttpOnly;
    • SameSite=Strict: Cookies are never sent with cross-site requests.
    • SameSite=Lax: Cookies are sent only for safe requests (GET, HEAD).

3. Verify Referrer or Origin Headers

  • Check the Origin or Referer header in incoming requests to ensure they come from trusted sources.
  • Example in Express.js:

    if (req.headers.origin !== 'https://my-bank.com') { return res.status(403).send('Forbidden'); }

4. Require User Confirmation

  • For sensitive actions, add an extra confirmation step (e.g., a CAPTCHA or confirmation dialog).
  • Example:
    • Before transferring money, ask for a PIN or OTP sent to the user.

5. Use Content Security Policy (CSP)

  • Set a CSP to restrict resources from untrusted origins, reducing the risk of malicious scripts submitting forms.

    Content-Security-Policy: default-src 'self'; form-action 'self';

How Preventive Methods Work Together

  • CSRF Tokens ensure that the request is intentionally submitted by the user.
  • Same-Site Cookies prevent cookies from being sent with requests from untrusted sites.
  • Referrer/Origin Validation ensures requests originate from your website.
  • User Confirmation adds an additional layer of security for critical actions.

Comments

Popular posts from this blog

JavaScript Must-Read Topics for Senior Developer Interviews

React.js Topics for a Mid-Senior Level Developer Interview Preparation

Recursive selection sort