Search in sources :

Example 26 with LDAPException

use of com.unboundid.ldap.sdk.LDAPException in project zm-mailbox by Zimbra.

the class UBIDLdapContext method searchDir.

@Override
public ZSearchResultEnumeration searchDir(String baseDN, ZLdapFilter filter, ZSearchControls searchControls) throws LdapException {
    UBIDSearchControls sc = (UBIDSearchControls) searchControls;
    try {
        SearchRequest searchRequest = new SearchRequest(baseDN, sc.getSearchScope(), derefAliasPolicy, sc.getSizeLimit(), sc.getTimeLimit(), sc.getTypesOnly(), ((UBIDLdapFilter) filter).getNative());
        searchRequest.setAttributes(sc.getReturnAttrs());
        SearchResult result = UBIDLdapOperation.SEARCH.execute(this, searchRequest, filter);
        return new UBIDSearchResultEnumeration(result);
    } catch (LDAPException e) {
        throw mapToLdapException("unable to search ldap", e);
    }
}
Also used : SearchRequest(com.unboundid.ldap.sdk.SearchRequest) LDAPException(com.unboundid.ldap.sdk.LDAPException) SearchResult(com.unboundid.ldap.sdk.SearchResult)

Example 27 with LDAPException

use of com.unboundid.ldap.sdk.LDAPException in project zm-mailbox by Zimbra.

the class UBIDLdapContext method ldapAuthenticate.

/**
 * authenticate to LDAP server.
 *
 * This is method is called for:
 *   - external LDAP auth
 *   - auth to Zimbra LDAP server when the stored password is not SSHA.
 *
 * @param urls
 * @param wantStartTLS
 * @param bindDN
 * @param password
 * @param note
 * @throws ServiceException
 */
private static void ldapAuthenticate(LdapServerConfig config, String bindDN, String password, LdapUsage usage) throws ServiceException {
    /*
         * About dereferencing alias.
         *
         * The legacy JNDI implementation supports specifying deref
         * alias policy during bind, via the "java.naming.ldap.derefAliases"
         * DirContext env property.
         *
         * Doesn't look like unboundid has an obvious way to specify
         * deref alias policy during bind.
         *
         * The LDAP protocol http://tools.ietf.org/html/rfc4511 disallows
         * LDAP server to deref alias during bind anyway.
         *
         * section 4.2
         * ..., it SHALL NOT perform alias dereferencing.
         *
         * Therefore, we do *not* support dereferencing alias during bind anymore.
         *
         */
    boolean succeeded = false;
    LdapServerPool serverPool = new LdapServerPool(config);
    LDAPConnection connection = null;
    BindResult bindResult = null;
    long startTime = UBIDLdapOperation.GENERIC_OP.begin();
    try {
        if (InMemoryLdapServer.isOn()) {
            connection = InMemoryLdapServer.getConnection();
            password = InMemoryLdapServer.Password.treatPassword(password);
        } else {
            connection = serverPool.getServerSet().getConnection();
        }
        if (serverPool.getConnectionType() == LdapConnType.STARTTLS) {
            SSLContext startTLSContext = LdapSSLUtil.createSSLContext(config.sslAllowUntrustedCerts());
            ExtendedResult extendedResult = connection.processExtendedOperation(new StartTLSExtendedRequest(startTLSContext));
            // response.
            if (extendedResult.getResultCode() != ResultCode.SUCCESS) {
                throw ServiceException.FAILURE("unable to send or receive startTLS extended operation", null);
            }
        }
        bindResult = connection.bind(bindDN, password);
        if (bindResult.getResultCode() != ResultCode.SUCCESS) {
            throw ServiceException.FAILURE("unable to bind", null);
        }
        succeeded = true;
    } catch (LDAPException e) {
        throw UBIDLdapException.mapToExternalLdapException("unable to ldap authenticate", e);
    } finally {
        UBIDLdapOperation.GENERIC_OP.end(LdapOp.OPEN_CONN, usage, startTime, succeeded, bindResult, String.format("conn=[%s], url=[%s], connType=[%s], bindDN=[%s]", connection == null ? "null" : connection.getConnectionID(), serverPool.getRawUrls(), serverPool.getConnectionType().name(), bindDN));
        if (connection != null) {
            UBIDLogger.beforeOp(LdapOp.CLOSE_CONN, connection);
            connection.close();
        }
    }
}
Also used : LDAPException(com.unboundid.ldap.sdk.LDAPException) ExtendedResult(com.unboundid.ldap.sdk.ExtendedResult) BindResult(com.unboundid.ldap.sdk.BindResult) LDAPConnection(com.unboundid.ldap.sdk.LDAPConnection) SSLContext(javax.net.ssl.SSLContext) StartTLSExtendedRequest(com.unboundid.ldap.sdk.extensions.StartTLSExtendedRequest)

Example 28 with LDAPException

use of com.unboundid.ldap.sdk.LDAPException in project zm-mailbox by Zimbra.

the class UBIDLdapContext method countEntries.

@Override
public long countEntries(String baseDN, ZLdapFilter filter, ZSearchControls searchControls) throws LdapException {
    UBIDSearchControls sc = (UBIDSearchControls) searchControls;
    try {
        SearchRequest searchRequest = new SearchRequest(baseDN, sc.getSearchScope(), derefAliasPolicy, sc.getSizeLimit(), sc.getTimeLimit(), sc.getTypesOnly(), ((UBIDLdapFilter) filter).getNative());
        NoopSearchControl noopSearchCtl = new NoopSearchControl();
        searchRequest.addControl(noopSearchCtl);
        // no point to request attributes
        if (sc.getReturnAttrs() != null) {
            throw LdapException.INVALID_REQUEST("return attributes are not allowed for countEntries", null);
        }
        SearchResult result = UBIDLdapOperation.SEARCH.execute(this, searchRequest, filter);
        NoopSearchControl control = NoopSearchControl.get(result);
        if (control == null) {
            throw LdapException.LDAP_ERROR("Noop search control is not present in response", null);
        }
        return control.getCount();
    } catch (LDAPException e) {
        throw mapToLdapException("unable to search ldap", e);
    }
}
Also used : SearchRequest(com.unboundid.ldap.sdk.SearchRequest) LDAPException(com.unboundid.ldap.sdk.LDAPException) SearchResult(com.unboundid.ldap.sdk.SearchResult)

Example 29 with LDAPException

use of com.unboundid.ldap.sdk.LDAPException in project cas by apereo.

the class LdapTestUtils method createLdapEntries.

/**
 * Creates the given LDAP entries.
 *
 * @param connection Open LDAP connection used to connect to directory.
 * @param entries    Collection of LDAP entries.
 * @param connInit   the connection initializer
 */
public static void createLdapEntries(final LDAPConnection connection, final Collection<LdapEntry> entries, final BindConnectionInitializer connInit) {
    for (val entry : entries) {
        val attrs = new ArrayList<Attribute>(entry.getAttributeNames().length);
        attrs.addAll(entry.getAttributes().stream().map(a -> new Attribute(a.getName(), a.getStringValues())).collect(Collectors.toList()));
        val ad = new AddRequest(entry.getDn(), attrs);
        LOGGER.debug("Creating entry [{}] with attributes [{}]", entry, attrs);
        try {
            connection.add(ad);
        } catch (final LDAPException e) {
            LOGGER.debug(e.getMessage(), e);
            if (e.getResultCode().equals(ResultCode.ENTRY_ALREADY_EXISTS)) {
                modifyLdapEntries(connection, entries, connInit);
            } else {
                LoggingUtils.error(LOGGER, e);
            }
        } catch (final Exception e) {
            LoggingUtils.error(LOGGER, e);
        }
    }
}
Also used : lombok.val(lombok.val) AddRequest(com.unboundid.ldap.sdk.AddRequest) LDAPException(com.unboundid.ldap.sdk.LDAPException) Attribute(com.unboundid.ldap.sdk.Attribute) LdapAttribute(org.ldaptive.LdapAttribute) ArrayList(java.util.ArrayList) LDAPException(com.unboundid.ldap.sdk.LDAPException) IOException(java.io.IOException)

Example 30 with LDAPException

use of com.unboundid.ldap.sdk.LDAPException in project graylog2-server by Graylog2.

the class ADAuthServiceBackend method authenticateAndProvision.

@Override
public Optional<AuthenticationDetails> authenticateAndProvision(AuthServiceCredentials authCredentials, ProvisionerService provisionerService) {
    try (final LDAPConnection connection = ldapConnector.connect(config.getLDAPConnectorConfig())) {
        if (connection == null) {
            return Optional.empty();
        }
        final Optional<LDAPUser> optionalUser = findUser(connection, authCredentials);
        if (!optionalUser.isPresent()) {
            LOG.debug("User <{}> not found in Active Directory", authCredentials.username());
            return Optional.empty();
        }
        final LDAPUser userEntry = optionalUser.get();
        if (!userEntry.accountIsEnabled()) {
            LOG.warn("Account disabled within Active Directory for user <{}> (DN: {})", authCredentials.username(), userEntry.dn());
            return Optional.empty();
        }
        if (!authCredentials.isAuthenticated()) {
            if (!isAuthenticated(connection, userEntry, authCredentials)) {
                LOG.debug("Invalid credentials for user <{}> (DN: {})", authCredentials.username(), userEntry.dn());
                return Optional.empty();
            }
        }
        final UserDetails userDetails = provisionerService.provision(provisionerService.newDetails(this).authServiceType(backendType()).authServiceId(backendId()).base64AuthServiceUid(userEntry.base64UniqueId()).username(userEntry.username()).accountIsEnabled(userEntry.accountIsEnabled()).fullName(userEntry.fullName()).email(userEntry.email()).defaultRoles(backend.defaultRoles()).build());
        return Optional.of(AuthenticationDetails.builder().userDetails(userDetails).build());
    } catch (GeneralSecurityException e) {
        LOG.error("Error setting up TLS connection", e);
        throw new AuthenticationServiceUnavailableException("Error setting up TLS connection", e);
    } catch (LDAPException e) {
        LOG.error("ActiveDirectory error", e);
        throw new AuthenticationServiceUnavailableException("ActiveDirectory error", e);
    }
}
Also used : UserDetails(org.graylog.security.authservice.UserDetails) LDAPException(com.unboundid.ldap.sdk.LDAPException) GeneralSecurityException(java.security.GeneralSecurityException) LDAPUser(org.graylog.security.authservice.ldap.LDAPUser) LDAPConnection(com.unboundid.ldap.sdk.LDAPConnection) AuthenticationServiceUnavailableException(org.graylog2.shared.security.AuthenticationServiceUnavailableException)

Aggregations

LDAPException (com.unboundid.ldap.sdk.LDAPException)59 SearchResult (com.unboundid.ldap.sdk.SearchResult)15 LDAPConnection (com.unboundid.ldap.sdk.LDAPConnection)13 SearchRequest (com.unboundid.ldap.sdk.SearchRequest)11 SearchResultEntry (com.unboundid.ldap.sdk.SearchResultEntry)11 IOException (java.io.IOException)11 ResultCode (com.unboundid.ldap.sdk.ResultCode)9 LDIFReader (com.unboundid.ldif.LDIFReader)8 GeneralSecurityException (java.security.GeneralSecurityException)8 DN (com.unboundid.ldap.sdk.DN)6 ASN1OctetString (com.unboundid.asn1.ASN1OctetString)5 Entry (com.unboundid.ldap.sdk.Entry)5 Filter (com.unboundid.ldap.sdk.Filter)5 LDAPConnectionPool (com.unboundid.ldap.sdk.LDAPConnectionPool)5 ArrayList (java.util.ArrayList)5 LdifDataUtility (org.gluu.persist.ldap.impl.LdifDataUtility)5 InMemoryDirectoryServer (com.unboundid.ldap.listener.InMemoryDirectoryServer)4 InMemoryDirectoryServerConfig (com.unboundid.ldap.listener.InMemoryDirectoryServerConfig)4 BindResult (com.unboundid.ldap.sdk.BindResult)4 SimpleBindRequest (com.unboundid.ldap.sdk.SimpleBindRequest)4