XSS防御加排外的处理
Posted gaomingman
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了XSS防御加排外的处理相关的知识,希望对你有一定的参考价值。
package com.zhaogang.scm.common.core.filter;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
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 com.alibaba.druid.util.DruidWebUtils;
import com.alibaba.druid.util.PatternMatcher;
import com.alibaba.druid.util.ServletPathMatcher;
public class XssFilter implements Filter {
protected PatternMatcher pathMatcher;
private Set excludesPattern;
FilterConfig filterConfig = null;
String contextPath;
public void init(FilterConfig config) throws ServletException {
String exclusions = config.getInitParameter("exclusions");
contextPath = DruidWebUtils.getContextPath(config.getServletContext());
if(exclusions != null && exclusions.trim().length() != 0)
excludesPattern = new HashSet(Arrays.asList(exclusions.split("\s*,\s*")));
}
public void destroy() {
this.filterConfig = null;
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
boolean isExcludedPage = false;
String requestURI;
HttpServletRequest httpRequest = (HttpServletRequest)request;
requestURI = httpRequest.getRequestURI();;
isExcludedPage = isExclusion(requestURI);
if (isExcludedPage) {
chain.doFilter(request, response);
} else {
chain.doFilter(new XssHttpServletRequestWrapper((HttpServletRequest) request), response);
}
}
public boolean isExclusion(String requestURI)
{
if(excludesPattern == null || requestURI == null)
return false;
if(contextPath != null && requestURI.startsWith(contextPath))
{
requestURI = requestURI.substring(contextPath.length());
if(!requestURI.startsWith("/"))
requestURI = (new StringBuilder()).append("/").append(requestURI).toString();
}
for(Iterator iterator = excludesPattern.iterator(); iterator.hasNext();)
{
String pattern = (String)iterator.next();
if(pathMatcher.matches(pattern, requestURI))
return true;
}
return false;
}
public XssFilter()
{
pathMatcher = new ServletPathMatcher();
}
}
package com.zhaogang.scm.common.core.filter;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import com.zhaogang.scm.common.log.Log;
import com.zhaogang.scm.common.util.LogUtil;
public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper {
private final Log log = LogUtil.getLogger();
boolean isUpData = false;// 判断是否是上传 上传忽略
public XssHttpServletRequestWrapper(HttpServletRequest servletRequest) {
super(servletRequest);
String contentType = servletRequest.getContentType();
if (null != contentType)
isUpData = contentType.startsWith("multipart");
}
@Override
public String[] getParameterValues(String parameter) {
String[] values = super.getParameterValues(parameter);
if (values == null) {
return null;
}
int count = values.length;
String[] encodedValues = new String[count];
for (int i = 0; i < count; i++) {
encodedValues[i] = cleanXSS(values[i]);
}
return encodedValues;
}
@Override
public String getParameter(String parameter) {
String value = super.getParameter(parameter);
if (value == null) {
return null;
}
return cleanXSS(value);
}
/**
* 获取request的属性时,做xss过滤
*/
@Override
public Object getAttribute(String name) {
Object value = super.getAttribute(name);
if (null != value && value instanceof String) {
value = cleanXSS((String) value);
}
return value;
}
@Override
public String getHeader(String name) {
String value = super.getHeader(name);
if (value == null)
return null;
return cleanXSS(value);
}
/**
* 做xss过滤特殊字符
*/
private static String cleanXSS(String value) {
if (value == null || value.isEmpty()) {
return value;
}
StringBuilder sb = new StringBuilder(value.length() + 16);
for (int i = 0; i < value.length(); i++) {
char c = value.charAt(i);
switch (c) {
case ‘>‘:
sb.append(‘>‘);// 全角大于号
break;
case ‘<‘:
sb.append(‘<‘);// 全角小于号
break;
case ‘#‘:
sb.append(‘#‘);// 全角井号
break;
default:
sb.append(c);
break;
}
}
return sb.toString();
}
/**
* getInputStream()方法的流处理,获取requestBody
*/
@Override
public ServletInputStream getInputStream() throws IOException {
if (isUpData) {
return super.getInputStream();
} else {
final ByteArrayInputStream bais = new ByteArrayInputStream(
inputHandlers(super.getInputStream()).getBytes());
return new ServletInputStream() {
@Override
public int read() throws IOException {
return bais.read();
}
};
}
}
public String inputHandlers(ServletInputStream servletInputStream) {
StringBuilder sb = new StringBuilder();
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(servletInputStream, Charset.forName("UTF-8")));
String line = "";
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
log.error(e, "SCM-COMMON", "XSSError reading the request body…");
} finally {
if (servletInputStream != null) {
try {
servletInputStream.close();
} catch (IOException e) {
log.error(e, "SCM-COMMON", "XSSError reading the request body…");
}
}
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
log.error(e, "SCM-COMMON", "XSSError reading the request body…");
}
}
}
return cleanXSS(sb.toString());
}
}
<!-- 配置防XSS过滤器 -->
<filter>
<filter-name>XssFilter</filter-name>
<filter-class>
com.zhaogang.scm.common.core.filter.XssFilter
</filter-class>
<!-- 配置排除防XSS -->
<init-param>
<param-name>exclusions</param-name>
<param-value></param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>XssFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
参考com.alibaba.druid.support.http.WebStatFilter源码
以上是关于XSS防御加排外的处理的主要内容,如果未能解决你的问题,请参考以下文章