Blog | G5 Cyber Security

CSRF Protection with HTTP Headers

TL;DR

Checking HTTP headers like Origin and Referer can help mitigate Cross-Site Request Forgery (CSRF) attacks, but it’s not a foolproof solution on its own. It’s best used as an *additional* layer of defence alongside proper CSRF tokens.

What is CSRF?

Cross-Site Request Forgery (CSRF) lets attackers trick users into performing actions they didn’t intend to, usually on websites where they are already logged in. Imagine you’re logged into your bank and an attacker gets you to click a malicious link – that link could make changes to your account without your knowledge.

How HTTP Headers Help

HTTP headers contain information about the request being sent from the browser to the server. We can use specific headers to verify if the request originated from our own website.

Steps to Implement Header-Based CSRF Protection

  1. Understand the Relevant Headers:
  • Server-Side Validation (Example using Python/Flask):
  • from flask import Flask, request, redirect, url_for
    
    app = Flask(__name__)
    
    @app.route('/sensitive-action', methods=['POST'])
    def sensitive_action():
      if request.origin != 'https://yourwebsite.com':
        return "Invalid Origin!", 403 #Forbidden
      # ... process the action safely...
      return redirect(url_for('home'))
    

    In this example, we check if the Origin header matches our website’s domain. If it doesn’t, we reject the request.

  • Check for Missing Headers:
  • If either Origin or Referer is missing, treat the request with suspicion. Some browsers don’t send these headers in all cases.

  • Consider Browser Compatibility:
  • Use with CSRF Tokens:
  • Crucially, don’t rely on HTTP headers alone! Always use proper CSRF tokens as your primary defence mechanism. Headers provide an extra layer of security but shouldn’t be the only protection.

    Limitations

    Conclusion

    Checking HTTP headers can be a useful addition to your CSRF protection strategy, but it’s not a replacement for proper CSRF tokens. Implement both for robust security.

    Exit mobile version