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

The following examples show how to use io.netty.handler.ssl.SslContextBuilder#keyManager() . 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: SslServerInitializerTest.java    From nomulus with Apache License 2.0 7 votes vote down vote up
private ChannelHandler getClientHandler(
    X509Certificate trustedCertificate, PrivateKey privateKey, X509Certificate certificate) {
  return new ChannelInitializer<LocalChannel>() {
    @Override
    protected void initChannel(LocalChannel ch) throws Exception {
      SslContextBuilder sslContextBuilder =
          SslContextBuilder.forClient().trustManager(trustedCertificate).sslProvider(sslProvider);
      if (privateKey != null && certificate != null) {
        sslContextBuilder.keyManager(privateKey, certificate);
      }
      SslHandler sslHandler =
          sslContextBuilder.build().newHandler(ch.alloc(), SSL_HOST, SSL_PORT);

      // Enable hostname verification.
      SSLEngine sslEngine = sslHandler.engine();
      SSLParameters sslParameters = sslEngine.getSSLParameters();
      sslParameters.setEndpointIdentificationAlgorithm("HTTPS");
      sslEngine.setSSLParameters(sslParameters);

      ch.pipeline().addLast(sslHandler);
    }
  };
}
 
Example 2
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 3
Source File: ClientHttpConnectorFactory.java    From spring-vault with Apache License 2.0 6 votes vote down vote up
private static void configureSsl(SslConfiguration sslConfiguration, SslContextBuilder sslContextBuilder) {

		try {

			if (sslConfiguration.getTrustStoreConfiguration().isPresent()) {
				sslContextBuilder
						.trustManager(createTrustManagerFactory(sslConfiguration.getTrustStoreConfiguration()));
			}

			if (sslConfiguration.getKeyStoreConfiguration().isPresent()) {
				sslContextBuilder.keyManager(createKeyManagerFactory(sslConfiguration.getKeyStoreConfiguration(),
						sslConfiguration.getKeyConfiguration()));
			}
		}
		catch (GeneralSecurityException | IOException e) {
			throw new IllegalStateException(e);
		}
	}
 
Example 4
Source File: SslBridgeHandler.java    From r2dbc-mysql with Apache License 2.0 5 votes vote down vote up
private static SslContextBuilder buildContext(MySqlSslConfiguration ssl, ServerVersion version) {
    SslContextBuilder builder = withTlsVersion(SslContextBuilder.forClient(), ssl, version);
    String sslKey = ssl.getSslKey();

    if (sslKey != null) {
        CharSequence keyPassword = ssl.getSslKeyPassword();
        String sslCert = ssl.getSslCert();

        if (sslCert == null) {
            throw new IllegalStateException("SSL key param requires but SSL cert param to be present");
        }

        builder.keyManager(new File(sslCert), new File(sslKey), keyPassword == null ? null : keyPassword.toString());
    }

    SslMode mode = ssl.getSslMode();
    if (mode.verifyCertificate()) {
        String sslCa = ssl.getSslCa();

        if (sslCa == null) {
            throw new IllegalStateException(String.format("SSL mode %s requires SSL CA parameter", mode));
        }

        builder.trustManager(new File(sslCa));
    } else {
        builder.trustManager(InsecureTrustManagerFactory.INSTANCE);
    }

    return ssl.customizeSslContext(builder);
}
 
Example 5
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 6
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 7
Source File: TwoWaySSLOpenSSLIT.java    From timely with Apache License 2.0 5 votes vote down vote up
protected SSLSocketFactory getSSLSocketFactory() throws Exception {
    SslContextBuilder builder = SslContextBuilder.forClient();
    builder.applicationProtocolConfig(ApplicationProtocolConfig.DISABLED);
    // Use server cert / key on client side.
    builder.keyManager(serverCert.key(), (String) null, serverCert.cert());
    builder.sslProvider(SslProvider.JDK);
    builder.trustManager(clientTrustStoreFile); // Trust the server cert
    SslContext ctx = builder.build();
    Assert.assertTrue(ctx.isClient());
    Assert.assertTrue(ctx instanceof JdkSslContext);
    JdkSslContext jdk = (JdkSslContext) ctx;
    SSLContext jdkSslContext = jdk.context();
    return jdkSslContext.getSocketFactory();
}
 
Example 8
Source File: TwoWaySSLIT.java    From timely with Apache License 2.0 5 votes vote down vote up
protected SSLSocketFactory getSSLSocketFactory() throws Exception {
    SslContextBuilder builder = SslContextBuilder.forClient();
    builder.applicationProtocolConfig(ApplicationProtocolConfig.DISABLED);
    // Use server cert / key on client side.
    builder.keyManager(serverCert.key(), (String) null, serverCert.cert());
    builder.sslProvider(SslProvider.JDK);
    builder.trustManager(clientTrustStoreFile); // Trust the server cert
    SslContext ctx = builder.build();
    Assert.assertTrue(ctx.isClient());
    Assert.assertTrue(ctx instanceof JdkSslContext);
    JdkSslContext jdk = (JdkSslContext) ctx;
    SSLContext jdkSslContext = jdk.context();
    return jdkSslContext.getSocketFactory();
}
 
Example 9
Source File: TwoWaySSLFailureIT.java    From timely with Apache License 2.0 5 votes vote down vote up
protected SSLSocketFactory getSSLSocketFactory() throws Exception {
    SslContextBuilder builder = SslContextBuilder.forClient();
    builder.applicationProtocolConfig(ApplicationProtocolConfig.DISABLED);
    // Use server cert / key on client side
    builder.keyManager(serverCert.key(), (String) null, serverCert.cert());
    builder.sslProvider(SslProvider.JDK);
    builder.trustManager(clientTrustStoreFile); // Trust the server cert
    SslContext ctx = builder.build();
    Assert.assertTrue(ctx.isClient());
    Assert.assertTrue(ctx instanceof JdkSslContext);
    JdkSslContext jdk = (JdkSslContext) ctx;
    SSLContext jdkSslContext = jdk.context();
    return jdkSslContext.getSocketFactory();
}
 
Example 10
Source File: TwoWaySSLOpenSSLIT.java    From qonduit with Apache License 2.0 5 votes vote down vote up
protected SSLSocketFactory getSSLSocketFactory() throws Exception {
    SslContextBuilder builder = SslContextBuilder.forClient();
    builder.applicationProtocolConfig(ApplicationProtocolConfig.DISABLED);
    // Use server cert / key on client side.
    builder.keyManager(serverCert.key(), (String) null, serverCert.cert());
    builder.sslProvider(SslProvider.JDK);
    builder.trustManager(clientTrustStoreFile); // Trust the server cert
    SslContext ctx = builder.build();
    Assert.assertTrue(ctx.isClient());
    JdkSslContext jdk = (JdkSslContext) ctx;
    SSLContext jdkSslContext = jdk.context();
    return jdkSslContext.getSocketFactory();
}
 
Example 11
Source File: TransportSupport.java    From qpid-jms with Apache License 2.0 5 votes vote down vote up
/**
 * Create a new Netty SslContext using the options specific in the given TransportOptions
 * instance.
 *
 * @param options
 *        the configured options used to create the SslContext.
 *
 * @return a new SslContext instance.
 *
 * @throws Exception if an error occurs while creating the context.
 */
public static SslContext createOpenSslContext(TransportOptions options) throws Exception {
    try {
        String contextProtocol = options.getContextProtocol();
        LOG.trace("Getting SslContext instance using protocol: {}", contextProtocol);

        KeyManagerFactory keyManagerFactory = loadKeyManagerFactory(options, SslProvider.OPENSSL);
        TrustManagerFactory trustManagerFactory = loadTrustManagerFactory(options);
        SslContextBuilder builder = SslContextBuilder.forClient().sslProvider(SslProvider.OPENSSL);

        // TODO - There is oddly no way in Netty right now to get the set of supported protocols
        //        when creating the SslContext or really even when creating the SSLEngine.  Seems
        //        like an oversight, for now we call it with TLSv1.2 so it looks like we did something.
        if (options.getContextProtocol().equals(TransportOptions.DEFAULT_CONTEXT_PROTOCOL)) {
            builder.protocols("TLSv1.2");
        } else {
            builder.protocols(options.getContextProtocol());
        }
        builder.keyManager(keyManagerFactory);
        builder.trustManager(trustManagerFactory);

        return builder.build();
    } catch (Exception e) {
        LOG.error("Failed to create SslContext: {}", e, e);
        throw e;
    }
}
 
Example 12
Source File: HelloWorldMutualTlsServiceTest.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@BeforeEach
public void init() throws SSLException {
    SslContextBuilder builder = GrpcSslContexts.forClient();
    builder.trustManager(new File("src/main/resources/tls/ca.pem"));
    builder.keyManager(new File("src/main/resources/tls/client.pem"),
            new File("src/main/resources/tls/client.key"));
    SslContext context = builder.build();

    channel = NettyChannelBuilder.forAddress("localhost", 9000)
            .sslContext(context)
            .build();
}
 
Example 13
Source File: SslBridgeHandler.java    From r2dbc-mysql with Apache License 2.0 5 votes vote down vote up
private static SslContextBuilder buildContext(MySqlSslConfiguration ssl, ServerVersion version) {
    SslContextBuilder builder = withTlsVersion(SslContextBuilder.forClient(), ssl, version);
    String sslKey = ssl.getSslKey();

    if (sslKey != null) {
        CharSequence keyPassword = ssl.getSslKeyPassword();
        String sslCert = ssl.getSslCert();

        if (sslCert == null) {
            throw new IllegalStateException("SSL key param requires but SSL cert param to be present");
        }

        builder.keyManager(new File(sslCert), new File(sslKey), keyPassword == null ? null : keyPassword.toString());
    }

    SslMode mode = ssl.getSslMode();
    if (mode.verifyCertificate()) {
        String sslCa = ssl.getSslCa();

        if (sslCa == null) {
            throw new IllegalStateException(String.format("SSL mode %s requires SSL CA parameter", mode));
        }

        builder.trustManager(new File(sslCa));
    } else {
        builder.trustManager(InsecureTrustManagerFactory.INSTANCE);
    }

    return ssl.customizeSslContext(builder);
}
 
Example 14
Source File: SslContextFactory.java    From servicetalk with Apache License 2.0 5 votes vote down vote up
/**
 * A new context for a client using the passed {@code config}.
 *
 * @param config SSL config.
 * @param supportedAlpnProtocols the list of supported ALPN protocols.
 * @return A new {@link SslContext} for a client.
 */
public static SslContext forClient(ReadOnlyClientSecurityConfig config, List<String> supportedAlpnProtocols) {
    requireNonNull(config);
    SslContextBuilder builder = SslContextBuilder.forClient()
            .sessionCacheSize(config.sessionCacheSize()).sessionTimeout(config.sessionTimeout());
    configureTrustManager(config, builder);
    KeyManagerFactory keyManagerFactory = config.keyManagerFactory();
    if (keyManagerFactory != null) {
        builder.keyManager(keyManagerFactory);
    } else {
        InputStream keyCertChainSupplier = null;
        InputStream keySupplier = null;
        try {
            keyCertChainSupplier = config.keyCertChainSupplier().get();
            keySupplier = config.keySupplier().get();
            builder.keyManager(keyCertChainSupplier, keySupplier, config.keyPassword());
        } finally {
            try {
                closeAndRethrowUnchecked(keyCertChainSupplier);
            } finally {
                closeAndRethrowUnchecked(keySupplier);
            }
        }
    }
    builder.sslProvider(toNettySslProvider(config.provider(), !supportedAlpnProtocols.isEmpty()));

    builder.protocols(config.protocols());
    builder.ciphers(config.ciphers());
    builder.applicationProtocolConfig(nettyApplicationProtocol(supportedAlpnProtocols));
    try {
        return builder.build();
    } catch (SSLException e) {
        throw new IllegalArgumentException(e);
    }
}
 
Example 15
Source File: SecretVolumeClientSslContextProvider.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
SslContext buildSslContextFromSecrets()
    throws IOException, CertificateException, CertStoreException {
  SslContextBuilder sslContextBuilder =
      GrpcSslContexts.forClient().trustManager(new SdsTrustManagerFactory(certContext));
  if (privateKey != null && certificateChain != null) {
    sslContextBuilder.keyManager(
        new File(certificateChain), new File(privateKey), privateKeyPassword);
  }
  return sslContextBuilder.build();
}
 
Example 16
Source File: SdsClientSslContextProvider.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Override
SslContextBuilder getSslContextBuilder(
    CertificateValidationContext localCertValidationContext)
    throws CertificateException, IOException, CertStoreException {
  SslContextBuilder sslContextBuilder =
      GrpcSslContexts.forClient()
          .trustManager(new SdsTrustManagerFactory(localCertValidationContext));
  if (tlsCertificate != null) {
    sslContextBuilder.keyManager(
        tlsCertificate.getCertificateChain().getInlineBytes().newInput(),
        tlsCertificate.getPrivateKey().getInlineBytes().newInput(),
        tlsCertificate.hasPassword() ? tlsCertificate.getPassword().getInlineString() : null);
  }
  return sslContextBuilder;
}
 
Example 17
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();
}
 
Example 18
Source File: Channels.java    From quarkus with Apache License 2.0 4 votes vote down vote up
public static Channel createChannel(String name) throws SSLException {
    InstanceHandle<GrpcClientConfigProvider> instance = Arc.container().instance(GrpcClientConfigProvider.class);

    if (!instance.isAvailable()) {
        throw new IllegalStateException("Unable to find the GrpcClientConfigProvider");
    }

    GrpcClientConfiguration config = instance.get().getConfiguration(name);
    String host = config.host;
    int port = config.port;
    boolean plainText = !config.ssl.trustStore.isPresent();
    Optional<Boolean> usePlainText = config.plainText;
    if (usePlainText.isPresent()) {
        plainText = usePlainText.get();
    }

    SslContext context = null;
    if (!plainText) {
        Path trustStorePath = config.ssl.trustStore.orElse(null);
        Path certificatePath = config.ssl.certificate.orElse(null);
        Path keyPath = config.ssl.key.orElse(null);
        SslContextBuilder sslContextBuilder = GrpcSslContexts.forClient();
        if (trustStorePath != null) {
            sslContextBuilder.trustManager(trustStorePath.toFile());
        }

        if (certificatePath != null && keyPath != null) {
            sslContextBuilder.keyManager(certificatePath.toFile(), keyPath.toFile());
        }

        context = sslContextBuilder.build();
    }

    NettyChannelBuilder builder = NettyChannelBuilder.forAddress(host, port)
            .flowControlWindow(config.flowControlWindow.orElse(DEFAULT_FLOW_CONTROL_WINDOW))
            .keepAliveWithoutCalls(config.keepAliveWithoutCalls)
            .maxHedgedAttempts(config.maxHedgedAttempts)
            .maxRetryAttempts(config.maxRetryAttempts)
            .maxInboundMetadataSize(config.maxInboundMessageSize.orElse(DEFAULT_MAX_HEADER_LIST_SIZE))
            .maxInboundMetadataSize(config.maxInboundMessageSize.orElse(DEFAULT_MAX_MESSAGE_SIZE))
            .negotiationType(NegotiationType.valueOf(config.negotiationType.toUpperCase()));

    if (config.retry) {
        builder.enableRetry();
    } else {
        builder.disableRetry();
    }

    if (config.maxTraceEvents.isPresent()) {
        builder.maxTraceEvents(config.maxTraceEvents.getAsInt());
    }
    Optional<String> userAgent = config.userAgent;
    if (userAgent.isPresent()) {
        builder.userAgent(userAgent.get());
    }
    if (config.retryBufferSize.isPresent()) {
        builder.retryBufferSize(config.retryBufferSize.getAsLong());
    }
    if (config.perRpcBufferLimit.isPresent()) {
        builder.perRpcBufferLimit(config.perRpcBufferLimit.getAsLong());
    }
    Optional<String> overrideAuthority = config.overrideAuthority;
    if (overrideAuthority.isPresent()) {
        builder.overrideAuthority(overrideAuthority.get());
    }
    Optional<Duration> keepAliveTime = config.keepAliveTime;
    if (keepAliveTime.isPresent()) {
        builder.keepAliveTime(keepAliveTime.get().toMillis(), TimeUnit.MILLISECONDS);
    }
    Optional<Duration> keepAliveTimeout = config.keepAliveTimeout;
    if (keepAliveTimeout.isPresent()) {
        builder.keepAliveTimeout(keepAliveTimeout.get().toMillis(), TimeUnit.MILLISECONDS);
    }
    Optional<Duration> idleTimeout = config.idleTimeout;
    if (idleTimeout.isPresent()) {
        builder.keepAliveTimeout(idleTimeout.get().toMillis(), TimeUnit.MILLISECONDS);
    }

    if (plainText) {
        builder.usePlaintext();
    }
    if (context != null) {
        builder.sslContext(context);
    }

    // Client-side interceptors
    Instance<ClientInterceptor> interceptors = Arc.container().beanManager().createInstance()
            .select(ClientInterceptor.class);
    for (ClientInterceptor clientInterceptor : getSortedInterceptors(interceptors)) {
        builder.intercept(clientInterceptor);
    }

    return builder.build();
}
 
Example 19
Source File: SecurityUtility.java    From pulsar with Apache License 2.0 4 votes vote down vote up
private static void setupKeyManager(SslContextBuilder builder, PrivateKey privateKey,
        X509Certificate[] certificates) {
    builder.keyManager(privateKey, (X509Certificate[]) certificates);
}
 
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);
}