The module for this lesson is still under development. Please contact us if you have any questions.


Cross-site Scripting (XSS)

1. Read Background
2. Execute Lab Assignment
3. Complete Security Checklist
4. Answer Discussion Questions



A web-browser may unknowingly run malicious client-side scripts (like JavaScript) that may be have been placed within the content from a trusted site.


Browsers can run scripts like JavaScript that are sent to them from a website. If a user trusts a website, then they are likely to allow these scripts to run. However, it is possible to ‘inject’ malicious scripts into content from trusted websites especially if those websites allow user generated content. These malicious scripts can hijack valid user sessions, deface the webpage being viewed, or redirect the user to other sites (hence the name ‘Cross-Site Scripting’ (XSS)).

XSS flaws can be generally categorized into two types: stored and reflected. Stored XSS flaws are those where the malicious code is permanently stored in the target website (for example, in databases – comments, product descriptions, etc.). Reflected XSS attacks on the other hand, are ‘reflected’ off a trusted webserver where the malicious content is injected into the response sent by the webserver (for example, a search result, or an error page). Reflected attacks are sent to the victim through another route like an email or another website (see Example in code – 1 below).

Risk – How can it happen?

XSS vulnerabilities can occur when a trusted website allows users to provide content. A classic example is a blog that allows its readers to comment on an article. An attacker can enter the following comment:

< script type="text/javascript" > alert("Your hard disk is corrupted."); < /script >

When the owner of the blog or any other user views the comments, the script is sent to their browser which executes it showing the victim the message in a pop-up alert box. This script (though probably harmless as it is written above) will get executed within the context of the victims browser and thus may have access to the victim’s login session and cookies. Such scripts do not have to be within HTML tags, they can also be associated with JavaScript events such as onLoad or MouseOver.

Example of occurrence:

On September 21st 2010, Twitter was effected by a XSS attack that was based on a mouseover event. If users moused over a link sent as a tweet to their accounts, they would be redirected to a third party site. This was because Twitter had failed to escape out parts of JavaScript from the posted Tweets.

Charles Arthur, “Twitter users including Sarah Brown hit by malicious hacker attack”

Example in code – 1:

Consider the following scenario: The attacker knows that the victim uses a popular e-commerce site (lets call it The attacker also knows that allows users to post comments for products. The URL for posting a comment is:

A valid link to post a comment sent to a user’s email looks like the following:

Click here to post a comment for the product you just bought

When the user clicks this link, the comment will be posted to The website may then display the product page back to the user with the new comment on it. In this scenario, the attacker may use the following link instead (where the comment text is replaced with a JavaScript) and send to the victim’s email:

Click here to post a comment for the product you just bought

In the above case, the comment posted to is


which may be converted to text:


When the website shows the victim the product page with his/her comment, the browser will execute this script. This vulnerability can be used to run other malicious scripts or redirect to other malicious  sites instead of popping a harmless alert box. This is a classic reflected XSS attack, where the malicious script is ‘reflected’ off a trusted website.

Example in code – 2:

Consider the following JSP script (Source:
It takes input from the user using a HTTP request and then displays it on the page.

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

In this case, if the the parameter eid is a alphanumeric parameter (which is what is expected), then, there may not be any problem. However, if eid is a script, then the browser may execute that script when the user views the page.

Code Responsibly – How can I avoid a XSS vulnerability?

The basic premise in avoiding a XSS vulnerability is to look out for untrusted data entering your application and escape any characters in the untrusted data (like Javascript tags) that may have special meaning. There are many places in aHTML document where an attacker might be able to introduce malicious code.

The OWASP XSS Cheat Sheet recommends rules to prevent XSS. The rules are based on the concept of having a whitelist rather than a blacklist for preventing security vulnerabilities. A whitelist is the best way to validate input to an application since a blacklist is likely to list only the known vulnerabilities and may miss unknown ways to attack an application. We adapt and list the most important rules here, for a thorough analysis visit the OWASP website.

  1. The first rule is based on the principle of deny all. Never insert untrusted data anywhere in the following contexts. Putting untrusted/user-generated data in these contexts is rarely (if ever) needed in a Web Application.
     directly in a script
     inside an HTML comment
    ...NEVER PUT UNTRUSTED DATA HERE...=test > ...
    in an attribute name <NEVER PUT UNTRUSTED DATA HERE... href="/test" /> in a tag name

    Most importantly, never accept actual JavaScript code from an untrusted source and then run it. All JavaScript from other sources (like in the code example) should be escaped.

  2. HTML escape before inserting data into HTML element content

    If you have to put untrusted data within a HTML document within tags like div, p, td. etc., then you have to escape it.


    The same is true for any other HTML element like


    , , etc.

    Escape the following characters that have special meaning in  HTML before you insert them in your document from untrusted sources.

    Replace & with &amp;
    Replace < with &lt;
    Replace > with &gt;
    Replace " with &quot;
    Replace ' with &#x27;
    Replace / with &#x2F;

    However, implementing Rule 2 is not easy. Even though escaping code in some situations is simple, it is difficult to predict all the possibilities in all the contexts.

    It is recommended that you use pre-built libraries to escape code. The OWASP ESAPI
    ( project has created an escaping library for many languages including Java, .NET,
    and PHP. Many web frameworks and languages also come with their own libraries.

    If you use the ESAPI libraries, then you have use the following statement for escaping characters obtained through user entered parameters before inserting them in the HTML document.

     $safe_input_from_user = ESAPI::getEncoder()->encodeForHTML( $input_from_user );

  3. Attribute Escape before inserting untrusted data into common HTML attributes. This rule is for putting data into attributes like width, name, value, href, style, etc.

    If you use the ESAPI libraries, then you have use the following statement for escaping characters obtained through user entered parameters before inserting them in the HTML attribute.

     $safe_input_from_user = ESAPI::getEncoder()->encodeForHTMLAttribute( $input_from_user );

Laboratory Assignment


Program 1

Consider the following simple web application:

Please take a moment to share your comments with us. Your Name:
Your E-mail address: Your Web Page address: Your occupation: Location (state): Favorite color: Comments:

The following code segment accepts data from the form above and inserts it into the database (assuming the database connection parameters are given):

 Thanks! We appreciate your comments on our application. ";

The following code segment queries that database to show all the comments to any user who views the page. It also shows the users comments in his/her favorite color:

    $result = mysql_query( "select name, email, url, job, location, comments from guestbook");
    if (mysql_num_rows($result)>0)
        echo "

View Guestbook Entries

"; // fetch the rows one at a time, and then echo the data to the page while ($row = mysql_fetch_row($result)) { echo "" echo "
" echo "
"; echo "Name: $row[0]"; echo "
E-mail: $row[1]"; echo "
Web Page: $row[2]"; echo "
Occupation: $row[3]"; echo "
From: $row[4]"; echo "
Comments:"; echo "
$row[6]"; echo "
" } mysql_free_result($result); mysql_close($connection); ?>
Lab Questions:
  1. Complete the security checklist for this program (click here to print the checklist and the code above).
  2. Provide example inputs that might cause Cross Site Scripting (XSS) problems, and describe the problems that they might cause.


Security Checklist

Vulnerability:Cross Site Scripting (XSS) Course: Web
Task – Check each line of code displaying on the web page Completed
1. Highlight/circle each line of code that inserts user supplied/untrusted data into the HTML comment tag.
2. Highlight /circle each line of code that inserts user supplied/untrusted data into an HTML attribute value.
3. Highlight/circle each line of code that inserts unescaped data inside an HTML tag content (like between ,

, etc.). This is a common issue, look carefully at all insertions into the HTML page.

Highlighted areas in the application may be vulnerable to XSS attacks!

Further Work (optional – check with your instructor if you need to answer the following questions. Note to instructor: these questions may take significant time and are best assigned as take home work)
  1. Revise the Program 1* to properly prevent Cross Site Scripting (XSS) problems. You may use the OWASP ESAPI toolkit for it. See an example here for using ESAPI to escape HTML tag and attribute content.
  2. Download an install the OWASP WebGoat application. WebGoat is a deliberately insecure J2EE web application maintained by OWASP designed to teach web application security lessons. Complete the XSS lesson.

*Copying and pasting programs may result in syntax errors and other inconsistencies. It is recommended you type each program.

Olsen, Kai. “The $100,000 Keying error” IEEE Computer, August 2008

Copyright © Towson University