当前位置:   article > 正文

SpringMVC 反射型跨站点脚本攻击_反射型跨站点脚本攻击解决方案

反射型跨站点脚本攻击解决方案

解决方案:

服务端校验,添加拦截器

配置web,xml
  1. <filter>
  2. <filter-name>xssFilter </filter-name>
  3. <filter-class>com.fh.filter.XssFilter </filter-class>
  4. </filter>
XssFilter
  1. package com.fh.filter;
  2. import com.fh.controller.base.BaseController;
  3. import lombok.extern.slf4j.Slf4j;
  4. import org.apache.commons.lang.StringUtils;
  5. import javax.servlet.*;
  6. import javax.servlet.http.HttpServletRequest;
  7. import javax.servlet.http.HttpServletResponse;
  8. import java.io.IOException;
  9. import java.util.ArrayList;
  10. import java.util.List;
  11. import java.util.regex.Matcher;
  12. import java.util.regex.Pattern;
  13. @Slf4j
  14. public class XssFilter extends BaseController implements Filter {
  15. /**
  16. * 不需要过滤的链接
  17. */
  18. public List<String> excludes = new ArrayList<>();
  19. /**
  20. * xss过滤开关
  21. */
  22. public boolean enabled = false;
  23. @Override
  24. public void init(FilterConfig filterConfig) throws ServletException {
  25. String tempExcludes = filterConfig.getInitParameter("excludes");
  26. String tempEnabled = filterConfig.getInitParameter("enabled");
  27. if (StringUtils.isNotEmpty(tempExcludes)) {
  28. String[] url = tempExcludes.split(",");
  29. for (int i = 0; url != null && i < url.length; i++) {
  30. excludes.add(url[i]);
  31. }
  32. }
  33. if (StringUtils.isNotEmpty(tempEnabled)) {
  34. enabled = Boolean.valueOf(tempEnabled);
  35. }
  36. }
  37. @Override
  38. public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
  39. HttpServletRequest req = (HttpServletRequest) request;
  40. HttpServletResponse resp = (HttpServletResponse) response;
  41. if (handleExcludeURL(req, resp)) {
  42. filterChain.doFilter(request, response);
  43. return;
  44. }
  45. filterChain.doFilter(new XssHttpServletRequestWrapper((HttpServletRequest) request), response);
  46. }
  47. @Override
  48. public void destroy() {
  49. // noop
  50. }
  51. private boolean handleExcludeURL(HttpServletRequest request, HttpServletResponse response) {
  52. if (!enabled) {
  53. return true;
  54. }
  55. if (excludes == null || excludes.isEmpty()) {
  56. return false;
  57. }
  58. String url = request.getServletPath();
  59. for (String pattern : excludes) {
  60. Pattern p = Pattern.compile("^" + pattern);
  61. Matcher m = p.matcher(url);
  62. if (m.find()){
  63. return true;
  64. }
  65. }
  66. return false;
  67. }
  68. }
XssHttpServletRequestWrapper
  1. package com.fh.filter;
  2. import lombok.extern.slf4j.Slf4j;
  3. import org.apache.commons.io.IOUtils;
  4. import org.apache.commons.lang.StringUtils;
  5. import org.springframework.http.HttpHeaders;
  6. import org.springframework.http.MediaType;
  7. import javax.servlet.ServletInputStream;
  8. import javax.servlet.http.HttpServletRequest;
  9. import javax.servlet.http.HttpServletRequestWrapper;
  10. import java.io.ByteArrayInputStream;
  11. import java.io.IOException;
  12. import java.util.*;
  13. @Slf4j
  14. public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper {
  15. private HttpServletRequest orgRequest;
  16. // html过滤
  17. private final static HTMLFilter htmlFilter = new HTMLFilter();
  18. public XssHttpServletRequestWrapper(HttpServletRequest request) {
  19. super(request);
  20. orgRequest = request;
  21. }
  22. @Override
  23. public ServletInputStream getInputStream() throws IOException {
  24. // 非json类型,直接返回
  25. if (!isJsonRequest()) {
  26. return super.getInputStream();
  27. }
  28. // 为空,直接返回
  29. String json = IOUtils.toString(super.getInputStream(), "utf-8");
  30. if (StringUtils.isBlank(json)) {
  31. return super.getInputStream();
  32. }
  33. // xss过滤
  34. json = xssEncode(json);
  35. final ByteArrayInputStream bis = new ByteArrayInputStream(json.getBytes("utf-8"));
  36. return new ServletInputStream() {
  37. @Override
  38. public int read() throws IOException {
  39. return bis.read();
  40. }
  41. };
  42. }
  43. /**
  44. * 覆盖getParameter方法,将参数名和参数值都做xss过滤。<br/>
  45. */
  46. @Override
  47. public String getParameter(String rawName) {
  48. String value = super.getParameter(xssEncode(rawName));
  49. if (StringUtils.isNotBlank(value)) {
  50. value = xssEncode(value);
  51. }
  52. return value;
  53. }
  54. @Override
  55. public String[] getParameterValues(String name) {
  56. String[] parameters = super.getParameterValues(name);
  57. if (parameters == null || parameters.length == 0) {
  58. return null;
  59. }
  60. for (int i = 0; i < parameters.length; i++) {
  61. parameters[i] = xssEncode(parameters[i]);
  62. }
  63. return parameters;
  64. }
  65. @Override
  66. public Enumeration<String> getParameterNames() {
  67. Enumeration<String> parameterNames = super.getParameterNames();
  68. List<String> list = new LinkedList<>();
  69. if (parameterNames != null) {
  70. while (parameterNames.hasMoreElements()) {
  71. String rawName = parameterNames.nextElement();
  72. String safetyName = xssEncode(rawName);
  73. if (!Objects.equals(rawName, safetyName))
  74. {
  75. log.warn("请求路径: {},参数键: {}, xss过滤后: {}. 疑似xss攻击",
  76. orgRequest.getRequestURI(), rawName, safetyName);
  77. }
  78. list.add(safetyName);
  79. }
  80. }
  81. return Collections.enumeration(list);
  82. }
  83. @Override
  84. public Map<String, String[]> getParameterMap() {
  85. Map<String, String[]> map = new LinkedHashMap<>();
  86. Map<String, String[]> parameters = super.getParameterMap();
  87. for (String key : parameters.keySet()) {
  88. String[] values = parameters.get(key);
  89. for (int i = 0; i < values.length; i++) {
  90. values[i] = xssEncode(values[i]);
  91. }
  92. map.put(key, values);
  93. }
  94. return map;
  95. }
  96. /**
  97. * 覆盖getHeader方法,将参数名和参数值都做xss过滤。<br/>
  98. * 如果需要获得原始的值,则通过super.getHeaders(name)来获取<br/>
  99. * getHeaderNames 也可能需要覆盖
  100. */
  101. @Override
  102. public String getHeader(String name) {
  103. String value = super.getHeader(xssEncode(name));
  104. if (StringUtils.isNotBlank(value)) {
  105. value = xssEncode(value);
  106. }
  107. return value;
  108. }
  109. private String xssEncode(String input) {
  110. return htmlFilter.filter(input);
  111. }
  112. /**
  113. * 是否是Json请求
  114. */
  115. public boolean isJsonRequest()
  116. {
  117. String header = super.getHeader(HttpHeaders.CONTENT_TYPE);
  118. return StringUtils.startsWithIgnoreCase(header, MediaType.APPLICATION_JSON_VALUE);
  119. }
  120. }
 HTMLFilter
  1. package com.fh.filter;
  2. import lombok.extern.slf4j.Slf4j;
  3. import java.util.*;
  4. import java.util.concurrent.ConcurrentHashMap;
  5. import java.util.concurrent.ConcurrentMap;
  6. import java.util.regex.Matcher;
  7. import java.util.regex.Pattern;
  8. @Slf4j
  9. public final class HTMLFilter {
  10. /** regex flag union representing /si modifiers in php **/
  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<String, Pattern>();
  37. private static final ConcurrentMap<String,Pattern> P_REMOVE_SELF_BLANKS = new ConcurrentHashMap<String, Pattern>();
  38. /** set of allowed html elements, along with allowed attributes for each element **/
  39. private final Map<String, List<String>> vAllowed;
  40. /** counts of open tags for each (allowable) html element **/
  41. private final Map<String, Integer> vTagCounts = new HashMap<String, Integer>();
  42. /** html elements which must always be self-closing (e.g. "<img />") **/
  43. private final String[] vSelfClosingTags;
  44. /** html elements which must always have separate opening and closing tags (e.g. "<b></b>") **/
  45. private final String[] vNeedClosingTags;
  46. /** set of disallowed html elements **/
  47. private final String[] vDisallowed;
  48. /** attributes which should be checked for valid protocols **/
  49. private final String[] vProtocolAtts;
  50. /** allowed protocols **/
  51. private final String[] vAllowedProtocols;
  52. /** tags which should be removed if they contain no content (e.g. "<b></b>" or "<b />") **/
  53. private final String[] vRemoveBlanks;
  54. /** entities allowed within html markup **/
  55. private final String[] vAllowedEntities;
  56. /** flag determining whether comments are allowed in input String. */
  57. private final boolean stripComment;
  58. private final boolean encodeQuotes;
  59. private boolean vDebug = false;
  60. /**
  61. * flag determining whether to try to make tags when presented with "unbalanced"
  62. * angle brackets (e.g. "<b text </b>" becomes "<b> text </b>"). If set to false,
  63. * unbalanced angle brackets will be html escaped.
  64. */
  65. private final boolean alwaysMakeTags;
  66. /** Default constructor.
  67. *
  68. */
  69. public HTMLFilter() {
  70. vAllowed = new HashMap<>();
  71. final ArrayList<String> a_atts = new ArrayList<String>();
  72. a_atts.add("href");
  73. a_atts.add("target");
  74. vAllowed.put("a", a_atts);
  75. final ArrayList<String> img_atts = new ArrayList<String>();
  76. img_atts.add("src");
  77. img_atts.add("width");
  78. img_atts.add("height");
  79. img_atts.add("alt");
  80. vAllowed.put("img", img_atts);
  81. final ArrayList<String> no_atts = new ArrayList<String>();
  82. vAllowed.put("b", no_atts);
  83. vAllowed.put("strong", no_atts);
  84. vAllowed.put("i", no_atts);
  85. vAllowed.put("em", no_atts);
  86. vSelfClosingTags = new String[]{"img"};
  87. vNeedClosingTags = new String[]{"a", "b", "strong", "i", "em"};
  88. vDisallowed = new String[]{};
  89. vAllowedProtocols = new String[]{"http", "mailto", "https"}; // no ftp.
  90. vProtocolAtts = new String[]{"src", "href"};
  91. vRemoveBlanks = new String[]{"a", "b", "strong", "i", "em"};
  92. vAllowedEntities = new String[]{"amp", "gt", "lt", "quot"};
  93. stripComment = true;
  94. encodeQuotes = true;
  95. alwaysMakeTags = true;
  96. }
  97. /** Set debug flag to true. Otherwise use default settings. See the default constructor.
  98. *
  99. * @param debug turn debug on with a true argument
  100. */
  101. public HTMLFilter(final boolean debug) {
  102. this();
  103. vDebug = debug;
  104. }
  105. /** Map-parameter configurable constructor.
  106. *
  107. * @param conf map containing configuration. keys match field names.
  108. */
  109. @SuppressWarnings("unchecked")
  110. public HTMLFilter(final Map<String,Object> conf) {
  111. assert conf.containsKey("vAllowed") : "configuration requires vAllowed";
  112. assert conf.containsKey("vSelfClosingTags") : "configuration requires vSelfClosingTags";
  113. assert conf.containsKey("vNeedClosingTags") : "configuration requires vNeedClosingTags";
  114. assert conf.containsKey("vDisallowed") : "configuration requires vDisallowed";
  115. assert conf.containsKey("vAllowedProtocols") : "configuration requires vAllowedProtocols";
  116. assert conf.containsKey("vProtocolAtts") : "configuration requires vProtocolAtts";
  117. assert conf.containsKey("vRemoveBlanks") : "configuration requires vRemoveBlanks";
  118. assert conf.containsKey("vAllowedEntities") : "configuration requires vAllowedEntities";
  119. vAllowed = Collections.unmodifiableMap((HashMap<String, List<String>>) conf.get("vAllowed"));
  120. vSelfClosingTags = (String[]) conf.get("vSelfClosingTags");
  121. vNeedClosingTags = (String[]) conf.get("vNeedClosingTags");
  122. vDisallowed = (String[]) conf.get("vDisallowed");
  123. vAllowedProtocols = (String[]) conf.get("vAllowedProtocols");
  124. vProtocolAtts = (String[]) conf.get("vProtocolAtts");
  125. vRemoveBlanks = (String[]) conf.get("vRemoveBlanks");
  126. vAllowedEntities = (String[]) conf.get("vAllowedEntities");
  127. stripComment = conf.containsKey("stripComment") ? (Boolean) conf.get("stripComment") : true;
  128. encodeQuotes = conf.containsKey("encodeQuotes") ? (Boolean) conf.get("encodeQuotes") : true;
  129. alwaysMakeTags = conf.containsKey("alwaysMakeTags") ? (Boolean) conf.get("alwaysMakeTags") : true;
  130. }
  131. private void reset() {
  132. vTagCounts.clear();
  133. }
  134. private void debug(final String msg) {
  135. if (vDebug) {
  136. log.info(msg);
  137. }
  138. }
  139. //---------------------------------------------------------------
  140. // my versions of some PHP library functions
  141. public static String chr(final int decimal) {
  142. return String.valueOf((char) decimal);
  143. }
  144. public static String htmlSpecialChars(final String s) {
  145. String result = s;
  146. result = regexReplace(P_AMP, "&amp;", result);
  147. result = regexReplace(P_QUOTE, "&quot;", result);
  148. result = regexReplace(P_LEFT_ARROW, "&lt;", result);
  149. result = regexReplace(P_RIGHT_ARROW, "&gt;", result);
  150. return result;
  151. }
  152. //---------------------------------------------------------------
  153. /**
  154. * given a user submitted input String, filter out any invalid or restricted
  155. * html.
  156. *
  157. * @param input text (i.e. submitted by a user) than may contain html
  158. * @return "clean" version of input, with only valid, whitelisted html elements allowed
  159. */
  160. public String filter(final String input) {
  161. reset();
  162. String s = input;
  163. debug("************************************************");
  164. debug(" INPUT: " + input);
  165. s = escapeComments(s);
  166. debug(" escapeComments: " + s);
  167. s = balanceHTML(s);
  168. debug(" balanceHTML: " + s);
  169. s = checkTags(s);
  170. debug(" checkTags: " + s);
  171. s = processRemoveBlanks(s);
  172. debug("processRemoveBlanks: " + s);
  173. s = validateEntities(s);
  174. debug(" validateEntites: " + s);
  175. debug("************************************************\n\n");
  176. return s;
  177. }
  178. public boolean isAlwaysMakeTags(){
  179. return alwaysMakeTags;
  180. }
  181. public boolean isStripComments(){
  182. return stripComment;
  183. }
  184. private String escapeComments(final String s) {
  185. final Matcher m = P_COMMENTS.matcher(s);
  186. final StringBuffer buf = new StringBuffer();
  187. if (m.find()) {
  188. final String match = m.group(1); //(.*?)
  189. m.appendReplacement(buf, Matcher.quoteReplacement("<!--" + htmlSpecialChars(match) + "-->"));
  190. }
  191. m.appendTail(buf);
  192. return buf.toString();
  193. }
  194. private String balanceHTML(String s) {
  195. if (alwaysMakeTags) {
  196. //
  197. // try and form html
  198. //
  199. s = regexReplace(P_END_ARROW, "", s);
  200. s = regexReplace(P_BODY_TO_END, "<$1>", s);
  201. s = regexReplace(P_XML_CONTENT, "$1<$2", s);
  202. } else {
  203. //
  204. // escape stray brackets
  205. //
  206. s = regexReplace(P_STRAY_LEFT_ARROW, "&lt;$1", s);
  207. s = regexReplace(P_STRAY_RIGHT_ARROW, "$1$2&gt;<", s);
  208. //
  209. // the last regexp causes '<>' entities to appear
  210. // (we need to do a lookahead assertion so that the last bracket can
  211. // be used in the next pass of the regexp)
  212. //
  213. s = regexReplace(P_BOTH_ARROWS, "", s);
  214. }
  215. return s;
  216. }
  217. private String checkTags(String s) {
  218. Matcher m = P_TAGS.matcher(s);
  219. final StringBuffer buf = new StringBuffer();
  220. while (m.find()) {
  221. String replaceStr = m.group(1);
  222. replaceStr = processTag(replaceStr);
  223. m.appendReplacement(buf, Matcher.quoteReplacement(replaceStr));
  224. }
  225. m.appendTail(buf);
  226. s = buf.toString();
  227. // these get tallied in processTag
  228. // (remember to reset before subsequent calls to filter method)
  229. for (String key : vTagCounts.keySet()) {
  230. for (int ii = 0; ii < vTagCounts.get(key); ii++) {
  231. s += "</" + key + ">";
  232. }
  233. }
  234. return s;
  235. }
  236. private String processRemoveBlanks(final String s) {
  237. String result = s;
  238. for (String tag : vRemoveBlanks) {
  239. if(!P_REMOVE_PAIR_BLANKS.containsKey(tag)){
  240. P_REMOVE_PAIR_BLANKS.putIfAbsent(tag, Pattern.compile("<" + tag + "(\\s[^>]*)?></" + tag + ">"));
  241. }
  242. result = regexReplace(P_REMOVE_PAIR_BLANKS.get(tag), "", result);
  243. if(!P_REMOVE_SELF_BLANKS.containsKey(tag)){
  244. P_REMOVE_SELF_BLANKS.putIfAbsent(tag, Pattern.compile("<" + tag + "(\\s[^>]*)?/>"));
  245. }
  246. result = regexReplace(P_REMOVE_SELF_BLANKS.get(tag), "", result);
  247. }
  248. return result;
  249. }
  250. private static String regexReplace(final Pattern regex_pattern, final String replacement, final String s) {
  251. Matcher m = regex_pattern.matcher(s);
  252. return m.replaceAll(replacement);
  253. }
  254. private String processTag(final String s) {
  255. // ending tags
  256. Matcher m = P_END_TAG.matcher(s);
  257. if (m.find()) {
  258. final String name = m.group(1).toLowerCase();
  259. if (allowed(name)) {
  260. if (!inArray(name, vSelfClosingTags)) {
  261. if (vTagCounts.containsKey(name)) {
  262. vTagCounts.put(name, vTagCounts.get(name) - 1);
  263. return "</" + name + ">";
  264. }
  265. }
  266. }
  267. }
  268. // starting tags
  269. m = P_START_TAG.matcher(s);
  270. if (m.find()) {
  271. final String name = m.group(1).toLowerCase();
  272. final String body = m.group(2);
  273. String ending = m.group(3);
  274. //debug( "in a starting tag, name='" + name + "'; body='" + body + "'; ending='" + ending + "'" );
  275. if (allowed(name)) {
  276. String params = "";
  277. final Matcher m2 = P_QUOTED_ATTRIBUTES.matcher(body);
  278. final Matcher m3 = P_UNQUOTED_ATTRIBUTES.matcher(body);
  279. final List<String> paramNames = new ArrayList<String>();
  280. final List<String> paramValues = new ArrayList<String>();
  281. while (m2.find()) {
  282. paramNames.add(m2.group(1)); //([a-z0-9]+)
  283. paramValues.add(m2.group(3)); //(.*?)
  284. }
  285. while (m3.find()) {
  286. paramNames.add(m3.group(1)); //([a-z0-9]+)
  287. paramValues.add(m3.group(3)); //([^\"\\s']+)
  288. }
  289. String paramName, paramValue;
  290. for (int ii = 0; ii < paramNames.size(); ii++) {
  291. paramName = paramNames.get(ii).toLowerCase();
  292. paramValue = paramValues.get(ii);
  293. // debug( "paramName='" + paramName + "'" );
  294. // debug( "paramValue='" + paramValue + "'" );
  295. // debug( "allowed? " + vAllowed.get( name ).contains( paramName ) );
  296. if (allowedAttribute(name, paramName)) {
  297. if (inArray(paramName, vProtocolAtts)) {
  298. paramValue = processParamProtocol(paramValue);
  299. }
  300. params += " " + paramName + "=\"" + paramValue + "\"";
  301. }
  302. }
  303. if (inArray(name, vSelfClosingTags)) {
  304. ending = " /";
  305. }
  306. if (inArray(name, vNeedClosingTags)) {
  307. ending = "";
  308. }
  309. if (ending == null || ending.length() < 1) {
  310. if (vTagCounts.containsKey(name)) {
  311. vTagCounts.put(name, vTagCounts.get(name) + 1);
  312. } else {
  313. vTagCounts.put(name, 1);
  314. }
  315. } else {
  316. ending = " /";
  317. }
  318. return "<" + name + params + ending + ">";
  319. } else {
  320. return "";
  321. }
  322. }
  323. // comments
  324. m = P_COMMENT.matcher(s);
  325. if (!stripComment && m.find()) {
  326. return "<" + m.group() + ">";
  327. }
  328. return "";
  329. }
  330. private String processParamProtocol(String s) {
  331. s = decodeEntities(s);
  332. final Matcher m = P_PROTOCOL.matcher(s);
  333. if (m.find()) {
  334. final String protocol = m.group(1);
  335. if (!inArray(protocol, vAllowedProtocols)) {
  336. // bad protocol, turn into local anchor link instead
  337. s = "#" + s.substring(protocol.length() + 1, s.length());
  338. if (s.startsWith("#//")) {
  339. s = "#" + s.substring(3, s.length());
  340. }
  341. }
  342. }
  343. return s;
  344. }
  345. private String decodeEntities(String s) {
  346. StringBuffer buf = new StringBuffer();
  347. Matcher m = P_ENTITY.matcher(s);
  348. while (m.find()) {
  349. final String match = m.group(1);
  350. final int decimal = Integer.decode(match).intValue();
  351. m.appendReplacement(buf, Matcher.quoteReplacement(chr(decimal)));
  352. }
  353. m.appendTail(buf);
  354. s = buf.toString();
  355. buf = new StringBuffer();
  356. m = P_ENTITY_UNICODE.matcher(s);
  357. while (m.find()) {
  358. final String match = m.group(1);
  359. final int decimal = Integer.valueOf(match, 16).intValue();
  360. m.appendReplacement(buf, Matcher.quoteReplacement(chr(decimal)));
  361. }
  362. m.appendTail(buf);
  363. s = buf.toString();
  364. buf = new StringBuffer();
  365. m = P_ENCODE.matcher(s);
  366. while (m.find()) {
  367. final String match = m.group(1);
  368. final int decimal = Integer.valueOf(match, 16).intValue();
  369. m.appendReplacement(buf, Matcher.quoteReplacement(chr(decimal)));
  370. }
  371. m.appendTail(buf);
  372. s = buf.toString();
  373. s = validateEntities(s);
  374. return s;
  375. }
  376. private String validateEntities(final String s) {
  377. StringBuffer buf = new StringBuffer();
  378. // validate entities throughout the string
  379. Matcher m = P_VALID_ENTITIES.matcher(s);
  380. while (m.find()) {
  381. final String one = m.group(1); //([^&;]*)
  382. final String two = m.group(2); //(?=(;|&|$))
  383. m.appendReplacement(buf, Matcher.quoteReplacement(checkEntity(one, two)));
  384. }
  385. m.appendTail(buf);
  386. return encodeQuotes(buf.toString());
  387. }
  388. private String encodeQuotes(final String s){
  389. if(encodeQuotes){
  390. StringBuffer buf = new StringBuffer();
  391. Matcher m = P_VALID_QUOTES.matcher(s);
  392. while (m.find()) {
  393. final String one = m.group(1); //(>|^)
  394. final String two = m.group(2); //([^<]+?)
  395. final String three = m.group(3); //(<|$)
  396. m.appendReplacement(buf, Matcher.quoteReplacement(one + regexReplace(P_QUOTE, "&quot;", two) + three));
  397. }
  398. m.appendTail(buf);
  399. return buf.toString();
  400. }else{
  401. return s;
  402. }
  403. }
  404. private String checkEntity(final String preamble, final String term) {
  405. return ";".equals(term) && isValidEntity(preamble)
  406. ? '&' + preamble
  407. : "&amp;" + preamble;
  408. }
  409. private boolean isValidEntity(final String entity) {
  410. return inArray(entity, vAllowedEntities);
  411. }
  412. private static boolean inArray(final String s, final String[] array) {
  413. for (String item : array) {
  414. if (item != null && item.equals(s)) {
  415. return true;
  416. }
  417. }
  418. return false;
  419. }
  420. private boolean allowed(final String name) {
  421. return (vAllowed.isEmpty() || vAllowed.containsKey(name)) && !inArray(name, vDisallowed);
  422. }
  423. private boolean allowedAttribute(final String name, final String paramName) {
  424. return allowed(name) && (vAllowed.isEmpty() || vAllowed.get(name).contains(paramName));
  425. }
  426. }

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

闽ICP备14008679号