Search in sources :

Example 91 with KeyStoreException

use of java.security.KeyStoreException in project wildfly by wildfly.

the class EncryptProtocolConfigurationBuilder method accept.

@Override
public void accept(P protocol) {
    KeyStore store = this.keyStore.getValue();
    String alias = this.keyAlias;
    try {
        if (!store.containsAlias(alias)) {
            throw JGroupsLogger.ROOT_LOGGER.keyEntryNotFound(alias);
        }
        PasswordCredential credential = this.credentialSource.getValue().getCredential(PasswordCredential.class);
        if (credential == null) {
            throw JGroupsLogger.ROOT_LOGGER.unexpectedCredentialSource();
        }
        ClearPassword password = credential.getPassword(ClearPassword.class);
        if (password == null) {
            throw JGroupsLogger.ROOT_LOGGER.unexpectedCredentialSource();
        }
        protocol.setKeyStore(this.keyStore.getValue());
        protocol.setKeyAlias(this.keyAlias);
        protocol.setKeyPassword(new KeyStore.PasswordProtection(password.getPassword()));
    } catch (KeyStoreException | IOException e) {
        throw new IllegalArgumentException(e);
    }
}
Also used : ClearPassword(org.wildfly.security.password.interfaces.ClearPassword) PasswordCredential(org.wildfly.security.credential.PasswordCredential) KeyStoreException(java.security.KeyStoreException) IOException(java.io.IOException) KeyStore(java.security.KeyStore)

Example 92 with KeyStoreException

use of java.security.KeyStoreException in project zm-mailbox by Zimbra.

the class ClientCertAuthenticator method validateClientCert.

private void validateClientCert(X509Certificate[] certs) throws ServiceException {
    String subjectDN = null;
    try {
        boolean revocationCheckEnabled = Provisioning.getInstance().getLocalServer().isMailSSLClientCertOCSPEnabled();
        Set<TrustAnchor> trustedCertsSet = null;
        if (revocationCheckEnabled) {
            char[] pass = LC.client_ssl_truststore_password.value().toCharArray();
            trustedCertsSet = CertValidationUtil.loadTrustedAnchors(pass, LC.client_ssl_truststore.value());
        }
        for (X509Certificate cert : certs) {
            subjectDN = getSubjectDNForLogging(cert);
            CertValidationUtil.validateCertificate(cert, revocationCheckEnabled, trustedCertsSet);
        }
    } catch (CertificateExpiredException e) {
        throw AuthFailedServiceException.AUTH_FAILED(subjectDN, "client certificate expired", e);
    } catch (CertificateNotYetValidException e) {
        throw AuthFailedServiceException.AUTH_FAILED(subjectDN, "client certificate not yet valid", e);
    } catch (CertificateException e) {
        throw AuthFailedServiceException.AUTH_FAILED(subjectDN, "can't generate certpath for client certificate", e);
    } catch (KeyStoreException e) {
        throw AuthFailedServiceException.AUTH_FAILED(subjectDN, "received KeyStoreException while loading KeyStore", e);
    } catch (NoSuchAlgorithmException e) {
        throw AuthFailedServiceException.AUTH_FAILED(subjectDN, "received NoSuchAlgorithmException while obtaining instance of certpath validator", e);
    } catch (FileNotFoundException e) {
        throw AuthFailedServiceException.AUTH_FAILED(subjectDN, "mailboxd keystore can't be found", e);
    } catch (IOException e) {
        throw AuthFailedServiceException.AUTH_FAILED(subjectDN, "received IOException", e);
    } catch (InvalidAlgorithmParameterException e) {
        throw AuthFailedServiceException.AUTH_FAILED(subjectDN, "received InvalidAlgorithmParameter while obtaining instance of certpath validator", e);
    } catch (CertPathValidatorException e) {
        throw AuthFailedServiceException.AUTH_FAILED(subjectDN, "received CertPathValidatorException" + e.getMessage(), e);
    }
}
Also used : CertificateNotYetValidException(java.security.cert.CertificateNotYetValidException) InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) CertificateExpiredException(java.security.cert.CertificateExpiredException) FileNotFoundException(java.io.FileNotFoundException) TrustAnchor(java.security.cert.TrustAnchor) CertificateException(java.security.cert.CertificateException) KeyStoreException(java.security.KeyStoreException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) IOException(java.io.IOException) X509Certificate(java.security.cert.X509Certificate) CertPathValidatorException(java.security.cert.CertPathValidatorException)

Example 93 with KeyStoreException

use of java.security.KeyStoreException in project karaf by apache.

the class ResourceKeystoreInstance method loadKeystoreData.

// ==================== Internals =====================
private boolean loadKeystoreData() {
    // Check to reload the data if needed
    if (keystoreFile != null && keystoreReadDate >= keystoreFile.lastModified()) {
        return true;
    }
    // If not a file, just not reload the data if it has already been loaded
    if (keystoreFile == null && keystore != null) {
        return true;
    }
    // Check if the file is invalid
    if (keystoreFile != null && (!keystoreFile.exists() || !keystoreFile.canRead())) {
        throw new IllegalArgumentException("Invalid keystore file (" + path + " = " + keystoreFile.getAbsolutePath() + ")");
    }
    // Load the keystore data
    try {
        keystoreReadDate = System.currentTimeMillis();
        privateKeys.clear();
        trustCerts.clear();
        if (keystore == null) {
            keystore = KeyStore.getInstance(JKS);
        }
        InputStream in = new BufferedInputStream(path.openStream());
        keystore.load(in, keystorePassword == null ? new char[0] : keystorePassword.toCharArray());
        in.close();
        Enumeration aliases = keystore.aliases();
        while (aliases.hasMoreElements()) {
            String alias = (String) aliases.nextElement();
            if (keystore.isKeyEntry(alias)) {
                privateKeys.add(alias);
            } else if (keystore.isCertificateEntry(alias)) {
                trustCerts.add(alias);
            }
        }
        return true;
    } catch (KeyStoreException e) {
        logger.error("Unable to open keystore with provided password", e);
    } catch (IOException e) {
        logger.error("Unable to open keystore with provided password", e);
    } catch (NoSuchAlgorithmException e) {
        logger.error("Unable to open keystore with provided password", e);
    } catch (CertificateException e) {
        logger.error("Unable to open keystore with provided password", e);
    }
    return false;
}
Also used : Enumeration(java.util.Enumeration) BufferedInputStream(java.io.BufferedInputStream) BufferedInputStream(java.io.BufferedInputStream) InputStream(java.io.InputStream) CertificateException(java.security.cert.CertificateException) KeyStoreException(java.security.KeyStoreException) IOException(java.io.IOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException)

Example 94 with KeyStoreException

use of java.security.KeyStoreException 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 95 with KeyStoreException

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

the class KeyStoreExceptionTest method testKeyStoreException02.

/**
     * Test for <code>KeyStoreException(String)</code> constructor Assertion:
     * constructs KeyStoreException with detail message msg. Parameter
     * <code>msg</code> is not null.
     */
public void testKeyStoreException02() {
    KeyStoreException tE;
    for (int i = 0; i < msgs.length; i++) {
        tE = new KeyStoreException(msgs[i]);
        assertEquals("getMessage() must return: ".concat(msgs[i]), tE.getMessage(), msgs[i]);
        assertNull("getCause() must return null", tE.getCause());
    }
}
Also used : KeyStoreException(java.security.KeyStoreException)

Aggregations

KeyStoreException (java.security.KeyStoreException)381 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)211 IOException (java.io.IOException)179 CertificateException (java.security.cert.CertificateException)148 KeyStore (java.security.KeyStore)141 X509Certificate (java.security.cert.X509Certificate)112 UnrecoverableKeyException (java.security.UnrecoverableKeyException)95 Certificate (java.security.cert.Certificate)73 KeyManagementException (java.security.KeyManagementException)69 CertificateFactory (java.security.cert.CertificateFactory)39 SSLContext (javax.net.ssl.SSLContext)38 TrustManagerFactory (javax.net.ssl.TrustManagerFactory)38 InputStream (java.io.InputStream)37 InvalidAlgorithmParameterException (java.security.InvalidAlgorithmParameterException)37 PrivateKey (java.security.PrivateKey)35 ByteArrayInputStream (java.io.ByteArrayInputStream)33 InvalidKeyException (java.security.InvalidKeyException)33 FileNotFoundException (java.io.FileNotFoundException)32 TrustManager (javax.net.ssl.TrustManager)30 NoSuchPaddingException (javax.crypto.NoSuchPaddingException)28