由于我们的项目遭受了一次sql注入攻击,被批评的头破血流,马不停蹄安排起来。
首先,了解一下@WebFilter注解
@WebFilter 用于将一个类声明为过滤器,被@WebFilter注解的类,会在容器启动时被加载,并进行属性配置。具体的参数就不详细放出来了。initParams是该过滤器的初始化参数。
@Slf4j
@Component
@WebFilter(urlPatterns = "/*", filterName = "SQLInjection", initParams = { @WebInitParam(name = "regex", value = "(?:')|(?:--)|(/\\*(?:.|[\\n\\r])*?\\*/)|" +
"(\\b(and|exec|execute|insert|select|delete|update|count|drop|%|chr|mid|master|truncate|char|declare|sitename|net user|xp_cmdshell|or|like'|and|exec|execute|insert|create|drop|table|from|grant|use|group_concat|column_name|information_schema.columns|table_schema|union|where|select|delete|update|order|by|count|chr|mid|master|truncate|char|declare|or|--|like)\\b)") })
public class SqlInjectFilter implements Filter {
private String regx;
@Override
public void init(FilterConfig filterConfig) throws ServletException {
this.regx = filterConfig.getInitParameter("regex");
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) servletRequest;
Map parametersMap = servletRequest.getParameterMap();
Iterator it = parametersMap.entrySet().iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry) it.next();
String[] value = (String[]) entry.getValue();
for (int i = 0; i < value.length; i++) {
if(null != value[i] && this.regx != null){
Pattern p = Pattern.compile(this.regx); Matcher m = p.matcher(value[i]);
if (m.find()) {
log.error("您输入的参数有非法字符,请输入正确的参数!");
servletRequest.setAttribute("err", "您输入的参数有非法字符,请输入正确的参数!");
servletRequest.setAttribute("pageUrl",req.getRequestURI());
servletRequest.getRequestDispatcher( "/error").forward(servletRequest, servletResponse);
return;
}
}
}
}
filterChain.doFilter(servletRequest, servletResponse);
}
@Override
public void destroy() {
}
}
顺便提一下Pattern
Pattern p = Pattern.compile(regex); //编译正则表达式,并创建Pattern类。
Matcher m = p.matcher(s); // 通过模式对象得到匹配器对象
boolean b= m.find(); // 通过对象的find方法就是查找有没有满足条件的子串
这里可以去看一下这篇文章,写的挺详细的。Java Pattern和Matcher字符匹配详解_知行流浪-CSDN博客_java pattern和matcher
最后,不能忘了启动类的注解!!!
@ServletComponentScan("xxx.xxx.xxx.filter")
在SpringBootApplication上使用@ServletComponentScan注解后,Filter、Listener可以直接通过@WebFilter、@WebListener注解自动注册。
告辞!