use of password.pwm.config.Configuration in project pwm by pwm-project.
the class NewUserServlet method preProcessCheck.
@Override
public ProcessStatus preProcessCheck(final PwmRequest pwmRequest) throws PwmUnrecoverableException, IOException, ServletException {
final PwmApplication pwmApplication = pwmRequest.getPwmApplication();
final Configuration config = pwmApplication.getConfig();
if (!config.readSettingAsBoolean(PwmSetting.NEWUSER_ENABLE)) {
throw new PwmUnrecoverableException(PwmError.ERROR_SERVICE_NOT_AVAILABLE);
}
final NewUserBean newUserBean = pwmApplication.getSessionStateService().getBean(pwmRequest, NewUserBean.class);
final String signedFormData = pwmRequest.readParameterAsString(PwmConstants.PARAM_SIGNED_FORM, PwmHttpRequestWrapper.Flag.BypassValidation);
if (!StringUtil.isEmpty(signedFormData)) {
final Map<String, String> jsonForm = RestFormSigningServer.readSignedFormValue(pwmApplication, signedFormData);
LOGGER.trace("detected signedForm parameter in request, will read and place in bean; keys=" + JsonUtil.serializeCollection(jsonForm.keySet()));
newUserBean.setRemoteInputData(jsonForm);
}
// convert a url command like /public/newuser/profile/xxx to set profile.
if (readProfileFromUrl(pwmRequest, newUserBean)) {
return ProcessStatus.Halt;
}
final ProcessAction action = this.readProcessAction(pwmRequest);
// convert a url command like /public/newuser/12321321 to redirect with a process action.
if (action == null) {
if (pwmRequest.convertURLtokenCommand(PwmServletDefinition.NewUser, NewUserAction.enterCode)) {
return ProcessStatus.Halt;
}
} else if (action != NewUserAction.complete && action != NewUserAction.checkProgress) {
if (pwmRequest.isAuthenticated()) {
pwmRequest.respondWithError(PwmError.ERROR_USERAUTHENTICATED.toInfo());
return ProcessStatus.Halt;
}
}
return ProcessStatus.Continue;
}
use of password.pwm.config.Configuration in project pwm by pwm-project.
the class NewUserUtils method sendNewUserEmailConfirmation.
private static void sendNewUserEmailConfirmation(final PwmRequest pwmRequest) throws PwmUnrecoverableException, ChaiUnavailableException {
final PwmSession pwmSession = pwmRequest.getPwmSession();
final UserInfo userInfo = pwmSession.getUserInfo();
final Configuration config = pwmRequest.getConfig();
final Locale locale = pwmSession.getSessionStateBean().getLocale();
final EmailItemBean configuredEmailSetting = config.readSettingAsEmail(PwmSetting.EMAIL_NEWUSER, locale);
if (configuredEmailSetting == null) {
NewUserUtils.LOGGER.debug(pwmSession, "skipping send of new user email for '" + userInfo.getUserIdentity().getUserDN() + "' no email configured");
return;
}
pwmRequest.getPwmApplication().getEmailQueue().submitEmail(configuredEmailSetting, pwmSession.getUserInfo(), pwmSession.getSessionManager().getMacroMachine(pwmRequest.getPwmApplication()));
}
use of password.pwm.config.Configuration 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.config.Configuration in project pwm by pwm-project.
the class ForgottenPasswordUtil method sendUnlockNoticeEmail.
static void sendUnlockNoticeEmail(final PwmRequest pwmRequest, final ForgottenPasswordBean forgottenPasswordBean) throws PwmUnrecoverableException, ChaiUnavailableException, IOException, ServletException {
final PwmApplication pwmApplication = pwmRequest.getPwmApplication();
final Configuration config = pwmRequest.getConfig();
final Locale locale = pwmRequest.getLocale();
final UserIdentity userIdentity = forgottenPasswordBean.getUserIdentity();
final EmailItemBean configuredEmailSetting = config.readSettingAsEmail(PwmSetting.EMAIL_UNLOCK, locale);
if (configuredEmailSetting == null) {
LOGGER.debug(pwmRequest, "skipping send unlock notice email for '" + userIdentity + "' no email configured");
return;
}
final UserInfo userInfo = readUserInfo(pwmRequest, forgottenPasswordBean);
final MacroMachine macroMachine = MacroMachine.forUser(pwmApplication, pwmRequest.getSessionLabel(), userInfo, null);
pwmApplication.getEmailQueue().submitEmail(configuredEmailSetting, userInfo, macroMachine);
}
use of password.pwm.config.Configuration in project pwm by pwm-project.
the class HelpdeskServlet method restSendVerificationTokenRequest.
@ActionHandler(action = "sendVerificationToken")
private ProcessStatus restSendVerificationTokenRequest(final PwmRequest pwmRequest) throws IOException, PwmUnrecoverableException, ServletException, ChaiUnavailableException {
final HelpdeskProfile helpdeskProfile = getHelpdeskProfile(pwmRequest);
final Instant startTime = Instant.now();
final Configuration config = pwmRequest.getConfig();
final Map<String, String> bodyParams = pwmRequest.readBodyAsJsonStringMap();
final UserIdentity userIdentity = UserIdentity.fromKey(bodyParams.get(PwmConstants.PARAM_USERKEY), pwmRequest.getPwmApplication());
final UserInfo userInfo = UserInfoFactory.newUserInfo(pwmRequest.getPwmApplication(), pwmRequest.getSessionLabel(), pwmRequest.getLocale(), userIdentity, getChaiUser(pwmRequest, helpdeskProfile, userIdentity).getChaiProvider());
final TokenDestinationItem tokenDestinationItem;
{
final MessageSendMethod effectiveSendMethod;
{
final MessageSendMethod configuredSendMethod = helpdeskProfile.readSettingAsEnum(PwmSetting.HELPDESK_TOKEN_SEND_METHOD, MessageSendMethod.class);
if (configuredSendMethod == MessageSendMethod.CHOICE_SMS_EMAIL) {
final String methodParamName = "method";
final String methodParam = bodyParams.getOrDefault(methodParamName, "");
switch(methodParam) {
case "sms":
effectiveSendMethod = MessageSendMethod.SMSONLY;
break;
case "email":
effectiveSendMethod = MessageSendMethod.EMAILONLY;
break;
default:
throw new UnsupportedOperationException("unknown tokenSendMethod: " + methodParam);
}
} else {
effectiveSendMethod = configuredSendMethod;
}
}
switch(effectiveSendMethod) {
case SMSONLY:
tokenDestinationItem = TokenDestinationItem.builder().id("0").display(userInfo.getUserSmsNumber()).value(userInfo.getUserSmsNumber()).type(TokenDestinationItem.Type.sms).build();
break;
case EMAILONLY:
tokenDestinationItem = TokenDestinationItem.builder().id("0").display(userInfo.getUserEmailAddress()).value(userInfo.getUserEmailAddress()).type(TokenDestinationItem.Type.email).build();
break;
default:
throw new UnsupportedOperationException("unknown tokenSendMethod: " + effectiveSendMethod);
}
}
final HelpdeskDetailInfoBean helpdeskDetailInfoBean = HelpdeskDetailInfoBean.makeHelpdeskDetailInfo(pwmRequest, helpdeskProfile, userIdentity);
if (helpdeskDetailInfoBean == null) {
final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_MISSING_PARAMETER, "unable to read helpdesk detail data for specified user");
LOGGER.error(pwmRequest, errorInformation);
pwmRequest.outputJsonResult(RestResultBean.fromError(errorInformation, pwmRequest));
return ProcessStatus.Halt;
}
final MacroMachine macroMachine = MacroMachine.forUser(pwmRequest.getPwmApplication(), pwmRequest.getSessionLabel(), userInfo, null);
final String configuredTokenString = config.readAppProperty(AppProperty.HELPDESK_TOKEN_VALUE);
final String tokenKey = macroMachine.expandMacros(configuredTokenString);
final EmailItemBean emailItemBean = config.readSettingAsEmail(PwmSetting.EMAIL_HELPDESK_TOKEN, pwmRequest.getLocale());
LOGGER.debug(pwmRequest, "generated token code for " + userIdentity.toDelimitedKey());
final String smsMessage = config.readSettingAsLocalizedString(PwmSetting.SMS_HELPDESK_TOKEN_TEXT, pwmRequest.getLocale());
try {
TokenService.TokenSender.sendToken(TokenService.TokenSendInfo.builder().pwmApplication(pwmRequest.getPwmApplication()).userInfo(userInfo).macroMachine(macroMachine).configuredEmailSetting(emailItemBean).tokenDestinationItem(tokenDestinationItem).smsMessage(smsMessage).tokenKey(tokenKey).sessionLabel(pwmRequest.getSessionLabel()).build());
} catch (PwmException e) {
LOGGER.error(pwmRequest, e.getErrorInformation());
pwmRequest.outputJsonResult(RestResultBean.fromError(e.getErrorInformation(), pwmRequest));
return ProcessStatus.Halt;
}
StatisticsManager.incrementStat(pwmRequest, Statistic.HELPDESK_TOKENS_SENT);
final HelpdeskVerificationRequestBean helpdeskVerificationRequestBean = new HelpdeskVerificationRequestBean();
helpdeskVerificationRequestBean.setDestination(tokenDestinationItem.getDisplay());
helpdeskVerificationRequestBean.setUserKey(bodyParams.get(PwmConstants.PARAM_USERKEY));
final HelpdeskVerificationRequestBean.TokenData tokenData = new HelpdeskVerificationRequestBean.TokenData();
tokenData.setToken(tokenKey);
tokenData.setIssueDate(new Date());
final SecureService secureService = pwmRequest.getPwmApplication().getSecureService();
helpdeskVerificationRequestBean.setTokenData(secureService.encryptObjectToString(tokenData));
final RestResultBean restResultBean = RestResultBean.withData(helpdeskVerificationRequestBean);
pwmRequest.outputJsonResult(restResultBean);
LOGGER.debug(pwmRequest, "helpdesk operator " + pwmRequest.getUserInfoIfLoggedIn().toDisplayString() + " issued token for verification against user " + userIdentity.toDisplayString() + " sent to destination(s) " + tokenDestinationItem.getDisplay() + " (" + TimeDuration.fromCurrent(startTime).asCompactString() + ")");
return ProcessStatus.Halt;
}
Aggregations