Search in sources :

Example 1 with TrustSelfSignedStrategy

use of org.apache.http.conn.ssl.TrustSelfSignedStrategy in project spring-boot by spring-projects.

the class EndpointWebMvcAutoConfigurationTests method assertContent.

private void assertContent(String scheme, String url, int port, Object expected) throws Exception {
    SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build());
    HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory).build();
    HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
    ClientHttpRequest request = requestFactory.createRequest(new URI(scheme + "://localhost:" + port + url), HttpMethod.GET);
    try {
        ClientHttpResponse response = request.execute();
        if (HttpStatus.NOT_FOUND.equals(response.getStatusCode())) {
            throw new FileNotFoundException();
        }
        try {
            String actual = StreamUtils.copyToString(response.getBody(), Charset.forName("UTF-8"));
            if (expected instanceof Matcher) {
                assertThat(actual).is(Matched.by((Matcher<?>) expected));
            } else {
                assertThat(actual).isEqualTo(expected);
            }
        } finally {
            response.close();
        }
    } catch (Exception ex) {
        if (expected == null) {
            if (SocketException.class.isInstance(ex) || FileNotFoundException.class.isInstance(ex)) {
                return;
            }
        }
        throw ex;
    }
}
Also used : Matcher(org.hamcrest.Matcher) HttpClient(org.apache.http.client.HttpClient) FileNotFoundException(java.io.FileNotFoundException) HttpComponentsClientHttpRequestFactory(org.springframework.http.client.HttpComponentsClientHttpRequestFactory) ClientHttpRequest(org.springframework.http.client.ClientHttpRequest) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) SSLContextBuilder(org.apache.http.ssl.SSLContextBuilder) URI(java.net.URI) ClientHttpResponse(org.springframework.http.client.ClientHttpResponse) TrustSelfSignedStrategy(org.apache.http.conn.ssl.TrustSelfSignedStrategy) FileNotFoundException(java.io.FileNotFoundException) WebServerException(org.springframework.boot.web.server.WebServerException) SocketException(java.net.SocketException) ExpectedException(org.junit.rules.ExpectedException)

Example 2 with TrustSelfSignedStrategy

use of org.apache.http.conn.ssl.TrustSelfSignedStrategy in project camel by apache.

the class JettySolrFactory method installAllTrustingClientSsl.

private static void installAllTrustingClientSsl() throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException {
    SSLContextBuilder builder = new SSLContextBuilder();
    builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
    // // Create a trust manager that does not validate certificate chains
    final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

        @Override
        public void checkClientTrusted(final X509Certificate[] chain, final String authType) {
        }

        @Override
        public void checkServerTrusted(final X509Certificate[] chain, final String authType) {
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    } };
    final SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
    SSLContext.setDefault(sslContext);
// // Install the all-trusting trust manager
// final SSLContext sslContext = SSLContext.getInstance( "SSL" );
// sslContext.init( null, trustAllCerts, new
// java.security.SecureRandom() );
// // Create an ssl socket factory with our all-trusting manager
// final SSLSocketFactory sslSocketFactory =
// sslContext.getSocketFactory();
// HttpsURLConnection.setDefaultSSLSocketFactory(sslSocketFactory);
}
Also used : X509TrustManager(javax.net.ssl.X509TrustManager) SSLContext(javax.net.ssl.SSLContext) SSLContextBuilder(org.apache.http.conn.ssl.SSLContextBuilder) TrustSelfSignedStrategy(org.apache.http.conn.ssl.TrustSelfSignedStrategy) X509Certificate(java.security.cert.X509Certificate) TrustManager(javax.net.ssl.TrustManager) X509TrustManager(javax.net.ssl.X509TrustManager)

Example 3 with TrustSelfSignedStrategy

use of org.apache.http.conn.ssl.TrustSelfSignedStrategy in project nifi by apache.

the class GetHTTP method createSSLContext.

private SSLContext createSSLContext(final SSLContextService service) throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException, KeyManagementException, UnrecoverableKeyException {
    final SSLContextBuilder sslContextBuilder = new SSLContextBuilder();
    if (StringUtils.isNotBlank(service.getTrustStoreFile())) {
        final KeyStore truststore = KeyStoreUtils.getTrustStore(service.getTrustStoreType());
        try (final InputStream in = new FileInputStream(new File(service.getTrustStoreFile()))) {
            truststore.load(in, service.getTrustStorePassword().toCharArray());
        }
        sslContextBuilder.loadTrustMaterial(truststore, new TrustSelfSignedStrategy());
    }
    if (StringUtils.isNotBlank(service.getKeyStoreFile())) {
        final KeyStore keystore = KeyStoreUtils.getKeyStore(service.getKeyStoreType());
        try (final InputStream in = new FileInputStream(new File(service.getKeyStoreFile()))) {
            keystore.load(in, service.getKeyStorePassword().toCharArray());
        }
        sslContextBuilder.loadKeyMaterial(keystore, service.getKeyStorePassword().toCharArray());
    }
    sslContextBuilder.useProtocol(service.getSslAlgorithm());
    return sslContextBuilder.build();
}
Also used : FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) SSLContextBuilder(org.apache.http.ssl.SSLContextBuilder) KeyStore(java.security.KeyStore) FlowFile(org.apache.nifi.flowfile.FlowFile) File(java.io.File) FileInputStream(java.io.FileInputStream) TrustSelfSignedStrategy(org.apache.http.conn.ssl.TrustSelfSignedStrategy)

Example 4 with TrustSelfSignedStrategy

use of org.apache.http.conn.ssl.TrustSelfSignedStrategy in project nifi by apache.

the class PostHTTP method createSSLContext.

private SSLContext createSSLContext(final SSLContextService service) throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException, KeyManagementException, UnrecoverableKeyException {
    SSLContextBuilder builder = SSLContexts.custom();
    final String trustFilename = service.getTrustStoreFile();
    if (trustFilename != null) {
        final KeyStore truststore = KeyStoreUtils.getTrustStore(service.getTrustStoreType());
        try (final InputStream in = new FileInputStream(new File(service.getTrustStoreFile()))) {
            truststore.load(in, service.getTrustStorePassword().toCharArray());
        }
        builder = builder.loadTrustMaterial(truststore, new TrustSelfSignedStrategy());
    }
    final String keyFilename = service.getKeyStoreFile();
    if (keyFilename != null) {
        final KeyStore keystore = KeyStoreUtils.getKeyStore(service.getKeyStoreType());
        try (final InputStream in = new FileInputStream(new File(service.getKeyStoreFile()))) {
            keystore.load(in, service.getKeyStorePassword().toCharArray());
        }
        builder = builder.loadKeyMaterial(keystore, service.getKeyStorePassword().toCharArray());
    }
    builder = builder.useProtocol(service.getSslAlgorithm());
    final SSLContext sslContext = builder.build();
    return sslContext;
}
Also used : BufferedInputStream(java.io.BufferedInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) SSLContext(javax.net.ssl.SSLContext) SSLContextBuilder(org.apache.http.conn.ssl.SSLContextBuilder) KeyStore(java.security.KeyStore) File(java.io.File) FlowFile(org.apache.nifi.flowfile.FlowFile) FileInputStream(java.io.FileInputStream) TrustSelfSignedStrategy(org.apache.http.conn.ssl.TrustSelfSignedStrategy)

Example 5 with TrustSelfSignedStrategy

use of org.apache.http.conn.ssl.TrustSelfSignedStrategy in project nifi by apache.

the class TlsCertificateSigningRequestPerformer method perform.

/**
 * Submits a CSR to the Certificate authority, checks the resulting hmac, and returns the chain if everything succeeds
 *
 * @param keyPair the keypair to generate the csr for
 * @throws IOException if there is a problem during the process
 * @return the resulting certificate chain
 */
public X509Certificate[] perform(KeyPair keyPair) throws IOException {
    try {
        List<X509Certificate> certificates = new ArrayList<>();
        HttpClientBuilder httpClientBuilder = httpClientBuilderSupplier.get();
        SSLContextBuilder sslContextBuilder = SSLContextBuilder.create();
        sslContextBuilder.useProtocol("TLSv1.2");
        // We will be validating that we are talking to the correct host once we get the response's hmac of the token and public key of the ca
        sslContextBuilder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
        httpClientBuilder.setSSLSocketFactory(new TlsCertificateAuthorityClientSocketFactory(sslContextBuilder.build(), caHostname, certificates));
        String jsonResponseString;
        int responseCode;
        try (CloseableHttpClient client = httpClientBuilder.build()) {
            JcaPKCS10CertificationRequest request = TlsHelper.generateCertificationRequest(dn, domainAlternativeNames, keyPair, signingAlgorithm);
            TlsCertificateAuthorityRequest tlsCertificateAuthorityRequest = new TlsCertificateAuthorityRequest(TlsHelper.calculateHMac(token, request.getPublicKey()), TlsHelper.pemEncodeJcaObject(request));
            HttpPost httpPost = new HttpPost();
            httpPost.setEntity(new ByteArrayEntity(objectMapper.writeValueAsBytes(tlsCertificateAuthorityRequest)));
            if (logger.isInfoEnabled()) {
                logger.info("Requesting certificate with dn " + dn + " from " + caHostname + ":" + port);
            }
            try (CloseableHttpResponse response = client.execute(new HttpHost(caHostname, port, "https"), httpPost)) {
                jsonResponseString = IOUtils.toString(new BoundedInputStream(response.getEntity().getContent(), 1024 * 1024), StandardCharsets.UTF_8);
                responseCode = response.getStatusLine().getStatusCode();
            }
        }
        if (responseCode != Response.SC_OK) {
            throw new IOException(RECEIVED_RESPONSE_CODE + responseCode + " with payload " + jsonResponseString);
        }
        if (certificates.size() != 1) {
            throw new IOException(EXPECTED_ONE_CERTIFICATE);
        }
        TlsCertificateAuthorityResponse tlsCertificateAuthorityResponse = objectMapper.readValue(jsonResponseString, TlsCertificateAuthorityResponse.class);
        if (!tlsCertificateAuthorityResponse.hasHmac()) {
            throw new IOException(EXPECTED_RESPONSE_TO_CONTAIN_HMAC);
        }
        X509Certificate caCertificate = certificates.get(0);
        byte[] expectedHmac = TlsHelper.calculateHMac(token, caCertificate.getPublicKey());
        if (!MessageDigest.isEqual(expectedHmac, tlsCertificateAuthorityResponse.getHmac())) {
            throw new IOException(UNEXPECTED_HMAC_RECEIVED_POSSIBLE_MAN_IN_THE_MIDDLE);
        }
        if (!tlsCertificateAuthorityResponse.hasCertificate()) {
            throw new IOException(EXPECTED_RESPONSE_TO_CONTAIN_CERTIFICATE);
        }
        X509Certificate x509Certificate = TlsHelper.parseCertificate(new StringReader(tlsCertificateAuthorityResponse.getPemEncodedCertificate()));
        x509Certificate.verify(caCertificate.getPublicKey());
        if (logger.isInfoEnabled()) {
            logger.info("Got certificate with dn " + x509Certificate.getSubjectX500Principal());
        }
        return new X509Certificate[] { x509Certificate, caCertificate };
    } catch (IOException e) {
        throw e;
    } catch (Exception e) {
        throw new IOException(e);
    }
}
Also used : CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) HttpPost(org.apache.http.client.methods.HttpPost) JcaPKCS10CertificationRequest(org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequest) TlsCertificateAuthorityResponse(org.apache.nifi.toolkit.tls.service.dto.TlsCertificateAuthorityResponse) ArrayList(java.util.ArrayList) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) IOException(java.io.IOException) X509Certificate(java.security.cert.X509Certificate) IOException(java.io.IOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) ByteArrayEntity(org.apache.http.entity.ByteArrayEntity) HttpHost(org.apache.http.HttpHost) BoundedInputStream(org.apache.commons.io.input.BoundedInputStream) TlsCertificateAuthorityRequest(org.apache.nifi.toolkit.tls.service.dto.TlsCertificateAuthorityRequest) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) StringReader(java.io.StringReader) SSLContextBuilder(org.apache.http.ssl.SSLContextBuilder) TrustSelfSignedStrategy(org.apache.http.conn.ssl.TrustSelfSignedStrategy)

Aggregations

TrustSelfSignedStrategy (org.apache.http.conn.ssl.TrustSelfSignedStrategy)56 SSLConnectionSocketFactory (org.apache.http.conn.ssl.SSLConnectionSocketFactory)41 SSLContextBuilder (org.apache.http.ssl.SSLContextBuilder)28 SSLContext (javax.net.ssl.SSLContext)20 IOException (java.io.IOException)15 HttpClient (org.apache.http.client.HttpClient)15 KeyStore (java.security.KeyStore)14 HttpComponentsClientHttpRequestFactory (org.springframework.http.client.HttpComponentsClientHttpRequestFactory)14 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)13 Test (org.junit.jupiter.api.Test)10 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)10 File (java.io.File)9 SSLContextBuilder (org.apache.http.conn.ssl.SSLContextBuilder)9 KeyManagementException (java.security.KeyManagementException)8 KeyStoreException (java.security.KeyStoreException)8 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)8 FileInputStream (java.io.FileInputStream)6 RequestConfig (org.apache.http.client.config.RequestConfig)6 ConnectionSocketFactory (org.apache.http.conn.socket.ConnectionSocketFactory)6 NoopHostnameVerifier (org.apache.http.conn.ssl.NoopHostnameVerifier)6