...
However, the attempt to implement the remember-me functionality is insecure because an attacker with access to the client machine can obtain this information directly on the client. This code also violates MSC62-J. Store passwords using a hash function and MSC00-J. Use SSLSocket rather than Socket for secure data exchange, because it transmits the password unencrypted in the response. The client may also have transmitted the password in clear unless it encrypted the password or uses HTTPS.
Compliant Solution (Session)
This compliant solution implements the remember-me functionality by storing the user name and a secure random string in the cookie. It also maintains state in the session using HttpSession
:.
Code Block | ||
---|---|---|
| ||
protected void doPost(HttpServletRequest request, HttpServletResponse response) { // Validate input (omitted) String username = request.getParameter("username"); char[] password = request.getParameter("password").toCharArray(); boolean rememberMe = Boolean.valueOf(request.getParameter("rememberme")); LoginService loginService = new LoginServiceImpl(); boolean validated = false; if (rememberMe) { if (request.getCookies()[0] != null && request.getCookies()[0].getValue() != null) { String[] value = request.getCookies()[0].getValue().split(";"); if (value.length != 2) { // Set error and return } if (!loginService.mappingExists(value[0], value[1])) { // (username, random) pair is checked // Set error and return } } else { validated = loginService.isUserValid(username, password); if (!validated) { // Set error and return } } String newRandom = loginService.getRandomString(); // Reset the random every time loginService.mapUserForRememberMe(username, newRandom); HttpSession session = request.getSession(); session.invalidate(); session = request.getSession(true); // Set session timeout to 15 minutes session.setMaxInactiveInterval(60 * 15); // Store user attribute and a random attribute in session scope session.setAttribute("user", loginService.getUsername()); Cookie loginCookie = new Cookie("rememberme", username + ";" + newRandom); loginCookie.setHttpOnly(true); loginCookie.setSecure(true); response.addCookie(loginCookie); // ... Forward to welcome page } else { // No remember-me functionality selected // ... Authenticate using isUserValid() and if failed, set error } Arrays.fill(password, ' '); } |
...