Search in sources :

Example 6 with SslContextBuilder

use of org.apache.flink.shaded.netty4.io.netty.handler.ssl.SslContextBuilder in project pravega by pravega.

the class ConnectionFactoryImpl method establishConnection.

@Override
public CompletableFuture<ClientConnection> establishConnection(PravegaNodeUri location, ReplyProcessor rp) {
    Preconditions.checkNotNull(location);
    Exceptions.checkNotClosed(closed.get(), this);
    final SslContext sslCtx;
    if (clientConfig.isEnableTls()) {
        try {
            SslContextBuilder sslCtxFactory = SslContextBuilder.forClient();
            if (Strings.isNullOrEmpty(clientConfig.getTrustStore())) {
                sslCtxFactory = sslCtxFactory.trustManager(FingerprintTrustManagerFactory.getInstance(FingerprintTrustManagerFactory.getDefaultAlgorithm()));
            } else {
                sslCtxFactory = SslContextBuilder.forClient().trustManager(new File(clientConfig.getTrustStore()));
            }
            sslCtx = sslCtxFactory.build();
        } catch (SSLException | NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    } else {
        sslCtx = null;
    }
    AppendBatchSizeTracker batchSizeTracker = new AppendBatchSizeTrackerImpl();
    ClientConnectionInboundHandler handler = new ClientConnectionInboundHandler(location.getEndpoint(), rp, batchSizeTracker);
    Bootstrap b = new Bootstrap();
    b.group(group).channel(nio ? NioSocketChannel.class : EpollSocketChannel.class).option(ChannelOption.TCP_NODELAY, true).handler(new ChannelInitializer<SocketChannel>() {

        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline p = ch.pipeline();
            if (sslCtx != null) {
                SslHandler sslHandler = sslCtx.newHandler(ch.alloc(), location.getEndpoint(), location.getPort());
                if (clientConfig.isValidateHostName()) {
                    SSLEngine sslEngine = sslHandler.engine();
                    SSLParameters sslParameters = sslEngine.getSSLParameters();
                    sslParameters.setEndpointIdentificationAlgorithm("HTTPS");
                    sslEngine.setSSLParameters(sslParameters);
                }
                p.addLast(sslHandler);
            }
            // p.addLast(new LoggingHandler(LogLevel.INFO));
            p.addLast(new ExceptionLoggingHandler(location.getEndpoint()), new CommandEncoder(batchSizeTracker), new LengthFieldBasedFrameDecoder(WireCommands.MAX_WIRECOMMAND_SIZE, 4, 4), new CommandDecoder(), handler);
        }
    });
    // Start the client.
    CompletableFuture<ClientConnection> connectionComplete = new CompletableFuture<>();
    try {
        b.connect(location.getEndpoint(), location.getPort()).addListener(new ChannelFutureListener() {

            @Override
            public void operationComplete(ChannelFuture future) {
                if (future.isSuccess()) {
                    // since ChannelFuture is complete future.channel() is not a blocking call.
                    Channel ch = future.channel();
                    log.debug("Connect operation completed for channel:{}, local address:{}, remote address:{}", ch.id(), ch.localAddress(), ch.remoteAddress());
                    // Once a channel is closed the channel group implementation removes it.
                    allChannels.add(ch);
                    connectionComplete.complete(handler);
                } else {
                    connectionComplete.completeExceptionally(new ConnectionFailedException(future.cause()));
                }
            }
        });
    } catch (Exception e) {
        connectionComplete.completeExceptionally(new ConnectionFailedException(e));
    }
    // check if channel is registered.
    CompletableFuture<Void> channelRegisteredFuture = new CompletableFuture<>();
    handler.completeWhenRegistered(channelRegisteredFuture);
    return connectionComplete.thenCombine(channelRegisteredFuture, (clientConnection, v) -> clientConnection);
}
Also used : NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) EpollSocketChannel(io.netty.channel.epoll.EpollSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) SSLEngine(javax.net.ssl.SSLEngine) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) CommandEncoder(io.pravega.shared.protocol.netty.CommandEncoder) SSLException(javax.net.ssl.SSLException) CompletableFuture(java.util.concurrent.CompletableFuture) SSLParameters(javax.net.ssl.SSLParameters) ExceptionLoggingHandler(io.pravega.shared.protocol.netty.ExceptionLoggingHandler) Bootstrap(io.netty.bootstrap.Bootstrap) EpollSocketChannel(io.netty.channel.epoll.EpollSocketChannel) LengthFieldBasedFrameDecoder(io.netty.handler.codec.LengthFieldBasedFrameDecoder) SslContext(io.netty.handler.ssl.SslContext) ChannelFuture(io.netty.channel.ChannelFuture) AppendBatchSizeTracker(io.pravega.shared.protocol.netty.AppendBatchSizeTracker) CommandDecoder(io.pravega.shared.protocol.netty.CommandDecoder) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) EpollSocketChannel(io.netty.channel.epoll.EpollSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) Channel(io.netty.channel.Channel) ChannelFutureListener(io.netty.channel.ChannelFutureListener) ConnectionFailedException(io.pravega.shared.protocol.netty.ConnectionFailedException) SSLException(javax.net.ssl.SSLException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) ChannelPipeline(io.netty.channel.ChannelPipeline) SslHandler(io.netty.handler.ssl.SslHandler) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SslContextBuilder(io.netty.handler.ssl.SslContextBuilder) File(java.io.File) ConnectionFailedException(io.pravega.shared.protocol.netty.ConnectionFailedException)

Example 7 with SslContextBuilder

use of org.apache.flink.shaded.netty4.io.netty.handler.ssl.SslContextBuilder in project bookkeeper by apache.

the class TLSContextFactory method createClientContext.

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");
    }
    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();
}
Also used : SslContextBuilder(io.netty.handler.ssl.SslContextBuilder) TrustManagerFactory(javax.net.ssl.TrustManagerFactory) SslProvider(io.netty.handler.ssl.SslProvider) File(java.io.File) ClientConfiguration(org.apache.bookkeeper.conf.ClientConfiguration) KeyManagerFactory(javax.net.ssl.KeyManagerFactory)

Example 8 with SslContextBuilder

use of org.apache.flink.shaded.netty4.io.netty.handler.ssl.SslContextBuilder in project incubator-pulsar by apache.

the class SecurityUtility method createNettySslContextForClient.

public static SslContext createNettySslContextForClient(boolean allowInsecureConnection, String trustCertsFilePath, Certificate[] certificates, PrivateKey privateKey) throws GeneralSecurityException, SSLException, FileNotFoundException, IOException {
    SslContextBuilder builder = SslContextBuilder.forClient();
    setupTrustCerts(builder, allowInsecureConnection, trustCertsFilePath);
    setupKeyManager(builder, privateKey, (X509Certificate[]) certificates);
    return builder.build();
}
Also used : SslContextBuilder(io.netty.handler.ssl.SslContextBuilder) X509Certificate(java.security.cert.X509Certificate)

Example 9 with SslContextBuilder

use of org.apache.flink.shaded.netty4.io.netty.handler.ssl.SslContextBuilder in project incubator-pulsar by apache.

the class SecurityUtility method createNettySslContextForServer.

public static SslContext createNettySslContextForServer(boolean allowInsecureConnection, String trustCertsFilePath, String certFilePath, String keyFilePath, Set<String> ciphers, Set<String> protocols, boolean requireTrustedClientCertOnConnect) throws GeneralSecurityException, SSLException, FileNotFoundException, IOException {
    X509Certificate[] certificates = loadCertificatesFromPemFile(certFilePath);
    PrivateKey privateKey = loadPrivateKeyFromPemFile(keyFilePath);
    SslContextBuilder builder = SslContextBuilder.forServer(privateKey, (X509Certificate[]) certificates);
    setupCiphers(builder, ciphers);
    setupProtocols(builder, protocols);
    setupTrustCerts(builder, allowInsecureConnection, trustCertsFilePath);
    setupKeyManager(builder, privateKey, certificates);
    setupClientAuthentication(builder, requireTrustedClientCertOnConnect);
    return builder.build();
}
Also used : PrivateKey(java.security.PrivateKey) SslContextBuilder(io.netty.handler.ssl.SslContextBuilder) X509Certificate(java.security.cert.X509Certificate)

Example 10 with SslContextBuilder

use of org.apache.flink.shaded.netty4.io.netty.handler.ssl.SslContextBuilder in project incubator-pulsar by apache.

the class DiscoveryServiceTest method connectToService.

/**
 * creates ClientHandler channel to connect and communicate with server
 *
 * @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;
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) PrivateKey(java.security.PrivateKey) InetSocketAddress(java.net.InetSocketAddress) URI(java.net.URI) URISyntaxException(java.net.URISyntaxException) SessionExpiredException(org.apache.zookeeper.KeeperException.SessionExpiredException) ExecutionException(java.util.concurrent.ExecutionException) SslContextBuilder(io.netty.handler.ssl.SslContextBuilder) Bootstrap(io.netty.bootstrap.Bootstrap) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) SslContext(io.netty.handler.ssl.SslContext)

Aggregations

SslContextBuilder (io.netty.handler.ssl.SslContextBuilder)49 SslContext (io.netty.handler.ssl.SslContext)14 SSLException (javax.net.ssl.SSLException)12 KeyManagerFactory (javax.net.ssl.KeyManagerFactory)11 InputStream (java.io.InputStream)10 TrustManagerFactory (javax.net.ssl.TrustManagerFactory)10 SslProvider (io.netty.handler.ssl.SslProvider)9 File (java.io.File)9 IOException (java.io.IOException)9 KeyStore (java.security.KeyStore)7 X509Certificate (java.security.cert.X509Certificate)7 ApplicationProtocolConfig (io.netty.handler.ssl.ApplicationProtocolConfig)5 PrivateKey (java.security.PrivateKey)5 SslHandler (io.netty.handler.ssl.SslHandler)4 SelfSignedCertificate (io.netty.handler.ssl.util.SelfSignedCertificate)4 FileInputStream (java.io.FileInputStream)4 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)4 CertificateException (java.security.cert.CertificateException)4 NettyChannelBuilder (io.grpc.netty.NettyChannelBuilder)3 Bootstrap (io.netty.bootstrap.Bootstrap)3