org.apache.http.conn.ssl.DefaultHostnameVerifier Java Examples

The following examples show how to use org.apache.http.conn.ssl.DefaultHostnameVerifier. 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: SSLFactoryTestHelper.java    From mutual-tls-ssl with Apache License 2.0 6 votes vote down vote up
public static SSLFactory createSSLFactory(boolean oneWayAuthenticationEnabled, boolean twoWayAuthenticationEnabled) {
    String keyStorePath = "keystores-for-unit-tests/identity.jks";
    String keyStorePassword = "secret";
    String trustStorePath = "keystores-for-unit-tests/truststore.jks";
    String trustStorePassword = "secret";

    SSLFactory.Builder sslFactoryBuilder = SSLFactory.builder();
    if (oneWayAuthenticationEnabled) {
        sslFactoryBuilder.withTrustMaterial(trustStorePath, trustStorePassword.toCharArray())
                .withHostnameVerifier(new DefaultHostnameVerifier());
    }

    if (twoWayAuthenticationEnabled) {
        sslFactoryBuilder.withIdentityMaterial(keyStorePath, keyStorePassword.toCharArray())
                .withTrustMaterial(trustStorePath, trustStorePassword.toCharArray())
                .withHostnameVerifier(new DefaultHostnameVerifier());
    }
    return Mockito.spy(sslFactoryBuilder.build());
}
 
Example #2
Source File: ClientConfigShould.java    From mutual-tls-ssl with Apache License 2.0 6 votes vote down vote up
@Test
public void createSslFactoryWithTwoWayAuthentication() {
    String keyStorePath = "keystores-for-unit-tests/identity.jks";
    String keyStorePassword = "secret";
    String trustStorePath = "keystores-for-unit-tests/truststore.jks";
    String trustStorePassword = "secret";

    SSLFactory sslFactory = victim.sslFactory(false, true,
            keyStorePath, keyStorePassword.toCharArray(), trustStorePath, trustStorePassword.toCharArray());

    assertThat(sslFactory).isNotNull();
    assertThat(sslFactory.getSslContext()).isNotNull();
    assertThat(sslFactory.getKeyManager()).isPresent();
    assertThat(sslFactory.getTrustManager()).isNotNull();
    assertThat(sslFactory.getHostnameVerifier()).isInstanceOf(DefaultHostnameVerifier.class);
    assertThat(sslFactory.getSslContext().getProtocol()).isEqualTo("TLSv1.3");
}
 
Example #3
Source File: HttpEventPublisher.java    From DataflowTemplates with Apache License 2.0 6 votes vote down vote up
/**
 * Utility method to create a {@link CloseableHttpClient} to make http POSTs against Splunk's
 * HEC.
 *
 * @param maxConnections max number of parallel connections.
 * @param disableCertificateValidation should disable certificate validation.
 */
private CloseableHttpClient getHttpClient(
    int maxConnections, boolean disableCertificateValidation)
    throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {

  HttpClientBuilder builder = ApacheHttpTransport.newDefaultHttpClientBuilder();

  if (genericUrl().getScheme().equalsIgnoreCase(HTTPS_PROTOCOL_PREFIX)) {
    LOG.info("SSL connection requested");

    HostnameVerifier hostnameVerifier =
        disableCertificateValidation
            ? NoopHostnameVerifier.INSTANCE
            : new DefaultHostnameVerifier();

    SSLContextBuilder sslContextBuilder = SSLContextBuilder.create();
    if (disableCertificateValidation) {
      LOG.info("Certificate validation is disabled");
      sslContextBuilder.loadTrustMaterial((TrustStrategy) (chain, authType) -> true);
    }

    SSLConnectionSocketFactory connectionSocketFactory =
        new SSLConnectionSocketFactory(sslContextBuilder.build(), hostnameVerifier);
    builder.setSSLSocketFactory(connectionSocketFactory);
  }

  builder.setMaxConnTotal(maxConnections);
  builder.setDefaultRequestConfig(
      RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build());

  return builder.build();
}
 
Example #4
Source File: AvaticaCommonsHttpClientImplTest.java    From calcite-avatica with Apache License 2.0 6 votes vote down vote up
@Test public void testHostnameVerification() throws Exception {
  AvaticaCommonsHttpClientImpl client = mock(AvaticaCommonsHttpClientImpl.class);
  // Call the real method
  when(client.getHostnameVerifier(nullable(HostnameVerification.class)))
      .thenCallRealMethod();

  // No verification should give the default (strict) verifier
  HostnameVerifier actualVerifier = client.getHostnameVerifier(null);
  assertNotNull(actualVerifier);
  assertTrue(actualVerifier instanceof DefaultHostnameVerifier);

  actualVerifier = client.getHostnameVerifier(HostnameVerification.STRICT);
  assertNotNull(actualVerifier);
  assertTrue(actualVerifier instanceof DefaultHostnameVerifier);

  actualVerifier = client.getHostnameVerifier(HostnameVerification.NONE);
  assertNotNull(actualVerifier);
  assertTrue(actualVerifier instanceof NoopHostnameVerifier);
}
 
Example #5
Source File: HttpClientUtilTest.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@Test
// commented out on: 24-Dec-2018   @BadApple(bugUrl="https://issues.apache.org/jira/browse/SOLR-12028") // added 20-Sep-2018
public void testSSLSystemProperties() throws IOException {

  assertNotNull("HTTPS scheme could not be created using system defaults",
                HttpClientUtil.getSocketFactoryRegistryProvider().getSocketFactoryRegistry().lookup("https"));

  assertSSLHostnameVerifier(DefaultHostnameVerifier.class, HttpClientUtil.getSocketFactoryRegistryProvider());

  System.setProperty(HttpClientUtil.SYS_PROP_CHECK_PEER_NAME, "true");
  resetHttpClientBuilder();
  assertSSLHostnameVerifier(DefaultHostnameVerifier.class, HttpClientUtil.getSocketFactoryRegistryProvider());

  System.setProperty(HttpClientUtil.SYS_PROP_CHECK_PEER_NAME, "");
  resetHttpClientBuilder();
  assertSSLHostnameVerifier(DefaultHostnameVerifier.class, HttpClientUtil.getSocketFactoryRegistryProvider());
  
  System.setProperty(HttpClientUtil.SYS_PROP_CHECK_PEER_NAME, "false");
  resetHttpClientBuilder();
  assertSSLHostnameVerifier(NoopHostnameVerifier.class, HttpClientUtil.getSocketFactoryRegistryProvider());
}
 
Example #6
Source File: DefaultEsClientFactory.java    From apiman with Apache License 2.0 5 votes vote down vote up
/**
 * Configures the SSL connection to use certificates by setting the keystores
 * @param httpConfig the http client configuration
 * @param config the configuration
 */
@SuppressWarnings("nls")
private void updateSslConfig(Builder httpConfig, Map<String, String> config) {
    try {
        String clientKeystorePath = config.get("client.keystore");
        String clientKeystorePassword = config.get("client.keystore.password");
        String trustStorePath = config.get("client.truststore");
        String trustStorePassword = config.get("client.truststore.password");

        SSLContextBuilder sslContextBuilder = SSLContextBuilder.create();

        String trustCertificate = config.get("client.trust.certificate");
        if (!StringUtils.isBlank(trustCertificate) && trustCertificate.equals("true")) {
            sslContextBuilder = sslContextBuilder.loadTrustMaterial(new TrustSelfSignedStrategy());
        }

        SSLContext sslContext = sslContextBuilder.build();
        Info kPathInfo = new Info(clientKeystorePath, clientKeystorePassword);
        Info tPathInfo = new Info(trustStorePath, trustStorePassword);
        sslContext.init(KeyStoreUtil.getKeyManagers(kPathInfo), KeyStoreUtil.getTrustManagers(tPathInfo), new SecureRandom());

        String trustHost = config.get("client.trust.host");
        HostnameVerifier hostnameVerifier = !StringUtils.isBlank(trustHost) && trustHost.equals("true") ? NoopHostnameVerifier.INSTANCE : new DefaultHostnameVerifier();

        SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
        SchemeIOSessionStrategy httpsIOSessionStrategy = new SSLIOSessionStrategy(sslContext, hostnameVerifier);

        httpConfig.defaultSchemeForDiscoveredNodes("https");
        httpConfig.sslSocketFactory(sslSocketFactory); // for sync calls
        httpConfig.httpsIOSessionStrategy(httpsIOSessionStrategy); // for async calls

    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example #7
Source File: Http4FileProvider.java    From commons-vfs with Apache License 2.0 5 votes vote down vote up
private HostnameVerifier createHostnameVerifier(final Http4FileSystemConfigBuilder builder,
        final FileSystemOptions fileSystemOptions) throws FileSystemException {
    if (!builder.isHostnameVerificationEnabled(fileSystemOptions)) {
        return NoopHostnameVerifier.INSTANCE;
    }

    return new DefaultHostnameVerifier();
}
 
Example #8
Source File: DefaultHttpConnector.java    From helios with Apache License 2.0 5 votes vote down vote up
public DefaultHttpConnector(final EndpointIterator endpointIterator,
                            final int httpTimeoutMillis,
                            final boolean sslHostnameVerificationEnabled) {
  this.endpointIterator = endpointIterator;
  this.httpTimeoutMillis = httpTimeoutMillis;
  this.hostnameVerifierProvider =
      new HostnameVerifierProvider(sslHostnameVerificationEnabled, new DefaultHostnameVerifier());
  this.extraHttpsHandler = null;
}
 
Example #9
Source File: SSLUtilsTest.java    From navigator-sdk with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetHostnameVerifier() {
  // Default
  HostnameVerifier verifier = SSLUtils.getHostnameVerifier(config);
  assertTrue(verifier instanceof DefaultHostnameVerifier);

  // Override
  config.setOverrideHostnameVerifier(new TestHostnameVerifier());
  verifier = SSLUtils.getHostnameVerifier(config);
  assertTrue(verifier instanceof TestHostnameVerifier);

  // Disabled
  config.setDisableSSLValidation(true);
  verifier = SSLUtils.getHostnameVerifier(config);
  assertTrue(verifier instanceof NoopHostnameVerifier);
}
 
Example #10
Source File: SSLUtils.java    From navigator-sdk with Apache License 2.0 5 votes vote down vote up
/**
 * If SSL validation is disabled then return a HostnameVerifier that accepts
 * everything. Otherwise, return the override HostnameVerifier in the config
 * if specified, or return a new DefaultHostnameVerifier
 *
 * @param config
 */
public static HostnameVerifier getHostnameVerifier(ClientConfig config) {
  if (config.isDisableSSLValidation()) {
    return new NoopHostnameVerifier();
  }
  if (config.getOverrideHostnameVerifier() == null) {
    return new DefaultHostnameVerifier();
  } else {
    return config.getOverrideHostnameVerifier();
  }
}
 
Example #11
Source File: DirectProxyHandler.java    From pulsar with Apache License 2.0 5 votes vote down vote up
private boolean verifyTlsHostName(String hostname, ChannelHandlerContext ctx) {
    ChannelHandler sslHandler = ctx.channel().pipeline().get("tls");

    SSLSession sslSession = null;
    if (sslHandler != null) {
        sslSession = ((SslHandler) sslHandler).engine().getSession();
        return (new DefaultHostnameVerifier()).verify(hostname, sslSession);
    }
    return false;
}
 
Example #12
Source File: AuthenticationTlsHostnameVerificationTest.java    From pulsar with Apache License 2.0 5 votes vote down vote up
/**
 * This test verifies {@link DefaultHostnameVerifier} behavior and gives fair idea about host matching result
 *
 * @throws Exception
 */
@Test
public void testDefaultHostVerifier() throws Exception {
    log.info("-- Starting {} test --", methodName);
    Method matchIdentityStrict = DefaultHostnameVerifier.class.getDeclaredMethod("matchIdentityStrict",
            String.class, String.class, PublicSuffixMatcher.class);
    matchIdentityStrict.setAccessible(true);
    Assert.assertTrue((boolean) matchIdentityStrict.invoke(null, "pulsar", "pulsar", null));
    Assert.assertFalse((boolean) matchIdentityStrict.invoke(null, "pulsar.com", "pulsar", null));
    Assert.assertTrue((boolean) matchIdentityStrict.invoke(null, "pulsar-broker1.com", "pulsar*.com", null));
    // unmatched remainder: "1-broker." should not contain "."
    Assert.assertFalse((boolean) matchIdentityStrict.invoke(null, "pulsar-broker1.com", "pulsar*com", null));
    Assert.assertFalse((boolean) matchIdentityStrict.invoke(null, "pulsar.com", "*", null));
    log.info("-- Exiting {} test --", methodName);
}
 
Example #13
Source File: HttpEventPublisher.java    From beam with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a {@link CloseableHttpClient} to make HTTP POSTs against Splunk's HEC.
 *
 * @param maxConnections max number of parallel connections
 * @param disableCertificateValidation should disable certificate validation
 */
private CloseableHttpClient getHttpClient(
    int maxConnections, boolean disableCertificateValidation)
    throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {

  HttpClientBuilder builder = ApacheHttpTransport.newDefaultHttpClientBuilder();

  if (genericUrl().getScheme().equalsIgnoreCase(HTTPS_PROTOCOL_PREFIX)) {
    LOG.info("SSL connection requested");

    HostnameVerifier hostnameVerifier =
        disableCertificateValidation
            ? NoopHostnameVerifier.INSTANCE
            : new DefaultHostnameVerifier();

    SSLContextBuilder sslContextBuilder = SSLContextBuilder.create();
    if (disableCertificateValidation) {
      LOG.info("Certificate validation is disabled");
      sslContextBuilder.loadTrustMaterial((TrustStrategy) (chain, authType) -> true);
    }

    SSLConnectionSocketFactory connectionSocketFactory =
        new SSLConnectionSocketFactory(sslContextBuilder.build(), hostnameVerifier);
    builder.setSSLSocketFactory(connectionSocketFactory);
  }

  builder.setMaxConnTotal(maxConnections);
  builder.setDefaultRequestConfig(
      RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build());

  return builder.build();
}
 
Example #14
Source File: SimpleHttpClient.java    From vespa with Apache License 2.0 5 votes vote down vote up
public SimpleHttpClient(SSLContext sslContext, List<String> enabledProtocols, List<String> enabledCiphers,
                        int listenPort, boolean useCompression) {
    HttpClientBuilder builder = HttpClientBuilder.create();
    if (!useCompression) {
        builder.disableContentCompression();
    }
    if (sslContext != null) {
        SSLConnectionSocketFactory sslConnectionFactory = new SSLConnectionSocketFactory(
                sslContext,
                toArray(enabledProtocols),
                toArray(enabledCiphers),
                new DefaultHostnameVerifier());
        builder.setSSLSocketFactory(sslConnectionFactory);

        Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("https", sslConnectionFactory)
                .build();
        builder.setConnectionManager(new BasicHttpClientConnectionManager(registry));
        scheme = "https";
    } else {
        scheme = "http";
    }
    this.delegate = builder.build();
    this.listenPort = listenPort;
}
 
Example #15
Source File: ExtendedHttpClientBuilder.java    From lavaplayer with Apache License 2.0 5 votes vote down vote up
private Registry<ConnectionSocketFactory> createConnectionSocketFactory() {
  HostnameVerifier hostnameVerifier = new DefaultHostnameVerifier(PublicSuffixMatcherLoader.getDefault());
  ConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContextOverride != null ?
      sslContextOverride : defaultSslContext, sslSupportedProtocols, null, hostnameVerifier);

  return RegistryBuilder.<ConnectionSocketFactory>create()
      .register("http", PlainConnectionSocketFactory.getSocketFactory())
      .register("https", sslSocketFactory)
      .build();
}
 
Example #16
Source File: SettingsBasedSSLConfigurator.java    From deprecated-security-advanced-modules with Apache License 2.0 5 votes vote down vote up
private HostnameVerifier getHostnameVerifier() {
    if (isHostnameVerificationEnabled()) {
        return new DefaultHostnameVerifier();
    } else {
        return NoopHostnameVerifier.INSTANCE;
    }
}
 
Example #17
Source File: HttpsFactoryTest.java    From api-layer with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void shouldCreateDefaultHostnameVerifier() {
    HttpsConfig httpsConfig = httpsConfigBuilder.build();
    HttpsFactory httpsFactory = new HttpsFactory(httpsConfig);
    HostnameVerifier hostnameVerifier = httpsFactory.createHostnameVerifier();
    assertEquals(DefaultHostnameVerifier.class, hostnameVerifier.getClass());
}
 
Example #18
Source File: CelleryCellStsService.java    From cellery-security with Apache License 2.0 5 votes vote down vote up
private void setHttpClientProperties() throws CelleryCellSTSException {

        CelleryTrustManager celleryTrustManager = new CelleryTrustManager();
        try {
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, new TrustManager[]{celleryTrustManager}, new java.security.SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
            HttpsURLConnection.setDefaultHostnameVerifier(
                    new CelleryHostnameVerifier(new DefaultHostnameVerifier()));
        } catch (KeyManagementException | NoSuchAlgorithmException e) {
            throw new CelleryCellSTSException("Error while initializing SSL context");
        }

    }
 
Example #19
Source File: WxPayServiceApacheHttpImpl.java    From weixin-java-tools with Apache License 2.0 5 votes vote down vote up
private void initSSLContext(HttpClientBuilder httpClientBuilder) throws WxPayException {
  SSLContext sslContext = this.getConfig().getSslContext();
  if (null == sslContext) {
    sslContext = this.getConfig().initSSLContext();
  }

  SSLConnectionSocketFactory connectionSocketFactory = new SSLConnectionSocketFactory(sslContext,
    new String[]{"TLSv1"}, null, new DefaultHostnameVerifier());
  httpClientBuilder.setSSLSocketFactory(connectionSocketFactory);
}
 
Example #20
Source File: ClientConfig.java    From mutual-tls-ssl with Apache License 2.0 5 votes vote down vote up
@Bean
@Scope("prototype")
public SSLFactory sslFactory(
        @Value("${client.ssl.one-way-authentication-enabled:false}") boolean oneWayAuthenticationEnabled,
        @Value("${client.ssl.two-way-authentication-enabled:false}") boolean twoWayAuthenticationEnabled,
        @Value("${client.ssl.key-store:}") String keyStorePath,
        @Value("${client.ssl.key-store-password:}") char[] keyStorePassword,
        @Value("${client.ssl.trust-store:}") String trustStorePath,
        @Value("${client.ssl.trust-store-password:}") char[] trustStorePassword) {
    if (!oneWayAuthenticationEnabled && !twoWayAuthenticationEnabled) {
        return null;
    }

    SSLFactory.Builder sslFactoryBuilder = SSLFactory.builder()
            .withHostnameVerifier(new DefaultHostnameVerifier())
            .withProtocol("TLSv1.3");

    if (oneWayAuthenticationEnabled) {
        sslFactoryBuilder.withTrustMaterial(trustStorePath, trustStorePassword);
    }

    if (twoWayAuthenticationEnabled) {
        sslFactoryBuilder.withIdentityMaterial(keyStorePath, keyStorePassword)
                .withTrustMaterial(trustStorePath, trustStorePassword);
    }
    return sslFactoryBuilder.build();
}
 
Example #21
Source File: ClientConfigShould.java    From mutual-tls-ssl with Apache License 2.0 5 votes vote down vote up
@Test
public void createSslFactoryWithOneWayAuthentication() {
    String trustStorePath = "keystores-for-unit-tests/truststore.jks";
    String trustStorePassword = "secret";

    SSLFactory sslFactory = victim.sslFactory(true, false,
            EMPTY, EMPTY.toCharArray(), trustStorePath, trustStorePassword.toCharArray());

    assertThat(sslFactory).isNotNull();
    assertThat(sslFactory.getSslContext()).isNotNull();
    assertThat(sslFactory.getKeyManager()).isNotPresent();
    assertThat(sslFactory.getTrustManager()).isNotNull();
    assertThat(sslFactory.getHostnameVerifier()).isInstanceOf(DefaultHostnameVerifier.class);
    assertThat(sslFactory.getSslContext().getProtocol()).isEqualTo("TLSv1.3");
}
 
Example #22
Source File: HtmlUnitSSLConnectionSocketFactory.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
private HtmlUnitSSLConnectionSocketFactory(final KeyStore keystore, final char[] keystorePassword,
        final KeyStore truststore, final boolean useInsecureSSL,
        final String[] supportedProtocols, final String[] supportedCipherSuites)
    throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
    super(SSLContexts.custom()
            .loadKeyMaterial(keystore, keystorePassword).loadTrustMaterial(truststore, null).build(),
            supportedProtocols, supportedCipherSuites,
            new DefaultHostnameVerifier());
    useInsecureSSL_ = useInsecureSSL;
}
 
Example #23
Source File: HTTPConnectionFactory.java    From emissary with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
HTTPConnectionFactory(final Configurator config) {
    Registry<ConnectionSocketFactory> registry = null;
    try {
        final Configurator cfg = config == null ? ConfigUtil.getConfigInfo(HTTPConnectionFactory.class) : config;
        // if someone doesn't want keep alives...
        if (!cfg.findBooleanEntry(CFG_HTTP_KEEPALIVE, DFLT_KEEPALIVE)) {
            this.connReuseStrategy = NoConnectionReuseStrategy.INSTANCE;
        }
        this.maxConns = cfg.findIntEntry(CFG_HTTP_MAXCONNS, DFLT_MAXCONNS);
        this.userAgent = cfg.findStringEntry(CFG_HTTP_AGENT, DEFAULT_HTTP_AGENT);
        final SSLContext sslContext = build(cfg);
        // mainly for using in test environments where cert name may not match host name
        final HostnameVerifier v = cfg.findBooleanEntry(CFG_NOOP_VERIFIER, false) ? new NoopHostnameVerifier() : new DefaultHostnameVerifier();
        registry =
                RegistryBuilder.<ConnectionSocketFactory>create().register(HTTP, PlainConnectionSocketFactory.getSocketFactory())
                        .register(HTTPS, new SSLConnectionSocketFactory(sslContext, v)).build();
    } catch (IOException | GeneralSecurityException ex) {
        log.error("Error configuring HTTPConnectionFactory. The connection factory will use HTTP Client default settings", ex);
    }
    if (registry == null) {
        this.connMan = new PoolingHttpClientConnectionManager();
    } else {
        this.connMan = new PoolingHttpClientConnectionManager(registry);
    }

    this.connMan.setMaxTotal(this.maxConns);
}
 
Example #24
Source File: SecurityUtils.java    From api-layer with Eclipse Public License 2.0 5 votes vote down vote up
public static SSLConfig getConfiguredSslConfig() {
    TlsConfiguration tlsConfiguration = ConfigReader.environmentConfiguration().getTlsConfiguration();
    try {
        SSLContext sslContext = SSLContexts.custom()
            .loadKeyMaterial(
                new File(tlsConfiguration.getKeyStore()),
                tlsConfiguration.getKeyStorePassword() != null ? tlsConfiguration.getKeyStorePassword().toCharArray() : null,
                tlsConfiguration.getKeyPassword() != null ? tlsConfiguration.getKeyPassword().toCharArray() : null,
                (aliases, socket) -> tlsConfiguration.getKeyAlias())
            .loadTrustMaterial(
                new File(tlsConfiguration.getTrustStore()),
                tlsConfiguration.getTrustStorePassword() != null ? tlsConfiguration.getTrustStorePassword().toCharArray() : null)
            .build();
        SSLSocketFactoryAdapter sslSocketFactory = new SSLSocketFactoryAdapter(new SSLConnectionSocketFactory(sslContext, new DefaultHostnameVerifier()));
        return SSLConfig.sslConfig().with().sslSocketFactory(sslSocketFactory);
    } catch (KeyManagementException | UnrecoverableKeyException | NoSuchAlgorithmException | KeyStoreException
        | CertificateException | IOException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}
 
Example #25
Source File: HttpClient.java    From qonduit with Apache License 2.0 5 votes vote down vote up
public static CloseableHttpClient get(SSLContext ssl, CookieStore cookieStore, boolean hostVerificationEnabled) {
    RequestConfig defaultRequestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build();

    HttpClientBuilder builder = HttpClients.custom().setSSLContext(ssl).setDefaultCookieStore(cookieStore)
            .setDefaultRequestConfig(defaultRequestConfig);
    if (hostVerificationEnabled) {
        builder.setSSLHostnameVerifier(new DefaultHostnameVerifier());
    } else {
        builder.setSSLHostnameVerifier(new NoopHostnameVerifier());
    }
    return builder.build();
}
 
Example #26
Source File: BaseParser.java    From substitution-schedule-parser with Mozilla Public License 2.0 4 votes vote down vote up
public CustomHostnameVerifier(String host) {
    this.host = host;
    this.defaultHostnameVerifier = new DefaultHostnameVerifier();
}
 
Example #27
Source File: SSLConnectionSocketFactoryFactory.java    From zap-extensions with Apache License 2.0 4 votes vote down vote up
/**
 * Creates a new SSLConnectionSocketFactory with the behavior described in
 * {@link #getFactory(String, CodeDxExtension)}. Instead of returning, this
 * method registers the factory instance to the <code>factoriesByHost<code>
 * map, as well as registering its <code>ExtraCertManager</code> to the
 * <code>certManagersByHost</code> map. The cert manager registration is
 * important in order to detect and purge trusted certificates on a per-host
 * basis.
 * 
 * @param host
 * @param extension
 * @throws IOException
 * @throws GeneralSecurityException
 */
private static void initializeFactory(
	String host,
	CodeDxExtension extension,
	String fingerprint,
	boolean acceptPermanently
) throws IOException, GeneralSecurityException {
	// set up the certificate management
	File managedKeyStoreFile = getTrustStoreForHost(host);
	ExtraCertManager certManager = new SingleExtraCertManager(managedKeyStoreFile, "u9lwIfUpaN");

	// get the default hostname verifier that gets used by the modified one
	// and the invalid cert dialog
	HostnameVerifier defaultHostnameVerifier = new DefaultHostnameVerifier();

	
	InvalidCertificateStrategy invalidCertStrat;
	if(fingerprint == null){
		invalidCertStrat = new InvalidCertificateDialogStrategy(defaultHostnameVerifier, host, extension);
	} else {
		invalidCertStrat = new InvalidCertificateFingerprintStrategy(fingerprint, acceptPermanently);
	}

	/*
	 * Set up a composite trust manager that uses the default trust manager
	 * before delegating to the "reloadable" trust manager that allows users
	 * to accept invalid certificates.
	 */
	List<X509TrustManager> trustManagersForComposite = new LinkedList<>();
	X509TrustManager systemTrustManager = getDefaultTrustManager();
	ReloadableX509TrustManager customTrustManager = new ReloadableX509TrustManager(certManager, invalidCertStrat);
	trustManagersForComposite.add(systemTrustManager);
	trustManagersForComposite.add(customTrustManager);
	X509TrustManager trustManager = new CompositeX509TrustManager(trustManagersForComposite);

	// setup the SSLContext using the custom trust manager
	SSLContext sslContext = SSLContext.getInstance("TLS");
	sslContext.init(null, new TrustManager[] { trustManager }, null);
	// the actual hostname verifier that will be used with the socket
	// factory
	Set<String> allowedHosts = new HashSet<>();
	allowedHosts.add(host);
	HostnameVerifier modifiedHostnameVerifier = new HostnameVerifierWithExceptions(defaultHostnameVerifier, allowedHosts);
	
	SSLConnectionSocketFactory factory = new SSLConnectionSocketFactory(sslContext, modifiedHostnameVerifier);
	// Register the `factory` and the `customTrustManager` under the given
	// `host`
	if(fingerprint == null){
		dialogFactoriesByHost.put(host, factory);
	} else {
		fingerprintFactoriesByHost.put(host, factory);
	}
}
 
Example #28
Source File: WebUtils.java    From nifi with Apache License 2.0 4 votes vote down vote up
/**
 * A helper method for creating clients. The client will be created using
 * the given configuration and security context. Additionally, the client
 * will be automatically configured for JSON serialization/deserialization.
 *
 * @param config client configuration
 * @param ctx    security context, which may be null for non-secure client
 *               creation
 * @return a Client instance
 */
private static Client createClientHelper(final ClientConfig config, final SSLContext ctx) {

    ClientBuilder clientBuilder = ClientBuilder.newBuilder();

    if (config != null) {
        clientBuilder = clientBuilder.withConfig(config);
    }

    if (ctx != null) {

        // Apache http DefaultHostnameVerifier that checks subject alternative names against the hostname of the URI
        clientBuilder = clientBuilder.sslContext(ctx).hostnameVerifier(new DefaultHostnameVerifier());
    }

    clientBuilder = clientBuilder.register(ObjectMapperResolver.class).register(JacksonJaxbJsonProvider.class);

    return clientBuilder.build();

}
 
Example #29
Source File: ClusterLoadBalanceAuthorizer.java    From nifi with Apache License 2.0 4 votes vote down vote up
public ClusterLoadBalanceAuthorizer(final ClusterCoordinator clusterCoordinator, final EventReporter eventReporter) {
    this.clusterCoordinator = clusterCoordinator;
    this.eventReporter = eventReporter;
    this.hostnameVerifier = new DefaultHostnameVerifier();
}
 
Example #30
Source File: AbstractAWSProcessor.java    From nifi with Apache License 2.0 4 votes vote down vote up
protected ClientConfiguration createConfiguration(final ProcessContext context) {
    final ClientConfiguration config = new ClientConfiguration();
    config.setMaxConnections(context.getMaxConcurrentTasks());
    config.setMaxErrorRetry(0);
    config.setUserAgent(DEFAULT_USER_AGENT);
    // If this is changed to be a property, ensure other uses are also changed
    config.setProtocol(DEFAULT_PROTOCOL);
    final int commsTimeout = context.getProperty(TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue();
    config.setConnectionTimeout(commsTimeout);
    config.setSocketTimeout(commsTimeout);

    if(this.getSupportedPropertyDescriptors().contains(SSL_CONTEXT_SERVICE)) {
        final SSLContextService sslContextService = context.getProperty(SSL_CONTEXT_SERVICE).asControllerService(SSLContextService.class);
        if (sslContextService != null) {
            final SSLContext sslContext = sslContextService.createSSLContext(SslContextFactory.ClientAuth.NONE);
            // NIFI-3788: Changed hostnameVerifier from null to DHV (BrowserCompatibleHostnameVerifier is deprecated)
            SdkTLSSocketFactory sdkTLSSocketFactory = new SdkTLSSocketFactory(sslContext, new DefaultHostnameVerifier());
            config.getApacheHttpClientConfig().setSslSocketFactory(sdkTLSSocketFactory);
        }
    }

    final ProxyConfiguration proxyConfig = ProxyConfiguration.getConfiguration(context, () -> {
        if (context.getProperty(PROXY_HOST).isSet()) {
            final ProxyConfiguration componentProxyConfig = new ProxyConfiguration();
            String proxyHost = context.getProperty(PROXY_HOST).evaluateAttributeExpressions().getValue();
            Integer proxyPort = context.getProperty(PROXY_HOST_PORT).evaluateAttributeExpressions().asInteger();
            String proxyUsername = context.getProperty(PROXY_USERNAME).evaluateAttributeExpressions().getValue();
            String proxyPassword = context.getProperty(PROXY_PASSWORD).evaluateAttributeExpressions().getValue();
            componentProxyConfig.setProxyType(Proxy.Type.HTTP);
            componentProxyConfig.setProxyServerHost(proxyHost);
            componentProxyConfig.setProxyServerPort(proxyPort);
            componentProxyConfig.setProxyUserName(proxyUsername);
            componentProxyConfig.setProxyUserPassword(proxyPassword);
            return componentProxyConfig;
        }
        return ProxyConfiguration.DIRECT_CONFIGURATION;
    });

    if (Proxy.Type.HTTP.equals(proxyConfig.getProxyType())) {
        config.setProxyHost(proxyConfig.getProxyServerHost());
        config.setProxyPort(proxyConfig.getProxyServerPort());

        if (proxyConfig.hasCredential()) {
            config.setProxyUsername(proxyConfig.getProxyUserName());
            config.setProxyPassword(proxyConfig.getProxyUserPassword());
        }
    }

    return config;
}