import java.io.IOException;
import java.util.Enumeration;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
/**
* <p>[过滤器解决SQL盲注安全问题]</p>
* *
*/
public class SqlFilter implements Filter{
private static Map<String,String> filterMap = new LinkedHashMap<String,String>();
private String failPage = "/error.jsp";//发生注入时,跳转页面
public void destroy() {
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain fc) throws IOException, ServletException {
//判断是否有注入攻击字符
HttpServletRequest req = (HttpServletRequest) request;
String inj = injectInput(req);
if (!inj.equals("")) {
request.getRequestDispatcher(failPage).forward(request, response);
return;
} else {
// 传递控制到下一个过滤器
fc.doFilter(request, response);
}
}
/**
* 判断request中是否含有注入攻击字符
*/
public String injectInput(ServletRequest request) {
Enumeration e = request.getParameterNames();
String attributeName;
String attributeValues[];
String inj = "";
String nameHasXss="";
while (e.hasMoreElements()) {
attributeName = (String)e.nextElement();
// //不对密码信息进行过滤,一般密码中可以包含特殊字符
// if(attributeName.equals("userPassword")||attributeName.equals("confirmPassword")||attributeName.equals("PASSWORD")
// ||attributeName.equals("password")||attributeName.equals("PASSWORD2")||attributeName.equals("valiPassword")){
// continue;
// }
nameHasXss = cleanXSS(attributeName);
if(!"".equals(nameHasXss)){
return nameHasXss;
}else{
attributeValues = request.getParameterValues(attributeName);
for (int i = 0; i < attributeValues.length; i++) {
if(attributeValues[i]==null||attributeValues[i].equals(""))
continue;
inj = cleanXSS(attributeValues[i]);
if (!inj.equals("")) {
return inj;
}
}
}
}
return inj;
}
/**
* 清除恶意的脚本
*/
private String cleanXSS(String value) {
Set<String> keySet = filterMap.keySet();
for(String key : keySet){
if(value.contains(key)){
return value;
}
}
return "";
}
public void init(FilterConfig fConfig) throws ServletException {
//含有脚本script
filterMap.put("[s|S][c|C][r|R][i|C][p|P][t|T]", "");
//含有脚本javascript
filterMap.put("[\\\"\\\'][\\s]*[j|J][a|A][v|V][a|A][s|S][c|C][r|R][i|I][p|P][t|T]:(.*)[\\\"\\\']", "\"\"");
//含有eval函数
filterMap.put("[e|E][v|V][a|A][l|L]\\((.*)\\)", "");
//含有特殊符号
filterMap.put("<", "<");
filterMap.put(">", ">");
filterMap.put("\\(", "(");
filterMap.put("\\)", ")");
filterMap.put("(", "(");
filterMap.put(")", ")");
filterMap.put("'", "'");
filterMap.put("\"", """);
filterMap.put(";", ";");
filterMap.put("+", "+");
filterMap.put("|", "¦");
filterMap.put("$", ";");
filterMap.put("@", ";");
filterMap.put("%", ";");
}
}