Example usage for io.netty.handler.ssl SslContextBuilder keyManager

List of usage examples for io.netty.handler.ssl SslContextBuilder keyManager

Introduction

In this page you can find the example usage for io.netty.handler.ssl SslContextBuilder keyManager.

Prototype

public SslContextBuilder keyManager(PrivateKey key, String keyPassword,
        Iterable<? extends X509Certificate> keyCertChain) 

Source Link

Document

Identifying certificate for this host.

Usage

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

License:Open Source License

/**
 * Constructs a new {@link ApnsClient} with the previously-set configuration.
 *
 * @return a new ApnsClient instance with the previously-set configuration
 *
 * @throws SSLException if an SSL context could not be created for the new client for any reason
 * @throws IllegalStateException if this method is called without specifying an APNs server address, if this method
 * is called without providing TLS credentials or a signing key, or if this method is called with both TLS
 * credentials and a signing key//from   w ww  .  j a v  a 2s .  c om
 *
 * @since 0.8
 */
public ApnsClient build() throws SSLException {
    if (this.apnsServerAddress == null) {
        throw new IllegalStateException("No APNs server address specified.");
    }

    if (this.clientCertificate == null && this.privateKey == null && this.signingKey == null) {
        throw new IllegalStateException("No client credentials specified; either TLS credentials (a "
                + "certificate/private key) or an APNs signing key must be provided before building a client.");
    } else if ((this.clientCertificate != null || this.privateKey != null) && this.signingKey != null) {
        throw new IllegalStateException("Clients may not have both a signing key and TLS credentials.");
    }

    final SslContext sslContext;
    {
        final SslProvider sslProvider;

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

        final SslContextBuilder sslContextBuilder = SslContextBuilder.forClient().sslProvider(sslProvider)
                .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE);

        if (this.clientCertificate != null && this.privateKey != null) {
            sslContextBuilder.keyManager(this.privateKey, this.privateKeyPassword, this.clientCertificate);
        }

        if (this.trustedServerCertificatePemFile != null) {
            sslContextBuilder.trustManager(this.trustedServerCertificatePemFile);
        } else if (this.trustedServerCertificateInputStream != null) {
            sslContextBuilder.trustManager(this.trustedServerCertificateInputStream);
        } else if (this.trustedServerCertificates != null) {
            sslContextBuilder.trustManager(this.trustedServerCertificates);
        }

        sslContext = sslContextBuilder.build();
    }

    final ApnsClient client = new ApnsClient(this.apnsServerAddress, sslContext, this.signingKey,
            this.proxyHandlerFactory, this.connectionTimeoutMillis, this.idlePingIntervalMillis,
            this.gracefulShutdownTimeoutMillis, this.concurrentConnections, this.metricsListener,
            this.frameLogger, this.eventLoopGroup);

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

    return client;
}

From source file:io.vitess.client.grpc.GrpcClientFactory.java

License:Apache License

/**
 * <p>Factory method to construct a gRPC client connection with transport-layer security.</p>
 *
 * <p>Within the <code>tlsOptions</code> parameter value, the <code>trustStore</code> field
 * should//from   w w w . jav a 2  s. c om
 * always be populated.  All other fields are optional.</p>
 *
 * @param ctx TODO: This parameter is not actually used, but probably SHOULD be so that
 *     timeout duration and caller ID settings aren't discarded
 * @param target target is passed to NettyChannelBuilder which will resolve based on scheme,
 *     by default dns.
 */
@Override
public RpcClient createTls(Context ctx, String target, TlsOptions tlsOptions) {
    final SslContextBuilder sslContextBuilder = GrpcSslContexts.forClient();

    // trustManager should always be set
    final KeyStore trustStore = loadKeyStore(tlsOptions.getTrustStore(), tlsOptions.getTrustStorePassword());
    if (trustStore == null) {
        throw new RuntimeException("Could not load trustStore");
    }
    final X509Certificate[] trustCertCollection = tlsOptions.getTrustAlias() == null
            ? loadCertCollection(trustStore)
            : loadCertCollectionForAlias(trustStore, tlsOptions.getTrustAlias());
    sslContextBuilder.trustManager(trustCertCollection);

    // keyManager should only be set if a keyStore is specified (meaning that client authentication
    // is enabled)
    final KeyStore keyStore = loadKeyStore(tlsOptions.getKeyStore(), tlsOptions.getKeyStorePassword());
    if (keyStore != null) {
        final PrivateKeyWrapper privateKeyWrapper = tlsOptions.getKeyAlias() == null
                ? loadPrivateKeyEntry(keyStore, tlsOptions.getKeyStorePassword(), tlsOptions.getKeyPassword())
                : loadPrivateKeyEntryForAlias(keyStore, tlsOptions.getKeyAlias(),
                        tlsOptions.getKeyStorePassword(), tlsOptions.getKeyPassword());
        if (privateKeyWrapper == null) {
            throw new RuntimeException("Could not retrieve private key and certificate chain from keyStore");
        }

        sslContextBuilder.keyManager(privateKeyWrapper.getPrivateKey(), privateKeyWrapper.getPassword(),
                privateKeyWrapper.getCertificateChain());
    }

    final SslContext sslContext;
    try {
        sslContext = sslContextBuilder.build();
    } catch (SSLException exc) {
        throw new RuntimeException(exc);
    }

    ClientInterceptor[] interceptors = getClientInterceptors();

    return new GrpcClient(channelBuilder(target).negotiationType(NegotiationType.TLS).sslContext(sslContext)
            .intercept(interceptors).build(), ctx);
}

From source file:org.apache.bookkeeper.tls.TLSContextFactory.java

License:Apache License

private void createClientContext(AbstractConfiguration conf)
        throws SecurityException, KeyStoreException, NoSuchAlgorithmException, CertificateException,
        IOException, UnrecoverableKeyException, InvalidKeySpecException, NoSuchProviderException {
    final SslContextBuilder sslContextBuilder;
    final ClientConfiguration clientConf;
    final SslProvider provider;
    final boolean clientAuthentication;

    // get key-file and trust-file locations and passwords
    if (!(conf instanceof ClientConfiguration)) {
        throw new SecurityException("Client configruation not provided");
    }//from w  w  w  .  jav  a  2 s  . c  om

    clientConf = (ClientConfiguration) conf;
    provider = getTLSProvider(clientConf.getTLSProvider());
    clientAuthentication = clientConf.getTLSClientAuthentication();

    switch (KeyStoreType.valueOf(clientConf.getTLSTrustStoreType())) {
    case PEM:
        if (Strings.isNullOrEmpty(clientConf.getTLSTrustStore())) {
            throw new SecurityException("CA Certificate required");
        }

        sslContextBuilder = SslContextBuilder.forClient().trustManager(new File(clientConf.getTLSTrustStore()))
                .ciphers(null).sessionCacheSize(0).sessionTimeout(0).sslProvider(provider)
                .clientAuth(ClientAuth.REQUIRE);

        break;
    case JKS:
        // falling thru, same as PKCS12
    case PKCS12:
        TrustManagerFactory tmf = initTrustManagerFactory(clientConf.getTLSTrustStoreType(),
                clientConf.getTLSTrustStore(), clientConf.getTLSTrustStorePasswordPath());

        sslContextBuilder = SslContextBuilder.forClient().trustManager(tmf).ciphers(null).sessionCacheSize(0)
                .sessionTimeout(0).sslProvider(provider).clientAuth(ClientAuth.REQUIRE);

        break;
    default:
        throw new SecurityException("Invalid Truststore type: " + clientConf.getTLSTrustStoreType());
    }

    if (clientAuthentication) {
        switch (KeyStoreType.valueOf(clientConf.getTLSKeyStoreType())) {
        case PEM:
            final String keyPassword;

            if (Strings.isNullOrEmpty(clientConf.getTLSCertificatePath())) {
                throw new SecurityException("Valid Certificate is missing");
            }

            if (Strings.isNullOrEmpty(clientConf.getTLSKeyStore())) {
                throw new SecurityException("Valid Key is missing");
            }

            if (!Strings.isNullOrEmpty(clientConf.getTLSKeyStorePasswordPath())) {
                keyPassword = getPasswordFromFile(clientConf.getTLSKeyStorePasswordPath());
            } else {
                keyPassword = null;
            }

            sslContextBuilder.keyManager(new File(clientConf.getTLSCertificatePath()),
                    new File(clientConf.getTLSKeyStore()), keyPassword);
            break;
        case JKS:
            // falling thru, same as PKCS12
        case PKCS12:
            KeyManagerFactory kmf = initKeyManagerFactory(clientConf.getTLSKeyStoreType(),
                    clientConf.getTLSKeyStore(), clientConf.getTLSKeyStorePasswordPath());

            sslContextBuilder.keyManager(kmf);
            break;
        default:
            throw new SecurityException("Invalid Keyfile type" + clientConf.getTLSKeyStoreType());
        }
    }

    sslContext = sslContextBuilder.build();
}

From source file:org.apache.rocketmq.remoting.netty.TlsHelper.java

License:Apache License

public static SslContext buildSslContext(boolean forClient) throws IOException, CertificateException {
    File configFile = new File(TlsSystemConfig.tlsConfigFile);
    extractTlsConfigFromFile(configFile);
    logTheFinalUsedTlsConfig();/*from   w ww. j  ava  2  s  . co m*/

    SslProvider provider;
    if (OpenSsl.isAvailable()) {
        provider = SslProvider.OPENSSL;
        LOGGER.info("Using OpenSSL provider");
    } else {
        provider = SslProvider.JDK;
        LOGGER.info("Using JDK SSL provider");
    }

    if (forClient) {
        if (tlsTestModeEnable) {
            return SslContextBuilder.forClient().sslProvider(SslProvider.JDK)
                    .trustManager(InsecureTrustManagerFactory.INSTANCE).build();
        } else {
            SslContextBuilder sslContextBuilder = SslContextBuilder.forClient().sslProvider(SslProvider.JDK);

            if (!tlsClientAuthServer) {
                sslContextBuilder.trustManager(InsecureTrustManagerFactory.INSTANCE);
            } else {
                if (!isNullOrEmpty(tlsClientTrustCertPath)) {
                    sslContextBuilder.trustManager(new File(tlsClientTrustCertPath));
                }
            }

            return sslContextBuilder
                    .keyManager(
                            !isNullOrEmpty(tlsClientCertPath) ? new FileInputStream(tlsClientCertPath) : null,
                            !isNullOrEmpty(tlsClientKeyPath)
                                    ? decryptionStrategy.decryptPrivateKey(tlsClientKeyPath, true)
                                    : null,
                            !isNullOrEmpty(tlsClientKeyPassword) ? tlsClientKeyPassword : null)
                    .build();
        }
    } else {

        if (tlsTestModeEnable) {
            SelfSignedCertificate selfSignedCertificate = new SelfSignedCertificate();
            return SslContextBuilder
                    .forServer(selfSignedCertificate.certificate(), selfSignedCertificate.privateKey())
                    .sslProvider(SslProvider.JDK).clientAuth(ClientAuth.OPTIONAL).build();
        } else {
            SslContextBuilder sslContextBuilder = SslContextBuilder
                    .forServer(
                            !isNullOrEmpty(tlsServerCertPath) ? new FileInputStream(tlsServerCertPath) : null,
                            !isNullOrEmpty(tlsServerKeyPath)
                                    ? decryptionStrategy.decryptPrivateKey(tlsServerKeyPath, false)
                                    : null,
                            !isNullOrEmpty(tlsServerKeyPassword) ? tlsServerKeyPassword : null)
                    .sslProvider(provider);

            if (!tlsServerAuthClient) {
                sslContextBuilder.trustManager(InsecureTrustManagerFactory.INSTANCE);
            } else {
                if (!isNullOrEmpty(tlsServerTrustCertPath)) {
                    sslContextBuilder.trustManager(new File(tlsServerTrustCertPath));
                }
            }

            sslContextBuilder.clientAuth(parseClientAuthMode(tlsServerNeedClientAuth));
            return sslContextBuilder.build();
        }
    }
}

From source file:org.apache.tinkerpop.gremlin.driver.Cluster.java

License:Apache License

SslContext createSSLContext() throws Exception {
    // if the context is provided then just use that and ignore the other settings
    if (manager.sslContextOptional.isPresent())
        return manager.sslContextOptional.get();

    final SslProvider provider = SslProvider.JDK;
    final Settings.ConnectionPoolSettings connectionPoolSettings = connectionPoolSettings();
    final SslContextBuilder builder = SslContextBuilder.forClient();

    if (connectionPoolSettings.trustCertChainFile != null)
        builder.trustManager(new File(connectionPoolSettings.trustCertChainFile));
    else {/*from w  ww  .j a  v  a2 s  . c o m*/
        logger.warn(
                "SSL configured without a trustCertChainFile and thus trusts all certificates without verification (not suitable for production)");
        builder.trustManager(InsecureTrustManagerFactory.INSTANCE);
    }

    if (null != connectionPoolSettings.keyCertChainFile && null != connectionPoolSettings.keyFile) {
        final File keyCertChainFile = new File(connectionPoolSettings.keyCertChainFile);
        final File keyFile = new File(connectionPoolSettings.keyFile);

        // note that keyPassword may be null here if the keyFile is not password-protected.
        builder.keyManager(keyCertChainFile, keyFile, connectionPoolSettings.keyPassword);
    }

    builder.sslProvider(provider);

    return builder.build();
}

From source file:org.ow2.petals.bc.gateway.commons.handlers.AuthenticatorSSLHandler.java

License:Open Source License

private void setUpSslHandlers(final ChannelHandlerContext ctx, final AbstractDomain domain,
        final @Nullable String certificate, final @Nullable String key, final @Nullable String passphrase,
        final @Nullable String remoteCertificate) throws SSLException {

    // TODO could we use certificate only for auth and not encryption?
    // TODO support openssl
    final SslHandler sslHandler;
    if (pdOrAuth.isB() && certificate != null && key != null) {
        // server side ssl, do not forget startTls so that our accept can be sent after the handler is added

        final ServiceUnitDataHandler handler = domain.getSUHandler();

        final SslContextBuilder builder = SslContextBuilder
                .forServer(ServiceUnitUtil.getFile(handler.getInstallRoot(), certificate),
                        ServiceUnitUtil.getFile(handler.getInstallRoot(), key), passphrase)
                .sslProvider(SslProvider.JDK).ciphers(null, IdentityCipherSuiteFilter.INSTANCE)
                .sessionCacheSize(0).sessionTimeout(0);

        if (remoteCertificate != null) {
            builder.trustManager(ServiceUnitUtil.getFile(handler.getInstallRoot(), remoteCertificate))
                    .clientAuth(ClientAuth.REQUIRE);
        }/*  w w  w  . j  av  a2s. c  o m*/

        // until https://github.com/netty/netty/issues/5170 is accepted
        // we need to create the handler by hand
        sslHandler = new SslHandler(builder.build().newEngine(ctx.alloc()), true);
    } else if (pdOrAuth.isA() && remoteCertificate != null) {
        // client side

        final String installRoot = domain.getSUHandler().getInstallRoot();
        final SslContextBuilder builder = SslContextBuilder.forClient().sslProvider(SslProvider.JDK)
                .trustManager(ServiceUnitUtil.getFile(installRoot, remoteCertificate))
                .ciphers(null, IdentityCipherSuiteFilter.INSTANCE).sessionCacheSize(0).sessionTimeout(0);

        if (certificate != null && key != null) {
            builder.keyManager(ServiceUnitUtil.getFile(installRoot, certificate),
                    ServiceUnitUtil.getFile(installRoot, key), passphrase);
        }

        sslHandler = builder.build().newHandler(ctx.alloc());
    } else {
        sslHandler = null;
    }

    // For a server, it contains the transporter name and the consumer domain name (it was updated in channelRead0)
    // For a client, it contains the provider domain name (it was set by the component)
    final String logName = logger.getName();

    // let's replace the debug logger with something specific to this consumer
    ctx.pipeline().replace(HandlerConstants.LOG_DEBUG_HANDLER, HandlerConstants.LOG_DEBUG_HANDLER,
            new LoggingHandler(logName, LogLevel.TRACE));

    ctx.pipeline().replace(HandlerConstants.LOG_ERRORS_HANDLER, HandlerConstants.LOG_ERRORS_HANDLER,
            new LastLoggingHandler(logName + ".errors"));

    if (sslHandler != null) {
        // if there is a sslHandler, then we can only add the domain handler after the handshake is finished
        // if not we risk sending things too early in it

        sslHandler.handshakeFuture().addListener(new FutureListener<Channel>() {
            @Override
            public void operationComplete(final @Nullable Future<Channel> future) throws Exception {
                assert future != null;
                if (!future.isSuccess()) {
                    authenticationFuture.setFailure(future.cause());
                } else {
                    // I must keep the handler here until now in case there is an exception so that I can log it
                    ctx.pipeline().replace(HandlerConstants.DOMAIN_HANDLER, HandlerConstants.DOMAIN_HANDLER,
                            dhb.build(domain));
                    authenticationFuture.setSuccess(ctx.channel());
                }
            }
        });

        ctx.pipeline().addAfter(HandlerConstants.LOG_DEBUG_HANDLER, HandlerConstants.SSL_HANDLER, sslHandler);
    }

    if (pdOrAuth.isB()) {
        if (logger.isLoggable(Level.FINE)) {
            logger.fine("Sending an Accept (" + ctx.channel().remoteAddress() + ")");
        }

        // this must be sent after the ssh handler is replaced (when using ssl) so that we are ready to receive ssl data right away
        // but this must be sent before the domain handler is replaced (when not using ssl), because it will send
        // data and it must arrive AFTER our Accept
        ctx.writeAndFlush(new AuthAccept());
    }

    // else it is done in the FutureListener
    if (sslHandler == null) {
        ctx.pipeline().replace(HandlerConstants.DOMAIN_HANDLER, HandlerConstants.DOMAIN_HANDLER,
                dhb.build(domain));
        authenticationFuture.setSuccess(ctx.channel());
    }
}