本文主要原理是转换过滤或拦截请求中的非法字符
FILTER代码:
XssFilter.java
/**
* <code>{@link CharLimitFilter}</code>
*
* 拦截防止XSS注入
*
* @author Administrator
*/
public class XssFilter implements Filter {
/* (non-Javadoc)
* @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
*/
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException,
ServletException {
XssHttpServletRequestWrapper xssRequest = new XssHttpServletRequestWrapper(
(HttpServletRequest) request);
filterChain.doFilter(xssRequest, response);
}
public void init(FilterConfig conf) throws ServletException {
System.out.println("PreventXSSInject Filter staring...");
System.out.println();
}
public void destroy() {
}
}
SqlInjectFilter.java
public class SqlInjectFilter implements Filter {
private static List<String> invalidsql = new ArrayList<String>();
private static String error = "/sqlerrors.jsp";
private static boolean debug = false;
public void destroy() {
}
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain fc) throws IOException, ServletException {
//防sql关键字注入
if(debug){
System.out.println("prevent sql inject filter works");
}
HttpServletRequest request = (HttpServletRequest)req;
HttpServletResponse response = (HttpServletResponse)res;
Map<String, String> params = request.getParameterMap();
Set<String> keys = params.keySet();
for(String key : keys){
String value = request.getParameter(key);
if(debug){
System.out.println("process params <key, value>: <"+key+", "+value+">");
}
for(String word : invalidsql){
if(word.equalsIgnoreCase(value) || value.contains(word)){
if(value.contains("<")){
value = value.replace("<", "<");
}
if(value.contains(">")){
value = value.replace(">", ">");
}
if(value.contains("(")){
value = value.replace("(", "(");
}
if(value.contains(")")){
value = value.replace(")", ")");
}
request.getSession().setAttribute("sqlInjectError", "您输入的参数值 \""+value+"\" 中包含关键字: \""+word+"\"");
response.sendRedirect(request.getContextPath()+error);
return;
}
}
}
fc.doFilter(req, res);
}
public void init(FilterConfig conf) throws ServletException {
String sql = conf.getInitParameter("invalidsql");
String errorpage = conf.getInitParameter("error");
String de = conf.getInitParameter("debug");
if(errorpage != null){
error = errorpage;
}
if(sql != null){
//invalidsql = Arrays.asList(sql.split(" "));
String[] sqlarr = sql.split(" ");
for(String sqlword:sqlarr){
invalidsql.add(sqlword);
}
invalidsql.add("<");
invalidsql.add(">");
invalidsql.add("(");
invalidsql.add(")");
}
if(de != null && Boolean.parseBoolean(de)){
debug = true;
System.out.println("PreventSQLInject Filter staring...");
System.out.println("print filter details");
System.out.println("invalid words as fllows (split with blank):");
for(String s : invalidsql){
System.out.print(s+" ");
}
System.out.println();
System.out.println("error page as fllows");
System.out.println(error);
System.out.println();
}
}
}
XSS包装器:
XssHttpServletRequestWrapper.java
/**
* <code>{@link XssHttpServletRequestWrapper}</code>
*
* TODO : document me
*
* @author Administrator
*/
public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper {
HttpServletRequest orgRequest = null;
public XssHttpServletRequestWrapper(HttpServletRequest request) {
super(request);
orgRequest = request;
}
/**
* 覆盖getParameter方法,将参数名和参数值都做xss过滤。<br/>
* 如果需要获得原始的值,则通过super.getParameterValues(name)来获取<br/>
* getParameterNames,getParameterValues和getParameterMap也可能需要覆盖
*/
@Override
public String getParameter(String name) {
String value = super.getParameter(xssEncode(name));
if (value != null) {
value = xssEncode(value);
}
return value;
}
/**
* 覆盖getHeader方法,将参数名和参数值都做xss过滤。<br/>
* 如果需要获得原始的值,则通过super.getHeaders(name)来获取<br/>
* getHeaderNames 也可能需要覆盖
*/
@Override
public String getHeader(String name) {
String value = super.getHeader(xssEncode(name));
if (value != null) {
value = xssEncode(value);
}
return value;
}
/**
* 将容易引起xss漏洞的半角字符直接替换成全角字符
*
* @param s
* @return
*/
private static String xssEncode(String s) {
if (s == null || "".equals(s)) {
return 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;
case '#':
sb.append('#');//全角井号
break;
case '(':
sb.append('(');//全角井号
break;
case ')':
sb.append(')');//全角井号
break;
default:
sb.append(c);
break;
}
}
return sb.toString();
}
/**
* 获取最原始的request
*
* @return
*/
public HttpServletRequest getOrgRequest() {
return orgRequest;
}
/**
* 获取最原始的request的静态方法
*
* @return
*/
public static HttpServletRequest getOrgRequest(HttpServletRequest req) {
if (req instanceof XssHttpServletRequestWrapper) {
return ((XssHttpServletRequestWrapper) req).getOrgRequest();
}
return req;
}
}
在WEB.XML中配置FILTER
<!-- XSS过滤器 -->
<filter>
<filter-name>XssFilter</filter-name>
<filter-class>
com.megait.jgjz.web.filter.XssFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>XssFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- SQL关键词注入过滤器 -->
<filter>
<filter-name>PreventSqlInject</filter-name>
<filter-class>com.megait.jgjz.web.filter.SqlInjectFilter</filter-class>
<!-- filter word, split with blank -->
<init-param>
<param-name>invalidsql</param-name>
<param-value>select insert delete from update create where union destory drop alter and or like exec count chr mid master truncate char declare ; - ' % | $ % @ " + cr lf , . script document eval</param-value>
</init-param>
<!-- error page -->
<init-param>
<param-name>error</param-name>
<param-value>/sqlerrors.jsp</param-value>
</init-param>
<!-- debug -->
<init-param>
<param-name>debug</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>PreventSqlInject</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
在应用里添加注入报错页面
sqlerrors.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Pragma" contect="no-cache">
<title>防sql注入系统</title>
</head>
<body>
这个是防sql注入系统,自动过滤您的请求,请更换请求字符串。
<%=session.getAttribute("sqlInjectError")%>
</body>
</html>