antisamy的配置以及使用实现XSS防御


一、maven、antisamy介绍以及XSS:

  antisamy是owasp的开源项目,它用来确保用户输入的HTML/CSS符合应用规范的API,可以有效防止xss攻击。它提供了用于验证用户输入的富文本以防御跨站脚本的API,适用于java编写的web项目。它提供了一些标准策略文件,根据自己产品的实际需求,在此基础上配置一份适合自己产品的策略文件。

具体参考

http://anquan.163.com/module/pedia/article-00016.html

二、所需的相关文件:


三、antisamy在eclipse的配置

   

注意Tomcat应用服务器的安装。具体详见 http://jingyan.baidu.com/article/3065b3b6efa9d7becff8a4c6.html

转换为maven项目后发现在Libraries下为发现maven的下拉菜单,如下图所示:

解决方法:

修改pom.xml中的代码,即增加以下代码:

     <dependencies>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.12</version>
        </dependency>
        <dependency>
            <groupId>org.owasp.antisamy</groupId>
            <artifactId>antisamy</artifactId>
            <version>1.5.3</version>
        </dependency>
    </dependencies>
保存后刷新项目即可以看到maven下出现了相关的jar文件,即已经将该jar包进行了下载,而不需要自己在下载在加入path路径:


此时,即将maven和antisamy配置完成。

整体截图:


pom.xml代码:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>webTest</groupId>
  <artifactId>webTest</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  <build>
    <sourceDirectory>src</sourceDirectory>
    <resources>
      <resource>
        <directory>src</directory>
        <excludes>
          <exclude>**/*.java</exclude>
        </excludes>
      </resource>
    </resources>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.3</version>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
      <plugin>
        <artifactId>maven-war-plugin</artifactId>
        <version>2.6</version>
        <configuration>
          <warSourceDirectory>WebContent</warSourceDirectory>
          <failOnMissingWebXml>false</failOnMissingWebXml>
        </configuration>
      </plugin>
    </plugins>
   </build>
	<dependencies>
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.12</version>
		</dependency>
		<dependency>
			<groupId>org.owasp.antisamy</groupId>
			<artifactId>antisamy</artifactId>
			<version>1.5.3</version>
		</dependency>
	</dependencies>
</project>

增加了以下代码:


四、tomcat安装

这里依赖于【eclipse创建javaweb项目的环境配置】

具体参见http://blog.csdn.net/redarmy_chen/article/details/7048317

也可以参照以下链接安装和部署:

http://jingyan.baidu.com/article/3065b3b6efa9d7becff8a4c6.html

需要注意的是在添加目录时要采用英文名。


五、代码

XssFilter.java代码如下:(注意代码的包的)

import java.io.IOException;
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;
public class XssFilter implements Filter {  
@SuppressWarnings("unused")  
private FilterConfig filterConfig;  
public void destroy() {  
    this.filterConfig = null;  
}  
public void doFilter(ServletRequest request, ServletResponse response,  
        FilterChain chain) throws IOException, ServletException {  
    chain.doFilter(new RequestWrapper((HttpServletRequest) request), response);  
}  
public void init(FilterConfig filterConfig) throws ServletException {  
    this.filterConfig = filterConfig;  
}     
} 

相关代码的注释可以参见:

http://blog.csdn.net/goskalrie/article/details/51350736

RequestWrapper.java代码:

import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

import org.owasp.validator.html.AntiSamy;
import org.owasp.validator.html.CleanResults;
import org.owasp.validator.html.Policy;
import org.owasp.validator.html.PolicyException;
import org.owasp.validator.html.ScanException;

public class RequestWrapper extends HttpServletRequestWrapper {

	public RequestWrapper(HttpServletRequest request) {
		super(request);
	}
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public Map<String,String[]> getParameterMap(){
		Map<String,String[]> request_map = super.getParameterMap();
		Iterator iterator = request_map.entrySet().iterator();
		while(iterator.hasNext()){
			Map.Entry me = (Map.Entry)iterator.next();
			//System.out.println(me.getKey()+":");
			String[] values = (String[])me.getValue();
			for(int i = 0 ; i < values.length ; i++){
				System.out.println(values[i]);
				values[i] = xssClean(values[i]);
			}
		}
		return request_map;
	}
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public String getParameter(String name) {
		String v=super.getParameter(name);
		if(v==null)
			return null;
		return xssClean(v);
	}
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public String[] getParameterValues(String name) {
		String[] v=super.getParameterValues(name);
		if(v==null || v.length==0)
			return v;
		for(int i=0;i<v.length;i++){
				v[i]=xssClean(v[i]);
		}
		return v;
	}

	private String xssClean(String value) {
        AntiSamy antiSamy = new AntiSamy();
        try {
        	Policy policy = Policy.getInstance("/antisamy-slashdot.xml");
        	//CleanResults cr = antiSamy.scan(dirtyInput, policyFilePath); 
            final CleanResults cr = antiSamy.scan(value, policy);
            //瀹夊叏鐨凥TML杈撳嚭
            
            System.out.println("clean:"+cr.getCleanHTML());
            
            return cr.getCleanHTML();
        } catch (ScanException e) {
            e.printStackTrace();
        } catch (PolicyException e) {
            e.printStackTrace();
        }
        return value;
	}
}

web.xml代码:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	id="WebApp_ID" version="2.5">
	<display-name>sdl</display-name>
	<!-- XSS -->
	<filter>
		<filter-name>XSS</filter-name>
		<filter-class>XssFilter</filter-class>
	</filter>

	<filter-mapping>
		<filter-name>XSS</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
	<welcome-file-list>
		<welcome-file>index.html</welcome-file>
		<welcome-file>index.htm</welcome-file>
		<welcome-file>index.jsp</welcome-file>
		<welcome-file>default.html</welcome-file>
		<welcome-file>default.htm</welcome-file>
		<welcome-file>default.jsp</welcome-file>
	</welcome-file-list>
</web-app>


六、验证


htmlTest.html代码

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="main.jsp" method="POST">
First Name: <input type="text" name="first_name">
<br />
Last Name: <input type="text" name="last_name" />
<input type="submit" value="Submit" />
</form>
</body>
</html>

如下所示:


main.jsp代码:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<center>
<h1>Using GET Method to Read Form Data</h1>
<ul>
<li><p><b>First Name:</b>
   <%= request.getParameter("first_name")%>
</p></li>
<li><p><b>Last  Name:</b>
   <%= request.getParameter("last_name")%>
</p></li>
</ul>
</body>
</html>

如下所示:



  • 3
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值