Search in sources :

Example 16 with CRLDistPoint

use of com.github.zhenwei.core.asn1.x509.CRLDistPoint in project LinLong-Java by zhenwei1108.

the class RFC3281CertPathUtilities method checkCRLs.

/**
 * Checks if an attribute certificate is revoked.
 *
 * @param attrCert      Attribute certificate to check if it is revoked.
 * @param paramsPKIX    PKIX parameters.
 * @param validityDate  The date when the certificate revocation status should be checked.
 * @param issuerCert    The issuer certificate of the attribute certificate
 *                      <code>attrCert</code>.
 * @param certPathCerts The certificates of the certification path to be checked.
 * @throws CertPathValidatorException if the certificate is revoked or the status cannot be
 *                                    checked or some error occurs.
 */
protected static void checkCRLs(X509AttributeCertificate attrCert, PKIXExtendedParameters paramsPKIX, Date currentDate, Date validityDate, X509Certificate issuerCert, List certPathCerts, JcaJceHelper helper) throws CertPathValidatorException {
    if (paramsPKIX.isRevocationEnabled()) {
        // check if revocation is available
        if (attrCert.getExtensionValue(NO_REV_AVAIL) == null) {
            CRLDistPoint crldp = null;
            try {
                crldp = CRLDistPoint.getInstance(CertPathValidatorUtilities.getExtensionValue(attrCert, CRL_DISTRIBUTION_POINTS));
            } catch (AnnotatedException e) {
                throw new CertPathValidatorException("CRL distribution point extension could not be read.", e);
            }
            List crlStores = new ArrayList();
            try {
                crlStores.addAll(CertPathValidatorUtilities.getAdditionalStoresFromCRLDistributionPoint(crldp, paramsPKIX.getNamedCRLStoreMap(), validityDate, helper));
            } catch (AnnotatedException e) {
                throw new CertPathValidatorException("No additional CRL locations could be decoded from CRL distribution point extension.", e);
            }
            PKIXExtendedParameters.Builder bldr = new PKIXExtendedParameters.Builder(paramsPKIX);
            for (Iterator it = crlStores.iterator(); it.hasNext(); ) {
                bldr.addCRLStore((PKIXCRLStore) crlStores);
            }
            paramsPKIX = bldr.build();
            CertStatus certStatus = new CertStatus();
            ReasonsMask reasonsMask = new ReasonsMask();
            AnnotatedException lastException = null;
            boolean validCrlFound = false;
            // for each distribution point
            if (crldp != null) {
                DistributionPoint[] dps = null;
                try {
                    dps = crldp.getDistributionPoints();
                } catch (Exception e) {
                    throw new ExtCertPathValidatorException("Distribution points could not be read.", e);
                }
                try {
                    for (int i = 0; i < dps.length && certStatus.getCertStatus() == CertStatus.UNREVOKED && !reasonsMask.isAllReasons(); i++) {
                        PKIXExtendedParameters paramsPKIXClone = (PKIXExtendedParameters) paramsPKIX.clone();
                        checkCRL(dps[i], attrCert, paramsPKIXClone, currentDate, validityDate, issuerCert, certStatus, reasonsMask, certPathCerts, helper);
                        validCrlFound = true;
                    }
                } catch (AnnotatedException e) {
                    lastException = new AnnotatedException("No valid CRL for distribution point found.", e);
                }
            }
            if (certStatus.getCertStatus() == CertStatus.UNREVOKED && !reasonsMask.isAllReasons()) {
                try {
                    /*
             * assume a DP with both the reasons and the cRLIssuer
             * fields omitted and a distribution point name of the
             * certificate issuer.
             */
                    X500Name issuer;
                    try {
                        issuer = PrincipalUtils.getEncodedIssuerPrincipal(attrCert);
                    } catch (Exception e) {
                        throw new AnnotatedException("Issuer from certificate for CRL could not be reencoded.", e);
                    }
                    DistributionPoint dp = new DistributionPoint(new DistributionPointName(0, new GeneralNames(new GeneralName(GeneralName.directoryName, issuer))), null, null);
                    PKIXExtendedParameters paramsPKIXClone = (PKIXExtendedParameters) paramsPKIX.clone();
                    checkCRL(dp, attrCert, paramsPKIXClone, currentDate, validityDate, issuerCert, certStatus, reasonsMask, certPathCerts, helper);
                    validCrlFound = true;
                } catch (AnnotatedException e) {
                    lastException = new AnnotatedException("No valid CRL for distribution point found.", e);
                }
            }
            if (!validCrlFound) {
                throw new ExtCertPathValidatorException("No valid CRL found.", lastException);
            }
            if (certStatus.getCertStatus() != CertStatus.UNREVOKED) {
                String message = "Attribute certificate revocation after " + certStatus.getRevocationDate();
                message += ", reason: " + RFC3280CertPathUtilities.crlReasons[certStatus.getCertStatus()];
                throw new CertPathValidatorException(message);
            }
            if (!reasonsMask.isAllReasons() && certStatus.getCertStatus() == CertStatus.UNREVOKED) {
                certStatus.setCertStatus(CertStatus.UNDETERMINED);
            }
            if (certStatus.getCertStatus() == CertStatus.UNDETERMINED) {
                throw new CertPathValidatorException("Attribute certificate status could not be determined.");
            }
        } else {
            if (attrCert.getExtensionValue(CRL_DISTRIBUTION_POINTS) != null || attrCert.getExtensionValue(AUTHORITY_INFO_ACCESS) != null) {
                throw new CertPathValidatorException("No rev avail extension is set, but also an AC revocation pointer.");
            }
        }
    }
}
Also used : CertPathBuilder(java.security.cert.CertPathBuilder) ArrayList(java.util.ArrayList) DistributionPointName(com.github.zhenwei.core.asn1.x509.DistributionPointName) X500Name(com.github.zhenwei.core.asn1.x500.X500Name) CertificateNotYetValidException(java.security.cert.CertificateNotYetValidException) CertificateExpiredException(java.security.cert.CertificateExpiredException) InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) CertPathBuilderException(java.security.cert.CertPathBuilderException) CertPathValidatorException(java.security.cert.CertPathValidatorException) IOException(java.io.IOException) ExtCertPathValidatorException(com.github.zhenwei.provider.jce.exception.ExtCertPathValidatorException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) NoSuchProviderException(java.security.NoSuchProviderException) DistributionPoint(com.github.zhenwei.core.asn1.x509.DistributionPoint) CRLDistPoint(com.github.zhenwei.core.asn1.x509.CRLDistPoint) CertPathValidatorException(java.security.cert.CertPathValidatorException) ExtCertPathValidatorException(com.github.zhenwei.provider.jce.exception.ExtCertPathValidatorException) PKIXExtendedParameters(com.github.zhenwei.provider.jcajce.PKIXExtendedParameters) ExtCertPathValidatorException(com.github.zhenwei.provider.jce.exception.ExtCertPathValidatorException) GeneralNames(com.github.zhenwei.core.asn1.x509.GeneralNames) Iterator(java.util.Iterator) ArrayList(java.util.ArrayList) List(java.util.List) DistributionPoint(com.github.zhenwei.core.asn1.x509.DistributionPoint) GeneralName(com.github.zhenwei.core.asn1.x509.GeneralName) CRLDistPoint(com.github.zhenwei.core.asn1.x509.CRLDistPoint)

Example 17 with CRLDistPoint

use of com.github.zhenwei.core.asn1.x509.CRLDistPoint in project LinLong-Java by zhenwei1108.

the class PKIXCertPathReviewer method getCRLDistUrls.

protected Vector getCRLDistUrls(CRLDistPoint crlDistPoints) {
    Vector urls = new Vector();
    if (crlDistPoints != null) {
        DistributionPoint[] distPoints = crlDistPoints.getDistributionPoints();
        for (int i = 0; i < distPoints.length; i++) {
            DistributionPointName dp_name = distPoints[i].getDistributionPoint();
            if (dp_name.getType() == DistributionPointName.FULL_NAME) {
                GeneralName[] generalNames = GeneralNames.getInstance(dp_name.getName()).getNames();
                for (int j = 0; j < generalNames.length; j++) {
                    if (generalNames[j].getTagNo() == GeneralName.uniformResourceIdentifier) {
                        String url = ((ASN1IA5String) generalNames[j].getName()).getString();
                        urls.add(url);
                    }
                }
            }
        }
    }
    return urls;
}
Also used : ASN1IA5String(com.github.zhenwei.core.asn1.ASN1IA5String) DistributionPointName(com.github.zhenwei.core.asn1.x509.DistributionPointName) IssuingDistributionPoint(com.github.zhenwei.core.asn1.x509.IssuingDistributionPoint) DistributionPoint(com.github.zhenwei.core.asn1.x509.DistributionPoint) GeneralName(com.github.zhenwei.core.asn1.x509.GeneralName) ASN1OctetString(com.github.zhenwei.core.asn1.ASN1OctetString) DEROctetString(com.github.zhenwei.core.asn1.DEROctetString) LocaleString(com.github.zhenwei.core.i18n.LocaleString) ASN1IA5String(com.github.zhenwei.core.asn1.ASN1IA5String) Vector(java.util.Vector) IssuingDistributionPoint(com.github.zhenwei.core.asn1.x509.IssuingDistributionPoint) CRLDistPoint(com.github.zhenwei.core.asn1.x509.CRLDistPoint) DistributionPoint(com.github.zhenwei.core.asn1.x509.DistributionPoint)

Example 18 with CRLDistPoint

use of com.github.zhenwei.core.asn1.x509.CRLDistPoint in project LinLong-Java by zhenwei1108.

the class PKIXCertPathReviewer method checkSignatures.

/*
   * checks: - signatures - name chaining - validity of certificates - todo:
   * if certificate revoked (if specified in the parameters)
   */
private void checkSignatures() {
    // 1.6.1 - Inputs
    // d)
    TrustAnchor trust = null;
    X500Principal trustPrincipal = null;
    // validation date
    {
        ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.certPathValidDate", new Object[] { new TrustedInput(validDate), new TrustedInput(currentDate) });
        addNotification(msg);
    }
    // find trust anchors
    try {
        X509Certificate cert = (X509Certificate) certs.get(certs.size() - 1);
        Collection trustColl = getTrustAnchors(cert, pkixParams.getTrustAnchors());
        if (trustColl.size() > 1) {
            // conflicting trust anchors
            ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.conflictingTrustAnchors", new Object[] { Integers.valueOf(trustColl.size()), new UntrustedInput(cert.getIssuerX500Principal()) });
            addError(msg);
        } else if (trustColl.isEmpty()) {
            ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.noTrustAnchorFound", new Object[] { new UntrustedInput(cert.getIssuerX500Principal()), Integers.valueOf(pkixParams.getTrustAnchors().size()) });
            addError(msg);
        } else {
            PublicKey trustPublicKey;
            trust = (TrustAnchor) trustColl.iterator().next();
            if (trust.getTrustedCert() != null) {
                trustPublicKey = trust.getTrustedCert().getPublicKey();
            } else {
                trustPublicKey = trust.getCAPublicKey();
            }
            try {
                CertPathValidatorUtilities.verifyX509Certificate(cert, trustPublicKey, pkixParams.getSigProvider());
            } catch (SignatureException e) {
                ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.trustButInvalidCert");
                addError(msg);
            } catch (Exception e) {
            // do nothing, error occurs again later
            }
        }
    } catch (CertPathReviewerException cpre) {
        addError(cpre.getErrorMessage());
    } catch (Throwable t) {
        ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.unknown", new Object[] { new UntrustedInput(t.getMessage()), new UntrustedInput(t) });
        addError(msg);
    }
    if (trust != null) {
        // get the name of the trustAnchor
        X509Certificate sign = trust.getTrustedCert();
        try {
            if (sign != null) {
                trustPrincipal = getSubjectPrincipal(sign);
            } else {
                trustPrincipal = new X500Principal(trust.getCAName());
            }
        } catch (IllegalArgumentException ex) {
            ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.trustDNInvalid", new Object[] { new UntrustedInput(trust.getCAName()) });
            addError(msg);
        }
        // test key usages of the trust anchor
        if (sign != null) {
            boolean[] ku = sign.getKeyUsage();
            if (ku != null && (ku.length <= 5 || !ku[5])) {
                ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.trustKeyUsage");
                addNotification(msg);
            }
        }
    }
    // 1.6.2 - Initialization
    PublicKey workingPublicKey = null;
    X500Principal workingIssuerName = trustPrincipal;
    X509Certificate sign = null;
    AlgorithmIdentifier workingAlgId = null;
    ASN1ObjectIdentifier workingPublicKeyAlgorithm = null;
    ASN1Encodable workingPublicKeyParameters = null;
    if (trust != null) {
        sign = trust.getTrustedCert();
        if (sign != null) {
            workingPublicKey = sign.getPublicKey();
        } else {
            workingPublicKey = trust.getCAPublicKey();
        }
        try {
            workingAlgId = getAlgorithmIdentifier(workingPublicKey);
            workingPublicKeyAlgorithm = workingAlgId.getAlgorithm();
            workingPublicKeyParameters = workingAlgId.getParameters();
        } catch (CertPathValidatorException ex) {
            ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.trustPubKeyError");
            addError(msg);
            workingAlgId = null;
        }
    }
    // Basic cert checks
    X509Certificate cert = null;
    int i;
    for (int index = certs.size() - 1; index >= 0; index--) {
        // 
        // i as defined in the algorithm description
        // 
        i = n - index;
        // 
        // set certificate to be checked in this round
        // sign and workingPublicKey and workingIssuerName are set
        // at the end of the for loop and initialied the
        // first time from the TrustAnchor
        // 
        cert = (X509Certificate) certs.get(index);
        // verify signature
        if (workingPublicKey != null) {
            try {
                CertPathValidatorUtilities.verifyX509Certificate(cert, workingPublicKey, pkixParams.getSigProvider());
            } catch (GeneralSecurityException ex) {
                ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.signatureNotVerified", new Object[] { ex.getMessage(), ex, ex.getClass().getName() });
                addError(msg, index);
            }
        } else if (isSelfIssued(cert)) {
            try {
                CertPathValidatorUtilities.verifyX509Certificate(cert, cert.getPublicKey(), pkixParams.getSigProvider());
                ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.rootKeyIsValidButNotATrustAnchor");
                addError(msg, index);
            } catch (GeneralSecurityException ex) {
                ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.signatureNotVerified", new Object[] { ex.getMessage(), ex, ex.getClass().getName() });
                addError(msg, index);
            }
        } else {
            ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.NoIssuerPublicKey");
            // if there is an authority key extension add the serial and issuer of the missing certificate
            byte[] akiBytes = cert.getExtensionValue(Extension.authorityKeyIdentifier.getId());
            if (akiBytes != null) {
                AuthorityKeyIdentifier aki = AuthorityKeyIdentifier.getInstance(DEROctetString.getInstance(akiBytes).getOctets());
                GeneralNames issuerNames = aki.getAuthorityCertIssuer();
                if (issuerNames != null) {
                    GeneralName name = issuerNames.getNames()[0];
                    BigInteger serial = aki.getAuthorityCertSerialNumber();
                    if (serial != null) {
                        Object[] extraArgs = { new LocaleString(RESOURCE_NAME, "missingIssuer"), " \"", name, "\" ", new LocaleString(RESOURCE_NAME, "missingSerial"), " ", serial };
                        msg.setExtraArguments(extraArgs);
                    }
                }
            }
            addError(msg, index);
        }
        // certificate valid?
        try {
            cert.checkValidity(validDate);
        } catch (CertificateNotYetValidException cnve) {
            ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.certificateNotYetValid", new Object[] { new TrustedInput(cert.getNotBefore()) });
            addError(msg, index);
        } catch (CertificateExpiredException cee) {
            ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.certificateExpired", new Object[] { new TrustedInput(cert.getNotAfter()) });
            addError(msg, index);
        }
        // certificate revoked?
        if (pkixParams.isRevocationEnabled()) {
            // read crl distribution points extension
            CRLDistPoint crlDistPoints = null;
            try {
                ASN1Primitive crl_dp = getExtensionValue(cert, CRL_DIST_POINTS);
                if (crl_dp != null) {
                    crlDistPoints = CRLDistPoint.getInstance(crl_dp);
                }
            } catch (AnnotatedException ae) {
                ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.crlDistPtExtError");
                addError(msg, index);
            }
            // read authority information access extension
            AuthorityInformationAccess authInfoAcc = null;
            try {
                ASN1Primitive auth_info_acc = getExtensionValue(cert, AUTH_INFO_ACCESS);
                if (auth_info_acc != null) {
                    authInfoAcc = AuthorityInformationAccess.getInstance(auth_info_acc);
                }
            } catch (AnnotatedException ae) {
                ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.crlAuthInfoAccError");
                addError(msg, index);
            }
            Vector crlDistPointUrls = getCRLDistUrls(crlDistPoints);
            Vector ocspUrls = getOCSPUrls(authInfoAcc);
            // add notifications with the crl distribution points
            // output crl distribution points
            Iterator urlIt = crlDistPointUrls.iterator();
            while (urlIt.hasNext()) {
                ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.crlDistPoint", new Object[] { new UntrustedUrlInput(urlIt.next()) });
                addNotification(msg, index);
            }
            // output ocsp urls
            urlIt = ocspUrls.iterator();
            while (urlIt.hasNext()) {
                ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.ocspLocation", new Object[] { new UntrustedUrlInput(urlIt.next()) });
                addNotification(msg, index);
            }
            // check CRLs
            try {
                checkRevocation(pkixParams, cert, validDate, sign, workingPublicKey, crlDistPointUrls, ocspUrls, index);
            } catch (CertPathReviewerException cpre) {
                addError(cpre.getErrorMessage(), index);
            }
        }
        // certificate issuer correct
        if (workingIssuerName != null && !cert.getIssuerX500Principal().equals(workingIssuerName)) {
            ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.certWrongIssuer", new Object[] { workingIssuerName.getName(), cert.getIssuerX500Principal().getName() });
            addError(msg, index);
        }
        // 
        if (i != n) {
            if (cert != null && cert.getVersion() == 1) {
                ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.noCACert");
                addError(msg, index);
            }
            // k)
            BasicConstraints bc;
            try {
                bc = BasicConstraints.getInstance(getExtensionValue(cert, BASIC_CONSTRAINTS));
                if (bc != null) {
                    if (!bc.isCA()) {
                        ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.noCACert");
                        addError(msg, index);
                    }
                } else {
                    ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.noBasicConstraints");
                    addError(msg, index);
                }
            } catch (AnnotatedException ae) {
                ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.errorProcesingBC");
                addError(msg, index);
            }
            // n)
            boolean[] keyUsage = cert.getKeyUsage();
            if (keyUsage != null && (keyUsage.length <= KEY_CERT_SIGN || !keyUsage[KEY_CERT_SIGN])) {
                ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.noCertSign");
                addError(msg, index);
            }
        }
        // if
        // set signing certificate for next round
        sign = cert;
        // c)
        workingIssuerName = cert.getSubjectX500Principal();
        try {
            workingPublicKey = getNextWorkingKey(certs, index);
            workingAlgId = getAlgorithmIdentifier(workingPublicKey);
            workingPublicKeyAlgorithm = workingAlgId.getAlgorithm();
            workingPublicKeyParameters = workingAlgId.getParameters();
        } catch (CertPathValidatorException ex) {
            ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.pubKeyError");
            addError(msg, index);
            workingAlgId = null;
            workingPublicKeyAlgorithm = null;
            workingPublicKeyParameters = null;
        }
    }
    // for
    trustAnchor = trust;
    subjectPublicKey = workingPublicKey;
}
Also used : AuthorityInformationAccess(com.github.zhenwei.core.asn1.x509.AuthorityInformationAccess) CertificateNotYetValidException(java.security.cert.CertificateNotYetValidException) CertificateExpiredException(java.security.cert.CertificateExpiredException) AuthorityKeyIdentifier(com.github.zhenwei.core.asn1.x509.AuthorityKeyIdentifier) SignatureException(java.security.SignatureException) UntrustedUrlInput(com.github.zhenwei.core.i18n.filter.UntrustedUrlInput) AlgorithmIdentifier(com.github.zhenwei.core.asn1.x509.AlgorithmIdentifier) TrustedInput(com.github.zhenwei.core.i18n.filter.TrustedInput) Iterator(java.util.Iterator) ASN1Encodable(com.github.zhenwei.core.asn1.ASN1Encodable) UntrustedInput(com.github.zhenwei.core.i18n.filter.UntrustedInput) CRLDistPoint(com.github.zhenwei.core.asn1.x509.CRLDistPoint) Vector(java.util.Vector) AnnotatedException(com.github.zhenwei.provider.jce.provider.AnnotatedException) LocaleString(com.github.zhenwei.core.i18n.LocaleString) PublicKey(java.security.PublicKey) GeneralSecurityException(java.security.GeneralSecurityException) TrustAnchor(java.security.cert.TrustAnchor) X509Certificate(java.security.cert.X509Certificate) CertificateExpiredException(java.security.cert.CertificateExpiredException) GeneralSecurityException(java.security.GeneralSecurityException) CertPathValidatorException(java.security.cert.CertPathValidatorException) AnnotatedException(com.github.zhenwei.provider.jce.provider.AnnotatedException) SignatureException(java.security.SignatureException) CertificateNotYetValidException(java.security.cert.CertificateNotYetValidException) PKIXNameConstraintValidatorException(com.github.zhenwei.provider.jce.provider.PKIXNameConstraintValidatorException) IOException(java.io.IOException) IssuingDistributionPoint(com.github.zhenwei.core.asn1.x509.IssuingDistributionPoint) CRLDistPoint(com.github.zhenwei.core.asn1.x509.CRLDistPoint) DistributionPoint(com.github.zhenwei.core.asn1.x509.DistributionPoint) CertPathValidatorException(java.security.cert.CertPathValidatorException) ErrorBundle(com.github.zhenwei.core.i18n.ErrorBundle) GeneralNames(com.github.zhenwei.core.asn1.x509.GeneralNames) X500Principal(javax.security.auth.x500.X500Principal) Collection(java.util.Collection) BigInteger(java.math.BigInteger) ASN1TaggedObject(com.github.zhenwei.core.asn1.ASN1TaggedObject) GeneralName(com.github.zhenwei.core.asn1.x509.GeneralName) ASN1Primitive(com.github.zhenwei.core.asn1.ASN1Primitive) BasicConstraints(com.github.zhenwei.core.asn1.x509.BasicConstraints) ASN1ObjectIdentifier(com.github.zhenwei.core.asn1.ASN1ObjectIdentifier)

Example 19 with CRLDistPoint

use of com.github.zhenwei.core.asn1.x509.CRLDistPoint in project LinLong-Java by zhenwei1108.

the class CertPathValidatorUtilities method getDeltaCRLs.

/**
 * Fetches delta CRLs according to RFC 3280 section 5.2.4.
 *
 * @param validityDate The date for which the delta CRLs must be valid.
 * @param completeCRL  The complete CRL the delta CRL is for.
 * @return A <code>Set</code> of <code>X509CRL</code>s with delta CRLs.
 * @throws AnnotatedException if an exception occurs while picking the delta CRLs.
 */
protected static Set getDeltaCRLs(Date validityDate, X509CRL completeCRL, List<CertStore> certStores, List<PKIXCRLStore> pkixCrlStores, JcaJceHelper helper) throws AnnotatedException {
    X509CRLSelector baseDeltaSelect = new X509CRLSelector();
    // 5.2.4 (a)
    try {
        baseDeltaSelect.addIssuerName(PrincipalUtils.getIssuerPrincipal(completeCRL).getEncoded());
    } catch (IOException e) {
        throw new AnnotatedException("Cannot extract issuer from CRL.", e);
    }
    BigInteger completeCRLNumber = null;
    try {
        ASN1Primitive derObject = CertPathValidatorUtilities.getExtensionValue(completeCRL, CRL_NUMBER);
        if (derObject != null) {
            completeCRLNumber = ASN1Integer.getInstance(derObject).getPositiveValue();
        }
    } catch (Exception e) {
        throw new AnnotatedException("CRL number extension could not be extracted from CRL.", e);
    }
    // 5.2.4 (b)
    byte[] idp;
    try {
        idp = completeCRL.getExtensionValue(ISSUING_DISTRIBUTION_POINT);
    } catch (Exception e) {
        throw new AnnotatedException("Issuing distribution point extension value could not be read.", e);
    }
    // 5.2.4 (d)
    baseDeltaSelect.setMinCRLNumber(completeCRLNumber == null ? null : completeCRLNumber.add(BigInteger.valueOf(1)));
    PKIXCRLStoreSelector.Builder selBuilder = new PKIXCRLStoreSelector.Builder(baseDeltaSelect);
    selBuilder.setIssuingDistributionPoint(idp);
    selBuilder.setIssuingDistributionPointEnabled(true);
    // 5.2.4 (c)
    selBuilder.setMaxBaseCRLNumber(completeCRLNumber);
    PKIXCRLStoreSelector deltaSelect = selBuilder.build();
    // find delta CRLs
    Set temp = PKIXCRLUtil.findCRLs(deltaSelect, validityDate, certStores, pkixCrlStores);
    // if the named CRL store is empty, and we're told to check with CRLDP
    if (temp.isEmpty() && Properties.isOverrideSet("com.github.zhenwei.provider.x509.enableCRLDP")) {
        CertificateFactory certFact;
        try {
            certFact = helper.createCertificateFactory("X.509");
        } catch (Exception e) {
            throw new AnnotatedException("cannot create certificate factory: " + e.getMessage(), e);
        }
        CRLDistPoint id = CRLDistPoint.getInstance(idp);
        DistributionPoint[] dps = id.getDistributionPoints();
        for (int i = 0; i < dps.length; i++) {
            DistributionPointName dpn = dps[i].getDistributionPoint();
            // look for URIs in fullName
            if (dpn != null && dpn.getType() == DistributionPointName.FULL_NAME) {
                GeneralName[] genNames = GeneralNames.getInstance(dpn.getName()).getNames();
                for (int j = 0; j < genNames.length; j++) {
                    GeneralName name = genNames[i];
                    if (name.getTagNo() == GeneralName.uniformResourceIdentifier) {
                        try {
                            PKIXCRLStore store = CrlCache.getCrl(certFact, validityDate, new URI(((ASN1String) name.getName()).getString()));
                            if (store != null) {
                                temp = PKIXCRLUtil.findCRLs(deltaSelect, validityDate, Collections.EMPTY_LIST, Collections.singletonList(store));
                            }
                            break;
                        } catch (Exception e) {
                        // ignore...  TODO: maybe log
                        }
                    }
                }
            }
        }
    }
    Set result = new HashSet();
    for (Iterator it = temp.iterator(); it.hasNext(); ) {
        X509CRL crl = (X509CRL) it.next();
        if (isDeltaCRL(crl)) {
            result.add(crl);
        }
    }
    return result;
}
Also used : Set(java.util.Set) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet) X509CRL(java.security.cert.X509CRL) PKIXCRLStoreSelector(com.github.zhenwei.provider.jcajce.PKIXCRLStoreSelector) CertificateFactory(java.security.cert.CertificateFactory) URI(java.net.URI) Iterator(java.util.Iterator) DistributionPoint(com.github.zhenwei.core.asn1.x509.DistributionPoint) CRLDistPoint(com.github.zhenwei.core.asn1.x509.CRLDistPoint) X509CRLSelector(java.security.cert.X509CRLSelector) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet) DistributionPointName(com.github.zhenwei.core.asn1.x509.DistributionPointName) IOException(java.io.IOException) GeneralSecurityException(java.security.GeneralSecurityException) CertPathValidatorException(java.security.cert.CertPathValidatorException) ParseException(java.text.ParseException) CertStoreException(java.security.cert.CertStoreException) ExtCertPathValidatorException(com.github.zhenwei.provider.jce.exception.ExtCertPathValidatorException) CRLException(java.security.cert.CRLException) StoreException(com.github.zhenwei.core.util.StoreException) CertificateParsingException(java.security.cert.CertificateParsingException) CertPathBuilderException(java.security.cert.CertPathBuilderException) IOException(java.io.IOException) ExtCertPathBuilderException(com.github.zhenwei.provider.jce.exception.ExtCertPathBuilderException) CRLDistPoint(com.github.zhenwei.core.asn1.x509.CRLDistPoint) DistributionPoint(com.github.zhenwei.core.asn1.x509.DistributionPoint) PKIXCRLStore(com.github.zhenwei.provider.jcajce.PKIXCRLStore) BigInteger(java.math.BigInteger) GeneralName(com.github.zhenwei.core.asn1.x509.GeneralName) ASN1String(com.github.zhenwei.core.asn1.ASN1String) ASN1Primitive(com.github.zhenwei.core.asn1.ASN1Primitive)

Example 20 with CRLDistPoint

use of com.github.zhenwei.core.asn1.x509.CRLDistPoint in project module-ballerina-http by ballerina-platform.

the class CRLVerifier method getCrlDistributionPoints.

/**
 * Extracts all CRL distribution point URLs from the "CRL Distribution Point"
 * extension in a X.509 certificate. If CRL distribution point extension is
 * unavailable, returns an empty list.
 */
private List<String> getCrlDistributionPoints(X509Certificate cert) throws CertificateVerificationException {
    // Gets the DER-encoded OCTET string for the extension value for CRLDistributionPoints.
    byte[] crlDPExtensionValue = cert.getExtensionValue(Extension.cRLDistributionPoints.getId());
    if (crlDPExtensionValue == null) {
        throw new CertificateVerificationException("Certificate doesn't have CRL distribution points");
    }
    // crlDPExtensionValue is encoded in ASN.1 format.
    ASN1InputStream asn1In = new ASN1InputStream(crlDPExtensionValue);
    // DER (Distinguished Encoding Rules) is one of ASN.1 encoding rules defined in ITU-T X.690, 2002, specification.
    // ASN.1 encoding rules can be used to encode any data object into a binary file. Read the object in octets.
    CRLDistPoint distPoint;
    try {
        DEROctetString crlDEROctetString = (DEROctetString) asn1In.readObject();
        // Get Input stream in octets.
        distPoint = getOctetInputStream(crlDEROctetString);
    } catch (IOException e) {
        throw new CertificateVerificationException("Cannot read certificate to get CRL URLs", e);
    } finally {
        try {
            asn1In.close();
        } catch (IOException e) {
            LOG.error("Cannot close input stream", e);
        }
    }
    List<String> crlUrls = new ArrayList<>();
    // Loop through ASN1Encodable DistributionPoints.
    for (DistributionPoint dp : distPoint.getDistributionPoints()) {
        // get ASN1Encodable DistributionPointName.
        DistributionPointName dpn = dp.getDistributionPoint();
        if (dpn != null && dpn.getType() == DistributionPointName.FULL_NAME) {
            // Create ASN1Encodable General Names.
            GeneralName[] genNames = GeneralNames.getInstance(dpn.getName()).getNames();
            // Look for a URI
            for (GeneralName genName : genNames) {
                if (genName.getTagNo() == GeneralName.uniformResourceIdentifier) {
                    // DERIA5String contains an ascii string.
                    // A IA5String is a restricted character string type in the ASN.1 notation.
                    String url = DERIA5String.getInstance(genName.getName()).getString().trim();
                    crlUrls.add(url);
                }
            }
        }
    }
    if (crlUrls.isEmpty()) {
        throw new CertificateVerificationException("Cant get CRL urls from certificate");
    }
    return crlUrls;
}
Also used : ASN1InputStream(org.bouncycastle.asn1.ASN1InputStream) ArrayList(java.util.ArrayList) DistributionPointName(org.bouncycastle.asn1.x509.DistributionPointName) IOException(java.io.IOException) DEROctetString(org.bouncycastle.asn1.DEROctetString) DERIA5String(org.bouncycastle.asn1.DERIA5String) DEROctetString(org.bouncycastle.asn1.DEROctetString) CertificateVerificationException(io.ballerina.stdlib.http.transport.contractimpl.common.certificatevalidation.CertificateVerificationException) DistributionPoint(org.bouncycastle.asn1.x509.DistributionPoint) GeneralName(org.bouncycastle.asn1.x509.GeneralName) CRLDistPoint(org.bouncycastle.asn1.x509.CRLDistPoint)

Aggregations

CRLDistPoint (org.bouncycastle.asn1.x509.CRLDistPoint)34 DistributionPoint (org.bouncycastle.asn1.x509.DistributionPoint)30 GeneralName (org.bouncycastle.asn1.x509.GeneralName)29 IOException (java.io.IOException)24 DistributionPointName (org.bouncycastle.asn1.x509.DistributionPointName)22 ArrayList (java.util.ArrayList)17 GeneralNames (org.bouncycastle.asn1.x509.GeneralNames)15 DERIA5String (org.bouncycastle.asn1.DERIA5String)14 CertPathValidatorException (java.security.cert.CertPathValidatorException)13 CRLDistPoint (com.github.zhenwei.core.asn1.x509.CRLDistPoint)11 GeneralSecurityException (java.security.GeneralSecurityException)11 ASN1Primitive (org.bouncycastle.asn1.ASN1Primitive)11 DistributionPoint (com.github.zhenwei.core.asn1.x509.DistributionPoint)10 GeneralName (com.github.zhenwei.core.asn1.x509.GeneralName)10 CRLException (java.security.cert.CRLException)10 ASN1InputStream (org.bouncycastle.asn1.ASN1InputStream)10 DistributionPointName (com.github.zhenwei.core.asn1.x509.DistributionPointName)9 ASN1OctetString (org.bouncycastle.asn1.ASN1OctetString)9 CertStoreException (java.security.cert.CertStoreException)8 HashSet (java.util.HashSet)7