Monday, May 27, 2013

XSS Filter and Modifying POST data for Spring controller


The Context :

In some cases we have to intercept the request for which we use filter concept in J2EE framework. A typical case is the one where we have to prevent XSS attacks. I was able to take care of the common stuff by implementing httpservletresponsewrapper however there were certain cases where we were posting data in a http post request .



To read this data from the request we can use the following code.

1:  StringBuffer jb = new StringBuffer();  
2:   String line = null;  
3:   try {  
4:    BufferedReader reader = request.getReader();  
5:    while ((line = reader.readLine()) != null)  
6:     jb.append(line);  
7:   } catch (Exception e) { /*report an error*/ }   
Next step is bit complicated as the following  post explains
 
Much thanks to original contributor.
http://www.coderanch.com/t/364591/Servlets/java/read-request-body-filter 
  
My code 
 
All i did was searched and replaced nay script tag using the following regex

private static String scriptStartpattern = "(?i)<\\s*script\\s*>";
private static String scriptEndpattern = "(?i)<\\s*/\\s*script\\s*>";

No comments: