DEV Community

Cover image for XS leaks: What they are and how to avoid them
SnykSec for Snyk

Posted on • Originally published at snyk.io

XS leaks: What they are and how to avoid them

Cross-site leaks (XS leaks) are a class of web security vulnerabilities that allow hackers to obtain sensitive information from a user’s browsing session on other websites or web apps. Modern web applications share data through various features and APIs — a function attackers can exploit to access this user data.

Ultimately, XS leaks lead to the disclosure of sensitive information, which malicious actors can use for numerous illicit purposes, like gaining unauthorized access to confidential systems or databases.

In this article, we’ll dive deeper into what XS leaks are and how they occur. Then, we’ll review some hands-on examples of how to prevent them. 

How XS leaks happen

Modern web applications are incredibly complex, comprising multiple domains with varying levels of trust. Therefore, maintaining a seamless in-browser experience necessitates that websites can share information. And while developers have ensured this communication is relatively secure, website and browser functionalities have certain inherent vulnerabilities.

XS leaks occur when attackers exploit these vulnerabilities to gain unauthorized access to private user data. By manipulating various web features — such as cookies, JavaScript APIs, CSS stylesheets, and HTML elements — and taking advantage of side channels and application-specific vulnerabilities, attackers can extract sensitive information from other websites a user visits. Moreover, these attacks occur silently, without the user’s knowledge or consent.

What are the different types of XS leaks?

There are several types of XS leaks that attackers can use. Let’s explore a few of them.

Timing attacks

In a timing attack, a malicious actor tries to gather sensitive system information by measuring how long it takes to perform various actions. The hacker sends specially crafted scripts to the target site to perform API calls, AJAX requests, or try to trigger resource requests that require cross-origin resource sharing (CORS). Then, they assess the durations of these processes to infer information about how the website functions or handles data.

For example, an attacker might observe how long the server-side validation process takes to send different input types — like username and password combinations — through cross-origin requests. Then, they can use noticeable time discrepancies to evaluate whether a login attempt is successful or to discern whether a user is an admin or a regular user. This information then informs an attacker’s next steps.

Frame counting

In frame counting attacks, the hacker creates multiple nested iFrames pointing toward different URLs within a targeted site. Then, they leverage the site’s CORS functionality to view the number of frames the user’s browser loads when they visit the targeted URLs. 

Consider an attacker who creates several nested iFrames for protected sections of a website, like the account settings and order history pages. When a user visits a page that contains the attacker’s injected iFrames, the attacker counts the frames that load successfully and those that don’t. They can then use this information to infer any account restrictions — such as authentication requirements or membership levels — to reveal whether a specific user has access privileges or previous interactions with particular areas of the targeted site.

Cache probing

Cache probing exploits browser caches, which store web content locally on users’ devices. To execute this attack, the hacker creates a malicious website that requests specific resources — like images or scripts — from the target site. The requested resources have distinctive characteristics, such as uncommon file sizes or loading times. 

Attackers measure how quickly the resources load when a user visits their malicious site, whether directly from the target server or through cached versions in the user’s browser. Then, the malicious actor uses this information to infer if those resources were already present in the user’s local browser cache.

Like frame counting, information obtained via cache probing can inform the customization of phishing campaigns, uncover the relationships between separate accounts used on multiple online services and platforms, and be used to coordinate more sophisticated attacks.

What are the mechanisms behind XS leaks?

XS leak attacks manipulate inherent browser functionalities and employ indirect observation techniques to gain unauthorized access to sensitive data. The mechanisms that contribute to the success of an XS leak attack include:

  • Exploiting browser features — Attackers use browser functionalities such as prefetching, prerendering, and various APIs like Fetch or WebSockets. They can extract sensitive information from users without directly violating the Same Origin Policy (SOP) by manipulating or combining these features with other techniques, like cache probing.
  • Side channels — These are indirect pathways through which attackers gather sensitive information. They do so by observing variations in factors such as rendering time or resource loading patterns on user browsers instead of accessing the data directly due to security restrictions imposed by SOPs within web applications.
  • Cross-origin communication — Attackers may also target cross-origin communication methods like postMessage API and web workers. They can then intercept or manipulate messages between different origins embedded within iFrames on a single page.

Vulnerabilities that XS leaks exploit

Using the mechanisms outlined above, attackers can gain access to sensitive information without directly violating security policies like CORS and SOP, which most modern websites employ. 

Such measures do not prevent XS leaks from occurring. Attackers can use side channels to leapfrog SOP guardrails, leverage CORS misconfiguration, and combine additional vulnerabilities into a more coordinated attack.

CORS and SOP control how resources from different origins interact. SOP restricts web pages from accessing data or content loaded from another domain, ensuring that scripts run within the context of their origin. CORS extends this policy by allowing specific cross-origin requests, where the server explicitly permits access to its resources through HTTP headers. This combination theoretically enables secure communication between websites and prevents malicious cross-domain interactions, such as cross site request forgery (CSRF) attacks and unauthorized data access.

However, because XS leaks exploit side channels and indirect data exposure, attackers can bypass SOP by deducing sensitive information from another origin. Likewise, if CORS is misconfigured or implemented insecurely on a web application, it can lead to information leakage.

Another way malicious actors could execute XS leak techniques is by stacking vulnerability exploits. Cross-site scripting (XSS) is an attack that works well with XS leaks. Once an attacker has leveraged an XSS vulnerability, they may also attempt to induce XS leaks through various browser features or APIs that expose side-channel information. 

A malicious actor can combine these two attack vectors to obtain sensitive data from the compromised domain and gather additional cross-origin insights without directly violating the SOP.

What are the consequences of XS leaks?

XS leak attacks can lead to severe consequences, such as disclosure of sensitive information where an attacker gains access to confidential data, including personal details or financial information. The attacker can then manipulate, steal, or misuse a user’s private information without their consent.

Additionally, session hijacking is another possible outcome of XS leak attacks. Session hijacking involves an attacker taking control of a user’s active session and potentially making unauthorized changes on their behalf. These consequences jeopardize individual users’ privacy and security and undermine trust in online platforms and services.

It’s important to note that XS leaks are often considered a part of broader attack techniques or vulnerabilities. High-profile data leaks that gain widespread media attention may not point to XS leaks as the key attack used. However, malicious attackers can use XS leaks to carry out more coordinated attacks.

Best practices to mitigate the risk of XS leak attacks

While there isn’t a one-size-fits-all solution for preventing XS leaks, there are ways to significantly reduce the associated risks. The following sections review best practices for mitigating XS leaks, providing hands-on demonstrations of how to implement them.

Use a Content Security Policy

Implement a strong Content Security Policy (CSP) to limit the sources of content that the browser can load on your sites. This practice reduces potential information leaks caused by attackers exploiting XSS or other injection-based vulnerabilities.

You can implement CSP using an HTTP response header called Content-Security-Policy, as shown below:

In this example, no external resources are allowed to load (default-src) unless explicitly specified by other directives. We can only load scripts (script-src), images (img-src), stylesheets (style-src), and fonts (font-src) from our domain (self) or Google API (googleapis.com).

A well-defined CSP helps prevent unauthorized cross-origin requests and inline code execution by specifying allowed sources for content like scripts, images, stylesheets, and more.

Enforce the SameSite attribute for cookies

The SameSite attribute within a cookie tells a browser whether we should include the cookie in external requests. In JavaScript, for example, it looks like this:

document.cookie = "username=JohnDoe; path=/; Secure; SameSite=Strict";
Enter fullscreen mode Exit fullscreen mode

The username cookie contains JohnDoe as the value, and the path / means the cookie will be accessible across all pages on our domain. The Secure keyword ensures that the cookie only transmits over HTTPS connections. Finally, we set the SameSite attribute to either:

  • None — The cookie will be attached if sent via a secure HTTPS channel.
  • Lax — This is the default behavior for Chromium-based browsers. The cookie will be sent for GET requests made to top-level navigation,
  • Strict — The cookie will never be sent outside our domain.

Setting the SameSite attribute in cookies to Strict prevents them from being sent during cross-site requests and mitigates CSRF and some XS leak attacks, such as those involving timing measurements.

Minimize the use of sensitive data in URLs

Minimizing the use of sensitive data in URLs is a crucial best practice in cybersecurity. Sensitive data, such as user credentials or personally identifiable information (PII), should never be included in URLs, as attackers can easily access it via browser histories, server logs, referrer headers, and unsanitized shared links.

Some ways to minimize the use of sensitive data include:

  • Using POST requests with HTTPS instead of including sensitive data in URLs
  • Using session tokens instead of directly passing user credentials or PII

Implement rate limiting

Another best practice is to apply rate limiting on sensitive endpoints, especially those vulnerable to enumeration or brute-force attempts. This strategy will limit the number of requests an attacker can make in a specified time frame and reduce the effectiveness of XS leak attacks. Various programming languages and web frameworks have libraries or middleware solutions for implementing rate limiting. 

In Node.js with Express, for example, you’ll need the express-rate-limit middleware installed via the npm install express-rate-limit command. Then, you can set up the server-side rate limiter as follows:

const express = require('express');
const app = express();
const RateLimit = require('express-rate-limit');

// Create a new limiter allowing 100 requests per hour from each IP address.
// You can adjust these numbers based on desired limits.
const apiLimiter = new RateLimit({
  windowMs: 60 * 60 * 1000,
    max: 100,
    message: "Too many requests from this IP. Please try again after an hour."
});

app.use('/api/sensitive-endpoint', apiLimiter); // Apply limit to sensitive API endpoint.

// Your other routes and middleware configurations here

app.listen(3000, () => {
 console.log("Server started on port ",3000);
});
Enter fullscreen mode Exit fullscreen mode

Note that this measure is most effective when combined with others. It hardens your security profile against XS leak attacks that rely on making many requests to your server to gather information.

Use proper CORS configurations

Ensure proper CORS configurations are in place for your application, preventing unauthorized domains from making cross-origin requests and accessing protected resources. Configure CORS headers, such as Access-Control-Allow-Origin, appropriately so that only trusted origins can send cross-origin requests while ensuring no unnecessary wildcards (*) are used in allowed origins lists.

If a server allows any origin (*) in its Access-Control-Allow-Origin header or uses dynamically generated origins without proper validation based on user input (such as a referrer), attackers could exploit this by making cross-origin requests from malicious websites.

Use integrations such as Snyk Code

Snyk Code helps you identify and fix security vulnerabilities by integrating into your development workflow, scanning dependencies, alerting you of vulnerabilities, suggesting and applying fixes, and continuously monitoring your project for security issues. For example, when creating a Node.js Express.js application, Snyk Code can help protect against vulnerabilities arising from the lack of security headers through a straightforward process:

  1. Scan dependencies — After integrating Snyk into your project, you can scan the project’s dependencies and check for known vulnerabilities in your packages.
  2. Identify the issue — If there’s a lack of security headers, Snyk Code will detect this vulnerability and alert you. For example, Snyk might identify that your application is missing the CSP header, which can help protect against XSS attacks.
  3. Suggest a fix — Snyk will recommend a fix for the identified vulnerability. In the case of missing security headers, it may suggest adding the helmet middleware to your Express.js application. Helmet is a popular package that helps set various security headers for your application by default.

Snyk can also continue monitoring your project for any new vulnerabilities or updates to existing ones. You will receive alerts if further issues arise, allowing you to continuously and consistently stay on top of your project’s security.

Controlling XS leaks

XS leaks enable attackers to obtain sensitive information from a user’s browsing session on another website. Hackers exploit browser features, side channels, and cross-origin communication. Some common XS leak techniques include timing attacks, frame counting, and cache probing.

There isn’t a guaranteed method for preventing XS leaks, but implementing the best practices outlined in this article can significantly reduce their risks and protect users’ sensitive information from unauthorized access or disclosure.

Top comments (0)