---
obj: concept
wiki: https://en.wikipedia.org/wiki/Cross-site_request_forgery
rev: 2024-05-02
---

# Cross-Site Request Forgery (CSRF)
Cross-Site Request Forgery (CSRF) is a type of security vulnerability that allows an attacker to execute unauthorized actions on behalf of a victim user. CSRF attacks occur when an attacker tricks a victim into making a request to a web application that the victim is authenticated with, without the victim's knowledge or consent.

## How CSRF Works
1. **Authentication**: The victim user is authenticated with a web application and has an active session.
2. **Malicious Request**: The attacker crafts a malicious request, such as changing the victim's email address or making a fund transfer, and embeds it in a web page or email.
3. **Trickery**: The attacker lures the victim into visiting a web page or clicking a link that triggers the malicious request. Since the victim is authenticated with the web application, the request is automatically executed in the victim's context.
4. **Unauthorized Action**: The web application processes the malicious request, unaware that it was initiated by the attacker, and performs the action on behalf of the victim.

## Impact of CSRF
- **Unauthorized Actions**: CSRF attacks can lead to unauthorized actions being performed by authenticated users, such as changing account settings, making financial transactions, or deleting data.
- **Data Tampering**: Attackers can manipulate data within the application, such as modifying user profiles, posting unauthorized content, or altering preferences.
- **Session Compromise**: CSRF attacks may lead to session compromise if sensitive actions, such as changing passwords or session tokens, are performed without the victim's consent.

## Prevention and Mitigation
1. **CSRF Tokens**: Implement CSRF tokens in web forms and AJAX requests to validate that the request originates from the legitimate user session. Include the token in each request and validate it on the server-side before processing the action.
2. **Same-Site Cookies**: Set the SameSite attribute on cookies to restrict them from being sent in cross-origin requests, mitigating the risk of CSRF attacks.
3. **Anti-CSRF Headers**: Use anti-CSRF headers such as X-Requested-With or Origin to validate the origin of requests and prevent cross-origin requests from being processed.
4. **Double Submit Cookies**: In addition to CSRF tokens, use double submit cookies where a random value is stored in both a cookie and a request parameter, and the server verifies that they match.
5. **HTTP Referer Header**: Validate the [HTTP](../internet/HTTP.md) Referer header on the server-side to ensure that requests originate from trusted sources.
6. **User Interaction**: Require user interaction, such as confirming sensitive actions or entering passwords, before executing critical actions to prevent automated CSRF attacks.
