Search in sources :

Example 16 with LdapException

use of org.forgerock.opendj.ldap.LdapException 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 17 with LdapException

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

the class AMSetupDSConfig method getLDAPConnection.

/**
     * Helper method to return Ldap connection 
     *
     * @param ssl <code>true</code> if directory server is running SSL.
     * @return Ldap connection 
     */
private synchronized Connection getLDAPConnection(boolean ssl) {
    try {
        if (ld == null) {
            ShutdownManager shutdownMan = com.sun.identity.common.ShutdownManager.getInstance();
            // All connections will use authentication
            SimpleBindRequest request = LDAPRequests.newSimpleBindRequest(dsManager, dsAdminPwd.toCharArray());
            Options options = Options.defaultOptions().set(REQUEST_TIMEOUT, new Duration((long) 3, TimeUnit.SECONDS)).set(AUTHN_BIND_REQUEST, request);
            if (ssl) {
                options = options.set(SSL_CONTEXT, new SSLContextBuilder().getSSLContext());
            }
            ld = new LDAPConnectionFactory(dsHostName, getPort(), options);
            shutdownMan.addShutdownListener(new ShutdownListener() {

                public void shutdown() {
                    disconnectDServer();
                }
            });
        }
        return ld.getConnection();
    } catch (LdapException e) {
        disconnectDServer();
        dsConfigInstance = null;
        ld = null;
    } catch (Exception e) {
        dsConfigInstance = null;
        ld = null;
    }
    return null;
}
Also used : ShutdownListener(org.forgerock.util.thread.listener.ShutdownListener) Options(org.forgerock.util.Options) SimpleBindRequest(org.forgerock.opendj.ldap.requests.SimpleBindRequest) ShutdownManager(org.forgerock.util.thread.listener.ShutdownManager) Duration(org.forgerock.util.time.Duration) LDAPConnectionFactory(org.forgerock.opendj.ldap.LDAPConnectionFactory) SSLContextBuilder(org.forgerock.opendj.ldap.SSLContextBuilder) LdapException(org.forgerock.opendj.ldap.LdapException) LdapException(org.forgerock.opendj.ldap.LdapException) IOException(java.io.IOException)

Example 18 with LdapException

use of org.forgerock.opendj.ldap.LdapException 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 19 with LdapException

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

the class DJLDAPv3Repo method authenticate.

/**
     * Tries to bind as the user with the credentials passed in via callbacks. This authentication mechanism does not
     * handle password policies, nor password expiration.
     *
     * @param credentials The username/password combination.
     * @return <code>true</code> if the bind operation was successful.
     * @throws IdRepoException If the passed in username/password was null, or if the specified user cannot be found.
     * @throws AuthLoginException If an LDAP error occurs during authentication.
     * @throws InvalidPasswordException If the provided password is not valid, so Account Lockout can be triggered.
     */
@Override
public boolean authenticate(Callback[] credentials) throws IdRepoException, AuthLoginException {
    if (DEBUG.messageEnabled()) {
        DEBUG.message("authenticate invoked");
    }
    String userName = null;
    char[] password = null;
    for (Callback callback : credentials) {
        if (callback instanceof NameCallback) {
            userName = ((NameCallback) callback).getName();
        } else if (callback instanceof PasswordCallback) {
            password = ((PasswordCallback) callback).getPassword();
        }
    }
    if (userName == null || password == null) {
        throw newIdRepoException(IdRepoErrorCode.UNABLE_TO_AUTHENTICATE, CLASS_NAME);
    }
    String dn = findDNForAuth(IdType.USER, userName);
    Connection conn = null;
    try {
        BindRequest bindRequest = LDAPRequests.newSimpleBindRequest(dn, password);
        conn = bindConnectionFactory.getConnection();
        BindResult bindResult = conn.bind(bindRequest);
        return bindResult.isSuccess();
    } catch (LdapException ere) {
        ResultCode resultCode = ere.getResult().getResultCode();
        if (DEBUG.messageEnabled()) {
            DEBUG.message("An error occurred while trying to authenticate a user: " + ere.toString());
        }
        if (resultCode.equals(ResultCode.INVALID_CREDENTIALS)) {
            throw new InvalidPasswordException(AM_AUTH, "InvalidUP", null, userName, null);
        } else if (resultCode.equals(ResultCode.UNWILLING_TO_PERFORM) || resultCode.equals(ResultCode.CONSTRAINT_VIOLATION)) {
            throw new AuthLoginException(AM_AUTH, "FAuth", null);
        } else if (resultCode.equals(ResultCode.INAPPROPRIATE_AUTHENTICATION)) {
            throw new AuthLoginException(AM_AUTH, "InappAuth", null);
        } else {
            throw new AuthLoginException(AM_AUTH, "LDAPex", null);
        }
    } finally {
        IOUtils.closeIfNotNull(conn);
    }
}
Also used : PasswordCallback(javax.security.auth.callback.PasswordCallback) Callback(javax.security.auth.callback.Callback) NameCallback(javax.security.auth.callback.NameCallback) NameCallback(javax.security.auth.callback.NameCallback) Connection(org.forgerock.opendj.ldap.Connection) BindRequest(org.forgerock.opendj.ldap.requests.BindRequest) PasswordCallback(javax.security.auth.callback.PasswordCallback) BindResult(org.forgerock.opendj.ldap.responses.BindResult) InvalidPasswordException(com.sun.identity.authentication.spi.InvalidPasswordException) AuthLoginException(com.sun.identity.authentication.spi.AuthLoginException) ByteString(org.forgerock.opendj.ldap.ByteString) LdapException(org.forgerock.opendj.ldap.LdapException) ResultCode(org.forgerock.opendj.ldap.ResultCode)

Example 20 with LdapException

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

the class DJLDAPv3Repo method modifyGroupMembership.

/**
     * Modifies group membership data in the directory. In case the memberOf attribute is configured, this will also
     * iterate through all the user entries and modify those as well. Otherwise this will only modify the uniquemember
     * attribute on the group entry based on the operation.
     *
     * @param groupDN The DN of the group.
     * @param memberDNs The DNs of the group members.
     * @param operation Whether the members needs to be added or removed from the group. Use {@link IdRepo#ADDMEMBER}
     * or {@link IdRepo#REMOVEMEMBER}.
     * @throws IdRepoException If there was an error while modifying the membership data.
     */
private void modifyGroupMembership(String groupDN, Set<String> memberDNs, int operation) throws IdRepoException {
    ModifyRequest modifyRequest = LDAPRequests.newModifyRequest(groupDN);
    Attribute attr = new LinkedAttribute(uniqueMemberAttr, memberDNs);
    ModificationType modType;
    if (ADDMEMBER == operation) {
        modType = ModificationType.ADD;
    } else {
        modType = ModificationType.DELETE;
    }
    modifyRequest.addModification(new Modification(modType, attr));
    Connection conn = null;
    try {
        conn = connectionFactory.getConnection();
        conn.modify(modifyRequest);
        if (memberOfAttr != null) {
            for (String member : memberDNs) {
                ModifyRequest userMod = LDAPRequests.newModifyRequest(member);
                userMod.addModification(modType, memberOfAttr, groupDN);
                conn.modify(userMod);
            }
        }
    } catch (LdapException ere) {
        DEBUG.error("An error occurred while trying to modify group membership. Name: " + groupDN + " memberDNs: " + memberDNs + " Operation: " + modType, ere);
        handleErrorResult(ere);
    } finally {
        IOUtils.closeIfNotNull(conn);
    }
}
Also used : Modification(org.forgerock.opendj.ldap.Modification) Attribute(org.forgerock.opendj.ldap.Attribute) LinkedAttribute(org.forgerock.opendj.ldap.LinkedAttribute) ModificationType(org.forgerock.opendj.ldap.ModificationType) Connection(org.forgerock.opendj.ldap.Connection) ModifyRequest(org.forgerock.opendj.ldap.requests.ModifyRequest) ByteString(org.forgerock.opendj.ldap.ByteString) LdapException(org.forgerock.opendj.ldap.LdapException) LinkedAttribute(org.forgerock.opendj.ldap.LinkedAttribute)

Aggregations

LdapException (org.forgerock.opendj.ldap.LdapException)90 Connection (org.forgerock.opendj.ldap.Connection)64 ByteString (org.forgerock.opendj.ldap.ByteString)45 SearchResultEntry (org.forgerock.opendj.ldap.responses.SearchResultEntry)38 ResultCode (org.forgerock.opendj.ldap.ResultCode)37 ConnectionEntryReader (org.forgerock.opendj.ldif.ConnectionEntryReader)37 SearchResultReferenceIOException (org.forgerock.opendj.ldap.SearchResultReferenceIOException)24 SearchRequest (org.forgerock.opendj.ldap.requests.SearchRequest)24 HashSet (java.util.HashSet)22 Attribute (org.forgerock.opendj.ldap.Attribute)19 PolicyException (com.sun.identity.policy.PolicyException)13 SMSException (com.sun.identity.sm.SMSException)12 ModifyRequest (org.forgerock.opendj.ldap.requests.ModifyRequest)12 SSOException (com.iplanet.sso.SSOException)11 LinkedHashSet (java.util.LinkedHashSet)11 DN (org.forgerock.opendj.ldap.DN)11 CaseInsensitiveHashSet (com.sun.identity.common.CaseInsensitiveHashSet)10 IOException (java.io.IOException)10 InvalidNameException (com.sun.identity.policy.InvalidNameException)9 NameNotFoundException (com.sun.identity.policy.NameNotFoundException)9