Search in sources :

Example 1 with CertPath

use of java.security.cert.CertPath 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 CertPath

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

the class PKIXCertPathBuilderSpi method build.

protected CertPathBuilderResult build(X509Certificate tbvCert, ExtendedPKIXBuilderParameters pkixParams, List tbvPath) {
    // PKI graph.
    if (tbvPath.contains(tbvCert)) {
        return null;
    }
    // chain.
    if (pkixParams.getExcludedCerts().contains(tbvCert)) {
        return null;
    }
    // test if certificate path exceeds maximum length
    if (pkixParams.getMaxPathLength() != -1) {
        if (tbvPath.size() - 1 > pkixParams.getMaxPathLength()) {
            return null;
        }
    }
    tbvPath.add(tbvCert);
    CertificateFactory cFact;
    CertPathValidator validator;
    CertPathBuilderResult builderResult = null;
    try {
        cFact = CertificateFactory.getInstance("X.509", BouncyCastleProvider.PROVIDER_NAME);
        validator = CertPathValidator.getInstance("PKIX", BouncyCastleProvider.PROVIDER_NAME);
    } catch (Exception e) {
        // cannot happen
        throw new RuntimeException("Exception creating support classes.");
    }
    try {
        // check whether the issuer of <tbvCert> is a TrustAnchor
        if (CertPathValidatorUtilities.findTrustAnchor(tbvCert, pkixParams.getTrustAnchors(), pkixParams.getSigProvider()) != null) {
            // exception message from possibly later tried certification
            // chains
            CertPath certPath = null;
            PKIXCertPathValidatorResult result = null;
            try {
                certPath = cFact.generateCertPath(tbvPath);
            } catch (Exception e) {
                throw new AnnotatedException("Certification path could not be constructed from certificate list.", e);
            }
            try {
                result = (PKIXCertPathValidatorResult) validator.validate(certPath, pkixParams);
            } catch (Exception e) {
                throw new AnnotatedException("Certification path could not be validated.", e);
            }
            return new PKIXCertPathBuilderResult(certPath, result.getTrustAnchor(), result.getPolicyTree(), result.getPublicKey());
        } else {
            // add additional X.509 stores from locations in certificate
            try {
                CertPathValidatorUtilities.addAdditionalStoresFromAltNames(tbvCert, pkixParams);
            } catch (CertificateParsingException e) {
                throw new AnnotatedException("No additiontal X.509 stores can be added from certificate locations.", e);
            }
            Collection issuers = new HashSet();
            // of the stores
            try {
                issuers.addAll(CertPathValidatorUtilities.findIssuerCerts(tbvCert, pkixParams));
            } catch (AnnotatedException e) {
                throw new AnnotatedException("Cannot find issuer certificate for certificate in certification path.", e);
            }
            if (issuers.isEmpty()) {
                throw new AnnotatedException("No issuer certificate for certificate in certification path found.");
            }
            Iterator it = issuers.iterator();
            while (it.hasNext() && builderResult == null) {
                X509Certificate issuer = (X509Certificate) it.next();
                builderResult = build(issuer, pkixParams, tbvPath);
            }
        }
    } catch (AnnotatedException e) {
        certPathException = e;
    }
    if (builderResult == null) {
        tbvPath.remove(tbvCert);
    }
    return builderResult;
}
Also used : CertificateParsingException(java.security.cert.CertificateParsingException) CertPathBuilderResult(java.security.cert.CertPathBuilderResult) PKIXCertPathBuilderResult(java.security.cert.PKIXCertPathBuilderResult) CertificateFactory(java.security.cert.CertificateFactory) CertificateParsingException(java.security.cert.CertificateParsingException) ExtCertPathBuilderException(org.bouncycastle.jce.exception.ExtCertPathBuilderException) InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) CertPathBuilderException(java.security.cert.CertPathBuilderException) X509Certificate(java.security.cert.X509Certificate) CertPathValidator(java.security.cert.CertPathValidator) PKIXCertPathValidatorResult(java.security.cert.PKIXCertPathValidatorResult) PKIXCertPathBuilderResult(java.security.cert.PKIXCertPathBuilderResult) Iterator(java.util.Iterator) Collection(java.util.Collection) CertPath(java.security.cert.CertPath) HashSet(java.util.HashSet)

Example 3 with CertPath

use of java.security.cert.CertPath in project OpenAM by OpenRock.

the class AMCertPath method verify.

/**
     * It does cert path validation together with CRL check and ocsp checking 
     * if they are properly configured.
     * @param certs
     **/
public boolean verify(X509Certificate[] certs, boolean crlEnabled, boolean ocspEnabled) {
    /*
        The entire contents of this method must be synchronized for the following reasons:
        1. The CertPathValidator#validate method is not thread-safe
        2. even if a non-static CertPathValidator instance were obtained in this method, each instance references
        the ocsp-related properties in the Security class. Thus the state set in Security.setProperty("ocsp.enable", true/false)
        will affect all CertPathValidator instances.
        Note that despite the synchronized block, the fact that static Security properties are being set and referenced
        exposes the code below to data races in the context of these Security properties. Currently, Security.setProperties
        is not being called from anywhere in the OpenAM code base. If this were to change, and the "ocsp.enable" property
        were manipulated, the OCSP-based checking below would be susceptible to data races. There does not seem to
        be an alternative however: the section on PKIXParameters here:
        http://docs.oracle.com/javase/6/docs/technotes/guides/security/certpath/CertPathProgGuide.html#Introduction
        mentions setting PKIXCertPathChecker implementations to do CRL or OCSP based checking, but there is no remove
        method, and the state returned from getCertPathCheckers is immutable.
         */
    synchronized (AMCertPath.class) {
        if (debug.messageEnabled()) {
            debug.message("AMCertPath.verify: invoked !");
        }
        try {
            final List<X509Certificate> certList = Arrays.asList(certs);
            final CertPath cp = (CertPath) cf.generateCertPath(certList);
            // init PKIXParameters
            Class<?> trustMgrClass = Class.forName("com.sun.identity.security.keystore.AMX509TrustManager");
            Object trustMgr = (Object) trustMgrClass.newInstance();
            Method method = trustMgrClass.getMethod("getKeyStore");
            KeyStore keystore = (KeyStore) method.invoke(trustMgr);
            PKIXParameters pkixparams = new PKIXParameters(keystore);
            if (debug.messageEnabled()) {
                debug.message("AMCertPath.verify: crlEnabled ---> " + crlEnabled);
                debug.message("AMCertPath.verify: ocspEnabled ---> " + ocspEnabled);
            }
            pkixparams.setRevocationEnabled(crlEnabled || ocspEnabled);
            if (ocspEnabled) {
                final String responderURLString = getResponderURLString();
                if (!StringUtils.isBlank(responderURLString)) {
                    Security.setProperty(OCSP_ENABLE, TRUE);
                    Security.setProperty(OCSP_RESPONDER_URL, responderURLString);
                    if (debug.messageEnabled()) {
                        debug.message("AMCertPath.verify: pkixparams.setRevocationEnabled " + "set to true, and ocsp.enabled set to true with a OCSP responder url of " + responderURLString);
                    }
                } else {
                    //OCSP revocation checking not configured properly. Disable the check if crl-based checking not enabled
                    pkixparams.setRevocationEnabled(crlEnabled);
                    Security.setProperty(OCSP_ENABLE, FALSE);
                    debug.error("AMCertPath.verify: OCSP is enabled, but the " + "com.sun.identity.authentication.ocsp.responder.url property does not specify a OCSP " + "responder. OCSP checking will NOT be performed.");
                }
            } else {
                //the Security properties are static - if we are doing crl validation, insure that the property
                //is not present which will toggle OCSP checking.
                Security.setProperty(OCSP_ENABLE, FALSE);
                if (debug.messageEnabled()) {
                    debug.message("AMCertPath.verify: pkixparams Security property ocsp.enabled set to false.");
                }
            }
            if (store != null) {
                pkixparams.addCertStore(store);
            }
            if (debug.messageEnabled()) {
                StringBuilder sb = new StringBuilder("The policy-related state in the PKIXParameters passed to the PKIX CertPathValidator: \n");
                sb.append("\tgetInitialPolicies: ").append(pkixparams.getInitialPolicies()).append('\n');
                sb.append("\tisExplicitPolicyRequired: ").append(pkixparams.isExplicitPolicyRequired()).append('\n');
                sb.append("\tisPolicyMappingInhibited: ").append(pkixparams.isPolicyMappingInhibited()).append('\n');
                debug.message(sb.toString());
            }
            // validate
            CertPathValidatorResult cpvResult = cpv.validate(cp, pkixparams);
            if (debug.messageEnabled()) {
                debug.message("AMCertPath.verify: PASS " + cpvResult.toString());
            }
        } catch (java.security.cert.CertPathValidatorException e) {
            debug.error("AMCertPath.verify: FAILED - " + e.getMessage());
            if (debug.messageEnabled()) {
                debug.message("AMCertPath.verify: FAILED", e);
            }
            return false;
        } catch (Throwable t) {
            debug.error("AMCertPath.verify: FAILED", t);
            return false;
        }
        return true;
    }
}
Also used : Method(java.lang.reflect.Method) KeyStore(java.security.KeyStore) X509Certificate(java.security.cert.X509Certificate) PKIXParameters(java.security.cert.PKIXParameters) CertPath(java.security.cert.CertPath) CertPathValidatorResult(java.security.cert.CertPathValidatorResult)

Example 4 with CertPath

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

the class BuildEEBasicConstraints method main.

public static void main(String[] args) throws Exception {
    // reset the security property to make sure that the algorithms
    // and keys used in this test are not disabled.
    Security.setProperty("jdk.certpath.disabledAlgorithms", "MD2");
    X509Certificate rootCert = CertUtils.getCertFromFile("anchor.cer");
    TrustAnchor anchor = new TrustAnchor(rootCert.getSubjectX500Principal(), rootCert.getPublicKey(), null);
    X509CertSelector sel = new X509CertSelector();
    sel.setBasicConstraints(-2);
    PKIXBuilderParameters params = new PKIXBuilderParameters(Collections.singleton(anchor), sel);
    params.setRevocationEnabled(false);
    X509Certificate eeCert = CertUtils.getCertFromFile("ee.cer");
    X509Certificate caCert = CertUtils.getCertFromFile("ca.cer");
    ArrayList<X509Certificate> certs = new ArrayList<X509Certificate>();
    certs.add(caCert);
    certs.add(eeCert);
    CollectionCertStoreParameters ccsp = new CollectionCertStoreParameters(certs);
    CertStore cs = CertStore.getInstance("Collection", ccsp);
    params.addCertStore(cs);
    PKIXCertPathBuilderResult res = CertUtils.build(params);
    CertPath cp = res.getCertPath();
    // check that first certificate is an EE cert
    List<? extends Certificate> certList = cp.getCertificates();
    X509Certificate cert = (X509Certificate) certList.get(0);
    if (cert.getBasicConstraints() != -1) {
        throw new Exception("Target certificate is not an EE certificate");
    }
}
Also used : CollectionCertStoreParameters(java.security.cert.CollectionCertStoreParameters) PKIXBuilderParameters(java.security.cert.PKIXBuilderParameters) PKIXCertPathBuilderResult(java.security.cert.PKIXCertPathBuilderResult) ArrayList(java.util.ArrayList) TrustAnchor(java.security.cert.TrustAnchor) X509CertSelector(java.security.cert.X509CertSelector) CertPath(java.security.cert.CertPath) CertStore(java.security.cert.CertStore) X509Certificate(java.security.cert.X509Certificate)

Example 5 with CertPath

use of java.security.cert.CertPath in project robovm by robovm.

the class CertificateFactory3Test method testGenerateCertPath01.

/**
     * Test for <code>generateCertPath(List certificates)</code> method
     * Assertion: returns CertPath with 1 Certificate
     */
public void testGenerateCertPath01() throws Exception {
    CertificateFactory[] certFs = initCertFs();
    assertNotNull("CertificateFactory objects were not created", certFs);
    // create list of certificates with one certificate
    Certificate cert = certFs[0].generateCertificate(new ByteArrayInputStream(TestUtils.getEncodedX509Certificate()));
    List<Certificate> list = new Vector<Certificate>();
    list.add(cert);
    for (int i = 0; i < certFs.length; i++) {
        CertPath certPath = null;
        certPath = certFs[i].generateCertPath(list);
        assertEquals(cert.getType(), certPath.getType());
        List<? extends Certificate> list1 = certPath.getCertificates();
        assertFalse("Result list is empty", list1.isEmpty());
        Iterator<? extends Certificate> it = list1.iterator();
        assertEquals("Incorrect Certificate in CertPath", cert, it.next());
    }
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) CertPath(java.security.cert.CertPath) CertificateFactory(java.security.cert.CertificateFactory) Vector(java.util.Vector) Certificate(java.security.cert.Certificate)

Aggregations

CertPath (java.security.cert.CertPath)84 X509Certificate (java.security.cert.X509Certificate)35 CertificateFactory (java.security.cert.CertificateFactory)29 Certificate (java.security.cert.Certificate)19 CertPathValidatorException (java.security.cert.CertPathValidatorException)18 CertPathValidator (java.security.cert.CertPathValidator)17 MyCertPath (org.apache.harmony.security.tests.support.cert.MyCertPath)17 CertificateException (java.security.cert.CertificateException)15 ArrayList (java.util.ArrayList)15 MyFailingCertPath (org.apache.harmony.security.tests.support.cert.MyFailingCertPath)14 PKIXParameters (java.security.cert.PKIXParameters)13 ByteArrayInputStream (java.io.ByteArrayInputStream)11 CertPathBuilderResult (java.security.cert.CertPathBuilderResult)11 InvalidAlgorithmParameterException (java.security.InvalidAlgorithmParameterException)10 PKIXCertPathValidatorResult (java.security.cert.PKIXCertPathValidatorResult)10 TrustAnchor (java.security.cert.TrustAnchor)10 HashSet (java.util.HashSet)10 PKIXBuilderParameters (java.security.cert.PKIXBuilderParameters)9 X509CertSelector (java.security.cert.X509CertSelector)9 IOException (java.io.IOException)8