0

If I append a script tag to a url in the browser the script executes and then the page loads. I want to avoid the execution of the script tag. I tried redirecting to the encoded url using servlet filter and owasp java encoder. The script is getting triggered first and then encoding happens. How do I prevent the script tag from executing?

Server: Tomcat v8.5

Browser: Chrome, Edge

Below is the code for the servlet filter

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    HttpServletRequest httpServletRequest = ((HttpServletRequest) request);
    String queryString = httpServletRequest.getQueryString();
    if (queryString.contains("script")) {
        HttpServletRequest modifiedRequest = new HttpServletRequestWrapper((httpServletRequest)) {
            @Override
            public String getRequestURI() {
                String encodedQueryString = Encode.forUri(httpServletRequest.getQueryString());
                return httpServletRequest.getRequestURI() + "?" + encodedQueryString;
            }
        };
        chain.doFilter(modifiedRequest, response);
    } else {
        chain.doFilter(request, response);
    }
}
  • 2
    XSS doesn't happen in URLs, it happens in HTML output. So that's the place where you need to prevent it, by encoding URLs and other content properly. Please edit your question to show the code where the URL ends up incorrectly encoded in the HTML output. – Thomas Dec 21 '22 at 08:30
  • You do not need to escape them during request processing. You need to escape them during generating the HTML code. See abovelinked duplicate. – BalusC Dec 21 '22 at 08:30
  • @BalusC The issue is if I add a script tag to the url in the browser the script executes and then the page loads. I want to avoid the execution of the script tag. So I tried using the above code to catch the query string and encode it to prevent script tag from executing but it didn't work. How can I prevent this from happening? Is there a way to catch the script tag? – Saikrishna Mahankali Dec 22 '22 at 13:32
  • The script only executes if it's embedded in a HTML page. The abovelinked duplicate shows how to prevent this from happening. – BalusC Dec 22 '22 at 13:38
  • @BalusC If I encode the HTML response in my servlet filter will it avoid the execution of the script tag? – Saikrishna Mahankali Dec 23 '22 at 04:04

0 Answers0