Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

  • In any Java servlet container, such as Apache Tomcat, HttpServlet is a singleton class (see MSC07-J. Prevent multiple instantiations of singleton objects for information related to singleton classes). Therefore, there can be only one instance of member variables, even if they are not declared static.
  • A servlet container is permitted to invoke the servlet from multiple threads. Consequently, accessing fields in the servlet can lead to data races.
  • If two clients initiate sessions with the servlet, the servlet can leak inforamtion information from one client to the other client.

...

In this noncompliant code example, the lastAddr field is static and is protected from concurrent access by a separate lock object, as is recommended by LCK00-J. Use private final lock objects to synchronize classes that may interact with untrusted code. This guarantees thread-safety in the servlet. However, the servlet can still return the email address provicded provided by a different session.

Code Block
bgColor#ffcccc
langjava
public class SampleServlet extends HttpServlet {
 
  private static String lastAddr = "nobody@nowhere.com";
  private static final Object lastAddrLock = new Object();

  public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws IOException, ServletException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    out.println("<html>");
 
    String emailAddr = request.getParameter("emailAddr");
 
    if (emailAddr != null) {
      out.println("Email Address::");
      out.println(sanitize(emailAddr));
      synchronized (lock) {
        out.println("<br>Previous Email Address::");
        out.println(sanitize(lastAddr));
      }
    };
 
    out.println("<p>");
    out.print("<form action=\"");
    out.print("SampleServlet\" ");
    out.println("method=POST>");
    out.println("Parameter:");
    out.println("<input type=text size=20 name=emailAddr>");
    out.println("<br>");
    out.println("<input type=submit>");
    out.println("</form>");
 
    synchronized (lock) {
      lastAddr = emailAddr;
    }
  }
 
  public void doPost(HttpServletRequest request, HttpServletResponse response)
    throws IOException, ServletException {
    doGet(request, response);
  }

  // Filter the specified message string for characters
  // that are sensitive in HTML.
  public static String sanitize(String message) {
    // ...
  }
}

...

 

...