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

The following examples show how to use org.apache.http.conn.ssl.TrustAllStrategy. 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: HttpClientSteps.java    From yaks with Apache License 2.0 6 votes vote down vote up
/**
 * Get secure http client implementation with trust all strategy and noop host name verifier.
 * @return
 */
private org.apache.http.client.HttpClient sslClient() {
    try {
        SSLContext sslcontext = SSLContexts
                .custom()
                .loadTrustMaterial(TrustAllStrategy.INSTANCE)
                .build();

        SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(
                sslcontext, NoopHostnameVerifier.INSTANCE);

        return HttpClients
                .custom()
                .setSSLSocketFactory(sslSocketFactory)
                .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
                .build();
    } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) {
        throw new CitrusRuntimeException("Failed to create http client for ssl connection", e);
    }
}
 
Example #2
Source File: DefaultConsulConfigGateway.java    From quarkus with Apache License 2.0 6 votes vote down vote up
private SSLConnectionSocketFactory createFactoryFromAgentConfig(ConsulConfig.AgentConfig agentConfig) {
    try {
        SSLContextBuilder sslContextBuilder = SSLContexts.custom();
        if (agentConfig.trustStore.isPresent()) {
            sslContextBuilder = sslContextBuilder
                    .loadTrustMaterial(readStore(agentConfig.trustStore.get(), agentConfig.trustStorePassword), null);
        } else if (agentConfig.trustCerts) {
            sslContextBuilder = sslContextBuilder.loadTrustMaterial(TrustAllStrategy.INSTANCE);
        }
        if (agentConfig.keyStore.isPresent()) {
            String keyPassword = agentConfig.keyPassword.orElse(agentConfig.keyStorePassword.orElse(""));
            sslContextBuilder = sslContextBuilder.loadKeyMaterial(
                    readStore(agentConfig.keyStore.get(), agentConfig.keyStorePassword), keyPassword.toCharArray());
        }
        return new SSLConnectionSocketFactory(sslContextBuilder.build(), NoopHostnameVerifier.INSTANCE);
    } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException | IOException | CertificateException
            | UnrecoverableKeyException e) {
        throw new RuntimeException(e);
    }
}
 
Example #3
Source File: APIImportConfigAdapter.java    From apimanager-swagger-promote with Apache License 2.0 6 votes vote down vote up
private SSLConnectionSocketFactory createSSLContext() throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException, UnrecoverableKeyException {
	SSLContextBuilder builder = new SSLContextBuilder();
	builder.loadTrustMaterial(null, new TrustAllStrategy());
	
	String keyStorePath=System.getProperty("javax.net.ssl.keyStore","");
	if (StringUtils.isNotEmpty(keyStorePath)) {
		String keyStorePassword=System.getProperty("javax.net.ssl.keyStorePassword","");
		if (StringUtils.isNotEmpty(keyStorePassword)) {
			String keystoreType=System.getProperty("javax.net.ssl.keyStoreType",KeyStore.getDefaultType());
			LOG.debug("Reading keystore from {}",keyStorePath);
			KeyStore ks = KeyStore.getInstance(keystoreType);
			ks.load(new FileInputStream(new File(keyStorePath)), keyStorePassword.toCharArray());				
			builder.loadKeyMaterial(ks,keyStorePassword.toCharArray());
		}
	} else {
		LOG.debug("NO javax.net.ssl.keyStore property.");
	}
	String [] tlsProts = getAcceptedTLSProtocols();
	SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
			builder.build(),
               tlsProts,
               null,
               new NoopHostnameVerifier());
	return sslsf;
}
 
Example #4
Source File: ConnectorCommon.java    From nextcloud-java-api with GNU General Public License v3.0 6 votes vote down vote up
public static CloseableHttpAsyncClient getInstance(ServerConfig serverConfig)
	throws IOException{
	if (HTTPC_CLIENT == null) {
		if (serverConfig.isTrustAllCertificates()) {
			try {
				SSLContext sslContext = SSLContexts.custom()
					.loadTrustMaterial(null, TrustAllStrategy.INSTANCE).build();
				HTTPC_CLIENT = HttpAsyncClients.custom()
					.setSSLHostnameVerifier((NoopHostnameVerifier.INSTANCE))
					.setSSLContext(sslContext)
					.build();
			} catch (KeyManagementException | NoSuchAlgorithmException
					| KeyStoreException e) {
				throw new IOException(e);
			} 
			
		} else {
			HTTPC_CLIENT = HttpAsyncClients.createDefault();
		}
		
		HTTPC_CLIENT.start();
	}
	return HTTPC_CLIENT;
}
 
Example #5
Source File: ReportPortalService.java    From courgette-jvm with MIT License 6 votes vote down vote up
private HttpResponse sendMultiPartPost(String url, String authorization, File file) {
    try {
        SSLContext trustedSSLContext = new SSLContextBuilder().loadTrustMaterial(null, TrustAllStrategy.INSTANCE).build();

        HttpClient httpClient = HttpClientBuilder.create().setSSLContext(trustedSSLContext).build();

        HttpEntity entity = MultipartEntityBuilder
                .create()
                .addBinaryBody("file", file)
                .build();

        HttpPost httpPost = new HttpPost(url);
        httpPost.addHeader("Authorization", authorization);
        httpPost.setEntity(entity);
        return httpClient.execute(httpPost);
    } catch (Exception e) {
        System.err.format("Unable to send the report to report portal server, reason: %s", e.getMessage());
        return null;
    }
}
 
Example #6
Source File: HealthCheckProxyHandler.java    From vespa with Apache License 2.0 6 votes vote down vote up
private SSLContext getSslContext(SslContextFactory.Server sslContextFactory) {
    if (sslContextFactory.getNeedClientAuth()) {
        log.info(String.format("Port %d requires client certificate. HTTPS client will use the target server connector's ssl context.", port));
        // A client certificate is only required if the server connector's ssl context factory is configured with "need-auth".
        // We use the server's ssl context (truststore + keystore) if a client certificate is required.
        // This will only work if the server certificate's CA is in the truststore.
        return sslContextFactory.getSslContext();
    } else {
        log.info(String.format(
                "Port %d does not require a client certificate. HTTPS client will use a custom ssl context accepting all certificates.", port));
        // No client certificate required. The client is configured with a trust manager that accepts all certificates.
        try {
            return SSLContexts.custom().loadTrustMaterial(new TrustAllStrategy()).build();
        } catch (GeneralSecurityException e) {
            throw new RuntimeException(e);
        }
    }
}
 
Example #7
Source File: SslContextFactory.java    From vividus with Apache License 2.0 5 votes vote down vote up
@Override
public SSLContext getTrustingAllSslContext(String protocol)
{
    try
    {
        return createBuilder(protocol)
                .loadTrustMaterial(TrustAllStrategy.INSTANCE)
                .build();
    }
    catch (GeneralSecurityException e)
    {
        throw new IllegalStateException(e);
    }
}
 
Example #8
Source File: HttpPingChecker.java    From jkube with Eclipse Public License 2.0 4 votes vote down vote up
private boolean ping() throws IOException {
    RequestConfig requestConfig =
            RequestConfig.custom()
                    .setSocketTimeout(HTTP_PING_TIMEOUT)
                    .setConnectTimeout(HTTP_PING_TIMEOUT)
                    .setConnectionRequestTimeout(HTTP_PING_TIMEOUT)
                    .setRedirectsEnabled(false)
                    .build();

    CloseableHttpClient httpClient;
    if (allowAllHosts) {
        SSLContextBuilder builder = new SSLContextBuilder();
        try {
            builder.loadTrustMaterial(new TrustAllStrategy());
            SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(builder.build(), NoopHostnameVerifier.INSTANCE);
            httpClient = HttpClientBuilder.create()
                                          .setDefaultRequestConfig(requestConfig)
                                          .setRetryHandler(new DefaultHttpRequestRetryHandler(HTTP_CLIENT_RETRIES, false))
                                          .setSSLSocketFactory(socketFactory)
                                          .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
                                          .build();
        } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) {
            throw new IOException("Unable to set self signed strategy on http wait: " + e, e);
        }
    } else {
        httpClient = HttpClientBuilder.create()
                .setDefaultRequestConfig(requestConfig)
                .setRetryHandler(new DefaultHttpRequestRetryHandler(HTTP_CLIENT_RETRIES, false))
                .build();
    }

    try (CloseableHttpResponse response = httpClient.execute(RequestBuilder.create(method.toUpperCase()).setUri(url).build())) {
        int responseCode = response.getStatusLine().getStatusCode();
        if (responseCode == HttpURLConnection.HTTP_NOT_IMPLEMENTED) {
            throw new IllegalArgumentException("Invalid or not supported HTTP method '" + method.toUpperCase() + "' for checking " + url);
        }
        return responseCode >= statusMin && responseCode <= statusMax;
    } finally {
      httpClient.close();
    }
}
 
Example #9
Source File: QWACValidationTest.java    From dss with GNU Lesser General Public License v2.1 4 votes vote down vote up
@Test
public void test() {

	TrustedListsCertificateSource trustedListsCertificateSource = new TrustedListsCertificateSource();
	RevocationSource<OCSP> ocspSource = new OnlineOCSPSource();
	RevocationSource<CRL> crlSource = new OnlineCRLSource();

	// tag::demo[]
	// We firstly need an Internet Access. Additional configuration may be required
	// (proxy,...)
	CommonsDataLoader dataLoader = new CommonsDataLoader();

	// We set an instance of TrustAllStrategy to rely on the Trusted Lists content
	// instead of the JVM trust store.
	dataLoader.setTrustStrategy(TrustAllStrategy.INSTANCE);

	// Secondly, we create an instance of SSLCertificateLoader which is responsible
	// of the SSL certificate(s) download.
	SSLCertificateLoader sslCertificateLoader = new SSLCertificateLoader();
	// We set the configured dataLoader
	sslCertificateLoader.setCommonsDataLoader(dataLoader);

	// Thirdly, we need to configure the CertificateVerifier
	CertificateVerifier cv = new CommonCertificateVerifier();
	cv.setTrustedCertSources(trustedListsCertificateSource); // configured trusted list certificate source
	cv.setDataLoader(dataLoader); // configured AIA Access
	cv.setOcspSource(ocspSource); // configured OCSP Access
	cv.setCrlSource(crlSource); // configured CRL Access

	// We retrieve the SSL certificates for the given URL
	List<CertificateToken> certificates = sslCertificateLoader.getCertificates("https://www.microsec.hu");

	CertificateToken sslCertificate = certificates.get(0);

	// Add intermediate certificates as non trusted certificates (adjunct)
	CertificateSource adjunctCertSource = new CommonCertificateSource();
	for (CertificateToken certificateToken : certificates) {
		adjunctCertSource.addCertificate(certificateToken);
	}
	cv.setAdjunctCertSources(adjunctCertSource);

	// Create an instance of CertificateValidator for the SSL Certificate with the
	// CertificateVerifier
	CertificateValidator validator = CertificateValidator.fromCertificate(sslCertificate);
	validator.setCertificateVerifier(cv);

	CertificateReports reports = validator.validate();
	SimpleCertificateReport simpleReport = reports.getSimpleReport();
	DetailedReport detailedReport = reports.getDetailedReport();
	DiagnosticData diagnosticData = reports.getDiagnosticData();

	// end::demo[]
	assertNotNull(simpleReport);
	assertNotNull(detailedReport);
	assertNotNull(diagnosticData);

}
 
Example #10
Source File: HttpPingChecker.java    From docker-maven-plugin with Apache License 2.0 4 votes vote down vote up
private boolean ping() throws IOException {
    RequestConfig requestConfig =
            RequestConfig.custom()
                    .setSocketTimeout(HTTP_PING_TIMEOUT)
                    .setConnectTimeout(HTTP_PING_TIMEOUT)
                    .setConnectionRequestTimeout(HTTP_PING_TIMEOUT)
                    .setRedirectsEnabled(false)
                    .build();

    CloseableHttpClient httpClient;
    if (allowAllHosts) {
        SSLContextBuilder builder = new SSLContextBuilder();
        try {
            builder.loadTrustMaterial(new TrustAllStrategy());
            SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(builder.build(), NoopHostnameVerifier.INSTANCE);
            httpClient = HttpClientBuilder.create()
                                          .setDefaultRequestConfig(requestConfig)
                                          .setRetryHandler(new DefaultHttpRequestRetryHandler(HTTP_CLIENT_RETRIES, false))
                                          .setSSLSocketFactory(socketFactory)
                                          .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
                                          .build();
        } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) {
            throw new IOException("Unable to set self signed strategy on http wait: " + e, e);
        }
    } else {
        httpClient = HttpClientBuilder.create()
                .setDefaultRequestConfig(requestConfig)
                .setRetryHandler(new DefaultHttpRequestRetryHandler(HTTP_CLIENT_RETRIES, false))
                .build();
    }

    try (CloseableHttpResponse response = httpClient.execute(RequestBuilder.create(method.toUpperCase()).setUri(url).build())) {
        int responseCode = response.getStatusLine().getStatusCode();
        if (responseCode == HttpURLConnection.HTTP_NOT_IMPLEMENTED) {
            throw new IllegalArgumentException("Invalid or not supported HTTP method '" + method.toUpperCase() + "' for checking " + url);
        }
        return responseCode >= statusMin && responseCode <= statusMax;
    } finally {
      httpClient.close();
    }
}