XSS跨站漏洞修复

避免XSS跨站漏洞的方法之一主要是将用户所提交的内容输入输出进行过滤,包括请求路径过滤与参数过滤。这里,我写一个过滤器专门处理XSS跨站漏洞,思路是将带有非法字符的请求转发到一个指定页面,将参数的非法字符过滤去除。

过滤器代码如下:

package com.eshore.itmp.model.web.security;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.regex.Pattern;

import javax.servlet.FilterChain;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.filter.OncePerRequestFilter;

/**
* XSS漏洞过滤器
*
* @author ahomeeye
*
*/
public class XssFilter extends OncePerRequestFilter {
private static Log logger = LogFactory.getLog(XssFilter.class);
private String forwardUrl = "/login.jsp";

@Override
protected void doFilterInternal(HttpServletRequest req,
HttpServletResponse res, FilterChain filterChain)
throws ServletException, IOException {
String uri = req.getRequestURI();
logger.info("-------uri=" + uri);

// 过滤请求的参数名和参数值
XssHttpServletRequestWrapper xssRequest = new XssHttpServletRequestWrapper(
(HttpServletRequest) req);

if (uri.contains("j_spring_security_check") && isContainSpecialChar(uri)) {// 判断uri是否合法
logger.info("-------uri包含特殊字符 uri=" + xssRequest.getRequestURI());
RequestDispatcher dispatcher = xssRequest
.getRequestDispatcher(forwardUrl);
dispatcher.forward(xssRequest, res);
} else {
filterChain.doFilter(xssRequest, res);// 执行其他过滤操作
}

}

/**
* 判断字符串是否包含特殊字符
*
* @param strVal
* @return
*/
public boolean isContainSpecialChar(String value) {
String strVal = "";
try {
strVal = URLDecoder.decode(value, "UTF-8");
} catch (UnsupportedEncodingException e) {
logger.error("URL解码错误", e);
}
boolean flag = false;
if (match(".*?*?.*?", strVal)) {// //匹配js脚本字符串
flag = true;
} else if (match(".*?<.*?>.*?", strVal)) {// 匹配html标签字符串
flag = true;
}
return flag;
}

/**
* 匹配正则表达式,大小写不敏感
*
* @param regex
* @param input
* @return
*/
public boolean match(String regex, CharSequence input) {
Pattern p = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
return p.matcher(input).matches();
}

public String getForwardUrl() {
return forwardUrl;
}

public void setForwardUrl(String forwardUrl) {
this.forwardUrl = forwardUrl;
}

}

在xml文件中声明过滤器,配置过滤器链































重写HttpServletRequest,覆盖一些方法

package com.eshore.itmp.model.web.security;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.regex.Pattern;

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

/**
* 请求参数过滤器(修复跨站脚本漏洞)
*
* @author ahomeeye
*
*/
public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper {

HttpServletRequest orgRequest = null;

public XssHttpServletRequestWrapper(HttpServletRequest request) {
super(request);
orgRequest = request;
}

/**
* 覆盖getParameter方法,将参数名和参数值都做xss过滤。

* 如果需要获得原始的值,则通过super.getParameterValues(name)来获取

* getParameterNames,getParameterValues和getParameterMap也可能需要覆盖
*/
@Override
public String getParameter(String name) {
String value = super.getParameter(xssEncode(name));
if (value != null) {
value = xssEncode(value);
}

return value;
}

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

return value;
}

/**
* 覆盖getHeader方法,将参数名和参数值都做xss过滤。

* 如果需要获得原始的值,则通过super.getHeaders(name)来获取

* getHeaderNames 也可能需要覆盖
*/
@Override
public String getHeader(String name) {

String value = super.getHeader(xssEncode(name));
if (value != null) {
value = xssEncode(value);
}
return value;
}

@Override
public String getRequestURI() {

String strVal = "";
try {
strVal = URLDecoder.decode(super.getRequestURI(), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}

String value = xssEncode(strVal);
if (value != null) {
value = xssEncode(value);
}

return value;
}

public String escape(String 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;
default:
sb.append(c);
break;
}

}
return sb.toString();
}

/**
* 将容易引起xss漏洞的半角字符直接替换成全角字符
*
* @param s
* @return
*/
public String xssEncode(String s) {
if (s == null || s.isEmpty()) {
return s;
}

String result = stripXSS(s);
if (null != result) {
result = escape(result);
}

return result;
}

private String stripXSS(String value) {
if (value != null) {
// NOTE: It's highly recommended to use the ESAPI library and
// uncomment the following line to
// avoid encoded attacks.
// value = ESAPI.encoder().canonicalize(value);
// Avoid null characters
value = value.replaceAll("", "");
// Avoid anything between script tags
Pattern scriptPattern = Pattern.compile("",
Pattern.CASE_INSENSITIVE);

value = scriptPattern.matcher(value).replaceAll("");
// Avoid anything in a src='...' type of expression
scriptPattern = Pattern.compile("src[\r\n]*=[\r\n]*\\\'(.*?)\\\'",
Pattern.CASE_INSENSITIVE | Pattern.MULTILINE
| Pattern.DOTALL);
value = scriptPattern.matcher(value).replaceAll("");
scriptPattern = Pattern.compile("src[\r\n]*=[\r\n]*\\\"(.*?)\\\"",
Pattern.CASE_INSENSITIVE | Pattern.MULTILINE
| Pattern.DOTALL);
value = scriptPattern.matcher(value).replaceAll("");
// Remove any lonesome tag
scriptPattern = Pattern.compile("",
Pattern.CASE_INSENSITIVE);
value = scriptPattern.matcher(value).replaceAll("");
// Remove any lonesome

























${sessionScope['SPRING_SECURITY_LAST_EXCEPTION'].message}

用户名
密   码
验证码









参考网址:
[url]http://yunjiechao-163-com.iteye.com/blog/1973803[/url]
[url]http://www.cnblogs.com/wuhuacong/archive/2013/04/15/3022011.html[/url]

你可能感兴趣的:(java,正则表达式)