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: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 .  j a  v a2s.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.bookkeeper.tls.TLSContextFactory.java

License:Apache License

private void createServerContext(AbstractConfiguration conf)
        throws SecurityException, KeyStoreException, NoSuchAlgorithmException, CertificateException,
        IOException, UnrecoverableKeyException, InvalidKeySpecException, IllegalArgumentException {
    final SslContextBuilder sslContextBuilder;
    final ServerConfiguration serverConf;
    final SslProvider provider;
    final boolean clientAuthentication;

    // get key-file and trust-file locations and passwords
    if (!(conf instanceof ServerConfiguration)) {
        throw new SecurityException("Server configruation not provided");
    }/* w w w .j a v a 2 s  .c  o  m*/

    serverConf = (ServerConfiguration) conf;
    provider = getTLSProvider(serverConf.getTLSProvider());
    clientAuthentication = serverConf.getTLSClientAuthentication();

    switch (KeyStoreType.valueOf(serverConf.getTLSKeyStoreType())) {
    case PEM:
        final String keyPassword;

        if (Strings.isNullOrEmpty(serverConf.getTLSKeyStore())) {
            throw new SecurityException("Key path is required");
        }

        if (Strings.isNullOrEmpty(serverConf.getTLSCertificatePath())) {
            throw new SecurityException("Certificate path is required");
        }

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

        sslContextBuilder = SslContextBuilder
                .forServer(new File(serverConf.getTLSCertificatePath()), new File(serverConf.getTLSKeyStore()),
                        keyPassword)
                .ciphers(null).sessionCacheSize(0).sessionTimeout(0).sslProvider(provider).startTls(true);

        break;
    case JKS:
        // falling thru, same as PKCS12
    case PKCS12:
        KeyManagerFactory kmf = initKeyManagerFactory(serverConf.getTLSKeyStoreType(),
                serverConf.getTLSKeyStore(), serverConf.getTLSKeyStorePasswordPath());

        sslContextBuilder = SslContextBuilder.forServer(kmf).ciphers(null).sessionCacheSize(0).sessionTimeout(0)
                .sslProvider(provider).startTls(true);

        break;
    default:
        throw new SecurityException("Invalid Keyfile type" + serverConf.getTLSKeyStoreType());
    }

    if (clientAuthentication) {
        sslContextBuilder.clientAuth(ClientAuth.REQUIRE);

        switch (KeyStoreType.valueOf(serverConf.getTLSTrustStoreType())) {
        case PEM:
            if (Strings.isNullOrEmpty(serverConf.getTLSTrustStore())) {
                throw new SecurityException("CA Certificate chain is required");
            }
            sslContextBuilder.trustManager(new File(serverConf.getTLSTrustStore()));
            break;
        case JKS:
            // falling thru, same as PKCS12
        case PKCS12:
            TrustManagerFactory tmf = initTrustManagerFactory(serverConf.getTLSTrustStoreType(),
                    serverConf.getTLSTrustStore(), serverConf.getTLSTrustStorePasswordPath());
            sslContextBuilder.trustManager(tmf);
            break;
        default:
            throw new SecurityException("Invalid Truststore type" + serverConf.getTLSTrustStoreType());
        }
    }

    sslContext = sslContextBuilder.build();
}

From source file:org.apache.nifi.processors.grpc.ListenGRPC.java

License:Apache License

@OnScheduled
public void startServer(final ProcessContext context) throws NoSuchAlgorithmException, IOException,
        KeyStoreException, CertificateException, UnrecoverableKeyException {
    final ComponentLog logger = getLogger();
    // gather configured properties
    final Integer port = context.getProperty(PROP_SERVICE_PORT).asInteger();
    final Boolean useSecure = context.getProperty(PROP_USE_SECURE).asBoolean();
    final Integer flowControlWindow = context.getProperty(PROP_FLOW_CONTROL_WINDOW).asDataSize(DataUnit.B)
            .intValue();/*from  ww  w  .ja  v  a  2s .c  om*/
    final Integer maxMessageSize = context.getProperty(PROP_MAX_MESSAGE_SIZE).asDataSize(DataUnit.B).intValue();
    final SSLContextService sslContextService = context.getProperty(PROP_SSL_CONTEXT_SERVICE)
            .asControllerService(SSLContextService.class);
    final SSLContext sslContext = sslContextService == null ? null
            : sslContextService.createSSLContext(SSLContextService.ClientAuth.NONE);
    final Pattern authorizedDnPattern = Pattern
            .compile(context.getProperty(PROP_AUTHORIZED_DN_PATTERN).getValue());
    final FlowFileIngestServiceInterceptor callInterceptor = new FlowFileIngestServiceInterceptor(getLogger());
    callInterceptor.enforceDNPattern(authorizedDnPattern);

    final FlowFileIngestService flowFileIngestService = new FlowFileIngestService(getLogger(),
            sessionFactoryReference, context);
    NettyServerBuilder serverBuilder = NettyServerBuilder.forPort(port)
            .addService(ServerInterceptors.intercept(flowFileIngestService, callInterceptor))
            // default (de)compressor registries handle both plaintext and gzip compressed messages
            .compressorRegistry(CompressorRegistry.getDefaultInstance())
            .decompressorRegistry(DecompressorRegistry.getDefaultInstance())
            .flowControlWindow(flowControlWindow).maxMessageSize(maxMessageSize);

    if (useSecure && sslContext != null) {
        // construct key manager
        if (StringUtils.isBlank(sslContextService.getKeyStoreFile())) {
            throw new IllegalStateException(
                    "SSL is enabled, but no keystore has been configured. You must configure a keystore.");
        }

        final KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm(), sslContext.getProvider());
        final KeyStore keyStore = KeyStore.getInstance(sslContextService.getKeyStoreType());
        try (final InputStream is = new FileInputStream(sslContextService.getKeyStoreFile())) {
            keyStore.load(is, sslContextService.getKeyStorePassword().toCharArray());
        }
        keyManagerFactory.init(keyStore, sslContextService.getKeyStorePassword().toCharArray());

        SslContextBuilder sslContextBuilder = SslContextBuilder.forServer(keyManagerFactory);

        // if the trust store is configured, then client auth is required.
        if (StringUtils.isNotBlank(sslContextService.getTrustStoreFile())) {
            final TrustManagerFactory trustManagerFactory = TrustManagerFactory
                    .getInstance(TrustManagerFactory.getDefaultAlgorithm(), sslContext.getProvider());
            final KeyStore trustStore = KeyStore.getInstance(sslContextService.getTrustStoreType());
            try (final InputStream is = new FileInputStream(sslContextService.getTrustStoreFile())) {
                trustStore.load(is, sslContextService.getTrustStorePassword().toCharArray());
            }
            trustManagerFactory.init(trustStore);
            sslContextBuilder = sslContextBuilder.trustManager(trustManagerFactory);
            sslContextBuilder = sslContextBuilder.clientAuth(ClientAuth.REQUIRE);
        } else {
            sslContextBuilder = sslContextBuilder.clientAuth(ClientAuth.NONE);
        }
        sslContextBuilder = GrpcSslContexts.configure(sslContextBuilder);
        serverBuilder = serverBuilder.sslContext(sslContextBuilder.build());
    }
    logger.info("Starting gRPC server on port: {}", new Object[] { port.toString() });
    this.server = serverBuilder.build().start();
}

From source file:org.apache.nifi.processors.grpc.TestGRPCClient.java

License:Apache License

/**
 * Build a channel with the given host and port and optional ssl properties.
 *
 * @param host          the host to establish a connection with
 * @param port          the port on which to communicate with the host
 * @param sslProperties the properties by which to establish an ssl connection
 * @return a constructed channel/*from  ww  w  .  j av a 2s  .co  m*/
 */
public static ManagedChannel buildChannel(final String host, final int port,
        final Map<String, String> sslProperties) throws NoSuchAlgorithmException, KeyStoreException,
        IOException, CertificateException, UnrecoverableKeyException {
    NettyChannelBuilder channelBuilder = NettyChannelBuilder.forAddress(host, port).directExecutor()
            .compressorRegistry(CompressorRegistry.getDefaultInstance())
            .decompressorRegistry(DecompressorRegistry.getDefaultInstance()).userAgent("testAgent");

    if (sslProperties != null) {
        SslContextBuilder sslContextBuilder = SslContextBuilder.forClient();

        if (sslProperties.get(StandardSSLContextService.KEYSTORE.getName()) != null) {
            final KeyManagerFactory keyManager = KeyManagerFactory
                    .getInstance(KeyManagerFactory.getDefaultAlgorithm());
            final KeyStore keyStore = KeyStore
                    .getInstance(sslProperties.get(StandardSSLContextService.KEYSTORE_TYPE.getName()));
            final String keyStoreFile = sslProperties.get(StandardSSLContextService.KEYSTORE.getName());
            final String keyStorePassword = sslProperties
                    .get(StandardSSLContextService.KEYSTORE_PASSWORD.getName());
            try (final InputStream is = new FileInputStream(keyStoreFile)) {
                keyStore.load(is, keyStorePassword.toCharArray());
            }
            keyManager.init(keyStore, keyStorePassword.toCharArray());
            sslContextBuilder = sslContextBuilder.keyManager(keyManager);
        }

        if (sslProperties.get(StandardSSLContextService.TRUSTSTORE.getName()) != null) {
            final TrustManagerFactory trustManagerFactory = TrustManagerFactory
                    .getInstance(TrustManagerFactory.getDefaultAlgorithm());
            final KeyStore trustStore = KeyStore
                    .getInstance(sslProperties.get(StandardSSLContextService.TRUSTSTORE_TYPE.getName()));
            final String trustStoreFile = sslProperties.get(StandardSSLContextService.TRUSTSTORE.getName());
            final String trustStorePassword = sslProperties
                    .get(StandardSSLContextService.TRUSTSTORE_PASSWORD.getName());
            try (final InputStream is = new FileInputStream(trustStoreFile)) {
                trustStore.load(is, trustStorePassword.toCharArray());
            }
            trustManagerFactory.init(trustStore);
            sslContextBuilder = sslContextBuilder.trustManager(trustManagerFactory);
        }

        final String clientAuth = sslProperties.get(NEED_CLIENT_AUTH);
        if (clientAuth == null) {
            sslContextBuilder = sslContextBuilder.clientAuth(ClientAuth.REQUIRE);
        } else {
            sslContextBuilder = sslContextBuilder.clientAuth(ClientAuth.valueOf(clientAuth));
        }
        sslContextBuilder = GrpcSslContexts.configure(sslContextBuilder);
        channelBuilder = channelBuilder.sslContext(sslContextBuilder.build());
    } else {
        channelBuilder.usePlaintext(true);
    }
    return channelBuilder.build();
}

From source file:org.apache.nifi.processors.grpc.TestGRPCServer.java

License:Apache License

/**
 * Starts the gRPC server @localhost:port.
 *//*from  w  ww.  j a va  2 s. c  om*/
public int start(final int port) throws Exception {
    final NettyServerBuilder nettyServerBuilder = NettyServerBuilder.forPort(port).directExecutor()
            .addService(clazz.newInstance()).compressorRegistry(CompressorRegistry.getDefaultInstance())
            .decompressorRegistry(DecompressorRegistry.getDefaultInstance());

    if (this.sslProperties != null) {
        if (sslProperties.get(StandardSSLContextService.KEYSTORE.getName()) == null) {
            throw new RuntimeException("You must configure a keystore in order to use SSL with gRPC.");
        }

        final KeyManagerFactory keyManager = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());
        final KeyStore keyStore = KeyStore
                .getInstance(sslProperties.get(StandardSSLContextService.KEYSTORE_TYPE.getName()));
        final String keyStoreFile = sslProperties.get(StandardSSLContextService.KEYSTORE.getName());
        final String keyStorePassword = sslProperties
                .get(StandardSSLContextService.KEYSTORE_PASSWORD.getName());
        try (final InputStream is = new FileInputStream(keyStoreFile)) {
            keyStore.load(is, keyStorePassword.toCharArray());
        }
        keyManager.init(keyStore, keyStorePassword.toCharArray());
        SslContextBuilder sslContextBuilder = SslContextBuilder.forServer(keyManager);

        if (sslProperties.get(StandardSSLContextService.TRUSTSTORE.getName()) != null) {
            final TrustManagerFactory trustManagerFactory = TrustManagerFactory
                    .getInstance(TrustManagerFactory.getDefaultAlgorithm());
            final KeyStore trustStore = KeyStore
                    .getInstance(sslProperties.get(StandardSSLContextService.TRUSTSTORE_TYPE.getName()));
            final String trustStoreFile = sslProperties.get(StandardSSLContextService.TRUSTSTORE.getName());
            final String trustStorePassword = sslProperties
                    .get(StandardSSLContextService.TRUSTSTORE_PASSWORD.getName());
            try (final InputStream is = new FileInputStream(trustStoreFile)) {
                trustStore.load(is, trustStorePassword.toCharArray());
            }
            trustManagerFactory.init(trustStore);
            sslContextBuilder = sslContextBuilder.trustManager(trustManagerFactory);
        }

        final String clientAuth = sslProperties.get(NEED_CLIENT_AUTH);
        if (clientAuth == null) {
            sslContextBuilder = sslContextBuilder.clientAuth(ClientAuth.REQUIRE);
        } else {
            sslContextBuilder = sslContextBuilder.clientAuth(ClientAuth.valueOf(clientAuth));
        }
        sslContextBuilder = GrpcSslContexts.configure(sslContextBuilder);
        nettyServerBuilder.sslContext(sslContextBuilder.build());
    }

    server = nettyServerBuilder.build().start();
    final int actualPort = server.getPort();

    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            // Use stderr here since the logger may have been reset by its JVM shutdown hook.
            System.err.println("*** shutting down gRPC server since JVM is shutting down");
            TestGRPCServer.this.stop();
            System.err.println("*** server shut down");
        }
    });
    return actualPort;
}

From source file:org.dvlyyon.nbi.gnmi.GnmiServer.java

License:Open Source License

private Server getTLSServer(GnmiServerContextInf cmd, BindableService service, AuthInterceptor interceptor)
        throws Exception {

    int port = cmd.getServerPort();

    SslContextBuilder contextBuilder = GrpcSslContexts.forServer(new File(cmd.getServerCACertificate()),
            new File(cmd.getServerKey()));

    if (cmd.getClientCACertificate() != null)
        contextBuilder = contextBuilder.trustManager(new File(cmd.getClientCACertificate()));

    contextBuilder = cmd.requireClientCert() ? contextBuilder.clientAuth(ClientAuth.REQUIRE)
            : contextBuilder.clientAuth(ClientAuth.OPTIONAL);

    server = NettyServerBuilder.forPort(port).sslContext(contextBuilder.build())
            .addService(ServerInterceptors.intercept(service, interceptor)).build();
    logger.info("Server started, listening on " + port);
    return server;
}

From source file:org.graylog2.plugin.inputs.transports.AbstractTcpTransport.java

License:Open Source License

private Callable<ChannelHandler> getSslHandlerCallable(MessageInput input) {
    final File certFile;
    final File keyFile;
    if (tlsCertFile.exists() && tlsKeyFile.exists()) {
        certFile = tlsCertFile;//from   ww  w  . j a  va  2 s . c  om
        keyFile = tlsKeyFile;
    } else {
        LOG.warn(
                "TLS key file or certificate file does not exist, creating a self-signed certificate for input [{}/{}].",
                input.getName(), input.getId());

        final String tmpDir = System.getProperty("java.io.tmpdir");
        checkState(tmpDir != null, "The temporary directory must not be null!");
        final Path tmpPath = Paths.get(tmpDir);
        if (!Files.isDirectory(tmpPath) || !Files.isWritable(tmpPath)) {
            throw new IllegalStateException(
                    "Couldn't write to temporary directory: " + tmpPath.toAbsolutePath());
        }

        try {
            final SelfSignedCertificate ssc = new SelfSignedCertificate(
                    configuration.getString(CK_BIND_ADDRESS) + ":" + configuration.getString(CK_PORT));
            certFile = ssc.certificate();
            keyFile = ssc.privateKey();
        } catch (CertificateException e) {
            final String msg = String.format(Locale.ENGLISH,
                    "Problem creating a self-signed certificate for input [%s/%s].", input.getName(),
                    input.getId());
            throw new IllegalStateException(msg, e);
        }
    }

    final ClientAuth clientAuth;
    switch (tlsClientAuth) {
    case TLS_CLIENT_AUTH_DISABLED:
        LOG.debug("Not using TLS client authentication");
        clientAuth = ClientAuth.NONE;
        break;
    case TLS_CLIENT_AUTH_OPTIONAL:
        LOG.debug("Using optional TLS client authentication");
        clientAuth = ClientAuth.OPTIONAL;
        break;
    case TLS_CLIENT_AUTH_REQUIRED:
        LOG.debug("Using mandatory TLS client authentication");
        clientAuth = ClientAuth.REQUIRE;
        break;
    default:
        throw new IllegalArgumentException("Unknown TLS client authentication mode: " + tlsClientAuth);
    }

    return buildSslHandlerCallable(nettyTransportConfiguration.getTlsProvider(), certFile, keyFile,
            tlsKeyPassword, clientAuth, tlsClientAuthCertFile);
}

From source file:org.graylog2.plugin.inputs.transports.AbstractTcpTransport.java

License:Open Source License

private Callable<ChannelHandler> buildSslHandlerCallable(SslProvider tlsProvider, File certFile, File keyFile,
        String password, ClientAuth clientAuth, File clientAuthCertFile) {
    return new Callable<ChannelHandler>() {
        @Override/*w w w  .  j a  va 2s  .  c  om*/
        public ChannelHandler call() throws Exception {
            try {
                return new SslHandler(createSslEngine());
            } catch (SSLException e) {
                LOG.error(
                        "Error creating SSL context. Make sure the certificate and key are in the correct format: cert=X.509 key=PKCS#8");
                throw e;
            }
        }

        private SSLEngine createSslEngine() throws IOException, CertificateException {
            final X509Certificate[] clientAuthCerts;
            if (EnumSet.of(ClientAuth.OPTIONAL, ClientAuth.REQUIRE).contains(clientAuth)) {
                if (clientAuthCertFile.exists()) {
                    clientAuthCerts = KeyUtil.loadCertificates(clientAuthCertFile.toPath()).stream()
                            .filter(certificate -> certificate instanceof X509Certificate)
                            .map(certificate -> (X509Certificate) certificate).toArray(X509Certificate[]::new);
                } else {
                    LOG.warn(
                            "Client auth configured, but no authorized certificates / certificate authorities configured");
                    clientAuthCerts = null;
                }
            } else {
                clientAuthCerts = null;
            }

            final SslContext sslContext = SslContextBuilder
                    .forServer(certFile, keyFile, Strings.emptyToNull(password)).sslProvider(tlsProvider)
                    .clientAuth(clientAuth).trustManager(clientAuthCerts).build();

            // TODO: Use byte buffer allocator of channel
            return sslContext.newEngine(ByteBufAllocator.DEFAULT);
        }
    };
}

From source file:org.hyperledger.fabric.sdk.security.TLSCertGenTest.java

License:Open Source License

@Ignore
// issue when moved up to latest netty http://openjdk.5641.n7.nabble.com/sun-security-ssl-ProtocolVersion-valueOf-in-Java8-and-TLSv1-3-td350186.html
@Test//from  w w w  .  j  a v a 2  s. c o m
public void selfSignedTLSCertTest() throws Exception {
    AtomicBoolean handshakeOccured = new AtomicBoolean(false);
    TLSCertificateBuilder certBuilder = new TLSCertificateBuilder();

    TLSCertificateKeyPair serverCert = certBuilder.serverCert("localhost");
    File serverCertFile = createFile("server-cert.pem", serverCert.getCertPEMBytes());
    File serverKeyFile = createFile("server-key.pem", serverCert.getKeyPemBytes());

    TLSCertificateKeyPair clientCert = certBuilder.clientCert();
    File clientCertFile = createFile("client-cert.pem", clientCert.getCertPEMBytes());
    File clientKeyFile = createFile("client-key.pem", clientCert.getKeyPemBytes());
    Server server = NettyServerBuilder.forPort(0).addService(new MockEndorser())
            .intercept(mutualTLSInterceptor(clientCert.getCertDERBytes(), handshakeOccured))
            .sslContext(GrpcSslContexts.forServer(serverCertFile, serverKeyFile).protocols(TLS_PROTOCOL)
                    .trustManager(clientCertFile).clientAuth(ClientAuth.REQUIRE).build())
            .build();

    server.start();

    if (vendor.contains("IBM")) {
        // The TLS handshake doesn't work with IBM JRE, skipping
        server.shutdown();
        return;
    }

    NettyChannelBuilder channelBuilder = NettyChannelBuilder.forAddress("localhost", server.getPort())
            .sslContext(getSslContextBuilder(clientCertFile, clientKeyFile, serverCertFile)
                    .protocols(TLS_PROTOCOL).build())
            .negotiationType(NegotiationType.TLS);
    ManagedChannel chan = channelBuilder.build();
    FabricProposal.SignedProposal prop = FabricProposal.SignedProposal.getDefaultInstance();
    EndorserGrpc.newBlockingStub(chan).processProposal(prop);
    // Ensure that TLS handshake occurred
    Assert.assertTrue("Handshake didn't occur", handshakeOccured.get());
    chan.shutdown();
    server.shutdown();
}

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  a  2 s  .  co 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());
    }
}