记一次JAVA WEB项目解决XSS攻击的办法(亲测有效)

  • 什么是XSS攻击

    简单来说,XSS 攻击是页面被注入了恶意的代码,度娘一大堆的东西,不想说

  • 系统架构主要是SSM框架,服务层另外使用了DubboX.

     为啥说这个,因为SpringMVC对于Xss攻击需要特殊处理

  • 思路  

    其实XSS工具解决思路就是捕获客户端提交的参数进行捕获,然后对参数值进行过滤处理,去除那些非法的字符.

    但是请求通常分为GET请求与POST请求,针对不同的请求,处理方式是不一样的

  • 步骤:

    1.针对GET与非文件格式上传的post请求.(form 表单提交的时候 没有这个参数enctype="multipart/form-data"),JSON请求等

1) web.xml配置过滤器

 <!-- xxs过滤 -->
<filter>
<filter-name>XssSqlFilter</filter-name>
<filter-class>cn.ffcs.web.filter.XssFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>XssSqlFilter</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>REQUEST</dispatcher>
</filter-mapping>

2)过滤器实现 XssFilter.java,针对部分特殊请求,要求不走过滤的,可以在此过滤器中放行

 package cn.ffcs.web.filter;

 import java.io.IOException;

 import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.filter.OncePerRequestFilter; public class XssFilter extends OncePerRequestFilter {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws ServletException, IOException {
try {
String uri = request.getRequestURI();
//特殊url不走过滤器
if (uri.contains("receipt") || uri.contains("mobile/buildingMgr")
|| uri.contains("bestPay") || uri.contains("backNotify") || uri.contains("frontNotify")
|| uri.contains("queryOrder") || uri.contains("refundNotify") || uri.contains("refund")
|| uri.contains("reverse")) {
chain.doFilter(request, response);
} else {
XssHttpServletRequestWrapper xssRequest = new XssHttpServletRequestWrapper((HttpServletRequest) request);
chain.doFilter(xssRequest, response);
}
} catch (Exception e) {
logger.error("Xss过滤器,包装request对象失败");
chain.doFilter(request, response);
}
}
}

3) XssHttpServletRequestWrapper

 package cn.ffcs.web.filter;

 import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper; public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper { HttpServletRequest orgRequest = null; public XssHttpServletRequestWrapper(HttpServletRequest request) {
super(request);
orgRequest = request;
} /**
* 覆盖getParameter方法,将参数名和参数值都做xss过滤
*/
@Override
public String getParameter(String name) {
String value = super.getParameter(xssEncode(name));
if (value != null) {
value = xssEncode(value);
}
return value;
}
/**
* 覆盖getParameterValues方法,将参数名和参数值都做xss过滤
*/
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] = xssEncode(values[i]);
}
return encodedValues;
} /**
* 获取request的属性时,做xss过滤
*/
@Override
public Object getAttribute(String name) {
Object value = super.getAttribute(name);
if (null != value && value instanceof String) {
value = xssEncode((String) value);
}
return value;
}; /**
* 覆盖getHeader方法,将参数名和参数值都做xss过滤。<br/>
*/
@Override
public String getHeader(String name) {
String value = super.getHeader(xssEncode(name));
if (value != null) {
value = xssEncode(value);
}
return value;
} /**
* 将容易引起xss漏洞的半角字符直接替换成全角字符
*
* @param s
* @return
*/
private static String xssEncode(String s) {
return XssEncode.xssEncode(s);
} /**
* 获取最原始的request
*
* @return
*/
public HttpServletRequest getOrgRequest() {
return orgRequest;
} /**
* 获取最原始的request的静态方法
*
* @return
*/
public static HttpServletRequest getOrgRequest(HttpServletRequest req) {
if (req instanceof XssHttpServletRequestWrapper) {
return ((XssHttpServletRequestWrapper) req).getOrgRequest();
} return req;
} }

4) 使用到的编码工具,过滤参数使用了xss-html-filter工具,具体可以自行替换

 package cn.ffcs.web.filter;

 import net.sf.xsshtmlfilter.HTMLFilter;

 public class XssEncode {
public static String xssEncode(String s) {
if (s == null || s.isEmpty()) {
return s;
}
try {
HTMLFilter htmlFilter = new HTMLFilter();
String clean = htmlFilter.filter(s);
return clean;
} catch (NullPointerException e) {
return s;
} catch (Exception ex) {
ex.printStackTrace();
} return null;
}
}

5) pom.xml 配置引用的jar

 <dependency>
<groupId>net.sf.xss-html-filter</groupId>
<artifactId>xss-html-filter</artifactId>
<version>1.5</version>
</dependency>

    2.针对enctype="multipart/form-data"格式的post提交

1) 更改springMVC默认Annotation适配器(org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter - ->    cn.ffcs.web.filter.XssAnnotationMethodHandlerAdapter),如果没有则添加

 <!-- annotation方法修饰器 -->
<bean id="handlerAdapter" class="cn.ffcs.web.filter.XssAnnotationMethodHandlerAdapter"> .... <bean>

2) 继承AnnotationMethodHandlerAdapter 并覆盖handle方法

 package cn.ffcs.web.filter;

 import java.util.Map;
import java.util.Set; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import net.sf.xsshtmlfilter.HTMLFilter; import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter;
@SuppressWarnings("deprecation")
public class XssAnnotationMethodHandlerAdapter extends
AnnotationMethodHandlerAdapter { @SuppressWarnings({ "rawtypes", "unchecked" })
private void myXss(HttpServletRequest request){
Map map = request.getParameterMap();
Set<String> keySet = map.keySet();
for(String key : keySet){
String[] values = request.getParameterValues(key);
if(values!=null&&values.length>0){
for(int i=0 ;i<values.length;i++){
if(!StringUtils.isBlank(values[i])){
values[i] = XssEncode.xssEncode(values[i]);
}
}
}
}
} @Override
public ModelAndView handle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {
myXss(request);
return super.handle(request, response, handler);
}
}

tip: 网上另外有说用反射实现带@Controller的控制器,感觉思路可以,但是没有成功.

上一篇:ZK集群搭建和配置


下一篇:在线的JSON formate工具