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

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

Introduction

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

Prototype

public SslContextBuilder trustManager(TrustManager trustManager) 

Source Link

Document

A single trusted manager for verifying the remote endpoint's certificate.

Usage

From source file:com.yahoo.pulsar.client.impl.ConnectionPool.java

License:Apache License

public ConnectionPool(final PulsarClientImpl client, EventLoopGroup eventLoopGroup) {
    this.eventLoopGroup = eventLoopGroup;
    this.maxConnectionsPerHosts = client.getConfiguration().getConnectionsPerBroker();

    pool = new ConcurrentHashMap<>();
    bootstrap = new Bootstrap();
    bootstrap.group(eventLoopGroup);//ww w .ja  va2  s.  co m
    if (SystemUtils.IS_OS_LINUX && eventLoopGroup instanceof EpollEventLoopGroup) {
        bootstrap.channel(EpollSocketChannel.class);
    } else {
        bootstrap.channel(NioSocketChannel.class);
    }

    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000);
    bootstrap.option(ChannelOption.TCP_NODELAY, client.getConfiguration().isUseTcpNoDelay());
    bootstrap.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
    bootstrap.handler(new ChannelInitializer<SocketChannel>() {
        public void initChannel(SocketChannel ch) throws Exception {
            ClientConfiguration clientConfig = client.getConfiguration();
            if (clientConfig.isUseTls()) {
                SslContextBuilder builder = SslContextBuilder.forClient();
                if (clientConfig.isTlsAllowInsecureConnection()) {
                    builder.trustManager(InsecureTrustManagerFactory.INSTANCE);
                } else {
                    if (clientConfig.getTlsTrustCertsFilePath().isEmpty()) {
                        // Use system default
                        builder.trustManager((File) null);
                    } else {
                        File trustCertCollection = new File(clientConfig.getTlsTrustCertsFilePath());
                        builder.trustManager(trustCertCollection);
                    }
                }

                // Set client certificate if available
                AuthenticationDataProvider authData = clientConfig.getAuthentication().getAuthData();
                if (authData.hasDataForTls()) {
                    builder.keyManager(authData.getTlsPrivateKey(),
                            (X509Certificate[]) authData.getTlsCertificates());
                }

                SslContext sslCtx = builder.build();
                ch.pipeline().addLast(TLS_HANDLER, sslCtx.newHandler(ch.alloc()));
            }
            ch.pipeline().addLast("frameDecoder",
                    new PulsarLengthFieldFrameDecoder(MaxMessageSize, 0, 4, 0, 4));
            ch.pipeline().addLast("handler", new ClientCnx(client));
        }
    });
}

From source file:com.yahoo.pulsar.common.util.SecurityUtility.java

License:Apache License

public static SslContext createNettySslContext(boolean allowInsecureConnection, String trustCertsFilePath,
        Certificate[] certificates, PrivateKey privateKey)
        throws GeneralSecurityException, SSLException, FileNotFoundException {
    SslContextBuilder builder = SslContextBuilder.forClient();
    if (allowInsecureConnection) {
        builder.trustManager(InsecureTrustManagerFactory.INSTANCE);
    } else {/* w w  w .ja  va2  s.  co m*/
        if (trustCertsFilePath != null && trustCertsFilePath.length() != 0) {
            builder.trustManager(new FileInputStream(trustCertsFilePath));
        }
    }
    builder.keyManager(privateKey, (X509Certificate[]) certificates);
    return builder.build();
}

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

License:Apache License

/**
 * creates ClientHandler channel to connect and communicate with server
 * //  w w  w.  j a  va 2s  . co  m
 * @param serviceUrl
 * @param latch
 * @return
 * @throws URISyntaxException
 */
public static NioEventLoopGroup connectToService(String serviceUrl, CountDownLatch latch, boolean tls)
        throws URISyntaxException {
    NioEventLoopGroup workerGroup = new NioEventLoopGroup();
    Bootstrap b = new Bootstrap();
    b.group(workerGroup);
    b.channel(NioSocketChannel.class);

    b.handler(new ChannelInitializer<SocketChannel>() {
        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            if (tls) {
                SslContextBuilder builder = SslContextBuilder.forClient();
                builder.trustManager(InsecureTrustManagerFactory.INSTANCE);
                X509Certificate[] certificates = SecurityUtility
                        .loadCertificatesFromPemFile(TLS_CLIENT_CERT_FILE_PATH);
                PrivateKey privateKey = SecurityUtility.loadPrivateKeyFromPemFile(TLS_CLIENT_KEY_FILE_PATH);
                builder.keyManager(privateKey, (X509Certificate[]) certificates);
                SslContext sslCtx = builder.build();
                ch.pipeline().addLast("tls", sslCtx.newHandler(ch.alloc()));
            }
            ch.pipeline().addLast(new ClientHandler(latch));
        }
    });
    URI uri = new URI(serviceUrl);
    InetSocketAddress serviceAddress = new InetSocketAddress(uri.getHost(), uri.getPort());
    b.connect(serviceAddress).addListener((ChannelFuture future) -> {
        if (!future.isSuccess()) {
            throw new IllegalStateException(future.cause());
        }
    });
    return workerGroup;
}

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  va2  s. c om
    ch.pipeline().addLast("frameDecoder",
            new PulsarLengthFieldFrameDecoder(PulsarDecoder.MaxFrameSize, 0, 4, 0, 4));
    ch.pipeline().addLast("handler", new ServerConnection(discoveryService));
}

From source file:io.airlift.drift.transport.netty.ssl.ReloadableSslContext.java

License:Apache License

public synchronized void reload() {
    try {/*from  w ww .j  av a 2  s .  co m*/
        // every watch must be called each time to update status
        boolean trustCertificateModified = trustCertificatesFileWatch.updateState();
        boolean clientCertificateModified = false;
        if (clientCertificatesFileWatch.isPresent()) {
            clientCertificateModified = clientCertificatesFileWatch.get().updateState();
        }
        boolean privateKeyModified = false;
        if (privateKeyFileWatch.isPresent()) {
            privateKeyModified = privateKeyFileWatch.get().updateState();
        }
        if (trustCertificateModified || clientCertificateModified || privateKeyModified) {
            PrivateKey privateKey = null;
            if (privateKeyFileWatch.isPresent()) {
                privateKey = loadPrivateKey(privateKeyFileWatch.get().getFile(), privateKeyPassword);
            }

            X509Certificate[] certificateChain = null;
            if (clientCertificatesFileWatch.isPresent()) {
                certificateChain = readCertificateChain(clientCertificatesFileWatch.get().getFile())
                        .toArray(new X509Certificate[0]);
            }

            SslContextBuilder sslContextBuilder;
            if (forClient) {
                sslContextBuilder = SslContextBuilder.forClient().keyManager(privateKey, certificateChain);
            } else {
                sslContextBuilder = SslContextBuilder.forServer(privateKey, certificateChain);
            }

            X509Certificate[] trustChain = readCertificateChain(trustCertificatesFileWatch.getFile())
                    .toArray(new X509Certificate[0]);

            sslContextBuilder.trustManager(trustChain).sessionCacheSize(sessionCacheSize)
                    .sessionTimeout(sessionTimeout.roundTo(SECONDS));
            if (!ciphers.isEmpty()) {
                sslContextBuilder.ciphers(ciphers);
            }
            sslContext.set(new SslContextHolder(sslContextBuilder.build()));
        }
    } catch (GeneralSecurityException e) {
        sslContext.set(new SslContextHolder(new UncheckedIOException(new IOException(e))));
    } catch (IOException e) {
        sslContext.set(new SslContextHolder(new UncheckedIOException(e)));
    }
}

From source file:io.crate.protocols.ssl.SslConfiguration.java

public static SslContext buildSslContext(Settings settings) {
    try {/*from   www . jav  a  2 s.  co m*/
        KeyStoreSettings keyStoreSettings = new KeyStoreSettings(settings);

        Optional<TrustStoreSettings> trustStoreSettings = TrustStoreSettings.tryLoad(settings);
        TrustManager[] trustManagers = null;
        if (trustStoreSettings.isPresent()) {
            trustManagers = trustStoreSettings.get().trustManagers;
        }

        // Use the newest SSL standard which is (at the time of writing) TLSv1.2
        // If we just specify "TLS" here, it depends on the JVM implementation which version we'll get.
        SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
        sslContext.init(keyStoreSettings.keyManagers, trustManagers, null);
        SSLContext.setDefault(sslContext);

        List<String> enabledCiphers = Arrays.asList(sslContext.createSSLEngine().getEnabledCipherSuites());

        final X509Certificate[] keystoreCerts = keyStoreSettings.exportServerCertChain();
        final PrivateKey privateKey = keyStoreSettings.exportDecryptedKey();

        X509Certificate[] trustedCertificates = keyStoreSettings.exportRootCertificates();
        if (trustStoreSettings.isPresent()) {
            trustedCertificates = trustStoreSettings.get().exportRootCertificates(trustedCertificates);
        }

        final SslContextBuilder sslContextBuilder = SslContextBuilder.forServer(privateKey, keystoreCerts)
                .ciphers(enabledCiphers).applicationProtocolConfig(ApplicationProtocolConfig.DISABLED)
                .clientAuth(ClientAuth.OPTIONAL).sessionCacheSize(0).sessionTimeout(0).startTls(false)
                .sslProvider(SslProvider.JDK);

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

        return sslContextBuilder.build();

    } catch (SslConfigurationException e) {
        throw e;
    } catch (Exception e) {
        throw new SslConfigurationException("Failed to build SSL configuration", e);
    }
}

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

License:Apache License

private static SslContext buildSslContext(String trustCertCollectionFilePath, String clientCertChainFilePath,
        String clientPrivateKeyFilePath) throws SSLException {
    SslContextBuilder builder = GrpcSslContexts.forClient();
    if (trustCertCollectionFilePath != null) {
        builder.trustManager(new File(trustCertCollectionFilePath));
    }/* w  w w  .j  a v a2 s  . c  o m*/
    if (clientCertChainFilePath != null && clientPrivateKeyFilePath != null) {
        builder.keyManager(new File(clientCertChainFilePath), new File(clientPrivateKeyFilePath));
    }
    return builder.build();
}

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

License:Apache License

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

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

License:Apache License

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

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

From source file:io.vertx.core.net.impl.SSLHelper.java

License:Open Source License

private SslContext createContext(VertxInternal vertx) {
    try {//from   ww  w. j a v a  2  s  .  co  m
        KeyManagerFactory keyMgrFactory = getKeyMgrFactory(vertx);
        TrustManagerFactory trustMgrFactory = getTrustMgrFactory(vertx);
        SslContextBuilder builder;
        if (client) {
            builder = SslContextBuilder.forClient();
            if (keyMgrFactory != null) {
                builder.keyManager(keyMgrFactory);
            }
        } else {
            if (keyMgrFactory == null) {
                throw new VertxException("Key/certificate is mandatory for SSL");
            }
            builder = SslContextBuilder.forServer(keyMgrFactory);
        }
        Collection<String> cipherSuites = enabledCipherSuites;
        if (openSsl) {
            builder.sslProvider(SslProvider.OPENSSL);
            if (cipherSuites == null || cipherSuites.isEmpty()) {
                cipherSuites = OpenSsl.availableOpenSslCipherSuites();
            }
        } else {
            builder.sslProvider(SslProvider.JDK);
            if (cipherSuites == null || cipherSuites.isEmpty()) {
                cipherSuites = DEFAULT_JDK_CIPHER_SUITE;
            }
        }
        if (trustMgrFactory != null) {
            builder.trustManager(trustMgrFactory);
        }
        if (cipherSuites != null && cipherSuites.size() > 0) {
            builder.ciphers(cipherSuites);
        }
        if (useAlpn && applicationProtocols != null && applicationProtocols.size() > 0) {
            builder.applicationProtocolConfig(new ApplicationProtocolConfig(
                    ApplicationProtocolConfig.Protocol.ALPN,
                    ApplicationProtocolConfig.SelectorFailureBehavior.NO_ADVERTISE,
                    ApplicationProtocolConfig.SelectedListenerFailureBehavior.ACCEPT, applicationProtocols
                            .stream().map(PROTOCOL_NAME_MAPPING::get).collect(Collectors.toList())));
        }
        return builder.build();
    } catch (Exception e) {
        throw new VertxException(e);
    }
}