OWASP 2013 A8: Cross-Site Request Forgery
Your user is logged in. Any other page they open can act as them.
Cross-Site Request Forgery (CSRF) is a security vulnerability in which another website makes a logged-in user’s browser send a request to your application, and your application obeys it as if the user meant it. It is number eight on the 2013 OWASP Top 10, the list of web application risks published by the Open Web Application Security Project (OWASP), and it is the quietest bug on the list. There is no payload in your database, no script in your page, nothing in your logs that looks wrong. The forged request is identical to a real one, because the browser built it the same way it builds every request: with the user’s cookies attached.
That is the whole problem. When a browser sends a request to your site, it attaches your cookies, no matter which page caused the request. A page on another domain can make the user’s browser send a fully authenticated request to your application. Your server sees a logged-in user doing something they are allowed to do, and obeys.
What the bug is, in plain words
A cookie is an access badge. Once your site hands a browser a session cookie, the browser shows that badge on every request back to your site until the cookie expires. It does not check who asked for the request. A form on evil.example, an image tag, a bit of JavaScript: all of them can aim a request at bank.example, and the browser will staple the bank.example session cookie to it on the way out.
So if your application changes state based only on “is this user logged in,” an attacker who can get your user to open a web page can perform that change as the user. Transfer money. Change the account email, then request a password reset to the new address. Add an admin. Delete a record. The attacker never sees the response, and does not need to. The action is the goal.
CSRF works on actions, not reading. The attacker cannot read the reply: the same-origin policy, the browser rule that stops one site from reading another’s responses, blocks that. But it does not stop the request from being sent and acted upon. CSRF lives in that gap, so it targets anything that writes.
How the attack works, step by step
Here is a transfer endpoint that trusts the session and nothing else.
POST /transfer HTTP/1.1
Host: bank.example
Cookie: session=9f3c... (sent automatically by the browser)
Content-Type: application/x-www-form-urlencoded
to=12345&amount=25
The attacker wants the user’s browser to send that same request, with their own account as to. They put this on any page the user might open, including a page they control or a comment field that renders HTML:
<form id="f" action="https://bank.example/transfer" method="POST">
<input type="hidden" name="to" value="99999">
<input type="hidden" name="amount" value="5000">
</form>
<script>document.getElementById('f').submit();</script>
The user opens the page. The form submits itself on load. The browser sends a POST to bank.example with the hidden values and, because the destination is bank.example, the user’s bank.example session cookie. The transfer goes through. The user saw a blank page, or an ad, or a cat.
No cookie is stolen. No script runs on your site. The request came from the real browser of the real, logged-in user. This is why CSRF is called a “confused deputy”: the browser acts on your user’s authority, and the attacker confuses it into acting for them.
Real cases
Home routers, 2007 to 2008. The most damaging early CSRF was not against a website at all. Home routers have a web admin panel on the local network, and most owners never change the default password. In 2007, researchers published CSRF flaws in 2wire gateway routers (CVE-2007-4389): a forged request could create DNS mappings as the administrator, which lets an attacker point the victim’s bank.example lookups at a server of their choice. This is pharming: poison the name resolution and every device on that network goes to the fake site. In January 2008 a security firm reported the first such attack seen in the wild: Spanish-language greeting card emails sent in Mexico carried an image tag that, when the message was opened, sent a request to the reader’s 2Wire router and changed its DNS settings, so the address of one of the country’s largest banks led to the attacker’s copy. The same year, a related technique combined Adobe Flash and Universal Plug and Play to change the primary DNS server on a range of home routers through a forged request (CVE-2008-1654). The user did nothing but open a page. The root cause was a router that accepted state-changing requests with no proof the admin intended them.
uTorrent, 2008. WebUI, the browser interface for the uTorrent download client, had a CSRF flaw (CVE-2008-6586): a forged request could make the logged-in user’s client download a torrent file chosen by the attacker, through the add-url action, or change its settings, including the administrator account, through setsetting. A page the user merely opened could drive the client. A desktop application with a local web interface is a web application, and it had the same hole as any website: it acted on a request without checking that its own interface sent it.
Both share the root cause of every CSRF bug: the server acted on the session alone, which the browser attaches for free, and never checked that the request came from its own pages.
Why the common fixes fail
Developers reach for several defenses that feel right and do nothing. Each is worth understanding, because each is a trap I still find in production.
“We use POST, not GET.” The self-submitting form above is a POST. Changing the method changes nothing; the browser will build a POST across origins just as happily as a GET. GET is worse, because a bare image tag triggers it, but POST is not safe.
“The request needs our session cookie, and the attacker does not have it.” They do not need it. The browser has it and sends it for them. This is the single most common misunderstanding of CSRF. A secret in a cookie is attached to the forged request automatically, so it protects nothing.
“It is a multi-step form.” The attacker scripts each step in order, submitting one hidden form after another. Wizards are not a defense.
“We check the Referer header and require it to be our domain.” Closer, but fragile as a sole defense. Browsers and privacy tools strip the Referer, and many legitimate requests arrive with it blank. If you reject blank Referers you break real users; if you allow blank Referers you have left the door open for any attacker whose page suppresses it. It is a useful layer, not a lock, and most useful under HTTPS, where proxies cannot strip it in transit.
“We serve everything over HTTPS.” HTTPS stops someone reading the traffic. It does nothing about a forged request, which is encrypted exactly like a real one.
The defense that ends it: a synchronizer token
The fix is to require, on every state-changing request, a secret that the browser will not attach on its own and the attacker cannot read. That secret is a CSRF token, also called a synchronizer token. It works because of the same-origin policy: your server puts a random token into each form, a real form carries it back, and an attacker’s page cannot read your form, so it cannot learn the token or include it. The forged request arrives without it, and you reject it.
Three rules make a token safe, and each is a place I have seen it done wrong:
-
The token must be unpredictable. Generate it from a cryptographically secure random source, not from
rand(), a timestamp, or a hash of the username. If the attacker can compute it, it is not a secret. -
The token must not ride in a cookie alone. If the only copy of the token is in a cookie, the browser attaches it to the forged request for free, and you are back where you started. The token has to travel somewhere the attacker’s page cannot reach: a hidden form field or a request header, checked against a copy held in the server session.
-
The comparison must be constant-time. Compare the submitted token to the expected one with a function that does not return early on the first wrong byte. A plain
==can leak the token one byte at a time through timing. PHP, Python and Java ship a constant-time compare in their standard libraries, and the major frameworks carry their own; use it.
PHP, done by hand
Vulnerable handler
<?php
session_start();
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Trusts the session only. Any page on the web can trigger this.
transfer($_SESSION['user_id'], $_POST['to'], $_POST['amount']);
}
Fixed handler, with token generation and a safe check:
<?php
session_start();
// Generate once per session, from a secure source.
function csrf_token() {
if (empty($_SESSION['csrf'])) {
$_SESSION['csrf'] = bin2hex(openssl_random_pseudo_bytes(32));
}
return $_SESSION['csrf'];
}
// Reject anything whose token is missing or wrong, in constant time.
function check_csrf() {
$sent = isset($_POST['csrf']) ? $_POST['csrf'] : '';
if (empty($_SESSION['csrf']) || !hash_equals($_SESSION['csrf'], $sent)) {
http_response_code(403);
exit('CSRF check failed');
}
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
check_csrf();
transfer($_SESSION['user_id'], $_POST['to'], $_POST['amount']);
}
The form puts the token in a hidden field, where the attacker’s page cannot read it:
<form action="/transfer.php" method="POST">
<input type="hidden" name="csrf" value="<?php echo htmlspecialchars(csrf_token(), ENT_QUOTES, 'UTF-8'); ?>">
<input name="to">
<input name="amount">
<button>Send</button>
</form>
openssl_random_pseudo_bytes gives you unpredictable bytes. hash_equals, available since PHP 5.6, compares in constant time. Both matter. Swap hash_equals for == and you have reintroduced a timing side channel; swap the random source for rand() and the token becomes guessable.
Rails, built in
Frameworks do this for you, and the common finding is that someone turned it off. A new Rails application ships with protection on:
class ApplicationController < ActionController::Base
# Raise an exception on any request whose CSRF token is missing or wrong.
protect_from_forgery with: :exception
end
Rails puts the token in a hidden field through form_authenticity_token, accepts it in the form body or in an X-CSRF-Token header for JavaScript, and compares it with a constant-time check. It treats GET and HEAD as safe and checks everything else. The way teams break it is skip_before_action :verify_authenticity_token, added to make “just this one API endpoint” work, which is usually the endpoint that matters. If an endpoint changes state, it needs the token, internal or not.
The subtle ones most articles miss
Login CSRF. Everyone protects the actions after login. Almost nobody protects login itself, because before login there is no session to tie a token to, so it feels like there is nothing to forge. There is. An attacker can forge a login that signs your user into the attacker’s account. The user then uses your site believing it is theirs, and their saved card, private notes and search history land in an account the attacker controls and can later open. Real products have fixed this as a security bug (MediaWiki, CVE-2010-1150; Roundcube Webmail, CVE-2011-1491). The defense is to start a session before login, put a token tied to it in the login form, check that token on submit, and issue a fresh session on success.
Tokens leaking through the URL. If you put the token in a query string instead of the form body, it escapes. It lands in your server logs, in the browser history, and in the Referer header sent to every third-party resource on the page. From there an attacker can read it and replay it. Keep the token in the request body or a header, never in a link.
Header checks as a second layer. On top of the token, reject state-changing requests whose Origin header, or failing that Referer, is present and does not match your site. The Origin header was built for exactly this. Chrome and Safari send it on cross-origin POSTs, but not every browser does yet. Treat it as a layer that catches mistakes, not as your only lock: when both headers are missing, this check lets the request through, and only the token stops it.
Re-ask for the password on the actions that matter. For a money transfer, a change of the account email, or a change of password, require the current password again in the form. An attacker who can forge a request still does not know the password, so the forged request fails the extra check. This is the strongest control for the few actions that deserve it, and it also blunts an attacker who got past your token somehow.
How to test your own application
Pick one state-changing action, such as changing the account email.
-
Log in with a test account. Open your browser’s developer tools and watch the request the real form sends. Note every parameter.
-
Build the attack page. Save this, filling in your real endpoint and fields, and open it in the same browser while still logged in:
<form id="f" action="https://app.example/account/email" method="POST">
<input type="hidden" name="email" value="attacker@evil.example">
</form>
<script>document.getElementById('f').submit();</script>
-
Check the result. If the email changed, the endpoint has no CSRF protection. If it was rejected, look at why: a token, or something weaker.
-
Test that the token is actually enforced, not merely present. In an intercepting proxy such as Burp Suite, take a real request, delete the token parameter, and send it. Then put the token back but change one character. Both must be rejected. A surprising number of applications generate a token, place it in the form, and never check it on the server.
-
Try the token from a different user’s session against your account. It must be rejected. A token that is not bound to the session is not a token.
-
Check the sensitive actions for password re-entry, and check that your login form itself carries a token.
Checklist
- Every state-changing request carries a secret token the attacker’s page cannot read.
- The token comes from a cryptographically secure random source.
- The token lives in a hidden field or a header, never in a cookie alone and never in the URL.
- The server compares tokens in constant time, and rejects a missing or wrong one.
- The token is bound to the user’s session.
- Login has its own CSRF protection.
- The highest-value actions ask for the password again.
- Origin or Referer is checked as a second layer, present-and-wrong rejected.
CSRF is cheap to exploit and cheap to prevent, and the two facts are related: the attack is a few lines of HTML, and the defense is one token, generated well and checked on every write. The only way to lose is to trust the cookie the browser hands you, because the browser hands that same cookie to everyone.