What is Cross-Site Request Forgery (CSRF) ?
Cross-Site Request Forgery (CSRF) is a type of security attack in which a malicious actor tricks a user into performing unintended actions on a web application where the user is authenticated. This exploit takes advantage of the trust that a web application has in the user’s browser.
How CSRF Works:
- Victim Authentication: The victim logs into a legitimate website (e.g., a banking site) and has an active session with it.
- Malicious Request: The attacker crafts a request (such as transferring funds, changing email settings, etc.) to the legitimate site and embeds it in a link, image, or form on their own malicious website or email.
- Unaware Execution: The victim unknowingly executes the attacker’s request by clicking a link, visiting a page, or submitting a form.
- Server Trust: Since the victim is already authenticated with the legitimate site, the server processes the malicious request, assuming it is legitimate.
Characteristics of CSRF:
- Targets authenticated users.
- Exploits existing trust between the user’s browser and the application.
- Relies on the user unknowingly performing actions.
Real-World Example:
A user is logged into their online banking account. An attacker sends the user an email containing a link:
<img src="http://bank.com/transfer?amount=1000&to=attackerAccount" />
If the user views the email while logged into their bank, their browser sends the request to transfer money because it includes the user’s valid authentication tokens.
Preventing CSRF:
- CSRF Tokens: Include unique, unpredictable tokens in forms and verify them on the server-side.
- SameSite Cookies: Configure cookies with the
SameSite
attribute to prevent them from being sent with cross-origin requests. - Authentication Checks: Require re-authentication or additional verification for sensitive actions.
- Referer or Origin Validation: Validate the
Referer
orOrigin
headers to ensure requests originate from trusted sources. - Use HTTP Methods Correctly: Use HTTP methods like
GET
only for read actions, and protect state-changing actions with CSRF mitigation techniques.
Proper implementation of these defences can significantly reduce the risk of CSRF attacks.