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

The following examples show how to use io.netty.handler.ssl.SslContextBuilder#forClient() . 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: SslUtil.java    From Dream-Catcher with MIT License 6 votes vote down vote up
/**
 * Creates a netty SslContext for use when connecting to upstream servers. Retrieves the list of trusted root CAs
 * from the trustSource. When trustSource is true, no upstream certificate verification will be performed.
 * <b>This will make it possible for attackers to MITM communications with the upstream server</b>, so always
 * supply an appropriate trustSource except in extraordinary circumstances (e.g. testing with dynamically-generated
 * certificates).
 *
 * @param cipherSuites    cipher suites to allow when connecting to the upstream server
 * @param trustSource     the trust store that will be used to validate upstream servers' certificates, or null to accept all upstream server certificates
 * @return an SSLContext to connect to upstream servers with
 */
public static SslContext getUpstreamServerSslContext(Collection<String> cipherSuites, TrustSource trustSource) {
    SslContextBuilder sslContextBuilder = SslContextBuilder.forClient();

    if (trustSource == null) {
        log.warn("Disabling upstream server certificate verification. This will allow attackers to intercept communications with upstream servers.");

        sslContextBuilder.trustManager(InsecureTrustManagerFactory.INSTANCE);
    } else {
        sslContextBuilder.trustManager(trustSource.getTrustedCAs());
    }

    sslContextBuilder.ciphers(cipherSuites, SupportedCipherSuiteFilter.INSTANCE);

    try {
        return sslContextBuilder.build();
    } catch (SSLException e) {
        throw new SslContextInitializationException("Error creating new SSL context for connection to upstream server", e);
    }
}
 
Example 2
Source File: SslUtil.java    From CapturePacket with MIT License 6 votes vote down vote up
/**
 * Creates a netty SslContext for use when connecting to upstream servers. Retrieves the list of trusted root CAs
 * from the trustSource. When trustSource is true, no upstream certificate verification will be performed.
 * <b>This will make it possible for attackers to MITM communications with the upstream server</b>, so always
 * supply an appropriate trustSource except in extraordinary circumstances (e.g. testing with dynamically-generated
 * certificates).
 *
 * @param cipherSuites    cipher suites to allow when connecting to the upstream server
 * @param trustSource     the trust store that will be used to validate upstream servers' certificates, or null to accept all upstream server certificates
 * @return an SSLContext to connect to upstream servers with
 */
public static SslContext getUpstreamServerSslContext(Collection<String> cipherSuites, TrustSource trustSource) {
    SslContextBuilder sslContextBuilder = SslContextBuilder.forClient();

    if (trustSource == null) {
        log.warn("Disabling upstream server certificate verification. This will allow attackers to intercept communications with upstream servers.");

        sslContextBuilder.trustManager(InsecureTrustManagerFactory.INSTANCE);
    } else {
        sslContextBuilder.trustManager(trustSource.getTrustedCAs());
    }

    sslContextBuilder.ciphers(cipherSuites, SupportedCipherSuiteFilter.INSTANCE);

    try {
        return sslContextBuilder.build();
    } catch (SSLException e) {
        throw new SslContextInitializationException("Error creating new SSL context for connection to upstream server", e);
    }
}
 
Example 3
Source File: GremlinServerSslIntegrateTest.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldEnableSslWithSslContextProgrammaticallySpecified() throws Exception {
    // just for testing - this is not good for production use
    final SslContextBuilder builder = SslContextBuilder.forClient();
    builder.trustManager(InsecureTrustManagerFactory.INSTANCE);
    builder.sslProvider(SslProvider.JDK);

    final Cluster cluster = TestClientFactory.build().enableSsl(true).sslContext(builder.build()).create();
    final Client client = cluster.connect();

    try {
        // this should return "nothing" - there should be no exception
        assertEquals("test", client.submit("'test'").one().getString());
    } finally {
        cluster.close();
    }
}
 
Example 4
Source File: ClientHttpConnectorFactory.java    From spring-vault with Apache License 2.0 6 votes vote down vote up
static ClientHttpConnector usingReactorNetty(ClientOptions options, SslConfiguration sslConfiguration) {
	HttpClient client = HttpClient.create();

	if (hasSslConfiguration(sslConfiguration)) {

		SslContextBuilder sslContextBuilder = SslContextBuilder.forClient();
		configureSsl(sslConfiguration, sslContextBuilder);

		client = client.secure(builder -> {
			builder.sslContext(sslContextBuilder);
		});
	}

	client = client.tcpConfiguration(it -> it.option(ChannelOption.CONNECT_TIMEOUT_MILLIS,
			Math.toIntExact(options.getConnectionTimeout().toMillis())));

	return new ReactorClientHttpConnector(client);
}
 
Example 5
Source File: ReactorEmeraldClient.java    From etherjar with Apache License 2.0 5 votes vote down vote up
/**
 * Setup x509 certificate for target server
 *
 * @param certificate x509 certificate
 * @return builder
 */
public Builder trustedCertificate(InputStream certificate) {
    if (sslContextBuilder == null) {
        sslContextBuilder = SslContextBuilder.forClient();
        channelBuilder.useTransportSecurity();
    }
    sslContextBuilder = sslContextBuilder.trustManager(certificate);
    return this;
}
 
Example 6
Source File: EmeraldTransport.java    From etherjar with Apache License 2.0 5 votes vote down vote up
/**
 * Setup client certificate
 *
 * @param certificate x509 certificate
 * @param key private key for the certificate in PKCS8 format
 * @return builder
 */
public Builder clientCertificate(File certificate, File key) {
    if (sslContextBuilder == null) {
        sslContextBuilder = SslContextBuilder.forClient();
        channelBuilder.useTransportSecurity();
    }
    sslContextBuilder = sslContextBuilder.keyManager(certificate, key);
    return this;
}
 
Example 7
Source File: EmeraldTransport.java    From etherjar with Apache License 2.0 5 votes vote down vote up
/**
 * Setup x509 certificate for target server
 *
 * @param certificate x509 certificate
 * @return builder
 */
public Builder trustedCertificate(File certificate) {
    if (sslContextBuilder == null) {
        sslContextBuilder = SslContextBuilder.forClient();
        channelBuilder.useTransportSecurity();
    }
    sslContextBuilder = sslContextBuilder.trustManager(certificate);
    return this;
}
 
Example 8
Source File: EmeraldTransport.java    From etherjar with Apache License 2.0 5 votes vote down vote up
/**
 * Setup x509 certificate for target server
 *
 * @param certificate x509 certificate
 * @return builder
 */
public Builder trustedCertificate(InputStream certificate) {
    if (sslContextBuilder == null) {
        sslContextBuilder = SslContextBuilder.forClient();
        channelBuilder.useTransportSecurity();
    }
    sslContextBuilder = sslContextBuilder.trustManager(certificate);
    return this;
}
 
Example 9
Source File: OneWaySSLBase.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);
    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: SecurityUtility.java    From pulsar with Apache License 2.0 5 votes vote down vote up
public static SslContext createNettySslContextForClient(boolean allowInsecureConnection, String trustCertsFilePath,
        Certificate[] certificates, PrivateKey privateKey)
        throws GeneralSecurityException, SSLException, FileNotFoundException, IOException {
    SslContextBuilder builder = SslContextBuilder.forClient();
    setupTrustCerts(builder, allowInsecureConnection, trustCertsFilePath);
    setupKeyManager(builder, privateKey, (X509Certificate[]) certificates);
    return builder.build();
}
 
Example 11
Source File: WebSocketClientIT.java    From timely with Apache License 2.0 5 votes vote down vote up
private void setupSslCtx() throws Exception {
    Assert.assertNotNull(clientTrustStoreFile);
    SslContextBuilder builder = SslContextBuilder.forClient();
    builder.applicationProtocolConfig(ApplicationProtocolConfig.DISABLED);
    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;
    sslCtx = jdk.context();
}
 
Example 12
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 13
Source File: ClientHttpRequestFactoryFactory.java    From spring-vault with Apache License 2.0 5 votes vote down vote up
static ClientHttpRequestFactory usingNetty(ClientOptions options, SslConfiguration sslConfiguration)
		throws GeneralSecurityException, IOException {

	Netty4ClientHttpRequestFactory requestFactory = new Netty4ClientHttpRequestFactory();

	if (hasSslConfiguration(sslConfiguration)) {

		SslContextBuilder sslContextBuilder = SslContextBuilder //
				.forClient();

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

		if (sslConfiguration.getKeyStoreConfiguration().isPresent()) {
			sslContextBuilder.keyManager(createKeyManagerFactory(sslConfiguration.getKeyStoreConfiguration(),
					sslConfiguration.getKeyConfiguration()));
		}

		requestFactory.setSslContext(sslContextBuilder.sslProvider(SslProvider.JDK).build());
	}

	requestFactory.setConnectTimeout(Math.toIntExact(options.getConnectionTimeout().toMillis()));
	requestFactory.setReadTimeout(Math.toIntExact(options.getReadTimeout().toMillis()));

	return requestFactory;
}
 
Example 14
Source File: OneWaySSLBase.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);
    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 15
Source File: ReactorEmeraldClient.java    From etherjar with Apache License 2.0 5 votes vote down vote up
/**
 * Setup client certificate
 *
 * @param certificate x509 certificate
 * @param key private key for the certificate in PKCS8 format
 * @return builder
 */
public Builder clientCertificate(InputStream certificate, InputStream key) {
    if (sslContextBuilder == null) {
        sslContextBuilder = SslContextBuilder.forClient();
        channelBuilder.useTransportSecurity();
    }
    sslContextBuilder = sslContextBuilder.keyManager(certificate, key);
    return this;
}
 
Example 16
Source File: WebSocketClientIT.java    From qonduit with Apache License 2.0 5 votes vote down vote up
private void setupSslCtx() throws Exception {
    Assert.assertNotNull(clientTrustStoreFile);
    SslContextBuilder builder = SslContextBuilder.forClient();
    builder.applicationProtocolConfig(ApplicationProtocolConfig.DISABLED);
    builder.sslProvider(SslProvider.JDK);
    builder.trustManager(clientTrustStoreFile); // Trust the server cert
    SslContext ctx = builder.build();
    Assert.assertTrue(ctx.isClient());
    JdkSslContext jdk = (JdkSslContext) ctx;
    sslCtx = jdk.context();
}
 
Example 17
Source File: TwoWaySSLFailureIT.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 18
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);
}
 
Example 19
Source File: TlsTest.java    From grpc-java with Apache License 2.0 4 votes vote down vote up
@Before
public void setUp() throws NoSuchAlgorithmException {
  executor = Executors.newSingleThreadScheduledExecutor();
  switch (tlsImpl) {
    case TCNATIVE:
      Assume.assumeTrue(OpenSsl.isAvailable());
      sslProvider = SslProvider.OPENSSL;
      break;
    case JDK:
      Assume.assumeTrue(Arrays.asList(
          SSLContext.getDefault().getSupportedSSLParameters().getCipherSuites())
          .contains("TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256"));
      sslProvider = SslProvider.JDK;
      jdkProvider = Security.getProvider("SunJSSE");
      Assume.assumeNotNull(jdkProvider);
      try {
        // Check for presence of an (ironic) class added in Java 9
        Class.forName("java.lang.Runtime$Version");
        // Java 9+
      } catch (ClassNotFoundException ignored) {
        // Before Java 9
        // TODO(ejona): remove this assume once we upgrade to Netty 4.1.50.Final. GrpcSslContexts
        // detects the Java 9 ALPN API in Java 8 u252, but Netty does not support it in our
        // current version
        Assume.assumeTrue("Jetty ALPN not found", JettyTlsUtil.isJettyAlpnConfigured());
        try {
          GrpcSslContexts.configure(SslContextBuilder.forClient(), jdkProvider);
        } catch (IllegalArgumentException ex) {
          Assume.assumeNoException("Not Java 9+ and Jetty ALPN does not seem available", ex);
        }
      }
      break;
    case CONSCRYPT:
      sslProvider = SslProvider.JDK;
      jdkProvider = Security.getProvider("Conscrypt");
      Assume.assumeNotNull(jdkProvider);
      break;
    default:
      throw new AssertionError();
  }
  clientContextBuilder = SslContextBuilder.forClient();
  if (sslProvider == SslProvider.JDK) {
    GrpcSslContexts.configure(clientContextBuilder, jdkProvider);
  } else {
    GrpcSslContexts.configure(clientContextBuilder, sslProvider);
  }
}
 
Example 20
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();
}