request.getParameter protect against XSS : what is the best practice?

14,777

I am not saying this is the best approach, but:

Can i somehow override the function 'request.getParameter' so it defaults to stringescapeutils.escapehtml(request.getParameter("")); ?

is easily achievable using servlet filter and by wrapping HTTP servlet request. This approach is described in How to add validation logic to HttpServletRequest.

However the most comprehensive approach is to escape when displaying, preferably only in JSP. Too bad you also generate HTML in servlets. See: Java 5 HTML escaping To Prevent XSS.

Share:
14,777
user1194465
Author by

user1194465

Updated on June 28, 2022

Comments

  • user1194465
    user1194465 over 1 year

    I've inherited a large code base of 1000+ JSP-files that is full of XSS-vulnerabilities.

    The code is full of

    <%= request.getParameter("theparam")%>
    

    and

    out.println("some stuff before"+request.getParameter("theparam")+"and some other stuff");
    

    and

    String myVar = request.getParameter("theparam");
    out.println(myVar);
    

    I want to secure all files without having to go through all of them individually.

    What is my best approach ?

    • Do a 'replace all' on "request.getParameter("xx")" to "StringEscapeUtils.escapeHtml(request.getParameter("xx")) on all source files ?

    • Can i somehow override the function 'request.getParameter' so it defaults to stringescapeutils.escapehtml(request.getParameter("")); ?

    thnx

  • user1194465
    user1194465 over 11 years
    Anyone a regexp gury ? I want to replace all occurrences of request.getParameter("thischangesallthetime") to stringescapeutils.escapehtml(request.getParameter("")); Can i do it with a regular expression replace ?
  • Tomasz Nurkiewicz
    Tomasz Nurkiewicz over 11 years
    @user1194465: absolutely you can, but please post another question (maybe it's even more suited on superuser?) and follow-up here. Also I am not sure whether this is a good approach - you should escape parameters when showing, not when reading.
  • user1194465
    user1194465 over 11 years