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

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

简述Xss

一,什么是Xss 攻击

百度百科:

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

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

通俗解释:

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

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

留言板

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

二,Xss的危害

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

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

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

窃取网页浏览中的cookie值

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

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

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

劫持流量实现恶意跳转

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

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

Xss攻击方式

大小写绕过

例如:

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

http://192.168.1.102/xss/example2.php?name=

利用过滤后返回语句再次构成攻击语句来绕过

并不是只有script标签才可以插入代码

我们利用如下方式:

[http://192.168.1.102/xss/example4.php?name=

src='w.123' onerror='alert("hey!")'>

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

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

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

当用户鼠标在这个块上面时即可运行(可以配合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 攻击流程图

代码编写流程图:

自定义过滤器

public class XssFilter implements Filter

{

/**

* 排除链接

*/

public List excludes = new ArrayList<>();

@Override

public void init(FilterConfig filterConfig) throws ServletException

{

String tempExcludes = filterConfig.getInitParameter("excludes");

if (StringUtils.isNotEmpty(tempExcludes))

{

String[] url = tempExcludes.split(",");

for (int i = 0; url != null && i < url.length; i++)

{

excludes.add(url[i]);

}

}

}

@Override

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)

throws IOException, ServletException

{

HttpServletRequest req = (HttpServletRequest) request;

HttpServletResponse resp = (HttpServletResponse) response;

if (handleExcludeURL(req, resp))

{

// 传递过滤器

chain.doFilter(request, response);

return;

}

XssHttpServletRequestWrapper xssRequest = new XssHttpServletRequestWrapper((HttpServletRequest) request);

chain.doFilter(xssRequest, response);

}

private boolean handleExcludeURL(HttpServletRequest request, HttpServletResponse response)

{

String url = request.getServletPath();

String method = request.getMethod();

// GET DELETE 不过滤

if (method == null || HttpMethod.GET.matches(method) || HttpMethod.DELETE.matches(method))

{

return true;

}

return StringUtils.matches(url, excludes);

}

@Override

public void destroy()

{

}

}

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

/**

* 查找指定字符串是否匹配指定字符串列表中的任意一个字符串

*

* @param str 指定字符串

* @param strs 需要检查的字符串数组

* @return 是否匹配

*/

public static boolean matches(String str, List strs)

{

if (isEmpty(str) || isEmpty(strs))

{

return false;

}

for (String pattern : strs)

{

if (isMatch(pattern, str))

{

return true;

}

}

return false;

}

/**

* 判断url是否与规则配置:

* ? 表示单个字符;

* * 表示一层路径内的任意字符串,不可跨层级;

* ** 表示任意层路径;

*

* @param pattern 匹配规则

* @param url 需要匹配的url

* @return

*/

public static boolean isMatch(String pattern, String url)

{

AntPathMatcher matcher = new AntPathMatcher();

return matcher.match(pattern, url);

}

Xss 过滤处理

/**

* XSS过滤处理

*

* @author lh

*/

public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper

{

/**

* @param request

*/

public XssHttpServletRequestWrapper(HttpServletRequest request)

{

super(request);

}

// 重写获取参数进行转义

@Override

public String[] getParameterValues(String name)

{

String[] values = super.getParameterValues(name);

if (values != null)

{

int length = values.length;

String[] escapesValues = new String[length];

for (int i = 0; i < length; i++)

{

// 防xss攻击和过滤前后空格

escapesValues[i] = EscapeUtil.clean(values[i]).trim();

}

return escapesValues;

}

return super.getParameterValues(name);

}

@Override

public ServletInputStream getInputStream() throws IOException

{

// 非json类型,直接返回

if (!isJsonRequest())

{

return super.getInputStream();

}

// 为空,直接返回

String json = IOUtils.toString(super.getInputStream(), "utf-8");

if (StringUtils.isEmpty(json))

{

return super.getInputStream();

}

// xss过滤

json = EscapeUtil.clean(json).trim();

byte[] jsonBytes = json.getBytes("utf-8");

final ByteArrayInputStream bis = new ByteArrayInputStream(jsonBytes);

return new ServletInputStream()

{

@Override

public boolean isFinished()

{

return true;

}

@Override

public boolean isReady()

{

return true;

}

@Override

public int available() throws IOException

{

return jsonBytes.length;

}

@Override

public void setReadListener(ReadListener readListener)

{

}

@Override

public int read() throws IOException

{

return bis.read();

}

};

}

/**

* 是否是Json请求

*

* @param request

*/

public boolean isJsonRequest()

{

String header = super.getHeader(HttpHeaders.CONTENT_TYPE);

return StringUtils.startsWithIgnoreCase(header, MediaType.APPLICATION_JSON_VALUE);

}

}

转义Html字符

Clean 方法

public static String clean(String content)

{

return new HTMLFilter().filter(content);

}

HTML 过滤器

/**

* HTML过滤器,用于去除XSS漏洞隐患。

*

* @author lh

*/

public final class HTMLFilter

{

/**

* regex flag union representing /si modifiers in php

**/

private static final int REGEX_FLAGS_SI = Pattern.CASE_INSENSITIVE | Pattern.DOTALL;

private static final Pattern P_COMMENTS = Pattern.compile("", Pattern.DOTALL);

private static final Pattern P_COMMENT = Pattern.compile("^!--(.*)--$", REGEX_FLAGS_SI);

private static final Pattern P_TAGS = Pattern.compile("<(.*?)>", Pattern.DOTALL);

private static final Pattern P_END_TAG = Pattern.compile("^/([a-z0-9]+)", REGEX_FLAGS_SI);

private static final Pattern P_START_TAG = Pattern.compile("^([a-z0-9]+)(.*?)(/?)$", REGEX_FLAGS_SI);

private static final Pattern P_QUOTED_ATTRIBUTES = Pattern.compile("([a-z0-9]+)=([\"'])(.*?)\\2", REGEX_FLAGS_SI);

private static final Pattern P_UNQUOTED_ATTRIBUTES = Pattern.compile("([a-z0-9]+)(=)([^\"\\s']+)", REGEX_FLAGS_SI);

private static final Pattern P_PROTOCOL = Pattern.compile("^([^:]+):", REGEX_FLAGS_SI);

private static final Pattern P_ENTITY = Pattern.compile("&#(\\d+);?");

private static final Pattern P_ENTITY_UNICODE = Pattern.compile("&#x([0-9a-f]+);?");

private static final Pattern P_ENCODE = Pattern.compile("%([0-9a-f]{2});?");

private static final Pattern P_VALID_ENTITIES = Pattern.compile("&([^&;]*)(?=(;|&|$))");

private static final Pattern P_VALID_QUOTES = Pattern.compile("(>|^)([^<]+?)(<|$)", Pattern.DOTALL);

private static final Pattern P_END_ARROW = Pattern.compile("^>");

private static final Pattern P_BODY_TO_END = Pattern.compile("<([^>]*?)(?=<|$)");

private static final Pattern P_XML_CONTENT = Pattern.compile("(^|>)([^<]*?)(?=>)");

private static final Pattern P_STRAY_LEFT_ARROW = Pattern.compile("<([^>]*?)(?=<|$)");

private static final Pattern P_STRAY_RIGHT_ARROW = Pattern.compile("(^|>)([^<]*?)(?=>)");

private static final Pattern P_AMP = Pattern.compile("&");

private static final Pattern P_QUOTE = Pattern.compile("\"");

private static final Pattern P_LEFT_ARROW = Pattern.compile("<");

private static final Pattern P_RIGHT_ARROW = Pattern.compile(">");

private static final Pattern P_BOTH_ARROWS = Pattern.compile("<>");

// @xxx could grow large... maybe use sesat's ReferenceMap

private static final ConcurrentMap P_REMOVE_PAIR_BLANKS = new ConcurrentHashMap<>();

private static final ConcurrentMap P_REMOVE_SELF_BLANKS = new ConcurrentHashMap<>();

/**

* set of allowed html elements, along with allowed attributes for each element

**/

private final Map> vAllowed;

/**

* counts of open tags for each (allowable) html element

**/

private final Map vTagCounts = new HashMap<>();

/**

* html elements which must always be self-closing (e.g. "")

**/

private final String[] vSelfClosingTags;

/**

* html elements which must always have separate opening and closing tags (e.g. "")

**/

private final String[] vNeedClosingTags;

/**

* set of disallowed html elements

**/

private final String[] vDisallowed;

/**

* attributes which should be checked for valid protocols

**/

private final String[] vProtocolAtts;

/**

* allowed protocols

**/

private final String[] vAllowedProtocols;

/**

* tags which should be removed if they contain no content (e.g. "" or "")

**/

private final String[] vRemoveBlanks;

/**

* entities allowed within html markup

**/

private final String[] vAllowedEntities;

/**

* flag determining whether comments are allowed in input String.

*/

private final boolean stripComment;

private final boolean encodeQuotes;

/**

* flag determining whether to try to make tags when presented with "unbalanced" angle brackets (e.g. ""

* becomes " text "). If set to false, unbalanced angle brackets will be html escaped.

*/

private final boolean alwaysMakeTags;

/**

* Default constructor.

*/

public HTMLFilter()

{

vAllowed = new HashMap<>();

final ArrayList a_atts = new ArrayList<>();

a_atts.add("href");

a_atts.add("target");

vAllowed.put("a", a_atts);

final ArrayList img_atts = new ArrayList<>();

img_atts.add("src");

img_atts.add("width");

img_atts.add("height");

img_atts.add("alt");

vAllowed.put("img", img_atts);

final ArrayList no_atts = new ArrayList<>();

vAllowed.put("b", no_atts);

vAllowed.put("strong", no_atts);

vAllowed.put("i", no_atts);

vAllowed.put("em", no_atts);

vSelfClosingTags = new String[] { "img" };

vNeedClosingTags = new String[] { "a", "b", "strong", "i", "em" };

vDisallowed = new String[] {};

vAllowedProtocols = new String[] { "http", "mailto", "https" }; // no ftp.

vProtocolAtts = new String[] { "src", "href" };

vRemoveBlanks = new String[] { "a", "b", "strong", "i", "em" };

vAllowedEntities = new String[] { "amp", "gt", "lt", "quot" };

stripComment = true;

encodeQuotes = true;

alwaysMakeTags = false;

}

/**

* Map-parameter configurable constructor.

*

* @param conf map containing configuration. keys match field names.

*/

@SuppressWarnings("unchecked")

public HTMLFilter(final Map conf)

{

assert conf.containsKey("vAllowed") : "configuration requires vAllowed";

assert conf.containsKey("vSelfClosingTags") : "configuration requires vSelfClosingTags";

assert conf.containsKey("vNeedClosingTags") : "configuration requires vNeedClosingTags";

assert conf.containsKey("vDisallowed") : "configuration requires vDisallowed";

assert conf.containsKey("vAllowedProtocols") : "configuration requires vAllowedProtocols";

assert conf.containsKey("vProtocolAtts") : "configuration requires vProtocolAtts";

assert conf.containsKey("vRemoveBlanks") : "configuration requires vRemoveBlanks";

assert conf.containsKey("vAllowedEntities") : "configuration requires vAllowedEntities";

vAllowed = Collections.unmodifiableMap((HashMap>) conf.get("vAllowed"));

vSelfClosingTags = (String[]) conf.get("vSelfClosingTags");

vNeedClosingTags = (String[]) conf.get("vNeedClosingTags");

vDisallowed = (String[]) conf.get("vDisallowed");

vAllowedProtocols = (String[]) conf.get("vAllowedProtocols");

vProtocolAtts = (String[]) conf.get("vProtocolAtts");

vRemoveBlanks = (String[]) conf.get("vRemoveBlanks");

vAllowedEntities = (String[]) conf.get("vAllowedEntities");

stripComment = conf.containsKey("stripComment") ? (Boolean) conf.get("stripComment") : true;

encodeQuotes = conf.containsKey("encodeQuotes") ? (Boolean) conf.get("encodeQuotes") : true;

alwaysMakeTags = conf.containsKey("alwaysMakeTags") ? (Boolean) conf.get("alwaysMakeTags") : true;

}

private void reset()

{

vTagCounts.clear();

}

// ---------------------------------------------------------------

// my versions of some PHP library functions

public static String chr(final int decimal)

{

return String.valueOf((char) decimal);

}

public static String htmlSpecialChars(final String s)

{

String result = s;

result = regexReplace(P_AMP, "&", result);

result = regexReplace(P_QUOTE, """, result);

result = regexReplace(P_LEFT_ARROW, "<", result);

result = regexReplace(P_RIGHT_ARROW, ">", result);

return result;

}

// ---------------------------------------------------------------

/**

* given a user submitted input String, filter out any invalid or restricted html.

*

* @param input text (i.e. submitted by a user) than may contain html

* @return "clean" version of input, with only valid, whitelisted html elements allowed

*/

public String filter(final String input)

{

reset();

String s = input;

s = escapeComments(s);

s = balanceHTML(s);

s = checkTags(s);

s = processRemoveBlanks(s);

// s = validateEntities(s);

return s;

}

public boolean isAlwaysMakeTags()

{

return alwaysMakeTags;

}

public boolean isStripComments()

{

return stripComment;

}

private String escapeComments(final String s)

{

final Matcher m = P_COMMENTS.matcher(s);

final StringBuffer buf = new StringBuffer();

if (m.find())

{

final String match = m.group(1); // (.*?)

m.appendReplacement(buf, Matcher.quoteReplacement(""));

}

m.appendTail(buf);

return buf.toString();

}

private String balanceHTML(String s)

{

if (alwaysMakeTags)

{

//

// try and form html

//

s = regexReplace(P_END_ARROW, "", s);

// 不追加结束标签

s = regexReplace(P_BODY_TO_END, "<$1>", s);

s = regexReplace(P_XML_CONTENT, "$1<$2", s);

}

else

{

//

// escape stray brackets

//

s = regexReplace(P_STRAY_LEFT_ARROW, "<$1", s);

s = regexReplace(P_STRAY_RIGHT_ARROW, "$1$2><", s);

//

// the last regexp causes '<>' entities to appear

// (we need to do a lookahead assertion so that the last bracket can

// be used in the next pass of the regexp)

//

s = regexReplace(P_BOTH_ARROWS, "", s);

}

return s;

}

private String checkTags(String s)

{

Matcher m = P_TAGS.matcher(s);

final StringBuffer buf = new StringBuffer();

while (m.find())

{

String replaceStr = m.group(1);

replaceStr = processTag(replaceStr);

m.appendReplacement(buf, Matcher.quoteReplacement(replaceStr));

}

m.appendTail(buf);

// these get tallied in processTag

// (remember to reset before subsequent calls to filter method)

final StringBuilder sBuilder = new StringBuilder(buf.toString());

for (String key : vTagCounts.keySet())

{

for (int ii = 0; ii < vTagCounts.get(key); ii++)

{

sBuilder.append("");

}

}

s = sBuilder.toString();

return s;

}

private String processRemoveBlanks(final String s)

{

String result = s;

for (String tag : vRemoveBlanks)

{

if (!P_REMOVE_PAIR_BLANKS.containsKey(tag))

{

P_REMOVE_PAIR_BLANKS.putIfAbsent(tag, Pattern.compile("<" + tag + "(\\s[^>]*)?>"));

}

result = regexReplace(P_REMOVE_PAIR_BLANKS.get(tag), "", result);

if (!P_REMOVE_SELF_BLANKS.containsKey(tag))

{

P_REMOVE_SELF_BLANKS.putIfAbsent(tag, Pattern.compile("<" + tag + "(\\s[^>]*)?/>"));

}

result = regexReplace(P_REMOVE_SELF_BLANKS.get(tag), "", result);

}

return result;

}

private static String regexReplace(final Pattern regex_pattern, final String replacement, final String s)

{

Matcher m = regex_pattern.matcher(s);

return m.replaceAll(replacement);

}

private String processTag(final String s)

{

// ending tags

Matcher m = P_END_TAG.matcher(s);

if (m.find())

{

final String name = m.group(1).toLowerCase();

if (allowed(name))

{

if (!inArray(name, vSelfClosingTags))

{

if (vTagCounts.containsKey(name))

{

vTagCounts.put(name, vTagCounts.get(name) - 1);

return "";

}

}

}

}

// starting tags

m = P_START_TAG.matcher(s);

if (m.find())

{

final String name = m.group(1).toLowerCase();

final String body = m.group(2);

String ending = m.group(3);

// debug( "in a starting tag, name='" + name + "'; body='" + body + "'; ending='" + ending + "'" );

if (allowed(name))

{

final StringBuilder params = new StringBuilder();

final Matcher m2 = P_QUOTED_ATTRIBUTES.matcher(body);

final Matcher m3 = P_UNQUOTED_ATTRIBUTES.matcher(body);

final List paramNames = new ArrayList<>();

final List paramValues = new ArrayList<>();

while (m2.find())

{

paramNames.add(m2.group(1)); // ([a-z0-9]+)

paramValues.add(m2.group(3)); // (.*?)

}

while (m3.find())

{

paramNames.add(m3.group(1)); // ([a-z0-9]+)

paramValues.add(m3.group(3)); // ([^\"\\s']+)

}

String paramName, paramValue;

for (int ii = 0; ii < paramNames.size(); ii++)

{

paramName = paramNames.get(ii).toLowerCase();

paramValue = paramValues.get(ii);

// debug( "paramName='" + paramName + "'" );

// debug( "paramValue='" + paramValue + "'" );

// debug( "allowed? " + vAllowed.get( name ).contains( paramName ) );

if (allowedAttribute(name, paramName))

{

if (inArray(paramName, vProtocolAtts))

{

paramValue = processParamProtocol(paramValue);

}

params.append(' ').append(paramName).append("=\\\"").append(paramValue).append("\\\"");

}

}

if (inArray(name, vSelfClosingTags))

{

ending = " /";

}

if (inArray(name, vNeedClosingTags))

{

ending = "";

}

if (ending == null || ending.length() < 1)

{

if (vTagCounts.containsKey(name))

{

vTagCounts.put(name, vTagCounts.get(name) + 1);

}

else

{

vTagCounts.put(name, 1);

}

}

else

{

ending = " /";

}

return "<" + name + params + ending + ">";

}

else

{

return "";

}

}

// comments

m = P_COMMENT.matcher(s);

if (!stripComment && m.find())

{

return "<" + m.group() + ">";

}

return "";

}

private String processParamProtocol(String s)

{

s = decodeEntities(s);

final Matcher m = P_PROTOCOL.matcher(s);

if (m.find())

{

final String protocol = m.group(1);

if (!inArray(protocol, vAllowedProtocols))

{

// bad protocol, turn into local anchor link instead

s = "#" + s.substring(protocol.length() + 1);

if (s.startsWith("#//"))

{

s = "#" + s.substring(3);

}

}

}

return s;

}

private String decodeEntities(String s)

{

StringBuffer buf = new StringBuffer();

Matcher m = P_ENTITY.matcher(s);

while (m.find())

{

final String match = m.group(1);

final int decimal = Integer.decode(match).intValue();

m.appendReplacement(buf, Matcher.quoteReplacement(chr(decimal)));

}

m.appendTail(buf);

s = buf.toString();

buf = new StringBuffer();

m = P_ENTITY_UNICODE.matcher(s);

while (m.find())

{

final String match = m.group(1);

final int decimal = Integer.valueOf(match, 16).intValue();

m.appendReplacement(buf, Matcher.quoteReplacement(chr(decimal)));

}

m.appendTail(buf);

s = buf.toString();

buf = new StringBuffer();

m = P_ENCODE.matcher(s);

while (m.find())

{

final String match = m.group(1);

final int decimal = Integer.valueOf(match, 16).intValue();

m.appendReplacement(buf, Matcher.quoteReplacement(chr(decimal)));

}

m.appendTail(buf);

s = buf.toString();

s = validateEntities(s);

return s;

}

private String validateEntities(final String s)

{

StringBuffer buf = new StringBuffer();

// validate entities throughout the string

Matcher m = P_VALID_ENTITIES.matcher(s);

while (m.find())

{

final String one = m.group(1); // ([^&;]*)

final String two = m.group(2); // (?=(;|&|$))

m.appendReplacement(buf, Matcher.quoteReplacement(checkEntity(one, two)));

}

m.appendTail(buf);

return encodeQuotes(buf.toString());

}

private String encodeQuotes(final String s)

{

if (encodeQuotes)

{

StringBuffer buf = new StringBuffer();

Matcher m = P_VALID_QUOTES.matcher(s);

while (m.find())

{

final String one = m.group(1); // (>|^)

final String two = m.group(2); // ([^<]+?)

final String three = m.group(3); // (<|$)

// 不替换双引号为",防止json格式无效 regexReplace(P_QUOTE, """, two)

m.appendReplacement(buf, Matcher.quoteReplacement(one + two + three));

}

m.appendTail(buf);

return buf.toString();

}

else

{

return s;

}

}

private String checkEntity(final String preamble, final String term)

{

return ";".equals(term) && isValidEntity(preamble) ? '&' + preamble : "&" + preamble;

}

private boolean isValidEntity(final String entity)

{

return inArray(entity, vAllowedEntities);

}

private static boolean inArray(final String s, final String[] array)

{

for (String item : array)

{

if (item != null && item.equals(s))

{

return true;

}

}

return false;

}

private boolean allowed(final String name)

{

return (vAllowed.isEmpty() || vAllowed.containsKey(name)) && !inArray(name, vDisallowed);

}

private boolean allowedAttribute(final String name, final String paramName)

{

return allowed(name) && (vAllowed.isEmpty() || vAllowed.get(name).contains(paramName));

}

}

注册配置过滤器bean

注册bean

@Configuration

public class FilterConfig

{

@Value("${xss.excludes}")

private String excludes;

@Value("${xss.urlPatterns}")

private String urlPatterns;

@SuppressWarnings({ "rawtypes", "unchecked" })

@Bean

@ConditionalOnProperty(value = "xss.enabled", havingValue = "true")

public FilterRegistrationBean xssFilterRegistration()

{

FilterRegistrationBean registration = new FilterRegistrationBean();

registration.setDispatcherTypes(DispatcherType.REQUEST);

registration.setFilter(new XssFilter());

//添加过滤路径

registration.addUrlPatterns(StringUtils.split(urlPatterns, ","));

registration.setName("xssFilter");

registration.setOrder(FilterRegistrationBean.HIGHEST_PRECEDENCE);

//设置初始化参数

Map initParameters = new HashMap();

initParameters.put("excludes", excludes);

registration.setInitParameters(initParameters);

return registration;

}

@SuppressWarnings({ "rawtypes", "unchecked" })

@Bean

public FilterRegistrationBean someFilterRegistration()

{

FilterRegistrationBean registration = new FilterRegistrationBean();

registration.setFilter(new RepeatableFilter());

registration.addUrlPatterns("/*");

registration.setName("repeatableFilter");

registration.setOrder(FilterRegistrationBean.LOWEST_PRECEDENCE);

return registration;

}

}

文件配置:

# 防止XSS攻击

xss:

# 过滤开关

enabled: true

# 排除链接(多个用逗号分隔)

excludes: /system/notice

# 匹配链接

urlPatterns: /system/*,/monitor/*,/tool/*

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

转义和反转义工具

/**

* 转义和反转义工具类

*

* @author lh

*/

public class EscapeUtil

{

public static final String RE_HTML_MARK = "(<[^<]*?>)|(<[\\s]*?/[^<]*?>)|(<[^<]*?/[\\s]*?>)";

private static final char[][] TEXT = new char[64][];

static

{

for (int i = 0; i < 64; i++)

{

TEXT[i] = new char[] { (char) i };

}

// special HTML characters

TEXT['\''] = "'".toCharArray(); // 单引号

TEXT['"'] = """.toCharArray(); // 双引号

TEXT['&'] = "&".toCharArray(); // &符

TEXT['<'] = "<".toCharArray(); // 小于号

TEXT['>'] = ">".toCharArray(); // 大于号

}

/**

* 转义文本中的HTML字符为安全的字符

*

* @param text 被转义的文本

* @return 转义后的文本

*/

public static String escape(String text)

{

return encode(text);

}

/**

* 还原被转义的HTML特殊字符

*

* @param content 包含转义符的HTML内容

* @return 转换后的字符串

*/

public static String unescape(String content)

{

return decode(content);

}

/**

* 清除所有HTML标签,但是不删除标签内的内容

*

* @param content 文本

* @return 清除标签后的文本

*/

public static String clean(String content)

{

return new HTMLFilter().filter(content);

}

/**

* Escape编码

*

* @param text 被编码的文本

* @return 编码后的字符

*/

private static String encode(String text)

{

if (StringUtils.isEmpty(text))

{

return StringUtils.EMPTY;

}

final StringBuilder tmp = new StringBuilder(text.length() * 6);

char c;

for (int i = 0; i < text.length(); i++)

{

c = text.charAt(i);

if (c < 256)

{

tmp.append("%");

if (c < 16)

{

tmp.append("0");

}

tmp.append(Integer.toString(c, 16));

}

else

{

tmp.append("%u");

if (c <= 0xfff)

{

// issue#I49JU8@Gitee

tmp.append("0");

}

tmp.append(Integer.toString(c, 16));

}

}

return tmp.toString();

}

/**

* Escape解码

*

* @param content 被转义的内容

* @return 解码后的字符串

*/

public static String decode(String content)

{

if (StringUtils.isEmpty(content))

{

return content;

}

StringBuilder tmp = new StringBuilder(content.length());

int lastPos = 0, pos = 0;

char ch;

while (lastPos < content.length())

{

pos = content.indexOf("%", lastPos);

if (pos == lastPos)

{

if (content.charAt(pos + 1) == 'u')

{

ch = (char) Integer.parseInt(content.substring(pos + 2, pos + 6), 16);

tmp.append(ch);

lastPos = pos + 6;

}

else

{

ch = (char) Integer.parseInt(content.substring(pos + 1, pos + 3), 16);

tmp.append(ch);

lastPos = pos + 3;

}

}

else

{

if (pos == -1)

{

tmp.append(content.substring(lastPos));

lastPos = content.length();

}

else

{

tmp.append(content.substring(lastPos, pos));

lastPos = pos;

}

}

}

return tmp.toString();

}

public static void main(String[] args)

{

String html = "";

String escape = EscapeUtil.escape(html);

// String html = "ipt>alert(\"XSS\")ipt>";

// String html = "<123";

// String html = "123>";

System.out.println("clean: " + EscapeUtil.clean(html));

System.out.println("escape: " + escape);

System.out.println("unescape: " + EscapeUtil.unescape(escape));

}

测试类

Controller 测试类

@Slf4j

@RestController

public class XssController {

//键值对

@PostMapping("xssFilter")

public String xssFilter(String name, String info) {

log.error(name + "---" + info);

return name + "---" + info;

}

//实体

@PostMapping("modelXssFilter")

public People modelXssFilter(@RequestBody UserEntity user) {

log.error(user.getUserName() + "---" + user.getMobile());

return user;

}

//不转义

@PostMapping("open/xssFilter")

public String openXssFilter(String name) {

return name;

}

//不转义2

@PostMapping("open2/xssFilter")

public String open2XssFilter(String name) {

return name;

}

// 这里最好单独建立实体,这里这里只是演示

@ApiModel(value = "UserEntity", description = "用户实体")

class UserEntity

{

@ApiModelProperty("用户ID")

private Integer userId;

@ApiModelProperty("用户名称")

private String username;

@ApiModelProperty("用户密码")

private String password;

@ApiModelProperty("用户手机")

private String mobile;

public UserEntity()

{

}

public UserEntity(Integer userId, String username, String password, String mobile)

{

this.userId = userId;

this.username = username;

this.password = password;

this.mobile = mobile;

}

public Integer getUserId()

{

return userId;

}

public void setUserId(Integer userId)

{

this.userId = userId;

}

public String getUsername()

{

return username;

}

public void setUsername(String username)

{

this.username = username;

}

public String getPassword()

{

return password;

}

public void setPassword(String password)

{

this.password = password;

}

public String getMobile()

{

return mobile;

}

public void setMobile(String mobile)

{

this.mobile = mobile;

}

}

}

总结

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

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

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

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

相关推荐

合作伙伴