实用:防止SQL、XSS等注入攻击的Filter

14 篇文章 0 订阅

本文主要原理是转换过滤或拦截请求中的非法字符

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> 


一、什么是XSS攻击 XSS是一种经常出现在web应用中的计算机安全漏洞,它允许恶意web用户将代码植入到提供给其它用户使用的页面中。比如这些代码包括HTML代码和客户端脚本。攻击者利用XSS漏洞旁路掉访问控制——例如同源策略(same origin policy)。这种类型的漏洞由于被黑客用来编写危害性更大的网络钓鱼(Phishing)攻击而变得广为人知。对于跨站脚本攻击,黑客界共识是:跨站脚本攻击是新型的“缓冲区溢出攻击“,而JavaScript是新型的“ShellCode”。 二、XSS漏洞的危害 (1)网络钓鱼,包括盗取各类用户账号; (2)窃取用户cookies资料,从而获取用户隐私信息,或利用用户身份进一步对网站执行操作; (3)劫持用户(浏览器)会话,从而执行任意操作,例如进行非法转账、强制发表日志、发送电子邮件等; (4)强制弹出广告页面、刷流量等; (5)网页挂马; (6)进行恶意操作,例如任意篡改页面信息、删除文章等; (7)进行大量的客户端攻击,如DDoS攻击; (8)获取客户端信息,例如用户的浏览历史、真实IP、开放端口等; (9)控制受害者机器向其他网站发起攻击; (10)结合其他漏洞,如CSRF漏洞,实施进一步作恶; (11)提升用户权限,包括进一步渗透网站; (12)传播跨站脚本蠕虫等; 三、过滤器配置 web.xml配置 XssFilter com.xxx.Filter.XssFilter XssFilter /*
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值