CSRF - Cross-Site Request Forgery
- Published on
One common and dangerous attack, which can be done to web application, is Cross-Site Request Forgery (CSRF).
What is CSRF?
Cross-Site Request Forgery (CSRF) is a type of attack that tricks a user into performing actions on a web application in which they are authenticated, without their consent. It exploits the trust that a web application has in the user's browser, allowing an attacker to perform actions such as changing account details, making unauthorized transactions, or altering data.
How CSRF Works
- User Authentication:
The user logs into a web application, which sets a session cookie in the user's browser.
- Malicious Request:
The attacker tricks the user into visiting a malicious website or clicking a link that sends a request to the target web application.
- Execution:
The malicious request is sent with the user's session cookie, making it appear as if the request is coming from the authenticated user.
- Unauthorized Action:
The web application processes the request and performs the action without the user's knowledge or consent.
Example Scenario
- User logs in to their banking application, which sets a session cookie.
- The attacker creates a malicious website with a form that submits a fund transfer request to the bank.
- The user visits the malicious website while still logged into their banking session.
- The form on the malicious website automatically submits a request to the banking application, transferring funds from the user's account to the attacker's account.
- The banking application processes the request because it includes the valid session cookie.
Protecting Against CSRF
CSRF Tokens
- Implementation: Include a unique CSRF token with each form submission and validate the token on the server-side.
- Example: Generate a token when the form is rendered and include it as a hidden input field.
<input type="hidden" name="csrf_token" value="generated_csrf_token">
- Validation: On form submission, check if the token matches the one stored on the server.
SameSite Cookie Attribute
- Implementation: Set the SameSite attribute for cookies to Strict or Lax, which prevents cookies from being sent with cross-site requests.
Set-Cookie: sessionid=abcd1234; SameSite=Strict
Double Submit Cookies
- Implementation: Send a CSRF token both as a cookie and as a request parameter, then validate both on the server-side.
- Validation: Ensure the token from the cookie matches the token from the request.
Custom Request Headers
- Implementation: Use custom request headers for requests, which are not automatically sent with cross-origin requests.
User Interaction
- Implementation: Require user interaction for critical actions (e.g., entering a password, using CAPTCHA).