private static void sendChangePasswordHelpdeskEmailNotice( final PwmSession pwmSession, final PwmApplication pwmApplication, final UserInfoBean userInfoBean) throws PwmUnrecoverableException { final Configuration config = pwmApplication.getConfig(); final Locale locale = pwmSession.getSessionStateBean().getLocale(); final EmailItemBean configuredEmailSetting = config.readSettingAsEmail(PwmSetting.EMAIL_CHANGEPASSWORD_HELPDESK, locale); if (configuredEmailSetting == null) { LOGGER.debug( pwmSession, "skipping send change password email for '" + pwmSession.getUserInfoBean().getUserIdentity() + "' no email configured"); return; } final MacroMachine macroMachine = userInfoBean == null ? null : new MacroMachine( pwmApplication, pwmSession.getLabel(), userInfoBean, null, LdapUserDataReader.appProxiedReader( pwmApplication, userInfoBean.getUserIdentity())); pwmApplication.getEmailQueue().submitEmail(configuredEmailSetting, userInfoBean, macroMachine); }
protected void processAction(final PwmRequest pwmRequest) throws ServletException, ChaiUnavailableException, IOException, PwmUnrecoverableException { // Fetch the session state bean. final PwmSession pwmSession = pwmRequest.getPwmSession(); final PwmApplication pwmApplication = pwmRequest.getPwmApplication(); final GuestRegistrationBean guestRegistrationBean = pwmApplication.getSessionStateService().getBean(pwmRequest, GuestRegistrationBean.class); final Configuration config = pwmApplication.getConfig(); if (!config.readSettingAsBoolean(PwmSetting.GUEST_ENABLE)) { pwmRequest.respondWithError(PwmError.ERROR_SERVICE_NOT_AVAILABLE.toInfo()); return; } if (!pwmSession .getSessionManager() .checkPermission(pwmApplication, Permission.GUEST_REGISTRATION)) { pwmRequest.respondWithError(PwmError.ERROR_UNAUTHORIZED.toInfo()); return; } checkConfiguration(config); final GuestRegistrationAction action = readProcessAction(pwmRequest); if (action != null) { pwmRequest.validatePwmFormID(); switch (action) { case create: handleCreateRequest(pwmRequest, guestRegistrationBean); return; case search: handleSearchRequest(pwmRequest, guestRegistrationBean); return; case update: handleUpdateRequest(pwmRequest, guestRegistrationBean); return; case selectPage: handleSelectPageRequest(pwmRequest, guestRegistrationBean); return; } } this.forwardToJSP(pwmRequest, guestRegistrationBean); }
private static void invokePostChangePasswordActions( final PwmSession pwmSession, final String newPassword) throws PwmUnrecoverableException { final List<PostChangePasswordAction> postChangePasswordActions = pwmSession.getUserSessionDataCacheBean().removePostChangePasswordActions(); if (postChangePasswordActions == null || postChangePasswordActions.isEmpty()) { LOGGER.trace(pwmSession, "no post change password actions pending from previous operations"); return; } for (final PostChangePasswordAction postChangePasswordAction : postChangePasswordActions) { try { postChangePasswordAction.doAction(pwmSession, newPassword); } catch (PwmUnrecoverableException e) { LOGGER.error( pwmSession, "error during post change password action '" + postChangePasswordAction.getLabel() + "' " + e.getMessage()); throw e; } catch (Exception e) { LOGGER.error( pwmSession, "unexpected error during post change password action '" + postChangePasswordAction.getLabel() + "' " + e.getMessage(), e); final ErrorInformation errorInfo = new ErrorInformation(PwmError.ERROR_UNKNOWN, e.getMessage()); throw new PwmUnrecoverableException(errorInfo); } } }
protected void processAction(final PwmRequest pwmRequest) throws ServletException, IOException, ChaiUnavailableException, PwmUnrecoverableException { final PwmSession pwmSession = pwmRequest.getPwmSession(); final PwmApplication pwmApplication = pwmRequest.getPwmApplication(); final UpdateProfileBean updateProfileBean = pwmSession.getUpdateProfileBean(); if (!pwmApplication.getConfig().readSettingAsBoolean(PwmSetting.UPDATE_PROFILE_ENABLE)) { pwmRequest.respondWithError(new ErrorInformation(PwmError.ERROR_SERVICE_NOT_AVAILABLE)); return; } if (!pwmSession .getSessionManager() .checkPermission(pwmApplication, Permission.PROFILE_UPDATE)) { pwmRequest.respondWithError(new ErrorInformation(PwmError.ERROR_UNAUTHORIZED)); return; } final UpdateProfileAction action = readProcessAction(pwmRequest); if (action != null) { pwmRequest.validatePwmFormID(); switch (action) { case updateProfile: handleUpdateRequest(pwmRequest, updateProfileBean); break; case agree: handleAgreeRequest(pwmRequest, updateProfileBean); break; case confirm: updateProfileBean.setConfirmationPassed(true); break; case unConfirm: handleUnconfirm(updateProfileBean); break; case validate: restValidateForm(pwmRequest, updateProfileBean); return; } } advanceToNextStep(pwmRequest, updateProfileBean); }
private void sendGuestUserEmailConfirmation( final PwmRequest pwmRequest, final UserIdentity userIdentity) throws PwmUnrecoverableException { final PwmSession pwmSession = pwmRequest.getPwmSession(); final PwmApplication pwmApplication = pwmRequest.getPwmApplication(); final Configuration config = pwmApplication.getConfig(); final Locale locale = pwmSession.getSessionStateBean().getLocale(); final EmailItemBean configuredEmailSetting = config.readSettingAsEmail(PwmSetting.EMAIL_GUEST, locale); if (configuredEmailSetting == null) { LOGGER.debug( pwmSession, "unable to send guest registration email for '" + userIdentity + "' no email configured"); return; } final MacroMachine macroMachine = MacroMachine.forUser(pwmRequest, userIdentity); pwmApplication.getEmailQueue().submitEmail(configuredEmailSetting, null, macroMachine); }
private Map<String, String> makeDisplayData( final PwmApplication pwmApplication, final PwmSession pwmSession, final String bundleName) { Class displayClass = LocaleHelper.classForShortName(bundleName); displayClass = displayClass == null ? Display.class : displayClass; final Locale userLocale = pwmSession.getSessionStateBean().getLocale(); final Configuration config = pwmApplication.getConfig(); final TreeMap<String, String> displayStrings = new TreeMap<>(); final ResourceBundle bundle = ResourceBundle.getBundle(displayClass.getName()); try { final MacroMachine macroMachine = pwmSession.getSessionManager().getMacroMachine(pwmApplication); for (final String key : new TreeSet<>(Collections.list(bundle.getKeys()))) { String displayValue = LocaleHelper.getLocalizedMessage(userLocale, key, config, displayClass); displayValue = macroMachine.expandMacros(displayValue); displayStrings.put(key, displayValue); } } catch (Exception e) { LOGGER.error(pwmSession, "error expanding macro display value: " + e.getMessage()); } return displayStrings; }
private static void sendProfileUpdateEmailNotice( final PwmSession pwmSession, final PwmApplication pwmApplication) throws PwmUnrecoverableException, ChaiUnavailableException { final Configuration config = pwmApplication.getConfig(); final Locale locale = pwmSession.getSessionStateBean().getLocale(); final EmailItemBean configuredEmailSetting = config.readSettingAsEmail(PwmSetting.EMAIL_UPDATEPROFILE, locale); if (configuredEmailSetting == null) { LOGGER.debug( pwmSession, "skipping send profile update email for '" + pwmSession.getUserInfoBean().getUserIdentity() + "' no email configured"); return; } pwmApplication .getEmailQueue() .submitEmail( configuredEmailSetting, pwmSession.getUserInfoBean(), pwmSession.getSessionManager().getMacroMachine(pwmApplication)); }
public static String makeClientEtag( final PwmApplication pwmApplication, final PwmSession pwmSession, final HttpServletRequest httpServletRequest) throws PwmUnrecoverableException { final StringBuilder inputString = new StringBuilder(); inputString.append(PwmConstants.BUILD_NUMBER); inputString.append(pwmApplication.getStartupTime().getTime()); inputString.append(httpServletRequest.getSession().getMaxInactiveInterval()); inputString.append(pwmApplication.getInstanceNonce()); if (pwmSession.getSessionStateBean().getLocale() != null) { inputString.append(pwmSession.getSessionStateBean().getLocale()); } inputString.append(pwmSession.getSessionStateBean().getSessionID()); if (pwmSession.isAuthenticated()) { inputString.append(pwmSession.getUserInfoBean().getUserGuid()); inputString.append(pwmSession.getLoginInfoBean().getAuthTime()); } return SecureEngine.hash(inputString.toString(), PwmHashAlgorithm.SHA1).toLowerCase(); }
@Override protected void processAction(final PwmRequest pwmRequest) throws ServletException, IOException, ChaiUnavailableException, PwmUnrecoverableException { final PwmSession pwmSession = pwmRequest.getPwmSession(); final PwmApplication pwmApplication = pwmRequest.getPwmApplication(); if ((pwmSession.getSessionBean(ConfigGuideBean.class)).getStep() == STEP.START) { pwmSession.clearSessionBeans(); pwmSession.getSessionStateBean().setTheme(null); } final ConfigGuideBean configGuideBean = pwmSession.getSessionBean(ConfigGuideBean.class); if (pwmApplication.getApplicationMode() != PwmApplication.MODE.NEW) { final ErrorInformation errorInformation = new ErrorInformation( PwmError.ERROR_SERVICE_NOT_AVAILABLE, "ConfigGuide unavailable unless in NEW mode"); LOGGER.error(pwmSession, errorInformation.toDebugStr()); pwmRequest.respondWithError(errorInformation); return; } if (!configGuideBean.getFormData().containsKey(PARAM_APP_SITEURL)) { final URI uri = URI.create(pwmRequest.getHttpServletRequest().getRequestURL().toString()); final int port = Helper.portForUriSchema(uri); final String newUri = uri.getScheme() + "://" + uri.getHost() + ":" + port + pwmRequest.getContextPath(); configGuideBean.getFormData().put(PARAM_APP_SITEURL, newUri); } pwmSession.setSessionTimeout( pwmRequest.getHttpServletRequest().getSession(), Integer.parseInt( pwmApplication.getConfig().readAppProperty(AppProperty.CONFIG_GUIDE_IDLE_TIMEOUT))); if (configGuideBean.getStep() == STEP.LDAP_CERT) { final String ldapServerString = ((List<String>) configGuideBean .getStoredConfiguration() .readSetting(PwmSetting.LDAP_SERVER_URLS, LDAP_PROFILE_KEY) .toNativeObject()) .get(0); try { final URI ldapServerUri = new URI(ldapServerString); if ("ldaps".equalsIgnoreCase(ldapServerUri.getScheme())) { configGuideBean.setLdapCertificates(X509Utils.readRemoteCertificates(ldapServerUri)); configGuideBean.setCertsTrustedbyKeystore( X509Utils.testIfLdapServerCertsInDefaultKeystore(ldapServerUri)); } else { configGuideBean.setLdapCertificates(null); configGuideBean.setCertsTrustedbyKeystore(false); } } catch (Exception e) { LOGGER.error("error reading/testing ldap server certificates: " + e.getMessage()); } } final ConfigGuideAction action = readProcessAction(pwmRequest); if (action != null) { pwmRequest.validatePwmFormID(); switch (action) { case ldapHealth: restLdapHealth(pwmRequest, configGuideBean); return; case updateForm: restUpdateLdapForm(pwmRequest, configGuideBean); return; case gotoStep: restGotoStep(pwmRequest, configGuideBean); return; case useConfiguredCerts: restUseConfiguredCerts(pwmRequest, configGuideBean); return; case uploadConfig: restUploadConfig(pwmRequest); return; case extendSchema: restExtendSchema(pwmRequest, configGuideBean); return; case viewAdminMatches: restViewAdminMatches(pwmRequest, configGuideBean); return; case browseLdap: restBrowseLdap(pwmRequest, configGuideBean); } } if (!pwmRequest.getPwmResponse().getHttpServletResponse().isCommitted()) { forwardToJSP(pwmRequest); } }
public static void doProfileUpdate( final PwmRequest pwmRequest, final Map<FormConfiguration, String> formValues, final ChaiUser theUser) throws PwmUnrecoverableException, ChaiUnavailableException, PwmOperationalException { final PwmApplication pwmApplication = pwmRequest.getPwmApplication(); final PwmSession pwmSession = pwmRequest.getPwmSession(); final UserInfoBean uiBean = pwmRequest.getPwmSession().getUserInfoBean(); // verify form meets the form requirements (may be redundant, but shouldn't hurt) verifyFormAttributes(pwmRequest, formValues, false); // write values. LOGGER.info( "updating profile for " + pwmRequest.getPwmSession().getUserInfoBean().getUserIdentity()); pwmRequest.getPwmSession().getSessionManager().getChaiProvider(); Helper.writeFormValuesToLdap( pwmRequest.getPwmApplication(), pwmRequest.getPwmSession(), theUser, formValues, false); final UserIdentity userIdentity = uiBean.getUserIdentity(); // re-populate the uiBean because we have changed some values. final UserStatusReader userStatusReader = new UserStatusReader(pwmRequest.getPwmApplication(), pwmRequest.getSessionLabel()); userStatusReader.populateActorUserInfoBean(pwmRequest.getPwmSession(), userIdentity); // clear cached read attributes. pwmRequest.getPwmSession().getSessionManager().clearUserDataReader(); { // execute configured actions final List<ActionConfiguration> actions = pwmApplication .getConfig() .readSettingAsAction(PwmSetting.UPDATE_PROFILE_WRITE_ATTRIBUTES); if (actions != null && !actions.isEmpty()) { LOGGER.debug(pwmRequest, "executing configured actions to user " + userIdentity); final ActionExecutor actionExecutor = new ActionExecutor.ActionExecutorSettings(pwmApplication, userIdentity) .setExpandPwmMacros(true) .createActionExecutor(); actionExecutor.executeActions(actions, pwmSession); } } sendProfileUpdateEmailNotice(pwmSession, pwmApplication); // mark the event log pwmApplication .getAuditManager() .submit(AuditEvent.UPDATE_PROFILE, pwmSession.getUserInfoBean(), pwmSession); // mark the uiBean so we user isn't recycled to the update profile page by the CommandServlet uiBean.setRequiresUpdateProfile(false); // clear out the updateProfileBean pwmSession.clearUpdateProfileBean(); // success, so forward to success page pwmApplication.getStatisticsManager().incrementValue(Statistic.UPDATE_ATTRIBUTES); }
private void advanceToNextStep( final PwmRequest pwmRequest, final UpdateProfileBean updateProfileBean) throws IOException, ServletException, PwmUnrecoverableException, ChaiUnavailableException { final PwmApplication pwmApplication = pwmRequest.getPwmApplication(); final PwmSession pwmSession = pwmRequest.getPwmSession(); final String updateProfileAgreementText = pwmApplication .getConfig() .readSettingAsLocalizedString( PwmSetting.UPDATE_PROFILE_AGREEMENT_MESSAGE, pwmSession.getSessionStateBean().getLocale()); if (updateProfileAgreementText != null && updateProfileAgreementText.length() > 0) { if (!updateProfileBean.isAgreementPassed()) { final MacroMachine macroMachine = pwmRequest .getPwmSession() .getSessionManager() .getMacroMachine(pwmRequest.getPwmApplication()); final String expandedText = macroMachine.expandMacros(updateProfileAgreementText); pwmRequest.setAttribute(PwmConstants.REQUEST_ATTR.AgreementText, expandedText); pwmRequest.forwardToJsp(PwmConstants.JSP_URL.UPDATE_ATTRIBUTES_AGREEMENT); return; } } final Map<FormConfiguration, String> formValues = updateProfileBean.getFormData(); if (!updateProfileBean.isFormSubmitted()) { final Map<FormConfiguration, String> formMap = updateProfileBean.getFormData(); final List<FormConfiguration> formFields = pwmApplication.getConfig().readSettingAsForm(PwmSetting.UPDATE_PROFILE_FORM); FormUtility.populateFormMapFromLdap( formFields, pwmRequest.getSessionLabel(), formMap, pwmSession.getSessionManager().getUserDataReader(pwmApplication)); forwardToForm(pwmRequest); return; } // make sure there is form data in the bean. if (updateProfileBean.getFormData() == null) { forwardToForm(pwmRequest); return; } // validate the form data. try { // verify form meets the form requirements verifyFormAttributes(pwmRequest, formValues, true); } catch (PwmOperationalException e) { LOGGER.error(pwmSession, e.getMessage()); pwmRequest.setResponseError(e.getErrorInformation()); forwardToForm(pwmRequest); return; } final boolean requireConfirmation = pwmApplication .getConfig() .readSettingAsBoolean(PwmSetting.UPDATE_PROFILE_SHOW_CONFIRMATION); if (requireConfirmation && !updateProfileBean.isConfirmationPassed()) { forwardToConfirmForm(pwmRequest); return; } try { // write the form values final ChaiUser theUser = pwmSession.getSessionManager().getActor(pwmApplication); doProfileUpdate(pwmRequest, formValues, theUser); pwmRequest.forwardToSuccessPage(Message.Success_UpdateProfile); return; } catch (PwmException e) { LOGGER.error(pwmSession, e.getMessage()); pwmRequest.setResponseError(e.getErrorInformation()); } catch (ChaiException e) { final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_UPDATE_ATTRS_FAILURE, e.toString()); LOGGER.error(pwmSession, errorInformation.toDebugStr()); pwmRequest.setResponseError(errorInformation); } forwardToForm(pwmRequest); }
private void handleCreateRequest( final PwmRequest pwmRequest, final GuestRegistrationBean guestRegistrationBean) throws PwmUnrecoverableException, ChaiUnavailableException, IOException, ServletException { final PwmSession pwmSession = pwmRequest.getPwmSession(); final PwmApplication pwmApplication = pwmRequest.getPwmApplication(); final LocalSessionStateBean ssBean = pwmSession.getSessionStateBean(); final Configuration config = pwmApplication.getConfig(); final Locale locale = ssBean.getLocale(); final List<FormConfiguration> guestUserForm = config.readSettingAsForm(PwmSetting.GUEST_FORM); try { // read the values from the request final Map<FormConfiguration, String> formValues = FormUtility.readFormValuesFromRequest(pwmRequest, guestUserForm, locale); // read the expiration date from the request. final Date expirationDate = readExpirationFromRequest(pwmRequest); // see if the values meet form requirements. FormUtility.validateFormValues(config, formValues, locale); // read new user DN final String guestUserDN = determineUserDN(formValues, config); // read a chai provider to make the user final ChaiProvider provider = pwmSession.getSessionManager().getChaiProvider(); // set up the user creation attributes final Map<String, String> createAttributes = new HashMap<>(); for (final FormConfiguration formItem : formValues.keySet()) { LOGGER.debug( pwmSession, "Attribute from form: " + formItem.getName() + " = " + formValues.get(formItem)); final String n = formItem.getName(); final String v = formValues.get(formItem); if (n != null && n.length() > 0 && v != null && v.length() > 0) { createAttributes.put(n, v); } } // Write creator DN createAttributes.put( config.readSettingAsString(PwmSetting.GUEST_ADMIN_ATTRIBUTE), pwmSession.getUserInfoBean().getUserIdentity().getUserDN()); // read the creation object classes. final Set<String> createObjectClasses = new HashSet<>(config.readSettingAsStringArray(PwmSetting.DEFAULT_OBJECT_CLASSES)); provider.createEntry(guestUserDN, createObjectClasses, createAttributes); LOGGER.info(pwmSession, "created user object: " + guestUserDN); final ChaiUser theUser = ChaiFactory.createChaiUser(guestUserDN, provider); final UserIdentity userIdentity = new UserIdentity( guestUserDN, pwmSession.getUserInfoBean().getUserIdentity().getLdapProfileID()); // write the expiration date: if (expirationDate != null) { final String expirationAttr = config.readSettingAsString(PwmSetting.GUEST_EXPIRATION_ATTRIBUTE); theUser.writeDateAttribute(expirationAttr, expirationDate); } final PwmPasswordPolicy passwordPolicy = PasswordUtility.readPasswordPolicyForUser( pwmApplication, pwmSession.getLabel(), userIdentity, theUser, locale); final PasswordData newPassword = RandomPasswordGenerator.createRandomPassword( pwmSession.getLabel(), passwordPolicy, pwmApplication); theUser.setPassword(newPassword.getStringValue()); /* final UserInfoBean guestUserInfoBean = new UserInfoBean(); final UserStatusReader userStatusReader = new UserStatusReader(pwmApplication); userStatusReader.populateUserInfoBean( pwmSession.getLabel(), guestUserInfoBean, pwmSession.getSessionStateBean().getLocale(), userIdentity, theUser.getChaiProvider() ); */ { // execute configured actions LOGGER.debug(pwmSession, "executing configured actions to user " + theUser.getEntryDN()); final List<ActionConfiguration> actions = pwmApplication.getConfig().readSettingAsAction(PwmSetting.GUEST_WRITE_ATTRIBUTES); if (actions != null && !actions.isEmpty()) { final MacroMachine macroMachine = MacroMachine.forUser(pwmRequest, userIdentity); final ActionExecutor actionExecutor = new ActionExecutor.ActionExecutorSettings(pwmApplication, theUser) .setExpandPwmMacros(true) .setMacroMachine(macroMachine) .createActionExecutor(); actionExecutor.executeActions(actions, pwmSession); } } // everything good so forward to success page. this.sendGuestUserEmailConfirmation(pwmRequest, userIdentity); pwmApplication.getStatisticsManager().incrementValue(Statistic.NEW_USERS); pwmRequest.getPwmResponse().forwardToSuccessPage(Message.Success_CreateGuest); } catch (ChaiOperationException e) { final ErrorInformation info = new ErrorInformation( PwmError.ERROR_NEW_USER_FAILURE, "error creating user: " + e.getMessage()); pwmRequest.setResponseError(info); LOGGER.warn(pwmSession, info); this.forwardToJSP(pwmRequest, guestRegistrationBean); } catch (PwmOperationalException e) { LOGGER.error(pwmSession, e.getErrorInformation().toDebugStr()); pwmRequest.setResponseError(e.getErrorInformation()); this.forwardToJSP(pwmRequest, guestRegistrationBean); } }
protected void handleUpdateRequest( final PwmRequest pwmRequest, final GuestRegistrationBean guestRegistrationBean) throws ServletException, ChaiUnavailableException, IOException, PwmUnrecoverableException { // Fetch the session state bean. final PwmSession pwmSession = pwmRequest.getPwmSession(); final LocalSessionStateBean ssBean = pwmSession.getSessionStateBean(); final PwmApplication pwmApplication = pwmRequest.getPwmApplication(); final Configuration config = pwmApplication.getConfig(); final List<FormConfiguration> formItems = pwmApplication.getConfig().readSettingAsForm(PwmSetting.GUEST_UPDATE_FORM); final String expirationAttribute = config.readSettingAsString(PwmSetting.GUEST_EXPIRATION_ATTRIBUTE); try { // read the values from the request final Map<FormConfiguration, String> formValues = FormUtility.readFormValuesFromRequest(pwmRequest, formItems, pwmRequest.getLocale()); // see if the values meet form requirements. FormUtility.validateFormValues(config, formValues, ssBean.getLocale()); // read current values from user. final ChaiUser theGuest = pwmSession .getSessionManager() .getActor(pwmApplication, guestRegistrationBean.getUpdateUserIdentity()); // check unique fields against ldap FormUtility.validateFormValueUniqueness( pwmApplication, formValues, ssBean.getLocale(), Collections.singletonList(guestRegistrationBean.getUpdateUserIdentity()), false); final Date expirationDate = readExpirationFromRequest(pwmRequest); // Update user attributes Helper.writeFormValuesToLdap(pwmApplication, pwmSession, theGuest, formValues, false); // Write expirationDate if (expirationDate != null) { theGuest.writeDateAttribute(expirationAttribute, expirationDate); } // send email. final UserStatusReader userStatusReader = new UserStatusReader(pwmApplication, pwmSession.getLabel()); final UserInfoBean guestUserInfoBean = new UserInfoBean(); userStatusReader.populateUserInfoBean( guestUserInfoBean, pwmSession.getSessionStateBean().getLocale(), guestRegistrationBean.getUpdateUserIdentity(), theGuest.getChaiProvider()); this.sendUpdateGuestEmailConfirmation(pwmRequest, guestUserInfoBean); pwmApplication.getStatisticsManager().incrementValue(Statistic.UPDATED_GUESTS); // everything good so forward to confirmation page. pwmRequest.getPwmResponse().forwardToSuccessPage(Message.Success_UpdateGuest); return; } catch (PwmOperationalException e) { LOGGER.error(pwmSession, e.getErrorInformation().toDebugStr()); pwmRequest.setResponseError(e.getErrorInformation()); } catch (ChaiOperationException e) { final ErrorInformation info = new ErrorInformation( PwmError.ERROR_UNKNOWN, "unexpected error writing to ldap: " + e.getMessage()); LOGGER.error(pwmSession, info); pwmRequest.setResponseError(info); } this.forwardToUpdateJSP(pwmRequest, guestRegistrationBean); }
public static void helpdeskSetUserPassword( final PwmSession pwmSession, final ChaiUser chaiUser, final UserIdentity userIdentity, final PwmApplication pwmApplication, final PasswordData newPassword) throws ChaiUnavailableException, PwmUnrecoverableException, PwmOperationalException { final SessionLabel sessionLabel = pwmSession.getLabel(); if (!pwmSession.isAuthenticated()) { final String errorMsg = "attempt to helpdeskSetUserPassword, but user is not authenticated"; final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_UNAUTHORIZED, errorMsg); throw new PwmOperationalException(errorInformation); } final HelpdeskProfile helpdeskProfile = pwmSession.getSessionManager().getHelpdeskProfile(pwmApplication); if (helpdeskProfile == null) { final String errorMsg = "attempt to helpdeskSetUserPassword, but user does not have helpdesk permission"; final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_UNAUTHORIZED, errorMsg); throw new PwmOperationalException(errorInformation); } try { chaiUser.setPassword(newPassword.getStringValue()); } catch (ChaiPasswordPolicyException e) { final String errorMsg = "error setting password for user '" + chaiUser.getEntryDN() + "'' " + e.toString(); final PwmError pwmError = PwmError.forChaiError(e.getErrorCode()); final ErrorInformation error = new ErrorInformation( pwmError == null ? PwmError.PASSWORD_UNKNOWN_VALIDATION : pwmError, errorMsg); throw new PwmOperationalException(error); } catch (ChaiOperationException e) { final String errorMsg = "error setting password for user '" + chaiUser.getEntryDN() + "'' " + e.getMessage(); final PwmError pwmError = PwmError.forChaiError(e.getErrorCode()) == null ? PwmError.ERROR_UNKNOWN : PwmError.forChaiError(e.getErrorCode()); final ErrorInformation error = new ErrorInformation(pwmError, errorMsg); throw new PwmOperationalException(error); } // at this point the password has been changed, so log it. LOGGER.info( sessionLabel, "user '" + pwmSession.getUserInfoBean().getUserIdentity() + "' successfully changed password for " + chaiUser.getEntryDN()); // create a proxy user object for pwm to update/read the user. final ChaiUser proxiedUser = pwmApplication.getProxiedChaiUser(userIdentity); // mark the event log { final HelpdeskAuditRecord auditRecord = pwmApplication .getAuditManager() .createHelpdeskAuditRecord( AuditEvent.HELPDESK_SET_PASSWORD, pwmSession.getUserInfoBean().getUserIdentity(), null, userIdentity, pwmSession.getSessionStateBean().getSrcAddress(), pwmSession.getSessionStateBean().getSrcHostname()); pwmApplication.getAuditManager().submit(auditRecord); } // update statistics pwmApplication.getStatisticsManager().updateEps(Statistic.EpsType.PASSWORD_CHANGES, 1); pwmApplication.getStatisticsManager().incrementValue(Statistic.HELPDESK_PASSWORD_SET); // create a uib for end user final UserInfoBean userInfoBean = new UserInfoBean(); final UserStatusReader userStatusReader = new UserStatusReader(pwmApplication, pwmSession.getLabel()); userStatusReader.populateUserInfoBean( userInfoBean, pwmSession.getSessionStateBean().getLocale(), userIdentity, proxiedUser.getChaiProvider()); { // execute configured actions LOGGER.debug( sessionLabel, "executing changepassword and helpdesk post password change writeAttributes to user " + userIdentity); final List<ActionConfiguration> actions = new ArrayList<>(); actions.addAll( pwmApplication .getConfig() .readSettingAsAction(PwmSetting.CHANGE_PASSWORD_WRITE_ATTRIBUTES)); actions.addAll( helpdeskProfile.readSettingAsAction( PwmSetting.HELPDESK_POST_SET_PASSWORD_WRITE_ATTRIBUTES)); if (!actions.isEmpty()) { final ActionExecutor actionExecutor = new ActionExecutor.ActionExecutorSettings(pwmApplication, userIdentity) .setMacroMachine( MacroMachine.forUser( pwmApplication, pwmSession.getSessionStateBean().getLocale(), sessionLabel, userIdentity)) .setExpandPwmMacros(true) .createActionExecutor(); actionExecutor.executeActions(actions, pwmSession); } } final HelpdeskClearResponseMode settingClearResponses = HelpdeskClearResponseMode.valueOf( helpdeskProfile.readSettingAsString(PwmSetting.HELPDESK_CLEAR_RESPONSES)); if (settingClearResponses == HelpdeskClearResponseMode.yes) { final String userGUID = LdapOperationsHelper.readLdapGuidValue(pwmApplication, sessionLabel, userIdentity, false); pwmApplication.getCrService().clearResponses(pwmSession, proxiedUser, userGUID); // mark the event log final HelpdeskAuditRecord auditRecord = pwmApplication .getAuditManager() .createHelpdeskAuditRecord( AuditEvent.HELPDESK_CLEAR_RESPONSES, pwmSession.getUserInfoBean().getUserIdentity(), null, userIdentity, pwmSession.getSessionStateBean().getSrcAddress(), pwmSession.getSessionStateBean().getSrcHostname()); pwmApplication.getAuditManager().submit(auditRecord); } // send email notification sendChangePasswordHelpdeskEmailNotice(pwmSession, pwmApplication, userInfoBean); // expire if so configured if (helpdeskProfile.readSettingAsBoolean(PwmSetting.HELPDESK_FORCE_PW_EXPIRATION)) { LOGGER.trace( pwmSession, "preparing to expire password for user " + userIdentity.toDisplayString()); try { proxiedUser.expirePassword(); } catch (ChaiOperationException e) { LOGGER.warn( pwmSession, "error while forcing password expiration for user " + userIdentity.toDisplayString() + ", error: " + e.getMessage()); e.printStackTrace(); } } // send password final boolean sendPassword = helpdeskProfile.readSettingAsBoolean(PwmSetting.HELPDESK_SEND_PASSWORD); if (sendPassword) { final MessageSendMethod messageSendMethod; { final String profileID = ProfileUtility.discoverProfileIDforUser( pwmApplication, sessionLabel, userIdentity, ProfileType.ForgottenPassword); final ForgottenPasswordProfile forgottenPasswordProfile = pwmApplication.getConfig().getForgottenPasswordProfiles().get(profileID); messageSendMethod = forgottenPasswordProfile.readSettingAsEnum( PwmSetting.RECOVERY_SENDNEWPW_METHOD, MessageSendMethod.class); } final UserDataReader userDataReader = new LdapUserDataReader(userIdentity, chaiUser); final LoginInfoBean loginInfoBean = new LoginInfoBean(); loginInfoBean.setUserCurrentPassword(newPassword); final MacroMachine macroMachine = new MacroMachine( pwmApplication, pwmSession.getLabel(), userInfoBean, loginInfoBean, userDataReader); PasswordUtility.sendNewPassword( userInfoBean, pwmApplication, macroMachine, newPassword, pwmSession.getSessionStateBean().getLocale(), messageSendMethod); } }
/** * This is the entry point under which all password changes are managed. The following is the * general procedure when this method is invoked. * * <ul> * <li>password is checked against PWM password requirement * <li>ldap password set is attempted<br> * <br> * if successful: * <ul> * <li>uiBean is updated with old and new passwords * <li>uiBean's password expire flag is set to false * <li>any configured external methods are invoked * <li>user email notification is sent * <li>return true * </ul> * <br> * if unsuccessful * <ul> * <li>ssBean is updated with appropriate error * <li>return false * </ul> * </ul> * * @param newPassword the new password that is being set. * @param pwmSession beanmanager for config and user info lookup * @throws com.novell.ldapchai.exception.ChaiUnavailableException if the ldap directory is not * unavailable * @throws password.pwm.error.PwmUnrecoverableException if user is not authenticated */ public static void setActorPassword( final PwmSession pwmSession, final PwmApplication pwmApplication, final PasswordData newPassword) throws ChaiUnavailableException, PwmUnrecoverableException, PwmOperationalException { final UserInfoBean uiBean = pwmSession.getUserInfoBean(); if (!pwmSession .getSessionManager() .checkPermission(pwmApplication, Permission.CHANGE_PASSWORD)) { final String errorMsg = "attempt to setActorPassword, but user does not have password change permission"; final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_UNAUTHORIZED, errorMsg); throw new PwmOperationalException(errorInformation); } // double check to make sure password meets PWM rule requirements. This should // have been done before setActorPassword() is invoked, so it should be redundant // but we do it just in case. try { final PwmPasswordRuleValidator pwmPasswordRuleValidator = new PwmPasswordRuleValidator(pwmApplication, uiBean.getPasswordPolicy()); pwmPasswordRuleValidator.testPassword( newPassword, null, uiBean, pwmSession.getSessionManager().getActor(pwmApplication)); } catch (PwmDataValidationException e) { final String errorMsg = "attempt to setActorPassword, but password does not pass local policy validator"; final ErrorInformation errorInformation = new ErrorInformation(e.getErrorInformation().getError(), errorMsg); throw new PwmOperationalException(errorInformation); } // retrieve the user's old password from the userInfoBean in the session final PasswordData oldPassword = pwmSession.getLoginInfoBean().getUserCurrentPassword(); boolean setPasswordWithoutOld = false; if (oldPassword == null) { if (pwmSession .getSessionManager() .getActor(pwmApplication) .getChaiProvider() .getDirectoryVendor() == ChaiProvider.DIRECTORY_VENDOR.MICROSOFT_ACTIVE_DIRECTORY) { setPasswordWithoutOld = true; } } if (!setPasswordWithoutOld) { // Check to make sure we actually have an old password if (oldPassword == null) { final String errorMsg = "cannot set password for user, old password is not available"; final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_WRONGPASSWORD, errorMsg); throw new PwmOperationalException(errorInformation); } } try { final ChaiProvider provider = pwmSession.getSessionManager().getChaiProvider(); final ChaiUser theUser = ChaiFactory.createChaiUser( pwmSession.getUserInfoBean().getUserIdentity().getUserDN(), provider); final boolean boundAsSelf = theUser .getEntryDN() .equals(provider.getChaiConfiguration().getSetting(ChaiSetting.BIND_DN)); LOGGER.trace( pwmSession, "preparing to setActorPassword for '" + theUser.getEntryDN() + "', bindAsSelf=" + boundAsSelf + ", authType=" + pwmSession.getLoginInfoBean().getType()); if (setPasswordWithoutOld) { theUser.setPassword(newPassword.getStringValue(), true); } else { theUser.changePassword(oldPassword.getStringValue(), newPassword.getStringValue()); } } catch (ChaiPasswordPolicyException e) { final String errorMsg = "error setting password for user '" + uiBean.getUserIdentity() + "'' " + e.toString(); final PwmError pwmError = PwmError.forChaiError(e.getErrorCode()); final ErrorInformation error = new ErrorInformation( pwmError == null ? PwmError.PASSWORD_UNKNOWN_VALIDATION : pwmError, errorMsg); throw new PwmOperationalException(error); } catch (ChaiOperationException e) { final String errorMsg = "error setting password for user '" + uiBean.getUserIdentity() + "'' " + e.getMessage(); final PwmError pwmError = PwmError.forChaiError(e.getErrorCode()) == null ? PwmError.ERROR_UNKNOWN : PwmError.forChaiError(e.getErrorCode()); final ErrorInformation error = new ErrorInformation(pwmError, errorMsg); throw new PwmOperationalException(error); } // at this point the password has been changed, so log it. LOGGER.info( pwmSession, "user '" + uiBean.getUserIdentity() + "' successfully changed password"); // update the session state bean's password modified flag pwmSession.getSessionStateBean().setPasswordModified(true); // update the login info bean with the user's new password pwmSession.getLoginInfoBean().setUserCurrentPassword(newPassword); // close any outstanding ldap connections (since they cache the old password) pwmSession .getSessionManager() .updateUserPassword(pwmApplication, uiBean.getUserIdentity(), newPassword); // clear the "requires new password flag" uiBean.setRequiresNewPassword(false); // mark the auth type as authenticatePd now that we have the user's natural password. pwmSession.getLoginInfoBean().setType(AuthenticationType.AUTHENTICATED); // update the uibean's "password expired flag". final UserStatusReader userStatusReader = new UserStatusReader(pwmApplication, pwmSession.getLabel()); uiBean.setPasswordState( userStatusReader.readPasswordStatus( pwmSession.getSessionManager().getActor(pwmApplication), uiBean.getPasswordPolicy(), uiBean, newPassword)); // create a proxy user object for pwm to update/read the user. final ChaiUser proxiedUser = pwmSession.getSessionManager().getActor(pwmApplication); // update statistics { pwmApplication.getStatisticsManager().incrementValue(Statistic.PASSWORD_CHANGES); pwmApplication.getStatisticsManager().updateEps(Statistic.EpsType.PASSWORD_CHANGES, 1); final int passwordStrength = PasswordUtility.judgePasswordStrength(newPassword.getStringValue()); pwmApplication .getStatisticsManager() .updateAverageValue(Statistic.AVG_PASSWORD_STRENGTH, passwordStrength); } // add the old password to the global history list (if the old password is known) if (oldPassword != null && pwmApplication .getConfig() .readSettingAsBoolean(PwmSetting.PASSWORD_SHAREDHISTORY_ENABLE)) { pwmApplication.getSharedHistoryManager().addWord(pwmSession, oldPassword.getStringValue()); } // invoke post password change actions invokePostChangePasswordActions(pwmSession, newPassword.getStringValue()); { // execute configured actions LOGGER.debug(pwmSession, "executing configured actions to user " + proxiedUser.getEntryDN()); final List<ActionConfiguration> configValues = pwmApplication .getConfig() .readSettingAsAction(PwmSetting.CHANGE_PASSWORD_WRITE_ATTRIBUTES); if (configValues != null && !configValues.isEmpty()) { final LoginInfoBean clonedLoginInfoBean = JsonUtil.cloneUsingJson(pwmSession.getLoginInfoBean(), LoginInfoBean.class); clonedLoginInfoBean.setUserCurrentPassword(newPassword); final MacroMachine macroMachine = new MacroMachine( pwmApplication, pwmSession.getLabel(), pwmSession.getUserInfoBean(), clonedLoginInfoBean, pwmSession.getSessionManager().getUserDataReader(pwmApplication)); final ActionExecutor actionExecutor = new ActionExecutor.ActionExecutorSettings(pwmApplication, uiBean.getUserIdentity()) .setMacroMachine(macroMachine) .setExpandPwmMacros(true) .createActionExecutor(); actionExecutor.executeActions(configValues, pwmSession); } } // update the current last password update field in ldap LdapOperationsHelper.updateLastPasswordUpdateAttribute( pwmApplication, pwmSession.getLabel(), uiBean.getUserIdentity()); }
private static Map<String, Object> makeClientData( final PwmApplication pwmApplication, final PwmSession pwmSession, final HttpServletRequest request, final HttpServletResponse response, final String pageUrl) throws ChaiUnavailableException, PwmUnrecoverableException { final Configuration config = pwmApplication.getConfig(); final TreeMap<String, Object> settingMap = new TreeMap<>(); settingMap.put( "client.ajaxTypingTimeout", Integer.parseInt(config.readAppProperty(AppProperty.CLIENT_AJAX_TYPING_TIMEOUT))); settingMap.put( "client.ajaxTypingWait", Integer.parseInt(config.readAppProperty(AppProperty.CLIENT_AJAX_TYPING_WAIT))); settingMap.put( "client.activityMaxEpsRate", Integer.parseInt(config.readAppProperty(AppProperty.CLIENT_ACTIVITY_MAX_EPS_RATE))); settingMap.put( "client.js.enableHtml5Dialog", Boolean.parseBoolean(config.readAppProperty(AppProperty.CLIENT_JS_ENABLE_HTML5DIALOG))); settingMap.put( "client.pwShowRevertTimeout", Integer.parseInt(config.readAppProperty(AppProperty.CLIENT_PW_SHOW_REVERT_TIMEOUT))); settingMap.put( "enableIdleTimeout", config.readSettingAsBoolean(PwmSetting.DISPLAY_IDLE_TIMEOUT)); settingMap.put( "pageLeaveNotice", config.readSettingAsLong(PwmSetting.SECURITY_PAGE_LEAVE_NOTICE_TIMEOUT)); settingMap.put( "setting-showHidePasswordFields", pwmApplication .getConfig() .readSettingAsBoolean( password.pwm.config.PwmSetting.DISPLAY_SHOW_HIDE_PASSWORD_FIELDS)); settingMap.put("setting-displayEula", PwmConstants.ENABLE_EULA_DISPLAY); settingMap.put( "setting-showStrengthMeter", config.readSettingAsBoolean(PwmSetting.PASSWORD_SHOW_STRENGTH_METER)); { long idleSeconds = config.readSettingAsLong(PwmSetting.IDLE_TIMEOUT_SECONDS); if (pageUrl == null || pageUrl.isEmpty()) { LOGGER.warn(pwmSession, "request to /client data did not incliude pageUrl"); } else { try { final PwmURL pwmURL = new PwmURL(new URI(pageUrl), request.getContextPath()); final TimeDuration maxIdleTime = IdleTimeoutCalculator.idleTimeoutForRequest(pwmURL, pwmApplication, pwmSession); idleSeconds = maxIdleTime.getTotalSeconds(); } catch (Exception e) { LOGGER.error( pwmSession, "error determining idle timeout time for request: " + e.getMessage()); } } settingMap.put("MaxInactiveInterval", idleSeconds); } settingMap.put("paramName.locale", config.readAppProperty(AppProperty.HTTP_PARAM_NAME_LOCALE)); settingMap.put("startupTime", pwmApplication.getStartupTime()); settingMap.put("applicationMode", pwmApplication.getApplicationMode()); final String contextPath = request.getContextPath(); settingMap.put("url-context", contextPath); settingMap.put( "url-logout", contextPath + PwmServletDefinition.Logout.servletUrl() + "?idle=true"); settingMap.put("url-command", contextPath + PwmServletDefinition.Command.servletUrl()); settingMap.put( "url-resources", contextPath + "/public/resources" + pwmApplication.getResourceServletService().getResourceNonce()); settingMap.put("url-restservice", contextPath + "/public/rest"); { String passwordGuideText = pwmApplication .getConfig() .readSettingAsLocalizedString( PwmSetting.DISPLAY_PASSWORD_GUIDE_TEXT, pwmSession.getSessionStateBean().getLocale()); final MacroMachine macroMachine = pwmSession.getSessionManager().getMacroMachine(pwmApplication); passwordGuideText = macroMachine.expandMacros(passwordGuideText); settingMap.put("passwordGuideText", passwordGuideText); } { final List<String> formTypeOptions = new ArrayList<>(); for (final FormConfiguration.Type type : FormConfiguration.Type.values()) { formTypeOptions.add(type.toString()); } settingMap.put("formTypeOptions", formTypeOptions); } { final List<String> actionTypeOptions = new ArrayList<>(); for (final ActionConfiguration.Type type : ActionConfiguration.Type.values()) { actionTypeOptions.add(type.toString()); } settingMap.put("actionTypeOptions", actionTypeOptions); } { final List<String> epsTypes = new ArrayList<>(); for (final Statistic.EpsType loopEpsType : Statistic.EpsType.values()) { epsTypes.add(loopEpsType.toString()); } settingMap.put("epsTypes", epsTypes); } { final List<String> epsDurations = new ArrayList<>(); for (final Statistic.EpsDuration loopEpsDuration : Statistic.EpsDuration.values()) { epsDurations.add(loopEpsDuration.toString()); } settingMap.put("epsDurations", epsDurations); } { final Map<String, String> localeInfo = new TreeMap<>(); final Map<String, String> localeDisplayNames = new TreeMap<>(); final Map<String, String> localeFlags = new TreeMap<>(); for (final Locale locale : pwmApplication.getConfig().getKnownLocales()) { final String flagCode = pwmApplication.getConfig().getKnownLocaleFlagMap().get(locale); localeFlags.put(locale.toString(), flagCode); localeInfo.put( locale.toString(), locale.getDisplayName() + " - " + locale.getDisplayLanguage(locale)); localeDisplayNames.put(locale.toString(), locale.getDisplayLanguage()); } settingMap.put("localeInfo", localeInfo); settingMap.put("localeDisplayNames", localeDisplayNames); settingMap.put("localeFlags", localeFlags); settingMap.put("defaultLocale", PwmConstants.DEFAULT_LOCALE.toString()); } if (pwmApplication .getConfig() .readSettingAsEnum(PwmSetting.LDAP_SELECTABLE_CONTEXT_MODE, SelectableContextMode.class) != SelectableContextMode.NONE) { final Map<String, Map<String, String>> ldapProfiles = new LinkedHashMap<>(); for (final String ldapProfile : pwmApplication.getConfig().getLdapProfiles().keySet()) { final Map<String, String> contexts = pwmApplication.getConfig().getLdapProfiles().get(ldapProfile).getLoginContexts(); ldapProfiles.put(ldapProfile, contexts); } settingMap.put("ldapProfiles", ldapProfiles); } return settingMap; }
static boolean checkAuthentication( final PwmRequest pwmRequest, final ConfigManagerBean configManagerBean) throws IOException, PwmUnrecoverableException, ServletException { final PwmApplication pwmApplication = pwmRequest.getPwmApplication(); final PwmSession pwmSession = pwmRequest.getPwmSession(); final ConfigurationReader runningConfigReader = ContextManager.getContextManager(pwmRequest.getHttpServletRequest().getSession()) .getConfigReader(); final StoredConfigurationImpl storedConfig = runningConfigReader.getStoredConfiguration(); boolean authRequired = false; if (storedConfig.hasPassword()) { authRequired = true; } if (PwmApplication.MODE.RUNNING == pwmRequest.getPwmApplication().getApplicationMode()) { if (!pwmSession.getSessionStateBean().isAuthenticated()) { throw new PwmUnrecoverableException(PwmError.ERROR_AUTHENTICATION_REQUIRED); } if (!pwmRequest .getPwmSession() .getSessionManager() .checkPermission(pwmRequest.getPwmApplication(), Permission.PWMADMIN)) { final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_UNAUTHORIZED); pwmRequest.respondWithError(errorInformation); return true; } if (pwmSession.getLoginInfoBean().getAuthenticationType() != AuthenticationType.AUTHENTICATED) { throw new PwmUnrecoverableException( new ErrorInformation( PwmError.ERROR_AUTHENTICATION_REQUIRED, "Username/Password authentication is required to edit configuration. This session has not been authenticated using a user password (SSO or other method used).")); } } if (PwmApplication.MODE.CONFIGURATION != pwmRequest.getPwmApplication().getApplicationMode()) { authRequired = true; } if (!authRequired) { return false; } if (!storedConfig.hasPassword()) { final String errorMsg = "config file does not have a configuration password"; final ErrorInformation errorInformation = new ErrorInformation(PwmError.CONFIG_FORMAT_ERROR, errorMsg, new String[] {errorMsg}); pwmRequest.respondWithError(errorInformation, true); return true; } if (configManagerBean.isPasswordVerified()) { return false; } String persistentLoginValue = null; boolean persistentLoginAccepted = false; boolean persistentLoginEnabled = false; if (pwmRequest.getConfig().isDefaultValue(PwmSetting.PWM_SECURITY_KEY)) { LOGGER.debug(pwmRequest, "security not available, persistent login not possible."); } else { persistentLoginEnabled = true; final PwmSecurityKey securityKey = pwmRequest.getConfig().getSecurityKey(); if (PwmApplication.MODE.RUNNING == pwmRequest.getPwmApplication().getApplicationMode()) { persistentLoginValue = SecureEngine.hash( storedConfig.readConfigProperty(ConfigurationProperty.PASSWORD_HASH) + pwmSession.getUserInfoBean().getUserIdentity().toDelimitedKey(), PwmHashAlgorithm.SHA512); } else { persistentLoginValue = SecureEngine.hash( storedConfig.readConfigProperty(ConfigurationProperty.PASSWORD_HASH), PwmHashAlgorithm.SHA512); } { final String cookieStr = ServletHelper.readCookie( pwmRequest.getHttpServletRequest(), PwmConstants.COOKIE_PERSISTENT_CONFIG_LOGIN); if (securityKey != null && cookieStr != null && !cookieStr.isEmpty()) { try { final String jsonStr = pwmApplication.getSecureService().decryptStringValue(cookieStr); final PersistentLoginInfo persistentLoginInfo = JsonUtil.deserialize(jsonStr, PersistentLoginInfo.class); if (persistentLoginInfo != null && persistentLoginValue != null) { if (persistentLoginInfo.getExpireDate().after(new Date())) { if (persistentLoginValue.equals(persistentLoginInfo.getPassword())) { persistentLoginAccepted = true; LOGGER.debug( pwmRequest, "accepting persistent config login from cookie (expires " + PwmConstants.DEFAULT_DATETIME_FORMAT.format( persistentLoginInfo.getExpireDate()) + ")"); } } } } catch (Exception e) { LOGGER.error( pwmRequest, "error examining persistent config login cookie: " + e.getMessage()); } if (!persistentLoginAccepted) { Cookie removalCookie = new Cookie(PwmConstants.COOKIE_PERSISTENT_CONFIG_LOGIN, null); removalCookie.setMaxAge(0); pwmRequest.getPwmResponse().addCookie(removalCookie); LOGGER.debug(pwmRequest, "removing non-working persistent config login cookie"); } } } } final String password = pwmRequest.readParameterAsString("password"); boolean passwordAccepted = false; if (!persistentLoginAccepted) { if (password != null && password.length() > 0) { if (storedConfig.verifyPassword(password)) { passwordAccepted = true; LOGGER.trace(pwmRequest, "valid configuration password accepted"); updateLoginHistory(pwmRequest, pwmRequest.getUserInfoIfLoggedIn(), true); } else { LOGGER.trace(pwmRequest, "configuration password is not correct"); pwmApplication.getIntruderManager().convenience().markAddressAndSession(pwmSession); pwmApplication .getIntruderManager() .mark( RecordType.USERNAME, PwmConstants.CONFIGMANAGER_INTRUDER_USERNAME, pwmSession.getLabel()); final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_WRONGPASSWORD); pwmRequest.setResponseError(errorInformation); updateLoginHistory(pwmRequest, pwmRequest.getUserInfoIfLoggedIn(), false); } } } if ((persistentLoginAccepted || passwordAccepted)) { configManagerBean.setPasswordVerified(true); pwmApplication.getIntruderManager().convenience().clearAddressAndSession(pwmSession); pwmApplication .getIntruderManager() .clear(RecordType.USERNAME, PwmConstants.CONFIGMANAGER_INTRUDER_USERNAME); if (persistentLoginEnabled && !persistentLoginAccepted && "on".equals(pwmRequest.readParameterAsString("remember"))) { final int persistentSeconds = figureMaxLoginSeconds(pwmRequest); if (persistentSeconds > 0) { final Date expirationDate = new Date(System.currentTimeMillis() + (persistentSeconds * 1000)); final PersistentLoginInfo persistentLoginInfo = new PersistentLoginInfo(expirationDate, persistentLoginValue); final String jsonPersistentLoginInfo = JsonUtil.serialize(persistentLoginInfo); final String cookieValue = pwmApplication.getSecureService().encryptToString(jsonPersistentLoginInfo); pwmRequest .getPwmResponse() .writeCookie( PwmConstants.COOKIE_PERSISTENT_CONFIG_LOGIN, cookieValue, persistentSeconds); LOGGER.debug( pwmRequest, "set persistent config login cookie (expires " + PwmConstants.DEFAULT_DATETIME_FORMAT.format(expirationDate) + ")"); } } if (configManagerBean.getPrePasswordEntryUrl() != null) { final String originalUrl = configManagerBean.getPrePasswordEntryUrl(); configManagerBean.setPrePasswordEntryUrl(null); pwmRequest.getPwmResponse().sendRedirect(originalUrl); return true; } return false; } if (configManagerBean.getPrePasswordEntryUrl() == null) { configManagerBean.setPrePasswordEntryUrl( pwmRequest.getHttpServletRequest().getRequestURL().toString()); } forwardToJsp(pwmRequest); return true; }
protected void handleSearchRequest( final PwmRequest pwmRequest, final GuestRegistrationBean guestRegistrationBean) throws ServletException, ChaiUnavailableException, IOException, PwmUnrecoverableException { LOGGER.trace(pwmRequest, "Enter: handleSearchRequest(...)"); final PwmSession pwmSession = pwmRequest.getPwmSession(); final PwmApplication pwmApplication = pwmRequest.getPwmApplication(); final ChaiProvider chaiProvider = pwmSession.getSessionManager().getChaiProvider(); final Configuration config = pwmApplication.getConfig(); final String adminDnAttribute = config.readSettingAsString(PwmSetting.GUEST_ADMIN_ATTRIBUTE); final Boolean origAdminOnly = config.readSettingAsBoolean(PwmSetting.GUEST_EDIT_ORIG_ADMIN_ONLY); final String usernameParam = pwmRequest.readParameterAsString("username"); final GuestRegistrationBean guBean = pwmApplication.getSessionStateService().getBean(pwmRequest, GuestRegistrationBean.class); final UserSearchEngine.SearchConfiguration searchConfiguration = new UserSearchEngine.SearchConfiguration(); searchConfiguration.setChaiProvider(chaiProvider); searchConfiguration.setContexts( Collections.singletonList(config.readSettingAsString(PwmSetting.GUEST_CONTEXT))); searchConfiguration.setEnableContextValidation(false); searchConfiguration.setUsername(usernameParam); final UserSearchEngine userSearchEngine = new UserSearchEngine(pwmApplication, pwmSession.getLabel()); try { final UserIdentity theGuest = userSearchEngine.performSingleUserSearch(searchConfiguration); final FormMap formProps = guBean.getFormValues(); try { final List<FormConfiguration> guestUpdateForm = config.readSettingAsForm(PwmSetting.GUEST_UPDATE_FORM); final Set<String> involvedAttrs = new HashSet<>(); for (final FormConfiguration formItem : guestUpdateForm) { if (!formItem.getName().equalsIgnoreCase(HTTP_PARAM_EXPIRATION_DATE)) { involvedAttrs.add(formItem.getName()); } } final UserDataReader userDataReader = LdapUserDataReader.selfProxiedReader(pwmApplication, pwmSession, theGuest); final Map<String, String> userAttrValues = userDataReader.readStringAttributes(involvedAttrs); if (origAdminOnly && adminDnAttribute != null && adminDnAttribute.length() > 0) { final String origAdminDn = userAttrValues.get(adminDnAttribute); if (origAdminDn != null && origAdminDn.length() > 0) { if (!pwmSession .getUserInfoBean() .getUserIdentity() .getUserDN() .equalsIgnoreCase(origAdminDn)) { final ErrorInformation info = new ErrorInformation(PwmError.ERROR_ORIG_ADMIN_ONLY); pwmRequest.setResponseError(info); LOGGER.warn(pwmSession, info); this.forwardToJSP(pwmRequest, guestRegistrationBean); } } } final String expirationAttribute = config.readSettingAsString(PwmSetting.GUEST_EXPIRATION_ATTRIBUTE); if (expirationAttribute != null && expirationAttribute.length() > 0) { final Date expiration = userDataReader.readDateAttribute(expirationAttribute); if (expiration != null) { guBean.setUpdateUserExpirationDate(expiration); } } for (final FormConfiguration formItem : guestUpdateForm) { final String key = formItem.getName(); final String value = userAttrValues.get(key); if (value != null) { formProps.put(key, value); } } guBean.setUpdateUserIdentity(theGuest); this.forwardToUpdateJSP(pwmRequest, guestRegistrationBean); return; } catch (ChaiOperationException e) { LOGGER.warn(pwmSession, "error reading current attributes for user: " + e.getMessage()); } } catch (PwmOperationalException e) { final ErrorInformation error = e.getErrorInformation(); pwmRequest.setResponseError(error); this.forwardToJSP(pwmRequest, guestRegistrationBean); return; } this.forwardToJSP(pwmRequest, guestRegistrationBean); }
private void advanceToNextStep( final PwmRequest pwmRequest, final UpdateAttributesProfile updateAttributesProfile, final UpdateProfileBean updateProfileBean) throws IOException, ServletException, PwmUnrecoverableException, ChaiUnavailableException { final PwmApplication pwmApplication = pwmRequest.getPwmApplication(); final PwmSession pwmSession = pwmRequest.getPwmSession(); final String updateProfileAgreementText = updateAttributesProfile.readSettingAsLocalizedString( PwmSetting.UPDATE_PROFILE_AGREEMENT_MESSAGE, pwmSession.getSessionStateBean().getLocale()); if (updateProfileAgreementText != null && updateProfileAgreementText.length() > 0) { if (!updateProfileBean.isAgreementPassed()) { final MacroMachine macroMachine = pwmRequest .getPwmSession() .getSessionManager() .getMacroMachine(pwmRequest.getPwmApplication()); final String expandedText = macroMachine.expandMacros(updateProfileAgreementText); pwmRequest.setAttribute(PwmRequest.Attribute.AgreementText, expandedText); pwmRequest.forwardToJsp(PwmConstants.JSP_URL.UPDATE_ATTRIBUTES_AGREEMENT); return; } } // make sure there is form data in the bean. if (updateProfileBean.getFormData() == null) { updateProfileBean.setFormData(formDataFromLdap(pwmRequest, updateAttributesProfile)); forwardToForm(pwmRequest, updateAttributesProfile, updateProfileBean); return; } if (!updateProfileBean.isFormSubmitted()) { forwardToForm(pwmRequest, updateAttributesProfile, updateProfileBean); return; } // validate the form data. try { // verify form meets the form requirements final List<FormConfiguration> formFields = updateAttributesProfile.readSettingAsForm(PwmSetting.UPDATE_PROFILE_FORM); final Map<FormConfiguration, String> formValues = FormUtility.readFormValuesFromMap( updateProfileBean.getFormData(), formFields, pwmRequest.getLocale()); verifyFormAttributes(pwmRequest, formValues, true); } catch (PwmException e) { LOGGER.error(pwmSession, e.getMessage()); pwmRequest.setResponseError(e.getErrorInformation()); forwardToForm(pwmRequest, updateAttributesProfile, updateProfileBean); return; } final boolean requireConfirmation = updateAttributesProfile.readSettingAsBoolean(PwmSetting.UPDATE_PROFILE_SHOW_CONFIRMATION); if (requireConfirmation && !updateProfileBean.isConfirmationPassed()) { forwardToConfirmForm(pwmRequest, updateAttributesProfile, updateProfileBean); return; } final Set<TokenVerificationProgress.TokenChannel> requiredVerifications = determineTokenPhaseRequired(pwmRequest, updateProfileBean, updateAttributesProfile); if (requiredVerifications != null) { for (final TokenVerificationProgress.TokenChannel tokenChannel : requiredVerifications) { if (requiredVerifications.contains(tokenChannel)) { if (!updateProfileBean .getTokenVerificationProgress() .getIssuedTokens() .contains(tokenChannel)) { initializeToken(pwmRequest, updateProfileBean, tokenChannel); } if (!updateProfileBean .getTokenVerificationProgress() .getPassedTokens() .contains(tokenChannel)) { updateProfileBean.getTokenVerificationProgress().setPhase(tokenChannel); pwmRequest.forwardToJsp(PwmConstants.JSP_URL.UPDATE_ATTRIBUTES_ENTER_CODE); return; } } } } try { // write the form values final ChaiUser theUser = pwmSession.getSessionManager().getActor(pwmApplication); doProfileUpdate(pwmRequest, updateProfileBean.getFormData(), theUser); pwmRequest.getPwmResponse().forwardToSuccessPage(Message.Success_UpdateProfile); return; } catch (PwmException e) { LOGGER.error(pwmSession, e.getMessage()); pwmRequest.setResponseError(e.getErrorInformation()); } catch (ChaiException e) { final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_UPDATE_ATTRS_FAILURE, e.toString()); LOGGER.error(pwmSession, errorInformation.toDebugStr()); pwmRequest.setResponseError(errorInformation); } forwardToForm(pwmRequest, updateAttributesProfile, updateProfileBean); }
public void initializeToken( final PwmRequest pwmRequest, final UpdateProfileBean updateProfileBean, final TokenVerificationProgress.TokenChannel tokenType) throws PwmUnrecoverableException { final PwmSession pwmSession = pwmRequest.getPwmSession(); final PwmApplication pwmApplication = pwmRequest.getPwmApplication(); if (pwmApplication.getConfig().getTokenStorageMethod() == TokenStorageMethod.STORE_LDAP) { throw new PwmUnrecoverableException( new ErrorInformation( PwmError.CONFIG_FORMAT_ERROR, null, new String[] { "cannot generate new user tokens when storage type is configured as STORE_LDAP." })); } final MacroMachine macroMachine = pwmRequest.getPwmSession().getSessionManager().getMacroMachine(pwmApplication); final Configuration config = pwmApplication.getConfig(); switch (tokenType) { case SMS: { final String telephoneNumberAttribute = pwmRequest.getConfig().readSettingAsString(PwmSetting.SMS_USER_PHONE_ATTRIBUTE); final String toNum = updateProfileBean.getFormData().get(telephoneNumberAttribute); final String tokenKey; try { final TokenPayload tokenPayload = pwmApplication .getTokenService() .createTokenPayload( TokenType.UPDATE_SMS, Collections.<String, String>emptyMap(), pwmRequest.getUserInfoIfLoggedIn(), Collections.singleton(toNum)); tokenKey = pwmApplication .getTokenService() .generateNewToken(tokenPayload, pwmRequest.getSessionLabel()); } catch (PwmOperationalException e) { throw new PwmUnrecoverableException(e.getErrorInformation()); } final String message = config.readSettingAsLocalizedString( PwmSetting.SMS_UPDATE_PROFILE_TOKEN_TEXT, pwmSession.getSessionStateBean().getLocale()); try { TokenService.TokenSender.sendSmsToken( pwmApplication, null, macroMachine, toNum, message, tokenKey); } catch (Exception e) { throw new PwmUnrecoverableException(new ErrorInformation(PwmError.ERROR_UNKNOWN)); } updateProfileBean .getTokenVerificationProgress() .getIssuedTokens() .add(TokenVerificationProgress.TokenChannel.SMS); updateProfileBean.getTokenVerificationProgress().setTokenDisplayText(toNum); updateProfileBean .getTokenVerificationProgress() .setPhase(TokenVerificationProgress.TokenChannel.SMS); } break; case EMAIL: { final EmailItemBean configuredEmailSetting = config.readSettingAsEmail( PwmSetting.EMAIL_UPDATEPROFILE_VERIFICATION, pwmRequest.getLocale()); final String emailAddressAttribute = pwmRequest.getConfig().readSettingAsString(PwmSetting.EMAIL_USER_MAIL_ATTRIBUTE); final String toAddress = updateProfileBean.getFormData().get(emailAddressAttribute); final String tokenKey; try { final TokenPayload tokenPayload = pwmApplication .getTokenService() .createTokenPayload( TokenType.UPDATE_EMAIL, Collections.<String, String>emptyMap(), pwmRequest.getUserInfoIfLoggedIn(), Collections.singleton(toAddress)); tokenKey = pwmApplication .getTokenService() .generateNewToken(tokenPayload, pwmRequest.getSessionLabel()); } catch (PwmOperationalException e) { throw new PwmUnrecoverableException(e.getErrorInformation()); } updateProfileBean .getTokenVerificationProgress() .getIssuedTokens() .add(TokenVerificationProgress.TokenChannel.EMAIL); updateProfileBean .getTokenVerificationProgress() .setPhase(TokenVerificationProgress.TokenChannel.EMAIL); updateProfileBean.getTokenVerificationProgress().setTokenDisplayText(toAddress); final EmailItemBean emailItemBean = new EmailItemBean( toAddress, configuredEmailSetting.getFrom(), configuredEmailSetting.getSubject(), configuredEmailSetting.getBodyPlain().replace("%TOKEN%", tokenKey), configuredEmailSetting.getBodyHtml().replace("%TOKEN%", tokenKey)); try { TokenService.TokenSender.sendEmailToken( pwmApplication, null, macroMachine, emailItemBean, toAddress, tokenKey); } catch (Exception e) { throw new PwmUnrecoverableException(new ErrorInformation(PwmError.ERROR_UNKNOWN)); } } break; default: LOGGER.error("Unimplemented token purpose: " + tokenType); updateProfileBean.getTokenVerificationProgress().setPhase(null); } }
private void restLockConfiguration(final PwmRequest pwmRequest) throws IOException, ServletException, PwmUnrecoverableException, ChaiUnavailableException { final PwmApplication pwmApplication = pwmRequest.getPwmApplication(); final PwmSession pwmSession = pwmRequest.getPwmSession(); if (PwmConstants.TRIAL_MODE) { final ErrorInformation errorInfo = new ErrorInformation( PwmError.ERROR_TRIAL_VIOLATION, "configuration lock not available in trial"); final RestResultBean restResultBean = RestResultBean.fromError(errorInfo, pwmRequest); LOGGER.debug(pwmSession, errorInfo); pwmRequest.outputJsonResult(restResultBean); return; } if (!pwmSession.isAuthenticated()) { final ErrorInformation errorInfo = new ErrorInformation( PwmError.ERROR_AUTHENTICATION_REQUIRED, "You must be authenticated before restricting the configuration"); final RestResultBean restResultBean = RestResultBean.fromError(errorInfo, pwmRequest); LOGGER.debug(pwmSession, errorInfo); pwmRequest.outputJsonResult(restResultBean); return; } if (!pwmSession.getSessionManager().checkPermission(pwmApplication, Permission.PWMADMIN)) { final ErrorInformation errorInfo = new ErrorInformation( PwmError.ERROR_UNAUTHORIZED, "You must be authenticated with admin privileges before restricting the configuration"); final RestResultBean restResultBean = RestResultBean.fromError(errorInfo, pwmRequest); LOGGER.debug(pwmSession, errorInfo); pwmRequest.outputJsonResult(restResultBean); return; } try { final StoredConfigurationImpl storedConfiguration = readCurrentConfiguration(pwmRequest); if (!storedConfiguration.hasPassword()) { final ErrorInformation errorInfo = new ErrorInformation( PwmError.CONFIG_FORMAT_ERROR, null, new String[] { "Please set a configuration password before restricting the configuration" }); final RestResultBean restResultBean = RestResultBean.fromError(errorInfo, pwmRequest); LOGGER.debug(pwmSession, errorInfo); pwmRequest.outputJsonResult(restResultBean); return; } storedConfiguration.writeConfigProperty(ConfigurationProperty.CONFIG_IS_EDITABLE, "false"); saveConfiguration(pwmRequest, storedConfiguration); final ConfigManagerBean configManagerBean = pwmRequest .getPwmApplication() .getSessionStateService() .getBean(pwmRequest, ConfigManagerBean.class); configManagerBean.setConfiguration(null); } catch (PwmException e) { final ErrorInformation errorInfo = e.getErrorInformation(); final RestResultBean restResultBean = RestResultBean.fromError(errorInfo, pwmRequest); LOGGER.debug(pwmSession, errorInfo.toDebugStr()); pwmRequest.outputJsonResult(restResultBean); return; } catch (Exception e) { final ErrorInformation errorInfo = new ErrorInformation(PwmError.ERROR_UNKNOWN, e.getMessage()); final RestResultBean restResultBean = RestResultBean.fromError(errorInfo, pwmRequest); LOGGER.debug(pwmSession, errorInfo.toDebugStr()); pwmRequest.outputJsonResult(restResultBean); return; } final HashMap<String, String> resultData = new HashMap<>(); LOGGER.info(pwmSession, "Configuration Locked"); pwmRequest.outputJsonResult(new RestResultBean(resultData)); }