Track 08 · Lesson 8 of 20Attacks and defenses

Track 08 · Attacks and defenses

Cross-site request forgery (CSRF)

Lesson 8 of 20· 7 min

Cross-site request forgery tricks a logged-in browser into doing something its user never asked for. Another site sends the request; your browser helpfully attaches your cookie; your server sees a valid session.

The free cruise

You’re logged in to your bank in another tab

bank.example · logged in as Ana

$5,000.00

Available balance

Your bank session cookie
The bank’s server also
  1. Open the page to watch the forged request.

🎉 You won a free cruise! (evil.example)

<!-- hidden on evil.example -->
<form action="https://bank.example/transfer" method="POST">
  <input type="hidden" name="to" value="mallory">
  <input type="hidden" name="amount" value="1000">
</form>
<script>document.forms[0].submit()</script>

Defenses, in layers#

  • SameSite=Lax or Strict on session cookies: the browser leaves the cookie off background requests from other sites.
  • CSRF tokens: a secret value in every form that other sites can’t read, so they can’t copy it.
  • Origin checks: refuse state-changing requests whose Origin header isn’t your own site.
  • Never change data with GET. Lax still sends cookies when someone follows a link.

CORS doesn’t help here: the forged request is sent whether or not anyone can read the answer.

The reverse: login CSRF#

Sometimes the attacker wants you logged in to their account. They send you their own email-verification or magic link; the page logs in whoever opens it; you then upload files or connect accounts that now belong to them.

In a code review

MediumFrontend

Login or verification that happens on page load

Fix: Show which account is affected and require a click; never silently replace a different signed-in user.

0 of 2 checked

Check yourself

Does a strict CORS policy stop CSRF?