Cross-Site Request Forgery (CSRF)

Cross-Site Request Forgery (CSRF) is an attack that forces authenticated users to execute unwanted actions on a web application. Since browsers automatically include session cookies with requests, attackers can forge requests that the server cannot distinguish from legitimate ones.

How It Works

The attacker hosts a malicious page that makes requests to a target site. When an authenticated victim visits this page, their browser automatically includes cookies, making the forged request appear legitimate to the server.

Example

Malicious page that changes a user's email:

<!-- Attacker's page -->
<html>
<body>
  <img src="https://bank.com/transfer?to=attacker&amount=10000">

  <!-- Or using a form for POST requests -->
  <form action="https://bank.com/transfer" method="POST" id="csrf">
    <input type="hidden" name="to" value="attacker">
    <input type="hidden" name="amount" value="10000">
  </form>
  <script>document.getElementById('csrf').submit();</script>
</body>
</html>

Prevention

  • CSRF Tokens: Include unpredictable tokens in forms/requests
  • SameSite Cookies: Set SameSite=Strict or SameSite=Lax
  • Check Origin/Referer: Verify request origin headers
  • Custom Headers: Require custom headers that can't be set cross-origin
  • Re-authentication: For sensitive actions, require password confirmation

PentesterLab Exercises

See Also