Xss漏洞解决方案
配置XssFilter过滤器
1.web.xml
<!-- XssFilter 漏洞解决方案 --> <filter> <filter-name>XssFilter</filter-name> <filter-class>com.xxx.filter.XssFilter</filter-class> </filter> <filter-mapping> <filter-name>XssFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
2.XssFilter:
package com.xxx.filter; 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 { FilterConfig filterConfig = null; @Override public void destroy() { this.filterConfig = null; } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { chain.doFilter(new XssShellInterceptor((HttpServletRequest) request), response); } @Override public void init(FilterConfig filterConfig) throws ServletException { this.filterConfig = filterConfig; } }
XssShellInterceptor:
package com.xxx.filter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; public class XssShellInterceptor extends HttpServletRequestWrapper { public XssShellInterceptor(HttpServletRequest request) { super(request); } @Override public String[] getParameterValues(String parameter) { String[] values = super.getParameterValues(parameter); if (values == null) { return null; } int count = values.length; String[] encodedValues = new String[count]; for (int i = 0; i < count; i++) { encodedValues[i] = cleanXSS(values[i]); } return encodedValues; } @Override public String getParameter(String parameter) { String value = super.getParameter(parameter); if (value == null) { return null; } return cleanXSS(value); } @Override public String getHeader(String name) { String value = super.getHeader(name); if (value == null) return null; return cleanXSS(value); } //过滤规则 目前我只配了过滤 script private String cleanXSS(String value) { value = value.replaceAll("'", "") .replaceAll(";","") .replaceAll("<", "") .replaceAll(">", "") .replaceAll("javascript","") .replaceAll("script", "") .replaceAll("jscript","") .replaceAll("vbscript",""); // value = value.replaceAll("[\\\"\\\'][\\s]*javascript:(.*)[\\\"\\\']", "\"\""); return value; } }