Home » Java » Enterprise Java » Cross Site Scripting (XSS) and prevention

About Advait Trivedi

Cross Site Scripting (XSS) and prevention

Variants of Cross site scripting (XSS) attacks are almost limitless as mentioned on the OWASP site (https://www.owasp.org/index.php/Cross-site_Scripting_(XSS)). Here I propose to use a Servlet Filter based solution for sanitization of HTTP Request.
The attack
Lets see how an XSS attack manifests itself. Attached is an over simplified portlet which shows a scenario which is very common in social and collaboration based systems like forums. See below psuedo-sequence diagram.


Here, 1. There is a form available where user can enter his comments with a submit button and textbox named “mytext”. User A renders this form. 2. User A enters a java script into input text box and submits the form (this is the step where evil enters your app). Just to make you see the problem; imagine that the script entered by user sends cookies stored by the app to an attacker’s site. 3. User B logs into the system and he wants to see the comments provided by User A. So he goes to respective page where system renders value of “mytext” provided by A. 4. Browser renders value of “mytext”, which is a java script that fetches all the cookies of current site stored for User B and sends it to the Attackers system.
The prevention (better than cure, always) We will see how cleansing of HTTP parameters help in thwarting off this kind of attack. For this attack to be successful what kind of response was sent to browser when B rendered A’s comments? Something like –
<div>A's Comments</div>
This script will get all cookies and will send them to attacker's site.
As you can see, the attack was possible due to the fact that, for a browser, an HTML document is mix of markup & executable code. The ability to mix executable code with markup is deadly combination which attackers can exploit. Using a Servlet Filter we can cleans all the input parameters and remove all special characters that can denote executable instructions for browser. This way no evil enters the system. Here is a very simple Servlet Filter that does this. A wrapper over HttpServletRequest is used and methods are override to return request parameter values after escaping. For escaping I suggest using StringEscapeUtils of Apache Commons project instead of doing some custom coding.
Another way is to let the users enter whatever they want but while rendering convert <,>,&,’,” to their corresponding character entity codes. Typically this can be done as using JSTL –
<div>A's comments</div>
<c:out value="${comments}" escapeXml="true" />
This approach is especially useful where users can share code snippets with each other.
Based on interaction between user and the system many other clever ways of launching an XSS attacks can be devised. But having absolute control over system input will can surely guard agains such attacks.


Reference: XSS and prevention from our JCG partner Advait Trivedi at the CoolCode blog.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!


1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design


and many more ....



One comment

  1. XSS attacks are frequent in dynamic websites that builds its contents within user’s interaction, for example a blog or a forum.

    It might happen that when you ask for user input you don’t sanitize the input properly before adding it to database (that can derive in a SQL injection) or when printing it to the website (that can derive in a XSS injection).
    A common thing that I do is to use a function exclusive to parse chars (, &…) to the HTML equivalent (<, >, &…) everytime I ask for user’s input.

    If you are working with PHP you can take a look at my Alexya framework (http://github.com/manulaiko/alexya) and simply call the method Core_Functions::sanitize() to parse user’s input before adding it to database (for example username might be a potential XSS and SQLi entry) that way you avoid SQL injection while building the query and XSS while showing the data.

    Here’s the function I use:

    * XSS and SQL Injection Fix
    * Will receive a string as parameter and will be parsed to HTML to avoid XSS
    * injection, can be used to avoid SQL injection too}
    * @param string text text to parse
    * @return string sanitized text
    public static function sanitize($text)
    $table = get_html_translation_table(HTML_ENTITIES, ENT_QUOTES);
    $textArray = str_split($text);
    $result = array();

    foreach($textArray as $key => $value) {
    if(isset($table[$value])) {
    $value = $table[$value];
    $result[] = $value;

    $str = nl2br(implode(“”, $result));
    $ret = str_replace(“\r\n”, “”, $str);

    return $ret;

    This function will not only parse all special chars to the HTML equivalent but replacing the new lines with so the output text is ready to be shown in HTML.

    See you! (-Manulaiko)

Leave a Reply

Your email address will not be published. Required fields are marked *


Want to take your Java Skills to the next level?
Grab our programming books for FREE!
  • Save time by leveraging our field-tested solutions to common problems.
  • The books cover a wide range of topics, from JPA and JUnit, to JMeter and Android.
  • Each book comes as a standalone guide (with source code provided), so that you use it as reference.
Last Step ...

Where should we send the free eBooks?

Good Work!
To download the books, please verify your email address by following the instructions found on the email we just sent you.