Example usage for javax.net.ssl SSLHandshakeException getCause

List of usage examples for javax.net.ssl SSLHandshakeException getCause

Introduction

In this page you can find the example usage for javax.net.ssl SSLHandshakeException getCause.

Prototype

public synchronized Throwable getCause() 

Source Link

Document

Returns the cause of this throwable or null if the cause is nonexistent or unknown.

Usage

From source file:org.coding.git.api.CodingNetConnection.java

@NotNull
private ResponsePage doRequest(@NotNull String uri, @Nullable String requestBody,
        @NotNull Collection<Header> headers, @NotNull HttpVerb verb) throws IOException {
    if (myAborted)
        throw new CodingNetOperationCanceledException();

    if (EventQueue.isDispatchThread() && !ApplicationManager.getApplication().isUnitTestMode()) {
        LOG.warn("Network operation in EDT"); // TODO: fix
    }/*from  w w w . j  av  a  2  s . c  o m*/

    CloseableHttpResponse response = null;
    try {
        response = doREST(uri, requestBody, headers, verb);

        if (myAborted)
            throw new CodingNetOperationCanceledException();

        //--HTTP??
        checkStatusCode(response, requestBody);

        HttpEntity entity = response.getEntity();
        if (entity == null) {
            return createResponse(response);
        }

        JsonElement ret = parseResponse(entity.getContent());
        if (ret.isJsonNull()) {
            return createResponse(response);
        }

        //--CodingNet??
        checkCodingNetCode(ret);

        String nextPage = null;
        Header pageHeader = response.getFirstHeader("Link");
        if (pageHeader != null) {
            for (HeaderElement element : pageHeader.getElements()) {
                NameValuePair rel = element.getParameterByName("rel");
                if (rel != null && "next".equals(rel.getValue())) {
                    String urlString = element.toString();
                    int begin = urlString.indexOf('<');
                    int end = urlString.lastIndexOf('>');
                    if (begin == -1 || end == -1) {
                        LOG.error("Invalid 'Link' header", "{" + pageHeader.toString() + "}");
                        break;
                    }

                    nextPage = urlString.substring(begin + 1, end);
                    break;
                }
            }
        }

        return createResponse(ret, nextPage, response);
    } catch (SSLHandshakeException e) { // User canceled operation from CertificateManager
        if (e.getCause() instanceof CertificateException) {
            LOG.info("Host SSL certificate is not trusted", e);
            throw new CodingNetOperationCanceledException("Host SSL certificate is not trusted", e);
        }
        throw e;
    } catch (IOException e) {
        if (myAborted)
            throw new CodingNetOperationCanceledException("Operation canceled", e);
        throw e;
    } finally {
        myRequest = null;
        if (response != null) {
            response.close();
        }
        if (!myReusable) {
            myClient.close();
        }
    }
}

From source file:org.elasticsearch.xpack.core.ssl.SSLConfigurationReloaderTests.java

/**
 * Tests the reloading of SSLContext when the trust store is modified. The same store is used as a TrustStore (for the
 * reloadable SSLContext used in the HTTPClient) and as a KeyStore for the MockWebServer
 *//*from   ww w  .j  a  v  a2 s.  co  m*/
public void testReloadingTrustStore() throws Exception {
    Path tempDir = createTempDir();
    Path trustStorePath = tempDir.resolve("testnode.jks");
    Path updatedTruststorePath = tempDir.resolve("testnode_updated.jks");
    Files.copy(getDataPath("/org/elasticsearch/xpack/security/transport/ssl/certs/simple/testnode.jks"),
            trustStorePath);
    Files.copy(getDataPath("/org/elasticsearch/xpack/security/transport/ssl/certs/simple/testnode_updated.jks"),
            updatedTruststorePath);
    MockSecureSettings secureSettings = new MockSecureSettings();
    secureSettings.setString("xpack.ssl.truststore.secure_password", "testnode");
    Settings settings = Settings.builder().put("xpack.ssl.truststore.path", trustStorePath)
            .put("path.home", createTempDir()).setSecureSettings(secureSettings).build();
    Environment env = randomBoolean() ? null : TestEnvironment.newEnvironment(settings);
    // Create the MockWebServer once for both pre and post checks
    try (MockWebServer server = getSslServer(trustStorePath, "testnode")) {
        final Consumer<SSLContext> trustMaterialPreChecks = (context) -> {
            try (CloseableHttpClient client = HttpClients.custom().setSSLContext(context).build()) {
                privilegedConnect(
                        () -> client.execute(new HttpGet("https://localhost:" + server.getPort())).close());
            } catch (Exception e) {
                throw new RuntimeException("Error connecting to the mock server", e);
            }
        };

        final Runnable modifier = () -> {
            try {
                atomicMoveIfPossible(updatedTruststorePath, trustStorePath);
            } catch (Exception e) {
                throw new RuntimeException("failed to modify file", e);
            }
        };

        // Client's truststore doesn't contain the server's certificate anymore so SSLHandshake should fail
        final Consumer<SSLContext> trustMaterialPostChecks = (updatedContext) -> {
            try (CloseableHttpClient client = HttpClients.custom().setSSLContext(updatedContext).build()) {
                SSLHandshakeException sslException = expectThrows(SSLHandshakeException.class,
                        () -> privilegedConnect(() -> client
                                .execute(new HttpGet("https://localhost:" + server.getPort())).close()));
                assertThat(sslException.getCause().getMessage(), containsString("PKIX path building failed"));
            } catch (Exception e) {
                throw new RuntimeException("Error closing CloseableHttpClient", e);
            }
        };
        validateSSLConfigurationIsReloaded(settings, env, trustMaterialPreChecks, modifier,
                trustMaterialPostChecks);
    }
}

From source file:org.elasticsearch.xpack.core.ssl.SSLConfigurationReloaderTests.java

/**
 * Tests reloading a keystore that is used in the KeyManager of SSLContext
 *//* w w  w .j a  v a 2  s .  co m*/
public void testReloadingKeyStore() throws Exception {
    final Path tempDir = createTempDir();
    final Path keystorePath = tempDir.resolve("testnode.jks");
    final Path updatedKeystorePath = tempDir.resolve("testnode_updated.jks");
    Files.copy(getDataPath("/org/elasticsearch/xpack/security/transport/ssl/certs/simple/testnode.jks"),
            keystorePath);
    Files.copy(getDataPath("/org/elasticsearch/xpack/security/transport/ssl/certs/simple/testnode_updated.jks"),
            updatedKeystorePath);
    MockSecureSettings secureSettings = new MockSecureSettings();
    secureSettings.setString("xpack.ssl.keystore.secure_password", "testnode");
    final Settings settings = Settings.builder().put("path.home", createTempDir())
            .put("xpack.ssl.keystore.path", keystorePath).setSecureSettings(secureSettings).build();
    final Environment env = randomBoolean() ? null : TestEnvironment.newEnvironment(settings);
    //Load HTTPClient only once. Client uses the same store as a truststore
    try (CloseableHttpClient client = getSSLClient(keystorePath, "testnode")) {
        final Consumer<SSLContext> keyMaterialPreChecks = (context) -> {
            try (MockWebServer server = new MockWebServer(context, true)) {
                server.enqueue(new MockResponse().setResponseCode(200).setBody("body"));
                server.start();
                privilegedConnect(
                        () -> client.execute(new HttpGet("https://localhost:" + server.getPort())).close());
            } catch (Exception e) {
                throw new RuntimeException("Exception starting or connecting to the mock server", e);
            }
        };

        final Runnable modifier = () -> {
            try {
                atomicMoveIfPossible(updatedKeystorePath, keystorePath);
            } catch (Exception e) {
                throw new RuntimeException("modification failed", e);
            }
        };

        // The new server certificate is not in the client's truststore so SSLHandshake should fail
        final Consumer<SSLContext> keyMaterialPostChecks = (updatedContext) -> {
            try (MockWebServer server = new MockWebServer(updatedContext, true)) {
                server.enqueue(new MockResponse().setResponseCode(200).setBody("body"));
                server.start();
                SSLHandshakeException sslException = expectThrows(SSLHandshakeException.class,
                        () -> privilegedConnect(() -> client
                                .execute(new HttpGet("https://localhost:" + server.getPort())).close()));
                assertThat(sslException.getCause().getMessage(), containsString("PKIX path validation failed"));
            } catch (Exception e) {
                throw new RuntimeException("Exception starting or connecting to the mock server", e);
            }
        };
        validateSSLConfigurationIsReloaded(settings, env, keyMaterialPreChecks, modifier,
                keyMaterialPostChecks);
    }
}

From source file:org.elasticsearch.xpack.core.ssl.SSLConfigurationReloaderTests.java

/**
 * Test the reloading of SSLContext whose trust config is backed by PEM certificate files.
 *///from  w  ww  .j a v  a  2 s.  co  m
public void testReloadingPEMTrustConfig() throws Exception {
    Path tempDir = createTempDir();
    Path clientCertPath = tempDir.resolve("testnode.crt");
    Path keyStorePath = tempDir.resolve("testnode.jks");
    Files.copy(getDataPath("/org/elasticsearch/xpack/security/transport/ssl/certs/simple/testnode.jks"),
            keyStorePath);
    //Our keystore contains two Certificates it can present. One build from the RSA keypair and one build from the EC keypair. EC is
    // used since it keyManager presents the first one in alias alphabetical order (and testnode_ec comes before testnode_rsa)
    Files.copy(getDataPath("/org/elasticsearch/xpack/security/transport/ssl/certs/simple/testnode_ec.crt"),
            clientCertPath);
    Settings settings = Settings.builder()
            .putList("xpack.ssl.certificate_authorities", clientCertPath.toString())
            .put("path.home", createTempDir()).build();
    Environment env = randomBoolean() ? null : TestEnvironment.newEnvironment(settings);
    // Create the MockWebServer once for both pre and post checks
    try (MockWebServer server = getSslServer(keyStorePath, "testnode")) {
        final Consumer<SSLContext> trustMaterialPreChecks = (context) -> {
            try (CloseableHttpClient client = HttpClients.custom().setSSLContext(context).build()) {
                privilegedConnect(
                        () -> client.execute(new HttpGet("https://localhost:" + server.getPort())).close());
            } catch (Exception e) {
                throw new RuntimeException("Exception connecting to the mock server", e);
            }
        };

        final Runnable modifier = () -> {
            try {
                Path updatedCert = tempDir.resolve("updated.crt");
                Files.copy(getDataPath(
                        "/org/elasticsearch/xpack/security/transport/ssl/certs/simple/testnode_updated.crt"),
                        updatedCert, StandardCopyOption.REPLACE_EXISTING);
                atomicMoveIfPossible(updatedCert, clientCertPath);
            } catch (Exception e) {
                throw new RuntimeException("failed to modify file", e);
            }
        };

        // Client doesn't trust the Server certificate anymore so SSLHandshake should fail
        final Consumer<SSLContext> trustMaterialPostChecks = (updatedContext) -> {
            try (CloseableHttpClient client = HttpClients.custom().setSSLContext(updatedContext).build()) {
                SSLHandshakeException sslException = expectThrows(SSLHandshakeException.class,
                        () -> privilegedConnect(() -> client
                                .execute(new HttpGet("https://localhost:" + server.getPort())).close()));
                assertThat(sslException.getCause().getMessage(), containsString("PKIX path building failed"));
            } catch (Exception e) {
                throw new RuntimeException("Error closing CloseableHttpClient", e);
            }
        };
        validateSSLConfigurationIsReloaded(settings, env, trustMaterialPreChecks, modifier,
                trustMaterialPostChecks);
    }
}

From source file:org.elasticsearch.xpack.core.ssl.SSLConfigurationReloaderTests.java

/**
 * Tests the reloading of SSLContext when a PEM key and certificate are used.
 *///  ww  w  . ja  v  a  2s.  c  o  m
public void testPEMKeyConfigReloading() throws Exception {
    Path tempDir = createTempDir();
    Path keyPath = tempDir.resolve("testnode.pem");
    Path updatedKeyPath = tempDir.resolve("testnode_updated.pem");
    Path certPath = tempDir.resolve("testnode.crt");
    Path updatedCertPath = tempDir.resolve("testnode_updated.crt");
    final Path clientTruststorePath = tempDir.resolve("testnode.jks");
    Files.copy(getDataPath("/org/elasticsearch/xpack/security/transport/ssl/certs/simple/testnode.pem"),
            keyPath);
    Files.copy(getDataPath("/org/elasticsearch/xpack/security/transport/ssl/certs/simple/testnode_updated.pem"),
            updatedKeyPath);
    Files.copy(getDataPath("/org/elasticsearch/xpack/security/transport/ssl/certs/simple/testnode_updated.crt"),
            updatedCertPath);
    Files.copy(getDataPath("/org/elasticsearch/xpack/security/transport/ssl/certs/simple/testnode.crt"),
            certPath);
    Files.copy(getDataPath("/org/elasticsearch/xpack/security/transport/ssl/certs/simple/testnode.jks"),
            clientTruststorePath);
    MockSecureSettings secureSettings = new MockSecureSettings();
    secureSettings.setString("xpack.ssl.secure_key_passphrase", "testnode");
    final Settings settings = Settings.builder().put("path.home", createTempDir()).put("xpack.ssl.key", keyPath)
            .put("xpack.ssl.certificate", certPath).setSecureSettings(secureSettings).build();
    final Environment env = randomBoolean() ? null
            : TestEnvironment.newEnvironment(Settings.builder().put("path.home", createTempDir()).build());
    // Load HTTPClient once. Client uses a keystore containing testnode key/cert as a truststore
    try (CloseableHttpClient client = getSSLClient(clientTruststorePath, "testnode")) {
        final Consumer<SSLContext> keyMaterialPreChecks = (context) -> {
            try (MockWebServer server = new MockWebServer(context, false)) {
                server.enqueue(new MockResponse().setResponseCode(200).setBody("body"));
                server.start();
                privilegedConnect(
                        () -> client.execute(new HttpGet("https://localhost:" + server.getPort())).close());
            } catch (Exception e) {
                throw new RuntimeException("Exception starting or connecting to the mock server", e);
            }
        };
        final Runnable modifier = () -> {
            try {
                atomicMoveIfPossible(updatedKeyPath, keyPath);
                atomicMoveIfPossible(updatedCertPath, certPath);
            } catch (Exception e) {
                throw new RuntimeException("failed to modify file", e);
            }
        };

        // The new server certificate is not in the client's truststore so SSLHandshake should fail
        final Consumer<SSLContext> keyMaterialPostChecks = (updatedContext) -> {
            try (MockWebServer server = new MockWebServer(updatedContext, false)) {
                server.enqueue(new MockResponse().setResponseCode(200).setBody("body"));
                server.start();
                SSLHandshakeException sslException = expectThrows(SSLHandshakeException.class,
                        () -> privilegedConnect(() -> client
                                .execute(new HttpGet("https://localhost:" + server.getPort())).close()));
                assertThat(sslException.getCause().getMessage(), containsString("PKIX path validation failed"));
            } catch (Exception e) {
                throw new RuntimeException("Exception starting or connecting to the mock server", e);
            }
        };
        validateSSLConfigurationIsReloaded(settings, env, keyMaterialPreChecks, modifier,
                keyMaterialPostChecks);
    }
}