Перейти к основному содержимому
Cross-Site Request Forgery (CSRF) & SameSite Defenses
Урок 7 из 18

Cross-Site Request Forgery (CSRF) & SameSite Defenses

Understand how browsers attach session cookies on cross-site requests, test state-changing endpoints safely in a lab, and combine anti-CSRF tokens with SameSite cookie attributes.

Средний 24 мин Веб-безопасность
Этого урока пока нет на выбранном языке — показана версия на другом языке. Перевод готовится.
Только в разрешённой среде — Описанные здесь приёмы применяются только в учебных лабораториях и в системах, которые принадлежат вам или на которые есть письменное разрешение.

Цели обучения

  • Explain why automatic cookie attachment enables Cross-Site Request Forgery even when SOP blocks reading responses
  • Identify state-changing endpoints vulnerable to forged GET, form-based POST, or simple cross-origin requests
  • Evaluate SameSite=Strict, SameSite=Lax, and SameSite=None cookie behaviour and known bypass conditions
  • Implement server-side anti-CSRF tokens and layered request-origin protections

Рекомендуется заранее: HTTP-запросы и ответы, cookie и управление сессиямиHTML/JS Execution, Same-Origin Policy, CORS & CSPWeb Authentication & Access Control Fundamentals

#Why this matters

When you log in to a web application, your browser stores a session cookie and sends it automatically on every subsequent request to that site. This convenience creates ambient authority: if a malicious page at evil.test makes your browser submit a hidden form to lab.local, your browser attaches your lab.local session cookie unless the site explicitly prevents it.

The Same-Origin Policy stops evil.test from reading the HTTP response from lab.local, but it does not stop the browser from sending the request. If the request changes a password, transfers funds, or updates an email address, the damage happens before any response is ever read.

#How cross-site requests carry credentials

A classic CSRF flaw needs three conditions:

  1. A relevant action. The endpoint changes state or privileges (changing email, adding an admin, triggering a transfer).
  2. Cookie-only authentication. The server identifies the user solely through a cookie or HTTP Basic auth, with no unpredictable secret in the request body or custom header.
  3. Predictable parameters. All required fields can be guessed or hardcoded by an external page.
Classic form-based CSRF flowClassic form-based CSRF flowBrowserevil.testlab.localVisit page while logged into lab.localHTML with auto-submitting POST formPOST /account/email (session cookie attached)200 OK (email updated)evil.test cannot read the reply, but the change succeeded

Notice that HTML forms using application/x-www-form-urlencoded, multipart/form-data, or text/plain qualify as CORS simple requests. The browser sends them immediately without asking lab.local via an OPTIONS preflight check. By contrast, sending Content-Type: application/json with a custom header from fetch() triggers a CORS preflight, which blocks unapproved cross-origin writes.

#Testing for CSRF safely

In a lab, start by capturing a state-changing request in Burp Suite and checking what authenticates it:

http
POST /profile/email HTTP/1.1
Host: lab.local
Cookie: session=eyJhbGciOi...; SameSite=None
Content-Type: application/x-www-form-urlencoded

email=attacker@example.test&csrf_token=8a4f2c91

Test the defences systematically:

  • Remove the token. Delete csrf_token or send an empty value; if the server still returns 200 OK, validation is missing or skipped when absent.
  • Swap the token. Use a token from a second test account (bob) on alice's session; if accepted, tokens are not bound to the user session.
  • Change the method. Try GET /profile/email?email=attacker@example.test; some frameworks accept query parameters for routes intended only for POST.

#SameSite cookies and their limits

The SameSite attribute on Set-Cookie tells the browser when to withhold cookies on cross-site requests.

Attribute Cross-site top-level GET Cross-site POST form Typical use
Strict Cookie withheld Cookie withheld High-security admin sessions
Lax Cookie sent Cookie withheld Default for normal user sessions
None; Secure Cookie sent Cookie sent Cross-site embeds over HTTPS only

Modern browsers treat cookies without an explicit SameSite attribute as Lax by default, though Chromium applies a legacy 120-second exception allowing newly created default-Lax cookies on top-level cross-site POST requests. Setting SameSite=Lax explicitly removes that 120-second window.

Even explicit SameSite=Lax has two important limits:

  • State-changing GET requests. Because Lax allows cookies on top-level navigations (<a href="..."> or window.location), any state change triggered by GET remains exploitable.
  • Same-site subdomains. SameSite checks the registrable domain (scheme + eTLD+1), not the full origin. If blog.lab.local has an XSS flaw or untrusted tenant content, requests from blog.lab.local to app.lab.local count as same-site and carry SameSite=Strict cookies.

#Defending properly

Treat SameSite as defence in depth, not a complete replacement for explicit CSRF protection:

  1. Use the synchronizer token pattern. Generate a cryptographically random token per session, embed it in forms or meta tags, and verify it on every POST, PUT, PATCH, and DELETE request using constant-time comparison.
  2. Use GET only for safe, read-only actions. Never mutate server state on GET or HEAD.
  3. Require custom headers for JSON APIs. Enforce Content-Type: application/json strictly on the server (rejecting text/plain bodies) and keep CORS Access-Control-Allow-Origin restricted to trusted origins without wildcards alongside Allow-Credentials: true.
  4. Set SameSite=Lax or Strict with HttpOnly and Secure flags on all session cookies.

#Common mistakes

  • Checking csrf_token only if the parameter exists in the request body.
  • Validating the Referer or Origin header with a loose substring check such as str_contains($origin, "lab.local"), which matches lab.local.evil.test.
  • Relying on SameSite=Lax while leaving state-changing GET routes or subdomain XSS issues unpatched.
  • Assuming CORS blocks form submissions: CORS restricts reading responses and sending non-simple requests, not classic HTML forms.

#Summary

  • CSRF exploits ambient cookie authority so a third-party site triggers unintended actions as a logged-in victim.
  • Standard HTML forms bypass CORS preflight because they count as simple requests.
  • SameSite=Lax blocks cross-site POST forms, yet still permits top-level GET navigations and same-site subdomain requests.
  • Reliable defence combines non-mutating GET semantics, session-bound anti-CSRF tokens, strict Content-Type checks on APIs, and SameSite cookies.

Проверка знаний

Войдите, чтобы проходить тест, завершать уроки и сохранять прогресс. Войти в систему

Практика: проверьте свои знания