Introduction#

  • 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 has three essential phases:
    • Phase:1 attacker already knows the format of web application’s requests to carry out a particular task and sends a malicious link to the user.
    • Phase:2 The victim’s identity on the website is verified, typically by cookies transmitted automatically with each domain request and clicks on link shared by attacker. This interaction could be a click, mouse over, or any other action.
    • Phase:3 Insufficient security measures prevent web application from distiguishing between authorized and unauthorized requests, leading to the execution of the attacker’s malicious request.

Effects of CSRf#

  • Risks associated with the CSRF include:
  • Unauthorized access: Access and control user’s actions, putting them at risk of losing money, damaging their reputation, and facing legal consequences.
  • Exploit Trust: CSRF exploits the trust websites put in their users, undermining the sense of security in online browsing.
  • Stealthy Exploitation: It works queitly, using standard browser behaviour without needing adavanced malware. Users might be unaware of the attack, making them susceptible to repeated exploitation.

Type of CSRF#

Traditional CSRF#

  • Conventional CSRF attacks frequently concentrate on state-changing actions carried out by submitting forms.
  • The victim is tricked into submitting a form without realising the associated data like cookies, URL parameters etc
  • The victim’s web browser sends http request to a web application from where the victim has already been authenticated.
  • These forms are made to transfer money, modify account information, or alter an email address.

XMLHttpRequest CSRF#

  • An asynchronus CSRF exploitation occurs when operations are intiated without a complete page request-response cycle.
  • This is typical of contemporary online apps that leverage asynchronous server communication (via XMLHttpRequest or Fetch API) and JavaScript to produce more dynamic user interfaces.
  • These attack use asynchronus calls instead of the more conventional form submision. Still, they exploit the same trust relationship between the user and the online service.
  • Consider an online email client, for instance, where users may change their email preferences without reloading the page. If this online application is CSRF-vulnerable, a hacker might create a fake asynchronous HTTP request, usually a POST request, and alter the victim’s email preferences, forwarding all their correspondence to a malicious address.

Flash based CSRF#

  • The term “Flash-based CSRF” describes the technique of conducting a CSRF attack by taking advantage of flaws in Adobe Flash Player components.
  • Internet applications with features like interactive content, video streaming, and intricate animationsflash based csrf have been made possible with Flash. But over time, security flaws in Flash, particularly those that can be used to launch CSRF attacks, have become a major source of worry.
  • As HTML5 technology advanced and security flaws multiplied, official support for Adobe Flash Player ceased on December 31, 2020.
  • Even though Flash is no longer supported, a talk about Flash-based cross-site request forgery threats is instructive, particularly for legacy systems that still rely on antiquated technologies.
  • A malicious Flash file (.swf) posted on the attacker’s website would typically send unauthorised requests to other websites to carry out Flash-based CSRF attacks.

Basic CSRF - Hidden Link/Image Exploitation#

  • A covert technique known as hidden link/image exploitation in CSRF involves an attacker inserting a 0x0 pixel image or a link into a webpage that is nearly undetectable to the user.
  • Typically, the src or href element of the image is set to a destination URL intended to act on the user’s behalf without the user’s awareness. It takes benefit of the fact that the user’s browser transfers credentials like cookies automatically.
    <!-- Website --> 
    <a href="https://mybank.thm/transfer.php" target="_blank">Click Here</a>  
    <!-- User visits attacker's website while authenticated -->
    
  • 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. The user fills 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 cookies come with a special attribute designed to control when they are sent along with cross-site requests.
  • Its implementation is reliable safeguard against cross origin data leaks, CSRF, and XSS attacks.
  • Depending on the request’s context, it tells the browser to transmit the cookie.
  • Strict, Lax and None are the three possible values for the Samesite attribute.

Type of Samesite Cookies#

  • Lax: Provide moderate level protection by allowing cookies to be sent in top-level navigation and safe HTTP methods like GET, HEAD, and OPTIONS. This means that cookies will be not sent with cross-origin POST requests, helping to mitigate certain type of CSRF attacks. However, cookies are still included in GET requests intiated by external websites, which may pose a security risk if senistive information stored in cookies.
  • Strict: Provide highest level of protection by ensuring cookies are never sent with cross-origin requests, including GET requests intiated by external websites. This makes it more secure but may impact functionality if not implemented carefully.
  • None: Provide no protection and allow cookies to be sent with all cross-origin requests, including GET requests intiated by external websites. This is the least secure option and should be used with caution.

Lax with POST - Chaining the Exploit#

  • As a pentester, it is important to check the cookies being set by website.
  • When the SameSite attribute was introduced to increase web security by restricting how cookies are sent in cross-site requests, chrome and other browsers did not enforce a default behavior for cookies without a specified samesite attribute. This meant developers had to explicitly set the SameSite=None to allow cookies to be sent with cross-origin requests.
  • However, Chrome has changed its behavior to enforce SameSite=Lax as default setting, allwing cookies to be sent in a first party context and with top level navigation GET requests, but not with cross-origin requests.
  • Chrome also said “It will make an exception for cookies set without a SameSite attribute less than 2 minutes ago. Such cookies will also be sent with POST top-level cross site requests despite a normal SameSite=Lax cookies requiring top-level cross-site requests to hava a GET method.”

Few Additional Exploitation Techniques#

XMLHTTPRequest Exploitation#

  • In the context of an AJAX request, CSRF is like someone making your web browser unknowigly send a request to a website where you have logged in. It’s as if someone tricked your browser into doing something on a trusted site without your awareness, potentially causing uninteded actions or changes in your account. CSRF attacks can still succeded even when AJAX requests are subjected to the Seme-ORigin-Policy (SOP), which trypically forbids cross-origin requests.
  • Here is the example of how an attacker can update a password of mybank.thm and send an asynchronus request to update the email seamlessly.
<script>
  var xhr = new XMLHttpRequest();
  xhr.open("POST", "http://mybank.thm/updatepassword.php", true);
  xhr.setRequestHeader("X-Requestsed-With", "XMLHttpRequest");
  xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  xhr.onreadystatechang = function() {
    if (xhr.readyState = XMLHttpRequest.DONE && xhr.status == 200) {
      alert("ACtion executed")
    }
  };
  xhr.send('actioni=execute&parameter=value');

Same Origin policy (SOP) and Cross-Origin Resource Shareing (CORS) Bypass#

  • CORS and SOP bypass to launch CSRF is like an attacker using to trick to make web browser send requests to different website than the on youre on. Under an appropriate CORS policy, certain requests could only be submitted by recognised origins. However, misconfiguration in CORS policies can allow attackers to circumvent these limitations if they rely on origins that attacker can control or if credentials are included in cross-origins requests.
  • Below is simple PHP server side script that handles POST requests. It has a vulnerable CORS configuration, allowing requests from any origin, and thus is vulnerable CSRF since it doesnt implement anti CSRF-measures.
<?php // Server-side code (PHP)
 header('Access-Control-Allow-Origin: *'); 
// Allow requests from any origin (vulnerable CORS configuration) .
// code to update email address ?>

Referer Header Bypass#

  • When making an HTTP request, the referer header contains the URL of the last page the user visited before making the current requests. Some websites guard against CSRF by only allowing queries if the referer header matches the domain. The utility of this as a stand-alone CSRF protection solution is reduced when this header may be changed or eliminated, as happens with user-installed browser extensions, privacy tools, or meta tags that instruct the browser to omit the referer.

Defence machanisms#

For pentesters/ Red Teamers#

  • CSRF Testing: activerly test application for CSRF vulnerabilities by attempting to execute unauthorized actions through manipulated requests and assess the effectiveness of implemented protections.
  • Boundary Validaton: Evaluate application’s validation mechanisms, ensuring that user inputs are appropriately validated and anti-csrf tokens are present.
  • Security Headers Analysis: Assess the presence and effectiveness of security headers, such as CORS, and Refere, to enhance the overall security and prevent various attack vectors, including CSRF.
  • Session Management TEsting: Examine the application’s session management mechanisms, ensuring that sessions tokens are securely generated, transmitted, and validated to prevvent unauthorized access and actions.

Secure Coders#

  • Integrate anti-csrf tokens into each form or requests.
  • Set samesite attribute on cookies to Strict or Lax to control when cookies are sent with cross-site requests, minimising the risk of CSRF by resticting the cookie behaviour.
  • Implement a Strict Referer policy, limiting the information disclosed in the referer header and ensuring that requests come from the trusted sources, there by preventing cross-site requests.
  • Implement a secure double- submit cookie pattern, where an anti-csrf is stored both in a cookie and as a request parameters.
  • Secure DEvelopers can implement CAPTCHAS challanges as an additional layer of defence against CSRF attacks especially in the user authentication, form submissions, and account creation processes.