Cross-Site Request Forgery (CSRF) is a type of attack where unauthorized commands are transmitted from a user that the web application trusts. Preventing CSRF typically involves server-side measures like:
- Using anti-CSRF tokens (synchronizer tokens) embedded in forms and validated on the server.
- Checking the
Origin or Referer headers.
- Requiring authentication for state-changing requests.
- Implementing SameSite cookies.
Can ModSecurity alone protect against CSRF?
ModSecurity is a Web Application Firewall (WAF) module that sits in front of the web server and can inspect, block, or modify HTTP requests and responses according to defined rules.
While ModSecurity can be configured to mitigate some CSRF attacks by inspecting requests, it cannot fully replace proper backend fixes that validate CSRF tokens or enforce secure state-changing request handling.
What ModSecurity can do:
-
Block requests missing or having invalid Referer or Origin headers
You can write or enable rules that verify these headers to ensure requests come from trusted origins.
-
Enforce stricter HTTP methods
Block unexpected HTTP verbs for certain URLs (e.g., only allow POST on sensitive endpoints).
-
Check for presence of custom headers (e.g., X-Requested-With)
Some apps use custom headers set by JavaScript as a quick CSRF protection signal.
-
Apply known CSRF detection rules
Some ModSecurity rule sets (like OWASP ModSecurity Core Rule Set - CRS) provide basic checks against CSRF vectors.
Limitations of ModSecurity-only protection:
-
Attackers can spoof Referer/Origin headers in some contexts.
-
ModSecurity can't generate or validate anti-CSRF tokens embedded in forms, which are the most robust protection.
-
Legitimate requests from users might be blocked if headers are missing (e.g., privacy-focused browsers or proxies that strip Referer).
-
Complex application logic validation is not feasible in the WAF.
Conclusion
ModSecurity can provide some level of mitigation against CSRF by blocking suspicious requests based on headers or methods, but it should not be considered a complete solution.
The recommended best practice is to fix CSRF vulnerabilities in the backend application by implementing proper token validation or other standard mechanisms. ModSecurity can be used as an additional layer of defense (defense-in-depth), not as a sole protective measure.
Summary
| Aspect | ModSecurity Only | Backend Fix Required |
|---|
| Anti-CSRF Token Validation | No | Yes |
| Check Origin/Referer | Partial (can block missing/wrong headers) | Complementary |
| Enforce HTTP Methods | Yes | Yes (application logic) |
| True CSRF Protection | No | Yes |
| False Positives Risk | Higher (due to missing headers) | Lower |
If you want, I can help draft some example ModSecurity rules to help mitigate CSRF to some extent. Would you like that?