配置過濾器filter對跨站指令碼攻擊XSS實現攔截
阿新 • • 發佈:2019-02-08
filter的原理圖見上博原理圖
1.web.xml中配置filter
<filter> <filter-name>XssFilter</filter-name> <filter-class>com.wk.util.XssFilter</filter-class> </filter> <filter-mapping> <filter-name>XssFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
2.編寫相應的filter的java類
3.編寫字元過濾類package com.wk.util; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; public class XssFilter implements Filter { @Override public void destroy() { } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { chain.doFilter(new XssHttpServletRequestWraper( (HttpServletRequest)request), response);//對request和response進行過濾 } @Override public void init(FilterConfig arg0) throws ServletException { } }
package com.wk.util; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; /** * * @author wk * @date 2015-8-6 */ public class XssHttpServletRequestWraper extends HttpServletRequestWrapper { public XssHttpServletRequestWraper(HttpServletRequest request) { super(request); } @Override public String getParameter(String name) { return clearXss(super.getParameter(name)); } @Override public String getHeader(String name) { return clearXss(super.getHeader(name)); } @Override public String[] getParameterValues(String name) { String[] values = super.getParameterValues(name); if (values == null) { return null; } String[] newValues = new String[values.length]; for (int i = 0; i < values.length; i++) { newValues[i] = clearXss(values[i]); } return newValues; } /** * 處理字元轉義 * * @param value * @return */ private String clearXss(String value) { if (value == null || "".equals(value)) { return value; } value = value.replaceAll("<", "<").replaceAll(">", ">"); value = value.replaceAll("\\(", "(").replace("\\)", ")"); value = value.replaceAll("'", "'"); value = value.replaceAll("eval\\((.*)\\)", ""); value = value.replaceAll("[\\\"\\\'][\\s]*javascript:(.*)[\\\"\\\']", "\"\""); value = value.replace("script", ""); return value; } }
4.當然嘍,此處多說一句,在裝飾類中不僅可以攔截XSS指令碼攻擊,還可以將請求引數中的空格去掉,這樣就不用在每一個action中都要去掉提交引數值的前後空格了,至於Injection Flows等sql注入的問題也可以一概解決了