DEV Community

Pramitha Jayasooriya
Pramitha Jayasooriya

Posted on

[Solved] Cross-Site Request Forgery (CSRF) Attacks with Spring Security.

CSRF Attact

A typical Cross-Site Request Forgery (CSRF or XSRF) attack aims to perform an operation in a web application on behalf of a user without their explicit consent. In general, it doesn’t directly steal the user’s identity, but it exploits the user to carry out an action without their will.

Consider you are using the website nextflix.com and the attacker’s website evil.com.

Step 1: The Netflix user login to Nextflix.com and the backend server of Nextflix will provide a cookie that will be stored in the browser against the domain name Nextflix.com

Step 2: The same Nexflix user opens an evil.com website in another tab of the browser

Step 3 : The user was tempted and clicked on the malicious link which makes a request to Nextflix.com. And since the login cookie is already present in the same browser and the request change email is being made to the same domain Nextflix.com, The backend server of Nextflix.com can’t differentiate from where the request came. So here the evil.com forged the request as if it is coming from a Nextflix.com UI page.

<form action="https://nextflix.com/changeEmail"
method= "POST" id = "form">
<input type= "hidden" name="email" value="user@evil.com">
</form>
<script>
doucment.getElementById('form').submit()
</script>
Enter fullscreen mode Exit fullscreen mode

Solution to CSRF attack

To defeat an SCRF attack, the application needs a way to determine if the HTTP request is legitimately generated via the application’s user interface. the best way to achieve this is through a CSRF token. A CSRF token is a secure random token that is used to prevent CSRF attacks. The token needs to be unique per user session and should be of large random value to make it difficult to guess.

Let’s see how the CSRF attacks by taking the previous Netflix example again.

Step 1: The Netflix user logs in to Nextflix.com and the backend server of Nextflix will provide a cookie that will be stored in the browser against the domain name Nextflix. com along with a randomly generated unique CSRF token for this particular user session. CSRF token is inserted within hidden parameters of HTML forms to avoid exposure to session cookies.

Step 2: The same Nextflix user opens the evils.com website in another tab of the browser.

Step 3: User tempted and clicked on the malicious link which make a request to Nextflix.com. Since the login cookie is already present in the same browser and the request to change email is being made to the same domain Netflix.com. This time the nextfllix.com backend server except for the CSRF token along with the cookie. the CSRF token must be the same as the initial value generated during the operation.

The CSRF token will be used by the application server to verify the legitimacy of the end-user request if it is coming from the same App UI or not. the application server rejects the request if the CSRF token fails to match the test.

TIPS

By default, Spring Security enables CSRF fixes for all the HTTP methods that result in data changes like POST, DELETE, etc. But not for GET.

Using Spring Security configurations we can disable the CSRF protection for complete applications or only a few paths based on our requirements like below.

http.csrf().disable()
http.csrf().ignoring RequestMatchers("/saveMsg")
Enter fullscreen mode Exit fullscreen mode

Thymeleaf has great integration & support with Spring Security to generate a CSRF token. We just need to add the below code in the login HTML form code and Thymeleaf will automatically append the CSRF token for the remaining pages/forms inside the web application,

<input type="hidden" th:name="${_csrf.parameterName}" th:value="${_csrf.token}" />
Enter fullscreen mode Exit fullscreen mode

Enhancements and Best Practices

1. CSRF Token Storage:
Ensure that the CSRF token is securely stored in the user’s session. Spring Security automatically handles this for you, but it’s crucial to emphasize the importance of secure session management.

2. Token Expiry and Regeneration:
Implement mechanisms to expire and regenerate CSRF tokens to prevent token reuse and enhance security. Spring Security offers built-in features for token expiration.

3. Custom CSRF Header:
Consider using a custom header for CSRF tokens, especially if your application involves multiple technologies or if you want to add an extra layer of security. Spring Security allows customization of the header name.

http.csrf().headerName("X-CSRF-TOKEN");

4. Strict Content Security Policy (CSP):
Enforce strict Content Security Policy headers on your web pages to mitigate the risk of XSS attacks. This will further secure your application by limiting the sources from which resources can be loaded.

http.headers().contentSecurityPolicy("default-src 'self'");

5. CSRF Token in AJAX Requests:
If your application makes AJAX requests, ensure that the CSRF token is included and validated in those requests. Modify your Thymeleaf code accordingly to handle AJAX scenarios.

$.ajax({
    url: '/changeEmail',
    type: 'POST',
    data: {
        email: 'user@evil.com',
        _csrf: /* CSRF Token value */
    },
    success: function(response) {
        // Handle success
    }
});
Enter fullscreen mode Exit fullscreen mode

6. Educate Users:
Educate your users about the importance of not clicking on suspicious links and being cautious while interacting with websites. User awareness is a crucial component in preventing CSRF attacks.

7. Logging and Monitoring:
Implement comprehensive logging and monitoring to keep track of suspicious activities and potential CSRF attacks. This will help in identifying and mitigating threats in real time.

Summary

Incorporating CSRF protection is a fundamental step in securing your Spring Boot applications. By following best practices and leveraging the capabilities of Spring Security, you can significantly reduce the risk of CSRF attacks. Remember that security is an ongoing process, and staying informed about the latest security developments is essential to maintaining a robust defense against evolving threats.

By implementing these additional measures and best practices, you can fortify your application’s security posture and provide a safer online experience for your users. Stay vigilant, keep your dependencies up-to-date, and regularly review and enhance your security practices to adapt to emerging threats.

~By Pramitha Jayasooriya

Contact Details
For further information or to discuss potential opportunities, please feel free to connect with me on my professional and social platforms:

LinkedIn: Pramitha Jayasooriya
GitHub: PramithaMJ
Personal Website: Pramithamj.me
Looking forward to connecting with you!

Top comments (2)

Collapse
 
thetharz profile image
Tharindu Jayawardhana

Great content and keep writing

Collapse
 
pramithamj profile image
Pramitha Jayasooriya

Thank you