TL;DR
HTTPS protects data in transit, but doesn’t stop Cross-Site Request Forgery (CSRF) attacks. This guide shows how to add CSRF tokens to your web application running on HTTPS for better security.
What is CSRF and Why it Matters Even with HTTPS
Cross-Site Request Forgery lets an attacker trick a logged-in user into performing unwanted actions on a website. HTTPS encrypts communication, but doesn’t verify the origin of requests. A malicious site can still send valid requests to your server if the user is authenticated.
Implementing CSRF Protection
Generate Unique Tokens: Your server needs to create a unique, unpredictable token for each user session (or even per-form). This token will be included with sensitive forms.
Use a cryptographically secure random number generator.
Store the token securely on the server, associated with the user’s session.
Include Token in Forms: Add a hidden field to every form that performs sensitive actions (e.g., changing passwords, making purchases).
<form action=”/change-password” method=”post”>
<input type=”hidden” name=”csrf_token” value=”{{ session[‘csrf_token’] }}”>
… other form fields …
</form>
Validate Token on Server-Side: When the form is submitted, your server must verify that the received token matches the one stored in the user’s session.
Compare the submitted token with the session token.
If they don’t match, reject the request immediately. Do not process it!
Consider regenerating the token after validation to prevent replay attacks.
Example Python (Flask) Code:
from flask import Flask, render_template, session, request
import secrets
app = Flask(__name__)
app.secret_key = ‘your-secret-key’ # Change this!
@app.route(‘/login’, methods=[‘POST’])
# … login logic …
session[‘csrf_token’] = secrets.token_hex(16) # Generate token on login
return render_template(‘home.html’)
@app.route(‘/change-password’, methods=[‘POST’])
if request.form[‘csrf_token’] == session[‘csrf_token’]:
# Process password change
session[‘csrf_token’] = secrets.token_hex(16) # Regenerate token
return ‘Password changed!’
else:
return ‘CSRF Token Invalid’, 403
Cookie Considerations: While storing the token in a session is common, you can also store it in an HTTP-only cookie. This offers some protection against JavaScript access but requires careful handling of SameSite attributes.
Set SameSite=Strict or SameSite=Lax on your CSRF cookie to prevent cross-site requests from including the token.
Ensure the cookie is marked as HTTPOnly to protect against XSS attacks.
Double Submit Cookie Pattern: An alternative approach involves storing a random value in both a session and an HTTP-only, SameSite cookie. The server validates that both values match on form submission.
Testing Your Implementation:
Attempt to submit a valid form from your own website (should succeed).
Attempt to submit the same form from a different domain (should fail).
Try submitting a modified form with an incorrect token (should fail).
Important Notes
HTTPS is essential: CSRF protection works best when combined with HTTPS.
Token Length: Use sufficiently long and random tokens to prevent guessing. 16 bytes (32 hex characters) is a good starting point.
Session Security: Protect your session management system from attacks like session fixation and hijacking.
The post CSRF Protection with HTTPS appeared first on Blog | G5 Cyber Security.
No Responses