Search in sources :

Example 41 with KeyManagementException

use of java.security.KeyManagementException in project cloudstack by apache.

the class HypervDirectConnectResource method postHttpRequest.

public static String postHttpRequest(final String jsonCmd, final URI agentUri) {
    // Using Apache's HttpClient for HTTP POST
    // Java-only approach discussed at on StackOverflow concludes with
    // comment to use Apache HttpClient
    // http://stackoverflow.com/a/2793153/939250, but final comment is to
    // use Apache.
    String logMessage = StringEscapeUtils.unescapeJava(jsonCmd);
    logMessage = cleanPassword(logMessage);
    s_logger.debug("POST request to " + agentUri.toString() + " with contents " + logMessage);
    // Create request
    HttpClient httpClient = null;
    final TrustStrategy easyStrategy = new TrustStrategy() {

        @Override
        public boolean isTrusted(final X509Certificate[] chain, final String authType) throws CertificateException {
            return true;
        }
    };
    try {
        final SSLSocketFactory sf = new SSLSocketFactory(easyStrategy, new AllowAllHostnameVerifier());
        final SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("https", DEFAULT_AGENT_PORT, sf));
        final ClientConnectionManager ccm = new BasicClientConnectionManager(registry);
        httpClient = new DefaultHttpClient(ccm);
    } catch (final KeyManagementException e) {
        s_logger.error("failed to initialize http client " + e.getMessage());
    } catch (final UnrecoverableKeyException e) {
        s_logger.error("failed to initialize http client " + e.getMessage());
    } catch (final NoSuchAlgorithmException e) {
        s_logger.error("failed to initialize http client " + e.getMessage());
    } catch (final KeyStoreException e) {
        s_logger.error("failed to initialize http client " + e.getMessage());
    }
    String result = null;
    // TODO: are there timeout settings and worker thread settings to tweak?
    try {
        final HttpPost request = new HttpPost(agentUri);
        // JSON encode command
        // Assumes command sits comfortably in a string, i.e. not used for
        // large data transfers
        final StringEntity cmdJson = new StringEntity(jsonCmd);
        request.addHeader("content-type", "application/json");
        request.setEntity(cmdJson);
        s_logger.debug("Sending cmd to " + agentUri.toString() + " cmd data:" + logMessage);
        final HttpResponse response = httpClient.execute(request);
        // Unsupported commands will not route.
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_FOUND) {
            final String errMsg = "Failed to send : HTTP error code : " + response.getStatusLine().getStatusCode();
            s_logger.error(errMsg);
            final String unsupportMsg = "Unsupported command " + agentUri.getPath() + ".  Are you sure you got the right type of" + " server?";
            final Answer ans = new UnsupportedAnswer(null, unsupportMsg);
            s_logger.error(ans);
            result = s_gson.toJson(new Answer[] { ans });
        } else if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            final String errMsg = "Failed send to " + agentUri.toString() + " : HTTP error code : " + response.getStatusLine().getStatusCode();
            s_logger.error(errMsg);
            return null;
        } else {
            result = EntityUtils.toString(response.getEntity());
            final String logResult = cleanPassword(StringEscapeUtils.unescapeJava(result));
            s_logger.debug("POST response is " + logResult);
        }
    } catch (final ClientProtocolException protocolEx) {
        // Problem with HTTP message exchange
        s_logger.error(protocolEx);
    } catch (final IOException connEx) {
        // Problem with underlying communications
        s_logger.error(connEx);
    } finally {
        httpClient.getConnectionManager().shutdown();
    }
    return result;
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) TrustStrategy(org.apache.http.conn.ssl.TrustStrategy) Scheme(org.apache.http.conn.scheme.Scheme) AllowAllHostnameVerifier(org.apache.http.conn.ssl.AllowAllHostnameVerifier) HttpResponse(org.apache.http.HttpResponse) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) KeyStoreException(java.security.KeyStoreException) IOException(java.io.IOException) BasicClientConnectionManager(org.apache.http.impl.conn.BasicClientConnectionManager) ClientConnectionManager(org.apache.http.conn.ClientConnectionManager) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) KeyManagementException(java.security.KeyManagementException) ClientProtocolException(org.apache.http.client.ClientProtocolException) StringEntity(org.apache.http.entity.StringEntity) UnsupportedAnswer(com.cloud.agent.api.UnsupportedAnswer) CheckSshAnswer(com.cloud.agent.api.check.CheckSshAnswer) GetDomRVersionAnswer(com.cloud.agent.api.GetDomRVersionAnswer) CheckS2SVpnConnectionsAnswer(com.cloud.agent.api.CheckS2SVpnConnectionsAnswer) SetPortForwardingRulesAnswer(com.cloud.agent.api.routing.SetPortForwardingRulesAnswer) SetSourceNatAnswer(com.cloud.agent.api.routing.SetSourceNatAnswer) PlugNicAnswer(com.cloud.agent.api.PlugNicAnswer) GetVmConfigAnswer(com.cloud.agent.api.GetVmConfigAnswer) NetworkUsageAnswer(com.cloud.agent.api.NetworkUsageAnswer) Answer(com.cloud.agent.api.Answer) UnPlugNicAnswer(com.cloud.agent.api.UnPlugNicAnswer) SetStaticNatRulesAnswer(com.cloud.agent.api.routing.SetStaticNatRulesAnswer) IpAssocAnswer(com.cloud.agent.api.routing.IpAssocAnswer) SetFirewallRulesAnswer(com.cloud.agent.api.routing.SetFirewallRulesAnswer) CheckRouterAnswer(com.cloud.agent.api.CheckRouterAnswer) SetStaticRouteAnswer(com.cloud.agent.api.routing.SetStaticRouteAnswer) UnsupportedAnswer(com.cloud.agent.api.UnsupportedAnswer) UnrecoverableKeyException(java.security.UnrecoverableKeyException) HttpClient(org.apache.http.client.HttpClient) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) SchemeRegistry(org.apache.http.conn.scheme.SchemeRegistry) BasicClientConnectionManager(org.apache.http.impl.conn.BasicClientConnectionManager) SSLSocketFactory(org.apache.http.conn.ssl.SSLSocketFactory)

Example 42 with KeyManagementException

use of java.security.KeyManagementException in project cloudstack by apache.

the class NexentaNmsClient method getHttpsClient.

protected DefaultHttpClient getHttpsClient() {
    try {
        SSLContext sslContext = SSLUtils.getSSLContext();
        X509TrustManager tm = new X509TrustManager() {

            @Override
            public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException {
            }

            @Override
            public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException {
            }

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };
        sslContext.init(null, new TrustManager[] { tm }, new SecureRandom());
        SSLSocketFactory socketFactory = new SSLSocketFactory(sslContext, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("https", nmsUrl.getPort(), socketFactory));
        BasicClientConnectionManager mgr = new BasicClientConnectionManager(registry);
        return new DefaultHttpClient(mgr);
    } catch (NoSuchAlgorithmException ex) {
        throw new CloudRuntimeException(ex.getMessage());
    } catch (KeyManagementException ex) {
        throw new CloudRuntimeException(ex.getMessage());
    }
}
Also used : Scheme(org.apache.http.conn.scheme.Scheme) SecureRandom(java.security.SecureRandom) SSLContext(javax.net.ssl.SSLContext) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) X509Certificate(java.security.cert.X509Certificate) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) KeyManagementException(java.security.KeyManagementException) X509TrustManager(javax.net.ssl.X509TrustManager) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) SchemeRegistry(org.apache.http.conn.scheme.SchemeRegistry) BasicClientConnectionManager(org.apache.http.impl.conn.BasicClientConnectionManager) SSLSocketFactory(org.apache.http.conn.ssl.SSLSocketFactory)

Example 43 with KeyManagementException

use of java.security.KeyManagementException in project robovm by robovm.

the class MySslContext method test_init$Ljavax_net_ssl_KeyManager$Ljavax_net_ssl_TrustManagerLjava_security_SecureRandom.

/**
      * @throws NoSuchAlgorithmException
     * @throws KeyStoreException
     * @throws FileNotFoundException
     * @throws KeyManagementException
     * javax.net.ssl.SSLContext#
      *     init(javax.net.ssl.KeyManager[], javax.net.ssl.TrustManager[],
      *     java.security.SecureRandom)
      */
public void test_init$Ljavax_net_ssl_KeyManager$Ljavax_net_ssl_TrustManagerLjava_security_SecureRandom() throws Exception {
    if (!DEFSupported)
        fail(NotSupportMsg);
    SSLContextSpi spi = new MySSLContextSpi();
    SSLContext sslContext = new MySslContext(spi, defaultProvider, defaultProtocol);
    try {
        sslContext.createSSLEngine();
        fail("Expected RuntimeException was not thrown");
    } catch (RuntimeException rte) {
    // expected
    }
    try {
        sslContext.init(null, null, null);
        fail("KeyManagementException wasn't thrown");
    } catch (KeyManagementException kme) {
    //expected
    }
    try {
        String tAlg = TrustManagerFactory.getDefaultAlgorithm();
        String kAlg = KeyManagerFactory.getDefaultAlgorithm();
        if (tAlg == null)
            fail("TrustManagerFactory default algorithm is not defined");
        if (kAlg == null)
            fail("KeyManagerFactory default algorithm is not defined");
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(kAlg);
        kmf.init(null, new char[11]);
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(tAlg);
        KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
        tmf.init(ks);
        TrustManager[] tms = tmf.getTrustManagers();
        sslContext.init(kmf.getKeyManagers(), tms, new SecureRandom());
    } catch (Exception e) {
        System.out.println("EE = " + e);
    }
}
Also used : SecureRandom(java.security.SecureRandom) SSLContext(javax.net.ssl.SSLContext) KeyStore(java.security.KeyStore) KeyManagementException(java.security.KeyManagementException) KeyManagementException(java.security.KeyManagementException) KeyStoreException(java.security.KeyStoreException) FileNotFoundException(java.io.FileNotFoundException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) NoSuchProviderException(java.security.NoSuchProviderException) KeyManagerFactory(javax.net.ssl.KeyManagerFactory) TrustManager(javax.net.ssl.TrustManager) MySSLContextSpi(org.apache.harmony.xnet.tests.support.MySSLContextSpi) MySSLContextSpi(org.apache.harmony.xnet.tests.support.MySSLContextSpi) SSLContextSpi(javax.net.ssl.SSLContextSpi) TrustManagerFactory(javax.net.ssl.TrustManagerFactory)

Example 44 with KeyManagementException

use of java.security.KeyManagementException in project robovm by robovm.

the class MySslContext method test_getServerSocketFactory.

/**
     * Test for <code>getServerSocketFactory()</code>
     * <code>getSocketFactory()</code>
     * <code>init(KeyManager[] km, TrustManager[] tm, SecureRandom random)</code>
     * methods Assertion: returns correspondent object
     *
     */
public void test_getServerSocketFactory() throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
    if (!DEFSupported) {
        fail(NotSupportMsg);
        return;
    }
    SSLContext[] sslC = createSSLCon();
    assertNotNull("SSLContext objects were not created", sslC);
    String tAlg = TrustManagerFactory.getDefaultAlgorithm();
    String kAlg = KeyManagerFactory.getDefaultAlgorithm();
    if (tAlg == null) {
        fail("TrustManagerFactory default algorithm is not defined");
        return;
    }
    if (kAlg == null) {
        fail("KeyManagerFactory default algorithm is not defined");
        return;
    }
    KeyManagerFactory kmf = KeyManagerFactory.getInstance(kAlg);
    KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
    try {
        ks.load(null, null);
    } catch (Exception e) {
        fail(e + " was thrown for method load(null, null)");
    }
    kmf.init(ks, new char[10]);
    KeyManager[] kms = kmf.getKeyManagers();
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(tAlg);
    tmf.init(ks);
    TrustManager[] tms = tmf.getTrustManagers();
    for (int i = 0; i < sslC.length; i++) {
        sslC[i].init(kms, tms, new SecureRandom());
        assertNotNull("No SSLServerSocketFactory available", sslC[i].getServerSocketFactory());
        assertNotNull("No SSLSocketFactory available", sslC[i].getSocketFactory());
    }
}
Also used : SecureRandom(java.security.SecureRandom) SSLContext(javax.net.ssl.SSLContext) KeyStore(java.security.KeyStore) KeyManagementException(java.security.KeyManagementException) KeyStoreException(java.security.KeyStoreException) FileNotFoundException(java.io.FileNotFoundException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) NoSuchProviderException(java.security.NoSuchProviderException) KeyManagerFactory(javax.net.ssl.KeyManagerFactory) TrustManager(javax.net.ssl.TrustManager) TrustManagerFactory(javax.net.ssl.TrustManagerFactory) KeyManager(javax.net.ssl.KeyManager)

Example 45 with KeyManagementException

use of java.security.KeyManagementException in project robovm by robovm.

the class SSLEngineTest method getEngine.

private SSLEngine getEngine(String host, int port) {
    SSLContext context = null;
    try {
        context = SSLContext.getInstance("TLS");
        context.init(null, null, null);
    } catch (KeyManagementException e) {
        fail("Could not get SSLEngine: key management exception " + e.getMessage());
    } catch (NoSuchAlgorithmException e) {
        fail("Could not get SSLEngine: no such algorithm " + e.getMessage());
    }
    return context.createSSLEngine(host, port);
}
Also used : SSLContext(javax.net.ssl.SSLContext) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) KeyManagementException(java.security.KeyManagementException)

Aggregations

KeyManagementException (java.security.KeyManagementException)157 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)111 SSLContext (javax.net.ssl.SSLContext)83 KeyStoreException (java.security.KeyStoreException)60 IOException (java.io.IOException)55 TrustManager (javax.net.ssl.TrustManager)45 CertificateException (java.security.cert.CertificateException)35 X509TrustManager (javax.net.ssl.X509TrustManager)28 SecureRandom (java.security.SecureRandom)27 X509Certificate (java.security.cert.X509Certificate)26 UnrecoverableKeyException (java.security.UnrecoverableKeyException)24 TrustManagerFactory (javax.net.ssl.TrustManagerFactory)24 KeyStore (java.security.KeyStore)22 KeyManager (javax.net.ssl.KeyManager)19 SSLSocketFactory (javax.net.ssl.SSLSocketFactory)16 HostnameVerifier (javax.net.ssl.HostnameVerifier)15 KeyManagerFactory (javax.net.ssl.KeyManagerFactory)15 InputStream (java.io.InputStream)12 HttpsURLConnection (javax.net.ssl.HttpsURLConnection)11 SSLSession (javax.net.ssl.SSLSession)10