Search in sources :

Example 11 with UserSearchEngine

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

the class RestUtility method resolveRequestedUsername.

public static RestServlet.TargetUserIdentity resolveRequestedUsername(final RestRequest restRequest, final String username) throws PwmUnrecoverableException {
    final PwmApplication pwmApplication = restRequest.getPwmApplication();
    if (StringUtil.isEmpty(username)) {
        if (restRequest.getRestAuthentication().getType() == RestAuthenticationType.NAMED_SECRET) {
            throw PwmUnrecoverableException.newException(PwmError.ERROR_REST_INVOCATION_ERROR, "username field required when using external web services secrets for authentication ");
        }
    } else {
        if (!restRequest.getRestAuthentication().isThirdPartyEnabled()) {
            throw PwmUnrecoverableException.newException(PwmError.ERROR_UNAUTHORIZED, "username specified in request, however third party permission is not granted to the authenticated login.");
        }
    }
    if (StringUtil.isEmpty(username)) {
        if (restRequest.getRestAuthentication().getType() == RestAuthenticationType.LDAP) {
            return new RestServlet.TargetUserIdentity(restRequest, restRequest.getRestAuthentication().getLdapIdentity(), true);
        }
    }
    final String ldapProfileID;
    final String effectiveUsername;
    if (username.contains("|")) {
        final int pipeIndex = username.indexOf("|");
        ldapProfileID = username.substring(0, pipeIndex);
        effectiveUsername = username.substring(pipeIndex + 1, username.length());
    } else {
        ldapProfileID = null;
        effectiveUsername = username;
    }
    try {
        final UserSearchEngine userSearchEngine = pwmApplication.getUserSearchEngine();
        final UserIdentity userIdentity = userSearchEngine.resolveUsername(effectiveUsername, null, ldapProfileID, restRequest.getSessionLabel());
        final LdapProfile ldapProfile = pwmApplication.getConfig().getLdapProfiles().get(userIdentity.getLdapProfileID());
        if (ldapProfile != null) {
            {
                final UserIdentity testUser = ldapProfile.getTestUser(pwmApplication);
                if (testUser != null && testUser.canonicalEquals(userIdentity, pwmApplication)) {
                    final String msg = "rest services can not be invoked against the configured LDAP profile test user";
                    final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_REST_INVOCATION_ERROR, msg);
                    throw new PwmUnrecoverableException(errorInformation);
                }
            }
            {
                final UserIdentity proxyUser = ldapProfile.getProxyUser(pwmApplication);
                if (proxyUser != null && proxyUser.canonicalEquals(userIdentity, pwmApplication)) {
                    final String msg = "rest services can not be invoked against the configured LDAP profile proxy user";
                    final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_REST_INVOCATION_ERROR, msg);
                    throw new PwmUnrecoverableException(errorInformation);
                }
            }
        }
        return new RestServlet.TargetUserIdentity(restRequest, userIdentity, false);
    } catch (PwmOperationalException e) {
        throw new PwmUnrecoverableException(e.getErrorInformation());
    }
}
Also used : ErrorInformation(password.pwm.error.ErrorInformation) PwmApplication(password.pwm.PwmApplication) UserSearchEngine(password.pwm.ldap.search.UserSearchEngine) UserIdentity(password.pwm.bean.UserIdentity) PwmUnrecoverableException(password.pwm.error.PwmUnrecoverableException) LdapProfile(password.pwm.config.profile.LdapProfile) PwmOperationalException(password.pwm.error.PwmOperationalException)

Example 12 with UserSearchEngine

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

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

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

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

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