Example usage for io.netty.handler.ssl ClientAuth REQUIRE

List of usage examples for io.netty.handler.ssl ClientAuth REQUIRE

Introduction

In this page you can find the example usage for io.netty.handler.ssl ClientAuth REQUIRE.

Prototype

ClientAuth REQUIRE

To view the source code for io.netty.handler.ssl ClientAuth REQUIRE.

Click Source Link

Document

Indicates that the javax.net.ssl.SSLEngine will *require* client authentication.

Usage

From source file:com.codahale.grpcproxy.util.TlsContext.java

License:Apache License

public SslContext toServerContext() throws SSLException {
    return GrpcSslContexts.configure(SslContextBuilder.forServer(cert, key), SslProvider.OPENSSL)
            .trustManager(trustedCerts).clientAuth(ClientAuth.REQUIRE).build();
}

From source file:com.floragunn.searchguard.ssl.DefaultSearchGuardKeyStore.java

License:Apache License

private void initSSLConfig() {

    final Environment env = new Environment(settings);
    log.info("Config directory is {}/, from there the key- and truststore files are resolved relatively",
            env.configFile().toAbsolutePath());

    if (transportSSLEnabled) {

        final String rawKeyStoreFilePath = settings
                .get(SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_KEYSTORE_FILEPATH, null);
        final String rawPemCertFilePath = settings
                .get(SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_PEMCERT_FILEPATH, null);

        if (rawKeyStoreFilePath != null) {

            final String keystoreFilePath = env.configFile()
                    .resolve(settings.get(SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_KEYSTORE_FILEPATH, ""))
                    .toAbsolutePath().toString();
            final String keystoreType = settings.get(SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_KEYSTORE_TYPE,
                    DEFAULT_STORE_TYPE);
            final String keystorePassword = settings.get(
                    SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_KEYSTORE_PASSWORD, DEFAULT_STORE_PASSWORD);
            final String keystoreAlias = settings
                    .get(SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_KEYSTORE_ALIAS, null);

            final String truststoreFilePath = env.configFile()
                    .resolve(settings.get(SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_TRUSTSTORE_FILEPATH, ""))
                    .toAbsolutePath().toString();

            checkStorePath(keystoreFilePath);

            if (settings.get(SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_TRUSTSTORE_FILEPATH, null) == null) {
                throw new ElasticsearchException(
                        SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_TRUSTSTORE_FILEPATH
                                + " must be set if transport ssl is reqested.");
            }/*from w w w .  ja va 2 s  .c om*/

            checkStorePath(truststoreFilePath);

            final String truststoreType = settings
                    .get(SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_TRUSTSTORE_TYPE, DEFAULT_STORE_TYPE);
            final String truststorePassword = settings.get(
                    SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_TRUSTSTORE_PASSWORD, DEFAULT_STORE_PASSWORD);
            final String truststoreAlias = settings
                    .get(SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_TRUSTSTORE_ALIAS, null);

            try {

                final KeyStore ks = KeyStore.getInstance(keystoreType);
                ks.load(new FileInputStream(new File(keystoreFilePath)),
                        (keystorePassword == null || keystorePassword.length() == 0) ? null
                                : keystorePassword.toCharArray());

                final X509Certificate[] transportKeystoreCert = SSLCertificateHelper.exportServerCertChain(ks,
                        keystoreAlias);
                final PrivateKey transportKeystoreKey = SSLCertificateHelper.exportDecryptedKey(ks,
                        keystoreAlias, (keystorePassword == null || keystorePassword.length() == 0) ? null
                                : keystorePassword.toCharArray());

                if (transportKeystoreKey == null) {
                    throw new ElasticsearchException(
                            "No key found in " + keystoreFilePath + " with alias " + keystoreAlias);
                }

                if (transportKeystoreCert != null && transportKeystoreCert.length > 0) {

                    //TODO create sensitive log property
                    /*for (int i = 0; i < transportKeystoreCert.length; i++) {
                    X509Certificate x509Certificate = transportKeystoreCert[i];
                            
                    if(x509Certificate != null) {
                        log.info("Transport keystore subject DN no. {} {}",i,x509Certificate.getSubjectX500Principal());
                    }
                    }*/
                } else {
                    throw new ElasticsearchException(
                            "No certificates found in " + keystoreFilePath + " with alias " + keystoreAlias);
                }

                final KeyStore ts = KeyStore.getInstance(truststoreType);
                ts.load(new FileInputStream(new File(truststoreFilePath)),
                        (truststorePassword == null || truststorePassword.length() == 0) ? null
                                : truststorePassword.toCharArray());

                final X509Certificate[] trustedTransportCertificates = SSLCertificateHelper
                        .exportRootCertificates(ts, truststoreAlias);

                if (trustedTransportCertificates == null) {
                    throw new ElasticsearchException("No truststore configured for server");
                }

                transportServerSslContext = buildSSLServerContext(transportKeystoreKey, transportKeystoreCert,
                        trustedTransportCertificates,
                        getEnabledSSLCiphers(this.sslTransportServerProvider, false),
                        this.sslTransportServerProvider, ClientAuth.REQUIRE);
                transportClientSslContext = buildSSLClientContext(transportKeystoreKey, transportKeystoreCert,
                        trustedTransportCertificates, getEnabledSSLCiphers(sslTransportClientProvider, false),
                        sslTransportClientProvider);

            } catch (final Exception e) {
                throw new ElasticsearchSecurityException(
                        "Error while initializing transport SSL layer: " + e.toString(), e);
            }

        } else if (rawPemCertFilePath != null) {

            final String pemCertFilePath = env.configFile().resolve(rawPemCertFilePath).toAbsolutePath()
                    .toString();
            final String pemKey = env.configFile()
                    .resolve(settings.get(SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_PEMKEY_FILEPATH, ""))
                    .toAbsolutePath().toString();
            final String trustedCas = env
                    .configFile().resolve(settings
                            .get(SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_PEMTRUSTEDCAS_FILEPATH, ""))
                    .toAbsolutePath().toString();

            checkStorePath(pemCertFilePath);
            checkStorePath(pemKey);
            checkStorePath(trustedCas);

            try {

                transportServerSslContext = buildSSLServerContext(new File(pemKey), new File(pemCertFilePath),
                        new File(trustedCas),
                        settings.get(SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_PEMKEY_PASSWORD),
                        getEnabledSSLCiphers(this.sslTransportServerProvider, false),
                        this.sslTransportServerProvider, ClientAuth.REQUIRE);
                transportClientSslContext = buildSSLClientContext(new File(pemKey), new File(pemCertFilePath),
                        new File(trustedCas),
                        settings.get(SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_PEMKEY_PASSWORD),
                        getEnabledSSLCiphers(sslTransportClientProvider, false), sslTransportClientProvider);

            } catch (final Exception e) {
                throw new ElasticsearchSecurityException(
                        "Error while initializing transport SSL layer from PEM: " + e.toString(), e);
            }

        } else {
            throw new ElasticsearchException(SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_KEYSTORE_FILEPATH
                    + " or " + SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_PEMKEY_FILEPATH
                    + " must be set if transport ssl is reqested.");
        }
    }

    final boolean client = !"node".equals(this.settings.get(SearchGuardSSLPlugin.CLIENT_TYPE));

    if (!client && httpSSLEnabled) {

        final String rawKeystoreFilePath = settings
                .get(SSLConfigConstants.SEARCHGUARD_SSL_HTTP_KEYSTORE_FILEPATH, null);
        final String rawPemCertFilePath = settings.get(SSLConfigConstants.SEARCHGUARD_SSL_HTTP_PEMCERT_FILEPATH,
                null);
        final ClientAuth httpClientAuthMode = ClientAuth.valueOf(settings
                .get(SSLConfigConstants.SEARCHGUARD_SSL_HTTP_CLIENTAUTH_MODE, ClientAuth.OPTIONAL.toString()));

        if (rawKeystoreFilePath != null) {

            final String keystoreFilePath = env.configFile()
                    .resolve(settings.get(SSLConfigConstants.SEARCHGUARD_SSL_HTTP_KEYSTORE_FILEPATH, ""))
                    .toAbsolutePath().toString();
            final String keystoreType = settings.get(SSLConfigConstants.SEARCHGUARD_SSL_HTTP_KEYSTORE_TYPE,
                    DEFAULT_STORE_TYPE);
            final String keystorePassword = settings
                    .get(SSLConfigConstants.SEARCHGUARD_SSL_HTTP_KEYSTORE_PASSWORD, DEFAULT_STORE_PASSWORD);
            final String keystoreAlias = settings.get(SSLConfigConstants.SEARCHGUARD_SSL_HTTP_KEYSTORE_ALIAS,
                    null);

            //TODO remove with next version
            //String _enforceHTTPClientAuth = settings.get("searchguard.ssl.http.enforce_clientauth");

            //if(_enforceHTTPClientAuth != null) {
            //    log.error("{} is deprecated and replaced by {}", "searchguard.ssl.http.enforce_clientauth", SSLConfigConstants.SEARCHGUARD_SSL_HTTP_CLIENTAUTH_MODE);
            //    throw new RuntimeException("searchguard.ssl.http.enforce_clientauth is deprecated");
            //}

            log.info("HTTPS client auth mode {}", httpClientAuthMode);

            final String truststoreFilePath = env.configFile()
                    .resolve(settings.get(SSLConfigConstants.SEARCHGUARD_SSL_HTTP_TRUSTSTORE_FILEPATH, ""))
                    .toAbsolutePath().toString();

            if (settings.get(SSLConfigConstants.SEARCHGUARD_SSL_HTTP_KEYSTORE_FILEPATH, null) == null) {
                throw new ElasticsearchException(SSLConfigConstants.SEARCHGUARD_SSL_HTTP_KEYSTORE_FILEPATH
                        + " must be set if https is reqested.");
            }

            checkStorePath(keystoreFilePath);

            if (httpClientAuthMode == ClientAuth.REQUIRE) {

                if (settings.get(SSLConfigConstants.SEARCHGUARD_SSL_HTTP_TRUSTSTORE_FILEPATH, null) == null) {
                    throw new ElasticsearchException(SSLConfigConstants.SEARCHGUARD_SSL_HTTP_TRUSTSTORE_FILEPATH
                            + " must be set if http ssl and client auth is reqested.");
                }

            }

            try {

                final KeyStore ks = KeyStore.getInstance(keystoreType);
                ks.load(new FileInputStream(new File(keystoreFilePath)),
                        (keystorePassword == null || keystorePassword.length() == 0) ? null
                                : keystorePassword.toCharArray());

                final X509Certificate[] httpKeystoreCert = SSLCertificateHelper.exportServerCertChain(ks,
                        keystoreAlias);
                final PrivateKey httpKeystoreKey = SSLCertificateHelper.exportDecryptedKey(ks, keystoreAlias,
                        (keystorePassword == null || keystorePassword.length() == 0) ? null
                                : keystorePassword.toCharArray());

                if (httpKeystoreKey == null) {
                    throw new ElasticsearchException(
                            "No key found in " + keystoreFilePath + " with alias " + keystoreAlias);
                }

                if (httpKeystoreCert != null && httpKeystoreCert.length > 0) {

                    //TODO create sensitive log property
                    /*for (int i = 0; i < httpKeystoreCert.length; i++) {
                    X509Certificate x509Certificate = httpKeystoreCert[i];
                            
                    if(x509Certificate != null) {
                        log.info("HTTP keystore subject DN no. {} {}",i,x509Certificate.getSubjectX500Principal());
                    }
                    }*/
                } else {
                    throw new ElasticsearchException(
                            "No certificates found in " + keystoreFilePath + " with alias " + keystoreAlias);
                }

                X509Certificate[] trustedHTTPCertificates = null;

                if (settings.get(SSLConfigConstants.SEARCHGUARD_SSL_HTTP_TRUSTSTORE_FILEPATH, null) != null) {

                    checkStorePath(truststoreFilePath);

                    final String truststoreType = settings
                            .get(SSLConfigConstants.SEARCHGUARD_SSL_HTTP_TRUSTSTORE_TYPE, DEFAULT_STORE_TYPE);
                    final String truststorePassword = settings.get(
                            SSLConfigConstants.SEARCHGUARD_SSL_HTTP_TRUSTSTORE_PASSWORD,
                            DEFAULT_STORE_PASSWORD);
                    final String truststoreAlias = settings
                            .get(SSLConfigConstants.SEARCHGUARD_SSL_HTTP_TRUSTSTORE_ALIAS, null);

                    final KeyStore ts = KeyStore.getInstance(truststoreType);
                    ts.load(new FileInputStream(new File(truststoreFilePath)),
                            (truststorePassword == null || truststorePassword.length() == 0) ? null
                                    : truststorePassword.toCharArray());

                    trustedHTTPCertificates = SSLCertificateHelper.exportRootCertificates(ts, truststoreAlias);
                }

                httpSslContext = buildSSLServerContext(httpKeystoreKey, httpKeystoreCert,
                        trustedHTTPCertificates, getEnabledSSLCiphers(this.sslHTTPProvider, true),
                        sslHTTPProvider, httpClientAuthMode);

            } catch (final Exception e) {
                throw new ElasticsearchSecurityException(
                        "Error while initializing HTTP SSL layer: " + e.toString(), e);
            }

        } else if (rawPemCertFilePath != null) {

            final String trustedCas = env.configFile()
                    .resolve(settings.get(SSLConfigConstants.SEARCHGUARD_SSL_HTTP_PEMTRUSTEDCAS_FILEPATH, ""))
                    .toAbsolutePath().toString();

            if (httpClientAuthMode == ClientAuth.REQUIRE) {

                if (trustedCas == null || trustedCas.equals(env.configFile().toAbsolutePath().toString())) {
                    throw new ElasticsearchException(
                            SSLConfigConstants.SEARCHGUARD_SSL_HTTP_PEMTRUSTEDCAS_FILEPATH
                                    + " must be set if http ssl and client auth is reqested.");
                }

                checkStorePath(trustedCas);

            }

            final String pemCertFilePath = env.configFile().resolve(rawPemCertFilePath).toAbsolutePath()
                    .toString();
            final String pemKey = env.configFile()
                    .resolve(settings.get(SSLConfigConstants.SEARCHGUARD_SSL_HTTP_PEMKEY_FILEPATH, ""))
                    .toAbsolutePath().toString();

            checkStorePath(pemCertFilePath);
            checkStorePath(pemKey);

            try {
                httpSslContext = buildSSLServerContext(new File(pemKey), new File(pemCertFilePath),
                        (trustedCas == null || trustedCas.equals(env.configFile().toAbsolutePath().toString()))
                                ? null
                                : new File(trustedCas),
                        settings.get(SSLConfigConstants.SEARCHGUARD_SSL_HTTP_PEMKEY_PASSWORD),
                        getEnabledSSLCiphers(this.sslHTTPProvider, true), sslHTTPProvider, httpClientAuthMode);
            } catch (final Exception e) {
                throw new ElasticsearchSecurityException(
                        "Error while initializing http SSL layer from PEM: " + e.toString(), e);
            }

        } else {
            throw new ElasticsearchException(SSLConfigConstants.SEARCHGUARD_SSL_HTTP_KEYSTORE_FILEPATH + " or "
                    + SSLConfigConstants.SEARCHGUARD_SSL_HTTP_PEMKEY_FILEPATH
                    + " must be set if http ssl is reqested.");
        }

    }
}

From source file:com.floragunn.searchguard.ssl.SearchGuardKeyStore.java

License:Apache License

private void initSSLConfig() {

    final Environment env = new Environment(settings);
    log.info("Config directory is {}/, from there the key- and truststore files are resolved relatively",
            env.configFile().toAbsolutePath());

    if (transportSSLEnabled) {

        final String keystoreFilePath = env.configFile()
                .resolve(settings.get(SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_KEYSTORE_FILEPATH, ""))
                .toAbsolutePath().toString();
        final String keystoreType = settings.get(SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_KEYSTORE_TYPE,
                DEFAULT_STORE_TYPE);//  w w w.  j a va 2 s  .c o m
        final String keystorePassword = settings
                .get(SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_KEYSTORE_PASSWORD, DEFAULT_STORE_PASSWORD);
        final String keystoreAlias = settings.get(SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_KEYSTORE_ALIAS,
                null);

        final String truststoreFilePath = env.configFile()
                .resolve(settings.get(SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_TRUSTSTORE_FILEPATH, ""))
                .toAbsolutePath().toString();

        if (settings.get(SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_KEYSTORE_FILEPATH, null) == null) {
            throw new ElasticsearchException(SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_KEYSTORE_FILEPATH
                    + " must be set if transport ssl is reqested.");
        }

        checkStorePath(keystoreFilePath);

        if (settings.get(SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_TRUSTSTORE_FILEPATH, null) == null) {
            throw new ElasticsearchException(SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_TRUSTSTORE_FILEPATH
                    + " must be set if transport ssl is reqested.");
        }

        checkStorePath(truststoreFilePath);

        final String truststoreType = settings.get(SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_TRUSTSTORE_TYPE,
                DEFAULT_STORE_TYPE);
        final String truststorePassword = settings
                .get(SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_TRUSTSTORE_PASSWORD, DEFAULT_STORE_PASSWORD);
        final String truststoreAlias = settings
                .get(SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_TRUSTSTORE_ALIAS, null);

        try {

            final KeyStore ks = KeyStore.getInstance(keystoreType);
            ks.load(new FileInputStream(new File(keystoreFilePath)),
                    (keystorePassword == null || keystorePassword.length() == 0) ? null
                            : keystorePassword.toCharArray());

            transportKeystoreCert = SSLCertificateHelper.exportCertificateChain(ks, keystoreAlias);
            transportKeystoreKey = SSLCertificateHelper.exportDecryptedKey(ks, keystoreAlias,
                    (keystorePassword == null || keystorePassword.length() == 0) ? null
                            : keystorePassword.toCharArray());

            if (transportKeystoreKey == null) {
                throw new ElasticsearchException(
                        "No key found in " + keystoreFilePath + " with alias " + keystoreAlias);
            }

            if (transportKeystoreCert != null && transportKeystoreCert.length > 0) {

                //TODO create sensitive log property
                /*for (int i = 0; i < transportKeystoreCert.length; i++) {
                X509Certificate x509Certificate = transportKeystoreCert[i];
                        
                if(x509Certificate != null) {
                    log.info("Transport keystore subject DN no. {} {}",i,x509Certificate.getSubjectX500Principal());
                }
                }*/
            } else {
                throw new ElasticsearchException(
                        "No certificates found in " + keystoreFilePath + " with alias " + keystoreAlias);
            }

            final KeyStore ts = KeyStore.getInstance(truststoreType);
            ts.load(new FileInputStream(new File(truststoreFilePath)),
                    (truststorePassword == null || truststorePassword.length() == 0) ? null
                            : truststorePassword.toCharArray());

            trustedTransportCertificates = SSLCertificateHelper.exportCertificateChain(ts, truststoreAlias);

            if (trustedTransportCertificates == null) {
                throw new ElasticsearchException("No truststore configured for server");
            }

            final SslContextBuilder sslServerContextBuilder = SslContextBuilder
                    .forServer(transportKeystoreKey, transportKeystoreCert)
                    .ciphers(getEnabledSSLCiphers(this.sslTransportServerProvider, false))
                    .applicationProtocolConfig(ApplicationProtocolConfig.DISABLED)
                    .clientAuth(ClientAuth.REQUIRE)
                    // https://github.com/netty/netty/issues/4722
                    .sessionCacheSize(0).sessionTimeout(0).sslProvider(this.sslTransportServerProvider)
                    .trustManager(trustedTransportCertificates);

            transportServerSslContext = buildSSLContext(sslServerContextBuilder);

            if (trustedTransportCertificates == null) {
                throw new ElasticsearchException("No truststore configured for client");
            }

            final SslContextBuilder sslClientContextBuilder = SslContextBuilder.forClient()
                    .ciphers(getEnabledSSLCiphers(sslTransportClientProvider, false))
                    .applicationProtocolConfig(ApplicationProtocolConfig.DISABLED).sessionCacheSize(0)
                    .sessionTimeout(0).sslProvider(sslTransportClientProvider)
                    .trustManager(trustedTransportCertificates)
                    .keyManager(transportKeystoreKey, transportKeystoreCert);

            transportClientSslContext = buildSSLContext(sslClientContextBuilder);

        } catch (final Exception e) {
            throw new ElasticsearchSecurityException(
                    "Error while initializing transport SSL layer: " + e.toString(), e);
        }

    }

    final boolean client = !"node".equals(this.settings.get(SearchGuardSSLPlugin.CLIENT_TYPE));

    if (!client && httpSSLEnabled) {
        final String keystoreFilePath = env.configFile()
                .resolve(settings.get(SSLConfigConstants.SEARCHGUARD_SSL_HTTP_KEYSTORE_FILEPATH, ""))
                .toAbsolutePath().toString();
        final String keystoreType = settings.get(SSLConfigConstants.SEARCHGUARD_SSL_HTTP_KEYSTORE_TYPE,
                DEFAULT_STORE_TYPE);
        final String keystorePassword = settings.get(SSLConfigConstants.SEARCHGUARD_SSL_HTTP_KEYSTORE_PASSWORD,
                DEFAULT_STORE_PASSWORD);
        final String keystoreAlias = settings.get(SSLConfigConstants.SEARCHGUARD_SSL_HTTP_KEYSTORE_ALIAS, null);
        httpClientAuthMode = ClientAuth.valueOf(settings
                .get(SSLConfigConstants.SEARCHGUARD_SSL_HTTP_CLIENTAUTH_MODE, ClientAuth.OPTIONAL.toString()));

        //TODO remove with next version
        String _enforceHTTPClientAuth = settings.get("searchguard.ssl.http.enforce_clientauth");

        if (_enforceHTTPClientAuth != null) {
            log.error("{} is deprecated and replaced by {}", "searchguard.ssl.http.enforce_clientauth",
                    SSLConfigConstants.SEARCHGUARD_SSL_HTTP_CLIENTAUTH_MODE);
            throw new RuntimeException("searchguard.ssl.http.enforce_clientauth is deprecated");
        }

        log.info("HTTPS client auth mode {}", httpClientAuthMode);

        final String truststoreFilePath = env.configFile()
                .resolve(settings.get(SSLConfigConstants.SEARCHGUARD_SSL_HTTP_TRUSTSTORE_FILEPATH, ""))
                .toAbsolutePath().toString();

        if (settings.get(SSLConfigConstants.SEARCHGUARD_SSL_HTTP_KEYSTORE_FILEPATH, null) == null) {
            throw new ElasticsearchException(SSLConfigConstants.SEARCHGUARD_SSL_HTTP_KEYSTORE_FILEPATH
                    + " must be set if https is reqested.");
        }

        checkStorePath(keystoreFilePath);

        if (httpClientAuthMode == ClientAuth.REQUIRE) {

            if (settings.get(SSLConfigConstants.SEARCHGUARD_SSL_HTTP_TRUSTSTORE_FILEPATH, null) == null) {
                throw new ElasticsearchException(SSLConfigConstants.SEARCHGUARD_SSL_HTTP_TRUSTSTORE_FILEPATH
                        + " must be set if http ssl and client auth is reqested.");
            }

        }

        try {

            final KeyStore ks = KeyStore.getInstance(keystoreType);
            ks.load(new FileInputStream(new File(keystoreFilePath)),
                    (keystorePassword == null || keystorePassword.length() == 0) ? null
                            : keystorePassword.toCharArray());

            httpKeystoreCert = SSLCertificateHelper.exportCertificateChain(ks, keystoreAlias);
            httpKeystoreKey = SSLCertificateHelper.exportDecryptedKey(ks, keystoreAlias,
                    (keystorePassword == null || keystorePassword.length() == 0) ? null
                            : keystorePassword.toCharArray());

            if (httpKeystoreKey == null) {
                throw new ElasticsearchException(
                        "No key found in " + keystoreFilePath + " with alias " + keystoreAlias);
            }

            if (httpKeystoreCert != null && httpKeystoreCert.length > 0) {

                //TODO create sensitive log property
                /*for (int i = 0; i < httpKeystoreCert.length; i++) {
                X509Certificate x509Certificate = httpKeystoreCert[i];
                        
                if(x509Certificate != null) {
                    log.info("HTTP keystore subject DN no. {} {}",i,x509Certificate.getSubjectX500Principal());
                }
                }*/
            } else {
                throw new ElasticsearchException(
                        "No certificates found in " + keystoreFilePath + " with alias " + keystoreAlias);
            }

            if (settings.get(SSLConfigConstants.SEARCHGUARD_SSL_HTTP_TRUSTSTORE_FILEPATH, null) != null) {

                checkStorePath(truststoreFilePath);

                final String truststoreType = settings
                        .get(SSLConfigConstants.SEARCHGUARD_SSL_HTTP_TRUSTSTORE_TYPE, DEFAULT_STORE_TYPE);
                final String truststorePassword = settings.get(
                        SSLConfigConstants.SEARCHGUARD_SSL_HTTP_TRUSTSTORE_PASSWORD, DEFAULT_STORE_PASSWORD);
                final String truststoreAlias = settings
                        .get(SSLConfigConstants.SEARCHGUARD_SSL_HTTP_TRUSTSTORE_ALIAS, null);

                final KeyStore ts = KeyStore.getInstance(truststoreType);
                ts.load(new FileInputStream(new File(truststoreFilePath)),
                        (truststorePassword == null || truststorePassword.length() == 0) ? null
                                : truststorePassword.toCharArray());

                trustedHTTPCertificates = SSLCertificateHelper.exportCertificateChain(ts, truststoreAlias);
            }

            final SslContextBuilder sslContextBuilder = SslContextBuilder
                    .forServer(httpKeystoreKey, httpKeystoreCert)
                    .ciphers(getEnabledSSLCiphers(this.sslHTTPProvider, true))
                    .applicationProtocolConfig(ApplicationProtocolConfig.DISABLED)
                    .clientAuth(Objects.requireNonNull(httpClientAuthMode)) // https://github.com/netty/netty/issues/4722
                    .sessionCacheSize(0).sessionTimeout(0).sslProvider(this.sslHTTPProvider);

            if (trustedHTTPCertificates != null && trustedHTTPCertificates.length > 0) {
                sslContextBuilder.trustManager(trustedHTTPCertificates);
            }

            httpSslContext = buildSSLContext(sslContextBuilder);

        } catch (final Exception e) {
            throw new ElasticsearchSecurityException("Error while initializing HTTP SSL layer: " + e.toString(),
                    e);
        }
    }
}

From source file:com.github.ambry.rest.NettySslFactory.java

License:Open Source License

/**
 * @param config the {@link SSLConfig}./* w w w  .j  a v  a 2  s .  c om*/
 * @return the {@link ClientAuth} setting.
 */
private static ClientAuth getClientAuth(SSLConfig config) {
    switch (config.sslClientAuthentication) {
    case "required":
        return ClientAuth.REQUIRE;
    case "requested":
        return ClientAuth.OPTIONAL;
    default:
        return ClientAuth.NONE;
    }
}

From source file:com.liferay.sync.engine.lan.server.file.LanFileServerInitializer.java

License:Open Source License

public void updateDomainNameMapping() {
    DomainNameMappingBuilder<SslContext> domainNameMappingBuilder = null;

    for (SyncAccount syncAccount : SyncAccountService.findAll()) {
        if (!syncAccount.isActive() || !syncAccount.isLanEnabled()) {
            continue;
        }//from  www. j  a  v a  2  s.c  o  m

        SslContext sslContext = null;

        try {
            X509Certificate x509Certificate = LanPEMParserUtil
                    .parseX509Certificate(syncAccount.getLanCertificate());

            SslContextBuilder sslContextBuilder = SslContextBuilder
                    .forServer(LanPEMParserUtil.parsePrivateKey(syncAccount.getLanKey()), x509Certificate);

            sslContextBuilder.clientAuth(ClientAuth.REQUIRE);
            sslContextBuilder.sslProvider(SslProvider.JDK);
            sslContextBuilder.trustManager(x509Certificate);

            sslContext = sslContextBuilder.build();
        } catch (Exception e) {
            _logger.error(e.getMessage(), e);

            continue;
        }

        if (domainNameMappingBuilder == null) {
            domainNameMappingBuilder = new DomainNameMappingBuilder<>(sslContext);
        }

        domainNameMappingBuilder.add(LanClientUtil.getSNIHostname(syncAccount.getLanServerUuid()), sslContext);
    }

    if (domainNameMappingBuilder == null) {
        return;
    }

    _domainNameMapping = domainNameMappingBuilder.build();
}

From source file:com.linkedin.r2.transport.http.client.Http2InitializerHandler.java

License:Apache License

/**
 * Sets up HTTP/2 over TLS through ALPN (h2) pipeline
 *///from   w  w w.  j a  v a  2s  .  c om
private void configureHttpsPipeline(ChannelHandlerContext ctx) throws Exception {
    JdkSslContext context = new JdkSslContext(_sslContext, IS_CLIENT,
            Arrays.asList(_sslParameters.getCipherSuites()), IdentityCipherSuiteFilter.INSTANCE,
            new ApplicationProtocolConfig(ApplicationProtocolConfig.Protocol.ALPN,
                    ApplicationProtocolConfig.SelectorFailureBehavior.NO_ADVERTISE,
                    ApplicationProtocolConfig.SelectedListenerFailureBehavior.ACCEPT,
                    ApplicationProtocolNames.HTTP_2, ApplicationProtocolNames.HTTP_1_1),
            _sslParameters.getNeedClientAuth() ? ClientAuth.REQUIRE : ClientAuth.OPTIONAL);
    SslHandler sslHandler = context.newHandler(ctx.alloc());

    Http2StreamCodec http2Codec = new Http2StreamCodecBuilder().connection(_connection)
            .maxContentLength(_maxResponseSize).maxHeaderSize(_maxHeaderSize)
            .gracefulShutdownTimeoutMillis(_gracefulShutdownTimeout).streamingTimeout(_streamingTimeout)
            .scheduler(_scheduler).build();

    Http2AlpnHandler alpnHandler = new Http2AlpnHandler(sslHandler, http2Codec);
    Http2SchemeHandler schemeHandler = new Http2SchemeHandler(HttpScheme.HTTPS.toString());
    Http2StreamResponseHandler responseHandler = new Http2StreamResponseHandler();
    Http2ChannelPoolHandler channelPoolHandler = new Http2ChannelPoolHandler();

    ctx.pipeline().addBefore(ctx.name(), "alpnHandler", alpnHandler);
    ctx.pipeline().addBefore(ctx.name(), "schemeHandler", schemeHandler);
    ctx.pipeline().addBefore(ctx.name(), "responseHandler", responseHandler);
    ctx.pipeline().addBefore(ctx.name(), "channelHandler", channelPoolHandler);

    _setupComplete = true;
}

From source file:io.grpc.examples.helloworldtls.HelloWorldServerTls.java

License:Apache License

private SslContextBuilder getSslContextBuilder() {
    SslContextBuilder sslClientContextBuilder = SslContextBuilder.forServer(new File(certChainFilePath),
            new File(privateKeyFilePath));
    if (trustCertCollectionFilePath != null) {
        sslClientContextBuilder.trustManager(new File(trustCertCollectionFilePath));
        sslClientContextBuilder.clientAuth(ClientAuth.REQUIRE);
    }//from   ww w  .j a v  a 2s .c  o m
    return GrpcSslContexts.configure(sslClientContextBuilder);
}

From source file:io.grpc.netty.NettyClientTransportTest.java

License:Apache License

@Test
public void tlsNegotiationFailurePropagatesToStatus() throws Exception {
    File serverCert = TestUtils.loadCert("server1.pem");
    File serverKey = TestUtils.loadCert("server1.key");
    // Don't trust ca.pem, so that client auth fails
    SslContext sslContext = GrpcSslContexts.forServer(serverCert, serverKey)
            .ciphers(TestUtils.preferredTestCiphers(), SupportedCipherSuiteFilter.INSTANCE)
            .clientAuth(ClientAuth.REQUIRE).build();
    negotiator = ProtocolNegotiators.serverTls(sslContext);
    startServer();//from ww  w .  j a  v a  2 s.  c o  m

    File caCert = TestUtils.loadCert("ca.pem");
    File clientCert = TestUtils.loadCert("client.pem");
    File clientKey = TestUtils.loadCert("client.key");
    SslContext clientContext = GrpcSslContexts.forClient().trustManager(caCert)
            .ciphers(TestUtils.preferredTestCiphers(), SupportedCipherSuiteFilter.INSTANCE)
            .keyManager(clientCert, clientKey).build();
    ProtocolNegotiator negotiator = ProtocolNegotiators.tls(clientContext);
    final NettyClientTransport transport = newTransport(negotiator);
    callMeMaybe(transport.start(clientTransportListener));

    Rpc rpc = new Rpc(transport).halfClose();
    try {
        rpc.waitForClose();
        fail("expected exception");
    } catch (ExecutionException ex) {
        StatusException sre = (StatusException) ex.getCause();
        assertEquals(Status.Code.UNAVAILABLE, sre.getStatus().getCode());
        assertThat(sre.getCause()).isInstanceOf(SSLHandshakeException.class);
        assertThat(sre.getCause().getMessage()).contains("SSLV3_ALERT_HANDSHAKE_FAILURE");
    }
}

From source file:io.grpc.netty.TlsTest.java

License:Apache License

private ServerBuilder<?> serverBuilder(int port, File serverCertChainFile, File serverPrivateKeyFile,
        X509Certificate[] serverTrustedCaCerts) throws IOException {
    SslContextBuilder sslContextBuilder = SslContextBuilder.forServer(serverCertChainFile,
            serverPrivateKeyFile);//from  w w w.ja v a 2  s. c o m
    if (sslProvider == SslProvider.JDK) {
        GrpcSslContexts.configure(sslContextBuilder, jdkProvider);
    } else {
        GrpcSslContexts.configure(sslContextBuilder, sslProvider);
    }
    sslContextBuilder.trustManager(serverTrustedCaCerts).clientAuth(ClientAuth.REQUIRE);

    return NettyServerBuilder.forPort(port).sslContext(sslContextBuilder.build());
}

From source file:io.grpc.testing.integration.ConcurrencyTest.java

License:Apache License

/**
 * Creates and starts a new {@link TestServiceImpl} server.
 *//*from  w ww .  ja  v a 2s .c  o  m*/
private Server newServer() throws CertificateException, IOException {
    File serverCertChainFile = TestUtils.loadCert("server1.pem");
    File serverPrivateKeyFile = TestUtils.loadCert("server1.key");
    X509Certificate[] serverTrustedCaCerts = { TestUtils.loadX509Cert("ca.pem") };

    SslContext sslContext = GrpcSslContexts.forServer(serverCertChainFile, serverPrivateKeyFile)
            .trustManager(serverTrustedCaCerts).clientAuth(ClientAuth.REQUIRE).build();

    return NettyServerBuilder.forPort(0).sslContext(sslContext).addService(new TestServiceImpl(serverExecutor))
            .build().start();
}