当前位置:   article > 正文

详解Xss 及SpringBoot 防范Xss攻击(附全部代码)_springboot xss攻击

springboot xss攻击

简述Xss

一,什么是Xss 攻击

百度百科:

XSS攻击通常指的是通过利用网页开发时留下的漏洞,通过巧妙的方法注入恶意指令代码到网页,使用户加载并执行攻击者恶意制造的网页程序。这些恶意网页程序通常是JavaScript,但实际上也可以包括Java、 VBScriptActiveX、 Flash 或者甚至是普通的HTML。攻击成功后,攻击者可能得到包括但不限于更高的权限(如执行一些操作)、私密网页内容、会话和cookie等各种内容。

目前,XSS是黑客最常用来攻击互联网的技术之一,其对互联网安全的危害性在国际排名第二,它是利用Web站点,把病毒混入文本,意图蒙蔽计算机中信息安全系统的"眼睛",对原网站代码进行攻击,盗取人们的信息

通俗解释:

​ 这里举一个简单的例子,就是留言板。我们知道留言板通常的任务就是把用户留言的内容展示出来。正常情况下,用户的留言都是正常的语言文字,留言板显示的内容也就没毛病。然而这个时候如果有人不按套路出牌,在留言内容中丢进去一行

<script>alert(“hey!you are attacked”)</script>

那么留言板界面的网页代码就会变成形如以下:

  1. <html>
  2. <head>
  3. <title>留言板</title>
  4. </head>
  5. <body>
  6. <div id=”board”
  7. <script>alert(“hey!you are attacked”)</script>
  8. </div>
  9. </body>
  10. </html>

那么这个时候问题就来了,当浏览器解析到用户输入的代码那一行时会发生什么呢?答案很显然,浏览器并不知道这些代码改变了原本程序的意图,会照做弹出一个信息框。就像这样。

二,Xss的危害

​ 其实归根结底,XSS的攻击方式就是想办法“教唆”用户的浏览器去执行一些这个网页中原本不存在的前端代码。达到对网页的攻击。

​ 尽管一个信息框突然弹出来并不怎么友好,但也不至于会造成什么真实伤害啊。的确如此,但要说明的是,这里拿信息框说事仅仅是为了举个例子,真正的黑客攻击在XSS中除非恶作剧,不然是不会在恶意植入代码中写上alert(“say something”)的。

在真正的应用中,XSS攻击可以干的事情还有很多,这里举两个例子。

窃取网页浏览中的cookie值

在网页浏览中我们常常涉及到用户登录,登录完毕之后服务端会返回一个cookie值。这个cookie值相当于一个令牌,拿着这张令牌就等同于证明了你是某个用户。

如果你的cookie值被窃取,那么攻击者很可能能够直接利用你的这张令牌不用密码就登录你的账户。如果想要通过script脚本获得当前页面的cookie值,通常会用到document.cookie。

试想下如果像空间说说中能够写入xss攻击语句,那岂不是看了你说说的人的号你都可以登录(不过某些厂商的cookie有其他验证措施如:Http-Only保证同一cookie不能被滥用)

劫持流量实现恶意跳转

这个很简单,就是在网页中想办法插入一句像这样的语句:

<script>window.location.href="http://www.baidu.com";</script>

那么所访问的网站就会被跳转到百度的首页。

Xss攻击方式

  • 大小写绕过

例如:

这个绕过方式的出现是因为网站仅仅只过滤了标签(Script),而没有考虑标签中的大小写并不影响浏览器的解释所致。具体的方式就像这样:

http://192.168.1.102/xss/example2.php?name=<sCript>alert("hey!")</scRipt>
  • 利用过滤后返回语句再次构成攻击语句来绕过
  • 并不是只有script标签才可以插入代码

我们利用如下方式:

[http://192.168.1.102/xss/example4.php?name=
src='w.123' οnerrοr='alert("hey!")'>

就可以再次愉快的弹窗。原因很简单,我们指定的图片地址根本不存在也就是一定会发生错误,这时候onerror里面的代码自然就得到了执行。

以下列举几个常用的可插入代码的标签。

<a onmousemove=’do something here’> 

当用户鼠标移动时即可运行代码

<div onmouseover=‘do something here’> 

当用户鼠标在这个块上面时即可运行(可以配合weight等参数将div覆盖页面,鼠标不划过都不行)

  • 编码脚本代码绕过关键字过滤

有的时候,服务器往往会对代码中的关键字(如alert)进行过滤,这个时候我们可以尝试将关键字进行编码后再插入,不过直接显示编码是不能被浏览器执行的,我们可以用另一个语句eval()来实现。eval()会将编码过的语句解码后再执行,简直太贴心了。

例如alert(1)编码过后就是

\u0061\u006c\u0065\u0072\u0074(1)

所以构建出来的攻击语句如下:

http://192.168.1.102/xss/example5.php?name=eval(\u0061\u006c\u0065\u0072\u0074(1))

  • 主动闭合标签实现注入代码
  • 组合各种方式

Xss 的防范手段

  • 首先是过滤。对诸如(script、img、a)等标签进行过滤。
  • 其次是编码。像一些常见的符号,如<>在输入的时候要对其进行转换编码,这样做浏览器是不会对该标签进行解释执行的,同时也不影响显示效果。
  • 最后是限制。通过以上的案例我们不难发现xss攻击要能达成往往需要较长的字符串,因此对于一些可以预期的输入可以通过限制长度强制截断来进行防御。

Spring Boot 防 Xss 代码攻击

从上面可以知道,Xss 攻击是对入参或者说输出进行修改,劫持内容达到目的。因此我们需要对整个系统的提交进行过滤和转义。

spring boot 防范 XSS 攻击可以使用过滤器,对内容进行转义,过滤。

这里就采用Spring boot+Filter的方式实现一个Xss的全局过滤器

Spring boot实现一个Xss过滤器, 常用的有两种方式:

第一种

  • 自定义过滤器
  • 重写HttpServletRequestWrapper、重写getHeader()、getParameter()、getParameterValues()、getInputStream()实现对传统“键值对”传参方式的过滤
  • 重写getInputStream()实现对Json方式传参的过滤,也就是@RequestBody参数

第二种

  • 自定义序列化器, 对MappingJackson2HttpMessageConverter 的objectMapper做设置.
    重写JsonSerializer.serialize()实现对出参的过滤 (PS: 数据原样保存, 取出来的时候转义)
    重写JsonDeserializer.deserialize()实现对入参的过滤 (PS: 数据转义后保存)

防 XSS 攻击流程图

代码编写流程图:

自定义过滤器

  1. public class XssFilter implements Filter
  2. {
  3. /**
  4. * 排除链接
  5. */
  6. public List<String> excludes = new ArrayList<>();
  7. @Override
  8. public void init(FilterConfig filterConfig) throws ServletException
  9. {
  10. String tempExcludes = filterConfig.getInitParameter("excludes");
  11. if (StringUtils.isNotEmpty(tempExcludes))
  12. {
  13. String[] url = tempExcludes.split(",");
  14. for (int i = 0; url != null && i < url.length; i++)
  15. {
  16. excludes.add(url[i]);
  17. }
  18. }
  19. }
  20. @Override
  21. public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
  22. throws IOException, ServletException
  23. {
  24. HttpServletRequest req = (HttpServletRequest) request;
  25. HttpServletResponse resp = (HttpServletResponse) response;
  26. if (handleExcludeURL(req, resp))
  27. {
  28. // 传递过滤器
  29. chain.doFilter(request, response);
  30. return;
  31. }
  32. XssHttpServletRequestWrapper xssRequest = new XssHttpServletRequestWrapper((HttpServletRequest) request);
  33. chain.doFilter(xssRequest, response);
  34. }
  35. private boolean handleExcludeURL(HttpServletRequest request, HttpServletResponse response)
  36. {
  37. String url = request.getServletPath();
  38. String method = request.getMethod();
  39. // GET DELETE 不过滤
  40. if (method == null || HttpMethod.GET.matches(method) || HttpMethod.DELETE.matches(method))
  41. {
  42. return true;
  43. }
  44. return StringUtils.matches(url, excludes);
  45. }
  46. @Override
  47. public void destroy()
  48. {
  49. }
  50. }

上面自定义过滤器需要到的StringUtils 工具类

  1. /**
  2. * 查找指定字符串是否匹配指定字符串列表中的任意一个字符串
  3. *
  4. * @param str 指定字符串
  5. * @param strs 需要检查的字符串数组
  6. * @return 是否匹配
  7. */
  8. public static boolean matches(String str, List<String> strs)
  9. {
  10. if (isEmpty(str) || isEmpty(strs))
  11. {
  12. return false;
  13. }
  14. for (String pattern : strs)
  15. {
  16. if (isMatch(pattern, str))
  17. {
  18. return true;
  19. }
  20. }
  21. return false;
  22. }
  23. /**
  24. * 判断url是否与规则配置:
  25. * ? 表示单个字符;
  26. * * 表示一层路径内的任意字符串,不可跨层级;
  27. * ** 表示任意层路径;
  28. *
  29. * @param pattern 匹配规则
  30. * @param url 需要匹配的url
  31. * @return
  32. */
  33. public static boolean isMatch(String pattern, String url)
  34. {
  35. AntPathMatcher matcher = new AntPathMatcher();
  36. return matcher.match(pattern, url);
  37. }

Xss 过滤处理

  1. /**
  2. * XSS过滤处理
  3. *
  4. * @author lh
  5. */
  6. public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper
  7. {
  8. /**
  9. * @param request
  10. */
  11. public XssHttpServletRequestWrapper(HttpServletRequest request)
  12. {
  13. super(request);
  14. }
  15. // 重写获取参数进行转义
  16. @Override
  17. public String[] getParameterValues(String name)
  18. {
  19. String[] values = super.getParameterValues(name);
  20. if (values != null)
  21. {
  22. int length = values.length;
  23. String[] escapesValues = new String[length];
  24. for (int i = 0; i < length; i++)
  25. {
  26. // 防xss攻击和过滤前后空格
  27. escapesValues[i] = EscapeUtil.clean(values[i]).trim();
  28. }
  29. return escapesValues;
  30. }
  31. return super.getParameterValues(name);
  32. }
  33. @Override
  34. public ServletInputStream getInputStream() throws IOException
  35. {
  36. // 非json类型,直接返回
  37. if (!isJsonRequest())
  38. {
  39. return super.getInputStream();
  40. }
  41. // 为空,直接返回
  42. String json = IOUtils.toString(super.getInputStream(), "utf-8");
  43. if (StringUtils.isEmpty(json))
  44. {
  45. return super.getInputStream();
  46. }
  47. // xss过滤
  48. json = EscapeUtil.clean(json).trim();
  49. byte[] jsonBytes = json.getBytes("utf-8");
  50. final ByteArrayInputStream bis = new ByteArrayInputStream(jsonBytes);
  51. return new ServletInputStream()
  52. {
  53. @Override
  54. public boolean isFinished()
  55. {
  56. return true;
  57. }
  58. @Override
  59. public boolean isReady()
  60. {
  61. return true;
  62. }
  63. @Override
  64. public int available() throws IOException
  65. {
  66. return jsonBytes.length;
  67. }
  68. @Override
  69. public void setReadListener(ReadListener readListener)
  70. {
  71. }
  72. @Override
  73. public int read() throws IOException
  74. {
  75. return bis.read();
  76. }
  77. };
  78. }
  79. /**
  80. * 是否是Json请求
  81. *
  82. * @param request
  83. */
  84. public boolean isJsonRequest()
  85. {
  86. String header = super.getHeader(HttpHeaders.CONTENT_TYPE);
  87. return StringUtils.startsWithIgnoreCase(header, MediaType.APPLICATION_JSON_VALUE);
  88. }
  89. }

转义Html字符

Clean 方法

  1. public static String clean(String content)
  2. {
  3. return new HTMLFilter().filter(content);
  4. }

HTML 过滤器

  1. /**
  2. * HTML过滤器,用于去除XSS漏洞隐患。
  3. *
  4. * @author lh
  5. */
  6. public final class HTMLFilter
  7. {
  8. /**
  9. * regex flag union representing /si modifiers in php
  10. **/
  11. private static final int REGEX_FLAGS_SI = Pattern.CASE_INSENSITIVE | Pattern.DOTALL;
  12. private static final Pattern P_COMMENTS = Pattern.compile("<!--(.*?)-->", Pattern.DOTALL);
  13. private static final Pattern P_COMMENT = Pattern.compile("^!--(.*)--$", REGEX_FLAGS_SI);
  14. private static final Pattern P_TAGS = Pattern.compile("<(.*?)>", Pattern.DOTALL);
  15. private static final Pattern P_END_TAG = Pattern.compile("^/([a-z0-9]+)", REGEX_FLAGS_SI);
  16. private static final Pattern P_START_TAG = Pattern.compile("^([a-z0-9]+)(.*?)(/?)$", REGEX_FLAGS_SI);
  17. private static final Pattern P_QUOTED_ATTRIBUTES = Pattern.compile("([a-z0-9]+)=([\"'])(.*?)\\2", REGEX_FLAGS_SI);
  18. private static final Pattern P_UNQUOTED_ATTRIBUTES = Pattern.compile("([a-z0-9]+)(=)([^\"\\s']+)", REGEX_FLAGS_SI);
  19. private static final Pattern P_PROTOCOL = Pattern.compile("^([^:]+):", REGEX_FLAGS_SI);
  20. private static final Pattern P_ENTITY = Pattern.compile("&#(\\d+);?");
  21. private static final Pattern P_ENTITY_UNICODE = Pattern.compile("&#x([0-9a-f]+);?");
  22. private static final Pattern P_ENCODE = Pattern.compile("%([0-9a-f]{2});?");
  23. private static final Pattern P_VALID_ENTITIES = Pattern.compile("&([^&;]*)(?=(;|&|$))");
  24. private static final Pattern P_VALID_QUOTES = Pattern.compile("(>|^)([^<]+?)(<|$)", Pattern.DOTALL);
  25. private static final Pattern P_END_ARROW = Pattern.compile("^>");
  26. private static final Pattern P_BODY_TO_END = Pattern.compile("<([^>]*?)(?=<|$)");
  27. private static final Pattern P_XML_CONTENT = Pattern.compile("(^|>)([^<]*?)(?=>)");
  28. private static final Pattern P_STRAY_LEFT_ARROW = Pattern.compile("<([^>]*?)(?=<|$)");
  29. private static final Pattern P_STRAY_RIGHT_ARROW = Pattern.compile("(^|>)([^<]*?)(?=>)");
  30. private static final Pattern P_AMP = Pattern.compile("&");
  31. private static final Pattern P_QUOTE = Pattern.compile("\"");
  32. private static final Pattern P_LEFT_ARROW = Pattern.compile("<");
  33. private static final Pattern P_RIGHT_ARROW = Pattern.compile(">");
  34. private static final Pattern P_BOTH_ARROWS = Pattern.compile("<>");
  35. // @xxx could grow large... maybe use sesat's ReferenceMap
  36. private static final ConcurrentMap<String, Pattern> P_REMOVE_PAIR_BLANKS = new ConcurrentHashMap<>();
  37. private static final ConcurrentMap<String, Pattern> P_REMOVE_SELF_BLANKS = new ConcurrentHashMap<>();
  38. /**
  39. * set of allowed html elements, along with allowed attributes for each element
  40. **/
  41. private final Map<String, List<String>> vAllowed;
  42. /**
  43. * counts of open tags for each (allowable) html element
  44. **/
  45. private final Map<String, Integer> vTagCounts = new HashMap<>();
  46. /**
  47. * html elements which must always be self-closing (e.g. "<img />")
  48. **/
  49. private final String[] vSelfClosingTags;
  50. /**
  51. * html elements which must always have separate opening and closing tags (e.g. "<b></b>")
  52. **/
  53. private final String[] vNeedClosingTags;
  54. /**
  55. * set of disallowed html elements
  56. **/
  57. private final String[] vDisallowed;
  58. /**
  59. * attributes which should be checked for valid protocols
  60. **/
  61. private final String[] vProtocolAtts;
  62. /**
  63. * allowed protocols
  64. **/
  65. private final String[] vAllowedProtocols;
  66. /**
  67. * tags which should be removed if they contain no content (e.g. "<b></b>" or "<b />")
  68. **/
  69. private final String[] vRemoveBlanks;
  70. /**
  71. * entities allowed within html markup
  72. **/
  73. private final String[] vAllowedEntities;
  74. /**
  75. * flag determining whether comments are allowed in input String.
  76. */
  77. private final boolean stripComment;
  78. private final boolean encodeQuotes;
  79. /**
  80. * flag determining whether to try to make tags when presented with "unbalanced" angle brackets (e.g. "<b text </b>"
  81. * becomes "<b> text </b>"). If set to false, unbalanced angle brackets will be html escaped.
  82. */
  83. private final boolean alwaysMakeTags;
  84. /**
  85. * Default constructor.
  86. */
  87. public HTMLFilter()
  88. {
  89. vAllowed = new HashMap<>();
  90. final ArrayList<String> a_atts = new ArrayList<>();
  91. a_atts.add("href");
  92. a_atts.add("target");
  93. vAllowed.put("a", a_atts);
  94. final ArrayList<String> img_atts = new ArrayList<>();
  95. img_atts.add("src");
  96. img_atts.add("width");
  97. img_atts.add("height");
  98. img_atts.add("alt");
  99. vAllowed.put("img", img_atts);
  100. final ArrayList<String> no_atts = new ArrayList<>();
  101. vAllowed.put("b", no_atts);
  102. vAllowed.put("strong", no_atts);
  103. vAllowed.put("i", no_atts);
  104. vAllowed.put("em", no_atts);
  105. vSelfClosingTags = new String[] { "img" };
  106. vNeedClosingTags = new String[] { "a", "b", "strong", "i", "em" };
  107. vDisallowed = new String[] {};
  108. vAllowedProtocols = new String[] { "http", "mailto", "https" }; // no ftp.
  109. vProtocolAtts = new String[] { "src", "href" };
  110. vRemoveBlanks = new String[] { "a", "b", "strong", "i", "em" };
  111. vAllowedEntities = new String[] { "amp", "gt", "lt", "quot" };
  112. stripComment = true;
  113. encodeQuotes = true;
  114. alwaysMakeTags = false;
  115. }
  116. /**
  117. * Map-parameter configurable constructor.
  118. *
  119. * @param conf map containing configuration. keys match field names.
  120. */
  121. @SuppressWarnings("unchecked")
  122. public HTMLFilter(final Map<String, Object> conf)
  123. {
  124. assert conf.containsKey("vAllowed") : "configuration requires vAllowed";
  125. assert conf.containsKey("vSelfClosingTags") : "configuration requires vSelfClosingTags";
  126. assert conf.containsKey("vNeedClosingTags") : "configuration requires vNeedClosingTags";
  127. assert conf.containsKey("vDisallowed") : "configuration requires vDisallowed";
  128. assert conf.containsKey("vAllowedProtocols") : "configuration requires vAllowedProtocols";
  129. assert conf.containsKey("vProtocolAtts") : "configuration requires vProtocolAtts";
  130. assert conf.containsKey("vRemoveBlanks") : "configuration requires vRemoveBlanks";
  131. assert conf.containsKey("vAllowedEntities") : "configuration requires vAllowedEntities";
  132. vAllowed = Collections.unmodifiableMap((HashMap<String, List<String>>) conf.get("vAllowed"));
  133. vSelfClosingTags = (String[]) conf.get("vSelfClosingTags");
  134. vNeedClosingTags = (String[]) conf.get("vNeedClosingTags");
  135. vDisallowed = (String[]) conf.get("vDisallowed");
  136. vAllowedProtocols = (String[]) conf.get("vAllowedProtocols");
  137. vProtocolAtts = (String[]) conf.get("vProtocolAtts");
  138. vRemoveBlanks = (String[]) conf.get("vRemoveBlanks");
  139. vAllowedEntities = (String[]) conf.get("vAllowedEntities");
  140. stripComment = conf.containsKey("stripComment") ? (Boolean) conf.get("stripComment") : true;
  141. encodeQuotes = conf.containsKey("encodeQuotes") ? (Boolean) conf.get("encodeQuotes") : true;
  142. alwaysMakeTags = conf.containsKey("alwaysMakeTags") ? (Boolean) conf.get("alwaysMakeTags") : true;
  143. }
  144. private void reset()
  145. {
  146. vTagCounts.clear();
  147. }
  148. // ---------------------------------------------------------------
  149. // my versions of some PHP library functions
  150. public static String chr(final int decimal)
  151. {
  152. return String.valueOf((char) decimal);
  153. }
  154. public static String htmlSpecialChars(final String s)
  155. {
  156. String result = s;
  157. result = regexReplace(P_AMP, "&amp;", result);
  158. result = regexReplace(P_QUOTE, "&quot;", result);
  159. result = regexReplace(P_LEFT_ARROW, "&lt;", result);
  160. result = regexReplace(P_RIGHT_ARROW, "&gt;", result);
  161. return result;
  162. }
  163. // ---------------------------------------------------------------
  164. /**
  165. * given a user submitted input String, filter out any invalid or restricted html.
  166. *
  167. * @param input text (i.e. submitted by a user) than may contain html
  168. * @return "clean" version of input, with only valid, whitelisted html elements allowed
  169. */
  170. public String filter(final String input)
  171. {
  172. reset();
  173. String s = input;
  174. s = escapeComments(s);
  175. s = balanceHTML(s);
  176. s = checkTags(s);
  177. s = processRemoveBlanks(s);
  178. // s = validateEntities(s);
  179. return s;
  180. }
  181. public boolean isAlwaysMakeTags()
  182. {
  183. return alwaysMakeTags;
  184. }
  185. public boolean isStripComments()
  186. {
  187. return stripComment;
  188. }
  189. private String escapeComments(final String s)
  190. {
  191. final Matcher m = P_COMMENTS.matcher(s);
  192. final StringBuffer buf = new StringBuffer();
  193. if (m.find())
  194. {
  195. final String match = m.group(1); // (.*?)
  196. m.appendReplacement(buf, Matcher.quoteReplacement("<!--" + htmlSpecialChars(match) + "-->"));
  197. }
  198. m.appendTail(buf);
  199. return buf.toString();
  200. }
  201. private String balanceHTML(String s)
  202. {
  203. if (alwaysMakeTags)
  204. {
  205. //
  206. // try and form html
  207. //
  208. s = regexReplace(P_END_ARROW, "", s);
  209. // 不追加结束标签
  210. s = regexReplace(P_BODY_TO_END, "<$1>", s);
  211. s = regexReplace(P_XML_CONTENT, "$1<$2", s);
  212. }
  213. else
  214. {
  215. //
  216. // escape stray brackets
  217. //
  218. s = regexReplace(P_STRAY_LEFT_ARROW, "&lt;$1", s);
  219. s = regexReplace(P_STRAY_RIGHT_ARROW, "$1$2&gt;<", s);
  220. //
  221. // the last regexp causes '<>' entities to appear
  222. // (we need to do a lookahead assertion so that the last bracket can
  223. // be used in the next pass of the regexp)
  224. //
  225. s = regexReplace(P_BOTH_ARROWS, "", s);
  226. }
  227. return s;
  228. }
  229. private String checkTags(String s)
  230. {
  231. Matcher m = P_TAGS.matcher(s);
  232. final StringBuffer buf = new StringBuffer();
  233. while (m.find())
  234. {
  235. String replaceStr = m.group(1);
  236. replaceStr = processTag(replaceStr);
  237. m.appendReplacement(buf, Matcher.quoteReplacement(replaceStr));
  238. }
  239. m.appendTail(buf);
  240. // these get tallied in processTag
  241. // (remember to reset before subsequent calls to filter method)
  242. final StringBuilder sBuilder = new StringBuilder(buf.toString());
  243. for (String key : vTagCounts.keySet())
  244. {
  245. for (int ii = 0; ii < vTagCounts.get(key); ii++)
  246. {
  247. sBuilder.append("</").append(key).append(">");
  248. }
  249. }
  250. s = sBuilder.toString();
  251. return s;
  252. }
  253. private String processRemoveBlanks(final String s)
  254. {
  255. String result = s;
  256. for (String tag : vRemoveBlanks)
  257. {
  258. if (!P_REMOVE_PAIR_BLANKS.containsKey(tag))
  259. {
  260. P_REMOVE_PAIR_BLANKS.putIfAbsent(tag, Pattern.compile("<" + tag + "(\\s[^>]*)?></" + tag + ">"));
  261. }
  262. result = regexReplace(P_REMOVE_PAIR_BLANKS.get(tag), "", result);
  263. if (!P_REMOVE_SELF_BLANKS.containsKey(tag))
  264. {
  265. P_REMOVE_SELF_BLANKS.putIfAbsent(tag, Pattern.compile("<" + tag + "(\\s[^>]*)?/>"));
  266. }
  267. result = regexReplace(P_REMOVE_SELF_BLANKS.get(tag), "", result);
  268. }
  269. return result;
  270. }
  271. private static String regexReplace(final Pattern regex_pattern, final String replacement, final String s)
  272. {
  273. Matcher m = regex_pattern.matcher(s);
  274. return m.replaceAll(replacement);
  275. }
  276. private String processTag(final String s)
  277. {
  278. // ending tags
  279. Matcher m = P_END_TAG.matcher(s);
  280. if (m.find())
  281. {
  282. final String name = m.group(1).toLowerCase();
  283. if (allowed(name))
  284. {
  285. if (!inArray(name, vSelfClosingTags))
  286. {
  287. if (vTagCounts.containsKey(name))
  288. {
  289. vTagCounts.put(name, vTagCounts.get(name) - 1);
  290. return "</" + name + ">";
  291. }
  292. }
  293. }
  294. }
  295. // starting tags
  296. m = P_START_TAG.matcher(s);
  297. if (m.find())
  298. {
  299. final String name = m.group(1).toLowerCase();
  300. final String body = m.group(2);
  301. String ending = m.group(3);
  302. // debug( "in a starting tag, name='" + name + "'; body='" + body + "'; ending='" + ending + "'" );
  303. if (allowed(name))
  304. {
  305. final StringBuilder params = new StringBuilder();
  306. final Matcher m2 = P_QUOTED_ATTRIBUTES.matcher(body);
  307. final Matcher m3 = P_UNQUOTED_ATTRIBUTES.matcher(body);
  308. final List<String> paramNames = new ArrayList<>();
  309. final List<String> paramValues = new ArrayList<>();
  310. while (m2.find())
  311. {
  312. paramNames.add(m2.group(1)); // ([a-z0-9]+)
  313. paramValues.add(m2.group(3)); // (.*?)
  314. }
  315. while (m3.find())
  316. {
  317. paramNames.add(m3.group(1)); // ([a-z0-9]+)
  318. paramValues.add(m3.group(3)); // ([^\"\\s']+)
  319. }
  320. String paramName, paramValue;
  321. for (int ii = 0; ii < paramNames.size(); ii++)
  322. {
  323. paramName = paramNames.get(ii).toLowerCase();
  324. paramValue = paramValues.get(ii);
  325. // debug( "paramName='" + paramName + "'" );
  326. // debug( "paramValue='" + paramValue + "'" );
  327. // debug( "allowed? " + vAllowed.get( name ).contains( paramName ) );
  328. if (allowedAttribute(name, paramName))
  329. {
  330. if (inArray(paramName, vProtocolAtts))
  331. {
  332. paramValue = processParamProtocol(paramValue);
  333. }
  334. params.append(' ').append(paramName).append("=\\\"").append(paramValue).append("\\\"");
  335. }
  336. }
  337. if (inArray(name, vSelfClosingTags))
  338. {
  339. ending = " /";
  340. }
  341. if (inArray(name, vNeedClosingTags))
  342. {
  343. ending = "";
  344. }
  345. if (ending == null || ending.length() < 1)
  346. {
  347. if (vTagCounts.containsKey(name))
  348. {
  349. vTagCounts.put(name, vTagCounts.get(name) + 1);
  350. }
  351. else
  352. {
  353. vTagCounts.put(name, 1);
  354. }
  355. }
  356. else
  357. {
  358. ending = " /";
  359. }
  360. return "<" + name + params + ending + ">";
  361. }
  362. else
  363. {
  364. return "";
  365. }
  366. }
  367. // comments
  368. m = P_COMMENT.matcher(s);
  369. if (!stripComment && m.find())
  370. {
  371. return "<" + m.group() + ">";
  372. }
  373. return "";
  374. }
  375. private String processParamProtocol(String s)
  376. {
  377. s = decodeEntities(s);
  378. final Matcher m = P_PROTOCOL.matcher(s);
  379. if (m.find())
  380. {
  381. final String protocol = m.group(1);
  382. if (!inArray(protocol, vAllowedProtocols))
  383. {
  384. // bad protocol, turn into local anchor link instead
  385. s = "#" + s.substring(protocol.length() + 1);
  386. if (s.startsWith("#//"))
  387. {
  388. s = "#" + s.substring(3);
  389. }
  390. }
  391. }
  392. return s;
  393. }
  394. private String decodeEntities(String s)
  395. {
  396. StringBuffer buf = new StringBuffer();
  397. Matcher m = P_ENTITY.matcher(s);
  398. while (m.find())
  399. {
  400. final String match = m.group(1);
  401. final int decimal = Integer.decode(match).intValue();
  402. m.appendReplacement(buf, Matcher.quoteReplacement(chr(decimal)));
  403. }
  404. m.appendTail(buf);
  405. s = buf.toString();
  406. buf = new StringBuffer();
  407. m = P_ENTITY_UNICODE.matcher(s);
  408. while (m.find())
  409. {
  410. final String match = m.group(1);
  411. final int decimal = Integer.valueOf(match, 16).intValue();
  412. m.appendReplacement(buf, Matcher.quoteReplacement(chr(decimal)));
  413. }
  414. m.appendTail(buf);
  415. s = buf.toString();
  416. buf = new StringBuffer();
  417. m = P_ENCODE.matcher(s);
  418. while (m.find())
  419. {
  420. final String match = m.group(1);
  421. final int decimal = Integer.valueOf(match, 16).intValue();
  422. m.appendReplacement(buf, Matcher.quoteReplacement(chr(decimal)));
  423. }
  424. m.appendTail(buf);
  425. s = buf.toString();
  426. s = validateEntities(s);
  427. return s;
  428. }
  429. private String validateEntities(final String s)
  430. {
  431. StringBuffer buf = new StringBuffer();
  432. // validate entities throughout the string
  433. Matcher m = P_VALID_ENTITIES.matcher(s);
  434. while (m.find())
  435. {
  436. final String one = m.group(1); // ([^&;]*)
  437. final String two = m.group(2); // (?=(;|&|$))
  438. m.appendReplacement(buf, Matcher.quoteReplacement(checkEntity(one, two)));
  439. }
  440. m.appendTail(buf);
  441. return encodeQuotes(buf.toString());
  442. }
  443. private String encodeQuotes(final String s)
  444. {
  445. if (encodeQuotes)
  446. {
  447. StringBuffer buf = new StringBuffer();
  448. Matcher m = P_VALID_QUOTES.matcher(s);
  449. while (m.find())
  450. {
  451. final String one = m.group(1); // (>|^)
  452. final String two = m.group(2); // ([^<]+?)
  453. final String three = m.group(3); // (<|$)
  454. // 不替换双引号为&quot;,防止json格式无效 regexReplace(P_QUOTE, "&quot;", two)
  455. m.appendReplacement(buf, Matcher.quoteReplacement(one + two + three));
  456. }
  457. m.appendTail(buf);
  458. return buf.toString();
  459. }
  460. else
  461. {
  462. return s;
  463. }
  464. }
  465. private String checkEntity(final String preamble, final String term)
  466. {
  467. return ";".equals(term) && isValidEntity(preamble) ? '&' + preamble : "&amp;" + preamble;
  468. }
  469. private boolean isValidEntity(final String entity)
  470. {
  471. return inArray(entity, vAllowedEntities);
  472. }
  473. private static boolean inArray(final String s, final String[] array)
  474. {
  475. for (String item : array)
  476. {
  477. if (item != null && item.equals(s))
  478. {
  479. return true;
  480. }
  481. }
  482. return false;
  483. }
  484. private boolean allowed(final String name)
  485. {
  486. return (vAllowed.isEmpty() || vAllowed.containsKey(name)) && !inArray(name, vDisallowed);
  487. }
  488. private boolean allowedAttribute(final String name, final String paramName)
  489. {
  490. return allowed(name) && (vAllowed.isEmpty() || vAllowed.get(name).contains(paramName));
  491. }
  492. }

注册配置过滤器bean

注册bean

  1. @Configuration
  2. public class FilterConfig
  3. {
  4. @Value("${xss.excludes}")
  5. private String excludes;
  6. @Value("${xss.urlPatterns}")
  7. private String urlPatterns;
  8. @SuppressWarnings({ "rawtypes", "unchecked" })
  9. @Bean
  10. @ConditionalOnProperty(value = "xss.enabled", havingValue = "true")
  11. public FilterRegistrationBean xssFilterRegistration()
  12. {
  13. FilterRegistrationBean registration = new FilterRegistrationBean();
  14. registration.setDispatcherTypes(DispatcherType.REQUEST);
  15. registration.setFilter(new XssFilter());
  16. //添加过滤路径
  17. registration.addUrlPatterns(StringUtils.split(urlPatterns, ","));
  18. registration.setName("xssFilter");
  19. registration.setOrder(FilterRegistrationBean.HIGHEST_PRECEDENCE);
  20. //设置初始化参数
  21. Map<String, String> initParameters = new HashMap<String, String>();
  22. initParameters.put("excludes", excludes);
  23. registration.setInitParameters(initParameters);
  24. return registration;
  25. }
  26. @SuppressWarnings({ "rawtypes", "unchecked" })
  27. @Bean
  28. public FilterRegistrationBean someFilterRegistration()
  29. {
  30. FilterRegistrationBean registration = new FilterRegistrationBean();
  31. registration.setFilter(new RepeatableFilter());
  32. registration.addUrlPatterns("/*");
  33. registration.setName("repeatableFilter");
  34. registration.setOrder(FilterRegistrationBean.LOWEST_PRECEDENCE);
  35. return registration;
  36. }
  37. }

文件配置:

  1. # 防止XSS攻击
  2. xss:
  3. # 过滤开关
  4. enabled: true
  5. # 排除链接(多个用逗号分隔)
  6. excludes: /system/notice
  7. # 匹配链接
  8. urlPatterns: /system/*,/monitor/*,/tool/*

这个时候就可以了,我们就可以进行测试了

转义和反转义工具

  1. /**
  2. * 转义和反转义工具类
  3. *
  4. * @author lh
  5. */
  6. public class EscapeUtil
  7. {
  8. public static final String RE_HTML_MARK = "(<[^<]*?>)|(<[\\s]*?/[^<]*?>)|(<[^<]*?/[\\s]*?>)";
  9. private static final char[][] TEXT = new char[64][];
  10. static
  11. {
  12. for (int i = 0; i < 64; i++)
  13. {
  14. TEXT[i] = new char[] { (char) i };
  15. }
  16. // special HTML characters
  17. TEXT['\''] = "&#039;".toCharArray(); // 单引号
  18. TEXT['"'] = "&#34;".toCharArray(); // 双引号
  19. TEXT['&'] = "&#38;".toCharArray(); // &符
  20. TEXT['<'] = "&#60;".toCharArray(); // 小于号
  21. TEXT['>'] = "&#62;".toCharArray(); // 大于号
  22. }
  23. /**
  24. * 转义文本中的HTML字符为安全的字符
  25. *
  26. * @param text 被转义的文本
  27. * @return 转义后的文本
  28. */
  29. public static String escape(String text)
  30. {
  31. return encode(text);
  32. }
  33. /**
  34. * 还原被转义的HTML特殊字符
  35. *
  36. * @param content 包含转义符的HTML内容
  37. * @return 转换后的字符串
  38. */
  39. public static String unescape(String content)
  40. {
  41. return decode(content);
  42. }
  43. /**
  44. * 清除所有HTML标签,但是不删除标签内的内容
  45. *
  46. * @param content 文本
  47. * @return 清除标签后的文本
  48. */
  49. public static String clean(String content)
  50. {
  51. return new HTMLFilter().filter(content);
  52. }
  53. /**
  54. * Escape编码
  55. *
  56. * @param text 被编码的文本
  57. * @return 编码后的字符
  58. */
  59. private static String encode(String text)
  60. {
  61. if (StringUtils.isEmpty(text))
  62. {
  63. return StringUtils.EMPTY;
  64. }
  65. final StringBuilder tmp = new StringBuilder(text.length() * 6);
  66. char c;
  67. for (int i = 0; i < text.length(); i++)
  68. {
  69. c = text.charAt(i);
  70. if (c < 256)
  71. {
  72. tmp.append("%");
  73. if (c < 16)
  74. {
  75. tmp.append("0");
  76. }
  77. tmp.append(Integer.toString(c, 16));
  78. }
  79. else
  80. {
  81. tmp.append("%u");
  82. if (c <= 0xfff)
  83. {
  84. // issue#I49JU8@Gitee
  85. tmp.append("0");
  86. }
  87. tmp.append(Integer.toString(c, 16));
  88. }
  89. }
  90. return tmp.toString();
  91. }
  92. /**
  93. * Escape解码
  94. *
  95. * @param content 被转义的内容
  96. * @return 解码后的字符串
  97. */
  98. public static String decode(String content)
  99. {
  100. if (StringUtils.isEmpty(content))
  101. {
  102. return content;
  103. }
  104. StringBuilder tmp = new StringBuilder(content.length());
  105. int lastPos = 0, pos = 0;
  106. char ch;
  107. while (lastPos < content.length())
  108. {
  109. pos = content.indexOf("%", lastPos);
  110. if (pos == lastPos)
  111. {
  112. if (content.charAt(pos + 1) == 'u')
  113. {
  114. ch = (char) Integer.parseInt(content.substring(pos + 2, pos + 6), 16);
  115. tmp.append(ch);
  116. lastPos = pos + 6;
  117. }
  118. else
  119. {
  120. ch = (char) Integer.parseInt(content.substring(pos + 1, pos + 3), 16);
  121. tmp.append(ch);
  122. lastPos = pos + 3;
  123. }
  124. }
  125. else
  126. {
  127. if (pos == -1)
  128. {
  129. tmp.append(content.substring(lastPos));
  130. lastPos = content.length();
  131. }
  132. else
  133. {
  134. tmp.append(content.substring(lastPos, pos));
  135. lastPos = pos;
  136. }
  137. }
  138. }
  139. return tmp.toString();
  140. }
  141. public static void main(String[] args)
  142. {
  143. String html = "<script>alert(1);</script>";
  144. String escape = EscapeUtil.escape(html);
  145. // String html = "<scr<script>ipt>alert(\"XSS\")</scr<script>ipt>";
  146. // String html = "<123";
  147. // String html = "123>";
  148. System.out.println("clean: " + EscapeUtil.clean(html));
  149. System.out.println("escape: " + escape);
  150. System.out.println("unescape: " + EscapeUtil.unescape(escape));
  151. }

测试类

Controller 测试类

  1. @Slf4j
  2. @RestController
  3. public class XssController {
  4. //键值对
  5. @PostMapping("xssFilter")
  6. public String xssFilter(String name, String info) {
  7. log.error(name + "---" + info);
  8. return name + "---" + info;
  9. }
  10. //实体
  11. @PostMapping("modelXssFilter")
  12. public People modelXssFilter(@RequestBody UserEntity user) {
  13. log.error(user.getUserName() + "---" + user.getMobile());
  14. return user;
  15. }
  16. //不转义
  17. @PostMapping("open/xssFilter")
  18. public String openXssFilter(String name) {
  19. return name;
  20. }
  21. //不转义2
  22. @PostMapping("open2/xssFilter")
  23. public String open2XssFilter(String name) {
  24. return name;
  25. }
  26. // 这里最好单独建立实体,这里这里只是演示
  27. @ApiModel(value = "UserEntity", description = "用户实体")
  28. class UserEntity
  29. {
  30. @ApiModelProperty("用户ID")
  31. private Integer userId;
  32. @ApiModelProperty("用户名称")
  33. private String username;
  34. @ApiModelProperty("用户密码")
  35. private String password;
  36. @ApiModelProperty("用户手机")
  37. private String mobile;
  38. public UserEntity()
  39. {
  40. }
  41. public UserEntity(Integer userId, String username, String password, String mobile)
  42. {
  43. this.userId = userId;
  44. this.username = username;
  45. this.password = password;
  46. this.mobile = mobile;
  47. }
  48. public Integer getUserId()
  49. {
  50. return userId;
  51. }
  52. public void setUserId(Integer userId)
  53. {
  54. this.userId = userId;
  55. }
  56. public String getUsername()
  57. {
  58. return username;
  59. }
  60. public void setUsername(String username)
  61. {
  62. this.username = username;
  63. }
  64. public String getPassword()
  65. {
  66. return password;
  67. }
  68. public void setPassword(String password)
  69. {
  70. this.password = password;
  71. }
  72. public String getMobile()
  73. {
  74. return mobile;
  75. }
  76. public void setMobile(String mobile)
  77. {
  78. this.mobile = mobile;
  79. }
  80. }
  81. }

总结

到这里spring boot 结合过滤器实现对Xss 攻击的防范就实现了,Xss 攻击总体来说危害还是挺大,对网站安全有较大风险,容易造成个人,公司等损失。

Xss 是较为平常的攻击,我们对网站,数据安全始终在奋进和优化的路上,确保网络环境安全,干净。

上面的攻击手法大家可不要对其他网站进行尝试哦!保护网络环境,平安你我他。

另外感谢大家的阅读:有任何问题,错误,想法欢迎大家留言评论。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/花生_TL007/article/detail/150072
推荐阅读
相关标签
  

闽ICP备14008679号