use of password.pwm.util.PasswordData in project pwm by pwm-project.
the class PasswordUtility method setActorPassword.
/**
* 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>
* <li> ldap password set is attempted<br/>
* <br/>if successful:
* <ul>
* <li> uiBean is updated with old and new passwords </li>
* <li> uiBean's password expire flag is set to false </li>
* <li> any configured external methods are invoked </li>
* <li> user email notification is sent </li>
* <li> return true </li>
* </ul>
* <br/>if unsuccessful
* <ul>
* <li> ssBean is updated with appropriate error </li>
* <li> return false </li>
* </ul>
* </li>
* </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 UserInfo userInfo = pwmSession.getUserInfo();
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);
}
// but we do it just in case.
try {
final PwmPasswordRuleValidator pwmPasswordRuleValidator = new PwmPasswordRuleValidator(pwmApplication, userInfo.getPasswordPolicy());
pwmPasswordRuleValidator.testPassword(newPassword, null, userInfo, 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() == DirectoryVendor.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);
}
}
final ChaiProvider provider = pwmSession.getSessionManager().getChaiProvider();
setPassword(pwmApplication, pwmSession.getLabel(), provider, userInfo, setPasswordWithoutOld ? null : oldPassword, newPassword);
// 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, userInfo.getUserIdentity(), newPassword);
// clear the "requires new password flag"
pwmSession.getLoginInfoBean().getLoginFlags().remove(LoginInfoBean.LoginFlag.forcePwChange);
// 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".
pwmSession.reloadUserInfoBean(pwmApplication);
// 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);
}
// 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 = MacroMachine.forUser(pwmApplication, pwmSession.getLabel(), pwmSession.getUserInfo(), clonedLoginInfoBean);
final ActionExecutor actionExecutor = new ActionExecutor.ActionExecutorSettings(pwmApplication, userInfo.getUserIdentity()).setMacroMachine(macroMachine).setExpandPwmMacros(true).createActionExecutor();
actionExecutor.executeActions(configValues, pwmSession.getLabel());
}
}
// update the current last password update field in ldap
LdapOperationsHelper.updateLastPasswordUpdateAttribute(pwmApplication, pwmSession.getLabel(), userInfo.getUserIdentity());
}
use of password.pwm.util.PasswordData in project pwm by pwm-project.
the class PasswordUtility method checkEnteredPassword.
public static PasswordCheckInfo checkEnteredPassword(final PwmApplication pwmApplication, final Locale locale, final ChaiUser user, final UserInfo userInfo, final LoginInfoBean loginInfoBean, final PasswordData password, final PasswordData confirmPassword) throws PwmUnrecoverableException, ChaiUnavailableException {
if (userInfo == null) {
throw new NullPointerException("userInfoBean cannot be null");
}
boolean pass = false;
String userMessage = "";
int errorCode = 0;
final boolean passwordIsCaseSensitive = userInfo.getPasswordPolicy() == null || userInfo.getPasswordPolicy().getRuleHelper().readBooleanValue(PwmPasswordRule.CaseSensitive);
final CachePolicy cachePolicy;
{
final long cacheLifetimeMS = Long.parseLong(pwmApplication.getConfig().readAppProperty(AppProperty.CACHE_PWRULECHECK_LIFETIME_MS));
cachePolicy = CachePolicy.makePolicyWithExpirationMS(cacheLifetimeMS);
}
if (password == null) {
userMessage = new ErrorInformation(PwmError.PASSWORD_MISSING).toUserStr(locale, pwmApplication.getConfig());
} else {
final CacheService cacheService = pwmApplication.getCacheService();
final CacheKey cacheKey = user != null && userInfo.getUserIdentity() != null ? CacheKey.makeCacheKey(PasswordUtility.class, userInfo.getUserIdentity(), user.getEntryDN() + ":" + password.hash()) : null;
if (pwmApplication.getConfig().isDevDebugMode()) {
LOGGER.trace("generated cacheKey for password check request: " + cacheKey);
}
try {
if (cacheService != null && cacheKey != null) {
final String cachedValue = cacheService.get(cacheKey);
if (cachedValue != null) {
if (NEGATIVE_CACHE_HIT.equals(cachedValue)) {
pass = true;
} else {
LOGGER.trace("cache hit!");
final ErrorInformation errorInformation = JsonUtil.deserialize(cachedValue, ErrorInformation.class);
throw new PwmDataValidationException(errorInformation);
}
}
}
if (!pass) {
final PwmPasswordRuleValidator pwmPasswordRuleValidator = new PwmPasswordRuleValidator(pwmApplication, userInfo.getPasswordPolicy(), locale);
final PasswordData oldPassword = loginInfoBean == null ? null : loginInfoBean.getUserCurrentPassword();
pwmPasswordRuleValidator.testPassword(password, oldPassword, userInfo, user);
pass = true;
if (cacheService != null && cacheKey != null) {
cacheService.put(cacheKey, cachePolicy, NEGATIVE_CACHE_HIT);
}
}
} catch (PwmDataValidationException e) {
errorCode = e.getError().getErrorCode();
userMessage = e.getErrorInformation().toUserStr(locale, pwmApplication.getConfig());
pass = false;
if (cacheService != null && cacheKey != null) {
final String jsonPayload = JsonUtil.serialize(e.getErrorInformation());
cacheService.put(cacheKey, cachePolicy, jsonPayload);
}
}
}
final PasswordCheckInfo.MatchStatus matchStatus = figureMatchStatus(passwordIsCaseSensitive, password, confirmPassword);
if (pass) {
switch(matchStatus) {
case EMPTY:
userMessage = new ErrorInformation(PwmError.PASSWORD_MISSING_CONFIRM).toUserStr(locale, pwmApplication.getConfig());
break;
case MATCH:
userMessage = new ErrorInformation(PwmError.PASSWORD_MEETS_RULES).toUserStr(locale, pwmApplication.getConfig());
break;
case NO_MATCH:
userMessage = new ErrorInformation(PwmError.PASSWORD_DOESNOTMATCH).toUserStr(locale, pwmApplication.getConfig());
break;
default:
userMessage = "";
}
}
final int strength = judgePasswordStrength(pwmApplication.getConfig(), password == null ? null : password.getStringValue());
return new PasswordCheckInfo(userMessage, pass, strength, matchStatus, errorCode);
}
use of password.pwm.util.PasswordData in project pwm by pwm-project.
the class ActionExecutor method executeWebserviceAction.
private void executeWebserviceAction(final SessionLabel sessionLabel, final ActionConfiguration actionConfiguration) throws PwmOperationalException, PwmUnrecoverableException {
String url = actionConfiguration.getUrl();
String body = actionConfiguration.getBody();
final Map<String, String> headers = new LinkedHashMap<>();
if (actionConfiguration.getHeaders() != null) {
headers.putAll(actionConfiguration.getHeaders());
}
try {
// expand using pwm macros
if (settings.isExpandPwmMacros()) {
if (settings.getMacroMachine() == null) {
throw new PwmUnrecoverableException(new ErrorInformation(PwmError.ERROR_UNKNOWN, "executor specified macro expansion but did not supply macro machine"));
}
final MacroMachine macroMachine = settings.getMacroMachine();
url = macroMachine.expandMacros(url);
body = body == null ? "" : macroMachine.expandMacros(body);
for (final Map.Entry<String, String> entry : headers.entrySet()) {
final String headerName = entry.getKey();
final String headerValue = entry.getValue();
if (headerValue != null) {
headers.put(headerName, macroMachine.expandMacros(headerValue));
}
}
}
// add basic auth header;
if (!StringUtil.isEmpty(actionConfiguration.getUsername()) && !StringUtil.isEmpty(actionConfiguration.getPassword())) {
final String authHeaderValue = new BasicAuthInfo(actionConfiguration.getUsername(), new PasswordData(actionConfiguration.getPassword())).toAuthHeader();
headers.put(HttpHeader.Authorization.getHttpName(), authHeaderValue);
}
final HttpMethod method = HttpMethod.fromString(actionConfiguration.getMethod().toString());
final PwmHttpClientRequest clientRequest = new PwmHttpClientRequest(method, url, body, headers);
final PwmHttpClient client;
{
if (actionConfiguration.getCertificates() != null) {
final PwmHttpClientConfiguration clientConfiguration = PwmHttpClientConfiguration.builder().certificates(actionConfiguration.getCertificates()).build();
client = new PwmHttpClient(pwmApplication, sessionLabel, clientConfiguration);
} else {
client = new PwmHttpClient(pwmApplication, sessionLabel);
}
}
final PwmHttpClientResponse clientResponse = client.makeRequest(clientRequest);
if (clientResponse.getStatusCode() != 200) {
throw new PwmOperationalException(new ErrorInformation(PwmError.ERROR_SERVICE_UNREACHABLE, "unexpected HTTP status code while calling external web service: " + clientResponse.getStatusCode() + " " + clientResponse.getStatusPhrase()));
}
} catch (PwmException e) {
if (e instanceof PwmOperationalException) {
throw (PwmOperationalException) e;
}
final String errorMsg = "unexpected error during API execution: " + e.getMessage();
LOGGER.error(errorMsg);
throw new PwmOperationalException(new ErrorInformation(PwmError.ERROR_UNKNOWN, errorMsg));
}
}
use of password.pwm.util.PasswordData in project pwm by pwm-project.
the class RestFormDataClient method invoke.
public FormDataResponseBean invoke(final FormDataRequestBean formDataRequestBean, final Locale locale) throws PwmUnrecoverableException {
final Map<String, String> httpHeaders = new LinkedHashMap<>();
httpHeaders.put(HttpHeader.Accept.getHttpName(), PwmConstants.AcceptValue.json.getHeaderValue());
httpHeaders.put(HttpHeader.Content_Type.getHttpName(), HttpContentType.json.getHeaderValue());
if (locale != null) {
httpHeaders.put(HttpHeader.Accept_Language.getHttpName(), locale.toString());
}
{
final Map<String, String> configuredHeaders = new LinkedHashMap<>(remoteWebServiceConfiguration.getHeaders());
// add basic auth header;
if (!StringUtil.isEmpty(remoteWebServiceConfiguration.getUsername()) && !StringUtil.isEmpty(remoteWebServiceConfiguration.getPassword())) {
final String authHeaderValue = new BasicAuthInfo(remoteWebServiceConfiguration.getUsername(), new PasswordData(remoteWebServiceConfiguration.getPassword())).toAuthHeader();
configuredHeaders.put(HttpHeader.Authorization.getHttpName(), authHeaderValue);
}
httpHeaders.putAll(configuredHeaders);
}
final String jsonRequestBody = JsonUtil.serialize(formDataRequestBean);
final PwmHttpClientRequest pwmHttpClientRequest = new PwmHttpClientRequest(HttpMethod.POST, remoteWebServiceConfiguration.getUrl(), jsonRequestBody, httpHeaders);
final PwmHttpClientResponse httpResponse;
try {
httpResponse = getHttpClient(pwmApplication.getConfig()).makeRequest(pwmHttpClientRequest);
final String responseBody = httpResponse.getBody();
LOGGER.trace("external rest call returned: " + httpResponse.getStatusPhrase() + ", body: " + responseBody);
if (httpResponse.getStatusCode() != 200) {
final String errorMsg = "received non-200 response code (" + httpResponse.getStatusCode() + ") when executing web-service";
LOGGER.error(errorMsg);
throw new PwmUnrecoverableException(new ErrorInformation(PwmError.ERROR_SERVICE_UNREACHABLE, errorMsg));
}
final FormDataResponseBean formDataResponseBean = JsonUtil.deserialize(responseBody, FormDataResponseBean.class);
return formDataResponseBean;
} catch (PwmUnrecoverableException e) {
final String errorMsg = "http response error while executing external rest call, error: " + e.getMessage();
LOGGER.error(errorMsg);
throw new PwmUnrecoverableException(new ErrorInformation(PwmError.ERROR_SERVICE_UNREACHABLE, errorMsg), e);
}
}
use of password.pwm.util.PasswordData in project pwm by pwm-project.
the class RestCheckPasswordServer method doOperation.
public RestResultBean doOperation(final RestRequest restRequest, final JsonInput jsonInput) throws PwmUnrecoverableException {
final Instant startTime = Instant.now();
if (StringUtil.isEmpty(jsonInput.getPassword1())) {
final String errorMessage = "missing field '" + FIELD_PASSWORD_1 + "'";
final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_FIELD_REQUIRED, errorMessage, new String[] { FIELD_PASSWORD_1 });
return RestResultBean.fromError(restRequest, errorInformation);
}
try {
final TargetUserIdentity targetUserIdentity = RestUtility.resolveRequestedUsername(restRequest, jsonInput.getUsername());
final UserInfo userInfo = UserInfoFactory.newUserInfo(restRequest.getPwmApplication(), restRequest.getSessionLabel(), restRequest.getLocale(), targetUserIdentity.getUserIdentity(), targetUserIdentity.getChaiProvider());
final PasswordCheckRequest checkRequest = new PasswordCheckRequest(targetUserIdentity.getUserIdentity(), StringUtil.isEmpty(jsonInput.getPassword1()) ? null : new PasswordData(jsonInput.getPassword1()), StringUtil.isEmpty(jsonInput.getPassword2()) ? null : new PasswordData(jsonInput.getPassword2()), userInfo);
restRequest.getPwmApplication().getStatisticsManager().incrementValue(Statistic.REST_CHECKPASSWORD);
final PasswordUtility.PasswordCheckInfo passwordCheckInfo = PasswordUtility.checkEnteredPassword(restRequest.getPwmApplication(), restRequest.getLocale(), targetUserIdentity.getChaiUser(), checkRequest.getUserInfo(), null, checkRequest.getPassword1(), checkRequest.getPassword2());
final JsonOutput jsonOutput = JsonOutput.fromPasswordCheckInfo(passwordCheckInfo);
final RestResultBean restResultBean = RestResultBean.withData(jsonOutput);
final TimeDuration timeDuration = TimeDuration.fromCurrent(startTime);
LOGGER.trace(restRequest.getSessionLabel(), "REST /checkpassword response (" + timeDuration.asCompactString() + "): " + JsonUtil.serialize(jsonOutput));
return restResultBean;
} catch (PwmException e) {
LOGGER.debug(restRequest.getSessionLabel(), "REST /checkpassword error during execution: " + e.getMessage());
return RestResultBean.fromError(restRequest, e.getErrorInformation());
} catch (Exception e) {
final String errorMessage = "unexpected error executing web service: " + e.getMessage();
final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_UNKNOWN, errorMessage);
LOGGER.error(restRequest.getSessionLabel(), errorInformation.toDebugStr(), e);
return RestResultBean.fromError(restRequest, errorInformation);
}
}
Aggregations