Link Search Menu Expand Document

Broken Session Management in Java

Java servlets

Vulnerable Example

Upon successful authentication, the current session is not invalidated:

public void doAction(HttpServletRequest request, HttpServletResponse response) {
    String pwd = request.getParameter("j_password");
    String usr = request.getParameter("j_username");
    SessionUser user = persistenceController.loginUser(usr, pwd);
    String msg = "";
    try {
        if (user != null) {

            // XXX session not invalidated!

            request.getSession().setAttribute(Constants.USER, user);
            msg = messageGenerator.redirectMessage("/ok.html");
        } else {
            msg = messageGenerator.redirectMessage("/error.html");
        }

        PrintWriter out;
        out = response.getWriter();
        out.print(msg);
        out.flush();
    } catch (IOException e) {
        // ...
    }
}

The solution is to invalidate the current session, and then create a new session for the newly logged-in user:

request.getSession().invalidate();
request.getSession(true);

Vulnerable Example

In this example, upon logout, the session is not invalidated. The cookie value is only cleared in the user’s browser:

@Override
public void doAction(HttpServletRequest request, HttpServletResponse response) {
    Cookie cookie = new Cookie("JSESSIONID","LOGOFF");
    response.addCookie(cookie);

    // XXX session not invalidated!

    response.sendRedirect("/");
}

The solution is to invalidate the session:

request.getSession().invalidate();

Prevention

For Session Fixation exposures, invoke the invalidate method of the HttpSession class upon successful authentication of the user. Then create a new session by passing true to the getSession method of the HttpServletRequest class.

Third-party frameworks may have managed a solution to handle session management; make sure to learn how to invalidate the session by reading the reference documentation.

Make sure to invalidate the session upon logout by invoking the invalidate method of the HttpSession class.