Java Code Examples for io.netty.handler.ssl.SslContextBuilder#clientAuth()

The following examples show how to use io.netty.handler.ssl.SslContextBuilder#clientAuth() . 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: RPCBootstrap.java    From WeCross with Apache License 2.0 6 votes vote down vote up
/**
 * init SslContext for http server
 *
 * @param caCrt
 * @param nodeCrt
 * @param nodeKey
 * @return
 * @throws IOException
 */
public SslContext initSslContextForServer(
        org.springframework.core.io.Resource caCrt,
        org.springframework.core.io.Resource nodeCrt,
        org.springframework.core.io.Resource nodeKey,
        int sslSwitch)
        throws IOException {

    SslContextBuilder sslContextBuilder =
            SslContextBuilder.forServer(nodeCrt.getInputStream(), nodeKey.getInputStream())
                    .trustManager(caCrt.getInputStream())
                    .sslProvider(SslProvider.JDK);

    if (sslSwitch == RPCConfig.SSLSwitch.SSL_ON_CLIENT_AUTH.getSwh()) {
        logger.info(" clientAuth ");
        sslContextBuilder.clientAuth(ClientAuth.REQUIRE);
    }

    return sslContextBuilder.build();
}
 
Example 2
Source File: SslContextFactory.java    From xio with Apache License 2.0 6 votes vote down vote up
public static SslContext buildServerContext(
    TlsConfig config, TrustManagerFactory trustManager, @Nullable ClientAuth clientAuth) {
  try {
    SslContextBuilder builder =
        configure(config, newServerBuilder(config))
            .trustManager(new XioTrustManagerFactory(trustManager));

    if (clientAuth != null) {
      builder.clientAuth(clientAuth);
    }

    return builder.build();
  } catch (SSLException e) {
    return null;
  }
}
 
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: 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 5
Source File: Server.java    From qonduit with Apache License 2.0 5 votes vote down vote up
protected SslContext createSSLContext(Configuration config) throws Exception {

        Configuration.Ssl sslCfg = config.getSecurity().getSsl();
        Boolean generate = sslCfg.isUseGeneratedKeypair();
        SslContextBuilder ssl;
        if (generate) {
            LOG.warn("Using generated self signed server certificate");
            Date begin = new Date();
            Date end = new Date(begin.getTime() + 86400000);
            SelfSignedCertificate ssc = new SelfSignedCertificate("localhost", begin, end);
            ssl = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey());
        } else {
            String cert = sslCfg.getCertificateFile();
            String key = sslCfg.getKeyFile();
            String keyPass = sslCfg.getKeyPassword();
            if (null == cert || null == key) {
                throw new IllegalArgumentException("Check your SSL properties, something is wrong.");
            }
            ssl = SslContextBuilder.forServer(new File(cert), new File(key), keyPass);
        }

        ssl.ciphers(sslCfg.getUseCiphers());

        // Can't set to REQUIRE because the CORS pre-flight requests will fail.
        ssl.clientAuth(ClientAuth.OPTIONAL);

        Boolean useOpenSSL = sslCfg.isUseOpenssl();
        if (useOpenSSL) {
            ssl.sslProvider(SslProvider.OPENSSL);
        } else {
            ssl.sslProvider(SslProvider.JDK);
        }
        String trustStore = sslCfg.getTrustStoreFile();
        if (null != trustStore) {
            if (!trustStore.isEmpty()) {
                ssl.trustManager(new File(trustStore));
            }
        }
        return ssl.build();
    }
 
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: SecurityUtility.java    From pulsar with Apache License 2.0 5 votes vote down vote up
private static void setupClientAuthentication(SslContextBuilder builder,
    boolean requireTrustedClientCertOnConnect) {
    if (requireTrustedClientCertOnConnect) {
        builder.clientAuth(ClientAuth.REQUIRE);
    } else {
        builder.clientAuth(ClientAuth.OPTIONAL);
    }
}
 
Example 8
Source File: Server.java    From timely with Apache License 2.0 5 votes vote down vote up
protected SslContext createSSLContext(Configuration config) throws Exception {

        ServerSsl sslCfg = config.getSecurity().getServerSsl();
        Boolean generate = sslCfg.isUseGeneratedKeypair();
        SslContextBuilder ssl;
        if (generate) {
            LOG.warn("Using generated self signed server certificate");
            Date begin = new Date();
            Date end = new Date(begin.getTime() + TimeUnit.DAYS.toMillis(7));
            SelfSignedCertificate ssc = new SelfSignedCertificate("localhost", begin, end);
            ssl = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey());
        } else {
            String cert = sslCfg.getCertificateFile();
            String key = sslCfg.getKeyFile();
            String keyPass = sslCfg.getKeyPassword();
            if (null == cert || null == key) {
                throw new IllegalArgumentException("Check your SSL properties, something is wrong.");
            }
            ssl = SslContextBuilder.forServer(new File(cert), new File(key), keyPass);
        }

        ssl.ciphers(sslCfg.getUseCiphers());

        // Can't set to REQUIRE because the CORS pre-flight requests will fail.
        ssl.clientAuth(ClientAuth.OPTIONAL);

        Boolean useOpenSSL = sslCfg.isUseOpenssl();
        if (useOpenSSL) {
            ssl.sslProvider(SslProvider.OPENSSL);
        } else {
            ssl.sslProvider(SslProvider.JDK);
        }
        String trustStore = sslCfg.getTrustStoreFile();
        if (null != trustStore) {
            if (!trustStore.isEmpty()) {
                ssl.trustManager(new File(trustStore));
            }
        }
        return ssl.build();
    }
 
Example 9
Source File: GrafanaAuth.java    From timely with Apache License 2.0 5 votes vote down vote up
protected SslContext createSSLContext(GrafanaAuthConfiguration config) throws Exception {

        ServerSsl sslCfg = config.getSecurity().getServerSsl();
        Boolean generate = sslCfg.isUseGeneratedKeypair();
        SslContextBuilder ssl;
        if (generate) {
            LOG.warn("Using generated self signed server certificate");
            Date begin = new Date();
            Date end = new Date(begin.getTime() + 86400000);
            SelfSignedCertificate ssc = new SelfSignedCertificate("localhost", begin, end);
            ssl = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey());
        } else {
            String cert = sslCfg.getCertificateFile();
            String key = sslCfg.getKeyFile();
            String keyPass = sslCfg.getKeyPassword();
            if (null == cert || null == key) {
                throw new IllegalArgumentException("Check your SSL properties, something is wrong.");
            }
            ssl = SslContextBuilder.forServer(new File(cert), new File(key), keyPass);
        }

        ssl.ciphers(sslCfg.getUseCiphers());

        // Can't set to REQUIRE because the CORS pre-flight requests will fail.
        ssl.clientAuth(ClientAuth.OPTIONAL);

        Boolean useOpenSSL = sslCfg.isUseOpenssl();
        if (useOpenSSL) {
            ssl.sslProvider(SslProvider.OPENSSL);
        } else {
            ssl.sslProvider(SslProvider.JDK);
        }
        String trustStore = sslCfg.getTrustStoreFile();
        if (null != trustStore) {
            if (!trustStore.isEmpty()) {
                ssl.trustManager(new File(trustStore));
            }
        }
        return ssl.build();
    }
 
Example 10
Source File: Balancer.java    From timely with Apache License 2.0 5 votes vote down vote up
protected SslContext createSSLContext(BalancerConfiguration config) throws Exception {

        ServerSsl sslCfg = config.getSecurity().getServerSsl();
        Boolean generate = sslCfg.isUseGeneratedKeypair();
        SslContextBuilder ssl;
        if (generate) {
            LOG.warn("Using generated self signed server certificate");
            Date begin = new Date();
            Date end = new Date(begin.getTime() + 86400000);
            SelfSignedCertificate ssc = new SelfSignedCertificate("localhost", begin, end);
            ssl = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey());
        } else {
            String cert = sslCfg.getCertificateFile();
            String key = sslCfg.getKeyFile();
            String keyPass = sslCfg.getKeyPassword();
            if (null == cert || null == key) {
                throw new IllegalArgumentException("Check your SSL properties, something is wrong.");
            }
            ssl = SslContextBuilder.forServer(new File(cert), new File(key), keyPass);
        }

        ssl.ciphers(sslCfg.getUseCiphers());

        // Can't set to REQUIRE because the CORS pre-flight requests will fail.
        ssl.clientAuth(ClientAuth.OPTIONAL);

        Boolean useOpenSSL = sslCfg.isUseOpenssl();
        if (useOpenSSL) {
            ssl.sslProvider(SslProvider.OPENSSL);
        } else {
            ssl.sslProvider(SslProvider.JDK);
        }
        String trustStore = sslCfg.getTrustStoreFile();
        if (null != trustStore) {
            if (!trustStore.isEmpty()) {
                ssl.trustManager(new File(trustStore));
            }
        }
        return ssl.build();
    }
 
Example 11
Source File: SslContextProvider.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
protected void setClientAuthValues(
    SslContextBuilder sslContextBuilder, CertificateValidationContext localCertValidationContext)
    throws CertificateException, IOException, CertStoreException {
  DownstreamTlsContext downstreamTlsContext = getDownstreamTlsContext();
  if (localCertValidationContext != null) {
    sslContextBuilder.trustManager(new SdsTrustManagerFactory(localCertValidationContext));
    sslContextBuilder.clientAuth(
        downstreamTlsContext.isRequireClientCertificate()
            ? ClientAuth.REQUIRE
            : ClientAuth.OPTIONAL);
  } else {
    sslContextBuilder.clientAuth(ClientAuth.NONE);
  }
}
 
Example 12
Source File: HttpServletProtocolSpringAdapter.java    From spring-boot-protocol with Apache License 2.0 5 votes vote down vote up
/**
 * Initialize the SSL security configuration for HTTPS
 * @param keyManagerFactory keyManagerFactory
 * @param ssl ssl
 * @param sslStoreProvider sslStoreProvider
 * @return The SSL context builder
 * @throws Exception Exception
 */
protected SslContextBuilder getSslContext(KeyManagerFactory keyManagerFactory, Ssl ssl, SslStoreProvider sslStoreProvider) throws Exception {
    SslContextBuilder builder = SslContextBuilder.forServer(keyManagerFactory);
    builder.trustManager(getTrustManagerFactory(ssl, sslStoreProvider));
    if (ssl.getEnabledProtocols() != null) {
        builder.protocols(ssl.getEnabledProtocols());
    }
    if (ssl.getCiphers() != null) {
        builder.ciphers(Arrays.asList(ssl.getCiphers()));
    }
    if (ssl.getClientAuth() == Ssl.ClientAuth.NEED) {
        builder.clientAuth(ClientAuth.REQUIRE);
    }
    else if (ssl.getClientAuth() == Ssl.ClientAuth.WANT) {
        builder.clientAuth(ClientAuth.OPTIONAL);
    }

    ApplicationProtocolConfig protocolConfig = new ApplicationProtocolConfig(
            ApplicationProtocolConfig.Protocol.ALPN,
            // NO_ADVERTISE is currently the only mode supported by both OpenSsl and JDK providers.
            ApplicationProtocolConfig.SelectorFailureBehavior.NO_ADVERTISE,
            // ACCEPT is currently the only mode supported by both OpenSsl and JDK providers.
            ApplicationProtocolConfig.SelectedListenerFailureBehavior.ACCEPT,
            ApplicationProtocolNames.HTTP_2,
            ApplicationProtocolNames.HTTP_1_1);
    builder.applicationProtocolConfig(protocolConfig);

    return builder;
}
 
Example 13
Source File: MqttSslContextCreator.java    From spring-boot-protocol with Apache License 2.0 5 votes vote down vote up
private void addClientAuthentication(KeyStore ks, SslContextBuilder contextBuilder)
        throws NoSuchAlgorithmException, KeyStoreException {
    logger.warn("Client authentication is enabled. The keystore will be used as a truststore.");
    // use keystore as truststore, as integration needs to trust certificates signed by the integration certificates
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(ks);
    contextBuilder.clientAuth(ClientAuth.REQUIRE);
    contextBuilder.trustManager(tmf);
}
 
Example 14
Source File: SignatureSourceServer.java    From compass with GNU Affero General Public License v3.0 5 votes vote down vote up
public void start() throws IOException {
  NettyServerBuilder builder =
      NettyServerBuilder.forPort(config.port)
          .addService(new SignatureSourceImpl(signatureSource));

  if (!config.plaintext) {
    if (config.certChain == null || config.certChain.isEmpty()) {
      throw new IllegalArgumentException("-certChain is required if not running in plaintext mode");
    }

    if (config.privateKey == null || config.privateKey.isEmpty()) {
      throw new IllegalArgumentException("-privateKey is required if not running in plaintext mode");
    }

    SslContextBuilder sslClientContextBuilder = SslContextBuilder.forServer(new File(config.certChain),
        new File(config.privateKey));
    if (config.trustCertCollection != null) {
      sslClientContextBuilder.trustManager(new File(config.trustCertCollection));
      sslClientContextBuilder.clientAuth(ClientAuth.REQUIRE);
    }

    builder = builder.sslContext(GrpcSslContexts.configure(sslClientContextBuilder,
        SslProvider.OPENSSL).build());
  }

  server = builder.build();
  server.start();

  log.info("Server started, listening on " + config.port);

  Runtime.getRuntime().addShutdownHook(new Thread(() -> {
    System.err.println("*** shutting down gRPC server since JVM is shutting down");
    SignatureSourceServer.this.stop();
    System.err.println("*** server shut down");
  }));
}
 
Example 15
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 16
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 17
Source File: SslContextFactory.java    From servicetalk with Apache License 2.0 4 votes vote down vote up
/**
 * A new context for a server using the passed {@code config}.
 *
 * @param config SSL config.
 * @param supportedAlpnProtocols the list of supported ALPN protocols.
 * @return A new {@link SslContext} for a server.
 */
public static SslContext forServer(ReadOnlyServerSecurityConfig config, List<String> supportedAlpnProtocols) {
    requireNonNull(config);
    SslContextBuilder builder;

    KeyManagerFactory keyManagerFactory = config.keyManagerFactory();
    if (keyManagerFactory != null) {
        builder = SslContextBuilder.forServer(keyManagerFactory);
    } else {
        InputStream keyCertChainSupplier = null;
        InputStream keySupplier = null;
        try {
            keyCertChainSupplier = config.keyCertChainSupplier().get();
            keySupplier = config.keySupplier().get();
            builder = SslContextBuilder.forServer(keyCertChainSupplier, keySupplier, config.keyPassword());
        } finally {
            try {
                closeAndRethrowUnchecked(keyCertChainSupplier);
            } finally {
                closeAndRethrowUnchecked(keySupplier);
            }
        }
    }

    builder.sessionCacheSize(config.sessionCacheSize()).sessionTimeout(config.sessionTimeout())
            .applicationProtocolConfig(nettyApplicationProtocol(supportedAlpnProtocols));

    switch (config.clientAuth()) {
        case NONE:
            builder.clientAuth(ClientAuth.NONE);
            break;
        case OPTIONAL:
            builder.clientAuth(ClientAuth.OPTIONAL);
            break;
        case REQUIRE:
            builder.clientAuth(ClientAuth.REQUIRE);
            break;
        default:
            throw new IllegalArgumentException("Unsupported ClientAuth value: " + config.clientAuth());
    }
    configureTrustManager(config, builder);
    builder.protocols(config.protocols());
    builder.ciphers(config.ciphers());

    builder.sslProvider(toNettySslProvider(config.provider(), !supportedAlpnProtocols.isEmpty()));
    try {
        return builder.build();
    } catch (SSLException e) {
        throw new IllegalArgumentException(e);
    }
}
 
Example 18
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 19
Source File: BridgeServerTlsContextImpl.java    From arcusplatform with Apache License 2.0 4 votes vote down vote up
@Inject
public BridgeServerTlsContextImpl(BridgeServerConfig serverConfig, BridgeServerTrustManagerFactory trustManagerFactory) {
   this.useTls = serverConfig.isTlsServer();
   if (!this.useTls) {
      logger.info("BridgeServerTlsContext is disabled.");
      this.context = null;
      return;
   }

   try {
      SslContextBuilder serverContext = null;

      if (serverConfig.getTlsServerCertificateFilepath().length() != 0) {
         logger.debug("assuming use of PEM formatted certificate/key instead of keystore");
         serverContext = getSslContextFromPemFiles(
                 serverConfig.getTlsServerCertificateFilepath(),
                 serverConfig.getTlsServerPrivateKeyFilepath())
                 .sslProvider(createSslProvider(serverConfig));
      } else { // old default
         KeyManagerFactory kmf = createKeyManagerFactory(serverConfig);
         serverContext = SslContextBuilder.forServer(kmf)
                 .sslProvider(createSslProvider(serverConfig));
      }

      if (serverConfig.getTlsSessionCacheSize() > 0) {
         serverContext.sessionCacheSize(serverConfig.getTlsSessionCacheSize());
      }

      if (serverConfig.getTlsSessionTimeout() > 0) {
         serverContext.sessionTimeout(serverConfig.getTlsSessionTimeout());
      }

      if (serverConfig.isTlsNeedClientAuth()) {
         serverContext.clientAuth(ClientAuth.REQUIRE);
      } else if (serverConfig.isTlsRequestClientAuth()) {
         serverContext.clientAuth(ClientAuth.OPTIONAL);
      } else {
         serverContext.clientAuth(ClientAuth.NONE);
      }

      if (serverConfig.isTlsNeedClientAuth() || serverConfig.isTlsRequestClientAuth()) {
         TrustManagerFactory tmf = trustManagerFactory.getTrustManagerFactory();
         if (tmf != null) {
            serverContext.trustManager(tmf);
         }
      }

      context = serverContext.build();
   } catch (Exception ex) {
      logger.error("Failed to initialize the server-size SSLContext", ex);
      throw new IllegalStateException("Failed to initialize the server-side SSLContext", ex);
   }
}
 
Example 20
Source File: NettySSLOptionsFactory.java    From dropwizard-cassandra with Apache License 2.0 4 votes vote down vote up
@Override
public SSLOptions build() {
    SslContextBuilder sslContextBuilder = SslContextBuilder.forClient();

    if (provider != null) {
        sslContextBuilder.sslProvider(provider);
    }

    if (ciphers != null) {
        sslContextBuilder.ciphers(ciphers);
    }

    if (clientAuth != null) {
        sslContextBuilder.clientAuth(clientAuth);
    }

    if (sessionCacheSize != null) {
        sslContextBuilder.sessionCacheSize(sessionCacheSize);
    }

    if (sessionTimeout != null) {
        sslContextBuilder.sessionTimeout(sessionTimeout.toSeconds());
    }

    if (trustCertChainFile != null) {
        sslContextBuilder.trustManager(trustCertChainFile);
    }

    if (keyManager != null) {
        sslContextBuilder.keyManager(
                keyManager.getKeyCertChainFile(),
                keyManager.getKeyFile(),
                keyManager.getKeyPassword());
    }

    SslContext sslContext;
    try {
        sslContext = sslContextBuilder.build();
    } catch (SSLException e) {
        throw new RuntimeException("Unable to build Netty SslContext", e);
    }

    return new NettySSLOptions(sslContext);
}