欢迎光临
这是我的个人博客

简单的预防XSS攻击,可以直接粘贴使用。

什么是XSS

XSSCross Site Scripting),跨站脚本攻击,是一种允许攻击者在另外一个用户的浏览器中执行恶意代码脚本的脚本注入式攻击。本来缩小应该是CSS,但为了和层叠样式(Cascading Style Sheet,CSS)有所区分,故称XSS

对于攻击者来说,能够让受害者浏览器执行恶意代码的唯一方式,就是把代码注入到受害者从网站下载的网页中。

不说那么多无用的,直接上代码!

OnRequestWrap.java
package com.gainet.filter;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

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

import org.apache.commons.lang.StringUtils;

/***
 * [XXS跨站脚本攻击过滤处理转换器]
 * 
 */
public class OnRequestWrap extends HttpServletRequestWrapper{
	
	/* XSS跨站脚本攻击转换签 */
	private String[] xssSource = new String[]{"\"", "'", "<", ">","data:", 
			/* 依次是URL编码, HTML10HEX,HTML16HEX,JSunicode,JS16HEX,JS8HEX */
			"data%3A", "&#100;&#97;&#116;&#97;&#58;", "&#x64;&#x61;&#x74;&#x61;&#x3a;", "\\u0064\\u0061\\u0074\\u0061\\u003a", "\\x64\\x61\\x74\\x61\\x3a", "\\144\\141\\164\\141\\72", /*英文冒号*/
			"%3C", "&#60;", "&#x3c;", "\\u003c", "\\x3c", "\\74",/*英文冒号右尖括号*/
			"%3E", "&#62;", "&#x3e;", "\\u003e", "\\x3e", "\\76"}; /*英文冒号左尖括号*/
	/* XSS跨站脚本攻击转换后 */
	private String[] xssTarget = new String[]{"“", "‘", "《", "》","data:",
			/* 依次是URL编码, HTML10HEX,HTML16HEX,JSunicode,JS16HEX,JS8HEX */
			"data%3A", "&#100;&#97;&#116;&#97;&#65306;", "&#x64;&#x61;&#x74;&#x61;&#xff1a;", "\\u0064\\u0061\\u0074\\u0061\\u00ff1a", "\\x64\\x61\\x74\\x61\\xff1a", "\\144\\141\\164\\141\\177432",/* 中文冒号 */
			"%E3%80%8A", "&#12298;", "&#x300a;", "\\u00300a", "\\x300a", "\\30012",/* 中文左尖括号 */
			"%E3%80%8B", "&#12299;", "&#x300b;", "\\u00300b", "\\x300b", "\\30013"};/* 中文右尖括号 */
	
	public OnRequestWrap(HttpServletRequest request) {
		super(request);
	}
	
	/* 格式化替换 */
	private String format(String name){
		return StringUtils.replaceEach(name, xssSource, xssTarget);
	}
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	public Map getParameterMap() {
		String key = "";
		Map<String, String[]> paramMap =  super.getParameterMap();
		HashMap<String, String[]> rm = new HashMap<String, String[]>();
		for (java.util.Iterator<Entry<String, String[]>> iterator = paramMap.entrySet().iterator(); iterator.hasNext(); ) {
			Map.Entry<String,String[]> entry = iterator.next();
			String [] values = entry.getValue();
			key = entry.getKey();
			for (int i = 0; i < values.length; i++) {
				if(values[i] instanceof String){
					values[i] = format(values[i]);
				}
			}
			rm.put(key,values);
		}
		return rm; 
	}
		

	@Override
	public String[] getParameterValues(String name) {
		String[] values = super.getParameterValues(name);
		if ( values != null ){
			for ( int i = 0; i < values.length; i++ ){
				values[i] = format(values[i]);
			}
		}
		return values;
	}

	@Override
	public Object getAttribute(String name){
		Object value = super.getAttribute(name);
		if ( value instanceof String ){
			value = format(String.valueOf(value));
		}
		return value;
	}

	@Override
	public String getParameter(String name) {
		String value = super.getParameter(name);
		if ( value == null ){
			return null;
		}
		return format(value);
	}
	
}
XSSFilter.java
package com.gainet.filter;

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;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * [XSS过滤]
 * 
 */
public class XSSFilter implements Filter {
	private Log logger = LogFactory.getLog(XSSFilter.class);

	@Override
	public void init(FilterConfig arg0) throws ServletException {

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain filterchain) throws IOException, ServletException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		/**
		 * 1,doFilter方法的第一个参数为ServletRequest对象。此对象给过滤器提供了对进入的信息(包括
		 * 表单数据、cookie和HTTP请求头)的完全访问。第二个参数为ServletResponse,通常在简单的过
		 * 滤器中忽略此参数。最后一个参数为FilterChain,此参数用来调用servlet或JSP页。
		 */
		HttpServletRequest request_ = (HttpServletRequest) request;
		/**
		 * 如果处理HTTP请求,并且需要访问诸如getHeader或getCookies等在ServletRequest中
		 * 无法得到的方法,就要把此request对象构造成HttpServletRequest
		 */
		@SuppressWarnings("unused")
		HttpServletResponse response_ = (HttpServletResponse) response;
		// 获取到来源路径
		String currentURL = request_.getRequestURI(); // 取得根目录所对应的绝对路径:
		@SuppressWarnings("unused")
		HttpSession session = request_.getSession(false);
		logger.debug("url:" + currentURL);
		logger.debug("网页来源" + request_.getHeader("Referer"));
		/* 排除地址*/
		if(!currentURL.contains("admin/checkusername") && !currentURL.contains("admin/showlogin")
		 && !currentURL.contains("admin/dologin") && !currentURL.contains("payNotify")
		 && !currentURL.contains("wxPayCallBack") && !currentURL.contains("admin/massmail/updateMassMail.action")   && !currentURL.contains("admin/massmail/importSendMassMail.action")
		 && !currentURL.contains("admin/help/addHelp.action") && !currentURL.contains("admin/help/addKyunHelp.action") && !currentURL.contains("admin/help/updateKyunHelp.action") && !currentURL.contains("admin/help/updateHelp.action") && !currentURL.contains("admin/help/updateAnswer.action")  && !currentURL.contains("admin/news/addNews.action") && !currentURL.contains("admin/news/updateNews.action")  && !currentURL.contains("admin/cloudhost/help/addHelp.action") && !currentURL.contains("admin/cloudhost/help/updateHelp.action") && !currentURL.contains("admin/notice/addNotice.action") && !currentURL.contains("admin/notice/updateNotice.action")
		)		
		{
			filterchain.doFilter(new OnRequestWrap((HttpServletRequest)request), response);
		}else{
			filterchain.doFilter(request, response);
		}
	}

	public boolean isActionUrl(String url) {
		url = url == null ? "" : url;
		// html jsp htm
		@SuppressWarnings("unused")
		boolean bl = false;
		if (isNotAction(url, ".html")) {
			return false;
		} else if (isNotAction(url, ".htm")) {
			return false;
		} else if (isNotAction(url, ".jsp")) {
			return false;
		} else
			return true;
	}

	public boolean isNotAction(String url, String type) {
		if (url.indexOf(type) > -1) {
			logger.debug("--" + url.indexOf(type));
			return true;
		} else {
			return false;
		}
	}

	@Override
	public void destroy() {
	}

然后在你项目中的web.xml中添加

   <filter>
       <filter-name>XssFilter</filter-name>
       <filter-class>com.gainet.filter.XSSFilter</filter-class>
    </filter>
    <filter-mapping>
       <filter-name>XssFilter</filter-name>
       <url-pattern>/*</url-pattern>
    </filter-mapping>

这样就可以使用了,亲测!filte 有加载顺序,位置一定要放好

赞(1)
未经允许不得转载:好好网 » 简单的预防XSS攻击,可以直接粘贴使用。

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址