SpringBoot防XSS攻擊
阿新 • • 發佈:2018-12-30
1 . pom中增加依賴
<!-- xss過濾元件 -->
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.9.2</version>
</dependency>
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 = " <a href=\"http://www.baidu.com/a\" onclick=\"alert(1);\">sss</a><script>alert(0);</script>sss "; System.out.println(clean(text)); } }
3 . 重寫請求引數處理函式
4 . 編寫XSSFilterpackage 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; /** * <code>{@link XssHttpServletRequestWrapper}</code> * @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過濾。<br/> * 如果需要獲得原始的值,則通過super.getParameterValues(name)來獲取<br/> * 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; } @Override public String[] getParameterValues(String name) { String[] arr = super.getParameterValues(name); if(arr != null){ for (int i=0;i<arr.length;i++) { arr[i] = JsoupUtil.clean(arr[i]); } } return arr; } /** * 覆蓋getHeader方法,將引數名和引數值都做xss過濾。<br/> * 如果需要獲得原始的值,則通過super.getHeaders(name)來獲取<br/> * 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; } }
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 = LogManager.getLogger(); /** * 是否過濾富文字內容 */ private static boolean IS_INCLUDE_RICH_TEXT = false; public List<String> excludes = new ArrayList<>(); @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException,ServletException { if(logger.isDebugEnabled()){ logger.debug("xss filter is open"); } HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse resp = (HttpServletResponse) response; if(handleExcludeURL(req, resp)){ filterChain.doFilter(request, response); return; } XssHttpServletRequestWrapper xssRequest = new XssHttpServletRequestWrapper((HttpServletRequest) request,IS_INCLUDE_RICH_TEXT); filterChain.doFilter(xssRequest, response); } private boolean handleExcludeURL(HttpServletRequest request, HttpServletResponse response) { if (excludes == null || excludes.isEmpty()) { return false; } String url = request.getServletPath(); for (String pattern : excludes) { Pattern p = Pattern.compile("^" + pattern); Matcher m = p.matcher(url); if (m.find()) { return true; } } return false; } @Override public void init(FilterConfig filterConfig) throws ServletException { if(logger.isDebugEnabled()){ logger.debug("xss filter init ===================="); } String isIncludeRichText = filterConfig.getInitParameter("isIncludeRichText"); if(StringUtils.isNotBlank(isIncludeRichText)){ IS_INCLUDE_RICH_TEXT = BooleanUtils.toBoolean(isIncludeRichText); } String temp = filterConfig.getInitParameter("excludes"); if (temp != null) { String[] url = temp.split(","); for (int i = 0; url != null && i < url.length; i++) { excludes.add(url[i]); } } } @Override public void destroy() {} }
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;
@Configuration
public class XssConfig{
/**
* xss過濾攔截器
*/
@Bean
public FilterRegistrationBean xssFilterRegistrationBean() {
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
filterRegistrationBean.setFilter(new XssFilter());
filterRegistrationBean.setOrder(1);
filterRegistrationBean.setEnabled(true);
filterRegistrationBean.addUrlPatterns("/*");
Map<String, String> initParameters = Maps.newHashMap();
initParameters.put("excludes", "/favicon.ico,/img/*,/js/*,/css/*");
initParameters.put("isIncludeRichText", "true");
filterRegistrationBean.setInitParameters(initParameters);
return filterRegistrationBean;
}
}
大功告成, 另外SpringMVC版本的XSS防範請參考另一篇文章SpringMVC防止XSS攻擊