Last active
October 18, 2016 14:43
-
-
Save jtryan/f93a9011a66be6ad6f381e52085782b1 to your computer and use it in GitHub Desktop.
Validation headers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.sigilius.utility; | |
import sun.text.Normalizer; | |
import javax.servlet.http.HttpServletRequest; | |
import javax.servlet.http.HttpServletRequestWrapper; | |
import javax.validation.ValidationException; | |
import java.util.regex.Pattern; | |
public class ValidatingHttpRequest extends HttpServletRequestWrapper { | |
public ValidatingHttpRequest(HttpServletRequest request) { | |
super(request); | |
} | |
public String getParameter(String name) { | |
HttpServletRequest req = (HttpServletRequest) super.getRequest(); | |
return validate( name, req.getParameter( name ) ); | |
} | |
public String getHeader(String name) { | |
HttpServletRequest req = (HttpServletRequest) super.getRequest(); | |
return validate( name, req.getHeader( name ) ); | |
} | |
// This is a VERY restrictive pattern alphanumeric < 20 chars | |
// It's easy to make this a parameter for the filter and configure in web.xml | |
private Pattern pattern = Pattern.compile("^[a-zA-Z0-9_.]{0,20}$"); | |
private String validate( String name, String input ) throws ValidationException { | |
// important - always canonicalize before validating | |
String canonical = canonicalize( input ); | |
// check to see if input matches whitelist character set | |
if ( !pattern.matcher( canonical ).matches() ) { | |
throw new ValidationException( "Improper format in " + name + " field"); | |
} | |
// you could html entity encode input, but it's probably better to do this before output | |
// canonical = HTMLEntityEncode( canonical ); | |
return canonical; | |
} | |
// Simplifies input to its simplest form to make encoding tricks more difficult | |
private String canonicalize( String input ) { | |
String canonical = sun.text.Normalizer.normalize( input, java.text.Normalizer.Form.NFD, 0 ); | |
return canonical; | |
} | |
// Return HTML Entity code equivalents for any special characters | |
public static String HTMLEntityEncode( String input ) { | |
StringBuffer sb = new StringBuffer(); | |
for ( int i = 0; i < input.length(); ++i ) { | |
char ch = input.charAt( i ); | |
if ( ch>='a' && ch<='z' || ch>='A' && ch<='Z' || ch>='0' && ch<='9' ) { | |
sb.append( ch ); | |
} else { | |
sb.append( "&#" + (int)ch + ";" ); | |
} | |
} | |
return sb.toString(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment