io.grpc.netty.GrpcSslContexts Java Examples

The following examples show how to use io.grpc.netty.GrpcSslContexts. 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: ConduitServer.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
@Override
public void start() throws Exception {
  final ConduitServiceRegistryImpl registry = (ConduitServiceRegistryImpl) registryProvider.get();

  for (BindableService service : registry.getServiceList()) {
    serverBuilder.addService(service);
  }

  for (CloseableBindableService closeableService : registry.getCloseableServiceList()) {
    serverBuilder.addService(closeableService);
    closeableServices.add(closeableService);
  }

  serverBuilder.maxInboundMetadataSize(Integer.MAX_VALUE).maxInboundMessageSize(Integer.MAX_VALUE)
    .intercept(TransmitStatusRuntimeExceptionInterceptor.instance());

  if (sslEngineFactory.isPresent()) {
    final SslContextBuilder contextBuilder = sslEngineFactory.get().newServerContextBuilder();
    // add gRPC overrides using #configure
    serverBuilder.sslContext(GrpcSslContexts.configure(contextBuilder).build());
  }
  server = serverBuilder.build();
  server.start();

  logger.info("ConduitServer is up. Listening on port '{}'", server.getPort());
}
 
Example #2
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 #3
Source File: Http2NettyTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@Override
protected ManagedChannel createChannel() {
  try {
    NettyChannelBuilder builder = NettyChannelBuilder
        .forAddress(TestUtils.testServerAddress(getPort()))
        .flowControlWindow(65 * 1024)
        .maxInboundMessageSize(AbstractInteropTest.MAX_MESSAGE_SIZE)
        .sslContext(GrpcSslContexts
            .forClient()
            .keyManager(TestUtils.loadCert("client.pem"), TestUtils.loadCert("client.key"))
            .trustManager(TestUtils.loadX509Cert("ca.pem"))
            .ciphers(TestUtils.preferredTestCiphers(), SupportedCipherSuiteFilter.INSTANCE)
            .build());
    io.grpc.internal.TestingAccessor.setStatsImplementation(
        builder, createClientCensusStatsModule());
    return builder.build();
  } catch (Exception ex) {
    throw new RuntimeException(ex);
  }
}
 
Example #4
Source File: Http2NettyTest.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 {
    return NettyServerBuilder.forPort(0)
        .flowControlWindow(65 * 1024)
        .maxInboundMessageSize(AbstractInteropTest.MAX_MESSAGE_SIZE)
        .sslContext(GrpcSslContexts
            .forServer(TestUtils.loadCert("server1.pem"), TestUtils.loadCert("server1.key"))
            .clientAuth(ClientAuth.REQUIRE)
            .trustManager(TestUtils.loadCert("ca.pem"))
            .ciphers(TestUtils.preferredTestCiphers(), SupportedCipherSuiteFilter.INSTANCE)
            .build());
  } catch (IOException ex) {
    throw new RuntimeException(ex);
  }
}
 
Example #5
Source File: LoadBalancedClusterMessageSender.java    From txle with Apache License 2.0 6 votes vote down vote up
private static SslContext buildSslContext(AlphaClusterConfig clusterConfig) throws SSLException {
  SslContextBuilder builder = GrpcSslContexts.forClient();
  // openssl must be used because some older JDk does not support cipher suites required by http2,
  // and the performance of JDK ssl is pretty low compared to openssl.
  builder.sslProvider(SslProvider.OPENSSL);

  Properties prop = new Properties();
  try {
    prop.load(LoadBalancedClusterMessageSender.class.getClassLoader().getResourceAsStream("ssl.properties"));
  } catch (IOException e) {
    throw new IllegalArgumentException("Unable to read ssl.properties.", e);
  }

  builder.protocols(prop.getProperty("protocols").split(","));
  builder.ciphers(Arrays.asList(prop.getProperty("ciphers").split(",")));
  builder.trustManager(new File(clusterConfig.getCertChain()));

  if (clusterConfig.isEnableMutualAuth()) {
    builder.keyManager(new File(clusterConfig.getCert()), new File(clusterConfig.getKey()));
  }

  return builder.build();
}
 
Example #6
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 #7
Source File: ConcurrencyTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
private ManagedChannel newClientChannel() throws CertificateException, IOException {
  File clientCertChainFile = TestUtils.loadCert("client.pem");
  File clientPrivateKeyFile = TestUtils.loadCert("client.key");
  X509Certificate[] clientTrustedCaCerts = {
    TestUtils.loadX509Cert("ca.pem")
  };

  SslContext sslContext =
      GrpcSslContexts.forClient()
                     .keyManager(clientCertChainFile, clientPrivateKeyFile)
                     .trustManager(clientTrustedCaCerts)
                     .build();

  return NettyChannelBuilder.forAddress("localhost", server.getPort())
      .overrideAuthority(TestUtils.TEST_SERVER_HOST)
      .negotiationType(NegotiationType.TLS)
      .sslContext(sslContext)
      .build();
}
 
Example #8
Source File: ConcurrencyTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
/**
 * Creates and starts a new {@link TestServiceImpl} server.
 */
private Server newServer() throws CertificateException, IOException {
  File serverCertChainFile = TestUtils.loadCert("server1.pem");
  File serverPrivateKeyFile = TestUtils.loadCert("server1.key");
  X509Certificate[] serverTrustedCaCerts = {
    TestUtils.loadX509Cert("ca.pem")
  };

  SslContext sslContext =
      GrpcSslContexts.forServer(serverCertChainFile, serverPrivateKeyFile)
                     .trustManager(serverTrustedCaCerts)
                     .clientAuth(ClientAuth.REQUIRE)
                     .build();

  return NettyServerBuilder.forPort(0)
      .sslContext(sslContext)
      .addService(new TestServiceImpl(serverExecutor))
      .build()
      .start();
}
 
Example #9
Source File: Http2NettyTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Override
protected ManagedChannel createChannel() {
  try {
    NettyChannelBuilder builder = NettyChannelBuilder
        .forAddress(TestUtils.testServerAddress((InetSocketAddress) getListenAddress()))
        .flowControlWindow(65 * 1024)
        .maxInboundMessageSize(AbstractInteropTest.MAX_MESSAGE_SIZE)
        .sslContext(GrpcSslContexts
            .forClient()
            .keyManager(TestUtils.loadCert("client.pem"), TestUtils.loadCert("client.key"))
            .trustManager(TestUtils.loadX509Cert("ca.pem"))
            .ciphers(TestUtils.preferredTestCiphers(), SupportedCipherSuiteFilter.INSTANCE)
            .build());
    // Disable the default census stats interceptor, use testing interceptor instead.
    io.grpc.internal.TestingAccessor.setStatsEnabled(builder, false);
    return builder.intercept(createCensusStatsClientInterceptor()).build();
  } catch (Exception ex) {
    throw new RuntimeException(ex);
  }
}
 
Example #10
Source File: ComputeEngineChannelBuilder.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
private ComputeEngineChannelBuilder(String target) {
  delegate = NettyChannelBuilder.forTarget(target);
  SslContext sslContext;
  try {
    sslContext = GrpcSslContexts.forClient().build();
  } catch (SSLException e) {
    throw new RuntimeException(e);
  }
  InternalNettyChannelBuilder.setProtocolNegotiatorFactory(
      delegate(),
      new GoogleDefaultProtocolNegotiatorFactory(
          /* targetServiceAccounts= */ ImmutableList.<String>of(),
          SharedResourcePool.forResource(HandshakerServiceChannel.SHARED_HANDSHAKER_CHANNEL),
          sslContext));
  CallCredentials credentials = MoreCallCredentials.from(ComputeEngineCredentials.create());
  Status status = Status.OK;
  if (!CheckGcpEnvironment.isOnGcp()) {
    status =
        Status.INTERNAL.withDescription(
            "Compute Engine Credentials can only be used on Google Cloud Platform");
  }
  delegate().intercept(new CallCredentialsInterceptor(credentials, status));
}
 
Example #11
Source File: HelloWorldClientTls.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
private static SslContext buildSslContext(String trustCertCollectionFilePath,
                                          String clientCertChainFilePath,
                                          String clientPrivateKeyFilePath) throws SSLException {
    SslContextBuilder builder = GrpcSslContexts.forClient();
    if (trustCertCollectionFilePath != null) {
        builder.trustManager(new File(trustCertCollectionFilePath));
    }
    if (clientCertChainFilePath != null && clientPrivateKeyFilePath != null) {
        builder.keyManager(new File(clientCertChainFilePath), new File(clientPrivateKeyFilePath));
    }
    return builder.build();
}
 
Example #12
Source File: ConcurrencyTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
private ManagedChannel newClientChannel() throws CertificateException, IOException {
  File clientCertChainFile = TestUtils.loadCert("client.pem");
  File clientPrivateKeyFile = TestUtils.loadCert("client.key");
  X509Certificate[] clientTrustedCaCerts = {
    TestUtils.loadX509Cert("ca.pem")
  };

  SslContext sslContext =
      GrpcSslContexts.forClient()
                     .keyManager(clientCertChainFile, clientPrivateKeyFile)
                     .trustManager(clientTrustedCaCerts)
                     .build();

  return NettyChannelBuilder.forAddress("localhost", server.getPort())
      .overrideAuthority(TestUtils.TEST_SERVER_HOST)
      .negotiationType(NegotiationType.TLS)
      .sslContext(sslContext)
      .build();
}
 
Example #13
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 #14
Source File: BaseIT.java    From kafka-pubsub-emulator with Apache License 2.0 6 votes vote down vote up
public static TransportChannelProvider getChannelProvider() {
  ManagedChannel channel = null;
  if (USE_SSL) {
    try {
      channel =
          NettyChannelBuilder.forAddress(LOCALHOST, PORT)
              .maxInboundMessageSize(100000)
              .sslContext(
                  GrpcSslContexts.forClient()
                      .trustManager(InsecureTrustManagerFactory.INSTANCE)
                      .build())
              .overrideAuthority(LOCALHOST + ":" + PORT)
              .build();
    } catch (SSLException e) {
      fail("Unable to create SSL channel " + e.getMessage());
    }
  } else {
    channel = ManagedChannelBuilder.forAddress(LOCALHOST, PORT).usePlaintext(true).build();
  }
  return FixedTransportChannelProvider.create(GrpcTransportChannel.create(channel));
}
 
Example #15
Source File: GrpcServerTestBase.java    From grpc-spring-boot-starter with Apache License 2.0 6 votes vote down vote up
@Before
public final void setupChannels() throws IOException {
    if(gRpcServerProperties.isEnabled()) {
        ManagedChannelBuilder<?> channelBuilder = ManagedChannelBuilder.forAddress("localhost", getPort());
        Resource certChain = Optional.ofNullable(gRpcServerProperties.getSecurity())
                .map(GRpcServerProperties.SecurityProperties::getCertChain)
                .orElse(null);
        if(null!= certChain){
            ((NettyChannelBuilder)channelBuilder)
                    .useTransportSecurity()
                    .sslContext(GrpcSslContexts.forClient().trustManager(certChain.getInputStream()).build());
        }else{
            channelBuilder.usePlaintext();
        }


        channel = onChannelBuild(channelBuilder).build();
    }
    if(StringUtils.hasText(gRpcServerProperties.getInProcessServerName())){
        inProcChannel = onChannelBuild(
                            InProcessChannelBuilder.forName(gRpcServerProperties.getInProcessServerName())
                            .usePlaintext()
                        ).build();

    }
}
 
Example #16
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 #17
Source File: KMSEncryptionProvider.java    From credhub with Apache License 2.0 6 votes vote down vote up
public KMSEncryptionProvider(final EncryptionConfiguration configuration) {
  super();

  setChannelInfo();

  SslContext sslContext;
  try {
    sslContext = GrpcSslContexts.forClient()
      .trustManager(new ByteArrayInputStream(configuration.getCa().getBytes(UTF_8)))
      .build();
  } catch (SSLException e) {
    throw new RuntimeException(e);
  }

  blockingStub = KeyManagementServiceGrpc.newBlockingStub(
    NettyChannelBuilder.forAddress(new DomainSocketAddress(configuration.getEndpoint()))
      .eventLoopGroup(group)
      .channelType(channelType)
      .keepAliveTime(DEFAULT_KEEPALIVE_TIMEOUT_NANOS, TimeUnit.NANOSECONDS)
      .useTransportSecurity()
      .sslContext(sslContext)
      .overrideAuthority(configuration.getHost())
      .build());
}
 
Example #18
Source File: CertGen.java    From snowblossom with Apache License 2.0 6 votes vote down vote up
public static SslContext getServerSSLContext(WalletDatabase db)
  throws Exception
{
  if (db.getKeysCount() != 1) throw new RuntimeException("Unexpected number of keys in wallet db");
  if (db.getAddressesCount() != 1) throw new RuntimeException("Unexpected number of addresses in wallet db");
  WalletKeyPair wkp = db.getKeys(0);
  AddressSpec address_spec = db.getAddresses(0);
  
  WalletKeyPair tls_wkp = KeyUtil.generateWalletRSAKey(2048);
  KeyPair tls_pair = KeyUtil.decodeKeypair(tls_wkp);

  X509Certificate cert = generateSelfSignedCert(wkp, tls_wkp, address_spec);
  //System.out.println(cert);

  ByteString pem_cert = pemCodeCert(cert);
  ByteString pem_prv = pemCodeECPrivateKey(tls_pair.getPrivate());

  return GrpcSslContexts.forServer(pem_cert.newInput(), pem_prv.newInput()).build();
}
 
Example #19
Source File: Client.java    From startup-os with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
  Flags.parseCurrentPackage(args);

  SslContext sslContext =
      GrpcSslContexts.forClient().trustManager(new File(certificateFile.get())).build();
  ManagedChannel channel =
      NettyChannelBuilder.forAddress("localhost", GRPC_PORT).sslContext(sslContext).build();

  GrpcAuthTestGrpc.GrpcAuthTestBlockingStub stub =
      GrpcAuthTestGrpc.newBlockingStub(channel)
          .withInterceptors(new ClientAuthInterceptor(token.get()));

  logger.at(Level.INFO).log("Calling server to increment %d", n.get());
  Protos.Response resp =
      stub.getNextNumber(Protos.Request.newBuilder().setNumber(n.get()).build());
  logger.at(Level.INFO).log("Got %d in response", resp.getNumber());
}
 
Example #20
Source File: BaseIT.java    From kafka-pubsub-emulator with Apache License 2.0 6 votes vote down vote up
public static AdminGrpc.AdminBlockingStub getAdminStub() {
  ManagedChannel channel = null;
  if (USE_SSL) {
    File certificate =
        new File(configurationRepository.getServer().getSecurity().getCertificateChainFile());
    try {
      channel =
          NettyChannelBuilder.forAddress(LOCALHOST, PORT)
              .maxInboundMessageSize(100000)
              .sslContext(GrpcSslContexts.forClient().trustManager(certificate).build())
              .build();
    } catch (SSLException e) {
      fail("Unable to create SSL channel " + e.getMessage());
    }
  } else {
    channel = ManagedChannelBuilder.forAddress(LOCALHOST, PORT).usePlaintext(true).build();
  }
  return AdminGrpc.newBlockingStub(channel);
}
 
Example #21
Source File: SmartContractBase.java    From julongchain with Apache License 2.0 6 votes vote down vote up
public ManagedChannel newPeerClientConnection() {
	final NettyChannelBuilder builder =
			NettyChannelBuilder.forAddress(host, port).maxInboundMessageSize(CommConstant.MAX_GRPC_MESSAGE_SIZE);
	logger.info("Configuring channel connection to peer.");

	if (tlsEnabled) {
		logger.info("TLS is enabled");
		try {
			final SslContext sslContext =
					GrpcSslContexts.forClient().trustManager(new File(this.rootCertFile)).build();
			builder.negotiationType(NegotiationType.TLS);
			if (!hostOverrideAuthority.equals("")) {
				logger.info("Host override " + hostOverrideAuthority);
				builder.overrideAuthority(hostOverrideAuthority);
			}
			builder.sslContext(sslContext);
			logger.info("TLS context built: " + sslContext);
		} catch (SSLException e) {
			logger.error("failed connect to peer with SSLException", e);
		}
	} else {
		builder.usePlaintext();
	}
	return builder.build();
}
 
Example #22
Source File: ConcurrencyTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
/**
 * Creates and starts a new {@link TestServiceImpl} server.
 */
private Server newServer() throws CertificateException, IOException {
  File serverCertChainFile = TestUtils.loadCert("server1.pem");
  File serverPrivateKeyFile = TestUtils.loadCert("server1.key");
  X509Certificate[] serverTrustedCaCerts = {
    TestUtils.loadX509Cert("ca.pem")
  };

  SslContext sslContext =
      GrpcSslContexts.forServer(serverCertChainFile, serverPrivateKeyFile)
                     .trustManager(serverTrustedCaCerts)
                     .clientAuth(ClientAuth.REQUIRE)
                     .build();

  return NettyServerBuilder.forPort(0)
      .sslContext(sslContext)
      .addService(new TestServiceImpl(serverExecutor))
      .build()
      .start();
}
 
Example #23
Source File: AlphaIntegrationWithSSLTest.java    From txle with Apache License 2.0 6 votes vote down vote up
private static SslContext getSslContext(){
  ClassLoader classLoader = AlphaIntegrationWithSSLTest.class.getClassLoader();
  SslContext sslContext = null;
  try {
    sslContext = GrpcSslContexts.forClient().sslProvider(SslProvider.OPENSSL)
        .protocols("TLSv1.2","TLSv1.1")
        .ciphers(Arrays.asList("ECDHE-RSA-AES128-GCM-SHA256",
            "ECDHE-RSA-AES256-GCM-SHA384",
            "ECDHE-ECDSA-AES128-SHA256"))
        .trustManager(new File(classLoader.getResource("ca.crt").getFile()))
        .keyManager(new File(classLoader.getResource("client.crt").getFile()),
            new File(classLoader.getResource("client.pem").getFile())).build();
  } catch (SSLException e) {
    e.printStackTrace();
  }
  return sslContext;
}
 
Example #24
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 #25
Source File: Utils.java    From dropwizard-grpc with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a <code>ManagedChannel</code> connecting to an <b>encrypted</b> gRPC server in
 * <code>TestApplication</code> in <code>testSupport</code>. The certificate is taken from the
 * <code>GrpcServerFactory</code> in the configuration.
 *
 * @param testSupport the already initialised (started) <code>DropwizardTestSupport</code> instance
 * @return the channel connecting to the server (to be used in a client)
 */
public static ManagedChannel createClientChannelForEncryptedServer(
        final DropwizardTestSupport<TestConfiguration> testSupport) throws SSLException {
    final SslContext sslContext = GrpcSslContexts.forClient()
        .trustManager(testSupport.getConfiguration().getGrpcServerFactory().getCertChainFile().toFile()).build();
    final TestApplication application = testSupport.getApplication();
    return NettyChannelBuilder.forAddress("localhost", application.getServer().getPort()).sslContext(sslContext)
        .overrideAuthority("grpc-dropwizard.example.com").build();
}
 
Example #26
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 #27
Source File: RemoteClientManager.java    From skywalking with Apache License 2.0 5 votes vote down vote up
/**
 * Initial the manager for all remote communication clients.
 * @param moduleDefineHolder for looking up other modules
 * @param remoteTimeout      for cluster internal communication, in second unit.
 * @param trustedCAFile         SslContext to verify server certificates.
 */
public RemoteClientManager(ModuleDefineHolder moduleDefineHolder,
                           int remoteTimeout,
                           File trustedCAFile) {
    this(moduleDefineHolder, remoteTimeout);
    try {
        sslContext = GrpcSslContexts.forClient().trustManager(trustedCAFile).build();
    } catch (SSLException e) {
        throw new IllegalArgumentException(e);
    }
}
 
Example #28
Source File: GRPCServer.java    From skywalking with Apache License 2.0 5 votes vote down vote up
@Override
public void start() throws ServerException {
    try {
        if (sslContextBuilder != null) {
            nettyServerBuilder = nettyServerBuilder.sslContext(GrpcSslContexts.configure(sslContextBuilder, SslProvider.OPENSSL)
                                                                              .build());
        }
        server = nettyServerBuilder.build();
        server.start();
    } catch (IOException e) {
        throw new GRPCServerException(e.getMessage(), e);
    }
}
 
Example #29
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 #30
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;
}