use of password.pwm.PwmApplication in project pwm by pwm-project.
the class NewUserServlet method verifyForm.
static PasswordUtility.PasswordCheckInfo verifyForm(final PwmRequest pwmRequest, final NewUserForm newUserForm, final boolean allowResultCaching) throws PwmDataValidationException, PwmUnrecoverableException, ChaiUnavailableException {
final Locale locale = pwmRequest.getLocale();
final PwmApplication pwmApplication = pwmRequest.getPwmApplication();
final NewUserProfile newUserProfile = getNewUserProfile(pwmRequest);
final List<FormConfiguration> formDefinition = newUserProfile.readSettingAsForm(PwmSetting.NEWUSER_FORM);
final Map<FormConfiguration, String> formValueData = FormUtility.readFormValuesFromMap(newUserForm.getFormData(), formDefinition, locale);
FormUtility.validateFormValues(pwmApplication.getConfig(), formValueData, locale);
final List<FormUtility.ValidationFlag> validationFlags = new ArrayList<>();
validationFlags.add(FormUtility.ValidationFlag.checkReadOnlyAndHidden);
if (allowResultCaching) {
validationFlags.add(FormUtility.ValidationFlag.allowResultCaching);
}
FormUtility.validateFormValueUniqueness(pwmApplication, formValueData, locale, Collections.emptyList(), validationFlags.toArray(new FormUtility.ValidationFlag[validationFlags.size()]));
NewUserUtils.remoteVerifyFormData(pwmRequest, newUserForm);
final UserInfo uiBean = UserInfoBean.builder().cachedPasswordRuleAttributes(FormUtility.asStringMap(formValueData)).passwordPolicy(newUserProfile.getNewUserPasswordPolicy(pwmApplication, locale)).build();
final boolean promptForPassword = newUserProfile.readSettingAsBoolean(PwmSetting.NEWUSER_PROMPT_FOR_PASSWORD);
if (promptForPassword) {
return PasswordUtility.checkEnteredPassword(pwmApplication, locale, null, uiBean, null, newUserForm.getNewUserPassword(), newUserForm.getConfirmPassword());
}
return new PasswordUtility.PasswordCheckInfo(null, true, 0, PasswordUtility.PasswordCheckInfo.MatchStatus.MATCH, 0);
}
use of password.pwm.PwmApplication in project pwm by pwm-project.
the class NewUserUtils method createUser.
@SuppressWarnings("checkstyle:MethodLength")
static void createUser(final NewUserForm newUserForm, final PwmRequest pwmRequest, final String newUserDN) throws PwmUnrecoverableException, ChaiUnavailableException, PwmOperationalException {
final PwmApplication pwmApplication = pwmRequest.getPwmApplication();
final PwmSession pwmSession = pwmRequest.getPwmSession();
final long startTime = System.currentTimeMillis();
// re-perform verification before proceeding
{
final PasswordUtility.PasswordCheckInfo passwordCheckInfo = NewUserServlet.verifyForm(pwmRequest, newUserForm, false);
passwordCheckInfoToException(passwordCheckInfo);
}
NewUserUtils.LOGGER.debug(pwmSession, "beginning createUser process for " + newUserDN);
final NewUserProfile newUserProfile = NewUserServlet.getNewUserProfile(pwmRequest);
final boolean promptForPassword = newUserProfile.readSettingAsBoolean(PwmSetting.NEWUSER_PROMPT_FOR_PASSWORD);
final PasswordData userPassword;
if (promptForPassword) {
userPassword = newUserForm.getNewUserPassword();
} else {
final PwmPasswordPolicy pwmPasswordPolicy = newUserProfile.getNewUserPasswordPolicy(pwmRequest.getPwmApplication(), pwmRequest.getLocale());
userPassword = RandomPasswordGenerator.createRandomPassword(pwmRequest.getSessionLabel(), pwmPasswordPolicy, pwmRequest.getPwmApplication());
}
// set up the user creation attributes
final Map<String, String> createAttributes = NewUserFormUtils.getLdapDataFromNewUserForm(NewUserServlet.getNewUserProfile(pwmRequest), newUserForm);
// read the creation object classes from configuration
final Set<String> createObjectClasses = new LinkedHashSet<>(pwmApplication.getConfig().readSettingAsStringArray(PwmSetting.DEFAULT_OBJECT_CLASSES));
// add the auto-add object classes
{
final LdapProfile defaultLDAPProfile = pwmApplication.getConfig().getDefaultLdapProfile();
createObjectClasses.addAll(defaultLDAPProfile.readSettingAsStringArray(PwmSetting.AUTO_ADD_OBJECT_CLASSES));
}
final ChaiProvider chaiProvider = pwmApplication.getConfig().getDefaultLdapProfile().getProxyChaiProvider(pwmApplication);
try {
// create the ldap entry
chaiProvider.createEntry(newUserDN, createObjectClasses, createAttributes);
NewUserUtils.LOGGER.info(pwmSession, "created user entry: " + newUserDN);
} catch (ChaiOperationException e) {
final String userMessage = "unexpected ldap error creating user entry: " + e.getMessage();
final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_NEW_USER_FAILURE, userMessage);
throw new PwmOperationalException(errorInformation);
}
final ChaiUser theUser = chaiProvider.getEntryFactory().newChaiUser(newUserDN);
final boolean useTempPw;
{
final String settingValue = pwmApplication.getConfig().readAppProperty(AppProperty.NEWUSER_LDAP_USE_TEMP_PW);
if ("auto".equalsIgnoreCase(settingValue)) {
useTempPw = chaiProvider.getDirectoryVendor() == DirectoryVendor.ACTIVE_DIRECTORY;
} else {
useTempPw = Boolean.parseBoolean(settingValue);
}
}
if (useTempPw) {
NewUserUtils.LOGGER.trace(pwmSession, "will use temporary password process for new user entry: " + newUserDN);
final PasswordData temporaryPassword;
{
final RandomPasswordGenerator.RandomGeneratorConfig randomGeneratorConfig = RandomPasswordGenerator.RandomGeneratorConfig.builder().passwordPolicy(newUserProfile.getNewUserPasswordPolicy(pwmApplication, pwmRequest.getLocale())).build();
temporaryPassword = RandomPasswordGenerator.createRandomPassword(pwmSession.getLabel(), randomGeneratorConfig, pwmApplication);
}
final ChaiUser proxiedUser = chaiProvider.getEntryFactory().newChaiUser(newUserDN);
try {
// set password as admin
proxiedUser.setPassword(temporaryPassword.getStringValue());
NewUserUtils.LOGGER.debug(pwmSession, "set temporary password for new user entry: " + newUserDN);
} catch (ChaiOperationException e) {
final String userMessage = "unexpected ldap error setting temporary password for new user entry: " + e.getMessage();
final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_NEW_USER_FAILURE, userMessage);
throw new PwmOperationalException(errorInformation);
}
// add AD-specific attributes
if (DirectoryVendor.ACTIVE_DIRECTORY == chaiProvider.getDirectoryVendor()) {
try {
NewUserUtils.LOGGER.debug(pwmSession, "setting userAccountControl attribute to enable account " + theUser.getEntryDN());
theUser.writeStringAttribute("userAccountControl", "512");
} catch (ChaiOperationException e) {
final String errorMsg = "error enabling AD account when writing userAccountControl attribute: " + e.getMessage();
final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_NEW_USER_FAILURE, errorMsg);
throw new PwmOperationalException(errorInformation);
}
}
try {
// bind as user
NewUserUtils.LOGGER.debug(pwmSession, "attempting bind as user to then allow changing to requested password for new user entry: " + newUserDN);
final ChaiConfiguration chaiConfiguration = ChaiConfiguration.builder(chaiProvider.getChaiConfiguration()).setSetting(ChaiSetting.BIND_DN, newUserDN).setSetting(ChaiSetting.BIND_PASSWORD, temporaryPassword.getStringValue()).build();
final ChaiProvider bindAsProvider = pwmApplication.getLdapConnectionService().getChaiProviderFactory().newProvider(chaiConfiguration);
final ChaiUser bindAsUser = bindAsProvider.getEntryFactory().newChaiUser(newUserDN);
bindAsUser.changePassword(temporaryPassword.getStringValue(), userPassword.getStringValue());
NewUserUtils.LOGGER.debug(pwmSession, "changed to user requested password for new user entry: " + newUserDN);
bindAsProvider.close();
} catch (ChaiOperationException e) {
final String userMessage = "unexpected ldap error setting user password for new user entry: " + e.getMessage();
final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_NEW_USER_FAILURE, userMessage);
throw new PwmOperationalException(errorInformation);
}
} else {
try {
// set password
theUser.setPassword(userPassword.getStringValue());
NewUserUtils.LOGGER.debug(pwmSession, "set user requested password for new user entry: " + newUserDN);
} catch (ChaiOperationException e) {
final String userMessage = "unexpected ldap error setting password for new user entry: " + e.getMessage();
final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_NEW_USER_FAILURE, userMessage);
throw new PwmOperationalException(errorInformation);
}
// add AD-specific attributes
if (DirectoryVendor.ACTIVE_DIRECTORY == chaiProvider.getDirectoryVendor()) {
try {
theUser.writeStringAttribute("userAccountControl", "512");
} catch (ChaiOperationException e) {
final String errorMsg = "error enabling AD account when writing userAccountControl attribute: " + e.getMessage();
final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_NEW_USER_FAILURE, errorMsg);
throw new PwmOperationalException(errorInformation);
}
}
}
NewUserUtils.LOGGER.trace(pwmSession, "new user ldap creation process complete, now authenticating user");
// write data to remote web service
remoteWriteFormData(pwmRequest, newUserForm);
// authenticate the user to pwm
final UserIdentity userIdentity = new UserIdentity(newUserDN, pwmApplication.getConfig().getDefaultLdapProfile().getIdentifier());
final SessionAuthenticator sessionAuthenticator = new SessionAuthenticator(pwmApplication, pwmSession, PwmAuthenticationSource.NEW_USER_REGISTRATION);
sessionAuthenticator.authenticateUser(userIdentity, userPassword);
{
// execute configured actions
final List<ActionConfiguration> actions = newUserProfile.readSettingAsAction(PwmSetting.NEWUSER_WRITE_ATTRIBUTES);
if (actions != null && !actions.isEmpty()) {
NewUserUtils.LOGGER.debug(pwmSession, "executing configured actions to user " + theUser.getEntryDN());
final ActionExecutor actionExecutor = new ActionExecutor.ActionExecutorSettings(pwmApplication, userIdentity).setExpandPwmMacros(true).setMacroMachine(pwmSession.getSessionManager().getMacroMachine(pwmApplication)).createActionExecutor();
actionExecutor.executeActions(actions, pwmSession.getLabel());
}
}
// send user email
sendNewUserEmailConfirmation(pwmRequest);
// add audit record
pwmApplication.getAuditManager().submit(AuditEvent.CREATE_USER, pwmSession.getUserInfo(), pwmSession);
// increment the new user creation statistics
pwmApplication.getStatisticsManager().incrementValue(Statistic.NEW_USERS);
NewUserUtils.LOGGER.debug(pwmSession, "completed createUser process for " + newUserDN + " (" + TimeDuration.fromCurrent(startTime).asCompactString() + ")");
}
use of password.pwm.PwmApplication in project pwm by pwm-project.
the class UpdateProfileServlet method nextStep.
protected void nextStep(final PwmRequest pwmRequest) throws IOException, ServletException, PwmUnrecoverableException {
final PwmApplication pwmApplication = pwmRequest.getPwmApplication();
final UpdateProfileBean updateProfileBean = getBean(pwmRequest);
final UpdateProfileProfile updateProfileProfile = getProfile(pwmRequest);
final PwmSession pwmSession = pwmRequest.getPwmSession();
{
final String updateProfileAgreementText = updateProfileProfile.readSettingAsLocalizedString(PwmSetting.UPDATE_PROFILE_AGREEMENT_MESSAGE, pwmSession.getSessionStateBean().getLocale());
if (!StringUtil.isEmpty(updateProfileAgreementText)) {
if (!updateProfileBean.isAgreementPassed()) {
final MacroMachine macroMachine = pwmRequest.getPwmSession().getSessionManager().getMacroMachine(pwmRequest.getPwmApplication());
final String expandedText = macroMachine.expandMacros(updateProfileAgreementText);
pwmRequest.setAttribute(PwmRequestAttribute.AgreementText, expandedText);
pwmRequest.forwardToJsp(JspUrl.UPDATE_ATTRIBUTES_AGREEMENT);
return;
}
}
}
// make sure there is form data in the bean.
if (!updateProfileBean.isFormLdapLoaded()) {
updateProfileBean.getFormData().clear();
updateProfileBean.getFormData().putAll((UpdateProfileUtil.formDataFromLdap(pwmRequest, updateProfileProfile)));
updateProfileBean.setFormLdapLoaded(true);
UpdateProfileUtil.forwardToForm(pwmRequest, updateProfileProfile, updateProfileBean);
return;
}
if (!updateProfileBean.isFormSubmitted()) {
UpdateProfileUtil.forwardToForm(pwmRequest, updateProfileProfile, updateProfileBean);
return;
}
// validate the form data.
try {
// verify form meets the form requirements
final List<FormConfiguration> formFields = updateProfileProfile.readSettingAsForm(PwmSetting.UPDATE_PROFILE_FORM);
final Map<FormConfiguration, String> formValues = FormUtility.readFormValuesFromMap(updateProfileBean.getFormData(), formFields, pwmRequest.getLocale());
UpdateProfileUtil.verifyFormAttributes(pwmRequest.getPwmApplication(), pwmRequest.getUserInfoIfLoggedIn(), pwmRequest.getLocale(), formValues, true);
} catch (PwmException e) {
LOGGER.error(pwmSession, e.getMessage());
setLastError(pwmRequest, e.getErrorInformation());
UpdateProfileUtil.forwardToForm(pwmRequest, updateProfileProfile, updateProfileBean);
return;
}
{
final boolean requireConfirmation = updateProfileProfile.readSettingAsBoolean(PwmSetting.UPDATE_PROFILE_SHOW_CONFIRMATION);
if (requireConfirmation && !updateProfileBean.isConfirmationPassed()) {
UpdateProfileUtil.forwardToConfirmForm(pwmRequest, updateProfileProfile, updateProfileBean);
return;
}
}
if (UpdateProfileUtil.checkForTokenVerificationProgress(pwmRequest, updateProfileBean, updateProfileProfile) == ProcessStatus.Halt) {
return;
}
try {
// write the form values
final ChaiUser theUser = pwmSession.getSessionManager().getActor(pwmApplication);
UpdateProfileUtil.doProfileUpdate(pwmRequest.getPwmApplication(), pwmRequest.getSessionLabel(), pwmRequest.getLocale(), pwmSession.getUserInfo(), pwmSession.getSessionManager().getMacroMachine(pwmApplication), updateProfileProfile, updateProfileBean.getFormData(), theUser);
// re-populate the uiBean because we have changed some values.
pwmSession.reloadUserInfoBean(pwmApplication);
// clear cached read attributes.
pwmRequest.getPwmSession().reloadUserInfoBean(pwmApplication);
// mark the event log
pwmApplication.getAuditManager().submit(AuditEvent.UPDATE_PROFILE, pwmSession.getUserInfo(), pwmSession);
// clear the bean
pwmApplication.getSessionStateService().clearBean(pwmRequest, UpdateProfileBean.class);
pwmRequest.getPwmResponse().forwardToSuccessPage(Message.Success_UpdateProfile);
return;
} catch (PwmException e) {
LOGGER.error(pwmSession, e.getMessage());
setLastError(pwmRequest, e.getErrorInformation());
} catch (ChaiException e) {
final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_UPDATE_ATTRS_FAILURE, e.toString());
LOGGER.error(pwmSession, errorInformation.toDebugStr());
setLastError(pwmRequest, errorInformation);
}
UpdateProfileUtil.forwardToForm(pwmRequest, updateProfileProfile, updateProfileBean);
}
use of password.pwm.PwmApplication in project pwm by pwm-project.
the class CaptchaUtility method verifyReCaptcha.
public static boolean verifyReCaptcha(final PwmRequest pwmRequest, final String recaptchaResponse) throws PwmUnrecoverableException {
if (!captchaEnabledForRequest(pwmRequest)) {
return true;
}
final PwmApplication pwmApplication = pwmRequest.getPwmApplication();
final PasswordData privateKey = pwmApplication.getConfig().readSettingAsPassword(PwmSetting.RECAPTCHA_KEY_PRIVATE);
final StringBuilder bodyText = new StringBuilder();
bodyText.append("secret=").append(privateKey.getStringValue());
bodyText.append("&");
bodyText.append("remoteip=").append(pwmRequest.getSessionLabel().getSrcAddress());
bodyText.append("&");
bodyText.append("response=").append(recaptchaResponse);
try {
final PwmHttpClientRequest clientRequest = new PwmHttpClientRequest(HttpMethod.POST, pwmApplication.getConfig().readAppProperty(AppProperty.RECAPTCHA_VALIDATE_URL), bodyText.toString(), Collections.singletonMap("Content-Type", HttpContentType.form.getHeaderValue()));
LOGGER.debug(pwmRequest, "sending reCaptcha verification request");
final PwmHttpClient client = new PwmHttpClient(pwmRequest.getPwmApplication(), pwmRequest.getSessionLabel());
final PwmHttpClientResponse clientResponse = client.makeRequest(clientRequest);
if (clientResponse.getStatusCode() != HttpServletResponse.SC_OK) {
throw new PwmUnrecoverableException(new ErrorInformation(PwmError.ERROR_CAPTCHA_API_ERROR, "unexpected HTTP status code (" + clientResponse.getStatusCode() + ")"));
}
final JsonElement responseJson = new JsonParser().parse(clientResponse.getBody());
final JsonObject topObject = responseJson.getAsJsonObject();
if (topObject != null && topObject.has("success")) {
final boolean success = topObject.get("success").getAsBoolean();
if (success) {
writeCaptchaSkipCookie(pwmRequest);
return true;
}
if (topObject.has("error-codes")) {
final List<String> errorCodes = new ArrayList<>();
for (final JsonElement element : topObject.get("error-codes").getAsJsonArray()) {
final String errorCode = element.getAsString();
errorCodes.add(errorCode);
}
LOGGER.debug(pwmRequest, "recaptcha error codes: " + JsonUtil.serializeCollection(errorCodes));
}
}
} catch (Exception e) {
final String errorMsg = "unexpected error during reCaptcha API execution: " + e.getMessage();
LOGGER.error(errorMsg, e);
final ErrorInformation errorInfo = new ErrorInformation(PwmError.ERROR_CAPTCHA_API_ERROR, errorMsg);
final PwmUnrecoverableException pwmE = new PwmUnrecoverableException(errorInfo);
pwmE.initCause(e);
throw pwmE;
}
return false;
}
use of password.pwm.PwmApplication in project pwm by pwm-project.
the class Validator method validatePwmFormID.
public static void validatePwmFormID(final PwmRequest pwmRequest) throws PwmUnrecoverableException {
final PwmSession pwmSession = pwmRequest.getPwmSession();
final PwmApplication pwmApplication = pwmRequest.getPwmApplication();
final String submittedPwmFormID = pwmRequest.readParameterAsString(PwmConstants.PARAM_FORM_ID);
if (pwmApplication.getConfig().readSettingAsBoolean(PwmSetting.SECURITY_ENABLE_FORM_NONCE)) {
final FormNonce formNonce = pwmRequest.getPwmApplication().getSecureService().decryptObject(submittedPwmFormID, FormNonce.class);
if (formNonce == null) {
throw new PwmUnrecoverableException(new ErrorInformation(PwmError.ERROR_INVALID_FORMID, "form nonce missing"));
}
if (!pwmSession.getLoginInfoBean().getGuid().equals(formNonce.getSessionGUID())) {
throw new PwmUnrecoverableException(new ErrorInformation(PwmError.ERROR_INVALID_FORMID, "form nonce incorrect"));
}
}
}
Aggregations