Search in sources :

Example 6 with SearchConfiguration

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

the class ForgottenUsernameServlet method handleSearchRequest.

public void handleSearchRequest(final PwmRequest pwmRequest) throws PwmUnrecoverableException, IOException, ServletException {
    final PwmApplication pwmApplication = pwmRequest.getPwmApplication();
    final PwmSession pwmSession = pwmRequest.getPwmSession();
    final LocalSessionStateBean ssBean = pwmSession.getSessionStateBean();
    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);
            forwardToFormJsp(pwmRequest);
            return;
        }
    }
    final String contextParam = pwmRequest.readParameterAsString(PwmConstants.PARAM_CONTEXT);
    final String ldapProfile = pwmRequest.readParameterAsString(PwmConstants.PARAM_LDAP_PROFILE);
    final List<FormConfiguration> forgottenUsernameForm = pwmApplication.getConfig().readSettingAsForm(PwmSetting.FORGOTTEN_USERNAME_FORM);
    // read the values from the request
    Map<FormConfiguration, String> formValues = new HashMap<>();
    try {
        formValues = FormUtility.readFormValuesFromRequest(pwmRequest, forgottenUsernameForm, ssBean.getLocale());
        // check for intruder search
        pwmApplication.getIntruderManager().convenience().checkAttributes(formValues);
        // see if the values meet the configured form requirements.
        FormUtility.validateFormValues(pwmRequest.getConfig(), formValues, ssBean.getLocale());
        final String searchFilter;
        {
            final String configuredSearchFilter = pwmApplication.getConfig().readSettingAsString(PwmSetting.FORGOTTEN_USERNAME_SEARCH_FILTER);
            if (configuredSearchFilter == null || configuredSearchFilter.isEmpty()) {
                searchFilter = FormUtility.ldapSearchFilterForForm(pwmApplication, forgottenUsernameForm);
                LOGGER.trace(pwmSession, "auto generated ldap search filter: " + searchFilter);
            } else {
                searchFilter = configuredSearchFilter;
            }
        }
        final UserIdentity userIdentity;
        {
            final UserSearchEngine userSearchEngine = pwmApplication.getUserSearchEngine();
            final SearchConfiguration searchConfiguration = SearchConfiguration.builder().filter(searchFilter).formValues(formValues).ldapProfile(ldapProfile).contexts(Collections.singletonList(contextParam)).build();
            userIdentity = userSearchEngine.performSingleUserSearch(searchConfiguration, pwmSession.getLabel());
        }
        if (userIdentity == null) {
            pwmApplication.getIntruderManager().convenience().markAddressAndSession(pwmSession);
            pwmApplication.getStatisticsManager().incrementValue(Statistic.FORGOTTEN_USERNAME_FAILURES);
            setLastError(pwmRequest, PwmError.ERROR_CANT_MATCH_USER.toInfo());
            forwardToFormJsp(pwmRequest);
            return;
        }
        // make sure the user isn't locked.
        pwmApplication.getIntruderManager().convenience().checkUserIdentity(userIdentity);
        final UserInfo forgottenUserInfo = UserInfoFactory.newUserInfoUsingProxy(pwmApplication, pwmRequest.getSessionLabel(), userIdentity, pwmRequest.getLocale());
        // send username
        sendUsername(pwmApplication, pwmSession, forgottenUserInfo);
        pwmApplication.getIntruderManager().convenience().clearAddressAndSession(pwmSession);
        pwmApplication.getIntruderManager().convenience().clearAttributes(formValues);
        pwmApplication.getStatisticsManager().incrementValue(Statistic.FORGOTTEN_USERNAME_SUCCESSES);
        // redirect user to success page.
        forwardToCompletePage(pwmRequest, userIdentity);
        return;
    } catch (PwmOperationalException e) {
        final ErrorInformation errorInfo;
        errorInfo = e.getError() == PwmError.ERROR_UNKNOWN ? new ErrorInformation(PwmError.ERROR_CANT_MATCH_USER, e.getErrorInformation().getDetailedErrorMsg(), e.getErrorInformation().getFieldValues()) : e.getErrorInformation();
        setLastError(pwmRequest, errorInfo);
        pwmApplication.getIntruderManager().convenience().markAddressAndSession(pwmSession);
        pwmApplication.getIntruderManager().convenience().markAttributes(formValues, pwmSession);
    }
    pwmApplication.getStatisticsManager().incrementValue(Statistic.FORGOTTEN_USERNAME_FAILURES);
    forwardToFormJsp(pwmRequest);
}
Also used : PwmApplication(password.pwm.PwmApplication) HashMap(java.util.HashMap) UserIdentity(password.pwm.bean.UserIdentity) UserSearchEngine(password.pwm.ldap.search.UserSearchEngine) SearchConfiguration(password.pwm.ldap.search.SearchConfiguration) UserInfo(password.pwm.ldap.UserInfo) PwmOperationalException(password.pwm.error.PwmOperationalException) ErrorInformation(password.pwm.error.ErrorInformation) LocalSessionStateBean(password.pwm.bean.LocalSessionStateBean) FormConfiguration(password.pwm.config.value.data.FormConfiguration) PwmSession(password.pwm.http.PwmSession)

Example 7 with SearchConfiguration

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

the class PeopleSearchDataReader method makeSearchResultsImpl.

private SearchResultBean makeSearchResultsImpl(final PwmRequest pwmRequest, final String username, final boolean includeDisplayName) throws ChaiUnavailableException, PwmUnrecoverableException {
    final Instant startTime = Instant.now();
    if (username == null || username.length() < 1) {
        return new SearchResultBean();
    }
    final boolean useProxy = useProxy();
    final UserSearchEngine userSearchEngine = pwmRequest.getPwmApplication().getUserSearchEngine();
    final SearchConfiguration searchConfiguration;
    {
        final SearchConfiguration.SearchConfigurationBuilder builder = SearchConfiguration.builder();
        builder.contexts(pwmRequest.getConfig().readSettingAsStringArray(PwmSetting.PEOPLE_SEARCH_SEARCH_BASE));
        builder.enableContextValidation(false);
        builder.username(username);
        builder.enableValueEscaping(false);
        builder.filter(getSearchFilter(pwmRequest.getConfig()));
        builder.enableSplitWhitespace(true);
        if (!useProxy) {
            builder.ldapProfile(pwmRequest.getPwmSession().getUserInfo().getUserIdentity().getLdapProfileID());
            builder.chaiProvider(pwmRequest.getPwmSession().getSessionManager().getChaiProvider());
        }
        searchConfiguration = builder.build();
    }
    final UserSearchResults results;
    final boolean sizeExceeded;
    try {
        final List<FormConfiguration> searchForm = pwmRequest.getConfig().readSettingAsForm(PwmSetting.PEOPLE_SEARCH_RESULT_FORM);
        final int maxResults = (int) pwmRequest.getConfig().readSettingAsLong(PwmSetting.PEOPLE_SEARCH_RESULT_LIMIT);
        final Locale locale = pwmRequest.getLocale();
        results = userSearchEngine.performMultiUserSearchFromForm(locale, searchConfiguration, maxResults, searchForm, pwmRequest.getSessionLabel());
        sizeExceeded = results.isSizeExceeded();
    } catch (PwmOperationalException e) {
        final ErrorInformation errorInformation = e.getErrorInformation();
        LOGGER.error(pwmRequest.getSessionLabel(), errorInformation.toDebugStr());
        throw new PwmUnrecoverableException(errorInformation);
    }
    final List<Map<String, Object>> resultOutput = new ArrayList<>(results.resultsAsJsonOutput(pwmRequest.getPwmApplication(), null));
    if (includeDisplayName) {
        for (final Map<String, Object> map : resultOutput) {
            final String userKey = (String) map.get("userKey");
            if (userKey != null) {
                final UserIdentity userIdentity = UserIdentity.fromKey(userKey, pwmRequest.getPwmApplication());
                final String displayValue = figureDisplaynameValue(pwmRequest, userIdentity);
                map.put("_displayName", displayValue);
            }
        }
    }
    final TimeDuration searchDuration = TimeDuration.fromCurrent(startTime);
    LOGGER.trace(pwmRequest.getPwmSession(), "finished rest peoplesearch search in " + searchDuration.asCompactString() + " not using cache, size=" + results.getResults().size());
    final SearchResultBean searchResultBean = new SearchResultBean();
    searchResultBean.setSearchResults(resultOutput);
    searchResultBean.setSizeExceeded(sizeExceeded);
    final String aboutMessage = LocaleHelper.getLocalizedMessage(pwmRequest.getLocale(), Display.Display_SearchResultsInfo.getKey(), pwmRequest.getConfig(), Display.class, new String[] { String.valueOf(results.getResults().size()), searchDuration.asLongString(pwmRequest.getLocale()) });
    searchResultBean.setAboutResultMessage(aboutMessage);
    return searchResultBean;
}
Also used : Locale(java.util.Locale) Instant(java.time.Instant) UserSearchEngine(password.pwm.ldap.search.UserSearchEngine) UserSearchResults(password.pwm.ldap.search.UserSearchResults) UserIdentity(password.pwm.bean.UserIdentity) ArrayList(java.util.ArrayList) SearchConfiguration(password.pwm.ldap.search.SearchConfiguration) PwmUnrecoverableException(password.pwm.error.PwmUnrecoverableException) PwmOperationalException(password.pwm.error.PwmOperationalException) ErrorInformation(password.pwm.error.ErrorInformation) FormConfiguration(password.pwm.config.value.data.FormConfiguration) TimeDuration(password.pwm.util.java.TimeDuration) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) TreeMap(java.util.TreeMap)

Example 8 with SearchConfiguration

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

the class ExportResponsesCommand method doCommand.

@Override
void doCommand() throws Exception {
    final PwmApplication pwmApplication = cliEnvironment.getPwmApplication();
    final File outputFile = (File) cliEnvironment.getOptions().get(CliParameters.REQUIRED_NEW_OUTPUT_FILE.getName());
    JavaHelper.pause(2000);
    final long startTime = System.currentTimeMillis();
    final UserSearchEngine userSearchEngine = pwmApplication.getUserSearchEngine();
    final SearchConfiguration searchConfiguration = SearchConfiguration.builder().enableValueEscaping(false).username("*").build();
    final String systemRecordDelimiter = System.getProperty("line.separator");
    final Writer writer = new BufferedWriter(new PrintWriter(outputFile, PwmConstants.DEFAULT_CHARSET.toString()));
    final Map<UserIdentity, Map<String, String>> results = userSearchEngine.performMultiUserSearch(searchConfiguration, Integer.MAX_VALUE, Collections.emptyList(), SessionLabel.SYSTEM_LABEL);
    out("searching " + results.size() + " users for stored responses to write to " + outputFile.getAbsolutePath() + "....");
    int counter = 0;
    for (final UserIdentity identity : results.keySet()) {
        final ChaiUser user = pwmApplication.getProxiedChaiUser(identity);
        final ResponseSet responseSet = pwmApplication.getCrService().readUserResponseSet(null, identity, user);
        if (responseSet != null) {
            counter++;
            out("found responses for '" + user + "', writing to output.");
            final RestChallengesServer.JsonChallengesData outputData = new RestChallengesServer.JsonChallengesData();
            outputData.challenges = responseSet.asChallengeBeans(true);
            outputData.helpdeskChallenges = responseSet.asHelpdeskChallengeBeans(true);
            outputData.minimumRandoms = responseSet.getChallengeSet().minimumResponses();
            outputData.username = identity.toDelimitedKey();
            writer.write(JsonUtil.serialize(outputData));
            writer.write(systemRecordDelimiter);
        } else {
            out("skipping '" + user.toString() + "', no stored responses.");
        }
    }
    writer.close();
    out("output complete, " + counter + " responses exported in " + TimeDuration.fromCurrent(startTime).asCompactString());
}
Also used : PwmApplication(password.pwm.PwmApplication) UserSearchEngine(password.pwm.ldap.search.UserSearchEngine) UserIdentity(password.pwm.bean.UserIdentity) ResponseSet(com.novell.ldapchai.cr.ResponseSet) SearchConfiguration(password.pwm.ldap.search.SearchConfiguration) BufferedWriter(java.io.BufferedWriter) ChaiUser(com.novell.ldapchai.ChaiUser) RestChallengesServer(password.pwm.ws.server.rest.RestChallengesServer) File(java.io.File) Map(java.util.Map) PrintWriter(java.io.PrintWriter) BufferedWriter(java.io.BufferedWriter) Writer(java.io.Writer) PrintWriter(java.io.PrintWriter)

Example 9 with SearchConfiguration

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

the class LdapPermissionTester method discoverMatchingUsers.

public static Map<UserIdentity, Map<String, String>> discoverMatchingUsers(final PwmApplication pwmApplication, final int maxResultSize, final List<UserPermission> userPermissions, final SessionLabel sessionLabel) throws Exception {
    final UserSearchEngine userSearchEngine = pwmApplication.getUserSearchEngine();
    final Map<UserIdentity, Map<String, String>> results = new TreeMap<>();
    for (final UserPermission userPermission : userPermissions) {
        if ((maxResultSize) - results.size() > 0) {
            final SearchConfiguration.SearchConfigurationBuilder builder = SearchConfiguration.builder();
            switch(userPermission.getType()) {
                case ldapQuery:
                    {
                        builder.filter(userPermission.getLdapQuery());
                        if (userPermission.getLdapBase() != null && !userPermission.getLdapBase().isEmpty()) {
                            builder.enableContextValidation(false);
                            builder.contexts(Collections.singletonList(userPermission.getLdapBase()));
                        }
                    }
                    break;
                case ldapGroup:
                    {
                        builder.groupDN(userPermission.getLdapBase());
                    }
                    break;
                default:
                    throw new PwmUnrecoverableException(new ErrorInformation(PwmError.ERROR_UNKNOWN, "unknown permission type: " + userPermission.getType()));
            }
            if (userPermission.getLdapProfileID() != null && !userPermission.getLdapProfileID().isEmpty() && !userPermission.getLdapProfileID().equals(PwmConstants.PROFILE_ID_ALL)) {
                builder.ldapProfile(userPermission.getLdapProfileID());
            }
            final SearchConfiguration searchConfiguration = builder.build();
            try {
                results.putAll(userSearchEngine.performMultiUserSearch(searchConfiguration, (maxResultSize) - results.size(), Collections.emptyList(), sessionLabel));
            } catch (PwmUnrecoverableException e) {
                LOGGER.error("error reading matching users: " + e.getMessage());
                throw new PwmOperationalException(e.getErrorInformation());
            }
        }
    }
    return results;
}
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) TreeMap(java.util.TreeMap) TreeMap(java.util.TreeMap) Map(java.util.Map) UserPermission(password.pwm.config.value.data.UserPermission) PwmOperationalException(password.pwm.error.PwmOperationalException)

Example 10 with SearchConfiguration

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

the class FormUtility method validateFormValueUniqueness.

@SuppressWarnings("checkstyle:MethodLength")
public static void validateFormValueUniqueness(final PwmApplication pwmApplication, final Map<FormConfiguration, String> formValues, final Locale locale, final Collection<UserIdentity> excludeDN, final ValidationFlag... validationFlags) throws PwmDataValidationException, PwmUnrecoverableException {
    final boolean allowResultCaching = JavaHelper.enumArrayContainsValue(validationFlags, ValidationFlag.allowResultCaching);
    final boolean checkReadOnlyAndHidden = JavaHelper.enumArrayContainsValue(validationFlags, ValidationFlag.checkReadOnlyAndHidden);
    final Map<String, String> filterClauses = new HashMap<>();
    final Map<String, String> labelMap = new HashMap<>();
    for (final Map.Entry<FormConfiguration, String> entry : formValues.entrySet()) {
        final FormConfiguration formItem = entry.getKey();
        if (formItem.isUnique()) {
            if (checkReadOnlyAndHidden || formItem.isReadonly()) {
                if (checkReadOnlyAndHidden || (formItem.getType() != FormConfiguration.Type.hidden)) {
                    final String value = entry.getValue();
                    if (value != null && value.length() > 0) {
                        filterClauses.put(formItem.getName(), value);
                        labelMap.put(formItem.getName(), formItem.getLabel(locale));
                    }
                }
            }
        }
    }
    if (filterClauses.isEmpty()) {
        // nothing to search
        return;
    }
    final StringBuilder filter = new StringBuilder();
    {
        // outer;
        filter.append("(&");
        // object classes;
        filter.append("(|");
        for (final String objectClass : pwmApplication.getConfig().readSettingAsStringArray(PwmSetting.DEFAULT_OBJECT_CLASSES)) {
            filter.append("(objectClass=").append(objectClass).append(")");
        }
        filter.append(")");
        // attributes
        filter.append("(|");
        for (final Map.Entry<String, String> entry : filterClauses.entrySet()) {
            final String name = entry.getKey();
            final String value = entry.getValue();
            filter.append("(").append(name).append("=").append(StringUtil.escapeLdapFilter(value)).append(")");
        }
        filter.append(")");
        filter.append(")");
    }
    final CacheService cacheService = pwmApplication.getCacheService();
    final CacheKey cacheKey = CacheKey.makeCacheKey(Validator.class, null, "attr_unique_check_" + filter.toString());
    if (allowResultCaching && cacheService != null) {
        final String cacheValue = cacheService.get(cacheKey);
        if (cacheValue != null) {
            if (NEGATIVE_CACHE_HIT.equals(cacheValue)) {
                return;
            } else {
                final ErrorInformation errorInformation = JsonUtil.deserialize(cacheValue, ErrorInformation.class);
                throw new PwmDataValidationException(errorInformation);
            }
        }
    }
    final SearchHelper searchHelper = new SearchHelper();
    searchHelper.setFilterAnd(filterClauses);
    final SearchConfiguration searchConfiguration = SearchConfiguration.builder().filter(filter.toString()).build();
    final int resultSearchSizeLimit = 1 + (excludeDN == null ? 0 : excludeDN.size());
    final long cacheLifetimeMS = Long.parseLong(pwmApplication.getConfig().readAppProperty(AppProperty.CACHE_FORM_UNIQUE_VALUE_LIFETIME_MS));
    final CachePolicy cachePolicy = CachePolicy.makePolicyWithExpirationMS(cacheLifetimeMS);
    try {
        final UserSearchEngine userSearchEngine = pwmApplication.getUserSearchEngine();
        final Map<UserIdentity, Map<String, String>> results = new LinkedHashMap<>(userSearchEngine.performMultiUserSearch(searchConfiguration, resultSearchSizeLimit, Collections.emptyList(), SessionLabel.SYSTEM_LABEL));
        if (excludeDN != null && !excludeDN.isEmpty()) {
            for (final UserIdentity loopIgnoreIdentity : excludeDN) {
                results.keySet().removeIf(loopIgnoreIdentity::equals);
            }
        }
        if (!results.isEmpty()) {
            final UserIdentity userIdentity = results.keySet().iterator().next();
            if (labelMap.size() == 1) {
                // since only one value searched, it must be that one value
                final String attributeName = labelMap.values().iterator().next();
                LOGGER.trace("found duplicate value for attribute '" + attributeName + "' on entry " + userIdentity);
                final ErrorInformation error = new ErrorInformation(PwmError.ERROR_FIELD_DUPLICATE, null, new String[] { attributeName });
                throw new PwmDataValidationException(error);
            }
            // do a compare on a user values to find one that matches.
            for (final Map.Entry<String, String> entry : filterClauses.entrySet()) {
                final String name = entry.getKey();
                final String value = entry.getValue();
                final boolean compareResult;
                try {
                    final ChaiUser theUser = pwmApplication.getProxiedChaiUser(userIdentity);
                    compareResult = theUser.compareStringAttribute(name, value);
                } catch (ChaiOperationException | ChaiUnavailableException e) {
                    final PwmError error = PwmError.forChaiError(e.getErrorCode());
                    throw new PwmUnrecoverableException(error.toInfo());
                }
                if (compareResult) {
                    final String label = labelMap.get(name);
                    LOGGER.trace("found duplicate value for attribute '" + label + "' on entry " + userIdentity);
                    final ErrorInformation error = new ErrorInformation(PwmError.ERROR_FIELD_DUPLICATE, null, new String[] { label });
                    throw new PwmDataValidationException(error);
                }
            }
            // user didn't match on the compare.. shouldn't read here but just in case
            final ErrorInformation error = new ErrorInformation(PwmError.ERROR_FIELD_DUPLICATE, null);
            throw new PwmDataValidationException(error);
        }
    } catch (PwmOperationalException e) {
        if (cacheService != null) {
            final String jsonPayload = JsonUtil.serialize(e.getErrorInformation());
            cacheService.put(cacheKey, cachePolicy, jsonPayload);
        }
        throw new PwmDataValidationException(e.getErrorInformation());
    }
    if (allowResultCaching && cacheService != null) {
        cacheService.put(cacheKey, cachePolicy, NEGATIVE_CACHE_HIT);
    }
}
Also used : ChaiUnavailableException(com.novell.ldapchai.exception.ChaiUnavailableException) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) UserSearchEngine(password.pwm.ldap.search.UserSearchEngine) PwmUnrecoverableException(password.pwm.error.PwmUnrecoverableException) SearchHelper(com.novell.ldapchai.util.SearchHelper) LinkedHashMap(java.util.LinkedHashMap) PwmOperationalException(password.pwm.error.PwmOperationalException) ErrorInformation(password.pwm.error.ErrorInformation) FormConfiguration(password.pwm.config.value.data.FormConfiguration) ChaiOperationException(com.novell.ldapchai.exception.ChaiOperationException) CacheKey(password.pwm.svc.cache.CacheKey) CacheService(password.pwm.svc.cache.CacheService) UserIdentity(password.pwm.bean.UserIdentity) PwmError(password.pwm.error.PwmError) SearchConfiguration(password.pwm.ldap.search.SearchConfiguration) PwmDataValidationException(password.pwm.error.PwmDataValidationException) CachePolicy(password.pwm.svc.cache.CachePolicy) ChaiUser(com.novell.ldapchai.ChaiUser) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map)

Aggregations

UserIdentity (password.pwm.bean.UserIdentity)13 SearchConfiguration (password.pwm.ldap.search.SearchConfiguration)13 UserSearchEngine (password.pwm.ldap.search.UserSearchEngine)13 ErrorInformation (password.pwm.error.ErrorInformation)10 PwmOperationalException (password.pwm.error.PwmOperationalException)10 Map (java.util.Map)8 FormConfiguration (password.pwm.config.value.data.FormConfiguration)7 PwmUnrecoverableException (password.pwm.error.PwmUnrecoverableException)7 HashMap (java.util.HashMap)5 PwmApplication (password.pwm.PwmApplication)5 LinkedHashMap (java.util.LinkedHashMap)4 PwmSession (password.pwm.http.PwmSession)4 Locale (java.util.Locale)3 TreeMap (java.util.TreeMap)3 UserInfo (password.pwm.ldap.UserInfo)3 ChaiUser (com.novell.ldapchai.ChaiUser)2 SearchHelper (com.novell.ldapchai.util.SearchHelper)2 Instant (java.time.Instant)2 ArrayList (java.util.ArrayList)2 LocalSessionStateBean (password.pwm.bean.LocalSessionStateBean)2