spring-security

why AbstractSessionFixationProtectionStrategy use mutex when migrating session in Spring Security


this is source code of AbstractSessionFixationProtectionStrategy in Spring Security Framework, which defines the main method to migrate session as an abtract class, and I wonder why use mutex to get newSessionId?

@Override
    public void onAuthentication(Authentication authentication, HttpServletRequest request,
            HttpServletResponse response) {
        boolean hadSessionAlready = request.getSession(false) != null;
        if (!hadSessionAlready && !this.alwaysCreateSession) {
            // Session fixation isn't a problem if there's no session
            return;
        }
        // Create new session if necessary
        HttpSession session = request.getSession();
        if (hadSessionAlready && request.isRequestedSessionIdValid()) {
            String originalSessionId;
            String newSessionId;
            Object mutex = WebUtils.getSessionMutex(session);
            synchronized (mutex) { // why
                // We need to migrate to a new session
                originalSessionId = session.getId();
                session = applySessionFixation(request);
                newSessionId = session.getId();
            }
            if (originalSessionId.equals(newSessionId)) {
                this.logger.warn("Your servlet container did not change the session ID when a new session "
                        + "was created. You will not be adequately protected against session-fixation attacks");
            }
            else {
                if (this.logger.isDebugEnabled()) {
                    this.logger.debug(LogMessage.format("Changed session id from %s", originalSessionId));
                }
            }
            onSessionChange(originalSessionId, session, authentication);
        }
    }

if without synchronized block, what would happen


Solution

  • See SEC-2306: Fix Session Fixation logging race condition:

    Previously session fixation protection could output an incorrect warning that session fixation protection did not work.

    The code now synchronizes on WebUtils.getSessionMutex(..).

    See also: SEC-2306: Session Fixation protection can improperly log warning about not being protected