List of usage examples for io.netty.handler.ssl SslContextBuilder trustManager
public SslContextBuilder trustManager(TrustManager trustManager)
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 w ww.j a v a2s . c o 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 www . j a v a2 s . c o m*/ 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.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 av a 2 s . co 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 om*/ 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 w ww . j a v a 2s .co 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.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.jooby.internal.netty.NettySslContext.java
License:Apache License
static SslContext build(final Config conf) throws IOException, CertificateException { String tmpdir = conf.getString("application.tmpdir"); boolean http2 = conf.getBoolean("server.http2.enabled"); File keyStoreCert = toFile(conf.getString("ssl.keystore.cert"), tmpdir); File keyStoreKey = toFile(conf.getString("ssl.keystore.key"), tmpdir); String keyStorePass = conf.hasPath("ssl.keystore.password") ? conf.getString("ssl.keystore.password") : null;/*w w w .j a va 2s . c o m*/ SslContextBuilder scb = SslContextBuilder.forServer(keyStoreCert, keyStoreKey, keyStorePass); if (conf.hasPath("ssl.trust.cert")) { scb.trustManager(toFile(conf.getString("ssl.trust.cert"), tmpdir)); } if (http2) { SslProvider provider = OpenSsl.isAlpnSupported() ? SslProvider.OPENSSL : SslProvider.JDK; return scb.sslProvider(provider).ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE) .applicationProtocolConfig(new ApplicationProtocolConfig(Protocol.ALPN, SelectorFailureBehavior.NO_ADVERTISE, SelectedListenerFailureBehavior.ACCEPT, Arrays.asList(ApplicationProtocolNames.HTTP_2, ApplicationProtocolNames.HTTP_1_1))) .build(); } return scb.build(); }
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); }//from ww w. java 2 s .c om // 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()); } }
From source file:org.redisson.client.handler.RedisChannelInitializer.java
License:Apache License
private void initSsl(final RedisClientConfig config, Channel ch) throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException, SSLException, UnrecoverableKeyException { if (!config.getAddress().isSsl()) { return;//from www . j a va 2 s.c o m } io.netty.handler.ssl.SslProvider provided = io.netty.handler.ssl.SslProvider.JDK; if (config.getSslProvider() == SslProvider.OPENSSL) { provided = io.netty.handler.ssl.SslProvider.OPENSSL; } SslContextBuilder sslContextBuilder = SslContextBuilder.forClient().sslProvider(provided); if (config.getSslTruststore() != null) { KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); InputStream stream = config.getSslTruststore().openStream(); try { char[] password = null; if (config.getSslTruststorePassword() != null) { password = config.getSslTruststorePassword().toCharArray(); } keyStore.load(stream, password); } finally { stream.close(); } TrustManagerFactory trustManagerFactory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(keyStore); sslContextBuilder.trustManager(trustManagerFactory); } if (config.getSslKeystore() != null) { KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); InputStream stream = config.getSslKeystore().openStream(); char[] password = null; if (config.getSslKeystorePassword() != null) { password = config.getSslKeystorePassword().toCharArray(); } try { keyStore.load(stream, password); } finally { stream.close(); } KeyManagerFactory keyManagerFactory = KeyManagerFactory .getInstance(KeyManagerFactory.getDefaultAlgorithm()); keyManagerFactory.init(keyStore, password); sslContextBuilder.keyManager(keyManagerFactory); } SSLParameters sslParams = new SSLParameters(); if (config.isSslEnableEndpointIdentification()) { // TODO remove for JDK 1.7+ try { Method method = sslParams.getClass().getDeclaredMethod("setEndpointIdentificationAlgorithm", String.class); method.invoke(sslParams, "HTTPS"); } catch (Exception e) { throw new SSLException(e); } } else { if (config.getSslTruststore() == null) { sslContextBuilder.trustManager(InsecureTrustManagerFactory.INSTANCE); } } SslContext sslContext = sslContextBuilder.build(); String hostname = config.getSslHostname(); if (hostname == null || NetUtil.createByteArrayFromIpAddressString(hostname) != null) { hostname = config.getAddress().getHost(); } SSLEngine sslEngine = sslContext.newEngine(ch.alloc(), hostname, config.getAddress().getPort()); sslEngine.setSSLParameters(sslParams); SslHandler sslHandler = new SslHandler(sslEngine); ch.pipeline().addLast(sslHandler); ch.pipeline().addLast(new ChannelInboundHandlerAdapter() { volatile boolean sslInitDone; @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { if (sslInitDone) { super.channelActive(ctx); } } @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { if (!sslInitDone && (evt instanceof SslHandshakeCompletionEvent)) { SslHandshakeCompletionEvent e = (SslHandshakeCompletionEvent) evt; if (e.isSuccess()) { sslInitDone = true; ctx.fireChannelActive(); } else { RedisConnection connection = RedisConnection.getFrom(ctx.channel()); connection.getConnectionPromise().tryFailure(e.cause()); } } super.userEventTriggered(ctx, evt); } }); }