Cookies are an essential part of any web application; they are used for many purposes, including user authentication. A cookie is a small piece of data that is set by a web server's response that is and stored for a certain period of time on the client's computer. After a cookie is set, all of the information within is sent in all subsequent requests to the cookie domain include all of the information held by the cookie. Consequently, the information within a cookie is insecure; it is vulnerable to cross-site scripting (XSS) and man-in-the-middle attacks (among others). Servers must ensure that cookies lack excess or sensitive information about users. A partial list of such information includes user names, passwords, password hashes, credit cards, and any personally identifiable information about the user.
...
This compliant solution stores user information using the HttpSesssion
class within the javax.servlet.http
package. Because HttpSession
objects are server-side, an attacker cannot use cross-site scripting or man-in-the-middle attacks to directly gain direct access to the session information. Rather, the cookie stores a session id that refers to the user's HttpSession
object stored on the server. Consequently, the attacker cannot gain access to the user's account details without first gaining access to the session id.
Code Block | ||
---|---|---|
| ||
public class InsecureServlet extends HttpServlet { private UserDAO userDAO; // ... private String login(HttpServletRequest request) { List<String> errors = new ArrayList<String>(); request.setAttribute("errors", errors); String username = request.getParameter("username"); char[] password = request.getParameter("password").toCharArray(); // Basic input validation if (!username.matches("[\\w]*") || !password.toString().matches("[\\w]*")) { errors.add("Incorrect user name or password format."); return "error.jsp"; } UserBean dbUser = this.userDAO.lookup(username); if (!dbUser.checkPassword(password)) { errors.add("Passwords do not match."); return "error.jsp"; } HttpSession session = request.getSession(); // Invalidate old session id session.invalidate(); // Generate new session id session = request.getSession(true); // Set session timeout to one hour session.setMaxInactiveInterval(60*60); // Store user bean within the session session.setAttribute("user", dbUser.getUsername()); // Clear password char array Arrays.fill(password, ' '); return "welcome.jsp"; } } |
This solution also invalidates avoids session fixation attacks [OWASP 2009] by invalidating the current session and creates creating a new session to avoid session fixation attacks; see [OWASP 2009]. The solution . It also reduces the window in which an attacker could perform a session hijacking attack by setting the session timeout to one.
...