Cross-Site Request Forgery (CSRF) is a web vulnerability that tricks authenticated users into performing actions they didn't intend. This is done by exploiting their session with a trusted website. For example, an attacker might send a malicious link that, when clicked, makes a user unknowingly transfer money, update account details, or perform administrative actions.
A CSRF attack relies on:
The victim being authenticated on the target site.
The attacker crafting a malicious request using the victim's session credentials.
Example Scenario
Imagine you're logged into your online banking account. While browsing another site, you click a suspicious link. Without your knowledge, this link triggers a request to transfer money from your account. Since you're already authenticated, the bank processes this as if you made the request.
Identify state-changing actions like form submissions (e.g., creating a user, updating data).
Examine the code for these actions (e.g., the /signup.html route in the main.py file).
Create a webpage that mimics a legitimate form but is pre-filled to exploit the vulnerability.
The provided index.html file demonstrates this:
The form is hidden.
It submits predefined credentials to /signup.html on the target server.
<form hidden id="hack" action="http://localhost:5000/signup.html" method="POST">
<input id="username" name="username" value="attacker_user">
<input name="password" value="password123">
<input name="dob" value="1990-01-01">
</form>
<button onclick="document.getElementById('hack').submit()">Submit Exploit</button>
Open the malicious page while logged into the application as an administrator.
Click the "Submit Exploit" button. This sends a POST request to the target endpoint using the victim's session.
White-box Testing: Check the database for the injected user credentials.
Black-box Testing: Log in with the credentials (e.g., attacker_user/password123) to confirm access.
Embed a unique CSRF token in each form.
Verify the token server-side before processing the request.
Example in Flask (using WTForms):
from flask_wtf.csrf import CSRFProtect
app = Flask(__name__)
csrf = CSRFProtect(app)
Configure cookies to be SameSite, which prevents them from being sent with cross-site requests.
Example:
app.config['SESSION_COOKIE_SAMESITE'] = 'Strict'
Teach users not to click suspicious links or interact with untrusted sources.
Limit the origins from which resources can be loaded, reducing the chances of malicious scripts being executed.
For critical actions, use 3FA to ensure legitimacy, such as:
Password
Mobile OTP
Biometric verification