Search in sources :

Example 1 with CertPathBuilder

use of java.security.cert.CertPathBuilder 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 2 with CertPathBuilder

use of java.security.cert.CertPathBuilder in project XobotOS by xamarin.

the class RFC3280CertPathUtilities method processCRLF.

/**
     * Obtain and validate the certification path for the complete CRL issuer.
     * If a key usage extension is present in the CRL issuer's certificate,
     * verify that the cRLSign bit is set.
     *
     * @param crl                CRL which contains revocation information for the certificate
     *                           <code>cert</code>.
     * @param cert               The attribute certificate or certificate to check if it is
     *                           revoked.
     * @param defaultCRLSignCert The issuer certificate of the certificate <code>cert</code>.
     * @param defaultCRLSignKey  The public key of the issuer certificate
     *                           <code>defaultCRLSignCert</code>.
     * @param paramsPKIX         paramsPKIX PKIX parameters.
     * @param certPathCerts      The certificates on the certification path.
     * @return A <code>Set</code> with all keys of possible CRL issuer
     *         certificates.
     * @throws AnnotatedException if the CRL is not valid or the status cannot be checked or
     *                            some error occurs.
     */
protected static Set processCRLF(X509CRL crl, Object cert, X509Certificate defaultCRLSignCert, PublicKey defaultCRLSignKey, ExtendedPKIXParameters paramsPKIX, List certPathCerts) throws AnnotatedException {
    // (f)
    // get issuer from CRL
    X509CertStoreSelector selector = new X509CertStoreSelector();
    try {
        byte[] issuerPrincipal = CertPathValidatorUtilities.getIssuerPrincipal(crl).getEncoded();
        selector.setSubject(issuerPrincipal);
    } catch (IOException e) {
        throw new AnnotatedException("Subject criteria for certificate selector to find issuer certificate for CRL could not be set.", e);
    }
    // get CRL signing certs
    Collection coll;
    try {
        coll = CertPathValidatorUtilities.findCertificates(selector, paramsPKIX.getStores());
        coll.addAll(CertPathValidatorUtilities.findCertificates(selector, paramsPKIX.getAdditionalStores()));
        coll.addAll(CertPathValidatorUtilities.findCertificates(selector, paramsPKIX.getCertStores()));
    } catch (AnnotatedException e) {
        throw new AnnotatedException("Issuer certificate for CRL cannot be searched.", e);
    }
    coll.add(defaultCRLSignCert);
    Iterator cert_it = coll.iterator();
    List validCerts = new ArrayList();
    List validKeys = new ArrayList();
    while (cert_it.hasNext()) {
        X509Certificate signingCert = (X509Certificate) cert_it.next();
        /*
             * CA of the certificate, for which this CRL is checked, has also
             * signed CRL, so skip the path validation, because is already done
             */
        if (signingCert.equals(defaultCRLSignCert)) {
            validCerts.add(signingCert);
            validKeys.add(defaultCRLSignKey);
            continue;
        }
        try {
            CertPathBuilder builder = CertPathBuilder.getInstance("PKIX", BouncyCastleProvider.PROVIDER_NAME);
            selector = new X509CertStoreSelector();
            selector.setCertificate(signingCert);
            ExtendedPKIXParameters temp = (ExtendedPKIXParameters) paramsPKIX.clone();
            temp.setTargetCertConstraints(selector);
            ExtendedPKIXBuilderParameters params = (ExtendedPKIXBuilderParameters) ExtendedPKIXBuilderParameters.getInstance(temp);
            /*
                 * if signingCert is placed not higher on the cert path a
                 * dependency loop results. CRL for cert is checked, but
                 * signingCert is needed for checking the CRL which is dependent
                 * on checking cert because it is higher in the cert path and so
                 * signing signingCert transitively. so, revocation is disabled,
                 * forgery attacks of the CRL are detected in this outer loop
                 * for all other it must be enabled to prevent forgery attacks
                 */
            if (certPathCerts.contains(signingCert)) {
                params.setRevocationEnabled(false);
            } else {
                params.setRevocationEnabled(true);
            }
            List certs = builder.build(params).getCertPath().getCertificates();
            validCerts.add(signingCert);
            validKeys.add(CertPathValidatorUtilities.getNextWorkingKey(certs, 0));
        } catch (CertPathBuilderException e) {
            throw new AnnotatedException("Internal error.", e);
        } catch (CertPathValidatorException e) {
            throw new AnnotatedException("Public key of issuer certificate of CRL could not be retrieved.", e);
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    }
    Set checkKeys = new HashSet();
    AnnotatedException lastException = null;
    for (int i = 0; i < validCerts.size(); i++) {
        X509Certificate signCert = (X509Certificate) validCerts.get(i);
        boolean[] keyusage = signCert.getKeyUsage();
        if (keyusage != null && (keyusage.length < 7 || !keyusage[CRL_SIGN])) {
            lastException = new AnnotatedException("Issuer certificate key usage extension does not permit CRL signing.");
        } else {
            checkKeys.add(validKeys.get(i));
        }
    }
    if (checkKeys.isEmpty() && lastException == null) {
        throw new AnnotatedException("Cannot find a valid issuer certificate.");
    }
    if (checkKeys.isEmpty() && lastException != null) {
        throw lastException;
    }
    return checkKeys;
}
Also used : Set(java.util.Set) HashSet(java.util.HashSet) ExtendedPKIXBuilderParameters(org.bouncycastle.x509.ExtendedPKIXBuilderParameters) X509CertStoreSelector(org.bouncycastle.x509.X509CertStoreSelector) ArrayList(java.util.ArrayList) IOException(java.io.IOException) X509Certificate(java.security.cert.X509Certificate) CertificateExpiredException(java.security.cert.CertificateExpiredException) GeneralSecurityException(java.security.GeneralSecurityException) CertPathValidatorException(java.security.cert.CertPathValidatorException) ExtCertPathValidatorException(org.bouncycastle.jce.exception.ExtCertPathValidatorException) CertificateNotYetValidException(java.security.cert.CertificateNotYetValidException) CertPathBuilderException(java.security.cert.CertPathBuilderException) IOException(java.io.IOException) IssuingDistributionPoint(org.bouncycastle.asn1.x509.IssuingDistributionPoint) CRLDistPoint(org.bouncycastle.asn1.x509.CRLDistPoint) DistributionPoint(org.bouncycastle.asn1.x509.DistributionPoint) CertPathValidatorException(java.security.cert.CertPathValidatorException) ExtCertPathValidatorException(org.bouncycastle.jce.exception.ExtCertPathValidatorException) ExtendedPKIXParameters(org.bouncycastle.x509.ExtendedPKIXParameters) CertPathBuilderException(java.security.cert.CertPathBuilderException) Iterator(java.util.Iterator) Collection(java.util.Collection) List(java.util.List) ArrayList(java.util.ArrayList) CertPathBuilder(java.security.cert.CertPathBuilder) HashSet(java.util.HashSet)

Example 3 with CertPathBuilder

use of java.security.cert.CertPathBuilder in project jdk8u_jdk by JetBrains.

the class BuildOddSel method build.

/**
     * Perform a PKIX build.
     *
     * @param params PKIXBuilderParameters to use in building
     * @throws Exception on error
     */
public static void build(PKIXBuilderParameters params) throws Exception {
    CertPathBuilder builder = CertPathBuilder.getInstance("PKIX");
    CertPathBuilderResult cpbr = builder.build(params);
}
Also used : CertPathBuilderResult(java.security.cert.CertPathBuilderResult) CertPathBuilder(java.security.cert.CertPathBuilder)

Example 4 with CertPathBuilder

use of java.security.cert.CertPathBuilder in project jdk8u_jdk by JetBrains.

the class ValidateNC method build.

/**
     * Perform a PKIX build.
     *
     * @param params PKIXBuilderParameters to use in the build
     * @throws Exception on error
     */
public static void build(PKIXBuilderParameters params) throws Exception {
    CertPathBuilder builder = CertPathBuilder.getInstance("PKIX", "SUN");
    CertPathBuilderResult cpbr = builder.build(params);
}
Also used : CertPathBuilderResult(java.security.cert.CertPathBuilderResult) CertPathBuilder(java.security.cert.CertPathBuilder)

Example 5 with CertPathBuilder

use of java.security.cert.CertPathBuilder in project jdk8u_jdk by JetBrains.

the class GetInstance method main.

public static void main(String[] argv) throws Exception {
    Provider stubProvider = new StubProvider();
    CertPathBuilder cpb = CertPathBuilder.getInstance("PKIX", stubProvider);
    System.out.println("Test passed.");
}
Also used : CertPathBuilder(java.security.cert.CertPathBuilder) Provider(java.security.Provider)

Aggregations

CertPathBuilder (java.security.cert.CertPathBuilder)36 PKIXBuilderParameters (java.security.cert.PKIXBuilderParameters)20 X509CertSelector (java.security.cert.X509CertSelector)20 X509Certificate (java.security.cert.X509Certificate)19 CollectionCertStoreParameters (java.security.cert.CollectionCertStoreParameters)15 HashSet (java.util.HashSet)14 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)10 CertPathBuilderException (java.security.cert.CertPathBuilderException)10 CertPathBuilderResult (java.security.cert.CertPathBuilderResult)10 TrustAnchor (java.security.cert.TrustAnchor)10 ArrayList (java.util.ArrayList)9 CertPath (java.security.cert.CertPath)8 InvalidAlgorithmParameterException (java.security.InvalidAlgorithmParameterException)7 NoSuchProviderException (java.security.NoSuchProviderException)7 CertPathValidator (java.security.cert.CertPathValidator)7 CertStore (java.security.cert.CertStore)7 GeneralSecurityException (java.security.GeneralSecurityException)6 Certificate (java.security.cert.Certificate)6 PKIXCertPathBuilderResult (java.security.cert.PKIXCertPathBuilderResult)6 IOException (java.io.IOException)5