Search in sources :

Example 26 with InitialLdapContext

use of javax.naming.ldap.InitialLdapContext in project OpenGrok by OpenGrok.

the class LdapServer method connect.

/**
 * Connects to the LDAP server.
 *
 * @return the new connection or null
 */
private synchronized LdapContext connect() {
    LOGGER.log(Level.INFO, "Connecting to LDAP server {0} ", this);
    if (errorTimestamp > 0 && errorTimestamp + interval > System.currentTimeMillis()) {
        LOGGER.log(Level.WARNING, "LDAP server {0} is down", this.url);
        close();
        return null;
    }
    if (ctx == null) {
        env.put(Context.PROVIDER_URL, this.url);
        if (this.username != null) {
            env.put(Context.SECURITY_PRINCIPAL, this.username);
        }
        if (this.password != null) {
            env.put(Context.SECURITY_CREDENTIALS, this.password);
        }
        if (this.connectTimeout > 0) {
            env.put(LDAP_CONNECT_TIMEOUT_PARAMETER, Integer.toString(this.connectTimeout));
        }
        if (this.readTimeout > 0) {
            env.put(LDAP_READ_TIMEOUT_PARAMETER, Integer.toString(this.readTimeout));
        }
        try {
            ctx = new InitialLdapContext(env, null);
            ctx.setRequestControls(null);
            LOGGER.log(Level.INFO, "Connected to LDAP server {0}", this);
            errorTimestamp = 0;
        } catch (NamingException ex) {
            LOGGER.log(Level.WARNING, "LDAP server {0} is not responding", env.get(Context.PROVIDER_URL));
            errorTimestamp = System.currentTimeMillis();
            close();
            return ctx = null;
        }
    }
    return ctx;
}
Also used : InitialLdapContext(javax.naming.ldap.InitialLdapContext) NamingException(javax.naming.NamingException)

Example 27 with InitialLdapContext

use of javax.naming.ldap.InitialLdapContext in project ranger by apache.

the class LdapUserGroupBuilder method createLdapContext.

private void createLdapContext() throws Throwable {
    Properties env = new Properties();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, ldapUrl);
    if (ldapUrl.startsWith("ldaps") && (config.getSSLTrustStorePath() != null && !config.getSSLTrustStorePath().trim().isEmpty())) {
        env.put("java.naming.ldap.factory.socket", "org.apache.ranger.ldapusersync.process.CustomSSLSocketFactory");
    }
    if (StringUtils.isNotEmpty(userCloudIdAttribute)) {
        if (config.getUserCloudIdAttributeDataType().equals(DATA_TYPE_BYTEARRAY)) {
            env.put("java.naming.ldap.attributes.binary", userCloudIdAttribute);
        }
    }
    if (StringUtils.isNotEmpty(groupCloudIdAttribute)) {
        if (config.getGroupCloudIdAttributeDataType().equals(DATA_TYPE_BYTEARRAY)) {
            env.put("java.naming.ldap.attributes.binary", groupCloudIdAttribute);
        }
    }
    for (String otherUserAttribute : otherUserAttributes) {
        String attrType = config.getOtherUserAttributeDataType(otherUserAttribute);
        if (attrType.equals(DATA_TYPE_BYTEARRAY)) {
            env.put("java.naming.ldap.attributes.binary", otherUserAttribute);
        }
    }
    for (String otherGroupAttribute : otherGroupAttributes) {
        String attrType = config.getOtherGroupAttributeDataType(otherGroupAttribute);
        if (attrType.equals(DATA_TYPE_BYTEARRAY)) {
            env.put("java.naming.ldap.attributes.binary", otherGroupAttribute);
        }
    }
    ldapContext = new InitialLdapContext(env, null);
    if (!ldapUrl.startsWith("ldaps")) {
        if (config.isStartTlsEnabled()) {
            tls = (StartTlsResponse) ldapContext.extendedOperation(new StartTlsRequest());
            if (config.getSSLTrustStorePath() != null && !config.getSSLTrustStorePath().trim().isEmpty()) {
                tls.negotiate(CustomSSLSocketFactory.getDefault());
            } else {
                tls.negotiate();
            }
            LOG.info("Starting TLS session...");
        }
    }
    ldapContext.addToEnvironment(Context.SECURITY_PRINCIPAL, ldapBindDn);
    ldapContext.addToEnvironment(Context.SECURITY_CREDENTIALS, ldapBindPassword);
    ldapContext.addToEnvironment(Context.SECURITY_AUTHENTICATION, ldapAuthenticationMechanism);
    ldapContext.addToEnvironment(Context.REFERRAL, ldapReferral);
}
Also used : InitialLdapContext(javax.naming.ldap.InitialLdapContext) Properties(java.util.Properties) StartTlsRequest(javax.naming.ldap.StartTlsRequest)

Example 28 with InitialLdapContext

use of javax.naming.ldap.InitialLdapContext in project alfresco-repository by Alfresco.

the class LDAPInitialDirContextFactoryImpl method buildInitialDirContext.

private InitialDirContext buildInitialDirContext(Hashtable<String, String> env, int pageSize, AuthenticationDiagnostic diagnostic) throws AuthenticationException {
    String securityPrincipal = env.get(Context.SECURITY_PRINCIPAL);
    String providerURL = env.get(Context.PROVIDER_URL);
    if (isSSLSocketFactoryRequired()) {
        KeyStore trustStore = initTrustStore();
        AlfrescoSSLSocketFactory.initTrustedSSLSocketFactory(trustStore);
        env.put("java.naming.ldap.factory.socket", AlfrescoSSLSocketFactory.class.getName());
    }
    if (diagnostic == null) {
        diagnostic = new AuthenticationDiagnostic();
    }
    try {
        // If a page size has been requested, use LDAP v3 paging
        if (pageSize > 0) {
            InitialLdapContext ctx = new InitialLdapContext(env, null);
            ctx.setRequestControls(new Control[] { new PagedResultsControl(pageSize, Control.CRITICAL) });
            return ctx;
        } else {
            InitialDirContext ret = new InitialDirContext(env);
            Object[] args = { providerURL, securityPrincipal };
            diagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_CONNECTED, true, args);
            return ret;
        }
    } catch (javax.naming.AuthenticationException ax) {
        Object[] args1 = { securityPrincipal };
        Object[] args = { providerURL, securityPrincipal };
        diagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_CONNECTED, true, args);
        diagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_AUTHENTICATION, false, args1);
        // wrong user/password - if we get this far the connection is O.K
        Object[] args2 = { securityPrincipal, ax.getLocalizedMessage() };
        throw new AuthenticationException("authentication.err.authentication", diagnostic, args2, ax);
    } catch (CommunicationException ce) {
        Object[] args1 = { providerURL };
        diagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_CONNECTING, false, args1);
        StringBuffer message = new StringBuffer();
        message.append(ce.getClass().getName() + ", " + ce.getMessage());
        Throwable cause = ce.getCause();
        while (cause != null) {
            message.append(", ");
            message.append(cause.getClass().getName() + ", " + cause.getMessage());
            cause = cause.getCause();
        }
        // failed to connect
        Object[] args = { providerURL, message.toString() };
        throw new AuthenticationException("authentication.err.communication", diagnostic, args, cause);
    } catch (NamingException nx) {
        Object[] args = { providerURL };
        diagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_CONNECTING, false, args);
        StringBuffer message = new StringBuffer();
        message.append(nx.getClass().getName() + ", " + nx.getMessage());
        Throwable cause = nx.getCause();
        while (cause != null) {
            message.append(", ");
            message.append(cause.getClass().getName() + ", " + cause.getMessage());
            cause = cause.getCause();
        }
        // failed to connect
        Object[] args1 = { providerURL, message.toString() };
        throw new AuthenticationException("authentication.err.connection", diagnostic, args1, nx);
    } catch (IOException e) {
        Object[] args = { providerURL, securityPrincipal };
        diagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_CONNECTED, true, args);
        throw new AuthenticationException("Unable to encode LDAP v3 request controls", e);
    }
}
Also used : CommunicationException(javax.naming.CommunicationException) AuthenticationException(org.alfresco.repo.security.authentication.AuthenticationException) InitialDirContext(javax.naming.directory.InitialDirContext) IOException(java.io.IOException) KeyStore(java.security.KeyStore) AlfrescoSSLSocketFactory(org.alfresco.repo.security.authentication.AlfrescoSSLSocketFactory) InitialLdapContext(javax.naming.ldap.InitialLdapContext) AuthenticationDiagnostic(org.alfresco.repo.security.authentication.AuthenticationDiagnostic) NamingException(javax.naming.NamingException) PagedResultsControl(javax.naming.ldap.PagedResultsControl)

Example 29 with InitialLdapContext

use of javax.naming.ldap.InitialLdapContext in project iaf by ibissource.

the class LdapFindMemberPipe method findMember.

private boolean findMember(String host, int port, String dnSearchIn, boolean useSsl, String dnFind, boolean recursiveSearch) throws NamingException {
    Hashtable<String, Object> env = new Hashtable<String, Object>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    String provUrl = retrieveUrl(host, port, dnSearchIn, useSsl);
    env.put(Context.PROVIDER_URL, provUrl);
    if (StringUtils.isNotEmpty(cf.getUsername())) {
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        env.put(Context.SECURITY_PRINCIPAL, cf.getUsername());
        env.put(Context.SECURITY_CREDENTIALS, cf.getPassword());
    } else {
        env.put(Context.SECURITY_AUTHENTICATION, "none");
    }
    DirContext ctx = null;
    try {
        try {
            ctx = new InitialDirContext(env);
        } catch (CommunicationException e) {
            log.info("Cannot create constructor for DirContext [" + e.getMessage() + "], will try again with dummy SocketFactory", e);
            env.put("java.naming.ldap.factory.socket", DummySSLSocketFactory.class.getName());
            ctx = new InitialLdapContext(env, null);
        }
        Attribute attrs = ctx.getAttributes("").get("member");
        if (attrs != null) {
            boolean found = false;
            for (int i = 0; i < attrs.size() && !found; i++) {
                String dnFound = (String) attrs.get(i);
                if (dnFound.equalsIgnoreCase(dnFind)) {
                    found = true;
                } else {
                    if (recursiveSearch) {
                        found = findMember(host, port, dnFound, useSsl, dnFind, recursiveSearch);
                    }
                }
            }
            return found;
        }
    } finally {
        if (ctx != null) {
            try {
                ctx.close();
            } catch (NamingException e) {
                log.warn("Exception closing DirContext", e);
            }
        }
    }
    return false;
}
Also used : CommunicationException(javax.naming.CommunicationException) Attribute(javax.naming.directory.Attribute) Hashtable(java.util.Hashtable) InitialLdapContext(javax.naming.ldap.InitialLdapContext) NamingException(javax.naming.NamingException) DirContext(javax.naming.directory.DirContext) InitialDirContext(javax.naming.directory.InitialDirContext) InitialDirContext(javax.naming.directory.InitialDirContext)

Example 30 with InitialLdapContext

use of javax.naming.ldap.InitialLdapContext in project hadoop by apache.

the class LdapAuthenticationHandler method authenticateWithTlsExtension.

private void authenticateWithTlsExtension(String userDN, String password) throws AuthenticationException {
    LdapContext ctx = null;
    Hashtable<String, Object> env = new Hashtable<String, Object>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, providerUrl);
    try {
        // Create initial context
        ctx = new InitialLdapContext(env, null);
        // Establish TLS session
        StartTlsResponse tls = (StartTlsResponse) ctx.extendedOperation(new StartTlsRequest());
        if (disableHostNameVerification) {
            tls.setHostnameVerifier(new HostnameVerifier() {

                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            });
        }
        tls.negotiate();
        // Initialize security credentials & perform read operation for
        // verification.
        ctx.addToEnvironment(Context.SECURITY_AUTHENTICATION, SECURITY_AUTHENTICATION);
        ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, userDN);
        ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, password);
        ctx.lookup(userDN);
        logger.debug("Authentication successful for {}", userDN);
    } catch (NamingException | IOException ex) {
        throw new AuthenticationException("Error validating LDAP user", ex);
    } finally {
        if (ctx != null) {
            try {
                ctx.close();
            } catch (NamingException e) {
            /* Ignore. */
            }
        }
    }
}
Also used : AuthenticationException(org.apache.hadoop.security.authentication.client.AuthenticationException) Hashtable(java.util.Hashtable) SSLSession(javax.net.ssl.SSLSession) IOException(java.io.IOException) HostnameVerifier(javax.net.ssl.HostnameVerifier) StartTlsResponse(javax.naming.ldap.StartTlsResponse) InitialLdapContext(javax.naming.ldap.InitialLdapContext) NamingException(javax.naming.NamingException) StartTlsRequest(javax.naming.ldap.StartTlsRequest) InitialLdapContext(javax.naming.ldap.InitialLdapContext) LdapContext(javax.naming.ldap.LdapContext)

Aggregations

InitialLdapContext (javax.naming.ldap.InitialLdapContext)54 NamingException (javax.naming.NamingException)30 Hashtable (java.util.Hashtable)17 LdapContext (javax.naming.ldap.LdapContext)17 Attributes (javax.naming.directory.Attributes)16 Properties (java.util.Properties)14 SearchResult (javax.naming.directory.SearchResult)14 IOException (java.io.IOException)11 AuthenticationException (javax.naming.AuthenticationException)10 NamingEnumeration (javax.naming.NamingEnumeration)10 StartTlsRequest (javax.naming.ldap.StartTlsRequest)10 BasicAttributes (javax.naming.directory.BasicAttributes)9 Attribute (javax.naming.directory.Attribute)8 SearchControls (javax.naming.directory.SearchControls)8 LdapConfigProperties (org.bedework.calfacade.configs.LdapConfigProperties)7 CalFacadeException (org.bedework.calfacade.exc.CalFacadeException)7 StartTlsResponse (javax.naming.ldap.StartTlsResponse)6 CommunicationException (javax.naming.CommunicationException)5 DirContext (javax.naming.directory.DirContext)5 BwGroup (org.bedework.calfacade.BwGroup)5