use of password.pwm.ldap.auth.SessionAuthenticator in project pwm by pwm-project.
the class TokenService method processUserEnteredCode.
public TokenPayload processUserEnteredCode(final PwmSession pwmSession, final UserIdentity sessionUserIdentity, final TokenType tokenType, final String userEnteredCode, final TokenEntryType tokenEntryType) throws PwmOperationalException, PwmUnrecoverableException {
try {
final TokenPayload tokenPayload = processUserEnteredCodeImpl(pwmSession, sessionUserIdentity, tokenType, userEnteredCode);
if (tokenPayload.getDestination() != null && !StringUtil.isEmpty(tokenPayload.getDestination().getValue())) {
pwmApplication.getIntruderManager().clear(RecordType.TOKEN_DEST, tokenPayload.getDestination().getValue());
}
markTokenAsClaimed(tokenMachine.keyFromKey(userEnteredCode), pwmSession, tokenPayload);
return tokenPayload;
} catch (Exception e) {
final ErrorInformation errorInformation;
if (e instanceof PwmException) {
errorInformation = ((PwmException) e).getErrorInformation();
} else {
errorInformation = new ErrorInformation(PwmError.ERROR_TOKEN_INCORRECT, e.getMessage());
}
LOGGER.debug(pwmSession, errorInformation.toDebugStr());
if (sessionUserIdentity != null && tokenEntryType == TokenEntryType.unauthenticated) {
final SessionAuthenticator sessionAuthenticator = new SessionAuthenticator(pwmApplication, pwmSession, null);
sessionAuthenticator.simulateBadPassword(sessionUserIdentity);
pwmApplication.getIntruderManager().convenience().markUserIdentity(sessionUserIdentity, pwmSession);
}
pwmApplication.getIntruderManager().convenience().markAddressAndSession(pwmSession);
pwmApplication.getStatisticsManager().incrementValue(Statistic.RECOVERY_FAILURES);
throw new PwmOperationalException(errorInformation);
}
}
use of password.pwm.ldap.auth.SessionAuthenticator in project pwm by pwm-project.
the class ForgottenPasswordServlet method executeResetPassword.
private void executeResetPassword(final PwmRequest pwmRequest) throws ChaiUnavailableException, IOException, ServletException, PwmUnrecoverableException {
final PwmApplication pwmApplication = pwmRequest.getPwmApplication();
final PwmSession pwmSession = pwmRequest.getPwmSession();
final ForgottenPasswordBean forgottenPasswordBean = forgottenPasswordBean(pwmRequest);
if (!forgottenPasswordBean.getProgress().isAllPassed()) {
return;
}
final UserIdentity userIdentity = forgottenPasswordBean.getUserIdentity();
final ChaiUser theUser = pwmApplication.getProxiedChaiUser(userIdentity);
try {
// try unlocking user
theUser.unlockPassword();
LOGGER.trace(pwmSession, "unlock account succeeded");
} catch (ChaiOperationException e) {
final String errorMsg = "unable to unlock user " + theUser.getEntryDN() + " error: " + e.getMessage();
final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_UNLOCK_FAILURE, errorMsg);
LOGGER.error(pwmSession, errorInformation.toDebugStr());
}
try {
final SessionAuthenticator sessionAuthenticator = new SessionAuthenticator(pwmApplication, pwmSession, PwmAuthenticationSource.FORGOTTEN_PASSWORD);
sessionAuthenticator.authUserWithUnknownPassword(userIdentity, AuthenticationType.AUTH_FROM_PUBLIC_MODULE);
pwmSession.getLoginInfoBean().getAuthFlags().add(AuthenticationType.AUTH_FROM_PUBLIC_MODULE);
LOGGER.info(pwmSession, "user successfully supplied password recovery responses, forward to change password page: " + theUser.getEntryDN());
// mark the event log
pwmApplication.getAuditManager().submit(AuditEvent.RECOVER_PASSWORD, pwmSession.getUserInfo(), pwmSession);
// add the post-forgotten password actions
addPostChangeAction(pwmRequest, userIdentity);
// mark user as requiring a new password.
pwmSession.getLoginInfoBean().getLoginFlags().add(LoginInfoBean.LoginFlag.forcePwChange);
// redirect user to change password screen.
pwmRequest.sendRedirect(PwmServletDefinition.PublicChangePassword.servletUrlName());
} catch (PwmUnrecoverableException e) {
LOGGER.warn(pwmSession, "unexpected error authenticating during forgotten password recovery process user: " + e.getMessage());
pwmRequest.respondWithError(e.getErrorInformation());
} finally {
clearForgottenPasswordBean(pwmRequest);
}
}
use of password.pwm.ldap.auth.SessionAuthenticator in project pwm by pwm-project.
the class OAuthConsumerServlet method processAction.
@Override
@SuppressWarnings("checkstyle:MethodLength")
protected void processAction(final PwmRequest pwmRequest) throws ServletException, IOException, PwmUnrecoverableException {
final PwmApplication pwmApplication = pwmRequest.getPwmApplication();
final Configuration config = pwmRequest.getConfig();
final PwmSession pwmSession = pwmRequest.getPwmSession();
final boolean userIsAuthenticated = pwmSession.isAuthenticated();
final Optional<OAuthRequestState> oAuthRequestState = OAuthMachine.readOAuthRequestState(pwmRequest);
final OAuthUseCase oAuthUseCaseCase = oAuthRequestState.isPresent() ? oAuthRequestState.get().getoAuthState().getUseCase() : OAuthUseCase.Authentication;
LOGGER.trace(pwmRequest, "processing oauth return request, useCase=" + oAuthUseCaseCase + ", incoming oAuthRequestState=" + (oAuthRequestState.isPresent() ? JsonUtil.serialize(oAuthRequestState.get()) : "none"));
// make sure it's okay to be processing this request.
switch(oAuthUseCaseCase) {
case Authentication:
{
if (!userIsAuthenticated && !pwmSession.getSessionStateBean().isOauthInProgress()) {
if (oAuthRequestState.isPresent()) {
final String nextUrl = oAuthRequestState.get().getoAuthState().getNextUrl();
LOGGER.debug(pwmSession, "received unrecognized oauth response, ignoring authcode and redirecting to embedded next url: " + nextUrl);
pwmRequest.sendRedirect(nextUrl);
return;
}
final String errorMsg = "oauth consumer reached, but oauth authentication has not yet been initiated.";
final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_OAUTH_ERROR, errorMsg);
pwmRequest.respondWithError(errorInformation);
LOGGER.error(pwmSession, errorMsg);
return;
}
}
break;
default:
// for non-auth requests its okay to continue
break;
}
// check if there is an "error" on the request sent from the oauth server., if there is then halt.
{
final String oauthRequestError = pwmRequest.readParameterAsString("error");
if (oauthRequestError != null && !oauthRequestError.isEmpty()) {
final String errorMsg = "incoming request from remote oauth server is indicating an error: " + oauthRequestError;
final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_OAUTH_ERROR, errorMsg, "Remote Error: " + oauthRequestError, null);
LOGGER.error(pwmSession, errorMsg);
pwmRequest.respondWithError(errorInformation);
return;
}
}
// check if user is already authenticated - shouldn't be in nominal usage.
if (userIsAuthenticated) {
switch(oAuthUseCaseCase) {
case Authentication:
LOGGER.debug(pwmSession, "oauth consumer reached, but user is already authenticated; will proceed and verify authcode matches current user identity.");
break;
case ForgottenPassword:
final String errorMsg = "oauth consumer reached via " + OAuthUseCase.ForgottenPassword + ", but user is already authenticated";
final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_OAUTH_ERROR, errorMsg);
pwmRequest.respondWithError(errorInformation);
LOGGER.error(pwmSession, errorMsg);
return;
default:
JavaHelper.unhandledSwitchStatement(oAuthUseCaseCase);
}
}
// mark the inprogress flag to false, if we get this far and fail user needs to start over.
pwmSession.getSessionStateBean().setOauthInProgress(false);
if (!oAuthRequestState.isPresent()) {
final String errorMsg = "state parameter is missing from oauth request";
final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_OAUTH_ERROR, errorMsg);
LOGGER.error(pwmSession, errorMsg);
pwmRequest.respondWithError(errorInformation);
return;
}
final OAuthState oauthState = oAuthRequestState.get().getoAuthState();
final OAuthSettings oAuthSettings = makeOAuthSettings(pwmRequest, oauthState);
final OAuthMachine oAuthMachine = new OAuthMachine(oAuthSettings);
// make sure request was initiated in users current session
if (!oAuthRequestState.get().isSessionMatch()) {
try {
switch(oAuthUseCaseCase) {
case Authentication:
LOGGER.debug(pwmSession, "oauth consumer reached but response is not for a request issued during the current session," + " will redirect back to oauth server for verification update");
final String nextURL = oauthState.getNextUrl();
oAuthMachine.redirectUserToOAuthServer(pwmRequest, nextURL, null, null);
return;
case ForgottenPassword:
LOGGER.debug(pwmSession, "oauth consumer reached but response is not for a request issued during the current session," + " will redirect back to forgotten password servlet");
pwmRequest.sendRedirect(PwmServletDefinition.ForgottenPassword);
return;
default:
JavaHelper.unhandledSwitchStatement(oAuthUseCaseCase);
}
} catch (PwmUnrecoverableException e) {
final String errorMsg = "unexpected error redirecting user to oauth page: " + e.toString();
final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_OAUTH_ERROR, errorMsg);
setLastError(pwmRequest, errorInformation);
LOGGER.error(errorInformation.toDebugStr());
}
}
final String requestCodeStr = pwmRequest.readParameterAsString(config.readAppProperty(AppProperty.HTTP_PARAM_OAUTH_CODE));
LOGGER.trace(pwmSession, "received code from oauth server: " + requestCodeStr);
final OAuthResolveResults resolveResults;
try {
resolveResults = oAuthMachine.makeOAuthResolveRequest(pwmRequest, requestCodeStr);
} catch (PwmException e) {
final String errorMsg = "unexpected error communicating with oauth server: " + e.toString();
final ErrorInformation errorInformation = new ErrorInformation(e.getError(), errorMsg);
setLastError(pwmRequest, errorInformation);
LOGGER.error(errorInformation.toDebugStr());
return;
}
if (resolveResults == null || resolveResults.getAccessToken() == null || resolveResults.getAccessToken().isEmpty()) {
final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_OAUTH_ERROR, "browser redirect from oauth server did not include an access token");
LOGGER.error(pwmRequest, errorInformation);
pwmRequest.respondWithError(errorInformation);
return;
}
if (resolveResults.getExpiresSeconds() > 0) {
if (resolveResults.getRefreshToken() == null || resolveResults.getRefreshToken().isEmpty()) {
final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_OAUTH_ERROR, "oauth server gave expiration for access token, but did not provide a refresh token");
LOGGER.error(pwmRequest, errorInformation);
pwmRequest.respondWithError(errorInformation);
return;
}
}
final String oauthSuppliedUsername;
{
final String getAttributeResponseBodyStr = oAuthMachine.makeOAuthGetAttributeRequest(pwmRequest, resolveResults.getAccessToken());
final Map<String, String> getAttributeResultValues = JsonUtil.deserializeStringMap(getAttributeResponseBodyStr);
oauthSuppliedUsername = getAttributeResultValues.get(oAuthSettings.getDnAttributeName());
if (oauthSuppliedUsername == null || oauthSuppliedUsername.isEmpty()) {
final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_OAUTH_ERROR, "OAuth server did not respond with an username attribute value");
LOGGER.error(pwmRequest, errorInformation);
pwmRequest.respondWithError(errorInformation);
return;
}
}
LOGGER.debug(pwmSession, "received user login id value from OAuth server: " + oauthSuppliedUsername);
if (oAuthUseCaseCase == OAuthUseCase.ForgottenPassword) {
redirectToForgottenPasswordServlet(pwmRequest, oauthSuppliedUsername);
return;
}
if (userIsAuthenticated) {
try {
final UserSearchEngine userSearchEngine = pwmApplication.getUserSearchEngine();
final UserIdentity resolvedIdentity = userSearchEngine.resolveUsername(oauthSuppliedUsername, null, null, pwmSession.getLabel());
if (resolvedIdentity != null && resolvedIdentity.canonicalEquals(pwmSession.getUserInfo().getUserIdentity(), pwmApplication)) {
LOGGER.debug(pwmSession, "verified incoming oauth code for already authenticated session does resolve to same as logged in user");
} else {
final String errorMsg = "incoming oauth code for already authenticated session does not resolve to same as logged in user ";
final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_OAUTH_ERROR, errorMsg);
LOGGER.error(pwmSession, errorMsg);
pwmRequest.respondWithError(errorInformation);
pwmSession.unauthenticateUser(pwmRequest);
return;
}
} catch (PwmOperationalException e) {
final String errorMsg = "error while examining incoming oauth code for already authenticated session: " + e.getMessage();
final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_OAUTH_ERROR, errorMsg);
LOGGER.error(pwmSession, errorMsg);
pwmRequest.respondWithError(errorInformation);
return;
}
}
try {
if (!userIsAuthenticated) {
final SessionAuthenticator sessionAuthenticator = new SessionAuthenticator(pwmApplication, pwmSession, PwmAuthenticationSource.OAUTH);
sessionAuthenticator.authUserWithUnknownPassword(oauthSuppliedUsername, AuthenticationType.AUTH_WITHOUT_PASSWORD);
}
// recycle the session to prevent session fixation attack.
pwmRequest.getPwmSession().getSessionStateBean().setSessionIdRecycleNeeded(true);
// forward to nextUrl
final String nextUrl = oauthState.getNextUrl();
LOGGER.debug(pwmSession, "oauth authentication completed, redirecting to originally requested URL: " + nextUrl);
pwmRequest.sendRedirect(nextUrl);
} catch (PwmException e) {
LOGGER.error(pwmSession, "error during OAuth authentication attempt: " + e.getMessage());
final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_OAUTH_ERROR, e.getMessage());
pwmRequest.respondWithError(errorInformation);
return;
}
LOGGER.trace(pwmSession, "OAuth login sequence successfully completed");
}
use of password.pwm.ldap.auth.SessionAuthenticator in project pwm by pwm-project.
the class ActivateUserUtils method activateUser.
@SuppressFBWarnings("SE_BAD_FIELD")
static void activateUser(final PwmRequest pwmRequest, final UserIdentity userIdentity) throws ChaiUnavailableException, PwmUnrecoverableException, PwmOperationalException {
final PwmApplication pwmApplication = pwmRequest.getPwmApplication();
final PwmSession pwmSession = pwmRequest.getPwmSession();
final Configuration config = pwmApplication.getConfig();
final ChaiUser theUser = pwmApplication.getProxiedChaiUser(userIdentity);
if (config.readSettingAsBoolean(PwmSetting.ACTIVATE_USER_UNLOCK)) {
try {
theUser.unlockPassword();
} catch (ChaiOperationException e) {
final String errorMsg = "error unlocking user " + userIdentity + ": " + e.getMessage();
final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_ACTIVATION_FAILURE, errorMsg);
throw new PwmOperationalException(errorInformation);
}
}
try {
{
// execute configured actions
LOGGER.debug(pwmSession.getLabel(), "executing configured pre-actions to user " + theUser.getEntryDN());
final List<ActionConfiguration> configValues = config.readSettingAsAction(PwmSetting.ACTIVATE_USER_PRE_WRITE_ATTRIBUTES);
if (configValues != null && !configValues.isEmpty()) {
final MacroMachine macroMachine = MacroMachine.forUser(pwmRequest, userIdentity);
final ActionExecutor actionExecutor = new ActionExecutor.ActionExecutorSettings(pwmApplication, userIdentity).setExpandPwmMacros(true).setMacroMachine(macroMachine).createActionExecutor();
actionExecutor.executeActions(configValues, pwmRequest.getSessionLabel());
}
}
// authenticate the pwm session
final SessionAuthenticator sessionAuthenticator = new SessionAuthenticator(pwmApplication, pwmSession, PwmAuthenticationSource.USER_ACTIVATION);
sessionAuthenticator.authUserWithUnknownPassword(userIdentity, AuthenticationType.AUTH_FROM_PUBLIC_MODULE);
// ensure a change password is triggered
pwmSession.getLoginInfoBean().setType(AuthenticationType.AUTH_FROM_PUBLIC_MODULE);
pwmSession.getLoginInfoBean().getAuthFlags().add(AuthenticationType.AUTH_FROM_PUBLIC_MODULE);
pwmSession.getLoginInfoBean().getLoginFlags().add(LoginInfoBean.LoginFlag.forcePwChange);
// mark the event log
pwmApplication.getAuditManager().submit(AuditEvent.ACTIVATE_USER, pwmSession.getUserInfo(), pwmSession);
// update the stats bean
pwmApplication.getStatisticsManager().incrementValue(Statistic.ACTIVATED_USERS);
// send email or sms
sendPostActivationNotice(pwmRequest);
// setup post-change attributes
final PostChangePasswordAction postAction = new PostChangePasswordAction() {
public String getLabel() {
return "ActivateUser write attributes";
}
public boolean doAction(final PwmSession pwmSession, final String newPassword) throws PwmUnrecoverableException {
try {
{
// execute configured actions
LOGGER.debug(pwmSession.getLabel(), "executing post-activate configured actions to user " + userIdentity.toDisplayString());
final MacroMachine macroMachine = pwmSession.getSessionManager().getMacroMachine(pwmApplication);
final List<ActionConfiguration> configValues = pwmApplication.getConfig().readSettingAsAction(PwmSetting.ACTIVATE_USER_POST_WRITE_ATTRIBUTES);
final ActionExecutor actionExecutor = new ActionExecutor.ActionExecutorSettings(pwmApplication, userIdentity).setExpandPwmMacros(true).setMacroMachine(macroMachine).createActionExecutor();
actionExecutor.executeActions(configValues, pwmRequest.getSessionLabel());
}
} catch (PwmOperationalException e) {
final ErrorInformation info = new ErrorInformation(PwmError.ERROR_ACTIVATION_FAILURE, e.getErrorInformation().getDetailedErrorMsg(), e.getErrorInformation().getFieldValues());
final PwmUnrecoverableException newException = new PwmUnrecoverableException(info);
newException.initCause(e);
throw newException;
} catch (ChaiUnavailableException e) {
final String errorMsg = "unable to reach ldap server while writing post-activate attributes: " + e.getMessage();
final ErrorInformation info = new ErrorInformation(PwmError.ERROR_ACTIVATION_FAILURE, errorMsg);
final PwmUnrecoverableException newException = new PwmUnrecoverableException(info);
newException.initCause(e);
throw newException;
}
return true;
}
};
pwmSession.getUserSessionDataCacheBean().addPostChangePasswordActions("activateUserWriteAttributes", postAction);
} catch (ImpossiblePasswordPolicyException e) {
final ErrorInformation info = new ErrorInformation(PwmError.ERROR_UNKNOWN, "unexpected ImpossiblePasswordPolicyException error while activating user");
LOGGER.warn(pwmSession, info, e);
throw new PwmOperationalException(info);
}
}
Aggregations