Alternative to using c:out to prevent XSS

后端 未结 3 1531
别跟我提以往
别跟我提以往 2020-12-31 17:15

I\'m working on preventing cross site scripting (XSS) in a Java, Spring based, Web application. I have already implemented a servlet filter similar to this example http://gr

3条回答
  •  甜味超标
    2020-12-31 17:29

    Since Servlet 2.5/JSP 2.1 you could create a custom ELResolver which does that. You can register it in ServletContextListener#contextInitialized().

    @Override
    public void contextInitialized(ServletContextEvent event) {
        JspFactory.getDefaultFactory()
            .getJspApplicationContext(event.getServletContext())
            .addELResolver(new YourCustomELResolver());
    }
    

    In the ELResolver#getValue() you could do the escaping job.

    Your only problem is that you will be unable to display HTML there where it's allowed (i.e. already sanitized from malicious tags/attributes by kind of a whitelist so that you end up with innocent tags like Jsoup can do).


    That said, I disagree the necessity to escape XSS during input by the Filter as you mentioned in 1st paragraph of the question. You risk double-escaping. You only need to escape it at exactly that point where it can possibly harm, i.e. straight in the view side there where it's going to be inlined among HTML, the output. I recommend to get rid of that so-called XSS filter and concentrate you on fixing it in the view side by either using JSTL or fn:escapeXml() (or a custom EL resolver, but that's definitely not the normal approach). The future code maintainers will be greatly thankful.

提交回复
热议问题