在我们的jfinal配置类当中,配置自定义Handler
public void configHandler(Handlers handler) {
//handler.add(我们自定义handler的实例)
handler.add(new XssHandler());
}
新建XssHandler类,继承com.jfinal.handler.Handler
public class XssHandler extends Handler{
@Override
public void handle(String target, HttpServletRequest request, HttpServletResponse response, boolean[] isHandled) {
// 这里我们也可以相关请求,通过target判断,因为有的时候不是所有请求都加防止XSS,比如一个富文本编辑器提交的html代码,则不要验证,加一个if即可,这里过滤所有
request = new XssRequestWrapper(request);
next.handle(target, request, response, isHandled);
}
}
新建XssRequestWrapper类,继承javax.servlet.http.HttpServletRequestWrapper
public class XssRequestWrapper extends HttpServletRequestWrapper {
private HttpServletRequest request;
public XssRequestWrapper(HttpServletRequest request) {
super(request);
this.request = request;
}
/**
* 重写getParameter方法
*/
@Override
public String getParameter(String name) {
String value = super.getParameter(name);
if (value == null) {
return null;
}
value = format(value);
return value;
}
/**
* 重写getParameterMap
*/
@Override
@SuppressWarnings("unchecked")
public Map<String, String[]> getParameterMap() {
HashMap<String, String[]> paramMap = (HashMap<String, String[]>) super.getParameterMap();
paramMap = (HashMap<String, String[]>) paramMap.clone();
for (Iterator iterator = paramMap.entrySet().iterator(); iterator.hasNext(); ) {
Map.Entry<String, String[]> entry = (Map.Entry<String, String[]>) iterator.next();
String [] values = entry.getValue();
for (int i = 0; i < values.length; i++) {
if(values[i] instanceof String){
values[i] = format(values[i]);
}
}
entry.setValue(values);
}
return paramMap;
}
/**
* 重写getParameterValues
*/
@Override
public String[] getParameterValues(String name) {
String[] values = super.getParameterValues(name);
int count = values.length;
String[] encodedValues = new String[count];
for (int i = 0; i < count; i++) {
encodedValues[i] = format(values[i]);
}
return encodedValues;
}
/**
* 重写getHeader
*/
@Override
public String getHeader(String name) {
// TODO Auto-generated method stub
return format(super.getHeader(name));
}
public String filter(String message) {
if (message == null)
return (null);
message = format(message);
return message;
}
/**
* @desc 统一处理特殊字符的方法,替换掉sql和js的特殊字符
* @param name 要替换的字符
*/
private String format(String name) {
return xssEncode(name);
}
/**
* 将容易引起xss & sql漏洞的半角字符直接替换成全角字符
*
* @param s
* @return
*/
private static String xssEncode(String s) {
if (s == null || s.isEmpty()) {
return s;
}else{
s = stripXSSAndSql(s);
}
StringBuilder sb = new StringBuilder(s.length() + 16);
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
switch (c) {
case '>':
sb.append(">");// 转义大于号
break;
case '<':
sb.append("<");// 转义小于号
break;
case '\'':
sb.append("'");// 转义单引号
break;
case '\"':
sb.append(""");// 转义双引号
break;
case '&':
sb.append("&");// 转义&
break;
case '#':
sb.append("#");// 转义#
break;
default:
sb.append(c);
break;
}
}
return sb.toString();
}
/**
*
* 防止xss跨脚本攻击(替换,根据实际情况调整)
*/
public static String stripXSSAndSql(String value) {
if (value != null) {
// NOTE: It's highly recommended to use the ESAPI library and
// uncomment the following line to
// avoid encoded attacks.
// value = ESAPI.encoder().canonicalize(value);
// Avoid null characters
/** value = value.replaceAll("", "");***/
// Avoid anything between script tags
Pattern scriptPattern = Pattern.compile("<[\r\n| | ]*script[\r\n| | ]*>(.*?)</[\r\n| | ]*script[\r\n| | ]*>", Pattern.CASE_INSENSITIVE);
value = scriptPattern.matcher(value).replaceAll("");
// Avoid anything in a src="http://www.yihaomen.com/article/java/..." type of e-xpression
scriptPattern = Pattern.compile("src[\r\n| | ]*=[\r\n| | ]*[\\\"|\\\'](.*?)[\\\"|\\\']", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
value = scriptPattern.matcher(value).replaceAll("");
// Remove any lonesome </script> tag
scriptPattern = Pattern.compile("</[\r\n| | ]*script[\r\n| | ]*>", Pattern.CASE_INSENSITIVE);
value = scriptPattern.matcher(value).replaceAll("");
// Remove any lonesome <script ...> tag
scriptPattern = Pattern.compile("<[\r\n| | ]*script(.*?)>", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
value = scriptPattern.matcher(value).replaceAll("");
// Avoid eval(...) expressions
scriptPattern = Pattern.compile("eval\\((.*?)\\)", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
value = scriptPattern.matcher(value).replaceAll("");
// Avoid e-xpression(...) expressions
scriptPattern = Pattern.compile("e-xpression\\((.*?)\\)", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
value = scriptPattern.matcher(value).replaceAll("");
// Avoid javascript:... expressions
scriptPattern = Pattern.compile("javascript[\r\n| | ]*:[\r\n| | ]*", Pattern.CASE_INSENSITIVE);
value = scriptPattern.matcher(value).replaceAll("");
// Avoid vbscript:... expressions
scriptPattern = Pattern.compile("vbscript[\r\n| | ]*:[\r\n| | ]*", Pattern.CASE_INSENSITIVE);
value = scriptPattern.matcher(value).replaceAll("");
// Avoid οnlοad= expressions
scriptPattern = Pattern.compile("onload(.*?)=", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
value = scriptPattern.matcher(value).replaceAll("");
}
return value;
}
}
网上也看到一个较简单的
private String cleanXSS(String value) {
value = value.replaceAll("<", "& lt;").replaceAll(">", "& gt;");
value = value.replaceAll("\\(", "& #40;").replaceAll("\\)", "& #41;");
value = value.replaceAll("'", "& #39;");
value = value.replaceAll("eval\\((.*)\\)", "");
value = value.replaceAll("[\\\"\\\'][\\s]*javascript:(.*)[\\\"\\\']", "\"\"");
value = value.replaceAll("script", "");
return value;
}