Hello你們好,本章咱們添加防止XSS攻擊功能 。有問題能夠聯繫我mr_beany@163.com。另求各路大神指點,感謝
XSS攻擊全稱跨站腳本攻擊,是一種在web應用中的計算機安全漏洞,它容許惡意web用戶將代碼植入到提供給其它用戶使用的頁面中。
css
你能夠本身作個簡單嘗試:
1. 在任何一個表單內,你輸入一段簡單的js代碼:<script>for(var i=0;i<1000;i++){alert("彈死你"+i);}</script>
,將其存入數據庫;
2. 在頁面上一個div元素內直接展現第一步內存入的值,你會發現彈出框出現了;java
以上兩個示例僅僅算是惡做劇,惡意用戶能作的更多,如獲取用戶信息,進行「網絡釣魚」攻擊等。node
應對XSS攻擊的其中一個方式就是後端對輸入內容進行過濾,輸入內容裏面的敏感信息直接過濾,如<script>
標籤等。git
Jsoup使用標籤白名單的機制用來進行防止XSS攻擊, 假設白名單中只容許p標籤存在, 此時在一段HTML代碼中, 只能存在p標籤 , 其餘標籤將會被清除只保留被標籤所包裹的內容,固然,Jsoup不單單能夠用來過濾,還能夠用來爬蟲,這裏先不作說明,後期會單寫一篇文章進行講解。
github
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.10.2</version>
</dependency>複製代碼
在core下建立filter
文件夾web
一、建立過濾規則spring
package com.example.demo.core.filter;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.safety.Whitelist;
/**
* @author 張瑤
* @Description: xss非法標籤過濾
* @date 2018/5/16 20:03
*/
public class XssFilterUtil {
/**
* 使用自帶的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) {
return Jsoup.clean(content, "", whitelist, outputSettings);
}
}
複製代碼
二、重寫請求參數處理函數,這是實現XSS過濾的關鍵,在其內重寫了getParameter,getParameterValues,getHeader等方法,對http請求內的參數進行了過濾。數據庫
package com.example.demo.core.filter;
import org.apache.commons.lang3.StringUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
/**
* 重寫請求參數處理函數
*/
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) {
if (("content".equals(name) || name.endsWith("WithHtml")) && !isIncludeRichText) {
return super.getParameter(name);
}
name = XssFilterUtil.clean(name);
String value = super.getParameter(name);
if (StringUtils.isNotBlank(value)) {
value = XssFilterUtil.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] = XssFilterUtil.clean(arr[i]);
}
}
return arr;
}
/**
* 覆蓋getHeader方法,將參數名和參數值都作xss過濾。<br/>
* 若是須要得到原始的值,則經過super.getHeaders(name)來獲取<br/>
* getHeaderNames 也可能須要覆蓋
*/
@Override
public String getHeader(String name) {
name = XssFilterUtil.clean(name);
String value = super.getHeader(name);
if (StringUtils.isNotBlank(value)) {
value = XssFilterUtil.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;
}
}複製代碼
三、添加過濾XSS請求的入口,在這裏經過XssHttpServletRequestWrapper將HttpServletRequest進行了封裝,filterChain.doFilter(xssRequest, response);
保證了後續代碼執行request.getParameter,request.getParameterValues,request.getHeader時調用的都是XssHttpServletRequestWrapper內重寫的方法,獲取到的參數是已經進行過標籤過濾的內容,從而消除了敏感信息。apache
package com.example.demo.core.filter;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
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;
/**
* @author 張瑤
* @Description: 攔截防止xss注入 經過Jsoup過濾請求參數內的特定字符
* @date 2018/5/16 20:04
*/
public class XssFilter implements Filter {
//是否過濾富文本內容
private static boolean IS_INCLUDE_RICH_TEXT = true;
public List<String> excludes = new ArrayList<>();
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
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 {
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() {
}
}
複製代碼
建立core→configurer→XssFilterConfigurer後端
package com.example.demo.core.configurer;
import com.example.demo.core.filter.XssFilter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.HashMap;
import java.util.Map;
/**
* @author 張瑤
* @Description:xss過濾攔截器配置文件
* @time 2018/5/16 20:47
*/
@Configuration
public class XssFilterConfigurer {
/**
* xss過濾攔截器
*/
@Bean
public FilterRegistrationBean xssFilterRegistrationBean() {
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
filterRegistrationBean.setFilter(new XssFilter());
filterRegistrationBean.setOrder(Integer.MAX_VALUE-1);
filterRegistrationBean.setEnabled(true);
filterRegistrationBean.addUrlPatterns("/*");
Map<String, String> initParameters = new HashMap();
//excludes用於配置不須要參數過濾的請求url
initParameters.put("excludes", "/favicon.ico,/img/*,/js/*,/css/*");
//isIncludeRichText主要用於設置富文本內容是否須要過濾
initParameters.put("isIncludeRichText", "true");
filterRegistrationBean.setInitParameters(initParameters);
return filterRegistrationBean;
}
}複製代碼
路徑localhost:8080/userInfo/selectById
請求參數id=1<a href="http://www.baidu.com/a" onclick="alert("模擬XSS攻擊");">sss</a><script>alert(0);</script>sss
結果:
咱們能夠看到<script></script>已經被過濾掉
碼雲地址: gitee.com/beany/mySpr…
GitHub地址: github.com/MyBeany/myS…
寫文章不易,如對您有幫助,請幫忙點下star
添加防止XSS攻擊功能已完成,後續功能接下來陸續更新,有問題能夠聯繫我mr_beany@163.com。另求各路大神指點,感謝你們。