Skip to content

Defensive Countermeasures

Web applications are vulnerable to CSRF and SSRF attacks, but robust defensive strategies can mitigate these risks. This section outlines countermeasures such as CSRF tokens, SameSite cookie attributes, and network segmentation to protect against these threats.


CSRF Token Implementation

CSRF tokens are cryptographically secure random values tied to user sessions. They ensure that requests originate from authenticated users.

Implementation Steps:
1. Generate a token for each session (e.g., using secrets.token_urlsafe() in Python).
2. Store the token server-side (e.g., in a session or database).
3. Include the token in forms and API requests (e.g., as a hidden input field or header).
4. Validate the token on the server during request processing.

Example (Flask):

from flask import Flask, session, request, redirect, render_template
import secrets

app = Flask(__name__)
app.secret_key = 'super-secret-key'

@app.route('/login')
def login():
    session['csrf_token'] = secrets.token_urlsafe(16)
    return render_template('login.html')

@app.route('/submit', methods=['POST'])
def submit():
    if request.form.get('csrf_token') != session.get('csrf_token'):
        return 'Invalid CSRF token', 403
    # Process request
    return 'Success'

Best Practices:
- Use one-time tokens for sensitive actions (e.g., password changes).
- Regenerate tokens after login or session renewal.


The SameSite attribute prevents cookies from being sent with cross-site requests, mitigating CSRF for cookies.

Options:
- Lax: Cookies are sent with top-level navigations (e.g., links).
- Strict: Cookies are only sent with same-site requests.
- None: Allows cross-site requests but requires the Secure flag.

Example (HTTP Response Header):

Set-Cookie: sessionid=abc123; Path=/; Secure; HttpOnly; SameSite=Lax

Best Practices:
- Set SameSite=Lax for most cookies.
- Avoid SameSite=None unless absolutely necessary (e.g., for third-party services).


Internal Network Segmentation

SSRF attacks exploit servers making unintended internal requests. Segmentation isolates internal services and restricts access.

Mitigation Strategies:
1. Firewall Rules: Block traffic to internal IPs unless explicitly allowed (e.g., using iptables or cloud firewall policies).

# Example: Deny traffic to internal subnet 192.168.0.0/24
iptables -A INPUT -d 192.168.0.0/24 -j DROP
2. Reverse Proxy Restrictions: Use a reverse proxy (e.g., Nginx) to block suspicious URLs:
location /internal {
    deny all;
    return 403;
}
3. Input Validation: Sanitize and restrict URLs to known internal services (e.g., allow only 127.0.0.1 or localhost).

Best Practices:
- Avoid exposing internal APIs to the public internet.
- Use private IP ranges (e.g., 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16).


Key takeaways

  • CSRF tokens must be unique per session, validated server-side, and included in all authenticated requests.
  • SameSite attributes should be set to Lax or Strict for cookies to prevent cross-site request forgery.
  • Network segmentation and firewall rules restrict SSRF by isolating internal services and blocking unauthorized access.
  • Combine these strategies with input validation and regular security audits for comprehensive protection.