【轉】HttpServletRequestWrapper 實現xss注入,
這裡說下最近項目中我們的解決方案,主要用到commons-lang3-3.1.jar這個包的org.apache.commons.lang3.StringEscapeUtils.escapeHtml4()這個方法。解決過程主要在使用者輸入和顯示輸出兩步:在輸入時對特殊字元如<>" ' & 轉義,在輸出時用jstl的fn:excapeXml("fff")方法。其中,輸入時的過濾是用一個filter來實現,實現過程:在web.xml加一個filter
<filter> <filter-name>XssEscape</filter-name> <filter-class>cn.pconline.morden.filter.XssFilter</filter-class> </filter> <filter-mapping> <filter-name>XssEscape</filter-name> <url-pattern>/*</url-pattern> <dispatcher>REQUEST</dispatcher> </filter-mapping>
XssFilter 的實現方式是實現servlet的Filter介面
package cn.pconline.morden.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 { @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { chain.doFilter(new XssHttpServletRequestWrapper((HttpServletRequest) request), response); } @Override public void destroy() { } }
關鍵是XssHttpServletRequestWrapper的實現方式,繼承servlet的HttpServletRequestWrapper,並重寫相應的幾個有可能帶xss攻擊的方法,如:
package cn.pconline.morden.filter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; import org.apache.commons.lang3.StringEscapeUtils; public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper { public XssHttpServletRequestWrapper(HttpServletRequest request) { super(request); } @Override public String getHeader(String name) { return StringEscapeUtils.escapeHtml4(super.getHeader(name)); } @Override public String getQueryString() { return StringEscapeUtils.escapeHtml4(super.getQueryString()); } @Override public String getParameter(String name) { return StringEscapeUtils.escapeHtml4(super.getParameter(name)); } @Override public String[] getParameterValues(String name) { String[] values = super.getParameterValues(name); if(values != null) { int length = values.length; String[] escapseValues = new String[length]; for(int i = 0; i < length; i++){ escapseValues[i] = StringEscapeUtils.escapeHtml4(values[i]); } return escapseValues; } return super.getParameterValues(name); } }
到此為止,在輸入的過濾就完成了。
在頁面顯示資料的時候,只是簡單地用fn:escapeXml()對有可能出現xss漏洞的地方做一下轉義輸出。
複雜內容的顯示,具體問題再具體分析。
另外,有些情況不想顯示過濾後內容的話,可以用StringEscapeUtils.unescapeHtml4()這個方法,把StringEscapeUtils.escapeHtml4()轉義之後的字元恢複原樣。