From a4d458bace4a13aac0df2d976b56364e9e31391b Mon Sep 17 00:00:00 2001 From: paulGao Date: Tue, 11 Jan 2022 11:20:54 +0800 Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E8=87=AA=E5=AE=9A=E4=B9=89xs?= =?UTF-8?q?s=E8=BF=87=E6=BB=A4=E7=AD=96=E7=95=A5=EF=BC=88=E5=8F=AF?= =?UTF-8?q?=E4=BF=9D=E5=AD=98iframe=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../filter/XssHttpServletRequestWrapper.java | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/framework/src/main/java/cn/lili/common/security/filter/XssHttpServletRequestWrapper.java b/framework/src/main/java/cn/lili/common/security/filter/XssHttpServletRequestWrapper.java index 2aca42cb..ad694aea 100644 --- a/framework/src/main/java/cn/lili/common/security/filter/XssHttpServletRequestWrapper.java +++ b/framework/src/main/java/cn/lili/common/security/filter/XssHttpServletRequestWrapper.java @@ -5,6 +5,8 @@ import cn.hutool.core.text.CharSequenceUtil; import cn.hutool.http.HtmlUtil; import cn.hutool.json.JSONUtil; import lombok.extern.slf4j.Slf4j; +import org.owasp.html.HtmlPolicyBuilder; +import org.owasp.html.PolicyFactory; import org.owasp.html.Sanitizers; import javax.servlet.ReadListener; @@ -57,6 +59,24 @@ public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper { "wechatpay", }; + //允许的标签 + private static final String[] allowedTags = {"h1", "h2", "h3", "h4", "h5", "h6", + "span", "strong", + "img", "video", "source", "iframe", "code", + "blockquote", "p", "div", + "ul", "ol", "li", + "table", "thead", "caption", "tbody", "tr", "th", "td", "br", + "a" + }; + + //需要转化的标签 + private static final String[] needTransformTags = {"article", "aside", "command", "datalist", "details", "figcaption", "figure", + "footer", "header", "hgroup", "section", "summary"}; + + //带有超链接的标签 + private static final String[] linkTags = {"img", "video", "source", "a", "iframe"}; + + public XssHttpServletRequestWrapper(HttpServletRequest request) { super(request); } @@ -257,6 +277,17 @@ public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper { private String cleanXSS(String value) { if (value != null) { + // 自定义策略 + PolicyFactory policy = new HtmlPolicyBuilder() + .allowStandardUrlProtocols() + //所有允许的标签 + .allowElements(allowedTags) + //内容标签转化为div + .allowElements((elementName, attributes) -> "div", needTransformTags) + .allowAttributes("src", "href", "target", "width", "height").onElements(linkTags) + //校验链接中的是否为http +// .allowUrlProtocols("https") + .toFactory(); // basic prepackaged policies for links, tables, integers, images, styles, blocks value = Sanitizers.FORMATTING .and(Sanitizers.STYLES) @@ -264,6 +295,7 @@ public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper { .and(Sanitizers.LINKS) .and(Sanitizers.BLOCKS) .and(Sanitizers.TABLES) + .and(policy) .sanitize(value); } return HtmlUtil.unescape(value);