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

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

Introduction

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

Prototype

ClientAuth OPTIONAL

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

Click Source Link

Document

Indicates that the javax.net.ssl.SSLEngine will request client authentication.

Usage

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.");
            }/*w  w w.  j  av  a2s  . co  m*/

            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);//ww  w  . ja v a 2  s. co  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}./*from ww w  . j a  v  a  2 s  . c o m*/
 * @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.linkedin.r2.transport.http.client.Http2InitializerHandler.java

License:Apache License

/**
 * Sets up HTTP/2 over TLS through ALPN (h2) pipeline
 */// w  w  w  .j  a  va2s .co m
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:com.relayrides.pushy.apns.MockApnsServerBuilder.java

License:Open Source License

/**
 * Constructs a new {@link MockApnsServer} with the previously-set configuration.
 *
 * @return a new MockApnsServer instance with the previously-set configuration
 *
 * @throws SSLException if an SSL context could not be created for the new server for any reason
 *
 * @since 0.8//from w  w  w . j  a  v a2  s .  co  m
 */
public MockApnsServer build() throws SSLException {
    final SslContext sslContext;
    {
        final SslProvider sslProvider;

        if (this.preferredSslProvider != null) {
            sslProvider = this.preferredSslProvider;
        } else {
            if (OpenSsl.isAvailable()) {
                if (OpenSsl.isAlpnSupported()) {
                    log.info("Native SSL provider is available and supports ALPN; will use native provider.");
                    sslProvider = SslProvider.OPENSSL;
                } else {
                    log.info(
                            "Native SSL provider is available, but does not support ALPN; will use JDK SSL provider.");
                    sslProvider = SslProvider.JDK;
                }
            } else {
                log.info("Native SSL provider not available; will use JDK SSL provider.");
                sslProvider = SslProvider.JDK;
            }
        }

        final SslContextBuilder sslContextBuilder;

        if (this.certificateChain != null && this.privateKey != null) {
            sslContextBuilder = SslContextBuilder.forServer(this.privateKey, this.privateKeyPassword,
                    this.certificateChain);
        } else if (this.certificateChainPemFile != null && this.privateKeyPkcs8File != null) {
            sslContextBuilder = SslContextBuilder.forServer(this.certificateChainPemFile,
                    this.privateKeyPkcs8File, this.privateKeyPassword);
        } else if (this.certificateChainInputStream != null && this.privateKeyPkcs8InputStream != null) {
            sslContextBuilder = SslContextBuilder.forServer(this.certificateChainInputStream,
                    this.privateKeyPkcs8InputStream, this.privateKeyPassword);
        } else {
            throw new IllegalStateException("Must specify server credentials before building a mock server.");
        }

        sslContextBuilder.sslProvider(sslProvider)
                .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE)
                .clientAuth(ClientAuth.OPTIONAL).applicationProtocolConfig(
                        new ApplicationProtocolConfig(Protocol.ALPN, SelectorFailureBehavior.NO_ADVERTISE,
                                SelectedListenerFailureBehavior.ACCEPT, ApplicationProtocolNames.HTTP_2));

        sslContext = sslContextBuilder.build();
    }

    final MockApnsServer server = new MockApnsServer(sslContext, this.eventLoopGroup);
    server.setEmulateInternalErrors(this.emulateInternalErrors);

    return server;
}

From source file:com.turo.pushy.apns.BenchmarkApnsServer.java

License:Open Source License

public BenchmarkApnsServer(final InputStream certificateChainInputStream,
        final InputStream privateKeyPkcs8InputStream, final NioEventLoopGroup eventLoopGroup)
        throws SSLException {
    final SslContext sslContext;
    {//ww  w . j a  v a 2s.c o m
        final SslProvider sslProvider;

        if (OpenSsl.isAvailable()) {
            if (OpenSsl.isAlpnSupported()) {
                sslProvider = SslProvider.OPENSSL;
            } else {
                sslProvider = SslProvider.JDK;
            }
        } else {
            sslProvider = SslProvider.JDK;
        }

        sslContext = SslContextBuilder.forServer(certificateChainInputStream, privateKeyPkcs8InputStream, null)
                .sslProvider(sslProvider)
                .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE)
                .clientAuth(ClientAuth.OPTIONAL)
                .applicationProtocolConfig(
                        new ApplicationProtocolConfig(ApplicationProtocolConfig.Protocol.ALPN,
                                ApplicationProtocolConfig.SelectorFailureBehavior.NO_ADVERTISE,
                                ApplicationProtocolConfig.SelectedListenerFailureBehavior.ACCEPT,
                                ApplicationProtocolNames.HTTP_2))
                .build();
    }

    this.bootstrap = new ServerBootstrap();
    this.bootstrap.group(eventLoopGroup);

    this.bootstrap.channel(NioServerSocketChannel.class);
    this.bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(final SocketChannel channel) throws Exception {
            final SslHandler sslHandler = sslContext.newHandler(channel.alloc());
            channel.pipeline().addLast(sslHandler);
            channel.pipeline()
                    .addLast(new ApplicationProtocolNegotiationHandler(ApplicationProtocolNames.HTTP_1_1) {

                        @Override
                        protected void configurePipeline(final ChannelHandlerContext context,
                                final String protocol) throws Exception {
                            if (ApplicationProtocolNames.HTTP_2.equals(protocol)) {
                                context.pipeline().addLast(
                                        new BenchmarkApnsServerHandler.BenchmarkApnsServerHandlerBuilder()
                                                .initialSettings(new Http2Settings()
                                                        .maxConcurrentStreams(MAX_CONCURRENT_STREAMS))
                                                .build());

                                BenchmarkApnsServer.this.allChannels.add(context.channel());
                            } else {
                                throw new IllegalStateException("Unexpected protocol: " + protocol);
                            }
                        }
                    });
        }
    });
}

From source file:com.turo.pushy.apns.MockApnsServerBuilder.java

License:Open Source License

/**
 * Constructs a new {@link MockApnsServer} with the previously-set configuration.
 *
 * @return a new MockApnsServer instance with the previously-set configuration
 *
 * @throws SSLException if an SSL context could not be created for the new server for any reason
 *
 * @since 0.8//from   w w w.j a  va 2 s .c  om
 */
public MockApnsServer build() throws SSLException {
    final SslContext sslContext;
    {
        final SslProvider sslProvider = SslUtil.getSslProvider();

        final SslContextBuilder sslContextBuilder;

        if (this.certificateChain != null && this.privateKey != null) {
            sslContextBuilder = SslContextBuilder.forServer(this.privateKey, this.privateKeyPassword,
                    this.certificateChain);
        } else if (this.certificateChainPemFile != null && this.privateKeyPkcs8File != null) {
            sslContextBuilder = SslContextBuilder.forServer(this.certificateChainPemFile,
                    this.privateKeyPkcs8File, this.privateKeyPassword);
        } else if (this.certificateChainInputStream != null && this.privateKeyPkcs8InputStream != null) {
            sslContextBuilder = SslContextBuilder.forServer(this.certificateChainInputStream,
                    this.privateKeyPkcs8InputStream, this.privateKeyPassword);
        } else {
            throw new IllegalStateException("Must specify server credentials before building a mock server.");
        }

        sslContextBuilder.sslProvider(sslProvider)
                .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE)
                .clientAuth(ClientAuth.OPTIONAL).applicationProtocolConfig(
                        new ApplicationProtocolConfig(Protocol.ALPN, SelectorFailureBehavior.NO_ADVERTISE,
                                SelectedListenerFailureBehavior.ACCEPT, ApplicationProtocolNames.HTTP_2));

        if (this.trustedClientCertificatePemFile != null) {
            sslContextBuilder.trustManager(this.trustedClientCertificatePemFile);
        } else if (this.trustedClientCertificateInputStream != null) {
            sslContextBuilder.trustManager(this.trustedClientCertificateInputStream);
        } else if (this.trustedClientCertificates != null) {
            sslContextBuilder.trustManager(this.trustedClientCertificates);
        }

        sslContext = sslContextBuilder.build();
    }

    final MockApnsServer server = new MockApnsServer(sslContext, this.eventLoopGroup);
    server.setEmulateInternalErrors(this.emulateInternalErrors);
    server.setEmulateExpiredFirstToken(this.emulateExpiredFirstToken);

    return server;
}

From source file:com.turo.pushy.apns.server.BaseHttp2ServerBuilder.java

License:Open Source License

/**
 * Constructs a new server with the previously-set configuration.
 *
 * @return a new server instance with the previously-set configuration
 *
 * @throws SSLException if an SSL context could not be created for the new server for any reason
 *
 * @since 0.8//from   w w  w . ja  va2s.  c  om
 */
public T build() throws SSLException {
    final SslContext sslContext;
    {
        final SslProvider sslProvider;

        if (OpenSsl.isAvailable()) {
            log.info("Native SSL provider is available; will use native provider.");
            sslProvider = SslProvider.OPENSSL;
        } else {
            log.info("Native SSL provider not available; will use JDK SSL provider.");
            sslProvider = SslProvider.JDK;
        }

        final SslContextBuilder sslContextBuilder;

        if (this.certificateChain != null && this.privateKey != null) {
            sslContextBuilder = SslContextBuilder.forServer(this.privateKey, this.privateKeyPassword,
                    this.certificateChain);
        } else if (this.certificateChainPemFile != null && this.privateKeyPkcs8File != null) {
            sslContextBuilder = SslContextBuilder.forServer(this.certificateChainPemFile,
                    this.privateKeyPkcs8File, this.privateKeyPassword);
        } else if (this.certificateChainInputStream != null && this.privateKeyPkcs8InputStream != null) {
            sslContextBuilder = SslContextBuilder.forServer(this.certificateChainInputStream,
                    this.privateKeyPkcs8InputStream, this.privateKeyPassword);
        } else {
            throw new IllegalStateException("Must specify server credentials before building a mock server.");
        }

        sslContextBuilder.sslProvider(sslProvider)
                .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE)
                .clientAuth(ClientAuth.OPTIONAL);

        if (this.trustedClientCertificatePemFile != null) {
            sslContextBuilder.trustManager(this.trustedClientCertificatePemFile);
        } else if (this.trustedClientCertificateInputStream != null) {
            sslContextBuilder.trustManager(this.trustedClientCertificateInputStream);
        } else if (this.trustedClientCertificates != null) {
            sslContextBuilder.trustManager(this.trustedClientCertificates);
        }

        if (this.useAlpn) {
            sslContextBuilder.applicationProtocolConfig(
                    new ApplicationProtocolConfig(ApplicationProtocolConfig.Protocol.ALPN,
                            ApplicationProtocolConfig.SelectorFailureBehavior.NO_ADVERTISE,
                            ApplicationProtocolConfig.SelectedListenerFailureBehavior.ACCEPT,
                            ApplicationProtocolNames.HTTP_2));
        }

        sslContext = sslContextBuilder.build();
    }

    final T server = this.constructServer(sslContext);

    if (sslContext instanceof ReferenceCounted) {
        ((ReferenceCounted) sslContext).release();
    }

    return server;
}

From source file:com.yahoo.pulsar.broker.service.PulsarChannelInitializer.java

License:Apache License

@Override
protected void initChannel(SocketChannel ch) throws Exception {
    if (enableTLS) {
        File tlsCert = new File(serviceConfig.getTlsCertificateFilePath());
        File tlsKey = new File(serviceConfig.getTlsKeyFilePath());
        SslContextBuilder builder = SslContextBuilder.forServer(tlsCert, tlsKey);
        if (serviceConfig.isTlsAllowInsecureConnection()) {
            builder.trustManager(InsecureTrustManagerFactory.INSTANCE);
        } else {/*from   ww  w  .j av  a  2 s  . co m*/
            if (serviceConfig.getTlsTrustCertsFilePath().isEmpty()) {
                // Use system default
                builder.trustManager((File) null);
            } else {
                File trustCertCollection = new File(serviceConfig.getTlsTrustCertsFilePath());
                builder.trustManager(trustCertCollection);
            }
        }
        SslContext sslCtx = builder.clientAuth(ClientAuth.OPTIONAL).build();
        ch.pipeline().addLast(TLS_HANDLER, sslCtx.newHandler(ch.alloc()));
    }
    ch.pipeline().addLast("frameDecoder",
            new PulsarLengthFieldFrameDecoder(PulsarDecoder.MaxFrameSize, 0, 4, 0, 4));
    ch.pipeline().addLast("handler", new ServerCnx(brokerService));
}

From source file:com.yahoo.pulsar.discovery.service.ServiceChannelInitializer.java

License:Apache License

@Override
protected void initChannel(SocketChannel ch) throws Exception {
    if (enableTLS) {
        File tlsCert = new File(serviceConfig.getTlsCertificateFilePath());
        File tlsKey = new File(serviceConfig.getTlsKeyFilePath());
        SslContextBuilder builder = SslContextBuilder.forServer(tlsCert, tlsKey);
        // allows insecure connection
        builder.trustManager(InsecureTrustManagerFactory.INSTANCE);
        SslContext sslCtx = builder.clientAuth(ClientAuth.OPTIONAL).build();
        ch.pipeline().addLast(TLS_HANDLER, sslCtx.newHandler(ch.alloc()));
    }//from w  w w.  j a v a2  s  .c o m
    ch.pipeline().addLast("frameDecoder",
            new PulsarLengthFieldFrameDecoder(PulsarDecoder.MaxFrameSize, 0, 4, 0, 4));
    ch.pipeline().addLast("handler", new ServerConnection(discoveryService));
}