Search in sources :

Example 81 with Extension

use of org.bouncycastle.asn1.x509.Extension in project XobotOS by xamarin.

the class RFC3280CertPathUtilities method processCRLB2.

/**
     * If the complete CRL includes an issuing distribution point (IDP) CRL
     * extension check the following:
     * <p/>
     * (i) If the distribution point name is present in the IDP CRL extension
     * and the distribution field is present in the DP, then verify that one of
     * the names in the IDP matches one of the names in the DP. If the
     * distribution point name is present in the IDP CRL extension and the
     * distribution field is omitted from the DP, then verify that one of the
     * names in the IDP matches one of the names in the cRLIssuer field of the
     * DP.
     * </p>
     * <p/>
     * (ii) If the onlyContainsUserCerts boolean is asserted in the IDP CRL
     * extension, verify that the certificate does not include the basic
     * constraints extension with the cA boolean asserted.
     * </p>
     * <p/>
     * (iii) If the onlyContainsCACerts boolean is asserted in the IDP CRL
     * extension, verify that the certificate includes the basic constraints
     * extension with the cA boolean asserted.
     * </p>
     * <p/>
     * (iv) Verify that the onlyContainsAttributeCerts boolean is not asserted.
     * </p>
     *
     * @param dp   The distribution point.
     * @param cert The certificate.
     * @param crl  The CRL.
     * @throws AnnotatedException if one of the conditions is not met or an error occurs.
     */
protected static void processCRLB2(DistributionPoint dp, Object cert, X509CRL crl) throws AnnotatedException {
    IssuingDistributionPoint idp = null;
    try {
        idp = IssuingDistributionPoint.getInstance(CertPathValidatorUtilities.getExtensionValue(crl, RFC3280CertPathUtilities.ISSUING_DISTRIBUTION_POINT));
    } catch (Exception e) {
        throw new AnnotatedException("Issuing distribution point extension could not be decoded.", e);
    }
    // distribution point name is present
    if (idp != null) {
        if (idp.getDistributionPoint() != null) {
            // make list of names
            DistributionPointName dpName = IssuingDistributionPoint.getInstance(idp).getDistributionPoint();
            List names = new ArrayList();
            if (dpName.getType() == DistributionPointName.FULL_NAME) {
                GeneralName[] genNames = GeneralNames.getInstance(dpName.getName()).getNames();
                for (int j = 0; j < genNames.length; j++) {
                    names.add(genNames[j]);
                }
            }
            if (dpName.getType() == DistributionPointName.NAME_RELATIVE_TO_CRL_ISSUER) {
                ASN1EncodableVector vec = new ASN1EncodableVector();
                try {
                    Enumeration e = ASN1Sequence.getInstance(ASN1Sequence.fromByteArray(CertPathValidatorUtilities.getIssuerPrincipal(crl).getEncoded())).getObjects();
                    while (e.hasMoreElements()) {
                        vec.add((DEREncodable) e.nextElement());
                    }
                } catch (IOException e) {
                    throw new AnnotatedException("Could not read CRL issuer.", e);
                }
                vec.add(dpName.getName());
                names.add(new GeneralName(X509Name.getInstance(new DERSequence(vec))));
            }
            boolean matches = false;
            // of the names in the DP.
            if (dp.getDistributionPoint() != null) {
                dpName = dp.getDistributionPoint();
                GeneralName[] genNames = null;
                if (dpName.getType() == DistributionPointName.FULL_NAME) {
                    genNames = GeneralNames.getInstance(dpName.getName()).getNames();
                }
                if (dpName.getType() == DistributionPointName.NAME_RELATIVE_TO_CRL_ISSUER) {
                    if (dp.getCRLIssuer() != null) {
                        genNames = dp.getCRLIssuer().getNames();
                    } else {
                        genNames = new GeneralName[1];
                        try {
                            genNames[0] = new GeneralName(new X509Name((ASN1Sequence) ASN1Sequence.fromByteArray(CertPathValidatorUtilities.getEncodedIssuerPrincipal(cert).getEncoded())));
                        } catch (IOException e) {
                            throw new AnnotatedException("Could not read certificate issuer.", e);
                        }
                    }
                    for (int j = 0; j < genNames.length; j++) {
                        Enumeration e = ASN1Sequence.getInstance(genNames[j].getName().getDERObject()).getObjects();
                        ASN1EncodableVector vec = new ASN1EncodableVector();
                        while (e.hasMoreElements()) {
                            vec.add((DEREncodable) e.nextElement());
                        }
                        vec.add(dpName.getName());
                        genNames[j] = new GeneralName(new X509Name(new DERSequence(vec)));
                    }
                }
                if (genNames != null) {
                    for (int j = 0; j < genNames.length; j++) {
                        if (names.contains(genNames[j])) {
                            matches = true;
                            break;
                        }
                    }
                }
                if (!matches) {
                    throw new AnnotatedException("No match for certificate CRL issuing distribution point name to cRLIssuer CRL distribution point.");
                }
            } else // verify that one of the names in
            // the IDP matches one of the names in the cRLIssuer field of
            // the DP
            {
                if (dp.getCRLIssuer() == null) {
                    throw new AnnotatedException("Either the cRLIssuer or the distributionPoint field must " + "be contained in DistributionPoint.");
                }
                GeneralName[] genNames = dp.getCRLIssuer().getNames();
                for (int j = 0; j < genNames.length; j++) {
                    if (names.contains(genNames[j])) {
                        matches = true;
                        break;
                    }
                }
                if (!matches) {
                    throw new AnnotatedException("No match for certificate CRL issuing distribution point name to cRLIssuer CRL distribution point.");
                }
            }
        }
        BasicConstraints bc = null;
        try {
            bc = BasicConstraints.getInstance(CertPathValidatorUtilities.getExtensionValue((X509Extension) cert, BASIC_CONSTRAINTS));
        } catch (Exception e) {
            throw new AnnotatedException("Basic constraints extension could not be decoded.", e);
        }
        if (cert instanceof X509Certificate) {
            // (b) (2) (ii)
            if (idp.onlyContainsUserCerts() && (bc != null && bc.isCA())) {
                throw new AnnotatedException("CA Cert CRL only contains user certificates.");
            }
            // (b) (2) (iii)
            if (idp.onlyContainsCACerts() && (bc == null || !bc.isCA())) {
                throw new AnnotatedException("End CRL only contains CA certificates.");
            }
        }
        // (b) (2) (iv)
        if (idp.onlyContainsAttributeCerts()) {
            throw new AnnotatedException("onlyContainsAttributeCerts boolean is asserted.");
        }
    }
}
Also used : IssuingDistributionPoint(org.bouncycastle.asn1.x509.IssuingDistributionPoint) Enumeration(java.util.Enumeration) DistributionPointName(org.bouncycastle.asn1.x509.DistributionPointName) ArrayList(java.util.ArrayList) IOException(java.io.IOException) 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) X509Certificate(java.security.cert.X509Certificate) DERSequence(org.bouncycastle.asn1.DERSequence) X509Name(org.bouncycastle.asn1.x509.X509Name) ASN1EncodableVector(org.bouncycastle.asn1.ASN1EncodableVector) List(java.util.List) ArrayList(java.util.ArrayList) GeneralName(org.bouncycastle.asn1.x509.GeneralName) BasicConstraints(org.bouncycastle.asn1.x509.BasicConstraints)

Example 82 with Extension

use of org.bouncycastle.asn1.x509.Extension in project XobotOS by xamarin.

the class RFC3280CertPathUtilities method prepareNextCertK.

protected static void prepareNextCertK(CertPath certPath, int index) throws CertPathValidatorException {
    List certs = certPath.getCertificates();
    X509Certificate cert = (X509Certificate) certs.get(index);
    //
    // (k)
    //
    BasicConstraints bc = null;
    try {
        bc = BasicConstraints.getInstance(CertPathValidatorUtilities.getExtensionValue(cert, RFC3280CertPathUtilities.BASIC_CONSTRAINTS));
    } catch (Exception e) {
        throw new ExtCertPathValidatorException("Basic constraints extension cannot be decoded.", e, certPath, index);
    }
    if (bc != null) {
        if (!(bc.isCA())) {
            throw new CertPathValidatorException("Not a CA certificate");
        }
    } else {
        throw new CertPathValidatorException("Intermediate certificate lacks BasicConstraints");
    }
}
Also used : CertPathValidatorException(java.security.cert.CertPathValidatorException) ExtCertPathValidatorException(org.bouncycastle.jce.exception.ExtCertPathValidatorException) ExtCertPathValidatorException(org.bouncycastle.jce.exception.ExtCertPathValidatorException) List(java.util.List) ArrayList(java.util.ArrayList) BasicConstraints(org.bouncycastle.asn1.x509.BasicConstraints) 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)

Example 83 with Extension

use of org.bouncycastle.asn1.x509.Extension in project nhin-d by DirectProject.

the class TrustChainValidator method resolveIssuers.

protected void resolveIssuers(X509Certificate certificate, /*in-out*/
Collection<X509Certificate> issuers, int chainLength, Collection<X509Certificate> anchors) {
    X500Principal issuerPrin = certificate.getIssuerX500Principal();
    if (issuerPrin.equals(certificate.getSubjectX500Principal())) {
        // no intermediate between me, myself, and I
        return;
    }
    // look in the issuer list and see if the certificate issuer already exists in the list
    for (X509Certificate issuer : issuers) {
        if (issuerPrin.equals(issuer.getSubjectX500Principal()))
            // already found the certificate issuer... done
            return;
    }
    if (chainLength >= maxIssuerChainLength) {
        // bail out with what we have now
        return;
    }
    // first check to see there is an AIA extension with one ore more caIssuer entries and attempt to resolve the
    // intermediate via the URL
    final Collection<X509Certificate> issuerCerts = getIntermediateCertsByAIA(certificate);
    // of using resolvers
    if (issuerCerts.isEmpty()) {
        final String address = this.getIssuerAddress(certificate);
        if (address == null || address.isEmpty())
            // not much we can do about this... the resolver interface only knows how to work with addresses
            return;
        // multiple resolvers
        for (CertificateResolver publicResolver : certResolvers) {
            Collection<X509Certificate> holdCerts = null;
            try {
                holdCerts = publicResolver.getCertificates(new InternetAddress(address));
            } catch (AddressException e) {
                continue;
            } catch (Exception e) {
            /* no-op*/
            }
            if (holdCerts != null && holdCerts.size() > 0)
                issuerCerts.addAll(holdCerts);
        }
    }
    if (issuerCerts.size() == 0)
        // no intermediates.. just return
        return;
    boolean issuerFoundInAnchors = false;
    Collection<X509Certificate> searchForParentIssuers = new ArrayList<X509Certificate>();
    for (X509Certificate issuerCert : issuerCerts) {
        if (issuerCert.getSubjectX500Principal().equals(issuerPrin) && !isIssuerInCollection(issuers, issuerCert) && !isIssuerInAnchors(anchors, issuerCert)) /* if we hit an anchor then stop */
        {
            searchForParentIssuers.add(issuerCert);
        } else if (isIssuerInAnchors(anchors, issuerCert)) {
            issuerFoundInAnchors = true;
            break;
        }
    }
    // the go up the next level in the chain
    if (!issuerFoundInAnchors) {
        for (X509Certificate issuerCert : searchForParentIssuers) {
            issuers.add(issuerCert);
            // see if this issuer also has intermediate certs
            resolveIssuers(issuerCert, issuers, chainLength + 1, anchors);
        }
    }
}
Also used : InternetAddress(javax.mail.internet.InternetAddress) AddressException(javax.mail.internet.AddressException) ArrayList(java.util.ArrayList) X500Principal(javax.security.auth.x500.X500Principal) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) CertificateResolver(org.nhindirect.stagent.cert.CertificateResolver) X509Certificate(java.security.cert.X509Certificate) CertificateParsingException(java.security.cert.CertificateParsingException) AddressException(javax.mail.internet.AddressException) PolicyProcessException(org.nhindirect.policy.PolicyProcessException) NHINDException(org.nhindirect.stagent.NHINDException)

Example 84 with Extension

use of org.bouncycastle.asn1.x509.Extension in project nhin-d by DirectProject.

the class TrustChainValidator method downloadCertsFromAIA.

/**
	 * Downloads certificates from the AIA URL and returns the result as a collection of certificates.
	 * @param url The URL listed in the AIA extension to locate the certificates.
	 * @return The certificates downloaded from the AIA extension URL
	 */
@SuppressWarnings("unchecked")
protected Collection<X509Certificate> downloadCertsFromAIA(String url) throws NHINDException {
    InputStream inputStream = null;
    Collection<? extends Certificate> retVal = null;
    try {
        // in this case the cert is a binary representation
        // of the CERT URL... transform to a string
        final URL certURL = new URL(url);
        final URLConnection connection = certURL.openConnection();
        // the connection is not actually made until the input stream
        // is open, so set the timeouts before getting the stream
        connection.setConnectTimeout(DEFAULT_URL_CONNECTION_TIMEOUT);
        connection.setReadTimeout(DEFAULT_URL_READ_TIMEOUT);
        // open the URL as in input stream
        inputStream = connection.getInputStream();
        // download the 
        retVal = CertificateFactory.getInstance("X.509").generateCertificates(inputStream);
    } catch (Exception e) {
        throw new NHINDException("Failed to download certificates from AIA extension.", e);
    } finally {
        IOUtils.closeQuietly(inputStream);
    }
    return (Collection<X509Certificate>) retVal;
}
Also used : ASN1InputStream(org.bouncycastle.asn1.ASN1InputStream) InputStream(java.io.InputStream) Collection(java.util.Collection) NHINDException(org.nhindirect.stagent.NHINDException) URL(java.net.URL) URLConnection(java.net.URLConnection) CertificateParsingException(java.security.cert.CertificateParsingException) AddressException(javax.mail.internet.AddressException) PolicyProcessException(org.nhindirect.policy.PolicyProcessException) NHINDException(org.nhindirect.stagent.NHINDException)

Example 85 with Extension

use of org.bouncycastle.asn1.x509.Extension in project nhin-d by DirectProject.

the class TrustChainValidator method getIntermediateCertsByAIA.

/**
     * Retrieves intermediate certificate using the AIA extension.
     * @param certificate The certificate to search for AIA extensions.
     * @return Returns a collection of intermediate certs using the AIA extension.  If the AIA extension does not exists
     * or the certificate cannot be downloaded from the URL, then an empty list is returned.
     */
protected Collection<X509Certificate> getIntermediateCertsByAIA(X509Certificate certificate) {
    final Collection<X509Certificate> retVal = new ArrayList<X509Certificate>();
    // check to see if there are extensions
    final AuthorityInfoAccessExtentionField aiaField = new AuthorityInfoAccessExtentionField(false);
    try {
        // we can get all names from the AuthorityInfoAccessExtentionField objects
        aiaField.injectReferenceValue(certificate);
        final Collection<String> urlPairs = aiaField.getPolicyValue().getPolicyValue();
        // look through all of the values (if they exist) for caIssuers
        for (String urlPair : urlPairs) {
            if (urlPair.startsWith(CA_ISSUER_CHECK_STRING)) {
                // the url pair is in the format of caIssuer:URL... need to break it 
                // apart to get the url
                final String url = urlPair.substring(CA_ISSUER_CHECK_STRING.length());
                // now pull the certificate from the URL
                try {
                    final Collection<X509Certificate> intermCerts = downloadCertsFromAIA(url);
                    retVal.addAll(intermCerts);
                } catch (NHINDException e) {
                    LOGGER.warn("Intermediate cert cannot be resolved from AIA extension.", e);
                }
            }
        }
    }///CLOVER:OFF
     catch (PolicyProcessException e) {
        LOGGER.warn("Intermediate cert cannot be resolved from AIA extension.", e);
    }
    return retVal;
}
Also used : AuthorityInfoAccessExtentionField(org.nhindirect.policy.x509.AuthorityInfoAccessExtentionField) ArrayList(java.util.ArrayList) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) NHINDException(org.nhindirect.stagent.NHINDException) X509Certificate(java.security.cert.X509Certificate) PolicyProcessException(org.nhindirect.policy.PolicyProcessException)

Aggregations

IOException (java.io.IOException)52 Enumeration (java.util.Enumeration)37 ArrayList (java.util.ArrayList)36 ExtCertPathValidatorException (org.bouncycastle.jce.exception.ExtCertPathValidatorException)36 List (java.util.List)35 CertPathValidatorException (java.security.cert.CertPathValidatorException)34 X509Certificate (java.security.cert.X509Certificate)34 GeneralSecurityException (java.security.GeneralSecurityException)33 CertificateExpiredException (java.security.cert.CertificateExpiredException)31 CertificateNotYetValidException (java.security.cert.CertificateNotYetValidException)31 CRLDistPoint (org.bouncycastle.asn1.x509.CRLDistPoint)31 IssuingDistributionPoint (org.bouncycastle.asn1.x509.IssuingDistributionPoint)31 DistributionPoint (org.bouncycastle.asn1.x509.DistributionPoint)28 CertPathBuilderException (java.security.cert.CertPathBuilderException)26 Extension (org.bouncycastle.asn1.x509.Extension)25 ASN1InputStream (org.bouncycastle.asn1.ASN1InputStream)22 ASN1Sequence (org.bouncycastle.asn1.ASN1Sequence)22 HashSet (java.util.HashSet)21 Set (java.util.Set)21 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)20