一:什么是XSS
XSS攻击全称跨站脚本攻击,是一种在web应用中的计算机安全漏洞,它允许恶意web用户将代码植入到提供给其它用户使用的页面中。
你可以自己做个简单尝试:
- 在任何一个表单内,你输入一段简单的js代码:<script>for(var i=0;i<1000;i++){alert("弹死你"+i);}</script>,将其存入数据库;
- 在页面上一个div元素内直接展示第一步内存入的值,你会发现弹出框出现了;
以上两个示例仅仅算是恶作剧,恶意用户能做的更多,如获取用户信息,进行“网络钓鱼”攻击等。
应对XSS攻击的其中一个方式就是后端对输入内容进行过滤,输入内容里面的敏感信息直接过滤,如<script>标签等。
二:添加Jsoup依赖
Jsoup使用标签白名单的机制用来进行防止XSS攻击, 假设白名单中只允许p标签存在, 此时在一段HTML代码中, 只能存在p标签 , 其他标签将会被清除只保留被标签所包裹的内容,当然,Jsoup不仅仅可以用来过滤,还可以用来爬虫,这里先不做说明,后期会单写一篇文章进行讲解。
1
2
3
4
5
6 1<dependency>
2 <groupId>org.jsoup</groupId>
3 <artifactId>jsoup</artifactId>
4 <version>1.10.2</version>
5</dependency>
6
三:创建过滤器
在core下创建filter文件夹
1、创建过滤规则
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35 1package com.example.demo.core.filter;
2
3import org.jsoup.Jsoup;
4import org.jsoup.nodes.Document;
5import org.jsoup.safety.Whitelist;
6
7/**phubing张瑶
8 * @Description: xss非法标签过滤
9 * @date 2019/5/16 20:03
10 */
11public class XssFilterUtil {
12
13 /**
14 * 使用自带的basicWithImages 白名单
15 * 允许的便签有a,b,blockquote,br,cite,code,dd,dl,dt,em,i,li,ol,p,pre,q,small,span,
16 * strike,strong,sub,sup,u,ul,img
17 * 以及a标签的href,img标签的src,align,alt,height,width,title属性
18 */
19 private static final Whitelist whitelist = Whitelist.basicWithImages();
20
21 /** 配置过滤化参数,不对代码进行格式化 */
22 private static final Document.OutputSettings outputSettings = new Document.OutputSettings().prettyPrint(false);
23 static {
24 // 富文本编辑时一些样式是使用style来进行实现的
25 // 比如红色字体 style="color:red;"
26 // 所以需要给所有标签添加style属性
27 whitelist.addAttributes(":all", "style");
28 }
29
30 public static String clean(String content) {
31 return Jsoup.clean(content, "", whitelist, outputSettings);
32 }
33}
34
35
2、重写请求参数处理函数,这是实现XSS过滤的关键,在其内重写了getParameter,getParameterValues,getHeader等方法,对http请求内的参数进行了过滤。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89 1package com.example.demo.core.filter;
2
3import org.apache.commons.lang3.StringUtils;
4
5import javax.servlet.http.HttpServletRequest;
6import javax.servlet.http.HttpServletRequestWrapper;
7
8/**
9 * 重写请求参数处理函数
10 */
11public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper {
12 HttpServletRequest orgRequest = null;
13
14 private boolean isIncludeRichText = false;
15
16 public XssHttpServletRequestWrapper(HttpServletRequest request, boolean isIncludeRichText) {
17 super(request);
18 orgRequest = request;
19 this.isIncludeRichText = isIncludeRichText;
20 }
21
22 /**
23 * 覆盖getParameter方法,将参数名和参数值都做xss过滤.
24 * 如果需要获得原始的值,则通过super.getParameterValues(name)来获取
25 * getParameterNames,getParameterValues和getParameterMap也可能需要覆盖
26 */
27 @Override
28 public String getParameter(String name) {
29 if (("content".equals(name) || name.endsWith("WithHtml")) && !isIncludeRichText) {
30 return super.getParameter(name);
31 }
32 name = XssFilterUtil.clean(name);
33 String value = super.getParameter(name);
34 if (StringUtils.isNotBlank(value)) {
35 value = XssFilterUtil.clean(value);
36 }
37 return value;
38 }
39
40 @Override
41 public String[] getParameterValues(String name) {
42 String[] arr = super.getParameterValues(name);
43 if (arr != null) {
44 for (int i = 0; i < arr.length; i++) {
45 arr[i] = XssFilterUtil.clean(arr[i]);
46 }
47 }
48 return arr;
49 }
50
51
52 /**
53 * 覆盖getHeader方法,将参数名和参数值都做xss过滤。<br/>
54 * 如果需要获得原始的值,则通过super.getHeaders(name)来获取<br/>
55 * getHeaderNames 也可能需要覆盖
56 */
57 @Override
58 public String getHeader(String name) {
59 name = XssFilterUtil.clean(name);
60 String value = super.getHeader(name);
61 if (StringUtils.isNotBlank(value)) {
62 value = XssFilterUtil.clean(value);
63 }
64 return value;
65 }
66
67 /**
68 * 获取最原始的request
69 *
70 * @return
71 */
72 public HttpServletRequest getOrgRequest() {
73 return orgRequest;
74 }
75
76 /**
77 * 获取最原始的request的静态方法
78 *
79 * @return
80 */
81 public static HttpServletRequest getOrgRequest(HttpServletRequest req) {
82 if (req instanceof XssHttpServletRequestWrapper) {
83 return ((XssHttpServletRequestWrapper) req).getOrgRequest();
84 }
85 return req;
86 }
87
88}
89
3、添加过滤XSS请求的入口,在这里通过XssHttpServletRequestWrapper将HttpServletRequest进行了封装,filterChain.doFilter(xssRequest, response);保证了后续代码执行request.getParameter,request.getParameterValues,request.getHeader时调用的都是XssHttpServletRequestWrapper内重写的方法,获取到的参数是已经进行过标签过滤的内容,从而消除了敏感信息。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76 1package com.example.demo.core.filter;
2
3
4import org.apache.commons.lang3.BooleanUtils;
5import org.apache.commons.lang3.StringUtils;
6
7import javax.servlet.*;
8import javax.servlet.http.HttpServletRequest;
9import javax.servlet.http.HttpServletResponse;
10import java.io.IOException;
11import java.util.ArrayList;
12import java.util.List;
13import java.util.regex.Matcher;
14import java.util.regex.Pattern;
15
16/**
17 * @author phubing
18 * @Description: 拦截防止xss注入 通过Jsoup过滤请求参数内的特定字符
19 * @date 2019/5/16 20:04
20 */
21public class XssFilter implements Filter {
22
23 //是否过滤富文本内容
24 private static boolean IS_INCLUDE_RICH_TEXT = true;
25
26 public List<String> excludes = new ArrayList<>();
27
28 @Override
29 public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
30 HttpServletRequest req = (HttpServletRequest) request;
31 HttpServletResponse resp = (HttpServletResponse) response;
32 if (handleExcludeURL(req, resp)) {
33 filterChain.doFilter(request, response);
34 return;
35 }
36 XssHttpServletRequestWrapper xssRequest = new XssHttpServletRequestWrapper((HttpServletRequest) request, IS_INCLUDE_RICH_TEXT);
37 filterChain.doFilter(xssRequest, response);
38 }
39
40 private boolean handleExcludeURL(HttpServletRequest request, HttpServletResponse response) {
41 if (excludes == null || excludes.isEmpty()) {
42 return false;
43 }
44 String url = request.getServletPath();
45 for (String pattern : excludes) {
46 Pattern p = Pattern.compile("^" + pattern);
47 Matcher m = p.matcher(url);
48 if (m.find()) {
49 return true;
50 }
51 }
52 return false;
53 }
54
55 @Override
56 public void init(FilterConfig filterConfig) throws ServletException {
57 String isIncludeRichText = filterConfig.getInitParameter("isIncludeRichText");
58 if (StringUtils.isNotBlank(isIncludeRichText)) {
59 IS_INCLUDE_RICH_TEXT = BooleanUtils.toBoolean(isIncludeRichText);
60 }
61 String temp = filterConfig.getInitParameter("excludes");
62 if (temp != null) {
63 String[] url = temp.split(",");
64 for (int i = 0; url != null && i < url.length; i++) {
65 excludes.add(url[i]);
66 }
67 }
68 }
69
70 @Override
71 public void destroy() {
72 }
73
74}
75
76
四:注册过滤器
创建core→configurer→XssFilterConfigurer
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38 1package com.example.demo.core.configurer;
2
3import com.example.demo.core.filter.XssFilter;
4import org.springframework.boot.web.servlet.FilterRegistrationBean;
5import org.springframework.context.annotation.Bean;
6import org.springframework.context.annotation.Configuration;
7
8import java.util.HashMap;
9import java.util.Map;
10
11/**
12 * @author phubing
13 * @Description:xss过滤拦截器配置文件
14 * @time 2019/5/16 20:47
15 */
16@Configuration
17public class XssFilterConfigurer {
18
19 /**
20 * xss过滤拦截器
21 */
22 @Bean
23 public FilterRegistrationBean xssFilterRegistrationBean() {
24 FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
25 filterRegistrationBean.setFilter(new XssFilter());
26 filterRegistrationBean.setOrder(Integer.MAX_VALUE-1);
27 filterRegistrationBean.setEnabled(true);
28 filterRegistrationBean.addUrlPatterns("/*");
29 Map<String, String> initParameters = new HashMap();
30 //excludes用于配置不需要参数过滤的请求url
31 initParameters.put("excludes", "/favicon.ico,/img/*,/js/*,/css/*");
32 //isIncludeRichText主要用于设置富文本内容是否需要过滤
33 initParameters.put("isIncludeRichText", "true");
34 filterRegistrationBean.setInitParameters(initParameters);
35 return filterRegistrationBean;
36 }
37}
38
五:测试
路径localhost:8080/userInfo/selectById
请求参数id=1<a href="http://www.baidu.com/a" onclick="alert("模拟XSS攻击");">sss</a><script>alert(0);</script>sss
结果:
我们可以看到<script></script>已经被过滤掉