List of usage examples for io.netty.handler.ssl SslContextBuilder forClient
public static SslContextBuilder forClient()
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 o m*/ 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.drill.exec.ssl.SSLConfigClient.java
License:Apache License
@Override public SslContext initNettySslContext() throws DrillException { final SslContext sslCtx; if (!userSslEnabled) { return null; }//from w w w. j a v a 2 s .co m TrustManagerFactory tmf; try { tmf = initializeTrustManagerFactory(); sslCtx = SslContextBuilder.forClient().sslProvider(getProvider()).trustManager(tmf).protocols(protocol) .build(); } catch (Exception e) { // Catch any SSL initialization Exceptions here and abort. throw new DrillException(new StringBuilder() .append("SSL is enabled but cannot be initialized due to the following exception: ") .append("[ ").append(e.getMessage()).append("]. ").toString()); } this.nettySslContext = sslCtx; return sslCtx; }
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/*w w w . ja v a 2s. com*/ */ 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.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 a v a 2 s . c o 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 w w.j a v a 2 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.apache.tinkerpop.gremlin.server.GremlinServerIntegrateTest.java
License:Apache License
@Test public void shouldEnableSslWithSslContextProgrammaticallySpecified() throws Exception { // just for testing - this is not good for production use final SslContextBuilder builder = SslContextBuilder.forClient(); builder.trustManager(InsecureTrustManagerFactory.INSTANCE); builder.sslProvider(SslProvider.JDK); final Cluster cluster = TestClientFactory.build().enableSsl(true).sslContext(builder.build()).create(); final Client client = cluster.connect(); try {//from ww w. j a v a 2s . c o m // this should return "nothing" - there should be no exception assertEquals("test", client.submit("'test'").one().getString()); } finally { cluster.close(); } }
From source file:org.asynchttpclient.netty.ssl.DefaultSslEngineFactory.java
License:Open Source License
private SslContext buildSslContext(AsyncHttpClientConfig config) throws SSLException { if (config.getSslContext() != null) return config.getSslContext(); SslContextBuilder sslContextBuilder = SslContextBuilder.forClient()// .sslProvider(config.isUseOpenSsl() ? SslProvider.OPENSSL : SslProvider.JDK)// .sessionCacheSize(config.getSslSessionCacheSize())// .sessionTimeout(config.getSslSessionTimeout()); if (config.isAcceptAnyCertificate()) sslContextBuilder.trustManager(InsecureTrustManagerFactory.INSTANCE); return configureSslContextBuilder(sslContextBuilder).build(); }
From source file:org.ballerinalang.composer.service.workspace.composerapi.WebSocketClient.java
License:Open Source License
/** * Do the handshake for the given url and return the state of the handshake. * * @return true if the handshake is done properly. * @throws URISyntaxException throws if there is an error in the URI syntax. * @throws InterruptedException throws if the connecting the server is interrupted. *///from ww w. j av a2s . com public boolean handhshake() throws InterruptedException, URISyntaxException, SSLException { boolean isDone; URI uri = new URI(url); String scheme = uri.getScheme() == null ? "ws" : uri.getScheme(); final String host = uri.getHost() == null ? "127.0.0.1" : uri.getHost(); final int port; if (uri.getPort() == -1) { if ("ws".equalsIgnoreCase(scheme)) { port = 80; } else if ("wss".equalsIgnoreCase(scheme)) { port = 443; } else { port = -1; } } else { port = uri.getPort(); } if (!"ws".equalsIgnoreCase(scheme) && !"wss".equalsIgnoreCase(scheme)) { log.error("Only WS and WSS protocols are supported."); return false; } final boolean ssl = "wss".equalsIgnoreCase(scheme); final SslContext sslCtx; if (ssl) { sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build(); } else { sslCtx = null; } group = new NioEventLoopGroup(); try { // Connect with V13 (RFC 6455 aka HyBi-17). You can change it to V08 or V00. // If you change it to V00, ping is not supported and remember to change // HttpResponseDecoder to WebSocketHttpResponseDecoder in the pipeline. handler = new WebSocketClientHandler(WebSocketClientHandshakerFactory.newHandshaker(uri, WebSocketVersion.V13, null, true, new DefaultHttpHeaders())); Bootstrap b = new Bootstrap(); b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) { ChannelPipeline p = ch.pipeline(); if (sslCtx != null) { p.addLast(sslCtx.newHandler(ch.alloc(), host, port)); } p.addLast(new HttpClientCodec(), new HttpObjectAggregator(8192), WebSocketClientCompressionHandler.INSTANCE, handler); } }); channel = b.connect(uri.getHost(), port).sync().channel(); isDone = handler.handshakeFuture().sync().isSuccess(); } catch (Exception e) { log.error("Handshake unsuccessful: " + e.getMessage(), e); return false; } log.info("WebSocket Handshake successful: " + isDone); return isDone; }
From source file:org.ballerinalang.test.util.http2.HTTP2Client.java
License:Open Source License
public HTTP2Client(boolean ssl, String host, int port) throws Exception { try {/*from ww w .j av a 2 s . c o m*/ final SslContext sslCtx; if (ssl) { SslProvider provider = OpenSsl.isAlpnSupported() ? SslProvider.OPENSSL : SslProvider.JDK; sslCtx = SslContextBuilder.forClient().sslProvider(provider) .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE) .trustManager(InsecureTrustManagerFactory.INSTANCE) .applicationProtocolConfig(new ApplicationProtocolConfig(Protocol.ALPN, // NO_ADVERTISE is currently the only mode supported by both OpenSsl and JDK providers. SelectorFailureBehavior.NO_ADVERTISE, // ACCEPT is currently the only mode supported by both OpenSsl and JDK providers. SelectedListenerFailureBehavior.ACCEPT, ApplicationProtocolNames.HTTP_2, ApplicationProtocolNames.HTTP_1_1)) .build(); } else { sslCtx = null; } workerGroup = new NioEventLoopGroup(); HTTP2ClientInitializer initializer = new HTTP2ClientInitializer(sslCtx, Integer.MAX_VALUE); // Configure the client. Bootstrap b = new Bootstrap(); b.group(workerGroup); b.channel(NioSocketChannel.class); b.option(ChannelOption.SO_KEEPALIVE, true); b.remoteAddress(host, port); b.handler(initializer); // Start the client. channel = b.connect().syncUninterruptibly().channel(); log.info("Connected to [" + host + ':' + port + ']'); // Wait for the HTTP/2 upgrade to occur. HTTP2SettingsHandler http2SettingsHandler = initializer.settingsHandler(); http2SettingsHandler.awaitSettings(TestConstant.HTTP2_RESPONSE_TIME_OUT, TestConstant.HTTP2_RESPONSE_TIME_UNIT); responseHandler = initializer.responseHandler(); scheme = ssl ? HttpScheme.HTTPS : HttpScheme.HTTP; hostName = new AsciiString(host + ':' + port); } catch (Exception ex) { log.error("Error while initializing http2 client " + ex); this.close(); } }
From source file:org.ballerinalang.test.util.websocket.client.WebSocketClient.java
License:Open Source License
/** * @return true if the handshake is done properly. * @throws URISyntaxException throws if there is an error in the URI syntax. * @throws InterruptedException throws if the connecting the server is interrupted. *//*from w ww . j a va 2 s . c o m*/ public boolean handhshake() throws InterruptedException, URISyntaxException, SSLException { boolean isDone = false; URI uri = new URI(url); String scheme = uri.getScheme() == null ? "ws" : uri.getScheme(); final String host = uri.getHost() == null ? "127.0.0.1" : uri.getHost(); final int port; if (uri.getPort() == -1) { if ("ws".equalsIgnoreCase(scheme)) { port = 80; } else if ("wss".equalsIgnoreCase(scheme)) { port = 443; } else { port = -1; } } else { port = uri.getPort(); } if (!"ws".equalsIgnoreCase(scheme) && !"wss".equalsIgnoreCase(scheme)) { logger.error("Only WS(S) is supported."); return false; } final boolean ssl = "wss".equalsIgnoreCase(scheme); final SslContext sslCtx; if (ssl) { sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build(); } else { sslCtx = null; } group = new NioEventLoopGroup(); DefaultHttpHeaders httpHeaders = new DefaultHttpHeaders(); headers.entrySet().forEach(header -> { httpHeaders.add(header.getKey(), header.getValue()); }); try { // Connect with V13 (RFC 6455 aka HyBi-17). You can change it to V08 or V00. // If you change it to V00, ping is not supported and remember to change // HttpResponseDecoder to WebSocketHttpResponseDecoder in the pipeline. handler = new WebSocketClientHandler(WebSocketClientHandshakerFactory.newHandshaker(uri, WebSocketVersion.V13, null, true, httpHeaders)); Bootstrap b = new Bootstrap(); b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) { ChannelPipeline p = ch.pipeline(); if (sslCtx != null) { p.addLast(sslCtx.newHandler(ch.alloc(), host, port)); } p.addLast(new HttpClientCodec(), new HttpObjectAggregator(8192), WebSocketClientCompressionHandler.INSTANCE, handler); } }); channel = b.connect(uri.getHost(), port).sync().channel(); isDone = handler.handshakeFuture().sync().isSuccess(); } catch (Exception e) { logger.error("Handshake unsuccessful : " + e.getMessage(), e); return false; } logger.info("WebSocket Handshake successful : " + isDone); return isDone; }