Search in sources :

Example 26 with CertificateException

use of java.security.cert.CertificateException in project Openfire by igniterealtime.

the class ClientTrustManager method checkClientTrusted.

@Override
public void checkClientTrusted(X509Certificate[] x509Certificates, String string) throws CertificateException {
    Log.debug("ClientTrustManager: checkClientTrusted(x509Certificates," + string + ") called");
    loadCRL();
    ArrayList<X509Certificate> certs = new ArrayList<>();
    for (int i = 0; i < x509Certificates.length; i++) {
        certs.add(x509Certificates[i]);
    }
    boolean verify = JiveGlobals.getBooleanProperty("xmpp.client.certificate.verify", true);
    if (verify) {
        int nSize = x509Certificates.length;
        List<String> peerIdentities = CertificateManager.getClientIdentities(x509Certificates[0]);
        if (JiveGlobals.getBooleanProperty("xmpp.client.certificate.verify.chain", true)) {
            // Working down the chain, for every certificate in the chain,
            // verify that the subject of the certificate is the issuer of the
            // next certificate in the chain.
            Principal principalLast = null;
            for (int i = nSize - 1; i >= 0; i--) {
                X509Certificate x509certificate = x509Certificates[i];
                Principal principalIssuer = x509certificate.getIssuerDN();
                Principal principalSubject = x509certificate.getSubjectDN();
                if (principalLast != null) {
                    if (principalIssuer.equals(principalLast)) {
                        try {
                            PublicKey publickey = x509Certificates[i + 1].getPublicKey();
                            x509Certificates[i].verify(publickey);
                        } catch (GeneralSecurityException generalsecurityexception) {
                            throw new CertificateException("signature verification failed of " + peerIdentities);
                        }
                    } else {
                        throw new CertificateException("subject/issuer verification failed of " + peerIdentities);
                    }
                }
                principalLast = principalSubject;
            }
        }
        if (JiveGlobals.getBooleanProperty("xmpp.client.certificate.verify.root", true)) {
            // Verify that the the last certificate in the chain was issued
            // by a third-party that the client trusts, or is trusted itself
            boolean trusted = false;
            try {
                Enumeration<String> aliases = trustStore.aliases();
                while (aliases.hasMoreElements()) {
                    String alias = aliases.nextElement();
                    X509Certificate tCert = (X509Certificate) trustStore.getCertificate(alias);
                    if (x509Certificates[nSize - 1].equals(tCert)) {
                        try {
                            PublicKey publickey = tCert.getPublicKey();
                            x509Certificates[nSize - 1].verify(publickey);
                        } catch (GeneralSecurityException generalsecurityexception) {
                            throw new CertificateException("signature verification failed of " + peerIdentities);
                        }
                        trusted = true;
                        break;
                    } else {
                        if (x509Certificates[nSize - 1].getIssuerDN().equals(tCert.getSubjectDN())) {
                            try {
                                PublicKey publickey = tCert.getPublicKey();
                                x509Certificates[nSize - 1].verify(publickey);
                            } catch (GeneralSecurityException generalsecurityexception) {
                                throw new CertificateException("signature verification failed of " + peerIdentities);
                            }
                            trusted = true;
                            break;
                        }
                    }
                }
            } catch (KeyStoreException e) {
                Log.error(e.getMessage(), e);
            }
            if (!trusted) {
                //Log.debug("certificate not trusted of "+peerIdentities);
                throw new CertificateException("root certificate not trusted of " + peerIdentities);
            }
        }
        if (JiveGlobals.getBooleanProperty("xmpp.client.certificate.verify.validity", true)) {
            // For every certificate in the chain, verify that the certificate
            // is valid at the current time.
            Date date = new Date();
            for (int i = 0; i < nSize; i++) {
                try {
                    x509Certificates[i].checkValidity(date);
                } catch (GeneralSecurityException generalsecurityexception) {
                    throw new CertificateException("invalid date of " + peerIdentities);
                }
            }
        }
        //Verify certificate path
        try {
            CertPathValidator cpv = CertPathValidator.getInstance("PKIX");
            CertPathBuilder cpb = CertPathBuilder.getInstance("PKIX");
            X509CertSelector certSelector = new X509CertSelector();
            certSelector.setCertificate(x509Certificates[0]);
            PKIXBuilderParameters params = new PKIXBuilderParameters(trustStore, certSelector);
            if (useCRLs) {
                params.addCertStore(crlStore);
            } else {
                Log.debug("ClientTrustManager: no CRL's found, so setRevocationEnabled(false)");
                params.setRevocationEnabled(false);
            }
            CertPathBuilderResult cpbr = cpb.build(params);
            CertPath cp = cpbr.getCertPath();
            if (JiveGlobals.getBooleanProperty("ocsp.enable", false)) {
                Log.debug("ClientTrustManager: OCSP requested");
                OCSPChecker ocspChecker = new OCSPChecker(cp, params);
                params.addCertPathChecker(ocspChecker);
            }
            PKIXCertPathValidatorResult cpvResult = (PKIXCertPathValidatorResult) cpv.validate(cp, params);
            X509Certificate trustedCert = cpvResult.getTrustAnchor().getTrustedCert();
            if (trustedCert == null) {
                throw new CertificateException("certificate path failed: Trusted CA is NULL");
            } else {
                Log.debug("ClientTrustManager: Trusted CA: " + trustedCert.getSubjectDN());
            }
        } catch (CertPathBuilderException | CertPathValidatorException e) {
            Log.debug("ClientTrustManager:", e);
            throw new CertificateException("certificate path failed: " + e.getMessage());
        } catch (Exception e) {
            Log.debug("ClientTrustManager:", e);
            throw new CertificateException("unexpected error: " + e.getMessage());
        }
    }
}
Also used : CertPathBuilderResult(java.security.cert.CertPathBuilderResult) ArrayList(java.util.ArrayList) CertificateException(java.security.cert.CertificateException) X509CertSelector(java.security.cert.X509CertSelector) CertPathBuilderException(java.security.cert.CertPathBuilderException) CertPathBuilder(java.security.cert.CertPathBuilder) CertPath(java.security.cert.CertPath) PublicKey(java.security.PublicKey) PKIXBuilderParameters(java.security.cert.PKIXBuilderParameters) GeneralSecurityException(java.security.GeneralSecurityException) KeyStoreException(java.security.KeyStoreException) X509Certificate(java.security.cert.X509Certificate) Date(java.util.Date) KeyStoreException(java.security.KeyStoreException) InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) CertPathBuilderException(java.security.cert.CertPathBuilderException) GeneralSecurityException(java.security.GeneralSecurityException) CertPathValidatorException(java.security.cert.CertPathValidatorException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) FileNotFoundException(java.io.FileNotFoundException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) CRLException(java.security.cert.CRLException) CertPathValidator(java.security.cert.CertPathValidator) CertPathValidatorException(java.security.cert.CertPathValidatorException) PKIXCertPathValidatorResult(java.security.cert.PKIXCertPathValidatorResult) Principal(java.security.Principal)

Example 27 with CertificateException

use of java.security.cert.CertificateException in project Openfire by igniterealtime.

the class CertificateManager method getEndEntityCertificate.

/**
     * Decide whether or not to trust the given supplied certificate chain, returning the
     * End Entity Certificate in this case where it can, and null otherwise.
     * A self-signed certificate will, for example, return null.
     * For certain failures, we SHOULD generate an exception - revocations and the like,
     * but we currently do not.
     *
     * @param chain an array of X509Certificate where the first one is the endEntityCertificate.
     * @param certStore a keystore containing untrusted certificates (including ICAs, etc).
     * @param trustStore a keystore containing Trust Anchors (most-trusted CA certificates).
     * @return trusted end-entity certificate, or null.
     */
public static X509Certificate getEndEntityCertificate(Certificate[] chain, KeyStore certStore, KeyStore trustStore) {
    if (chain.length == 0) {
        return null;
    }
    X509Certificate first = (X509Certificate) chain[0];
    try {
        first.checkValidity();
    } catch (CertificateException e) {
        Log.warn("EE Certificate not valid: " + e.getMessage());
        return null;
    }
    if (chain.length == 1 && first.getSubjectX500Principal().equals(first.getIssuerX500Principal())) {
        // Chain is single cert, and self-signed.
        try {
            if (trustStore.getCertificateAlias(first) != null) {
                // Interesting case: trusted self-signed cert.
                return first;
            }
        } catch (KeyStoreException e) {
            Log.warn("Keystore error while looking for self-signed cert; assuming untrusted.");
        }
        return null;
    }
    final List<Certificate> all_certs = new ArrayList<>();
    try {
        // It's a mystery why these objects are different.
        for (Enumeration<String> aliases = certStore.aliases(); aliases.hasMoreElements(); ) {
            String alias = aliases.nextElement();
            if (certStore.isCertificateEntry(alias)) {
                X509Certificate cert = (X509Certificate) certStore.getCertificate(alias);
                all_certs.add(cert);
            }
        }
        // Now add the trusted certs.
        for (Enumeration<String> aliases = trustStore.aliases(); aliases.hasMoreElements(); ) {
            String alias = aliases.nextElement();
            if (trustStore.isCertificateEntry(alias)) {
                X509Certificate cert = (X509Certificate) trustStore.getCertificate(alias);
                all_certs.add(cert);
            }
        }
        // Finally, add all the certs in the chain:
        for (int i = 0; i < chain.length; ++i) {
            all_certs.add(chain[i]);
        }
        CertStore cs = CertStore.getInstance("Collection", new CollectionCertStoreParameters(all_certs));
        X509CertSelector selector = new X509CertSelector();
        selector.setCertificate(first);
        // / selector.setSubject(first.getSubjectX500Principal());
        PKIXBuilderParameters params = new PKIXBuilderParameters(trustStore, selector);
        params.addCertStore(cs);
        params.setDate(new Date());
        params.setRevocationEnabled(false);
        /* Code here is the right way to do things. */
        CertPathBuilder pathBuilder = CertPathBuilder.getInstance(CertPathBuilder.getDefaultType());
        CertPath cp = pathBuilder.build(params).getCertPath();
        /**
             * This section is an alternative to using CertPathBuilder which is
             * not as complete (or safe), but will emit much better errors. If
             * things break, swap around the code.
             *
             **** COMMENTED OUT. ****
            ArrayList<X509Certificate> ls = new ArrayList<X509Certificate>();
            for (int i = 0; i < chain.length; ++i) {
                ls.add((X509Certificate) chain[i]);
            }
            for (X509Certificate last = ls.get(ls.size() - 1); !last
                    .getIssuerX500Principal().equals(last.getSubjectX500Principal()); last = ls
                    .get(ls.size() - 1)) {
                X509CertSelector sel = new X509CertSelector();
                sel.setSubject(last.getIssuerX500Principal());
                ls.add((X509Certificate) cs.getCertificates(sel).toArray()[0]);
            }
            CertPath cp = CertificateFactory.getInstance("X.509").generateCertPath(ls);
             ****** END ALTERNATIVE. ****
             */
        // Not entirely sure if I need to do this with CertPathBuilder.
        // Can't hurt.
        CertPathValidator pathValidator = CertPathValidator.getInstance("PKIX");
        pathValidator.validate(cp, params);
        return (X509Certificate) cp.getCertificates().get(0);
    } catch (CertPathBuilderException e) {
        Log.warn("Path builder: " + e.getMessage());
    } catch (CertPathValidatorException e) {
        Log.warn("Path validator: " + e.getMessage());
    } catch (Exception e) {
        Log.warn("Unkown exception while validating certificate chain: " + e.getMessage());
    }
    return null;
}
Also used : PKIXBuilderParameters(java.security.cert.PKIXBuilderParameters) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) ArrayList(java.util.ArrayList) CertificateException(java.security.cert.CertificateException) X509CertSelector(java.security.cert.X509CertSelector) KeyStoreException(java.security.KeyStoreException) X509Certificate(java.security.cert.X509Certificate) Date(java.util.Date) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) KeyStoreException(java.security.KeyStoreException) GeneralSecurityException(java.security.GeneralSecurityException) CertPathValidatorException(java.security.cert.CertPathValidatorException) CertException(org.bouncycastle.cert.CertException) CertPathBuilderException(java.security.cert.CertPathBuilderException) PKCSException(org.bouncycastle.pkcs.PKCSException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) NoSuchProviderException(java.security.NoSuchProviderException) CertPathValidator(java.security.cert.CertPathValidator) CertPathValidatorException(java.security.cert.CertPathValidatorException) CollectionCertStoreParameters(java.security.cert.CollectionCertStoreParameters) CertPathBuilderException(java.security.cert.CertPathBuilderException) CertPathBuilder(java.security.cert.CertPathBuilder) CertPath(java.security.cert.CertPath) CertStore(java.security.cert.CertStore) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Example 28 with CertificateException

use of java.security.cert.CertificateException in project Smack by igniterealtime.

the class XmppHostnameVerifier method matchDns.

/**
     * Try to match a certificate with a DNS name. This method returns if the certificate matches or
     * throws a {@link CertificateException} if not.
     *
     * @param name the DNS name.
     * @param cert the certificate.
     * @throws CertificateException if the DNS name does not match the certificate.
     */
private static void matchDns(String name, X509Certificate cert) throws CertificateException {
    Collection<List<?>> subjAltNames = cert.getSubjectAlternativeNames();
    if (subjAltNames != null) {
        List<String> nonMatchingDnsAltnames = new LinkedList<>();
        for (List<?> san : subjAltNames) {
            if (((Integer) san.get(0)).intValue() != ALTNAME_DNS) {
                continue;
            }
            String dnsName = (String) san.get(1);
            if (matchesPerRfc2818(name, dnsName)) {
                // Signal success by returning.
                return;
            } else {
                nonMatchingDnsAltnames.add(dnsName);
            }
        }
        if (!nonMatchingDnsAltnames.isEmpty()) {
            // Reject if certificate contains subject alt names, but none of them matches
            StringBuilder sb = new StringBuilder("No subject alternative DNS name matching " + name + " found. Tried: ");
            for (String nonMatchingDnsAltname : nonMatchingDnsAltnames) {
                sb.append(nonMatchingDnsAltname).append(',');
            }
            throw new CertificateException(sb.toString());
        }
    }
    // Control flow will end here if the X509 certificate does not have *any* Subject
    // Alternative Names (SANs). Fallback trying to validate against the CN of the subject.
    LdapName dn = null;
    try {
        dn = new LdapName(cert.getSubjectX500Principal().getName());
    } catch (InvalidNameException e) {
        LOGGER.warning("Invalid DN: " + e.getMessage());
    }
    if (dn != null) {
        for (Rdn rdn : dn.getRdns()) {
            if (rdn.getType().equalsIgnoreCase("CN")) {
                if (matchesPerRfc2818(name, rdn.getValue().toString())) {
                    // Signal success by returning.
                    return;
                }
                break;
            }
        }
    }
    throw new CertificateException("No name matching " + name + " found");
}
Also used : InvalidNameException(javax.naming.InvalidNameException) List(java.util.List) LinkedList(java.util.LinkedList) CertificateException(java.security.cert.CertificateException) Rdn(javax.naming.ldap.Rdn) LinkedList(java.util.LinkedList) LdapName(javax.naming.ldap.LdapName)

Example 29 with CertificateException

use of java.security.cert.CertificateException in project k-9 by k9mail.

the class LocalKeyStore method setKeyStoreFile.

/**
     * Reinitialize the local key store with certificates contained in
     * {@code file}
     *
     * @param file
     *            {@link File} containing locally saved certificates. May be 0
     *            length, in which case it is deleted and recreated. May be
     *            {@code null}, in which case a default file location is used.
     * @throws CertificateException
     *            Occurs if {@code file == null} and
     *            {@code setKeyStoreLocation(directory)} was not called previously.
     */
public synchronized void setKeyStoreFile(File file) throws CertificateException {
    if (file == null) {
        file = new File(getKeyStoreFilePath(KEY_STORE_FILE_VERSION));
    }
    if (file.length() == 0) {
        /*
             * The file may be empty (e.g., if it was created with
             * File.createTempFile). We can't pass an empty file to
             * Keystore.load. Instead, we let it be created anew.
             */
        if (file.exists() && !file.delete()) {
            Log.d(LOG_TAG, "Failed to delete empty keystore file: " + file.getAbsolutePath());
        }
    }
    FileInputStream fis = null;
    try {
        fis = new FileInputStream(file);
    } catch (FileNotFoundException e) {
    // If the file doesn't exist, that's fine, too
    }
    try {
        KeyStore store = KeyStore.getInstance(KeyStore.getDefaultType());
        store.load(fis, "".toCharArray());
        mKeyStore = store;
        mKeyStoreFile = file;
    } catch (Exception e) {
        Log.e(LOG_TAG, "Failed to initialize local key store", e);
        // Use of the local key store is effectively disabled.
        mKeyStore = null;
        mKeyStoreFile = null;
    } finally {
        IOUtils.closeQuietly(fis);
    }
}
Also used : FileNotFoundException(java.io.FileNotFoundException) File(java.io.File) KeyStore(java.security.KeyStore) FileInputStream(java.io.FileInputStream) IOException(java.io.IOException) KeyStoreException(java.security.KeyStoreException) CertificateException(java.security.cert.CertificateException) FileNotFoundException(java.io.FileNotFoundException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException)

Example 30 with CertificateException

use of java.security.cert.CertificateException in project c-geo by just-radovan.

the class cgBase method trustAllHosts.

public static void trustAllHosts() {
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return new java.security.cert.X509Certificate[] {};
        }

        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }
    } };
    try {
        SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (Exception e) {
        Log.e(cgSettings.tag, "cgBase.trustAllHosts: " + e.toString());
    }
}
Also used : X509TrustManager(javax.net.ssl.X509TrustManager) SSLContext(javax.net.ssl.SSLContext) X509Certificate(java.security.cert.X509Certificate) SocketException(java.net.SocketException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) TrustManager(javax.net.ssl.TrustManager) X509TrustManager(javax.net.ssl.X509TrustManager)

Aggregations

CertificateException (java.security.cert.CertificateException)456 IOException (java.io.IOException)221 X509Certificate (java.security.cert.X509Certificate)215 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)141 KeyStoreException (java.security.KeyStoreException)123 CertificateFactory (java.security.cert.CertificateFactory)103 ByteArrayInputStream (java.io.ByteArrayInputStream)97 Certificate (java.security.cert.Certificate)75 KeyStore (java.security.KeyStore)58 InputStream (java.io.InputStream)55 UnrecoverableKeyException (java.security.UnrecoverableKeyException)53 ArrayList (java.util.ArrayList)49 InvalidKeyException (java.security.InvalidKeyException)44 X509TrustManager (javax.net.ssl.X509TrustManager)41 SSLContext (javax.net.ssl.SSLContext)36 FileInputStream (java.io.FileInputStream)34 InvalidAlgorithmParameterException (java.security.InvalidAlgorithmParameterException)34 RemoteException (android.os.RemoteException)33 FileNotFoundException (java.io.FileNotFoundException)30 KeyManagementException (java.security.KeyManagementException)30