作者:mobiledu2502927723 | 来源:互联网 | 2023-09-04 18:24
1 . pom中增加依赖
org.jsoupjsoup1.9.2
2 . 增加标签处理类
package com.xbz.utils;import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.safety.Whitelist;import java.io.IOException;/*** xss非法标签过滤工具类* 过滤html中的xss字符* @author xbz*/
public class JsoupUtil {/*** 使用自带的basicWithImages 白名单* 允许的便签有a,b,blockquote,br,cite,code,dd,dl,dt,em,i,li,ol,p,pre,q,small,span,* strike,strong,sub,sup,u,ul,img* 以及a标签的href,img标签的src,align,alt,height,width,title属性*/private static final Whitelist whitelist = Whitelist.basicWithImages();/** 配置过滤化参数,不对代码进行格式化 */private static final Document.OutputSettings outputSettings = new Document.OutputSettings().prettyPrint(false);static {// 富文本编辑时一些样式是使用style来进行实现的// 比如红色字体 style="color:red;"// 所以需要给所有标签添加style属性whitelist.addAttributes(":all", "style");}public static String clean(String content) {if(StringUtils.isNotBlank(content)){content = content.trim();}return Jsoup.clean(content, "", whitelist, outputSettings);}public static void main(String[] args) throws IOException {String text = " ssssss ";System.out.println(clean(text));}
}
3 . 重写请求参数处理函数
package com.xbz.web.common.filter;import com.xbz.utils.JsoupUtil;
import org.apache.commons.lang3.StringUtils;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;/** * {@link XssHttpServletRequestWrapper}
* @author*/
public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper { HttpServletRequest orgRequest = null; private boolean isIncludeRichText = false;public XssHttpServletRequestWrapper(HttpServletRequest request, boolean isIncludeRichText) { super(request); orgRequest = request;this.isIncludeRichText = isIncludeRichText;} /** * 覆盖getParameter方法,将参数名和参数值都做xss过滤。
* 如果需要获得原始的值,则通过super.getParameterValues(name)来获取
* getParameterNames,getParameterValues和getParameterMap也可能需要覆盖 */ @Override public String getParameter(String name) {Boolean flag = ("content".equals(name) || name.endsWith("WithHtml"));if( flag && !isIncludeRichText){return super.getParameter(name);}name = JsoupUtil.clean(name);String value = super.getParameter(name); if (StringUtils.isNotBlank(value)) {value = JsoupUtil.clean(value);}return value; } @Overridepublic String[] getParameterValues(String name) {String[] arr = super.getParameterValues(name);if(arr != null){for (int i=0;i * 如果需要获得原始的值,则通过super.getHeaders(name)来获取
* getHeaderNames 也可能需要覆盖 */ @Override public String getHeader(String name) { name = JsoupUtil.clean(name);String value = super.getHeader(name); if (StringUtils.isNotBlank(value)) { value = JsoupUtil.clean(value); } return value; } /** * 获取最原始的request * * @return */ public HttpServletRequest getOrgRequest() { return orgRequest; } /** * 获取最原始的request的静态方法 * * @return */ public static HttpServletRequest getOrgRequest(HttpServletRequest req) { if (req instanceof XssHttpServletRequestWrapper) { return ((XssHttpServletRequestWrapper) req).getOrgRequest(); } return req; } }
4 . 编写XSSFilter
package com.xbz.web.common.filter;import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;/** * 拦截防止xss注入* 通过Jsoup过滤请求参数内的特定字符* @author yangwk */
public class XssFilter implements Filter { private static final Logger logger &#61; LogManager.getLogger();/*** 是否过滤富文本内容*/private static boolean IS_INCLUDE_RICH_TEXT &#61; false;public List excludes &#61; new ArrayList<>();&#64;Overridepublic void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException,ServletException {if(logger.isDebugEnabled()){logger.debug("xss filter is open");}HttpServletRequest req &#61; (HttpServletRequest) request;HttpServletResponse resp &#61; (HttpServletResponse) response;if(handleExcludeURL(req, resp)){filterChain.doFilter(request, response);return;}XssHttpServletRequestWrapper xssRequest &#61; new XssHttpServletRequestWrapper((HttpServletRequest) request,IS_INCLUDE_RICH_TEXT);filterChain.doFilter(xssRequest, response);}private boolean handleExcludeURL(HttpServletRequest request, HttpServletResponse response) {if (excludes &#61;&#61; null || excludes.isEmpty()) {return false;}String url &#61; request.getServletPath();for (String pattern : excludes) {Pattern p &#61; Pattern.compile("^" &#43; pattern);Matcher m &#61; p.matcher(url);if (m.find()) {return true;}}return false;}&#64;Overridepublic void init(FilterConfig filterConfig) throws ServletException {if(logger.isDebugEnabled()){logger.debug("xss filter init &#61;&#61;&#61;&#61;&#61;&#61;&#61;&#61;&#61;&#61;&#61;&#61;&#61;&#61;&#61;&#61;&#61;&#61;&#61;&#61;");}String isIncludeRichText &#61; filterConfig.getInitParameter("isIncludeRichText");if(StringUtils.isNotBlank(isIncludeRichText)){IS_INCLUDE_RICH_TEXT &#61; BooleanUtils.toBoolean(isIncludeRichText);}String temp &#61; filterConfig.getInitParameter("excludes");if (temp !&#61; null) {String[] url &#61; temp.split(",");for (int i &#61; 0; url !&#61; null && i
5 . 增加XSS配置
package com.xbz.web.common.config;import com.xbz.web.common.filter.XssFilter;
import com.google.common.collect.Maps;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;import java.util.Map;&#64;Configuration
public class XssConfig{/*** xss过滤拦截器*/&#64;Beanpublic FilterRegistrationBean xssFilterRegistrationBean() {FilterRegistrationBean filterRegistrationBean &#61; new FilterRegistrationBean();filterRegistrationBean.setFilter(new XssFilter());filterRegistrationBean.setOrder(1);filterRegistrationBean.setEnabled(true);filterRegistrationBean.addUrlPatterns("/*");Map initParameters &#61; Maps.newHashMap();initParameters.put("excludes", "/favicon.ico,/img/*,/js/*,/css/*");initParameters.put("isIncludeRichText", "true");filterRegistrationBean.setInitParameters(initParameters);return filterRegistrationBean;}
}
大功告成, 另外SpringMVC版本的XSS防范请参考另一篇文章SpringMVC防止XSS攻击