6 CSRF Mitigation Techniques You Must Know

Oliver Moradov

What Is CSRF (Cross-Site Request Forgery)?

Cross-site request forgery (CSRF) is a cyber attack technique in which hackers impersonate a legitimate, trusted user. CSRF attacks can be used to change firewall settings, post malicious data to forums, or conduct fraudulent financial transactions. 

What makes CSRF attacks especially concerning is that users whose account is impersonated are typically unaware that the attack has occurred. If a user becomes aware of an attack, it may have been after the damage has occurred and recovery may not be possible.

CSRF relies on a browser-based process that makes login to applications more convenient. When a user accesses a site after they have already logged in, the browser often keeps the user signed in by passing an authentication token. This token typically includes the user’s session cookies, basic authentication credentials, IP address, and even Windows domain credentials. 

The problem is that if there is no validation of the authentication token, it is easy for an attacker to steal the token and impersonate the user. The website cannot differentiate between a fake user request and a legitimate user request. This has given rise to the use of CSRF tokens in all web frameworks, which can allow websites to verify that a session token is valid.

Related content: Read our guide to CSRF attacks

In this article:

CSRF Mitigation Techniques

Here are some techniques that can help prevent and mitigate CSRF attacks.

1. Token Synchronization

CSRF tokens help prevent CSRF attacks because attackers cannot make requests to the backend without valid tokens. Each CSRF token should be secret, unpredictable, and unique to the user session. 

Ideally, the server-side should create CSRF tokens, generating a single token for every user request or session. It is more secure to use separate tokens per request than per session because it shortens an attacker’s window to exploit stolen tokens. 

However, the per-request token pattern can impact usability. For example, it might hinder the browser’s ability to return to previous pages with expired tokens. Interacting with a previous page could generate false-positive CSRF security events. With the per-session token pattern, the server stores the value of each token in the session, allowing all subsequent requests to use it for the duration of the session. 

If the client issues a request, the server-side must verify the token’s validity, comparing the request token against the user session token. If the server-side component cannot identify a token in the request, or if it finds a token that doesn’t match the user session’s value, it should abort the request. It is recommended to log such events as potential CSRF attacks.

Related content: Read our guide to CSRF tokens

2. Double-Submitting Cookies

The double-submit cookie method is an alternative to maintaining the CSRF token state on the server-side, which can be problematic. It is a stateless, easily implemented technique that sends random values twice (once as request parameters and again in cookies). The server then checks the two random values from the request parameter and cookie to ensure they match.

Before a user authenticates, the site should create a cryptographically robust random value, setting it as a separate cookie on the user device. This additional cookie, combined with the session identifier, provides an added layer of defense, requiring all transaction requests to include the random (or pseudorandom) value. The server only accepts requests as legitimate if both cookies match on the server-side—otherwise, it rejects the requests.

Including tokens in encrypted cookies (in addition to authentication cookies) can help enhance this technique’s security. Once decrypted, the server must match each cookie with the hidden token in a form field or AJAX parameter call. This technique ensures that subdomains cannot overwrite encrypted cookies unless they have information like an encryption key. 

Cookies containing hash-based message authentication code (HMAC) values are a simpler option than encrypted cookies, enabling tokens to contain secret keys that only the server knows. They work similarly to encrypted cookies, which also rely on server-exclusive information, but they require less computational power than encryption and decryption. Both encryption and HMAC-based cookies effectively mitigate CSRF because attackers lack the knowledge required to recreate cookie values from stolen tokens. 

3. Same-Site Cookies

Same-site cookies help defend against CSRF attacks by restricting the cookies sent alongside each request. The ability of HTML elements to send cookies with requests provides an opening for CSRF. The developer can ensure that only certain cookies can accompany a request with same-site cookies. 

The browser stores several elements when a web app sets cookies on a website. In addition to key and value data, cookies contain a domain field that helps distinguish between first- and third-party cookies. A first-party cookie has a domain field matching the URL in the browser’s address bar, while the domain of a third-party cookie does not match the URL. Web apps often use first-party cookies to store session information, while analytics tools often use third-party cookies.

Same-site cookies contain an additional field specifying whether the browser can send a first-party cookie with requests from HTML elements from different URLs. This mechanism lets the application restrict requests to sites with the same URL. 

4. Enabling User Interaction

While most CSRF techniques do not involve user interaction, users can help secure transactions in some cases. Requiring user interaction helps prevent operations by unauthorized users, including CSRF attacks. When properly implemented, re-authentication mechanisms, CAPTCHA challenges, and one-time tokens can provide a strong defense against CSRF. 

These techniques are useful but not always practical, as they create additional hurdles that impact user experience. Therefore, this approach is best suited for critical operations like financial transactions, account detail modifications, or password changes.

5. Custom Headers for Requests

Adding custom request headers is an especially effective defense for API and AJAX endpoints. This technique uses same-origin policies (SOPs) to restrict the ability to add custom headers. Users can only add custom headers using JavaScript and must add the headers within their origin. 

Most browsers do not permit JavaScript to use custom headers for cross-origin requests by default. To prevent a CSRF attack, developers can verify the presence of custom headers and values across the AJAX endpoints on the server-side. This approach does not usually require introducing server-side state data or making UI changes. It is especially suitable for REST services because developers can easily add a custom header (and value). 

While this method is suited to AJAX calls, it is insufficient for protecting <form> tags, which requires additional security measures like tokens. The Cross-Origin Resource Sharing (CORS) configuration must be strong to ensure the solution’s efficacy. A custom header for a request from another domain will trigger a preflight CORS check.

6. Conduct Regular Web Application Security Tests to Identify CSRF

Even if vulnerabilities in web applications with CSRF attacks are successfully addressed, application updates and code changes may expose your application to CSRF in the future. Dynamic application security testing (DAST) helps you continuously scan and test for potential security weaknesses in web applications, including CSRF vulnerabilities.

Bright Security is a next-generation DAST solution that helps automate the detection and remediation of many vulnerabilities including CSRF, early in the development process, across web applications and APIs. 

By shifting DAST scans left, and integrating them into the SDLC, developers and application security professionals can detect vulnerabilities early, and remediate them before they appear in production. NexDAST completes scans in minutes and achieves zero false positives, by automatically validating every vulnerability. This allows developers to adopt the solution and use it throughout the development lifecycle. 

Scan any web app, or REST, SOAP and GraphQL APIs to prevent CSRF vulnerabilities try Bright Security free

Secure your app with every build

Sign up for a FREE Bright account.
Related Articles
Categories