Search in sources :

Example 6 with SearchRequest

use of org.forgerock.opendj.ldap.requests.SearchRequest in project OpenAM by OpenRock.

the class LDAPGroups method getUserDN.

/**
     * Get the full DN for the user using the RDN against the
     * LDAP server configured in the policy config service.
     */
private DN getUserDN(String userRDN) throws SSOException, PolicyException {
    DN userDN = null;
    if (userRDN != null) {
        Set<String> qualifiedUserDNs = new HashSet<>();
        String searchFilter = null;
        if ((userSearchFilter != null) && !(userSearchFilter.length() == 0)) {
            searchFilter = "(&" + userSearchFilter + userRDN + ")";
        } else {
            searchFilter = userRDN;
        }
        if (debug.messageEnabled()) {
            debug.message("LDAPGroups.getUserDN(): search filter is: " + searchFilter);
        }
        String[] attrs = { userRDNAttrName };
        try (Connection conn = connPool.getConnection()) {
            SearchRequest searchRequest = LDAPRequests.newSearchRequest(baseDN, userSearchScope, searchFilter, attrs);
            ConnectionEntryReader reader = conn.search(searchRequest);
            while (reader.hasNext()) {
                if (reader.isReference()) {
                    //Ignore
                    reader.readReference();
                } else {
                    SearchResultEntry entry = reader.readEntry();
                    if (entry != null) {
                        qualifiedUserDNs.add(entry.getName().toString());
                    }
                }
            }
        } catch (LdapException le) {
            ResultCode resultCode = le.getResult().getResultCode();
            if (ResultCode.SIZE_LIMIT_EXCEEDED.equals(resultCode)) {
                String[] objs = { orgName };
                debug.warning("LDAPGroups.isMember(): exceeded the size limit");
                throw new PolicyException(ResBundleUtils.rbName, "ldap_search_exceed_size_limit", objs, null);
            } else if (ResultCode.TIME_LIMIT_EXCEEDED.equals(resultCode)) {
                String[] objs = { orgName };
                debug.warning("LDAPGroups.isMember(): exceeded the time limit");
                throw new PolicyException(ResBundleUtils.rbName, "ldap_search_exceed_time_limit", objs, null);
            } else if (ResultCode.INVALID_CREDENTIALS.equals(resultCode)) {
                throw new PolicyException(ResBundleUtils.rbName, "ldap_invalid_password", null, null);
            } else if (ResultCode.NO_SUCH_OBJECT.equals(resultCode)) {
                String[] objs = { baseDN };
                throw new PolicyException(ResBundleUtils.rbName, "no_such_ldap_base_dn", objs, null);
            }
            String errorMsg = le.getMessage();
            String additionalMsg = le.getResult().getDiagnosticMessage();
            if (additionalMsg != null) {
                throw new PolicyException(errorMsg + ": " + additionalMsg);
            } else {
                throw new PolicyException(errorMsg);
            }
        } catch (Exception e) {
            throw new PolicyException(e);
        }
        // check if the user belongs to any of the selected groups
        if (qualifiedUserDNs.size() > 0) {
            debug.message("LDAPGroups.getUserDN(): qualified users={}", qualifiedUserDNs);
            Iterator<String> iter = qualifiedUserDNs.iterator();
            // we only take the first qualified DN if the DN
            userDN = DN.valueOf(iter.next());
        }
    }
    return userDN;
}
Also used : SearchRequest(org.forgerock.opendj.ldap.requests.SearchRequest) Connection(org.forgerock.opendj.ldap.Connection) DN(org.forgerock.opendj.ldap.DN) ByteString(org.forgerock.opendj.ldap.ByteString) LdapException(org.forgerock.opendj.ldap.LdapException) NameNotFoundException(com.sun.identity.policy.NameNotFoundException) PolicyException(com.sun.identity.policy.PolicyException) InvalidNameException(com.sun.identity.policy.InvalidNameException) SSOException(com.iplanet.sso.SSOException) LocalizedIllegalArgumentException(org.forgerock.i18n.LocalizedIllegalArgumentException) ConnectionEntryReader(org.forgerock.opendj.ldif.ConnectionEntryReader) PolicyException(com.sun.identity.policy.PolicyException) LdapException(org.forgerock.opendj.ldap.LdapException) ResultCode(org.forgerock.opendj.ldap.ResultCode) HashSet(java.util.HashSet) SearchResultEntry(org.forgerock.opendj.ldap.responses.SearchResultEntry)

Example 7 with SearchRequest

use of org.forgerock.opendj.ldap.requests.SearchRequest in project OpenAM by OpenRock.

the class LDAPAuthUtils method searchForUser.

/**
     * Searches and returns user for a specified attribute using parameters
     * specified in constructor and/or by setting properties.
     *
     * @throws LDAPUtilException
     */
public void searchForUser() throws LDAPUtilException {
    // assume that there is only one user attribute
    if (searchScope == SearchScope.BASE_OBJECT) {
        if (userSearchAttrs.size() == 1) {
            StringBuilder dnBuffer = new StringBuilder();
            dnBuffer.append((String) userSearchAttrs.iterator().next());
            dnBuffer.append("=");
            dnBuffer.append(userId);
            dnBuffer.append(",");
            dnBuffer.append(baseDN);
            userDN = dnBuffer.toString();
            if (debug.messageEnabled()) {
                debug.message("searchForUser, searchScope = BASE," + "userDN =" + userDN);
            }
            if (!isDynamicUserEnabled && userSearchAttrs.contains(userNamingAttr)) {
                return;
            } else if (isDynamicUserEnabled && (userAttributes == null || userAttributes.isEmpty())) {
                debug.message("user creation attribute list is empty ");
                return;
            }
            baseDN = userDN;
        } else {
            if (debug.messageEnabled()) {
                debug.message("cannot find user entry using scope=0" + "setting scope=1");
            }
            searchScope = SearchScope.SINGLE_LEVEL;
        }
    }
    if (searchFilter == null || searchFilter.length() == 0) {
        searchFilter = buildUserFilter();
    } else {
        StringBuilder bindFilter = new StringBuilder(200);
        if (userId != null) {
            bindFilter.append("(&");
            bindFilter.append(buildUserFilter());
            bindFilter.append(searchFilter);
            bindFilter.append(")");
        } else {
            bindFilter.append(searchFilter);
        }
        searchFilter = bindFilter.toString();
    }
    userDN = null;
    Connection conn = null;
    try {
        if (debug.messageEnabled()) {
            debug.message("Connecting to " + servers + "\nSearching " + baseDN + " for " + searchFilter + "\nscope = " + searchScope);
        }
        // Search
        int userAttrSize = 0;
        if (attrs == null) {
            if ((userAttributes == null) || (userAttributes.isEmpty())) {
                userAttrSize = 2;
                attrs = new String[userAttrSize];
                attrs[0] = "dn";
                attrs[1] = userNamingAttr;
            } else {
                userAttrSize = userAttributes.size();
                attrs = new String[userAttrSize + 2];
                attrs[0] = "dn";
                attrs[1] = userNamingAttr;
                Iterator attrItr = userAttributes.iterator();
                for (int i = 2; i < userAttrSize + 2; i++) {
                    attrs[i] = (String) attrItr.next();
                }
            }
        }
        if (debug.messageEnabled()) {
            debug.message("userAttrSize is : " + userAttrSize);
        }
        ConnectionEntryReader results;
        SearchRequest searchForUser = LDAPRequests.newSearchRequest(baseDN, searchScope, searchFilter, attrs);
        int userMatches = 0;
        SearchResultEntry entry;
        boolean userNamingValueSet = false;
        try {
            conn = getAdminConnection();
            results = conn.search(searchForUser);
            while (results.hasNext()) {
                if (results.isEntry()) {
                    entry = results.readEntry();
                    userDN = entry.getName().toString();
                    userMatches++;
                    if (attrs != null && attrs.length > 1) {
                        userNamingValueSet = true;
                        Attribute attr = entry.getAttribute(userNamingAttr);
                        if (attr != null) {
                            userNamingValue = attr.firstValueAsString();
                        }
                        if (isDynamicUserEnabled && (attrs.length > 2)) {
                            for (int i = 2; i < userAttrSize + 2; i++) {
                                attr = entry.getAttribute(attrs[i]);
                                if (attr != null) {
                                    Set<String> s = new HashSet<String>();
                                    Iterator<ByteString> values = attr.iterator();
                                    while (values.hasNext()) {
                                        s.add(values.next().toString());
                                    }
                                    userAttributeValues.put(attrs[i], s);
                                }
                            }
                        }
                    }
                } else {
                    //read and ignore references
                    results.readReference();
                }
            }
        } finally {
            if (conn != null) {
                conn.close();
            }
        }
        if (userNamingValueSet && (userDN == null || userNamingValue == null)) {
            if (debug.messageEnabled()) {
                debug.message("Cannot find entries for " + searchFilter);
            }
            setState(ModuleState.USER_NOT_FOUND);
            return;
        } else {
            if (userDN == null) {
                if (debug.messageEnabled()) {
                    debug.message("Cannot find entries for " + searchFilter);
                }
                setState(ModuleState.USER_NOT_FOUND);
                return;
            } else {
                setState(ModuleState.USER_FOUND);
            }
        }
        if (userMatches > 1) {
            // multiple user matches found
            debug.error("searchForUser : Multiple matches found for user '" + userId + "'. Please modify search start DN/filter/scope " + "to make sure unique match returned. Contact your " + "administrator to fix the problem");
            throw new LDAPUtilException("multipleUserMatchFound", (Object[]) null);
        }
    } catch (LdapException ere) {
        if (debug.warningEnabled()) {
            debug.warning("Search for User error: ", ere);
            debug.warning("resultCode: " + ere.getResult().getResultCode());
        }
        if (ere.getResult().getResultCode().equals(ResultCode.CLIENT_SIDE_CONNECT_ERROR) || ere.getResult().getResultCode().equals(ResultCode.CLIENT_SIDE_SERVER_DOWN) || ere.getResult().getResultCode().equals(ResultCode.UNAVAILABLE) || ere.getResult().getResultCode().equals(ResultCode.CLIENT_SIDE_TIMEOUT)) {
            if (debug.warningEnabled()) {
                debug.warning("Cannot connect to " + servers, ere);
            }
            setState(ModuleState.SERVER_DOWN);
        } else if (ere.getResult().getResultCode().equals(ResultCode.INVALID_CREDENTIALS)) {
            if (debug.warningEnabled()) {
                debug.warning("Cannot authenticate ");
            }
            throw new LDAPUtilException("FConnect", ResultCode.INVALID_CREDENTIALS, null);
        } else if (ere.getResult().getResultCode().equals(ResultCode.UNWILLING_TO_PERFORM)) {
            if (debug.warningEnabled()) {
                debug.message("Account Inactivated or Locked ");
            }
            throw new LDAPUtilException("FConnect", ResultCode.UNWILLING_TO_PERFORM, null);
        } else if (ere.getResult().getResultCode().equals(ResultCode.NO_SUCH_OBJECT)) {
            throw new LDAPUtilException("noUserMatchFound", ResultCode.NO_SUCH_OBJECT, null);
        } else {
            if (debug.warningEnabled()) {
                debug.warning("Exception while searching", ere);
            }
            setState(ModuleState.USER_NOT_FOUND);
        }
    } catch (SearchResultReferenceIOException srrio) {
        debug.error("Unable to complete search for user: " + userId, srrio);
        throw new LDAPUtilException(srrio);
    }
}
Also used : SearchRequest(org.forgerock.opendj.ldap.requests.SearchRequest) Attribute(org.forgerock.opendj.ldap.Attribute) ByteString(org.forgerock.opendj.ldap.ByteString) Connection(org.forgerock.opendj.ldap.Connection) ByteString(org.forgerock.opendj.ldap.ByteString) SearchResultReferenceIOException(org.forgerock.opendj.ldap.SearchResultReferenceIOException) ConnectionEntryReader(org.forgerock.opendj.ldif.ConnectionEntryReader) Iterator(java.util.Iterator) LdapException(org.forgerock.opendj.ldap.LdapException) SearchResultEntry(org.forgerock.opendj.ldap.responses.SearchResultEntry) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet)

Example 8 with SearchRequest

use of org.forgerock.opendj.ldap.requests.SearchRequest in project OpenAM by OpenRock.

the class DJLDAPv3Repo method getRoleMembers.

/**
     * Returns the DNs of the members of this role. To do that this will execute an LDAP search with a filter looking
     * for nsRoleDN=roleDN.
     *
     * @param dn The DN of the role to query.
     * @return The DNs of the members.
     * @throws IdRepoException If there is an error while trying to retrieve the role members.
     */
private Set<String> getRoleMembers(String dn) throws IdRepoException {
    Set<String> results = new HashSet<String>();
    DN roleBase = getBaseDN(IdType.ROLE);
    Filter filter = Filter.equality(roleDNAttr, dn);
    SearchRequest searchRequest = LDAPRequests.newSearchRequest(roleBase, roleScope, filter, DN_ATTR);
    searchRequest.setTimeLimit(defaultTimeLimit);
    searchRequest.setSizeLimit(defaultSizeLimit);
    Connection conn = null;
    try {
        conn = connectionFactory.getConnection();
        ConnectionEntryReader reader = conn.search(searchRequest);
        while (reader.hasNext()) {
            if (reader.isEntry()) {
                results.add(reader.readEntry().getName().toString());
            } else {
                //ignore search result references
                reader.readReference();
            }
        }
    } catch (LdapException ere) {
        DEBUG.error("An error occurred while trying to retrieve filtered role members for " + dn, ere);
        handleErrorResult(ere);
    } catch (SearchResultReferenceIOException srrioe) {
        //should never ever happen...
        DEBUG.error("Got reference instead of entry", srrioe);
        throw newIdRepoException(IdRepoErrorCode.SEARCH_FAILED, CLASS_NAME);
    } finally {
        IOUtils.closeIfNotNull(conn);
    }
    return results;
}
Also used : SearchRequest(org.forgerock.opendj.ldap.requests.SearchRequest) ConnectionEntryReader(org.forgerock.opendj.ldif.ConnectionEntryReader) Filter(org.forgerock.opendj.ldap.Filter) Connection(org.forgerock.opendj.ldap.Connection) DN(org.forgerock.opendj.ldap.DN) ByteString(org.forgerock.opendj.ldap.ByteString) SearchResultReferenceIOException(org.forgerock.opendj.ldap.SearchResultReferenceIOException) LdapException(org.forgerock.opendj.ldap.LdapException) CaseInsensitiveHashSet(com.sun.identity.common.CaseInsensitiveHashSet) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet)

Example 9 with SearchRequest

use of org.forgerock.opendj.ldap.requests.SearchRequest in project OpenAM by OpenRock.

the class DJLDAPv3Repo method getDN.

private String getDN(IdType type, String name, boolean shouldGenerate, String searchAttr) throws IdRepoException {
    Object cachedDn = null;
    if (dnCacheEnabled) {
        cachedDn = dnCache.get(generateDNCacheKey(name, type));
    }
    if (cachedDn != null) {
        return cachedDn.toString();
    }
    String dn = null;
    DN searchBase = getBaseDN(type);
    if (shouldGenerate) {
        return searchBase.child(getSearchAttribute(type), name).toString();
    }
    if (searchAttr == null) {
        searchAttr = getSearchAttribute(type);
    }
    Filter filter = Filter.and(Filter.equality(searchAttr, name), getObjectClassFilter(type));
    SearchRequest searchRequest = LDAPRequests.newSearchRequest(searchBase, defaultScope, filter, DN_ATTR);
    Connection conn = null;
    try {
        conn = connectionFactory.getConnection();
        ConnectionEntryReader reader = conn.search(searchRequest);
        SearchResultEntry entry = null;
        while (reader.hasNext()) {
            if (reader.isEntry()) {
                if (entry != null) {
                    throw newIdRepoException(ResultCode.CLIENT_SIDE_UNEXPECTED_RESULTS_RETURNED, IdRepoErrorCode.LDAP_EXCEPTION_OCCURRED, CLASS_NAME, ResultCode.CLIENT_SIDE_UNEXPECTED_RESULTS_RETURNED.intValue());
                }
                entry = reader.readEntry();
            } else {
                //ignore references
                reader.readReference();
            }
        }
        if (entry == null) {
            DEBUG.message("Unable to find entry with name: " + name + " under searchbase: " + searchBase + " with scope: " + defaultScope);
            throw new IdentityNotFoundException(IdRepoBundle.BUNDLE_NAME, IdRepoErrorCode.TYPE_NOT_FOUND, ResultCode.CLIENT_SIDE_NO_RESULTS_RETURNED, new Object[] { name, type.getName() });
        }
        dn = entry.getName().toString();
    } catch (LdapException ere) {
        DEBUG.error("An error occurred while querying entry DN", ere);
        handleErrorResult(ere);
    } catch (SearchResultReferenceIOException srrioe) {
        //should never ever happen...
        DEBUG.error("Got reference instead of entry", srrioe);
        throw newIdRepoException(IdRepoErrorCode.SEARCH_FAILED, CLASS_NAME);
    } finally {
        IOUtils.closeIfNotNull(conn);
    }
    if (dnCacheEnabled && !shouldGenerate) {
        dnCache.put(generateDNCacheKey(name, type), dn);
    }
    return dn;
}
Also used : SearchRequest(org.forgerock.opendj.ldap.requests.SearchRequest) ConnectionEntryReader(org.forgerock.opendj.ldif.ConnectionEntryReader) Filter(org.forgerock.opendj.ldap.Filter) Connection(org.forgerock.opendj.ldap.Connection) DN(org.forgerock.opendj.ldap.DN) ByteString(org.forgerock.opendj.ldap.ByteString) SearchResultReferenceIOException(org.forgerock.opendj.ldap.SearchResultReferenceIOException) LdapException(org.forgerock.opendj.ldap.LdapException) SearchResultEntry(org.forgerock.opendj.ldap.responses.SearchResultEntry)

Example 10 with SearchRequest

use of org.forgerock.opendj.ldap.requests.SearchRequest in project OpenAM by OpenRock.

the class DJLDAPv3Repo method getFilteredRoleMembers.

/**
     * Returns the DNs of the members of this filtered role. To do that this will execute a read on the filtered role
     * entry to get the values of the nsRoleFilter attribute, and then it will perform searches using the retrieved
     * filters.
     *
     * @param dn The DN of the filtered role to query.
     * @return The DNs of the members.
     * @throws IdRepoException If there is an error while trying to retrieve the filtered role members.
     */
private Set<String> getFilteredRoleMembers(String dn) throws IdRepoException {
    Set<String> results = new HashSet<String>();
    Connection conn = null;
    try {
        conn = connectionFactory.getConnection();
        SearchResultEntry entry = conn.searchSingleEntry(LDAPRequests.newSingleEntrySearchRequest(dn, roleFilterAttr));
        Attribute filterAttr = entry.getAttribute(roleFilterAttr);
        if (filterAttr != null) {
            for (ByteString byteString : filterAttr) {
                Filter filter = Filter.valueOf(byteString.toString());
                //TODO: would it make sense to OR these filters and run a single search?
                SearchRequest searchRequest = LDAPRequests.newSearchRequest(rootSuffix, defaultScope, filter.toString(), DN_ATTR);
                searchRequest.setTimeLimit(defaultTimeLimit);
                searchRequest.setSizeLimit(defaultSizeLimit);
                ConnectionEntryReader reader = conn.search(searchRequest);
                while (reader.hasNext()) {
                    if (reader.isEntry()) {
                        results.add(reader.readEntry().getName().toString());
                    } else {
                        //ignore search result references
                        reader.readReference();
                    }
                }
            }
        }
    } catch (LdapException ere) {
        DEBUG.error("An error occurred while trying to retrieve filtered role members for " + dn, ere);
        handleErrorResult(ere);
    } catch (SearchResultReferenceIOException srrioe) {
        //should never ever happen...
        DEBUG.error("Got reference instead of entry", srrioe);
        throw newIdRepoException(IdRepoErrorCode.SEARCH_FAILED, CLASS_NAME);
    } finally {
        IOUtils.closeIfNotNull(conn);
    }
    return results;
}
Also used : SearchRequest(org.forgerock.opendj.ldap.requests.SearchRequest) ConnectionEntryReader(org.forgerock.opendj.ldif.ConnectionEntryReader) Attribute(org.forgerock.opendj.ldap.Attribute) LinkedAttribute(org.forgerock.opendj.ldap.LinkedAttribute) Filter(org.forgerock.opendj.ldap.Filter) ByteString(org.forgerock.opendj.ldap.ByteString) Connection(org.forgerock.opendj.ldap.Connection) ByteString(org.forgerock.opendj.ldap.ByteString) SearchResultReferenceIOException(org.forgerock.opendj.ldap.SearchResultReferenceIOException) LdapException(org.forgerock.opendj.ldap.LdapException) CaseInsensitiveHashSet(com.sun.identity.common.CaseInsensitiveHashSet) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet) SearchResultEntry(org.forgerock.opendj.ldap.responses.SearchResultEntry)

Aggregations

SearchRequest (org.forgerock.opendj.ldap.requests.SearchRequest)32 ConnectionEntryReader (org.forgerock.opendj.ldif.ConnectionEntryReader)26 LdapException (org.forgerock.opendj.ldap.LdapException)25 Connection (org.forgerock.opendj.ldap.Connection)20 SearchResultEntry (org.forgerock.opendj.ldap.responses.SearchResultEntry)19 ByteString (org.forgerock.opendj.ldap.ByteString)18 ResultCode (org.forgerock.opendj.ldap.ResultCode)15 HashSet (java.util.HashSet)13 SearchResultReferenceIOException (org.forgerock.opendj.ldap.SearchResultReferenceIOException)10 Attribute (org.forgerock.opendj.ldap.Attribute)9 DN (org.forgerock.opendj.ldap.DN)9 SSOException (com.iplanet.sso.SSOException)8 PolicyException (com.sun.identity.policy.PolicyException)8 InvalidNameException (com.sun.identity.policy.InvalidNameException)7 NameNotFoundException (com.sun.identity.policy.NameNotFoundException)7 LinkedHashSet (java.util.LinkedHashSet)7 SMSException (com.sun.identity.sm.SMSException)6 Filter (org.forgerock.opendj.ldap.Filter)6 CaseInsensitiveHashSet (com.sun.identity.common.CaseInsensitiveHashSet)5 ArrayList (java.util.ArrayList)4