Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Always generate new session id on login #5288

Merged
merged 2 commits into from
Jun 25, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -45,15 +45,15 @@ public HttpSession createNewAuthenticatedSession(final HttpServletRequest reques
}

final HttpSession newSession = request.getSession(true);
request.changeSessionId();

newSession.setAttribute(SessionAttributes.AUTORIZED_USER.getValue(), user);
updateLastActivity(newSession);

final Optional<Integer> credentialsHash = userAdminHelper.getCredentialsHash(user);

if (credentialsHash.isPresent()) {
newSession.setAttribute(SessionAttributes.CREDENTIALS_HASH.getValue(),
credentialsHash.get());
newSession.setAttribute(SessionAttributes.CREDENTIALS_HASH.getValue(), credentialsHash.get());
}

getOrCreateXsrfToken(newSession);
Expand Down Expand Up @@ -95,8 +95,7 @@ public Optional<Principal> getPrincipalFromSession(final HttpSession session) {
}

public boolean credentialsChanged(final HttpSession session, final String userName) {
return !Objects.equals(
session.getAttribute(SessionAttributes.CREDENTIALS_HASH.getValue()),
return !Objects.equals(session.getAttribute(SessionAttributes.CREDENTIALS_HASH.getValue()),
userAdminHelper.getCredentialsHash(userName).orElse(null));
}

Expand All @@ -123,8 +122,7 @@ public boolean isSessionExpired(final HttpSession session, final int maxInactive
}

public Optional<String> getXsrfToken(final HttpSession httpSession) {
return Optional
.ofNullable(httpSession.getAttribute(SessionAttributes.XSRF_TOKEN.getValue()))
return Optional.ofNullable(httpSession.getAttribute(SessionAttributes.XSRF_TOKEN.getValue()))
.flatMap(t -> t instanceof String ? Optional.of((String) t) : Optional.empty());
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*******************************************************************************
* Copyright (c) 2023 Eurotech and/or its affiliates and others
* Copyright (c) 2023, 2024 Eurotech and/or its affiliates and others
*
* This program and the accompanying materials are made
* available under the terms of the Eclipse Public License 2.0
Expand Down Expand Up @@ -84,8 +84,7 @@ public void setOptions(final RestServiceOptions options) {
@Path(SessionRestServiceConstants.LOGIN_PASSWORD_PATH)
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public AuthenticationResponseDTO authenticateWithUsernameAndPassword(
final UsernamePasswordDTO usernamePassword,
public AuthenticationResponseDTO authenticateWithUsernameAndPassword(final UsernamePasswordDTO usernamePassword,
@Context final HttpServletRequest request) {

if (!options.isSessionManagementEnabled() || !options.isPasswordAuthEnabled()) {
Expand All @@ -100,8 +99,7 @@ public AuthenticationResponseDTO authenticateWithUsernameAndPassword(

try {

this.userAdminHelper.verifyUsernamePassword(usernamePassword.getUsername(),
usernamePassword.getPassword());
this.userAdminHelper.verifyUsernamePassword(usernamePassword.getUsername(), usernamePassword.getPassword());

final HttpSession session = this.restSessionHelper.createNewAuthenticatedSession(request,
usernamePassword.getUsername());
Expand All @@ -117,8 +115,12 @@ public AuthenticationResponseDTO authenticateWithUsernameAndPassword(
return response;

} catch (final AuthenticationException e) {
invalidateCurrentSession(request);
handleAuthenticationException(e);
throw new IllegalStateException("unreachable");
} catch (final Exception e) {
invalidateCurrentSession(request);
throw e;
}
}

Expand All @@ -131,21 +133,27 @@ public AuthenticationResponseDTO authenticateWithCertificate(@Context final Http
throw new WebApplicationException(Status.NOT_FOUND);
}

final CertificateAuthenticationProvider certificateAuthProvider = new CertificateAuthenticationProvider(
userAdminHelper);
try {

final Optional<Principal> principal = certificateAuthProvider.authenticate(requestContext,
"Create session via certificate authentication");
final CertificateAuthenticationProvider certificateAuthProvider = new CertificateAuthenticationProvider(
userAdminHelper);

if (principal.isPresent()) {
this.restSessionHelper.createNewAuthenticatedSession(request,
principal.get().getName());
} else {
throw DefaultExceptionHandler.buildWebApplicationException(Status.UNAUTHORIZED,
"Certificate authentication failed");
}
final Optional<Principal> principal = certificateAuthProvider.authenticate(requestContext,
"Create session via certificate authentication");

if (principal.isPresent()) {
this.restSessionHelper.createNewAuthenticatedSession(request, principal.get().getName());
} else {

return buildAuthenticationResponse(principal.get().getName());
throw DefaultExceptionHandler.buildWebApplicationException(Status.UNAUTHORIZED,
"Certificate authentication failed");
}

return buildAuthenticationResponse(principal.get().getName());
} catch (final Exception e) {
invalidateCurrentSession(request);
throw e;
}
}

@GET
Expand All @@ -159,13 +167,11 @@ public XsrfTokenDTO getXSRFToken(@Context final HttpServletRequest request,
final Optional<HttpSession> session = this.restSessionHelper.getExistingSession(request);

if (!session.isPresent()) {
throw DefaultExceptionHandler.buildWebApplicationException(Status.UNAUTHORIZED,
INVALID_SESSION_MESSAGE);
throw DefaultExceptionHandler.buildWebApplicationException(Status.UNAUTHORIZED, INVALID_SESSION_MESSAGE);
}

if (!this.restSessionHelper.getCurrentPrincipal(requestContext).isPresent()) {
throw DefaultExceptionHandler.buildWebApplicationException(Status.UNAUTHORIZED,
INVALID_SESSION_MESSAGE);
throw DefaultExceptionHandler.buildWebApplicationException(Status.UNAUTHORIZED, INVALID_SESSION_MESSAGE);
}

return new XsrfTokenDTO(this.restSessionHelper.getOrCreateXsrfToken(session.get()));
Expand All @@ -174,8 +180,7 @@ public XsrfTokenDTO getXSRFToken(@Context final HttpServletRequest request,
@POST
@Path(SessionRestServiceConstants.CHANGE_PASSWORD_PATH)
public void updateUserPassword(@Context final ContainerRequestContext requestContext,
@Context final HttpServletRequest request,
final UpdatePasswordDTO passwordUpdate) {
@Context final HttpServletRequest request, final UpdatePasswordDTO passwordUpdate) {

passwordUpdate.validate();

Expand All @@ -196,13 +201,15 @@ public void updateUserPassword(@Context final ContainerRequestContext requestCon

this.userAdminHelper.changeUserPassword(username.get(), passwordUpdate.getNewPassword());

final Optional<HttpSession> session = this.restSessionHelper.getExistingSession(request);
final HttpSession session = this.restSessionHelper.createNewAuthenticatedSession(request, newPassword);
this.restSessionHelper.unlockSession(session);

if (session.isPresent()) {
this.restSessionHelper.unlockSession(session.get());
}
} catch (final AuthenticationException e) {
invalidateCurrentSession(request);
handleAuthenticationException(e);
} catch (final Exception e) {
invalidateCurrentSession(request);
throw e;
}
}

Expand All @@ -215,14 +222,12 @@ public void logout(@Context final HttpServletRequest request, @Context final Htt
}

if (!this.restSessionHelper.getCurrentPrincipal(requestContext).isPresent()) {
throw DefaultExceptionHandler.buildWebApplicationException(Status.UNAUTHORIZED,
INVALID_SESSION_MESSAGE);
throw DefaultExceptionHandler.buildWebApplicationException(Status.UNAUTHORIZED, INVALID_SESSION_MESSAGE);
}

this.restSessionHelper.logout(request, response);

auditLogger.info("{} Rest - Success - Logout succeeded",
AuditContext.currentOrInternal());
auditLogger.info("{} Rest - Success - Logout succeeded", AuditContext.currentOrInternal());
}

@GET
Expand All @@ -237,14 +242,12 @@ public IdentityInfoDTO getCurrentIdentityInfo(@Context final ContainerRequestCon
final Optional<Principal> currentPrincipal = this.restSessionHelper.getCurrentPrincipal(requestContext);

if (!currentPrincipal.isPresent()) {
throw DefaultExceptionHandler.buildWebApplicationException(Status.UNAUTHORIZED,
INVALID_SESSION_MESSAGE);
throw DefaultExceptionHandler.buildWebApplicationException(Status.UNAUTHORIZED, INVALID_SESSION_MESSAGE);
}

final String identityName = currentPrincipal.get().getName();
final Set<String> permissions = this.userAdminHelper.getIdentityPermissions(identityName);
final boolean needsPasswordChange = this.userAdminHelper
.isPasswordChangeRequired(identityName);
final boolean needsPasswordChange = this.userAdminHelper.isPasswordChangeRequired(identityName);

return new IdentityInfoDTO(identityName, needsPasswordChange, permissions);
}
Expand All @@ -269,8 +272,7 @@ public AuthenticationInfoDTO getAuthenticationMethodInfo() {
final Map<String, Object> httpServiceConfig = ConfigurationAdminHelper
.loadHttpServiceConfigurationProperties(configAdmin);

final Set<Integer> httpsClientAuthPorts = ConfigurationAdminHelper
.getHttpsMutualAuthPorts(httpServiceConfig);
final Set<Integer> httpsClientAuthPorts = ConfigurationAdminHelper.getHttpsMutualAuthPorts(httpServiceConfig);

if (!httpsClientAuthPorts.isEmpty()) {
return new AuthenticationInfoDTO(isPasswordAuthEnabled, true, httpsClientAuthPorts, message);
Expand Down Expand Up @@ -299,8 +301,7 @@ private void validatePasswordStrength(final String newPassword) {
}

private AuthenticationResponseDTO buildAuthenticationResponse(final String username) {
final boolean needsPasswordChange = this.userAdminHelper
.isPasswordChangeRequired(username);
final boolean needsPasswordChange = this.userAdminHelper.isPasswordChangeRequired(username);

return new AuthenticationResponseDTO(needsPasswordChange);
}
Expand All @@ -309,23 +310,29 @@ private void handleAuthenticationException(final AuthenticationException e) {
final AuditContext auditContext = AuditContext.currentOrInternal();

switch (e.getReason()) {
case INCORRECT_PASSWORD:
case USER_NOT_FOUND:
auditLogger.warn(AUDIT_FORMAT_STRING, auditContext, BAD_USERNAME_OR_PASSWORD_MESSAGE);
throw DefaultExceptionHandler.buildWebApplicationException(Status.UNAUTHORIZED,
BAD_USERNAME_OR_PASSWORD_MESSAGE);
case PASSWORD_CHANGE_WITH_SAME_PASSWORD:
auditLogger.warn(AUDIT_FORMAT_STRING, auditContext, PASSWORD_CHANGE_SAME_PASSWORD_MESSAGE);
throw DefaultExceptionHandler.buildWebApplicationException(Status.BAD_REQUEST,
PASSWORD_CHANGE_SAME_PASSWORD_MESSAGE);
case USER_NOT_IN_ROLE:
auditLogger.warn(AUDIT_FORMAT_STRING, auditContext, IDENTITY_NOT_IN_ROLE_MESSAGE);
throw DefaultExceptionHandler.buildWebApplicationException(Status.FORBIDDEN,
IDENTITY_NOT_IN_ROLE_MESSAGE);
default:
throw DefaultExceptionHandler.buildWebApplicationException(Status.INTERNAL_SERVER_ERROR,
"An internal error occurred");
case INCORRECT_PASSWORD:
case USER_NOT_FOUND:
auditLogger.warn(AUDIT_FORMAT_STRING, auditContext, BAD_USERNAME_OR_PASSWORD_MESSAGE);
throw DefaultExceptionHandler.buildWebApplicationException(Status.UNAUTHORIZED,
BAD_USERNAME_OR_PASSWORD_MESSAGE);
case PASSWORD_CHANGE_WITH_SAME_PASSWORD:
auditLogger.warn(AUDIT_FORMAT_STRING, auditContext, PASSWORD_CHANGE_SAME_PASSWORD_MESSAGE);
throw DefaultExceptionHandler.buildWebApplicationException(Status.BAD_REQUEST,
PASSWORD_CHANGE_SAME_PASSWORD_MESSAGE);
case USER_NOT_IN_ROLE:
auditLogger.warn(AUDIT_FORMAT_STRING, auditContext, IDENTITY_NOT_IN_ROLE_MESSAGE);
throw DefaultExceptionHandler.buildWebApplicationException(Status.FORBIDDEN, IDENTITY_NOT_IN_ROLE_MESSAGE);
default:
throw DefaultExceptionHandler.buildWebApplicationException(Status.INTERNAL_SERVER_ERROR,
"An internal error occurred");
}
}

private void invalidateCurrentSession(final HttpServletRequest request) {
final HttpSession currentSession = request.getSession(false);

if (currentSession != null) {
currentSession.invalidate();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -377,7 +377,10 @@ public HttpSession createNewSession(final HttpServletRequest request) {
existingSession.invalidate();
}

return createSession(request);
final HttpSession newSession = createSession(request);
request.changeSessionId();

return newSession;
}

public HttpSession createSession(final HttpServletRequest request) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,8 @@ public void updatePassword(GwtXSRFToken xsrfToken, String oldPassword, String ne
throw new GwtKuraException(GwtKuraErrorCode.INTERNAL_ERROR);
}

setAuthenticated(session, username);
final HttpSession newSession = Console.instance().createNewSession(request);
setAuthenticated(newSession, username);
}

private String getSessionUsername(HttpSession session) throws GwtKuraException {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,12 +57,6 @@ public SslAuthenticationServlet(final String redirectPath, final UserManager use
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

final Console console = Console.instance();
final HttpSession session = console.createSession(req);

if (console.getUsername(session).isPresent()) {
sendRedirect(resp, redirectPath);
return;
}

final AuditContext auditContext = Console.instance().initAuditContext(req);

Expand Down Expand Up @@ -95,6 +89,8 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws Se

auditContext.getProperties().put(AuditConstants.KEY_IDENTITY.getValue(), commonName);

final HttpSession session = console.createNewSession(req);

console.setAuthenticated(session, commonName, auditContext);
auditContext.getProperties().put("session.id", GwtServerUtil.getSessionIdHash(session));

Expand All @@ -104,6 +100,12 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws Se
sendRedirect(resp, redirectPath);

} catch (final Exception e) {
final HttpSession existingSession = req.getSession(false);

if (existingSession != null) {
existingSession.invalidate();
}

auditLogger.info("{} UI Login - Failure - Certificate login", auditContext);
logger.warn("certificate authentication failed", e);
sendUnauthorized(resp);
Expand Down
Loading
Loading