use of password.pwm.error.PwmException in project pwm by pwm-project.
the class PasswordUtility method setPassword.
public static void setPassword(final PwmApplication pwmApplication, final SessionLabel sessionLabel, final ChaiProvider chaiProvider, final UserInfo userInfo, final PasswordData oldPassword, final PasswordData newPassword) throws PwmUnrecoverableException, PwmOperationalException {
final UserIdentity userIdentity = userInfo.getUserIdentity();
final Instant startTime = Instant.now();
final boolean bindIsSelf;
final String bindDN;
try {
final ChaiUser theUser = chaiProvider.getEntryFactory().newChaiUser(userIdentity.getUserDN());
final Locale locale = PwmConstants.DEFAULT_LOCALE;
final PwmPasswordPolicy passwordPolicy = PasswordUtility.readPasswordPolicyForUser(pwmApplication, sessionLabel, userIdentity, theUser, locale);
final PwmPasswordRuleValidator pwmPasswordRuleValidator = new PwmPasswordRuleValidator(pwmApplication, passwordPolicy);
pwmPasswordRuleValidator.testPassword(newPassword, null, userInfo, theUser);
} catch (ChaiUnavailableException e) {
throw PwmUnrecoverableException.fromChaiException(e);
} catch (PwmException e) {
throw new PwmUnrecoverableException(e.getErrorInformation());
}
try {
final ChaiUser theUser = chaiProvider.getEntryFactory().newChaiUser(userIdentity.getUserDN());
bindDN = chaiProvider.getChaiConfiguration().getSetting(ChaiSetting.BIND_DN);
bindIsSelf = userIdentity.canonicalEquals(new UserIdentity(bindDN, userIdentity.getLdapProfileID()), pwmApplication);
LOGGER.trace(sessionLabel, "preparing to setActorPassword for '" + theUser.getEntryDN() + "', using bind DN: " + bindDN);
final boolean settingEnableChange = Boolean.parseBoolean(pwmApplication.getConfig().readAppProperty(AppProperty.LDAP_PASSWORD_CHANGE_SELF_ENABLE));
if (settingEnableChange) {
if (oldPassword == null) {
theUser.setPassword(newPassword.getStringValue(), true);
} else {
theUser.changePassword(oldPassword.getStringValue(), newPassword.getStringValue());
}
} else {
LOGGER.debug(sessionLabel, "skipping actual ldap password change operation due to app property " + AppProperty.LDAP_PASSWORD_CHANGE_SELF_ENABLE.getKey() + "=false");
}
} catch (ChaiPasswordPolicyException e) {
final String errorMsg = "error setting password for user '" + userIdentity.toDisplayString() + "'' " + 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 '" + userIdentity.toDisplayString() + "'' " + 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);
} catch (ChaiUnavailableException e) {
throw PwmUnrecoverableException.fromChaiException(e);
}
// 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(sessionLabel, oldPassword.getStringValue());
}
// update stats
pwmApplication.getStatisticsManager().updateEps(EpsStatistic.PASSWORD_CHANGES, 1);
final int passwordStrength = PasswordUtility.judgePasswordStrength(pwmApplication.getConfig(), newPassword.getStringValue());
pwmApplication.getStatisticsManager().updateAverageValue(Statistic.AVG_PASSWORD_STRENGTH, passwordStrength);
// at this point the password has been changed, so log it.
final String msg = (bindIsSelf ? "user " + userIdentity.toDisplayString() + " has changed own password" : "password for user '" + userIdentity.toDisplayString() + "' has been changed by " + bindDN) + " (" + TimeDuration.fromCurrent(startTime).asCompactString() + ")";
LOGGER.info(sessionLabel, msg);
}
use of password.pwm.error.PwmException 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.error.PwmException in project pwm by pwm-project.
the class DatabaseService method healthCheck.
public List<HealthRecord> healthCheck() {
if (status == PwmService.STATUS.CLOSED) {
return Collections.emptyList();
}
final List<HealthRecord> returnRecords = new ArrayList<>();
if (!initialized) {
returnRecords.add(new HealthRecord(HealthStatus.WARN, HealthTopic.Database, makeUninitializedError().getDetailedErrorMsg()));
return returnRecords;
}
try {
final Map<String, String> tempMap = new HashMap<>();
tempMap.put("date", JavaHelper.toIsoDate(Instant.now()));
final DatabaseAccessor accessor = getAccessor();
accessor.put(DatabaseTable.PWM_META, KEY_TEST, JsonUtil.serializeMap(tempMap));
} catch (PwmException e) {
returnRecords.add(new HealthRecord(HealthStatus.WARN, HealthTopic.Database, "Error writing to database: " + e.getErrorInformation().toDebugStr()));
return returnRecords;
}
if (lastError != null) {
final TimeDuration errorAge = TimeDuration.fromCurrent(lastError.getDate());
if (errorAge.isShorterThan(TimeDuration.HOUR)) {
final String msg = "Database server was recently unavailable (" + errorAge.asLongString(PwmConstants.DEFAULT_LOCALE) + " ago at " + lastError.getDate().toString() + "): " + lastError.toDebugStr();
returnRecords.add(new HealthRecord(HealthStatus.CAUTION, HealthTopic.Database, msg));
}
}
if (returnRecords.isEmpty()) {
returnRecords.add(new HealthRecord(HealthStatus.GOOD, HealthTopic.Database, "Database connection to " + this.dbConfiguration.getConnectionString() + " okay"));
}
return returnRecords;
}
use of password.pwm.error.PwmException in project pwm by pwm-project.
the class ExternalRestMacro method replaceValue.
public String replaceValue(final String matchValue, final MacroRequestInfo macroRequestInfo) {
final PwmApplication pwmApplication = macroRequestInfo.getPwmApplication();
final UserInfo userInfoBean = macroRequestInfo.getUserInfo();
final String inputString = matchValue.substring(11, matchValue.length() - 1);
final Map<String, Object> sendData = new HashMap<>();
try {
if (userInfoBean != null) {
final MacroMachine macroMachine = MacroMachine.forUser(pwmApplication, PwmConstants.DEFAULT_LOCALE, SessionLabel.SYSTEM_LABEL, userInfoBean.getUserIdentity());
final PublicUserInfoBean publicUserInfoBean = PublicUserInfoBean.fromUserInfoBean(userInfoBean, pwmApplication.getConfig(), PwmConstants.DEFAULT_LOCALE, macroMachine);
sendData.put("userInfo", publicUserInfoBean);
}
sendData.put("input", inputString);
final String requestBody = JsonUtil.serializeMap(sendData);
final String responseBody = RestClientHelper.makeOutboundRestWSCall(pwmApplication, PwmConstants.DEFAULT_LOCALE, url, requestBody);
final Map<String, Object> responseMap = JsonUtil.deserialize(responseBody, new TypeToken<Map<String, Object>>() {
});
if (responseMap.containsKey("output")) {
return responseMap.get("output").toString();
} else {
return "";
}
} catch (PwmException e) {
final String errorMsg = "error while executing external macro '" + matchValue + "', error: " + e.getMessage();
LOGGER.error(errorMsg);
throw new IllegalStateException(errorMsg);
}
}
use of password.pwm.error.PwmException 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