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

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

Introduction

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

Prototype

public SslContext build() throws SSLException 

Source Link

Document

Create new SslContext instance with configured settings.

Usage

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

License:Apache License

public synchronized void reload() {
    try {//  w w  w  .  j a va 2  s.  com
        // 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   ww w . ja  v  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.gatling.http.client.impl.DefaultHttpClient.java

License:Apache License

public DefaultHttpClient(HttpClientConfig config) {
    this.config = config;
    try {//from www  . j  ava 2 s .c o m
        SslContextBuilder sslContextBuilder = SslContextBuilder.forClient();

        if (config.getSslSessionCacheSize() > 0) {
            sslContextBuilder.sessionCacheSize(config.getSslSessionCacheSize());
        }

        if (config.getSslSessionTimeout() > 0) {
            sslContextBuilder.sessionTimeout(config.getSslSessionTimeout());
        }

        if (isNonEmpty(config.getEnabledSslProtocols())) {
            sslContextBuilder.protocols(config.getEnabledSslProtocols());
        }

        if (isNonEmpty(config.getEnabledSslCipherSuites())) {
            sslContextBuilder.ciphers(Arrays.asList(config.getEnabledSslCipherSuites()));
        } else if (!config.isFilterInsecureCipherSuites()) {
            sslContextBuilder.ciphers(null, IdentityCipherSuiteFilter.INSTANCE_DEFAULTING_TO_SUPPORTED_CIPHERS);
        }

        sslContextBuilder.sslProvider(config.isUseOpenSsl() ? SslProvider.OPENSSL : SslProvider.JDK)
                .keyManager(config.getKeyManagerFactory()).trustManager(config.getTrustManagerFactory());

        this.sslContext = sslContextBuilder.build();

        this.alpnSslContext = sslContextBuilder.applicationProtocolConfig(
                new ApplicationProtocolConfig(ApplicationProtocolConfig.Protocol.ALPN,
                        // NO_ADVERTISE is currently the only mode supported by both OpenSsl and JDK providers.
                        ApplicationProtocolConfig.SelectorFailureBehavior.NO_ADVERTISE,
                        // ACCEPT is currently the only mode supported by both OpenSsl and JDK providers.
                        ApplicationProtocolConfig.SelectedListenerFailureBehavior.ACCEPT,
                        ApplicationProtocolNames.HTTP_2, ApplicationProtocolNames.HTTP_1_1))
                .build();

    } catch (SSLException e) {
        throw new IllegalArgumentException("Impossible to create SslContext", e);
    }

    DefaultThreadFactory threadFactory = new DefaultThreadFactory(config.getThreadPoolName());
    eventLoopGroup = config.isUseNativeTransport() ? new EpollEventLoopGroup(0, threadFactory)
            : new NioEventLoopGroup(0, threadFactory);
    eventLoopPicker = new AffinityEventLoopPicker(eventLoopGroup);
    channelGroup = new DefaultChannelGroup(eventLoopGroup.next());
}

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));
    }//from w w w  .  j av a 2s.  c o  m
    if (clientCertChainFilePath != null && clientPrivateKeyFilePath != null) {
        builder.keyManager(new File(clientCertChainFilePath), new File(clientPrivateKeyFilePath));
    }
    return builder.build();
}

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 ww  w .j a  v  a2s. 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.opendevice.sonoff.SonOffServerConnection.java

License:Open Source License

private SslContext generateSSLContext() {

    //        File certFile = config.getFile("sonoff.ssl.certificateFile");
    //        if(cert == null) throw new IllegalArgumentException("Certificate not found (check sonoff.ssl.certificateFile) !");
    //        File key = config.getFile("sonoff.ssl.certificateKey");
    //        if(key == null) throw new IllegalArgumentException("Certificate key must be provided (check sonoff.ssl.certificateKey) !");

    OpenDeviceConfig config = ODev.getConfig();

    InputStream cert = null;//from w w w. j  av  a  2s.co m
    InputStream key = null;

    try {
        File certFile = config.getFile("sonoff.ssl.certificateFile");
        if (certFile != null) {
            cert = new FileInputStream(certFile);
        } else {
            log.info("Using self-signed embedded certificate ...");
            cert = getClass().getClassLoader().getResourceAsStream("ssl/cert.pem");
        }

        File keyFile = config.getFile("sonoff.ssl.certificateKey");
        if (keyFile != null) {
            key = new FileInputStream(keyFile);
        } else {
            key = getClass().getClassLoader().getResourceAsStream("ssl/key.pem");
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

    try {
        SslContextBuilder sslContextBuilder = SslContextBuilder.forServer(cert, key);
        sslContextBuilder.sslProvider(SslProvider.JDK);
        SslContext sslContext = sslContextBuilder.build();
        return sslContext;
    } catch (SSLException e) {
        e.printStackTrace();
    }

    return null;
}

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

License:Open Source License

private SslContext createContext(VertxInternal vertx) {
    try {//www  . j  a  va 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);
    }
}

From source file:io.viewserver.network.netty.tcp.NettyTcpEndpoint.java

License:Apache License

@Override
public IClient getClient(EventLoopGroup eventLoopGroup, ChannelHandler handler) {
    SslContext sslContext;// ww  w .  ja v a 2 s.  c o m
    if (this.uri.getScheme().equals("tcps")) {
        try {
            SslContextBuilder builder = SslContextBuilder.forClient();
            if (bypassCertificateChecks || usingSelfSignedCertificate) {
                builder.trustManager(InsecureTrustManagerFactory.INSTANCE);
            }
            sslContext = builder.build();
        } catch (SSLException e) {
            throw new RuntimeException(e);
        }
    } else {
        sslContext = null;
    }

    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(eventLoopGroup).channel(NioSocketChannel.class).handler(new ChannelInitializer<Channel>() {
        @Override
        protected void initChannel(Channel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();
            if (sslContext != null) {
                pipeline.addLast(sslContext.newHandler(ch.alloc(), uri.getHost(), uri.getPort()));
            }
            pipeline.addLast(handler);
        }
    });
    return () -> bootstrap.connect(uri.getHost(), uri.getPort());
}

From source file:io.viewserver.network.netty.websocket.NettyWebSocketEndpoint.java

License:Apache License

@Override
public IClient getClient(EventLoopGroup eventLoopGroup, ChannelHandler handler) {
    SslContext sslContext;/*from   ww  w.ja  v  a2 s.  co m*/
    if (this.uri.getScheme().equals("wss")) {
        try {
            SslContextBuilder builder = SslContextBuilder.forClient();
            if (bypassCertificateChecks || usingSelfSignedCertificate) {
                builder.trustManager(InsecureTrustManagerFactory.INSTANCE);
            }
            sslContext = builder.build();
        } catch (SSLException e) {
            throw new RuntimeException(e);
        }
    } else {
        sslContext = null;
    }

    Bootstrap bootstrap = new Bootstrap();
    WebSocketClientHandshaker handshaker = WebSocketClientHandshakerFactory.newHandshaker(uri,
            WebSocketVersion.V13, null, false, new DefaultHttpHeaders());
    bootstrap.group(eventLoopGroup).channel(NioSocketChannel.class).handler(new ChannelInitializer<Channel>() {
        @Override
        protected void initChannel(Channel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();
            if (sslContext != null) {
                pipeline.addLast(sslContext.newHandler(ch.alloc(), uri.getHost(), uri.getPort()));
            }
            pipeline.addLast(new HttpClientCodec());
            pipeline.addLast(new HttpObjectAggregator(1 << 30));
            pipeline.addLast("websocket", new WebSocketClientProtocolHandler(handshaker));
            pipeline.addLast(new ChannelInboundHandlerAdapter() {
                @Override
                public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
                    if (evt == WebSocketClientProtocolHandler.ClientHandshakeStateEvent.HANDSHAKE_COMPLETE) {
                        ChannelPipeline pipeline = ctx.channel().pipeline();
                        pipeline.addAfter("websocket", "ws-decoder-xx",
                                new MessageToMessageDecoder<BinaryWebSocketFrame>() {
                                    @Override
                                    protected void decode(ChannelHandlerContext ctx, BinaryWebSocketFrame msg,
                                            List<Object> out) throws Exception {
                                        out.add(msg.content().retain());
                                    }
                                });

                        pipeline.addAfter("websocket", "ws-encoder-xx", new MessageToMessageEncoder<ByteBuf>() {
                            @Override
                            protected void encode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out)
                                    throws Exception {
                                out.add(new BinaryWebSocketFrame(msg).retain());
                            }
                        });
                    }

                    super.userEventTriggered(ctx, evt);
                }
            });

            pipeline.addLast("frameDecoder", new ChannelInboundHandlerAdapter());
            pipeline.addLast("frameEncoder", new ChannelOutboundHandlerAdapter());
            pipeline.addLast(handler);
        }
    });
    return () -> bootstrap.connect(uri.getHost(), uri.getPort());
}

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 ww.j  av 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);
}