Cross-site scripting

From Wikipedia, the free encyclopedia
  (Redirected from Cross site scripting)
Jump to: navigation, search

Cross-site scripting (XSS) is a type of computer security vulnerability typically found in Web applications. XSS enables attackers to inject client-side script into Web pages viewed by other users. A cross-site scripting vulnerability may be used by attackers to bypass access controls such as the same origin policy. Cross-site scripting carried out on websites accounted for roughly 84% of all security vulnerabilities documented by Symantec as of 2007.[1] Their effect may range from a petty nuisance to a significant security risk, depending on the sensitivity of the data handled by the vulnerable site and the nature of any security mitigation implemented by the site's owner.


Security on the web is based on a variety of mechanisms, including an underlying concept of trust known as the same origin policy. This essentially states that if content from one site (such as is granted permission to access resources on the system, then any content from that site will share these permissions, while content from another site ( will have to be granted permissions separately.[2]

Cross-site scripting uses known vulnerabilities in web-based applications, their servers, or plug-in systems on which they rely. Exploiting one of these, attackers fold malicious content into the content being delivered from the compromised site. When the resulting combined content arrives at the client-side web browser, it has all been delivered from the trusted source, and thus operates under the permissions granted to that system. By finding ways of injecting malicious scripts into web pages, an attacker can gain elevated access-privileges to sensitive page content, session cookies, and a variety of other information maintained by the browser on behalf of the user. Cross-site scripting attacks are therefore a special case of code injection.[citation needed]

The expression "cross-site scripting" originally referred to the act of loading the attacked, third-party web application from an unrelated attack site, in a manner that executes a fragment of JavaScript prepared by the attacker in the security context of the targeted domain (a reflected or non-persistent XSS vulnerability). The definition gradually expanded to encompass other modes of code injection, including persistent and non-JavaScript vectors (including ActiveX, Java, VBScript, Flash, or even HTML scripts), causing some confusion to newcomers to the field of information security.[3]

XSS vulnerabilities have been reported and exploited since the 1990s. Prominent sites affected in the past include the social-networking sites Twitter,[4] Facebook,[5] MySpace, YouTube and Orkut.[6][7] In recent years, cross-site scripting flaws surpassed buffer overflows to become the most common publicly reported security vulnerability,[8] with some researchers in 2007 viewing as many as 68% of websites as likely open to XSS attacks.[9]


There is no single, standardized classification of cross-site scripting flaws, but most experts distinguish between at least two primary flavors of XSS: non-persistent and persistent. Some sources further divide these two groups into traditional (caused by server-side code flaws) and DOM-based (in client-side code).

Reflected (non-persistent)[edit]

Example of non-persistent XSS
Non-persistent XSS vulnerabilities in Google could allow malicious sites to attack Google users who visit them while logged in.[10]

The non-persistent (or reflected) cross-site scripting vulnerability is by far the most common type.[11] These holes show up when the data provided by a web client, most commonly in HTTP query parameters or in HTML form submissions, is used immediately by server-side scripts to parse and display a page of results for and to that user, without properly sanitizing the request.[12]

Because HTML documents have a flat, serial structure that mixes control statements, formatting, and the actual content, any non-validated user-supplied data included in the resulting page without proper HTML encoding, may lead to markup injection.[11][12] A classic example of a potential vector is a site search engine: if one searches for a string, the search string will typically be redisplayed verbatim on the result page to indicate what was searched for. If this response does not properly escape or reject HTML control characters, a cross-site scripting flaw will ensue.[13]

A reflected attack is typically delivered via email or a neutral web site. The bait is an innocent-looking URL, pointing to a trusted site but containing the XSS vector. If the trusted site is vulnerable to the vector, clicking the link can cause the victim's browser to execute the injected script.


Example of persistent XSS
A persistent cross-zone scripting vulnerability coupled with a computer worm allowed execution of arbitrary code and listing of filesystem contents via a QuickTime movie on MySpace.[14]

The persistent (or stored) XSS vulnerability is a more devastating variant of a cross-site scripting flaw: it occurs when the data provided by the attacker is saved by the server, and then permanently displayed on "normal" pages returned to other users in the course of regular browsing, without proper HTML escaping. A classic example of this is with online message boards where users are allowed to post HTML formatted messages for other users to read.[12]

For example, suppose there is a dating website where members scan the profiles of other members to see if they look interesting. For privacy reasons, this site hides everybody's real name and email. These are kept secret on the server. The only time a member's real name and email are in the browser is when the member is signed in, and they can't see anyone else's.

Suppose that Mallory, an attacker, joins the site and wants to figure out the real names of the people she sees on the site. To do so, she writes a script designed to run from other people's browsers when they visit her profile. The script then sends a quick message to her own server, which collects this information.

To do this, for the question "Describe your Ideal First Date", Mallory gives a short answer (to appear normal) but the text at the end of her answer is her script to steal names and emails. If the script is enclosed inside a <script> element, it won't be shown on the screen. Then suppose that Bob, a member of the dating site, reaches Mallory’s profile, which has her answer to the First Date question. Her script is run automatically by the browser and steals a copy of Bob’s real name and email directly from his own machine.

Persistent XSS can be more significant than other types because an attacker's malicious script is rendered automatically, without the need to individually target victims or lure them to a third-party website. Particularly in the case of social networking sites, the code would be further designed to self-propagate across accounts, creating a type of a client-side worm.[15]

The methods of injection can vary a great deal; in some cases, the attacker may not even need to directly interact with the web functionality itself to exploit such a hole. Any data received by the web application (via email, system logs, IM etc.) that can be controlled by an attacker could become an injection vector.

Server-side versus DOM-based vulnerabilities[edit]

Example of DOM-based XSS
Before the bug was resolved, Bugzilla error pages were open to DOM-based XSS attack in which arbitrary HTML and scripts could be injected using forced error messages.[16]

Historically XSS was first found in applications that performed all data processing on the server side. User input (including an XSS vector) would be sent to the server, and then sent back to the user as a web page. The need for an improved user experience resulted in popularity of applications that had a majority of the presentation logic (maybe written in JavaScript) working on the client-side that pulled data, on-demand, from the server using AJAX.

As the JavaScript code was also processing user input and rendering it in the web page content, a new sub-class of reflected XSS attacks started to appear that was called DOM-based cross-site scripting. In the DOM-based XSS, the malicious data does not touch the web server. Rather, it is being reflected by the JavaScript code, fully on the client side.[17]

An example of DOM-based XSS is the bug found in 2011 in a number of JQuery plugins.[18] Prevention of DOM-based XSS includes very similar measures to traditional XSS, just implemented in JavaScript code and sent in web pages — input validation and escaping.[19] Some JavaScript frameworks have built-in countermeasures against this and other types of attack — for example Angular.js.[20]

Exploit examples[edit]

Attackers intending to exploit cross-site scripting vulnerabilities must approach each class of vulnerability differently. For each class, a specific attack vector is described here. The names below are technical terms, taken from the cast of characters commonly used in computer security.


  1. Alice often visits a particular website, which is hosted by Bob. Bob's website allows Alice to log in with a username/password pair and stores sensitive data, such as billing information. When a user logs in, their browser keeps an Authorization Cookie, which just looks like some garbage characters, so both computers remember that she's logged in.
  2. Mallory observes that Bob's website contains a reflected XSS vulnerability:
    1. When she visits the Search page, inputs a search term in the search box, and clicks the submit button, if no results were found, the page will display the term she searched for, followed by the words "not found", and the url will be search term.
    2. With a normal search query, like the word "puppies", the page simply displays "puppies not found" and the url is "" - which is perfectly normal behavior.
    3. However, when she submits an abnormal search query, like "<script type='text/javascript'>alert('pwnd');</script>",
      1. an alert box appears (that says "pwnd"),
      2. the page displays "<script type='text/javascript'>alert('pwnd');</script> not found", along with an error message with the text 'pwnd',
      3. and the url is "<script%20type='text/javascript'>alert('pwnd');</script> - which is exploitable behavior.
  3. Mallory crafts a URL to exploit the vulnerability.
    1. She makes the URL<script%20src=""> and,
    2. sends an email to some unsuspecting members of Bob's site, saying "Check out some cute puppies!"
  4. Alice gets the email. She loves puppies and clicks on the link. It goes to Bob's website to search, doesn't find anything, and displays "puppies not found" but right in the middle, the script tag runs (it is invisible on the screen) and loads and runs Mallory's program authstealer.js (This is the actual XSS vulnerability.) Alice forgets about it.
  5. The authstealer.js program runs in Alice's browser, as if it is part of Bob's website. It grabs a copy of Alice's Authorization Cookie and sends it to Mallory's server, where Mallory retrieves it.
  6. Mallory now sets Alice's auth cookie into her browser as if it is her own auth cookie. She then goes to Bob's site and she is now logged in as Alice.
  7. Now that she's in, Mallory goes to the Billing section of the website and looks up Alice's credit card number and grabs a copy. Then she goes and changes her password, to a password of her choosing, so Alice can't even log in anymore.
  8. She decides to take it a step further and send a similarly crafted link to Bob himself, thus gaining administrator privileges to his website.

Several things could have been done to mitigate this attack:

  1. the search input could have been sanitized which would include proper encoding checking.
  2. the web server could be set to redirect invalid requests.
  3. the web server could detect a simultaneous login and invalidate the sessions.
  4. the web server could detect a simultaneous login from two different ip addresses and invalidate the sessions.
  5. the website could only display the last few digits of a previously used credit card.
  6. the website could require a user to enter their old password before changing registration information.
  7. the website could enact various aspects of the Content Security Policy
  8. and most importantly users could be educated to not click nefarious but 'benign-looking' links.

Persistent attack:

  1. Mallory gets an account on Bob's website.
  2. Mallory observes that Bob's website contains a stored XSS vulnerability. If you go to the News section, and post a comment, it will display whatever she types in for the comment. But, if the comment text contains HTML tags in it, the tags get displayed as-is, and any script tags get run.
  3. Mallory reads an article in the News section, and writes in a comment at the bottom in the Comments section. In the comment, she inserts this text: I love the puppies in this story! They're so cute!<script src=""> That'll take the current user's authorization cookie and send it to Mallory's secret server for collection. Bob's website software should have stripped out the script tag or done something to make sure it didn't work, but he didn't; that's the security bug.
  4. When Alice(or anyone)loads the page with the message, Mallory's script tag runs and steals Alice's authorization cookie.
  5. Mallory can now hijack Alice's session and impersonate Alice.[21]


The Browser Exploitation Framework could be used to attack the web site and the user's local environment.

Reducing the threat[edit]

Contextual output encoding/escaping of string input[edit]

The primary defense mechanism to stop XSS is contextual output encoding/escaping. There are several different escaping schemes that must be used depending on where the untrusted string needs to be placed within an HTML document including HTML entity encoding, JavaScript escaping, CSS escaping, and URL (or percent) encoding.[22] Most web applications that do not need to accept rich data can use escaping to largely eliminate the risk of XSS in a fairly straightforward manner.

It is worth noting that although it is widely recommended, simply performing HTML entity encoding on the five XML significant characters is not always sufficient to prevent many forms of XSS. Encoding can be tricky, and the use of a security encoding library is highly recommended.[22]

Safely validating untrusted HTML input[edit]

Many operators of particular web applications (e.g. forums and webmail) wish to allow users to utilize some of the features HTML provides, such as a limited subset of HTML markup. When accepting HTML input from users (say, <b>very</b> large), output encoding (such as &lt;b&gt;very&lt;/b&gt; large) will not suffice since the user input needs to be rendered as HTML by the browser (so it shows as "very large", instead of "<b>very</b> large"). Stopping XSS when accepting HTML input from users is much more complex in this situation. Untrusted HTML input must be run through an HTML sanitization engine to ensure that it does not contain XSS.

Cookie security[edit]

Besides content filtering, other imperfect methods for cross-site scripting mitigation are also commonly used. One example is the use of additional security controls when handling cookie-based user authentication. Many web applications rely on session cookies for authentication between individual HTTP requests, and because client-side scripts generally have access to these cookies, simple XSS exploits can steal these cookies.[23] To mitigate this particular threat (though not the XSS problem in general), many web applications tie session cookies to the IP address of the user who originally logged in, and only permit that IP to use that cookie.[24] This is effective in most situations (if an attacker is only after the cookie), but obviously breaks down in situations where an attacker is behind the same NATed IP address or web proxy as the victim, or the victim is changing his or her mobile IP.[24]

Another mitigation present in Internet Explorer (since version 6), Firefox (since version, Safari (since version 4), Opera (since version 9.5) and Google Chrome, is an HttpOnly flag which allows a web server to set a cookie that is unavailable to client-side scripts. While beneficial, the feature does not fully prevent cookie theft nor can it prevent attacks within the browser.[25]

Disabling scripts[edit]

Finally, while Web 2.0 and Ajax designers favor the use of JavaScript,[26] some web applications are written to (sometimes optionally) operate completely without the need for client-side scripts.[27] This allows users, if they choose, to disable scripting in their browsers before using the application. In this way, even potentially malicious client-side scripts could be inserted unescaped on a page, and users would not be susceptible to XSS attacks.

Some browsers or browser plugins can be configured to disable client-side scripts on a per-domain basis. If scripting is allowed by default, then this approach is of limited value, since it blocks bad sites only after the user knows that they are bad, which is too late. Functionality that blocks all scripting and external inclusions by default and then allows the user to enable it on a per-domain basis is more effective. This has been possible for a long time in Internet Explorer (since version 4) by setting up its so called "Security Zones",[28] and in Opera (since version 9) using its "Site Specific Preferences".[29] A solution for Firefox and other Gecko-based browsers is the open source NoScript add-on which, in addition to the ability to enable scripts on a per-domain basis, provides some anti-XSS protection even when scripts are enabled.[30]

The most significant problem with blocking all scripts on all websites by default is substantial reduction in functionality and responsiveness (client-side scripting can be much faster than server-side scripting because it does not need to connect to a remote server and the page or frame does not need to be reloaded).[31] Another problem with script blocking is that many users do not understand it, and do not know how to properly secure their browsers. Yet another drawback is that many sites do not work without client-side scripting, forcing users to disable protection for that site and opening their systems to vulnerabilities.[32] The Firefox NoScript extension enables users to allow scripts selectively from a given page while disallowing others on the same page. For example, scripts from could be allowed, while scripts from that are attempting to run on the same page could be disallowed.[33]

Emerging defensive technologies[edit]

There are three classes of XSS defense that are emerging. These include Content Security Policy,[34] Javascript sandbox tools, and auto-escaping templates. These mechanisms are still evolving but promise a future of heavily reduced XSS.

Scanning service[edit]

Some companies offer a periodic scan service, essentially simulating an attack from their server to a client's in order to check if the attack is successful. If the attack succeeds, the client receives detailed information on how it was performed and thus has a chance to fix the issues before the same attack is attempted by someone else. A trust seal can be displayed on the site that passes a recent scan. The scanner may not find all possible vulnerabilities,[35] and therefore sites with trust seals may still be vulnerable to new types of attack, but the scan may detect some problems. After the client fixes them, the site is more secure than it was before using the service. For sites that require complete mitigation of XSS, assessment techniques like manual code review are necessary. Additionally, if Javascript is executing on the page, the seal can be overwritten with a static copy of the seal.

Related vulnerabilities[edit]

In Universal Cross Site Scripting (UXSS, or Universal XSS), vulnerabilities in the browser are exploited, commonly used by Anonymous along with DDoS, rather than in other websites in XSS.[36]

Several classes of vulnerabilities or attack techniques are related to XSS: cross-zone scripting exploits "zone" concepts in certain browsers and usually executes code with a greater privilege.[37] HTTP header injection can be used to create cross-site scripting conditions due to escaping problems on HTTP protocol level (in addition to enabling attacks such as HTTP response splitting).[38]

Cross-site request forgery (CSRF/XSRF) is almost the opposite of XSS, in that rather than exploiting the user's trust in a site, the attacker (and his malicious page) exploits the site's trust in the client software, submitting requests that the site believes represent conscious and intentional actions of authenticated users.[39] XSS vulnerabilities (even in other applications running on the same domain) allow attackers to bypass CSRF preventions.[40]

Covert Redirect takes advantage of third-party clients susceptible to XSS or Open Redirect.[41] It is discovered by a mathematical PhD student Wang Jing from Nanyang Technological University, Singapore. "Normal phishing attempts can be easy to spot, because the malicious page's URL will usually be off by a couple of letters from that of the real site. The difference with Covert Redirect is that an attacker could use the real website instead by corrupting the site with a malicious login popup dialogue box."[42]

Lastly, SQL injection exploits a vulnerability in the database layer of an application. When user input is incorrectly filtered, any SQL statements can be executed by the application.[43][44]

See also[edit]


  1. ^ During the second half of 2007, 11,253 site-specific cross-site vulnerabilities were documented by XSSed, compared to 2,134 "traditional" vulnerabilities documented by Symantec, in "Symantec Internet Security Threat Report: Trends for July–December 2007 (Executive Summary)" (PDF) XIII. Symantec Corp. April 2008. pp. 1–3. Retrieved May 11, 2008. 
  2. ^ "Same Origin Policy - Web Security.".  Retrieved on November 4, 2014.
  3. ^ Grossman, Jeremiah (July 30, 2006). "The origins of Cross-Site Scripting (XSS)". Retrieved September 15, 2008. 
  4. ^ Arthur, Charles (September 21, 2010). "Twitter users including Sarah Brown hit by malicious hacker attack". The Guardian. Retrieved September 21, 2010. 
  5. ^ Leyden, John (May 23, 2008). "Facebook poked by XSS flaw". The Register. Retrieved May 28, 2008. 
  6. ^ "Full List of Incidents". Web Application Security Consortium. February 17, 2008. Retrieved May 28, 2008. 
  7. ^ "Obama site hacked; Redirected to Hillary Clinton". ZDNet. April 21, 2008. Retrieved May 28, 2008. 
  8. ^ Christey, Steve and Martin, Robert A. (May 22, 2007). "Vulnerability Type Distributions in CVE (version 1.1)". MITRE Corporation. Retrieved June 7, 2008. 
  9. ^ Berinato, Scott (January 1, 2007). "Software Vulnerability Disclosure: The Chilling Effect". CSO (CXO Media). p. 7. Archived from the original on April 18, 2008. Retrieved June 7, 2008. 
  10. ^ Amit, Yair (December 21, 2005). " UTF-7 XSS Vulnerabilities". Watchfire. Retrieved May 29, 2008. 
  11. ^ a b Hope, Paco; Walther, Ben (2008). Web Security Testing Cookbook. Sebastopol, CA: O'Reilly Media, Inc. p. 128. ISBN 978-0-596-51483-9. 
  12. ^ a b c "Cross-site Scripting". Web Application Security Consortium. 2005. Retrieved May 28, 2008. 
  13. ^ Grossman, Jeremiah and Robert Hansen, Seth Fogie, Petko D. Petkov and Anton Rager (2007). XSS Attacks: Cross Site Scripting Exploits and Defense (Abstract). Elsevier Science & Technology via Google Book Search. pp. 70, 156. ISBN 1-59749-154-3. Retrieved May 28, 2008. 
  14. ^ This worm is named JS/Ofigel-A, JS/Quickspace.A and JS.Qspace, in "JS/Ofigel-A". Sophos. Retrieved June 5, 2008.  and "F-Secure Malware Information Pages: JS/Quickspace.A". F-Secure. January 5, 2007. Retrieved June 5, 2008.  and "JS.Qspace". Symantec Corp. February 13, 2007. Retrieved June 5, 2008. 
  15. ^ Viruses and worms in Alcorn, Wade (September 27, 2005). "The Cross-site Scripting Virus". Retrieved May 27, 2008.  and Grossman, Jeremiah (April 2006). "Cross-Site Scripting Worms and Viruses: The Impending Threat and the Best Defense" (PDF). WhiteHat Security. p. 20. Retrieved June 6, 2008. 
  16. ^ "Bug 272620 – XSS vulnerability in internal error messages". Bugzilla@Mozilla. 2004. Retrieved May 29, 2008. 
  17. ^ "DOM based XSS". OWASP. 
  18. ^ "JQuery bug #9521". 2011. 
  19. ^ "DOM based XSS prevention cheat sheet". OWASP. 
  20. ^ "Strict Contextual Escaping". Angular.js. 
  21. ^ Brodkin, Jon (October 4, 2007). "The top 10 reasons Web sites get hacked". Network World (IDG). Retrieved June 8, 2008. 
  22. ^ a b Williams,Jeff (January 19, 2009). "XSS (Cross Site Scripting) Prevention Cheat Sheet". OWASP. Retrieved February 4, 2009. 
  23. ^ Sharma, Anand (February 3, 2004). "Prevent a cross-site scripting attack". IBM. Retrieved May 29, 2008. 
  24. ^ a b "ModSecurity: Features: PDF Universal XSS Protection". Breach Security. Retrieved June 6, 2008. 
  25. ^ "Ajax and Mashup Security". OpenAjax Alliance. Retrieved June 9, 2008. 
  26. ^ O'Reilly, Tim (September 30, 2005). "What Is Web 2.0". O'Reilly Media. pp. 4–5. Retrieved June 4, 2008. 
  27. ^ "A page should work, even if in a degraded form, without JavaScript." in Zammetti, Frank (April 16, 2007). Practical JavaScript, DOM Scripting and Ajax Projects via Amazon Reader. Apress. p. 36. ISBN 1-59059-816-4. Retrieved June 4, 2008. 
  28. ^ "How to use security zones in Internet ?Explorer". Microsoft. December 18, 2007. Retrieved June 4, 2008. 
  29. ^ Håkon Wium Lie (February 7, 2006). "Opera 9 Technology Preview 2". Opera Software. Retrieved June 4, 2008. 
  30. ^ "NoScript". Mozilla. May 30, 2008. Retrieved June 4, 2008.  and Mogull, Rich (March 18, 2008). "Should Mac Users Run Antivirus Software?". TidBITS (TidBITS Publishing). Retrieved June 4, 2008. 
  31. ^ ""Using client-side events" in DataWindow Programmer's Guide". Sybase. March 2003. Retrieved June 4, 2008. 
  32. ^ 73% of sites relied on JavaScript in late 2006, in "'Most websites' failing disabled". BBC News. December 6, 2006. Retrieved June 4, 2008. 
  33. ^ "NoScript Features". Retrieved March 7, 2009. 
  34. ^ "Content Security Policy 1.0". W3C Candidate Recommendation. 15 November 2012. Retrieved February 22, 2013. 
  35. ^ Sceptic blog
  36. ^ Stefano Di Paola (January 3, 2007). "Adobe Acrobat Reader Plugin - Multiple Vulnerabilities". Retrieved March 13, 2012. 
  37. ^ "Security hole in Internet Explorer allows attackers to execute arbitrary programs". Heise Media UK. May 16, 2008. Retrieved June 7, 2008. 
  38. ^ "Update available for potential HTTP header injection vulnerabilities in Adobe Flash Player". Adobe Systems. November 14, 2006. Retrieved June 7, 2008. 
  39. ^ Auger, Robert (April 17, 2008). "The Cross-Site Request Forgery (CSRF/XSRF) FAQ (version 1.59)". Retrieved June 7, 2008. 
  40. ^ "Article about CSRF and same-origin XSS"
  41. ^ "OAuth 2.0 and OpenID Redirect Vulnerability". Hacker News. 2 May 2014. Retrieved 21 December 2014. 
  42. ^ Jill Scharr (2 May 2014). "Facebook, Google Users Threatened by New Security Flaw". Tom's Guide. Retrieved 21 December 2014. 
  43. ^ "SQL Injection". Web Application Security Consortium. 2005. Retrieved June 7, 2008. 
  44. ^ "The Cross-Site Scripting FAQ". 2002. Retrieved June 7, 2008. 

External links[edit]