Search in sources :

Example 16 with UserSearchEngine

use of password.pwm.ldap.search.UserSearchEngine 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 17 with UserSearchEngine

use of password.pwm.ldap.search.UserSearchEngine in project pwm by pwm-project.

the class ForgottenPasswordServlet method processSearch.

@ActionHandler(action = "search")
private ProcessStatus processSearch(final PwmRequest pwmRequest) throws ChaiUnavailableException, PwmUnrecoverableException, IOException, ServletException {
    final PwmSession pwmSession = pwmRequest.getPwmSession();
    final Locale userLocale = pwmRequest.getLocale();
    final PwmApplication pwmApplication = pwmRequest.getPwmApplication();
    final String contextParam = pwmRequest.readParameterAsString(PwmConstants.PARAM_CONTEXT);
    final String ldapProfile = pwmRequest.readParameterAsString(PwmConstants.PARAM_LDAP_PROFILE);
    final boolean bogusUserModeEnabled = pwmRequest.getConfig().readSettingAsBoolean(PwmSetting.RECOVERY_BOGUS_USER_ENABLE);
    // clear the bean
    clearForgottenPasswordBean(pwmRequest);
    if (CaptchaUtility.captchaEnabledForRequest(pwmRequest)) {
        if (!CaptchaUtility.verifyReCaptcha(pwmRequest)) {
            final ErrorInformation errorInfo = new ErrorInformation(PwmError.ERROR_BAD_CAPTCHA_RESPONSE);
            LOGGER.debug(pwmRequest, errorInfo);
            setLastError(pwmRequest, errorInfo);
            return ProcessStatus.Continue;
        }
    }
    final List<FormConfiguration> forgottenPasswordForm = pwmApplication.getConfig().readSettingAsForm(PwmSetting.FORGOTTEN_PASSWORD_SEARCH_FORM);
    Map<FormConfiguration, String> formValues = new LinkedHashMap<>();
    try {
        // read the values from the request
        formValues = FormUtility.readFormValuesFromRequest(pwmRequest, forgottenPasswordForm, userLocale);
        // check for intruder search values
        pwmApplication.getIntruderManager().convenience().checkAttributes(formValues);
        // see if the values meet the configured form requirements.
        FormUtility.validateFormValues(pwmRequest.getConfig(), formValues, userLocale);
        final String searchFilter;
        {
            final String configuredSearchFilter = pwmApplication.getConfig().readSettingAsString(PwmSetting.FORGOTTEN_PASSWORD_SEARCH_FILTER);
            if (configuredSearchFilter == null || configuredSearchFilter.isEmpty()) {
                searchFilter = FormUtility.ldapSearchFilterForForm(pwmApplication, forgottenPasswordForm);
                LOGGER.trace(pwmSession, "auto generated ldap search filter: " + searchFilter);
            } else {
                searchFilter = configuredSearchFilter;
            }
        }
        // convert the username field to an identity
        final UserIdentity userIdentity;
        {
            final UserSearchEngine userSearchEngine = pwmApplication.getUserSearchEngine();
            final SearchConfiguration searchConfiguration = SearchConfiguration.builder().filter(searchFilter).formValues(formValues).contexts(Collections.singletonList(contextParam)).ldapProfile(ldapProfile).build();
            userIdentity = userSearchEngine.performSingleUserSearch(searchConfiguration, pwmRequest.getSessionLabel());
        }
        if (userIdentity == null) {
            throw new PwmOperationalException(new ErrorInformation(PwmError.ERROR_CANT_MATCH_USER));
        }
        AuthenticationUtility.checkIfUserEligibleToAuthentication(pwmApplication, userIdentity);
        final ForgottenPasswordBean forgottenPasswordBean = forgottenPasswordBean(pwmRequest);
        ForgottenPasswordUtil.initForgottenPasswordBean(pwmRequest, userIdentity, forgottenPasswordBean);
        // clear intruder search values
        pwmApplication.getIntruderManager().convenience().clearAttributes(formValues);
        return ProcessStatus.Continue;
    } catch (PwmOperationalException e) {
        if (e.getError() != PwmError.ERROR_CANT_MATCH_USER || !bogusUserModeEnabled) {
            final ErrorInformation errorInfo = new ErrorInformation(PwmError.ERROR_RESPONSES_NORESPONSES, e.getErrorInformation().getDetailedErrorMsg(), e.getErrorInformation().getFieldValues());
            pwmApplication.getStatisticsManager().incrementValue(Statistic.RECOVERY_FAILURES);
            pwmApplication.getIntruderManager().convenience().markAddressAndSession(pwmSession);
            pwmApplication.getIntruderManager().convenience().markAttributes(formValues, pwmSession);
            LOGGER.debug(pwmSession, errorInfo.toDebugStr());
            setLastError(pwmRequest, errorInfo);
            return ProcessStatus.Continue;
        }
    }
    if (bogusUserModeEnabled) {
        ForgottenPasswordUtil.initBogusForgottenPasswordBean(pwmRequest);
        forgottenPasswordBean(pwmRequest).setUserSearchValues(FormUtility.asStringMap(formValues));
    }
    return ProcessStatus.Continue;
}
Also used : Locale(java.util.Locale) PwmApplication(password.pwm.PwmApplication) UserIdentity(password.pwm.bean.UserIdentity) UserSearchEngine(password.pwm.ldap.search.UserSearchEngine) SearchConfiguration(password.pwm.ldap.search.SearchConfiguration) LinkedHashMap(java.util.LinkedHashMap) PwmOperationalException(password.pwm.error.PwmOperationalException) ErrorInformation(password.pwm.error.ErrorInformation) FormConfiguration(password.pwm.config.value.data.FormConfiguration) PwmSession(password.pwm.http.PwmSession) ForgottenPasswordBean(password.pwm.http.bean.ForgottenPasswordBean)

Example 18 with UserSearchEngine

use of password.pwm.ldap.search.UserSearchEngine in project pwm by pwm-project.

the class NewUserUtils method testIfEntryNameExists.

private static boolean testIfEntryNameExists(final PwmRequest pwmRequest, final String rdnValue) throws PwmUnrecoverableException, ChaiUnavailableException {
    final UserSearchEngine userSearchEngine = pwmRequest.getPwmApplication().getUserSearchEngine();
    final SearchConfiguration searchConfiguration = SearchConfiguration.builder().username(rdnValue).build();
    try {
        final Map<UserIdentity, Map<String, String>> results = userSearchEngine.performMultiUserSearch(searchConfiguration, 2, Collections.emptyList(), pwmRequest.getSessionLabel());
        return results != null && !results.isEmpty();
    } catch (PwmOperationalException e) {
        final String msg = "ldap error while searching for duplicate entry names: " + e.getMessage();
        NewUserUtils.LOGGER.error(pwmRequest, msg);
        throw new PwmUnrecoverableException(new ErrorInformation(PwmError.ERROR_NEW_USER_FAILURE, msg));
    }
}
Also used : ErrorInformation(password.pwm.error.ErrorInformation) UserSearchEngine(password.pwm.ldap.search.UserSearchEngine) UserIdentity(password.pwm.bean.UserIdentity) SearchConfiguration(password.pwm.ldap.search.SearchConfiguration) PwmUnrecoverableException(password.pwm.error.PwmUnrecoverableException) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap) PwmOperationalException(password.pwm.error.PwmOperationalException)

Example 19 with UserSearchEngine

use of password.pwm.ldap.search.UserSearchEngine in project pwm by pwm-project.

the class OAuthConsumerServlet method processAction.

@Override
@SuppressWarnings("checkstyle:MethodLength")
protected void processAction(final PwmRequest pwmRequest) throws ServletException, IOException, PwmUnrecoverableException {
    final PwmApplication pwmApplication = pwmRequest.getPwmApplication();
    final Configuration config = pwmRequest.getConfig();
    final PwmSession pwmSession = pwmRequest.getPwmSession();
    final boolean userIsAuthenticated = pwmSession.isAuthenticated();
    final Optional<OAuthRequestState> oAuthRequestState = OAuthMachine.readOAuthRequestState(pwmRequest);
    final OAuthUseCase oAuthUseCaseCase = oAuthRequestState.isPresent() ? oAuthRequestState.get().getoAuthState().getUseCase() : OAuthUseCase.Authentication;
    LOGGER.trace(pwmRequest, "processing oauth return request, useCase=" + oAuthUseCaseCase + ", incoming oAuthRequestState=" + (oAuthRequestState.isPresent() ? JsonUtil.serialize(oAuthRequestState.get()) : "none"));
    // make sure it's okay to be processing this request.
    switch(oAuthUseCaseCase) {
        case Authentication:
            {
                if (!userIsAuthenticated && !pwmSession.getSessionStateBean().isOauthInProgress()) {
                    if (oAuthRequestState.isPresent()) {
                        final String nextUrl = oAuthRequestState.get().getoAuthState().getNextUrl();
                        LOGGER.debug(pwmSession, "received unrecognized oauth response, ignoring authcode and redirecting to embedded next url: " + nextUrl);
                        pwmRequest.sendRedirect(nextUrl);
                        return;
                    }
                    final String errorMsg = "oauth consumer reached, but oauth authentication has not yet been initiated.";
                    final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_OAUTH_ERROR, errorMsg);
                    pwmRequest.respondWithError(errorInformation);
                    LOGGER.error(pwmSession, errorMsg);
                    return;
                }
            }
            break;
        default:
            // for non-auth requests its okay to continue
            break;
    }
    // check if there is an "error" on the request sent from the oauth server., if there is then halt.
    {
        final String oauthRequestError = pwmRequest.readParameterAsString("error");
        if (oauthRequestError != null && !oauthRequestError.isEmpty()) {
            final String errorMsg = "incoming request from remote oauth server is indicating an error: " + oauthRequestError;
            final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_OAUTH_ERROR, errorMsg, "Remote Error: " + oauthRequestError, null);
            LOGGER.error(pwmSession, errorMsg);
            pwmRequest.respondWithError(errorInformation);
            return;
        }
    }
    // check if user is already authenticated - shouldn't be in nominal usage.
    if (userIsAuthenticated) {
        switch(oAuthUseCaseCase) {
            case Authentication:
                LOGGER.debug(pwmSession, "oauth consumer reached, but user is already authenticated; will proceed and verify authcode matches current user identity.");
                break;
            case ForgottenPassword:
                final String errorMsg = "oauth consumer reached via " + OAuthUseCase.ForgottenPassword + ", but user is already authenticated";
                final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_OAUTH_ERROR, errorMsg);
                pwmRequest.respondWithError(errorInformation);
                LOGGER.error(pwmSession, errorMsg);
                return;
            default:
                JavaHelper.unhandledSwitchStatement(oAuthUseCaseCase);
        }
    }
    // mark the inprogress flag to false, if we get this far and fail user needs to start over.
    pwmSession.getSessionStateBean().setOauthInProgress(false);
    if (!oAuthRequestState.isPresent()) {
        final String errorMsg = "state parameter is missing from oauth request";
        final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_OAUTH_ERROR, errorMsg);
        LOGGER.error(pwmSession, errorMsg);
        pwmRequest.respondWithError(errorInformation);
        return;
    }
    final OAuthState oauthState = oAuthRequestState.get().getoAuthState();
    final OAuthSettings oAuthSettings = makeOAuthSettings(pwmRequest, oauthState);
    final OAuthMachine oAuthMachine = new OAuthMachine(oAuthSettings);
    // make sure request was initiated in users current session
    if (!oAuthRequestState.get().isSessionMatch()) {
        try {
            switch(oAuthUseCaseCase) {
                case Authentication:
                    LOGGER.debug(pwmSession, "oauth consumer reached but response is not for a request issued during the current session," + " will redirect back to oauth server for verification update");
                    final String nextURL = oauthState.getNextUrl();
                    oAuthMachine.redirectUserToOAuthServer(pwmRequest, nextURL, null, null);
                    return;
                case ForgottenPassword:
                    LOGGER.debug(pwmSession, "oauth consumer reached but response is not for a request issued during the current session," + " will redirect back to forgotten password servlet");
                    pwmRequest.sendRedirect(PwmServletDefinition.ForgottenPassword);
                    return;
                default:
                    JavaHelper.unhandledSwitchStatement(oAuthUseCaseCase);
            }
        } catch (PwmUnrecoverableException e) {
            final String errorMsg = "unexpected error redirecting user to oauth page: " + e.toString();
            final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_OAUTH_ERROR, errorMsg);
            setLastError(pwmRequest, errorInformation);
            LOGGER.error(errorInformation.toDebugStr());
        }
    }
    final String requestCodeStr = pwmRequest.readParameterAsString(config.readAppProperty(AppProperty.HTTP_PARAM_OAUTH_CODE));
    LOGGER.trace(pwmSession, "received code from oauth server: " + requestCodeStr);
    final OAuthResolveResults resolveResults;
    try {
        resolveResults = oAuthMachine.makeOAuthResolveRequest(pwmRequest, requestCodeStr);
    } catch (PwmException e) {
        final String errorMsg = "unexpected error communicating with oauth server: " + e.toString();
        final ErrorInformation errorInformation = new ErrorInformation(e.getError(), errorMsg);
        setLastError(pwmRequest, errorInformation);
        LOGGER.error(errorInformation.toDebugStr());
        return;
    }
    if (resolveResults == null || resolveResults.getAccessToken() == null || resolveResults.getAccessToken().isEmpty()) {
        final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_OAUTH_ERROR, "browser redirect from oauth server did not include an access token");
        LOGGER.error(pwmRequest, errorInformation);
        pwmRequest.respondWithError(errorInformation);
        return;
    }
    if (resolveResults.getExpiresSeconds() > 0) {
        if (resolveResults.getRefreshToken() == null || resolveResults.getRefreshToken().isEmpty()) {
            final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_OAUTH_ERROR, "oauth server gave expiration for access token, but did not provide a refresh token");
            LOGGER.error(pwmRequest, errorInformation);
            pwmRequest.respondWithError(errorInformation);
            return;
        }
    }
    final String oauthSuppliedUsername;
    {
        final String getAttributeResponseBodyStr = oAuthMachine.makeOAuthGetAttributeRequest(pwmRequest, resolveResults.getAccessToken());
        final Map<String, String> getAttributeResultValues = JsonUtil.deserializeStringMap(getAttributeResponseBodyStr);
        oauthSuppliedUsername = getAttributeResultValues.get(oAuthSettings.getDnAttributeName());
        if (oauthSuppliedUsername == null || oauthSuppliedUsername.isEmpty()) {
            final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_OAUTH_ERROR, "OAuth server did not respond with an username attribute value");
            LOGGER.error(pwmRequest, errorInformation);
            pwmRequest.respondWithError(errorInformation);
            return;
        }
    }
    LOGGER.debug(pwmSession, "received user login id value from OAuth server: " + oauthSuppliedUsername);
    if (oAuthUseCaseCase == OAuthUseCase.ForgottenPassword) {
        redirectToForgottenPasswordServlet(pwmRequest, oauthSuppliedUsername);
        return;
    }
    if (userIsAuthenticated) {
        try {
            final UserSearchEngine userSearchEngine = pwmApplication.getUserSearchEngine();
            final UserIdentity resolvedIdentity = userSearchEngine.resolveUsername(oauthSuppliedUsername, null, null, pwmSession.getLabel());
            if (resolvedIdentity != null && resolvedIdentity.canonicalEquals(pwmSession.getUserInfo().getUserIdentity(), pwmApplication)) {
                LOGGER.debug(pwmSession, "verified incoming oauth code for already authenticated session does resolve to same as logged in user");
            } else {
                final String errorMsg = "incoming oauth code for already authenticated session does not resolve to same as logged in user ";
                final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_OAUTH_ERROR, errorMsg);
                LOGGER.error(pwmSession, errorMsg);
                pwmRequest.respondWithError(errorInformation);
                pwmSession.unauthenticateUser(pwmRequest);
                return;
            }
        } catch (PwmOperationalException e) {
            final String errorMsg = "error while examining incoming oauth code for already authenticated session: " + e.getMessage();
            final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_OAUTH_ERROR, errorMsg);
            LOGGER.error(pwmSession, errorMsg);
            pwmRequest.respondWithError(errorInformation);
            return;
        }
    }
    try {
        if (!userIsAuthenticated) {
            final SessionAuthenticator sessionAuthenticator = new SessionAuthenticator(pwmApplication, pwmSession, PwmAuthenticationSource.OAUTH);
            sessionAuthenticator.authUserWithUnknownPassword(oauthSuppliedUsername, AuthenticationType.AUTH_WITHOUT_PASSWORD);
        }
        // recycle the session to prevent session fixation attack.
        pwmRequest.getPwmSession().getSessionStateBean().setSessionIdRecycleNeeded(true);
        // forward to nextUrl
        final String nextUrl = oauthState.getNextUrl();
        LOGGER.debug(pwmSession, "oauth authentication completed, redirecting to originally requested URL: " + nextUrl);
        pwmRequest.sendRedirect(nextUrl);
    } catch (PwmException e) {
        LOGGER.error(pwmSession, "error during OAuth authentication attempt: " + e.getMessage());
        final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_OAUTH_ERROR, e.getMessage());
        pwmRequest.respondWithError(errorInformation);
        return;
    }
    LOGGER.trace(pwmSession, "OAuth login sequence successfully completed");
}
Also used : PwmApplication(password.pwm.PwmApplication) Configuration(password.pwm.config.Configuration) SessionAuthenticator(password.pwm.ldap.auth.SessionAuthenticator) UserSearchEngine(password.pwm.ldap.search.UserSearchEngine) UserIdentity(password.pwm.bean.UserIdentity) PwmUnrecoverableException(password.pwm.error.PwmUnrecoverableException) PwmOperationalException(password.pwm.error.PwmOperationalException) PwmException(password.pwm.error.PwmException) ErrorInformation(password.pwm.error.ErrorInformation) PwmSession(password.pwm.http.PwmSession) HashMap(java.util.HashMap) Map(java.util.Map)

Example 20 with UserSearchEngine

use of password.pwm.ldap.search.UserSearchEngine in project pwm by pwm-project.

the class AdminServlet method processDebugUserSearch.

private void processDebugUserSearch(final PwmRequest pwmRequest) throws PwmUnrecoverableException {
    final String username = pwmRequest.readParameterAsString("username", PwmHttpRequestWrapper.Flag.BypassValidation);
    if (StringUtil.isEmpty(username)) {
        return;
    }
    final UserSearchEngine userSearchEngine = pwmRequest.getPwmApplication().getUserSearchEngine();
    final UserIdentity userIdentity;
    try {
        userIdentity = userSearchEngine.resolveUsername(username, null, null, pwmRequest.getSessionLabel());
        final AdminBean adminBean = pwmRequest.getPwmApplication().getSessionStateService().getBean(pwmRequest, AdminBean.class);
        adminBean.setLastUserDebug(userIdentity);
    } catch (PwmUnrecoverableException e) {
        setLastError(pwmRequest, e.getErrorInformation());
        return;
    } catch (PwmOperationalException e) {
        setLastError(pwmRequest, e.getErrorInformation());
        return;
    }
    final UserDebugDataBean userDebugData = UserDebugDataReader.readUserDebugData(pwmRequest.getPwmApplication(), pwmRequest.getLocale(), pwmRequest.getSessionLabel(), userIdentity);
    pwmRequest.setAttribute(PwmRequestAttribute.UserDebugData, userDebugData);
}
Also used : UserSearchEngine(password.pwm.ldap.search.UserSearchEngine) UserIdentity(password.pwm.bean.UserIdentity) AdminBean(password.pwm.http.bean.AdminBean) PwmUnrecoverableException(password.pwm.error.PwmUnrecoverableException) PwmOperationalException(password.pwm.error.PwmOperationalException)

Aggregations

UserSearchEngine (password.pwm.ldap.search.UserSearchEngine)20 UserIdentity (password.pwm.bean.UserIdentity)19 PwmOperationalException (password.pwm.error.PwmOperationalException)17 ErrorInformation (password.pwm.error.ErrorInformation)14 SearchConfiguration (password.pwm.ldap.search.SearchConfiguration)13 PwmUnrecoverableException (password.pwm.error.PwmUnrecoverableException)12 Map (java.util.Map)9 PwmApplication (password.pwm.PwmApplication)7 FormConfiguration (password.pwm.config.value.data.FormConfiguration)7 HashMap (java.util.HashMap)6 PwmSession (password.pwm.http.PwmSession)5 LinkedHashMap (java.util.LinkedHashMap)4 Locale (java.util.Locale)3 TreeMap (java.util.TreeMap)3 Configuration (password.pwm.config.Configuration)3 UserInfo (password.pwm.ldap.UserInfo)3 ChaiUser (com.novell.ldapchai.ChaiUser)2 ChaiUnavailableException (com.novell.ldapchai.exception.ChaiUnavailableException)2 SearchHelper (com.novell.ldapchai.util.SearchHelper)2 Instant (java.time.Instant)2