码迷,mamicode.com
首页 > 其他好文 > 详细

XSS防御加排外的处理

时间:2019-03-06 15:13:51      阅读:164      评论:0      收藏:0      [点我收藏+]

标签:att   ||   https   builder   static   iterator   ash   init   substr   

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防御加排外的处理

标签:att   ||   https   builder   static   iterator   ash   init   substr   

原文地址:https://www.cnblogs.com/gaomingman/p/10482952.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!