[置顶] 简单web安全框架

 

web安全框架,主要用servlet filter方式覆盖httpServletRequest和HttpServletResponse方式增加一些输入输出的过滤,github地址:https://github.com/zhwj184/webSecurity

主要实现的安全包括:

  1. XSS过滤(获取用户输入参数和参数值进行XSS过滤,对Header和cookie value值进行XSS过滤(转码Script标签的< > 符号),

  2. 对Response的setStatus(int sc, String sm)方法 sm错误信息进行XSS过滤;

  3. 对Header的CLRF进行过滤;

  4. 对cookie大小和cookie的白名单进行验证;

  5. 对文件上传后缀白名单进行验证;

  6. 对只允许POST提交的url进行验证;

  7. CSRF攻击 tokenID防御支持;

  8. SESSION通过加密存储到cookie支持;

  9. 静态资源路径去除../上级目录符号;

使用指南:只需要在web.xml中配置对应的filter即可。

HttpSessionCookitStoreFilter是session存储到cookie的支持,encryKey加密密钥;

DefaultBaseSecurityFilter是默认的安全过滤filter,

securityFilterList可以配置对应的filter;

CookieWhiteListFilter:cookie白名单配置,如果配置这个,则需要配置参数cookieWhiteList;

CsrfTokenCkeckFilter:对post表单提交进行csrf token验证;使用CsrfTokenIdCreator生成csrf tokenid后放入表单还有session中,key名称必须为csrf_开头;为了支持多个form表单;

FileUploadSecurityFilter:文件上传后缀白名单验证,需要配置whitefilePostFixList参数;

FormPostPermitCheckFilter;只允许post提交的url列表,需要配置onlyPostUrlList参数;

redirectWhiteList:是配置重定向白名单url参数;

StaticFilePathSecurityFilter:url的../上级路径过滤;

 

使用在

<filter>
    <filter-name>HttpSessionCookitStoreFilter</filter-name>
    <filter-class>org.websecurity.filter.HttpSessionCookitStoreFilter</filter-class>
    <init-param>    
        <param-name>encryKey</param-name>
        <param-value>1234567887654321</param-value>
    </init-param>
</filter>

<filter>
    <filter-name>DefaultBaseSecurityFilter</filter-name>
    <filter-class>org.websecurity.DefaultBaseSecurityFilter</filter-class>
    <init-param>
        <param-name>securityFilterList</param-name><!-- ,org.websecurity.filter.CsrfTokenCkeckFilter -->
        <param-value>org.websecurity.filter.CookieWhiteListFilter,org.websecurity.filter.FormPostPermitCheckFilter</param-value>
    </init-param>
    <init-param>
        <param-name>cookieWhiteList</param-name>
        <param-value>id,JESSIONID,name,clrf</param-value>
    </init-param>
    <init-param>
        <param-name>onlyPostUrlList</param-name>
        <param-value>/d/sssecurity, /user/aaa/name*</param-value><!-- 支持正则匹配 -->
    </init-param>
    <init-param>
        <param-name>whitefilePostFixList</param-name>
        <param-value>jpg,png,doc,xls</param-value>
    </init-param>
    <init-param>
        <param-name>encryKey</param-name>
        <param-value>1234567887654321</param-value>
    </init-param>
    <init-param>
        <param-name>redirectWhiteList</param-name>
        <param-value>http://localhost:8080/[0-9A-Za-z]*,http://www.taobao.com/[0-9A-Za-z]*</param-value>
    </init-param>
</filter>

<filter-mapping>
    <filter-name>HttpSessionCookitStoreFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

<filter-mapping>
    <filter-name>DefaultBaseSecurityFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

 

测试代码:

@WebServlet(urlPatterns={"/security"},initParams={@WebInitParam(name="f", value="valuef"),@WebInitParam(name="g", value="valueg")})
public class MySecurityTest extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public MySecurityTest() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//xss params filter
		//url:
		System.out.println(request.getParameter("xssparam")); //output:
		System.out.println(request.getParameterMap().toString());
		
		//cookie white list output filter
		System.out.println(request.getCookies().toString());
		response.addCookie(new Cookie("name", "valName"));//valid
		response.addCookie(new Cookie("clrf", "valName\r\n<script>"));//valid
		try{
			response.addCookie(new Cookie("invalidName", "invalidvalName"));//not valid, throw runtimeexception
		}catch(Exception e){
			e.printStackTrace();
		}
		
		//cookie maxsize filter
		response.addCookie(new Cookie("id", ByteBuffer.allocate(4 * 1024 + 2).toString()));//valid
		
		//head security filter
		response.setHeader("aaa\r\nbbb", "ccc\r\\ddd\n");
		
		//session store to cookie
		System.out.println(request.getSession().getAttribute("sescookie"));
		request.getSession().setAttribute("sescookie", "sessioncookiestoretest");
		
		//rediction filter
//		response.sendRedirect("http://www.163.com");//failed
		
		//status filter
		response.setStatus(404, "<script>alert(1)</script>");
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.getWriter().write("hello, world");
	}

}

 

 一些输出:

&lt;script&gt;alert(1)&lt;/script&gt;
{xssparam=[Ljava.lang.String;@3476a7}
[Ljavax.servlet.http.Cookie;@1f5865a
java.lang.RuntimeException: cookie:invalidName is not in whitelist,not valid.
	at org.websecurity.SecurityHttpServletResponse.addCookie(SecurityHttpServletResponse.java:34)
	at org.websecurity.test.MySecurityTest.doGet(MySecurityTest.java:44)
	at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
	at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:304)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
	at com.filter.My3Filter2.doFilter(My3Filter2.java:28)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
	at com.filter.My3Filter.doFilter(My3Filter.java:29)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
	at org.websecurity.DefaultBaseSecurityFilter.doFilter(DefaultBaseSecurityFilter.java:44)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
	at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:240)
	at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:164)
	at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:462)
	at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:164)
	at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
	at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:562)
	at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
	at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:395)
	at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:250)
	at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:188)
	at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:166)
	at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:302)
	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
	at java.lang.Thread.run(Thread.java:722)

 

 



 

posted @ 2013-03-16 11:51  zhwj184  阅读(335)  评论(0编辑  收藏  举报