Web Security: CSRF
CSRF is less famous than XSS but is a common and high-risk vulnerability. Here’s a quick review.
Concept
CSRF (Cross-Site Request Forgery) is an attack that forges requests to a server by impersonating a trusted, logged-in user.
Examples
Concepts can be abstract—examples help.
Suppose you open a phishing email with enticing text like “You’ve won $5,000,000!”. The HTML includes:
<img src="https://test1.com/index?action=delete&id=123">
When the email loads, the <img>
triggers a GET request. If you’re logged in to test1.com
, the browser sends cookies and the request succeeds, deleting the resource with id=123
.
To avoid this, you switch deletes to POST—but attackers can do this:
<form method="POST" action="https://test1.com/index">
<input type="hidden" name="action" value="delete"/>
<input type="hidden" name="id" value="123"/>
</form>
<script> document.forms[0].submit(); </script>
There are also link-based and XHR-based attacks that rely on user interaction:
<a href="https://test1.com/index?action=delete&id=123">
点击就中500万
</a>
These are common CSRF techniques.
Analysis
The pattern is: the victim is logged in at site A. While visiting site B, a request is sent to A without the victim’s awareness, performing an unintended action.
Defenses
Given the above, combine multiple defenses wherever possible:
- RESTful API design: destructive actions use the proper verbs (e.g., DELETE). Simple links/GETs or bare POSTs can’t trigger them.
- SameSite cookies: set
SameSite
on cookies. WithStrict
, third-party requests won’t send cookies. WithLax
, only top-level GET navigations send cookies. - CORS: lock down cross-origin requests to prevent illicit XHRs.
- Referer/Origin checks: e.g., reject requests not originating from your domain(s).
- CSRF tokens: include a per-request or per-session anti-CSRF token that cross-site scripts can’t access.
- For sensitive cookies, set
SameSite
as above; withStrict
, no cross-site cookies; withLax
, only GET navigations send them.
Final Thoughts
Security is essential for open web systems—take it seriously and apply layered defenses.