TryHackMe - CSRF
CSRF
Learn how a CSRF vulnerability works and methods to exploit and defend against CSRF vulnerabilities.
What is CSRF?
CSRF is a type of security vulnerability where an attacker tricks a user’s web browser into performing an unwanted action on a trusted site where the user is authenticated. This is achieved by exploiting the fact that the browser includes any relevant cookies (credentials) automatically, allowing the attacker to forge and submit unauthorised requests on behalf of the user (through the browser). The attacker’s website may contain HTML forms or JavaScript code that is intended to send queries to the targeted web application.
Cycle of CSRF
A CSRF attack has three essential phases:
- The attacker already knows the format of the web application’s requests to carry out a particular task and sends a malicious link to the user.
- The victim’s identity on the website is verified, typically by cookies transmitted automatically with each domain request and clicks on the link shared by the attacker. This interaction could be a click, mouse over, or any other action.
- Insufficient security measures prevent the web application from distinguishing between authentic user requests and those that have been falsified.
Effects of CSRF
Understanding CSRF’s impact is crucial for keeping online activities secure. Although CSRF attacks don’t directly expose user data, they can still cause harm by changing passwords and email addresses or making financial transactions. The risks associated with CSRF include:
- Unauthorised Access: Attackers can access and control a user’s actions, putting them at risk of losing money, damaging their reputation, and facing legal consequences.
- Exploiting Trust: CSRF exploits the trust websites put in their users, undermining the sense of security in online browsing.
- Stealthy Exploitation: CSRF works quietly, using standard browser behaviour without needing advanced malware. Users might be unaware of the attack, making them susceptible to repeated exploitation.
Understanding these risks is essential for implementing effective measures to protect web applications from CSRF vulnerabilities.
Double Submit Cookie Bypass
Overview
We’ve observed that without CSRF tokens, the bank web application was susceptible to vulnerabilities, exposing it to potential exploitation. However, the introduction of CSRF tokens significantly enhances security measures.
A CSRF token is a unique, unpredictable value associated with a user’s session, ensuring each request comes from a legitimate source. One effective implementation is the Double Submit Cookies technique, where a cookie value corresponds to a value in a hidden form field. When the server receives a request, it checks that the cookie value matches the form field value, providing an additional layer of verification.
How it works
- Token Generation: When a user logs in or initiates a session, the server generates a unique CSRF token.
- This token is sent to the user’s browser both as a cookie (CSRF-Token cookie) and embedded in hidden form fields of web forms where actions are performed (like money transfers).
- User Action: Suppose the user wants to transfer money. They fill out the transfer form on the website, which includes the hidden CSRF token.
- Form Submission: Upon submitting the form, two versions of the CSRF token are sent to the server: one in the cookie and the other as part of the form data.
- Server Validation: The server then checks if the CSRF token in the cookie matches the one sent in the form data. If they match, the request is considered legitimate and processed; if not, the request is rejected.
Possible Vulnerable Scenarios
Despite its effectiveness, it’s crucial to acknowledge that hackers are persistent and have identified various methods to bypass Double Submit Cookies:
- Session Cookie Hijacking (Man in the Middle Attack): If the CSRF token is not appropriately isolated and safeguarded from the session, an attacker may also be able to access it by other means (such as malware, network spying, etc.).
- Subverting the Same-Origin Policy (Attacker Controlled Subdomain): An attacker can set up a situation where the browser’s same-origin policy is broken. Browser vulnerabilities or deceiving the user into sending a request through an attacker-controlled subdomain with permission to set cookies for its parent domain could be used.
- Exploiting XSS Vulnerabilities: An attacker may be able to obtain the CSRF token from the cookie or the page itself if the web application is susceptible to Cross-Site Scripting (XSS). By creating fraudulent requests with the double-submitted cookie CSRF token, the attacker can get around the defence once they have the CSRF token.
- Predicting or Interfering with Token Generation: An attacker may be able to guess or modify the CSRF token if the tokens are not generated securely and are predictable or if they can tamper with the token generation process.
- Subdomain Cookie Injection: Injecting cookies into a user’s browser from a related subdomain is another potentially sophisticated technique that might be used. This could fool the server’s CSRF protection system by appearing authentic to the main domain.
Samesite Cookie Bypass
Let’s dive into a crucial defence mechanism known as SameSite cookies. These cookies come with a special attribute designed to control when they are sent along with cross-site requests. Implementing the SameSite cookie property is a reliable safeguard against cross-origin data leaks, CSRF, and XSS attacks. Depending on the request’s context, it tells the browser when to transmit the cookie. Strict, Lax, and None are the three potential values for the attribute.
The most substantial level of protection is offered by setting it to strict, which guarantees that the cookie is only sent if the request comes from the same origin as the cookie. Specific cross-site usage is permitted by lax, such as top-level navigations, which are less likely to raise red flags. None of them need the secure attribute, and all requests made by websites that belong to third parties will send cookies.
Different Types of SameSite Cookies
- Lax: Lax SameSite cookies are like a friendly neighbour. They provide a moderate level of protection by allowing cookies to be sent in top-level navigations and safe HTTP methods like GET, HEAD, and OPTIONS. This means that cookies will not be sent with cross-origin POST requests, helping to mitigate certain types of CSRF attacks. However, cookies are still included in GET requests initiated by external websites, which may pose a security risk if sensitive information is stored in cookies.
- Strict: Strict SameSite cookies act as vigilant guards. They offer the highest level of protection by restricting cookies to be sent only in a first-party context. This means that cookies are only sent with requests originating from the same site that set the cookie, effectively preventing cross-site request forgery attacks. By enforcing strict isolation between different origins, strict SameSite cookies significantly enhance the security of web applications, especially in scenarios where sensitive user data is involved.
- None: None SameSite cookies behave like carefree globetrotters. They are sent with both first-party and cross-site requests, making them convenient for scenarios where cookies need to be accessible across different origins. However, to prevent potential security risks associated with cross-site requests, None SameSite cookies require the Secure attribute if the request is made over HTTPS. This ensures that cookies are only transmitted over secure connections, reducing the likelihood of interception or tampering by malicious actors during transit.
Lax with POST Scenario - Chaining the Exploit
As a pentester, it is important to check the cookies being set by the website. As the cookie set in the last example was Lax, it was possible to logout any user. But the above scenario is possible only with GET requests, and nothing can be done in case of POST requests.
Initially, when the SameSite attribute was introduced to increase web security by restricting how cookies are sent in cross-site requests, Google Chrome and other browsers did not enforce a default behaviour for cookies without a specified SameSite attribute. This meant developers had to explicitly set SameSite=None
to allow cookies to be sent in cross-site requests, such as in iframes or third-party content. However, Chrome changed its default behaviour to enhance security and privacy further and better protect against CSRF attacks. If a SameSite attribute is not specified for a cookie, Chrome automatically treats it as SameSite=Lax
. This default setting allows cookies to be sent in a first-party context and with top-level navigation GET requests but not in third-party or cross-site requests, thereby balancing usability with increased security measures.
But what if we want to make a POST request? Can we do something? The answer is Yes. As per the official documentation by Chrome:
“Chrome will make an exception for cookies set without a SameSite attribute less than 2 minutes ago. Such cookies will also be sent with non-idempotent (e.g. POST) top-level cross-site requests despite normal SameSite=Lax cookies requiring top-level cross-site requests to have a safe (e.g. GET) HTTP method.”
- We can exploit the Chrome feature that sends the cookies in each web request if modified in the last 2 minutes. As a pentester, it is essential to understand each web request and response. The
isBanned
cookie value is updated in two instances, once during login and the other during logout. - We can chain the process to make the user visit the logout link; once he is logged out and the
isBanned
cookie is updated, we have a 2-minute window to callindex.php
to update the isBanned cookie value. - Here is the code that will take the user to the logout page and then make a call to
index.php
with the updatedisBanned
cookie value.
Defense Mechanism
Secure Coders
- Anti-CSRF Tokens: Integrate anti-CSRF tokens into each form or request to ensure that only requests with valid and unpredictable tokens are accepted, thwarting CSRF attacks.
- SameSite Cookie Attribute: Set the SameSite attribute on cookies to ‘Strict’ or ‘Lax’ to control when cookies are sent with cross-site requests, minimising the risk of CSRF by restricting cookie behaviour.
- Referrer Policy: Implement a strict referrer policy, limiting the information disclosed in the referer header and ensuring that requests come from trusted sources, thereby preventing unauthorised cross-site requests.
- Content Security Policy (CSP): Utilise CSP to define and enforce a policy that specifies the trusted sources of content, mitigating the risk of injecting malicious scripts into web pages.
- Double-Submit Cookie Pattern: Implement a secure double-submit cookie pattern, where an anti-CSRF token is stored both in a cookie and as a request parameter. The server then compares both values to authenticate requests.
- Implement CAPTCHAS: Secure developers can incorporate CAPTCHA challenges as an additional layer of defense against CSRF attacks especially in user authentication, form submissions, and account creation processes.
Pentesters/Red Teamers
- CSRF Testing: Actively test applications for CSRF vulnerabilities by attempting to execute unauthorised actions through manipulated requests and assess the effectiveness of implemented protections.
- Boundary Validation: Evaluate the application’s validation mechanisms, ensuring that user inputs are appropriately validated and anti-CSRF tokens are present and correctly verified to prevent request forgery.
- Security Headers Analysis: Assess the presence and effectiveness of security headers, such as CORS and Referer, to enhance the overall security and prevent various attack vectors, including CSRF.
- Session Management Testing: Examine the application’s session management mechanisms, ensuring that session tokens are securely generated, transmitted, and validated to prevent unauthorised access and actions.
- CSRF Exploitation Scenarios: Explore various CSRF exploitation scenarios, such as embedding malicious requests in image tags or exploiting trusted endpoints, to identify potential weaknesses in the application’s defences and improve security measures.