spring解决sql注入问题:自定义拦截器

        近期刚做完的restful接口项目用安全软件扫描后,出现blind sql inject高危漏洞,查看,程序里已经使用了PreparedStatement预编译sql,却仍不好使,找不出原因,最后不得已,自定义了一个sql注入拦截器,对含有非法攻击字符的接口输入参数进行拦截,再次扫描后,漏洞消失。具体实现如下:

      一、自定义拦截器类SqlInjectInterceptor,实现spring包的HandlerInterceptor拦截接口:

package com.bonc.cb.interceptor;
public class SqlInjectInterceptor implements HandlerInterceptor{

	@Override
	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
			throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2) throws Exception {
		// TODO Auto-generated method stub
		if(arg0.getRequestURI().indexOf("CheckAcc")>-1){
			Enumeration names = arg0.getParameterNames();
			while(names.hasMoreElements()){
				String name = names.nextElement();
				String[] values = arg0.getParameterValues(name);
				for(String value: values){
					if(judgeXSS(value.toLowerCase())){
						arg1.setContentType("text/html;charset=UTF-8");
						arg1.getWriter().print("参数含有非法攻击字符,已禁止继续访问!");
						return false;
					}
				}
			}
		}
		
		return true;
	}
	
	/**
	 * 判断参数是否含有攻击串
	 * @param value
	 * @return
	 */
	public boolean judgeXSS(String value){
		if(value == null || "".equals(value)){
			return false;
		}
		String xssStr = "and|or|select|update|delete|drop|truncate|%20|=|-|--|;|'|%|#|+|,|//|/| |\\|!=|(|)";
		String[] xssArr = xssStr.split("\\|");
		for(int i=0;i-1){
				return true;
			}
		}
		return false;
		
	}

}
        二、自定义拦截器配置


	

	  
	      
	          
	              
	          
	      
	

注明:本解决办法为参考了多个文章的基础上,自己编程实现,如有雷同,请谅解。


你可能感兴趣的:(安全扫描漏洞,sql注入)