防止SpringMVC的XSS攻擊的方法
阿新 • • 發佈:2019-02-01
XSS攻擊,即Cross Site Script,跨指令碼攻擊,往web頁面注入html程式碼或者script程式碼,造成頁面混亂。
HttpServletRequestWrapper 是HttpServletRequest的裝飾器。
大體流程:包裝request->建立過濾器->新增過濾器
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import org.apache.commons.lang.StringUtils;
public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper {
String method = null;
public DMTRequest(HttpServletRequest servletRequest) {
super(servletRequest);
}
public String[] getParameterValues(String parameter) {
String[] values = super.getParameterValues(parameter);
if (values == null) {
return null;
} else {
int count = values.length;
String[] encodedValues = new String[count];
for(int i = 0; i < count; ++i) {
encodedValues[i] = this.cleanXSS(values[i]);
}
return encodedValues;
}
}
public String getParameter(String parameter) {
String value = super.getParameter(parameter);
return value == null?null:this.cleanXSS(value);
}
public String getHeader(String name) {
String value = super.getHeader(name);
return value == null?null:this.cleanXSS(value);
}
private String cleanXSS(String value) {
if(StringUtils.isEmpty(value)) {
return "";
} else {
value = value.replaceAll("\"", "").replaceAll("\'", "").replaceAll("<", "").replaceAll(">", "");
value = value.replaceAll("eval\\((.*)\\)", "");
value = value.replaceAll("[\\\"\\\'][\\s]*javascript:(.*)[\\\"\\\']", "\"\"");
value = value.replaceAll("script", "");
return value;
}
}
}
public class XssFilter implements Filter {
FilterConfig filterConfig = null;
public void init(FilterConfig filterConfig) throws ServletException {
this.filterConfig = filterConfig;
}
public void destroy() {
this.filterConfig = null;
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
chain.doFilter(new XssHttpServletRequestWrapper (
(HttpServletRequest) request), response);
}
}
在web.xml檔案中將該過濾器放在最前面或者是字元編碼過濾器之後:
filter>
<filter-name>xssFilter</filter-name>
<filter-class>xxx.xxx.filter.XssFilter</filter-class>
<init-param>
<param-name>exclude</param-name>
<param-value>/;/scripts/*;/styles/*;/images/*</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>xssFilter</filter-name>
<url-pattern>*.html</url-pattern>
<!-- 直接從客戶端過來的請求以及通過forward過來的請求都要經過該過濾器 -->
<dispatcher>REQUEST</dispatcher>
<dispatcher>FORWARD</dispatcher>
</filter-mapping>