Example usage for javax.naming.ldap StartTlsResponse setHostnameVerifier

List of usage examples for javax.naming.ldap StartTlsResponse setHostnameVerifier

Introduction

In this page you can find the example usage for javax.naming.ldap StartTlsResponse setHostnameVerifier.

Prototype

public abstract void setHostnameVerifier(HostnameVerifier verifier);

Source Link

Document

Sets the hostname verifier used by negotiate() after the TLS handshake has completed and the default hostname verification has failed.

Usage

From source file:org.apache.directory.studio.connection.core.io.jndi.JNDIConnectionWrapper.java

private void doConnect(final StudioProgressMonitor monitor) throws NamingException {
    context = null;//from   w  w  w  . j a  v a2  s. c  om
    isConnected = true;

    // setup connection parameters
    String host = connection.getConnectionParameter().getHost();
    int port = connection.getConnectionParameter().getPort();
    long timeout = connection.getConnectionParameter().getTimeout();

    useLdaps = connection.getConnectionParameter()
            .getEncryptionMethod() == ConnectionParameter.EncryptionMethod.LDAPS;
    useStartTLS = connection.getConnectionParameter()
            .getEncryptionMethod() == ConnectionParameter.EncryptionMethod.START_TLS;

    environment = new Hashtable<>();
    Preferences preferences = ConnectionCorePlugin.getDefault().getPluginPreferences();
    final boolean validateCertificates = preferences
            .getBoolean(ConnectionCoreConstants.PREFERENCE_VALIDATE_CERTIFICATES);
    String ldapCtxFactory = preferences.getString(ConnectionCoreConstants.PREFERENCE_LDAP_CONTEXT_FACTORY);
    environment.put(Context.INITIAL_CONTEXT_FACTORY, ldapCtxFactory);
    environment.put(JAVA_NAMING_LDAP_VERSION, "3"); //$NON-NLS-1$

    // timeouts
    /*
     *  Don't use a timeout when using ldaps: JNDI throws a SocketException  when setting a timeout on SSL connections.
     *  See https://bugs.openjdk.java.net/browse/JDK-8173451
     */
    if (!useLdaps) {
        if (timeout < 0) {
            timeout = 0;
        }
        environment.put(COM_SUN_JNDI_LDAP_CONNECT_TIMEOUT, Long.toString(timeout)); //$NON-NLS-1$
    }

    environment.put(COM_SUN_JNDI_DNS_TIMEOUT_INITIAL, "2000"); //$NON-NLS-1$
    environment.put(COM_SUN_JNDI_DNS_TIMEOUT_RETRIES, "3"); //$NON-NLS-1$

    // ldaps://
    if (useLdaps) {
        environment.put(Context.PROVIDER_URL, LdapUrl.LDAPS_SCHEME + host + ':' + port);
        environment.put(Context.SECURITY_PROTOCOL, "ssl"); //$NON-NLS-1$
        // host name verification is done in StudioTrustManager
        environment.put(JAVA_NAMING_LDAP_FACTORY_SOCKET,
                validateCertificates ? StudioSSLSocketFactory.class.getName()
                        : DummySSLSocketFactory.class.getName());
    } else {
        environment.put(Context.PROVIDER_URL, LdapUrl.LDAP_SCHEME + host + ':' + port);
    }

    if (binaryAttributes != null) {
        setBinaryAttributes(binaryAttributes);
    }

    InnerRunnable runnable = new InnerRunnable() {
        public void run() {
            try {
                context = new InitialLdapContext(environment, null);

                if (useStartTLS) {
                    try {
                        StartTlsResponse tls = (StartTlsResponse) context
                                .extendedOperation(new StartTlsRequest());
                        // deactivate host name verification at this level,
                        // host name verification is done in StudioTrustManager
                        tls.setHostnameVerifier((hostname, session) -> true);

                        if (validateCertificates) {
                            tls.negotiate(StudioSSLSocketFactory.getDefault());
                        } else {
                            tls.negotiate(DummySSLSocketFactory.getDefault());
                        }
                    } catch (Exception e) {
                        namingException = new NamingException(e.getMessage() != null ? e.getMessage()
                                : "Error while establishing TLS session"); //$NON-NLS-1$
                        namingException.setRootCause(e);
                        context.close();
                    }
                }
            } catch (NamingException ne) {
                namingException = ne;
            }
        }
    };

    runAndMonitor(runnable, monitor);

    if (runnable.getException() != null) {
        throw runnable.getException();
    } else if (context != null) {
        // all OK
    } else {
        throw new NamingException("???"); //$NON-NLS-1$
    }
}

From source file:org.apache.hadoop.security.authentication.server.LdapAuthenticationHandler.java

private void authenticateWithTlsExtension(String userDN, String password) throws AuthenticationException {
    LdapContext ctx = null;/*from  w  ww. java  2s.  co  m*/
    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. */
            }
        }
    }
}