CSRF Takedown: Defeating Web Exploits with Code

Jeremiah Talamantes
InfoSec Write-ups
Published in
5 min readMar 28, 2023

--

Attacking the Authenticated User

Photo credit: Computerworld 2018

Today, we’re going to dive into a fascinating topic in the realm of cybersecurity: Cross-Site Request Forgery, or CSRF for short. Have you ever wondered how malicious actors can exploit a user’s authenticated session to perform unauthorized actions on their behalf? That’s CSRF in action, and it’s as sneaky as it sounds.

So, what exactly is CSRF? In simple terms, it’s a type of attack where an unsuspecting user is tricked into performing actions on a website without their consent, all while using their authenticated session. That’s right, and the attackers don’t need your password to cause havoc — they need you to be logged in.

If you like my content, please visit Compliiant.io and share it with your friends and colleagues! Cybersecurity services, like Penetration Testing and Vulnerability Management, for a low monthly subscription. Pause or cancel at any time. See https://compliiant.io/

Cybersecurity Services as a Subscription with Compliiant

Real-life CSRF Attack

Let’s imagine a real-life scenario to make this concept clearer. Picture this: You’re an avid online banking user, and you’ve just finished transferring money to your friend. While your bank’s website is still open in your browser, you visit another site to catch up on the latest news. Unfortunately, this news site has a hidden, malicious script lurking behind the scenes.

Here’s where the CSRF magic (or mischief) happens. The malicious script sends a request to your bank’s website to transfer a hefty sum to the attacker’s account, all without your knowledge. Since you’re still logged in and have a valid session, the bank’s website processes the request as if you initiated it. And just like that, your hard-earned money has vanished into thin air!

That’s a frightening example of the impact of CSRF attacks. They exploit a website's trust in a user’s session, resulting in unauthorized actions, stolen data, and even financial loss. Sounds like something we should protect against, right? Absolutely!

Defeating CSRF Attacks!

Thankfully, there are effective methods to defend against CSRF attacks. One popular technique is to use CSRF tokens (aka, Anti-CSRF). These tokens are unique, random values generated by the server and sent to the client as a hidden form field. When the client submits the form, the token is sent back to the server, verifying if it matches the stored token. If the tokens match, the request is legitimate; if not, the request is rejected.

So, why does this work? Well, CSRF tokens are unique to each user and each session. This means that even if an attacker crafts a malicious request, they won’t have the correct token to accompany it, rendering their attempt futile.

Our online banking scenario would play out differently with CSRF protection in place. The attacker’s malicious script would still send a request to transfer money, but without the correct token, the bank’s server would reject it. Your account balance remains intact, and the CSRF villain is foiled!

Many frameworks these days have built-in methods for CSRF. However, to illustrate how these methods work in action, look at the sample code below.

Anti-CSRF Sample Code

Look at the sample code below and clone it from my Github. The CSRFProtection class is a simple yet effective implementation for defending against CSRF attacks. It encapsulates the functionality required to generate and validate CSRF tokens, ensuring that requests made to your web application are legitimate and not initiated by malicious actors.

The class has two primary methods:

  1. generateToken(): This method generates a secure, random CSRF token, stores it in the user's session, and returns it. The token is generated using the random_bytes() function, which creates a cryptographically secure random value.
  2. validateToken($receivedToken): This method checks whether the provided $receivedToken matches the token stored in the user's session. If the tokens match, the request is considered valid, and the method returns true. The method returns if the tokens do not match or are missing (false), indicating a potential CSRF attack.
https://github.com/jeremiahtalamantes/csrf-class

The following code demonstrates how to use the CSRFProtection class to generate a CSRF token and include it in an HTML form as a hidden field. This is a crucial step in implementing CSRF protection in your web application.

By including the CSRF token in the form, you provide a unique identifier that ties the form submission to the user’s session. This token is used later to validate the legitimacy of the submitted request, helping to prevent CSRF attacks.

https://github.com/jeremiahtalamantes/csrf-class

The following code demonstrates how to use the CSRFProtection class to validate a submitted CSRF token when processing form data in the submit.php script. Validating the token ensures the request is legitimate and not a CSRF attack.

First, the CSRFProtection.php file is included, and an instance of the CSRFProtection class is created. Next, the script checks if the HTTP request method is POST. If so, it retrieves the submitted CSRF token from the $_POST array. The validateToken($receivedToken) method is then called to check if the submitted token matches the token stored in the user's session.

https://github.com/jeremiahtalamantes/csrf-class

If the tokens match, the request is considered valid, and the form data can be processed safely. If the tokens do not match or are missing, the script handles the error, in this case, by displaying an “Invalid CSRF token” message and terminating the script execution.

By validating the CSRF token in the form processing script, you can effectively prevent unauthorized requests and protect your web application against CSRF attacks.

CSRF is a sneaky and potentially devastating security risk. As web developers, it’s essential to understand the nature of these attacks and implement appropriate defenses to safeguard our users’ data and actions. With proper measures, we can turn the tide against CSRF attacks and make the internet safer.

Thanks for reading!

--

--

Founder @ Compliiant.io, Founder @ Mitigated.io, Security @ Microsoft, Author of Building Security Partner Programs, Founder @ RedTeam Security, Former CISO