Search in sources :

Example 36 with UserInfo

use of password.pwm.ldap.UserInfo in project pwm by pwm-project.

the class LdapTokenMachine method retrieveToken.

public TokenPayload retrieveToken(final TokenKey tokenKey) throws PwmOperationalException, PwmUnrecoverableException {
    final String searchFilter;
    {
        final String storedHash = tokenKey.getStoredHash();
        final SearchHelper tempSearchHelper = new SearchHelper();
        final Map<String, String> filterAttributes = new HashMap<>();
        for (final String loopStr : pwmApplication.getConfig().readSettingAsStringArray(PwmSetting.DEFAULT_OBJECT_CLASSES)) {
            filterAttributes.put("objectClass", loopStr);
        }
        filterAttributes.put(tokenAttribute, storedHash + "*");
        tempSearchHelper.setFilterAnd(filterAttributes);
        searchFilter = tempSearchHelper.getFilter();
    }
    try {
        final UserSearchEngine userSearchEngine = pwmApplication.getUserSearchEngine();
        final SearchConfiguration searchConfiguration = SearchConfiguration.builder().filter(searchFilter).build();
        final UserIdentity user = userSearchEngine.performSingleUserSearch(searchConfiguration, null);
        if (user == null) {
            return null;
        }
        final UserInfo userInfo = UserInfoFactory.newUserInfoUsingProxy(pwmApplication, null, user, null);
        final String tokenAttributeValue = userInfo.readStringAttribute(tokenAttribute);
        if (tokenAttribute != null && tokenAttributeValue.length() > 0) {
            final String[] splitString = tokenAttributeValue.split(KEY_VALUE_DELIMITER);
            if (splitString.length != 2) {
                final String errorMsg = "error parsing ldap stored token, not enough delimited values";
                final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_TOKEN_INCORRECT, errorMsg);
                throw new PwmOperationalException(errorInformation);
            }
            return tokenService.fromEncryptedString(splitString[1]);
        }
    } catch (PwmOperationalException e) {
        if (e.getError() == PwmError.ERROR_CANT_MATCH_USER) {
            return null;
        }
        throw e;
    } catch (PwmUnrecoverableException e) {
        final String errorMsg = "unexpected ldap error searching for token: " + e.getMessage();
        final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_TOKEN_INCORRECT, errorMsg);
        throw new PwmOperationalException(errorInformation);
    }
    return null;
}
Also used : ErrorInformation(password.pwm.error.ErrorInformation) UserSearchEngine(password.pwm.ldap.search.UserSearchEngine) UserIdentity(password.pwm.bean.UserIdentity) SearchConfiguration(password.pwm.ldap.search.SearchConfiguration) UserInfo(password.pwm.ldap.UserInfo) PwmUnrecoverableException(password.pwm.error.PwmUnrecoverableException) SearchHelper(com.novell.ldapchai.util.SearchHelper) HashMap(java.util.HashMap) Map(java.util.Map) PwmOperationalException(password.pwm.error.PwmOperationalException)

Example 37 with UserInfo

use of password.pwm.ldap.UserInfo 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());
}
Also used : LoginInfoBean(password.pwm.bean.LoginInfoBean) UserInfo(password.pwm.ldap.UserInfo) PwmOperationalException(password.pwm.error.PwmOperationalException) ErrorInformation(password.pwm.error.ErrorInformation) PwmPasswordRuleValidator(password.pwm.util.PwmPasswordRuleValidator) PwmDataValidationException(password.pwm.error.PwmDataValidationException) ChaiProvider(com.novell.ldapchai.provider.ChaiProvider) ChaiUser(com.novell.ldapchai.ChaiUser) PasswordData(password.pwm.util.PasswordData) MacroMachine(password.pwm.util.macro.MacroMachine) List(java.util.List) ArrayList(java.util.ArrayList)

Example 38 with UserInfo

use of password.pwm.ldap.UserInfo 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);
    }
}
Also used : PwmException(password.pwm.error.PwmException) PwmApplication(password.pwm.PwmApplication) HashMap(java.util.HashMap) UserInfo(password.pwm.ldap.UserInfo) HashMap(java.util.HashMap) Map(java.util.Map) PublicUserInfoBean(password.pwm.bean.pub.PublicUserInfoBean)

Example 39 with UserInfo

use of password.pwm.ldap.UserInfo 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);
    }
}
Also used : Instant(java.time.Instant) PasswordUtility(password.pwm.util.operations.PasswordUtility) UserInfo(password.pwm.ldap.UserInfo) PwmUnrecoverableException(password.pwm.error.PwmUnrecoverableException) PwmException(password.pwm.error.PwmException) IOException(java.io.IOException) PwmException(password.pwm.error.PwmException) ErrorInformation(password.pwm.error.ErrorInformation) PasswordData(password.pwm.util.PasswordData) TimeDuration(password.pwm.util.java.TimeDuration) RestResultBean(password.pwm.ws.server.RestResultBean)

Example 40 with UserInfo

use of password.pwm.ldap.UserInfo in project pwm by pwm-project.

the class RestSetPasswordServer method doSetPassword.

private static RestResultBean doSetPassword(final RestRequest restRequest, final JsonInputData jsonInputData) {
    final String password = jsonInputData.getPassword();
    final boolean random = jsonInputData.isRandom();
    if ((password == null || password.length() < 1) && !random) {
        final String errorMessage = "field '" + FIELD_PASSWORD + "' must have a value or field '" + FIELD_RANDOM + "' must be set to true";
        final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_MISSING_PARAMETER, errorMessage, new String[] { FIELD_PASSWORD });
        return RestResultBean.fromError(restRequest, errorInformation);
    }
    if ((password != null && password.length() > 0) && random) {
        final String errorMessage = "field '" + FIELD_PASSWORD + "' cannot have a value or field '" + FIELD_RANDOM + "' must be set to true";
        final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_MISSING_PARAMETER, errorMessage, new String[] { FIELD_PASSWORD });
        return RestResultBean.fromError(restRequest, errorInformation);
    }
    try {
        final TargetUserIdentity targetUserIdentity = RestUtility.resolveRequestedUsername(restRequest, jsonInputData.username);
        final PasswordData newPassword;
        if (random) {
            final PwmPasswordPolicy passwordPolicy = PasswordUtility.readPasswordPolicyForUser(restRequest.getPwmApplication(), restRequest.getSessionLabel(), targetUserIdentity.getUserIdentity(), targetUserIdentity.getChaiUser(), restRequest.getLocale());
            newPassword = RandomPasswordGenerator.createRandomPassword(restRequest.getSessionLabel(), passwordPolicy, restRequest.getPwmApplication());
        } else {
            newPassword = new PasswordData(password);
        }
        final PasswordData oldPassword;
        if (targetUserIdentity.isSelf()) {
            final BasicAuthInfo basicAuthInfo = BasicAuthInfo.parseAuthHeader(restRequest.getPwmApplication(), restRequest.getHttpServletRequest());
            oldPassword = basicAuthInfo == null ? null : basicAuthInfo.getPassword();
        } else {
            oldPassword = null;
        }
        final UserInfo userInfo = UserInfoFactory.newUserInfoUsingProxy(restRequest.getPwmApplication(), restRequest.getSessionLabel(), targetUserIdentity.getUserIdentity(), restRequest.getLocale());
        PasswordUtility.setPassword(restRequest.getPwmApplication(), restRequest.getSessionLabel(), targetUserIdentity.getChaiProvider(), userInfo, oldPassword, newPassword);
        StatisticsManager.incrementStat(restRequest.getPwmApplication(), Statistic.REST_SETPASSWORD);
        final JsonInputData jsonResultData = new JsonInputData(targetUserIdentity.getUserIdentity().toDelimitedKey(), null, random);
        return RestResultBean.forSuccessMessage(jsonResultData, restRequest, Message.Success_PasswordChange);
    } catch (PwmException e) {
        LOGGER.error("error during set password REST operation: " + 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("error during set password REST operation: " + e.getMessage(), e);
        return RestResultBean.fromError(restRequest, errorInformation);
    }
}
Also used : PwmException(password.pwm.error.PwmException) ErrorInformation(password.pwm.error.ErrorInformation) PasswordData(password.pwm.util.PasswordData) PwmPasswordPolicy(password.pwm.config.profile.PwmPasswordPolicy) BasicAuthInfo(password.pwm.util.BasicAuthInfo) UserInfo(password.pwm.ldap.UserInfo) PwmUnrecoverableException(password.pwm.error.PwmUnrecoverableException) PwmException(password.pwm.error.PwmException) IOException(java.io.IOException)

Aggregations

UserInfo (password.pwm.ldap.UserInfo)60 ErrorInformation (password.pwm.error.ErrorInformation)23 PwmUnrecoverableException (password.pwm.error.PwmUnrecoverableException)23 FormConfiguration (password.pwm.config.value.data.FormConfiguration)20 PwmApplication (password.pwm.PwmApplication)18 UserIdentity (password.pwm.bean.UserIdentity)15 Configuration (password.pwm.config.Configuration)15 Locale (java.util.Locale)13 MacroMachine (password.pwm.util.macro.MacroMachine)13 ChaiUser (com.novell.ldapchai.ChaiUser)12 PwmOperationalException (password.pwm.error.PwmOperationalException)12 PwmSession (password.pwm.http.PwmSession)12 PasswordData (password.pwm.util.PasswordData)10 Instant (java.time.Instant)9 ArrayList (java.util.ArrayList)8 ActionConfiguration (password.pwm.config.value.data.ActionConfiguration)8 SearchConfiguration (password.pwm.ldap.search.SearchConfiguration)8 RestResultBean (password.pwm.ws.server.RestResultBean)8 List (java.util.List)7 EmailItemBean (password.pwm.bean.EmailItemBean)7