List of usage examples for io.netty.handler.ssl SslContextBuilder build
public SslContext build() throws SSLException
From source file:org.apache.nifi.processors.grpc.ListenGRPC.java
License:Apache License
@OnScheduled public void startServer(final ProcessContext context) throws NoSuchAlgorithmException, IOException, KeyStoreException, CertificateException, UnrecoverableKeyException { final ComponentLog logger = getLogger(); // gather configured properties final Integer port = context.getProperty(PROP_SERVICE_PORT).asInteger(); final Boolean useSecure = context.getProperty(PROP_USE_SECURE).asBoolean(); final Integer flowControlWindow = context.getProperty(PROP_FLOW_CONTROL_WINDOW).asDataSize(DataUnit.B) .intValue();//from w w w . ja v a 2 s .c o m final Integer maxMessageSize = context.getProperty(PROP_MAX_MESSAGE_SIZE).asDataSize(DataUnit.B).intValue(); final SSLContextService sslContextService = context.getProperty(PROP_SSL_CONTEXT_SERVICE) .asControllerService(SSLContextService.class); final SSLContext sslContext = sslContextService == null ? null : sslContextService.createSSLContext(SSLContextService.ClientAuth.NONE); final Pattern authorizedDnPattern = Pattern .compile(context.getProperty(PROP_AUTHORIZED_DN_PATTERN).getValue()); final FlowFileIngestServiceInterceptor callInterceptor = new FlowFileIngestServiceInterceptor(getLogger()); callInterceptor.enforceDNPattern(authorizedDnPattern); final FlowFileIngestService flowFileIngestService = new FlowFileIngestService(getLogger(), sessionFactoryReference, context); NettyServerBuilder serverBuilder = NettyServerBuilder.forPort(port) .addService(ServerInterceptors.intercept(flowFileIngestService, callInterceptor)) // default (de)compressor registries handle both plaintext and gzip compressed messages .compressorRegistry(CompressorRegistry.getDefaultInstance()) .decompressorRegistry(DecompressorRegistry.getDefaultInstance()) .flowControlWindow(flowControlWindow).maxMessageSize(maxMessageSize); if (useSecure && sslContext != null) { // construct key manager if (StringUtils.isBlank(sslContextService.getKeyStoreFile())) { throw new IllegalStateException( "SSL is enabled, but no keystore has been configured. You must configure a keystore."); } final KeyManagerFactory keyManagerFactory = KeyManagerFactory .getInstance(KeyManagerFactory.getDefaultAlgorithm(), sslContext.getProvider()); final KeyStore keyStore = KeyStore.getInstance(sslContextService.getKeyStoreType()); try (final InputStream is = new FileInputStream(sslContextService.getKeyStoreFile())) { keyStore.load(is, sslContextService.getKeyStorePassword().toCharArray()); } keyManagerFactory.init(keyStore, sslContextService.getKeyStorePassword().toCharArray()); SslContextBuilder sslContextBuilder = SslContextBuilder.forServer(keyManagerFactory); // if the trust store is configured, then client auth is required. if (StringUtils.isNotBlank(sslContextService.getTrustStoreFile())) { final TrustManagerFactory trustManagerFactory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm(), sslContext.getProvider()); final KeyStore trustStore = KeyStore.getInstance(sslContextService.getTrustStoreType()); try (final InputStream is = new FileInputStream(sslContextService.getTrustStoreFile())) { trustStore.load(is, sslContextService.getTrustStorePassword().toCharArray()); } trustManagerFactory.init(trustStore); sslContextBuilder = sslContextBuilder.trustManager(trustManagerFactory); sslContextBuilder = sslContextBuilder.clientAuth(ClientAuth.REQUIRE); } else { sslContextBuilder = sslContextBuilder.clientAuth(ClientAuth.NONE); } sslContextBuilder = GrpcSslContexts.configure(sslContextBuilder); serverBuilder = serverBuilder.sslContext(sslContextBuilder.build()); } logger.info("Starting gRPC server on port: {}", new Object[] { port.toString() }); this.server = serverBuilder.build().start(); }
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 w w. j ava 2 s . c om*/ */ 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. *///w w w .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 a va 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 . com 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.AbstractChannelizer.java
License:Apache License
private SslContext createSSLContext(final Settings settings) { final Settings.SslSettings sslSettings = settings.ssl; if (sslSettings.getSslContext().isPresent()) { logger.info("Using the SslContext override"); return sslSettings.getSslContext().get(); }/*from ww w .j a v a 2 s . c o m*/ final SslProvider provider = SslProvider.JDK; final SslContextBuilder builder; // if the config doesn't contain a cert or key then use a self signed cert - not suitable for production if (null == sslSettings.keyCertChainFile || null == sslSettings.keyFile) { try { logger.warn("Enabling SSL with self-signed certificate (NOT SUITABLE FOR PRODUCTION)"); final SelfSignedCertificate ssc = new SelfSignedCertificate(); builder = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()); } catch (CertificateException ce) { logger.error("There was an error creating the self-signed certificate for SSL - SSL is not enabled", ce); return null; } } else { final File keyCertChainFile = new File(sslSettings.keyCertChainFile); final File keyFile = new File(sslSettings.keyFile); final File trustCertChainFile = null == sslSettings.trustCertChainFile ? null : new File(sslSettings.trustCertChainFile); // note that keyPassword may be null here if the keyFile is not password-protected. passing null to // trustManager is also ok (default will be used) builder = SslContextBuilder.forServer(keyCertChainFile, keyFile, sslSettings.keyPassword) .trustManager(trustCertChainFile); } builder.sslProvider(provider); try { return builder.build(); } catch (SSLException ssle) { logger.error("There was an error enabling SSL", ssle); return null; } }
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 . java 2s.com*/ // this should return "nothing" - there should be no exception assertEquals("test", client.submit("'test'").one().getString()); } finally { cluster.close(); } }
From source file:org.conscrypt.OpenJdkEngineFactoryConfig.java
License:Apache License
private static SslContext newNettyClientContext(io.netty.handler.ssl.SslProvider sslProvider, boolean useAlpn) { try {//from w w w . j a v a 2s. c om TestKeyStore server = TestKeyStore.getServer(); SslContextBuilder ctx = SslContextBuilder.forClient().sslProvider(sslProvider) .trustManager((X509Certificate[]) server.getPrivateKey("RSA", "RSA").getCertificateChain()); if (useAlpn) { ctx.applicationProtocolConfig(OpenJdkEngineFactoryConfig.NETTY_ALPN_CONFIG); } return ctx.build(); } catch (SSLException e) { throw new RuntimeException(e); } }
From source file:org.conscrypt.OpenJdkEngineFactoryConfig.java
License:Apache License
private static SslContext newNettyServerContext(io.netty.handler.ssl.SslProvider sslProvider, boolean useAlpn) { try {// w w w . j ava 2s. com PrivateKeyEntry server = TestKeyStore.getServer().getPrivateKey("RSA", "RSA"); SslContextBuilder ctx = SslContextBuilder .forServer(server.getPrivateKey(), (X509Certificate[]) server.getCertificateChain()) .sslProvider(sslProvider); if (useAlpn) { ctx.applicationProtocolConfig(OpenJdkEngineFactoryConfig.NETTY_ALPN_CONFIG); } return ctx.build(); } catch (SSLException e) { throw new RuntimeException(e); } }
From source file:org.conscrypt.testing.TestUtil.java
License:Apache License
public static SslContext newNettyClientContext(String cipher) { try {//from www . j a va2s . com TestKeyStore server = TestKeyStore.getServer(); SslContextBuilder ctx = SslContextBuilder.forClient() .sslProvider(io.netty.handler.ssl.SslProvider.OPENSSL) .trustManager((X509Certificate[]) server.getPrivateKey("RSA", "RSA").getCertificateChain()); if (cipher != null) { ctx.ciphers(Collections.singletonList(cipher)); } return ctx.build(); } catch (SSLException e) { throw new RuntimeException(e); } }