CSRF Attacks: Mechanisms, Real‑World Examples, and Defense Strategies
This article explains the background and risks of Cross‑Site Request Forgery (CSRF) attacks, illustrates real‑world exploitation scenarios, and provides comprehensive defense techniques such as origin/referrer checks, CSRF tokens, double‑cookie verification, SameSite cookies, and best practices for developers and security teams.
Background
With the rapid growth of the Internet, information security has become a top concern for enterprises, and the front‑end is a high‑risk point for security issues. In addition to classic XSS and CSRF problems, modern front‑end developers also face threats such as network hijacking and illegal calls to hybrid APIs.
CSRF Attack Overview
CSRF (Cross‑Site Request Forgery) tricks a victim into sending a request to a target site where the victim is already authenticated, allowing the attacker to perform actions on behalf of the victim.
A typical CSRF flow includes:
The victim logs into a.com and retains authentication cookies.
The attacker lures the victim to b.com .
b.com sends a request to a.com (e.g., a.com/act=xx ) which automatically includes the victim's cookies.
a.com processes the request as if it originated from the victim.
Common Attack Types
GET‑based CSRF : A simple image tag triggers a GET request, e.g., <img src="http://bank.example/withdraw?amount=10000&for=hacker"> .
POST‑based CSRF : An auto‑submitting form sends a POST request, e.g., <form action="http://bank.example/withdraw" method="POST"> <input type="hidden" name="account" value="xiaoming"/> <input type="hidden" name="amount" value="10000"/> <input type="hidden" name="for" value="hacker"/> <script>document.forms[0].submit();</script> </form>
Link‑based CSRF : An attacker embeds a malicious hyperlink that the victim must click, e.g., <a href="http://test.com/csrf/withdraw.php?amount=1000&for=hacker" target="_blank">Click me!</a>
CSRF Characteristics
Attacks originate from third‑party domains; the victim site cannot fully prevent them.
Attackers exploit the victim's existing authentication credentials without stealing them.
Various vectors (images, links, forms, CORS, scripts) can be used to launch the attack.
Defense Strategies
Same‑Origin Verification
Validate the Origin or Referer header to ensure the request originates from a trusted domain. If the headers are missing (e.g., IE11, 302 redirects), the request should be blocked.
CSRF Token
Generate a random token per session, embed it in every form or AJAX request, and verify it on the server.
Example Java implementation:
HttpServletRequest req = (HttpServletRequest)request;
HttpSession s = req.getSession();
String sToken = (String)s.getAttribute("csrftoken");
if (sToken == null) {
sToken = generateToken();
s.setAttribute("csrftoken", sToken);
chain.doFilter(request, response);
} else {
String xhrToken = req.getHeader("csrftoken");
String pToken = req.getParameter("csrftoken");
if (sToken != null && ((xhrToken != null && sToken.equals(xhrToken)) || (pToken != null && sToken.equals(pToken)))) {
chain.doFilter(request, response);
} else {
request.getRequestDispatcher("error.jsp").forward(request, response);
}
}Double‑Cookie Verification
Set a random cookie (e.g., csrfcookie=v8g9e4ksfhw ) and require the same value to be sent as a request parameter or header. The server compares the two values and rejects mismatches.
SameSite Cookie Attribute
Configure cookies with SameSite=Strict or SameSite=Lax to restrict their inclusion in cross‑site requests. Strict blocks all third‑party usage, while Lax allows cookies on top‑level navigation GET requests.
Implementation Tips
Prefer server‑side token validation over client‑side checks.
In distributed systems, store tokens in a shared store (e.g., Redis) or use encrypted token patterns to avoid session affinity.
Apply Content‑Security‑Policy and X‑Content‑Type‑Options: nosniff headers to mitigate content injection.
Testing and Monitoring
Tools like CSRFTester can record legitimate user interactions, modify parameters, and replay them to detect missing protections. Monitoring at the proxy layer for cross‑origin requests with unexpected MIME types (e.g., image requests returning JSON) can flag potential CSRF attempts.
Historical Cases
WordPress (2012) : CSRF allowed attackers to create admin users, modify site settings, and delete comments.
YouTube (2008) : Almost all user actions were vulnerable; attackers could add videos to favorites, modify friend lists, and share malicious links.
Conclusion
Effective CSRF protection combines automatic same‑origin checks, explicit CSRF tokens (or double‑cookie verification), and proper cookie attributes. Developers should avoid state‑changing GET requests, enforce idempotent APIs, and adopt layered defenses tailored to their application architecture.
Qunar Tech Salon
Qunar Tech Salon is a learning and exchange platform for Qunar engineers and industry peers. We share cutting-edge technology trends and topics, providing a free platform for mid-to-senior technical professionals to exchange and learn.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.