XSSFilter for java

來源:互聯網
上載者:User

Here is a good and simple anti cross-site scripting (XSS) filter written for Java web applications. What it basically does is remove all suspicious strings from request parameters before returning them to the application. It’s an improvement over my
previous post on the topic.You should configure it as the first filter in your chain (web.xml) and it’s generally a good idea to let it catch every request made to your site.The actual implementation consists of two classes, the actual filter is quite simple, it wraps the HTTP request object in a specialized HttpServletRequestWrapper that will perform our filtering.
public class XSSFilter implements Filter {    @Override    public void init(FilterConfig filterConfig) throws ServletException {    }    @Override    public void destroy() {    }    @Override    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)        throws IOException, ServletException {        chain.doFilter(new XSSRequestWrapper((HttpServletRequest) request), response);    }}

The wrapper overrides the getParameterValues(), getParameter() and getHeader() methods to execute the filtering before returning the desired field to the caller. The actual XSS checking and striping is performed in the stripXSS() private method.

import java.util.regex.Pattern;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletRequestWrapper;public class XSSRequestWrapper extends HttpServletRequestWrapper {    public XSSRequestWrapper(HttpServletRequest servletRequest) {        super(servletRequest);    }    @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] = stripXSS(values[i]);        }        return encodedValues;    }    @Override    public String getParameter(String parameter) {        String value = super.getParameter(parameter);        return stripXSS(value);    }    @Override    public String getHeader(String name) {        String value = super.getHeader(name);        return stripXSS(value);    }    private String stripXSS(String value) {        if (value != null) {            // NOTE: It's highly recommended to use the ESAPI library and uncomment the following line to            // avoid encoded attacks.            // value = ESAPI.encoder().canonicalize(value);            // Avoid null characters            value = value.replaceAll("", "");            // Avoid anything between script tags            Pattern scriptPattern = Pattern.compile("<script>(.*?)</script>", Pattern.CASE_INSENSITIVE);            value = scriptPattern.matcher(value).replaceAll("");            // Avoid anything in a src='...' type of expression            scriptPattern = Pattern.compile("src[\r\n]*=[\r\n]*\\\'(.*?)\\\'", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);            value = scriptPattern.matcher(value).replaceAll("");            scriptPattern = Pattern.compile("src[\r\n]*=[\r\n]*\\\"(.*?)\\\"", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);            value = scriptPattern.matcher(value).replaceAll("");            // Remove any lonesome </script> tag            scriptPattern = Pattern.compile("</script>", Pattern.CASE_INSENSITIVE);            value = scriptPattern.matcher(value).replaceAll("");            // Remove any lonesome <script ...> tag            scriptPattern = Pattern.compile("<script(.*?)>", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);            value = scriptPattern.matcher(value).replaceAll("");            // Avoid eval(...) expressions            scriptPattern = Pattern.compile("eval\\((.*?)\\)", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);            value = scriptPattern.matcher(value).replaceAll("");            // Avoid expression(...) expressions            scriptPattern = Pattern.compile("expression\\((.*?)\\)", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);            value = scriptPattern.matcher(value).replaceAll("");            // Avoid javascript:... expressions            scriptPattern = Pattern.compile("javascript:", Pattern.CASE_INSENSITIVE);            value = scriptPattern.matcher(value).replaceAll("");            // Avoid vbscript:... expressions            scriptPattern = Pattern.compile("vbscript:", Pattern.CASE_INSENSITIVE);            value = scriptPattern.matcher(value).replaceAll("");            // Avoid onload= expressions            scriptPattern = Pattern.compile("onload(.*?)=", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);            value = scriptPattern.matcher(value).replaceAll("");        }        return value;    }}

Notice the comment about the ESAPI library, I strongly
recommend you check it out and try to include it in your projects.

If you want to dig deeper on the topic I suggest you check out the OWASP page about
XSS and RSnake’s XSS (Cross Site Scripting) Cheat Sheet.

http://searchsecurity.techtarget.in/tip/Using-ESAPI-to-fix-XSS-in-your-Java-code

http://www.javacodegeeks.com/2012/07/anti-cross-site-scripting-xss-filter.html

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.