From 2779700f4995f3ecf67f935996a680ccf535d1e1 Mon Sep 17 00:00:00 2001 From: ronger Date: Mon, 23 May 2022 13:01:36 +0800 Subject: [PATCH] =?UTF-8?q?:lock:=20xss=20=E8=BF=87=E6=BB=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/com/rymcu/forest/util/XssUtils.java | 22 +++++++++---------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/src/main/java/com/rymcu/forest/util/XssUtils.java b/src/main/java/com/rymcu/forest/util/XssUtils.java index abc1343..6760653 100644 --- a/src/main/java/com/rymcu/forest/util/XssUtils.java +++ b/src/main/java/com/rymcu/forest/util/XssUtils.java @@ -17,6 +17,7 @@ import java.util.regex.Pattern; * @packageName com.rymcu.forest.util */ public class XssUtils { + private static final String regex = "(
[\\s|\\S]+?
)|([\\s|\\S]+?)"; /** * 滤除content中的危险 HTML 代码, 主要是脚本代码, 滚动字幕代码以及脚本事件处理代码 @@ -48,10 +49,11 @@ public class XssUtils { } public static String filterHtmlCode(String content) { - String regex = "
[\\s|\\S]+?
"; + if(StringUtils.isBlank(content)) { + return content; + } // 拿到匹配的pre标签List List resultFindAll = ReUtil.findAll(regex, content, 0, new ArrayList<>()); - String result = ""; // size大于0,就做替换 if (resultFindAll.size() > 0) { // 生成一个待替换唯一字符串 @@ -63,17 +65,15 @@ public class XssUtils { Pattern pattern = Pattern.compile(preTagReplace); // 替换pre标签内容 String preFilter = ReUtil.replaceAll(content, regex, preTagReplace); - System.err.println("pre标签替换"); - System.err.println(preFilter); - final String[] filterResult = {HtmlUtil.filter(preFilter)}; - resultFindAll.forEach(obj -> { - filterResult[0] = ReUtil.replaceFirst(pattern, filterResult[0], obj); - }); - result = filterResult[0]; + // 拦截xss + final String[] filterResult = {replaceHtmlCode(preFilter)}; + + // 依次将替换后的pre标签换回来 + resultFindAll.forEach(obj -> filterResult[0] = ReUtil.replaceFirst(pattern, filterResult[0], obj)); + return filterResult[0]; } else { - result = HtmlUtil.filter(content); + return replaceHtmlCode(content); } - return result; } }