Weaknesscore
Cross-site request forgery
Also called CSRF, XSRF, sea surf, session riding, one-click attack, cwe-352.
Cross-site request forgery happens when a web application trusts a request because it carries the user's cookies, so a page on another site can make the browser act for the user.
- CWE
- CWE-352
- Abstraction
- compound
- OWASP Top 10 (2025)
- A01
- CWE Top 25 (2025)
- rank 3
- Languages affected
- any-web-server
Description
A browser adds the cookies of a site to every request that it sends to that site. It does this when the user clicks a button on the site, and also when a page on another site holds a form, an image or a script that points to the site.49 A web application that identifies the user by a session cookie therefore sees two kinds of request that look the same. One comes from its own page, because the user wants the action. The other comes from a page that an attacker wrote, and the user does not know about it. Cross-site request forgery (CSRF) happens when the application cannot tell the two apart and carries out both.1
The root cause is that a cookie answers the wrong question. It answers "who is this user?". It does not answer "did this user ask for this action?". CWE-352 is a composite weakness. It requires several weaknesses at the same time, among them CWE-346, an origin validation error, and CWE-441, an unintended proxy or intermediary. The browser of the user is that intermediary. Removing one of the weaknesses removes or sharply reduces the risk.1 Peter W wrote in 2001 that many web applications are good at identifying users and understanding requests, but terrible at verifying origins and intent.5 The check of the session in CWE-352 Example 1 is correct, and the application is still vulnerable, because the forged request carries a valid session.1
The weakness is there by default, because a server that works for its users already has it. A form, a handler and a session check are all that a normal feature needs. Nothing fails in a test, because the test never sends a request from another site. HTTPS does not help, since the forged request uses HTTPS too.9
The consequences depend on what the request can do. CWE-352 says that the server treats the forged request as authentic, so the attacker performs operations as the victim. If the victim is an administrator, the attacker may get complete control over the web application.1 Cross-site scripting defeats most CSRF defences, because a script on the site can read the tokens and send requests from the right origin.14 The page Cross-site scripting covers that weakness.
CWE-352 is rank 3 in the 2025 CWE Top 25, with no CVEs in the CISA catalogue of known exploited vulnerabilities, up from rank 4 the year before.2 The OWASP Top 10:2025 maps it to A01:2025 Broken Access Control.3
History
On June 15, 2001, Peter W replied on the Bugtraq list to a post about images on message boards. The post had shown that an [img] tag on a forum makes each reader's browser send a GET request to any URL. Peter W named the general problem Cross-Site Request Forgeries, CSRF, pronounced "sea surf".5 He wrote that the problem is not the image tag. It is the backend application that the tag reaches. He also set CSRF apart from cross-site scripting. Cross-site scripting puts active code into a page. CSRF uses tags such as IMG to forge requests with the user's credentials, to the site of the page or to any other site.5 Early records in CWE-352 match his description, such as CVE-2004-1703, where an image tag in a comment added user accounts.116
Vulnerable code
The handler below changes the email address of the logged-in user. It runs in the same process, with requests as dictionaries, so the page needs no network. The second request is the classic demonstration: a form on another site posts to the handler, and Alice's browser adds her session cookie.
This code runs but gives a wrong answer on purpose.
SESSIONS = {"c0ffee": "alice"}
EMAILS = {"alice": "alice@example.com"}
def change_email(request: dict) -> str:
user = SESSIONS.get(request["cookies"].get("session"))
if user is None:
return "401 not logged in"
EMAILS[user] = request["form"]["email"]
return f"200 email of {user} is {EMAILS[user]}"
# Alice submits the form on the site.
print(change_email({
"headers": {"Sec-Fetch-Site": "same-origin"},
"cookies": {"session": "c0ffee"},
"form": {"email": "alice@example.net"},
}))
# A page on another site submits a form to the same URL.
print(change_email({
"headers": {"Sec-Fetch-Site": "cross-site", "Origin": "https://attacker.example"},
"cookies": {"session": "c0ffee"},
"form": {"email": "mallory@attacker.example"},
}))
200 email of alice is alice@example.net
200 email of alice is mallory@attacker.example
Both requests succeed. The handler checks the session, and the session is valid in both. The headers show where the second request came from, but the handler does not read them. If the site sends password resets to this address, the attacker can now take over the account.
Fixed code
The fix adds a second secret that only the site's own pages have: a synchronizer token. The server makes a random token for each session, puts it in each form as a hidden field, and compares it on each request that changes state. The OWASP cheat sheet says that the token must be unique per session, secret and unpredictable.4 The secrets module is the source for security tokens in Python, and hmac.compare_digest compares without the timing leak of ==.1011
import hmac
import secrets
SESSIONS = {"c0ffee": {"user": "alice", "csrf": secrets.token_urlsafe(32)}}
EMAILS = {"alice": "alice@example.com"}
def form_token(session_id: str) -> str:
# The server puts this value in a hidden field of its own form.
return SESSIONS[session_id]["csrf"]
def change_email(request: dict) -> str:
session = SESSIONS.get(request["cookies"].get("session"))
if session is None:
return "401 not logged in"
sent = request["form"].get("csrf_token", "")
if not hmac.compare_digest(sent, session["csrf"]):
return "403 missing or wrong CSRF token"
EMAILS[session["user"]] = request["form"]["email"]
return f"200 email of {session['user']} is {EMAILS[session['user']]}"
print(change_email({
"cookies": {"session": "c0ffee"},
"form": {"email": "alice@example.net", "csrf_token": form_token("c0ffee")},
}))
# The other site cannot read the token from the site's pages.
print(change_email({
"cookies": {"session": "c0ffee"},
"form": {"email": "mallory@attacker.example"},
}))
200 email of alice is alice@example.net
403 missing or wrong CSRF token
The attacker's page can make the browser send the cookie, but it cannot read the site's pages, so it does not have the token. The same-origin policy is what keeps the token secret. A token in a GET URL can leak through logs, history and the Referer header, so it belongs in the body or in a request header.4
Checking where the request came from
Browsers also tell the server where a request came from. The Sec-Fetch-Site header has the value same-origin, same-site, cross-site or none.6 The OWASP cheat sheet accepts this header as a defence, with a fallback to the Origin header for browsers that do not send it.4 The Go standard library has the check as http.CrossOriginProtection. It allows GET, HEAD and OPTIONS, rejects cross-origin requests with other methods, and compares the Origin header with the Host header when Sec-Fetch-Site is absent.7
package main
import (
"fmt"
"net/http"
"net/http/httptest"
"strings"
)
func main() {
mux := http.NewServeMux()
mux.HandleFunc("POST /email", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "email changed")
})
handler := http.NewCrossOriginProtection().Handler(mux)
cases := []struct{ name, header, value string }{
{"own page", "Sec-Fetch-Site", "same-origin"},
{"other site", "Sec-Fetch-Site", "cross-site"},
{"other origin, older browser", "Origin", "https://attacker.example"},
}
for _, c := range cases {
req := httptest.NewRequest("POST", "https://app.example/email", strings.NewReader("email=x"))
req.Header.Set(c.header, c.value)
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)
fmt.Printf("%s: %d\n", c.name, rec.Code)
}
}
own page: 200
other site: 403
other origin, older browser: 403
The check works only if no GET request changes state. The Go documentation and the cheat sheet both say so.74 Requests with neither header pass, because they come from the same origin or from a client that is not a browser.7
How to detect it
- Manual testing. CWE-352 rates manual analysis as highly effective. For each request that changes state, send it again from a page on another origin and see if it succeeds.1
- Static analysis. CWE-352 rates automated static analysis as limited, because each application has its own rules about which requests an outsider may cause.1 Tools find a missing or a disabled defence instead. CodeQL queries
js/missing-token-validation,py/csrf-protection-disabled,java/spring-disabled-csrf-protectionandcs/web/missing-token-validationreport handlers or settings without the framework's CSRF check.12131415 - Code review. List every route that changes state. Check that none of them accepts GET, that each one is behind the framework's CSRF check, and that no route is exempt without a reason. Look for login forms too, because a forged login can put the user in the attacker's account.15
How to prevent it
- Use the framework's defence. The OWASP cheat sheet says to check for built-in protection first.4 Django keeps a random secret in a cookie and requires a matching
csrfmiddlewaretokenfield on every request that is not GET, HEAD, OPTIONS or TRACE, and returns 403 if it is wrong.8 ASP.NET Core and Go have their own mechanisms.97 CodeQL says that in many frameworks the default configuration is sufficient against most CSRF attacks.13 - Use tokens or Fetch Metadata. Stateful applications use the synchronizer token pattern. Stateless applications use the double-submit cookie pattern in its signed form, and the cheat sheet discourages the naive form.4 For browsers that send
Sec-Fetch-Site, a check of that header with anOriginfallback is a defence too.4 - Keep state changes off GET. CWE-352 and the cheat sheet both say not to use GET for any request that changes state.14
- Fix cross-site scripting. CWE-352 says that most CSRF defences can be bypassed by script that the attacker controls.1
- Set SameSite on cookies as defence in depth.
SameSite=LaxorStrictkeeps the browser from sending the cookie on many cross-site requests. The cheat sheet says that it does not replace a CSRF defence:Laxstill sends the cookie on top-level GET navigations, and "site" covers every subdomain of the registrable domain.4 - Ask again for dangerous actions. CWE-352 suggests a separate confirmation for an especially dangerous operation, such as a change of password.1
Real cases
| Case | Date | What happened |
|---|---|---|
| CVE-2004-1703 | published 2005-02-26 | In Fusion News, a comment with an img bbcode tag pointed at the signup action. When a logged-in administrator viewed the page, the browser called it and added a user account.161 |
| CVE-2009-3022 | published 2009-08-31 | A CSRF weakness in bingo!CMS let remote attackers hijack the authentication of other users for requests that changed configuration or content.17 |
| CVE-2009-3759 | published 2009-10-22 | Sample code in the XenServer Resource Kit in Citrix XenCenterWeb let remote attackers hijack the authentication of administrators to change a password or stop a virtual machine.18 |
SAFE_METHODS = {"GET", "HEAD", "OPTIONS"}
OWN_ORIGIN = "https://app.example"
def allowed(request: dict) -> bool:
if request["method"] in SAFE_METHODS:
return True # safe methods must not change state
site = request["headers"].get("Sec-Fetch-Site")
if site is not None:
return site in ("same-origin", "none")
origin = request["headers"].get("Origin")
if origin is not None:
return origin == OWN_ORIGIN
return False # no signal at all: refuse on a sensitive endpoint
requests = [
("own page", {"method": "POST", "headers": {"Sec-Fetch-Site": "same-origin"}}),
("other site", {"method": "POST", "headers": {"Sec-Fetch-Site": "cross-site"}}),
("sibling subdomain", {"method": "POST", "headers": {"Sec-Fetch-Site": "same-site"}}),
("older browser, other origin", {"method": "POST", "headers": {"Origin": "https://attacker.example"}}),
("no headers", {"method": "POST", "headers": {}}),
]
for name, request in requests:
print(f"{name}: {'allowed' if allowed(request) else 'refused'}")
own page: allowed
other site: refused
sibling subdomain: refused
older browser, other origin: refused
no headers: refused
The policy follows the OWASP cheat sheet. Sec-Fetch-Site is the main signal. A same-site request comes from a sibling subdomain, so the policy refuses it unless the application trusts every subdomain. When the header is absent, the policy falls back to Origin. With no signal at all, it fails safe and refuses.
- Verdict: idiom. The standard library has no web framework and no CSRF check. Django has one in
CsrfViewMiddleware, and CodeQL querypy/csrf-protection-disabledreports a Django project that removes it. - In Django, keep
CsrfViewMiddlewarein the middleware list, put{% csrf_token %}in each POST form, and do not mark a viewcsrf_exemptwithout a reason. - For a custom server, use
secrets.token_urlsafefor tokens andhmac.compare_digestto compare them, as in the main example.
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.HexFormat;
import java.util.Map;
public class Main {
record Session(String user, String csrf) {}
static final SecureRandom RANDOM = new SecureRandom();
static String newToken() {
byte[] bytes = new byte[32];
RANDOM.nextBytes(bytes);
return HexFormat.of().formatHex(bytes);
}
static final Map<String, Session> SESSIONS = Map.of("c0ffee", new Session("alice", newToken()));
static String changeEmail(String cookie, String formToken, String email) {
Session s = SESSIONS.get(cookie);
if (s == null) {
return "401 not logged in";
}
boolean match = MessageDigest.isEqual(
formToken.getBytes(StandardCharsets.UTF_8),
s.csrf().getBytes(StandardCharsets.UTF_8));
if (!match) {
return "403 missing or wrong CSRF token";
}
return "200 email of " + s.user() + " is " + email;
}
public static void main(String[] args) {
System.out.println(changeEmail("c0ffee", SESSIONS.get("c0ffee").csrf(), "alice@example.net"));
System.out.println(changeEmail("c0ffee", "", "mallory@attacker.example"));
}
}
200 email of alice is alice@example.net
403 missing or wrong CSRF token
SecureRandom makes the token, and MessageDigest.isEqual compares the two byte arrays in a time that depends only on the length of the first one.
- Verdict: idiom. The Java standard library has an HTTP server but no CSRF check. Web frameworks such as Spring Security have one, and it is on by default there.
- Do not turn off the framework's CSRF protection for a browser application that uses cookies. CodeQL query
java/spring-disabled-csrf-protectionreports code that does. - Use
SecureRandomfor tokens, neverjava.util.Random.
using System.Security.Cryptography;
using System.Text;
var sessions = new Dictionary<string, Session>
{
["c0ffee"] = new Session("alice", Convert.ToHexString(RandomNumberGenerator.GetBytes(32))),
};
string ChangeEmail(string cookie, string formToken, string email)
{
if (!sessions.TryGetValue(cookie, out var s))
{
return "401 not logged in";
}
bool match = CryptographicOperations.FixedTimeEquals(
Encoding.UTF8.GetBytes(formToken), Encoding.UTF8.GetBytes(s.Csrf));
if (!match)
{
return "403 missing or wrong CSRF token";
}
return $"200 email of {s.User} is {email}";
}
Console.WriteLine(ChangeEmail("c0ffee", sessions["c0ffee"].Csrf, "alice@example.net"));
Console.WriteLine(ChangeEmail("c0ffee", "", "mallory@attacker.example"));
record Session(string User, string Csrf);
200 email of alice is alice@example.net
403 missing or wrong CSRF token
RandomNumberGenerator makes the token, and CryptographicOperations.FixedTimeEquals compares in constant time.
- Verdict: stdlib. ASP.NET Core has antiforgery tokens. MVC and Razor Pages validate them with built-in filters, and Blazor and Minimal APIs need the antiforgery middleware.
- Put
[ValidateAntiForgeryToken]on each POST action, or add a global filter for all POST requests, as CodeQL querycs/web/missing-token-validationrecommends. - Protect the login form too, so that an attacker cannot log the user in to the attacker's account.
const { randomBytes, timingSafeEqual } = require("node:crypto");
const sessions = new Map([["c0ffee", { user: "alice", csrf: randomBytes(32).toString("hex") }]]);
function changeEmail(cookie, formToken, email) {
const s = sessions.get(cookie);
if (s === undefined) {
return "401 not logged in";
}
const sent = Buffer.from(formToken);
const expected = Buffer.from(s.csrf);
// timingSafeEqual needs buffers of the same length.
if (sent.length !== expected.length || !timingSafeEqual(sent, expected)) {
return "403 missing or wrong CSRF token";
}
return `200 email of ${s.user} is ${email}`;
}
console.log(changeEmail("c0ffee", sessions.get("c0ffee").csrf, "alice@example.net"));
console.log(changeEmail("c0ffee", "", "mallory@attacker.example"));
200 email of alice is alice@example.net
403 missing or wrong CSRF token
crypto.randomBytes makes the token. crypto.timingSafeEqual compares in constant time, and it throws when the lengths differ, so the code checks the length first. The length of the token is not a secret.
- Verdict: idiom. Node.js has no CSRF check in its HTTP server. Express needs a middleware, and CodeQL query
js/missing-token-validationreports a cookie-based Express app without one. - Send the token in the body or in a custom request header, never in the URL.
package main
import (
"crypto/rand"
"crypto/subtle"
"encoding/hex"
"fmt"
)
type session struct {
user, csrf string
}
func newToken() string {
b := make([]byte, 32)
rand.Read(b) // crypto/rand, not math/rand
return hex.EncodeToString(b)
}
var sessions = map[string]*session{"c0ffee": {user: "alice", csrf: newToken()}}
func changeEmail(cookie, formToken, email string) string {
s, ok := sessions[cookie]
if !ok {
return "401 not logged in"
}
if subtle.ConstantTimeCompare([]byte(formToken), []byte(s.csrf)) != 1 {
return "403 missing or wrong CSRF token"
}
return fmt.Sprintf("200 email of %s is %s", s.user, email)
}
func main() {
fmt.Println(changeEmail("c0ffee", sessions["c0ffee"].csrf, "alice@example.net"))
fmt.Println(changeEmail("c0ffee", "", "mallory@attacker.example"))
}
200 email of alice is alice@example.net
403 missing or wrong CSRF token
The token comes from crypto/rand, and subtle.ConstantTimeCompare compares it without a timing leak. The main example shows http.CrossOriginProtection, which needs no token.
- Verdict: stdlib.
net/httphasCrossOriginProtection, a check ofSec-Fetch-Sitewith anOriginfallback. It allows GET, HEAD and OPTIONS, so those methods must not change state. - Wrap the whole mux with
CrossOriginProtection.Handler, not single routes, so that a route added later is covered too. - Use
AddTrustedOriginfor the other origins that may post to the server. KeepAddInsecureBypassPatternfor endpoints that must accept cross-origin requests and have another defence.
References
- CWE-352: Cross-Site Request Forgery (CSRF), Description; Alternate Terms; Common Consequences; Potential Mitigations; Composite Components; Demonstrative Examples, Example 1; Detection Methods; Observed Examples
- 2025 CWE Top 25 Most Dangerous Software Weaknesses, the ranked list, rank 3, CVEs in KEV, Rank Last Year
- OWASP Top 10:2025, A01:2025 Broken Access Control, Background; List of Mapped CWEs
- OWASP Cheat Sheet Series, Cross-Site Request Forgery Prevention Cheat Sheet, Introduction; Cross-Site Scripting (XSS) will defeat all CSRF mitigation techniques; Built-In Or Existing CSRF Implementations; Synchronizer Token Pattern; Fetch Metadata headers; Using Standard Headers to Verify Origin; SameSite (Cookie Attribute), Limitations of SameSite
- Peter W, Cross-Site Request Forgeries (Re: The Dangers of Allowing Users to Post Images), Bugtraq, 2001-06-15, the opening paragraphs; The difference between XSS and CSRF
- MDN Web Docs, Sec-Fetch-Site, Directives
- Go standard library, net/http, CrossOriginProtection, the type description
- Django documentation, Cross Site Request Forgery protection, How it works
- ASP.NET Core documentation, Prevent Cross-Site Request Forgery (XSRF/CSRF) attacks, the opening section, an example of a CSRF attack
- The Python Standard Library, secrets, the opening section; Generating tokens
- The Python Standard Library, hmac, hmac.compare_digest
- CodeQL query help, Missing CSRF middleware (js/missing-token-validation), the query description; Recommendation
- CodeQL query help, CSRF protection weakened or disabled (py/csrf-protection-disabled), the query description; Recommendation
- CodeQL query help, Disabled Spring CSRF protection (java/spring-disabled-csrf-protection), the query description
- CodeQL query help, Missing cross-site request forgery token validation (cs/web/missing-token-validation), the query description; Recommendation
- CVE-2004-1703, Fusion News, the description and the publication date
- CVE-2009-3022, bingo!CMS, the description and the publication date
- CVE-2009-3759, Citrix XenCenterWeb, the description and the publication date
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag SFBRKW Edit this page History Report an error Markdown