Panel Discussion: API Security in DevSecOps. Watch the Recording

Panel Discussion: API Security in DevSecOps. Watch the Recording

Panel Discussion: API Security in DevSecOps. Watch the Recording

Exploring Cross-Site Request Forgery (CSRF) vulnerabilities: Still a threat!

CSRF is a type of attack that occurs when a user clicks on a malicious website, email, or another message that causes the user's web browser to perform an unwanted action on a trusted site on which the user is currently authenticated.

Medusa

9 mins

Exploring CSRF
Exploring CSRF
Exploring CSRF

Attackers can use CSRF to compromise sensitive information and user accounts, such as stealing login credentials and session tokens. CSRF is a serious threat to APIs.

In 2018, a vulnerability in Facebook's "View As" feature was exploited by attackers to steal access tokens, which could then be used to take over user accounts. The attack was possible because of a combination of factors, including improper validation of user input and a bug in the implementation of the "View As" feature. The attack affected millions of users and resulted in a significant loss of trust in the company. Facebook has since implemented measures to prevent such attacks from happening again, but the incident remains a reminder of the importance of constant vigilance in protecting APIs from security threats such as CSRF.

This blog covers the following topics:

  • Understanding Cross-Site Request Sharing (CSRF)

  • Conditions for CSRF to occur

  • Types of CSRF attacks

  • How attackers exploit CSRF Vulnerabilities

  • Prevention measures

What is CSRF (Cross-Site Request Forgery)?

Cross-site request forgery (CSRF) is a type of attack that occurs when a user clicks on a malicious website, email, or another message that causes the user's web browser to perform an unwanted action on a trusted site on which the user is currently authenticated. The attacker can use this attack to steal sensitive information such as login credentials, session tokens, and other sensitive data.

Here is a video tutorial to understand in depth.


What is CSRF Token?

A CSRF token is a unique value that is generated by the server and included in each form submitted by the user. The server then validates the token when the form is submitted to ensure that the request is coming from an authorized source. This technique helps prevent CSRF attacks by ensuring that only authorized requests can be submitted to the server, even if an attacker is able to trick the user into visiting a malicious website or clicking a specially crafted link.

Why is a CSRF token useful?

When a user submits a form, the server generates a unique CSRF token and includes it in the form as a hidden field. The server also stores the token in a session variable on the server side. When the server receives the form submission, it compares the value of the CSRF token in the form with the value stored in the session variable. If the values match, the request is considered to be valid and is processed. If the values do not match, the request is rejected as potentially malicious. This technique helps prevent CSRF attacks by ensuring that only authorized requests can be submitted to the server, even if an attacker is able to trick the user into visiting a malicious website or clicking a specially crafted link.

CSRF tokens come with expiration dates to prevent relayed API requests.

Example of Cross-Site Request Forgery Vulnerability

One example of a cross-site request forgery attack is a hacker creating an HTML form that submits to a trusted website. The form could be designed to look like a harmless survey or login page and may even be hosted on a legitimate-looking domain. When the user submits the form, their web browser sends a request automatically to the trusted site with all the user's session cookies, which allows the attacker to perform actions on behalf of the user.

For example, let's say a user is logged into their bank account and then visits a malicious website that contains a hidden form that submits a transfer request to the bank on the user's behalf. If the user submits the form, their browser will send the request to the bank, along with their session cookies. The bank's servers will see the request as coming from the user and will execute it, transferring money out of the user's account without their knowledge or consent.

For a successful CSRF attack, the following conditions must be met:

  1. The user must be logged in to the target site.

  2. The attacker must be able to create a malicious request that will perform an unwanted action on the target site.

  3. The user must be tricked into performing the malicious action, either by visiting a malicious website or by clicking a specially crafted link.

There are two types of Cross-Site Request Forgery:

  • Stored CSRF: This type of attack occurs when an attacker is able to inject malicious code into a trusted website through a sophisticated XSS attack. The code is then executed when the user visits the site, and can perform actions on behalf of the user, such as changing their password or making unwanted purchases.

  • Reflected CSRF: This type of attack occurs when an attacker is able to trick a user into clicking a link that contains a specially crafted URL. When the user clicks the link, their browser sends a request to the trusted site with all their session cookies, allowing the attacker to perform actions on behalf of the user.

This blog explores the reflected Cross-Site Request Forgery (CSRF) vulnerability.

Below is the flowchart for the attack we will demonstrate in practice.

CSRF in Action

CSRF in action

Example of CSRF with Practical Demonstration

For the demonstration, I’m going to use a lab from PortSwigger.

This is a blogging website with a change in email functionality. This functionality allows user to update their email.

blogging website


My proxy is already turned on. I'm going to change my email from weiner@normal-user.net to weiner00@normal-user.net, and then click on "update email."

Trying to change my email


This is the request that i’ve captured in BurpSuite, i’m going to send this to repeater

Request captured


Here we can see two parameters: "email" and "csrf". These parameters contain the values of our updated email and CSRF token, respectively.

updated email and CSRF token

Once i send the request, there we can see the updated email address. So is how the function normally works.

Exploitation

I am going to recapture the update email request and send it to the repeater. However, this time I will change the value of the CSRF token to a random value, such as "test."

changing the csrf token

Sending the request led to a 400 Bad Request error because the CSRF token was incorrect.

Test for CSRF using the best proactive API Security product

Our customers love us for our proactive approach and world class API Security test templates. Try Akto's test library yourself in your testing playground. Play with the default test or add your own.

Test for CSRF using the best proactive API Security product

Our customers love us for our proactive approach and world class API Security test templates. Try Akto's test library yourself in your testing playground. Play with the default test or add your own.

Test for CSRF using the best proactive API Security product

Our customers love us for our proactive approach and world class API Security test templates. Try Akto's test library yourself in your testing playground. Play with the default test or add your own.

How to Bypass CSRF?

Again i’m going to change the value of the email parameter to attacker@normal-user.net

change email param


To change the HTTP method of a request, left-click on the request and select the "Change the HTTP Method" option from the menu. The request will then be updated to reflect the selected method, as shown in the image below.

change HTTP method


response is 200 OK


Send the request and you will see that the response is 200 OK and the email has been successfully changed, even though the CSRF token is incorrect. Therefore, the server is not verifying the CSRF token when the HTTP method is GET.

This confirms that the server is vulnerable to CSRF, but how can we exploit it to affect other users?

Creating PoC

To affect other users, an attacker will host their own domain, inject some malicious JavaScript into it, and send the link to the intended victims. When the victim clicks on the link, the JavaScript is triggered and automatically makes a request to the vulnerable server to update the victim's email. Since the server does not verify the CSRF token when the request HTTP method is "GET", the email address of the victim can be changed without their consent.

CSRF POC


This is the exploit server and the malicious javascript code is in the body.

<form action="[<https://YOUR-LAB-ID.web-security-academy.net/my-account/change-email>](<https://your-lab-id.web-security-academy.net/my-account/change-email>)">
<input type="hidden" name="email" value="anything%[40web-security-academy.net](<http://40web-security-academy.net/>)"> 
</form>

This is an HTML <form> element that has an action attribute set to "<https://YOUR-LAB-ID.web-security-academy.net/my-account/change-email>". The action attribute specifies the URL where the form data will be sent when the form is submitted.

Inside the form, there is an <input> element with the following attributes:

  • type="hidden": This specifies that the input field is hidden and not visible to the user.

  • name="email": This assigns the name "email" to the input field.

  • value="anything%40web-security-academy.net": This sets the initial value of the input field to "anything@web-security-academy.net". The %40 is an URL-encoded representation of the "@" symbol.

<script> 
  document.forms[0].submit();
</script>

This is a JavaScript code block enclosed in <script> tags. It uses the submit() method to automatically submit the first form on the page.

document.forms[0] refers to the first form element in the document (assuming there is at least one form). The submit() method triggers the form submission process, which would typically send the form data to the URL specified in the action attribute.

Once you deliver the exploit to the victim, and they click on it, the exploitation will be successful.

XSS versus CSRF

Cross-Site Scripting (XSS) and Cross-Site Request Forgery (CSRF) are both web application vulnerabilities, but they differ in their nature and impact:

Cross-Site Scripting (XSS):

XSS occurs when an attacker injects malicious scripts into a trusted website, which are then executed by the victim's web browser. This vulnerability allows attackers to steal sensitive information, such as login credentials, and perform actions on behalf of the user. XSS attacks can be classified into three types:

  1. Stored XSS: The malicious script is permanently stored on the target website, such as in a database. When a user accesses the affected page, the script is rendered, and the user's browser executes it.

  2. Reflected XSS: The malicious script is embedded in a URL or a form input that is immediately reflected back to the user. When the user clicks on the manipulated URL or submits the form, the script is executed by their browser.

  3. DOM-based XSS: The vulnerability arises from insecure JavaScript coding that manipulates the Document Object Model (DOM) of a web page. The malicious script affects the page's structure and content, leading to the execution of unauthorized actions.

Cross-Site Request Forgery (CSRF):

CSRF occurs when an attacker tricks a user into performing unwanted actions on a trusted website where the user is authenticated. This is achieved by exploiting the trust placed in the website and bypassing the same-origin policy. CSRF attacks can lead to actions being performed on behalf of the user without their consent. CSRF attacks are typically executed through maliciously crafted links or forms.

The main difference between XSS and CSRF is the nature of the attack:

  • XSS focuses on injecting and executing malicious scripts within a website, affecting the user's browsing experience and compromising their data.

  • CSRF focuses on tricking the user into performing unintended actions on a trusted website, using the user's existing authentication.

Bypassing anti-CSRF measures

To bypass anti-CSRF measures, attackers may employ various techniques depending on the specific implementation and vulnerabilities present. Here are a few common methods:

Referer-based CSRF defenses

In addition to CSRF token defenses, some applications rely on the HTTP Referer header to protect against CSRF attacks. They do this by checking if the request originates from their own domain. However, this method is less effective and can often be bypassed.

Certain applications check the Referer header in a simplistic manner that can be tricked. For instance, if the application only checks if the domain in the Referer begins with the expected value, an attacker can insert this value as a subdomain in their own domain, like so: http://vulnerable-website.com.attacker-website.com/csrf-attack.

Similarly, if the application merely checks if the Referer includes its own domain name, the attacker can put the necessary value in a different part of the URL, such as http://attacker-website.com/csrf-attack?vulnerable-website.com.

Same-Site Cookies

SameSite cookies are a browser security feature that helps defend against CSRF (Cross-Site Request Forgery) attacks. They control when cookies are sent with cross-origin requests, which is crucial for CSRF protection.

How SameSite Cookies Work:

  • SameSite cookies can be set to "Strict," "Lax," or "None."

  • When set to "Strict" or "Lax," these cookies block the automatic inclusion of cookies in cross-origin requests, reducing the risk of CSRF attacks.

Defending Against CSRF with SameSite Cookies:

  • Request Control: SameSite cookies prevent automatic cookie inclusion in cross-origin requests, making it harder for attackers to exploit user sessions.

  • Mitigating CSRF: CSRF attacks often rely on automatic cookie inclusion, which SameSite cookies help prevent.

Bypassing SameSite Cookies:

  • Insecure Third-Party Contexts: If set to "None," SameSite cookies can still be sent in cross-origin requests, potentially enabling CSRF attacks.

  • Cookie Theft: If an attacker steals a user's session cookie directly, SameSite may not prevent its misuse.

  • Cookieless CSRF: Some CSRF attacks don't rely on cookies and can bypass SameSite protections.

CSRF Token Validation:

In some cases, the validation of a CSRF token can vary based on factors like the HTTP method used, whether the token is present, or even whether the token is checked against the user's session. Additionally, some applications may not always confirm that the token matches the user's current session when processing a request.

Prevention of CSRF

The following are some preventive measures for Cross-Site Request Forgery (CSRF):

  • Use a unique and short-lived CSRF token for each form submitted by the user and validate it on the server side.

  • It is not recommended to use GET requests when attempting to change the state of a system. Instead, it is advisable to use other HTTP methods such as POST, PUT, or DELETE requests, which are more appropriate for state-changing operations.

  • For API-driven sites that do not use <form> tags, consider utilizing custom request headers for CSRF prevention.

  • Consider verifying the origin with standard headers using the guidelines provided in OWASP's Cross-Site Request Forgery Prevention Cheat Sheet.

  • Use same-site cookies to prevent cookies from being sent with cross-site requests.

  • Consider implementing user interaction based protection for highly sensitive operations.

  • Implementing Anti-CSRF tokens can effectively prevent CSRF attacks and protect users' sensitive information and accounts. It is an essential yet simple step towards ensuring the security of web applications.

  • Use Content Security Policy (CSP) to limit the sources of content that can be loaded on a web page.

  • If possible, limit the HTTP methods and verify the CSRF token in each request.

In conclusion, Cross-Site Request Forgery (CSRF) is a serious threat to APIs that can result in the compromise of sensitive information and user accounts. It is important for developers to understand the conditions necessary for a CSRF attack to occur and to implement prevention measures, such as CSRF tokens, same-site cookies, and proper validation and sanitization of user input. By following these best practices, developers can help protect their users and their APIs from this common type of attack.

Thank you for being a part of this blog. Check out Akto's test library to start testing for API vulnerabilities.

Want to ask something?

Our community offers a network of support and resources. You can ask any question there and will get a reply in 24 hours.

Want to ask something?

Our community offers a network of support and resources. You can ask any question there and will get a reply in 24 hours.

Want to ask something?

Our community offers a network of support and resources. You can ask any question there and will get a reply in 24 hours.

Follow us for more updates

Experience enterprise-grade API Security solution