Java Code Examples for io.grpc.netty.GrpcSslContexts#configure()

The following examples show how to use io.grpc.netty.GrpcSslContexts#configure() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Http2OkHttpTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@Override
protected AbstractServerImplBuilder<?> getServerBuilder() {
  // Starts the server with HTTPS.
  try {
    SslProvider sslProvider = SslContext.defaultServerProvider();
    if (sslProvider == SslProvider.OPENSSL && !OpenSsl.isAlpnSupported()) {
      // OkHttp only supports Jetty ALPN on OpenJDK. So if OpenSSL doesn't support ALPN, then we
      // are forced to use Jetty ALPN for Netty instead of OpenSSL.
      sslProvider = SslProvider.JDK;
    }
    SslContextBuilder contextBuilder = SslContextBuilder
        .forServer(TestUtils.loadCert("server1.pem"), TestUtils.loadCert("server1.key"));
    GrpcSslContexts.configure(contextBuilder, sslProvider);
    contextBuilder.ciphers(TestUtils.preferredTestCiphers(), SupportedCipherSuiteFilter.INSTANCE);
    return NettyServerBuilder.forPort(0)
        .flowControlWindow(65 * 1024)
        .maxInboundMessageSize(AbstractInteropTest.MAX_MESSAGE_SIZE)
        .sslContext(contextBuilder.build());
  } catch (IOException ex) {
    throw new RuntimeException(ex);
  }
}
 
Example 2
Source File: LoadBalanceClusterMessageSenderWithTLSTest.java    From txle with Apache License 2.0 6 votes vote down vote up
private static SslContextBuilder getSslContextBuilder() {
  ClassLoader classLoader = LoadBalanceClusterMessageSenderWithTLSTest.class.getClassLoader();
  SslContextBuilder sslClientContextBuilder = SslContextBuilder.forServer(
      new File(classLoader.getResource("server.crt").getFile()),
      new File(classLoader.getResource("server.pem").getFile()))
      .protocols("TLSv1.2","TLSv1.1")
      .ciphers(Arrays.asList("ECDHE-RSA-AES128-GCM-SHA256",
          "ECDHE-RSA-AES256-GCM-SHA384",
          "ECDHE-ECDSA-AES128-SHA256"));

    sslClientContextBuilder.trustManager(new File(classLoader.getResource("client.crt").getFile()));
    sslClientContextBuilder.clientAuth(ClientAuth.REQUIRE);

  return GrpcSslContexts.configure(sslClientContextBuilder,
      SslProvider.OPENSSL);
}
 
Example 3
Source File: GrpcStartable.java    From txle with Apache License 2.0 6 votes vote down vote up
private SslContextBuilder getSslContextBuilder(GrpcServerConfig config) {

    Properties prop = new Properties();
    ClassLoader classLoader = getClass().getClassLoader();
    try {
      prop.load(classLoader.getResourceAsStream("ssl.properties"));
    } catch (IOException e) {
      throw new IllegalStateException("Unable to read ssl.properties.", e);
    }

    InputStream cert = getInputStream(classLoader, config.getCert(), "Server Cert");
    InputStream key = getInputStream(classLoader, config.getKey(), "Server Key");

    SslContextBuilder sslClientContextBuilder = SslContextBuilder.forServer(cert, key)
        .protocols(prop.getProperty("protocols"))
        .ciphers(Arrays.asList(prop.getProperty("ciphers").split(",")));
    if (config.isMutualAuth()) {
      InputStream clientCert = getInputStream(classLoader, config.getClientCert(), "Client Cert");
      sslClientContextBuilder.trustManager(clientCert);
      sslClientContextBuilder.clientAuth(ClientAuth.REQUIRE);
    }
    return GrpcSslContexts.configure(sslClientContextBuilder,
        SslProvider.OPENSSL);
  }
 
Example 4
Source File: GrpcStartable.java    From servicecomb-pack with Apache License 2.0 6 votes vote down vote up
private SslContextBuilder getSslContextBuilder(GrpcServerConfig config) {

    Properties prop = new Properties();
    ClassLoader classLoader = getClass().getClassLoader();
    try {
      prop.load(classLoader.getResourceAsStream("ssl.properties"));
    } catch (IOException e) {
      throw new IllegalStateException("Unable to read ssl.properties.", e);
    }

    InputStream cert = getInputStream(classLoader, config.getCert(), "Server Cert");
    InputStream key = getInputStream(classLoader, config.getKey(), "Server Key");

    SslContextBuilder sslClientContextBuilder = SslContextBuilder.forServer(cert, key)
        .protocols(prop.getProperty("protocols"))
        .ciphers(Arrays.asList(prop.getProperty("ciphers").split(",")));
    if (config.isMutualAuth()) {
      InputStream clientCert = getInputStream(classLoader, config.getClientCert(), "Client Cert");
      sslClientContextBuilder.trustManager(clientCert);
      sslClientContextBuilder.clientAuth(ClientAuth.REQUIRE);
    }
    return GrpcSslContexts.configure(sslClientContextBuilder,
        SslProvider.OPENSSL);
  }
 
Example 5
Source File: Http2OkHttpTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Override
protected AbstractServerImplBuilder<?> getServerBuilder() {
  // Starts the server with HTTPS.
  try {
    SslProvider sslProvider = SslContext.defaultServerProvider();
    if (sslProvider == SslProvider.OPENSSL && !SslProvider.isAlpnSupported(SslProvider.OPENSSL)) {
      // OkHttp only supports Jetty ALPN on OpenJDK. So if OpenSSL doesn't support ALPN, then we
      // are forced to use Jetty ALPN for Netty instead of OpenSSL.
      sslProvider = SslProvider.JDK;
    }
    SslContextBuilder contextBuilder = SslContextBuilder
        .forServer(TestUtils.loadCert("server1.pem"), TestUtils.loadCert("server1.key"));
    GrpcSslContexts.configure(contextBuilder, sslProvider);
    contextBuilder.ciphers(TestUtils.preferredTestCiphers(), SupportedCipherSuiteFilter.INSTANCE);
    return NettyServerBuilder.forPort(0)
        .flowControlWindow(65 * 1024)
        .maxInboundMessageSize(AbstractInteropTest.MAX_MESSAGE_SIZE)
        .sslContext(contextBuilder.build());
  } catch (IOException ex) {
    throw new RuntimeException(ex);
  }
}
 
Example 6
Source File: HelloWorldServerTls.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
private SslContextBuilder getSslContextBuilder() {
    SslContextBuilder sslClientContextBuilder = SslContextBuilder.forServer(new File(certChainFilePath),
            new File(privateKeyFilePath));
    if (trustCertCollectionFilePath != null) {
        sslClientContextBuilder.trustManager(new File(trustCertCollectionFilePath));
        sslClientContextBuilder.clientAuth(ClientAuth.REQUIRE);
    }
    return GrpcSslContexts.configure(sslClientContextBuilder,
            SslProvider.OPENSSL);
}
 
Example 7
Source File: SagaLoadBalanceSenderWithTLSTest.java    From servicecomb-pack with Apache License 2.0 5 votes vote down vote up
private static SslContextBuilder getSslContextBuilder() {
  ClassLoader classLoader = SagaLoadBalanceSenderWithTLSTest.class.getClassLoader();
  SslContextBuilder sslClientContextBuilder = SslContextBuilder.forServer(
      new File(classLoader.getResource("server.crt").getFile()),
      new File(classLoader.getResource("server.pem").getFile()))
      .protocols("TLSv1.2","TLSv1.1")
      .ciphers(Arrays.asList("ECDHE-RSA-AES128-GCM-SHA256",
          "ECDHE-RSA-AES256-GCM-SHA384"));

    sslClientContextBuilder.trustManager(new File(classLoader.getResource("client.crt").getFile()));
    sslClientContextBuilder.clientAuth(ClientAuth.REQUIRE);

  return GrpcSslContexts.configure(sslClientContextBuilder,
      SslProvider.OPENSSL);
}
 
Example 8
Source File: Endpoint.java    From fabric-sdk-java with Apache License 2.0 5 votes vote down vote up
SslContextBuilder getSslContextBuilder(X509Certificate[] clientCert, PrivateKey clientKey, SslProvider sslprovider) {
    SslContextBuilder clientContextBuilder = GrpcSslContexts.configure(SslContextBuilder.forClient(), sslprovider);
    if (clientKey != null && clientCert != null) {
        clientContextBuilder = clientContextBuilder.keyManager(clientKey, clientCert);
    } else {
        logger.debug(format("Endpoint %s with no ssl context", url));
    }
    return clientContextBuilder;
}
 
Example 9
Source File: TLSCertGenTest.java    From fabric-sdk-java with Apache License 2.0 5 votes vote down vote up
private SslContextBuilder getSslContextBuilder(File clientCertFile, File clientKeyFile, File serverCertFile) {
    SslProvider sslprovider = SslProvider.OPENSSL;
    SslContextBuilder ctxBuilder = SslContextBuilder.forClient().protocols(TLS_PROTOCOL).trustManager(serverCertFile);
    SslContextBuilder clientContextBuilder = GrpcSslContexts.configure(ctxBuilder, sslprovider);
    clientContextBuilder = clientContextBuilder.keyManager(clientCertFile, clientKeyFile);
    return clientContextBuilder;
}
 
Example 10
Source File: RemoteWorker.java    From bazel with Apache License 2.0 5 votes vote down vote up
private SslContextBuilder getSslContextBuilder(RemoteWorkerOptions workerOptions) {
  SslContextBuilder sslContextBuilder =
      SslContextBuilder.forServer(
          new File(workerOptions.tlsCertificate), new File(workerOptions.tlsPrivateKey));
  if (workerOptions.tlsCaCertificate != null) {
    sslContextBuilder.clientAuth(ClientAuth.REQUIRE);
    sslContextBuilder.trustManager(new File(workerOptions.tlsCaCertificate));
  }
  return GrpcSslContexts.configure(sslContextBuilder, SslProvider.OPENSSL);
}
 
Example 11
Source File: HelloWorldServerTls.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
private SslContextBuilder getSslContextBuilder() {
    SslContextBuilder sslClientContextBuilder = SslContextBuilder.forServer(new File(certChainFilePath),
            new File(privateKeyFilePath));
    if (trustCertCollectionFilePath != null) {
        sslClientContextBuilder.trustManager(new File(trustCertCollectionFilePath));
        sslClientContextBuilder.clientAuth(ClientAuth.REQUIRE);
    }
    return GrpcSslContexts.configure(sslClientContextBuilder);
}
 
Example 12
Source File: ListenGRPC.java    From nifi with Apache License 2.0 4 votes vote down vote up
@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();
    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(SslContextFactory.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();
}
 
Example 13
Source File: TestGRPCServer.java    From nifi with Apache License 2.0 4 votes vote down vote up
/**
 * Starts the gRPC server @localhost:port.
 */
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;
}
 
Example 14
Source File: TestGRPCClient.java    From nifi with Apache License 2.0 4 votes vote down vote up
/**
 * 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
 */
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();
}