Regular Expressions

Posted on October 24, 2012. Filed under: SANS Dev 541 |

Data Validation is one of the most effective ways of preventing XSS, we either whitelist characters we accept for a field or blacklist malicious special characters, for example:

Char < > : { } [ ] ;
Hex Char Code %3c %3e %22 %3a %7b %7d %5b %5d %3b

With java regular expressions, we can apply blacklist and/or whitelist to data fields in web applications, providing that we know exactly what character set the web page will use.

For example, the following code snippets check servlet request for malicious xxs and sql injection special characters:

import java.util.regex.*;
import javax.servlet.*;
import java.util.Enumeration;

 * @param request
 * @return
 private boolean validateParameters(ServletRequest request) {
 Enumeration<String> params = request.getParameterNames();
 String paramName;
 while (params.hasMoreElements()) {
 paramName = params.nextElement();
 if (searchReservedChars(request.getParameter(paramName), paramName)) {
 return false;

 return true;

private boolean searchReservedChars(String value, String paramName) {

 Pattern xsspattern = Pattern.compile([\\w]*((%27)|(‘))\\s*((%6F)|o|(%4F))((%72)|r|(%52))”
 + “|[\\w]*((%27)|(‘))\\s*((%61)|a|(%41))((%6E)|n|(%4E))((%64)|d|(%44))”
 + “|(((%3E)|>|(%3C)|<))”
 + “|(((%3E)|>|(%3C)|<)+.*[://.=/(/);'\"&#-]+.*)”
 + “|(.*[://.=/(/);'\"&#-]+.*((%3E)|>|(%3C)|<)+)”
 + “|(((%3C)|<)((%69)|i|(%49))((%6D)|m|(%4D))((%67)|g|(%47))[^\\n]+((%3E)|>)));
 Matcher match = xsspattern.matcher(value);
 if(match.find()) {
 errorMessage = new StringBuffer();
 String charstr = value.substring(match.start(), match.end());
 charstr = charstr.replaceAll(“>”, “&gt;”);
 charstr = charstr.replaceAll(“<”, “&lt;”);
 errorMessage.append(“Suspicious input [ ").append(charstr).append(" ]. Use the browser Back key to return to the previous screen to correct this problem.”);
 return true;
 return false;

The following video is an introduction of java.util.regex.* library and how to construct regular expressions.


Make a Comment

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Liked it here?
Why not try sites on the blogroll...

%d bloggers like this: