Cross-Site Request Forgery (CSRF) is a web security vulnerability that tricks a user into executing unwanted actions on a different website where they are authenticated. This can lead to unauthorized transactions, data changes, or account settings modifications without the user's consent.
CSRF exploits the trust that a web application has in the user's browser. If a user is logged into a site (like a banking application) and visits a malicious site, that site can send requests to the original site using the user's credentials (session cookies) without their knowledge.
Imagine a user is logged into their banking application (e.g., bank.com
). The application allows users to transfer money using a simple form:
<form action="<https://bank.com/transfer>" method="POST">
<input type="hidden" name="amount" value="1000">
<input type="hidden" name="to" value="attacker_account">
<input type="submit" value="Transfer">
</form>
Now, if the user visits a malicious site while still logged in to their bank account, the attacker can create a malicious page with the following code:
<img src="<https://bank.com/transfer?amount=1000&to=attacker_account>" style="display:none;">
When the user’s browser loads the malicious page, it will send a GET request to the bank's transfer endpoint with the user's session cookies, completing the transaction without the user's knowledge.
Anti-CSRF Tokens: Include a unique, secret token in each state-changing request (like form submissions). The server verifies this token upon receiving the request.
Example:
<form action="<https://bank.com/transfer>" method="POST">
<input type="hidden" name="csrf_token" value="RANDOM_TOKEN">
<input type="hidden" name="amount" value="1000">
<input type="hidden" name="to" value="attacker_account">
<input type="submit" value="Transfer">
</form>
The server checks that csrf_token
matches the expected value.
SameSite Cookies: Use the SameSite
attribute for cookies to prevent them from being sent with cross-site requests.
Example:
Set-Cookie: sessionid=abc123; SameSite=Strict;
User Interaction Verification: Require users to confirm actions through an additional verification step, such as entering a password or completing a CAPTCHA.
Referer Header Validation: Check the Referer
header of incoming requests to ensure they originate from the same site.
CSRF is a significant vulnerability that can lead to unauthorized actions by exploiting user sessions. Understanding how it works and implementing effective prevention techniques is crucial for web developers and security professionals to safeguard applications against such attacks.