Table of Contents

About

cross-site scripting (XSS) is a injection security vulnerability that happens when external javascript code is injected in the page via user input.

Injected JavaScript can then steal authentication tokens from local data such as cookies and local storage.

This is similar to SQL injection attacks

Web browsers, for security and privacy reasons, prevent documents in different domains from affecting each other; that is, cross-site scripting is disallowed.

Prevention

  • the user input should be validated or escaped.
  • Restricting the media type when hosting untrusted content (such as user-generated content)

For example, serving user-generated content as image/png is less risky than serving user-generated content as text/html (HTML may include code via the script element). The applications risk leaking their origin's authority to the untrusted content.

Example

Suppose a page looked at its URL's query string to determine what to display, and the site then redirected the user to that page to display a message, as in:

<ul>
 <li><a href="message.cgi?say=Hello">Say Hello</a>
 <li><a href="message.cgi?say=Welcome">Say Welcome</a>
 <li><a href="message.cgi?say=Kittens">Say Kittens</a>
</ul>

If the message was just displayed to the user without escaping, a hostile attacker could then craft a URL that contained a script element:

http://example.com/message.cgi?say=%3Cscript%3Ealert%28%27Oh%20no%21%27%29%3C/script%3E

If the attacker then convinced a victim user to visit this page, a script of the attacker's choosing would run on the page. Such a script could do any number of hostile actions, limited only by what the site offers: if the site is an e-commerce shop, for instance, such a script could cause the user to unknowingly make arbitrarily many unwanted purchases.

This is called a cross-site scripting attack.

Documentation / Reference