One of the URL in my application is vulnerable to XSS attack, so I am handling it in the below way.
I created a util class:
import java.util.regex.Pattern;
public class HtmlUtils {
public final static String tagStart = "\\<\\w+((\\s+\\w+(\\s*\\=\\s*(?:\".*?\"|'.*?'|[^'\"\\>\\s]+))?)+\\s*|\\s*)\\>";
public final static String tagEnd = "\\</\\w+\\>";
public final static String tagSelfClosing = "\\<\\w+((\\s+\\w+(\\s*\\=\\s*(?:\".*?\"|'.*?'|[^'\"\\>\\s]+))?)+\\s*|\\s*)/\\>";
public final static String htmlEntity = "&[a-zA-Z][a-zA-Z0-9]+;";
public final static Pattern htmlPattern = Pattern.compile("(" + tagStart + ".*" + tagEnd + ")|(" + tagSelfClosing
+ ")|(" + htmlEntity + ")", Pattern.DOTALL);
public static boolean isHtml(String s) {
boolean ret = false;
if (s != null) {
ret = htmlPattern.matcher(s).find();
}
return ret;
}
}
And in the controller, I am throwing an exception if the requested value has an HTML script:
def isValidRequest(request){
def htmlRequest = false
def params = request.getParameterNames();
while(params.hasMoreElements()){
String paramName = (String)params.nextElement();
def value = request.getParameter(paramName);
htmlRequest = HtmlUtils.isHtml(value);
if(BooleanUtils.isTrue(htmlRequest))
break;
}
if(BooleanUtils.isTrue(htmlRequest))
throw new AccessDeniedException("Access Denied");
}
Does this look good or is there a better way to handle the XSS attack in the controller?