Search in sources :

Example 11 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 12 with SearchResultReferenceIOException

use of org.forgerock.opendj.ldap.SearchResultReferenceIOException in project ddf by codice.

the class SslLdapLoginModule method doLogin.

protected boolean doLogin() throws LoginException {
    //--------- EXTRACT USERNAME AND PASSWORD FOR LDAP LOOKUP -------------
    Callback[] callbacks = new Callback[2];
    callbacks[0] = new NameCallback("Username: ");
    callbacks[1] = new PasswordCallback("Password: ", false);
    try {
        callbackHandler.handle(callbacks);
    } catch (IOException ioException) {
        throw new LoginException(ioException.getMessage());
    } catch (UnsupportedCallbackException unsupportedCallbackException) {
        boolean result;
        throw new LoginException(unsupportedCallbackException.getMessage() + " not available to obtain information from user.");
    }
    user = ((NameCallback) callbacks[0]).getName();
    if (user == null) {
        return false;
    }
    user = user.trim();
    validateUsername(user);
    char[] tmpPassword = ((PasswordCallback) callbacks[1]).getPassword();
    // this method.
    if ("none".equalsIgnoreCase(getBindMethod()) && (tmpPassword != null)) {
        LOGGER.debug("Changing from authentication = none to simple since user or password was specified.");
        // default to simple so that the provided user/password will get checked
        setBindMethod(DEFAULT_AUTHENTICATION);
    }
    if (tmpPassword == null) {
        tmpPassword = new char[0];
    }
    //---------------------------------------------------------------------
    // RESET OBJECT STATE AND DECLARE LOCAL VARS
    principals = new HashSet<>();
    Connection connection;
    String userDn;
    //------------- CREATE CONNECTION #1 ----------------------------------
    try {
        connection = ldapConnectionFactory.getConnection();
    } catch (LdapException e) {
        LOGGER.info("Unable to get LDAP Connection from factory.", e);
        return false;
    }
    if (connection != null) {
        try {
            //------------- BIND #1 (CONNECTION USERNAME & PASSWORD) --------------
            try {
                BindRequest request;
                switch(getBindMethod()) {
                    case "Simple":
                        request = Requests.newSimpleBindRequest(connectionUsername, connectionPassword);
                        break;
                    case "SASL":
                        request = Requests.newPlainSASLBindRequest(connectionUsername, connectionPassword);
                        break;
                    case "GSSAPI SASL":
                        request = Requests.newGSSAPISASLBindRequest(connectionUsername, connectionPassword);
                        ((GSSAPISASLBindRequest) request).setRealm(realm);
                        ((GSSAPISASLBindRequest) request).setKDCAddress(kdcAddress);
                        break;
                    case "Digest MD5 SASL":
                        request = Requests.newDigestMD5SASLBindRequest(connectionUsername, connectionPassword);
                        ((DigestMD5SASLBindRequest) request).setCipher(DigestMD5SASLBindRequest.CIPHER_HIGH);
                        ((DigestMD5SASLBindRequest) request).getQOPs().clear();
                        ((DigestMD5SASLBindRequest) request).getQOPs().add(DigestMD5SASLBindRequest.QOP_AUTH_CONF);
                        ((DigestMD5SASLBindRequest) request).getQOPs().add(DigestMD5SASLBindRequest.QOP_AUTH_INT);
                        ((DigestMD5SASLBindRequest) request).getQOPs().add(DigestMD5SASLBindRequest.QOP_AUTH);
                        if (StringUtils.isNotEmpty(realm)) {
                            ((DigestMD5SASLBindRequest) request).setRealm(realm);
                        }
                        break;
                    default:
                        request = Requests.newSimpleBindRequest(connectionUsername, connectionPassword);
                        break;
                }
                BindResult bindResult = connection.bind(request);
                if (!bindResult.isSuccess()) {
                    LOGGER.debug("Bind failed");
                    return false;
                }
            } catch (LdapException e) {
                LOGGER.debug("Unable to bind to LDAP server.", e);
                return false;
            }
            //--------- SEARCH #1, FIND USER DISTINGUISHED NAME -----------
            SearchScope scope;
            if (userSearchSubtree) {
                scope = SearchScope.WHOLE_SUBTREE;
            } else {
                scope = SearchScope.SINGLE_LEVEL;
            }
            userFilter = userFilter.replaceAll(Pattern.quote("%u"), Matcher.quoteReplacement(user));
            userFilter = userFilter.replace("\\", "\\\\");
            ConnectionEntryReader entryReader = connection.search(userBaseDN, scope, userFilter);
            try {
                if (!entryReader.hasNext()) {
                    LOGGER.info("User {} not found in LDAP.", user);
                    return false;
                }
                SearchResultEntry searchResultEntry = entryReader.readEntry();
                userDn = searchResultEntry.getName().toString();
            } catch (LdapException | SearchResultReferenceIOException e) {
                LOGGER.info("Unable to read contents of LDAP user search.", e);
                return false;
            }
        } finally {
            //------------ CLOSE CONNECTION -------------------------------
            connection.close();
        }
    } else {
        return false;
    }
    //------------- CREATE CONNECTION #2 ----------------------------------
    try {
        connection = ldapConnectionFactory.getConnection();
    } catch (LdapException e) {
        LOGGER.info("Unable to get LDAP Connection from factory.", e);
        return false;
    }
    if (connection != null) {
        // Validate user's credentials.
        try {
            BindResult bindResult = connection.bind(userDn, tmpPassword);
            if (!bindResult.isSuccess()) {
                LOGGER.info("Bind failed");
                return false;
            }
        } catch (Exception e) {
            LOGGER.info("Unable to bind user to LDAP server.", e);
            return false;
        } finally {
            //------------ CLOSE CONNECTION -------------------------------
            connection.close();
        }
        //---------- ADD USER AS PRINCIPAL --------------------------------
        principals.add(new UserPrincipal(user));
    } else {
        return false;
    }
    //-------------- CREATE CONNECTION #3 ---------------------------------
    try {
        connection = ldapConnectionFactory.getConnection();
    } catch (LdapException e) {
        LOGGER.info("Unable to get LDAP Connection from factory.", e);
        return false;
    }
    if (connection != null) {
        try {
            //----- BIND #3 (CONNECTION USERNAME & PASSWORD) --------------
            try {
                BindResult bindResult = connection.bind(connectionUsername, connectionPassword);
                if (!bindResult.isSuccess()) {
                    LOGGER.info("Bind failed");
                    return false;
                }
            } catch (LdapException e) {
                LOGGER.info("Unable to bind to LDAP server.", e);
                return false;
            }
            //--------- SEARCH #3, GET ROLES ------------------------------
            SearchScope scope;
            if (roleSearchSubtree) {
                scope = SearchScope.WHOLE_SUBTREE;
            } else {
                scope = SearchScope.SINGLE_LEVEL;
            }
            roleFilter = roleFilter.replaceAll(Pattern.quote("%u"), Matcher.quoteReplacement(user));
            roleFilter = roleFilter.replaceAll(Pattern.quote("%dn"), Matcher.quoteReplacement(userBaseDN));
            roleFilter = roleFilter.replaceAll(Pattern.quote("%fqdn"), Matcher.quoteReplacement(userDn));
            roleFilter = roleFilter.replace("\\", "\\\\");
            ConnectionEntryReader entryReader = connection.search(roleBaseDN, scope, roleFilter, roleNameAttribute);
            SearchResultEntry entry;
            //------------- ADD ROLES AS NEW PRINCIPALS -------------------
            try {
                while (entryReader.hasNext()) {
                    entry = entryReader.readEntry();
                    Attribute attr = entry.getAttribute(roleNameAttribute);
                    for (ByteString role : attr) {
                        principals.add(new RolePrincipal(role.toString()));
                    }
                }
            } catch (Exception e) {
                boolean result;
                throw new LoginException("Can't get user " + user + " roles: " + e.getMessage());
            }
        } finally {
            //------------ CLOSE CONNECTION -------------------------------
            connection.close();
        }
    } else {
        return false;
    }
    return true;
}
Also used : Attribute(org.forgerock.opendj.ldap.Attribute) ByteString(org.forgerock.opendj.ldap.ByteString) DigestMD5SASLBindRequest(org.forgerock.opendj.ldap.requests.DigestMD5SASLBindRequest) GSSAPISASLBindRequest(org.forgerock.opendj.ldap.requests.GSSAPISASLBindRequest) BindRequest(org.forgerock.opendj.ldap.requests.BindRequest) ByteString(org.forgerock.opendj.ldap.ByteString) GSSAPISASLBindRequest(org.forgerock.opendj.ldap.requests.GSSAPISASLBindRequest) PasswordCallback(javax.security.auth.callback.PasswordCallback) UnsupportedCallbackException(javax.security.auth.callback.UnsupportedCallbackException) RolePrincipal(org.apache.karaf.jaas.boot.principal.RolePrincipal) LdapException(org.forgerock.opendj.ldap.LdapException) Connection(org.forgerock.opendj.ldap.Connection) IOException(java.io.IOException) SearchResultReferenceIOException(org.forgerock.opendj.ldap.SearchResultReferenceIOException) SearchResultReferenceIOException(org.forgerock.opendj.ldap.SearchResultReferenceIOException) LoginException(javax.security.auth.login.LoginException) UnsupportedCallbackException(javax.security.auth.callback.UnsupportedCallbackException) LdapException(org.forgerock.opendj.ldap.LdapException) GeneralSecurityException(java.security.GeneralSecurityException) IOException(java.io.IOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) SearchResultReferenceIOException(org.forgerock.opendj.ldap.SearchResultReferenceIOException) UserPrincipal(org.apache.karaf.jaas.boot.principal.UserPrincipal) ConnectionEntryReader(org.forgerock.opendj.ldif.ConnectionEntryReader) PasswordCallback(javax.security.auth.callback.PasswordCallback) NameCallback(javax.security.auth.callback.NameCallback) Callback(javax.security.auth.callback.Callback) NameCallback(javax.security.auth.callback.NameCallback) DigestMD5SASLBindRequest(org.forgerock.opendj.ldap.requests.DigestMD5SASLBindRequest) SearchScope(org.forgerock.opendj.ldap.SearchScope) LoginException(javax.security.auth.login.LoginException) BindResult(org.forgerock.opendj.ldap.responses.BindResult) SearchResultEntry(org.forgerock.opendj.ldap.responses.SearchResultEntry)

Example 13 with SearchResultReferenceIOException

use of org.forgerock.opendj.ldap.SearchResultReferenceIOException in project admin-console-beta by connexta.

the class LdapUserAttributes method performFunction.

@Override
public ListField<StringField> performFunction() {
    LdapConnectionAttempt ldapConnectionAttempt = utils.bindUserToLdapConnection(config.connectionField(), config.bindUserInfoField());
    addArgumentMessages(ldapConnectionAttempt.messages());
    if (!ldapConnectionAttempt.connection().isPresent()) {
        // TODO: tbatie - 4/3/17 - Make a toString for LDAPConfig
        LOGGER.warn("Error binding to LDAP server with config: {}", config.toString());
        return null;
    }
    Set<String> ldapEntryAttributes = null;
    try {
        ServerGuesser serverGuesser = ServerGuesser.buildGuesser(ldapType.getValue(), ldapConnectionAttempt.connection().get());
        ldapEntryAttributes = serverGuesser.getClaimAttributeOptions(config.settingsField().baseUserDn());
    } catch (SearchResultReferenceIOException | LdapException e) {
        // TODO: tbatie - 4/3/17 - Make a toString for LDAPConfig
        LOGGER.warn("Error retrieving attributes from LDAP server; this may indicate a " + "configuration issue with config: ", config.toString());
    }
    // TODO: tbatie - 4/3/17 - Make a set field instead
    ListFieldImpl entries = new ListFieldImpl<>(StringField.class);
    entries.setValue(Arrays.asList(ldapEntryAttributes.toArray()));
    return entries;
}
Also used : ListFieldImpl(org.codice.ddf.admin.common.fields.base.ListFieldImpl) SearchResultReferenceIOException(org.forgerock.opendj.ldap.SearchResultReferenceIOException) LdapException(org.forgerock.opendj.ldap.LdapException) LdapConnectionAttempt(org.codice.ddf.admin.ldap.commons.LdapConnectionAttempt) ServerGuesser(org.codice.ddf.admin.ldap.commons.ServerGuesser)

Example 14 with SearchResultReferenceIOException

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

the class SMSLdapObject method getSubEntries.

private Set<String> getSubEntries(SSOToken token, String dn, String filter, int numOfEntries, boolean sortResults, boolean ascendingOrder) throws SMSException, SSOException {
    SearchRequest request = getSearchRequest(dn, filter, SearchScope.SINGLE_LEVEL, numOfEntries, 0, sortResults, ascendingOrder, getNamingAttribute(), O_ATTR);
    int retry = 0;
    Set<String> answer = new LinkedHashSet<>();
    ConnectionEntryReader results;
    while (retry <= connNumRetry) {
        debug.message("SMSLdapObject.subEntries() retry: {}", retry);
        try (Connection conn = getConnection(token.getPrincipal())) {
            // Get the sub entries
            ConnectionEntryReader iterResults = conn.search(request);
            iterResults.hasNext();
            results = iterResults;
            // Construct the results and return
            try {
                while (results != null && results.hasNext()) {
                    try {
                        if (results.isReference()) {
                            debug.warning("Skipping reference result: {}", results.readReference());
                            continue;
                        }
                        SearchResultEntry entry = results.readEntry();
                        // Workaround for 3823, where (objectClass=*) is used
                        if (entry.getName().toString().toLowerCase().startsWith("ou=")) {
                            answer.add(entry.getName().rdn().getFirstAVA().getAttributeValue().toString());
                        }
                    } catch (SearchResultReferenceIOException e) {
                        debug.error("SMSLdapObject.subEntries: Reference should be handled already for dn {}", dn, e);
                    }
                }
            } catch (LdapException e) {
                debug.warning("SMSLdapObject.subEntries: Error in obtaining sub-entries: {}", dn, e);
                throw new SMSException(e, "sms-entry-cannot-obtain");
            }
            break;
        } catch (LdapException e) {
            ResultCode errorCode = e.getResult().getResultCode();
            if (errorCode.equals(ResultCode.NO_SUCH_OBJECT)) {
                debug.message("SMSLdapObject.subEntries(): entry not present: {}", dn);
                break;
            }
            if (!retryErrorCodes.contains(errorCode) || retry >= connNumRetry) {
                debug.warning("SMSLdapObject.subEntries: Unable to search for sub-entries: {}", dn, e);
                throw new SMSException(e, "sms-entry-cannot-search");
            }
            retry++;
            try {
                Thread.sleep(connRetryInterval);
            } catch (InterruptedException ex) {
            // ignored
            }
        }
    }
    debug.message("SMSLdapObject.subEntries: Successfully obtained sub-entries for {}", dn);
    return answer;
}
Also used : LinkedHashSet(java.util.LinkedHashSet) SearchRequest(org.forgerock.opendj.ldap.requests.SearchRequest) SMSException(com.sun.identity.sm.SMSException) Connection(org.forgerock.opendj.ldap.Connection) SearchResultReferenceIOException(org.forgerock.opendj.ldap.SearchResultReferenceIOException) ConnectionEntryReader(org.forgerock.opendj.ldif.ConnectionEntryReader) LdapException(org.forgerock.opendj.ldap.LdapException) ResultCode(org.forgerock.opendj.ldap.ResultCode) SearchResultEntry(org.forgerock.opendj.ldap.responses.SearchResultEntry)

Example 15 with SearchResultReferenceIOException

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

the class SMSLdapObject method toDNStrings.

private Set<String> toDNStrings(ConnectionEntryReader results, String dn, String errorCode) throws SMSException {
    // Construct the results and return
    Set<String> answer = new LinkedHashSet<>();
    try {
        while (results != null && results.hasNext()) {
            try {
                if (results.isReference()) {
                    debug.warning("SMSLdapObject.toDNStrings: Skipping reference result: {}", results.readReference());
                    continue;
                }
                answer.add(results.readEntry().getName().toString());
            } catch (SearchResultReferenceIOException e) {
                debug.error("SMSLdapObject.toDNStrings: Reference should be handled already for {}", dn, e);
            }
        }
    } catch (LdapException e) {
        debug.warning("SMSLdapObject.toDNStrings: Error in obtaining suborg names: {}", dn, e);
        throw new SMSException(e, errorCode);
    }
    debug.message("SMSLdapObject.searchSubOrganizationName: Successfully obtained suborganization names for {}: {}", dn, answer);
    return answer;
}
Also used : LinkedHashSet(java.util.LinkedHashSet) SMSException(com.sun.identity.sm.SMSException) SearchResultReferenceIOException(org.forgerock.opendj.ldap.SearchResultReferenceIOException) LdapException(org.forgerock.opendj.ldap.LdapException)

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