Search in sources :

Example 1 with SearchResultReferenceIOException

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

the class LocalLdapAuthModule method getDN.

private String getDN(String uid) throws LoginException {
    String retVal = "";
    if (uid == null) {
        throw (new LoginException(AuthI18n.authI18n.getString("com.iplanet.auth.invalid-username")));
    }
    if (LDAPUtils.isDN(uid)) {
        return uid;
    }
    String namingAttribute = UIDATTR;
    try {
        String orgName = (String) options.get(LoginContext.ORGNAME);
        if ((orgName != null) && !LDAPUtils.isDN(orgName)) {
            // Use orgname only if it a DN, else baseDN
            orgName = baseDN;
        }
        if (com.sun.identity.sm.ServiceManager.isAMSDKConfigured()) {
            namingAttribute = TemplateManager.getTemplateManager().getCreationTemplate(TEMPLATE_NAME, (orgName == null) ? null : new Guid(orgName)).getNamingAttribute();
        }
    } catch (Exception e) {
    // Ignore the exception and use the default naming attribute
    }
    StringBuilder filter = new StringBuilder();
    filter.append('(').append(namingAttribute).append('=').append(uid).append(')');
    String[] attrs = { "noAttr" };
    ConnectionEntryReader results = null;
    try {
        // Read the serverconfig.xml for LDAP information
        if (!readServerConfiguration) {
            readServerConfig();
        }
        if (conn == null) {
            debug.warning("LocalLdapAuthModule.getDN(): lda connection is null");
            throw (new LoginException("INVALID_USER_NAME"));
        } else {
            results = conn.search(LDAPRequests.newSearchRequest(baseDN, SearchScope.WHOLE_SUBTREE, filter.toString(), attrs));
        }
        if (results.hasNext()) {
            SearchResultEntry entry = results.readEntry();
            retVal = entry.getName().toString();
        }
        if (retVal == null || retVal.equals("")) {
            throw new LoginException("INVALID_USER_NAME");
        }
        return retVal;
    } catch (LdapException | SearchResultReferenceIOException ex) {
        throw new LoginException(ex.getMessage());
    } finally {
        IOUtils.closeIfNotNull(conn);
        conn = null;
    }
}
Also used : ConnectionEntryReader(org.forgerock.opendj.ldif.ConnectionEntryReader) LoginException(javax.security.auth.login.LoginException) Guid(com.iplanet.ums.Guid) SearchResultReferenceIOException(org.forgerock.opendj.ldap.SearchResultReferenceIOException) LdapException(org.forgerock.opendj.ldap.LdapException) LoginException(javax.security.auth.login.LoginException) LDAPServiceException(com.iplanet.services.ldap.LDAPServiceException) UnsupportedCallbackException(javax.security.auth.callback.UnsupportedCallbackException) LdapException(org.forgerock.opendj.ldap.LdapException) GeneralSecurityException(java.security.GeneralSecurityException) IOException(java.io.IOException) SearchResultReferenceIOException(org.forgerock.opendj.ldap.SearchResultReferenceIOException) SearchResultEntry(org.forgerock.opendj.ldap.responses.SearchResultEntry)

Example 2 with SearchResultReferenceIOException

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

the class SearchResultIterator method hasNext.

public boolean hasNext() {
    try {
        if (results.hasNext()) {
            if (current == null) {
                if (results.isReference()) {
                    debug.warning("SearchResultIterator: ignoring reference: {}", results.readReference());
                    return hasNext();
                }
                SearchResultEntry entry = results.readEntry();
                String dn = entry.getName().toString();
                if (hasExcludeDNs && excludeDNs.contains(dn)) {
                    return hasNext();
                }
                current = new SMSDataEntry(dn, SMSUtils.convertEntryToAttributesMap(entry));
            }
            return true;
        }
    } catch (LdapException e) {
        ResultCode errorCode = e.getResult().getResultCode();
        if (errorCode.equals(ResultCode.SIZE_LIMIT_EXCEEDED)) {
            debug.message("SearchResultIterator: size limit exceeded");
        } else {
            debug.error("SearchResultIterator.hasNext", e);
        }
    } catch (SearchResultReferenceIOException e) {
        debug.error("SearchResultIterator.hasNext: reference should be already handled", e);
        return hasNext();
    }
    conn.close();
    return false;
}
Also used : SMSDataEntry(com.sun.identity.sm.SMSDataEntry) SearchResultReferenceIOException(org.forgerock.opendj.ldap.SearchResultReferenceIOException) LdapException(org.forgerock.opendj.ldap.LdapException) ResultCode(org.forgerock.opendj.ldap.ResultCode) SearchResultEntry(org.forgerock.opendj.ldap.responses.SearchResultEntry)

Example 3 with SearchResultReferenceIOException

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

the class LDAPUsers method getUserDN.

/**
     * Gets the DN for a user identified 
     * by the token. If the Directory server is locally installed to speed
     * up the search, no directoty search is performed and the DN obtained
     * from the token is returned. If the directory is remote
     * a LDAP search is performed to get the user DN.
     */
private DN getUserDN(SSOToken token) throws SSOException, PolicyException {
    Set<String> qualifiedUserDNs = new HashSet<>();
    String userLocalDN = token.getPrincipal().getName();
    DN userDN = null;
    if (localDS && !PolicyUtils.principalNameEqualsUuid(token)) {
        userDN = DN.valueOf(userLocalDN);
    } else {
        // try to figure out the user name from the local user DN
        int beginIndex = userLocalDN.indexOf("=");
        int endIndex = userLocalDN.indexOf(",");
        if ((beginIndex <= 0) || (endIndex <= 0) || (beginIndex >= endIndex)) {
            throw (new PolicyException(ResBundleUtils.rbName, "ldapusers_subject_invalid_local_user_dn", null, null));
        }
        String userName = userLocalDN.substring(beginIndex + 1, endIndex);
        String searchFilter = null;
        if ((userSearchFilter != null) && !(userSearchFilter.length() == 0)) {
            searchFilter = "(&" + userSearchFilter + PolicyUtils.constructUserFilter(token, userRDNAttrName, userName, aliasEnabled) + ")";
        } else {
            searchFilter = PolicyUtils.constructUserFilter(token, userRDNAttrName, userName, aliasEnabled);
        }
        if (debug.messageEnabled()) {
            debug.message("LDAPUsers.getUserDN(): search filter is: " + searchFilter);
        }
        String[] attrs = { userRDNAttrName };
        // search the remote ldap and find out the user DN
        try (Connection ld = connPool.getConnection()) {
            ConnectionEntryReader res = search(searchFilter, ld, attrs);
            while (res.hasNext()) {
                try {
                    SearchResultEntry entry = res.readEntry();
                    qualifiedUserDNs.add(entry.getName().toString());
                } catch (SearchResultReferenceIOException e) {
                    // ignore referrals
                    continue;
                } catch (LdapException e) {
                    String[] objs = { orgName };
                    ResultCode resultCode = e.getResult().getResultCode();
                    if (resultCode.equals(ResultCode.SIZE_LIMIT_EXCEEDED)) {
                        debug.warning("LDAPUsers.getUserDN(): exceeded the size limit");
                        throw new PolicyException(ResBundleUtils.rbName, "ldap_search_exceed_size_limit", objs, null);
                    } else if (resultCode.equals(ResultCode.TIME_LIMIT_EXCEEDED)) {
                        debug.warning("LDAPUsers.getUserDN(): exceeded the time limit");
                        throw new PolicyException(ResBundleUtils.rbName, "ldap_search_exceed_time_limit", objs, null);
                    } else {
                        throw new PolicyException(e);
                    }
                }
            }
        } catch (LdapException e) {
            throw handleResultException(e);
        } catch (Exception e) {
            throw new PolicyException(e);
        }
        // check if the user belongs to any of the selected users
        if (qualifiedUserDNs.size() > 0) {
            debug.message("LDAPUsers.getUserDN(): qualified users={}", qualifiedUserDNs);
            Iterator<String> iter = qualifiedUserDNs.iterator();
            // we only take the first qualified DN
            userDN = DN.valueOf(iter.next());
        }
    }
    return userDN;
}
Also used : 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) NameNotFoundException(com.sun.identity.policy.NameNotFoundException) PolicyException(com.sun.identity.policy.PolicyException) InvalidNameException(com.sun.identity.policy.InvalidNameException) SSOException(com.iplanet.sso.SSOException) SearchResultReferenceIOException(org.forgerock.opendj.ldap.SearchResultReferenceIOException) 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 4 with SearchResultReferenceIOException

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

the class LDAPUsers method getValidEntries.

/**
     * Returns a set of possible values that satisfy the <code>pattern</code>.
     * The returned <code>ValidValues</code> object contains a set of
     * map of user DN to a map of user's attribute name to a string array of
     * attribute values.
     *
     * @param token Single Sign On token for fetching the possible values.
     * @param pattern Search pattern of which possible values are matched to.
     * @param attributeNames Array of attribute names to be to returned.
     * @return a set of possible values that satify the <code>pattern</code>.
     * @throws SSOException if <code>SSOToken</code> is invalid.
     * @throws PolicyException if there are problems getting these values.
     */
public ValidValues getValidEntries(SSOToken token, String pattern, String[] attributeNames) throws SSOException, PolicyException {
    if (!initialized) {
        throw (new PolicyException(ResBundleUtils.rbName, "ldapusers_subject_not_yet_initialized", null, null));
    }
    Set<Map<String, Map<String, String[]>>> results = new HashSet<>();
    String searchFilter = getSearchFilter(pattern);
    int status = ValidValues.SUCCESS;
    try (Connection ld = connPool.getConnection()) {
        ConnectionEntryReader res = search(searchFilter, ld, attributeNames);
        Map<String, Map<String, String[]>> map = new HashMap<>();
        results.add(map);
        while (res.hasNext()) {
            try {
                SearchResultEntry entry = res.readEntry();
                if (entry != null) {
                    String userDN = entry.getName().toString();
                    map.put(userDN, getUserAttributeValues(entry, attributeNames));
                }
            } catch (SearchResultReferenceIOException lre) {
                // ignore referrals
                continue;
            } catch (LdapException e) {
                ResultCode resultCode = e.getResult().getResultCode();
                if (resultCode.equals(ResultCode.SIZE_LIMIT_EXCEEDED)) {
                    debug.warning("LDAPUsers.getValidEntries(): exceeded the size limit");
                    status = ValidValues.SIZE_LIMIT_EXCEEDED;
                } else if (resultCode.equals(ResultCode.TIME_LIMIT_EXCEEDED)) {
                    debug.warning("LDAPUsers.getValidEntries(): exceeded the time limit");
                    status = ValidValues.TIME_LIMIT_EXCEEDED;
                } else {
                    throw new PolicyException(e);
                }
            }
        }
    } catch (LdapException e) {
        throw handleResultException(e);
    } catch (Exception e) {
        throw new PolicyException(e);
    }
    return new ValidValues(status, results);
}
Also used : HashMap(java.util.HashMap) ValidValues(com.sun.identity.policy.ValidValues) Connection(org.forgerock.opendj.ldap.Connection) ByteString(org.forgerock.opendj.ldap.ByteString) SearchResultReferenceIOException(org.forgerock.opendj.ldap.SearchResultReferenceIOException) 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) SearchResultReferenceIOException(org.forgerock.opendj.ldap.SearchResultReferenceIOException) ConnectionEntryReader(org.forgerock.opendj.ldif.ConnectionEntryReader) PolicyException(com.sun.identity.policy.PolicyException) HashMap(java.util.HashMap) Map(java.util.Map) LdapException(org.forgerock.opendj.ldap.LdapException) ResultCode(org.forgerock.opendj.ldap.ResultCode) HashSet(java.util.HashSet) SearchResultEntry(org.forgerock.opendj.ldap.responses.SearchResultEntry)

Example 5 with SearchResultReferenceIOException

use of org.forgerock.opendj.ldap.SearchResultReferenceIOException 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)

Aggregations

LdapException (org.forgerock.opendj.ldap.LdapException)21 SearchResultReferenceIOException (org.forgerock.opendj.ldap.SearchResultReferenceIOException)21 SearchResultEntry (org.forgerock.opendj.ldap.responses.SearchResultEntry)18 ConnectionEntryReader (org.forgerock.opendj.ldif.ConnectionEntryReader)18 Connection (org.forgerock.opendj.ldap.Connection)16 ByteString (org.forgerock.opendj.ldap.ByteString)14 HashSet (java.util.HashSet)10 SearchRequest (org.forgerock.opendj.ldap.requests.SearchRequest)9 LinkedHashSet (java.util.LinkedHashSet)8 Attribute (org.forgerock.opendj.ldap.Attribute)8 ResultCode (org.forgerock.opendj.ldap.ResultCode)7 CaseInsensitiveHashSet (com.sun.identity.common.CaseInsensitiveHashSet)5 Filter (org.forgerock.opendj.ldap.Filter)5 PolicyException (com.sun.identity.policy.PolicyException)4 DN (org.forgerock.opendj.ldap.DN)4 LinkedAttribute (org.forgerock.opendj.ldap.LinkedAttribute)4 SSOException (com.iplanet.sso.SSOException)2 InvalidNameException (com.sun.identity.policy.InvalidNameException)2 NameNotFoundException (com.sun.identity.policy.NameNotFoundException)2 ValidValues (com.sun.identity.policy.ValidValues)2