Make Your Java Web Applications Impervious to Cross-site Scripting, Page 2
Client-Side Protection: Removing Malicious Characters
To help prevent attackers from running cross-site scripts on client side, you can remove malicious characters from request parameters and cookies. The following steps will accomplish this:
- Identify malicious characters, such as <, >, (, ), and %, in parameters and cookies.
- Filter out the malicious characters from the parameters or cookies.
For example, the following request header for the URL http://www.examplesite/welcome.html?user=siva has cross-site scripting in the parameter 'user'.
After the user sends the request, the server-side filter will remove all malicious characters from the parameter, avoiding cross-site script execution on client side and thereby sending a secured response to the client.
Filters are processed based on the declared order in their deployment descriptors. So, to declare a filter for the current example, you would place the following filter (crossSite) on top of all other filters in the deployment descriptor (web.xml) of web application.
<filter> <filter-name>crossSite</filter-name> <filter-class>com.filters.RequestFilter</filter-class> </filter> <filter-mapping> <filter-name>crossSite</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
This filter mapping calls all requests using the URL pattern
A Custom Filter
The custom filter in Listing 1 will remove the untrusted characters from requests and cookies using the HttpServletRequestWrapper class, which is used to wrap the user's request (wrapped request object). Based upon the user's request to get the parameters or cookies, this wrapped request object removes the unsafe characters from the request and returns the response to the client. The wrapped request contains the trusted character for further processing.
Server-Side Protection: Implementing the Filter
The following steps implement the server-side filter in your web application.
- Add the compiled RequestFilter class in the
WEB-INF/classesfolder of the web application.
- Add the filter declaration in the deployment descriptor (web.xml).
With the techniques you have learned here (client-side validation and server-side filtering), you are ready to combat cross-site scripting in your Java-based web applications.
About the Authors
Sivakumar Kuppusamy is a product technical lead with product incubation engineering at Infosys, involved in the design and development of Java EE applications.
Ramasubramanian Thiyagarajan is a technology analyst with product incubation engineering at Infosys, involved in the design and development of Java EE applications.
Vijayasaradhi Paramakusum is a technology lead with product incubation engineering at Infosys, involved in the design and development of Java EE applications.