Versions Compared

Key

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

Cookies are an essential part of any web application and can be used for a number of different purposes such as user authentication. A cookie is a small piece of data that is set by a web server's response that will be stored for a certain period of time on the requesting userclient's computer. After a cookie has been set, all of the information within it will be sent in all subsequent requests to the cookie domain. Because of this, the information within a cookie is not secure and can be retrieved through a variety of attacks such as cross-site scripting (XSS) or man-in-the-middle attacks. As a result, it is important that the server does not set a cookie that contains excess or sensitive information about a user. This includes, but is not limited to, user names, passwords, password hashes, credit cards, and any personally identifiable information about the user.

...

Code Block
bgColor#FFcccc
private String login(HttpServletRequest request, HttpServletResponse response) {
  List<String> errors = new ArrayList<String>();
  request.setAttribute("errors", errors);
        
  String username = request.getParameter("username");
  String password = request.getParameter("password");
        
  // Basic input validation
  if(username.matches("[\\w]*")) errors.add("Incorrect user name format.");
  if(password.matches("[\\w]*")) errors.add("Incorrect password format.");
        
  if(errors.size() > 0) return "error.jsp";
        
  UserBean dbUser = this.userDAO.lookup(username);
  if(!dbUser.checkPassword(password)) {
    errors.add("Passwords do not match.");
    return "error.jsp";
  }
        
  Cookie userCookie = new Cookie("userusername", username); // Create a cookie that contains the username
  Cookie passCookie = new Cookie("password", password); // Creates a cookie that contains the password
  response.addCookie(userCookie); // Send the cookie information to the client
  response.addCookie(passCookie);

  return "welcome.jsp";
}

Note that the above non compliant code example stores the user name within the cookie for authentication purposes. This particular code example is insecure because an attacker could possibly perform a cross-site scripting attack or sniff packets to find the user name within the cookie. If an attacker had the user name of a particular individual, they could forget their own cookie containing the user name and easily gain access to their account within the web application assuming that the application uses the cookie to identify a user.

...