记⼀次JAVAWEB项⽬解决XSS攻击的办法(亲测有效)什么是XSS攻击
    简单来说,XSS 攻击是页⾯被注⼊了恶意的代码,度娘⼀⼤堆的东西,不想说
系统架构主要是SSM框架,服务层另外使⽤了DubboX.
   为啥说这个,因为SpringMVC对于Xss攻击需要特殊处理
思路 
    其实XSS⼯具解决思路就是捕获客户端提交的参数进⾏捕获,然后对参数值进⾏过滤处理,去除那些⾮法的字符.
    但是请求通常分为GET请求与POST请求,针对不同的请求,处理⽅式是不⼀样的
步骤:
    1.针对GET与⾮⽂件格式上传的post请求.(form 表单提交的时候没有这个参数enctype="multipart/form-data"),JSON请求等1) l配置过滤器
1<!-- xxs过滤 -->
java dubbo
2<filter>
3<filter-name>XssSqlFilter</filter-name>
4<filter-class>cn.ffcs.web.filter.XssFilter</filter-class>
5</filter>
6<filter-mapping>
7<filter-name>XssSqlFilter</filter-name>
8<url-pattern>/*</url-pattern>
9<dispatcher>REQUEST</dispatcher>
10</filter-mapping>
View Code
2)过滤器实现 XssFilter.java,针对部分特殊请求,要求不⾛过滤的,可以在此过滤器中放⾏
1package cn.ffcs.web.filter;
2
3import java.io.IOException;
4
5import javax.servlet.FilterChain;
6import javax.servlet.ServletException;
7import javax.servlet.http.HttpServletRequest;
8import javax.servlet.http.HttpServletResponse;
9
10import org.slf4j.Logger;
11import org.slf4j.LoggerFactory;
12import org.springframework.web.filter.OncePerRequestFilter;
13
14public class XssFilter extends OncePerRequestFilter {
15private final Logger logger = Class());
16      @Override
17protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
18throws ServletException, IOException {
19try {
20                String uri = RequestURI();
21//特殊url不⾛过滤器
22if (ains("receipt") || ains("mobile/buildingMgr")
23                          || ains("bestPay") || ains("backNotify") || ains("frontNotify")
24                          || ains("queryOrder") || ains("refundNotify") || ains("refund")
25                          || ains("reverse")) {
26                    chain.doFilter(request, response);
27                } else {
28                    XssHttpServletRequestWrapper xssRequest = new XssHttpServletRequestWrapper((HttpServletRequest) request);
29                    chain.doFilter(xssRequest, response);
30                }
31            } catch (Exception e) {
32                ("Xss过滤器,包装request对象失败");
33                chain.doFilter(request, response);
34            }
35        }
36 }
View Code
3) XssHttpServletRequestWrapper
1package cn.ffcs.web.filter;
2
3import javax.servlet.http.HttpServletRequest;
4import javax.servlet.http.HttpServletRequestWrapper;
5
6public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper {  7
8    HttpServletRequest orgRequest = null;
9
10public XssHttpServletRequestWrapper(HttpServletRequest request) {
11super(request);
12        orgRequest = request;
13    }
14
15/**
16    * 覆盖getParameter⽅法,将参数名和参数值都做xss过滤
17*/
18    @Override
19public String getParameter(String name) {
20        String value = Parameter(xssEncode(name));
21if (value != null) {
22            value = xssEncode(value);
23        }
24return value;
25    }
26/**
27    * 覆盖getParameterValues⽅法,将参数名和参数值都做xss过滤
28*/
29public String[] getParameterValues(String parameter) {
30        String[] values = ParameterValues(parameter);
31if (values==null)  {
32return null;
33        }
34int count = values.length;
35        String[] encodedValues = new String[count];
36for (int i = 0; i < count; i++) {
37            encodedValues[i] = xssEncode(values[i]);
38        }
39return encodedValues;
40    }
41
42/**
43    * 获取request的属性时,做xss过滤
44*/
45      @Override
46public Object getAttribute(String name) {
47        Object value = Attribute(name);
48if (null != value && value instanceof String) {
49            value = xssEncode((String) value);
50        }
51return value;
52    };
53
54/**
55    * 覆盖getHeader⽅法,将参数名和参数值都做xss过滤。<br/>
56*/
57    @Override
58public String getHeader(String name) {
59        String value = Header(xssEncode(name));
60if (value != null) {
61            value = xssEncode(value);
62        }
63return value;
64    }
65
66
67/**
68    * 将容易引起xss漏洞的半⾓字符直接替换成全⾓字符
69    *
70    * @param s
71    * @return
72*/
73private static String xssEncode(String s) {
74return XssEncode.xssEncode(s);
75    }
76
77/**
78    * 获取最原始的request
79    *
80    * @return
81*/
82public HttpServletRequest getOrgRequest() {
83return orgRequest;
84    }
85
86/**
87    * 获取最原始的request的静态⽅法
88    *
89    * @return
90*/
91public static HttpServletRequest getOrgRequest(HttpServletRequest req) {
92if (req instanceof XssHttpServletRequestWrapper) {
93return ((XssHttpServletRequestWrapper) req).getOrgRequest();
94        }
95
96return req;
97    }
98
99
100 }
View Code
4) 使⽤到的编码⼯具,过滤参数使⽤了xss-html-filter⼯具,具体可以⾃⾏替换
1package cn.ffcs.web.filter;
2
3import net.sf.xsshtmlfilter.HTMLFilter;
4
5public class XssEncode {
6public static String xssEncode(String s) {
7if (s == null || s.isEmpty()) {
8return s;
9        }
10try {
11            HTMLFilter htmlFilter = new HTMLFilter();
12            String clean = htmlFilter.filter(s);
13return clean;
14        } catch (NullPointerException e) {
15return s;
16        } catch (Exception ex) {
17            ex.printStackTrace();
18        }
19
20return null;
21    }
22 }
View Code
5) l 配置引⽤的jar
1<dependency>
2<groupId>net.sf.xss-html-filter</groupId>
3<artifactId>xss-html-filter</artifactId>
4<version>1.5</version>
5</dependency>
View Code
    2.针对enctype="multipart/form-data"格式的post提交
1) 更改springMVC默认Annotation适配器(org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter - ->  cn.ffcs.web.filter.XssAnnotationMethodHandlerAdapter),如果没有则添加
1<!-- annotation⽅法修饰器 -->
2<bean id="handlerAdapter" class="cn.ffcs.web.filter.XssAnnotationMethodHandlerAdapter">
3
4 ....
5
6<bean>
2) 继承AnnotationMethodHandlerAdapter 并覆盖handle⽅法
1package cn.ffcs.web.filter;
2
3import java.util.Map;
4import java.util.Set;
5
6import javax.servlet.http.HttpServletRequest;
7import javax.servlet.http.HttpServletResponse;
8
9import net.sf.xsshtmlfilter.HTMLFilter;
10
11import org.apachemons.lang.StringUtils;
12import org.springframework.web.servlet.ModelAndView;
13import org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter;
14 @SuppressWarnings("deprecation")
15public class XssAnnotationMethodHandlerAdapter extends
16        AnnotationMethodHandlerAdapter {
17
18
19    @SuppressWarnings({ "rawtypes", "unchecked" })
20private void myXss(HttpServletRequest request){
21        Map map = ParameterMap();
22        Set<String> keySet = map.keySet();
23for(String key : keySet){
24            String[] values = ParameterValues(key);
25if(values!=null&&values.length>0){
26for(int i=0 ;i<values.length;i++){
27if(!StringUtils.isBlank(values[i])){
28                        values[i] = XssEncode.xssEncode(values[i]);
29                    }
30                }
31            }
32        }
33    }
34
35    @Override
36public ModelAndView handle(HttpServletRequest request,
37            HttpServletResponse response, Object handler) throws Exception {
38        myXss(request);
39return super.handle(request, response, handler);
40    }
41 }
View Code
tip: ⽹上另外有说⽤反射实现带@Controller的控制器,感觉思路可以,但是没有成功.

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。